/**
 * MapLibre GL JS
 * @license 3-Clause BSD. Full text of license: https://github.com/maplibre/maplibre-gl-js/blob/v5.23.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$1) { '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, Iterator */

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 = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["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 = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), 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;
};

var ownKeys = function(o) {
    ownKeys = Object.getOwnPropertyNames || function (o) {
        var ar = [];
        for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
        return ar;
    };
    return ownKeys(o);
};

function __importStar(mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
    __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;
    }
    var r, s = 0;
    function next() {
        while (r = env.stack.pop()) {
            try {
                if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
                if (r.dispose) {
                    var result = r.dispose.call(r.value);
                    if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
                }
                else s |= 1;
            }
            catch (e) {
                fail(e);
            }
        }
        if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
        if (env.hasError) throw env.error;
    }
    return next();
}

function __rewriteRelativeImportExtension(path, preserveJsx) {
    if (typeof path === "string" && /^\.\.?\//.test(path)) {
        return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
            return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
        });
    }
    return path;
}

var tslib_es6 = {
    __extends: __extends,
    __assign: __assign,
    __rest: __rest,
    __decorate: __decorate,
    __param: __param,
    __esDecorate: __esDecorate,
    __runInitializers: __runInitializers,
    __propKey: __propKey,
    __setFunctionName: __setFunctionName,
    __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,
    __rewriteRelativeImportExtension: __rewriteRelativeImportExtension,
};

/**
 * A standalone point geometry with useful accessor, comparison, and
 * modification methods.
 *
 * @class
 * @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
 * const point = new Point(-77, 38);
 */
function Point(x, y) {
    this.x = x;
    this.y = y;
}

Point.prototype = {
    /**
     * Clone this point, returning a new point that can be modified
     * without affecting the old one.
     * @return {Point} the clone
     */
    clone() { return new Point(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(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(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(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(p) { return this.clone()._divByPoint(p); },

    /**
     * Multiply this point's x & y coordinates by a factor,
     * yielding a new point.
     * @param {number} k factor
     * @return {Point} output point
     */
    mult(k) { return this.clone()._mult(k); },

    /**
     * Divide this point's x & y coordinates by a factor,
     * yielding a new point.
     * @param {number} k factor
     * @return {Point} output point
     */
    div(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(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(a, p) { return this.clone()._rotateAround(a, p); },

    /**
     * Multiply this point by a 4x1 transformation matrix
     * @param {[number, number, number, number]} m transformation matrix
     * @return {Point} output point
     */
    matMult(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() { 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() { return this.clone()._perp(); },

    /**
     * Return a version of this point with the x & y coordinates
     * rounded to integers.
     * @return {Point} rounded point
     */
    round() { return this.clone()._round(); },

    /**
     * Return the magnitude 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() {
        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(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(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(p) {
        const 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() {
        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(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(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(x, y) {
        return Math.atan2(
            this.x * y - this.y * x,
            this.x * x + this.y * y);
    },

    /** @param {[number, number, number, number]} m */
    _matMult(m) {
        const 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;
    },

    /** @param {Point} p */
    _add(p) {
        this.x += p.x;
        this.y += p.y;
        return this;
    },

    /** @param {Point} p */
    _sub(p) {
        this.x -= p.x;
        this.y -= p.y;
        return this;
    },

    /** @param {number} k */
    _mult(k) {
        this.x *= k;
        this.y *= k;
        return this;
    },

    /** @param {number} k */
    _div(k) {
        this.x /= k;
        this.y /= k;
        return this;
    },

    /** @param {Point} p */
    _multByPoint(p) {
        this.x *= p.x;
        this.y *= p.y;
        return this;
    },

    /** @param {Point} p */
    _divByPoint(p) {
        this.x /= p.x;
        this.y /= p.y;
        return this;
    },

    _unit() {
        this._div(this.mag());
        return this;
    },

    _perp() {
        const y = this.y;
        this.y = this.x;
        this.x = -y;
        return this;
    },

    /** @param {number} angle */
    _rotate(angle) {
        const 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;
    },

    /**
     * @param {number} angle
     * @param {Point} p
     */
    _rotateAround(angle, p) {
        const 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() {
        this.x = Math.round(this.x);
        this.y = Math.round(this.y);
        return this;
    },

    constructor: Point
};

/**
 * Construct a point from an array if necessary, otherwise if the input
 * is already a Point, return it unchanged.
 * @param {Point | [number, number] | {x: number, y: number}} p input value
 * @return {Point} constructed point.
 * @example
 * // this
 * var point = Point.convert([0, 1]);
 * // is equivalent to
 * var point = new Point(0, 1);
 */
Point.convert = function (p) {
    if (p instanceof Point) {
        return /** @type {Point} */ (p);
    }
    if (Array.isArray(p)) {
        return new Point(+p[0], +p[1]);
    }
    if (p.x !== undefined && p.y !== undefined) {
        return new Point(+p.x, +p.y);
    }
    throw new Error('Expected [x, y] or {x, y} point format');
};

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 (Object.prototype.hasOwnProperty.call(n, '__esModule')) return n;
  var f = n.default;
	if (typeof f == "function") {
		var a = function a () {
			var isInstance = false;
      try {
        isInstance = this instanceof a;
      } catch {}
			if (isInstance) {
        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;
}

var unitbezier$1;
var hasRequiredUnitbezier$1;

function requireUnitbezier$1 () {
	if (hasRequiredUnitbezier$1) return unitbezier$1;
	hasRequiredUnitbezier$1 = 1;
	'use strict';

	unitbezier$1 = 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));
	    }
	};
	return unitbezier$1;
}

var unitbezierExports$1 = requireUnitbezier$1();
var UnitBezier$1 = /*@__PURE__*/getDefaultExportFromCjs$1(unitbezierExports$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;
}

/**
 * Common utilities
 * @module glMatrix
 */

// Configuration Constants
var EPSILON = 0.000001;
var ARRAY_TYPE = typeof Float32Array !== "undefined" ? Float32Array : Array;
var RANDOM = Math.random;
var ANGLE_ORDER = "zyx";

/**
 * Symmetric round
 * see https://www.npmjs.com/package/round-half-up-symmetric#user-content-detailed-background
 *
 * @param {Number} a value to round
 */
function round$3(a) {
  if (a >= 0) return Math.round(a);
  return a % 0.5 === 0 ? Math.floor(a) : Math.round(a);
}

/**
 * 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;
var radian = 180 / Math.PI;

/**
 * Convert Degree To Radian
 *
 * @param {Number} a Angle in Degrees
 */
function toRadian(a) {
  return a * degree;
}

/**
 * Convert Radian To Degree
 *
 * @param {Number} a Angle in Radians
 */
function toDegree(a) {
  return a * radian;
}

/**
 * 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.
 * @param {Number} tolerance  Absolute or relative tolerance (default glMatrix.EPSILON)
 * @returns {Boolean} True if the numbers are approximately equal, false otherwise.
 */
function equals$a(a, b) {
  var tolerance = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : EPSILON;
  return Math.abs(a - b) <= tolerance * Math.max(1, Math.abs(a), Math.abs(b));
}

var common = /*#__PURE__*/Object.freeze({
__proto__: null,
ANGLE_ORDER: ANGLE_ORDER,
get ARRAY_TYPE () { return ARRAY_TYPE; },
EPSILON: EPSILON,
RANDOM: RANDOM,
equals: equals$a,
round: round$3,
setMatrixArrayType: setMatrixArrayType,
toDegree: toDegree,
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$9(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 | null} out, or null if source matrix is not invertible
 */
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 necessary 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.sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2] + a[3] * 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$9,
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:
 * <pre>
 * [a, b,
 *  c, d,
 *  tx, ty]
 * </pre>
 * This is a short form for the 3x3 matrix:
 * <pre>
 * [a, b, 0,
 *  c, d, 0,
 *  tx, ty, 1]
 * </pre>
 * 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$8(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 | null} out, or null if source matrix is not invertible
 */
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$4(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.sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2] + a[3] * a[3] + a[4] * a[4] + a[5] * 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$8,
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$4
});

/**
 * 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$7(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 | null} out, or null if source matrix is not invertible
 */
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$3(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 scale
 * @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$1(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.sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2] + a[3] * a[3] + a[4] * a[4] + a[5] * a[5] + a[6] * a[6] + a[7] * a[7] + a[8] * 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$7,
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$1,
rotate: rotate$2,
scale: scale$6,
set: set$6,
str: str$6,
sub: sub$4,
subtract: subtract$4,
translate: translate$3,
transpose: transpose$1
});

/**
 * 4x4 Matrix<br>Format: column-major, when typed out it looks like row-major<br>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$6(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 | null} out, or null if source matrix is not invertible
 */
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];
  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;
  out[0] = a11 * b11 - a12 * b10 + a13 * b09;
  out[1] = a02 * b10 - a01 * b11 - a03 * b09;
  out[2] = a31 * b05 - a32 * b04 + a33 * b03;
  out[3] = a22 * b04 - a21 * b05 - a23 * b03;
  out[4] = a12 * b08 - a10 * b11 - a13 * b07;
  out[5] = a00 * b11 - a02 * b08 + a03 * b07;
  out[6] = a32 * b02 - a30 * b05 - a33 * b01;
  out[7] = a20 * b05 - a22 * b02 + a23 * b01;
  out[8] = a10 * b10 - a11 * b08 + a13 * b06;
  out[9] = a01 * b08 - a00 * b10 - a03 * b06;
  out[10] = a30 * b04 - a31 * b02 + a33 * b00;
  out[11] = a21 * b02 - a20 * b04 - a23 * b00;
  out[12] = a11 * b07 - a10 * b09 - a12 * b06;
  out[13] = a00 * b09 - a01 * b07 + a02 * b06;
  out[14] = a31 * b01 - a30 * b03 - a32 * b00;
  out[15] = a20 * b03 - a21 * b01 + a22 * b00;
  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 b0 = a00 * a11 - a01 * a10;
  var b1 = a00 * a12 - a02 * a10;
  var b2 = a01 * a12 - a02 * a11;
  var b3 = a20 * a31 - a21 * a30;
  var b4 = a20 * a32 - a22 * a30;
  var b5 = a21 * a32 - a22 * a31;
  var b6 = a00 * b5 - a01 * b4 + a02 * b3;
  var b7 = a10 * b5 - a11 * b4 + a12 * b3;
  var b8 = a20 * b2 - a21 * b1 + a22 * b0;
  var b9 = a30 * b2 - a31 * b1 + a32 * b0;

  // Calculate the determinant
  return a13 * b6 - a03 * b7 + a33 * b8 - a23 * b9;
}

/**
 * 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$2(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.sqrt(x * x + y * y + z * 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.sqrt(x * x + y * y + z * 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, dest, vec);
 *     let quatMat = mat4.create();
 *     mat4.fromQuat(quatMat, quat);
 *     mat4.multiply(dest, dest, quatMat);
 *
 * @param {mat4} out mat4 receiving operation result
 * @param {quat} 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 parameter, 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.sqrt(m11 * m11 + m12 * m12 + m13 * m13);
  out[1] = Math.sqrt(m21 * m21 + m22 * m22 + m23 * m23);
  out[2] = Math.sqrt(m31 * m31 + m32 * m32 + m33 * 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;
}

/**
 * Decomposes a transformation matrix into its rotation, translation
 * and scale components. Returns only the rotation component
 * @param  {quat} out_r Quaternion to receive the rotation component
 * @param  {vec3} out_t Vector to receive the translation vector
 * @param  {vec3} out_s Vector to receive the scaling factor
 * @param  {ReadonlyMat4} mat Matrix to be decomposed (input)
 * @returns {quat} out_r
 */
function decompose(out_r, out_t, out_s, mat) {
  out_t[0] = mat[12];
  out_t[1] = mat[13];
  out_t[2] = mat[14];
  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_s[0] = Math.sqrt(m11 * m11 + m12 * m12 + m13 * m13);
  out_s[1] = Math.sqrt(m21 * m21 + m22 * m22 + m23 * m23);
  out_s[2] = Math.sqrt(m31 * m31 + m32 * m32 + m33 * m33);
  var is1 = 1 / out_s[0];
  var is2 = 1 / out_s[1];
  var is3 = 1 / out_s[2];
  var sm11 = m11 * is1;
  var sm12 = m12 * is2;
  var sm13 = m13 * is3;
  var sm21 = m21 * is1;
  var sm22 = m22 * is2;
  var sm23 = m23 * is3;
  var sm31 = m31 * is1;
  var sm32 = m32 * is2;
  var sm33 = m33 * is3;
  var trace = sm11 + sm22 + sm33;
  var S = 0;
  if (trace > 0) {
    S = Math.sqrt(trace + 1.0) * 2;
    out_r[3] = 0.25 * S;
    out_r[0] = (sm23 - sm32) / S;
    out_r[1] = (sm31 - sm13) / S;
    out_r[2] = (sm12 - sm21) / S;
  } else if (sm11 > sm22 && sm11 > sm33) {
    S = Math.sqrt(1.0 + sm11 - sm22 - sm33) * 2;
    out_r[3] = (sm23 - sm32) / S;
    out_r[0] = 0.25 * S;
    out_r[1] = (sm12 + sm21) / S;
    out_r[2] = (sm31 + sm13) / S;
  } else if (sm22 > sm33) {
    S = Math.sqrt(1.0 + sm22 - sm11 - sm33) * 2;
    out_r[3] = (sm31 - sm13) / S;
    out_r[0] = (sm12 + sm21) / S;
    out_r[1] = 0.25 * S;
    out_r[2] = (sm23 + sm32) / S;
  } else {
    S = Math.sqrt(1.0 + sm33 - sm11 - sm22) * 2;
    out_r[3] = (sm12 - sm21) / S;
    out_r[0] = (sm31 + sm13) / S;
    out_r[1] = (sm23 + sm32) / S;
    out_r[2] = 0.25 * S;
  }
  return out_r;
}

/**
 * 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, dest, vec);
 *     let quatMat = mat4.create();
 *     mat4.fromQuat(quatMat, quat);
 *     mat4.multiply(dest, dest, quatMat);
 *     mat4.scale(dest, dest, scale)
 *
 * @param {mat4} out mat4 receiving operation result
 * @param {quat} 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, dest, vec);
 *     mat4.translate(dest, dest, origin);
 *     let quatMat = mat4.create();
 *     mat4.fromQuat(quatMat, quat);
 *     mat4.multiply(dest, dest, quatMat);
 *     mat4.scale(dest, dest, scale)
 *     mat4.translate(dest, dest, negativeOrigin);
 *
 * @param {mat4} out mat4 receiving operation result
 * @param {quat} 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);
  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) {
    var 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);
  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) {
    var 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.sqrt(z0 * z0 + z1 * z1 + z2 * z2);
  z0 *= len;
  z1 *= len;
  z2 *= len;
  x0 = upy * z2 - upz * z1;
  x1 = upz * z0 - upx * z2;
  x2 = upx * z1 - upy * z0;
  len = Math.sqrt(x0 * x0 + x1 * x1 + x2 * 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.sqrt(y0 * y0 + y1 * y1 + y2 * 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} target 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.sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2] + a[3] * a[3] + a[4] * a[4] + a[5] * a[5] + a[6] * a[6] + a[7] * a[7] + a[8] * a[8] + a[9] * a[9] + a[10] * a[10] + a[11] * a[11] + a[12] * a[12] + a[13] * a[13] + a[14] * a[14] + a[15] * 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$6,
copy: copy$5,
create: create$5,
decompose: decompose,
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$2,
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$5(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.sqrt(x * x + y * y + z * 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;
}

/**
 * symmetric 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] = round$3(a[0]);
  out[1] = round$3(a[1]);
  out[2] = round$3(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.sqrt(x * x + y * y + z * 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$5(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 spherical 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 slerp$1(out, a, b, t) {
  var angle = Math.acos(Math.min(Math.max(dot$5(a, b), -1), 1));
  var sinTotal = Math.sin(angle);
  var ratioA = Math.sin((1 - t) * angle) / sinTotal;
  var ratioB = Math.sin(t * angle) / sinTotal;
  out[0] = ratioA * a[0] + ratioB * b[0];
  out[1] = ratioA * a[1] + ratioB * b[1];
  out[2] = ratioA * a[2] + ratioB * b[2];
  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$1(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 omitted, a unit vector will be returned
 * @returns {vec3} out
 */
function random$3(out, scale) {
  scale = scale === undefined ? 1.0 : scale;
  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 normalized quaternion to transform with
 * @returns {vec3} out
 */
function transformQuat$1(out, a, q) {
  // Fast Vector Rotation using Quaternions by Robert Eisele
  // https://raw.org/proof/vector-rotation-using-quaternions/

  var qx = q[0],
    qy = q[1],
    qz = q[2],
    qw = q[3];
  var vx = a[0],
    vy = a[1],
    vz = a[2];

  // t = q x v
  var tx = qy * vz - qz * vy;
  var ty = qz * vx - qx * vz;
  var tz = qx * vy - qy * vx;

  // t = 2t
  tx = tx + tx;
  ty = ty + ty;
  tz = tz + tz;

  // v + w t + q x t
  out[0] = vx + qw * tx + qy * tz - qz * ty;
  out[1] = vy + qw * ty + qz * tx - qx * tz;
  out[2] = vz + qw * tz + qx * ty - qy * tx;
  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],
    mag = Math.sqrt((ax * ax + ay * ay + az * az) * (bx * bx + by * by + bz * bz)),
    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$1,
ceil: ceil$2,
clone: clone$5,
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$5,
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,
slerp: slerp$1,
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$4(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;
}

/**
 * symmetric 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] = round$3(a[0]);
  out[1] = round$3(a[1]);
  out[2] = round$3(a[2]);
  out[3] = round$3(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.sqrt(x * x + y * y + z * z + w * 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.sqrt(x * x + y * y + z * z + w * 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} out 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$4(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 omitted, a unit vector will be returned
 * @returns {vec4} out
 */
function random$2(out, scale) {
  scale = scale === undefined ? 1.0 : scale;

  // 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;
  var rand;
  rand = RANDOM();
  v1 = rand * 2 - 1;
  v2 = (4 * RANDOM() - 2) * Math.sqrt(rand * -rand + rand);
  s1 = v1 * v1 + v2 * v2;
  rand = RANDOM();
  v3 = rand * 2 - 1;
  v4 = (4 * RANDOM() - 2) * Math.sqrt(rand * -rand + rand);
  s2 = v3 * v3 + v4 * v4;
  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 normalized quaternion to transform with
 * @returns {vec4} out
 */
function transformQuat(out, a, q) {
  // Fast Vector Rotation using Quaternions by Robert Eisele
  // https://raw.org/proof/vector-rotation-using-quaternions/

  var qx = q[0],
    qy = q[1],
    qz = q[2],
    qw = q[3];
  var vx = a[0],
    vy = a[1],
    vz = a[2];

  // t = q x v
  var tx = qy * vz - qz * vy;
  var ty = qz * vx - qx * vz;
  var tz = qx * vy - qy * vx;

  // t = 2t
  tx = tx + tx;
  ty = ty + ty;
  tz = tz + tz;

  // v + w t + q x t
  out[0] = vx + qw * tx + qy * tz - qz * ty;
  out[1] = vy + qw * ty + qz * tx - qx * tz;
  out[2] = vz + qw * tz + qx * ty - qy * tx;
  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$4,
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$4,
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 in the format XYZW
 * @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 using the provided intrinsic order for the conversion.
 *
 * @param {quat} out the receiving quaternion
 * @param {Number} x Angle to rotate around X axis in degrees.
 * @param {Number} y Angle to rotate around Y axis in degrees.
 * @param {Number} z Angle to rotate around Z axis in degrees.
 * @param {'xyz'|'xzy'|'yxz'|'yzx'|'zxy'|'zyx'} order Intrinsic order for conversion, default is zyx.
 * @returns {quat} out
 * @function
 */
function fromEuler(out, x, y, z) {
  var order = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : ANGLE_ORDER;
  var halfToRad = Math.PI / 360;
  x *= halfToRad;
  z *= halfToRad;
  y *= 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);
  switch (order) {
    case "xyz":
      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;
      break;
    case "xzy":
      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;
      break;
    case "yxz":
      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;
      break;
    case "yzx":
      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;
      break;
    case "zxy":
      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;
      break;
    case "zyx":
      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;
      break;
    default:
      throw new Error('Unknown angle order ' + order);
  }
  return out;
}

/**
 * Returns a string representation of a quaternion
 *
 * @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$3 = clone$4;

/**
 * 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$3 = lerp$4;

/**
 * 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 point approximately to the same direction.
 *
 * Both quaternions are assumed to be unit length.
 *
 * @param {ReadonlyQuat} a The first unit quaternion.
 * @param {ReadonlyQuat} b The second unit quaternion.
 * @returns {Boolean} True if the quaternions are equal, false otherwise.
 */
function equals$3(a, b) {
  return Math.abs(dot$4(a, b)) >= 1 - EPSILON;
}

/**
 * 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$3,
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$3,
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<br>
 * Format: [real, dual]<br>
 * Quaternion format: XYZW<br>
 * Make sure to have normalized dual quaternions, otherwise the functions may not work as intended.<br>
 * @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$2(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 translation 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$1(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.sqrt(axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * 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$2(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 quaternion
 *
 * @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$2,
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$2,
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$1
});

/**
 * 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$1(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;
}

/**
 * symmetric 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] = round$3(a[0]);
  out[1] = round$3(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.sqrt(x * x + y * 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.sqrt(x * x + y * 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$1(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 omitted, a unit vector will be returned
 * @returns {vec2} out
 */
function random(out, scale) {
  scale = scale === undefined ? 1.0 : scale;
  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 smallest 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 ax = a[0],
    ay = a[1],
    bx = b[0],
    by = b[1];
  return Math.abs(Math.atan2(ay * bx - ax * by, ax * bx + ay * by));
}

/**
 * Get the signed angle in the interval [-pi,pi] between two 2D vectors (positive if `a` is to the right of `b`)
 * 
 * @param {ReadonlyVec2} a The first vector
 * @param {ReadonlyVec2} b The second vector
 * @returns {number} The signed angle in radians
 */
function signedAngle(a, b) {
  var ax = a[0],
    ay = a[1],
    bx = b[0],
    by = b[1];
  return Math.atan2(ax * by - ay * bx, ax * bx + ay * by);
}

/**
 * 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$1,
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$1,
max: max,
min: min,
mul: mul,
multiply: multiply,
negate: negate,
normalize: normalize,
random: random,
rotate: rotate,
round: round,
scale: scale,
scaleAndAdd: scaleAndAdd,
set: set,
signedAngle: signedAngle,
sqrDist: sqrDist,
sqrLen: sqrLen,
squaredDistance: squaredDistance,
squaredLength: squaredLength,
str: str,
sub: sub,
subtract: subtract,
transformMat2: transformMat2,
transformMat2d: transformMat2d,
transformMat3: transformMat3,
transformMat4: transformMat4,
zero: zero
});

/**
 * 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$1 = 8192;

/**
 * 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$1 / (tile.tileSize * Math.pow(2, z - tile.tileID.overscaledZ)));
}

/**
 * Ensures that a value is an `Error` instance.
 * If the value is already an `Error`, it is returned as-is.
 * Otherwise, a new `Error` is created from its string representation.
 */
function ensureError(e) {
    if (e instanceof Error)
        return e;
    return new Error(typeof e === 'string' ? e : String(e));
}
/**
 * Returns a new 64 bit float vec4 of zeroes.
 */
function createVec4f64() { return new Float64Array(4); }
/**
 * Returns a new 64 bit float vec3 of zeroes.
 */
function createVec3f64() { return new Float64Array(3); }
/**
 * Returns a new 64 bit float mat4 of zeroes.
 */
function createMat4f64() { return new Float64Array(16); }
/**
 * Returns a new 32 bit float mat4 of zeroes.
 */
function createMat4f32() { return new Float32Array(16); }
/**
 * Returns a new 64 bit float mat4 set to identity.
 */
function createIdentityMat4f64() {
    const m = new Float64Array(16);
    identity$2(m);
    return m;
}
/**
 * Returns a new 32 bit float mat4 set to identity.
 */
function createIdentityMat4f32() {
    const m = new Float32Array(16);
    identity$2(m);
    return m;
}
/**
 * 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.
 */
function translatePosition(transform, tile, translate, translateAnchor, inViewportPixelUnitsUnits = false) {
    if (!translate[0] && !translate[1])
        return [0, 0];
    const angle = inViewportPixelUnitsUnits ?
        (translateAnchor === 'map' ? -transform.bearingInRadians : 0) :
        (translateAnchor === 'viewport' ? transform.bearingInRadians : 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)
    ];
}
/**
 * Returns the signed distance between a point and a plane.
 * @param plane - The plane equation, in the form where the first three components are the normal and the fourth component is the plane's distance from origin along normal.
 * @param point - The point whose distance from plane is returned.
 * @returns Signed distance of the point from the plane. Positive distances are in the half space where the plane normal points to, negative otherwise.
 */
function pointPlaneSignedDistance(plane, point) {
    return plane[0] * point[0] + plane[1] * point[1] + plane[2] * point[2] + plane[3];
}
/**
 * Finds an intersection points of three planes. Returns `null` if no such (single) point exists.
 * The planes *must* be in Hessian normal form - their xyz components must form a unit vector.
 */
function threePlaneIntersection(plane0, plane1, plane2) {
    // https://mathworld.wolfram.com/Plane-PlaneIntersection.html
    const det = determinant$1([
        plane0[0], plane0[1], plane0[2],
        plane1[0], plane1[1], plane1[2],
        plane2[0], plane2[1], plane2[2]
    ]);
    if (det === 0) {
        return null;
    }
    const cross12 = cross$2([], [plane1[0], plane1[1], plane1[2]], [plane2[0], plane2[1], plane2[2]]);
    const cross20 = cross$2([], [plane2[0], plane2[1], plane2[2]], [plane0[0], plane0[1], plane0[2]]);
    const cross01 = cross$2([], [plane0[0], plane0[1], plane0[2]], [plane1[0], plane1[1], plane1[2]]);
    const sum = scale$4([], cross12, -plane0[3]);
    add$4(sum, sum, scale$4([], cross20, -plane1[3]));
    add$4(sum, sum, scale$4([], cross01, -plane2[3]));
    scale$4(sum, sum, 1.0 / det);
    return sum;
}
/**
 * Returns a parameter `t` such that the point obtained by
 * `origin + direction * t` lies on the given plane.
 * If the ray is parallel to the plane, returns null.
 * Returns a negative value if the ray is pointing away from the plane.
 * Direction does not need to be normalized.
 */
function rayPlaneIntersection(origin, direction, plane) {
    const dotOriginPlane = origin[0] * plane[0] + origin[1] * plane[1] + origin[2] * plane[2];
    const dotDirectionPlane = direction[0] * plane[0] + direction[1] * plane[1] + direction[2] * plane[2];
    if (dotDirectionPlane === 0) {
        return null;
    }
    return (-dotOriginPlane - plane[3]) / dotDirectionPlane;
}
/**
 * Solves a quadratic equation in the form ax^2 + bx + c = 0 and returns its roots in no particular order.
 * Returns null if the equation has no roots or if it has infinitely many roots.
 */
function solveQuadratic(a, b, c) {
    const d = b * b - 4 * a * c;
    if (d < 0 || (a === 0 && b === 0)) {
        return null;
    }
    // Uses a more precise solution from the book Ray Tracing Gems, chapter 7.
    // https://www.realtimerendering.com/raytracinggems/rtg/index.html
    const q = -0.5 * (b + Math.sign(b) * Math.sqrt(d));
    if (Math.abs(q) > 1e-12) {
        return {
            t0: c / q,
            t1: q / a
        };
    }
    else {
        // Use the schoolbook way if q is too small
        return {
            t0: (-b + Math.sqrt(d)) * 0.5 / a,
            t1: (-b + Math.sqrt(d)) * 0.5 / a
        };
    }
}
/**
 * Returns the angle in radians between two 2D vectors.
 * The angle is signed and describes how much the first vector would need to be be rotated clockwise
 * (assuming X is right and Y is down) so that it points in the same direction as the second vector.
 * @param vec1x - The X component of the first vector.
 * @param vec1y - The Y component of the first vector.
 * @param vec2x - The X component of the second vector.
 * @param vec2y - The Y component of the second vector.
 * @returns The signed angle between the two vectors, in range -PI..PI.
 */
function angleToRotateBetweenVectors2D(vec1x, vec1y, vec2x, vec2y) {
    // Normalize both vectors
    const length1 = Math.sqrt(vec1x * vec1x + vec1y * vec1y);
    const length2 = Math.sqrt(vec2x * vec2x + vec2y * vec2y);
    vec1x /= length1;
    vec1y /= length1;
    vec2x /= length2;
    vec2y /= length2;
    const dot = vec1x * vec2x + vec1y * vec2y;
    const angle = Math.acos(dot);
    // dot second vector with vector to the right of first (-vec1y, vec1x)
    const isVec2RightOfVec1 = (-vec1y * vec2x + vec1x * vec2y) > 0;
    if (isVec2RightOfVec1) {
        return angle;
    }
    else {
        return -angle;
    }
}
/**
 * For two angles in degrees, returns how many degrees to add to the first angle in order to obtain the second angle.
 * The returned difference value is always the shorted of the two - its absolute value is never greater than 180°.
 */
function differenceOfAnglesDegrees(degreesA, degreesB) {
    const a = mod(degreesA, 360);
    const b = mod(degreesB, 360);
    const diff1 = b - a;
    const diff2 = (b > a) ? (diff1 - 360) : (diff1 + 360);
    if (Math.abs(diff1) < Math.abs(diff2)) {
        return diff1;
    }
    else {
        return diff2;
    }
}
/**
 * For two angles in radians, returns how many radians to add to the first angle in order to obtain the second angle.
 * The returned difference value is always the shorted of the two - its absolute value is never greater than PI.
 */
function differenceOfAnglesRadians(degreesA, degreesB) {
    const a = mod(degreesA, Math.PI * 2);
    const b = mod(degreesB, Math.PI * 2);
    const diff1 = b - a;
    const diff2 = (b > a) ? (diff1 - Math.PI * 2) : (diff1 + Math.PI * 2);
    if (Math.abs(diff1) < Math.abs(diff2)) {
        return diff1;
    }
    else {
        return diff2;
    }
}
/**
 * When given two angles in degrees, returns the angular distance between them - the shorter one of the two possible arcs.
 */
function distanceOfAnglesDegrees(degreesA, degreesB) {
    const a = mod(degreesA, 360);
    const b = mod(degreesB, 360);
    return Math.min(Math.abs(a - b), Math.abs(a - b + 360), Math.abs(a - b - 360));
}
/**
 * When given two angles in radians, returns the angular distance between them - the shorter one of the two possible arcs.
 */
function distanceOfAnglesRadians(radiansA, radiansB) {
    const a = mod(radiansA, Math.PI * 2);
    const b = mod(radiansB, Math.PI * 2);
    return Math.min(Math.abs(a - b), Math.abs(a - b + Math.PI * 2), Math.abs(a - b - Math.PI * 2));
}
/**
 * Modulo function, as opposed to javascript's `%`, which is a remainder.
 * This functions will return positive values, even if the first operand is negative.
 */
function mod(n, m) {
    return ((n % m) + m) % m;
}
/**
 * Takes a value in *old range*, linearly maps that range to *new range*, and returns the value in that new range.
 * Additionally, if the value is outside *old range*, it is clamped inside it.
 * Also works if one of the ranges is flipped (its `min` being larger than `max`).
 */
function remapSaturate(value, oldRangeMin, oldRangeMax, newRangeMin, newRangeMax) {
    const inOldRange = clamp$2((value - oldRangeMin) / (oldRangeMax - oldRangeMin), 0.0, 1.0);
    return lerp(newRangeMin, newRangeMax, inOldRange);
}
/**
 * Linearly interpolate between two values, similar to `mix` function from GLSL. No clamping is done.
 * @param a - The first value to interpolate. This value is returned when mix=0.
 * @param b - The second value to interpolate. This value is returned when mix=1.
 * @param mix - The interpolation factor. Range 0..1 interpolates between `a` and `b`, but values outside this range are also accepted.
 */
function lerp(a, b, mix) {
    return a * (1.0 - mix) + b * mix;
}
/**
 * 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];
}
/**
 * For a given set of tile ids, returns the edge tile ids for the bounding box.
 */
function getEdgeTiles(tileIDs) {
    if (!tileIDs.length)
        return new Set();
    // set a common zoom for calculation (highest zoom) to reproject all tiles to this same zoom
    const targetZ = Math.max(...tileIDs.map(id => id.canonical.z));
    // vars to store the min and max tile x/y coordinates for edge finding
    let minX = Infinity, maxX = -Infinity;
    let minY = Infinity, maxY = -Infinity;
    // project all tiles to targetZ while maintaining the reference to the original tile
    const projected = [];
    for (const id of tileIDs) {
        const { x, y, z } = id.canonical;
        const scale = Math.pow(2, targetZ - z);
        const px = x * scale;
        const py = y * scale;
        projected.push({ id, x: px, y: py });
        if (px < minX)
            minX = px;
        if (px > maxX)
            maxX = px;
        if (py < minY)
            minY = py;
        if (py > maxY)
            maxY = py;
    }
    // find edge tiles using the reprojected tile ids
    const edgeTiles = new Set();
    for (const p of projected) {
        if (p.x === minX || p.x === maxX || p.y === minY || p.y === maxY) {
            edgeTiles.add(p.id);
        }
    }
    return edgeTiles;
}
/**
 * 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$1(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$2(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(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 (const k of properties) {
        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));
}
/**
 * Computes scaling from zoom level.
 */
function zoomScale(zoom) { return Math.pow(2, zoom); }
/**
 * Computes zoom level from scaling.
 */
function scaleZoom(scale) { return Math.log(scale) / Math.LN2; }
/**
 * Evaluates the snapped zoom level based on zoomSnap. If zoomSnap is 0 or less, the zoom level is returned unchanged.
 * If delta is provided, it performs directional snapping (ceil for zoom-in, floor for zoom-out).
 * @param zoom - The input zoom level
 * @param zoomSnap - The grid interval to snap to, e.g. 1.0 for 1.0 zoom levels, 0.5 for 0.5 zoom levels, etc.
 * @param delta - Optional scroll delta or direction. If positive, snaps up; if negative, snaps down.
 * @returns The snapped zoom level
 */
function evaluateZoomSnap(zoom, zoomSnap, delta) {
    if (zoomSnap <= 0)
        return zoom;
    const inv = 1 / zoomSnap;
    if (delta === undefined || Math.abs(delta) < 1e-10) {
        return Math.round(zoom * inv) / inv;
    }
    return (delta > 0 ? Math.ceil(zoom * inv - 1e-9) : Math.floor(zoom * inv + 1e-10)) / inv;
}
/**
 * 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(input) {
    if (Array.isArray(input)) {
        return input.map(clone);
    }
    else if (typeof input === 'object' && input) {
        return mapObject(input, clone);
    }
    else {
        return input;
    }
}
/**
 * Check if two arrays have at least one common element.
 */
function arraysIntersect(a, b) {
    for (const element of a) {
        if (b.includes(element))
            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(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 (_a) {
        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 ${ensureError(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 (_a) {
                // 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;
}
/**
 * This method converts radians to degrees.
 * The return value is the degrees value.
 * @param degrees - The number of radians
 * @returns degrees
 */
function radiansToDegrees(degrees) {
    return degrees / Math.PI * 180;
}
function rollPitchBearingEqual(a, b) {
    return a.roll == b.roll && a.pitch == b.pitch && a.bearing == b.bearing;
}
/**
 * This method converts a rotation quaternion to roll, pitch, and bearing angles in degrees.
 * @param rotation - The rotation quaternion
 * @returns roll, pitch, and bearing angles in degrees
 */
function getRollPitchBearing(rotation) {
    const m = new Float64Array(9);
    fromQuat$1(m, rotation);
    const xAngle = radiansToDegrees(-Math.asin(clamp$2(m[2], -1, 1)));
    let roll;
    let bearing;
    if (Math.hypot(m[5], m[8]) < 1.0e-3) {
        roll = 0.0;
        bearing = -radiansToDegrees(Math.atan2(m[3], m[4]));
    }
    else {
        roll = radiansToDegrees((m[5] === 0.0 && m[8] === 0.0) ? 0.0 : Math.atan2(m[5], m[8]));
        bearing = radiansToDegrees((m[1] === 0.0 && m[0] === 0.0) ? 0.0 : Math.atan2(m[1], m[0]));
    }
    return { roll, pitch: xAngle + 90.0, bearing };
}
function getAngleDelta(lastPoint, currentPoint, center) {
    const pointVect = fromValues(currentPoint.x - center.x, currentPoint.y - center.y);
    const lastPointVec = fromValues(lastPoint.x - center.x, lastPoint.y - center.y);
    const crossProduct = pointVect[0] * lastPointVec[1] - pointVect[1] * lastPointVec[0];
    const angleRadians = Math.atan2(crossProduct, dot$1(pointVect, lastPointVec));
    return radiansToDegrees(angleRadians);
}
/**
 * This method converts roll, pitch, and bearing angles in degrees to a rotation quaternion.
 * @param roll - Roll angle in degrees
 * @param pitch - Pitch angle in degrees
 * @param bearing - Bearing angle in degrees
 * @returns The rotation quaternion
 */
function rollPitchBearingToQuat(roll, pitch, bearing) {
    const rotation = new Float64Array(4);
    fromEuler(rotation, roll, pitch - 90.0, bearing);
    return rotation;
}
/**
 * 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;
const MAX_VALID_LATITUDE = 85.051129;
const touchableEvents = {
    touchstart: true,
    touchmove: true,
    touchmoveWindow: true,
    touchend: true,
    touchcancel: true
};
const pointableEvents = {
    dblclick: true,
    click: true,
    mouseover: true,
    mouseout: true,
    mousedown: true,
    mousemove: true,
    mousemoveWindow: true,
    mouseup: true,
    mouseupWindow: true,
    contextmenu: true,
    wheel: true
};
function isTouchableEvent(event, eventType) {
    return touchableEvents[eventType] && 'touches' in event;
}
/**
 * Checks if an event is a pointable event (mouse or wheel event).
 * Uses the event target's window context for cross-window support.
 */
function isPointableEvent(event, eventType) {
    var _a;
    if (!pointableEvents[eventType])
        return false;
    // Get the window context from the event target to use the correct constructor.
    const domEvent = event;
    const target = domEvent === null || domEvent === void 0 ? void 0 : domEvent.target;
    const targetWindow = ((_a = target === null || target === void 0 ? void 0 : target.ownerDocument) === null || _a === void 0 ? void 0 : _a.defaultView) || window;
    return domEvent instanceof targetWindow.MouseEvent || domEvent instanceof targetWindow.WheelEvent;
}
function isTouchableOrPointableType(eventType) {
    return touchableEvents[eventType] || pointableEvents[eventType];
}

/**
 * An error message to use when an operation is aborted
 */
const ABORT_ERROR = 'AbortError';
class AbortError extends Error {
    constructor(messageOrError = ABORT_ERROR) {
        super(messageOrError instanceof Error ? messageOrError.message : messageOrError);
        this.name = ABORT_ERROR;
        if (messageOrError instanceof Error && messageOrError.stack) {
            this.stack = messageOrError.stack;
        }
    }
}
/**
 * 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 instanceof Error && error.name === ABORT_ERROR;
}
/**
 * Throws an AbortError if the provided abort signal has already been aborted.
 *
 * @param signal - The abort signal to check.
 * @throws AbortError If the signal is aborted.
 */
function throwIfAborted(signal) {
    if (signal.aborted) {
        throw new AbortError(signal.reason);
    }
}

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');
 * });
 * ```
 * @see [Add a COG raster source](https://maplibre.org/maplibre-gl-js/docs/examples/add-a-cog-raster-source/)
 * @see [Add Contour Lines](https://maplibre.org/maplibre-gl-js/docs/examples/add-contour-lines/)
 * @see [PMTiles source and protocol](https://maplibre.org/maplibre-gl-js/docs/examples/pmtiles-source-and-protocol/)
 * @see [Use addProtocol to Transform Feature Properties](https://maplibre.org/maplibre-gl-js/docs/examples/use-addprotocol-to-transform-feature-properties/)
 */
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 = () => {
    var _a;
    return isWorker(self) ?
        (_a = self.worker) === null || _a === void 0 ? void 0 : _a.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 => { var _a; return url.startsWith('file:') || (((_a = getReferrer()) === null || _a === void 0 ? void 0 : _a.startsWith('file:')) && !/^\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(),
            referrerPolicy: requestParameters.referrerPolicy,
            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');
        }
        let response;
        try {
            response = yield fetch(request);
        }
        catch (e) {
            // Pass through AbortErrors for upstream handling
            if (isAbortError(e)) {
                throw e;
            }
            // When the error is due to CORS policy, DNS issue or malformed URL, the fetch call does not resolve but throws a generic TypeError instead.
            // It is preferable to throw an AJAXError so that the Map event "error" can catch it and still have
            // access to the faulty url. In such case, we provide the arbitrary HTTP error code of `0`.
            throw new AJAXError(0, ensureError(e).message, requestParameters.url, new Blob());
        }
        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;
        throwIfAborted(abortController.signal);
        return { data: result, cacheControl: response.headers.get('Cache-Control'), expires: response.headers.get('Expires'), etag: response.headers.get('ETag') };
    });
}
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'), etag: xhr.getResponseHeader('ETag') });
            }
            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(new AbortError(abortController.signal.reason));
        });
        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) {
    return __awaiter(this, void 0, void 0, function* () {
        var _a, _b;
        if (requestParameters.url.includes('://') && !(/^https?:|^file:/.test(requestParameters.url))) {
            const protocolLoadFn = getProtocol(requestParameters.url);
            if (protocolLoadFn) {
                const response = yield protocolLoadFn(requestParameters, abortController);
                if (!response.data && requestParameters.type === 'arrayBuffer') {
                    // A successful array buffer request should always return data even if empty
                    return extend(response, { data: new ArrayBuffer(0) });
                }
                return response;
            }
            if (isWorker(self) && ((_a = self.worker) === null || _a === void 0 ? void 0 : _a.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.hasOwn(Request.prototype, 'signal')) {
                return makeFetchRequest(requestParameters, abortController);
            }
            if (isWorker(self) && ((_b = self.worker) === null || _b === void 0 ? void 0 : _b.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.startsWith('data:image/') || // data image URL
        inComingUrl.startsWith('blob:')) { // 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) {
    var _a;
    const listenerExists = (_a = listenerList[type]) === null || _a === void 0 ? void 0 : _a.includes(listener);
    if (!listenerExists) {
        listenerList[type] = listenerList[type] || [];
        listenerList[type].push(listener);
    }
}
function _removeEventListener(type, listener, listenerList) {
    if (listenerList === null || listenerList === void 0 ? void 0 : 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 {
            unsubscribe: () => {
                this.off(type, listener);
            }
        };
    }
    /**
     * 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) {
        var _a, _b;
        // 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 = ((_a = this._listeners) === null || _a === void 0 ? void 0 : _a[type]) ? this._listeners[type].slice() : [];
            for (const listener of listeners) {
                listener.call(this, event);
            }
            const oneTimeListeners = ((_b = this._oneTimeListeners) === null || _b === void 0 ? void 0 : _b[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) {
        var _a, _b, _c, _d, _e;
        return ((((_b = (_a = this._listeners) === null || _a === void 0 ? void 0 : _a[type]) === null || _b === void 0 ? void 0 : _b.length) > 0) ||
            (((_d = (_c = this._oneTimeListeners) === null || _c === void 0 ? void 0 : _c[type]) === null || _d === void 0 ? void 0 : _d.length) > 0) ||
            ((_e = this._eventedParent) === null || _e === void 0 ? void 0 : _e.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",
		length: 2
	},
	centerAltitude: {
		type: "number"
	},
	zoom: {
		type: "number"
	},
	bearing: {
		type: "number",
		"default": 0,
		period: 360,
		units: "degrees"
	},
	pitch: {
		type: "number",
		"default": 0,
		units: "degrees"
	},
	roll: {
		type: "number",
		"default": 0,
		units: "degrees"
	},
	state: {
		type: "state",
		"default": {
		}
	},
	light: {
		type: "light"
	},
	sky: {
		type: "sky"
	},
	projection: {
		type: "projection"
	},
	terrain: {
		type: "terrain"
	},
	sources: {
		required: true,
		type: "sources"
	},
	sprite: {
		type: "sprite"
	},
	glyphs: {
		type: "string"
	},
	"font-faces": {
		type: "fontFaces"
	},
	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
	},
	encoding: {
		type: "enum",
		values: {
			mvt: {
			},
			mlt: {
			}
		},
		"default": "mvt"
	},
	"*": {
		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: "filter"
	},
	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: {
			},
			"color-relief": {
			},
			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_color-relief",
	"layout_background"
];
var layout_background = {
	visibility: {
		type: "enum",
		values: {
			visible: {
			},
			none: {
			}
		},
		"default": "visible",
		expression: {
			interpolated: false,
			parameters: [
				"global-state"
			]
		},
		"property-type": "data-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",
		expression: {
			interpolated: false,
			parameters: [
				"global-state"
			]
		},
		"property-type": "data-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",
		expression: {
			interpolated: false,
			parameters: [
				"global-state"
			]
		},
		"property-type": "data-constant"
	}
};
var layout_heatmap = {
	visibility: {
		type: "enum",
		values: {
			visible: {
			},
			none: {
			}
		},
		"default": "visible",
		expression: {
			interpolated: false,
			parameters: [
				"global-state"
			]
		},
		"property-type": "data-constant"
	}
};
var layout_line = {
	"line-cap": {
		type: "enum",
		values: {
			butt: {
			},
			round: {
			},
			square: {
			}
		},
		"default": "butt",
		expression: {
			interpolated: false,
			parameters: [
				"zoom",
				"feature"
			]
		},
		"property-type": "data-driven"
	},
	"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",
				"feature"
			]
		},
		"property-type": "data-driven"
	},
	"line-round-limit": {
		type: "number",
		"default": 1.05,
		requires: [
			{
				"line-join": "round"
			}
		],
		expression: {
			interpolated: true,
			parameters: [
				"zoom",
				"feature"
			]
		},
		"property-type": "data-driven"
	},
	"line-sort-key": {
		type: "number",
		expression: {
			interpolated: false,
			parameters: [
				"zoom",
				"feature"
			]
		},
		"property-type": "data-driven"
	},
	visibility: {
		type: "enum",
		values: {
			visible: {
			},
			none: {
			}
		},
		"default": "visible",
		expression: {
			interpolated: false,
			parameters: [
				"global-state"
			]
		},
		"property-type": "data-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",
		expression: {
			interpolated: false,
			parameters: [
				"global-state"
			]
		},
		"property-type": "data-constant"
	}
};
var layout_raster = {
	visibility: {
		type: "enum",
		values: {
			visible: {
			},
			none: {
			}
		},
		"default": "visible",
		expression: {
			interpolated: false,
			parameters: [
				"global-state"
			]
		},
		"property-type": "data-constant"
	}
};
var layout_hillshade = {
	visibility: {
		type: "enum",
		values: {
			visible: {
			},
			none: {
			}
		},
		"default": "visible",
		expression: {
			interpolated: false,
			parameters: [
				"global-state"
			]
		},
		"property-type": "data-constant"
	}
};
var filter = {
	type: "boolean",
	expression: {
		interpolated: false,
		parameters: [
			"zoom",
			"feature"
		]
	},
	"property-type": "data-driven"
};
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: "expression_name",
	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: "projectionDefinition",
		"default": "mercator",
		"property-type": "data-constant",
		transition: false,
		expression: {
			interpolated: true,
			parameters: [
				"zoom"
			]
		}
	}
};
var paint$a = [
	"paint_fill",
	"paint_line",
	"paint_circle",
	"paint_heatmap",
	"paint_fill-extrusion",
	"paint_symbol",
	"paint_raster",
	"paint_hillshade",
	"paint_color-relief",
	"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",
				"feature"
			]
		},
		"property-type": "cross-faded-data-driven"
	},
	"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"
	},
	resampling: {
		type: "enum",
		values: {
			linear: {
			},
			nearest: {
			}
		},
		"default": "linear",
		expression: {
			interpolated: false,
			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: "numberArray",
		"default": 335,
		minimum: 0,
		maximum: 359,
		transition: false,
		expression: {
			interpolated: true,
			parameters: [
				"zoom"
			]
		},
		"property-type": "data-constant"
	},
	"hillshade-illumination-altitude": {
		type: "numberArray",
		"default": 45,
		minimum: 0,
		maximum: 90,
		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: "colorArray",
		"default": "#000000",
		transition: true,
		expression: {
			interpolated: true,
			parameters: [
				"zoom"
			]
		},
		"property-type": "data-constant"
	},
	"hillshade-highlight-color": {
		type: "colorArray",
		"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"
	},
	"hillshade-method": {
		type: "enum",
		values: {
			standard: {
			},
			basic: {
			},
			combined: {
			},
			igor: {
			},
			multidirectional: {
			}
		},
		"default": "standard",
		expression: {
			interpolated: false,
			parameters: [
				"zoom"
			]
		},
		"property-type": "data-constant"
	},
	resampling: {
		type: "enum",
		values: {
			linear: {
			},
			nearest: {
			}
		},
		"default": "linear",
		expression: {
			interpolated: false,
			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 interpolation = {
	type: "array",
	value: "interpolation_name",
	minimum: 1
};
var interpolation_name = {
	type: "enum",
	values: {
		linear: {
			syntax: {
				overloads: [
					{
						parameters: [
						],
						"output-type": "interpolation"
					}
				],
				parameters: [
				]
			}
		},
		exponential: {
			syntax: {
				overloads: [
					{
						parameters: [
							"base"
						],
						"output-type": "interpolation"
					}
				],
				parameters: [
					{
						name: "base",
						type: "number literal"
					}
				]
			}
		},
		"cubic-bezier": {
			syntax: {
				overloads: [
					{
						parameters: [
							"x1",
							"y1",
							"x2",
							"y2"
						],
						"output-type": "interpolation"
					}
				],
				parameters: [
					{
						name: "x1",
						type: "number literal"
					},
					{
						name: "y1",
						type: "number literal"
					},
					{
						name: "x2",
						type: "number literal"
					},
					{
						name: "y2",
						type: "number literal"
					}
				]
			}
		}
	}
};
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",
		expression: {
			interpolated: false,
			parameters: [
				"global-state"
			]
		},
		"property-type": "data-constant"
	}
},
	layout_line: layout_line,
	layout_symbol: layout_symbol,
	layout_raster: layout_raster,
	layout_hillshade: layout_hillshade,
	"layout_color-relief": {
	visibility: {
		type: "enum",
		values: {
			visible: {
			},
			none: {
			}
		},
		"default": "visible",
		expression: {
			interpolated: false,
			parameters: [
				"global-state"
			]
		},
		"property-type": "data-constant"
	}
},
	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$a,
	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_color-relief": {
	"color-relief-opacity": {
		type: "number",
		"default": 1,
		minimum: 0,
		maximum: 1,
		transition: true,
		expression: {
			interpolated: true,
			parameters: [
				"zoom"
			]
		},
		"property-type": "data-constant"
	},
	"color-relief-color": {
		type: "color",
		transition: false,
		expression: {
			interpolated: true,
			parameters: [
				"elevation"
			]
		},
		"property-type": "color-ramp"
	},
	resampling: {
		type: "enum",
		values: {
			linear: {
			},
			nearest: {
			}
		},
		"default": "linear",
		expression: {
			interpolated: false,
			parameters: [
				"zoom"
			]
		},
		"property-type": "data-constant"
	}
},
	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,
	interpolation: interpolation,
	interpolation_name: interpolation_name
};

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;
}
/**
 *
 * The input is not modified. The output may contain references to portions
 * of the input.
 *
 * @param layers - array of layers, some of which may contain `ref` properties
 * whose value is the `id` of another property
 * @returns 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.
 */
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 diff(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.state, after.state)) {
            commands.push({ command: 'setGlobalState', args: [after.state] });
        }
        if (!deepEqual(before.centerAltitude, after.centerAltitude)) {
            commands.push({ command: 'setCenterAltitude', args: [after.centerAltitude] });
        }
        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.roll, after.roll)) {
            commands.push({ command: 'setRoll', args: [after.roll] });
        }
        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 ProjectionDefinitionType = {
    kind: 'projectionDefinition'
};
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 ColorArrayType = { kind: 'colorArray' };
const NumberArrayType = { kind: 'numberArray' };
const ResolvedImageType = { kind: 'resolvedImage' };
const VariableAnchorOffsetCollectionType = {
    kind: 'variableAnchorOffsetCollection'
};
function array(itemType, N) {
    return {
        kind: 'array',
        itemType,
        N
    };
}
function typeToString(type) {
    if (type.kind === 'array') {
        const itemType = typeToString(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,
    ProjectionDefinitionType,
    FormattedType,
    ObjectType,
    array(ValueType),
    PaddingType,
    NumberArrayType,
    ColorArrayType,
    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 ${typeToString(expected)} but found ${typeToString(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.033454 * 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];
}

// polyfill for Object.hasOwn
const hasOwnProperty = Object.hasOwn ||
    function hasOwnProperty(object, key) {
        return Object.prototype.hasOwnProperty.call(object, key);
    };
function getOwn(object, key) {
    return hasOwnProperty(object, key) ? object[key] : undefined;
}

/**
 * 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:
 *
 * <alpha-value> = <number> | <percentage>
 *         <hue> = <number> | <angle>
 *
 *         rgb() = rgb( <percentage>{3} [ / <alpha-value> ]? ) | rgb( <number>{3} [ / <alpha-value> ]? )
 *         rgb() = rgb( <percentage>#{3} , <alpha-value>? )    | rgb( <number>#{3} , <alpha-value>? )
 *
 *         hsl() = hsl( <hue> <percentage> <percentage> [ / <alpha-value> ]? )
 *         hsl() = hsl( <hue>, <percentage>, <percentage>, <alpha-value>? )
 *
 * Caveats:
 *   - <angle> - <number> 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 = getOwn(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, // <numeric>
            rp, // %         (optional)
            f1, // ,         (optional)
            g, // <numeric>
            gp, // %         (optional)
            f2, // ,         (optional)
            b, // <numeric>
            bp, // %         (optional)
            f3, // ,|/       (optional)
            a, // <numeric> (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$1(+r / maxValue, 0, 1),
                        clamp$1(+g / maxValue, 0, 1),
                        clamp$1(+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, // <numeric>
        f1, // ,         (optional)
        s, // <numeric>
        f2, // ,         (optional)
        l, // <numeric>
        f3, // ,|/       (optional)
        a, // <numeric> (optional)
        ap // %         (optional)
        ] = hslMatch;
        const argFormat = [f1 || ' ', f2 || ' ', f3].join('');
        if (argFormat === '  ' ||
            argFormat === '  /' ||
            argFormat === ',,' ||
            argFormat === ',,,') {
            const hsla = [
                +h,
                clamp$1(+s, 0, 100),
                clamp$1(+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$1(asPercentage ? a / 100 : a, 0, 1);
}
function clamp$1(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]
};

function interpolateNumber(from, to, t) {
    return from + t * (to - from);
}
function interpolateArray(from, to, t) {
    return from.map((d, i) => {
        return interpolateNumber(d, to[i], t);
    });
}

/**
 * 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';
}
/**
 * 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})`;
    }
    static interpolate(from, to, t, spaceKey = 'rgb') {
        switch (spaceKey) {
            case 'rgb': {
                const [r, g, b, alpha] = interpolateArray(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 : interpolateNumber(chroma0, chroma1, t),
                    interpolateNumber(light0, light1, t),
                    interpolateNumber(alphaF, alphaT, t)
                ]);
                return new Color(r, g, b, alpha, false);
            }
            case 'lab': {
                const [r, g, b, alpha] = labToRgb(interpolateArray(from.lab, to.lab, t));
                return new Color(r, g, b, alpha, false);
            }
        }
    }
}
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);

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;
    }
}

const VERTICAL_ALIGN_OPTIONS = ['bottom', 'center', 'top'];
class FormattedSection {
    constructor(text, image, scale, fontStack, textColor, verticalAlign) {
        this.text = text;
        this.image = image;
        this.scale = scale;
        this.fontStack = fontStack;
        this.textColor = textColor;
        this.verticalAlign = verticalAlign;
    }
}
class Formatted {
    constructor(sections) {
        this.sections = sections;
    }
    static fromString(unformatted) {
        return new Formatted([new FormattedSection(unformatted, null, 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);
    }
    static interpolate(from, to, t) {
        return new Padding(interpolateArray(from.values, to.values, t));
    }
}

/**
 * An array of numbers. Create instances from
 * bare arrays or numeric values using the static method `NumberArray.parse`.
 * @private
 */
class NumberArray {
    constructor(values) {
        this.values = values.slice();
    }
    /**
     * Numeric NumberArray values
     * @param input A NumberArray value
     * @returns A `NumberArray` instance, or `undefined` if the input is not a valid NumberArray value.
     */
    static parse(input) {
        if (input instanceof NumberArray) {
            return input;
        }
        // Backwards compatibility (e.g. hillshade-illumination-direction): bare number is treated the same as array with single value.
        if (typeof input === 'number') {
            return new NumberArray([input]);
        }
        if (!Array.isArray(input)) {
            return undefined;
        }
        for (const val of input) {
            if (typeof val !== 'number') {
                return undefined;
            }
        }
        return new NumberArray(input);
    }
    toString() {
        return JSON.stringify(this.values);
    }
    static interpolate(from, to, t) {
        return new NumberArray(interpolateArray(from.values, to.values, t));
    }
}

/**
 * An array of colors. Create instances from
 * bare arrays or strings using the static method `ColorArray.parse`.
 * @private
 */
class ColorArray {
    constructor(values) {
        this.values = values.slice();
    }
    /**
     * ColorArray values
     * @param input A ColorArray value
     * @returns A `ColorArray` instance, or `undefined` if the input is not a valid ColorArray value.
     */
    static parse(input) {
        if (input instanceof ColorArray) {
            return input;
        }
        // Backwards compatibility (e.g. hillshade-shadow-color): bare Color is treated the same as array with single value.
        if (typeof input === 'string') {
            const parsed_val = Color.parse(input);
            if (!parsed_val) {
                return undefined;
            }
            return new ColorArray([parsed_val]);
        }
        if (!Array.isArray(input)) {
            return undefined;
        }
        const colors = [];
        for (const val of input) {
            if (typeof val !== 'string') {
                return undefined;
            }
            const parsed_val = Color.parse(val);
            if (!parsed_val) {
                return undefined;
            }
            colors.push(parsed_val);
        }
        return new ColorArray(colors);
    }
    toString() {
        return JSON.stringify(this.values);
    }
    static interpolate(from, to, t, spaceKey = 'rgb') {
        const colors = [];
        if (from.values.length != to.values.length) {
            throw new Error(`colorArray: Arrays have mismatched length (${from.values.length} vs. ${to.values.length}), cannot interpolate.`);
        }
        for (let i = 0; i < from.values.length; i++) {
            colors.push(Color.interpolate(from.values[i], to.values[i], t, spaceKey));
        }
        return new ColorArray(colors);
    }
}

class RuntimeError extends Error {
    constructor(message) {
        super(message);
        this.name = 'RuntimeError';
    }
    toJSON() {
        return this.message;
    }
}

/** 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);
    }
    static interpolate(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([interpolateNumber(fx, tx, t), interpolateNumber(fy, ty, t)]);
        }
        return new VariableAnchorOffsetCollection(output);
    }
}

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 });
    }
}

class ProjectionDefinition {
    constructor(from, to, transition) {
        this.from = from;
        this.to = to;
        this.transition = transition;
    }
    static interpolate(from, to, t) {
        return new ProjectionDefinition(from, to, t);
    }
    static parse(input) {
        if (input instanceof ProjectionDefinition) {
            return input;
        }
        if (Array.isArray(input) &&
            input.length === 3 &&
            typeof input[0] === 'string' &&
            typeof input[1] === 'string' &&
            typeof input[2] === 'number') {
            return new ProjectionDefinition(input[0], input[1], input[2]);
        }
        if (typeof input === 'object' &&
            typeof input.from === 'string' &&
            typeof input.to === 'string' &&
            typeof input.transition === 'number') {
            return new ProjectionDefinition(input.from, input.to, input.transition);
        }
        if (typeof input === 'string') {
            return new ProjectionDefinition(input, input, 1);
        }
        return undefined;
    }
}

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 ProjectionDefinition ||
        mixed instanceof Color ||
        mixed instanceof Collator ||
        mixed instanceof Formatted ||
        mixed instanceof Padding ||
        mixed instanceof NumberArray ||
        mixed instanceof ColorArray ||
        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 ProjectionDefinition) {
        return ProjectionDefinitionType;
    }
    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 NumberArray) {
        return NumberArrayType;
    }
    else if (value instanceof ColorArray) {
        return ColorArrayType;
    }
    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(itemType || ValueType, length);
    }
    else {
        return ObjectType;
    }
}
function valueToString(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 ProjectionDefinition ||
        value instanceof Formatted ||
        value instanceof Padding ||
        value instanceof NumberArray ||
        value instanceof ColorArray ||
        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;
    }
}

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(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 ${typeToString(this.type)}, but found ${typeToString(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 rgba 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 'numberArray': {
                let input;
                for (const arg of this.args) {
                    input = arg.evaluate(ctx);
                    const val = NumberArray.parse(input);
                    if (val) {
                        return val;
                    }
                }
                throw new RuntimeError(`Could not parse numberArray from value '${typeof input === 'string' ? input : JSON.stringify(input)}'`);
            }
            case 'colorArray': {
                let input;
                for (const arg of this.args) {
                    input = arg.evaluate(ctx);
                    const val = ColorArray.parse(input);
                    if (val) {
                        return val;
                    }
                }
                throw new RuntimeError(`Could not parse colorArray 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(valueToString(this.args[0].evaluate(ctx)));
            case 'resolvedImage':
                return ResolvedImage.fromString(valueToString(this.args[0].evaluate(ctx)));
            case 'projectionDefinition':
                return this.args[0].evaluate(ctx);
            default:
                return valueToString(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 = new Map();
        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.get(input);
        if (!cached) {
            cached = Color.parse(input);
            this._parseColorCache.set(input, cached);
        }
        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 (('projectionDefinition' === expected.kind &&
                        ['string', 'array'].includes(actual.kind)) ||
                        (['color', 'formatted', 'resolvedImage'].includes(expected.kind) &&
                            ['value', 'string'].includes(actual.kind)) ||
                        (['padding', 'numberArray'].includes(expected.kind) &&
                            ['value', 'number', 'array'].includes(actual.kind)) ||
                        ('colorArray' === expected.kind &&
                            ['value', 'string', 'array'].includes(actual.kind)) ||
                        ('variableAnchorOffsetCollection' === expected.kind &&
                            ['value', 'array'].includes(actual.kind))) {
                        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(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 ${typeToString(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 ${typeToString(typeOf(needle))} instead.`);
        }
        if (!isValidNativeType(haystack, ['string', 'array'])) {
            throw new RuntimeError(`Expected second argument to be of type array or string, but found ${typeToString(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 2 or 3 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 ${typeToString(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 ${typeToString(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 ${typeToString(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 2 or 3 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(ValueType), StringType, ValueType])) {
            return context.error(`Expected first argument to be of type array or string, but found ${typeToString(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 ${typeToString(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;
var hasRequiredUnitbezier;

function requireUnitbezier () {
	if (hasRequiredUnitbezier) return unitbezier;
	hasRequiredUnitbezier = 1;

	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));
	    }
	};
	return unitbezier;
}

var unitbezierExports = requireUnitbezier();
var UnitBezier = /*@__PURE__*/getDefaultExportFromCjs(unitbezierExports);

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(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') &&
            context.expectedType != ColorArrayType) {
            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, ProjectionDefinitionType) &&
            !verifyType(outputType, ColorType) &&
            !verifyType(outputType, PaddingType) &&
            !verifyType(outputType, NumberArrayType) &&
            !verifyType(outputType, ColorArrayType) &&
            !verifyType(outputType, VariableAnchorOffsetCollectionType) &&
            !verifyType(outputType, array(NumberType))) {
            return context.error(`Type ${typeToString(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':
                switch (this.type.kind) {
                    case 'number':
                        return interpolateNumber(outputLower, outputUpper, t);
                    case 'color':
                        return Color.interpolate(outputLower, outputUpper, t);
                    case 'padding':
                        return Padding.interpolate(outputLower, outputUpper, t);
                    case 'colorArray':
                        return ColorArray.interpolate(outputLower, outputUpper, t);
                    case 'numberArray':
                        return NumberArray.interpolate(outputLower, outputUpper, t);
                    case 'variableAnchorOffsetCollection':
                        return VariableAnchorOffsetCollection.interpolate(outputLower, outputUpper, t);
                    case 'array':
                        return interpolateArray(outputLower, outputUpper, t);
                    case 'projectionDefinition':
                        return ProjectionDefinition.interpolate(outputLower, outputUpper, t);
                }
            case 'interpolate-hcl':
                switch (this.type.kind) {
                    case 'color':
                        return Color.interpolate(outputLower, outputUpper, t, 'hcl');
                    case 'colorArray':
                        return ColorArray.interpolate(outputLower, outputUpper, t, 'hcl');
                }
            case 'interpolate-lab':
                switch (this.type.kind) {
                    case 'color':
                        return Color.interpolate(outputLower, outputUpper, t, 'lab');
                    case 'colorArray':
                        return ColorArray.interpolate(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);
    }
}
const interpolateFactory = {
    color: Color.interpolate,
    number: interpolateNumber,
    padding: Padding.interpolate,
    numberArray: NumberArray.interpolate,
    colorArray: ColorArray.interpolate,
    variableAnchorOffsetCollection: VariableAnchorOffsetCollection.interpolate,
    array: interpolateArray
};

class Coalesce {
    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 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 '${typeToString(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 '${typeToString(rhs.type)}'.`);
            }
            if (lhs.type.kind !== rhs.type.kind &&
                lhs.type.kind !== 'value' &&
                rhs.type.kind !== 'value') {
                return context.error(`Cannot compare types '${typeToString(lhs.type)}' and '${typeToString(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, unit, minFractionDigits, maxFractionDigits) {
        this.type = StringType;
        this.number = number;
        this.locale = locale;
        this.currency = currency;
        this.unit = unit;
        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 unit = null;
        if (options['unit']) {
            unit = context.parse(options['unit'], 1, StringType);
            if (!unit)
                return null;
        }
        if (currency && unit) {
            return context.error('NumberFormat options `currency` and `unit` are mutually exclusive');
        }
        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, unit, minFractionDigits, maxFractionDigits);
    }
    evaluate(ctx) {
        return new Intl.NumberFormat(this.locale ? this.locale.evaluate(ctx) : [], {
            style: this.currency ? 'currency' : this.unit ? 'unit' : 'decimal',
            currency: this.currency ? this.currency.evaluate(ctx) : undefined,
            unit: this.unit ? this.unit.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.unit) {
            fn(this.unit);
        }
        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(StringType));
                    if (!font)
                        return null;
                }
                let textColor = null;
                if (arg['text-color']) {
                    textColor = context.parse(arg['text-color'], 1, ColorType);
                    if (!textColor)
                        return null;
                }
                let verticalAlign = null;
                if (arg['vertical-align']) {
                    if (typeof arg['vertical-align'] === 'string' &&
                        !VERTICAL_ALIGN_OPTIONS.includes(arg['vertical-align'])) {
                        return context.error(`'vertical-align' must be one of: 'bottom', 'center', 'top' but found '${arg['vertical-align']}' instead.`);
                    }
                    verticalAlign = context.parse(arg['vertical-align'], 1, StringType);
                    if (!verticalAlign)
                        return null;
                }
                const lastExpression = sections[sections.length - 1];
                lastExpression.scale = scale;
                lastExpression.font = font;
                lastExpression.textColor = textColor;
                lastExpression.verticalAlign = verticalAlign;
            }
            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,
                    verticalAlign: 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, section.verticalAlign ? section.verticalAlign.evaluate(ctx) : null);
            }
            return new FormattedSection(valueToString(evaluatedContent), null, section.scale ? section.scale.evaluate(ctx) : null, section.font ? section.font.evaluate(ctx).join(',') : null, section.textColor ? section.textColor.evaluate(ctx) : null, section.verticalAlign ? section.verticalAlign.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);
            }
            if (section.verticalAlign) {
                fn(section.verticalAlign);
            }
        }
    }
    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 ${typeToString(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 ${typeToString(typeOf(input))} instead.`);
        }
    }
    eachChild(fn) {
        fn(this.input);
    }
    outputDefined() {
        return false;
    }
}

const EXTENT = 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), Math.round(y * tilesAtZoom * EXTENT)];
}
function getLngLatFromTileCoord(coord, canonical) {
    const tilesAtZoom = Math.pow(2, canonical.z);
    const x = (coord[0] / EXTENT + canonical.x) / tilesAtZoom;
    const y = (coord[1] / EXTENT + 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;
    const shifts = [canonical.x * EXTENT, canonical.y * EXTENT];
    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;
    const shifts = [canonical.x * EXTENT, canonical.y * EXTENT];
    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;
    }
};

/**
 * Rearranges items so that all items in the [left, k] are the smallest.
 * The k-th element will have the (k - left + 1)-th smallest value in [left, right].
 *
 * @template T
 * @param {T[]} arr the array to partially sort (in place)
 * @param {number} k middle index for partial sorting (as defined above)
 * @param {number} [left=0] left index of the range to sort
 * @param {number} [right=arr.length-1] right index
 * @param {(a: T, b: T) => number} [compare = (a, b) => a - b] compare function
 */
function quickselect(arr, k, left = 0, right = arr.length - 1, compare = defaultCompare) {

    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));
            quickselect(arr, k, newLeft, newRight, compare);
        }

        const t = arr[k];
        let i = left;
        /** @type {number} */
        let 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;
    }
}

/**
 * @template T
 * @param {T[]} arr
 * @param {number} i
 * @param {number} j
 */
function swap$2(arr, i, j) {
    const tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}

/**
 * @template T
 * @param {T} a
 * @param {T} b
 * @returns {number}
 */
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 meridional 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;
    }
}

class GlobalState {
    constructor(key) {
        this.type = ValueType;
        this.key = key;
    }
    static parse(args, context) {
        if (args.length !== 2) {
            return context.error(`Expected 1 argument, but found ${args.length - 1} instead.`);
        }
        const key = args[1];
        if (key === undefined || key === null) {
            return context.error('Global state property must be defined.');
        }
        if (typeof key !== 'string') {
            return context.error(`Global state property must be string, but found ${typeof args[1]} instead.`);
        }
        return new GlobalState(key);
    }
    evaluate(ctx) {
        var _a;
        const globalState = (_a = ctx.globals) === null || _a === void 0 ? void 0 : _a.globalState;
        if (!globalState || Object.keys(globalState).length === 0)
            return null;
        return getOwn(globalState, this.key);
    }
    eachChild() { }
    outputDefined() {
        return false;
    }
}

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,
    'global-state': GlobalState
};

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(typeToString(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]) => typeToString(typeOf(v.evaluate(ctx)))],
    'to-rgba': [
        array(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],
    elevation: [NumberType, [], (ctx) => ctx.globals.elevation || 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(StringType)],
        (ctx, [v]) => v.value.indexOf(ctx.geometryType()) >= 0
    ],
    'filter-id-in': [
        BooleanType,
        [array(ValueType)],
        (ctx, [v]) => v.value.indexOf(ctx.id()) >= 0
    ],
    'filter-in-small': [
        BooleanType,
        [StringType, array(ValueType)],
        // assumes v is an array literal
        (ctx, [k, v]) => v.value.indexOf(ctx.properties()[k.value]) >= 0
    ],
    'filter-in-large': [
        BooleanType,
        [StringType, array(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) => valueToString(arg.evaluate(ctx))).join('')
    ],
    split: [
        array(StringType),
        [StringType, StringType],
        (ctx, [s, delim]) => s.evaluate(ctx).split(delim.evaluate(ctx))
    ],
    join: [
        StringType,
        [array(StringType), StringType],
        (ctx, [arr, delim]) => arr.evaluate(ctx).join(delim.evaluate(ctx))
    ],
    'resolved-locale': [
        StringType,
        [CollatorType],
        (ctx, [collator]) => collator.evaluate(ctx).resolvedLocale()
    ]
});
function stringifySignature(signature) {
    if (Array.isArray(signature)) {
        return `(${signature.map(typeToString).join(', ')})`;
    }
    else {
        return `(${typeToString(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;
    }
    else if (expression instanceof GlobalState) {
        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',
            'elevation',
            '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) &&
        typeOf(value) === ObjectType);
}
function identityFunction(x) {
    return x;
}
function getParseFunction(propertySpec) {
    switch (propertySpec.type) {
        case 'color':
            return Color.parse;
        case 'padding':
            return Padding.parse;
        case 'numberArray':
            return NumberArray.parse;
        case 'colorArray':
            return ColorArray.parse;
        default:
            return null;
    }
}
function getInnerFunction(type) {
    switch (type) {
        case 'exponential':
            return evaluateExponentialFunction;
        case 'interval':
            return evaluateIntervalFunction;
        case 'categorical':
            return evaluateCategoricalFunction;
        case 'identity':
            return evaluateIdentityFunction;
        default:
            throw new Error(`Unknown function type "${type}"`);
    }
}
function createFunction(parameters, propertySpec) {
    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');
    const parseFn = getParseFunction(propertySpec);
    if (parseFn) {
        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}"`);
    }
    const innerFun = getInnerFunction(type);
    let hashedStops;
    let categoricalKeyType;
    if (type === 'categorical') {
        // 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];
    }
    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 = interpolateFactory[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;
        case 'colorArray':
            input = ColorArray.parse(input);
            break;
        case 'numberArray':
            input = NumberArray.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, globalState) {
        this.expression = expression;
        this._warningHistory = {};
        this._evaluator = new EvaluationContext();
        this._defaultValue = propertySpec ? getDefaultValue(propertySpec) : null;
        this._enumValues =
            propertySpec && propertySpec.type === 'enum' ? propertySpec.values : null;
        this._globalState = globalState;
    }
    evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) {
        if (this._globalState) {
            globals = addGlobalState(globals, this._globalState);
        }
        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) {
        if (this._globalState) {
            globals = addGlobalState(globals, this._globalState);
        }
        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);
            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, globalState) {
    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, globalState));
}
class ZoomConstantExpression {
    constructor(kind, expression, globalState) {
        this.kind = kind;
        this._styleExpression = expression;
        this.isStateDependent =
            kind !== 'constant' && !isStateConstant(expression.expression);
        this.globalStateRefs = findGlobalStateRefs(expression.expression);
        this._globalState = globalState;
    }
    evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) {
        if (this._globalState) {
            globals = addGlobalState(globals, this._globalState);
        }
        return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection);
    }
    evaluate(globals, feature, featureState, canonical, availableImages, formattedSection) {
        if (this._globalState) {
            globals = addGlobalState(globals, this._globalState);
        }
        return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection);
    }
}
class ZoomDependentExpression {
    constructor(kind, expression, zoomStops, interpolationType, globalState) {
        this.kind = kind;
        this.zoomStops = zoomStops;
        this._styleExpression = expression;
        this.isStateDependent =
            kind !== 'camera' && !isStateConstant(expression.expression);
        this.globalStateRefs = findGlobalStateRefs(expression.expression);
        this.interpolationType = interpolationType;
        this._globalState = globalState;
    }
    evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) {
        if (this._globalState) {
            globals = addGlobalState(globals, this._globalState);
        }
        return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection);
    }
    evaluate(globals, feature, featureState, canonical, availableImages, formattedSection) {
        if (this._globalState) {
            globals = addGlobalState(globals, this._globalState);
        }
        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, globalState) {
    const expression = createExpression(expressionInput, propertySpec, globalState);
    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, globalState)
            : new ZoomConstantExpression('source', expression.value, globalState));
    }
    const interpolationType = zoomCurve instanceof Interpolate ? zoomCurve.interpolation : undefined;
    return success(isFeatureConstantResult
        ? new ZoomDependentExpression('camera', expression.value, zoomCurve.labels, interpolationType, globalState)
        : new ZoomDependentExpression('composite', expression.value, zoomCurve.labels, interpolationType, globalState));
}
// 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, globalState) {
    if (isFunction$1(value)) {
        return new StylePropertyFunction(value, specification);
    }
    else if (isExpression(value)) {
        const expression = createPropertyExpression(value, specification, globalState);
        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 === 'numberArray' &&
            (typeof value === 'number' || Array.isArray(value))) {
            constant = NumberArray.parse(value);
        }
        else if (specification.type === 'colorArray' &&
            (typeof value === 'string' || Array.isArray(value))) {
            constant = ColorArray.parse(value);
        }
        else if (specification.type === 'variableAnchorOffsetCollection' &&
            Array.isArray(value)) {
            constant = VariableAnchorOffsetCollection.parse(value);
        }
        else if (specification.type === 'projectionDefinition' && typeof value === 'string') {
            constant = ProjectionDefinition.parse(value);
        }
        return {
            globalStateRefs: new Set(),
            _globalState: null,
            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 findGlobalStateRefs(expression, results = new Set()) {
    if (expression instanceof GlobalState) {
        results.add(expression.key);
    }
    expression.eachChild((childExpression) => {
        findGlobalStateRefs(childExpression, results);
    });
    return results;
}
function getExpectedType(spec) {
    const types = {
        color: ColorType,
        string: StringType,
        number: NumberType,
        enum: StringType,
        boolean: BooleanType,
        formatted: FormattedType,
        padding: PaddingType,
        numberArray: NumberArrayType,
        colorArray: ColorArrayType,
        projectionDefinition: ProjectionDefinitionType,
        resolvedImage: ResolvedImageType,
        variableAnchorOffsetCollection: VariableAnchorOffsetCollectionType
    };
    if (spec.type === 'array') {
        return array(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);
    }
    switch (spec.type) {
        case 'color':
            return Color.parse(spec.default) || null;
        case 'padding':
            return Padding.parse(spec.default) || null;
        case 'numberArray':
            return NumberArray.parse(spec.default) || null;
        case 'colorArray':
            return ColorArray.parse(spec.default) || null;
        case 'variableAnchorOffsetCollection':
            return VariableAnchorOffsetCollection.parse(spec.default) || null;
        case 'projectionDefinition':
            return ProjectionDefinition.parse(spec.default) || null;
        default:
            return spec.default === undefined ? null : spec.default;
    }
}
function addGlobalState(globals, globalState) {
    const { zoom, heatmapDensity, elevation, lineProgress, isSupportedScript, accumulated } = globals !== null && globals !== void 0 ? globals : {};
    return {
        zoom,
        heatmapDensity,
        elevation,
        lineProgress,
        isSupportedScript,
        accumulated,
        globalState
    };
}

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 filter MapLibre filter
 * @param [globalState] Global state object to be used for evaluating 'global-state' expressions
 * @returns filter-evaluating function
 */
function featureFilter(filter, globalState) {
    if (filter === null || filter === undefined) {
        return { filter: () => true, needGeometry: false, getGlobalStateRefs: () => new Set() };
    }
    if (!isExpressionFilter(filter)) {
        filter = convertFilter$1(filter);
    }
    const compiled = createExpression(filter, filterSpec, globalState);
    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,
            getGlobalStateRefs: () => findGlobalStateRefs(compiled.value.expression)
        };
    }
}
// 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 evaluation 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;
}
/**
 * Groups layers by their 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.
 *
 * @param layers - an array of {@link LayerSpecification}.
 * @param cachedKeys - an object to keep already calculated keys.
 * @returns an array of arrays of {@link LayerSpecification} objects, where each inner array
 * contains layers that share the same layout-affecting properties.
 */
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 specification = v8Spec['$root'][styleKey];
        if (specification.required) {
            let value = null;
            if (styleKey === 'version') {
                value = version;
            }
            else {
                if (specification.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'
        // objectKey comes from the user controlled style input, so elementSpecKey may be e.g. "__proto__"
        const elementSpec = getOwn(elementSpecs, elementSpecKey) || elementSpecs['*'];
        let validateElement;
        if (getOwn(elementValidators, elementSpecKey)) {
            validateElement = elementValidators[elementSpecKey];
        }
        else if (getOwn(elementSpecs, elementSpecKey)) {
            if (object[objectKey] === undefined) {
                // property is possible, set but set to undefined
                // we only check it if it is required and not defaulted in the next loop
                // without skipping here, we would alert to properties being set to undefined
                continue;
            }
            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`)
        ];
    }
    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);
    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],
                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-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) {
    var _a, _b;
    let errors = [];
    const layer = options.value;
    const key = options.key;
    const style = options.style;
    const styleSpec = options.styleSpec;
    if (getType(layer) !== 'object') {
        return [new ValidationError(key, layer, `object expected, ${getType(layer)} found`)];
    }
    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-dem' && type === 'color-relief') {
                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' &&
                type !== 'color-relief') {
                errors.push(new ValidationError(key, layer.source, "raster-dem source can only be used with layer type 'hillshade' or 'color-relief'."));
            }
            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.`));
            }
        }
    }
    if (type === 'raster' && ((_a = layer.paint) === null || _a === void 0 ? void 0 : _a.resampling) && ((_b = layer.paint) === null || _b === void 0 ? void 0 : _b['raster-resampling'])) {
        errors.push(new ValidationError(key, layer.paint, `layer "${layer.id}" redundantly specifies "resampling" and "raster-resampling" paint properties, but only one is allowed. It is advised to use "resampling".`));
    }
    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,
                        expressionContext: 'cluster-map'
                    }));
                    errors.push(...validateExpression({
                        key: `${key}.${prop}.reduce`,
                        value: reduceExpr,
                        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']
                }});
    }
}
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 validateNumberArray(options) {
    const key = options.key;
    const value = options.value;
    const type = getType(value);
    if (type === 'array') {
        const arrayElementSpec = {
            type: 'number'
        };
        if (value.length < 1) {
            return [
                new ValidationError(key, value, 'array length at least 1 expected, length 0 found')
            ];
        }
        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 validateColorArray(options) {
    const key = options.key;
    const value = options.value;
    const type = getType(value);
    if (type === 'array') {
        if (value.length < 1) {
            return [
                new ValidationError(key, value, 'array length at least 1 expected, length 0 found')
            ];
        }
        let errors = [];
        for (let i = 0; i < value.length; i++) {
            errors = errors.concat(validateColor({
                key: `${key}[${i}]`,
                value: value[i]}));
        }
        return errors;
    }
    else {
        return validateColor({
            key,
            value});
    }
}

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;
}

function validateProjectionDefinition(options) {
    const key = options.key;
    let value = options.value;
    value = value instanceof String ? value.valueOf() : value;
    const type = getType(value);
    if (type === 'array' &&
        !isProjectionDefinitionValue(value) &&
        !isPropertyValueSpecification(value)) {
        return [
            new ValidationError(key, value, `projection expected, invalid array ${JSON.stringify(value)} found`)
        ];
    }
    else if (!['array', 'string'].includes(type)) {
        return [
            new ValidationError(key, value, `projection expected, invalid type "${type}" found`)
        ];
    }
    return [];
}
function isPropertyValueSpecification(value) {
    if (['interpolate', 'step', 'literal'].includes(value[0])) {
        return true;
    }
    return false;
}
function isProjectionDefinitionValue(value) {
    return (Array.isArray(value) &&
        value.length === 3 &&
        typeof value[0] === 'string' &&
        typeof value[1] === 'string' &&
        typeof value[2] === 'number');
}

function isObjectLiteral(anything) {
    return Boolean(anything) && anything.constructor === Object;
}

function validateState(options) {
    if (!isObjectLiteral(options.value)) {
        return [
            new ValidationError(options.key, options.value, `object expected, ${getType(options.value)} found`)
        ];
    }
    return [];
}

function validateFontFaces(options) {
    const key = options.key;
    const value = options.value;
    const validateSpec = options.validateSpec;
    const styleSpec = options.styleSpec;
    const style = options.style;
    if (!isObjectLiteral(value)) {
        return [new ValidationError(key, value, `object expected, ${getType(value)} found`)];
    }
    const errors = [];
    for (const fontName in value) {
        const fontValue = value[fontName];
        const fontValueType = getType(fontValue);
        if (fontValueType === 'string') {
            // Validate as a string URL
            errors.push(...validateString({
                key: `${key}.${fontName}`,
                value: fontValue
            }));
        }
        else if (fontValueType === 'array') {
            // Validate as an array of font face objects
            const fontFaceSpec = {
                url: {
                    type: 'string',
                    required: true
                },
                'unicode-range': {
                    type: 'array',
                    value: 'string'
                }
            };
            for (const [i, fontFace] of fontValue.entries()) {
                errors.push(...validateObject({
                    key: `${key}.${fontName}[${i}]`,
                    value: fontFace,
                    valueSpec: fontFaceSpec,
                    styleSpec,
                    style,
                    validateSpec
                }));
            }
        }
        else {
            errors.push(new ValidationError(`${key}.${fontName}`, fontValue, `string or array expected, ${fontValueType} found`));
        }
    }
    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,
    projectionDefinition: validateProjectionDefinition,
    string: validateString,
    formatted: validateFormatted,
    resolvedImage: validateImage,
    padding: validatePadding,
    numberArray: validateNumberArray,
    colorArray: validateColorArray,
    variableAnchorOffsetCollection: validateVariableAnchorOffsetCollection,
    sprite: validateSprite,
    state: validateState,
    fontFaces: validateFontFaces
};
/**
 * 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']}));
    }
    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.state = wrapCleanErrors(injectValidateSpec(validateState));
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(Object.assign({}, 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, key, value, reference, set }) => {
        if (isExpression(value) || key.endsWith('-transition') || reference === null)
            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');
 * const 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 === null || reference === void 0 ? void 0 : reference.type) === 'color') {
            set(migrateColors(value));
        }
    });
    if (!migrated) {
        throw new Error(`Cannot migrate from ${style.version}`);
    }
    return style;
}

const visibilitySpec = {
    type: 'enum',
    'property-type': 'data-constant',
    expression: {
        interpolated: false,
        parameters: ['global-state']
    },
    values: { visible: {}, none: {} },
    transition: false,
    default: 'visible'
};
class VisibilityExpressionClass {
    constructor(visibility, globalState) {
        this._globalState = globalState;
        this.setValue(visibility);
    }
    evaluate() {
        var _a;
        return (_a = this._literalValue) !== null && _a !== void 0 ? _a : this._compiledValue.evaluate({});
    }
    setValue(visibility) {
        if (visibility === null ||
            visibility === undefined ||
            visibility === 'visible' ||
            visibility === 'none') {
            this._literalValue = visibility === 'none' ? 'none' : 'visible';
            this._compiledValue = undefined;
            this._globalStateRefs = new Set();
            return;
        }
        const compiled = createExpression(visibility, visibilitySpec, this._globalState);
        if (compiled.result === 'error') {
            this._literalValue = 'visible';
            this._compiledValue = undefined;
            throw new Error(compiled.value.map((err) => `${err.key}: ${err.message}`).join(', '));
        }
        this._literalValue = undefined;
        this._compiledValue = compiled.value;
        this._globalStateRefs = findGlobalStateRefs(compiled.value.expression);
    }
    getGlobalStateRefs() {
        return this._globalStateRefs;
    }
}
/**
 * Creates a visibility expression from a visibility specification.
 * @param visibility - the visibility specification, literal or expression
 * @param globalState - the global state object
 * @returns visibility expression object
 */
function createVisibility(visibility, globalState) {
    return new VisibilityExpressionClass(visibility, globalState);
}

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 === null || errors === void 0 ? void 0 : 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) {
            return [...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 (const uid of cell) {
                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 (const cell of this.cells) {
            totalCellLength += cell.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('Set', Set);
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) {
    var _a;
    return value && typeof ArrayBuffer !== 'undefined' &&
        (value instanceof ArrayBuffer || (((_a = value.constructor) === null || _a === void 0 ? void 0 : _a.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);
    return classRegistryKey && classRegistryKey !== 'Object';
}
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)) {
            if (transferables) {
                transferables.push(input.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;
            if (registry[classRegistryKey].omit.includes(key))
                continue;
            const property = input[key];
            properties[key] = registry[classRegistryKey].shallow.includes(key) ?
                property :
                serialize(property, transferables);
        }
        if (input instanceof Error) {
            properties.message = input.message;
        }
    }
    else {
        if (properties === (transferables === null || transferables === void 0 ? void 0 : 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.includes(key) ? 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;
    }
}

// This file is generated. Edit build/generate-unicode-data.ts, then run `npm run generate-unicode-data`.
/**
 * Returns whether the fallback fonts specified by the
 * `localIdeographFontFamily` map option apply to the given codepoint.
 */
function codePointUsesLocalIdeographFontFamily(codePoint) {
    return /[\u02EA\u02EB\u1100-\u11FF\u2E80-\u2FDF\u3000-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u4DBF\u4E00-\uA48C\uA490-\uA4C6\uA960-\uA97C\uAC00-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFE10-\uFE1F\uFE30-\uFE4F\uFF00-\uFFEF]|\uD81B[\uDFE0-\uDFFF]|[\uD81C-\uD822\uD840-\uD868\uD86A-\uD86D\uD86F-\uD872\uD874-\uD879\uD880-\uD883\uD885-\uD88C][\uDC00-\uDFFF]|\uD823[\uDC00-\uDCD5\uDCFF-\uDD1E\uDD80-\uDDF2]|\uD82B[\uDFF0-\uDFFF]|\uD82C[\uDC00-\uDEFB]|\uD83C[\uDE00-\uDEFF]|\uD869[\uDC00-\uDEDF\uDF00-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEAD\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0\uDFF0-\uDFFF]|\uD87B[\uDC00-\uDE5D]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A\uDF50-\uDFFF]|\uD88D[\uDC00-\uDC79]/gim.test(String.fromCodePoint(codePoint));
}
/**
 * Returns whether the given codepoint participates in ideographic line
 * breaking.
 */
function codePointAllowsIdeographicBreaking(codePoint) {
    return /[\u02EA\u02EB\u2E80-\u2FDF\u2FF0-\u303F\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FD-\u30FF\u3105-\u312F\u31A0-\u4DBF\u4E00-\uA48C\uA490-\uA4C6\uF900-\uFA6D\uFA70-\uFAD9\uFE10-\uFE1F\uFE30-\uFE4F\uFF00-\uFFEF]|\uD81B[\uDFE0-\uDFFF]|[\uD81C-\uD822\uD840-\uD868\uD86A-\uD86D\uD86F-\uD872\uD874-\uD879\uD880-\uD883\uD885-\uD88C][\uDC00-\uDFFF]|\uD823[\uDC00-\uDCD5\uDCFF-\uDD1E\uDD80-\uDDF2]|\uD82B[\uDFF0-\uDFFF]|\uD82C[\uDC00-\uDEFB]|\uD83C[\uDE00-\uDEFF]|\uD869[\uDC00-\uDEDF\uDF00-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEAD\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0\uDFF0-\uDFFF]|\uD87B[\uDC00-\uDE5D]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A\uDF50-\uDFFF]|\uD88D[\uDC00-\uDC79]/gim.test(String.fromCodePoint(codePoint));
}
/**
 * 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 codePointHasUprightVerticalOrientation(codePoint) {
    return /[\u02EA\u02EB\u1100-\u11FF\u1400-\u167F\u18B0-\u18F5\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u3007\u3012\u3013\u3020-\u302F\u3031-\u303F\u3041-\u3096\u309D-\u30FB\u30FD-\u30FF\u3105-\u312F\u3131-\u318E\u3190-\uA48C\uA490-\uA4C6\uA960-\uA97C\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFE10-\uFE1F\uFE30-\uFE48\uFE50-\uFE57\uFE5F-\uFE62\uFE67-\uFE6F\uFF00-\uFF07\uFF0A-\uFF0C\uFF0E-\uFF19\uFF1F-\uFF3A\uFF3C\uFF3E\uFF40-\uFF5A\uFFE0-\uFFE2\uFFE4-\uFFE7]|\uD802[\uDD80-\uDD9F]|\uD805[\uDD80-\uDDFF]|\uD806[\uDE00-\uDEBF]|\uD811[\uDC00-\uDE7F]|\uD81B[\uDFE0-\uDFE4\uDFF0-\uDFF6]|[\uD81C-\uD822\uD83D\uD840-\uD868\uD86A-\uD86D\uD86F-\uD872\uD874-\uD879\uD880-\uD883\uD885-\uD88C][\uDC00-\uDFFF]|\uD823[\uDC00-\uDCD5\uDCFF-\uDD1E\uDD80-\uDDF2]|\uD82B[\uDFF0-\uDFF3\uDFF5-\uDFFB\uDFFD\uDFFE]|\uD82C[\uDC00-\uDD22\uDD30-\uDEFB]|\uD833[\uDEC0-\uDFCF]|\uD834[\uDC00-\uDDFF\uDEE0-\uDF7F]|\uD836[\uDC00-\uDEAF]|\uD83C[\uDC00-\uDE00\uDF00-\uDFFF]|\uD83E[\uDD00-\uDEFF]|\uD869[\uDC00-\uDEDF\uDF00-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEAD\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0\uDFF0-\uDFFF]|\uD87B[\uDC00-\uDE5D]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A\uDF50-\uDFFF]|\uD88D[\uDC00-\uDC79]/gim.test(String.fromCodePoint(codePoint));
}
/**
 * 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 codePointHasNeutralVerticalOrientation(codePoint) {
    return /[\xA7\xA9\xAE\xB1\xBC-\xBE\xD7\xF7\u2016\u2020\u2021\u2030\u2031\u203B\u203C\u2042\u2047-\u2049\u2051\u2100-\u218F\u221E\u2234\u2235\u2300-\u2307\u230C-\u231F\u2324-\u2328\u232B\u237D-\u239A\u23BE-\u23CD\u23CF\u23D1-\u23DB\u23E2-\u2422\u2424-\u24FF\u25A0-\u2619\u2620-\u2767\u2776-\u2793\u2B12-\u2B2F\u2B50-\u2B59\u2BB8-\u2BEB\u3000-\u303F\u30A0-\u30FF\uE000-\uF8FF\uFE30-\uFE6F\uFF00-\uFFEF\uFFFC\uFFFD]|[\uDB80-\uDBFF][\uDC00-\uDFFF]/gim.test(String.fromCodePoint(codePoint));
}
/**
 * Returns whether the give codepoint is likely to require complex text shaping.
 */
function codePointRequiresComplexTextShaping(codePoint) {
    return /[\u0900-\u0DFF\u0F00-\u109F\u1780-\u17FF]/gim.test(String.fromCodePoint(codePoint));
}

function charIsWhitespace(char) {
    return /\s/u.test(String.fromCodePoint(char));
}
function allowsIdeographicBreaking(chars) {
    for (const char of chars) {
        if (!codePointAllowsIdeographicBreaking(char.codePointAt(0)))
            return false;
    }
    return true;
}
function allowsVerticalWritingMode(chars) {
    for (const char of chars) {
        if (codePointHasUprightVerticalOrientation(char.codePointAt(0)))
            return true;
    }
    return false;
}
function allowsLetterSpacing(chars) {
    for (const char of chars) {
        if (!charAllowsLetterSpacing(char.codePointAt(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 (_a) {
            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));
}
/**
 * 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 !(codePointHasUprightVerticalOrientation(char) ||
        codePointHasNeutralVerticalOrientation(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;
    }
    return !codePointRequiresComplexTextShaping(char);
}
function stringContainsRTLText(chars) {
    for (const char of chars) {
        if (charInRTLScript(char.codePointAt(0))) {
            return true;
        }
    }
    return false;
}
function isStringInSupportedScript(chars, canRenderRTL) {
    for (const char of chars) {
        if (!charInSupportedScript(char.codePointAt(0), canRenderRTL)) {
            return false;
        }
    }
    return true;
}

class RTLWorkerPlugin {
    constructor() {
        this.TIMEOUT = 5000;
        this.applyArabicShaping = null;
        this.processBidirectionalText = null;
        this.processStyledBidirectionalText = null;
        this.pluginStatus = 'unavailable';
        this.pluginURL = null;
        this.loadScriptResolve = () => { };
    }
    setState(state) {
        this.pluginStatus = state.pluginStatus;
        this.pluginURL = state.pluginURL;
    }
    getState() {
        return {
            pluginStatus: this.pluginStatus,
            pluginURL: this.pluginURL
        };
    }
    setMethods(rtlTextPlugin) {
        if (rtlWorkerPlugin.isParsed()) {
            throw new Error('RTL text plugin already registered.');
        }
        this.applyArabicShaping = rtlTextPlugin.applyArabicShaping;
        this.processBidirectionalText = rtlTextPlugin.processBidirectionalText;
        this.processStyledBidirectionalText = rtlTextPlugin.processStyledBidirectionalText;
        this.loadScriptResolve();
    }
    isParsed() {
        return this.applyArabicShaping != null &&
            this.processBidirectionalText != null &&
            this.processStyledBidirectionalText != null;
    }
    getRTLTextPluginStatus() {
        return this.pluginStatus;
    }
    syncState(incomingState, importScripts) {
        return __awaiter(this, void 0, void 0, function* () {
            // Parsed plugin cannot be changed, so just return its current state.
            if (this.isParsed()) {
                return this.getState();
            }
            if (incomingState.pluginStatus !== 'loading') {
                // simply sync and done
                this.setState(incomingState);
                return incomingState;
            }
            const urlToLoad = incomingState.pluginURL;
            const loadScriptPromise = new Promise((resolve) => {
                this.loadScriptResolve = resolve;
            });
            importScripts(urlToLoad);
            const dontWaitForeverTimeoutPromise = new Promise((resolve) => setTimeout(() => resolve(), this.TIMEOUT));
            yield Promise.race([loadScriptPromise, dontWaitForeverTimeoutPromise]);
            const complete = this.isParsed();
            if (complete) {
                const loadedState = {
                    pluginStatus: 'loaded',
                    pluginURL: urlToLoad
                };
                this.setState(loadedState);
                return loadedState;
            }
            // error case
            this.setState({
                pluginStatus: 'error',
                pluginURL: ''
            });
            throw new Error(`RTL Text Plugin failed to import scripts from ${urlToLoad}`);
        });
    }
}
const rtlWorkerPlugin = new RTLWorkerPlugin();

/**
 * @internal
 * A parameter that can be evaluated to a value.
 * It's main purpose is a parameter to expression `evaluate` methods.
 */
class EvaluationParameters {
    // "options" may also be another EvaluationParameters to copy, see CrossFadedProperty.possiblyEvaluate
    constructor(zoom, options) {
        // has to be an own property of an object to be used in expressions
        // if defined as class method, it'll hidden from operations
        // that iterate over own enumerable properties
        // (i..e spread operator (...), Object.keys(), for...in statement, etc.)
        this.isSupportedScript = isSupportedScript;
        this.zoom = zoom;
        if (options) {
            this.now = options.now || 0;
            this.fadeDuration = options.fadeDuration || 0;
            this.zoomHistory = options.zoomHistory || new ZoomHistory();
            this.transition = options.transition || {};
        }
        else {
            this.now = 0;
            this.fadeDuration = 0;
            this.zoomHistory = new ZoomHistory();
            this.transition = {};
        }
    }
    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 };
    }
}
function isSupportedScript(str) {
    return isStringInSupportedScript(str, rtlWorkerPlugin.getRTLTextPluginStatus() === 'loaded');
}

const TRANSITION_SUFFIX = '-transition';
/**
 * @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, globalState) {
        this.property = property;
        this.value = value;
        this.expression = normalizePropertyExpression(value === undefined ? property.specification.default : value, property.specification, globalState);
    }
    isDataDriven() {
        return this.expression.kind === 'source' || this.expression.kind === 'composite';
    }
    getGlobalStateRefs() {
        return this.expression.globalStateRefs || new Set();
    }
    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, globalState) {
        this.property = property;
        this.value = new PropertyValue(property, undefined, globalState);
    }
    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, globalState) {
        this._properties = properties;
        this._values = (Object.create(properties.defaultTransitionablePropertyValues));
        this._globalState = globalState;
    }
    hasProperty(name) {
        return name in this._properties.defaultTransitionablePropertyValues;
    }
    getValue(name) {
        return clone(this._values[name].value.value);
    }
    setValue(name, value) {
        if (!Object.hasOwn(this._values, name)) {
            this._values[name] = new TransitionablePropertyValue(this._values[name].property, this._globalState);
        }
        // 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(value), this._globalState);
    }
    getTransition(name) {
        return clone(this._values[name].transition);
    }
    setTransition(name, value) {
        if (!Object.hasOwn(this._values, name)) {
            this._values[name] = new TransitionablePropertyValue(this._values[name].property, this._globalState);
        }
        this._values[name].transition = clone(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_SUFFIX}`] = 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, globalState) {
        this._properties = properties;
        this._values = (Object.create(properties.defaultPropertyValues));
        this._globalState = globalState;
    }
    hasValue(name) {
        return this._values[name].value !== undefined;
    }
    hasProperty(name) {
        return name in this._properties.defaultPropertyValues;
    }
    getValue(name) {
        return clone(this._values[name].value);
    }
    setValue(name, value) {
        this._values[name] = new PropertyValue(this._values[name].property, value === null ? undefined : clone(value), this._globalState);
    }
    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 = interpolateFactory[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<T>`; 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 = interpolateFactory[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, undefined);
            const defaultTransitionablePropertyValue = this.defaultTransitionablePropertyValues[property] =
                new TransitionablePropertyValue(prop, undefined);
            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 ERROR_PAINT_NOT_LAYOUT = ' is a PAINT property not a LAYOUT property. Use get/setPaintProperty instead?';
const ERROR_LAYOUT_NOT_PAINT = ' is a LAYOUT property not a PAINT property. Use get/setLayoutProperty instead?';
/**
 * A base class for style layers
 */
class StyleLayer extends Evented {
    constructor(layer, properties, globalState) {
        super();
        this.id = layer.id;
        this.type = layer.type;
        this._globalState = globalState;
        this._featureFilter = { filter: () => true, needGeometry: false, getGlobalStateRefs: () => new Set() };
        this._visibilityExpression = createVisibility(this.visibility, globalState);
        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;
            this._featureFilter = featureFilter(layer.filter, globalState);
        }
        if (properties.layout) {
            this._unevaluatedLayout = new Layout(properties.layout, globalState);
        }
        if (properties.paint) {
            this._transitionablePaint = new Transitionable(properties.paint, globalState);
            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);
        }
    }
    setFilter(filter) {
        this.filter = filter;
        this._featureFilter = featureFilter(filter, this._globalState);
    }
    getCrossfadeParameters() {
        return this._crossfadeParameters;
    }
    getLayoutProperty(name) {
        var _a;
        if (name === 'visibility') {
            return this.visibility;
        }
        if ((_a = this._transitionablePaint) === null || _a === void 0 ? void 0 : _a.hasProperty(name)) {
            throw new Error(name + ERROR_PAINT_NOT_LAYOUT);
        }
        if (!this._unevaluatedLayout) {
            throw new Error(`Cannot get layout property "${name}" on layer type "${this.type}" which has no layout properties.`);
        }
        return this._unevaluatedLayout.getValue(name);
    }
    /**
     * Get list of global state references that are used within layout or filter properties.
     * This is used to determine if layer source need to be reloaded when global state property changes.
     *
     */
    getLayoutAffectingGlobalStateRefs() {
        const globalStateRefs = new Set();
        for (const globalStateRef of this._visibilityExpression.getGlobalStateRefs()) {
            globalStateRefs.add(globalStateRef);
        }
        if (this._unevaluatedLayout) {
            for (const propertyName in this._unevaluatedLayout._values) {
                const value = this._unevaluatedLayout._values[propertyName];
                for (const globalStateRef of value.getGlobalStateRefs()) {
                    globalStateRefs.add(globalStateRef);
                }
            }
        }
        for (const globalStateRef of this._featureFilter.getGlobalStateRefs()) {
            globalStateRefs.add(globalStateRef);
        }
        return globalStateRefs;
    }
    /**
     * Get list of global state references that are used within paint properties.
     * This is used to determine if layer needs to be repainted when global state property changes.
     *
     */
    getPaintAffectingGlobalStateRefs() {
        var _a;
        const globalStateRefs = new globalThis.Map();
        if (this._transitionablePaint) {
            for (const propertyName in this._transitionablePaint._values) {
                const value = this._transitionablePaint._values[propertyName].value;
                for (const globalStateRef of value.getGlobalStateRefs()) {
                    const properties = (_a = globalStateRefs.get(globalStateRef)) !== null && _a !== void 0 ? _a : [];
                    properties.push({ name: propertyName, value: value.value });
                    globalStateRefs.set(globalStateRef, properties);
                }
            }
        }
        return globalStateRefs;
    }
    /**
     * Get list of global state references that are used within visibility expression.
     * This is used to determine if layer visibility needs to be updated when global state property changes.
     */
    getVisibilityAffectingGlobalStateRefs() {
        return this._visibilityExpression.getGlobalStateRefs();
    }
    setLayoutProperty(name, value, options = {}) {
        var _a;
        if (name === 'visibility') {
            this.visibility = value;
            this._visibilityExpression.setValue(value);
            this.recalculateVisibility();
            return;
        }
        if ((_a = this._transitionablePaint) === null || _a === void 0 ? void 0 : _a.hasProperty(name)) {
            this.fire(new ErrorEvent(new Error(name + ERROR_PAINT_NOT_LAYOUT)));
            return;
        }
        if (value !== null && value !== undefined && this._validate(validateLayoutProperty, `layers.${this.id}.layout.${name}`, name, value, options))
            return;
        this._unevaluatedLayout.setValue(name, value);
    }
    getPaintProperty(name) {
        var _a, _b;
        if (name.endsWith(TRANSITION_SUFFIX)) {
            const baseName = name.slice(0, -TRANSITION_SUFFIX.length);
            if (baseName === 'visibility' || ((_a = this._unevaluatedLayout) === null || _a === void 0 ? void 0 : _a.hasProperty(baseName))) {
                throw new Error(name + ERROR_LAYOUT_NOT_PAINT);
            }
            return this._transitionablePaint.getTransition(baseName);
        }
        else {
            if (name === 'visibility' || ((_b = this._unevaluatedLayout) === null || _b === void 0 ? void 0 : _b.hasProperty(name))) {
                throw new Error(name + ERROR_LAYOUT_NOT_PAINT);
            }
            return this._transitionablePaint.getValue(name);
        }
    }
    setPaintProperty(name, value, options = {}) {
        var _a;
        if (name === 'visibility' || ((_a = this._unevaluatedLayout) === null || _a === void 0 ? void 0 : _a.hasProperty(name))) {
            this.fire(new ErrorEvent(new Error(name + ERROR_LAYOUT_NOT_PAINT)));
            return false;
        }
        if (value !== null && value !== undefined && this._validate(validatePaintProperty, `layers.${this.id}.paint.${name}`, 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 = this.minzoom, roundMinZoom = false) {
        if (this.minzoom && zoom < (roundMinZoom ? Math.floor(this.minzoom) : this.minzoom))
            return true;
        if (this.maxzoom && zoom >= this.maxzoom)
            return true;
        return this._evaluatedVisibility === 'none';
    }
    updateTransitions(parameters) {
        this._transitioningPaint = this._transitionablePaint.transitioned(parameters, this._transitioningPaint);
    }
    hasTransition() {
        return this._transitioningPaint.hasTransition();
    }
    recalculateVisibility() {
        this._evaluatedVisibility = this._visibilityExpression.evaluate();
    }
    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() {
        var _a, _b;
        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': (_a = this._unevaluatedLayout) === null || _a === void 0 ? void 0 : _a.serialize(),
            'paint': (_b = this._transitionablePaint) === null || _b === void 0 ? void 0 : _b.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 === null || options === void 0 ? void 0 : 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;
    }
}

// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'.
/* eslint-disable */
let paint$9;
const getPaint$9 = () => paint$9 = paint$9 || 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"]),
    "resampling": new DataConstantProperty(v8Spec["paint_raster"]["resampling"]),
    "raster-resampling": new DataConstantProperty(v8Spec["paint_raster"]["raster-resampling"]),
    "raster-fade-duration": new DataConstantProperty(v8Spec["paint_raster"]["raster-fade-duration"]),
});
var properties$9 = ({ get paint() { return getPaint$9(); } });

const isRasterStyleLayer = (layer) => layer.type === 'raster';
class RasterStyleLayer extends StyleLayer {
    constructor(layer, globalState) {
        super(layer, properties$9, globalState);
    }
}

// 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');
    }
    /**
     * Replace the buffer with an empty one so typed views release the original ArrayBuffer for GC.
     */
    freeBufferAfterUpload() {
        this.arrayBuffer = new ArrayBuffer(0);
        this._refreshViews();
    }
}
/**
 * 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] - Uint16[8]
 *
 */
class StructArrayLayout8ui16 extends StructArray {
    _refreshViews() {
        this.uint8 = new Uint8Array(this.arrayBuffer);
        this.uint16 = new Uint16Array(this.arrayBuffer);
    }
    emplaceBack(v0, v1, v2, v3, v4, v5, v6, v7) {
        const i = this.length;
        this.resize(i + 1);
        return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7);
    }
    emplace(i, v0, v1, v2, v3, v4, v5, v6, v7) {
        const o2 = i * 8;
        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;
        return i;
    }
}
StructArrayLayout8ui16.prototype.bytesPerElement = 16;
register('StructArrayLayout8ui16', StructArrayLayout8ui16);
/**
 * @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(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 DashLayoutArray extends StructArrayLayout8ui16 {
}
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._forceNewSegmentOnNextPrepare = false;
        this.segments = segments;
    }
    /**
     * Returns the last segment if `numVertices` fits into it.
     * If there are no segments yet or `numVertices` doesn't fit into the last one, creates a new empty segment and returns it.
     */
    prepareSegment(numVertices, layoutVertexArray, indexArray, sortKey) {
        const lastSegment = 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}. Consider using the \`fillLargeMeshArrays\` function if you require meshes with more than ${SegmentVector.MAX_VERTEX_ARRAY_LENGTH} vertices.`);
        }
        if (this._forceNewSegmentOnNextPrepare || !lastSegment || lastSegment.vertexLength + numVertices > SegmentVector.MAX_VERTEX_ARRAY_LENGTH || lastSegment.sortKey !== sortKey) {
            return this.createNewSegment(layoutVertexArray, indexArray, sortKey);
        }
        else {
            return lastSegment;
        }
    }
    /**
     * Creates a new empty segment and returns it.
     */
    createNewSegment(layoutVertexArray, indexArray, sortKey) {
        const segment = {
            vertexOffset: layoutVertexArray.length,
            primitiveOffset: indexArray.length,
            vertexLength: 0,
            primitiveLength: 0,
            vaos: {}
        };
        if (sortKey !== undefined) {
            segment.sortKey = sortKey;
        }
        // If this was set, we have no need to create a new segment on next prepareSegment call,
        // since this function already created a new, empty segment.
        this._forceNewSegmentOnNextPrepare = false;
        this.segments.push(segment);
        return segment;
    }
    /**
     * Returns the last segment, or creates a new segments if there are no segments yet.
     */
    getOrCreateLatestSegment(layoutVertexArray, indexArray, sortKey) {
        return this.prepareSegment(0, layoutVertexArray, indexArray, sortKey);
    }
    /**
     * Causes the next call to {@link prepareSegment} to always return a new segment,
     * not reusing the current segment even if the new geometry would fit it.
     */
    forceNewSegmentOnNextPrepare() {
        this._forceNewSegmentOnNextPrepare = true;
    }
    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$2(Math.floor(a), 0, 255);
    b = clamp$2(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' },
]);

const dashAttributes = createLayout([
    // [0, y, height, width]
    { name: 'a_dasharray_from', components: 4, type: 'Uint16' },
    { name: 'a_dasharray_to', components: 4, type: 'Uint16' },
]);

var murmurhashJs$1 = {exports: {}};

var murmurhash3_gc$1 = {exports: {}};

/**
 * JS Implementation of MurmurHash3 (r136) (as of May 20, 2011)
 * 
 * @author <a href="mailto:gary.court@gmail.com">Gary Court</a>
 * @see http://github.com/garycourt/murmurhash-js
 * @author <a href="mailto:aappleby@gmail.com">Austin Appleby</a>
 * @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$1.exports;

var hasRequiredMurmurhash3_gc;

function requireMurmurhash3_gc () {
	if (hasRequiredMurmurhash3_gc) return murmurhash3_gc$1.exports;
	hasRequiredMurmurhash3_gc = 1;
	(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$1));
	return murmurhash3_gc$1.exports;
}

var murmurhash2_gc$1 = {exports: {}};

/**
 * JS Implementation of MurmurHash2
 * 
 * @author <a href="mailto:gary.court@gmail.com">Gary Court</a>
 * @see http://github.com/garycourt/murmurhash-js
 * @author <a href="mailto:aappleby@gmail.com">Austin Appleby</a>
 * @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$1.exports;

var hasRequiredMurmurhash2_gc;

function requireMurmurhash2_gc () {
	if (hasRequiredMurmurhash2_gc) return murmurhash2_gc$1.exports;
	hasRequiredMurmurhash2_gc = 1;
	(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$1));
	return murmurhash2_gc$1.exports;
}

var murmurhashJs = murmurhashJs$1.exports;

var hasRequiredMurmurhashJs;

function requireMurmurhashJs () {
	if (hasRequiredMurmurhashJs) return murmurhashJs$1.exports;
	hasRequiredMurmurhashJs = 1;
	var murmur3 = requireMurmurhash3_gc();
	var murmur2 = requireMurmurhash2_gc();

	murmurhashJs$1.exports = murmur3;
	murmurhashJs$1.exports.murmur3 = murmur3;
	murmurhashJs$1.exports.murmur2 = murmur2;
	return murmurhashJs$1.exports;
}

var murmurhashJsExports = requireMurmurhashJs();
var murmur3 = /*@__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(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);
        }
    }
}
class UniformColorArray extends Uniform {
    constructor(context, location) {
        super(context, location);
        this.current = new Array();
    }
    set(v) {
        if (v != this.current) {
            this.current = v;
            const values = new Float32Array(v.length * 4);
            for (let i = 0; i < v.length; i++) {
                values[4 * i] = v[i].r;
                values[4 * i + 1] = v[i].g;
                values[4 * i + 2] = v[i].b;
                values[4 * i + 3] = v[i].a;
            }
            this.gl.uniform4fv(this.location, values);
        }
    }
}
class UniformFloatArray extends Uniform {
    constructor(context, location) {
        super(context, location);
        this.current = new Array();
    }
    set(v) {
        if (v != this.current) {
            this.current = v;
            const values = new Float32Array(v);
            this.gl.uniform1fv(this.location, values);
        }
    }
}
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;
    }
    setConstantDashPositions(dashTo, dashFrom) {
        this.dashTo = [0, dashTo.y, dashTo.height, dashTo.width];
        this.dashFrom = [0, dashFrom.y, dashFrom.height, dashFrom.width];
    }
    setUniform(uniform, globals, currentValue, uniformName) {
        let value = null;
        if (uniformName === 'u_pattern_to') {
            value = this.patternTo;
        }
        else if (uniformName === 'u_pattern_from') {
            value = this.patternFrom;
        }
        else if (uniformName === 'u_dasharray_to') {
            value = this.dashTo;
        }
        else if (uniformName === 'u_dasharray_from') {
            value = this.dashFrom;
        }
        else if (uniformName === 'u_pixel_ratio_to') {
            value = this.pixelRatioTo;
        }
        else if (uniformName === 'u_pixel_ratio_from') {
            value = this.pixelRatioFrom;
        }
        if (value !== null) {
            uniform.set(value);
        }
    }
    getBinding(context, location, name) {
        return (name.startsWith('u_pattern') || name.startsWith('u_dasharray_')) ?
            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, options) {
        const start = this.paintVertexArray.length;
        const value = this.expression.evaluate(new EvaluationParameters(0, options), feature, {}, options.canonical, [], options.formattedSection);
        this.paintVertexArray.resize(newLength);
        this._setPaintValue(start, newLength, value);
    }
    updatePaintArray(start, end, feature, featureState, options) {
        const value = this.expression.evaluate(new EvaluationParameters(0, options), 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) {
        var _a, _b;
        if ((_a = this.paintVertexArray) === null || _a === void 0 ? void 0 : _a.arrayBuffer.byteLength) {
            if ((_b = this.paintVertexBuffer) === null || _b === void 0 ? void 0 : _b.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, options) {
        const min = this.expression.evaluate(new EvaluationParameters(this.zoom, options), feature, {}, options.canonical, [], options.formattedSection);
        const max = this.expression.evaluate(new EvaluationParameters(this.zoom + 1, options), feature, {}, options.canonical, [], options.formattedSection);
        const start = this.paintVertexArray.length;
        this.paintVertexArray.resize(newLength);
        this._setPaintValue(start, newLength, min, max);
    }
    updatePaintArray(start, end, feature, featureState, options) {
        const min = this.expression.evaluate(new EvaluationParameters(this.zoom, options), feature, featureState);
        const max = this.expression.evaluate(new EvaluationParameters(this.zoom + 1, options), 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) {
        var _a, _b;
        if ((_a = this.paintVertexArray) === null || _a === void 0 ? void 0 : _a.arrayBuffer.byteLength) {
            if ((_b = this.paintVertexBuffer) === null || _b === void 0 ? void 0 : _b.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$2(this.expression.interpolationFactor(currentZoom, this.zoom, this.zoom + 1), 0, 1);
        uniform.set(factor);
    }
    getBinding(context, location, _) {
        return new Uniform1f(context, location);
    }
}
class CrossFadedBinder {
    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, options) {
        const start = this.zoomInPaintVertexArray.length;
        this.zoomInPaintVertexArray.resize(length);
        this.zoomOutPaintVertexArray.resize(length);
        this._setPaintValues(start, length, this.getPositionIds(feature), options);
    }
    updatePaintArray(start, end, feature, featureState, options) {
        this._setPaintValues(start, end, this.getPositionIds(feature), options);
    }
    _setPaintValues(start, end, positionIds, options) {
        const positions = this.getPositions(options);
        if (!positions || !positionIds)
            return;
        const min = positions[positionIds.min];
        const mid = positions[positionIds.mid];
        const max = positions[positionIds.max];
        if (!min || !mid || !max)
            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.emplace(this.zoomInPaintVertexArray, i, mid, min);
            this.emplace(this.zoomOutPaintVertexArray, i, mid, max);
        }
    }
    upload(context) {
        var _a, _b;
        if (((_a = this.zoomInPaintVertexArray) === null || _a === void 0 ? void 0 : _a.arrayBuffer.byteLength) && ((_b = this.zoomOutPaintVertexArray) === null || _b === void 0 ? void 0 : _b.arrayBuffer.byteLength)) {
            const attributes = this.getVertexAttributes();
            this.zoomInPaintVertexBuffer = context.createVertexBuffer(this.zoomInPaintVertexArray, attributes, this.expression.isStateDependent);
            this.zoomOutPaintVertexBuffer = context.createVertexBuffer(this.zoomOutPaintVertexArray, attributes, this.expression.isStateDependent);
        }
    }
    destroy() {
        if (this.zoomOutPaintVertexBuffer)
            this.zoomOutPaintVertexBuffer.destroy();
        if (this.zoomInPaintVertexBuffer)
            this.zoomInPaintVertexBuffer.destroy();
    }
}
class CrossFadedPatternBinder extends CrossFadedBinder {
    getPositions(options) {
        return options.imagePositions;
    }
    getPositionIds(feature) {
        var _a;
        return (_a = feature.patterns) === null || _a === void 0 ? void 0 : _a[this.layerId];
    }
    getVertexAttributes() {
        return patternAttributes.members;
    }
    emplace(array, index, midPos, minMaxPos) {
        array.emplace(index, midPos.tlbr[0], midPos.tlbr[1], midPos.tlbr[2], midPos.tlbr[3], minMaxPos.tlbr[0], minMaxPos.tlbr[1], minMaxPos.tlbr[2], minMaxPos.tlbr[3], midPos.pixelRatio, minMaxPos.pixelRatio);
    }
}
class CrossFadedDasharrayBinder extends CrossFadedBinder {
    getPositions(options) {
        return options.dashPositions;
    }
    getPositionIds(feature) {
        var _a;
        return (_a = feature.dashes) === null || _a === void 0 ? void 0 : _a[this.layerId];
    }
    getVertexAttributes() {
        return dashAttributes.members;
    }
    emplace(array, index, midPos, minMaxPos) {
        array.emplace(index, 0, midPos.y, midPos.height, midPos.width, 0, minMaxPos.y, minMaxPos.height, minMaxPos.width);
    }
}
/**
 * @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 ?
                    property === 'line-dasharray' ?
                        new CrossFadedDasharrayBinder(expression, type, useIntegerZoom, zoom, StructArrayLayout, layer.id) :
                        new CrossFadedPatternBinder(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, options) {
        for (const property in this.binders) {
            const binder = this.binders[property];
            if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof CrossFadedBinder)
                binder.populatePaintArray(newLength, feature, options);
        }
    }
    setConstantPatternPositions(posTo, posFrom) {
        for (const property in this.binders) {
            const binder = this.binders[property];
            if (binder instanceof CrossFadedConstantBinder)
                binder.setConstantPatternPositions(posTo, posFrom);
        }
    }
    setConstantDashPositions(dashTo, dashFrom) {
        for (const property in this.binders) {
            const binder = this.binders[property];
            if (binder instanceof CrossFadedConstantBinder)
                binder.setConstantDashPositions(dashTo, dashFrom);
        }
    }
    updatePaintArrays(featureStates, featureMap, vtLayer, layer, options) {
        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 CrossFadedBinder) && 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], options);
                        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 (const attribute of binder.paintVertexAttributes) {
                    result.push(attribute.name);
                }
            }
            else if (binder instanceof CrossFadedBinder) {
                const attributes = binder.getVertexAttributes();
                for (const attribute of attributes) {
                    result.push(attribute.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 CrossFadedBinder) {
                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 CrossFadedBinder)
                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 CrossFadedBinder)
                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, options) {
        for (const key in this.programConfigurations) {
            this.programConfigurations[key].populatePaintArrays(length, feature, options);
        }
        if (feature.id !== undefined) {
            this._featureMap.add(feature.id, index, this._bufferOffset, length);
        }
        this._bufferOffset = length;
        this.needsUpload = true;
    }
    updatePaintArrays(featureStates, vtLayer, layers, options) {
        for (const layer of layers) {
            this.needsUpload = this.programConfigurations[layer.id].updatePaintArrays(featureStates, this._featureMap, vtLayer, layer, options) || 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-dasharray': ['dasharray_to', 'dasharray_from'],
        '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
        },
        'line-dasharray': {
            'source': DashLayoutArray,
            'composite': DashLayoutArray
        },
    };
    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 === null || layoutException === void 0 ? void 0 : layoutException[binderType]) || defaultLayouts[type][binderType];
}
register('ConstantBinder', ConstantBinder);
register('CrossFadedConstantBinder', CrossFadedConstantBinder);
register('SourceExpressionBinder', SourceExpressionBinder);
register('CrossFadedPatternBinder', CrossFadedPatternBinder);
register('CrossFadedDasharrayBinder', CrossFadedDasharrayBinder);
register('CompositeExpressionBinder', CompositeExpressionBinder);
register('ProgramConfiguration', ProgramConfiguration, { omit: ['_buffers'] });
register('ProgramConfigurationSet', ProgramConfigurationSet);

// 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 VectorTileFeatureLike and scales it to the common extent
 * used internally.
 * @param feature - the vector tile feature to load
 */
function loadGeometry(feature) {
    const scale = EXTENT$1 / feature.extent;
    const geometry = feature.loadGeometry();
    for (const ring of geometry) {
        for (const point of ring) {
            // round here because mapbox-gl-native uses integers to represent
            // points and we need to do the same to avoid rendering differences.
            const x = Math.round(point.x * scale);
            const y = Math.round(point.y * scale);
            point.x = clamp$2(x, MIN, MAX);
            point.y = clamp$2(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 VectorTileFeatureLike 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) : [] };
}

const VERTEX_MIN_VALUE = -32768; // -(2^15)
// Extrude is in range 0..7, which will be mapped to -1..1 in the shader.
function addCircleVertex(layoutVertexArray, x, y, extrudeX, extrudeY) {
    // We pack circle position and extrude into range 0..65535, but vertices are stored as *signed* 16-bit integers, so we need to offset the number by 2^15.
    layoutVertexArray.emplaceBack(VERTEX_MIN_VALUE + (x * 8) + extrudeX, VERTEX_MIN_VALUE + (y * 8) + extrudeY);
}
/**
 * @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.hasDependencies = 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 circles are usually large (and map-pitch-aligned), tessellate them to allow curvature along the globe.
        let subdivide = styleLayer.type === 'heatmap';
        // Heatmap layers are handled in this bucket and have no evaluated properties, so we check our access
        if (styleLayer.type === 'circle') {
            const circleStyle = styleLayer;
            circleSortKey = circleStyle.layout.get('circle-sort-key');
            sortFeaturesByKey = !circleSortKey.isConstant();
            // Circles that are "printed" onto the map surface should be tessellated to follow the globe's curvature.
            subdivide = subdivide || circleStyle.paint.get('circle-pitch-alignment') === 'map';
        }
        const granularity = subdivide ? options.subdivisionGranularity.circle : 1;
        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, granularity);
            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, granularity = 1) {
        // Since we store the circle's center in each vertex, we only have 3 bits for actual vertex position in each axis.
        // Thus the valid range of positions is 0..7.
        // This gives us 4 possible granularity settings that are symmetrical.
        // This array stores vertex positions that should by used by the tessellated quad.
        let extrudes;
        switch (granularity) {
            case 1:
                extrudes = [0, 7];
                break;
            case 3:
                extrudes = [0, 2, 5, 7];
                break;
            case 5:
                extrudes = [0, 1, 3, 4, 6, 7];
                break;
            case 7:
                extrudes = [0, 1, 2, 3, 4, 5, 6, 7];
                break;
            default:
                throw new Error(`Invalid circle bucket granularity: ${granularity}; valid values are 1, 3, 5, 7.`);
        }
        const verticesPerAxis = extrudes.length;
        for (const ring of geometry) {
            for (const point of ring) {
                const vx = point.x;
                const vy = point.y;
                // Do not include points that are outside the tile boundaries.
                if (vx < 0 || vx >= EXTENT$1 || vy < 0 || vy >= EXTENT$1) {
                    continue;
                }
                const segment = this.segments.prepareSegment(verticesPerAxis * verticesPerAxis, this.layoutVertexArray, this.indexArray, feature.sortKey);
                const index = segment.vertexLength;
                for (let y = 0; y < verticesPerAxis; y++) {
                    for (let x = 0; x < verticesPerAxis; x++) {
                        addCircleVertex(this.layoutVertexArray, vx, vy, extrudes[x], extrudes[y]);
                    }
                }
                for (let y = 0; y < verticesPerAxis - 1; y++) {
                    for (let x = 0; x < verticesPerAxis - 1; x++) {
                        const lowerIndex = index + y * verticesPerAxis + x;
                        const upperIndex = index + (y + 1) * verticesPerAxis + x;
                        this.indexArray.emplaceBack(lowerIndex, upperIndex + 1, lowerIndex + 1);
                        this.indexArray.emplaceBack(lowerIndex, upperIndex, upperIndex + 1);
                    }
                }
                segment.vertexLength += verticesPerAxis * verticesPerAxis;
                segment.primitiveLength += (verticesPerAxis - 1) * (verticesPerAxis - 1) * 2;
            }
        }
        this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, { imagePositions: {}, canonical });
    }
}
register('CircleBucket', CircleBucket, { omit: ['layers'] });

function polygonIntersectsPolygon(polygonA, polygonB) {
    for (const point of polygonA) {
        if (polygonContainsPoint(polygonB, point))
            return true;
    }
    for (const point of polygonB) {
        if (polygonContainsPoint(polygonA, point))
            return true;
    }
    return lineIntersectsLine(polygonA, polygonB);
}
function polygonIntersectsBufferedPoint(polygon, point, radius) {
    if (polygonContainsPoint(polygon, point))
        return true;
    return pointIntersectsBufferedLine(point, polygon, radius);
}
function polygonIntersectsMultiPolygon(polygon, multiPolygon) {
    if (polygon.length === 1) {
        return multiPolygonContainsPoint(multiPolygon, polygon[0]);
    }
    for (const ring of multiPolygon) {
        for (const point of ring) {
            if (polygonContainsPoint(polygon, point))
                return true;
        }
    }
    for (const point of polygon) {
        if (multiPolygonContainsPoint(multiPolygon, point))
            return true;
    }
    for (const ring of multiPolygon) {
        if (lineIntersectsLine(polygon, ring))
            return true;
    }
    return false;
}
function polygonIntersectsBufferedMultiLine(polygon, multiLine, radius) {
    for (const line of multiLine) {
        if (polygon.length >= 3) {
            for (const point of line) {
                if (polygonContainsPoint(polygon, point))
                    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 (const point of lineB) {
            if (pointIntersectsBufferedLine(point, lineA, radius))
                return true;
        }
    }
    for (const point of lineA) {
        if (pointIntersectsBufferedLine(point, 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 (const currentRing of rings) {
        ring = currentRing;
        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(boxX1, boxY1),
        new Point(boxX1, boxY2),
        new Point(boxX2, boxY2),
        new Point(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]);
}
/**
 * @internal
 * Translates a geometry by a certain pixels in tile coordinates
 * @param queryGeometry - The geometry to translate in tile coordinates
 * @param translate - The translation in pixels
 * @param translateAnchor - The anchor of the translation
 * @param bearing - The bearing of the map
 * @param pixelsToTileUnits - The scale factor from pixels to tile units
 * @returns the translated geometry in tile coordinates
 */
function translate(queryGeometry, translate, translateAnchor, bearing, pixelsToTileUnits) {
    if (!translate[0] && !translate[1]) {
        return queryGeometry;
    }
    const pt = Point.convert(translate)._mult(pixelsToTileUnits);
    if (translateAnchor === 'viewport') {
        pt._rotate(-bearing);
    }
    const translated = [];
    for (const point of queryGeometry) {
        translated.push(point.sub(pt));
    }
    return translated;
}
/**
 * Filter out consecutive duplicate points from a line
 */
function _stripDuplicates(ring) {
    const filteredRing = [];
    for (let index = 0; index < ring.length; index++) {
        const point = ring[index];
        const prevPoint = filteredRing.at(-1);
        if (index === 0 || (prevPoint && !(point.equals(prevPoint)))) {
            filteredRing.push(point);
        }
    }
    return filteredRing;
}
function offsetLine(rings, offset) {
    const newRings = [];
    for (const rawRing of rings) {
        const ring = _stripDuplicates(rawRing);
        const newRing = [];
        for (let index = 0; index < ring.length; index++) {
            const point = ring[index];
            const prevPoint = ring[index - 1];
            const nextPoint = ring[index + 1];
            // perpendicular unit vectors (outward unit normal vector):
            // these indicate which direction the segments should be offset in
            const unitNormalAB = index === 0 ? new Point(0, 0) : point.sub(prevPoint)._unit()._perp();
            const unitNormalBC = index === ring.length - 1 ? new Point(0, 0) : nextPoint.sub(point)._unit()._perp();
            // unit bisector direction
            const bisectorDir = unitNormalAB._add(unitNormalBC)._unit();
            const cosHalfAngle = bisectorDir.x * unitNormalBC.x + bisectorDir.y * unitNormalBC.y;
            if (cosHalfAngle !== 0) {
                bisectorDir._mult(1 / cosHalfAngle);
            }
            newRing.push(bisectorDir._mult(offset)._add(point));
        }
        newRings.push(newRing);
    }
    return newRings;
}
function intersectionTestMapMap({ queryGeometry, size }, point) {
    return polygonIntersectsBufferedPoint(queryGeometry, point, size);
}
function intersectionTestMapViewport({ queryGeometry, size, transform, unwrappedTileID, getElevation }, point) {
    const w = transform.projectTileCoordinates(point.x, point.y, unwrappedTileID, getElevation).signedDistanceFromCamera;
    const adjustedSize = size * (w / transform.cameraToCenterDistance);
    return polygonIntersectsBufferedPoint(queryGeometry, point, adjustedSize);
}
function intersectionTestViewportMap({ queryGeometry, size, transform, unwrappedTileID, getElevation }, point) {
    const w = transform.projectTileCoordinates(point.x, point.y, unwrappedTileID, getElevation).signedDistanceFromCamera;
    const adjustedSize = size * (transform.cameraToCenterDistance / w);
    return polygonIntersectsBufferedPoint(queryGeometry, projectPoint(point, transform, unwrappedTileID, getElevation), adjustedSize);
}
function intersectionTestViewportViewport({ queryGeometry, size, transform, unwrappedTileID, getElevation }, point) {
    return polygonIntersectsBufferedPoint(queryGeometry, projectPoint(point, transform, unwrappedTileID, getElevation), size);
}
function circleIntersection({ queryGeometry, size, transform, unwrappedTileID, getElevation, pitchAlignment = 'map', pitchScale = 'map' }, geometry) {
    const intersectionTest = pitchAlignment === 'map'
        ? (pitchScale === 'map' ? intersectionTestMapMap : intersectionTestMapViewport)
        : (pitchScale === 'map' ? intersectionTestViewportMap : intersectionTestViewportViewport);
    const param = { queryGeometry, size, transform, unwrappedTileID, getElevation };
    for (const ring of geometry) {
        for (const point of ring) {
            if (intersectionTest(param, point)) {
                return true;
            }
        }
    }
    return false;
}
function projectPoint(tilePoint, transform, unwrappedTileID, getElevation) {
    // Convert `tilePoint` from tile coordinates to clip coordinates.
    const clipPoint = transform.projectTileCoordinates(tilePoint.x, tilePoint.y, unwrappedTileID, getElevation).point;
    // Convert `clipPoint` from clip coordinates into pixel/screen coordinates.
    return new Point((clipPoint.x * 0.5 + 0.5) * transform.width, (-clipPoint.y * 0.5 + 0.5) * transform.height);
}
function projectQueryGeometry$1(queryGeometry, transform, unwrappedTileID, getElevation) {
    return queryGeometry.map((p) => {
        return projectPoint(p, transform, unwrappedTileID, getElevation);
    });
}

// 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(); } });

const isCircleStyleLayer = (layer) => layer.type === 'circle';
/**
 * A style layer that defines a circle
 */
class CircleStyleLayer extends StyleLayer {
    constructor(layer, globalState) {
        super(layer, properties$8, globalState);
    }
    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, transform, pixelsToTileUnits, unwrappedTileID, getElevation }) {
        const translatedPolygon = translate(queryGeometry, this.paint.get('circle-translate'), this.paint.get('circle-translate-anchor'), -transform.bearingInRadians, 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 pitchScale = this.paint.get('circle-pitch-scale');
        const pitchAlignment = this.paint.get('circle-pitch-alignment');
        let transformedPolygon;
        let transformedSize;
        if (pitchAlignment === 'map') {
            transformedPolygon = translatedPolygon;
            transformedSize = size * pixelsToTileUnits;
        }
        else {
            transformedPolygon = projectQueryGeometry$1(translatedPolygon, transform, unwrappedTileID, getElevation);
            transformedSize = size;
        }
        return circleIntersection({
            queryGeometry: transformedPolygon,
            size: transformedSize,
            transform,
            unwrappedTileID,
            getElevation,
            pitchAlignment,
            pitchScale
        }, geometry);
    }
}

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.
 * Premultiplication is applied in JS before 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);
    }
    setPixel(row, col, value) {
        const rLocation = (row * this.width + col) * 4;
        this.data[rLocation + 0] = Math.round(value.r * 255 / value.a);
        this.data[rLocation + 1] = Math.round(value.g * 255 / value.a);
        this.data[rLocation + 2] = Math.round(value.b * 255 / value.a);
        this.data[rLocation + 3] = Math.round(value.a * 255);
    }
}
/** Returns a copy of RGBA data with premultiplied alpha. */
function premultiplyAlpha(data) {
    const out = new Uint8Array(data.length);
    for (let i = 0; i < data.length; i += 4) {
        const a = data[i + 3];
        out[i + 0] = Math.round(data[i + 0] * a / 255);
        out[i + 1] = Math.round(data[i + 1] * a / 255);
        out[i + 2] = Math.round(data[i + 2] * a / 255);
        out[i + 3] = a;
    }
    return out;
}
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);
        image.setPixel(stride / 4 / width, index / 4, pxColor);
    };
    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';
const isHeatmapStyleLayer = (layer) => layer.type === 'heatmap';
/**
 * A style layer that defines a heatmap
 */
class HeatmapStyleLayer extends StyleLayer {
    createBucket(options) {
        return new HeatmapBucket(options);
    }
    constructor(layer, globalState) {
        super(layer, properties$7, globalState);
        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(bucket) {
        return getMaximumPaintValue('heatmap-radius', this, bucket);
    }
    queryIntersectsFeature({ queryGeometry, feature, featureState, geometry, transform, pixelsToTileUnits, unwrappedTileID, getElevation }) {
        return circleIntersection({
            queryGeometry,
            size: this.paint.get('heatmap-radius').evaluate(feature, featureState) * pixelsToTileUnits,
            transform,
            unwrappedTileID,
            getElevation
        }, geometry);
    }
    hasOffscreenPass() {
        return this.paint.get('heatmap-opacity') !== 0 && !this.isHidden();
    }
}

// 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-altitude": new DataConstantProperty(v8Spec["paint_hillshade"]["hillshade-illumination-altitude"]),
    "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"]),
    "hillshade-method": new DataConstantProperty(v8Spec["paint_hillshade"]["hillshade-method"]),
    "resampling": new DataConstantProperty(v8Spec["paint_hillshade"]["resampling"]),
});
var properties$6 = ({ get paint() { return getPaint$6(); } });

const isHillshadeStyleLayer = (layer) => layer.type === 'hillshade';
class HillshadeStyleLayer extends StyleLayer {
    constructor(layer, globalState) {
        super(layer, properties$6, globalState);
        this.recalculate({ zoom: 0, zoomHistory: {} }, undefined);
    }
    getIlluminationProperties() {
        let direction = this.paint.get('hillshade-illumination-direction').values;
        let altitude = this.paint.get('hillshade-illumination-altitude').values;
        let highlightColor = this.paint.get('hillshade-highlight-color').values;
        let shadowColor = this.paint.get('hillshade-shadow-color').values;
        // ensure all illumination properties have the same length
        const numIlluminationSources = Math.max(direction.length, altitude.length, highlightColor.length, shadowColor.length);
        direction = direction.concat(Array(numIlluminationSources - direction.length).fill(direction.at(-1)));
        altitude = altitude.concat(Array(numIlluminationSources - altitude.length).fill(altitude.at(-1)));
        highlightColor = highlightColor.concat(Array(numIlluminationSources - highlightColor.length).fill(highlightColor.at(-1)));
        shadowColor = shadowColor.concat(Array(numIlluminationSources - shadowColor.length).fill(shadowColor.at(-1)));
        const altitudeRadians = altitude.map(degreesToRadians);
        const directionRadians = direction.map(degreesToRadians);
        return { directionRadians, altitudeRadians, shadowColor, highlightColor };
    }
    hasOffscreenPass() {
        return this.paint.get('hillshade-exaggeration') !== 0 && !this.isHidden();
    }
}

// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'.
/* eslint-disable */
let paint$5;
const getPaint$5 = () => paint$5 = paint$5 || new Properties({
    "color-relief-opacity": new DataConstantProperty(v8Spec["paint_color-relief"]["color-relief-opacity"]),
    "color-relief-color": new ColorRampProperty(v8Spec["paint_color-relief"]["color-relief-color"]),
    "resampling": new DataConstantProperty(v8Spec["paint_color-relief"]["resampling"]),
});
var properties$5 = ({ get paint() { return getPaint$5(); } });

function hasDataProperty(image) {
    return 'data' in image;
}
/**
 * @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._ownedHandle = this.texture;
        this.update(image, options);
    }
    update(image, options, position) {
        var _a;
        const { width, height } = image;
        const resize = (((_a = this.size) === null || _a === void 0 ? void 0 : _a[0]) !== width || this.size[1] !== height) && !position;
        const { context } = this;
        const { gl } = context;
        this.useMipmap = Boolean(options === null || options === void 0 ? void 0 : options.useMipmap);
        gl.bindTexture(gl.TEXTURE_2D, this.texture);
        context.pixelStoreUnpackFlipY.set(false);
        context.pixelStoreUnpack.set(1);
        const wantPremultiply = this.format === gl.RGBA && ((options === null || options === void 0 ? void 0 : options.premultiply) !== false);
        if (resize) {
            this.size = [width, height];
            if (hasDataProperty(image)) {
                // #2030: raw data is premultiplied in JS
                context.pixelStoreUnpackPremultiplyAlpha.set(false);
                this._uploadRawData(image, wantPremultiply, width, height, gl);
            }
            else {
                context.pixelStoreUnpackPremultiplyAlpha.set(wantPremultiply);
                this._uploadDomImage(image, gl);
            }
        }
        else {
            const { x, y } = position || { x: 0, y: 0 };
            if (hasDataProperty(image)) {
                context.pixelStoreUnpackPremultiplyAlpha.set(false);
                this._updateRawData(image, wantPremultiply, x, y, width, height, gl);
            }
            else {
                context.pixelStoreUnpackPremultiplyAlpha.set(wantPremultiply);
                this._updateDomImage(image, x, y, gl);
            }
        }
        if (this.useMipmap && this.isSizePowerOfTwo()) {
            gl.generateMipmap(gl.TEXTURE_2D);
        }
        context.pixelStoreUnpackFlipY.setDefault();
        context.pixelStoreUnpack.setDefault();
        context.pixelStoreUnpackPremultiplyAlpha.setDefault();
    }
    _uploadDomImage(image, gl) {
        gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, gl.UNSIGNED_BYTE, image);
    }
    _uploadRawData(image, wantPremultiply, width, height, gl) {
        let { data } = image;
        if (wantPremultiply && data)
            data = premultiplyAlpha(data);
        gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, gl.UNSIGNED_BYTE, data);
    }
    _updateDomImage(image, x, y, gl) {
        gl.texSubImage2D(gl.TEXTURE_2D, 0, x, y, gl.RGBA, gl.UNSIGNED_BYTE, image);
    }
    _updateRawData(image, wantPremultiply, x, y, width, height, gl) {
        let { data } = image;
        if (wantPremultiply && data)
            data = premultiplyAlpha(data);
        gl.texSubImage2D(gl.TEXTURE_2D, 0, x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, data);
    }
    bind(filter, wrap, minFilter) {
        const { context } = this;
        const { gl } = context;
        if (this.texture !== this._ownedHandle) {
            this.texture = this._ownedHandle;
        }
        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;
        this._ownedHandle = null;
    }
}

/**
 * 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 png raw 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. x: ${x}, y: ${y}, dim: ${this.dim}`);
        return (y + 1) * this.stride + (x + 1);
    }
    unpack(r, g, b) {
        return (r * this.redFactor + g * this.greenFactor + b * this.blueFactor - this.baseShift);
    }
    pack(v) {
        return packDEMData(v, this.getUnpackVector());
    }
    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)];
            }
        }
    }
}
function packDEMData(v, unpackVector) {
    const redFactor = unpackVector[0];
    const greenFactor = unpackVector[1];
    const blueFactor = unpackVector[2];
    const baseShift = unpackVector[3];
    const minScale = Math.min(redFactor, greenFactor, blueFactor);
    const vScaled = Math.round((v + baseShift) / minScale);
    return {
        r: Math.floor(vScaled * minScale / redFactor) % 256,
        g: Math.floor(vScaled * minScale / greenFactor) % 256,
        b: Math.floor(vScaled * minScale / blueFactor) % 256
    };
}
register('DEMData', DEMData);

const isColorReliefStyleLayer = (layer) => layer.type === 'color-relief';
class ColorReliefStyleLayer extends StyleLayer {
    constructor(layer, globalState) {
        super(layer, properties$5, globalState);
    }
    /**
     * Create the color ramp, enforcing a maximum length for the vectors. This modifies the internal color ramp,
     * so that the remapping is only performed once.
     *
     * @param maxLength - the maximum number of stops in the color ramp
     *
     * @return a `ColorRamp` object with no more than `maxLength` stops.
     *
     */
    _createColorRamp(maxLength) {
        const colorRamp = { elevationStops: [], colorStops: [] };
        const expression = this._transitionablePaint._values['color-relief-color'].value.expression;
        if (expression instanceof ZoomConstantExpression && expression._styleExpression.expression instanceof Interpolate) {
            this.colorRampExpression = expression;
            const interpolater = expression._styleExpression.expression;
            colorRamp.elevationStops = interpolater.labels;
            colorRamp.colorStops = [];
            for (const label of colorRamp.elevationStops) {
                colorRamp.colorStops.push(interpolater.evaluate({ globals: { elevation: label } }));
            }
        }
        if (colorRamp.elevationStops.length < 1) {
            colorRamp.elevationStops = [0];
            colorRamp.colorStops = [Color.transparent];
        }
        if (colorRamp.elevationStops.length < 2) {
            colorRamp.elevationStops.push(colorRamp.elevationStops[0] + 1);
            colorRamp.colorStops.push(colorRamp.colorStops[0]);
        }
        if (colorRamp.elevationStops.length <= maxLength) {
            return colorRamp;
        }
        const remappedColorRamp = { elevationStops: [], colorStops: [] };
        const remapStepSize = (colorRamp.elevationStops.length - 1) / (maxLength - 1);
        for (let i = 0; i < colorRamp.elevationStops.length - 0.5; i += remapStepSize) {
            remappedColorRamp.elevationStops.push(colorRamp.elevationStops[Math.round(i)]);
            remappedColorRamp.colorStops.push(colorRamp.colorStops[Math.round(i)]);
        }
        warnOnce(`Too many colors in specification of ${this.id} color-relief layer, may not render properly. Max possible colors: ${maxLength}, provided: ${colorRamp.elevationStops.length}`);
        return remappedColorRamp;
    }
    _colorRampChanged() {
        return this.colorRampExpression != this._transitionablePaint._values['color-relief-color'].value.expression;
    }
    getColorRampTextures(context, maxLength, unpackVector) {
        if (this.colorRampTextures && !this._colorRampChanged()) {
            return this.colorRampTextures;
        }
        const colorRamp = this._createColorRamp(maxLength);
        const colorImage = new RGBAImage({ width: colorRamp.colorStops.length, height: 1 });
        const elevationImage = new RGBAImage({ width: colorRamp.colorStops.length, height: 1 });
        for (let i = 0; i < colorRamp.elevationStops.length; i++) {
            const elevationPacked = packDEMData(colorRamp.elevationStops[i], unpackVector);
            elevationImage.setPixel(0, i, new Color(elevationPacked.r / 255, elevationPacked.g / 255, elevationPacked.b / 255, 1));
            colorImage.setPixel(0, i, colorRamp.colorStops[i]);
        }
        this.colorRampTextures = {
            elevationTexture: new Texture(context, elevationImage, context.gl.RGBA),
            colorTexture: new Texture(context, colorImage, context.gl.RGBA)
        };
        return this.colorRampTextures;
    }
    hasOffscreenPass() {
        return !this.isHidden() && !!this.colorRampTextures;
    }
}

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 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, parameters, options) {
    const { zoom } = parameters;
    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 === null || min === void 0 ? void 0 : min.name) ? min.name : min;
            mid = (mid === null || mid === void 0 ? void 0 : mid.name) ? mid.name : mid;
            max = (max === null || max === void 0 ? void 0 : 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;
}

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 = data[0];
        minY = data[1];
        let maxX = minX;
        let maxY = minY;

        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
    const x0 = Math.min(ax, bx, cx),
        y0 = Math.min(ay, by, cy),
        x1 = Math.max(ax, bx, cx),
        y1 = Math.max(ay, by, cy);

    let p = c.next;
    while (p !== a) {
        if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
            pointInTriangleExceptFirst(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
    const x0 = Math.min(ax, bx, cx),
        y0 = Math.min(ay, by, cy),
        x1 = Math.max(ax, bx, cx),
        y1 = Math.max(ay, 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 &&
            pointInTriangleExceptFirst(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 &&
            pointInTriangleExceptFirst(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 &&
            pointInTriangleExceptFirst(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 &&
            pointInTriangleExceptFirst(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(compareXYSlope);

    // process holes from left to right
    for (let i = 0; i < queue.length; i++) {
        outerNode = eliminateHole(queue[i], outerNode);
    }

    return outerNode;
}

function compareXYSlope(a, b) {
    let result = a.x - b.x;
    // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find
    // the bridge to the outer shell is always the point that they meet at.
    if (result === 0) {
        result = a.y - b.y;
        if (result === 0) {
            const aSlope = (a.next.y - a.y) / (a.next.x - a.x);
            const bSlope = (b.next.y - b.y) / (b.next.x - b.x);
            result = aSlope - bSlope;
        }
    }
    return result;
}

// find a bridge between vertices that connects hole with an outer ring 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
    // unless they intersect at a vertex, then choose the vertex
    if (equals(hole, p)) return p;
    do {
        if (equals(hole, p.next)) return p.next;
        else 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 point lies within a convex triangle but false if its equal to the first point of the triangle
function pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {
    return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, 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) && // doesn'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$1(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};
}

// Should match actual possible granularity settings from circle_bucket.ts
/**
 * Controls how much subdivision happens for a given type of geometry at different zoom levels.
 */
class SubdivisionGranularityExpression {
    constructor(baseZoomGranularity, minGranularity) {
        if (minGranularity > baseZoomGranularity) {
            throw new Error('Min granularity must not be greater than base granularity.');
        }
        this._baseZoomGranularity = baseZoomGranularity;
        this._minGranularity = minGranularity;
    }
    getGranularityForZoomLevel(zoomLevel) {
        const divisor = 1 << zoomLevel;
        return Math.max(Math.floor(this._baseZoomGranularity / divisor), this._minGranularity, 1);
    }
}
/**
 * An object describing how much subdivision should be applied to different types of geometry at different zoom levels.
 */
class SubdivisionGranularitySetting {
    constructor(options) {
        this.fill = options.fill;
        this.line = options.line;
        this.tile = options.tile;
        this.stencil = options.stencil;
        this.circle = options.circle;
    }
}
/**
 * Granularity settings that disable subdivision altogether.
 */
SubdivisionGranularitySetting.noSubdivision = new SubdivisionGranularitySetting({
    fill: new SubdivisionGranularityExpression(0, 0),
    line: new SubdivisionGranularityExpression(0, 0),
    tile: new SubdivisionGranularityExpression(0, 0),
    stencil: new SubdivisionGranularityExpression(0, 0),
    circle: 1
});

register('SubdivisionGranularityExpression', SubdivisionGranularityExpression);
register('SubdivisionGranularitySetting', SubdivisionGranularitySetting);
// Special pole vertices have coordinates -32768,-32768 for the north pole and 32767,32767 for the south pole.
// First, find any *non-pole* vertices at those coordinates and move them slightly elsewhere.
const NORTH_POLE_Y = -32768;
const SOUTH_POLE_Y = 32767;
class Subdivider {
    constructor(granularity, canonical) {
        /**
         * Flattened vertex positions (xyxyxy).
         */
        this._vertexBuffer = [];
        /**
         * Map of "vertex x and y coordinate" to "index of such vertex".
         */
        this._vertexDictionary = new Map();
        this._used = false;
        this._granularity = granularity;
        this._granularityCellSize = EXTENT$1 / granularity;
        this._canonical = canonical;
    }
    _getKey(x, y) {
        // Assumes signed 16 bit positions.
        x = x + 32768;
        y = y + 32768;
        return (x << 16) | (y << 0);
    }
    /**
     * Returns an index into the internal vertex buffer for a vertex at the given coordinates.
     * If the internal vertex buffer contains no such vertex, then it is added.
     */
    _vertexToIndex(x, y) {
        if (x < -32768 || y < -32768 || x > 32767 || y > 32767) {
            throw new Error('Vertex coordinates are out of signed 16 bit integer range.');
        }
        const xInt = Math.round(x) | 0;
        const yInt = Math.round(y) | 0;
        const key = this._getKey(xInt, yInt);
        if (this._vertexDictionary.has(key)) {
            return this._vertexDictionary.get(key);
        }
        const index = this._vertexBuffer.length / 2;
        this._vertexDictionary.set(key, index);
        this._vertexBuffer.push(xInt, yInt);
        return index;
    }
    /**
     * Subdivides a polygon by iterating over rows of granularity subdivision cells and splitting each row along vertical subdivision axes.
     * @param inputIndices - Indices into the internal vertex buffer of the triangulated polygon (after running `earcut`).
     * @returns Indices into the internal vertex buffer for triangles that are a subdivision of the input geometry.
     */
    _subdivideTrianglesScanline(inputIndices) {
        // A granularity cell is the square space between axes that subdivide geometry.
        // For granularity 8, cells would be 1024 by 1024 units.
        // For each triangle, we iterate over all cell rows it intersects, and generate subdivided geometry
        // only within one cell row at a time. This way, we implicitly subdivide along the X-parallel axes (cell row boundaries).
        // For each cell row, we generate an ordered point ring that describes the subdivided geometry inside this row (an intersection of the triangle and a given cell row).
        // Such ordered ring can be trivially triangulated.
        // Each ring may consist of sections of triangle edges that lie inside the cell row, and cell boundaries that lie inside the triangle. Both must be further subdivided along Y-parallel axes.
        // Most complexity of this function comes from generating correct vertex rings, and from placing the vertices into the ring in the correct order.
        if (this._granularity < 2) {
            // The actual subdivision code always produces triangles with the correct winding order.
            // Also apply winding order correction when skipping subdivision altogether to maintain consistency.
            return fixWindingOrder(this._vertexBuffer, inputIndices);
        }
        const finalIndices = [];
        // Iterate over all input triangles
        const numIndices = inputIndices.length;
        for (let primitiveIndex = 0; primitiveIndex < numIndices; primitiveIndex += 3) {
            const triangleIndices = [
                inputIndices[primitiveIndex + 0], // v0
                inputIndices[primitiveIndex + 1], // v1
                inputIndices[primitiveIndex + 2], // v2
            ];
            const triangleVertices = [
                this._vertexBuffer[inputIndices[primitiveIndex + 0] * 2 + 0], // v0.x
                this._vertexBuffer[inputIndices[primitiveIndex + 0] * 2 + 1], // v0.y
                this._vertexBuffer[inputIndices[primitiveIndex + 1] * 2 + 0], // v1.x
                this._vertexBuffer[inputIndices[primitiveIndex + 1] * 2 + 1], // v1.y
                this._vertexBuffer[inputIndices[primitiveIndex + 2] * 2 + 0], // v2.x
                this._vertexBuffer[inputIndices[primitiveIndex + 2] * 2 + 1], // v2.y
            ];
            let minX = Infinity;
            let minY = Infinity;
            let maxX = -Infinity;
            let maxY = -Infinity;
            // Compute AABB
            for (let i = 0; i < 3; i++) {
                const vx = triangleVertices[i * 2];
                const vy = triangleVertices[i * 2 + 1];
                minX = Math.min(minX, vx);
                maxX = Math.max(maxX, vx);
                minY = Math.min(minY, vy);
                maxY = Math.max(maxY, vy);
            }
            if (minX === maxX || minY === maxY) {
                continue; // Skip degenerate linear axis-aligned triangles
            }
            const cellXmin = Math.floor(minX / this._granularityCellSize);
            const cellXmax = Math.ceil(maxX / this._granularityCellSize);
            const cellYmin = Math.floor(minY / this._granularityCellSize);
            const cellYmax = Math.ceil(maxY / this._granularityCellSize);
            // Skip subdividing triangles that do not span multiple cells - just add them "as is".
            if (cellXmin === cellXmax && cellYmin === cellYmax) {
                finalIndices.push(...triangleIndices);
                continue;
            }
            // Iterate over cell rows that intersect this triangle
            for (let cellRow = cellYmin; cellRow < cellYmax; cellRow++) {
                const ring = this._scanlineGenerateVertexRingForCellRow(cellRow, triangleVertices, triangleIndices);
                scanlineTriangulateVertexRing(this._vertexBuffer, ring, finalIndices);
            }
        }
        return finalIndices;
    }
    /**
     * Takes a triangle and a cell row index, returns a subdivided vertex ring of the intersection of the triangle and the cell row.
     * @param cellRow - Index of the cell row. A cell row of index `i` convert range from `i * granularityCellSize` to `(i + 1) * granularityCellSize`.
     * @param triangleVertices - An array of 6 elements, contains flattened positions of the triangle's vertices: `[v0x, v0y, v1x, v1y, v2x, v2y]`.
     * @param triangleIndices - An array of 3 elements, contains the original indices of the triangle's vertices: `[index0, index1, index2]`.
     * @returns The resulting ring of vertex indices and the index (to the returned ring array) of the leftmost vertex in the ring.
     */
    _scanlineGenerateVertexRingForCellRow(cellRow, triangleVertices, triangleIndices) {
        const cellRowYTop = cellRow * this._granularityCellSize;
        const cellRowYBottom = cellRowYTop + this._granularityCellSize;
        const ring = [];
        // Generate the vertex ring
        for (let edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
            // Current edge that will be subdivided: a --> b
            // The remaining vertex of the triangle: c
            const aX = triangleVertices[edgeIndex * 2];
            const aY = triangleVertices[edgeIndex * 2 + 1];
            const bX = triangleVertices[((edgeIndex + 1) * 2) % 6];
            const bY = triangleVertices[((edgeIndex + 1) * 2 + 1) % 6];
            const cX = triangleVertices[((edgeIndex + 2) * 2) % 6];
            const cY = triangleVertices[((edgeIndex + 2) * 2 + 1) % 6];
            // Edge direction
            const dirX = bX - aX;
            const dirY = bY - aY;
            // Edges parallel with either axis will need special handling later.
            const isParallelY = dirX === 0;
            const isParallelX = dirY === 0;
            // Distance along edge where it enters/exits current cell row,
            // where distance 0 is the edge start point, 1 the endpoint, 0.5 the mid point, etc.
            const tTop = (cellRowYTop - aY) / dirY;
            const tBottom = (cellRowYBottom - aY) / dirY;
            const tEnter = Math.min(tTop, tBottom);
            const tExit = Math.max(tTop, tBottom);
            // Determine if edge lies entirely outside this cell row.
            // Check entry and exit points, or if edge is parallel with X, check its Y coordinate.
            if ((!isParallelX && (tEnter >= 1 || tExit <= 0)) ||
                (isParallelX && (aY < cellRowYTop || aY > cellRowYBottom))) {
                // Skip this edge
                // But make sure to add its endpoint vertex if needed.
                if (bY >= cellRowYTop && bY <= cellRowYBottom) {
                    // The edge endpoint is within this row, add it to the ring
                    ring.push(triangleIndices[(edgeIndex + 1) % 3]);
                }
                continue;
            }
            // Do not add original triangle vertices now, those are handled separately later
            // Special case: edge vertex for entry into cell row
            // If edge is parallel with X axis, there is no entry vertex
            if (!isParallelX && tEnter > 0) {
                const x = aX + dirX * tEnter;
                const y = aY + dirY * tEnter;
                ring.push(this._vertexToIndex(x, y));
            }
            // The X coordinates of the points where the edge enters/exits the current cell row,
            // or the edge start/endpoint, if the entry/exit happens beyond the edge bounds.
            const enterX = aX + dirX * Math.max(tEnter, 0);
            const exitX = aX + dirX * Math.min(tExit, 1);
            // Generate edge interior vertices
            // No need to subdivide (along X) edges that are parallel with Y
            if (!isParallelY) {
                this._generateIntraEdgeVertices(ring, aX, aY, bX, bY, enterX, exitX);
            }
            // Special case: edge vertex for exit from cell row
            if (!isParallelX && tExit < 1) {
                const x = aX + dirX * tExit;
                const y = aY + dirY * tExit;
                ring.push(this._vertexToIndex(x, y));
            }
            // When to split inter-edge boundary segments?
            // When the boundary doesn't intersect a vertex, its easy. But what if it does?
            //      a
            //     /|
            //    / |
            // --c--|--boundary
            //    \ |
            //     \|
            //      b
            //
            // Inter-edge region should be generated when processing the a-b edge.
            // This happens fine for the top row, for the bottom row,
            //
            //      x
            //     /|
            //    / |
            // --x--x--boundary
            //
            // Edge that lies on boundary should be subdivided in its edge phase.
            // The inter-edge phase will correctly skip it.
            // Add endpoint vertex
            if (isParallelX || (bY >= cellRowYTop && bY <= cellRowYBottom)) {
                ring.push(triangleIndices[(edgeIndex + 1) % 3]);
            }
            // Any edge that has endpoint outside this row or on its boundary gets
            // inter-edge vertices.
            // No row boundary to split for edges parallel with X
            if (!isParallelX && (bY <= cellRowYTop || bY >= cellRowYBottom)) {
                this._generateInterEdgeVertices(ring, aX, aY, bX, bY, cX, cY, exitX, cellRowYTop, cellRowYBottom);
            }
        }
        return ring;
    }
    /**
     * Generates ring vertices along an edge A-\>B, but only in the part that intersects a given cell row.
     * Does not handle adding edge endpoint vertices or edge cell row enter/exit vertices.
     * @param ring - Ordered array of vertex indices for the constructed ring. New indices are placed here.
     * @param enterX - The X coordinate of the point where edge A-\>B enters the current cell row.
     * @param exitX - The X coordinate of the point where edge A-\>B exits the current cell row.
     */
    _generateIntraEdgeVertices(ring, aX, aY, bX, bY, enterX, exitX) {
        const dirX = bX - aX;
        const dirY = bY - aY;
        const isParallelX = dirY === 0;
        const leftX = isParallelX ? Math.min(aX, bX) : Math.min(enterX, exitX);
        const rightX = isParallelX ? Math.max(aX, bX) : Math.max(enterX, exitX);
        const edgeSubdivisionLeftCellX = Math.floor(leftX / this._granularityCellSize) + 1;
        const edgeSubdivisionRightCellX = Math.ceil(rightX / this._granularityCellSize) - 1;
        const isEdgeLeftToRight = isParallelX ? (aX < bX) : (enterX < exitX);
        if (isEdgeLeftToRight) {
            // Left to right
            for (let cellX = edgeSubdivisionLeftCellX; cellX <= edgeSubdivisionRightCellX; cellX++) {
                const x = cellX * this._granularityCellSize;
                const y = aY + dirY * (x - aX) / dirX;
                ring.push(this._vertexToIndex(x, y));
            }
        }
        else {
            // Right to left
            for (let cellX = edgeSubdivisionRightCellX; cellX >= edgeSubdivisionLeftCellX; cellX--) {
                const x = cellX * this._granularityCellSize;
                const y = aY + dirY * (x - aX) / dirX;
                ring.push(this._vertexToIndex(x, y));
            }
        }
    }
    /**
     * Generates ring vertices along cell border.
     * Call when processing an edge A-\>B that exits the current row (B lies outside the current row).
     * Generates vertices along the cell edge between the exit point from cell row
     * of edge A-\>B and entry of edge B-\>C, or entry of C-\>A if both A and C lie outside the cell row.
     * Does not handle adding edge endpoint vertices or edge cell row enter/exit vertices.
     * @param ring - Ordered array of vertex indices for the constructed ring. New indices are placed here.
     * @param exitX - The X coordinate of the point where edge A-\>B exits the current cell row.
     * @param cellRowYTop - The current cell row top Y coordinate.
     * @param cellRowYBottom - The current cell row bottom Y coordinate.
     */
    _generateInterEdgeVertices(ring, aX, aY, bX, bY, cX, cY, exitX, cellRowYTop, cellRowYBottom) {
        const dirY = bY - aY;
        const dir2X = cX - bX;
        const dir2Y = cY - bY;
        const t2Top = (cellRowYTop - bY) / dir2Y;
        const t2Bottom = (cellRowYBottom - bY) / dir2Y;
        // The distance along edge B->C where it enters/exits the current cell row,
        // where distance 0 is B, 1 is C, 0.5 is the edge midpoint, etc.
        const t2Enter = Math.min(t2Top, t2Bottom);
        const t2Exit = Math.max(t2Top, t2Bottom);
        const enter2X = bX + dir2X * t2Enter;
        let boundarySubdivisionLeftCellX = Math.floor(Math.min(enter2X, exitX) / this._granularityCellSize) + 1;
        let boundarySubdivisionRightCellX = Math.ceil(Math.max(enter2X, exitX) / this._granularityCellSize) - 1;
        let isBoundaryLeftToRight = exitX < enter2X;
        const isParallelX2 = dir2Y === 0;
        if (isParallelX2 && (cY === cellRowYTop || cY === cellRowYBottom)) {
            // Special case when edge b->c that lies on the cell boundary.
            // Do not generate any inter-edge vertices in this case,
            // this b->c edge gets subdivided when it is itself processed.
            return;
        }
        if (isParallelX2 || t2Enter >= 1 || t2Exit <= 0) {
            // The next edge (b->c) lies entirely outside this cell row
            // Find entry point for the edge after that instead (c->a)
            // There may be at most 1 edge that is parallel to X in a triangle.
            // The main "a->b" edge must not be parallel at this point in the code.
            // We know that "a->b" crosses the current cell row boundary, such that point "b" is beyond the boundary.
            // If "b->c" is parallel to X, then "c->a" must not be parallel and must cross the cell row boundary back:
            //      a
            //      |\
            // -----|-\--cell row boundary----
            //      |  \
            //      c---b
            // If "b->c" is not parallel to X and doesn't cross the cell row boundary,
            // then c->a must also not be parallel to X and must cross the cell boundary back,
            // since points "a" and "c" lie on different sides of the boundary and on different Y coordinates.
            //
            // Thus there is no need for "parallel with X" checks inside this condition branch.
            // Compute the X coordinate where edge C->A enters the current cell row
            const dir3X = aX - cX;
            const dir3Y = aY - cY;
            const t3Top = (cellRowYTop - cY) / dir3Y;
            const t3Bottom = (cellRowYBottom - cY) / dir3Y;
            const t3Enter = Math.min(t3Top, t3Bottom);
            const enter3X = cX + dir3X * t3Enter;
            boundarySubdivisionLeftCellX = Math.floor(Math.min(enter3X, exitX) / this._granularityCellSize) + 1;
            boundarySubdivisionRightCellX = Math.ceil(Math.max(enter3X, exitX) / this._granularityCellSize) - 1;
            isBoundaryLeftToRight = exitX < enter3X;
        }
        const boundaryY = dirY > 0 ? cellRowYBottom : cellRowYTop;
        if (isBoundaryLeftToRight) {
            // Left to right
            for (let cellX = boundarySubdivisionLeftCellX; cellX <= boundarySubdivisionRightCellX; cellX++) {
                const x = cellX * this._granularityCellSize;
                ring.push(this._vertexToIndex(x, boundaryY));
            }
        }
        else {
            // Right to left
            for (let cellX = boundarySubdivisionRightCellX; cellX >= boundarySubdivisionLeftCellX; cellX--) {
                const x = cellX * this._granularityCellSize;
                ring.push(this._vertexToIndex(x, boundaryY));
            }
        }
    }
    /**
     * Generates an outline for a given polygon, returns a list of arrays of line indices.
     */
    _generateOutline(polygon) {
        const subdividedLines = [];
        for (const ring of polygon) {
            const line = subdivideVertexLine(ring, this._granularity, true);
            const pathIndices = this._pointArrayToIndices(line);
            // Points returned by subdivideVertexLine are "path" waypoints,
            // for example with indices 0 1 2 3 0.
            // We need list of individual line segments for rendering,
            // for example 0, 1, 1, 2, 2, 3, 3, 0.
            const lineIndices = [];
            for (let i = 1; i < pathIndices.length; i++) {
                lineIndices.push(pathIndices[i - 1]);
                lineIndices.push(pathIndices[i]);
            }
            subdividedLines.push(lineIndices);
        }
        return subdividedLines;
    }
    /**
     * Adds pole geometry if needed.
     * @param subdividedTriangles - Array of generated triangle indices, new pole geometry is appended here.
     */
    _handlePoles(subdividedTriangles) {
        // Add pole vertices if the tile is at north/south mercator edge
        let north = false;
        let south = false;
        if (this._canonical) {
            if (this._canonical.y === 0) {
                north = true;
            }
            if (this._canonical.y === (1 << this._canonical.z) - 1) {
                south = true;
            }
        }
        if (north || south) {
            this._fillPoles(subdividedTriangles, north, south);
        }
    }
    /**
     * Checks the internal vertex buffer for all vertices that might lie on the special pole coordinates and shifts them by one unit.
     * Use for removing unintended pole vertices that might have been created during subdivision. After calling this function, actual pole vertices can be safely generated.
     */
    _ensureNoPoleVertices() {
        const flattened = this._vertexBuffer;
        for (let i = 0; i < flattened.length; i += 2) {
            const vy = flattened[i + 1];
            if (vy === NORTH_POLE_Y) {
                // Move slightly down
                flattened[i + 1] = NORTH_POLE_Y + 1;
            }
            if (vy === SOUTH_POLE_Y) {
                // Move slightly down
                flattened[i + 1] = SOUTH_POLE_Y - 1;
            }
        }
    }
    /**
     * Generates a quad from an edge to a pole with the correct winding order.
     * Helper function used inside {@link _fillPoles}.
     * @param indices - Index array into which the geometry is generated.
     * @param i0 - Index of the first edge vertex.
     * @param i1 - Index of the second edge vertex.
     * @param v0x - X coordinate of the first edge vertex.
     * @param v1x - X coordinate of the second edge vertex.
     * @param poleY - The Y coordinate of the desired pole (NORTH_POLE_Y or SOUTH_POLE_Y).
     */
    _generatePoleQuad(indices, i0, i1, v0x, v1x, poleY) {
        const flip = (v0x > v1x) !== (poleY === NORTH_POLE_Y);
        if (flip) {
            indices.push(i0);
            indices.push(i1);
            indices.push(this._vertexToIndex(v0x, poleY));
            indices.push(i1);
            indices.push(this._vertexToIndex(v1x, poleY));
            indices.push(this._vertexToIndex(v0x, poleY));
        }
        else {
            indices.push(i1);
            indices.push(i0);
            indices.push(this._vertexToIndex(v0x, poleY));
            indices.push(this._vertexToIndex(v1x, poleY));
            indices.push(i1);
            indices.push(this._vertexToIndex(v0x, poleY));
        }
    }
    /**
     * Detects edges that border the north or south tile edge
     * and adds triangles that extend those edges to the poles.
     * Only run this function on tiles that border the poles.
     * Assumes that supplied geometry is clipped to the inclusive range of 0..EXTENT.
     * Mutates the supplies vertex and index arrays.
     * @param indices - Triangle indices. This array is appended with new primitives.
     * @param north - Whether to generate geometry for the north pole.
     * @param south - Whether to generate geometry for the south pole.
     */
    _fillPoles(indices, north, south) {
        const flattened = this._vertexBuffer;
        const northEdge = 0;
        const southEdge = EXTENT$1;
        const numIndices = indices.length;
        for (let primitiveIndex = 2; primitiveIndex < numIndices; primitiveIndex += 3) {
            const i0 = indices[primitiveIndex - 2];
            const i1 = indices[primitiveIndex - 1];
            const i2 = indices[primitiveIndex];
            const v0x = flattened[i0 * 2];
            const v0y = flattened[i0 * 2 + 1];
            const v1x = flattened[i1 * 2];
            const v1y = flattened[i1 * 2 + 1];
            const v2x = flattened[i2 * 2];
            const v2y = flattened[i2 * 2 + 1];
            if (north) {
                if (v0y === northEdge && v1y === northEdge) {
                    this._generatePoleQuad(indices, i0, i1, v0x, v1x, NORTH_POLE_Y);
                }
                if (v1y === northEdge && v2y === northEdge) {
                    this._generatePoleQuad(indices, i1, i2, v1x, v2x, NORTH_POLE_Y);
                }
                if (v2y === northEdge && v0y === northEdge) {
                    this._generatePoleQuad(indices, i2, i0, v2x, v0x, NORTH_POLE_Y);
                }
            }
            if (south) {
                if (v0y === southEdge && v1y === southEdge) {
                    this._generatePoleQuad(indices, i0, i1, v0x, v1x, SOUTH_POLE_Y);
                }
                if (v1y === southEdge && v2y === southEdge) {
                    this._generatePoleQuad(indices, i1, i2, v1x, v2x, SOUTH_POLE_Y);
                }
                if (v2y === southEdge && v0y === southEdge) {
                    this._generatePoleQuad(indices, i2, i0, v2x, v0x, SOUTH_POLE_Y);
                }
            }
        }
    }
    /**
     * Adds all vertices in the supplied flattened vertex buffer into the internal vertex buffer.
     */
    _initializeVertices(flattened) {
        for (let i = 0; i < flattened.length; i += 2) {
            this._vertexToIndex(flattened[i], flattened[i + 1]);
        }
    }
    /**
     * Subdivides an input mesh. Imagine a regular square grid with the target granularity overlaid over the mesh - this is the subdivision's result.
     * Assumes a mesh of tile features - vertex coordinates are integers, visible range where subdivision happens is 0..8192.
     * @param polygon - The input polygon, specified as a list of vertex rings.
     * @param generateOutlineLines - When true, also generates line indices for outline of the supplied polygon.
     * @returns Vertex and index buffers with subdivision applied.
     */
    subdividePolygonInternal(polygon, generateOutlineLines) {
        if (this._used) {
            throw new Error('Subdivision: multiple use not allowed.');
        }
        this._used = true;
        // Initialize the vertex dictionary with input vertices since we will use all of them anyway
        const { flattened, holeIndices } = flatten(polygon);
        this._initializeVertices(flattened);
        // Subdivide triangles
        let subdividedTriangles;
        try {
            // At this point this._finalVertices is just flattened polygon points
            const earcutResult = earcut(flattened, holeIndices);
            const cut = this._convertIndices(flattened, earcutResult);
            subdividedTriangles = this._subdivideTrianglesScanline(cut);
        }
        catch (e) {
            console.error(e);
        }
        // Subdivide lines
        let subdividedLines = [];
        if (generateOutlineLines) {
            subdividedLines = this._generateOutline(polygon);
        }
        // Ensure no vertex has the special value used for pole vertices
        this._ensureNoPoleVertices();
        // Add pole geometry if needed
        this._handlePoles(subdividedTriangles);
        return {
            verticesFlattened: this._vertexBuffer,
            indicesTriangles: subdividedTriangles,
            indicesLineList: subdividedLines,
        };
    }
    /**
     * Sometimes the supplies vertex and index array has duplicate vertices - same coordinates that are referenced by multiple different indices.
     * That is not allowed for purposes of subdivision, duplicates are removed in `this.initializeVertices`.
     * This function converts the original index array that indexes into the original vertex array with duplicates
     * into an index array that indexes into `this._finalVertices`.
     * @param vertices - Flattened vertex array used by the old indices. This may contain duplicate vertices.
     * @param oldIndices - Indices into the old vertex array.
     * @returns Indices transformed so that they are valid indices into `this._finalVertices` (with duplicates removed).
     */
    _convertIndices(vertices, oldIndices) {
        const newIndices = [];
        for (const oldIndex of oldIndices) {
            const x = vertices[oldIndex * 2];
            const y = vertices[oldIndex * 2 + 1];
            newIndices.push(this._vertexToIndex(x, y));
        }
        return newIndices;
    }
    /**
     * Converts an array of points into an array of indices into the internal vertex buffer (`_finalVertices`).
     */
    _pointArrayToIndices(array) {
        const indices = [];
        for (const p of array) {
            indices.push(this._vertexToIndex(p.x, p.y));
        }
        return indices;
    }
}
/**
 * Subdivides a polygon to a given granularity. Intended for preprocessing geometry for the 'fill' and 'fill-extrusion' layer types.
 * All returned triangles have the counter-clockwise winding order.
 * @param polygon - An array of point rings that specify the polygon. The first ring is the polygon exterior, all subsequent rings form holes inside the first ring.
 * @param canonical - The canonical tile ID of the tile this polygon belongs to. Needed for generating special geometry for tiles that border the poles.
 * @param granularity - The subdivision granularity. If we assume tile EXTENT=8192, then a granularity of 2 will result in geometry being "cut" on each axis
 * divisible by 4096 (including outside the tile range, so -8192, -4096, or 12288...), granularity of 8 on axes divisible by 1024 and so on.
 * Granularity of 1 or lower results in *no* subdivision.
 * @param generateOutlineLines - When true, also generates index arrays for subdivided lines that form the outline of the supplied polygon. True by default.
 * @returns An object that contains the generated vertex array, triangle index array and, if specified, line index arrays.
 */
function subdividePolygon(polygon, canonical, granularity, generateOutlineLines = true) {
    const subdivider = new Subdivider(granularity, canonical);
    return subdivider.subdividePolygonInternal(polygon, generateOutlineLines);
}
/**
 * Subdivides a line represented by an array of points. Mainly intended for preprocessing geometry for the 'line' layer type.
 * Assumes a line segment between each two consecutive points in the array.
 * Does not assume a line segment from last point to first point, unless `isRing` is set to `true`.
 * For example, an array of 4 points describes exactly 3 line segments.
 * @param linePoints - An array of points describing the line segments.
 * @param granularity - Subdivision granularity.
 * @param isRing - When true, an additional line segment is assumed to exist between the input array's last and first point.
 * @returns A new array of points of the subdivided line segments. The array may contain some of the original Point objects. If `isRing` is set to `true`, then this also includes the (subdivided) segment from the last point of the input array to the first point.
 *
 * @example
 * ```ts
 * const result = subdivideVertexLine([
 *   new Point(0, 0),
 *   new Point(8, 0),
 *   new Point(0, 8),
 * ], EXTENT / 4, false);
 * // Results in an array of points with these (x, y) coordinates:
 * //   0, 0
 * //   4, 0
 * //   8, 0
 * //   4, 4
 * //   0, 8
 * ```
 *
 * @example
 * ```ts
 * const result = subdivideVertexLine([
 *   new Point(0, 0),
 *   new Point(8, 0),
 *   new Point(0, 8),
 * ], EXTENT / 4, true);
 * // Results in an array of points with these (x, y) coordinates:
 * //   0, 0
 * //   4, 0
 * //   8, 0
 * //   4, 4
 * //   0, 8
 * //   0, 4
 * //   0, 0
 * ```
 */
function subdivideVertexLine(linePoints, granularity, isRing = false) {
    if (!linePoints || linePoints.length < 1) {
        return [];
    }
    if (linePoints.length < 2) {
        return [];
    }
    // Generate an extra line segment between the input array's first and last points,
    // but only if isRing=true AND the first and last points actually differ.
    const first = linePoints[0];
    const last = linePoints[linePoints.length - 1];
    const addLastToFirstSegment = isRing && (first.x !== last.x || first.y !== last.y);
    if (granularity < 2) {
        if (addLastToFirstSegment) {
            return [...linePoints, linePoints[0]];
        }
        else {
            return [...linePoints];
        }
    }
    const cellSize = Math.floor(EXTENT$1 / granularity);
    const finalLineVertices = [];
    finalLineVertices.push(new Point(linePoints[0].x, linePoints[0].y));
    // Iterate over all input lines
    const totalPoints = linePoints.length;
    const lastIndex = addLastToFirstSegment ? totalPoints : (totalPoints - 1);
    for (let pointIndex = 0; pointIndex < lastIndex; pointIndex++) {
        const linePoint0 = linePoints[pointIndex];
        const linePoint1 = pointIndex < (totalPoints - 1) ? linePoints[pointIndex + 1] : linePoints[0];
        const lineVertex0x = linePoint0.x;
        const lineVertex0y = linePoint0.y;
        const lineVertex1x = linePoint1.x;
        const lineVertex1y = linePoint1.y;
        const dirXnonZero = lineVertex0x !== lineVertex1x;
        const dirYnonZero = lineVertex0y !== lineVertex1y;
        if (!dirXnonZero && !dirYnonZero) {
            continue;
        }
        const dirX = lineVertex1x - lineVertex0x;
        const dirY = lineVertex1y - lineVertex0y;
        const absDirX = Math.abs(dirX);
        const absDirY = Math.abs(dirY);
        let lastPointX = lineVertex0x;
        let lastPointY = lineVertex0y;
        // Walk along the line segment from start to end. In every step,
        // find out the distance from start until the line intersects either the X-parallel or Y-parallel subdivision axis.
        // Pick the closer intersection, add it to the final line points and consider that point the new start of the line.
        // But also make sure the intersection point does not lie beyond the end of the line.
        // If none of the intersection points is closer than line end, add the endpoint to the final line and break the loop.
        while (true) {
            const nextBoundaryX = dirX > 0 ?
                ((Math.floor(lastPointX / cellSize) + 1) * cellSize) :
                ((Math.ceil(lastPointX / cellSize) - 1) * cellSize);
            const nextBoundaryY = dirY > 0 ?
                ((Math.floor(lastPointY / cellSize) + 1) * cellSize) :
                ((Math.ceil(lastPointY / cellSize) - 1) * cellSize);
            const axisDistanceToBoundaryX = Math.abs(lastPointX - nextBoundaryX);
            const axisDistanceToBoundaryY = Math.abs(lastPointY - nextBoundaryY);
            const axisDistanceToEndX = Math.abs(lastPointX - lineVertex1x);
            const axisDistanceToEndY = Math.abs(lastPointY - lineVertex1y);
            const realDistanceToBoundaryX = dirXnonZero ? axisDistanceToBoundaryX / absDirX : Number.POSITIVE_INFINITY;
            const realDistanceToBoundaryY = dirYnonZero ? axisDistanceToBoundaryY / absDirY : Number.POSITIVE_INFINITY;
            if ((axisDistanceToEndX <= axisDistanceToBoundaryX || !dirXnonZero) &&
                (axisDistanceToEndY <= axisDistanceToBoundaryY || !dirYnonZero)) {
                break;
            }
            if ((realDistanceToBoundaryX < realDistanceToBoundaryY && dirXnonZero) || !dirYnonZero) {
                // We hit the X cell boundary first
                // Always consider the X cell hit if Y dir is zero
                lastPointX = nextBoundaryX;
                lastPointY = lastPointY + dirY * realDistanceToBoundaryX;
                const next = new Point(lastPointX, Math.round(lastPointY));
                // Do not add the next vertex if it is equal to the last added vertex
                if (finalLineVertices[finalLineVertices.length - 1].x !== next.x ||
                    finalLineVertices[finalLineVertices.length - 1].y !== next.y) {
                    finalLineVertices.push(next);
                }
            }
            else {
                lastPointX = lastPointX + dirX * realDistanceToBoundaryY;
                lastPointY = nextBoundaryY;
                const next = new Point(Math.round(lastPointX), lastPointY);
                if (finalLineVertices[finalLineVertices.length - 1].x !== next.x ||
                    finalLineVertices[finalLineVertices.length - 1].y !== next.y) {
                    finalLineVertices.push(next);
                }
            }
        }
        const last = new Point(lineVertex1x, lineVertex1y);
        if (finalLineVertices[finalLineVertices.length - 1].x !== last.x ||
            finalLineVertices[finalLineVertices.length - 1].y !== last.y) {
            finalLineVertices.push(last);
        }
    }
    return finalLineVertices;
}
/**
 * Takes a polygon as an array of point rings, returns a flattened array of the X,Y coordinates of these points.
 * Also creates an array of hole indices. Both returned arrays are required for `earcut`.
 */
function flatten(polygon) {
    const holeIndices = [];
    const flattened = [];
    for (const ring of polygon) {
        if (ring.length === 0) {
            continue;
        }
        if (ring !== polygon[0]) {
            holeIndices.push(flattened.length / 2);
        }
        for (const vertex of ring) {
            flattened.push(vertex.x);
            flattened.push(vertex.y);
        }
    }
    return {
        flattened,
        holeIndices
    };
}
/**
 * Returns a new array of indices where all triangles have the counter-clockwise winding order.
 * @param flattened - Flattened vertex buffer.
 * @param indices - Triangle indices.
 */
function fixWindingOrder(flattened, indices) {
    const corrected = [];
    for (let i = 0; i < indices.length; i += 3) {
        const i0 = indices[i];
        const i1 = indices[i + 1];
        const i2 = indices[i + 2];
        const v0x = flattened[i0 * 2];
        const v0y = flattened[i0 * 2 + 1];
        const v1x = flattened[i1 * 2];
        const v1y = flattened[i1 * 2 + 1];
        const v2x = flattened[i2 * 2];
        const v2y = flattened[i2 * 2 + 1];
        const e0x = v1x - v0x;
        const e0y = v1y - v0y;
        const e1x = v2x - v0x;
        const e1y = v2y - v0y;
        const crossProduct = e0x * e1y - e0y * e1x;
        if (crossProduct > 0) {
            // Flip
            corrected.push(i0);
            corrected.push(i2);
            corrected.push(i1);
        }
        else {
            // Don't flip
            corrected.push(i0);
            corrected.push(i1);
            corrected.push(i2);
        }
    }
    return corrected;
}
/**
 * Triangulates a ring of vertex indices. Appends to the supplied array of final triangle indices.
 * @param vertexBuffer - Flattened vertex coordinate array.
 * @param ring - Ordered ring of vertex indices to triangulate.
 * @param leftmostIndex - The index of the leftmost vertex in the supplied ring.
 * @param finalIndices - Array of final triangle indices, into where the resulting triangles are appended.
 */
function scanlineTriangulateVertexRing(vertexBuffer, ring, finalIndices) {
    // Triangulate the ring
    // It is guaranteed to be convex and ordered
    if (ring.length === 0) {
        throw new Error('Subdivision vertex ring is empty.');
    }
    // Find the leftmost vertex in the ring
    let leftmostIndex = 0;
    let leftmostX = vertexBuffer[ring[0] * 2];
    for (let i = 1; i < ring.length; i++) {
        const x = vertexBuffer[ring[i] * 2];
        if (x < leftmostX) {
            leftmostX = x;
            leftmostIndex = i;
        }
    }
    // Traverse the ring in both directions from the leftmost vertex
    // Assume ring is in CCW order (to produce CCW triangles)
    const ringVertexLength = ring.length;
    let lastEdgeA = leftmostIndex;
    let lastEdgeB = (lastEdgeA + 1) % ringVertexLength;
    while (true) {
        const candidateIndexA = (lastEdgeA - 1) >= 0 ? (lastEdgeA - 1) : (ringVertexLength - 1);
        const candidateIndexB = (lastEdgeB + 1) % ringVertexLength;
        // Pick candidate, move edge
        const candidateAx = vertexBuffer[ring[candidateIndexA] * 2];
        const candidateAy = vertexBuffer[ring[candidateIndexA] * 2 + 1];
        const candidateBx = vertexBuffer[ring[candidateIndexB] * 2];
        const candidateBy = vertexBuffer[ring[candidateIndexB] * 2 + 1];
        const lastEdgeAx = vertexBuffer[ring[lastEdgeA] * 2];
        const lastEdgeAy = vertexBuffer[ring[lastEdgeA] * 2 + 1];
        const lastEdgeBx = vertexBuffer[ring[lastEdgeB] * 2];
        const lastEdgeBy = vertexBuffer[ring[lastEdgeB] * 2 + 1];
        let pickA = false;
        if (candidateAx < candidateBx) {
            pickA = true;
        }
        else if (candidateAx > candidateBx) {
            pickA = false;
        }
        else {
            // Pick the candidate that is more "right" of the last edge's line
            const nx = lastEdgeBy - lastEdgeAy;
            const ny = -(lastEdgeBx - lastEdgeAx);
            const sign = (lastEdgeAy < lastEdgeBy) ? 1 : -1;
            // dot( (candidateA <-- lastEdgeA), normal )
            const aRight = ((candidateAx - lastEdgeAx) * nx + (candidateAy - lastEdgeAy) * ny) * sign;
            // dot( (candidateB <-- lastEdgeA), normal )
            const bRight = ((candidateBx - lastEdgeAx) * nx + (candidateBy - lastEdgeAy) * ny) * sign;
            if (aRight > bRight) {
                pickA = true;
            }
        }
        if (pickA) {
            // Pick candidate A
            const c = ring[candidateIndexA];
            const a = ring[lastEdgeA];
            const b = ring[lastEdgeB];
            if (c !== a && c !== b && a !== b) {
                finalIndices.push(b, a, c);
            }
            lastEdgeA--;
            if (lastEdgeA < 0) {
                lastEdgeA = ringVertexLength - 1;
            }
        }
        else {
            // Pick candidate B
            const c = ring[candidateIndexB];
            const a = ring[lastEdgeA];
            const b = ring[lastEdgeB];
            if (c !== a && c !== b && a !== b) {
                finalIndices.push(b, a, c);
            }
            lastEdgeB++;
            if (lastEdgeB >= ringVertexLength) {
                lastEdgeB = 0;
            }
        }
        if (candidateIndexA === candidateIndexB) {
            break; // We ran out of ring vertices
        }
    }
}

/**
 * This function will take any "mesh" and fill in into vertex buffers, breaking it up into multiple drawcalls as needed
 * if too many (\>65535) vertices are used.
 * This function is mainly intended for use with subdivided geometry, since sometimes subdivision might generate
 * more vertices than what fits into 16 bit indices.
 *
 * Accepts a triangle mesh, optionally with a line list (for fill outlines) as well. The triangle and line segments are expected to share a single vertex buffer.
 *
 * Mutates the provided `segmentsTriangles` and `segmentsLines` SegmentVectors,
 * `vertexArray`, `triangleIndexArray` and optionally `lineIndexArray`.
 * Does not mutate the input `flattened` vertices, `triangleIndices` and `lineList`.
 * @param addVertex - A function for adding a new vertex into `vertexArray`. We might sometimes want to add more values per vertex than just X and Y coordinates, which can be handled in this function.
 * @param segmentsTriangles - The segment array for triangle draw calls. New segments will be placed here.
 * @param vertexArray - The vertex array into which new vertices are placed by the provided `addVertex` function.
 * @param triangleIndexArray - Index array for drawing triangles. New triangle indices are placed here.
 * @param flattened - The input flattened array or vertex coordinates.
 * @param triangleIndices - Triangle indices into `flattened`.
 * @param segmentsLines - Segment array for line draw calls. New segments will be placed here. Only needed if the mesh also contains lines.
 * @param lineIndexArray - Index array for drawing lines. New triangle indices are placed here. Only needed if the mesh also contains lines.
 * @param lineList - Line indices into `flattened`. Only needed if the mesh also contains lines.
 */
function fillLargeMeshArrays(addVertex, segmentsTriangles, vertexArray, triangleIndexArray, flattened, triangleIndices, segmentsLines, lineIndexArray, lineList) {
    const numVertices = flattened.length / 2;
    const hasLines = segmentsLines && lineIndexArray && lineList;
    if (numVertices < SegmentVector.MAX_VERTEX_ARRAY_LENGTH) {
        // The fast path - no segmentation needed
        const triangleSegment = segmentsTriangles.prepareSegment(numVertices, vertexArray, triangleIndexArray);
        const triangleIndex = triangleSegment.vertexLength;
        for (let i = 0; i < triangleIndices.length; i += 3) {
            triangleIndexArray.emplaceBack(triangleIndex + triangleIndices[i], triangleIndex + triangleIndices[i + 1], triangleIndex + triangleIndices[i + 2]);
        }
        triangleSegment.vertexLength += numVertices;
        triangleSegment.primitiveLength += triangleIndices.length / 3;
        let lineIndicesStart;
        let lineSegment;
        if (hasLines) {
            // Note that segment creation must happen *before* we add vertices into the vertex buffer
            lineSegment = segmentsLines.prepareSegment(numVertices, vertexArray, lineIndexArray);
            lineIndicesStart = lineSegment.vertexLength;
            lineSegment.vertexLength += numVertices;
        }
        // Add vertices into vertex buffer
        for (let i = 0; i < flattened.length; i += 2) {
            addVertex(flattened[i], flattened[i + 1]);
        }
        if (hasLines) {
            for (const lineIndices of lineList) {
                for (let i = 1; i < lineIndices.length; i += 2) {
                    lineIndexArray.emplaceBack(lineIndicesStart + lineIndices[i - 1], lineIndicesStart + lineIndices[i]);
                }
                lineSegment.primitiveLength += lineIndices.length / 2;
            }
        }
    }
    else {
        // Assumption: the incoming triangle indices use vertices in roughly linear order,
        // for example a grid of quads where both vertices and quads are created row by row would satisfy this.
        // Some completely random arbitrary vertex/triangle order would not.
        // Thus, if we encounter a vertex that doesn't fit into MAX_VERTEX_ARRAY_LENGTH,
        // we can just stop appending into the old segment and start a new segment and only append to the new segment,
        // copying vertices that are already present in the old segment into the new segment if needed,
        // because there will not be too many of such vertices.
        // Normally, (out)lines share the same vertex buffer as triangles, but since we need to somehow split it into several drawcalls,
        // it is easier to just consider (out)lines separately and duplicate their vertices.
        fillSegmentsTriangles(segmentsTriangles, vertexArray, triangleIndexArray, flattened, triangleIndices, addVertex);
        if (hasLines) {
            fillSegmentsLines(segmentsLines, vertexArray, lineIndexArray, flattened, lineList, addVertex);
        }
        // Triangles and lines share the same vertex buffer, and they usually also share the same vertices.
        // But this method might create the vertices for triangles and for lines separately, and thus increasing the vertex count
        // of the triangle and line segments by different amounts.
        // The non-splitting fillLargeMeshArrays logic (and old fill-bucket logic) assumes the vertex counts to be the same,
        // and forcing both SegmentVectors to return a new segment upon next prepare call satisfies this.
        segmentsTriangles.forceNewSegmentOnNextPrepare();
        segmentsLines === null || segmentsLines === void 0 ? void 0 : segmentsLines.forceNewSegmentOnNextPrepare();
    }
}
/**
 * Determines the new index of a vertex given by its old index.
 * @param actualVertexIndices - Array that maps the old index of a given vertex to a new index in the final vertex buffer.
 * @param flattened - Old vertex buffer.
 * @param addVertex - Function for creating a new vertex in the final vertex buffer.
 * @param totalVerticesCreated - Reference to an int holding how many vertices were added to the final vertex buffer.
 * @param oldIndex - The old index of the desired vertex.
 * @param needsCopy - Whether to duplicate the desired vertex in the final vertex buffer.
 * @param segment - The current segment.
 * @returns Index of the vertex in the final vertex array.
 */
function copyOrReuseVertex(actualVertexIndices, flattened, addVertex, totalVerticesCreated, oldIndex, needsCopy, segment) {
    if (needsCopy) {
        const newIndex = totalVerticesCreated.count;
        addVertex(flattened[oldIndex * 2], flattened[oldIndex * 2 + 1]);
        actualVertexIndices[oldIndex] = totalVerticesCreated.count;
        totalVerticesCreated.count++;
        segment.vertexLength++;
        return newIndex;
    }
    else {
        return actualVertexIndices[oldIndex];
    }
}
function fillSegmentsTriangles(segmentsTriangles, vertexArray, triangleIndexArray, flattened, triangleIndices, addVertex) {
    // Array, or rather a map of [vertex index in the original data] -> index of the latest copy of this vertex in the final vertex buffer.
    const actualVertexIndices = [];
    for (let i = 0; i < flattened.length / 2; i++) {
        actualVertexIndices.push(-1);
    }
    const totalVerticesCreated = { count: 0 };
    let currentSegmentCutoff = 0;
    let segment = segmentsTriangles.getOrCreateLatestSegment(vertexArray, triangleIndexArray);
    let baseVertex = segment.vertexLength;
    for (let primitiveEndIndex = 2; primitiveEndIndex < triangleIndices.length; primitiveEndIndex += 3) {
        const i0 = triangleIndices[primitiveEndIndex - 2];
        const i1 = triangleIndices[primitiveEndIndex - 1];
        const i2 = triangleIndices[primitiveEndIndex];
        let i0needsVertexCopy = actualVertexIndices[i0] < currentSegmentCutoff;
        let i1needsVertexCopy = actualVertexIndices[i1] < currentSegmentCutoff;
        let i2needsVertexCopy = actualVertexIndices[i2] < currentSegmentCutoff;
        const vertexCopyCount = (i0needsVertexCopy ? 1 : 0) + (i1needsVertexCopy ? 1 : 0) + (i2needsVertexCopy ? 1 : 0);
        // Will needed vertex copies fit into this segment?
        if (segment.vertexLength + vertexCopyCount > SegmentVector.MAX_VERTEX_ARRAY_LENGTH) {
            // Break up into a new segment if not.
            segment = segmentsTriangles.createNewSegment(vertexArray, triangleIndexArray);
            currentSegmentCutoff = totalVerticesCreated.count;
            i0needsVertexCopy = true;
            i1needsVertexCopy = true;
            i2needsVertexCopy = true;
            baseVertex = 0;
        }
        const actualIndex0 = copyOrReuseVertex(actualVertexIndices, flattened, addVertex, totalVerticesCreated, i0, i0needsVertexCopy, segment);
        const actualIndex1 = copyOrReuseVertex(actualVertexIndices, flattened, addVertex, totalVerticesCreated, i1, i1needsVertexCopy, segment);
        const actualIndex2 = copyOrReuseVertex(actualVertexIndices, flattened, addVertex, totalVerticesCreated, i2, i2needsVertexCopy, segment);
        triangleIndexArray.emplaceBack(baseVertex + actualIndex0 - currentSegmentCutoff, baseVertex + actualIndex1 - currentSegmentCutoff, baseVertex + actualIndex2 - currentSegmentCutoff);
        segment.primitiveLength++;
    }
}
function fillSegmentsLines(segmentsLines, vertexArray, lineIndexArray, flattened, lineList, addVertex) {
    // Array, or rather a map of [vertex index in the original data] -> index of the latest copy of this vertex in the final vertex buffer.
    const actualVertexIndices = [];
    for (let i = 0; i < flattened.length / 2; i++) {
        actualVertexIndices.push(-1);
    }
    const totalVerticesCreated = { count: 0 };
    let currentSegmentCutoff = 0;
    let segment = segmentsLines.getOrCreateLatestSegment(vertexArray, lineIndexArray);
    let baseVertex = segment.vertexLength;
    for (const currentLine of lineList) {
        for (let lineVertex = 1; lineVertex < currentLine.length; lineVertex += 2) {
            const i0 = currentLine[lineVertex - 1];
            const i1 = currentLine[lineVertex];
            let i0needsVertexCopy = actualVertexIndices[i0] < currentSegmentCutoff;
            let i1needsVertexCopy = actualVertexIndices[i1] < currentSegmentCutoff;
            const vertexCopyCount = (i0needsVertexCopy ? 1 : 0) + (i1needsVertexCopy ? 1 : 0);
            // Will needed vertex copies fit into this segment?
            if (segment.vertexLength + vertexCopyCount > SegmentVector.MAX_VERTEX_ARRAY_LENGTH) {
                // Break up into a new segment if not.
                segment = segmentsLines.createNewSegment(vertexArray, lineIndexArray);
                currentSegmentCutoff = totalVerticesCreated.count;
                i0needsVertexCopy = true;
                i1needsVertexCopy = true;
                baseVertex = 0;
            }
            const actualIndex0 = copyOrReuseVertex(actualVertexIndices, flattened, addVertex, totalVerticesCreated, i0, i0needsVertexCopy, segment);
            const actualIndex1 = copyOrReuseVertex(actualVertexIndices, flattened, addVertex, totalVerticesCreated, i1, i1needsVertexCopy, segment);
            lineIndexArray.emplaceBack(baseVertex + actualIndex0 - currentSegmentCutoff, baseVertex + actualIndex1 - currentSegmentCutoff);
            segment.primitiveLength++;
        }
    }
}

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.hasDependencies = 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.hasDependencies = 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.hasDependencies) {
                const patternFeature = addPatternDependencies('fill', this.layers, bucketFeature, { zoom: 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, {}, options.subdivisionGranularity);
            }
            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, options.subdivisionGranularity);
        }
    }
    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, subdivisionGranularity) {
        for (const polygon of classifyRings$1(geometry, EARCUT_MAX_RINGS$1)) {
            const subdivided = subdividePolygon(polygon, canonical, subdivisionGranularity.fill.getGranularityForZoomLevel(canonical.z));
            const vertexArray = this.layoutVertexArray;
            fillLargeMeshArrays((x, y) => {
                vertexArray.emplaceBack(x, y);
            }, this.segments, this.layoutVertexArray, this.indexArray, subdivided.verticesFlattened, subdivided.indicesTriangles, this.segments2, this.indexArray2, subdivided.indicesLineList);
        }
        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$4;
const getPaint$4 = () => paint$4 = paint$4 || 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$4 = ({ get paint() { return getPaint$4(); }, get layout() { return getLayout$2(); } });

const isFillStyleLayer = (layer) => layer.type === 'fill';
class FillStyleLayer extends StyleLayer {
    constructor(layer, globalState) {
        super(layer, properties$4, globalState);
    }
    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, geometry, transform, pixelsToTileUnits }) {
        const translatedPolygon = translate(queryGeometry, this.paint.get('fill-translate'), this.paint.get('fill-translate-anchor'), -transform.bearingInRadians, 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;

/** @import Pbf from 'pbf' */
/** @import {Feature} from 'geojson' */

class VectorTileFeature {
    /**
     * @param {Pbf} pbf
     * @param {number} end
     * @param {number} extent
     * @param {string[]} keys
     * @param {(number | string | boolean)[]} values
     */
    constructor(pbf, end, extent, keys, values) {
        // Public

        /** @type {Record<string, number | string | boolean>} */
        this.properties = {};

        this.extent = extent;
        /** @type {0 | 1 | 2 | 3} */
        this.type = 0;

        /** @type {number | undefined} */
        this.id = undefined;

        /** @private */
        this._pbf = pbf;
        /** @private */
        this._geometry = -1;
        /** @private */
        this._keys = keys;
        /** @private */
        this._values = values;

        pbf.readFields(readFeature, this, end);
    }

    loadGeometry() {
        const pbf = this._pbf;
        pbf.pos = this._geometry;

        const end = pbf.readVarint() + pbf.pos;

        /** @type Point[][] */
        const lines = [];

        /** @type Point[] | undefined */
        let line;

        let cmd = 1;
        let length = 0;
        let x = 0;
        let y = 0;

        while (pbf.pos < end) {
            if (length <= 0) {
                const 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 = [];
                }

                if (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;
    }

    bbox() {
        const pbf = this._pbf;
        pbf.pos = this._geometry;

        const end = pbf.readVarint() + pbf.pos;
        let cmd = 1,
            length = 0,
            x = 0,
            y = 0,
            x1 = Infinity,
            x2 = -Infinity,
            y1 = Infinity,
            y2 = -Infinity;

        while (pbf.pos < end) {
            if (length <= 0) {
                const 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];
    }

    /**
     * @param {number} x
     * @param {number} y
     * @param {number} z
     * @return {Feature}
     */
    toGeoJSON(x, y, z) {
        const size = this.extent * Math.pow(2, z),
            x0 = this.extent * x,
            y0 = this.extent * y,
            vtCoords = this.loadGeometry();

        /** @param {Point} p */
        function projectPoint(p) {
            return [
                (p.x + x0) * 360 / size - 180,
                360 / Math.PI * Math.atan(Math.exp((1 - (p.y + y0) * 2 / size) * Math.PI)) - 90
            ];
        }

        /** @param {Point[]} line */
        function projectLine(line) {
            return line.map(projectPoint);
        }

        /** @type {Feature["geometry"]} */
        let geometry;

        if (this.type === 1) {
            const points = [];
            for (const line of vtCoords) {
                points.push(line[0]);
            }
            const coordinates = projectLine(points);
            geometry = points.length === 1 ?
                {type: 'Point', coordinates: coordinates[0]} :
                {type: 'MultiPoint', coordinates};

        } else if (this.type === 2) {

            const coordinates = vtCoords.map(projectLine);
            geometry = coordinates.length === 1 ?
                {type: 'LineString', coordinates: coordinates[0]} :
                {type: 'MultiLineString', coordinates};

        } else if (this.type === 3) {
            const polygons = classifyRings(vtCoords);
            const coordinates = [];
            for (const polygon of polygons) {
                coordinates.push(polygon.map(projectLine));
            }
            geometry = coordinates.length === 1 ?
                {type: 'Polygon', coordinates: coordinates[0]} :
                {type: 'MultiPolygon', coordinates};
        } else {

            throw new Error('unknown feature type');
        }

        /** @type {Feature} */
        const result = {
            type: 'Feature',
            geometry,
            properties: this.properties
        };

        if (this.id != null) {
            result.id = this.id;
        }

        return result;
    }
}

/** @type {['Unknown', 'Point', 'LineString', 'Polygon']} */
VectorTileFeature.types = ['Unknown', 'Point', 'LineString', 'Polygon'];

/**
 * @param {number} tag
 * @param {VectorTileFeature} feature
 * @param {Pbf} pbf
 */
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 = /** @type {0 | 1 | 2 | 3} */ (pbf.readVarint());
    // @ts-expect-error TS2341 deliberately accessing a private property
    else if (tag === 4) feature._geometry = pbf.pos;
}

/**
 * @param {Pbf} pbf
 * @param {VectorTileFeature} feature
 */
function readTag(pbf, feature) {
    const end = pbf.readVarint() + pbf.pos;

    while (pbf.pos < end) {
        // @ts-expect-error TS2341 deliberately accessing a private property
        const key = feature._keys[pbf.readVarint()];
        // @ts-expect-error TS2341 deliberately accessing a private property
        const value = feature._values[pbf.readVarint()];
        feature.properties[key] = value;
    }
}

/** classifies an array of rings into polygons with outer rings and holes
 * @param {Point[][]} rings
 */
function classifyRings(rings) {
    const len = rings.length;

    if (len <= 1) return [rings];

    const polygons = [];
    let polygon, ccw;

    for (let i = 0; i < len; i++) {
        const 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 if (polygon) {
            polygon.push(rings[i]);
        }
    }
    if (polygon) polygons.push(polygon);

    return polygons;
}

/** @param {Point[]} ring */
function signedArea(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;
}

class VectorTileLayer {
    /**
     * @param {Pbf} pbf
     * @param {number} [end]
     */
    constructor(pbf, end) {
        // Public
        this.version = 1;
        this.name = '';
        this.extent = 4096;
        this.length = 0;

        /** @private */
        this._pbf = pbf;

        /** @private
         * @type {string[]} */
        this._keys = [];

        /** @private
         * @type {(number | string | boolean)[]} */
        this._values = [];

        /** @private
         * @type {number[]} */
        this._features = [];

        pbf.readFields(readLayer, this, end);

        this.length = this._features.length;
    }

    /** return feature `i` from this layer as a `VectorTileFeature`
     * @param {number} i
     */
    feature(i) {
        if (i < 0 || i >= this._features.length) throw new Error('feature index out of bounds');

        this._pbf.pos = this._features[i];

        const end = this._pbf.readVarint() + this._pbf.pos;
        return new VectorTileFeature(this._pbf, end, this.extent, this._keys, this._values);
    }
}

/**
 * @param {number} tag
 * @param {VectorTileLayer} layer
 * @param {Pbf} pbf
 */
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();
    // @ts-expect-error TS2341 deliberately accessing a private property
    else if (tag === 2) layer._features.push(pbf.pos);
    // @ts-expect-error TS2341 deliberately accessing a private property
    else if (tag === 3) layer._keys.push(pbf.readString());
    // @ts-expect-error TS2341 deliberately accessing a private property
    else if (tag === 4) layer._values.push(readValueMessage(pbf));
}

/**
 * @param {Pbf} pbf
 */
function readValueMessage(pbf) {
    let value = null;
    const end = pbf.readVarint() + pbf.pos;

    while (pbf.pos < end) {
        const 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;
    }
    if (value == null) {
        throw new Error('unknown feature value');
    }

    return value;
}

class VectorTile {
    /**
     * @param {Pbf} pbf
     * @param {number} [end]
     */
    constructor(pbf, end) {
        /** @type {Record<string, VectorTileLayer>} */
        this.layers = pbf.readFields(readTile, {}, end);
    }
}

/**
 * @param {number} tag
 * @param {Record<string, VectorTileLayer>} layers
 * @param {Pbf} pbf
 */
function readTile(tag, layers, pbf) {
    if (tag === 3) {
        const layer = new VectorTileLayer(pbf, pbf.readVarint() + pbf.pos);
        if (layer.length) layers[layer.name] = layer;
    }
}

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.hasDependencies = 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.hasDependencies = 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.hasDependencies) {
                this.features.push(addPatternDependencies('fill-extrusion', this.layers, bucketFeature, { zoom: this.zoom }, options));
            }
            else {
                this.addFeature(bucketFeature, bucketFeature.geometry, index, canonical, {}, options.subdivisionGranularity);
            }
            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, options.subdivisionGranularity);
        }
    }
    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, subdivisionGranularity) {
        for (const polygon of classifyRings$1(geometry, EARCUT_MAX_RINGS)) {
            // Compute polygon centroid to calculate elevation in GPU
            const centroid = { x: 0, y: 0, sampleCount: 0 };
            const oldVertexCount = this.layoutVertexArray.length;
            this.processPolygon(centroid, canonical, feature, polygon, subdivisionGranularity);
            const addedVertices = this.layoutVertexArray.length - oldVertexCount;
            const centroidX = Math.floor(centroid.x / centroid.sampleCount);
            const centroidY = Math.floor(centroid.y / centroid.sampleCount);
            for (let i = 0; i < addedVertices; i++) {
                this.centroidVertexArray.emplaceBack(centroidX, centroidY);
            }
        }
        this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, { imagePositions, canonical });
    }
    processPolygon(centroid, canonical, feature, polygon, subdivisionGranularity) {
        if (polygon.length < 1) {
            return;
        }
        if (isEntirelyOutside(polygon[0])) {
            return;
        }
        // Only consider the un-subdivided polygon outer ring for centroid calculation
        for (const ring of polygon) {
            if (ring.length === 0) {
                continue;
            }
            // Here we don't mind if a hole ring is entirely outside, unlike when generating geometry later.
            accumulatePointsToCentroid(centroid, ring);
        }
        const segmentReference = {
            segment: this.segments.prepareSegment(4, this.layoutVertexArray, this.indexArray)
        };
        const granularity = subdivisionGranularity.fill.getGranularityForZoomLevel(canonical.z);
        const isPolygon = VectorTileFeature.types[feature.type] === 'Polygon';
        for (const ring of polygon) {
            if (ring.length === 0) {
                continue;
            }
            if (isEntirelyOutside(ring)) {
                continue;
            }
            const subdividedRing = subdivideVertexLine(ring, granularity, isPolygon);
            this._generateSideFaces(subdividedRing, segmentReference);
        }
        // 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 (!isPolygon)
            return;
        // Do not generate outlines, since outlines already got subdivided earlier.
        const subdividedPolygon = subdividePolygon(polygon, canonical, granularity, false);
        const vertexArray = this.layoutVertexArray;
        fillLargeMeshArrays((x, y) => {
            addVertex$1(vertexArray, x, y, 0, 0, 1, 1, 0);
        }, this.segments, this.layoutVertexArray, this.indexArray, subdividedPolygon.verticesFlattened, subdividedPolygon.indicesTriangles);
    }
    /**
     * Generates side faces for the supplied geometry. Assumes `geometry` to be a line string, like the output of {@link subdivideVertexLine}.
     * For rings, it is assumed that the first and last vertex of `geometry` are equal.
     */
    _generateSideFaces(geometry, segmentReference) {
        let edgeDistance = 0;
        for (let p = 1; p < geometry.length; p++) {
            const p1 = geometry[p];
            const p2 = geometry[p - 1];
            if (isBoundaryEdge(p1, p2)) {
                continue;
            }
            if (segmentReference.segment.vertexLength + 4 > SegmentVector.MAX_VERTEX_ARRAY_LENGTH) {
                segmentReference.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);
            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);
            const bottomRight = segmentReference.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);
            segmentReference.segment.vertexLength += 4;
            segmentReference.segment.primitiveLength += 2;
        }
    }
}
/**
 * Accumulates geometry to centroid. Geometry can be either a polygon ring, a line string or a closed line string.
 * In case of a polygon ring or line ring, the last vertex is ignored if it is the same as the first vertex.
 */
function accumulatePointsToCentroid(centroid, geometry) {
    for (let i = 0; i < geometry.length; i++) {
        const p = geometry[i];
        if (i === geometry.length - 1 && geometry[0].x === p.x && geometry[0].y === p.y) {
            continue;
        }
        centroid.x += p.x;
        centroid.y += p.y;
        centroid.sampleCount++;
    }
}
register('FillExtrusionBucket', FillExtrusionBucket, { omit: ['layers', 'features'] });
function isBoundaryEdge(p1, p2) {
    return (p1.x === p2.x && (p1.x < 0 || p1.x > EXTENT$1)) ||
        (p1.y === p2.y && (p1.y < 0 || p1.y > EXTENT$1));
}
function isEntirelyOutside(ring) {
    return ring.every(p => p.x < 0) ||
        ring.every(p => p.x > EXTENT$1) ||
        ring.every(p => p.y < 0) ||
        ring.every(p => p.y > EXTENT$1);
}

// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'.
/* eslint-disable */
let paint$3;
const getPaint$3 = () => paint$3 = paint$3 || 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$3 = ({ get paint() { return getPaint$3(); } });

class Point3D extends Point {
}
const isFillExtrusionStyleLayer = (layer) => layer.type === 'fill-extrusion';
class FillExtrusionStyleLayer extends StyleLayer {
    constructor(layer, globalState) {
        super(layer, properties$3, globalState);
    }
    createBucket(parameters) {
        return new FillExtrusionBucket(parameters);
    }
    queryRadius() {
        return translateDistance(this.paint.get('fill-extrusion-translate'));
    }
    is3D() {
        return true;
    }
    queryIntersectsFeature({ queryGeometry, feature, featureState, geometry, transform, pixelsToTileUnits, pixelPosMatrix }) {
        const translatedPolygon = translate(queryGeometry, this.paint.get('fill-extrusion-translate'), this.paint.get('fill-extrusion-translate-anchor'), -transform.bearingInRadians, 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, 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(baseX / baseW, baseY / baseW);
            b.z = baseZ / baseW;
            ringBase.push(b);
            const t = new Point(topX / topW, topY / topW);
            t.z = topZ / topW;
            ringTop.push(t);
        }
        projectedBase.push(ringBase);
        projectedTop.push(ringTop);
    }
    return [projectedBase, projectedTop];
}
function projectQueryGeometry(queryGeometry, pixelPosMatrix, 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(v[0] / v[3], v[1] / v[3]));
    }
    return projectedQueryGeometry;
}

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<TypedArrayConstructor>} 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<TypedArrayConstructor>} 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<TypedArrayConstructor>} 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<TypedArrayConstructor>} 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;
}

/**
 * calculate simplification data using optimized Douglas-Peucker algorithm
 * @param coords - flat array of coordinates
 * @param first - index of the first coordinate in the segment
 * @param last - index of the last coordinate in the segment
 * @param sqTolerance - square tolerance value
 */
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;
            continue;
        }
        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);
    }
}
/**
 * Claculates the square distance from a point to a segment
 * @param px - x coordinate of the point
 * @param py - y coordinate of the point
 * @param x - x coordinate of the first segment endpoint
 * @param y - y coordinate of the first segment endpoint
 * @param bx - x coordinate of the second segment endpoint
 * @param by - y coordinate of the second segment endpoint
 * @returns 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;
}

/**
 *
 * @param id - the feature's ID
 * @param type - the feature's type
 * @param geom - the feature's geometry
 * @param tags - the feature's properties
 * @returns the created feature
 */
function createFeature(id, type, geom, tags) {
    // This is mostly for TypeScript type narrowing
    const data = { type, geom };
    const feature = {
        id: id == null ? null : id,
        type: data.type,
        geometry: data.geom,
        tags,
        minX: Infinity,
        minY: Infinity,
        maxX: -Infinity,
        maxY: -Infinity
    };
    switch (data.type) {
        case 'Point':
        case 'MultiPoint':
            calcLineBBox(feature, data.geom);
            break;
        case 'LineString':
            calcLineBBox(feature, data.geom.points);
            break;
        case 'Polygon':
            // the outer ring (ie [0]) contains all inner rings
            calcLineBBox(feature, data.geom[0].points);
            break;
        case 'MultiLineString':
            for (const line of data.geom) {
                calcLineBBox(feature, line.points);
            }
            break;
        case 'MultiPolygon':
            for (const polygon of data.geom) {
                // the outer ring (ie [0]) contains all inner rings
                calcLineBBox(feature, polygon[0].points);
            }
            break;
    }
    return feature;
}
function optimizeLineMemory(line) {
    const lineImmutable = line;
    if (line.points.length > 64) {
        lineImmutable.points = new Float64Array(line.points);
    }
}
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 to internal source features (an intermediate projected JSON vector format with simplification data)
 * @param data
 * @param options
 * @returns
 */
function convertToInternal(data, options) {
    const features = [];
    switch (data.type) {
        case 'FeatureCollection':
            for (let i = 0; i < data.features.length; i++) {
                featureToInternal(features, data.features[i], options, i);
            }
            break;
        case 'Feature':
            featureToInternal(features, data, options);
            break;
        default:
            featureToInternal(features, { geometry: data, properties: undefined }, options);
    }
    return features;
}
function featureToInternal(features, geojson, options, index) {
    if (!geojson.geometry)
        return;
    if (geojson.geometry.type === 'GeometryCollection') {
        convertGeometryCollection(features, geojson, geojson.geometry, options, index);
        return;
    }
    const coords = geojson.geometry.coordinates;
    if (!coords?.length)
        return;
    const id = getFeatureId(geojson, options, index);
    const tolerance = Math.pow(options.tolerance / ((1 << options.maxZoom) * options.extent), 2);
    switch (geojson.geometry.type) {
        case 'Point':
            convertPointFeature(features, id, geojson.geometry, geojson.properties);
            return;
        case 'MultiPoint':
            convertMultiPointFeature(features, id, geojson.geometry, geojson.properties);
            return;
        case 'LineString':
            convertLineStringFeature(features, id, geojson.geometry, tolerance, geojson.properties);
            return;
        case 'MultiLineString':
            convertMultiLineStringFeature(features, id, geojson.geometry, tolerance, options, geojson.properties);
            return;
        case 'Polygon':
            convertPolygonFeature(features, id, geojson.geometry, tolerance, geojson.properties);
            return;
        case 'MultiPolygon':
            convertMultiPolygonFeature(features, id, geojson.geometry, tolerance, geojson.properties);
            return;
        default:
            throw new Error('Input data is not a valid GeoJSON object.');
    }
}
function getFeatureId(geojson, options, index) {
    if (options.promoteId) {
        return geojson.properties?.[options.promoteId];
    }
    if (options.generateId) {
        return index || 0;
    }
    return geojson.id;
}
function convertGeometryCollection(features, geojson, geometry, options, index) {
    for (const geom of geometry.geometries) {
        featureToInternal(features, {
            id: geojson.id,
            geometry: geom,
            properties: geojson.properties
        }, options, index);
    }
}
function convertPointFeature(features, id, geom, properties) {
    const out = [];
    out.push(projectX(geom.coordinates[0]), projectY(geom.coordinates[1]), 0);
    features.push(createFeature(id, 'Point', out, properties));
}
function convertMultiPointFeature(features, id, geom, properties) {
    const out = [];
    for (const coords of geom.coordinates) {
        out.push(projectX(coords[0]), projectY(coords[1]), 0);
    }
    features.push(createFeature(id, 'MultiPoint', out, properties));
}
function convertLineStringFeature(features, id, geom, tolerance, properties) {
    const out = { points: [] };
    convertLine(geom.coordinates, out, tolerance, false);
    features.push(createFeature(id, 'LineString', out, properties));
}
function convertMultiLineStringFeature(features, id, geom, tolerance, options, properties) {
    if (options.lineMetrics) {
        // explode into linestrings to be able to track metrics
        for (const line of geom.coordinates) {
            const out = { points: [] };
            convertLine(line, out, tolerance, false);
            features.push(createFeature(id, 'LineString', out, properties));
        }
    }
    else {
        const out = [];
        convertLines(geom.coordinates, out, tolerance, false);
        features.push(createFeature(id, 'MultiLineString', out, properties));
    }
}
function convertPolygonFeature(features, id, geom, tolerance, properties) {
    const out = [];
    convertLines(geom.coordinates, out, tolerance, true);
    features.push(createFeature(id, 'Polygon', out, properties));
}
function convertMultiPolygonFeature(features, id, geom, tolerance, properties) {
    const out = [];
    for (const polygon of geom.coordinates) {
        const polygonOut = [];
        convertLines(polygon, polygonOut, tolerance, true);
        out.push(polygonOut);
    }
    features.push(createFeature(id, 'MultiPolygon', out, properties));
}
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.points.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.points.length - 3;
    out.points[2] = 1;
    if (tolerance > 0)
        simplify(out.points, 0, last, tolerance);
    out.points[last + 2] = 1;
    optimizeLineMemory(out);
    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 = { points: [] };
        convertLine(rings[i], geom, tolerance, isPolygon);
        out.push(geom);
    }
}
/**
 * Convert longitude to spherical mercator in [0..1] range
 */
function projectX(x) {
    return x / 360 + 0.5;
}
/**
 * Convert latitude to spherical mercator in [0..1] range
 */
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;
}

/**
 * Converts internal source features back to GeoJSON format.
 */
function convertToGeoJSON(source) {
    const geojson = {
        type: 'FeatureCollection',
        features: source.map(feature => featureToGeoJSON(feature))
    };
    return geojson;
}
/**
 * Converts a single internal feature to GeoJSON format.
 */
function featureToGeoJSON(feature) {
    const geojsonFeature = {
        type: 'Feature',
        geometry: geometryToGeoJSON(feature),
        properties: feature.tags
    };
    if (feature.id != null) {
        geojsonFeature.id = feature.id;
    }
    return geojsonFeature;
}
/**
 * Converts a single internal feature geometry to GeoJSON format.
 */
function geometryToGeoJSON(feature) {
    const { type, geometry } = feature;
    switch (type) {
        case 'Point':
            return {
                type: type,
                coordinates: unprojectPoint(geometry[0], geometry[1])
            };
        case 'MultiPoint':
            return {
                type: type,
                coordinates: unprojectPoints(geometry)
            };
        case 'LineString':
            return {
                type: type,
                coordinates: unprojectPoints(geometry.points)
            };
        case 'MultiLineString':
        case 'Polygon':
            return {
                type: type,
                coordinates: geometry.map(ring => unprojectPoints(ring.points))
            };
        case 'MultiPolygon':
            return {
                type: type,
                coordinates: geometry.map(polygon => polygon.map(ring => unprojectPoints(ring.points)))
            };
    }
}
function unprojectPoints(coords) {
    const result = [];
    for (let i = 0; i < coords.length; i += 3) {
        result.push(unprojectPoint(coords[i], coords[i + 1]));
    }
    return result;
}
function unprojectPoint(x, y) {
    return [unprojectX(x), unprojectY(y)];
}
/**
 * Convert spherical mercator in [0..1] range to longitude
 */
function unprojectX(x) {
    return (x - 0.5) * 360;
}
/**
 * Convert spherical mercator in [0..1] range to latitude
 */
function unprojectY(y) {
    const y2 = (180 - y * 360) * Math.PI / 180;
    return 360 * Math.atan(Math.exp(y2)) / Math.PI - 90;
}

var AxisType;
(function (AxisType) {
    AxisType[AxisType["X"] = 0] = "X";
    AxisType[AxisType["Y"] = 1] = "Y";
})(AxisType || (AxisType = {}));
/**
 * clip features between two vertical or horizontal axis-parallel lines:
 *     |        |
 *  ___|___     |     /
 * /   |   \____|____/
 *     |        |
 *
 * @param features - the features to clip
 * @param scale - the scale to divide start and end inputs
 * @param start - the start of the clip range
 * @param end - the end of the clip range
 * @param axis - which axis to clip against
 * @param minAll - the minimum for all features in the relevant axis
 * @param maxAll - the maximum for all features in the relevant axis
 */
function clip(features, scale, start, end, axis, minAll, maxAll, options) {
    start /= scale;
    end /= scale;
    if (minAll >= start && maxAll < end) { // trivial accept
        return features;
    }
    if (maxAll < start || minAll >= end) { // trivial reject
        return null;
    }
    const clipped = [];
    for (const feature of features) {
        const min = axis === AxisType.X ? feature.minX : feature.minY;
        const max = axis === AxisType.X ? feature.maxX : feature.maxY;
        if (min >= start && max < end) { // trivial accept
            clipped.push(feature);
            continue;
        }
        if (max < start || min >= end) { // trivial reject
            continue;
        }
        switch (feature.type) {
            case 'Point':
            case 'MultiPoint': {
                clipPointFeature(feature, clipped, start, end, axis);
                continue;
            }
            case 'LineString': {
                clipLineStringFeature(feature, clipped, start, end, axis, options);
                continue;
            }
            case 'MultiLineString': {
                clipMultiLineStringFeature(feature, clipped, start, end, axis);
                continue;
            }
            case 'Polygon': {
                clipPolygonFeature(feature, clipped, start, end, axis);
                continue;
            }
            case 'MultiPolygon': {
                clipMultiPolygonFeature(feature, clipped, start, end, axis);
                continue;
            }
        }
    }
    if (!clipped.length)
        return null;
    return clipped;
}
function clipPointFeature(feature, clipped, start, end, axis) {
    const geom = [];
    clipPoints$1(feature.geometry, geom, start, end, axis);
    if (!geom.length)
        return;
    const type = geom.length === 3 ? 'Point' : 'MultiPoint';
    clipped.push(createFeature(feature.id, type, geom, feature.tags));
}
function clipLineStringFeature(feature, clipped, start, end, axis, options) {
    const geom = [];
    clipLine$1(feature.geometry, geom, start, end, axis, false, options.lineMetrics);
    if (!geom.length)
        return;
    if (options.lineMetrics) {
        for (const line of geom) {
            clipped.push(createFeature(feature.id, 'LineString', line, feature.tags));
        }
        return;
    }
    if (geom.length > 1) {
        clipped.push(createFeature(feature.id, 'MultiLineString', geom, feature.tags));
        return;
    }
    clipped.push(createFeature(feature.id, 'LineString', geom[0], feature.tags));
}
function clipMultiLineStringFeature(feature, clipped, start, end, axis) {
    const geom = [];
    clipLines$1(feature.geometry, geom, start, end, axis, false);
    if (!geom.length)
        return;
    if (geom.length === 1) {
        clipped.push(createFeature(feature.id, 'LineString', geom[0], feature.tags));
        return;
    }
    clipped.push(createFeature(feature.id, 'MultiLineString', geom, feature.tags));
}
function clipPolygonFeature(feature, clipped, start, end, axis) {
    const geom = [];
    clipLines$1(feature.geometry, geom, start, end, axis, true);
    if (!geom.length)
        return;
    clipped.push(createFeature(feature.id, 'Polygon', geom, feature.tags));
}
function clipMultiPolygonFeature(feature, clipped, start, end, axis) {
    const geom = [];
    for (const polygon of feature.geometry) {
        const newPolygon = [];
        clipLines$1(polygon, newPolygon, start, end, axis, true);
        if (!newPolygon.length)
            continue;
        geom.push(newPolygon);
    }
    if (!geom.length)
        return;
    clipped.push(createFeature(feature.id, 'MultiPolygon', geom, feature.tags));
}
function clipPoints$1(geom, newGeom, start, end, axis) {
    for (let i = 0; i < geom.length; i += 3) {
        const a = geom[i + axis];
        if (a >= start && a <= end) {
            addPoint(newGeom, geom[i], geom[i + 1], geom[i + 2]);
        }
    }
}
function clipLine$1(geom, newGeom, start, end, axis, isPolygon, trackMetrics) {
    let slice = newSlice(geom);
    const intersect = axis === AxisType.X ? intersectX : intersectY;
    let len = geom.start;
    let segLen, t;
    for (let i = 0; i < geom.points.length - 3; i += 3) {
        const ax = geom.points[i];
        const ay = geom.points[i + 1];
        const az = geom.points[i + 2];
        const bx = geom.points[i + 3];
        const by = geom.points[i + 4];
        const a = axis === AxisType.X ? ax : ay;
        const b = axis === AxisType.X ? bx : by;
        let exited = false;
        if (trackMetrics)
            segLen = Math.sqrt(Math.pow(ax - bx, 2) + Math.pow(ay - by, 2));
        if (a < start) {
            // ---|-->  | (line enters the clip region from the left)
            if (b > start) {
                t = intersect(slice, ax, ay, bx, by, start);
                if (trackMetrics)
                    slice.start = len + segLen * t;
            }
        }
        else if (a > end) {
            // |  <--|--- (line enters the clip region from the right)
            if (b < end) {
                t = intersect(slice, ax, ay, bx, by, end);
                if (trackMetrics)
                    slice.start = len + segLen * t;
            }
        }
        else {
            addPoint(slice.points, ax, ay, az);
        }
        if (b < start && a >= start) {
            // <--|---  | or <--|-----|--- (line exits the clip region on the left)
            t = intersect(slice, ax, ay, bx, by, start);
            exited = true;
        }
        if (b > end && a <= end) {
            // |  ---|--> or ---|-----|--> (line exits the clip region on the right)
            t = intersect(slice, ax, ay, bx, by, end);
            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.points.length - 3;
    const ax = geom.points[last];
    const ay = geom.points[last + 1];
    const az = geom.points[last + 2];
    const a = axis === AxisType.X ? ax : ay;
    if (a >= start && a <= end)
        addPoint(slice.points, ax, ay, az);
    // close the polygon if its endpoints are not the same after clipping
    last = slice.points.length - 3;
    if (isPolygon && last >= 3 && (slice.points[last] !== slice.points[0] || slice.points[last + 1] !== slice.points[1])) {
        addPoint(slice.points, slice.points[0], slice.points[1], slice.points[2]);
    }
    // add the final slice
    if (slice.points.length) {
        optimizeLineMemory(slice);
        newGeom.push(slice);
    }
}
function newSlice(line) {
    return {
        points: [],
        size: line.size,
        start: line.start,
        end: line.end
    };
}
function clipLines$1(geom, newGeom, start, end, axis, isPolygon) {
    for (const line of geom) {
        clipLine$1(line, newGeom, start, end, 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.points, x, ay + (by - ay) * t, 1);
    return t;
}
function intersectY(out, ax, ay, bx, by, y) {
    const t = (y - ay) / (by - ay);
    addPoint(out.points, 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, AxisType.X, -1, 2, options); // left world copy
    const right = clip(features, 1, 1 - buffer, 2 + buffer, AxisType.X, -1, 2, options); // right world copy
    if (!left && !right)
        return merged;
    merged = clip(features, 1, -buffer, 1 + buffer, AxisType.X, -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 (const feature of features) {
        switch (feature.type) {
            case 'Point':
            case 'MultiPoint': {
                const newGeometry = shiftPointCoords(feature.geometry, offset);
                newFeatures.push(createFeature(feature.id, feature.type, newGeometry, feature.tags));
                continue;
            }
            case 'LineString': {
                const newGeometry = shiftLineCoords(feature.geometry, offset);
                newFeatures.push(createFeature(feature.id, feature.type, newGeometry, feature.tags));
                continue;
            }
            case 'MultiLineString':
            case 'Polygon': {
                const newGeometry = [];
                for (const line of feature.geometry) {
                    newGeometry.push(shiftLineCoords(line, offset));
                }
                newFeatures.push(createFeature(feature.id, feature.type, newGeometry, feature.tags));
                continue;
            }
            case 'MultiPolygon': {
                const newGeometry = [];
                for (const polygon of feature.geometry) {
                    const newPolygon = [];
                    for (const line of polygon) {
                        newPolygon.push(shiftLineCoords(line, offset));
                    }
                    newGeometry.push(newPolygon);
                }
                newFeatures.push(createFeature(feature.id, feature.type, newGeometry, feature.tags));
                continue;
            }
        }
    }
    return newFeatures;
}
function shiftPointCoords(coords, offset) {
    const newCoords = [];
    for (let i = 0; i < coords.length; i += 3) {
        newCoords.push(coords[i] + offset, coords[i + 1], coords[i + 2]);
    }
    return newCoords;
}
function shiftLineCoords(line, offset) {
    const newLine = {
        points: [],
        size: line.size
    };
    if (line.start !== undefined) {
        newLine.start = line.start;
        newLine.end = line.end;
    }
    for (let i = 0; i < line.points.length; i += 3) {
        newLine.points.push(line.points[i] + offset, line.points[i + 1], line.points[i + 2]);
    }
    optimizeLineMemory(newLine);
    return newLine;
}

/**
 * Applies a GeoJSON Source Diff to an existing set of simplified features
 * @param source
 * @param dataDiff
 * @param options
 * @returns
 */
function applySourceDiff(source, dataDiff, options) {
    // convert diff to sets/maps for o(1) lookups
    const diff = diffToHashed(dataDiff, options);
    // collection for features that will be affected by this update and used to invalidate tiles
    let affected = [];
    if (diff.removeAll) {
        affected = source;
        source = [];
    }
    if (diff.remove.size || diff.add.size) {
        const removeFeatures = [];
        // Collect features to remove (explicit removals + replacements via add)
        for (const feature of source) {
            if (diff.remove.has(feature.id) || diff.add.has(feature.id)) {
                removeFeatures.push(feature);
            }
        }
        if (removeFeatures.length) {
            affected.push(...removeFeatures);
            const removeIds = new Set(removeFeatures.map(f => f.id));
            source = source.filter(f => !removeIds.has(f.id));
        }
        if (diff.add.size) {
            let addFeatures = convertToInternal({ type: 'FeatureCollection', features: Array.from(diff.add.values()) }, options);
            addFeatures = wrap(addFeatures, options);
            affected.push(...addFeatures);
            source.push(...addFeatures);
        }
    }
    if (diff.update.size) {
        // Features can be duplicated across the antimeridian (wrap) in a single tile, so must update all instances with the same id
        const oldFeaturesMap = new Map();
        const keepFeatures = [];
        for (const feature of source) {
            if (diff.update.has(feature.id)) {
                oldFeaturesMap.set(feature.id, [...(oldFeaturesMap.get(feature.id) || []), feature]);
            }
            else {
                keepFeatures.push(feature);
            }
        }
        for (const [id, update] of diff.update) {
            const oldFeatures = oldFeaturesMap.get(id);
            if (!oldFeatures || oldFeatures.length === 0)
                continue;
            const updatedFeatures = getUpdatedFeatures(oldFeatures, update, options);
            affected.push(...oldFeatures, ...updatedFeatures);
            keepFeatures.push(...updatedFeatures);
        }
        source = keepFeatures;
    }
    return { affected, source };
}
/**
 * Gets updated simplified feature(s) based on a diff update object.
 * @param vtFeatures - the original features
 * @param update - the update object to apply
 * @param options - the options to use for the wrap method
 * @returns Updated features. If geometry is updated, returns new feature(s) converted from geojson and wrapped. If only properties are updated, returns feature(s) with tags updated.
 */
function getUpdatedFeatures(vtFeatures, update, options) {
    const changeGeometry = !!update.newGeometry;
    const changeProps = update.removeAllProperties ||
        update.removeProperties?.length > 0 ||
        update.addOrUpdateProperties?.length > 0;
    // if geometry changed, need to create a new geojson feature and convert to internal format
    if (changeGeometry) {
        const vtFeature = vtFeatures[0];
        const geojsonFeature = {
            type: 'Feature',
            id: vtFeature.id,
            geometry: update.newGeometry,
            properties: changeProps ? applyPropertyUpdates(vtFeature.tags, update) : vtFeature.tags
        };
        let features = convertToInternal({ type: 'FeatureCollection', features: [geojsonFeature] }, options);
        features = wrap(features, options);
        return features;
    }
    if (changeProps) {
        const updated = [];
        for (const vtFeature of vtFeatures) {
            const feature = { ...vtFeature };
            feature.tags = applyPropertyUpdates(feature.tags, update);
            updated.push(feature);
        }
        return updated;
    }
    return vtFeatures;
}
/**
 * helper to apply property updates from a diff update object to a properties object
 */
function applyPropertyUpdates(tags, update) {
    if (update.removeAllProperties) {
        return {};
    }
    const properties = { ...tags || {} };
    if (update.removeProperties) {
        for (const key of update.removeProperties) {
            delete properties[key];
        }
    }
    if (update.addOrUpdateProperties) {
        for (const { key, value } of update.addOrUpdateProperties) {
            properties[key] = value;
        }
    }
    return properties;
}
/**
 * Convert a GeoJSON Source Diff to an idempotent hashed representation using Sets and Maps
 */
function diffToHashed(diff, options) {
    if (!diff)
        return {
            remove: new Set(),
            add: new Map(),
            update: new Map()
        };
    const hashed = {
        removeAll: diff.removeAll,
        remove: new Set(diff.remove || []),
        add: new Map(diff.add?.map(feature => [options.promoteId ? feature.properties[options.promoteId] : feature.id, feature])),
        update: new Map(diff.update?.map(update => [update.id, update]))
    };
    return hashed;
}

const defaultClusterOptions = {
    minZoom: 0,
    maxZoom: 16,
    minPoints: 2,
    radius: 40,
    extent: 512,
    nodeSize: 64,
    log: false,
    generateId: false,
    reduce: null,
    map: (props) => props
};
const OFFSET_ZOOM = 2;
const OFFSET_ID = 3;
const OFFSET_PARENT = 4;
const OFFSET_NUM = 5;
const OFFSET_PROP = 6;
/**
 * This class allow clustering of geojson points.
 */
class ClusterTileIndex {
    constructor(options) {
        this.options = Object.assign(Object.create(defaultClusterOptions), options);
        this.trees = new Array(this.options.maxZoom + 1);
        this.stride = this.options.reduce ? 7 : 6;
        this.clusterProps = [];
        this.points = [];
    }
    /**
     * Loads GeoJSON point features and builds the internal clustering index.
     * @param points - GeoJSON point features to cluster.
     */
    load(points) {
        const features = [];
        // Convert GeoJSON point features to GeoJSONVT internal point features
        for (const point of points) {
            if (!point.geometry) {
                continue;
            }
            const [lng, lat] = point.geometry.coordinates;
            const [x, y] = [projectX(lng), projectY(lat)];
            const feature = {
                id: point.id,
                type: 'Point',
                geometry: [x, y],
                tags: point.properties
            };
            features.push(feature);
        }
        this.createIndex(features);
    }
    /**
     * @internal
     * Loads internal GeoJSONVT point features from a data source and builds the clustering index.
     * @param features - {@link GeoJSONVTInternalFeature} data source features to filter and cluster.
     */
    initialize(features) {
        const points = [];
        for (const feature of features) {
            if (feature.type !== 'Point')
                continue;
            points.push(feature);
        }
        this.createIndex(points);
    }
    /**
     * @internal
     * Updates the cluster data by rebuilding.
     * @param features
     */
    updateIndex(features, _affected, options) {
        this.options = Object.assign(Object.create(defaultClusterOptions), options.clusterOptions);
        this.initialize(features);
    }
    createIndex(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;
            let [x, y] = p.geometry;
            x = Math.fround(x);
            y = Math.fround(y);
            // 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');
    }
    /**
     * Returns clusters and/or points within a bounding box at a given zoom level.
     * @param bbox - Bounding box in `[westLng, southLat, eastLng, northLat]` order.
     * @param zoom - Zoom level to query.
     */
    getClusters(bbox, zoom) {
        const clusterInternal = this.getClustersInternal(bbox, zoom);
        return clusterInternal.map((f) => featureToGeoJSON(f));
    }
    getClustersInternal(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.getClustersInternal([minLng, minLat, 180, maxLat], zoom);
            const westernHem = this.getClustersInternal([-180, minLat, maxLng, maxLat], zoom);
            return easternHem.concat(westernHem);
        }
        const tree = this.trees[this.limitZoom(zoom)];
        const ids = tree.range(projectX(minLng), projectY(maxLat), projectX(maxLng), projectY(minLat));
        const data = tree.flatData;
        const clusters = [];
        for (const id of ids) {
            const k = this.stride * id;
            clusters.push(data[k + OFFSET_NUM] > 1 ? getClusterFeature(data, k, this.clusterProps) : this.points[data[k + OFFSET_ID]]);
        }
        return clusters;
    }
    /**
     * Returns the immediate children (clusters or points) of a cluster as GeoJSON.
     * @param clusterId - The target cluster id.
     */
    getChildren(clusterId) {
        const originId = this.getOriginId(clusterId);
        const originZoom = this.getOriginZoom(clusterId);
        const clusterError = new Error('No cluster with the specified id: ' + clusterId);
        const tree = this.trees[originZoom];
        if (!tree)
            throw clusterError;
        const data = tree.flatData;
        if (originId * this.stride >= data.length)
            throw clusterError;
        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 ? getClusterGeoJSON(data, k, this.clusterProps) : featureToGeoJSON(this.points[data[k + OFFSET_ID]]));
            }
        }
        if (children.length === 0)
            throw clusterError;
        return children;
    }
    /**
     * Returns leaf point features under a cluster, paginated by `limit` and `offset`.
     * @param clusterId - The target cluster id.
     * @param limit - Maximum number of points to return (defaults to `10`).
     * @param offset - Number of points to skip before collecting results (defaults to `0`).
     */
    getLeaves(clusterId, limit, offset) {
        limit = limit || 10;
        offset = offset || 0;
        const leaves = [];
        this.appendLeaves(leaves, clusterId, limit, offset, 0);
        return leaves;
    }
    /**
     * Generates a vector-tile-like representation of a single tile.
     * @param z - Tile zoom.
     * @param x - Tile x coordinate.
     * @param y - Tile y coordinate.
     */
    getTile(z, x, y) {
        const tree = this.trees[this.limitZoom(z)];
        if (!tree) {
            return null;
        }
        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 = {
            transformed: true,
            features: [],
            source: null,
            x: x,
            y: y,
            z: z
        };
        this.addTileFeatures(tree.range((x - p) / z2, top, (x + 1 + p) / z2, bottom), tree.flatData, x, y, z2, tile);
        if (x === 0) {
            this.addTileFeatures(tree.range(1 - p / z2, top, 1, bottom), tree.flatData, z2, y, z2, tile);
        }
        if (x === z2 - 1) {
            this.addTileFeatures(tree.range(0, top, p / z2, bottom), tree.flatData, -1, y, z2, tile);
        }
        return tile;
    }
    /**
     * Returns the zoom level at which a cluster expands into multiple children.
     * @param clusterId - The target cluster id.
     */
    getClusterExpansionZoom(clusterId) {
        return this.getOriginZoom(clusterId);
    }
    appendLeaves(result, clusterId, limit, offset, skipped) {
        const children = this.getChildren(clusterId);
        for (const child of children) {
            const props = child.properties;
            if (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.flatData = data;
        tree.data = null; // clear original data to free memory as it isn't used later on.
        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;
            let px;
            let 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.tags;
                [px, py] = p.geometry;
            }
            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.flatData;
        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]].tags;
        const result = this.options.map(original);
        return clone && result === original ? Object.assign({}, result) : result;
    }
}
function getClusterFeature(data, i, clusterProps) {
    return {
        id: data[i + OFFSET_ID],
        type: 'Point',
        tags: getClusterProperties(data, i, clusterProps),
        geometry: [data[i], data[i + 1]]
    };
}
function getClusterGeoJSON(data, i, clusterProps) {
    return {
        type: 'Feature',
        id: data[i + OFFSET_ID],
        properties: getClusterProperties(data, i, clusterProps),
        geometry: {
            type: 'Point',
            coordinates: [unprojectX(data[i]), unprojectY(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
    });
}

const GEOJSONVT_CLIP_START = 'geojsonvt_clip_start';
const GEOJSONVT_CLIP_END = 'geojsonvt_clip_end';
/**
 * Creates a tile object from the given features
 * @param features - the features to include in the tile
 * @param z
 * @param tx
 * @param ty
 * @param options - the options object
 * @returns the created tile
 */
function createTile(features, z, tx, ty, options) {
    const tolerance = z === options.maxZoom ? 0 : options.tolerance / ((1 << z) * options.extent);
    const tile = {
        transformed: false,
        features: [],
        source: null,
        x: tx,
        y: ty,
        z: z,
        minX: 2,
        minY: 1,
        maxX: -1,
        maxY: 0,
        numPoints: 0,
        numSimplified: 0,
        numFeatures: features.length
    };
    for (const feature of features) {
        addFeature$1(tile, feature, tolerance, options);
    }
    return tile;
}
function addFeature$1(tile, feature, tolerance, options) {
    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);
    switch (feature.type) {
        case 'Point':
        case 'MultiPoint':
            addPointsTileFeature(tile, feature);
            return;
        case 'LineString':
            addLineTileFeautre(tile, feature, tolerance, options);
            return;
        case 'MultiLineString':
        case 'Polygon':
            addLinesTileFeature(tile, feature, tolerance);
            return;
        case 'MultiPolygon':
            addMultiPolygonTileFeature(tile, feature, tolerance);
            return;
    }
}
function addPointsTileFeature(tile, feature) {
    const geometry = [];
    for (let i = 0; i < feature.geometry.length; i += 3) {
        geometry.push(feature.geometry[i], feature.geometry[i + 1]);
        tile.numPoints++;
        tile.numSimplified++;
    }
    if (!geometry.length)
        return;
    const tileFeature = {
        type: 1,
        tags: feature.tags || null,
        geometry: geometry
    };
    if (feature.id !== null) {
        tileFeature.id = feature.id;
    }
    tile.features.push(tileFeature);
}
function addLineTileFeautre(tile, feature, tolerance, options) {
    const geometry = [];
    addLine(geometry, feature.geometry, tile, tolerance, false, false);
    if (!geometry.length)
        return;
    let tags = feature.tags || null;
    if (options.lineMetrics) {
        tags = {};
        for (const key in feature.tags)
            tags[key] = feature.tags[key];
        tags[GEOJSONVT_CLIP_START] = feature.geometry.start / feature.geometry.size;
        tags[GEOJSONVT_CLIP_END] = feature.geometry.end / feature.geometry.size;
    }
    const tileFeature = {
        type: 2,
        tags: tags,
        geometry: geometry
    };
    if (feature.id !== null) {
        tileFeature.id = feature.id;
    }
    tile.features.push(tileFeature);
}
function addLinesTileFeature(tile, feature, tolerance) {
    const geometry = [];
    for (let i = 0; i < feature.geometry.length; i++) {
        addLine(geometry, feature.geometry[i], tile, tolerance, feature.type === 'Polygon', i === 0);
    }
    if (!geometry.length)
        return;
    const tileFeature = {
        type: feature.type === 'Polygon' ? 3 : 2,
        tags: feature.tags || null,
        geometry: geometry
    };
    if (feature.id !== null) {
        tileFeature.id = feature.id;
    }
    tile.features.push(tileFeature);
}
function addMultiPolygonTileFeature(tile, feature, tolerance) {
    const geometry = [];
    for (let k = 0; k < feature.geometry.length; k++) {
        const polygon = feature.geometry[k];
        for (let i = 0; i < polygon.length; i++) {
            addLine(geometry, polygon[i], tile, tolerance, true, i === 0);
        }
    }
    if (!geometry.length)
        return;
    const tileFeature = {
        type: 3,
        tags: feature.tags || null,
        geometry: geometry
    };
    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.points.length / 3;
        return;
    }
    const ring = [];
    for (let i = 0; i < geom.points.length; i += 3) {
        if (tolerance === 0 || geom.points[i + 2] > sqTolerance) {
            tile.numSimplified++;
            ring.push(geom.points[i], geom.points[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)
        return;
    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;
    }
}

/**
 * Transforms the coordinates of each feature in the given tile from
 * mercator-projected space into (extent x extent) tile space.
 * @param tile - the tile to transform, this gets modified in place
 * @param extent - the tile extent (usually 4096)
 * @returns the transformed tile
 */
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) {
        if (feature.type === 1) {
            transformPointFeature(feature, extent, z2, tx, ty);
        }
        else {
            transformNonPointFeature(feature, extent, z2, tx, ty);
        }
    }
    tile.transformed = true;
    return tile;
}
/**
 * Transforms a single point feature from mercator-projected space into (extent x extent) tile space.
 */
function transformPointFeature(feature, extent, z2, tx, ty) {
    const transformed = feature;
    const geometry = feature.geometry;
    const point = [];
    for (let i = 0; i < geometry.length; i += 2) {
        point.push(transformPoint(geometry[i], geometry[i + 1], extent, z2, tx, ty));
    }
    transformed.geometry = point;
    return transformed;
}
/**
 * Transforms a single non-point feature from mercator-projected space into (extent x extent) tile space.
 */
function transformNonPointFeature(feature, extent, z2, tx, ty) {
    const transformed = feature;
    const geometry = feature.geometry;
    const nonPoint = [];
    for (const geom of geometry) {
        const ring = [];
        for (let i = 0; i < geom.length; i += 2) {
            ring.push(transformPoint(geom[i], geom[i + 1], extent, z2, tx, ty));
        }
        nonPoint.push(ring);
    }
    transformed.geometry = nonPoint;
    return transformed;
}
function transformPoint(x, y, extent, z2, tx, ty) {
    return [
        Math.round(extent * (x * z2 - tx)),
        Math.round(extent * (y * z2 - ty))
    ];
}

class TileIndex {
    constructor(options) {
        this.options = options;
        this.total = 0;
        /** @internal */
        this.stats = {};
        this.tiles = {};
        this.tileCoords = [];
        this.stats = {};
        this.total = 0;
    }
    initialize(features) {
        // start slicing from the top tile down
        this.splitTile(features, 0, 0, 0);
        if (this.options.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));
        }
    }
    /** {@inheritdoc} */
    updateIndex(source, affected, options) {
        if (options.debug > 1) {
            console.log('invalidating tiles');
            console.time('invalidating');
        }
        this.invalidateTiles(affected);
        if (options.debug > 1)
            console.timeEnd('invalidating');
        // re-generate root tile with updated feature set
        const [z, x, y] = [0, 0, 0];
        const rootTile = createTile(source, z, x, y, options);
        rootTile.source = source;
        // update tile index with new root tile - ready for getTile calls
        const id = toID(z, x, y);
        this.tiles[id] = rootTile;
        this.tileCoords.push({ z, x, y, id });
        if (options.debug) {
            const key = `z${z}`;
            this.stats[key] = (this.stats[key] || 0) + 1;
            this.total++;
        }
    }
    /** {@inheritdoc} */
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    getClusterExpansionZoom(_clusterId) {
        return null;
    }
    /** {@inheritdoc} */
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    getChildren(_clusterId) {
        return null;
    }
    /** {@inheritdoc} */
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    getLeaves(_clusterId, _limit, _offset) {
        return null;
    }
    /** {@inheritdoc} */
    getTile(z, x, y) {
        const { extent, debug } = this.options;
        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?.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');
        if (!this.tiles[id])
            return null;
        return transformTile(this.tiles[id], extent);
    }
    /**
     * 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.
     * @internal
     * @param features - features to split
     * @param z - tile zoom level
     * @param x - tile x coordinate
     * @param y - tile y coordinate
     * @param cz - target tile zoom level
     * @param cx - target tile x coordinate
     * @param cy - target tile y coordinate
     */
    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, id });
                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)
                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;
            const left = clip(features, z2, x - k1, x + k3, AxisType.X, tile.minX, tile.maxX, options);
            const right = clip(features, z2, x + k2, x + k4, AxisType.X, tile.minX, tile.maxX, options);
            if (left) {
                tl = clip(left, z2, y - k1, y + k3, AxisType.Y, tile.minY, tile.maxY, options);
                bl = clip(left, z2, y + k2, y + k4, AxisType.Y, tile.minY, tile.maxY, options);
            }
            if (right) {
                tr = clip(right, z2, y - k1, y + k3, AxisType.Y, tile.minY, tile.maxY, options);
                br = clip(right, z2, y + k2, y + k4, AxisType.Y, tile.minY, tile.maxY, options);
            }
            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);
        }
    }
    /**
     * Invalidates (removes) tiles affected by the provided features
     * @internal
     * @param features
     */
    invalidateTiles(features) {
        if (!features.length)
            return;
        const options = this.options;
        const { debug } = options;
        // calculate bounding box of all features for trivial reject
        let minX = Infinity;
        let maxX = -Infinity;
        let minY = Infinity;
        let maxY = -Infinity;
        for (const feature of features) {
            minX = Math.min(minX, feature.minX);
            maxX = Math.max(maxX, feature.maxX);
            minY = Math.min(minY, feature.minY);
            maxY = Math.max(maxY, feature.maxY);
        }
        // tile buffer clipping value - not halved as in splitTile above because checking against tile's own extent
        const k1 = options.buffer / options.extent;
        // track removed tile ids for o(1) lookup
        const removedLookup = new Set();
        // iterate through existing tiles and remove ones that are affected by features
        for (const id in this.tiles) {
            const tile = this.tiles[id];
            // calculate tile bounds including buffer
            const z2 = 1 << tile.z;
            const tileMinX = (tile.x - k1) / z2;
            const tileMaxX = (tile.x + 1 + k1) / z2;
            const tileMinY = (tile.y - k1) / z2;
            const tileMaxY = (tile.y + 1 + k1) / z2;
            // trivial reject if feature bounds don't intersect tile
            if (maxX < tileMinX || minX >= tileMaxX ||
                maxY < tileMinY || minY >= tileMaxY) {
                continue;
            }
            // check if any feature intersects with the tile
            let intersects = false;
            for (const feature of features) {
                if (feature.maxX >= tileMinX && feature.minX < tileMaxX &&
                    feature.maxY >= tileMinY && feature.minY < tileMaxY) {
                    intersects = true;
                    break;
                }
            }
            if (!intersects)
                continue;
            if (debug) {
                if (debug > 1) {
                    console.log('invalidate tile z%d-%d-%d (features: %d, points: %d, simplified: %d)', tile.z, tile.x, tile.y, tile.numFeatures, tile.numPoints, tile.numSimplified);
                }
                const key = `z${tile.z}`;
                this.stats[key] = (this.stats[key] || 0) - 1;
                this.total--;
            }
            delete this.tiles[id];
            removedLookup.add(id);
        }
        // remove tile coords that are no longer in the index
        if (removedLookup.size) {
            this.tileCoords = this.tileCoords.filter(c => !removedLookup.has(c.id));
        }
    }
}
function toID(z, x, y) {
    return (((1 << z) * y + x) * 32) + z;
}

const defaultOptions = {
    maxZoom: 14,
    indexMaxZoom: 5,
    indexMaxPoints: 100000,
    tolerance: 3,
    extent: 4096,
    buffer: 64,
    lineMetrics: false,
    promoteId: null,
    generateId: false,
    updateable: false,
    cluster: false,
    clusterOptions: defaultClusterOptions,
    debug: 0
};
/**
 * Main class for creating and managing a vector tile index from GeoJSON data.
 */
class GeoJSONVT {
    constructor(data, options) {
        options = this.options = Object.assign({}, 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 = convertToInternal(data, options);
        if (debug) {
            console.timeEnd('preprocess data');
            console.log('index: maxZoom: %d, maxPoints: %d', options.indexMaxZoom, options.indexMaxPoints);
            console.time('generate tiles');
        }
        // wraps features (ie extreme west and extreme east)
        features = wrap(features, options);
        // for updateable indexes, store a copy of the original simplified features
        if (options.updateable) {
            this.source = features;
        }
        this.initializeIndex(features, options);
    }
    initializeIndex(features, options) {
        this.tileIndex = options.cluster ? new ClusterTileIndex(options.clusterOptions) : new TileIndex(options);
        if (!features.length)
            return;
        this.tileIndex.initialize(features);
    }
    /**
     * Given z, x, and y tile coordinates, returns the corresponding tile with geometries in tile coordinates, much like MVT data is stored.
     * @param z - tile zoom level
     * @param x - tile x coordinate
     * @param y - tile y coordinate
     * @returns the transformed tile or null if not found
     */
    getTile(z, x, y) {
        z = +z;
        x = +x;
        y = +y;
        if (z < 0 || z > 24)
            return null;
        return this.tileIndex.getTile(z, x, y);
    }
    /**
     * Updates the source data feature set using a {@link GeoJSONVTSourceDiff}
     * @param diff - the source diff object
     */
    updateData(diff, filter) {
        const options = this.options;
        if (!options.updateable)
            throw new Error('to update tile geojson `updateable` option must be set to true');
        // apply diff and collect affected features and updated source that will be used to invalidate tiles
        let { affected, source } = applySourceDiff(this.source, diff, options);
        if (filter) {
            ({ affected, source } = this.filterUpdate(source, affected, filter));
        }
        // nothing has changed
        if (!affected.length)
            return;
        // update source with new simplified feature set
        this.source = source;
        this.tileIndex.updateIndex(source, affected, options);
    }
    /**
     * Filter an update using a predicate function. Returns the affected and updated source features.
     */
    filterUpdate(source, affected, predicate) {
        const removeIds = new Set();
        for (const feature of source) {
            if (feature.id == undefined)
                continue;
            if (predicate(featureToGeoJSON(feature)))
                continue;
            affected.push(feature);
            removeIds.add(feature.id);
        }
        source = source.filter(feature => !removeIds.has(feature.id));
        return { affected, source };
    }
    /**
     * Returns source data as GeoJSON - only available when `updateable` option is set to true.
     */
    getData() {
        if (!this.options.updateable)
            throw new Error('to retrieve data the `updateable` option must be set to true');
        return convertToGeoJSON(this.source);
    }
    /**
     * Update supercluster options and regenerate the index.
     * @param cluster - whether to enable clustering
     * @param clusterOptions - {@link SuperclusterOptions}
     */
    updateClusterOptions(cluster, clusterOptions) {
        const wasCluster = this.options.cluster;
        this.options.cluster = cluster;
        this.options.clusterOptions = clusterOptions;
        if (wasCluster == cluster) {
            this.tileIndex.updateIndex(this.source, [], this.options);
            return;
        }
        this.initializeIndex(this.source, this.options);
    }
    /**
     * Returns the zoom level at which a cluster expands into multiple children.
     * @param clusterId - The target cluster id.
     * @returns the expansion zoom or null in case of non-clustered source
     */
    getClusterExpansionZoom(clusterId) {
        return this.tileIndex.getClusterExpansionZoom(clusterId);
    }
    /**
     * Returns the immediate children (clusters or points) of a cluster as GeoJSON.
     * @param clusterId - The target cluster id.
     * @returns the immediate children or null in case of non-clustered source
     */
    getClusterChildren(clusterId) {
        return this.tileIndex.getChildren(clusterId);
    }
    /**
     * Returns leaf point features under a cluster, paginated by `limit` and `offset`.
     * @param clusterId - The target cluster id.
     * @param limit - Maximum number of points to return (defaults to `10`).
     * @param offset - Number of points to skip before collecting results (defaults to `0`).
     * @returns leaf point features under a cluster or null in case of non-clustered source
     */
    getClusterLeaves(clusterId, limit, offset) {
        return this.tileIndex.getLeaves(clusterId, limit, offset);
    }
}

/**
 * Converts GeoJSON data directly to a single vector tile without building a tile index.
 *
 * Unlike the {@link GeoJSONVT} class which builds a hierarchical tile index for efficient
 * repeated tile access, this function generates a single tile on-demand. This is useful when:
 * - You only need one specific tile and don't need to query multiple tiles
 * - The source data is already spatially filtered to the tile's bounding box
 * - You want to avoid the overhead of building a full tile index
 *
 * @example
 * ```ts
 * import {geoJSONToTile} from '@maplibre/geojson-vt';
 *
 * const geojson = {
 *   type: 'FeatureCollection',
 *   features: [{
 *     type: 'Feature',
 *     geometry: { type: 'Point', coordinates: [-77.03, 38.90] },
 *     properties: { name: 'Washington, D.C.' }
 *   }]
 * };
 *
 * const tile = geoJSONToTile(geojson, 10, 292, 391, { extent: 4096 });
 * ```
 *
 * @param data - GeoJSON data (Feature, FeatureCollection, or Geometry)
 * @param z - Tile zoom level
 * @param x - Tile x coordinate
 * @param y - Tile y coordinate
 * @param options - Optional configuration for tile generation
 * @returns The generated tile with geometries in tile coordinates, or null if no features
 */
function geoJSONToTile(data, z, x, y, options = {}) {
    options = { ...defaultOptions, ...options };
    const { wrap: shouldWrap = false, clip: shouldClip = false } = options;
    let features = convertToInternal(data, options);
    if (shouldWrap) {
        features = wrap(features, options);
    }
    if (shouldClip || options.lineMetrics) {
        const pow2 = 1 << z;
        const buffer = options.buffer / options.extent;
        const left = clip(features, pow2, (x - buffer), (x + 1 + buffer), AxisType.X, -1, 2, options);
        features = clip(left || [], pow2, (y - buffer), (y + 1 + buffer), AxisType.Y, -1, 2, options);
    }
    return transformTile(createTile(features ?? [], z, x, y, options), options.extent);
}

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;

// 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.hasDependencies = false;
        this.patternFeatures = [];
        this.lineClipsArray = [];
        this.gradients = {};
        for (const layer of this.layers) {
            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.hasDependencies = hasPattern('line', this.layers, options) || this.hasLineDasharray(this.layers);
        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: {},
                dashes: {},
                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.hasDependencies) {
                if (hasPattern('line', this.layers, options)) {
                    addPatternDependencies('line', this.layers, bucketFeature, { zoom: this.zoom }, options);
                }
                else if (this.hasLineDasharray(this.layers)) {
                    this.addLineDashDependencies(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(bucketFeature);
            }
            else {
                this.addFeature(bucketFeature, geometry, index, canonical, {}, {}, options.subdivisionGranularity);
            }
            const feature = features[index].feature;
            options.featureIndex.insert(feature, geometry, index, sourceLayerIndex, this.index);
        }
    }
    update(states, vtLayer, imagePositions, dashPositions) {
        if (!this.stateDependentLayers.length)
            return;
        this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, {
            imagePositions,
            dashPositions
        });
    }
    addFeatures(options, canonical, imagePositions, dashPositions) {
        for (const feature of this.patternFeatures) {
            this.addFeature(feature, feature.geometry, feature.index, canonical, imagePositions, dashPositions, options.subdivisionGranularity);
        }
    }
    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.hasOwn(feature.properties, GEOJSONVT_CLIP_START) && Object.hasOwn(feature.properties, GEOJSONVT_CLIP_END)) {
            const start = +feature.properties[GEOJSONVT_CLIP_START];
            const end = +feature.properties[GEOJSONVT_CLIP_END];
            return { start, end };
        }
    }
    addFeature(feature, geometry, index, canonical, imagePositions, dashPositions, subdivisionGranularity) {
        const layout = this.layers[0].layout;
        const join = layout.get('line-join').evaluate(feature, {});
        const cap = layout.get('line-cap').evaluate(feature, {});
        const miterLimit = layout.get('line-miter-limit').evaluate(feature, {});
        const roundLimit = layout.get('line-round-limit').evaluate(feature, {});
        this.lineClips = this.lineFeatureClips(feature);
        for (const line of geometry) {
            this.addLine(line, feature, join, cap, miterLimit, roundLimit, canonical, subdivisionGranularity);
        }
        this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, { imagePositions, dashPositions, canonical });
    }
    addLine(vertices, feature, join, cap, miterLimit, roundLimit, canonical, subdivisionGranularity) {
        this.distance = 0;
        this.scaledDistance = 0;
        this.totalDistance = 0;
        // First, subdivide the line if needed (mostly for globe rendering)
        const granularity = canonical ? subdivisionGranularity.line.getGranularityForZoomLevel(canonical.z) : 1;
        vertices = subdivideVertexLine(vertices, granularity);
        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 = VectorTileFeature.types[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$1 / (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, e, this.e2);
            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();
    }
    hasLineDasharray(layers) {
        for (const layer of layers) {
            const dasharrayProperty = layer.paint.get('line-dasharray');
            if (dasharrayProperty && !dasharrayProperty.isConstant()) {
                return true;
            }
        }
        return false;
    }
    addLineDashDependencies(layers, bucketFeature, zoom, options) {
        for (const layer of layers) {
            const dasharrayProperty = layer.paint.get('line-dasharray');
            if (!dasharrayProperty || dasharrayProperty.value.kind === 'constant') {
                continue;
            }
            const round = layer.layout.get('line-cap').evaluate(bucketFeature, {}) === 'round';
            const min = {
                dasharray: dasharrayProperty.value.evaluate({ zoom: zoom - 1 }, bucketFeature, {}),
                round
            };
            const mid = {
                dasharray: dasharrayProperty.value.evaluate({ zoom }, bucketFeature, {}),
                round
            };
            const max = {
                dasharray: dasharrayProperty.value.evaluate({ zoom: zoom + 1 }, bucketFeature, {}),
                round
            };
            const minKey = `${min.dasharray.join(',')},${min.round}`;
            const midKey = `${mid.dasharray.join(',')},${mid.round}`;
            const maxKey = `${max.dasharray.join(',')},${max.round}`;
            options.dashDependencies[minKey] = min;
            options.dashDependencies[midKey] = mid;
            options.dashDependencies[maxKey] = max;
            bucketFeature.dashes[layer.id] = { min: minKey, mid: midKey, max: maxKey };
        }
    }
}
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 DataDrivenProperty(v8Spec["layout_line"]["line-cap"]),
    "line-join": new DataDrivenProperty(v8Spec["layout_line"]["line-join"]),
    "line-miter-limit": new DataDrivenProperty(v8Spec["layout_line"]["line-miter-limit"]),
    "line-round-limit": new DataDrivenProperty(v8Spec["layout_line"]["line-round-limit"]),
    "line-sort-key": new DataDrivenProperty(v8Spec["layout_line"]["line-sort-key"]),
});
let paint$2;
const getPaint$2 = () => paint$2 = paint$2 || 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 CrossFadedDataDrivenProperty(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$2 = ({ get paint() { return getPaint$2(); }, 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;
const isLineStyleLayer = (layer) => layer.type === 'line';
class LineStyleLayer extends StyleLayer {
    constructor(layer, globalState) {
        super(layer, properties$2, globalState);
        this.gradientVersion = 0;
        if (!lineFloorwidthProperty) {
            lineFloorwidthProperty =
                new LineFloorwidthProperty(properties$2.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, transform, pixelsToTileUnits }) {
        const translatedPolygon = translate(queryGeometry, this.paint.get('line-translate'), this.paint.get('line-translate-anchor'), -transform.bearingInRadians, 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) {
    for (const section of text.sections) {
        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);
}

// ONE_EM constant used to go between "em" units used in style spec and "points" used internally for layout
var ONE_EM = 24;

const verticalizedCharacterMap = {
    '!': '︕',
    '#': '＃',
    '$': '＄',
    '%': '％',
    '&': '＆',
    '(': '︵',
    ')': '︶',
    '*': '＊',
    '+': '＋',
    ',': '︐',
    '-': '︲',
    '.': '・',
    '/': '／',
    ':': '︓',
    ';': '︔',
    '<': '︿',
    '=': '＝',
    '>': '﹀',
    '?': '︖',
    '@': '＠',
    '[': '﹇',
    '\\': '＼',
    ']': '﹈',
    '^': '＾',
    '_': '︳',
    '`': '｀',
    '{': '︷',
    '|': '―',
    '}': '︸',
    '~': '～',
    '¢': '￠',
    '£': '￡',
    '¥': '￥',
    '¦': '￤',
    '¬': '￢',
    '¯': '￣',
    '–': '︲',
    '—': '︱',
    '‘': '﹃',
    '’': '﹄',
    '“': '﹁',
    '”': '﹂',
    '…': '︙',
    '⋯': '︙',
    '‧': '・',
    '₩': '￦',
    '、': '︑',
    '。': '︒',
    '〈': '︿',
    '〉': '﹀',
    '《': '︽',
    '》': '︾',
    '「': '﹁',
    '」': '﹂',
    '『': '﹃',
    '』': '﹄',
    '【': '︻',
    '】': '︼',
    '〔': '︹',
    '〕': '︺',
    '〖': '︗',
    '〗': '︘',
    '！': '︕',
    '（': '︵',
    '）': '︶',
    '，': '︐',
    '－': '︲',
    '．': '・',
    '：': '︓',
    '；': '︔',
    '＜': '︿',
    '＞': '﹀',
    '？': '︖',
    '［': '﹇',
    '］': '﹈',
    '＿': '︳',
    '｛': '︷',
    '｜': '―',
    '｝': '︸',
    '｟': '︵',
    '｠': '︶',
    '｡': '︒',
    '｢': '﹁',
    '｣': '﹂'
};
function verticalizePunctuation(input) {
    let output = '';
    let prevChar = { premature: true, value: undefined };
    const chars = input[Symbol.iterator]();
    let char = chars.next();
    const nextChars = input[Symbol.iterator]();
    nextChars.next();
    let nextChar = nextChars.next();
    while (!char.done) {
        const canReplacePunctuation = ((nextChar.done || !charHasRotatedVerticalOrientation(nextChar.value.codePointAt(0)) || verticalizedCharacterMap[nextChar.value]) &&
            (prevChar.premature || !charHasRotatedVerticalOrientation(prevChar.value.codePointAt(0)) || verticalizedCharacterMap[prevChar.value]));
        if (canReplacePunctuation && verticalizedCharacterMap[char.value]) {
            output += verticalizedCharacterMap[char.value];
        }
        else {
            output += char.value;
        }
        prevChar = { value: char.value, premature: false };
        char = chars.next();
        nextChar = nextChars.next();
    }
    return output;
}

// 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;
// using computed properties due to https://github.com/facebook/flow/issues/380
/* eslint no-useless-computed-key: 0 */
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 in codePointHasNeutralVerticalOrientation in unicode_properties
    // 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 ('fontStack' in section) {
        const positions = glyphMap[section.fontStack];
        const glyph = positions === null || positions === void 0 ? void 0 : 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 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);
}
class TaggedString {
    constructor(text = '', sections = [], sectionIndex = []) {
        this.text = text;
        this.sections = sections;
        this.sectionIndex = sectionIndex;
        this.imageSectionID = null;
    }
    static fromFeature(text, defaultFontStack) {
        const result = new TaggedString();
        for (const section of text.sections) {
            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];
    }
    verticalizePunctuation() {
        this.text = verticalizePunctuation(this.text);
    }
    /**
     * Returns whether the text contains zero-width spaces.
     *
     * Some tilesets such as Mapbox Streets insert ZWSPs as hints for line
     * breaking in CJK text.
     */
    hasZeroWidthSpaces() {
        return this.text.includes('\u200b');
    }
    trim() {
        const leadingWhitespace = this.text.match(/^\s*/);
        const leadingLength = leadingWhitespace ? leadingWhitespace[0].length : 0;
        // Require a preceding non-space character to avoid overlapping leading and trailing matches.
        const trailingWhitespace = this.text.match(/\S\s*$/);
        const trailingLength = trailingWhitespace ? trailingWhitespace[0].length - 1 : 0;
        this.text = this.text.substring(leadingLength, this.text.length - trailingLength);
        this.sectionIndex = this.sectionIndex.slice(leadingLength, this.sectionIndex.length - trailingLength);
    }
    substring(start, end) {
        const text = [...this.text].slice(start, end).join('');
        const sectionIndex = this.sectionIndex.slice(start, end);
        return new TaggedString(text, this.sections, sectionIndex);
    }
    /**
     * Converts a UTF-16 character index to a UTF-16 code unit (JavaScript character index).
     */
    toCodeUnitIndex(unicodeIndex) {
        return [...this.text].slice(0, unicodeIndex).join('').length;
    }
    toString() {
        return this.text;
    }
    getMaxScale() {
        return this.sectionIndex.reduce((max, index) => Math.max(max, this.sections[index].scale), 0);
    }
    getMaxImageSize(imagePositions) {
        let maxImageWidth = 0;
        let maxImageHeight = 0;
        for (let i = 0; i < this.length(); i++) {
            const section = this.getSection(i);
            if ('imageName' in section) {
                const imagePosition = imagePositions[section.imageName];
                if (!imagePosition)
                    continue;
                const size = imagePosition.displaySize;
                maxImageWidth = Math.max(maxImageWidth, size[0]);
                maxImageHeight = Math.max(maxImageHeight, size[1]);
            }
        }
        return { maxImageWidth, maxImageHeight };
    }
    addTextSection(section, defaultFontStack) {
        this.text += section.text;
        this.sections.push({
            scale: section.scale || 1,
            verticalAlign: section.verticalAlign || 'bottom',
            fontStack: section.fontStack || defaultFontStack,
        });
        const index = this.sections.length - 1;
        this.sectionIndex.push(...[...section.text].map(() => 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({
            scale: 1,
            verticalAlign: section.verticalAlign || 'bottom',
            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;
    }
    determineLineBreaks(spacing, maxWidth, glyphMap, imagePositions, layoutTextSize) {
        const potentialLineBreaks = [];
        const targetWidth = this.determineAverageLineWidth(spacing, maxWidth, glyphMap, imagePositions, layoutTextSize);
        const hasZeroWidthSpaces = this.hasZeroWidthSpaces();
        let currentX = 0;
        let i = 0;
        const chars = this.text[Symbol.iterator]();
        let char = chars.next();
        const nextChars = this.text[Symbol.iterator]();
        nextChars.next();
        let nextChar = nextChars.next();
        const nextNextChars = this.text[Symbol.iterator]();
        nextNextChars.next();
        nextNextChars.next();
        let nextNextChar = nextNextChars.next();
        while (!char.done) {
            const section = this.getSection(i);
            const codePoint = char.value.codePointAt(0);
            if (!charIsWhitespace(codePoint))
                currentX += getGlyphAdvance(codePoint, section, glyphMap, imagePositions, spacing, layoutTextSize);
            // Ideographic characters, spaces, and word-breaking punctuation that often appear without
            // surrounding spaces.
            if (!nextChar.done) {
                const ideographicBreak = codePointAllowsIdeographicBreaking(codePoint);
                const nextCodePoint = nextChar.value.codePointAt(0);
                if (breakable[codePoint] || ideographicBreak || 'imageName' in section || (!nextNextChar.done && breakableBefore[nextCodePoint])) {
                    potentialLineBreaks.push(evaluateBreak(i + 1, currentX, targetWidth, potentialLineBreaks, calculatePenalty(codePoint, nextCodePoint, ideographicBreak && hasZeroWidthSpaces), false));
                }
            }
            i++;
            char = chars.next();
            nextChar = nextChars.next();
            nextNextChar = nextNextChars.next();
        }
        return leastBadBreaks(evaluateBreak(this.length(), currentX, targetWidth, potentialLineBreaks, 0, true));
    }
    determineAverageLineWidth(spacing, maxWidth, glyphMap, imagePositions, layoutTextSize) {
        let totalWidth = 0;
        let index = 0;
        for (const char of this.text) {
            const section = this.getSection(index);
            totalWidth += getGlyphAdvance(char.codePointAt(0), section, glyphMap, imagePositions, spacing, layoutTextSize);
            index++;
        }
        const lineCount = Math.max(1, Math.ceil(totalWidth / maxWidth));
        return totalWidth / lineCount;
    }
}

const SHIFT_LEFT_32 = (1 << 16) * (1 << 16);
const 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)
const TEXT_DECODER_MIN_LENGTH$1 = 12;
const utf8TextDecoder$1 = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf-8');

const PBF_VARINT  = 0; // varint: int32, int64, uint32, uint64, sint32, sint64, bool, enum
const PBF_FIXED64 = 1; // 64-bit: double, fixed64, sfixed64
const PBF_BYTES   = 2; // length-delimited: string, bytes, embedded messages, packed repeated fields
const PBF_FIXED32 = 5; // 32-bit: float, fixed32, sfixed32

class Pbf {
    /**
     * @param {Uint8Array | ArrayBuffer} [buf]
     */
    constructor(buf = new Uint8Array(16)) {
        this.buf = ArrayBuffer.isView(buf) ? buf : new Uint8Array(buf);
        this.dataView = new DataView(this.buf.buffer);
        this.pos = 0;
        this.type = 0;
        this.length = this.buf.length;
    }

    // === READING =================================================================

    /**
     * @template T
     * @param {(tag: number, result: T, pbf: Pbf) => void} readField
     * @param {T} result
     * @param {number} [end]
     */
    readFields(readField, result, end = this.length) {
        while (this.pos < end) {
            const 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;
    }

    /**
     * @template T
     * @param {(tag: number, result: T, pbf: Pbf) => void} readField
     * @param {T} result
     */
    readMessage(readField, result) {
        return this.readFields(readField, result, this.readVarint() + this.pos);
    }

    readFixed32() {
        const val = this.dataView.getUint32(this.pos, true);
        this.pos += 4;
        return val;
    }

    readSFixed32() {
        const val = this.dataView.getInt32(this.pos, true);
        this.pos += 4;
        return val;
    }

    // 64-bit int handling is based on github.com/dpw/node-buffer-more-ints (MIT-licensed)

    readFixed64() {
        const val = this.dataView.getUint32(this.pos, true) + this.dataView.getUint32(this.pos + 4, true) * SHIFT_LEFT_32;
        this.pos += 8;
        return val;
    }

    readSFixed64() {
        const val = this.dataView.getUint32(this.pos, true) + this.dataView.getInt32(this.pos + 4, true) * SHIFT_LEFT_32;
        this.pos += 8;
        return val;
    }

    readFloat() {
        const val = this.dataView.getFloat32(this.pos, true);
        this.pos += 4;
        return val;
    }

    readDouble() {
        const val = this.dataView.getFloat64(this.pos, true);
        this.pos += 8;
        return val;
    }

    /**
     * @param {boolean} [isSigned]
     */
    readVarint(isSigned) {
        const buf = this.buf;
        let 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() { // for compatibility with v2.0.1
        return this.readVarint(true);
    }

    readSVarint() {
        const num = this.readVarint();
        return num % 2 === 1 ? (num + 1) / -2 : num / 2; // zigzag encoding
    }

    readBoolean() {
        return Boolean(this.readVarint());
    }

    readString() {
        const end = this.readVarint() + this.pos;
        const pos = this.pos;
        this.pos = end;

        if (end - pos >= TEXT_DECODER_MIN_LENGTH$1 && utf8TextDecoder$1) {
            // longer strings are fast with the built-in browser TextDecoder API
            return utf8TextDecoder$1.decode(this.buf.subarray(pos, end));
        }
        // short strings are fast with our custom implementation
        return readUtf8$1(this.buf, pos, end);
    }

    readBytes() {
        const 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

    /**
     * @param {number[]} [arr]
     * @param {boolean} [isSigned]
     */
    readPackedVarint(arr = [], isSigned) {
        const end = this.readPackedEnd();
        while (this.pos < end) arr.push(this.readVarint(isSigned));
        return arr;
    }
    /** @param {number[]} [arr] */
    readPackedSVarint(arr = []) {
        const end = this.readPackedEnd();
        while (this.pos < end) arr.push(this.readSVarint());
        return arr;
    }
    /** @param {boolean[]} [arr] */
    readPackedBoolean(arr = []) {
        const end = this.readPackedEnd();
        while (this.pos < end) arr.push(this.readBoolean());
        return arr;
    }
    /** @param {number[]} [arr] */
    readPackedFloat(arr = []) {
        const end = this.readPackedEnd();
        while (this.pos < end) arr.push(this.readFloat());
        return arr;
    }
    /** @param {number[]} [arr] */
    readPackedDouble(arr = []) {
        const end = this.readPackedEnd();
        while (this.pos < end) arr.push(this.readDouble());
        return arr;
    }
    /** @param {number[]} [arr] */
    readPackedFixed32(arr = []) {
        const end = this.readPackedEnd();
        while (this.pos < end) arr.push(this.readFixed32());
        return arr;
    }
    /** @param {number[]} [arr] */
    readPackedSFixed32(arr = []) {
        const end = this.readPackedEnd();
        while (this.pos < end) arr.push(this.readSFixed32());
        return arr;
    }
    /** @param {number[]} [arr] */
    readPackedFixed64(arr = []) {
        const end = this.readPackedEnd();
        while (this.pos < end) arr.push(this.readFixed64());
        return arr;
    }
    /** @param {number[]} [arr] */
    readPackedSFixed64(arr = []) {
        const end = this.readPackedEnd();
        while (this.pos < end) arr.push(this.readSFixed64());
        return arr;
    }
    readPackedEnd() {
        return this.type === PBF_BYTES ? this.readVarint() + this.pos : this.pos + 1;
    }

    /** @param {number} val */
    skip(val) {
        const 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 =================================================================

    /**
     * @param {number} tag
     * @param {number} type
     */
    writeTag(tag, type) {
        this.writeVarint((tag << 3) | type);
    }

    /** @param {number} min */
    realloc(min) {
        let length = this.length || 16;

        while (length < this.pos + min) length *= 2;

        if (length !== this.length) {
            const buf = new Uint8Array(length);
            buf.set(this.buf);
            this.buf = buf;
            this.dataView = new DataView(buf.buffer);
            this.length = length;
        }
    }

    finish() {
        this.length = this.pos;
        this.pos = 0;
        return this.buf.subarray(0, this.length);
    }

    /** @param {number} val */
    writeFixed32(val) {
        this.realloc(4);
        this.dataView.setInt32(this.pos, val, true);
        this.pos += 4;
    }

    /** @param {number} val */
    writeSFixed32(val) {
        this.realloc(4);
        this.dataView.setInt32(this.pos, val, true);
        this.pos += 4;
    }

    /** @param {number} val */
    writeFixed64(val) {
        this.realloc(8);
        this.dataView.setInt32(this.pos, val & -1, true);
        this.dataView.setInt32(this.pos + 4, Math.floor(val * SHIFT_RIGHT_32), true);
        this.pos += 8;
    }

    /** @param {number} val */
    writeSFixed64(val) {
        this.realloc(8);
        this.dataView.setInt32(this.pos, val & -1, true);
        this.dataView.setInt32(this.pos + 4, Math.floor(val * SHIFT_RIGHT_32), true);
        this.pos += 8;
    }

    /** @param {number} val */
    writeVarint(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;
    }

    /** @param {number} val */
    writeSVarint(val) {
        this.writeVarint(val < 0 ? -val * 2 - 1 : val * 2);
    }

    /** @param {boolean} val */
    writeBoolean(val) {
        this.writeVarint(+val);
    }

    /** @param {string} str */
    writeString(str) {
        str = String(str);
        this.realloc(str.length * 4);

        this.pos++; // reserve 1 byte for short string length

        const startPos = this.pos;
        // write the string directly to the buffer and see how much was written
        this.pos = writeUtf8(this.buf, str, this.pos);
        const 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;
    }

    /** @param {number} val */
    writeFloat(val) {
        this.realloc(4);
        this.dataView.setFloat32(this.pos, val, true);
        this.pos += 4;
    }

    /** @param {number} val */
    writeDouble(val) {
        this.realloc(8);
        this.dataView.setFloat64(this.pos, val, true);
        this.pos += 8;
    }

    /** @param {Uint8Array} buffer */
    writeBytes(buffer) {
        const len = buffer.length;
        this.writeVarint(len);
        this.realloc(len);
        for (let i = 0; i < len; i++) this.buf[this.pos++] = buffer[i];
    }

    /**
     * @template T
     * @param {(obj: T, pbf: Pbf) => void} fn
     * @param {T} obj
     */
    writeRawMessage(fn, obj) {
        this.pos++; // reserve 1 byte for short message length

        // write the message directly to the buffer and see how much was written
        const startPos = this.pos;
        fn(obj, this);
        const 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;
    }

    /**
     * @template T
     * @param {number} tag
     * @param {(obj: T, pbf: Pbf) => void} fn
     * @param {T} obj
     */
    writeMessage(tag, fn, obj) {
        this.writeTag(tag, PBF_BYTES);
        this.writeRawMessage(fn, obj);
    }

    /**
     * @param {number} tag
     * @param {number[]} arr
     */
    writePackedVarint(tag, arr) {
        if (arr.length) this.writeMessage(tag, writePackedVarint, arr);
    }
    /**
     * @param {number} tag
     * @param {number[]} arr
     */
    writePackedSVarint(tag, arr) {
        if (arr.length) this.writeMessage(tag, writePackedSVarint, arr);
    }
    /**
     * @param {number} tag
     * @param {boolean[]} arr
     */
    writePackedBoolean(tag, arr) {
        if (arr.length) this.writeMessage(tag, writePackedBoolean, arr);
    }
    /**
     * @param {number} tag
     * @param {number[]} arr
     */
    writePackedFloat(tag, arr) {
        if (arr.length) this.writeMessage(tag, writePackedFloat, arr);
    }
    /**
     * @param {number} tag
     * @param {number[]} arr
     */
    writePackedDouble(tag, arr) {
        if (arr.length) this.writeMessage(tag, writePackedDouble, arr);
    }
    /**
     * @param {number} tag
     * @param {number[]} arr
     */
    writePackedFixed32(tag, arr) {
        if (arr.length) this.writeMessage(tag, writePackedFixed32, arr);
    }
    /**
     * @param {number} tag
     * @param {number[]} arr
     */
    writePackedSFixed32(tag, arr) {
        if (arr.length) this.writeMessage(tag, writePackedSFixed32, arr);
    }
    /**
     * @param {number} tag
     * @param {number[]} arr
     */
    writePackedFixed64(tag, arr) {
        if (arr.length) this.writeMessage(tag, writePackedFixed64, arr);
    }
    /**
     * @param {number} tag
     * @param {number[]} arr
     */
    writePackedSFixed64(tag, arr) {
        if (arr.length) this.writeMessage(tag, writePackedSFixed64, arr);
    }

    /**
     * @param {number} tag
     * @param {Uint8Array} buffer
     */
    writeBytesField(tag, buffer) {
        this.writeTag(tag, PBF_BYTES);
        this.writeBytes(buffer);
    }
    /**
     * @param {number} tag
     * @param {number} val
     */
    writeFixed32Field(tag, val) {
        this.writeTag(tag, PBF_FIXED32);
        this.writeFixed32(val);
    }
    /**
     * @param {number} tag
     * @param {number} val
     */
    writeSFixed32Field(tag, val) {
        this.writeTag(tag, PBF_FIXED32);
        this.writeSFixed32(val);
    }
    /**
     * @param {number} tag
     * @param {number} val
     */
    writeFixed64Field(tag, val) {
        this.writeTag(tag, PBF_FIXED64);
        this.writeFixed64(val);
    }
    /**
     * @param {number} tag
     * @param {number} val
     */
    writeSFixed64Field(tag, val) {
        this.writeTag(tag, PBF_FIXED64);
        this.writeSFixed64(val);
    }
    /**
     * @param {number} tag
     * @param {number} val
     */
    writeVarintField(tag, val) {
        this.writeTag(tag, PBF_VARINT);
        this.writeVarint(val);
    }
    /**
     * @param {number} tag
     * @param {number} val
     */
    writeSVarintField(tag, val) {
        this.writeTag(tag, PBF_VARINT);
        this.writeSVarint(val);
    }
    /**
     * @param {number} tag
     * @param {string} str
     */
    writeStringField(tag, str) {
        this.writeTag(tag, PBF_BYTES);
        this.writeString(str);
    }
    /**
     * @param {number} tag
     * @param {number} val
     */
    writeFloatField(tag, val) {
        this.writeTag(tag, PBF_FIXED32);
        this.writeFloat(val);
    }
    /**
     * @param {number} tag
     * @param {number} val
     */
    writeDoubleField(tag, val) {
        this.writeTag(tag, PBF_FIXED64);
        this.writeDouble(val);
    }
    /**
     * @param {number} tag
     * @param {boolean} val
     */
    writeBooleanField(tag, val) {
        this.writeVarintField(tag, +val);
    }
};

/**
 * @param {number} l
 * @param {boolean | undefined} s
 * @param {Pbf} p
 */
function readVarintRemainder(l, s, p) {
    const buf = p.buf;
    let 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');
}

/**
 * @param {number} low
 * @param {number} high
 * @param {boolean} [isSigned]
 */
function toNum(low, high, isSigned) {
    return isSigned ? high * 0x100000000 + (low >>> 0) : ((high >>> 0) * 0x100000000) + (low >>> 0);
}

/**
 * @param {number} val
 * @param {Pbf} pbf
 */
function writeBigVarint(val, pbf) {
    let 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);
}

/**
 * @param {number} high
 * @param {number} low
 * @param {Pbf} 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;
}

/**
 * @param {number} high
 * @param {Pbf} pbf
 */
function writeBigVarintHigh(high, pbf) {
    const 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;
}

/**
 * @param {number} startPos
 * @param {number} len
 * @param {Pbf} pbf
 */
function makeRoomForExtraLength(startPos, len, pbf) {
    const 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 (let i = pbf.pos - 1; i >= startPos; i--) pbf.buf[i + extraLen] = pbf.buf[i];
}

/**
 * @param {number[]} arr
 * @param {Pbf} pbf
 */
function writePackedVarint(arr, pbf) {
    for (let i = 0; i < arr.length; i++) pbf.writeVarint(arr[i]);
}
/**
 * @param {number[]} arr
 * @param {Pbf} pbf
 */
function writePackedSVarint(arr, pbf) {
    for (let i = 0; i < arr.length; i++) pbf.writeSVarint(arr[i]);
}
/**
 * @param {number[]} arr
 * @param {Pbf} pbf
 */
function writePackedFloat(arr, pbf) {
    for (let i = 0; i < arr.length; i++) pbf.writeFloat(arr[i]);
}
/**
 * @param {number[]} arr
 * @param {Pbf} pbf
 */
function writePackedDouble(arr, pbf) {
    for (let i = 0; i < arr.length; i++) pbf.writeDouble(arr[i]);
}
/**
 * @param {boolean[]} arr
 * @param {Pbf} pbf
 */
function writePackedBoolean(arr, pbf) {
    for (let i = 0; i < arr.length; i++) pbf.writeBoolean(arr[i]);
}
/**
 * @param {number[]} arr
 * @param {Pbf} pbf
 */
function writePackedFixed32(arr, pbf) {
    for (let i = 0; i < arr.length; i++) pbf.writeFixed32(arr[i]);
}
/**
 * @param {number[]} arr
 * @param {Pbf} pbf
 */
function writePackedSFixed32(arr, pbf) {
    for (let i = 0; i < arr.length; i++) pbf.writeSFixed32(arr[i]);
}
/**
 * @param {number[]} arr
 * @param {Pbf} pbf
 */
function writePackedFixed64(arr, pbf) {
    for (let i = 0; i < arr.length; i++) pbf.writeFixed64(arr[i]);
}
/**
 * @param {number[]} arr
 * @param {Pbf} pbf
 */
function writePackedSFixed64(arr, pbf) {
    for (let i = 0; i < arr.length; i++) pbf.writeSFixed64(arr[i]);
}

// Buffer code below from https://github.com/feross/buffer, MIT-licensed

/**
 * @param {Uint8Array} buf
 * @param {number} pos
 * @param {number} end
 */
function readUtf8$1(buf, pos, end) {
    let str = '';
    let i = pos;

    while (i < end) {
        const b0 = buf[i];
        let c = null; // codepoint
        let bytesPerSequence =
            b0 > 0xEF ? 4 :
            b0 > 0xDF ? 3 :
            b0 > 0xBF ? 2 : 1;

        if (i + bytesPerSequence > end) break;

        let 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;
}

/**
 * @param {Uint8Array} buf
 * @param {string} str
 * @param {number} pos
 */
function writeUtf8(buf, str, pos) {
    for (let 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;
}

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 Pbf(data).readFields(readFontstacks, []);
}
const GLYPH_PBF_BORDER = border$1;

/**
 * @typedef {Object} PotpackBox
 * @property {number} w Box width.
 * @property {number} h Box height.
 * @property {number} [x] X coordinate in the resulting container.
 * @property {number} [y] Y coordinate in the resulting container.
 */

/**
 * @typedef {Object} PotpackStats
 * @property {number} w Width of the resulting container.
 * @property {number} h Height of the resulting container.
 * @property {number} fill The space utilization value (0 to 1). Higher is better.
 */

/**
 * Packs 2D rectangles into a near-square container.
 *
 * Mutates the {@link boxes} array: it's sorted (by height/width),
 * and box objects are augmented with `x`, `y` coordinates.
 *
 * @param {PotpackBox[]} boxes
 * @return {PotpackStats}
 */
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 (last && 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$1.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$1.WritingMode || (exports$1.WritingMode = {}));
const SHAPING_DEFAULT_OFFSET = -17;
function isEmpty(positionedLines) {
    for (const line of positionedLines) {
        if (line.positionedGlyphs.length !== 0) {
            return false;
        }
    }
    return true;
}
function breakLines(input, lineBreakPoints) {
    const lines = [];
    let start = 0;
    for (const lineBreak of lineBreakPoints) {
        lines.push(input.substring(start, lineBreak));
        start = lineBreak;
    }
    if (start < input.length()) {
        lines.push(input.substring(start, input.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$1.WritingMode.vertical) {
        logicalInput.verticalizePunctuation();
    }
    let lines;
    let lineBreaks = logicalInput.determineLineBreaks(spacing, maxWidth, glyphMap, imagePositions, layoutTextSize);
    const { processBidirectionalText, processStyledBidirectionalText } = rtlWorkerPlugin;
    if (processBidirectionalText && logicalInput.sections.length === 1) {
        // Bidi doesn't have to be style-aware
        lines = [];
        // ICU operates on code units.
        lineBreaks = lineBreaks.map(index => logicalInput.toCodeUnitIndex(index));
        const untaggedLines = processBidirectionalText(logicalInput.toString(), lineBreaks);
        for (const line of untaggedLines) {
            const sectionIndex = [...line].map(() => 0);
            lines.push(new TaggedString(line, logicalInput.sections, sectionIndex));
        }
    }
    else if (processStyledBidirectionalText) {
        // Need version of mapbox-gl-rtl-text with style support for combining RTL text
        // with formatting
        lines = [];
        // ICU operates on code units.
        lineBreaks = lineBreaks.map(index => logicalInput.toCodeUnitIndex(index));
        // Convert character-based section index to be based on code units.
        let i = 0;
        const sectionIndex = [];
        for (const char of logicalInput.text) {
            sectionIndex.push(...Array(char.length).fill(logicalInput.sectionIndex[i]));
            i++;
        }
        const processedLines = processStyledBidirectionalText(logicalInput.text, sectionIndex, lineBreaks);
        for (const line of processedLines) {
            const sectionIndex = [];
            let elapsedChars = '';
            for (const char of line[0]) {
                sectionIndex.push(line[1][elapsedChars.length]);
                elapsedChars += char;
            }
            lines.push(new TaggedString(line[0], logicalInput.sections, sectionIndex));
        }
    }
    else {
        lines = breakLines(logicalInput, lineBreaks);
    }
    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;
}
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 calculateLineContentSize(imagePositions, line, layoutTextSizeFactor) {
    const maxGlyphSize = line.getMaxScale() * ONE_EM;
    const { maxImageWidth, maxImageHeight } = line.getMaxImageSize(imagePositions);
    const horizontalLineContentHeight = Math.max(maxGlyphSize, maxImageHeight * layoutTextSizeFactor);
    const verticalLineContentWidth = Math.max(maxGlyphSize, maxImageWidth * layoutTextSizeFactor);
    return { verticalLineContentWidth, horizontalLineContentHeight };
}
function getVerticalAlignFactor(verticalAlign) {
    switch (verticalAlign) {
        case 'top':
            return 0;
        case 'center':
            return 0.5;
        default:
            return 1;
    }
}
function getRectAndMetrics(glyphPosition, glyphMap, section, codePoint) {
    if (glyphPosition === null || glyphPosition === void 0 ? void 0 : glyphPosition.rect) {
        return glyphPosition;
    }
    const glyphs = glyphMap[section.fontStack];
    const glyph = glyphs === null || glyphs === void 0 ? void 0 : glyphs[codePoint];
    if (!glyph)
        return null;
    const metrics = glyph.metrics;
    return { rect: null, metrics };
}
function isLineVertical(writingMode, allowVerticalPlacement, codePoint) {
    return !(writingMode === exports$1.WritingMode.horizontal ||
        // Don't verticalize glyphs that have no upright orientation if vertical placement is disabled.
        (!allowVerticalPlacement && !codePointHasUprightVerticalOrientation(codePoint)) ||
        // If vertical placement is enabled, don't verticalize glyphs that
        // are from complex text layout script, or whitespaces.
        (allowVerticalPlacement && (charIsWhitespace(codePoint) || charInComplexShapingScript(codePoint))));
}
function shapeLines(shaping, glyphMap, glyphPositions, imagePositions, lines, lineHeight, textAnchor, textJustify, writingMode, spacing, allowVerticalPlacement, layoutTextSizeThisZoom) {
    let x = 0;
    let y = 0;
    let maxLineLength = 0;
    let maxLineHeight = 0;
    const justify = textJustify === 'right' ? 1 :
        textJustify === 'left' ? 0 : 0.5;
    const layoutTextSizeFactor = ONE_EM / layoutTextSizeThisZoom;
    let lineIndex = 0;
    for (const line of lines) {
        line.trim();
        const lineMaxScale = line.getMaxScale();
        const positionedLine = { positionedGlyphs: [], lineOffset: 0 };
        shaping.positionedLines[lineIndex] = positionedLine;
        const positionedGlyphs = positionedLine.positionedGlyphs;
        let imageOffset = 0.0;
        if (!line.length()) {
            y += lineHeight; // Still need a line feed after empty line
            ++lineIndex;
            continue;
        }
        const lineShapingSize = calculateLineContentSize(imagePositions, line, layoutTextSizeFactor);
        let i = 0;
        for (const char of line.text) {
            const section = line.getSection(i);
            const codePoint = char.codePointAt(0);
            const vertical = isLineVertical(writingMode, allowVerticalPlacement, codePoint);
            const positionedGlyph = {
                glyph: codePoint,
                imageName: null,
                x,
                y: y + SHAPING_DEFAULT_OFFSET,
                vertical,
                scale: 1,
                fontStack: '',
                sectionIndex: line.getSectionIndex(i),
                metrics: null,
                rect: null
            };
            let sectionAttributes;
            if ('fontStack' in section) {
                sectionAttributes = shapeTextSection(section, codePoint, vertical, lineShapingSize, glyphMap, glyphPositions);
                if (!sectionAttributes)
                    continue;
                positionedGlyph.fontStack = section.fontStack;
            }
            else {
                shaping.iconsInText = true;
                // 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 *= layoutTextSizeFactor;
                sectionAttributes = shapeImageSection(section, vertical, lineMaxScale, lineShapingSize, imagePositions);
                if (!sectionAttributes)
                    continue;
                imageOffset = Math.max(imageOffset, sectionAttributes.imageOffset);
                positionedGlyph.imageName = section.imageName;
            }
            const { rect, metrics, baselineOffset } = sectionAttributes;
            positionedGlyph.y += baselineOffset;
            positionedGlyph.scale = section.scale;
            positionedGlyph.metrics = metrics;
            positionedGlyph.rect = rect;
            positionedGlyphs.push(positionedGlyph);
            if (!vertical) {
                x += metrics.advance * section.scale + spacing;
            }
            else {
                shaping.verticalizable = true;
                const verticalAdvance = 'imageName' in section ? metrics.advance : ONE_EM;
                x += verticalAdvance * section.scale + spacing;
            }
            i++;
        }
        // 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);
        }
        x = 0;
        const maxLineOffset = (lineMaxScale - 1) * ONE_EM;
        positionedLine.lineOffset = Math.max(imageOffset, maxLineOffset);
        const currentLineHeight = lineHeight * lineMaxScale + imageOffset;
        y += currentLineHeight;
        maxLineHeight = Math.max(currentLineHeight, maxLineHeight);
        ++lineIndex;
    }
    // Calculate the bounding box and justify / align text block.
    const { horizontalAlign, verticalAlign } = getAnchorAlignment(textAnchor);
    align(shaping.positionedLines, justify, horizontalAlign, verticalAlign, maxLineLength, maxLineHeight, lineHeight, y, lines.length);
    // Calculate the bounding box
    // shaping.top & shaping.left already include text offset (text-radial-offset or text-offset)
    shaping.top += -verticalAlign * y;
    shaping.bottom = shaping.top + y;
    shaping.left += -horizontalAlign * maxLineLength;
    shaping.right = shaping.left + maxLineLength;
}
function shapeTextSection(section, codePoint, vertical, lineShapingSize, glyphMap, glyphPositions) {
    const positions = glyphPositions[section.fontStack];
    const glyphPosition = positions === null || positions === void 0 ? void 0 : positions[codePoint];
    const rectAndMetrics = getRectAndMetrics(glyphPosition, glyphMap, section, codePoint);
    if (rectAndMetrics === null)
        return null;
    let baselineOffset;
    if (vertical) {
        baselineOffset = lineShapingSize.verticalLineContentWidth - section.scale * ONE_EM;
    }
    else {
        const verticalAlignFactor = getVerticalAlignFactor(section.verticalAlign);
        baselineOffset = (lineShapingSize.horizontalLineContentHeight - section.scale * ONE_EM) * verticalAlignFactor;
    }
    return {
        rect: rectAndMetrics.rect,
        metrics: rectAndMetrics.metrics,
        baselineOffset
    };
}
function shapeImageSection(section, vertical, lineMaxScale, lineShapingSize, imagePositions) {
    const imagePosition = imagePositions[section.imageName];
    if (!imagePosition)
        return null;
    const rect = imagePosition.paddedRect;
    const size = imagePosition.displaySize;
    const metrics = { width: size[0],
        height: size[1],
        left: IMAGE_PADDING,
        top: -GLYPH_PBF_BORDER,
        advance: vertical ? size[1] : size[0] };
    let baselineOffset;
    if (vertical) {
        baselineOffset = lineShapingSize.verticalLineContentWidth - size[1] * section.scale;
    }
    else {
        const verticalAlignFactor = getVerticalAlignFactor(section.verticalAlign);
        baselineOffset = (lineShapingSize.horizontalLineContentHeight - size[1] * section.scale) * verticalAlignFactor;
    }
    // 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 imageOffset = (vertical ? size[0] : size[1]) * section.scale - ONE_EM * lineMaxScale;
    return { rect, metrics, baselineOffset, imageOffset };
}
// justify right = 1, left = 0, center = 0.5
function justifyLine(positionedGlyphs, start, end, justify) {
    if (justify === 0)
        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;
    }
}
/**
 * Aligns the lines based on horizontal and vertical alignment.
 */
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 * lineHeight + 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
        // transferable 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 interpolateFactory.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$2(Interpolate.interpolationFactor(interpolationType, zoom, minZoom, maxZoom), 0, 1);
        if (sizeData.kind === 'camera') {
            uSize = interpolateFactory.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;
}

// 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.hasDependencies = false;
        this.hasRTLText = false;
        this.sortKeyRanges = [];
        this.collisionCircleArray = [];
        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$1.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 => property.startsWith('text')));
        this.icon = new SymbolBuffers(new ProgramConfigurationSet(this.layers, this.zoom, property => property.startsWith('icon')));
        this.glyphOffsetArray = new GlyphOffsetArray();
        this.lineVertexArray = new SymbolLineVertexArray();
        this.symbolInstances = new SymbolInstanceArray();
        this.textAnchorOffsets = new TextAnchorOffsetArray();
    }
    calculateGlyphDependencies(text, stack, textAlongLine, allowVerticalPlacement, doesAllowVerticalWritingMode) {
        for (const char of text) {
            stack[char.codePointAt(0)] = true;
            if ((textAlongLine || allowVerticalPlacement) && doesAllowVerticalWritingMode) {
                const verticalChar = verticalizedCharacterMap[char];
                if (verticalChar) {
                    stack[verticalChar.codePointAt(0)] = true;
                }
            }
        }
    }
    populate(features, options, canonical) {
        var _a;
        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: VectorTileFeature.types[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 = (_a = this.writingModes) === null || _a === void 0 ? void 0 : _a.includes(exports$1.WritingMode.vertical);
                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$1.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 + 2, index + 1);
            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, { imagePositions: {}, canonical, formattedSection: sections === null || sections === void 0 ? void 0 : 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(x1, y1));
        this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point(x2, y1));
        this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point(x2, y2));
        this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point(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 + 2, vertexIndex + 1);
            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 === null || last === void 0 ? void 0 : 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);
            const textIndices = [
                symbolInstance.rightJustifiedTextSymbolIndex,
                symbolInstance.centerJustifiedTextSymbolIndex,
                symbolInstance.leftJustifiedTextSymbolIndex
            ];
            for (let i = 0; i < textIndices.length; i++) {
                const index = textIndices[i];
                // 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 && textIndices.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$1;
const getPaint$1 = () => paint$1 = paint$1 || 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$1 = ({ get paint() { return getPaint$1(); }, 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 === null || overrides === void 0 ? void 0 : 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'] });

const isSymbolStyleLayer = (layer) => layer.type === 'symbol';
class SymbolStyleLayer extends StyleLayer {
    constructor(layer, globalState) {
        super(layer, properties$1, globalState);
    }
    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.includes(m))
                        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$1.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$1.paint.properties[propertyName];
        let hasOverrides = false;
        const checkSections = (sections) => {
            var _a;
            for (const section of sections) {
                if ((_a = property.overrides) === null || _a === void 0 ? void 0 : _a.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' || textField.value.kind === 'composite') {
            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 === null || result === void 0 ? void 0 : 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;
const getPaint = () => paint = paint || 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 = ({ get paint() { return getPaint(); } });

const isBackgroundStyleLayer = (layer) => layer.type === 'background';
class BackgroundStyleLayer extends StyleLayer {
    constructor(layer, globalState) {
        super(layer, properties, globalState);
    }
}

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;
}
const isCustomStyleLayer = (layer) => layer.type === 'custom';
class CustomStyleLayer extends StyleLayer {
    constructor(implementation, globalState) {
        super(implementation, {}, globalState);
        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, globalState) {
    if (layer.type === 'custom') {
        return new CustomStyleLayer(layer, globalState);
    }
    switch (layer.type) {
        case 'background':
            return new BackgroundStyleLayer(layer, globalState);
        case 'circle':
            return new CircleStyleLayer(layer, globalState);
        case 'color-relief':
            return new ColorReliefStyleLayer(layer, globalState);
        case 'fill':
            return new FillStyleLayer(layer, globalState);
        case 'fill-extrusion':
            return new FillExtrusionStyleLayer(layer, globalState);
        case 'heatmap':
            return new HeatmapStyleLayer(layer, globalState);
        case 'hillshade':
            return new HillshadeStyleLayer(layer, globalState);
        case 'line':
            return new LineStyleLayer(layer, globalState);
        case 'raster':
            return new RasterStyleLayer(layer, globalState);
        case 'symbol':
            return new SymbolStyleLayer(layer, globalState);
    }
}

/**
 * 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;
        this._channel = new MessageChannel();
        this._channel.port2.onmessage = () => {
            this._triggered = false;
            this._methodToThrottle();
        };
    }
    trigger() {
        var _a;
        if (this._triggered) {
            return;
        }
        this._triggered = true;
        (_a = this._channel) === null || _a === void 0 ? void 0 : _a.port1.postMessage(true);
    }
    remove() {
        delete this._channel;
        this._methodToThrottle = () => { };
    }
}

const addEventDefaultOptions = { once: true };
/**
 * 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;
    }
    unregisterMessageHandler(type) {
        delete this.messageHandlers[type];
    }
    /**
     * 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);
            const subscription = abortController ? subscribe(abortController.signal, 'abort', () => {
                subscription === null || subscription === void 0 ? void 0 : subscription.unsubscribe();
                delete this.resolveRejects[id];
                const cancelMessage = {
                    id,
                    type: '<cancel>',
                    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.
            }, addEventDefaultOptions) : null;
            this.resolveRejects[id] = {
                resolve: (value) => {
                    subscription === null || subscription === void 0 ? void 0 : subscription.unsubscribe();
                    resolve(value);
                },
                reject: (reason) => {
                    subscription === null || subscription === void 0 ? void 0 : subscription.unsubscribe();
                    reject(reason);
                }
            };
            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;
        const SPECIAL_ORIGINS = ['file://', 'resource://android', 'null'];
        const origins = [data.origin, location.origin];
        const isSameOrigin = data.origin === location.origin;
        const hasSpecialOrigin = origins.some((origin) => SPECIAL_ORIGINS.includes(origin));
        // Ignore cross-origin messages except for special origins.
        if (!isSameOrigin && !hasSpecialOrigin) {
            return;
        }
        if (data.targetMapId && this.mapId !== data.targetMapId) {
            return;
        }
        if (data.type === '<cancel>') {
            // 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,
            // <cancel> messages. Some tasks may take a while in the worker thread, so before
            // executing the next task in our queue, postMessage preempts this and <cancel>
            // 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 === '<response>') {
                // 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(ensureError(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, ensureError(err));
            }
        });
    }
    completeTask(id, err, data) {
        const buffers = [];
        delete this.abortControllers[id];
        const responseMessage = {
            id,
            type: '<response>',
            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/get-coordinates-of-the-mouse-pointer/)
 */
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);
        return earthRadius * Math.acos(Math.min(a, 1));
    }
    /**
     * 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: <lng>, lat: <lat>}, an object {lon: <lng>, lat: <lat>}, or an array of [<lng>, <lat>]');
    }
}

/*
 * 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/add-a-custom-style-layer/)
 * @see [Add a 3D model using three.js](https://maplibre.org/maplibre-gl-js/docs/examples/add-a-3d-model-using-threejs/)
 * @see [Add a simple custom layer on a globe](https://maplibre.org/maplibre-gl-js/docs/examples/add-a-simple-custom-layer-on-a-globe/)
 */
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 = calculateTileKey(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((coord.x * tilesAtZoom - this.x) * EXTENT$1, (coord.y * tilesAtZoom - this.y) * EXTENT$1);
    }
    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 = calculateTileKey(wrap, canonical.z, canonical.z, canonical.x, canonical.y);
    }
}
/**
 * An overscaled tile identifier
 */
class OverscaledTileID {
    constructor(overscaledZ, wrap, z, x, y) {
        /**
         * This matrix is used during terrain's render-to-texture stage only.
         * If the render-to-texture stage is active, this matrix will be present
         * and should be used, otherwise this matrix will be null.
         * The matrix should be float32 in order to avoid slow WebGL calls in Chrome.
         */
        this.terrainRttPosMatrix32f = null;
        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 = calculateTileKey(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);
    }
    /**
     * Returns a new `OverscaledTileID` representing the tile at the target zoom level.
     * When targetZ is greater than the current canonical z, the canonical coordinates are unchanged.
     * When targetZ is less than the current canonical z, the canonical coordinates are updated.
     * @param targetZ - the zoom level to scale to. Must be less than or equal to this.overscaledZ
     * @returns a new OverscaledTileID representing the tile at the target zoom level
     * @throws if targetZ is greater than this.overscaledZ
     */
    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);
        }
    }
    isOverscaled() {
        return (this.overscaledZ > this.canonical.z);
    }
    /*
     * 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 calculateTileKey(this.wrap * +withWrap, targetZ, this.canonical.z, this.canonical.x, this.canonical.y);
        }
        else {
            return calculateTileKey(this.wrap * +withWrap, targetZ, targetZ, this.canonical.x >> zDifference, this.canonical.y >> zDifference);
        }
    }
    isChildOf(parent) {
        if (parent.wrap !== this.wrap)
            return false; // different world copy
        const zDifference = this.overscaledZ - parent.overscaledZ;
        if (zDifference <= 0)
            return false; // must be deeper zoom
        //special case for root tile (bitwise math doesn't work for root)
        if (parent.overscaledZ === 0)
            return this.overscaledZ > 0;
        const dz = this.canonical.z - parent.canonical.z;
        if (dz < 0)
            return false; // parent can't be deeper canonically
        return (parent.canonical.x === (this.canonical.x >> dz) &&
            parent.canonical.y === (this.canonical.y >> dz));
    }
    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;
        return this.canonical.y < rhs.canonical.y;
    }
    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));
    }
    /**
     * Maps tile-local coordinates that may fall outside the `[0, extent)` range
     * to the correct neighbor tile and the corresponding in-tile position.
     *
     * Coordinates can exceed tile bounds when geometry (e.g. symbol labels along
     * lines) extends across tile edges. This method resolves such coordinates to
     * the appropriate adjacent tile, wrapping horizontally across world boundaries
     * and returning `null` when the target falls beyond the polar tile-grid limits.
     *
     * When the coordinates are already in bounds, the original tile ID is returned.
     *
     * @param x - x coordinate relative to this tile, may be outside `[0, extent)`
     * @param y - y coordinate relative to this tile, may be outside `[0, extent)`
     * @param extent - tile coordinate extent, default {@link EXTENT}
     * @returns the resolved tile ID and in-tile coordinates, or `null` if the
     *          target is beyond the tile grid (e.g. past the poles)
     */
    normalizeCoordinates(x, y, extent = EXTENT$1) {
        if (x >= 0 && x < extent && y >= 0 && y < extent) {
            return { tileID: this, x, y };
        }
        const tileOffsetX = Math.floor(x / extent);
        const tileOffsetY = Math.floor(y / extent);
        const newX = x - tileOffsetX * extent;
        const newY = y - tileOffsetY * extent;
        const z = this.canonical.z;
        const dim = 1 << z;
        const newCanonicalY = this.canonical.y + tileOffsetY;
        if (newCanonicalY < 0 || newCanonicalY >= dim)
            return null;
        let newCanonicalX = this.canonical.x + tileOffsetX;
        let newWrap = this.wrap;
        if (newCanonicalX < 0) {
            newWrap -= Math.ceil(-newCanonicalX / dim);
            newCanonicalX = ((newCanonicalX % dim) + dim) % dim;
        }
        else if (newCanonicalX >= dim) {
            newWrap += Math.floor(newCanonicalX / dim);
            newCanonicalX = newCanonicalX % dim;
        }
        return {
            tileID: new OverscaledTileID(this.overscaledZ, newWrap, z, newCanonicalX, newCanonicalY),
            x: newX,
            y: newY,
        };
    }
}
function calculateTileKey(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 = '';
    for (let i = z; i > 0; i--) {
        const mask = 1 << (i - 1);
        quadkey += ((x & mask ? 1 : 0) + (y & mask ? 2 : 0));
    }
    return quadkey;
}
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;
}
register('CanonicalTileID', CanonicalTileID);
register('OverscaledTileID', OverscaledTileID, { omit: ['terrainRttPosMatrix32f'] });

/** A 2-d bounding box covering an X and Y range. */
class Bounds {
    constructor() {
        this.minX = Infinity;
        this.maxX = -Infinity;
        this.minY = Infinity;
        this.maxY = -Infinity;
    }
    /**
     * Expands this bounding box to include point.
     *
     * @param point - The point to include in this bounding box
     * @returns This mutated bounding box
     */
    extend(point) {
        this.minX = Math.min(this.minX, point.x);
        this.minY = Math.min(this.minY, point.y);
        this.maxX = Math.max(this.maxX, point.x);
        this.maxY = Math.max(this.maxY, point.y);
        return this;
    }
    /**
     * Expands this bounding box by a fixed amount in each direction.
     *
     * @param amount - The amount to expand the box by, or contract if negative
     * @returns This mutated bounding box
     */
    expandBy(amount) {
        this.minX -= amount;
        this.minY -= amount;
        this.maxX += amount;
        this.maxY += amount;
        // check if bounds collapsed in either dimension
        if (this.minX > this.maxX || this.minY > this.maxY) {
            this.minX = Infinity;
            this.maxX = -Infinity;
            this.minY = Infinity;
            this.maxY = -Infinity;
        }
        return this;
    }
    /**
     * Shrinks this bounding box by a fixed amount in each direction.
     *
     * @param amount - The amount to shrink the box by
     * @returns This mutated bounding box
     */
    shrinkBy(amount) {
        return this.expandBy(-amount);
    }
    /**
     * Returns a new bounding box that contains all of the corners of this bounding
     * box with a transform applied. Does not modify this bounding box.
     *
     * @param fn - The function to apply to each corner
     * @returns A new bounding box containing all of the mapped points.
     */
    map(fn) {
        const result = new Bounds();
        result.extend(fn(new Point(this.minX, this.minY)));
        result.extend(fn(new Point(this.maxX, this.minY)));
        result.extend(fn(new Point(this.minX, this.maxY)));
        result.extend(fn(new Point(this.maxX, this.maxY)));
        return result;
    }
    /**
     * Creates a new bounding box that includes all points provided.
     *
     * @param points - The points to include inside the bounding box
     * @returns The new bounding box
     */
    static fromPoints(points) {
        const result = new Bounds();
        for (const p of points) {
            result.extend(p);
        }
        return result;
    }
    contains(point) {
        return point.x >= this.minX && point.x <= this.maxX && point.y >= this.minY && point.y <= this.maxY;
    }
    empty() {
        return this.minX > this.maxX;
    }
    width() {
        return this.maxX - this.minX;
    }
    height() {
        return this.maxY - this.minY;
    }
    covers(other) {
        return !this.empty() && !other.empty() &&
            other.minX >= this.minX &&
            other.maxX <= this.maxX &&
            other.minY >= this.minY &&
            other.maxY <= this.maxY;
    }
    intersects(other) {
        return !this.empty() && !other.empty() &&
            other.minX <= this.maxX &&
            other.maxX >= this.minX &&
            other.minY <= this.maxY &&
            other.maxY >= this.minY;
    }
}

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;
        this._x = x;
        this._y = y;
        this._z = z;
        this.properties = vectorTileFeature.properties;
        this.id = id;
    }
    projectPoint(p, x0, y0, size) {
        return [
            (p.x + x0) * 360 / size - 180,
            360 / Math.PI * Math.atan(Math.exp((1 - (p.y + y0) * 2 / size) * Math.PI)) - 90
        ];
    }
    projectLine(line, x0, y0, size) {
        return line.map(p => this.projectPoint(p, x0, y0, size));
    }
    get geometry() {
        if (this._geometry)
            return this._geometry;
        const feature = this._vectorTileFeature;
        // Copied from https://github.com/mapbox/vector-tile-js/blob/f1457ee47d0a261e6246d68c959fbd12bf56aeeb/index.js
        const size = feature.extent * Math.pow(2, this._z);
        const x0 = feature.extent * this._x;
        const y0 = feature.extent * this._y;
        const vtCoords = feature.loadGeometry();
        switch (feature.type) {
            case 1: {
                const points = [];
                for (const line of vtCoords) {
                    points.push(line[0]);
                }
                const coordinates = this.projectLine(points, x0, y0, size);
                this._geometry = points.length === 1 ?
                    { type: 'Point', coordinates: coordinates[0] } :
                    { type: 'MultiPoint', coordinates };
                break;
            }
            case 2: {
                const coordinates = vtCoords.map(coord => this.projectLine(coord, x0, y0, size));
                this._geometry = coordinates.length === 1 ?
                    { type: 'LineString', coordinates: coordinates[0] } :
                    { type: 'MultiLineString', coordinates };
                break;
            }
            case 3: {
                const polygons = classifyRings(vtCoords);
                const coordinates = [];
                for (const polygon of polygons) {
                    coordinates.push(polygon.map(coord => this.projectLine(coord, x0, y0, size)));
                }
                this._geometry = coordinates.length === 1 ?
                    { type: 'Polygon', coordinates: coordinates[0] } :
                    { type: 'MultiPolygon', coordinates };
                break;
            }
            default:
                throw new Error(`unknown feature type: ${feature.type}`);
        }
        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' || i === '_x' || i === '_y' || i === '_z')
                continue;
            json[i] = (this)[i];
        }
        return json;
    }
}

class Vector {
    constructor(_name, dataBuffer, sizeOrNullabilityBuffer) {
        this._name = _name;
        this.dataBuffer = dataBuffer;
        if (typeof sizeOrNullabilityBuffer === "number") {
            this._size = sizeOrNullabilityBuffer;
        }
        else {
            this.nullabilityBuffer = sizeOrNullabilityBuffer;
            this._size = sizeOrNullabilityBuffer.size();
        }
    }
    getValue(index) {
        return this.nullabilityBuffer && !this.nullabilityBuffer.get(index) ? null : this.getValueFromBuffer(index);
    }
    has(index) {
        return this.nullabilityBuffer?.get(index) || !this.nullabilityBuffer;
    }
    get name() {
        return this._name;
    }
    get size() {
        return this._size;
    }
}

class FixedSizeVector extends Vector {
}

class Int32FlatVector extends FixedSizeVector {
    getValueFromBuffer(index) {
        return this.dataBuffer[index];
    }
}

class DoubleFlatVector extends FixedSizeVector {
    getValueFromBuffer(index) {
        return this.dataBuffer[index];
    }
}

class SequenceVector extends Vector {
    constructor(name, baseValueBuffer, delta, size) {
        super(name, baseValueBuffer, size);
        this.delta = delta;
    }
}

class Int32SequenceVector extends SequenceVector {
    constructor(name, baseValue, delta, size) {
        super(name, Int32Array.of(baseValue), delta, size);
    }
    getValueFromBuffer(index) {
        return this.dataBuffer[0] + index * this.delta;
    }
}

class Int32ConstVector extends Vector {
    constructor(name, value, sizeOrNullabilityBuffer, isSigned) {
        super(name, isSigned ? Int32Array.of(value) : Uint32Array.of(value), sizeOrNullabilityBuffer);
    }
    getValueFromBuffer(_index) {
        return this.dataBuffer[0];
    }
}

class FeatureTable {
    constructor(_name, _geometryVector, _idVector, _propertyVectors, _extent = 4096) {
        this._name = _name;
        this._geometryVector = _geometryVector;
        this._idVector = _idVector;
        this._propertyVectors = _propertyVectors;
        this._extent = _extent;
    }
    get name() {
        return this._name;
    }
    get idVector() {
        return this._idVector;
    }
    get geometryVector() {
        return this._geometryVector;
    }
    get propertyVectors() {
        return this._propertyVectors;
    }
    getPropertyVector(name) {
        if (!this.propertyVectorsMap) {
            this.propertyVectorsMap = new Map(this._propertyVectors.map((vector) => [vector.name, vector]));
        }
        return this.propertyVectorsMap.get(name);
    }
    get numFeatures() {
        return this.geometryVector.numGeometries;
    }
    get extent() {
        return this._extent;
    }
    /**
     * Returns all features as an array
     */
    getFeatures() {
        const features = [];
        const geometries = this.geometryVector.getGeometries();
        for (let i = 0; i < this.numFeatures; i++) {
            let id;
            if (this.idVector) {
                const idValue = this.idVector.getValue(i);
                id = this.containsMaxSafeIntegerValues(this.idVector) && idValue !== null ? Number(idValue) : idValue;
            }
            const geometry = {
                coordinates: geometries[i],
                type: this.geometryVector.geometryType(i),
            };
            const properties = {};
            for (const propertyColumn of this.propertyVectors) {
                if (!propertyColumn)
                    continue;
                const columnName = propertyColumn.name;
                const propertyValue = propertyColumn.getValue(i);
                if (propertyValue !== null) {
                    properties[columnName] = propertyValue;
                }
            }
            features.push({ id, geometry, properties });
        }
        return features;
    }
    containsMaxSafeIntegerValues(idVector) {
        return (idVector instanceof Int32FlatVector ||
            idVector instanceof Int32ConstVector ||
            idVector instanceof Int32SequenceVector ||
            idVector instanceof DoubleFlatVector);
    }
}

// based on ../spec/schema/mlt_tileset_metadata.proto
const ColumnScope = {
    FEATURE: 0,
    VERTEX: 1,
};
const ScalarType = {
    BOOLEAN: 0,
    INT_8: 1,
    UINT_8: 2,
    INT_32: 3,
    UINT_32: 4,
    INT_64: 5,
    UINT_64: 6,
    FLOAT: 7,
    DOUBLE: 8,
    STRING: 9,
};
const ComplexType = {
    GEOMETRY: 0,
    STRUCT: 1,
};
const LogicalScalarType = {
    ID: 0,
};
const LogicalComplexType = {
    BINARY: 0,
    RANGE_MAP: 1,
};

// Ported from https://github.com/lemire/JavaFastPFOR/blob/master/src/main/java/me/lemire/integercompression/IntWrapper.java
class IntWrapper {
    constructor(value) {
        this.value = value;
    }
    get() {
        return this.value;
    }
    set(v) {
        this.value = v;
    }
    increment() {
        return this.value++;
    }
    add(v) {
        this.value += v;
    }
}

var LogicalLevelTechnique;
(function (LogicalLevelTechnique) {
    LogicalLevelTechnique["NONE"] = "NONE";
    LogicalLevelTechnique["DELTA"] = "DELTA";
    LogicalLevelTechnique["COMPONENTWISE_DELTA"] = "COMPONENTWISE_DELTA";
    LogicalLevelTechnique["RLE"] = "RLE";
    LogicalLevelTechnique["MORTON"] = "MORTON";
    // Pseudodecimal Encoding of floats -> only for the exponent integer part an additional logical level technique is used.
    // Both exponent and significant parts are encoded with the same physical level technique
    LogicalLevelTechnique["PDE"] = "PDE";
})(LogicalLevelTechnique || (LogicalLevelTechnique = {}));

var PhysicalLevelTechnique;
(function (PhysicalLevelTechnique) {
    PhysicalLevelTechnique["NONE"] = "NONE";
    /**
     * Preferred option, tends to produce the best compression ratio and decoding performance.
     * But currently only limited to 32 bit integer.
     */
    PhysicalLevelTechnique["FAST_PFOR"] = "FAST_PFOR";
    /**
     * Can produce better results in combination with a heavyweight compression scheme like Gzip.
     * Simple compression scheme where the decoder are easier to implement compared to FastPfor.
     */
    PhysicalLevelTechnique["VARINT"] = "VARINT";
    /**
     * Adaptive Lossless floating-Point Compression
     */
    PhysicalLevelTechnique["ALP"] = "ALP";
})(PhysicalLevelTechnique || (PhysicalLevelTechnique = {}));

/**
 * Bit masks for each bitwidth 0-32.
 * DO NOT MUTATE - this is a shared constant.
 */
const masks = new Uint32Array(33);
masks[0] = 0;
for (let bitWidth = 1; bitWidth <= 32; bitWidth++) {
    masks[bitWidth] = bitWidth === 32 ? 0xffffffff : 0xffffffff >>> (32 - bitWidth);
}
const MASKS = masks;
const DEFAULT_PAGE_SIZE = 65536;
const BLOCK_SIZE = 256;
function greatestMultiple(value, factor) {
    return value - (value % factor);
}
function roundUpToMultipleOf32(value) {
    return greatestMultiple(value + 31, 32);
}
function normalizePageSize(pageSize) {
    if (!Number.isFinite(pageSize) || pageSize <= 0)
        return DEFAULT_PAGE_SIZE;
    const aligned = greatestMultiple(Math.floor(pageSize), BLOCK_SIZE);
    return aligned === 0 ? BLOCK_SIZE : aligned;
}
function bswap32(value) {
    const x = value >>> 0;
    return (((x & 0xff) << 24) | ((x & 0xff00) << 8) | ((x >>> 8) & 0xff00) | ((x >>> 24) & 0xff)) >>> 0;
}

function fastUnpack32_1(inValues, inPos, out, outPos) {
    const in0 = inValues[inPos] >>> 0;
    for (let i = 0; i < 32; i++) {
        out[outPos + i] = (in0 >>> i) & 1;
    }
}
function fastUnpack32_2(inValues, inPos, out, outPos) {
    let op = outPos;
    const in0 = inValues[inPos] >>> 0;
    const in1 = inValues[inPos + 1] >>> 0;
    out[op++] = (in0 >>> 0) & 0x3;
    out[op++] = (in0 >>> 2) & 0x3;
    out[op++] = (in0 >>> 4) & 0x3;
    out[op++] = (in0 >>> 6) & 0x3;
    out[op++] = (in0 >>> 8) & 0x3;
    out[op++] = (in0 >>> 10) & 0x3;
    out[op++] = (in0 >>> 12) & 0x3;
    out[op++] = (in0 >>> 14) & 0x3;
    out[op++] = (in0 >>> 16) & 0x3;
    out[op++] = (in0 >>> 18) & 0x3;
    out[op++] = (in0 >>> 20) & 0x3;
    out[op++] = (in0 >>> 22) & 0x3;
    out[op++] = (in0 >>> 24) & 0x3;
    out[op++] = (in0 >>> 26) & 0x3;
    out[op++] = (in0 >>> 28) & 0x3;
    out[op++] = (in0 >>> 30) & 0x3;
    out[op++] = (in1 >>> 0) & 0x3;
    out[op++] = (in1 >>> 2) & 0x3;
    out[op++] = (in1 >>> 4) & 0x3;
    out[op++] = (in1 >>> 6) & 0x3;
    out[op++] = (in1 >>> 8) & 0x3;
    out[op++] = (in1 >>> 10) & 0x3;
    out[op++] = (in1 >>> 12) & 0x3;
    out[op++] = (in1 >>> 14) & 0x3;
    out[op++] = (in1 >>> 16) & 0x3;
    out[op++] = (in1 >>> 18) & 0x3;
    out[op++] = (in1 >>> 20) & 0x3;
    out[op++] = (in1 >>> 22) & 0x3;
    out[op++] = (in1 >>> 24) & 0x3;
    out[op++] = (in1 >>> 26) & 0x3;
    out[op++] = (in1 >>> 28) & 0x3;
    out[op] = (in1 >>> 30) & 0x3;
}
function fastUnpack32_3(inValues, inPos, out, outPos) {
    let op = outPos;
    const in0 = inValues[inPos] >>> 0;
    const in1 = inValues[inPos + 1] >>> 0;
    const in2 = inValues[inPos + 2] >>> 0;
    out[op++] = (in0 >>> 0) & 0x7;
    out[op++] = (in0 >>> 3) & 0x7;
    out[op++] = (in0 >>> 6) & 0x7;
    out[op++] = (in0 >>> 9) & 0x7;
    out[op++] = (in0 >>> 12) & 0x7;
    out[op++] = (in0 >>> 15) & 0x7;
    out[op++] = (in0 >>> 18) & 0x7;
    out[op++] = (in0 >>> 21) & 0x7;
    out[op++] = (in0 >>> 24) & 0x7;
    out[op++] = (in0 >>> 27) & 0x7;
    out[op++] = ((in0 >>> 30) | ((in1 & 0x1) << 2)) & 0x7;
    out[op++] = (in1 >>> 1) & 0x7;
    out[op++] = (in1 >>> 4) & 0x7;
    out[op++] = (in1 >>> 7) & 0x7;
    out[op++] = (in1 >>> 10) & 0x7;
    out[op++] = (in1 >>> 13) & 0x7;
    out[op++] = (in1 >>> 16) & 0x7;
    out[op++] = (in1 >>> 19) & 0x7;
    out[op++] = (in1 >>> 22) & 0x7;
    out[op++] = (in1 >>> 25) & 0x7;
    out[op++] = (in1 >>> 28) & 0x7;
    out[op++] = ((in1 >>> 31) | ((in2 & 0x3) << 1)) & 0x7;
    out[op++] = (in2 >>> 2) & 0x7;
    out[op++] = (in2 >>> 5) & 0x7;
    out[op++] = (in2 >>> 8) & 0x7;
    out[op++] = (in2 >>> 11) & 0x7;
    out[op++] = (in2 >>> 14) & 0x7;
    out[op++] = (in2 >>> 17) & 0x7;
    out[op++] = (in2 >>> 20) & 0x7;
    out[op++] = (in2 >>> 23) & 0x7;
    out[op++] = (in2 >>> 26) & 0x7;
    out[op] = (in2 >>> 29) & 0x7;
}
function fastUnpack32_4(inValues, inPos, out, outPos) {
    let op = outPos;
    const in0 = inValues[inPos] >>> 0;
    const in1 = inValues[inPos + 1] >>> 0;
    const in2 = inValues[inPos + 2] >>> 0;
    const in3 = inValues[inPos + 3] >>> 0;
    out[op++] = (in0 >>> 0) & 0xf;
    out[op++] = (in0 >>> 4) & 0xf;
    out[op++] = (in0 >>> 8) & 0xf;
    out[op++] = (in0 >>> 12) & 0xf;
    out[op++] = (in0 >>> 16) & 0xf;
    out[op++] = (in0 >>> 20) & 0xf;
    out[op++] = (in0 >>> 24) & 0xf;
    out[op++] = (in0 >>> 28) & 0xf;
    out[op++] = (in1 >>> 0) & 0xf;
    out[op++] = (in1 >>> 4) & 0xf;
    out[op++] = (in1 >>> 8) & 0xf;
    out[op++] = (in1 >>> 12) & 0xf;
    out[op++] = (in1 >>> 16) & 0xf;
    out[op++] = (in1 >>> 20) & 0xf;
    out[op++] = (in1 >>> 24) & 0xf;
    out[op++] = (in1 >>> 28) & 0xf;
    out[op++] = (in2 >>> 0) & 0xf;
    out[op++] = (in2 >>> 4) & 0xf;
    out[op++] = (in2 >>> 8) & 0xf;
    out[op++] = (in2 >>> 12) & 0xf;
    out[op++] = (in2 >>> 16) & 0xf;
    out[op++] = (in2 >>> 20) & 0xf;
    out[op++] = (in2 >>> 24) & 0xf;
    out[op++] = (in2 >>> 28) & 0xf;
    out[op++] = (in3 >>> 0) & 0xf;
    out[op++] = (in3 >>> 4) & 0xf;
    out[op++] = (in3 >>> 8) & 0xf;
    out[op++] = (in3 >>> 12) & 0xf;
    out[op++] = (in3 >>> 16) & 0xf;
    out[op++] = (in3 >>> 20) & 0xf;
    out[op++] = (in3 >>> 24) & 0xf;
    out[op] = (in3 >>> 28) & 0xf;
}
function fastUnpack32_5(inValues, inPos, out, outPos) {
    let op = outPos;
    const in0 = inValues[inPos] >>> 0;
    const in1 = inValues[inPos + 1] >>> 0;
    const in2 = inValues[inPos + 2] >>> 0;
    const in3 = inValues[inPos + 3] >>> 0;
    const in4 = inValues[inPos + 4] >>> 0;
    out[op++] = (in0 >>> 0) & 0x1f;
    out[op++] = (in0 >>> 5) & 0x1f;
    out[op++] = (in0 >>> 10) & 0x1f;
    out[op++] = (in0 >>> 15) & 0x1f;
    out[op++] = (in0 >>> 20) & 0x1f;
    out[op++] = (in0 >>> 25) & 0x1f;
    out[op++] = ((in0 >>> 30) | ((in1 & 0x7) << 2)) & 0x1f;
    out[op++] = (in1 >>> 3) & 0x1f;
    out[op++] = (in1 >>> 8) & 0x1f;
    out[op++] = (in1 >>> 13) & 0x1f;
    out[op++] = (in1 >>> 18) & 0x1f;
    out[op++] = (in1 >>> 23) & 0x1f;
    out[op++] = ((in1 >>> 28) | ((in2 & 0x1) << 4)) & 0x1f;
    out[op++] = (in2 >>> 1) & 0x1f;
    out[op++] = (in2 >>> 6) & 0x1f;
    out[op++] = (in2 >>> 11) & 0x1f;
    out[op++] = (in2 >>> 16) & 0x1f;
    out[op++] = (in2 >>> 21) & 0x1f;
    out[op++] = (in2 >>> 26) & 0x1f;
    out[op++] = ((in2 >>> 31) | ((in3 & 0xf) << 1)) & 0x1f;
    out[op++] = (in3 >>> 4) & 0x1f;
    out[op++] = (in3 >>> 9) & 0x1f;
    out[op++] = (in3 >>> 14) & 0x1f;
    out[op++] = (in3 >>> 19) & 0x1f;
    out[op++] = (in3 >>> 24) & 0x1f;
    out[op++] = ((in3 >>> 29) | ((in4 & 0x3) << 3)) & 0x1f;
    out[op++] = (in4 >>> 2) & 0x1f;
    out[op++] = (in4 >>> 7) & 0x1f;
    out[op++] = (in4 >>> 12) & 0x1f;
    out[op++] = (in4 >>> 17) & 0x1f;
    out[op++] = (in4 >>> 22) & 0x1f;
    out[op] = (in4 >>> 27) & 0x1f;
}
function fastUnpack32_6(inValues, inPos, out, outPos) {
    let op = outPos;
    const in0 = inValues[inPos] >>> 0;
    const in1 = inValues[inPos + 1] >>> 0;
    const in2 = inValues[inPos + 2] >>> 0;
    const in3 = inValues[inPos + 3] >>> 0;
    const in4 = inValues[inPos + 4] >>> 0;
    const in5 = inValues[inPos + 5] >>> 0;
    out[op++] = (in0 >>> 0) & 0x3f;
    out[op++] = (in0 >>> 6) & 0x3f;
    out[op++] = (in0 >>> 12) & 0x3f;
    out[op++] = (in0 >>> 18) & 0x3f;
    out[op++] = (in0 >>> 24) & 0x3f;
    out[op++] = ((in0 >>> 30) | ((in1 & 0xf) << 2)) & 0x3f;
    out[op++] = (in1 >>> 4) & 0x3f;
    out[op++] = (in1 >>> 10) & 0x3f;
    out[op++] = (in1 >>> 16) & 0x3f;
    out[op++] = (in1 >>> 22) & 0x3f;
    out[op++] = ((in1 >>> 28) | ((in2 & 0x3) << 4)) & 0x3f;
    out[op++] = (in2 >>> 2) & 0x3f;
    out[op++] = (in2 >>> 8) & 0x3f;
    out[op++] = (in2 >>> 14) & 0x3f;
    out[op++] = (in2 >>> 20) & 0x3f;
    out[op++] = (in2 >>> 26) & 0x3f;
    out[op++] = (in3 >>> 0) & 0x3f;
    out[op++] = (in3 >>> 6) & 0x3f;
    out[op++] = (in3 >>> 12) & 0x3f;
    out[op++] = (in3 >>> 18) & 0x3f;
    out[op++] = (in3 >>> 24) & 0x3f;
    out[op++] = ((in3 >>> 30) | ((in4 & 0xf) << 2)) & 0x3f;
    out[op++] = (in4 >>> 4) & 0x3f;
    out[op++] = (in4 >>> 10) & 0x3f;
    out[op++] = (in4 >>> 16) & 0x3f;
    out[op++] = (in4 >>> 22) & 0x3f;
    out[op++] = ((in4 >>> 28) | ((in5 & 0x3) << 4)) & 0x3f;
    out[op++] = (in5 >>> 2) & 0x3f;
    out[op++] = (in5 >>> 8) & 0x3f;
    out[op++] = (in5 >>> 14) & 0x3f;
    out[op++] = (in5 >>> 20) & 0x3f;
    out[op] = (in5 >>> 26) & 0x3f;
}
function fastUnpack32_7(inValues, inPos, out, outPos) {
    let op = outPos;
    const in0 = inValues[inPos] >>> 0;
    const in1 = inValues[inPos + 1] >>> 0;
    const in2 = inValues[inPos + 2] >>> 0;
    const in3 = inValues[inPos + 3] >>> 0;
    const in4 = inValues[inPos + 4] >>> 0;
    const in5 = inValues[inPos + 5] >>> 0;
    const in6 = inValues[inPos + 6] >>> 0;
    out[op++] = (in0 >>> 0) & 0x7f;
    out[op++] = (in0 >>> 7) & 0x7f;
    out[op++] = (in0 >>> 14) & 0x7f;
    out[op++] = (in0 >>> 21) & 0x7f;
    out[op++] = ((in0 >>> 28) | ((in1 & 0x7) << 4)) & 0x7f;
    out[op++] = (in1 >>> 3) & 0x7f;
    out[op++] = (in1 >>> 10) & 0x7f;
    out[op++] = (in1 >>> 17) & 0x7f;
    out[op++] = (in1 >>> 24) & 0x7f;
    out[op++] = ((in1 >>> 31) | ((in2 & 0x3f) << 1)) & 0x7f;
    out[op++] = (in2 >>> 6) & 0x7f;
    out[op++] = (in2 >>> 13) & 0x7f;
    out[op++] = (in2 >>> 20) & 0x7f;
    out[op++] = ((in2 >>> 27) | ((in3 & 0x3) << 5)) & 0x7f;
    out[op++] = (in3 >>> 2) & 0x7f;
    out[op++] = (in3 >>> 9) & 0x7f;
    out[op++] = (in3 >>> 16) & 0x7f;
    out[op++] = (in3 >>> 23) & 0x7f;
    out[op++] = ((in3 >>> 30) | ((in4 & 0x1f) << 2)) & 0x7f;
    out[op++] = (in4 >>> 5) & 0x7f;
    out[op++] = (in4 >>> 12) & 0x7f;
    out[op++] = (in4 >>> 19) & 0x7f;
    out[op++] = ((in4 >>> 26) | ((in5 & 0x1) << 6)) & 0x7f;
    out[op++] = (in5 >>> 1) & 0x7f;
    out[op++] = (in5 >>> 8) & 0x7f;
    out[op++] = (in5 >>> 15) & 0x7f;
    out[op++] = (in5 >>> 22) & 0x7f;
    out[op++] = ((in5 >>> 29) | ((in6 & 0xf) << 3)) & 0x7f;
    out[op++] = (in6 >>> 4) & 0x7f;
    out[op++] = (in6 >>> 11) & 0x7f;
    out[op++] = (in6 >>> 18) & 0x7f;
    out[op] = (in6 >>> 25) & 0x7f;
}
function fastUnpack32_8(inValues, inPos, out, outPos) {
    let op = outPos;
    const in0 = inValues[inPos] >>> 0;
    const in1 = inValues[inPos + 1] >>> 0;
    const in2 = inValues[inPos + 2] >>> 0;
    const in3 = inValues[inPos + 3] >>> 0;
    const in4 = inValues[inPos + 4] >>> 0;
    const in5 = inValues[inPos + 5] >>> 0;
    const in6 = inValues[inPos + 6] >>> 0;
    const in7 = inValues[inPos + 7] >>> 0;
    out[op++] = (in0 >>> 0) & 0xff;
    out[op++] = (in0 >>> 8) & 0xff;
    out[op++] = (in0 >>> 16) & 0xff;
    out[op++] = (in0 >>> 24) & 0xff;
    out[op++] = (in1 >>> 0) & 0xff;
    out[op++] = (in1 >>> 8) & 0xff;
    out[op++] = (in1 >>> 16) & 0xff;
    out[op++] = (in1 >>> 24) & 0xff;
    out[op++] = (in2 >>> 0) & 0xff;
    out[op++] = (in2 >>> 8) & 0xff;
    out[op++] = (in2 >>> 16) & 0xff;
    out[op++] = (in2 >>> 24) & 0xff;
    out[op++] = (in3 >>> 0) & 0xff;
    out[op++] = (in3 >>> 8) & 0xff;
    out[op++] = (in3 >>> 16) & 0xff;
    out[op++] = (in3 >>> 24) & 0xff;
    out[op++] = (in4 >>> 0) & 0xff;
    out[op++] = (in4 >>> 8) & 0xff;
    out[op++] = (in4 >>> 16) & 0xff;
    out[op++] = (in4 >>> 24) & 0xff;
    out[op++] = (in5 >>> 0) & 0xff;
    out[op++] = (in5 >>> 8) & 0xff;
    out[op++] = (in5 >>> 16) & 0xff;
    out[op++] = (in5 >>> 24) & 0xff;
    out[op++] = (in6 >>> 0) & 0xff;
    out[op++] = (in6 >>> 8) & 0xff;
    out[op++] = (in6 >>> 16) & 0xff;
    out[op++] = (in6 >>> 24) & 0xff;
    out[op++] = (in7 >>> 0) & 0xff;
    out[op++] = (in7 >>> 8) & 0xff;
    out[op++] = (in7 >>> 16) & 0xff;
    out[op] = (in7 >>> 24) & 0xff;
}
function fastUnpack32_9(inValues, inPos, out, outPos) {
    let op = outPos;
    const in0 = inValues[inPos] >>> 0;
    const in1 = inValues[inPos + 1] >>> 0;
    const in2 = inValues[inPos + 2] >>> 0;
    const in3 = inValues[inPos + 3] >>> 0;
    const in4 = inValues[inPos + 4] >>> 0;
    const in5 = inValues[inPos + 5] >>> 0;
    const in6 = inValues[inPos + 6] >>> 0;
    const in7 = inValues[inPos + 7] >>> 0;
    const in8 = inValues[inPos + 8] >>> 0;
    out[op++] = (in0 >>> 0) & 0x1ff;
    out[op++] = (in0 >>> 9) & 0x1ff;
    out[op++] = (in0 >>> 18) & 0x1ff;
    out[op++] = ((in0 >>> 27) | ((in1 & 0xf) << 5)) & 0x1ff;
    out[op++] = (in1 >>> 4) & 0x1ff;
    out[op++] = (in1 >>> 13) & 0x1ff;
    out[op++] = (in1 >>> 22) & 0x1ff;
    out[op++] = ((in1 >>> 31) | ((in2 & 0xff) << 1)) & 0x1ff;
    out[op++] = (in2 >>> 8) & 0x1ff;
    out[op++] = (in2 >>> 17) & 0x1ff;
    out[op++] = ((in2 >>> 26) | ((in3 & 0x7) << 6)) & 0x1ff;
    out[op++] = (in3 >>> 3) & 0x1ff;
    out[op++] = (in3 >>> 12) & 0x1ff;
    out[op++] = (in3 >>> 21) & 0x1ff;
    out[op++] = ((in3 >>> 30) | ((in4 & 0x7f) << 2)) & 0x1ff;
    out[op++] = (in4 >>> 7) & 0x1ff;
    out[op++] = (in4 >>> 16) & 0x1ff;
    out[op++] = ((in4 >>> 25) | ((in5 & 0x3) << 7)) & 0x1ff;
    out[op++] = (in5 >>> 2) & 0x1ff;
    out[op++] = (in5 >>> 11) & 0x1ff;
    out[op++] = (in5 >>> 20) & 0x1ff;
    out[op++] = ((in5 >>> 29) | ((in6 & 0x3f) << 3)) & 0x1ff;
    out[op++] = (in6 >>> 6) & 0x1ff;
    out[op++] = (in6 >>> 15) & 0x1ff;
    out[op++] = ((in6 >>> 24) | ((in7 & 0x1) << 8)) & 0x1ff;
    out[op++] = (in7 >>> 1) & 0x1ff;
    out[op++] = (in7 >>> 10) & 0x1ff;
    out[op++] = (in7 >>> 19) & 0x1ff;
    out[op++] = ((in7 >>> 28) | ((in8 & 0x1f) << 4)) & 0x1ff;
    out[op++] = (in8 >>> 5) & 0x1ff;
    out[op++] = (in8 >>> 14) & 0x1ff;
    out[op] = (in8 >>> 23) & 0x1ff;
}
function fastUnpack32_10(inValues, inPos, out, outPos) {
    let op = outPos;
    const in0 = inValues[inPos] >>> 0;
    const in1 = inValues[inPos + 1] >>> 0;
    const in2 = inValues[inPos + 2] >>> 0;
    const in3 = inValues[inPos + 3] >>> 0;
    const in4 = inValues[inPos + 4] >>> 0;
    const in5 = inValues[inPos + 5] >>> 0;
    const in6 = inValues[inPos + 6] >>> 0;
    const in7 = inValues[inPos + 7] >>> 0;
    const in8 = inValues[inPos + 8] >>> 0;
    const in9 = inValues[inPos + 9] >>> 0;
    out[op++] = (in0 >>> 0) & 0x3ff;
    out[op++] = (in0 >>> 10) & 0x3ff;
    out[op++] = (in0 >>> 20) & 0x3ff;
    out[op++] = ((in0 >>> 30) | ((in1 & 0xff) << 2)) & 0x3ff;
    out[op++] = (in1 >>> 8) & 0x3ff;
    out[op++] = (in1 >>> 18) & 0x3ff;
    out[op++] = ((in1 >>> 28) | ((in2 & 0x3f) << 4)) & 0x3ff;
    out[op++] = (in2 >>> 6) & 0x3ff;
    out[op++] = (in2 >>> 16) & 0x3ff;
    out[op++] = ((in2 >>> 26) | ((in3 & 0xf) << 6)) & 0x3ff;
    out[op++] = (in3 >>> 4) & 0x3ff;
    out[op++] = (in3 >>> 14) & 0x3ff;
    out[op++] = ((in3 >>> 24) | ((in4 & 0x3) << 8)) & 0x3ff;
    out[op++] = (in4 >>> 2) & 0x3ff;
    out[op++] = (in4 >>> 12) & 0x3ff;
    out[op++] = (in4 >>> 22) & 0x3ff;
    out[op++] = (in5 >>> 0) & 0x3ff;
    out[op++] = (in5 >>> 10) & 0x3ff;
    out[op++] = (in5 >>> 20) & 0x3ff;
    out[op++] = ((in5 >>> 30) | ((in6 & 0xff) << 2)) & 0x3ff;
    out[op++] = (in6 >>> 8) & 0x3ff;
    out[op++] = (in6 >>> 18) & 0x3ff;
    out[op++] = ((in6 >>> 28) | ((in7 & 0x3f) << 4)) & 0x3ff;
    out[op++] = (in7 >>> 6) & 0x3ff;
    out[op++] = (in7 >>> 16) & 0x3ff;
    out[op++] = ((in7 >>> 26) | ((in8 & 0xf) << 6)) & 0x3ff;
    out[op++] = (in8 >>> 4) & 0x3ff;
    out[op++] = (in8 >>> 14) & 0x3ff;
    out[op++] = ((in8 >>> 24) | ((in9 & 0x3) << 8)) & 0x3ff;
    out[op++] = (in9 >>> 2) & 0x3ff;
    out[op++] = (in9 >>> 12) & 0x3ff;
    out[op] = (in9 >>> 22) & 0x3ff;
}
function fastUnpack32_11(inValues, inPos, out, outPos) {
    let op = outPos;
    const in0 = inValues[inPos] >>> 0;
    const in1 = inValues[inPos + 1] >>> 0;
    const in2 = inValues[inPos + 2] >>> 0;
    const in3 = inValues[inPos + 3] >>> 0;
    const in4 = inValues[inPos + 4] >>> 0;
    const in5 = inValues[inPos + 5] >>> 0;
    const in6 = inValues[inPos + 6] >>> 0;
    const in7 = inValues[inPos + 7] >>> 0;
    const in8 = inValues[inPos + 8] >>> 0;
    const in9 = inValues[inPos + 9] >>> 0;
    const in10 = inValues[inPos + 10] >>> 0;
    out[op++] = (in0 >>> 0) & 0x7ff;
    out[op++] = (in0 >>> 11) & 0x7ff;
    out[op++] = ((in0 >>> 22) | ((in1 & 0x1) << 10)) & 0x7ff;
    out[op++] = (in1 >>> 1) & 0x7ff;
    out[op++] = (in1 >>> 12) & 0x7ff;
    out[op++] = ((in1 >>> 23) | ((in2 & 0x3) << 9)) & 0x7ff;
    out[op++] = (in2 >>> 2) & 0x7ff;
    out[op++] = (in2 >>> 13) & 0x7ff;
    out[op++] = ((in2 >>> 24) | ((in3 & 0x7) << 8)) & 0x7ff;
    out[op++] = (in3 >>> 3) & 0x7ff;
    out[op++] = (in3 >>> 14) & 0x7ff;
    out[op++] = ((in3 >>> 25) | ((in4 & 0xf) << 7)) & 0x7ff;
    out[op++] = (in4 >>> 4) & 0x7ff;
    out[op++] = (in4 >>> 15) & 0x7ff;
    out[op++] = ((in4 >>> 26) | ((in5 & 0x1f) << 6)) & 0x7ff;
    out[op++] = (in5 >>> 5) & 0x7ff;
    out[op++] = (in5 >>> 16) & 0x7ff;
    out[op++] = ((in5 >>> 27) | ((in6 & 0x3f) << 5)) & 0x7ff;
    out[op++] = (in6 >>> 6) & 0x7ff;
    out[op++] = (in6 >>> 17) & 0x7ff;
    out[op++] = ((in6 >>> 28) | ((in7 & 0x7f) << 4)) & 0x7ff;
    out[op++] = (in7 >>> 7) & 0x7ff;
    out[op++] = (in7 >>> 18) & 0x7ff;
    out[op++] = ((in7 >>> 29) | ((in8 & 0xff) << 3)) & 0x7ff;
    out[op++] = (in8 >>> 8) & 0x7ff;
    out[op++] = (in8 >>> 19) & 0x7ff;
    out[op++] = ((in8 >>> 30) | ((in9 & 0x1ff) << 2)) & 0x7ff;
    out[op++] = (in9 >>> 9) & 0x7ff;
    out[op++] = (in9 >>> 20) & 0x7ff;
    out[op++] = ((in9 >>> 31) | ((in10 & 0x3ff) << 1)) & 0x7ff;
    out[op++] = (in10 >>> 10) & 0x7ff;
    out[op] = (in10 >>> 21) & 0x7ff;
}
function fastUnpack32_12(inValues, inPos, out, outPos) {
    let op = outPos;
    const in0 = inValues[inPos] >>> 0;
    const in1 = inValues[inPos + 1] >>> 0;
    const in2 = inValues[inPos + 2] >>> 0;
    const in3 = inValues[inPos + 3] >>> 0;
    const in4 = inValues[inPos + 4] >>> 0;
    const in5 = inValues[inPos + 5] >>> 0;
    const in6 = inValues[inPos + 6] >>> 0;
    const in7 = inValues[inPos + 7] >>> 0;
    const in8 = inValues[inPos + 8] >>> 0;
    const in9 = inValues[inPos + 9] >>> 0;
    const in10 = inValues[inPos + 10] >>> 0;
    const in11 = inValues[inPos + 11] >>> 0;
    out[op++] = (in0 >>> 0) & 0xfff;
    out[op++] = (in0 >>> 12) & 0xfff;
    out[op++] = ((in0 >>> 24) | ((in1 & 0xf) << 8)) & 0xfff;
    out[op++] = (in1 >>> 4) & 0xfff;
    out[op++] = (in1 >>> 16) & 0xfff;
    out[op++] = ((in1 >>> 28) | ((in2 & 0xff) << 4)) & 0xfff;
    out[op++] = (in2 >>> 8) & 0xfff;
    out[op++] = (in2 >>> 20) & 0xfff;
    out[op++] = (in3 >>> 0) & 0xfff;
    out[op++] = (in3 >>> 12) & 0xfff;
    out[op++] = ((in3 >>> 24) | ((in4 & 0xf) << 8)) & 0xfff;
    out[op++] = (in4 >>> 4) & 0xfff;
    out[op++] = (in4 >>> 16) & 0xfff;
    out[op++] = ((in4 >>> 28) | ((in5 & 0xff) << 4)) & 0xfff;
    out[op++] = (in5 >>> 8) & 0xfff;
    out[op++] = (in5 >>> 20) & 0xfff;
    out[op++] = (in6 >>> 0) & 0xfff;
    out[op++] = (in6 >>> 12) & 0xfff;
    out[op++] = ((in6 >>> 24) | ((in7 & 0xf) << 8)) & 0xfff;
    out[op++] = (in7 >>> 4) & 0xfff;
    out[op++] = (in7 >>> 16) & 0xfff;
    out[op++] = ((in7 >>> 28) | ((in8 & 0xff) << 4)) & 0xfff;
    out[op++] = (in8 >>> 8) & 0xfff;
    out[op++] = (in8 >>> 20) & 0xfff;
    out[op++] = (in9 >>> 0) & 0xfff;
    out[op++] = (in9 >>> 12) & 0xfff;
    out[op++] = ((in9 >>> 24) | ((in10 & 0xf) << 8)) & 0xfff;
    out[op++] = (in10 >>> 4) & 0xfff;
    out[op++] = (in10 >>> 16) & 0xfff;
    out[op++] = ((in10 >>> 28) | ((in11 & 0xff) << 4)) & 0xfff;
    out[op++] = (in11 >>> 8) & 0xfff;
    out[op] = (in11 >>> 20) & 0xfff;
}
function fastUnpack32_16(inValues, inPos, out, outPos) {
    let op = outPos;
    const in0 = inValues[inPos] >>> 0;
    const in1 = inValues[inPos + 1] >>> 0;
    const in2 = inValues[inPos + 2] >>> 0;
    const in3 = inValues[inPos + 3] >>> 0;
    const in4 = inValues[inPos + 4] >>> 0;
    const in5 = inValues[inPos + 5] >>> 0;
    const in6 = inValues[inPos + 6] >>> 0;
    const in7 = inValues[inPos + 7] >>> 0;
    const in8 = inValues[inPos + 8] >>> 0;
    const in9 = inValues[inPos + 9] >>> 0;
    const in10 = inValues[inPos + 10] >>> 0;
    const in11 = inValues[inPos + 11] >>> 0;
    const in12 = inValues[inPos + 12] >>> 0;
    const in13 = inValues[inPos + 13] >>> 0;
    const in14 = inValues[inPos + 14] >>> 0;
    const in15 = inValues[inPos + 15] >>> 0;
    out[op++] = (in0 >>> 0) & 0xffff;
    out[op++] = (in0 >>> 16) & 0xffff;
    out[op++] = (in1 >>> 0) & 0xffff;
    out[op++] = (in1 >>> 16) & 0xffff;
    out[op++] = (in2 >>> 0) & 0xffff;
    out[op++] = (in2 >>> 16) & 0xffff;
    out[op++] = (in3 >>> 0) & 0xffff;
    out[op++] = (in3 >>> 16) & 0xffff;
    out[op++] = (in4 >>> 0) & 0xffff;
    out[op++] = (in4 >>> 16) & 0xffff;
    out[op++] = (in5 >>> 0) & 0xffff;
    out[op++] = (in5 >>> 16) & 0xffff;
    out[op++] = (in6 >>> 0) & 0xffff;
    out[op++] = (in6 >>> 16) & 0xffff;
    out[op++] = (in7 >>> 0) & 0xffff;
    out[op++] = (in7 >>> 16) & 0xffff;
    out[op++] = (in8 >>> 0) & 0xffff;
    out[op++] = (in8 >>> 16) & 0xffff;
    out[op++] = (in9 >>> 0) & 0xffff;
    out[op++] = (in9 >>> 16) & 0xffff;
    out[op++] = (in10 >>> 0) & 0xffff;
    out[op++] = (in10 >>> 16) & 0xffff;
    out[op++] = (in11 >>> 0) & 0xffff;
    out[op++] = (in11 >>> 16) & 0xffff;
    out[op++] = (in12 >>> 0) & 0xffff;
    out[op++] = (in12 >>> 16) & 0xffff;
    out[op++] = (in13 >>> 0) & 0xffff;
    out[op++] = (in13 >>> 16) & 0xffff;
    out[op++] = (in14 >>> 0) & 0xffff;
    out[op++] = (in14 >>> 16) & 0xffff;
    out[op++] = (in15 >>> 0) & 0xffff;
    out[op] = (in15 >>> 16) & 0xffff;
}
function fastUnpack256_1(inValues, inPos, out, outPos) {
    let op = outPos;
    let ip = inPos;
    for (let c = 0; c < 8; c++) {
        const in0 = inValues[ip++] >>> 0;
        out[op++] = (in0 >>> 0) & 0x1;
        out[op++] = (in0 >>> 1) & 0x1;
        out[op++] = (in0 >>> 2) & 0x1;
        out[op++] = (in0 >>> 3) & 0x1;
        out[op++] = (in0 >>> 4) & 0x1;
        out[op++] = (in0 >>> 5) & 0x1;
        out[op++] = (in0 >>> 6) & 0x1;
        out[op++] = (in0 >>> 7) & 0x1;
        out[op++] = (in0 >>> 8) & 0x1;
        out[op++] = (in0 >>> 9) & 0x1;
        out[op++] = (in0 >>> 10) & 0x1;
        out[op++] = (in0 >>> 11) & 0x1;
        out[op++] = (in0 >>> 12) & 0x1;
        out[op++] = (in0 >>> 13) & 0x1;
        out[op++] = (in0 >>> 14) & 0x1;
        out[op++] = (in0 >>> 15) & 0x1;
        out[op++] = (in0 >>> 16) & 0x1;
        out[op++] = (in0 >>> 17) & 0x1;
        out[op++] = (in0 >>> 18) & 0x1;
        out[op++] = (in0 >>> 19) & 0x1;
        out[op++] = (in0 >>> 20) & 0x1;
        out[op++] = (in0 >>> 21) & 0x1;
        out[op++] = (in0 >>> 22) & 0x1;
        out[op++] = (in0 >>> 23) & 0x1;
        out[op++] = (in0 >>> 24) & 0x1;
        out[op++] = (in0 >>> 25) & 0x1;
        out[op++] = (in0 >>> 26) & 0x1;
        out[op++] = (in0 >>> 27) & 0x1;
        out[op++] = (in0 >>> 28) & 0x1;
        out[op++] = (in0 >>> 29) & 0x1;
        out[op++] = (in0 >>> 30) & 0x1;
        out[op++] = (in0 >>> 31) & 0x1;
    }
}
function fastUnpack256_2(inValues, inPos, out, outPos) {
    let op = outPos;
    let ip = inPos;
    for (let c = 0; c < 8; c++) {
        const in0 = inValues[ip++] >>> 0;
        const in1 = inValues[ip++] >>> 0;
        out[op++] = (in0 >>> 0) & 0x3;
        out[op++] = (in0 >>> 2) & 0x3;
        out[op++] = (in0 >>> 4) & 0x3;
        out[op++] = (in0 >>> 6) & 0x3;
        out[op++] = (in0 >>> 8) & 0x3;
        out[op++] = (in0 >>> 10) & 0x3;
        out[op++] = (in0 >>> 12) & 0x3;
        out[op++] = (in0 >>> 14) & 0x3;
        out[op++] = (in0 >>> 16) & 0x3;
        out[op++] = (in0 >>> 18) & 0x3;
        out[op++] = (in0 >>> 20) & 0x3;
        out[op++] = (in0 >>> 22) & 0x3;
        out[op++] = (in0 >>> 24) & 0x3;
        out[op++] = (in0 >>> 26) & 0x3;
        out[op++] = (in0 >>> 28) & 0x3;
        out[op++] = (in0 >>> 30) & 0x3;
        out[op++] = (in1 >>> 0) & 0x3;
        out[op++] = (in1 >>> 2) & 0x3;
        out[op++] = (in1 >>> 4) & 0x3;
        out[op++] = (in1 >>> 6) & 0x3;
        out[op++] = (in1 >>> 8) & 0x3;
        out[op++] = (in1 >>> 10) & 0x3;
        out[op++] = (in1 >>> 12) & 0x3;
        out[op++] = (in1 >>> 14) & 0x3;
        out[op++] = (in1 >>> 16) & 0x3;
        out[op++] = (in1 >>> 18) & 0x3;
        out[op++] = (in1 >>> 20) & 0x3;
        out[op++] = (in1 >>> 22) & 0x3;
        out[op++] = (in1 >>> 24) & 0x3;
        out[op++] = (in1 >>> 26) & 0x3;
        out[op++] = (in1 >>> 28) & 0x3;
        out[op++] = (in1 >>> 30) & 0x3;
    }
}
function fastUnpack256_3(inValues, inPos, out, outPos) {
    let op = outPos;
    let ip = inPos;
    for (let c = 0; c < 8; c++) {
        const in0 = inValues[ip++] >>> 0;
        const in1 = inValues[ip++] >>> 0;
        const in2 = inValues[ip++] >>> 0;
        out[op++] = (in0 >>> 0) & 0x7;
        out[op++] = (in0 >>> 3) & 0x7;
        out[op++] = (in0 >>> 6) & 0x7;
        out[op++] = (in0 >>> 9) & 0x7;
        out[op++] = (in0 >>> 12) & 0x7;
        out[op++] = (in0 >>> 15) & 0x7;
        out[op++] = (in0 >>> 18) & 0x7;
        out[op++] = (in0 >>> 21) & 0x7;
        out[op++] = (in0 >>> 24) & 0x7;
        out[op++] = (in0 >>> 27) & 0x7;
        out[op++] = ((in0 >>> 30) | ((in1 & 0x1) << 2)) & 0x7;
        out[op++] = (in1 >>> 1) & 0x7;
        out[op++] = (in1 >>> 4) & 0x7;
        out[op++] = (in1 >>> 7) & 0x7;
        out[op++] = (in1 >>> 10) & 0x7;
        out[op++] = (in1 >>> 13) & 0x7;
        out[op++] = (in1 >>> 16) & 0x7;
        out[op++] = (in1 >>> 19) & 0x7;
        out[op++] = (in1 >>> 22) & 0x7;
        out[op++] = (in1 >>> 25) & 0x7;
        out[op++] = (in1 >>> 28) & 0x7;
        out[op++] = ((in1 >>> 31) | ((in2 & 0x3) << 1)) & 0x7;
        out[op++] = (in2 >>> 2) & 0x7;
        out[op++] = (in2 >>> 5) & 0x7;
        out[op++] = (in2 >>> 8) & 0x7;
        out[op++] = (in2 >>> 11) & 0x7;
        out[op++] = (in2 >>> 14) & 0x7;
        out[op++] = (in2 >>> 17) & 0x7;
        out[op++] = (in2 >>> 20) & 0x7;
        out[op++] = (in2 >>> 23) & 0x7;
        out[op++] = (in2 >>> 26) & 0x7;
        out[op++] = (in2 >>> 29) & 0x7;
    }
}
function fastUnpack256_4(inValues, inPos, out, outPos) {
    let op = outPos;
    let ip = inPos;
    for (let c = 0; c < 8; c++) {
        const in0 = inValues[ip++] >>> 0;
        const in1 = inValues[ip++] >>> 0;
        const in2 = inValues[ip++] >>> 0;
        const in3 = inValues[ip++] >>> 0;
        out[op++] = (in0 >>> 0) & 0xf;
        out[op++] = (in0 >>> 4) & 0xf;
        out[op++] = (in0 >>> 8) & 0xf;
        out[op++] = (in0 >>> 12) & 0xf;
        out[op++] = (in0 >>> 16) & 0xf;
        out[op++] = (in0 >>> 20) & 0xf;
        out[op++] = (in0 >>> 24) & 0xf;
        out[op++] = (in0 >>> 28) & 0xf;
        out[op++] = (in1 >>> 0) & 0xf;
        out[op++] = (in1 >>> 4) & 0xf;
        out[op++] = (in1 >>> 8) & 0xf;
        out[op++] = (in1 >>> 12) & 0xf;
        out[op++] = (in1 >>> 16) & 0xf;
        out[op++] = (in1 >>> 20) & 0xf;
        out[op++] = (in1 >>> 24) & 0xf;
        out[op++] = (in1 >>> 28) & 0xf;
        out[op++] = (in2 >>> 0) & 0xf;
        out[op++] = (in2 >>> 4) & 0xf;
        out[op++] = (in2 >>> 8) & 0xf;
        out[op++] = (in2 >>> 12) & 0xf;
        out[op++] = (in2 >>> 16) & 0xf;
        out[op++] = (in2 >>> 20) & 0xf;
        out[op++] = (in2 >>> 24) & 0xf;
        out[op++] = (in2 >>> 28) & 0xf;
        out[op++] = (in3 >>> 0) & 0xf;
        out[op++] = (in3 >>> 4) & 0xf;
        out[op++] = (in3 >>> 8) & 0xf;
        out[op++] = (in3 >>> 12) & 0xf;
        out[op++] = (in3 >>> 16) & 0xf;
        out[op++] = (in3 >>> 20) & 0xf;
        out[op++] = (in3 >>> 24) & 0xf;
        out[op++] = (in3 >>> 28) & 0xf;
    }
}
function fastUnpack256_5(inValues, inPos, out, outPos) {
    let op = outPos;
    let ip = inPos;
    for (let c = 0; c < 8; c++) {
        const in0 = inValues[ip++] >>> 0;
        const in1 = inValues[ip++] >>> 0;
        const in2 = inValues[ip++] >>> 0;
        const in3 = inValues[ip++] >>> 0;
        const in4 = inValues[ip++] >>> 0;
        out[op++] = (in0 >>> 0) & 0x1f;
        out[op++] = (in0 >>> 5) & 0x1f;
        out[op++] = (in0 >>> 10) & 0x1f;
        out[op++] = (in0 >>> 15) & 0x1f;
        out[op++] = (in0 >>> 20) & 0x1f;
        out[op++] = (in0 >>> 25) & 0x1f;
        out[op++] = ((in0 >>> 30) | ((in1 & 0x7) << 2)) & 0x1f;
        out[op++] = (in1 >>> 3) & 0x1f;
        out[op++] = (in1 >>> 8) & 0x1f;
        out[op++] = (in1 >>> 13) & 0x1f;
        out[op++] = (in1 >>> 18) & 0x1f;
        out[op++] = (in1 >>> 23) & 0x1f;
        out[op++] = ((in1 >>> 28) | ((in2 & 0x1) << 4)) & 0x1f;
        out[op++] = (in2 >>> 1) & 0x1f;
        out[op++] = (in2 >>> 6) & 0x1f;
        out[op++] = (in2 >>> 11) & 0x1f;
        out[op++] = (in2 >>> 16) & 0x1f;
        out[op++] = (in2 >>> 21) & 0x1f;
        out[op++] = (in2 >>> 26) & 0x1f;
        out[op++] = ((in2 >>> 31) | ((in3 & 0xf) << 1)) & 0x1f;
        out[op++] = (in3 >>> 4) & 0x1f;
        out[op++] = (in3 >>> 9) & 0x1f;
        out[op++] = (in3 >>> 14) & 0x1f;
        out[op++] = (in3 >>> 19) & 0x1f;
        out[op++] = (in3 >>> 24) & 0x1f;
        out[op++] = ((in3 >>> 29) | ((in4 & 0x3) << 3)) & 0x1f;
        out[op++] = (in4 >>> 2) & 0x1f;
        out[op++] = (in4 >>> 7) & 0x1f;
        out[op++] = (in4 >>> 12) & 0x1f;
        out[op++] = (in4 >>> 17) & 0x1f;
        out[op++] = (in4 >>> 22) & 0x1f;
        out[op++] = (in4 >>> 27) & 0x1f;
    }
}
function fastUnpack256_6(inValues, inPos, out, outPos) {
    let op = outPos;
    let ip = inPos;
    for (let c = 0; c < 8; c++) {
        const in0 = inValues[ip++] >>> 0;
        const in1 = inValues[ip++] >>> 0;
        const in2 = inValues[ip++] >>> 0;
        const in3 = inValues[ip++] >>> 0;
        const in4 = inValues[ip++] >>> 0;
        const in5 = inValues[ip++] >>> 0;
        out[op++] = (in0 >>> 0) & 0x3f;
        out[op++] = (in0 >>> 6) & 0x3f;
        out[op++] = (in0 >>> 12) & 0x3f;
        out[op++] = (in0 >>> 18) & 0x3f;
        out[op++] = (in0 >>> 24) & 0x3f;
        out[op++] = ((in0 >>> 30) | ((in1 & 0xf) << 2)) & 0x3f;
        out[op++] = (in1 >>> 4) & 0x3f;
        out[op++] = (in1 >>> 10) & 0x3f;
        out[op++] = (in1 >>> 16) & 0x3f;
        out[op++] = (in1 >>> 22) & 0x3f;
        out[op++] = ((in1 >>> 28) | ((in2 & 0x3) << 4)) & 0x3f;
        out[op++] = (in2 >>> 2) & 0x3f;
        out[op++] = (in2 >>> 8) & 0x3f;
        out[op++] = (in2 >>> 14) & 0x3f;
        out[op++] = (in2 >>> 20) & 0x3f;
        out[op++] = (in2 >>> 26) & 0x3f;
        out[op++] = (in3 >>> 0) & 0x3f;
        out[op++] = (in3 >>> 6) & 0x3f;
        out[op++] = (in3 >>> 12) & 0x3f;
        out[op++] = (in3 >>> 18) & 0x3f;
        out[op++] = (in3 >>> 24) & 0x3f;
        out[op++] = ((in3 >>> 30) | ((in4 & 0xf) << 2)) & 0x3f;
        out[op++] = (in4 >>> 4) & 0x3f;
        out[op++] = (in4 >>> 10) & 0x3f;
        out[op++] = (in4 >>> 16) & 0x3f;
        out[op++] = (in4 >>> 22) & 0x3f;
        out[op++] = ((in4 >>> 28) | ((in5 & 0x3) << 4)) & 0x3f;
        out[op++] = (in5 >>> 2) & 0x3f;
        out[op++] = (in5 >>> 8) & 0x3f;
        out[op++] = (in5 >>> 14) & 0x3f;
        out[op++] = (in5 >>> 20) & 0x3f;
        out[op++] = (in5 >>> 26) & 0x3f;
    }
}
function fastUnpack256_7(inValues, inPos, out, outPos) {
    let op = outPos;
    let ip = inPos;
    for (let c = 0; c < 8; c++) {
        const in0 = inValues[ip++] >>> 0;
        const in1 = inValues[ip++] >>> 0;
        const in2 = inValues[ip++] >>> 0;
        const in3 = inValues[ip++] >>> 0;
        const in4 = inValues[ip++] >>> 0;
        const in5 = inValues[ip++] >>> 0;
        const in6 = inValues[ip++] >>> 0;
        out[op++] = (in0 >>> 0) & 0x7f;
        out[op++] = (in0 >>> 7) & 0x7f;
        out[op++] = (in0 >>> 14) & 0x7f;
        out[op++] = (in0 >>> 21) & 0x7f;
        out[op++] = ((in0 >>> 28) | ((in1 & 0x7) << 4)) & 0x7f;
        out[op++] = (in1 >>> 3) & 0x7f;
        out[op++] = (in1 >>> 10) & 0x7f;
        out[op++] = (in1 >>> 17) & 0x7f;
        out[op++] = (in1 >>> 24) & 0x7f;
        out[op++] = ((in1 >>> 31) | ((in2 & 0x3f) << 1)) & 0x7f;
        out[op++] = (in2 >>> 6) & 0x7f;
        out[op++] = (in2 >>> 13) & 0x7f;
        out[op++] = (in2 >>> 20) & 0x7f;
        out[op++] = ((in2 >>> 27) | ((in3 & 0x3) << 5)) & 0x7f;
        out[op++] = (in3 >>> 2) & 0x7f;
        out[op++] = (in3 >>> 9) & 0x7f;
        out[op++] = (in3 >>> 16) & 0x7f;
        out[op++] = (in3 >>> 23) & 0x7f;
        out[op++] = ((in3 >>> 30) | ((in4 & 0x1f) << 2)) & 0x7f;
        out[op++] = (in4 >>> 5) & 0x7f;
        out[op++] = (in4 >>> 12) & 0x7f;
        out[op++] = (in4 >>> 19) & 0x7f;
        out[op++] = ((in4 >>> 26) | ((in5 & 0x1) << 6)) & 0x7f;
        out[op++] = (in5 >>> 1) & 0x7f;
        out[op++] = (in5 >>> 8) & 0x7f;
        out[op++] = (in5 >>> 15) & 0x7f;
        out[op++] = (in5 >>> 22) & 0x7f;
        out[op++] = ((in5 >>> 29) | ((in6 & 0xf) << 3)) & 0x7f;
        out[op++] = (in6 >>> 4) & 0x7f;
        out[op++] = (in6 >>> 11) & 0x7f;
        out[op++] = (in6 >>> 18) & 0x7f;
        out[op++] = (in6 >>> 25) & 0x7f;
    }
}
function fastUnpack256_8(inValues, inPos, out, outPos) {
    let op = outPos;
    let ip = inPos;
    for (let c = 0; c < 8; c++) {
        const in0 = inValues[ip++] >>> 0;
        const in1 = inValues[ip++] >>> 0;
        const in2 = inValues[ip++] >>> 0;
        const in3 = inValues[ip++] >>> 0;
        const in4 = inValues[ip++] >>> 0;
        const in5 = inValues[ip++] >>> 0;
        const in6 = inValues[ip++] >>> 0;
        const in7 = inValues[ip++] >>> 0;
        out[op++] = (in0 >>> 0) & 0xff;
        out[op++] = (in0 >>> 8) & 0xff;
        out[op++] = (in0 >>> 16) & 0xff;
        out[op++] = (in0 >>> 24) & 0xff;
        out[op++] = (in1 >>> 0) & 0xff;
        out[op++] = (in1 >>> 8) & 0xff;
        out[op++] = (in1 >>> 16) & 0xff;
        out[op++] = (in1 >>> 24) & 0xff;
        out[op++] = (in2 >>> 0) & 0xff;
        out[op++] = (in2 >>> 8) & 0xff;
        out[op++] = (in2 >>> 16) & 0xff;
        out[op++] = (in2 >>> 24) & 0xff;
        out[op++] = (in3 >>> 0) & 0xff;
        out[op++] = (in3 >>> 8) & 0xff;
        out[op++] = (in3 >>> 16) & 0xff;
        out[op++] = (in3 >>> 24) & 0xff;
        out[op++] = (in4 >>> 0) & 0xff;
        out[op++] = (in4 >>> 8) & 0xff;
        out[op++] = (in4 >>> 16) & 0xff;
        out[op++] = (in4 >>> 24) & 0xff;
        out[op++] = (in5 >>> 0) & 0xff;
        out[op++] = (in5 >>> 8) & 0xff;
        out[op++] = (in5 >>> 16) & 0xff;
        out[op++] = (in5 >>> 24) & 0xff;
        out[op++] = (in6 >>> 0) & 0xff;
        out[op++] = (in6 >>> 8) & 0xff;
        out[op++] = (in6 >>> 16) & 0xff;
        out[op++] = (in6 >>> 24) & 0xff;
        out[op++] = (in7 >>> 0) & 0xff;
        out[op++] = (in7 >>> 8) & 0xff;
        out[op++] = (in7 >>> 16) & 0xff;
        out[op++] = (in7 >>> 24) & 0xff;
    }
}
function fastUnpack256_16(inValues, inPos, out, outPos) {
    let op = outPos;
    let ip = inPos;
    for (let i = 0; i < 128; i++) {
        const in0 = inValues[ip++] >>> 0;
        out[op++] = in0 & 0xffff;
        out[op++] = (in0 >>> 16) & 0xffff;
    }
}
function fastUnpack256_Generic(inValues, inPos, out, outPos, bitWidth) {
    const mask = MASKS[bitWidth] >>> 0;
    let inputWordIndex = inPos;
    let bitOffset = 0;
    let currentWord = inValues[inputWordIndex] >>> 0;
    let op = outPos;
    for (let c = 0; c < 8; c++) {
        for (let i = 0; i < 32; i++) {
            if (bitOffset + bitWidth <= 32) {
                const value = (currentWord >>> bitOffset) & mask;
                out[op + i] = value | 0;
                bitOffset += bitWidth;
                if (bitOffset === 32) {
                    bitOffset = 0;
                    inputWordIndex++;
                    if (i !== 31) {
                        currentWord = inValues[inputWordIndex] >>> 0;
                    }
                }
            }
            else {
                const lowBits = 32 - bitOffset;
                const low = currentWord >>> bitOffset;
                inputWordIndex++;
                currentWord = inValues[inputWordIndex] >>> 0;
                const highBits = bitWidth - lowBits;
                const highMask = (-1 >>> (32 - highBits)) >>> 0;
                const high = currentWord & highMask;
                const value = (low | (high << lowBits)) & mask;
                out[op + i] = value | 0;
                bitOffset = highBits;
            }
        }
        op += 32;
        bitOffset = 0;
        if (c < 7) {
            currentWord = inValues[inputWordIndex] >>> 0;
        }
    }
}

const MAX_BIT_WIDTH = 32;
const BIT_WIDTH_SLOTS = MAX_BIT_WIDTH + 1;
const PAGE_SIZE = normalizePageSize(DEFAULT_PAGE_SIZE);
const BYTE_CONTAINER_SIZE = ((3 * PAGE_SIZE) / BLOCK_SIZE + PAGE_SIZE) | 0;
/**
 * Creates an isolated workspace for decoding.
 * Reusing a workspace across calls avoids repeated allocations.
 */
function createDecoderWorkspace() {
    const byteContainer = new Uint8Array(BYTE_CONTAINER_SIZE);
    return {
        dataToBePacked: new Array(BIT_WIDTH_SLOTS),
        dataPointers: new Int32Array(BIT_WIDTH_SLOTS),
        byteContainer,
        byteContainerI32: new Int32Array(byteContainer.buffer, byteContainer.byteOffset, byteContainer.byteLength >>> 2),
        exceptionSizes: new Int32Array(BIT_WIDTH_SLOTS),
    };
}
function createFastPforWireDecodeWorkspace(initialEncodedWordCapacity = 16) {
    if (initialEncodedWordCapacity < 0) {
        throw new RangeError(`initialEncodedWordCapacity must be >= 0, got ${initialEncodedWordCapacity}`);
    }
    const capacity = Math.max(16, initialEncodedWordCapacity | 0);
    return {
        encodedWords: new Uint32Array(capacity),
        decoderWorkspace: createDecoderWorkspace(),
    };
}
function ensureFastPforWireEncodedWordsCapacity(workspace, requiredWordCount) {
    if (requiredWordCount <= workspace.encodedWords.length)
        return workspace.encodedWords;
    const next = new Uint32Array(Math.max(16, requiredWordCount * 2));
    workspace.encodedWords = next;
    return next;
}
function materializeByteContainer(inValues, byteContainerStart, byteSize, workspace) {
    if (workspace.byteContainer.length < byteSize) {
        workspace.byteContainer = new Uint8Array(byteSize * 2);
        workspace.byteContainerI32 = undefined;
    }
    const byteContainer = workspace.byteContainer;
    const numFullInts = byteSize >>> 2;
    if ((byteContainer.byteOffset & 3) === 0) {
        let intView = workspace.byteContainerI32;
        if (!intView ||
            intView.buffer !== byteContainer.buffer ||
            intView.byteOffset !== byteContainer.byteOffset ||
            intView.length < numFullInts) {
            intView = workspace.byteContainerI32 = new Int32Array(byteContainer.buffer, byteContainer.byteOffset, byteContainer.byteLength >>> 2);
        }
        intView.set(inValues.subarray(byteContainerStart, byteContainerStart + numFullInts));
    }
    else {
        for (let i = 0; i < numFullInts; i = (i + 1) | 0) {
            const val = inValues[(byteContainerStart + i) | 0] | 0;
            const base = i << 2;
            byteContainer[base] = val & 0xff;
            byteContainer[(base + 1) | 0] = (val >>> 8) & 0xff;
            byteContainer[(base + 2) | 0] = (val >>> 16) & 0xff;
            byteContainer[(base + 3) | 0] = (val >>> 24) & 0xff;
        }
    }
    const remainder = byteSize & 3;
    if (remainder > 0) {
        const lastIntIdx = (byteContainerStart + numFullInts) | 0;
        const lastVal = inValues[lastIntIdx] | 0;
        const base = numFullInts << 2;
        for (let r = 0; r < remainder; r = (r + 1) | 0) {
            byteContainer[(base + r) | 0] = (lastVal >>> (r << 3)) & 0xff;
        }
    }
    return byteContainer;
}
/**
 * Unpacks the per-bitWidth "exception streams" described by the page's bitmap.
 *
 * @remarks
 * For each bit-width present in the bitmap, a stream header gives the count of outlier values for that
 * bit-width, followed by packed bits representing those values.
 *
 * @param inValues - Packed input (32-bit words).
 * @param inExcept - Offset (32-bit word index) where the exception bitmap starts.
 * @param workspace - Decoder workspace used to store the unpacked exception streams.
 * @returns The new input offset (32-bit word index) after consuming all exception streams.
 */
function unpackExceptionStreams(inValues, inExcept, workspace) {
    const bitmap = inValues[inExcept++] | 0;
    const dataToBePacked = workspace.dataToBePacked;
    for (let bitWidth = 2; bitWidth <= MAX_BIT_WIDTH; bitWidth = (bitWidth + 1) | 0) {
        if (((bitmap >>> (bitWidth - 1)) & 1) === 0)
            continue;
        if (inExcept >= inValues.length) {
            throw new Error(`FastPFOR decode: truncated exception stream header (bitWidth=${bitWidth}, streamWordIndex=${inExcept}, needWords=1, availableWords=${inValues.length - inExcept}, encodedWords=${inValues.length})`);
        }
        const size = inValues[inExcept++] >>> 0;
        const roundedUp = roundUpToMultipleOf32(size);
        const wordsNeeded = (size * bitWidth + 31) >>> 5;
        if (inExcept + wordsNeeded > inValues.length) {
            throw new Error(`FastPFOR decode: truncated exception stream (bitWidth=${bitWidth}, size=${size}, streamWordIndex=${inExcept}, needWords=${wordsNeeded}, availableWords=${inValues.length - inExcept}, encodedWords=${inValues.length})`);
        }
        let exceptionStream = dataToBePacked[bitWidth];
        if (!exceptionStream || exceptionStream.length < roundedUp) {
            exceptionStream = dataToBePacked[bitWidth] = new Uint32Array(roundedUp);
        }
        let j = 0;
        for (; j < size; j = (j + 32) | 0) {
            fastUnpack32(inValues, inExcept, exceptionStream, j, bitWidth);
            inExcept = (inExcept + bitWidth) | 0;
        }
        const overflow = (j - size) | 0;
        inExcept = (inExcept - ((overflow * bitWidth) >>> 5)) | 0;
        workspace.exceptionSizes[bitWidth] = size;
    }
    return inExcept;
}
/**
 * Unpacks one 256-value block from the packed bitstream using a specialized implementation for common widths.
 *
 * @param inValues - Packed input (32-bit words).
 * @param inPos - Input offset (32-bit word index) where the packed block starts.
 * @param out - Output buffer.
 * @param outPos - Output offset where the 256 values will be written.
 * @param bitWidth - Base bit-width used for this block.
 * @returns The new input offset (32-bit word index) right after the packed block data.
 */
function unpackBlock256(inValues, inPos, out, outPos, bitWidth) {
    switch (bitWidth) {
        case 1:
            fastUnpack256_1(inValues, inPos, out, outPos);
            break;
        case 2:
            fastUnpack256_2(inValues, inPos, out, outPos);
            break;
        case 3:
            fastUnpack256_3(inValues, inPos, out, outPos);
            break;
        case 4:
            fastUnpack256_4(inValues, inPos, out, outPos);
            break;
        case 5:
            fastUnpack256_5(inValues, inPos, out, outPos);
            break;
        case 6:
            fastUnpack256_6(inValues, inPos, out, outPos);
            break;
        case 7:
            fastUnpack256_7(inValues, inPos, out, outPos);
            break;
        case 8:
            fastUnpack256_8(inValues, inPos, out, outPos);
            break;
        case 16:
            fastUnpack256_16(inValues, inPos, out, outPos);
            break;
        default:
            fastUnpack256_Generic(inValues, inPos, out, outPos, bitWidth);
            break;
    }
    return (inPos + (bitWidth << 3)) | 0;
}
/**
 * Reads and validates the 2-byte block header from the byteContainer.
 *
 * @remarks
 * The header is `[bitWidth, exceptionCount]`, both stored as single bytes.
 *
 * @param byteContainer - Byte metadata buffer for the page.
 * @param byteContainerLen - The valid byte length in `byteContainer` for this page.
 * @param bytePosIn - Current offset in `byteContainer`.
 * @param block - Block index within the page (for error messages).
 * @returns The parsed header and the updated `bytePosIn`.
 */
function readBlockHeader(byteContainer, byteContainerLen, bytePosIn, block) {
    if (bytePosIn + 2 > byteContainerLen) {
        throw new Error(`FastPFOR decode: byteContainer underflow at block=${block} (need 2 bytes for [bitWidth, exceptionCount], bytePos=${bytePosIn}, byteSize=${byteContainerLen})`);
    }
    const bitWidth = byteContainer[bytePosIn++];
    const exceptionCount = byteContainer[bytePosIn++];
    if (bitWidth > MAX_BIT_WIDTH) {
        throw new Error(`FastPFOR decode: invalid bitWidth=${bitWidth} at block=${block} (expected 0..${MAX_BIT_WIDTH}). This likely indicates corrupted or truncated input.`);
    }
    return { bitWidth, exceptionCount, bytePosIn };
}
/**
 * Reads and validates the exception header for a block.
 *
 * @remarks
 * The header contains `maxBits` (1 byte), which defines the width of the outlier values as
 * `exceptionBitWidth = maxBits - bitWidth`.
 *
 * @param byteContainer - Byte metadata buffer for the page.
 * @param byteContainerLen - The valid byte length in `byteContainer` for this page.
 * @param bytePosIn - Current offset in `byteContainer`.
 * @param bitWidth - Base bit-width for the block.
 * @param exceptionCount - Number of exceptions/outliers in this block.
 * @param block - Block index within the page (for error messages).
 * @returns Parsed `maxBits`, `exceptionBitWidth`, and the updated `bytePosIn`.
 */
function readBlockExceptionHeader(byteContainer, byteContainerLen, bytePosIn, bitWidth, exceptionCount, block) {
    if (bytePosIn + 1 > byteContainerLen) {
        throw new Error(`FastPFOR decode: exception header underflow at block=${block} (need 1 byte for maxBits, bytePos=${bytePosIn}, byteSize=${byteContainerLen})`);
    }
    const maxBits = byteContainer[bytePosIn++];
    if (maxBits < bitWidth || maxBits > MAX_BIT_WIDTH) {
        throw new Error(`FastPFOR decode: invalid maxBits=${maxBits} at block=${block} (bitWidth=${bitWidth}, expected ${bitWidth}..${MAX_BIT_WIDTH})`);
    }
    const exceptionBitWidth = (maxBits - bitWidth) | 0;
    if (exceptionBitWidth < 1 || exceptionBitWidth > MAX_BIT_WIDTH) {
        throw new Error(`FastPFOR decode: invalid exceptionBitWidth=${exceptionBitWidth} at block=${block} (bitWidth=${bitWidth}, maxBits=${maxBits})`);
    }
    if (bytePosIn + exceptionCount > byteContainerLen) {
        throw new Error(`FastPFOR decode: exception positions underflow at block=${block} (need=${exceptionCount}, have=${byteContainerLen - bytePosIn})`);
    }
    return { maxBits, exceptionBitWidth, bytePosIn };
}
/**
 * Applies (block-local) FastPFOR "exceptions" (outliers) to an already-unpacked base 256-value block.
 *
 * @param out - Output buffer containing the base unpacked values for the block.
 * @param blockOutPos - Offset in `out` where the 256-value block starts.
 * @param bitWidth - Base bit-width for the block.
 * @param exceptionCount - Number of exceptions/outliers in this block.
 * @param byteContainer - Byte metadata buffer for the page.
 * @param byteContainerLen - The valid byte length in `byteContainer` for this page.
 * @param bytePosIn - Current offset in `byteContainer` (right after `[bitWidth, exceptionCount]`).
 * @param workspace - Decoder workspace holding the unpacked exception streams.
 * @param block - Block index within the page (for error messages).
 * @returns The updated `bytePosIn` after consuming the exception metadata bytes.
 *
 * The exception metadata is stored in `byteContainer`:
 * - `maxBits` (1 byte): the maximum bit-width of any value in the block
 * - `exceptionCount` exception positions (1 byte each, 0..255)
 *
 * The exception values themselves are read from the pre-unpacked exception streams stored in `workspace`.
 * Returns the new position in the byteContainer after consuming the exception metadata bytes.
 */
function applyBlockExceptions(out, blockOutPos, bitWidth, exceptionCount, byteContainer, byteContainerLen, bytePosIn, workspace, block) {
    const { maxBits, exceptionBitWidth, bytePosIn: afterHeaderPos, } = readBlockExceptionHeader(byteContainer, byteContainerLen, bytePosIn, bitWidth, exceptionCount, block);
    bytePosIn = afterHeaderPos;
    if (exceptionBitWidth === 1) {
        const shift = 1 << bitWidth;
        for (let k = 0; k < exceptionCount; k = (k + 1) | 0) {
            const pos = byteContainer[bytePosIn++];
            out[(pos + blockOutPos) | 0] |= shift;
        }
        return bytePosIn;
    }
    const exceptionValues = workspace.dataToBePacked[exceptionBitWidth];
    if (!exceptionValues) {
        throw new Error(`FastPFOR decode: missing exception stream for exceptionBitWidth=${exceptionBitWidth} (bitWidth=${bitWidth}, maxBits=${maxBits}) at block ${block}`);
    }
    const exceptionPointers = workspace.dataPointers;
    let exPtr = exceptionPointers[exceptionBitWidth] | 0;
    const exSize = workspace.exceptionSizes[exceptionBitWidth] | 0;
    if (exPtr + exceptionCount > exSize) {
        throw new Error(`FastPFOR decode: exception stream overflow for exceptionBitWidth=${exceptionBitWidth} (ptr=${exPtr}, need ${exceptionCount}, size=${exSize}) at block ${block}`);
    }
    for (let k = 0; k < exceptionCount; k = (k + 1) | 0) {
        const pos = byteContainer[bytePosIn++];
        const val = exceptionValues[exPtr++] | 0;
        out[(pos + blockOutPos) | 0] |= val << bitWidth;
    }
    exceptionPointers[exceptionBitWidth] = exPtr;
    return bytePosIn;
}
function decodePageBlocks(inValues, pageStart, inPos, packedEnd, out, outPos, blocks, byteContainer, byteContainerLen, workspace) {
    let tmpInPos = inPos | 0;
    let bytePosIn = 0;
    for (let run = 0; run < blocks; run = (run + 1) | 0) {
        const header = readBlockHeader(byteContainer, byteContainerLen, bytePosIn, run);
        bytePosIn = header.bytePosIn;
        const bitWidth = header.bitWidth;
        const exceptionCount = header.exceptionCount;
        const blockOutPos = (outPos + run * BLOCK_SIZE) | 0;
        switch (bitWidth) {
            case 0:
                out.fill(0, blockOutPos, blockOutPos + BLOCK_SIZE);
                break;
            case 32:
                for (let i = 0; i < BLOCK_SIZE; i = (i + 1) | 0) {
                    out[(blockOutPos + i) | 0] = inValues[(tmpInPos + i) | 0] | 0;
                }
                tmpInPos = (tmpInPos + BLOCK_SIZE) | 0;
                break;
            default:
                tmpInPos = unpackBlock256(inValues, tmpInPos, out, blockOutPos, bitWidth);
                break;
        }
        if (exceptionCount > 0) {
            bytePosIn = applyBlockExceptions(out, blockOutPos, bitWidth, exceptionCount, byteContainer, byteContainerLen, bytePosIn, workspace, run);
        }
    }
    if (tmpInPos !== packedEnd) {
        throw new Error(`FastPFOR decode: packed region mismatch (pageStart=${pageStart}, packedStart=${inPos}, consumedPackedEnd=${tmpInPos}, expectedPackedEnd=${packedEnd}, packedWords=${packedEnd - inPos}, encoded.length=${inValues.length})`);
    }
    return;
}
/**
 * Decodes one FastPFOR page (aligned to 256-value blocks).
 */
function decodePage(inValues, out, inPos, outPos, thisSize, workspace) {
    const pageStart = inPos | 0;
    const whereMeta = inValues[pageStart] | 0;
    if (whereMeta <= 0 || pageStart + whereMeta > inValues.length - 1) {
        throw new Error(`FastPFOR decode: invalid whereMeta=${whereMeta} at pageStart=${pageStart} (expected > 0 and pageStart+whereMeta < encoded.length=${inValues.length})`);
    }
    const packedStart = (pageStart + 1) | 0;
    const packedEnd = (pageStart + whereMeta) | 0;
    const byteSize = inValues[packedEnd] >>> 0;
    const metaInts = (byteSize + 3) >>> 2;
    const byteContainerStart = packedEnd + 1;
    const bitmapPos = byteContainerStart + metaInts;
    if (bitmapPos >= inValues.length) {
        throw new Error(`FastPFOR decode: invalid byteSize=${byteSize} (metaInts=${metaInts}, pageStart=${pageStart}, packedEnd=${packedEnd}, byteContainerStart=${byteContainerStart}) causes bitmapPos=${bitmapPos} out of bounds (encoded.length=${inValues.length})`);
    }
    const byteContainer = materializeByteContainer(inValues, byteContainerStart, byteSize, workspace);
    const byteContainerLen = byteSize;
    const inExcept = unpackExceptionStreams(inValues, bitmapPos, workspace);
    const exceptionPointers = workspace.dataPointers;
    exceptionPointers.fill(0);
    const startOutPos = outPos | 0;
    const blocks = (thisSize / BLOCK_SIZE) | 0;
    decodePageBlocks(inValues, pageStart, packedStart, packedEnd, out, startOutPos, blocks, byteContainer, byteContainerLen, workspace);
    return inExcept;
}
function decodeAlignedPages(inValues, out, inPos, outPos, outLength, workspace) {
    const alignedOutLength = greatestMultiple(outLength, BLOCK_SIZE);
    const finalOut = outPos + alignedOutLength;
    let tmpOutPos = outPos;
    let tmpInPos = inPos;
    while (tmpOutPos !== finalOut) {
        const thisSize = Math.min(PAGE_SIZE, finalOut - tmpOutPos);
        tmpInPos = decodePage(inValues, out, tmpInPos, tmpOutPos, thisSize, workspace);
        tmpOutPos = (tmpOutPos + thisSize) | 0;
    }
    return tmpInPos;
}
/**
 * Decodes the VariableByte tail (MSB=1 terminator, opposite of Protobuf Varint).
 */
function decodeVByte(inValues, inPos, inLength, out, outPos, expectedCount) {
    if (expectedCount === 0)
        return inPos;
    let bitOffset = 0;
    let wordIndex = inPos;
    const finalWordIndex = inPos + inLength;
    const outPos0 = outPos;
    let tmpOutPos = outPos;
    const targetOut = outPos + expectedCount;
    let accumulator = 0;
    let accumulatorShift = 0;
    while (wordIndex < finalWordIndex && tmpOutPos < targetOut) {
        const word = inValues[wordIndex];
        const byte = (word >>> bitOffset) & 0xff;
        bitOffset += 8;
        wordIndex += bitOffset >>> 5;
        bitOffset &= 31;
        accumulator |= (byte & 0x7f) << accumulatorShift;
        if ((byte & 0x80) !== 0) {
            out[tmpOutPos++] = accumulator | 0;
            accumulator = 0;
            accumulatorShift = 0;
        }
        else {
            accumulatorShift += 7;
            if (accumulatorShift > 28) {
                throw new Error(`FastPFOR VByte: unterminated value (expected MSB=1 terminator within 5 bytes; shift=${accumulatorShift}, partial=${accumulator}, decoded=${tmpOutPos - outPos0}/${expectedCount}, inPos=${wordIndex}, inEnd=${finalWordIndex})`);
            }
        }
    }
    if (tmpOutPos !== targetOut) {
        throw new Error(`FastPFOR VByte: truncated stream (decoded=${tmpOutPos - outPos0}, expected=${expectedCount}, consumedWords=${wordIndex - inPos}/${inLength}, vbyteStart=${inPos}, vbyteEnd=${finalWordIndex})`);
    }
    return wordIndex;
}
/**
 * Decodes a sequence of FastPFOR-encoded integers.
 *
 * @param encoded The input buffer containing FastPFOR encoded data.
 * @param numValues The number of integers expected to be decoded.
 * @param workspace Optional workspace for reuse across calls. If omitted, a new workspace is created per call.
 */
function decodeFastPforInt32(encoded, numValues, workspace) {
    let inPos = 0;
    let outPos = 0;
    const decoded = new Uint32Array(numValues);
    const decoderWorkspace = workspace ?? createDecoderWorkspace();
    if (encoded.length > 0) {
        const alignedLength = encoded[inPos] | 0;
        inPos = (inPos + 1) | 0;
        if ((alignedLength & (BLOCK_SIZE - 1)) !== 0) {
            throw new Error(`FastPFOR decode: invalid alignedLength=${alignedLength} (expected multiple of ${BLOCK_SIZE})`);
        }
        if (outPos + alignedLength > decoded.length) {
            throw new Error(`FastPFOR decode: output buffer too small (outPos=${outPos}, alignedLength=${alignedLength}, out.length=${decoded.length})`);
        }
        inPos = decodeAlignedPages(encoded, decoded, inPos, outPos, alignedLength, decoderWorkspace);
        outPos = (outPos + alignedLength) | 0;
    }
    const remainingLength = (encoded.length - inPos) | 0;
    const expectedTail = (numValues - outPos) | 0;
    decodeVByte(encoded, inPos, remainingLength, decoded, outPos, expectedTail);
    return decoded;
}
function fastUnpack32(inValues, inPos, out, outPos, bitWidth) {
    switch (bitWidth) {
        case 2:
            fastUnpack32_2(inValues, inPos, out, outPos);
            return;
        case 3:
            fastUnpack32_3(inValues, inPos, out, outPos);
            return;
        case 4:
            fastUnpack32_4(inValues, inPos, out, outPos);
            return;
        case 5:
            fastUnpack32_5(inValues, inPos, out, outPos);
            return;
        case 6:
            fastUnpack32_6(inValues, inPos, out, outPos);
            return;
        case 7:
            fastUnpack32_7(inValues, inPos, out, outPos);
            return;
        case 8:
            fastUnpack32_8(inValues, inPos, out, outPos);
            return;
        case 9:
            fastUnpack32_9(inValues, inPos, out, outPos);
            return;
        case 10:
            fastUnpack32_10(inValues, inPos, out, outPos);
            return;
        case 11:
            fastUnpack32_11(inValues, inPos, out, outPos);
            return;
        case 12:
            fastUnpack32_12(inValues, inPos, out, outPos);
            return;
        case 16:
            fastUnpack32_16(inValues, inPos, out, outPos);
            return;
        case 32:
            for (let i = 0; i < 32; i = (i + 1) | 0) {
                out[(outPos + i) | 0] = inValues[(inPos + i) | 0] | 0;
            }
            return;
        default:
            break;
    }
    const valueMask = MASKS[bitWidth] >>> 0;
    let inputWordIndex = inPos;
    let bitOffset = 0;
    let currentWord = inValues[inputWordIndex] >>> 0;
    for (let i = 0; i < 32; i++) {
        if (bitOffset + bitWidth <= 32) {
            const value = (currentWord >>> bitOffset) & valueMask;
            out[outPos + i] = value | 0;
            bitOffset += bitWidth;
            if (bitOffset === 32) {
                bitOffset = 0;
                inputWordIndex++;
                if (i !== 31)
                    currentWord = inValues[inputWordIndex] >>> 0;
            }
        }
        else {
            const lowBits = 32 - bitOffset;
            const low = currentWord >>> bitOffset;
            inputWordIndex++;
            currentWord = inValues[inputWordIndex] >>> 0;
            const highMask = MASKS[bitWidth - lowBits] >>> 0;
            const high = currentWord & highMask;
            const value = (low | (high << lowBits)) & valueMask;
            out[outPos + i] = value | 0;
            bitOffset = bitWidth - lowBits;
        }
    }
}

/**
 * Decodes big-endian bytes into `out` without allocating the output buffer.
 *
 * This function does not copy `bytes`; it writes decoded words into the provided `out` array.
 * For aligned inputs it may create a temporary typed-array view (`Uint32Array`) over `bytes.buffer`
 * to speed up decoding.
 *
 * If `byteLength` is not a multiple of 4, the final word is padded with zeros.
 *
 * @returns Number of int32 words written.
 * @throws RangeError If `(offset, byteLength)` is out of bounds, or if `out` is too small.
 */
function decodeBigEndianInt32sInto(bytes, offset, byteLength, out) {
    if (offset < 0 || byteLength < 0 || offset + byteLength > bytes.length) {
        throw new RangeError(`decodeBigEndianInt32sInto: out of bounds (offset=${offset}, byteLength=${byteLength}, bytes.length=${bytes.length})`);
    }
    const numCompleteInts = Math.floor(byteLength / 4);
    const hasTrailingBytes = byteLength % 4 !== 0;
    const numInts = hasTrailingBytes ? numCompleteInts + 1 : numCompleteInts;
    if (out.length < numInts) {
        throw new RangeError(`decodeBigEndianInt32sInto: out.length=${out.length} < ${numInts}`);
    }
    if (numCompleteInts > 0) {
        const absoluteOffset = bytes.byteOffset + offset;
        if ((absoluteOffset & 3) === 0) {
            const u32 = new Uint32Array(bytes.buffer, absoluteOffset, numCompleteInts);
            for (let i = 0; i < numCompleteInts; i++) {
                out[i] = bswap32(u32[i]) | 0;
            }
        }
        else {
            for (let i = 0; i < numCompleteInts; i++) {
                const base = offset + i * 4;
                out[i] = (bytes[base] << 24) | (bytes[base + 1] << 16) | (bytes[base + 2] << 8) | bytes[base + 3] | 0;
            }
        }
    }
    if (hasTrailingBytes) {
        const base = offset + numCompleteInts * 4;
        const remaining = byteLength - numCompleteInts * 4;
        let v = 0;
        for (let i = 0; i < remaining; i++) {
            v |= bytes[base + i] << (24 - i * 8);
        }
        out[numCompleteInts] = v | 0;
    }
    return numInts;
}

//based on https://github.com/mapbox/pbf/blob/main/index.js
function decodeVarintInt32(buf, bufferOffset, numValues) {
    const dst = new Uint32Array(numValues);
    let dstOffset = 0;
    let offset = bufferOffset.get();
    for (let i = 0; i < dst.length; i++) {
        let b = buf[offset++];
        let val = b & 0x7f;
        if (b < 0x80) {
            dst[dstOffset++] = val;
            continue;
        }
        b = buf[offset++];
        val |= (b & 0x7f) << 7;
        if (b < 0x80) {
            dst[dstOffset++] = val;
            continue;
        }
        b = buf[offset++];
        val |= (b & 0x7f) << 14;
        if (b < 0x80) {
            dst[dstOffset++] = val;
            continue;
        }
        b = buf[offset++];
        val |= (b & 0x7f) << 21;
        if (b < 0x80) {
            dst[dstOffset++] = val;
            continue;
        }
        b = buf[offset++];
        val |= (b & 0x0f) << 28;
        dst[dstOffset++] = val;
    }
    bufferOffset.set(offset);
    return dst;
}
function decodeVarintInt64(src, offset, numValues) {
    const dst = new BigUint64Array(numValues);
    for (let i = 0; i < dst.length; i++) {
        dst[i] = decodeVarintInt64Value(src, offset);
    }
    return dst;
}
// Source: https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/util/VarInt.java
function decodeVarintInt64Value(bytes, pos) {
    let value = 0n;
    let shift = 0;
    let index = pos.get();
    while (index < bytes.length) {
        const b = bytes[index++];
        value |= BigInt(b & 0x7f) << BigInt(shift);
        if ((b & 0x80) === 0) {
            break;
        }
        shift += 7;
        if (shift >= 64) {
            throw new Error("Varint too long");
        }
    }
    pos.set(index);
    return value;
}
/*
 * Since decoding Int64 values to BigInt is more than an order of magnitude slower in the tests then using a Float64,
 * this decoding method limits the max size of a Long value to 53 bits
 */
function decodeVarintFloat64(src, offset, numValues) {
    const dst = new Float64Array(numValues);
    for (let i = 0; i < numValues; i++) {
        dst[i] = decodeVarintFloat64Value(src, offset);
    }
    return dst;
}
//based on https://github.com/mapbox/pbf/blob/main/index.js
function decodeVarintFloat64Value(buf, offset) {
    let val;
    let b;
    b = buf[offset.get()];
    offset.increment();
    val = b & 0x7f;
    if (b < 0x80)
        return val;
    b = buf[offset.get()];
    offset.increment();
    val |= (b & 0x7f) << 7;
    if (b < 0x80)
        return val;
    b = buf[offset.get()];
    offset.increment();
    val |= (b & 0x7f) << 14;
    if (b < 0x80)
        return val;
    b = buf[offset.get()];
    offset.increment();
    val |= (b & 0x7f) << 21;
    if (b < 0x80)
        return val;
    b = buf[offset.get()];
    val |= (b & 0x0f) << 28;
    return decodeVarintRemainder(val, buf, offset);
}
function decodeVarintRemainder(l, buf, offset) {
    let h;
    let b;
    b = buf[offset.get()];
    offset.increment();
    h = (b & 0x70) >> 4;
    if (b < 0x80)
        return h * 0x100000000 + (l >>> 0);
    b = buf[offset.get()];
    offset.increment();
    h |= (b & 0x7f) << 3;
    if (b < 0x80)
        return h * 0x100000000 + (l >>> 0);
    b = buf[offset.get()];
    offset.increment();
    h |= (b & 0x7f) << 10;
    if (b < 0x80)
        return h * 0x100000000 + (l >>> 0);
    b = buf[offset.get()];
    offset.increment();
    h |= (b & 0x7f) << 17;
    if (b < 0x80)
        return h * 0x100000000 + (l >>> 0);
    b = buf[offset.get()];
    offset.increment();
    h |= (b & 0x7f) << 24;
    if (b < 0x80)
        return h * 0x100000000 + (l >>> 0);
    b = buf[offset.get()];
    offset.increment();
    h |= (b & 0x01) << 31;
    if (b < 0x80)
        return h * 0x100000000 + (l >>> 0);
    throw new Error("Expected varint not more than 10 bytes");
}
function decodeFastPfor(encodedBytes, expectedValueCount, encodedByteLength, offset) {
    const workspace = createFastPforWireDecodeWorkspace(encodedByteLength >>> 2);
    return decodeFastPforWithWorkspace(encodedBytes, expectedValueCount, encodedByteLength, offset, workspace);
}
function decodeFastPforWithWorkspace(encodedBytes, expectedValueCount, encodedByteLength, offset, workspace) {
    const inputByteOffset = offset.get();
    if ((encodedByteLength & 3) !== 0) {
        throw new Error(`FastPFOR: invalid encodedByteLength=${encodedByteLength} at offset=${inputByteOffset} (encodedBytes.length=${encodedBytes.length}; expected a multiple of 4 bytes for an int32 big-endian word stream)`);
    }
    const encodedWordCount = encodedByteLength >>> 2;
    const encodedWordBuffer = ensureFastPforWireEncodedWordsCapacity(workspace, encodedWordCount);
    decodeBigEndianInt32sInto(encodedBytes, inputByteOffset, encodedByteLength, encodedWordBuffer);
    const decodedValues = decodeFastPforInt32(encodedWordBuffer.subarray(0, encodedWordCount), expectedValueCount, workspace.decoderWorkspace);
    offset.add(encodedByteLength);
    return decodedValues;
}
function decodeZigZagInt32Value(encoded) {
    return (encoded >>> 1) ^ -(encoded & 1);
}
function decodeZigZagInt64Value(encoded) {
    return (encoded >> 1n) ^ -(encoded & 1n);
}
function decodeZigZagFloat64Value(encoded) {
    return encoded % 2 === 1 ? (encoded + 1) / -2 : encoded / 2;
}
function decodeZigZagInt32(encodedData) {
    const decodedValues = new Int32Array(encodedData.length);
    for (let i = 0; i < encodedData.length; i++) {
        decodedValues[i] = decodeZigZagInt32Value(encodedData[i]);
    }
    return decodedValues;
}
function decodeZigZagInt64(encodedData) {
    const decodedValues = new BigInt64Array(encodedData.length);
    for (let i = 0; i < encodedData.length; i++) {
        decodedValues[i] = decodeZigZagInt64Value(encodedData[i]);
    }
    return decodedValues;
}
function decodeZigZagFloat64(encodedData) {
    for (let i = 0; i < encodedData.length; i++) {
        encodedData[i] = decodeZigZagFloat64Value(encodedData[i]);
    }
}
function decodeUnsignedRleInt32(encodedData, numRuns, numTotalValues) {
    // If numTotalValues not provided, calculate from runs (nullable case)
    if (numTotalValues === undefined) {
        numTotalValues = 0;
        for (let i = 0; i < numRuns; i++) {
            numTotalValues += encodedData[i];
        }
    }
    const decodedValues = new Uint32Array(numTotalValues);
    let offset = 0;
    for (let i = 0; i < numRuns; i++) {
        const runLength = encodedData[i];
        const value = encodedData[i + numRuns];
        decodedValues.fill(value, offset, offset + runLength);
        offset += runLength;
    }
    return decodedValues;
}
function decodeUnsignedRleInt64(encodedData, numRuns, numTotalValues) {
    // If numTotalValues not provided, calculate from runs (nullable case)
    if (numTotalValues === undefined) {
        numTotalValues = 0;
        for (let i = 0; i < numRuns; i++) {
            numTotalValues += Number(encodedData[i]);
        }
    }
    const decodedValues = new BigUint64Array(numTotalValues);
    let offset = 0;
    for (let i = 0; i < numRuns; i++) {
        const runLength = Number(encodedData[i]);
        const value = encodedData[i + numRuns];
        decodedValues.fill(value, offset, offset + runLength);
        offset += runLength;
    }
    return decodedValues;
}
function decodeUnsignedRleFloat64(encodedData, numRuns, numTotalValues) {
    const decodedValues = new Float64Array(numTotalValues);
    let offset = 0;
    for (let i = 0; i < numRuns; i++) {
        const runLength = encodedData[i];
        const value = encodedData[i + numRuns];
        decodedValues.fill(value, offset, offset + runLength);
        offset += runLength;
    }
    return decodedValues;
}
/*
 * In place decoding of the zigzag encoded delta values.
 * Inspired by https://github.com/lemire/JavaFastPFOR/blob/master/src/main/java/me/lemire/integercompression/differential/Delta.java
 */
function decodeZigZagDeltaInt32(data) {
    const decodedValues = new Int32Array(data.length);
    decodedValues[0] = decodeZigZagInt32Value(data[0]);
    const sz0 = (data.length / 4) * 4;
    let i = 1;
    if (sz0 >= 4) {
        for (; i < sz0 - 4; i += 4) {
            const data1 = data[i];
            const data2 = data[i + 1];
            const data3 = data[i + 2];
            const data4 = data[i + 3];
            decodedValues[i] = decodeZigZagInt32Value(data1) + decodedValues[i - 1];
            decodedValues[i + 1] = decodeZigZagInt32Value(data2) + decodedValues[i];
            decodedValues[i + 2] = decodeZigZagInt32Value(data3) + decodedValues[i + 1];
            decodedValues[i + 3] = decodeZigZagInt32Value(data4) + decodedValues[i + 2];
        }
    }
    for (; i !== data.length; ++i) {
        decodedValues[i] = decodeZigZagInt32Value(data[i]) + decodedValues[i - 1];
    }
    return decodedValues;
}
function decodeZigZagDeltaInt64(data) {
    const decodedValues = new BigInt64Array(data.length);
    decodedValues[0] = decodeZigZagInt64Value(data[0]);
    const sz0 = (data.length / 4) * 4;
    let i = 1;
    if (sz0 >= 4) {
        for (; i < sz0 - 4; i += 4) {
            const data1 = data[i];
            const data2 = data[i + 1];
            const data3 = data[i + 2];
            const data4 = data[i + 3];
            decodedValues[i] = decodeZigZagInt64Value(data1) + decodedValues[i - 1];
            decodedValues[i + 1] = decodeZigZagInt64Value(data2) + decodedValues[i];
            decodedValues[i + 2] = decodeZigZagInt64Value(data3) + decodedValues[i + 1];
            decodedValues[i + 3] = decodeZigZagInt64Value(data4) + decodedValues[i + 2];
        }
    }
    for (; i !== decodedValues.length; ++i) {
        decodedValues[i] = decodeZigZagInt64Value(data[i]) + decodedValues[i - 1];
    }
    return decodedValues;
}
function decodeZigZagDeltaFloat64(data) {
    data[0] = decodeZigZagFloat64Value(data[0]);
    const sz0 = (data.length / 4) * 4;
    let i = 1;
    if (sz0 >= 4) {
        for (; i < sz0 - 4; i += 4) {
            const data1 = data[i];
            const data2 = data[i + 1];
            const data3 = data[i + 2];
            const data4 = data[i + 3];
            data[i] = decodeZigZagFloat64Value(data1) + data[i - 1];
            data[i + 1] = decodeZigZagFloat64Value(data2) + data[i];
            data[i + 2] = decodeZigZagFloat64Value(data3) + data[i + 1];
            data[i + 3] = decodeZigZagFloat64Value(data4) + data[i + 2];
        }
    }
    for (; i !== data.length; ++i) {
        data[i] = decodeZigZagFloat64Value(data[i]) + data[i - 1];
    }
}
function decodeZigZagRleInt32(data, numRuns, numTotalValues) {
    // If numTotalValues not provided, calculate from runs (nullable case)
    if (numTotalValues === undefined) {
        numTotalValues = 0;
        for (let i = 0; i < numRuns; i++) {
            numTotalValues += data[i];
        }
    }
    const decodedValues = new Int32Array(numTotalValues);
    let offset = 0;
    for (let i = 0; i < numRuns; i++) {
        const runLength = data[i];
        let value = data[i + numRuns];
        value = decodeZigZagInt32Value(value);
        decodedValues.fill(value, offset, offset + runLength);
        offset += runLength;
    }
    return decodedValues;
}
function decodeZigZagRleInt64(data, numRuns, numTotalValues) {
    // If numTotalValues not provided, calculate from runs (nullable case)
    if (numTotalValues === undefined) {
        numTotalValues = 0;
        for (let i = 0; i < numRuns; i++) {
            numTotalValues += Number(data[i]);
        }
    }
    const decodedValues = new BigInt64Array(numTotalValues);
    let offset = 0;
    for (let i = 0; i < numRuns; i++) {
        const runLength = Number(data[i]);
        let value = data[i + numRuns];
        value = decodeZigZagInt64Value(value);
        decodedValues.fill(value, offset, offset + runLength);
        offset += runLength;
    }
    return decodedValues;
}
function decodeZigZagRleFloat64(data, numRuns, numTotalValues) {
    const decodedValues = new Float64Array(numTotalValues);
    let offset = 0;
    for (let i = 0; i < numRuns; i++) {
        const runLength = data[i];
        let value = data[i + numRuns];
        value = decodeZigZagFloat64Value(value);
        decodedValues.fill(value, offset, offset + runLength);
        offset += runLength;
    }
    return decodedValues;
}
/*
 * Inspired by https://github.com/lemire/JavaFastPFOR/blob/master/src/main/java/me/lemire/integercompression/differential/Delta.java
 */
function fastInverseDelta(data) {
    const sz0 = (data.length / 4) * 4;
    let i = 1;
    if (sz0 >= 4) {
        for (let a = data[0]; i < sz0 - 4; i += 4) {
            a = data[i] += a;
            a = data[i + 1] += a;
            a = data[i + 2] += a;
            a = data[i + 3] += a;
        }
    }
    while (i !== data.length) {
        data[i] += data[i - 1];
        ++i;
    }
}
function inverseDelta(data) {
    let prevValue = 0;
    for (let i = 0; i < data.length; i++) {
        data[i] += prevValue;
        prevValue = data[i];
    }
}
/*
 * In place decoding of the zigzag delta encoded Vec2.
 * Inspired by https://github.com/lemire/JavaFastPFOR/blob/master/src/main/java/me/lemire/integercompression/differential/Delta.java
 */
function decodeComponentwiseDeltaVec2(data) {
    if (data.length < 2)
        return new Int32Array(data);
    const decodedData = new Int32Array(data.length);
    decodedData[0] = decodeZigZagInt32Value(data[0]);
    decodedData[1] = decodeZigZagInt32Value(data[1]);
    const sz0 = (data.length / 4) * 4;
    let i = 2;
    if (sz0 >= 4) {
        for (; i < sz0 - 4; i += 4) {
            const x1 = data[i];
            const y1 = data[i + 1];
            const x2 = data[i + 2];
            const y2 = data[i + 3];
            decodedData[i] = decodeZigZagInt32Value(x1) + decodedData[i - 2];
            decodedData[i + 1] = decodeZigZagInt32Value(y1) + decodedData[i - 1];
            decodedData[i + 2] = decodeZigZagInt32Value(x2) + decodedData[i];
            decodedData[i + 3] = decodeZigZagInt32Value(y2) + decodedData[i + 1];
        }
    }
    for (; i !== data.length; i += 2) {
        decodedData[i] = decodeZigZagInt32Value(data[i]) + decodedData[i - 2];
        decodedData[i + 1] = decodeZigZagInt32Value(data[i + 1]) + decodedData[i - 1];
    }
    return decodedData;
}
function decodeComponentwiseDeltaVec2Scaled(data, scale, min, max) {
    if (data.length < 2)
        return new Int32Array(data);
    const decodedData = new Int32Array(data.length);
    let previousVertexX = decodeZigZagInt32Value(data[0]);
    let previousVertexY = decodeZigZagInt32Value(data[1]);
    decodedData[0] = clamp(Math.round(previousVertexX * scale), min, max);
    decodedData[1] = clamp(Math.round(previousVertexY * scale), min, max);
    const sz0 = data.length / 16;
    let i = 2;
    if (sz0 >= 4) {
        for (; i < sz0 - 4; i += 4) {
            const x1 = data[i];
            const y1 = data[i + 1];
            const currentVertexX = decodeZigZagInt32Value(x1) + previousVertexX;
            const currentVertexY = decodeZigZagInt32Value(y1) + previousVertexY;
            decodedData[i] = clamp(Math.round(currentVertexX * scale), min, max);
            decodedData[i + 1] = clamp(Math.round(currentVertexY * scale), min, max);
            const x2 = data[i + 2];
            const y2 = data[i + 3];
            previousVertexX = decodeZigZagInt32Value(x2) + currentVertexX;
            previousVertexY = decodeZigZagInt32Value(y2) + currentVertexY;
            decodedData[i + 2] = clamp(Math.round(previousVertexX * scale), min, max);
            decodedData[i + 3] = clamp(Math.round(previousVertexY * scale), min, max);
        }
    }
    for (; i !== data.length; i += 2) {
        previousVertexX += decodeZigZagInt32Value(data[i]);
        previousVertexY += decodeZigZagInt32Value(data[i + 1]);
        decodedData[i] = clamp(Math.round(previousVertexX * scale), min, max);
        decodedData[i + 1] = clamp(Math.round(previousVertexY * scale), min, max);
    }
    return decodedData;
}
function clamp(n, min, max) {
    return Math.min(max, Math.max(min, n));
}
/* Transform data to allow util access ------------------------------------------------------------------------ */
function decodeZigZagDeltaOfDeltaInt32(data) {
    const decodedData = new Int32Array(data.length + 1);
    decodedData[0] = 0;
    decodedData[1] = decodeZigZagInt32Value(data[0]);
    let deltaSum = decodedData[1];
    for (let i = 2; i !== decodedData.length; ++i) {
        const zigZagValue = data[i - 1];
        const delta = decodeZigZagInt32Value(zigZagValue);
        deltaSum += delta;
        decodedData[i] = decodedData[i - 1] + deltaSum;
    }
    return new Uint32Array(decodedData);
}
function decodeZigZagRleDeltaInt32(data, numRuns, numTotalValues) {
    const decodedValues = new Int32Array(numTotalValues + 1);
    decodedValues[0] = 0;
    let offset = 1;
    let previousValue = decodedValues[0];
    for (let i = 0; i < numRuns; i++) {
        const runLength = data[i];
        let value = data[i + numRuns];
        value = decodeZigZagInt32Value(value);
        for (let j = offset; j < offset + runLength; j++) {
            decodedValues[j] = value + previousValue;
            previousValue = decodedValues[j];
        }
        offset += runLength;
    }
    return decodedValues;
}
function decodeRleDeltaInt32(data, numRuns, numTotalValues) {
    const decodedValues = new Uint32Array(numTotalValues + 1);
    decodedValues[0] = 0;
    let offset = 1;
    let previousValue = decodedValues[0];
    for (let i = 0; i < numRuns; i++) {
        const runLength = data[i];
        const value = data[i + numRuns];
        for (let j = offset; j < offset + runLength; j++) {
            decodedValues[j] = value + previousValue;
            previousValue = decodedValues[j];
        }
        offset += runLength;
    }
    return decodedValues;
}
/**
 * Decode Delta-RLE with multiple runs by fully reconstructing values.
 *
 * @param data RLE encoded data: [run1, run2, ..., value1, value2, ...]
 * @param numRuns Number of runs in the RLE encoding
 * @param numValues Total number of values to reconstruct
 * @returns Reconstructed values with deltas applied
 */
function decodeDeltaRleInt32(data, numRuns, numValues) {
    const result = new Int32Array(numValues);
    let outPos = 0;
    let previousValue = 0;
    for (let i = 0; i < numRuns; i++) {
        const runLength = data[i];
        const zigZagDelta = data[i + numRuns];
        const delta = decodeZigZagInt32Value(zigZagDelta);
        for (let j = 0; j < runLength; j++) {
            previousValue += delta;
            result[outPos++] = previousValue;
        }
    }
    return result;
}
/**
 * Decode Delta-RLE with multiple runs for 64-bit integers.
 */
function decodeDeltaRleInt64(data, numRuns, numValues) {
    const result = new BigInt64Array(numValues);
    let outPos = 0;
    let previousValue = 0n;
    for (let i = 0; i < numRuns; i++) {
        const runLength = Number(data[i]);
        const zigZagDelta = data[i + numRuns];
        const delta = decodeZigZagInt64Value(zigZagDelta);
        for (let j = 0; j < runLength; j++) {
            previousValue += delta;
            result[outPos++] = previousValue;
        }
    }
    return result;
}
function decodeUnsignedZigZagDeltaInt32(data) {
    const decodedValues = new Uint32Array(data.length);
    decodedValues[0] = decodeZigZagInt32Value(data[0]) >>> 0;
    for (let i = 1; i < data.length; i++) {
        decodedValues[i] = (decodedValues[i - 1] + decodeZigZagInt32Value(data[i])) >>> 0;
    }
    return decodedValues;
}
function decodeUnsignedZigZagDeltaInt64(data) {
    const decodedValues = new BigUint64Array(data.length);
    decodedValues[0] = BigInt.asUintN(64, decodeZigZagInt64Value(data[0]));
    for (let i = 1; i < data.length; i++) {
        decodedValues[i] = BigInt.asUintN(64, decodedValues[i - 1] + decodeZigZagInt64Value(data[i]));
    }
    return decodedValues;
}
function decodeUnsignedComponentwiseDeltaVec2(data) {
    if (data.length < 2) {
        return new Uint32Array(data);
    }
    const decodedData = new Uint32Array(data.length);
    decodedData[0] = decodeZigZagInt32Value(data[0]) >>> 0;
    decodedData[1] = decodeZigZagInt32Value(data[1]) >>> 0;
    for (let i = 2; i < data.length; i += 2) {
        decodedData[i] = (decodedData[i - 2] + decodeZigZagInt32Value(data[i])) >>> 0;
        decodedData[i + 1] = (decodedData[i - 1] + decodeZigZagInt32Value(data[i + 1])) >>> 0;
    }
    return decodedData;
}
function decodeUnsignedComponentwiseDeltaVec2Scaled(data, scale, min, max) {
    const scaledValues = decodeComponentwiseDeltaVec2Scaled(data, scale, min, max);
    return new Uint32Array(scaledValues);
}
function decodeUnsignedConstRleInt32(data) {
    return data[1];
}
function decodeZigZagConstRleInt32(data) {
    return decodeZigZagInt32Value(data[1]);
}
function decodeZigZagSequenceRleInt32(data) {
    /* base value and delta value are equal */
    if (data.length === 2) {
        const value = decodeZigZagInt32Value(data[1]);
        return [value, value];
    }
    /* base value and delta value are not equal -> 2 runs and 2 values*/
    const base = decodeZigZagInt32Value(data[2]);
    const delta = decodeZigZagInt32Value(data[3]);
    return [base, delta];
}
function decodeUnsignedConstRleInt64(data) {
    return data[1];
}
function decodeZigZagConstRleInt64(data) {
    return decodeZigZagInt64Value(data[1]);
}
function decodeZigZagSequenceRleInt64(data) {
    /* base value and delta value are equal */
    if (data.length === 2) {
        const value = decodeZigZagInt64Value(data[1]);
        return [value, value];
    }
    /* base value and delta value are not equal -> 2 runs and 2 values*/
    const base = decodeZigZagInt64Value(data[2]);
    const delta = decodeZigZagInt64Value(data[3]);
    return [base, delta];
}

var PhysicalStreamType;
(function (PhysicalStreamType) {
    PhysicalStreamType["PRESENT"] = "PRESENT";
    PhysicalStreamType["DATA"] = "DATA";
    PhysicalStreamType["OFFSET"] = "OFFSET";
    PhysicalStreamType["LENGTH"] = "LENGTH";
})(PhysicalStreamType || (PhysicalStreamType = {}));

var DictionaryType;
(function (DictionaryType) {
    DictionaryType["NONE"] = "NONE";
    DictionaryType["SINGLE"] = "SINGLE";
    DictionaryType["SHARED"] = "SHARED";
    DictionaryType["VERTEX"] = "VERTEX";
    DictionaryType["MORTON"] = "MORTON";
    DictionaryType["FSST"] = "FSST";
})(DictionaryType || (DictionaryType = {}));

var OffsetType;
(function (OffsetType) {
    OffsetType["VERTEX"] = "VERTEX";
    OffsetType["INDEX"] = "INDEX";
    OffsetType["STRING"] = "STRING";
    OffsetType["KEY"] = "KEY";
})(OffsetType || (OffsetType = {}));

var LengthType;
(function (LengthType) {
    LengthType["VAR_BINARY"] = "VAR_BINARY";
    LengthType["GEOMETRIES"] = "GEOMETRIES";
    LengthType["PARTS"] = "PARTS";
    LengthType["RINGS"] = "RINGS";
    LengthType["TRIANGLES"] = "TRIANGLES";
    LengthType["SYMBOL"] = "SYMBOL";
    LengthType["DICTIONARY"] = "DICTIONARY";
})(LengthType || (LengthType = {}));

function decodeStreamMetadata(tile, offset) {
    const streamMetadata = decodeStreamMetadataInternal(tile, offset);
    if (streamMetadata.logicalLevelTechnique1 === LogicalLevelTechnique.MORTON) {
        return decodePartialMortonEncodedStreamMetadata(streamMetadata, tile, offset);
    }
    if ((LogicalLevelTechnique.RLE === streamMetadata.logicalLevelTechnique1 ||
        LogicalLevelTechnique.RLE === streamMetadata.logicalLevelTechnique2) &&
        PhysicalLevelTechnique.NONE !== streamMetadata.physicalLevelTechnique) {
        return decodePartialRleEncodedStreamMetadata(streamMetadata, tile, offset);
    }
    return streamMetadata;
}
function decodePartialMortonEncodedStreamMetadata(streamMetadata, tile, offset) {
    const mortonInfo = decodeVarintInt32(tile, offset, 2);
    return {
        physicalStreamType: streamMetadata.physicalStreamType,
        logicalStreamType: streamMetadata.logicalStreamType,
        logicalLevelTechnique1: streamMetadata.logicalLevelTechnique1,
        logicalLevelTechnique2: streamMetadata.logicalLevelTechnique2,
        physicalLevelTechnique: streamMetadata.physicalLevelTechnique,
        numValues: streamMetadata.numValues,
        byteLength: streamMetadata.byteLength,
        decompressedCount: streamMetadata.decompressedCount,
        numBits: mortonInfo[0],
        coordinateShift: mortonInfo[1],
    };
}
function decodePartialRleEncodedStreamMetadata(streamMetadata, tile, offset) {
    const rleInfo = decodeVarintInt32(tile, offset, 2);
    return {
        physicalStreamType: streamMetadata.physicalStreamType,
        logicalStreamType: streamMetadata.logicalStreamType,
        logicalLevelTechnique1: streamMetadata.logicalLevelTechnique1,
        logicalLevelTechnique2: streamMetadata.logicalLevelTechnique2,
        physicalLevelTechnique: streamMetadata.physicalLevelTechnique,
        numValues: streamMetadata.numValues,
        byteLength: streamMetadata.byteLength,
        decompressedCount: rleInfo[1],
        runs: rleInfo[0],
        numRleValues: rleInfo[1],
    };
}
function decodeStreamMetadataInternal(tile, offset) {
    const stream_type = tile[offset.get()];
    const physicalStreamType = Object.values(PhysicalStreamType)[stream_type >> 4];
    let logicalStreamType = null;
    switch (physicalStreamType) {
        case PhysicalStreamType.DATA:
            logicalStreamType = {
                dictionaryType: Object.values(DictionaryType)[stream_type & 0xf],
            };
            break;
        case PhysicalStreamType.OFFSET:
            logicalStreamType = {
                offsetType: Object.values(OffsetType)[stream_type & 0xf],
            };
            break;
        case PhysicalStreamType.LENGTH:
            logicalStreamType = {
                lengthType: Object.values(LengthType)[stream_type & 0xf],
            };
            break;
    }
    offset.increment();
    const encodings_header = tile[offset.get()];
    const llt1 = Object.values(LogicalLevelTechnique)[encodings_header >> 5];
    const llt2 = Object.values(LogicalLevelTechnique)[(encodings_header >> 2) & 0x7];
    const plt = Object.values(PhysicalLevelTechnique)[encodings_header & 0x3];
    offset.increment();
    const sizeInfo = decodeVarintInt32(tile, offset, 2);
    const numValues = sizeInfo[0];
    const byteLength = sizeInfo[1];
    return {
        physicalStreamType,
        logicalStreamType,
        logicalLevelTechnique1: llt1,
        logicalLevelTechnique2: llt2,
        physicalLevelTechnique: plt,
        numValues,
        byteLength,
        decompressedCount: numValues,
    };
}

var VectorType;
(function (VectorType) {
    VectorType[VectorType["FLAT"] = 0] = "FLAT";
    VectorType[VectorType["CONST"] = 1] = "CONST";
    VectorType[VectorType["SEQUENCE"] = 2] = "SEQUENCE";
    VectorType[VectorType["DICTIONARY"] = 3] = "DICTIONARY";
    VectorType[VectorType["FSST_DICTIONARY"] = 4] = "FSST_DICTIONARY";
})(VectorType || (VectorType = {}));

class BitVector {
    /**
     * @param values The byte buffer containing the bit values in least-significant bit (LSB)
     *     numbering
     */
    constructor(values, size) {
        this.values = values;
        this._size = size;
    }
    get(index) {
        const byteIndex = Math.floor(index / 8);
        const bitIndex = index % 8;
        const b = this.values[byteIndex];
        return ((b >> bitIndex) & 1) === 1;
    }
    set(index, value) {
        //TODO: refactor -> improve quick and dirty solution
        const byteIndex = Math.floor(index / 8);
        const bitIndex = index % 8;
        this.values[byteIndex] = this.values[byteIndex] | ((value ? 1 : 0) << bitIndex);
    }
    getInt(index) {
        const byteIndex = Math.floor(index / 8);
        const bitIndex = index % 8;
        const b = this.values[byteIndex];
        return (b >> bitIndex) & 1;
    }
    size() {
        return this._size;
    }
    getBuffer() {
        return this.values;
    }
}

/**
 * Generic unpacking function.
 * Reconstructs the full array by inserting default values at null positions.
 *
 * @param dataStream The compact data stream containing only non-null values
 * @param presentBits BitVector indicating which positions have values (null if non-nullable)
 * @param defaultValue The default value to insert at null positions (0, 0n, etc.)
 * @returns Full array with default values at null positions
 */
function unpackNullable(dataStream, presentBits, defaultValue) {
    // Non-nullable case: return data stream as-is
    if (!presentBits) {
        return dataStream;
    }
    const size = presentBits.size();
    // Create new array of same type with full size
    const constructor = dataStream.constructor;
    const result = new constructor(size);
    let counter = 0;
    for (let i = 0; i < size; i++) {
        // If position has a value, take from data stream; otherwise use default
        result[i] = presentBits.get(i) ? dataStream[counter++] : defaultValue;
    }
    return result;
}
/**
 * Special case for boolean columns because BitVector is not directly compatible with TypedArray.
 *
 * @param dataStream The compact BitVector data containing only non-null boolean values
 * @param dataStreamSize The number of actual values in dataStream
 * @param presentBits BitVector indicating which positions have values (null if non-nullable)
 * @returns Uint8Array buffer for BitVector with false at null positions
 */
function unpackNullableBoolean(dataStream, dataStreamSize, presentBits) {
    // Non-nullable case
    if (!presentBits) {
        return dataStream;
    }
    const numFeatures = presentBits.size();
    const bitVector = new BitVector(dataStream, dataStreamSize);
    const result = new BitVector(new Uint8Array(Math.ceil(numFeatures / 8)), numFeatures);
    let counter = 0;
    for (let i = 0; i < numFeatures; i++) {
        // If position has a value, take from data stream; otherwise use false
        const value = presentBits.get(i) ? bitVector.get(counter++) : false;
        result.set(i, value);
    }
    return result.getBuffer();
}

function decodeSignedInt32Stream(data, offset, streamMetadata, scalingData, nullabilityBuffer) {
    const values = decodePhysicalLevelTechnique(data, offset, streamMetadata);
    return decodeSignedInt32(values, streamMetadata, scalingData, nullabilityBuffer);
}
function decodeUnsignedInt32Stream(data, offset, streamMetadata, scalingData, nullabilityBuffer) {
    const values = decodePhysicalLevelTechnique(data, offset, streamMetadata);
    return decodeUnsignedInt32(values, streamMetadata, scalingData, nullabilityBuffer);
}
function decodeLengthStreamToOffsetBuffer(data, offset, streamMetadata) {
    const values = decodePhysicalLevelTechnique(data, offset, streamMetadata);
    return decodeLengthToOffsetBuffer(values, streamMetadata);
}
function decodePhysicalLevelTechnique(data, offset, streamMetadata) {
    const physicalLevelTechnique = streamMetadata.physicalLevelTechnique;
    switch (physicalLevelTechnique) {
        case PhysicalLevelTechnique.FAST_PFOR:
            return decodeFastPfor(data, streamMetadata.numValues, streamMetadata.byteLength, offset);
        case PhysicalLevelTechnique.VARINT:
            return decodeVarintInt32(data, offset, streamMetadata.numValues);
        case PhysicalLevelTechnique.NONE: {
            const dataOffset = offset.get();
            const byteLength = streamMetadata.byteLength;
            offset.add(byteLength);
            const slice = data.subarray(dataOffset, offset.get());
            return new Uint32Array(slice);
        }
        default:
            throw new Error(`Specified physicalLevelTechnique ${physicalLevelTechnique} is not supported (yet).`);
    }
}
function decodeSignedConstInt32Stream(data, offset, streamMetadata) {
    const values = decodePhysicalLevelTechnique(data, offset, streamMetadata);
    if (values.length === 1) {
        return decodeZigZagInt32Value(values[0]);
    }
    return decodeZigZagConstRleInt32(values);
}
function decodeUnsignedConstInt32Stream(data, offset, streamMetadata) {
    const values = decodePhysicalLevelTechnique(data, offset, streamMetadata);
    if (values.length === 1) {
        return values[0];
    }
    return decodeUnsignedConstRleInt32(values);
}
function decodeSequenceInt32Stream(data, offset, streamMetadata) {
    const values = decodePhysicalLevelTechnique(data, offset, streamMetadata);
    return decodeZigZagSequenceRleInt32(values);
}
function decodeSequenceInt64Stream(data, offset, streamMetadata) {
    const values = decodeVarintInt64(data, offset, streamMetadata.numValues);
    return decodeZigZagSequenceRleInt64(values);
}
function decodeSignedInt64Stream(data, offset, streamMetadata, nullabilityBuffer) {
    const values = decodeVarintInt64(data, offset, streamMetadata.numValues);
    return decodeSignedInt64(values, streamMetadata, nullabilityBuffer);
}
function decodeUnsignedInt64Stream(data, offset, streamMetadata, nullabilityBuffer) {
    const values = decodeVarintInt64(data, offset, streamMetadata.numValues);
    return decodeUnsignedInt64(values, streamMetadata, nullabilityBuffer);
}
function decodeSignedInt64AsFloat64Stream(data, offset, streamMetadata) {
    const values = decodeVarintFloat64(data, offset, streamMetadata.numValues);
    return decodeFloat64Values(values, streamMetadata, true);
}
function decodeUnsignedInt64AsFloat64Stream(data, offset, streamMetadata) {
    const values = decodeVarintFloat64(data, offset, streamMetadata.numValues);
    return decodeFloat64Values(values, streamMetadata, false);
}
function decodeSignedConstInt64Stream(data, offset, streamMetadata) {
    const values = decodeVarintInt64(data, offset, streamMetadata.numValues);
    if (values.length === 1) {
        return decodeZigZagInt64Value(values[0]);
    }
    return decodeZigZagConstRleInt64(values);
}
function decodeUnsignedConstInt64Stream(data, offset, streamMetadata) {
    const values = decodeVarintInt64(data, offset, streamMetadata.numValues);
    if (values.length === 1) {
        return values[0];
    }
    return decodeUnsignedConstRleInt64(values);
}
/**
 * This method decodes integer streams.
 * Currently the encoder uses only fixed combinations of encodings.
 * For performance reasons it is also uses a fixed combination of the encodings on the decoding side.
 * The following encodings and combinations are used:
 *   - Morton Delta -> always sorted so not ZigZag encoding needed
 *   - Delta -> currently always in combination with ZigZag encoding
 *   - Rle -> in combination with ZigZag encoding if data type is signed
 *   - Delta Rle
 *   - Componentwise Delta -> always ZigZag encoding is used
 */
function decodeSignedInt32(values, streamMetadata, scalingData, nullabilityBuffer) {
    let decodedValues;
    switch (streamMetadata.logicalLevelTechnique1) {
        case LogicalLevelTechnique.DELTA:
            if (streamMetadata.logicalLevelTechnique2 === LogicalLevelTechnique.RLE) {
                const rleMetadata = streamMetadata;
                if (!nullabilityBuffer) {
                    return decodeDeltaRleInt32(values, rleMetadata.runs, rleMetadata.numRleValues);
                }
                values = decodeUnsignedRleInt32(values, rleMetadata.runs, rleMetadata.numRleValues);
                decodedValues = decodeZigZagDeltaInt32(values);
            }
            else {
                decodedValues = decodeZigZagDeltaInt32(values);
            }
            break;
        case LogicalLevelTechnique.RLE:
            decodedValues = decodeZigZagRleInt32(values, streamMetadata.runs, streamMetadata.numRleValues);
            break;
        case LogicalLevelTechnique.MORTON:
            fastInverseDelta(values);
            decodedValues = new Int32Array(values);
            break;
        case LogicalLevelTechnique.COMPONENTWISE_DELTA:
            if (scalingData && !nullabilityBuffer) {
                return decodeComponentwiseDeltaVec2Scaled(values, scalingData.scale, scalingData.min, scalingData.max);
            }
            decodedValues = decodeComponentwiseDeltaVec2(values);
            break;
        case LogicalLevelTechnique.NONE:
            decodedValues = decodeZigZagInt32(values);
            break;
        default:
            throw new Error(`The specified Logical level technique is not supported: ${streamMetadata.logicalLevelTechnique1}`);
    }
    if (nullabilityBuffer) {
        return unpackNullable(decodedValues, nullabilityBuffer, 0);
    }
    return decodedValues;
}
function decodeUnsignedInt32(values, streamMetadata, scalingData, nullabilityBuffer) {
    let decodedValues;
    switch (streamMetadata.logicalLevelTechnique1) {
        case LogicalLevelTechnique.DELTA:
            if (streamMetadata.logicalLevelTechnique2 === LogicalLevelTechnique.RLE) {
                const rleMetadata = streamMetadata;
                const deltaValues = decodeUnsignedRleInt32(values, rleMetadata.runs, rleMetadata.numRleValues);
                decodedValues = decodeUnsignedZigZagDeltaInt32(deltaValues);
            }
            else {
                decodedValues = decodeUnsignedZigZagDeltaInt32(values);
            }
            break;
        case LogicalLevelTechnique.RLE:
            decodedValues = decodeUnsignedRleInt32(values, streamMetadata.runs, streamMetadata.numRleValues);
            break;
        case LogicalLevelTechnique.MORTON:
            fastInverseDelta(values);
            decodedValues = values;
            break;
        case LogicalLevelTechnique.COMPONENTWISE_DELTA:
            if (scalingData && !nullabilityBuffer) {
                decodedValues = decodeUnsignedComponentwiseDeltaVec2Scaled(values, scalingData.scale, scalingData.min, scalingData.max);
            }
            else {
                decodedValues = decodeUnsignedComponentwiseDeltaVec2(values);
            }
            break;
        case LogicalLevelTechnique.NONE:
            decodedValues = values;
            break;
        default:
            throw new Error(`The specified Logical level technique is not supported: ${streamMetadata.logicalLevelTechnique1}`);
    }
    if (nullabilityBuffer) {
        return unpackNullable(decodedValues, nullabilityBuffer, 0);
    }
    return decodedValues;
}
function decodeSignedInt64(values, streamMetadata, nullabilityBuffer) {
    let decodedValues;
    switch (streamMetadata.logicalLevelTechnique1) {
        case LogicalLevelTechnique.DELTA:
            if (streamMetadata.logicalLevelTechnique2 === LogicalLevelTechnique.RLE) {
                const rleMetadata = streamMetadata;
                if (!nullabilityBuffer) {
                    return decodeDeltaRleInt64(values, rleMetadata.runs, rleMetadata.numRleValues);
                }
                values = decodeUnsignedRleInt64(values, rleMetadata.runs, rleMetadata.numRleValues);
                decodedValues = decodeZigZagDeltaInt64(values);
            }
            else {
                decodedValues = decodeZigZagDeltaInt64(values);
            }
            break;
        case LogicalLevelTechnique.RLE:
            decodedValues = decodeZigZagRleInt64(values, streamMetadata.runs, streamMetadata.numRleValues);
            break;
        case LogicalLevelTechnique.NONE:
            decodedValues = decodeZigZagInt64(values);
            break;
        default:
            throw new Error(`The specified Logical level technique is not supported: ${streamMetadata.logicalLevelTechnique1}`);
    }
    if (nullabilityBuffer) {
        return unpackNullable(decodedValues, nullabilityBuffer, 0n);
    }
    return decodedValues;
}
function decodeUnsignedInt64(values, streamMetadata, nullabilityBuffer) {
    let decodedValues;
    switch (streamMetadata.logicalLevelTechnique1) {
        case LogicalLevelTechnique.DELTA:
            if (streamMetadata.logicalLevelTechnique2 === LogicalLevelTechnique.RLE) {
                const rleMetadata = streamMetadata;
                const deltaValues = decodeUnsignedRleInt64(values, rleMetadata.runs, rleMetadata.numRleValues);
                decodedValues = decodeUnsignedZigZagDeltaInt64(deltaValues);
            }
            else {
                decodedValues = decodeUnsignedZigZagDeltaInt64(values);
            }
            break;
        case LogicalLevelTechnique.RLE:
            decodedValues = decodeUnsignedRleInt64(values, streamMetadata.runs, streamMetadata.numRleValues);
            break;
        case LogicalLevelTechnique.NONE:
            decodedValues = values;
            break;
        default:
            throw new Error(`The specified Logical level technique is not supported: ${streamMetadata.logicalLevelTechnique1}`);
    }
    if (nullabilityBuffer) {
        return unpackNullable(decodedValues, nullabilityBuffer, 0n);
    }
    return decodedValues;
}
function decodeFloat64Values(values, streamMetadata, isSigned) {
    switch (streamMetadata.logicalLevelTechnique1) {
        case LogicalLevelTechnique.DELTA:
            if (streamMetadata.logicalLevelTechnique2 === LogicalLevelTechnique.RLE) {
                const rleMetadata = streamMetadata;
                values = decodeUnsignedRleFloat64(values, rleMetadata.runs, rleMetadata.numRleValues);
            }
            decodeZigZagDeltaFloat64(values);
            return values;
        case LogicalLevelTechnique.RLE:
            return decodeRleFloat64(values, streamMetadata, isSigned);
        case LogicalLevelTechnique.NONE:
            if (isSigned) {
                decodeZigZagFloat64(values);
            }
            return values;
        default:
            throw new Error(`The specified Logical level technique is not supported: ${streamMetadata.logicalLevelTechnique1}`);
    }
}
function decodeLengthToOffsetBuffer(values, streamMetadata) {
    if (streamMetadata.logicalLevelTechnique1 === LogicalLevelTechnique.DELTA &&
        streamMetadata.logicalLevelTechnique2 === LogicalLevelTechnique.NONE) {
        return decodeZigZagDeltaOfDeltaInt32(values);
    }
    if (streamMetadata.logicalLevelTechnique1 === LogicalLevelTechnique.RLE &&
        streamMetadata.logicalLevelTechnique2 === LogicalLevelTechnique.NONE) {
        const rleMetadata = streamMetadata;
        return decodeRleDeltaInt32(values, rleMetadata.runs, rleMetadata.numRleValues);
    }
    if (streamMetadata.logicalLevelTechnique1 === LogicalLevelTechnique.NONE &&
        streamMetadata.logicalLevelTechnique2 === LogicalLevelTechnique.NONE) {
        //TODO: use fastInverseDelta again and check what are the performance problems in zoom 14
        //fastInverseDelta(values);
        inverseDelta(values);
        const offsets = new Uint32Array(streamMetadata.numValues + 1);
        offsets[0] = 0;
        offsets.set(values, 1);
        return offsets;
    }
    if (streamMetadata.logicalLevelTechnique1 === LogicalLevelTechnique.DELTA &&
        streamMetadata.logicalLevelTechnique2 === LogicalLevelTechnique.RLE) {
        const rleMetadata = streamMetadata;
        const decodedValues = decodeZigZagRleDeltaInt32(values, rleMetadata.runs, rleMetadata.numRleValues);
        fastInverseDelta(decodedValues);
        return new Uint32Array(decodedValues);
    }
    throw new Error("Only delta encoding is supported for transforming length to offset streams yet.");
}
function getVectorType(streamMetadata, sizeOrNullabilityBuffer, data, offset, varintWidth = "int32") {
    const logicalLevelTechnique1 = streamMetadata.logicalLevelTechnique1;
    if (logicalLevelTechnique1 === LogicalLevelTechnique.RLE) {
        return streamMetadata.runs === 1 ? VectorType.CONST : VectorType.FLAT;
    }
    if (logicalLevelTechnique1 !== LogicalLevelTechnique.DELTA ||
        streamMetadata.logicalLevelTechnique2 !== LogicalLevelTechnique.RLE) {
        return streamMetadata.numValues === 1 ? VectorType.CONST : VectorType.FLAT;
    }
    const numFeatures = sizeOrNullabilityBuffer instanceof BitVector ? sizeOrNullabilityBuffer.size() : sizeOrNullabilityBuffer;
    const rleMetadata = streamMetadata;
    if (rleMetadata.numRleValues !== numFeatures) {
        return VectorType.FLAT;
    }
    // Single run is always a sequence
    if (rleMetadata.runs === 1) {
        return VectorType.SEQUENCE;
    }
    if (rleMetadata.runs !== 2) {
        return streamMetadata.numValues === 1 ? VectorType.CONST : VectorType.FLAT;
    }
    // Two runs can be a sequence if both deltas are equal to 1
    const savedOffset = offset.get();
    if (streamMetadata.physicalLevelTechnique === PhysicalLevelTechnique.VARINT) {
        if (isDeltaRleSequenceVarintWidth(data, offset, varintWidth)) {
            return VectorType.SEQUENCE;
        }
        return streamMetadata.numValues === 1 ? VectorType.CONST : VectorType.FLAT;
    }
    const byteOffset = offset.get();
    const values = new Int32Array(data.buffer, data.byteOffset + byteOffset, 4);
    offset.set(savedOffset);
    // Check if both deltas are encoded 1
    const zigZagOne = 2;
    if (values[2] === zigZagOne && values[3] === zigZagOne) {
        return VectorType.SEQUENCE;
    }
    return streamMetadata.numValues === 1 ? VectorType.CONST : VectorType.FLAT;
}
function isDeltaRleSequenceVarintWidth(data, offset, varintWidth) {
    const peekOffset = new IntWrapper(offset.get());
    if (varintWidth === "int64") {
        const values = decodeVarintInt64(data, peekOffset, 4);
        return values[2] === 2n && values[3] === 2n;
    }
    const values = decodeVarintInt32(data, peekOffset, 4);
    return values[2] === 2 && values[3] === 2;
}
function decodeRleFloat64(data, streamMetadata, isSigned) {
    return isSigned
        ? decodeZigZagRleFloat64(data, streamMetadata.runs, streamMetadata.numRleValues)
        : decodeUnsignedRleFloat64(data, streamMetadata.runs, streamMetadata.numRleValues);
}

class Int64FlatVector extends FixedSizeVector {
    getValueFromBuffer(index) {
        return this.dataBuffer[index];
    }
}

class Int64SequenceVector extends SequenceVector {
    constructor(name, baseValue, delta, size) {
        super(name, BigInt64Array.of(baseValue), delta, size);
    }
    getValueFromBuffer(index) {
        return this.dataBuffer[0] + BigInt(index) * this.delta;
    }
}

function decodeZOrderCurve(mortonCode, numBits, coordinateShift) {
    const x = decodeMorton(mortonCode, numBits) - coordinateShift;
    const y = decodeMorton(mortonCode >> 1, numBits) - coordinateShift;
    return { x, y };
}
function decodeMorton(code, numBits) {
    let coordinate = 0;
    for (let i = 0; i < numBits; i++) {
        coordinate |= (code & (1 << (2 * i))) >> i;
    }
    return coordinate;
}

var GEOMETRY_TYPE;
(function (GEOMETRY_TYPE) {
    GEOMETRY_TYPE[GEOMETRY_TYPE["POINT"] = 0] = "POINT";
    GEOMETRY_TYPE[GEOMETRY_TYPE["LINESTRING"] = 1] = "LINESTRING";
    GEOMETRY_TYPE[GEOMETRY_TYPE["POLYGON"] = 2] = "POLYGON";
    GEOMETRY_TYPE[GEOMETRY_TYPE["MULTIPOINT"] = 3] = "MULTIPOINT";
    GEOMETRY_TYPE[GEOMETRY_TYPE["MULTILINESTRING"] = 4] = "MULTILINESTRING";
    GEOMETRY_TYPE[GEOMETRY_TYPE["MULTIPOLYGON"] = 5] = "MULTIPOLYGON";
})(GEOMETRY_TYPE || (GEOMETRY_TYPE = {}));
var SINGLE_PART_GEOMETRY_TYPE;
(function (SINGLE_PART_GEOMETRY_TYPE) {
    SINGLE_PART_GEOMETRY_TYPE[SINGLE_PART_GEOMETRY_TYPE["POINT"] = 0] = "POINT";
    SINGLE_PART_GEOMETRY_TYPE[SINGLE_PART_GEOMETRY_TYPE["LINESTRING"] = 1] = "LINESTRING";
    SINGLE_PART_GEOMETRY_TYPE[SINGLE_PART_GEOMETRY_TYPE["POLYGON"] = 2] = "POLYGON";
})(SINGLE_PART_GEOMETRY_TYPE || (SINGLE_PART_GEOMETRY_TYPE = {}));

var VertexBufferType;
(function (VertexBufferType) {
    VertexBufferType[VertexBufferType["MORTON"] = 0] = "MORTON";
    VertexBufferType[VertexBufferType["VEC_2"] = 1] = "VEC_2";
    VertexBufferType[VertexBufferType["VEC_3"] = 2] = "VEC_3";
})(VertexBufferType || (VertexBufferType = {}));

function convertGeometryVector(geometryVector) {
    const geometries = new Array(geometryVector.numGeometries);
    let partOffsetCounter = 1;
    let ringOffsetsCounter = 1;
    let geometryOffsetsCounter = 1;
    let geometryCounter = 0;
    let vertexBufferOffset = 0;
    let vertexOffsetsOffset = 0;
    const mortonSettings = geometryVector.mortonSettings;
    const topologyVector = geometryVector.topologyVector;
    const geometryOffsets = topologyVector.geometryOffsets;
    const partOffsets = topologyVector.partOffsets;
    const ringOffsets = topologyVector.ringOffsets;
    const vertexOffsets = geometryVector.vertexOffsets;
    const nonOffset = !vertexOffsets || vertexOffsets.length === 0;
    const containsPolygon = geometryVector.containsPolygonGeometry();
    const vertexBuffer = geometryVector.vertexBuffer;
    for (let i = 0; i < geometryVector.numGeometries; i++) {
        const geometryType = geometryVector.geometryType(i);
        switch (geometryType) {
            case GEOMETRY_TYPE.POINT:
                {
                    let x;
                    let y;
                    if (nonOffset) {
                        x = vertexBuffer[vertexBufferOffset++];
                        y = vertexBuffer[vertexBufferOffset++];
                    }
                    else if (geometryVector.vertexBufferType === VertexBufferType.MORTON) {
                        const offset = vertexOffsets[vertexOffsetsOffset++];
                        const mortonCode = vertexBuffer[offset];
                        const vertex = decodeZOrderCurve(mortonCode, mortonSettings.numBits, mortonSettings.coordinateShift);
                        x = vertex.x;
                        y = vertex.y;
                    }
                    else {
                        const offset = vertexOffsets[vertexOffsetsOffset++] * 2;
                        x = vertexBuffer[offset];
                        y = vertexBuffer[offset + 1];
                    }
                    geometries[geometryCounter++] = [[new Point(x, y)]];
                    if (geometryOffsets)
                        geometryOffsetsCounter++;
                    if (partOffsets)
                        partOffsetCounter++;
                    if (ringOffsets)
                        ringOffsetsCounter++;
                }
                break;
            case GEOMETRY_TYPE.MULTIPOINT:
                {
                    const numPoints = geometryOffsets[geometryOffsetsCounter] - geometryOffsets[geometryOffsetsCounter - 1];
                    geometryOffsetsCounter++;
                    const points = new Array(numPoints);
                    if (nonOffset) {
                        for (let j = 0; j < numPoints; j++) {
                            const x = vertexBuffer[vertexBufferOffset++];
                            const y = vertexBuffer[vertexBufferOffset++];
                            points[j] = new Point(x, y);
                        }
                    }
                    else {
                        for (let j = 0; j < numPoints; j++) {
                            const offset = vertexOffsets[vertexOffsetsOffset++] * 2;
                            const x = vertexBuffer[offset];
                            const y = vertexBuffer[offset + 1];
                            points[j] = new Point(x, y);
                        }
                    }
                    geometries[geometryCounter++] = points.map((point) => [point]);
                    // MULTIPOINT must increment offset counters like POINT does
                    partOffsetCounter += numPoints;
                    ringOffsetsCounter += numPoints;
                }
                break;
            case GEOMETRY_TYPE.LINESTRING:
                {
                    let numVertices;
                    if (containsPolygon) {
                        numVertices = ringOffsets[ringOffsetsCounter] - ringOffsets[ringOffsetsCounter - 1];
                        ringOffsetsCounter++;
                    }
                    else {
                        numVertices = partOffsets[partOffsetCounter] - partOffsets[partOffsetCounter - 1];
                    }
                    partOffsetCounter++;
                    let vertices;
                    if (nonOffset) {
                        vertices = getLineStringOrRing(vertexBuffer, vertexBufferOffset, numVertices, false);
                        vertexBufferOffset += numVertices * 2;
                    }
                    else {
                        vertices = decodeDictionaryEncodedLineStringOrRing(geometryVector.vertexBufferType, vertexBuffer, vertexOffsets, vertexOffsetsOffset, numVertices, false, mortonSettings);
                        vertexOffsetsOffset += numVertices;
                    }
                    geometries[geometryCounter++] = [vertices];
                    if (geometryOffsets)
                        geometryOffsetsCounter++;
                }
                break;
            case GEOMETRY_TYPE.POLYGON:
                {
                    const numRings = partOffsets[partOffsetCounter] - partOffsets[partOffsetCounter - 1];
                    partOffsetCounter++;
                    const rings = new Array(numRings - 1);
                    let shell;
                    let numVertices = ringOffsets[ringOffsetsCounter] - ringOffsets[ringOffsetsCounter - 1];
                    ringOffsetsCounter++;
                    if (nonOffset) {
                        shell = getLineStringOrRing(vertexBuffer, vertexBufferOffset, numVertices, true);
                        vertexBufferOffset += numVertices * 2;
                        for (let j = 0; j < rings.length; j++) {
                            numVertices = ringOffsets[ringOffsetsCounter] - ringOffsets[ringOffsetsCounter - 1];
                            ringOffsetsCounter++;
                            rings[j] = getLineStringOrRing(vertexBuffer, vertexBufferOffset, numVertices, true);
                            vertexBufferOffset += numVertices * 2;
                        }
                    }
                    else {
                        shell = decodeDictionaryEncodedLineStringOrRing(geometryVector.vertexBufferType, vertexBuffer, vertexOffsets, vertexOffsetsOffset, numVertices, true, mortonSettings);
                        vertexOffsetsOffset += numVertices;
                        for (let j = 0; j < rings.length; j++) {
                            numVertices = ringOffsets[ringOffsetsCounter] - ringOffsets[ringOffsetsCounter - 1];
                            ringOffsetsCounter++;
                            rings[j] = decodeDictionaryEncodedLineStringOrRing(geometryVector.vertexBufferType, vertexBuffer, vertexOffsets, vertexOffsetsOffset, numVertices, true, mortonSettings);
                            vertexOffsetsOffset += numVertices;
                        }
                    }
                    geometries[geometryCounter++] = [shell].concat(rings);
                    if (geometryOffsets)
                        geometryOffsetsCounter++;
                }
                break;
            case GEOMETRY_TYPE.MULTILINESTRING:
                {
                    const numLineStrings = geometryOffsets[geometryOffsetsCounter] - geometryOffsets[geometryOffsetsCounter - 1];
                    geometryOffsetsCounter++;
                    const lineStrings = new Array(numLineStrings);
                    for (let j = 0; j < numLineStrings; j++) {
                        let numVertices;
                        if (containsPolygon) {
                            numVertices = ringOffsets[ringOffsetsCounter] - ringOffsets[ringOffsetsCounter - 1];
                            ringOffsetsCounter++;
                        }
                        else {
                            numVertices = partOffsets[partOffsetCounter] - partOffsets[partOffsetCounter - 1];
                        }
                        partOffsetCounter++;
                        if (nonOffset) {
                            lineStrings[j] = getLineStringOrRing(vertexBuffer, vertexBufferOffset, numVertices, false);
                            vertexBufferOffset += numVertices * 2;
                        }
                        else {
                            const vertices = decodeDictionaryEncodedLineStringOrRing(geometryVector.vertexBufferType, vertexBuffer, vertexOffsets, vertexOffsetsOffset, numVertices, false, mortonSettings);
                            lineStrings[j] = vertices;
                            vertexOffsetsOffset += numVertices;
                        }
                    }
                    geometries[geometryCounter++] = lineStrings;
                }
                break;
            case GEOMETRY_TYPE.MULTIPOLYGON:
                {
                    const numPolygons = geometryOffsets[geometryOffsetsCounter] - geometryOffsets[geometryOffsetsCounter - 1];
                    geometryOffsetsCounter++;
                    const polygons = new Array(numPolygons);
                    for (let j = 0; j < numPolygons; j++) {
                        const numRings = partOffsets[partOffsetCounter] - partOffsets[partOffsetCounter - 1];
                        partOffsetCounter++;
                        let shell;
                        const rings = new Array(numRings - 1);
                        const numVertices = ringOffsets[ringOffsetsCounter] - ringOffsets[ringOffsetsCounter - 1];
                        ringOffsetsCounter++;
                        if (nonOffset) {
                            shell = getLineStringOrRing(vertexBuffer, vertexBufferOffset, numVertices, true);
                            vertexBufferOffset += numVertices * 2;
                        }
                        else {
                            shell = decodeDictionaryEncodedLineStringOrRing(geometryVector.vertexBufferType, vertexBuffer, vertexOffsets, vertexOffsetsOffset, numVertices, true, mortonSettings);
                            vertexOffsetsOffset += numVertices;
                        }
                        for (let k = 0; k < rings.length; k++) {
                            const numRingVertices = ringOffsets[ringOffsetsCounter] - ringOffsets[ringOffsetsCounter - 1];
                            ringOffsetsCounter++;
                            if (nonOffset) {
                                rings[k] = getLineStringOrRing(vertexBuffer, vertexBufferOffset, numRingVertices, true);
                                vertexBufferOffset += numRingVertices * 2;
                            }
                            else {
                                rings[k] = decodeDictionaryEncodedLineStringOrRing(geometryVector.vertexBufferType, vertexBuffer, vertexOffsets, vertexOffsetsOffset, numRingVertices, true, mortonSettings);
                                vertexOffsetsOffset += numRingVertices;
                            }
                        }
                        polygons[j] = [shell].concat(rings);
                    }
                    geometries[geometryCounter++] = polygons.flat();
                }
                break;
            default:
                throw new Error("The specified geometry type is currently not supported.");
        }
    }
    return geometries;
}
function decodeDictionaryEncodedLineStringOrRing(vertexBufferType, vertexBuffer, vertexOffsets, vertexOffset, numVertices, closeLineString, mortonSettings) {
    if (vertexBufferType === VertexBufferType.MORTON) {
        return decodeMortonDictionaryEncodedLineString(vertexBuffer, vertexOffsets, vertexOffset, numVertices, closeLineString, mortonSettings);
    }
    else {
        return decodeDictionaryEncodedLineString(vertexBuffer, vertexOffsets, vertexOffset, numVertices, closeLineString);
    }
}
function getLineStringOrRing(vertexBuffer, startIndex, numVertices, closeLineString) {
    const vertices = new Array(closeLineString ? numVertices + 1 : numVertices);
    for (let i = 0; i < numVertices * 2; i += 2) {
        const x = vertexBuffer[startIndex + i];
        const y = vertexBuffer[startIndex + i + 1];
        vertices[i / 2] = new Point(x, y);
    }
    if (closeLineString) {
        vertices[vertices.length - 1] = vertices[0];
    }
    return vertices;
}
function decodeDictionaryEncodedLineString(vertexBuffer, vertexOffsets, vertexOffset, numVertices, closeLineString) {
    const vertices = new Array(closeLineString ? numVertices + 1 : numVertices);
    for (let i = 0; i < numVertices * 2; i += 2) {
        const offset = vertexOffsets[vertexOffset + i / 2] * 2;
        const x = vertexBuffer[offset];
        const y = vertexBuffer[offset + 1];
        vertices[i / 2] = new Point(x, y);
    }
    if (closeLineString) {
        vertices[vertices.length - 1] = vertices[0];
    }
    return vertices;
}
function decodeMortonDictionaryEncodedLineString(vertexBuffer, vertexOffsets, vertexOffset, numVertices, closeLineString, mortonSettings) {
    const vertices = new Array(closeLineString ? numVertices + 1 : numVertices);
    for (let i = 0; i < numVertices; i++) {
        const offset = vertexOffsets[vertexOffset + i];
        const mortonEncodedVertex = vertexBuffer[offset];
        const vertex = decodeZOrderCurve(mortonEncodedVertex, mortonSettings.numBits, mortonSettings.coordinateShift);
        vertices[i] = new Point(vertex.x, vertex.y);
    }
    if (closeLineString) {
        vertices[vertices.length - 1] = vertices[0];
    }
    return vertices;
}

class GeometryVector {
    constructor(_vertexBufferType, _topologyVector, _vertexOffsets, _vertexBuffer, _mortonSettings) {
        this._vertexBufferType = _vertexBufferType;
        this._topologyVector = _topologyVector;
        this._vertexOffsets = _vertexOffsets;
        this._vertexBuffer = _vertexBuffer;
        this._mortonSettings = _mortonSettings;
    }
    get vertexBufferType() {
        return this._vertexBufferType;
    }
    get topologyVector() {
        return this._topologyVector;
    }
    get vertexOffsets() {
        return this._vertexOffsets;
    }
    get vertexBuffer() {
        return this._vertexBuffer;
    }
    /* Allows faster access to the vertices since morton encoding is currently not used in the POC. Morton encoding
       will be used after adapting the shader to decode the morton codes on the GPU. */
    getSimpleEncodedVertex(index) {
        const offset = this.vertexOffsets ? this.vertexOffsets[index] * 2 : index * 2;
        const x = this.vertexBuffer[offset];
        const y = this.vertexBuffer[offset + 1];
        return [x, y];
    }
    //TODO: add scaling information to the constructor
    getVertex(index) {
        if (this.vertexOffsets && this.mortonSettings) {
            //TODO: move decoding of the morton codes on the GPU in the vertex shader
            const vertexOffset = this.vertexOffsets[index];
            const mortonEncodedVertex = this.vertexBuffer[vertexOffset];
            //TODO: improve performance -> inline calculation and move to decoding of VertexBuffer
            const vertex = decodeZOrderCurve(mortonEncodedVertex, this.mortonSettings.numBits, this.mortonSettings.coordinateShift);
            return [vertex.x, vertex.y];
        }
        const offset = this.vertexOffsets ? this.vertexOffsets[index] * 2 : index * 2;
        const x = this.vertexBuffer[offset];
        const y = this.vertexBuffer[offset + 1];
        return [x, y];
    }
    getGeometries() {
        return convertGeometryVector(this);
    }
    get mortonSettings() {
        return this._mortonSettings;
    }
}

function createConstGeometryVector(numGeometries, geometryType, topologyVector, vertexOffsets, vertexBuffer) {
    return new ConstGeometryVector(numGeometries, geometryType, VertexBufferType.VEC_2, topologyVector, vertexOffsets, vertexBuffer);
}
function createMortonEncodedConstGeometryVector(numGeometries, geometryType, topologyVector, vertexOffsets, vertexBuffer, mortonInfo) {
    return new ConstGeometryVector(numGeometries, geometryType, VertexBufferType.MORTON, topologyVector, vertexOffsets, vertexBuffer, mortonInfo);
}
class ConstGeometryVector extends GeometryVector {
    constructor(_numGeometries, _geometryType, vertexBufferType, topologyVector, vertexOffsets, vertexBuffer, mortonSettings) {
        super(vertexBufferType, topologyVector, vertexOffsets, vertexBuffer, mortonSettings);
        this._numGeometries = _numGeometries;
        this._geometryType = _geometryType;
    }
    geometryType(_index) {
        return this._geometryType;
    }
    get numGeometries() {
        return this._numGeometries;
    }
    containsPolygonGeometry() {
        return this._geometryType === GEOMETRY_TYPE.POLYGON || this._geometryType === GEOMETRY_TYPE.MULTIPOLYGON;
    }
    containsSingleGeometryType() {
        return true;
    }
}

function createFlatGeometryVector(geometryTypes, topologyVector, vertexOffsets, vertexBuffer) {
    return new FlatGeometryVector(VertexBufferType.VEC_2, geometryTypes, topologyVector, vertexOffsets, vertexBuffer);
}
function createFlatGeometryVectorMortonEncoded(geometryTypes, topologyVector, vertexOffsets, vertexBuffer, mortonInfo) {
    return new FlatGeometryVector(VertexBufferType.MORTON, geometryTypes, topologyVector, vertexOffsets, vertexBuffer, mortonInfo);
}
class FlatGeometryVector extends GeometryVector {
    constructor(vertexBufferType, _geometryTypes, topologyVector, vertexOffsets, vertexBuffer, mortonSettings) {
        super(vertexBufferType, topologyVector, vertexOffsets, vertexBuffer, mortonSettings);
        this._geometryTypes = _geometryTypes;
    }
    geometryType(index) {
        return this._geometryTypes[index];
    }
    get numGeometries() {
        return this._geometryTypes.length;
    }
    containsPolygonGeometry() {
        for (let i = 0; i < this.numGeometries; i++) {
            if (this.geometryType(i) === GEOMETRY_TYPE.POLYGON || this.geometryType(i) === GEOMETRY_TYPE.MULTIPOLYGON) {
                return true;
            }
        }
        return false;
    }
    containsSingleGeometryType() {
        return false;
    }
}

class GpuVector {
    constructor(_triangleOffsets, _indexBuffer, _vertexBuffer, _topologyVector) {
        this._triangleOffsets = _triangleOffsets;
        this._indexBuffer = _indexBuffer;
        this._vertexBuffer = _vertexBuffer;
        this._topologyVector = _topologyVector;
    }
    get triangleOffsets() {
        return this._triangleOffsets;
    }
    get indexBuffer() {
        return this._indexBuffer;
    }
    get vertexBuffer() {
        return this._vertexBuffer;
    }
    get topologyVector() {
        return this._topologyVector;
    }
    /**
     * Returns geometries as coordinate arrays by extracting polygon outlines from topology.
     * The vertexBuffer contains the outline vertices, separate from the tessellated triangles.
     */
    getGeometries() {
        if (!this._topologyVector) {
            throw new Error("Cannot convert GpuVector to coordinates without topology information");
        }
        const geometries = new Array(this.numGeometries);
        const topology = this._topologyVector;
        const partOffsets = topology.partOffsets;
        const ringOffsets = topology.ringOffsets;
        const geometryOffsets = topology.geometryOffsets;
        // Use counters to track position in offset arrays (like Java implementation)
        let vertexBufferOffset = 0;
        let partOffsetCounter = 1;
        let ringOffsetsCounter = 1;
        let geometryOffsetsCounter = 1;
        for (let i = 0; i < this.numGeometries; i++) {
            const geometryType = this.geometryType(i);
            switch (geometryType) {
                case GEOMETRY_TYPE.POLYGON:
                    {
                        // Get number of rings for this polygon
                        const numRings = partOffsets[partOffsetCounter] - partOffsets[partOffsetCounter - 1];
                        partOffsetCounter++;
                        const rings = [];
                        for (let j = 0; j < numRings; j++) {
                            // Get number of vertices in this ring
                            const numVertices = ringOffsets[ringOffsetsCounter] - ringOffsets[ringOffsetsCounter - 1];
                            ringOffsetsCounter++;
                            const ring = [];
                            for (let k = 0; k < numVertices; k++) {
                                const x = this._vertexBuffer[vertexBufferOffset++];
                                const y = this._vertexBuffer[vertexBufferOffset++];
                                ring.push(new Point(x, y));
                            }
                            // Close the ring by duplicating the first vertex (MVT format requirement)
                            if (ring.length > 0) {
                                ring.push(ring[0]);
                            }
                            rings.push(ring);
                        }
                        geometries[i] = rings;
                        if (geometryOffsets)
                            geometryOffsetsCounter++;
                    }
                    break;
                case GEOMETRY_TYPE.MULTIPOLYGON:
                    {
                        // Get number of polygons in this multipolygon
                        const numPolygons = geometryOffsets[geometryOffsetsCounter] - geometryOffsets[geometryOffsetsCounter - 1];
                        geometryOffsetsCounter++;
                        const allRings = [];
                        for (let p = 0; p < numPolygons; p++) {
                            // Get number of rings in this polygon
                            const numRings = partOffsets[partOffsetCounter] - partOffsets[partOffsetCounter - 1];
                            partOffsetCounter++;
                            for (let j = 0; j < numRings; j++) {
                                // Get number of vertices in this ring
                                const numVertices = ringOffsets[ringOffsetsCounter] - ringOffsets[ringOffsetsCounter - 1];
                                ringOffsetsCounter++;
                                const ring = [];
                                for (let k = 0; k < numVertices; k++) {
                                    const x = this._vertexBuffer[vertexBufferOffset++];
                                    const y = this._vertexBuffer[vertexBufferOffset++];
                                    ring.push(new Point(x, y));
                                }
                                // Close the ring by duplicating the first vertex (MVT format requirement)
                                if (ring.length > 0) {
                                    ring.push(ring[0]);
                                }
                                allRings.push(ring);
                            }
                        }
                        geometries[i] = allRings;
                    }
                    break;
            }
        }
        return geometries;
    }
    [Symbol.iterator]() {
        /*for(let i = 1; i < this.triangleOffsets.length; i++) {
           const numTriangles = this.triangleOffsets[i] - this.triangleOffsets[i-1];
           const startIndex = this.triangleOffsets[i-1] * 3;
           const endIndex = this.triangleOffsets[i] * 3;
       }

        while (index < this.numGeometries) {
            yield geometries[index++];
        }*/
        //throw new Error("Iterator on a GpuVector is not implemented yet.");
        return null;
    }
}

function createConstGpuVector(numGeometries, geometryType, triangleOffsets, indexBuffer, vertexBuffer, topologyVector) {
    return new ConstGpuVector(numGeometries, geometryType, triangleOffsets, indexBuffer, vertexBuffer, topologyVector);
}
//TODO: extend from GeometryVector -> make topology vector optional
class ConstGpuVector extends GpuVector {
    constructor(_numGeometries, _geometryType, triangleOffsets, indexBuffer, vertexBuffer, topologyVector) {
        super(triangleOffsets, indexBuffer, vertexBuffer, topologyVector);
        this._numGeometries = _numGeometries;
        this._geometryType = _geometryType;
    }
    geometryType(_index) {
        return this._geometryType;
    }
    get numGeometries() {
        return this._numGeometries;
    }
    containsSingleGeometryType() {
        return true;
    }
}

function createFlatGpuVector(geometryTypes, triangleOffsets, indexBuffer, vertexBuffer, topologyVector) {
    return new FlatGpuVector(geometryTypes, triangleOffsets, indexBuffer, vertexBuffer, topologyVector);
}
//TODO: extend from GeometryVector -> make topology vector optional
class FlatGpuVector extends GpuVector {
    constructor(_geometryTypes, triangleOffsets, indexBuffer, vertexBuffer, topologyVector) {
        super(triangleOffsets, indexBuffer, vertexBuffer, topologyVector);
        this._geometryTypes = _geometryTypes;
    }
    geometryType(index) {
        return this._geometryTypes[index];
    }
    get numGeometries() {
        return this._geometryTypes.length;
    }
    containsSingleGeometryType() {
        return false;
    }
}

// TODO: get rid of numFeatures parameter
function decodeGeometryColumn(tile, numStreams, offset, numFeatures, scalingData) {
    const geometryTypeMetadata = decodeStreamMetadata(tile, offset);
    const geometryTypesVectorType = getVectorType(geometryTypeMetadata, numFeatures, tile, offset);
    let vertexOffsets;
    let vertexBuffer;
    let mortonSettings;
    let indexBuffer;
    if (geometryTypesVectorType === VectorType.CONST) {
        /* All geometries in the column have the same geometry type */
        const geometryType = decodeUnsignedConstInt32Stream(tile, offset, geometryTypeMetadata);
        // Variables for const geometry path (directly decoded as offsets)
        let geometryOffsets;
        let partOffsets;
        let ringOffsets;
        //TODO: use geometryOffsets for that? -> but then tessellated polygons can't be used with normal polygons
        // in one FeatureTable?
        let triangleOffsets;
        for (let i = 0; i < numStreams - 1; i++) {
            const geometryStreamMetadata = decodeStreamMetadata(tile, offset);
            switch (geometryStreamMetadata.physicalStreamType) {
                case PhysicalStreamType.LENGTH:
                    switch (geometryStreamMetadata.logicalStreamType.lengthType) {
                        case LengthType.GEOMETRIES:
                            geometryOffsets = decodeLengthStreamToOffsetBuffer(tile, offset, geometryStreamMetadata);
                            break;
                        case LengthType.PARTS:
                            partOffsets = decodeLengthStreamToOffsetBuffer(tile, offset, geometryStreamMetadata);
                            break;
                        case LengthType.RINGS:
                            ringOffsets = decodeLengthStreamToOffsetBuffer(tile, offset, geometryStreamMetadata);
                            break;
                        case LengthType.TRIANGLES:
                            triangleOffsets = decodeLengthStreamToOffsetBuffer(tile, offset, geometryStreamMetadata);
                    }
                    break;
                case PhysicalStreamType.OFFSET: {
                    switch (geometryStreamMetadata.logicalStreamType.offsetType) {
                        case OffsetType.VERTEX:
                            vertexOffsets = decodeUnsignedInt32Stream(tile, offset, geometryStreamMetadata);
                            break;
                        case OffsetType.INDEX:
                            indexBuffer = decodeUnsignedInt32Stream(tile, offset, geometryStreamMetadata);
                            break;
                    }
                    break;
                }
                case PhysicalStreamType.DATA: {
                    if (DictionaryType.VERTEX === geometryStreamMetadata.logicalStreamType.dictionaryType) {
                        vertexBuffer = decodeSignedInt32Stream(tile, offset, geometryStreamMetadata, scalingData);
                    }
                    else {
                        const mortonMetadata = geometryStreamMetadata;
                        mortonSettings = {
                            numBits: mortonMetadata.numBits,
                            coordinateShift: mortonMetadata.coordinateShift,
                        };
                        vertexBuffer = decodeUnsignedInt32Stream(tile, offset, geometryStreamMetadata, scalingData);
                    }
                    break;
                }
            }
        }
        if (indexBuffer) {
            if (geometryOffsets !== undefined || partOffsets !== undefined) {
                /* Case when the indices of a Polygon outline are encoded in the tile */
                const topologyVector = { geometryOffsets, partOffsets, ringOffsets };
                return createConstGpuVector(numFeatures, geometryType, triangleOffsets, indexBuffer, vertexBuffer, topologyVector);
            }
            /* Case when the no Polygon outlines are encoded in the tile */
            return createConstGpuVector(numFeatures, geometryType, triangleOffsets, indexBuffer, vertexBuffer);
        }
        return mortonSettings === undefined
            ? /* Currently only 2D coordinates (Vec2) are implemented in the encoder  */
                createConstGeometryVector(numFeatures, geometryType, { geometryOffsets, partOffsets, ringOffsets }, vertexOffsets, vertexBuffer)
            : createMortonEncodedConstGeometryVector(numFeatures, geometryType, { geometryOffsets, partOffsets, ringOffsets }, vertexOffsets, vertexBuffer, mortonSettings);
    }
    /* Different geometry types are mixed in the geometry column */
    const geometryTypeVector = decodeUnsignedInt32Stream(tile, offset, geometryTypeMetadata);
    // Variables for flat geometry path (decoded as lengths, then converted to offsets)
    let geometryLengths;
    let partLengths;
    let ringLengths;
    //TODO: use geometryOffsets for that? -> but then tessellated polygons can't be used with normal polygons
    // in one FeatureTable?
    let triangleOffsets;
    for (let i = 0; i < numStreams - 1; i++) {
        const geometryStreamMetadata = decodeStreamMetadata(tile, offset);
        switch (geometryStreamMetadata.physicalStreamType) {
            case PhysicalStreamType.LENGTH:
                switch (geometryStreamMetadata.logicalStreamType.lengthType) {
                    case LengthType.GEOMETRIES:
                        geometryLengths = decodeUnsignedInt32Stream(tile, offset, geometryStreamMetadata);
                        break;
                    case LengthType.PARTS:
                        partLengths = decodeUnsignedInt32Stream(tile, offset, geometryStreamMetadata);
                        break;
                    case LengthType.RINGS:
                        ringLengths = decodeUnsignedInt32Stream(tile, offset, geometryStreamMetadata);
                        break;
                    case LengthType.TRIANGLES:
                        triangleOffsets = decodeLengthStreamToOffsetBuffer(tile, offset, geometryStreamMetadata);
                }
                break;
            case PhysicalStreamType.OFFSET:
                switch (geometryStreamMetadata.logicalStreamType.offsetType) {
                    case OffsetType.VERTEX:
                        vertexOffsets = decodeUnsignedInt32Stream(tile, offset, geometryStreamMetadata);
                        break;
                    case OffsetType.INDEX:
                        indexBuffer = decodeUnsignedInt32Stream(tile, offset, geometryStreamMetadata);
                        break;
                }
                break;
            case PhysicalStreamType.DATA:
                if (DictionaryType.VERTEX === geometryStreamMetadata.logicalStreamType.dictionaryType) {
                    vertexBuffer = decodeSignedInt32Stream(tile, offset, geometryStreamMetadata, scalingData);
                }
                else {
                    const mortonMetadata = geometryStreamMetadata;
                    mortonSettings = {
                        numBits: mortonMetadata.numBits,
                        coordinateShift: mortonMetadata.coordinateShift,
                    };
                    vertexBuffer = decodeUnsignedInt32Stream(tile, offset, geometryStreamMetadata, scalingData);
                }
                break;
        }
    }
    // TODO: refactor the following instructions -> decode in one pass for performance reasons
    /* Calculate the offsets from the length buffer for util access */
    let geometryOffsets;
    let partOffsets;
    let ringOffsets;
    if (geometryLengths) {
        geometryOffsets = decodeRootLengthStream(geometryTypeVector, geometryLengths, 2);
        if (partLengths && ringLengths) {
            partOffsets = decodeLevel1LengthStream(geometryTypeVector, geometryOffsets, partLengths, false);
            ringOffsets = decodeLevel2LengthStream(geometryTypeVector, geometryOffsets, partOffsets, ringLengths);
        }
        else if (partLengths) {
            partOffsets = decodeLevel1WithoutRingBufferLengthStream(geometryTypeVector, geometryOffsets, partLengths);
        }
    }
    else if (partLengths && ringLengths) {
        partOffsets = decodeRootLengthStream(geometryTypeVector, partLengths, 1);
        ringOffsets = decodeLevel1LengthStream(geometryTypeVector, partOffsets, ringLengths, true);
    }
    else if (partLengths) {
        partOffsets = decodeRootLengthStream(geometryTypeVector, partLengths, 0);
    }
    if (indexBuffer && !partOffsets) {
        /* Case when the indices of a Polygon outline are not encoded in the data so no
         *  topology data are present in the tile */
        return createFlatGpuVector(geometryTypeVector, triangleOffsets, indexBuffer, vertexBuffer);
    }
    if (indexBuffer) {
        /* Case when the indices of a Polygon outline are encoded in the tile */
        return createFlatGpuVector(geometryTypeVector, triangleOffsets, indexBuffer, vertexBuffer, {
            geometryOffsets,
            partOffsets,
            ringOffsets,
        });
    }
    return mortonSettings === undefined /* Currently only 2D coordinates (Vec2) are implemented in the encoder  */
        ? createFlatGeometryVector(geometryTypeVector, { geometryOffsets, partOffsets, ringOffsets }, vertexOffsets, vertexBuffer)
        : createFlatGeometryVectorMortonEncoded(geometryTypeVector, { geometryOffsets, partOffsets, ringOffsets }, vertexOffsets, vertexBuffer, mortonSettings);
}
/*
 * Handle the parsing of the different topology length buffers separate not generic to reduce the
 * branching and improve the performance
 */
function decodeRootLengthStream(geometryTypes, rootLengthStream, bufferId) {
    const rootBufferOffsets = new Uint32Array(geometryTypes.length + 1);
    let previousOffset = 0;
    rootBufferOffsets[0] = previousOffset;
    let rootLengthCounter = 0;
    for (let i = 0; i < geometryTypes.length; i++) {
        /* Test if the geometry has and entry in the root buffer
         * BufferId: 2 GeometryOffsets -> MultiPolygon, MultiLineString, MultiPoint
         * BufferId: 1 PartOffsets -> Polygon
         * BufferId: 0 PartOffsets, RingOffsets -> LineString
         * */
        previousOffset = rootBufferOffsets[i + 1] =
            previousOffset + (geometryTypes[i] > bufferId ? rootLengthStream[rootLengthCounter++] : 1);
    }
    return rootBufferOffsets;
}
function decodeLevel1LengthStream(geometryTypes, rootOffsetBuffer, level1LengthBuffer, isLineStringPresent) {
    const level1BufferOffsets = new Uint32Array(rootOffsetBuffer[rootOffsetBuffer.length - 1] + 1);
    let previousOffset = 0;
    level1BufferOffsets[0] = previousOffset;
    let level1BufferCounter = 1;
    let level1LengthBufferCounter = 0;
    for (let i = 0; i < geometryTypes.length; i++) {
        const geometryType = geometryTypes[i];
        const numGeometries = rootOffsetBuffer[i + 1] - rootOffsetBuffer[i];
        if (geometryType === 5 ||
            geometryType === 2 ||
            (isLineStringPresent && (geometryType === 4 || geometryType === 1))) {
            /* For MultiPolygon, Polygon and in some cases for MultiLineString and LineString
             * a value in the level1LengthBuffer exists */
            for (let j = 0; j < numGeometries; j++) {
                previousOffset = level1BufferOffsets[level1BufferCounter++] =
                    previousOffset + level1LengthBuffer[level1LengthBufferCounter++];
            }
        }
        else {
            /* For MultiPoint and Point and in some cases for MultiLineString and LineString no value in the
             * level1LengthBuffer exists */
            for (let j = 0; j < numGeometries; j++) {
                level1BufferOffsets[level1BufferCounter++] = ++previousOffset;
            }
        }
    }
    return level1BufferOffsets;
}
/*
 * Case where no ring buffer exists so no MultiPolygon or Polygon geometry is part of the buffer
 */
function decodeLevel1WithoutRingBufferLengthStream(geometryTypes, rootOffsetBuffer, level1LengthBuffer) {
    const level1BufferOffsets = new Uint32Array(rootOffsetBuffer[rootOffsetBuffer.length - 1] + 1);
    let previousOffset = 0;
    level1BufferOffsets[0] = previousOffset;
    let level1OffsetBufferCounter = 1;
    let level1LengthCounter = 0;
    for (let i = 0; i < geometryTypes.length; i++) {
        const geometryType = geometryTypes[i];
        const numGeometries = rootOffsetBuffer[i + 1] - rootOffsetBuffer[i];
        if (geometryType === 4 || geometryType === 1) {
            /* For MultiLineString and LineString a value in the level1LengthBuffer exists */
            for (let j = 0; j < numGeometries; j++) {
                previousOffset = level1BufferOffsets[level1OffsetBufferCounter++] =
                    previousOffset + level1LengthBuffer[level1LengthCounter++];
            }
        }
        else {
            /* For MultiPoint and Point no value in level1LengthBuffer exists */
            for (let j = 0; j < numGeometries; j++) {
                level1BufferOffsets[level1OffsetBufferCounter++] = ++previousOffset;
            }
        }
    }
    return level1BufferOffsets;
}
function decodeLevel2LengthStream(geometryTypes, rootOffsetBuffer, level1OffsetBuffer, level2LengthBuffer) {
    const level2BufferOffsets = new Uint32Array(level1OffsetBuffer[level1OffsetBuffer.length - 1] + 1);
    let previousOffset = 0;
    level2BufferOffsets[0] = previousOffset;
    let level1OffsetBufferCounter = 1;
    let level2OffsetBufferCounter = 1;
    let level2LengthBufferCounter = 0;
    for (let i = 0; i < geometryTypes.length; i++) {
        const geometryType = geometryTypes[i];
        const numGeometries = rootOffsetBuffer[i + 1] - rootOffsetBuffer[i];
        if (geometryType !== 0 && geometryType !== 3) {
            /* For MultiPolygon, MultiLineString, Polygon and LineString a value in level2LengthBuffer
             * exists */
            for (let j = 0; j < numGeometries; j++) {
                const numParts = level1OffsetBuffer[level1OffsetBufferCounter] - level1OffsetBuffer[level1OffsetBufferCounter - 1];
                level1OffsetBufferCounter++;
                for (let k = 0; k < numParts; k++) {
                    previousOffset = level2BufferOffsets[level2OffsetBufferCounter++] =
                        previousOffset + level2LengthBuffer[level2LengthBufferCounter++];
                }
            }
        }
        else {
            /* For MultiPoint and Point no value in level2LengthBuffer exists */
            for (let j = 0; j < numGeometries; j++) {
                level2BufferOffsets[level2OffsetBufferCounter++] = ++previousOffset;
                level1OffsetBufferCounter++;
            }
        }
    }
    return level2BufferOffsets;
}

class BooleanFlatVector extends Vector {
    constructor(name, dataVector, sizeOrNullabilityBuffer) {
        super(name, dataVector.getBuffer(), sizeOrNullabilityBuffer);
        this.dataVector = dataVector;
    }
    getValueFromBuffer(index) {
        return this.dataVector.get(index);
    }
}

class FloatFlatVector extends FixedSizeVector {
    getValueFromBuffer(index) {
        return this.dataBuffer[index];
    }
}

class Int64ConstVector extends Vector {
    constructor(name, value, sizeOrNullabilityBuffer, isSigned) {
        super(name, isSigned ? BigInt64Array.of(value) : BigUint64Array.of(value), sizeOrNullabilityBuffer);
    }
    getValueFromBuffer(_index) {
        return this.dataBuffer[0];
    }
}

function skipColumn(numStreams, tile, offset) {
    //TODO: add size of column in Mlt for fast skipping
    for (let i = 0; i < numStreams; i++) {
        const streamMetadata = decodeStreamMetadata(tile, offset);
        offset.add(streamMetadata.byteLength);
    }
}
function decodeBooleanRle(buffer, numBooleans, byteLength, pos, nullabilityBuffer) {
    const numBytes = Math.ceil(numBooleans / 8.0);
    const values = decodeByteRle(buffer, numBytes, byteLength, pos);
    if (nullabilityBuffer) {
        return unpackNullableBoolean(values, numBooleans, nullabilityBuffer);
    }
    return values;
}
function decodeByteRle(buffer, numBytes, byteLength, pos) {
    const values = new Uint8Array(numBytes);
    let valueOffset = 0;
    const streamEndPos = pos.get() + byteLength;
    while (valueOffset < numBytes) {
        if (pos.get() >= streamEndPos) {
            break;
        }
        const header = buffer[pos.increment()];
        /* Runs */
        if (header <= 0x7f) {
            const numRuns = header + 3;
            const value = buffer[pos.increment()];
            const endValueOffset = Math.min(valueOffset + numRuns, numBytes);
            values.fill(value, valueOffset, endValueOffset);
            valueOffset = endValueOffset;
        }
        else {
            /* Literals */
            const numLiterals = 256 - header;
            for (let i = 0; i < numLiterals && valueOffset < numBytes; i++) {
                values[valueOffset++] = buffer[pos.increment()];
            }
        }
    }
    pos.set(streamEndPos);
    return values;
}
function decodeFloatsLE(encodedValues, pos, numValues, nullabilityBuffer) {
    const currentPos = pos.get();
    const newOffset = currentPos + numValues * Float32Array.BYTES_PER_ELEMENT;
    const newBuf = new Uint8Array(encodedValues.subarray(currentPos, newOffset)).buffer;
    const fb = new Float32Array(newBuf);
    pos.set(newOffset);
    if (nullabilityBuffer) {
        return unpackNullable(fb, nullabilityBuffer, 0);
    }
    return fb;
}
function decodeDoublesLE(encodedValues, pos, numValues, nullabilityBuffer) {
    const currentPos = pos.get();
    const newOffset = currentPos + numValues * Float64Array.BYTES_PER_ELEMENT;
    const newBuf = new Uint8Array(encodedValues.subarray(currentPos, newOffset)).buffer;
    const fb = new Float64Array(newBuf);
    pos.set(newOffset);
    if (nullabilityBuffer) {
        return unpackNullable(fb, nullabilityBuffer, 0);
    }
    return fb;
}
const TEXT_DECODER_MIN_LENGTH = 12;
const utf8TextDecoder = new TextDecoder();
// Source: https://github.com/mapbox/pbf/issues/106
function decodeString$2(buf, pos, end) {
    if (end - pos >= TEXT_DECODER_MIN_LENGTH) {
        // longer strings are fast with the built-in browser TextDecoder API
        return utf8TextDecoder.decode(buf.subarray(pos, end));
    }
    // short strings are fast with custom implementation
    return readUtf8(buf, pos, end);
}
function readUtf8(buf, pos, end) {
    let str = "";
    let i = pos;
    while (i < end) {
        const b0 = buf[i];
        let c = null; // codepoint
        let bytesPerSequence = b0 > 0xef ? 4 : b0 > 0xdf ? 3 : b0 > 0xbf ? 2 : 1;
        if (i + bytesPerSequence > end)
            break;
        let b1;
        let b2;
        let 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 getVectorTypeBooleanStream(numFeatures, byteLength, data, offset) {
    const valuesPerRun = 0x83;
    // TODO: use VectorType metadata field for to test which VectorType is used
    return Math.ceil(numFeatures / valuesPerRun) * 2 === byteLength &&
        /* Test the first value byte if all bits are set to true */
        (data[offset.get() + 1] & 0xff) === (bitCount(numFeatures) << 2) - 1
        ? VectorType.CONST
        : VectorType.FLAT;
}
function bitCount(number) {
    //TODO: refactor to get rid of special case handling
    return number === 0 ? 1 : Math.floor(Math.log2(number) + 1);
}

class VariableSizeVector extends Vector {
    constructor(name, offsetBuffer, dataBuffer, sizeOrNullabilityBuffer) {
        super(name, dataBuffer, sizeOrNullabilityBuffer);
        this.offsetBuffer = offsetBuffer;
    }
}

class StringFlatVector extends VariableSizeVector {
    constructor(name, offsetBuffer, dataBuffer, nullabilityBuffer) {
        super(name, offsetBuffer, dataBuffer, nullabilityBuffer ?? offsetBuffer.length - 1);
    }
    getValueFromBuffer(index) {
        const start = this.offsetBuffer[index];
        const end = this.offsetBuffer[index + 1];
        return decodeString$2(this.dataBuffer, start, end);
    }
}

class StringDictionaryVector extends VariableSizeVector {
    constructor(name, indexBuffer, offsetBuffer, dictionaryBuffer, nullabilityBuffer) {
        super(name, offsetBuffer, dictionaryBuffer, nullabilityBuffer ?? indexBuffer.length);
        this.indexBuffer = indexBuffer;
        this.indexBuffer = indexBuffer;
    }
    getValueFromBuffer(index) {
        const offset = this.indexBuffer[index];
        const start = this.offsetBuffer[offset];
        const end = this.offsetBuffer[offset + 1];
        return decodeString$2(this.dataBuffer, start, end);
    }
}

/**
 * Decode FSST compressed data
 *
 * @param symbols           Array of symbols, where each symbol can be between 1 and 8 bytes
 * @param symbolLengths     Array of symbol lengths, length of each symbol in symbols array
 * @param compressedData    FSST Compressed data, where each entry is an index to the symbols array
 * @returns                 Decoded data as Uint8Array
 */
//TODO: improve -> quick and dirty implementation
function decodeFsst(symbols, symbolLengths, compressedData) {
    //TODO: use typed array directly
    const decodedData = [];
    const symbolOffsets = new Array(symbolLengths.length).fill(0);
    for (let i = 1; i < symbolLengths.length; i++) {
        symbolOffsets[i] = symbolOffsets[i - 1] + symbolLengths[i - 1];
    }
    for (let i = 0; i < compressedData.length; i++) {
        if (compressedData[i] === 255) {
            decodedData.push(compressedData[++i]);
        }
        else {
            const symbolLength = symbolLengths[compressedData[i]];
            const symbolOffset = symbolOffsets[compressedData[i]];
            for (let j = 0; j < symbolLength; j++) {
                decodedData.push(symbols[symbolOffset + j]);
            }
        }
    }
    return new Uint8Array(decodedData);
}

class StringFsstDictionaryVector extends VariableSizeVector {
    constructor(name, indexBuffer, offsetBuffer, dictionaryBuffer, symbolOffsetBuffer, symbolTableBuffer, nullabilityBuffer) {
        super(name, offsetBuffer, dictionaryBuffer, nullabilityBuffer);
        this.indexBuffer = indexBuffer;
        this.symbolOffsetBuffer = symbolOffsetBuffer;
        this.symbolTableBuffer = symbolTableBuffer;
    }
    getValueFromBuffer(index) {
        if (this.decodedDictionary == null) {
            if (this.symbolLengthBuffer == null) {
                // TODO: change FsstEncoder to take offsets instead of length to get rid of this conversion
                this.symbolLengthBuffer = this.offsetToLengthBuffer(this.symbolOffsetBuffer);
            }
            this.decodedDictionary = decodeFsst(this.symbolTableBuffer, this.symbolLengthBuffer, this.dataBuffer);
        }
        const offset = this.indexBuffer[index];
        const start = this.offsetBuffer[offset];
        const end = this.offsetBuffer[offset + 1];
        return decodeString$2(this.decodedDictionary, start, end);
    }
    // TODO: get rid of that conversion
    offsetToLengthBuffer(offsetBuffer) {
        const lengthBuffer = new Uint32Array(offsetBuffer.length - 1);
        let previousOffset = offsetBuffer[0];
        for (let i = 1; i < offsetBuffer.length; i++) {
            const offset = offsetBuffer[i];
            lengthBuffer[i - 1] = offset - previousOffset;
            previousOffset = offset;
        }
        return lengthBuffer;
    }
}

function decodeString$1(name, data, offset, numStreams, bitVector) {
    let dictionaryLengthStream = null;
    let offsetStream = null;
    let dictionaryStream = null;
    let symbolLengthStream = null;
    let symbolTableStream = null;
    let nullabilityBuffer = bitVector ?? null;
    let plainLengthStream = null;
    let plainDataStream = null;
    for (let i = 0; i < numStreams; i++) {
        const streamMetadata = decodeStreamMetadata(data, offset);
        switch (streamMetadata.physicalStreamType) {
            case PhysicalStreamType.PRESENT: {
                const presentData = decodeBooleanRle(data, streamMetadata.numValues, streamMetadata.byteLength, offset);
                const presentStream = new BitVector(presentData, streamMetadata.numValues);
                nullabilityBuffer = bitVector ?? presentStream;
                break;
            }
            case PhysicalStreamType.OFFSET: {
                offsetStream = decodeUnsignedInt32Stream(data, offset, streamMetadata, undefined, nullabilityBuffer);
                break;
            }
            case PhysicalStreamType.LENGTH: {
                const lengthStream = decodeLengthStreamToOffsetBuffer(data, offset, streamMetadata);
                if (LengthType.DICTIONARY === streamMetadata.logicalStreamType.lengthType) {
                    dictionaryLengthStream = lengthStream;
                }
                else if (LengthType.SYMBOL === streamMetadata.logicalStreamType.lengthType) {
                    symbolLengthStream = lengthStream;
                }
                else {
                    // Plain string encoding uses VAR_BINARY length type
                    plainLengthStream = lengthStream;
                }
                break;
            }
            case PhysicalStreamType.DATA: {
                const dataStream = data.subarray(offset.get(), offset.get() + streamMetadata.byteLength);
                offset.add(streamMetadata.byteLength);
                const dictType = streamMetadata.logicalStreamType.dictionaryType;
                if (DictionaryType.FSST === dictType) {
                    symbolTableStream = dataStream;
                }
                else if (DictionaryType.SINGLE === dictType || DictionaryType.SHARED === dictType) {
                    dictionaryStream = dataStream;
                }
                else if (DictionaryType.NONE === dictType) {
                    plainDataStream = dataStream;
                }
                break;
            }
        }
    }
    return (decodeFsstDictionaryVector(name, symbolTableStream, offsetStream, dictionaryLengthStream, dictionaryStream, symbolLengthStream, nullabilityBuffer) ??
        decodeDictionaryVector(name, dictionaryStream, offsetStream, dictionaryLengthStream, nullabilityBuffer) ??
        decodePlainStringVector(name, plainLengthStream, plainDataStream, offsetStream, nullabilityBuffer));
}
function decodeFsstDictionaryVector(name, symbolTableStream, offsetStream, dictionaryLengthStream, dictionaryStream, symbolLengthStream, nullabilityBuffer) {
    if (!symbolTableStream) {
        return null;
    }
    return new StringFsstDictionaryVector(name, offsetStream, dictionaryLengthStream, dictionaryStream, symbolLengthStream, symbolTableStream, nullabilityBuffer);
}
function decodeDictionaryVector(name, dictionaryStream, offsetStream, dictionaryLengthStream, nullabilityBuffer) {
    if (!dictionaryStream) {
        return null;
    }
    return nullabilityBuffer
        ? new StringDictionaryVector(name, offsetStream, dictionaryLengthStream, dictionaryStream, nullabilityBuffer)
        : new StringDictionaryVector(name, offsetStream, dictionaryLengthStream, dictionaryStream);
}
function decodePlainStringVector(name, plainLengthStream, plainDataStream, offsetStream, nullabilityBuffer) {
    if (!plainLengthStream || !plainDataStream) {
        return null;
    }
    if (offsetStream) {
        return nullabilityBuffer
            ? new StringDictionaryVector(name, offsetStream, plainLengthStream, plainDataStream, nullabilityBuffer)
            : new StringDictionaryVector(name, offsetStream, plainLengthStream, plainDataStream);
    }
    if (nullabilityBuffer && nullabilityBuffer.size() !== plainLengthStream.length - 1) {
        const sparseOffsetStream = new Uint32Array(nullabilityBuffer.size());
        let valueIndex = 0;
        for (let i = 0; i < nullabilityBuffer.size(); i++) {
            if (nullabilityBuffer.get(i)) {
                sparseOffsetStream[i] = valueIndex++;
            }
            else {
                sparseOffsetStream[i] = 0;
            }
        }
        return new StringDictionaryVector(name, sparseOffsetStream, plainLengthStream, plainDataStream, nullabilityBuffer);
    }
    return nullabilityBuffer
        ? new StringFlatVector(name, plainLengthStream, plainDataStream, nullabilityBuffer)
        : new StringFlatVector(name, plainLengthStream, plainDataStream);
}
function decodeSharedDictionary(data, offset, column, numFeatures, propertyColumnNames) {
    let dictionaryOffsetBuffer = null;
    let dictionaryBuffer = null;
    let symbolOffsetBuffer = null;
    let symbolTableBuffer = null;
    let dictionaryStreamDecoded = false;
    while (!dictionaryStreamDecoded) {
        const streamMetadata = decodeStreamMetadata(data, offset);
        switch (streamMetadata.physicalStreamType) {
            case PhysicalStreamType.LENGTH:
                if (LengthType.DICTIONARY === streamMetadata.logicalStreamType.lengthType) {
                    dictionaryOffsetBuffer = decodeLengthStreamToOffsetBuffer(data, offset, streamMetadata);
                }
                else {
                    symbolOffsetBuffer = decodeLengthStreamToOffsetBuffer(data, offset, streamMetadata);
                }
                break;
            case PhysicalStreamType.DATA:
                if (DictionaryType.SINGLE === streamMetadata.logicalStreamType.dictionaryType ||
                    DictionaryType.SHARED === streamMetadata.logicalStreamType.dictionaryType) {
                    dictionaryBuffer = data.subarray(offset.get(), offset.get() + streamMetadata.byteLength);
                    dictionaryStreamDecoded = true;
                }
                else {
                    symbolTableBuffer = data.subarray(offset.get(), offset.get() + streamMetadata.byteLength);
                }
                offset.add(streamMetadata.byteLength);
                break;
        }
    }
    const childFields = column.complexType.children;
    const stringDictionaryVectors = [];
    let i = 0;
    for (const childField of childFields) {
        const numStreams = decodeVarintInt32(data, offset, 1)[0];
        if (numStreams === 0) {
            /* Column is not present in the tile */
            continue;
        }
        const columnName = childField.name ? `${column.name}${childField.name}` : column.name;
        if (propertyColumnNames) {
            if (!propertyColumnNames.has(columnName)) {
                //TODO: add size of sub column to Mlt for faster skipping
                skipColumn(numStreams, data, offset);
                continue;
            }
        }
        if (numStreams !== 2 ||
            childField.type !== "scalarField" ||
            childField.scalarField.physicalType !== ScalarType.STRING) {
            throw new Error("Currently only optional string fields are implemented for a struct.");
        }
        const presentStreamMetadata = decodeStreamMetadata(data, offset);
        const presentStream = decodeBooleanRle(data, presentStreamMetadata.numValues, presentStreamMetadata.byteLength, offset);
        const offsetStreamMetadata = decodeStreamMetadata(data, offset);
        const offsetCount = offsetStreamMetadata.decompressedCount;
        const isNullable = offsetCount !== numFeatures;
        const offsetStream = decodeUnsignedInt32Stream(data, offset, offsetStreamMetadata, undefined, isNullable ? new BitVector(presentStream, presentStreamMetadata.numValues) : undefined);
        stringDictionaryVectors[i++] = symbolTableBuffer
            ? new StringFsstDictionaryVector(columnName, offsetStream, dictionaryOffsetBuffer, dictionaryBuffer, symbolOffsetBuffer, symbolTableBuffer, new BitVector(presentStream, presentStreamMetadata.numValues))
            : new StringDictionaryVector(columnName, offsetStream, dictionaryOffsetBuffer, dictionaryBuffer, new BitVector(presentStream, presentStreamMetadata.numValues));
    }
    return stringDictionaryVectors;
}

function decodePropertyColumn(data, offset, columnMetadata, numStreams, numFeatures, propertyColumnNames) {
    if (columnMetadata.type === "scalarType") {
        if (propertyColumnNames && !propertyColumnNames.has(columnMetadata.name)) {
            skipColumn(numStreams, data, offset);
            return null;
        }
        return decodeScalarPropertyColumn(numStreams, data, offset, numFeatures, columnMetadata.scalarType, columnMetadata);
    }
    if (numStreams === 0) {
        return null;
    }
    return decodeSharedDictionary(data, offset, columnMetadata, numFeatures, propertyColumnNames);
}
function decodeScalarPropertyColumn(numStreams, data, offset, numFeatures, column, columnMetadata) {
    let nullabilityBuffer = null;
    if (numStreams === 0) {
        return null;
    }
    if (columnMetadata.nullable) {
        const presentStreamMetadata = decodeStreamMetadata(data, offset);
        const numValues = presentStreamMetadata.numValues;
        const streamDataStart = offset.get();
        const presentVector = decodeBooleanRle(data, numValues, presentStreamMetadata.byteLength, offset);
        offset.set(streamDataStart + presentStreamMetadata.byteLength);
        nullabilityBuffer = new BitVector(presentVector, presentStreamMetadata.numValues);
    }
    const sizeOrNullabilityBuffer = nullabilityBuffer ?? numFeatures;
    const scalarType = column.physicalType;
    switch (scalarType) {
        case ScalarType.UINT_32:
        case ScalarType.INT_32:
            return decodeInt32Column(data, offset, columnMetadata, column, sizeOrNullabilityBuffer);
        case ScalarType.STRING: {
            // In embedded format: numStreams includes nullability stream if column is nullable
            const stringDataStreams = columnMetadata.nullable ? numStreams - 1 : numStreams;
            return decodeString$1(columnMetadata.name, data, offset, stringDataStreams, nullabilityBuffer);
        }
        case ScalarType.BOOLEAN:
            return decodeBooleanColumn(data, offset, columnMetadata, numFeatures, sizeOrNullabilityBuffer);
        case ScalarType.UINT_64:
        case ScalarType.INT_64:
            return decodeInt64Column(data, offset, columnMetadata, sizeOrNullabilityBuffer, column);
        case ScalarType.FLOAT:
            return decodeFloatColumn(data, offset, columnMetadata, sizeOrNullabilityBuffer);
        case ScalarType.DOUBLE:
            return decodeDoubleColumn(data, offset, columnMetadata, sizeOrNullabilityBuffer);
        default:
            throw new Error(`The specified data type for the field is currently not supported: ${column}`);
    }
}
function decodeBooleanColumn(data, offset, column, _numFeatures, sizeOrNullabilityBuffer) {
    const dataStreamMetadata = decodeStreamMetadata(data, offset);
    const numValues = dataStreamMetadata.numValues;
    const streamDataStart = offset.get();
    const nullabilityBuffer = isNullabilityBuffer(sizeOrNullabilityBuffer) ? sizeOrNullabilityBuffer : undefined;
    const dataStream = decodeBooleanRle(data, numValues, dataStreamMetadata.byteLength, offset, nullabilityBuffer);
    offset.set(streamDataStart + dataStreamMetadata.byteLength);
    const dataVector = new BitVector(dataStream, numValues);
    return new BooleanFlatVector(column.name, dataVector, sizeOrNullabilityBuffer);
}
function decodeFloatColumn(data, offset, column, sizeOrNullabilityBuffer) {
    const dataStreamMetadata = decodeStreamMetadata(data, offset);
    const nullabilityBuffer = isNullabilityBuffer(sizeOrNullabilityBuffer) ? sizeOrNullabilityBuffer : undefined;
    const dataStream = decodeFloatsLE(data, offset, dataStreamMetadata.numValues, nullabilityBuffer);
    return new FloatFlatVector(column.name, dataStream, sizeOrNullabilityBuffer);
}
function decodeDoubleColumn(data, offset, column, sizeOrNullabilityBuffer) {
    const dataStreamMetadata = decodeStreamMetadata(data, offset);
    const nullabilityBuffer = isNullabilityBuffer(sizeOrNullabilityBuffer) ? sizeOrNullabilityBuffer : undefined;
    const dataStream = decodeDoublesLE(data, offset, dataStreamMetadata.numValues, nullabilityBuffer);
    return new DoubleFlatVector(column.name, dataStream, sizeOrNullabilityBuffer);
}
function decodeInt64Column(data, offset, column, sizeOrNullabilityBuffer, scalarColumn) {
    const dataStreamMetadata = decodeStreamMetadata(data, offset);
    const vectorType = getVectorType(dataStreamMetadata, sizeOrNullabilityBuffer, data, offset, "int64");
    const isSigned = scalarColumn.physicalType === ScalarType.INT_64;
    if (vectorType === VectorType.FLAT) {
        const nullabilityBuffer = isNullabilityBuffer(sizeOrNullabilityBuffer) ? sizeOrNullabilityBuffer : undefined;
        const dataStream = isSigned
            ? decodeSignedInt64Stream(data, offset, dataStreamMetadata, nullabilityBuffer)
            : decodeUnsignedInt64Stream(data, offset, dataStreamMetadata, nullabilityBuffer);
        return new Int64FlatVector(column.name, dataStream, sizeOrNullabilityBuffer);
    }
    if (vectorType === VectorType.SEQUENCE) {
        const id = decodeSequenceInt64Stream(data, offset, dataStreamMetadata);
        return new Int64SequenceVector(column.name, id[0], id[1], dataStreamMetadata.numRleValues);
    }
    const constValue = isSigned
        ? decodeSignedConstInt64Stream(data, offset, dataStreamMetadata)
        : decodeUnsignedConstInt64Stream(data, offset, dataStreamMetadata);
    return new Int64ConstVector(column.name, constValue, sizeOrNullabilityBuffer, isSigned);
}
function decodeInt32Column(data, offset, column, scalarColumn, sizeOrNullabilityBuffer) {
    const dataStreamMetadata = decodeStreamMetadata(data, offset);
    const vectorType = getVectorType(dataStreamMetadata, sizeOrNullabilityBuffer, data, offset);
    const isSigned = scalarColumn.physicalType === ScalarType.INT_32;
    if (vectorType === VectorType.FLAT) {
        const nullabilityBuffer = isNullabilityBuffer(sizeOrNullabilityBuffer) ? sizeOrNullabilityBuffer : undefined;
        const dataStream = isSigned
            ? decodeSignedInt32Stream(data, offset, dataStreamMetadata, undefined, nullabilityBuffer)
            : decodeUnsignedInt32Stream(data, offset, dataStreamMetadata, undefined, nullabilityBuffer);
        return new Int32FlatVector(column.name, dataStream, sizeOrNullabilityBuffer);
    }
    if (vectorType === VectorType.SEQUENCE) {
        const id = decodeSequenceInt32Stream(data, offset, dataStreamMetadata);
        return new Int32SequenceVector(column.name, id[0], id[1], dataStreamMetadata.numRleValues);
    }
    const constValue = isSigned
        ? decodeSignedConstInt32Stream(data, offset, dataStreamMetadata)
        : decodeUnsignedConstInt32Stream(data, offset, dataStreamMetadata);
    return new Int32ConstVector(column.name, constValue, sizeOrNullabilityBuffer, isSigned);
}
function isNullabilityBuffer(sizeOrNullabilityBuffer) {
    return sizeOrNullabilityBuffer instanceof BitVector;
}

/**
 * The type code is a single varint32 that encodes:
 * - Physical or logical type
 * - Nullable flag
 * - Whether the column has a name (typeCode >= 10)
 * - Whether the column has children (typeCode == 30 for STRUCT)
 * - For ID types: whether it uses long (64-bit) IDs
 */
/**
 * Decodes a type code into a Column structure.
 *
 * ID type codes (0..3):
 * - Bit 0: nullable
 * - Bit 1: longID (0/1 -> uint32 IDs, 2/3 -> uint64 IDs)
 *
 * ID columns are kept as logical types so they remain distinguishable
 * from feature properties that may also be named "id".
 */
function decodeColumnType(typeCode) {
    switch (typeCode) {
        case 0:
        case 1:
        case 2:
        case 3: {
            const column = {};
            column.nullable = (typeCode & 1) !== 0;
            column.columnScope = ColumnScope.FEATURE;
            const scalarCol = {};
            scalarCol.type = "logicalType";
            scalarCol.logicalType = LogicalScalarType.ID;
            scalarCol.longID = (typeCode & 2) !== 0;
            column.scalarType = scalarCol;
            column.type = "scalarType";
            return column;
        }
        case 4: {
            // GEOMETRY (non-nullable, no children)
            const column = {};
            column.nullable = false;
            column.columnScope = ColumnScope.FEATURE;
            const complexCol = {};
            complexCol.type = "physicalType";
            complexCol.physicalType = ComplexType.GEOMETRY;
            column.type = "complexType";
            column.complexType = complexCol;
            return column;
        }
        case 30: {
            // STRUCT (non-nullable with children)
            const column = {};
            column.nullable = false;
            column.columnScope = ColumnScope.FEATURE;
            const complexCol = {};
            complexCol.type = "physicalType";
            complexCol.physicalType = ComplexType.STRUCT;
            column.type = "complexType";
            column.complexType = complexCol;
            return column;
        }
        default:
            return mapScalarType(typeCode);
    }
}
/**
 * Returns true if this type code requires a name to be stored.
 * ID (0-3) and GEOMETRY (4) columns have implicit names.
 * All other types (>= 10) require explicit names.
 */
function columnTypeHasName(typeCode) {
    return typeCode >= 10;
}
/**
 * Returns true if this type code has child fields.
 * Only STRUCT (typeCode 30) has children.
 */
function columnTypeHasChildren(typeCode) {
    return typeCode === 30;
}
/**
 * Determines if a stream count needs to be read for this column.
 * Mirrors the logic in cpp/include/mlt/metadata/type_map.hpp lines 85-122
 */
function hasStreamCount(column) {
    if (column.type === "scalarType") {
        const scalarCol = column.scalarType;
        if (scalarCol.type === "physicalType") {
            const physicalType = scalarCol.physicalType;
            switch (physicalType) {
                case ScalarType.BOOLEAN:
                case ScalarType.INT_8:
                case ScalarType.UINT_8:
                case ScalarType.INT_32:
                case ScalarType.UINT_32:
                case ScalarType.INT_64:
                case ScalarType.UINT_64:
                case ScalarType.FLOAT:
                case ScalarType.DOUBLE:
                    return false;
                case ScalarType.STRING:
                    return true;
                default:
                    return false;
            }
        }
        if (scalarCol.type === "logicalType") {
            return false;
        }
    }
    else if (column.type === "complexType") {
        const complexCol = column.complexType;
        if (complexCol.type === "physicalType") {
            const physicalType = complexCol.physicalType;
            switch (physicalType) {
                case ComplexType.GEOMETRY:
                case ComplexType.STRUCT:
                    return true;
                default:
                    return false;
            }
        }
    }
    console.warn("Unexpected column type in hasStreamCount", column);
    return false;
}
function isLogicalIdColumn(column) {
    return (column.type === "scalarType" &&
        column.scalarType?.type === "logicalType" &&
        column.scalarType.logicalType === LogicalScalarType.ID);
}
function isGeometryColumn(column) {
    return (column.type === "complexType" &&
        column.complexType?.type === "physicalType" &&
        column.complexType.physicalType === ComplexType.GEOMETRY);
}
/**
 * Maps a scalar type code to a Column with ScalarType.
 * Type codes 10-29 encode scalar types with nullable flag.
 * Even codes are non-nullable, odd codes are nullable.
 */
function mapScalarType(typeCode) {
    let scalarType;
    switch (typeCode) {
        case 10:
        case 11:
            scalarType = ScalarType.BOOLEAN;
            break;
        case 12:
        case 13:
            scalarType = ScalarType.INT_8;
            break;
        case 14:
        case 15:
            scalarType = ScalarType.UINT_8;
            break;
        case 16:
        case 17:
            scalarType = ScalarType.INT_32;
            break;
        case 18:
        case 19:
            scalarType = ScalarType.UINT_32;
            break;
        case 20:
        case 21:
            scalarType = ScalarType.INT_64;
            break;
        case 22:
        case 23:
            scalarType = ScalarType.UINT_64;
            break;
        case 24:
        case 25:
            scalarType = ScalarType.FLOAT;
            break;
        case 26:
        case 27:
            scalarType = ScalarType.DOUBLE;
            break;
        case 28:
        case 29:
            scalarType = ScalarType.STRING;
            break;
        default:
            return null;
    }
    const column = {};
    column.nullable = (typeCode & 1) !== 0;
    column.columnScope = ColumnScope.FEATURE;
    const scalarCol = {};
    scalarCol.type = "physicalType";
    scalarCol.physicalType = scalarType;
    column.type = "scalarType";
    column.scalarType = scalarCol;
    return column;
}

const textDecoder = new TextDecoder();
const SUPPORTED_COLUMN_TYPES = "0-3(ID), 4(GEOMETRY), 10-29(scalars), 30(STRUCT)";
const SUPPORTED_FIELD_TYPES = "10-29(scalars), 30(STRUCT)";
/**
 * Decodes a length-prefixed UTF-8 string.
 * Layout: [len: varint32][bytes: len]
 */
function decodeString(src, offset) {
    const length = decodeVarintInt32(src, offset, 1)[0];
    if (length === 0) {
        return "";
    }
    const start = offset.get();
    const end = start + length;
    const view = src.subarray(start, end);
    offset.add(length);
    return textDecoder.decode(view);
}
/**
 * Converts a Column to a Field.
 * Used when decoding Field metadata which has the same format as Column.
 */
function columnToField(column) {
    return {
        name: column.name,
        nullable: column.nullable,
        scalarField: column.scalarType,
        complexField: column.complexType,
        type: column.type === "scalarType" ? "scalarField" : "complexField",
    };
}
/**
 * Decodes a Field used as part of complex types (STRUCT children).
 */
function decodeField(src, offset) {
    const typeCode = decodeVarintInt32(src, offset, 1)[0] >>> 0;
    if (typeCode < 10 || typeCode > 30) {
        throw new Error(`Unsupported field type code ${typeCode}. Supported: ${SUPPORTED_FIELD_TYPES}`);
    }
    const column = decodeColumnType(typeCode);
    if (columnTypeHasName(typeCode)) {
        column.name = decodeString(src, offset);
    }
    if (columnTypeHasChildren(typeCode)) {
        const childCount = decodeVarintInt32(src, offset, 1)[0] >>> 0;
        column.complexType.children = new Array(childCount);
        for (let i = 0; i < childCount; i++) {
            column.complexType.children[i] = decodeField(src, offset);
        }
    }
    return columnToField(column);
}
/**
 * The typeCode encodes the column type, nullable flag, and whether it has name/children.
 */
function decodeColumn(src, offset) {
    const typeCode = decodeVarintInt32(src, offset, 1)[0] >>> 0;
    const column = decodeColumnType(typeCode);
    if (!column) {
        throw new Error(`Unsupported column type code ${typeCode}. Supported: ${SUPPORTED_COLUMN_TYPES}`);
    }
    if (columnTypeHasName(typeCode)) {
        column.name = decodeString(src, offset);
    }
    else {
        // ID and GEOMETRY columns have implicit names
        if (typeCode >= 0 && typeCode <= 3) {
            column.name = "id";
        }
        else if (typeCode === 4) {
            column.name = "geometry";
        }
    }
    if (columnTypeHasChildren(typeCode)) {
        // Only STRUCT (typeCode 30) has children
        const childCount = decodeVarintInt32(src, offset, 1)[0] >>> 0;
        const complexCol = column.complexType;
        complexCol.children = new Array(childCount);
        for (let i = 0; i < childCount; i++) {
            complexCol.children[i] = decodeField(src, offset);
        }
    }
    return column;
}
/**
 * Top-level decoder for embedded tileset metadata.
 * Reads exactly ONE FeatureTableSchema from the stream.
 *
 * @param bytes The byte array containing the metadata
 * @param offset The current offset in the byte array (will be advanced)
 */
function decodeEmbeddedTileSetMetadata(bytes, offset) {
    const meta = {};
    meta.featureTables = [];
    const table = {};
    table.name = decodeString(bytes, offset);
    const extent = decodeVarintInt32(bytes, offset, 1)[0] >>> 0;
    const columnCount = decodeVarintInt32(bytes, offset, 1)[0] >>> 0;
    table.columns = new Array(columnCount);
    for (let j = 0; j < columnCount; j++) {
        table.columns[j] = decodeColumn(bytes, offset);
    }
    meta.featureTables.push(table);
    return [meta, extent];
}

/**
 * Decodes a tile with embedded metadata (Tag 0x01 format).
 * This is the primary decoder function for MLT tiles.
 *
 * @param tile The tile data to decode (will be decompressed if gzip-compressed)
 * @param geometryScaling Optional geometry scaling parameters
 * @param idWithinMaxSafeInteger If true, limits ID values to JavaScript safe integer range (53 bits)
 */
function decodeTile(tile, geometryScaling, idWithinMaxSafeInteger = true) {
    const offset = new IntWrapper(0);
    const featureTables = [];
    while (offset.get() < tile.length) {
        const blockLength = decodeVarintInt32(tile, offset, 1)[0] >>> 0;
        const blockStart = offset.get();
        const blockEnd = blockStart + blockLength;
        if (blockEnd > tile.length) {
            throw new Error(`Block overruns tile: ${blockEnd} > ${tile.length}`);
        }
        const tag = decodeVarintInt32(tile, offset, 1)[0] >>> 0;
        if (tag !== 1) {
            // Skip unknown block types
            offset.set(blockEnd);
            continue;
        }
        const [metadata, extent] = decodeEmbeddedTileSetMetadata(tile, offset);
        const featureTableMetadata = metadata.featureTables[0];
        let idVector = null;
        let geometryVector = null;
        const propertyVectors = [];
        let numFeatures = 0;
        for (const columnMetadata of featureTableMetadata.columns) {
            const columnName = columnMetadata.name;
            if (isLogicalIdColumn(columnMetadata)) {
                let nullabilityBuffer = null;
                // Check column metadata nullable flag, not numStreams (ID columns don't have stream count)
                if (columnMetadata.nullable) {
                    const presentStreamMetadata = decodeStreamMetadata(tile, offset);
                    const streamDataStart = offset.get();
                    const values = decodeBooleanRle(tile, presentStreamMetadata.numValues, presentStreamMetadata.byteLength, offset);
                    offset.set(streamDataStart + presentStreamMetadata.byteLength);
                    nullabilityBuffer = new BitVector(values, presentStreamMetadata.numValues);
                }
                const idDataStreamMetadata = decodeStreamMetadata(tile, offset);
                // decompressedCount is the count WITHOUT nulls, but we may have nulls
                numFeatures = nullabilityBuffer ? nullabilityBuffer.size() : idDataStreamMetadata.decompressedCount;
                idVector = decodeIdColumn(tile, columnMetadata, offset, columnName, idDataStreamMetadata, nullabilityBuffer ?? numFeatures, idWithinMaxSafeInteger);
            }
            else if (isGeometryColumn(columnMetadata)) {
                const numStreams = decodeVarintInt32(tile, offset, 1)[0];
                // If no ID column, get numFeatures from geometry type stream metadata
                if (numFeatures === 0) {
                    const savedOffset = offset.get();
                    const geometryTypeMetadata = decodeStreamMetadata(tile, offset);
                    numFeatures = geometryTypeMetadata.decompressedCount;
                    offset.set(savedOffset); // Reset to re-read in decodeGeometryColumn
                }
                if (geometryScaling) {
                    geometryScaling.scale = geometryScaling.extent / extent;
                }
                geometryVector = decodeGeometryColumn(tile, numStreams, offset, numFeatures, geometryScaling);
            }
            else {
                const columnHasStreamCount = hasStreamCount(columnMetadata);
                const numStreams = columnHasStreamCount ? decodeVarintInt32(tile, offset, 1)[0] : 1;
                if (numStreams === 0) {
                    continue;
                }
                const propertyVector = decodePropertyColumn(tile, offset, columnMetadata, numStreams, numFeatures, undefined);
                if (propertyVector) {
                    if (Array.isArray(propertyVector)) {
                        for (const property of propertyVector) {
                            propertyVectors.push(property);
                        }
                    }
                    else {
                        propertyVectors.push(propertyVector);
                    }
                }
            }
        }
        const featureTable = new FeatureTable(featureTableMetadata.name, geometryVector, idVector, propertyVectors, extent);
        featureTables.push(featureTable);
        offset.set(blockEnd);
    }
    return featureTables;
}
function decodeIdColumn(tile, columnMetadata, offset, columnName, idDataStreamMetadata, sizeOrNullabilityBuffer, idWithinMaxSafeInteger = false) {
    const scalarTypeMetadata = columnMetadata.scalarType;
    if (!scalarTypeMetadata ||
        scalarTypeMetadata.type !== "logicalType" ||
        scalarTypeMetadata.logicalType !== LogicalScalarType.ID) {
        throw new Error(`ID column must be a logical ID scalar type: ${columnName}`);
    }
    const idDataType = scalarTypeMetadata.longID ? ScalarType.UINT_64 : ScalarType.UINT_32;
    const nullabilityBuffer = typeof sizeOrNullabilityBuffer === "number" ? undefined : sizeOrNullabilityBuffer;
    const vectorType = getVectorType(idDataStreamMetadata, sizeOrNullabilityBuffer, tile, offset, idDataType === ScalarType.UINT_64 ? "int64" : "int32");
    if (idDataType === ScalarType.UINT_32) {
        switch (vectorType) {
            case VectorType.FLAT: {
                const id = decodeUnsignedInt32Stream(tile, offset, idDataStreamMetadata, undefined, nullabilityBuffer);
                return new Int32FlatVector(columnName, id, sizeOrNullabilityBuffer);
            }
            case VectorType.SEQUENCE: {
                const id = decodeSequenceInt32Stream(tile, offset, idDataStreamMetadata);
                return new Int32SequenceVector(columnName, id[0], id[1], idDataStreamMetadata.numRleValues);
            }
            case VectorType.CONST: {
                const id = decodeUnsignedConstInt32Stream(tile, offset, idDataStreamMetadata);
                return new Int32ConstVector(columnName, id, sizeOrNullabilityBuffer, false);
            }
        }
    }
    switch (vectorType) {
        case VectorType.FLAT: {
            if (idWithinMaxSafeInteger) {
                const id = decodeUnsignedInt64AsFloat64Stream(tile, offset, idDataStreamMetadata);
                return new DoubleFlatVector(columnName, id, sizeOrNullabilityBuffer);
            }
            const id = decodeUnsignedInt64Stream(tile, offset, idDataStreamMetadata, nullabilityBuffer);
            return new Int64FlatVector(columnName, id, sizeOrNullabilityBuffer);
        }
        case VectorType.SEQUENCE: {
            const id = decodeSequenceInt64Stream(tile, offset, idDataStreamMetadata);
            return new Int64SequenceVector(columnName, id[0], id[1], idDataStreamMetadata.numRleValues);
        }
        case VectorType.CONST: {
            const id = decodeUnsignedConstInt64Stream(tile, offset, idDataStreamMetadata);
            return new Int64ConstVector(columnName, id, sizeOrNullabilityBuffer, false);
        }
    }
    throw new Error("Vector type not supported for id column.");
}

class MLTVectorTileFeature {
    constructor(feature, extent) {
        var _a;
        this._featureData = feature;
        this.properties = this._featureData.properties || {};
        switch ((_a = this._featureData.geometry) === null || _a === void 0 ? void 0 : _a.type) {
            case GEOMETRY_TYPE.POINT:
            case GEOMETRY_TYPE.MULTIPOINT:
                this.type = 1;
                break;
            case GEOMETRY_TYPE.LINESTRING:
            case GEOMETRY_TYPE.MULTILINESTRING:
                this.type = 2;
                break;
            case GEOMETRY_TYPE.POLYGON:
            case GEOMETRY_TYPE.MULTIPOLYGON:
                this.type = 3;
                break;
            default:
                this.type = 0;
        }
        ;
        this.extent = extent;
        this.id = Number(this._featureData.id);
    }
    loadGeometry() {
        const points = [];
        for (const ring of this._featureData.geometry.coordinates) {
            const pointRing = [];
            for (const coord of ring) {
                pointRing.push(new Point(coord.x, coord.y));
            }
            points.push(pointRing);
        }
        return points;
    }
}
class MLTVectorTileLayer {
    constructor(featureTable) {
        this.features = [];
        this.featureTable = featureTable;
        this.name = featureTable.name;
        this.extent = featureTable.extent;
        this.version = 2;
        this.features = featureTable.getFeatures();
        this.length = this.features.length;
    }
    feature(i) {
        return new MLTVectorTileFeature(this.features[i], this.extent);
    }
}
class MLTVectorTile {
    constructor(buffer) {
        this.layers = {};
        const features = decodeTile(new Uint8Array(buffer));
        this.layers = features.reduce((acc, f) => (Object.assign(Object.assign({}, acc), { [f.name]: new MLTVectorTileLayer(f) })), {});
    }
}

class FeatureWrapper {
    constructor(feature, extent) {
        this.feature = feature;
        this.type = feature.type;
        this.properties = feature.tags ? feature.tags : {};
        this.extent = extent;
        // 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) {
            if (typeof feature.id === 'string') {
                this.id = parseInt(feature.id, 10);
            }
            else if (typeof feature.id === 'number' && !isNaN(feature.id)) {
                this.id = feature.id;
            }
        }
    }
    loadGeometry() {
        const geometry = [];
        const rawGeo = this.feature.type === 1 ? [this.feature.geometry] : this.feature.geometry;
        for (const ring of rawGeo) {
            const newRing = [];
            for (const point of ring) {
                newRing.push(new Point(point[0], point[1]));
            }
            geometry.push(newRing);
        }
        return geometry;
    }
}
const GEOJSON_TILE_LAYER_NAME = "_geojsonTileLayer";
class GeoJSONWrapper {
    constructor(features, options) {
        this.layers = { [GEOJSON_TILE_LAYER_NAME]: this };
        this.name = GEOJSON_TILE_LAYER_NAME;
        this.version = options ? options.version : 1;
        this.extent = options ? options.extent : 4096;
        this.length = features.length;
        this.features = features;
    }
    feature(i) {
        return new FeatureWrapper(this.features[i], this.extent);
    }
}

/**
 * Serialize a vector-tile-js-created tile to pbf
 *
 * @param tile - the tile to serialize
 * @param jsonPrefix - a string prefix to prepend to JSON-stringified non-primitive property values, used to distinguish them from regular string values when parsing the tile later. Default is "".
 * @return uncompressed, pbf-serialized tile data
 */
function fromVectorTileJs(tile, jsonPrefix = "") {
    const out = new Pbf();
    writeTile(tile, out, jsonPrefix);
    return out.finish();
}
/**
 * Serialized a geojson-vt-created tile to pbf.
 *
 * @param layers - An object mapping layer names to geojson-vt-created vector tile objects
 * @param options - An object specifying the vector-tile specification version and extent that were used to create `layers`.
 * @return uncompressed, pbf-serialized tile data
 */
function fromGeojsonVt(layers, options) {
    const l = {};
    // eslint-disable-next-line @typescript-eslint/no-for-in-array
    for (const k in layers) {
        l[k] = new GeoJSONWrapper(layers[k].features, options);
        l[k].name = k;
        l[k].version = options ? options.version : 1;
        l[k].extent = options ? options.extent : 4096;
    }
    return fromVectorTileJs({ layers: l });
}
function writeTile(tile, pbf, jsonPrefix = "") {
    for (const key in tile.layers) {
        pbf.writeMessage(3, (layer, pbf) => writeLayer(layer, pbf, jsonPrefix), tile.layers[key]);
    }
}
function writeLayer(layer, pbf, jsonPrefix = "") {
    pbf.writeVarintField(15, layer.version || 1);
    pbf.writeStringField(1, layer.name || '');
    pbf.writeVarintField(5, layer.extent || 4096);
    const context = {
        jsonPrefix,
        keys: [],
        values: [],
        keycache: {},
        valuecache: {}
    };
    for (let i = 0; i < layer.length; i++) {
        context.feature = layer.feature(i);
        pbf.writeMessage(2, writeFeature, context);
    }
    const keys = context.keys;
    for (const key of keys) {
        pbf.writeStringField(3, key);
    }
    const values = context.values;
    for (const value of values) {
        pbf.writeMessage(4, writeValue, value);
    }
}
function writeFeature(context, pbf) {
    if (!context.feature) {
        return;
    }
    const 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) {
    for (const key in context.feature?.properties) {
        let value = context.feature.properties[key];
        let keyIndex = context.keycache[key];
        if (value == null)
            continue; // don't encode null/undefined value properties
        if (typeof keyIndex === 'undefined') {
            context.keys.push(key);
            keyIndex = context.keys.length - 1;
            context.keycache[key] = keyIndex;
        }
        pbf.writeVarint(keyIndex);
        if (typeof value !== 'string' && typeof value !== 'boolean' && typeof value !== 'number') {
            value = context.jsonPrefix + JSON.stringify(value);
        }
        const valueKey = typeof value + ':' + value;
        let valueIndex = context.valuecache[valueKey];
        if (typeof valueIndex === 'undefined') {
            context.values.push(value);
            valueIndex = context.values.length - 1;
            context.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) {
    const geometry = feature.loadGeometry();
    const type = feature.type;
    let x = 0;
    let y = 0;
    for (const ring of geometry) {
        let count = 1;
        if (type === 1) {
            count = ring.length;
        }
        pbf.writeVarint(command(1, count)); // moveto
        // do not write polygon closing path as lineto
        const lineCount = type === 3 ? ring.length - 1 : ring.length;
        for (let i = 0; i < lineCount; i++) {
            if (i === 1 && type !== 1) {
                pbf.writeVarint(command(2, lineCount - 1)); // lineto
            }
            const dx = ring[i].x - x;
            const dy = ring[i].y - y;
            pbf.writeVarint(zigzag(dx));
            pbf.writeVarint(zigzag(dy));
            x += dx;
            y += dy;
        }
        if (feature.type === 3) {
            pbf.writeVarint(command(7, 1)); // closepath
        }
    }
}
function writeValue(value, pbf) {
    const 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);
        }
    }
}

/**
 * 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$1, 16, 0);
        this.grid3D = new TransferableGridIndex(EXTENT$1, 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 (const ring of geometry) {
            const bbox = [Infinity, Infinity, -Infinity, -Infinity];
            for (const p of ring) {
                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$1 &&
                bbox[1] < EXTENT$1 &&
                bbox[2] >= 0 &&
                bbox[3] >= 0) {
                grid.insert(key, bbox[0], bbox[1], bbox[2], bbox[3]);
            }
        }
    }
    loadVTLayers() {
        if (!this.vtLayers) {
            this.vtLayers = this.encoding !== 'mlt'
                ? new VectorTile(new Pbf(this.rawTileData)).layers
                : new MLTVectorTile(this.rawTileData).layers;
            this.sourceLayerCoder = new DictionaryCoder(this.vtLayers ? Object.keys(this.vtLayers).sort() : [GEOJSON_TILE_LAYER_NAME]);
        }
        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;
        const pixelsToTileUnits = EXTENT$1 / args.tileSize / args.scale;
        const filter = featureFilter(params.filter, params.globalState);
        const queryGeometry = args.queryGeometry;
        const queryPadding = args.queryPadding * pixelsToTileUnits;
        const bounds = Bounds.fromPoints(queryGeometry);
        const matching = this.grid.query(bounds.minX - queryPadding, bounds.minY - queryPadding, bounds.maxX + queryPadding, bounds.maxY + queryPadding);
        const cameraBounds = Bounds.fromPoints(args.cameraQueryGeometry).expandBy(queryPadding);
        const matching3D = this.grid3D.query(cameraBounds.minX, cameraBounds.minY, cameraBounds.maxX, cameraBounds.maxY, (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 (const index of matching) {
            // 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,
                    geometry: featureGeometry,
                    zoom: this.z,
                    transform: args.transform,
                    pixelsToTileUnits,
                    pixelPosMatrix: args.pixelPosMatrix,
                    unwrappedTileID: this.tileID.toUnwrapped(),
                    getElevation: args.getElevation
                });
            });
        }
        return result;
    }
    loadMatchingFeature(result, bucketIndex, sourceLayerIndex, featureIndex, filter, filterLayerIDs, availableImages, styleLayers, serializedLayers, sourceFeatureState, intersectionTest) {
        const layerIDs = this.bucketLayerIDs[bucketIndex];
        if (filterLayerIDs && !layerIDs.some(id => filterLayerIDs.has(id)))
            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 (const layerID of layerIDs) {
            if (filterLayerIDs && !filterLayerIDs.has(layerID)) {
                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 || GEOJSON_TILE_LAYER_NAME, 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, filterParams, filterLayerIDs, availableImages, styleLayers) {
        const result = {};
        this.loadVTLayers();
        const filter = featureFilter(filterParams.filterSpec, filterParams.globalState);
        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) {
        var _a;
        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);
            // When cluster is true, the id is the cluster_id even though promoteId is set
            if (id === undefined && ((_a = feature.properties) === null || _a === void 0 ? void 0 : _a.cluster) && this.promoteId) {
                id = Number(feature.properties.cluster_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 === null || prop === void 0 ? void 0 : prop.evaluate) ? prop.evaluate(feature, featureState, availableImages) : prop;
    });
}
function topDownFeatureComparator(a, b) {
    return b - a;
}

/**
 * @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
 *
 * TileManager offloads currently unused tiles to this cache, and when a tile gets used again,
 * it is also removed from this cache. Thus addition is the only operation that counts as "usage"
 * for the purposes of LRU behaviour.
 */
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);
        }
    }
}
class BoundedLRUCache {
    constructor(maxEntries) {
        this.maxEntries = maxEntries;
        this.map = new Map();
    }
    get(key) {
        const value = this.map.get(key);
        if (value !== undefined) {
            // Move key to end (most recently used)
            this.map.delete(key);
            this.map.set(key, value);
        }
        return value;
    }
    set(key, value) {
        if (this.map.has(key)) {
            this.map.delete(key);
        }
        else if (this.map.size >= this.maxEntries) {
            // Delete oldest
            const oldestKey = this.map.keys().next().value;
            this.map.delete(oldestKey);
        }
        this.map.set(key, value);
    }
    clear() {
        this.map.clear();
    }
}

/**
 * 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 (const line of lines) {
        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(x1, p0.y + (p1.y - p0.y) * ((x1 - p0.x) / (p1.x - p0.x)))._round();
            }
            else if (p1.x < x1) {
                p1 = new Point(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(p0.x + (p1.x - p0.x) * ((y1 - p0.y) / (p1.y - p0.y)), y1)._round();
            }
            else if (p1.y < y1) {
                p1 = new Point(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(x2, p0.y + (p1.y - p0.y) * ((x2 - p0.x) / (p1.x - p0.x)))._round();
            }
            else if (p1.x >= x2) {
                p1 = new Point(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(p0.x + (p1.x - p0.x) * ((y2 - p0.y) / (p1.y - p0.y)), y2)._round();
            }
            else if (p1.y >= y2) {
                p1 = new Point(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;
}
/**
 * Clips the geometry to the given bounds.
 * @param geometry - the geometry to clip
 * @param type - the geometry type (1=POINT, 2=LINESTRING, 3=POLYGON)
 * @param x1 - the left edge of the clipping box
 * @param y1 - the top edge of the clipping box
 * @param x2 - the right edge of the clipping box
 * @param y2 - the bottom edge of the clipping box
 * @returns the clipped geometry
 */
function clipGeometry(geometry, type, x1, y1, x2, y2) {
    let clippedGeometry = clipGeometryOnAxis(geometry, type, x1, x2, 0 /* AxisType.X */);
    clippedGeometry = clipGeometryOnAxis(clippedGeometry, type, y1, y2, 1 /* AxisType.Y */);
    return clippedGeometry;
}
/**
 * Clip features between two vertical or horizontal axis-parallel lines:
 * ```
 *     |        |
 *  ___|___     |     /
 * /   |   \____|____/
 *     |        |
 *```
 * @param geometry - the geometry to clip
 * @param type - the geometry type (1=POINT, 2=LINESTRING, 3=POLYGON)
 * @param start - the start line coordinate (x or y) to clip against
 * @param end - the end line coordinate (x or y) to clip against
 * @param axis - the axis to clip on (X or Y)
 * @returns the clipped geometry
 */
function clipGeometryOnAxis(geometry, type, start, end, axis) {
    switch (type) {
        case 1: // POINT
            return clipPoints(geometry, start, end, axis);
        case 2: // LINESTRING
            return clipLines(geometry, start, end, axis, false);
        case 3: // POLYGON
            return clipLines(geometry, start, end, axis, true);
    }
    return [];
}
function clipPoints(geometry, start, end, axis) {
    const newGeometry = [];
    for (const ring of geometry) {
        for (const point of ring) {
            const a = axis === 0 /* AxisType.X */ ? point.x : point.y;
            if (a >= start && a <= end) {
                newGeometry.push([point]);
            }
        }
    }
    return newGeometry;
}
/**
 * Clips a line to the given start and end coordinates.
 * @param line - the line to clip
 * @param start - the start line coordinate (x or y) to clip against
 * @param end - the end line coordinate (x or y) to clip against
 * @param axis - the axis to clip on (X or Y)
 * @param isPolygon - whether the line is part of a polygon
 * @returns the clipped line(s)
 */
function clipLineInternal(line, start, end, axis, isPolygon) {
    const intersectionPoint = axis === 0 /* AxisType.X */ ? intersectionPointX : intersectionPointY;
    let slice = [];
    const newLine = [];
    for (let i = 0; i < line.length - 1; i++) {
        const p1 = line[i];
        const p2 = line[i + 1];
        const pos1 = axis === 0 /* AxisType.X */ ? p1.x : p1.y;
        const pos2 = axis === 0 /* AxisType.X */ ? p2.x : p2.y;
        let exited = false;
        if (pos1 < start) {
            // ---|-->  | (line enters the clip region from the left)
            if (pos2 > start) {
                slice.push(intersectionPoint(p1, p2, start));
            }
        }
        else if (pos1 > end) {
            // |  <--|--- (line enters the clip region from the right)
            if (pos2 < end) {
                slice.push(intersectionPoint(p1, p2, end));
            }
        }
        else {
            slice.push(p1);
        }
        if (pos2 < start && pos1 >= start) {
            // <--|---  | or <--|-----|--- (line exits the clip region on the left)
            slice.push(intersectionPoint(p1, p2, start));
            exited = true;
        }
        if (pos2 > end && pos1 <= end) {
            // |  ---|--> or ---|-----|--> (line exits the clip region on the right)
            slice.push(intersectionPoint(p1, p2, end));
            exited = true;
        }
        if (!isPolygon && exited) {
            newLine.push(slice);
            slice = [];
        }
    }
    // add the last point
    const last = line.length - 1;
    const lastPos = axis === 0 /* AxisType.X */ ? line[last].x : line[last].y;
    if (lastPos >= start && lastPos <= end) {
        slice.push(line[last]);
    }
    // close the polygon if its endpoints are not the same after clipping
    if (isPolygon && slice.length > 0 && !slice[0].equals(slice[slice.length - 1])) {
        slice.push(new Point(slice[0].x, slice[0].y));
    }
    if (slice.length > 0) {
        newLine.push(slice);
    }
    return newLine;
}
function clipLines(geometry, start, end, axis, isPolygon) {
    const newGeometry = [];
    for (const line of geometry) {
        const clippedLines = clipLineInternal(line, start, end, axis, isPolygon);
        if (clippedLines.length > 0) {
            newGeometry.push(...clippedLines);
        }
    }
    return newGeometry;
}
function intersectionPointX(p1, p2, x) {
    const t = (x - p1.x) / (p2.x - p1.x);
    return new Point(x, p1.y + (p2.y - p1.y) * t);
}
function intersectionPointY(p1, p2, y) {
    const t = (y - p1.y) / (p2.y - p1.y);
    return new Point(p1.x + (p2.x - p1.x) * t, y);
}

class Anchor extends Point {
    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 = interpolateFactory.number(a.x, b.x, t), y = interpolateFactory.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;
    let 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 = interpolateFactory.number(a.x, b.x, t), y = interpolateFactory.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(leftEm, topEm);
        const tr = new Point(rightEm, topEm);
        const br = new Point(rightEm, bottomEm);
        const bl = new Point(leftEm, bottomEm);
        const pixelOffsetTL = new Point(leftPx / pixelRatio, topPx / pixelRatio);
        const pixelOffsetBR = new Point(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(x1, y1);
            const tr = new Point(x2, y1);
            const bl = new Point(x1, y2);
            const br = new Point(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(-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(5 - SHAPING_DEFAULT_OFFSET - xHalfWidthOffsetCorrection, -yImageOffsetCorrection);
                const verticalOffsetCorrection = new Point(...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(0, 0);
            const pixelOffsetBR = new Point(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(icon.x1, icon.y1);
                const tr = new Point(icon.x2, icon.y1);
                const bl = new Point(icon.x1, icon.y2);
                const br = new Point(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
 * @returns Pole of Inaccessibility.
 */
function findPoleOfInaccessibility(polygonRings, precision = 1) {
    const bounds = Bounds.fromPoints(polygonRings[0]);
    const cellSize = Math.min(bounds.width(), bounds.height());
    let h = cellSize / 2;
    // a priority queue of cells in order of their "potential" (max distance to polygon)
    const cellQueue = new TinyQueue([], compareMax);
    const { minX, minY, maxX, maxY } = bounds;
    if (cellSize === 0)
        return new Point(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
    const centroidCell = getCentroidCell(polygonRings);
    let bestCell = centroidCell;
    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;
        }
        // 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));
    }
    // For convex or nearly-convex polygons, the centroid provides visually
    // better label placement than the mathematical POI.
    // Coordinate rounding (e.g. in geojson-vt) can break polygon symmetry and cause the POI to
    // drift far from center even though its distance-to-edge is only marginally better.
    // Prefer the centroid when it is inside the polygon
    // and its distance is within `precision` of the best found.
    if (centroidCell.d > 0 && bestCell.d - centroidCell.d <= precision) {
        return centroidCell.p;
    }
    return bestCell.p;
}
function compareMax(a, b) {
    return b.max - a.max;
}
class Cell {
    constructor(x, y, h, polygon) {
        this.p = new Point(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 (const ring of polygon) {
        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$1.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$1.TextAnchorEnum || (exports$1.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) {
    var _a;
    var _b;
    args.bucket.createArrays();
    const tileSize = 512 * args.bucket.overscaling;
    args.bucket.tilePixelRatio = EXTENT$1 / 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$1.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$1.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$1.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$1.WritingMode.vertical, false, layoutTextSize, layoutTextSizeThisZoom);
                }
            }
        }
        let shapedIcon;
        let isSDFIcon = false;
        if ((_a = feature.icon) === null || _a === void 0 ? void 0 : _a.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;
        (_b = args.bucket).iconsInText || (_b.iconsInText = shapedText ? shapedText.iconsInText : false);
        if (shapedText || shapedIcon) {
            addFeature(args.bucket, feature, shapedTextOrientations, shapedIcon, args.imageMap, sizes, layoutTextSize, layoutIconSize, textOffset, isSDFIcon, args.canonical, args.subdivisionGranularity);
        }
    }
    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 it 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, subdivisionGranularity) {
    // 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 granularity = (canonical) ? subdivisionGranularity.line.getGranularityForZoomLevel(canonical.z) : 1;
    const addSymbolAtAnchor = (line, anchor) => {
        if (anchor.x < 0 || anchor.x >= EXTENT$1 || anchor.y < 0 || anchor.y >= EXTENT$1) {
            // 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$1, EXTENT$1)) {
            const subdividedLine = subdivideVertexLine(line, granularity);
            const anchors = getAnchors(subdividedLine, symbolMinDistance, textMaxAngle, shapedTextOrientations.vertical || defaultHorizontalShaping, shapedIcon, glyphSize, textMaxBoxScale, bucket.overscaling, EXTENT$1);
            for (const anchor of anchors) {
                const shapedText = defaultHorizontalShaping;
                if (!shapedText || !anchorIsTooClose(bucket, shapedText.text, textRepeatDistance, anchor)) {
                    addSymbolAtAnchor(subdividedLine, 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 subdividedLine = subdivideVertexLine(line, granularity);
                const anchor = getCenterAnchor(subdividedLine, textMaxAngle, shapedTextOrientations.vertical || defaultHorizontalShaping, shapedIcon, glyphSize, textMaxBoxScale);
                if (anchor) {
                    addSymbolAtAnchor(subdividedLine, 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);
            const subdividedLine = subdivideVertexLine(polygon[0], granularity, true);
            addSymbolAtAnchor(subdividedLine, 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) {
            const subdividedLine = subdivideVertexLine(line, granularity);
            addSymbolAtAnchor(subdividedLine, new Anchor(subdividedLine[0].x, subdividedLine[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$1.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('');
    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$1.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$1.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(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$1.WritingMode.horizontal : exports$1.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$1.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 === null || feature === void 0 ? void 0 : 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;
}

exports$1.AJAXError = AJAXError;
exports$1.AbortError = AbortError;
exports$1.Actor = Actor;
exports$1.AlphaImage = AlphaImage;
exports$1.BoundedLRUCache = BoundedLRUCache;
exports$1.Bounds = Bounds;
exports$1.CanonicalTileID = CanonicalTileID;
exports$1.CollisionBoxArray = CollisionBoxArray;
exports$1.CollisionCircleLayoutArray = CollisionCircleLayoutArray;
exports$1.Color = Color;
exports$1.DEMData = DEMData;
exports$1.DataConstantProperty = DataConstantProperty;
exports$1.DictionaryCoder = DictionaryCoder;
exports$1.EXTENT = EXTENT$1;
exports$1.ErrorEvent = ErrorEvent;
exports$1.EvaluationParameters = EvaluationParameters;
exports$1.Event = Event;
exports$1.Evented = Evented;
exports$1.FeatureIndex = FeatureIndex;
exports$1.FillBucket = FillBucket;
exports$1.FillExtrusionBucket = FillExtrusionBucket;
exports$1.GEOJSON_TILE_LAYER_NAME = GEOJSON_TILE_LAYER_NAME;
exports$1.GLOBAL_DISPATCHER_ID = GLOBAL_DISPATCHER_ID;
exports$1.GeoJSONFeature = GeoJSONFeature;
exports$1.GeoJSONVT = GeoJSONVT;
exports$1.GeoJSONWrapper = GeoJSONWrapper;
exports$1.HEATMAP_FULL_RENDER_FBO_KEY = HEATMAP_FULL_RENDER_FBO_KEY;
exports$1.ImageAtlas = ImageAtlas;
exports$1.ImagePosition = ImagePosition;
exports$1.KDBush = KDBush;
exports$1.LineBucket = LineBucket;
exports$1.LineStripIndexArray = LineStripIndexArray;
exports$1.LngLat = LngLat;
exports$1.MAX_TILE_ZOOM = MAX_TILE_ZOOM;
exports$1.MAX_VALID_LATITUDE = MAX_VALID_LATITUDE;
exports$1.MLTVectorTile = MLTVectorTile;
exports$1.MercatorCoordinate = MercatorCoordinate;
exports$1.NORTH_POLE_Y = NORTH_POLE_Y;
exports$1.ONE_EM = ONE_EM;
exports$1.OverscaledTileID = OverscaledTileID;
exports$1.Pbf = Pbf;
exports$1.Point = Point;
exports$1.Pos3dArray = Pos3dArray;
exports$1.PosArray = PosArray;
exports$1.ProjectionDefinition = ProjectionDefinition;
exports$1.Properties = Properties;
exports$1.QuadTriangleArray = QuadTriangleArray;
exports$1.RGBAImage = RGBAImage;
exports$1.RasterBoundsArray = RasterBoundsArray;
exports$1.SOUTH_POLE_Y = SOUTH_POLE_Y;
exports$1.SegmentVector = SegmentVector;
exports$1.SubdivisionGranularityExpression = SubdivisionGranularityExpression;
exports$1.SubdivisionGranularitySetting = SubdivisionGranularitySetting;
exports$1.SymbolBucket = SymbolBucket;
exports$1.TRANSITION_SUFFIX = TRANSITION_SUFFIX;
exports$1.Texture = Texture;
exports$1.TileCache = TileCache;
exports$1.Transitionable = Transitionable;
exports$1.TriangleIndexArray = TriangleIndexArray;
exports$1.Uniform1f = Uniform1f;
exports$1.Uniform1i = Uniform1i;
exports$1.Uniform2f = Uniform2f;
exports$1.Uniform3f = Uniform3f;
exports$1.Uniform4f = Uniform4f;
exports$1.UniformColor = UniformColor;
exports$1.UniformColorArray = UniformColorArray;
exports$1.UniformFloatArray = UniformFloatArray;
exports$1.UniformMatrix4f = UniformMatrix4f;
exports$1.UnwrappedTileID = UnwrappedTileID;
exports$1.ValidationError = ValidationError;
exports$1.VectorTile = VectorTile;
exports$1.ZoomHistory = ZoomHistory;
exports$1.__awaiter = __awaiter;
exports$1.add = add$4;
exports$1.addDynamicAttributes = addDynamicAttributes;
exports$1.addProtocol = addProtocol;
exports$1.altitudeFromMercatorZ = altitudeFromMercatorZ;
exports$1.angleToRotateBetweenVectors2D = angleToRotateBetweenVectors2D;
exports$1.arrayBufferToImage = arrayBufferToImage;
exports$1.arrayBufferToImageBitmap = arrayBufferToImageBitmap;
exports$1.bezier = bezier;
exports$1.calculateTileKey = calculateTileKey;
exports$1.clamp = clamp$2;
exports$1.clipGeometry = clipGeometry;
exports$1.clipLine = clipLine;
exports$1.clone = clone$5;
exports$1.clone$1 = clone$6;
exports$1.clone$2 = clone;
exports$1.codePointUsesLocalIdeographFontFamily = codePointUsesLocalIdeographFontFamily;
exports$1.collisionCircleLayout = collisionCircleLayout;
exports$1.compareTileId = compareTileId;
exports$1.config = config;
exports$1.copy = copy$5;
exports$1.create = create$5;
exports$1.create$1 = create$8;
exports$1.create$2 = create;
exports$1.create$3 = create$6;
exports$1.createExpression = createExpression;
exports$1.createIdentityMat4f32 = createIdentityMat4f32;
exports$1.createIdentityMat4f64 = createIdentityMat4f64;
exports$1.createLayout = createLayout;
exports$1.createMat4f64 = createMat4f64;
exports$1.createStyleLayer = createStyleLayer;
exports$1.createVec3f64 = createVec3f64;
exports$1.createVec4f64 = createVec4f64;
exports$1.cross = cross$2;
exports$1.deepEqual = deepEqual$1;
exports$1.defaultEasing = defaultEasing;
exports$1.degreesToRadians = degreesToRadians;
exports$1.derefLayers = derefLayers;
exports$1.diff = diff;
exports$1.differenceOfAnglesDegrees = differenceOfAnglesDegrees;
exports$1.distanceOfAnglesRadians = distanceOfAnglesRadians;
exports$1.dot = dot$5;
exports$1.earthRadius = earthRadius;
exports$1.easeCubicInOut = easeCubicInOut;
exports$1.emitValidationErrors = emitValidationErrors;
exports$1.emptyStyle = emptyStyle;
exports$1.ensureError = ensureError;
exports$1.equals = equals$6;
exports$1.evaluateSizeForFeature = evaluateSizeForFeature;
exports$1.evaluateSizeForZoom = evaluateSizeForZoom;
exports$1.evaluateZoomSnap = evaluateZoomSnap;
exports$1.exactEquals = exactEquals$5;
exports$1.extend = extend;
exports$1.featureFilter = featureFilter;
exports$1.filterObject = filterObject;
exports$1.findLineIntersection = findLineIntersection;
exports$1.fromEuler = fromEuler;
exports$1.fromRotation = fromRotation$2;
exports$1.fromScaling = fromScaling;
exports$1.fromVectorTileJs = fromVectorTileJs;
exports$1.getAABB = getAABB;
exports$1.getAnchorAlignment = getAnchorAlignment;
exports$1.getAnchorJustification = getAnchorJustification;
exports$1.getAngleDelta = getAngleDelta;
exports$1.getArrayBuffer = getArrayBuffer;
exports$1.getEdgeTiles = getEdgeTiles;
exports$1.getImageData = getImageData;
exports$1.getJSON = getJSON;
exports$1.getOverlapMode = getOverlapMode;
exports$1.getProtocol = getProtocol;
exports$1.getReferrer = getReferrer;
exports$1.getRollPitchBearing = getRollPitchBearing;
exports$1.getVideo = getVideo;
exports$1.groupByLayout = groupByLayout;
exports$1.identity = identity$2;
exports$1.interpolateFactory = interpolateFactory;
exports$1.invert = invert$5;
exports$1.invert$1 = invert$2;
exports$1.isAbortError = isAbortError;
exports$1.isBackgroundStyleLayer = isBackgroundStyleLayer;
exports$1.isCircleStyleLayer = isCircleStyleLayer;
exports$1.isColorReliefStyleLayer = isColorReliefStyleLayer;
exports$1.isCustomStyleLayer = isCustomStyleLayer;
exports$1.isFillExtrusionStyleLayer = isFillExtrusionStyleLayer;
exports$1.isFillStyleLayer = isFillStyleLayer;
exports$1.isHeatmapStyleLayer = isHeatmapStyleLayer;
exports$1.isHillshadeStyleLayer = isHillshadeStyleLayer;
exports$1.isImageBitmap = isImageBitmap;
exports$1.isInBoundsForZoomLngLat = isInBoundsForZoomLngLat;
exports$1.isLineStyleLayer = isLineStyleLayer;
exports$1.isOffscreenCanvasDistorted = isOffscreenCanvasDistorted;
exports$1.isPointableEvent = isPointableEvent;
exports$1.isRasterStyleLayer = isRasterStyleLayer;
exports$1.isSafari = isSafari;
exports$1.isSymbolStyleLayer = isSymbolStyleLayer;
exports$1.isTouchableEvent = isTouchableEvent;
exports$1.isTouchableOrPointableType = isTouchableOrPointableType;
exports$1.isWorker = isWorker;
exports$1.latFromMercatorY = latFromMercatorY;
exports$1.len = len$4;
exports$1.length = length;
exports$1.length$1 = length$4;
exports$1.lerp = lerp;
exports$1.lngFromMercatorX = lngFromMercatorX;
exports$1.makeRequest = makeRequest;
exports$1.mapObject = mapObject;
exports$1.mercatorXfromLng = mercatorXfromLng;
exports$1.mercatorYfromLat = mercatorYfromLat;
exports$1.mercatorZfromAltitude = mercatorZfromAltitude;
exports$1.mod = mod;
exports$1.mul = mul$3;
exports$1.multiply = multiply$5;
exports$1.nextPowerOfTwo = nextPowerOfTwo;
exports$1.normalize = normalize$4;
exports$1.offscreenCanvasSupported = offscreenCanvasSupported;
exports$1.ortho = ortho;
exports$1.parseCacheControl = parseCacheControl;
exports$1.parseGlyphPbf = parseGlyphPbf;
exports$1.performSymbolLayout = performSymbolLayout;
exports$1.perspective = perspective;
exports$1.pick = pick;
exports$1.pixelsToTileUnits = pixelsToTileUnits;
exports$1.pointPlaneSignedDistance = pointPlaneSignedDistance;
exports$1.polygonIntersectsPolygon = polygonIntersectsPolygon;
exports$1.potpack = potpack;
exports$1.radiansToDegrees = radiansToDegrees;
exports$1.rayPlaneIntersection = rayPlaneIntersection;
exports$1.readImageUsingVideoFrame = readImageUsingVideoFrame;
exports$1.register = register;
exports$1.remapSaturate = remapSaturate;
exports$1.removeProtocol = removeProtocol;
exports$1.renderColorRamp = renderColorRamp;
exports$1.rollPitchBearingEqual = rollPitchBearingEqual;
exports$1.rollPitchBearingToQuat = rollPitchBearingToQuat;
exports$1.rotate = rotate$4;
exports$1.rotateX = rotateX$3;
exports$1.rotateX$1 = rotateX$2;
exports$1.rotateY = rotateY$2;
exports$1.rotateY$1 = rotateY$3;
exports$1.rotateZ = rotateZ$3;
exports$1.rotateZ$1 = rotateZ$2;
exports$1.rtlWorkerPlugin = rtlWorkerPlugin;
exports$1.sameOrigin = sameOrigin;
exports$1.scale = scale$5;
exports$1.scale$1 = scale;
exports$1.scale$2 = scale$4;
exports$1.scale$3 = scale$3;
exports$1.scaleAndAdd = scaleAndAdd$2;
exports$1.scaleZoom = scaleZoom;
exports$1.slerp = slerp;
exports$1.sphericalToCartesian = sphericalToCartesian;
exports$1.sqrLen = sqrLen;
exports$1.sub = sub$2;
exports$1.subscribe = subscribe;
exports$1.threePlaneIntersection = threePlaneIntersection;
exports$1.throwIfAborted = throwIfAborted;
exports$1.toEvaluationFeature = toEvaluationFeature;
exports$1.transformMat3 = transformMat3$1;
exports$1.transformMat4 = transformMat4$1;
exports$1.transformMat4$1 = transformMat4$2;
exports$1.transformMat4$2 = transformMat4;
exports$1.transformQuat = transformQuat$1;
exports$1.translate = translate$2;
exports$1.translatePosition = translatePosition;
exports$1.uniqueId = uniqueId;
exports$1.v8 = v8;
exports$1.v8Spec = v8Spec;
exports$1.validateCustomStyleLayer = validateCustomStyleLayer;
exports$1.validateLight = validateLight;
exports$1.validateSky = validateSky;
exports$1.validateStyle = validateStyle;
exports$1.warnOnce = warnOnce;
exports$1.wrap = wrap$1;
exports$1.zero = zero;
exports$1.zero$1 = zero$2;
exports$1.zoomScale = zoomScale;

}));

define('worker', ['./shared'], (function (symbol_layout) { 'use strict';

class StyleLayerIndex {
    constructor(layerConfigs, globalState) {
        this.keyCache = {};
        if (layerConfigs) {
            this.replace(layerConfigs, globalState);
        }
    }
    replace(layerConfigs, globalState) {
        this._layerConfigs = {};
        this._layers = {};
        this.update(layerConfigs, [], globalState);
    }
    update(layerConfigs, removedIds, globalState) {
        for (const layerConfig of layerConfigs) {
            this._layerConfigs[layerConfig.id] = layerConfig;
            const layer = this._layers[layerConfig.id] = symbol_layout.createStyleLayer(layerConfig, globalState);
            layer._featureFilter = symbol_layout.featureFilter(layer.filter, globalState);
            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 = symbol_layout.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.isHidden()) {
                continue;
            }
            const sourceId = layer.source || '';
            let sourceGroup = this.familiesBySource[sourceId];
            if (!sourceGroup) {
                sourceGroup = this.familiesBySource[sourceId] = {};
            }
            const sourceLayerId = layer.sourceLayer || symbol_layout.GEOJSON_TILE_LAYER_NAME;
            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 } = symbol_layout.potpack(bins);
        const image = new symbol_layout.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;
                symbol_layout.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;
    }
}
symbol_layout.register('GlyphAtlas', GlyphAtlas);

class WorkerTile {
    constructor(params) {
        this.tileID = new symbol_layout.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, subdivisionGranularity) {
        return symbol_layout.__awaiter(this, void 0, void 0, function* () {
            this.status = 'parsing';
            this.data = data;
            this.collisionBoxArray = new symbol_layout.CollisionBoxArray();
            const sourceLayerCoder = new symbol_layout.DictionaryCoder(Object.keys(data.layers).sort());
            const featureIndex = new symbol_layout.FeatureIndex(this.tileID, this.promoteId);
            featureIndex.bucketLayerIDs = [];
            const buckets = {};
            const options = {
                featureIndex,
                iconDependencies: {},
                patternDependencies: {},
                glyphDependencies: {},
                dashDependencies: {},
                availableImages,
                subdivisionGranularity
            };
            const layerFamilies = layerIndex.familiesBySource[this.source];
            for (const sourceLayerId in layerFamilies) {
                const sourceLayer = data.layers[sourceLayerId];
                if (!sourceLayer) {
                    continue;
                }
                if (sourceLayer.version === 1) {
                    symbol_layout.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) {
                        symbol_layout.warnOnce(`layer.source = ${layer.source} does not equal this.source = ${this.source}`);
                    }
                    if (layer.isHidden(this.zoom, true))
                        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 = symbol_layout.mapObject(options.glyphDependencies, (glyphs) => Object.keys(glyphs).map(Number));
            for (const request of this.inFlightDependencies) {
                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({});
            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);
            }
            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 dashes = options.dashDependencies;
            let getDashesPromise = Promise.resolve({});
            if (Object.keys(dashes).length) {
                const abortController = new AbortController();
                this.inFlightDependencies.push(abortController);
                getDashesPromise = actor.sendAsync({ type: "GDA" /* MessageType.getDashes */, data: { dashes } }, abortController);
            }
            const [glyphMap, iconMap, patternMap, dashPositions] = yield Promise.all([getGlyphsPromise, getIconsPromise, getPatternsPromise, getDashesPromise]);
            const glyphAtlas = new GlyphAtlas(glyphMap);
            const imageAtlas = new symbol_layout.ImageAtlas(iconMap, patternMap);
            for (const key in buckets) {
                const bucket = buckets[key];
                if (bucket instanceof symbol_layout.SymbolBucket) {
                    recalculateLayers(bucket.layers, this.zoom, availableImages);
                    symbol_layout.performSymbolLayout({
                        bucket,
                        glyphMap,
                        glyphPositions: glyphAtlas.positions,
                        imageMap: iconMap,
                        imagePositions: imageAtlas.iconPositions,
                        showCollisionBoxes: this.showCollisionBoxes,
                        canonical: this.tileID.canonical,
                        subdivisionGranularity: options.subdivisionGranularity
                    });
                }
                else if (bucket.hasDependencies && (bucket instanceof symbol_layout.FillBucket || bucket instanceof symbol_layout.FillExtrusionBucket || bucket instanceof symbol_layout.LineBucket)) {
                    recalculateLayers(bucket.layers, this.zoom, availableImages);
                    bucket.addFeatures(options, this.tileID.canonical, imageAtlas.patternPositions, dashPositions);
                }
            }
            this.status = 'done';
            return {
                buckets: Object.values(buckets).filter(b => !b.isEmpty()),
                featureIndex,
                collisionBoxArray: this.collisionBoxArray,
                glyphAtlasImage: glyphAtlas.image,
                imageAtlas,
                dashPositions,
                // 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 symbol_layout.EvaluationParameters(zoom);
    for (const layer of layers) {
        layer.recalculate(parameters, availableImages);
    }
}

class WorkerTileState {
    constructor() {
        this.loading = {};
        this.loaded = {};
        this.parsing = {};
    }
    startLoading(uid, tile) {
        this.loading[uid] = tile;
    }
    finishLoading(uid) {
        delete this.loading[uid];
    }
    abort(uid) {
        const tile = this.loading[uid];
        if (!(tile === null || tile === void 0 ? void 0 : tile.abort))
            return;
        tile.abort.abort();
        delete this.loading[uid];
    }
    setParsing(uid, state) {
        this.parsing[uid] = state;
    }
    consumeParsing(uid) {
        const state = this.parsing[uid];
        if (!state)
            return undefined;
        delete this.parsing[uid];
        return state;
    }
    clearParsing(uid) {
        delete this.parsing[uid];
    }
    markLoaded(uid, tile) {
        this.loaded[uid] = tile;
    }
    getLoaded(uid) {
        const tile = this.loaded[uid];
        if (!tile)
            return undefined;
        return tile;
    }
    removeLoaded(uid) {
        delete this.loaded[uid];
    }
    clearLoaded() {
        this.loaded = {};
    }
}

/**
 * @internal
 * Safe wrapper for the performance resource timing API in web workers with graceful degradation
 */
class RequestPerformance {
    constructor(url) {
        this.start = `${url}#start`;
        this.end = `${url}#end`;
        this.measure = url;
        performance.mark(this.start);
    }
    finish() {
        performance.mark(this.end);
        let resourceTimingData = performance.getEntriesByName(this.measure);
        // fallback if web worker implementation of perf.getEntriesByName returns empty
        if (resourceTimingData.length === 0) {
            performance.measure(this.measure, this.start, this.end);
            resourceTimingData = performance.getEntriesByName(this.measure);
            // cleanup
            performance.clearMarks(this.start);
            performance.clearMarks(this.end);
            performance.clearMeasures(this.measure);
        }
        return resourceTimingData;
    }
}

class VectorTileFeatureOverzoomed {
    constructor(type, geometry, properties, id, extent) {
        this.type = type;
        this.properties = properties ? properties : {};
        this.extent = extent;
        this.pointsArray = geometry;
        this.id = id;
    }
    loadGeometry() {
        // Clone the geometry and ensure all points are Point instances
        return this.pointsArray.map(ring => ring.map(point => new symbol_layout.Point(point.x, point.y)));
    }
}
class VectorTileLayerOverzoomed {
    constructor(features, layerName, extent) {
        this.version = 2;
        this._myFeatures = features;
        this.name = layerName;
        this.length = features.length;
        this.extent = extent;
    }
    feature(i) {
        return this._myFeatures[i];
    }
}
class VectorTileOverzoomed {
    constructor() {
        this.layers = {};
    }
    addLayer(layer) {
        this.layers[layer.name] = layer;
    }
}
/**
 * Encodes the virtual tile into binary vector tile form.
 * This is a convenience that allows `FeatureIndex` to operate the same way across `VectorTileSource` and `GeoJSONSource` data.
 * @param virtualVectorTile - a syntetically created vector tile, this tile should have the relevant layer and features already added to it.
 * @returns - the encoded vector tile along with the original virtual tile binary data.
 */
function toVirtualVectorTile(virtualVectorTile) {
    let pbf = symbol_layout.fromVectorTileJs(virtualVectorTile);
    if (pbf.byteOffset !== 0 || pbf.byteLength !== pbf.buffer.byteLength) {
        pbf = new Uint8Array(pbf); // Compatibility with node Buffer (https://github.com/mapbox/pbf/issues/35)
    }
    return {
        vectorTile: virtualVectorTile,
        rawData: pbf.buffer
    };
}
/**
 * This function slices a source tile layer into an overzoomed tile layer for a target tile ID.
 * @param sourceLayer - the source tile layer to slice
 * @param maxZoomTileID - the maximum zoom tile ID
 * @param targetTileID - the target tile ID
 * @returns - the overzoomed tile layer
 */
function sliceVectorTileLayer(sourceLayer, maxZoomTileID, targetTileID) {
    const { extent } = sourceLayer;
    const dz = targetTileID.z - maxZoomTileID.z;
    const scale = Math.pow(2, dz);
    // Calculate the target tile's position within the source tile in target coordinate space
    // This ensures all tiles share the same coordinate system
    const offsetX = (targetTileID.x - maxZoomTileID.x * scale) * extent;
    const offsetY = (targetTileID.y - maxZoomTileID.y * scale) * extent;
    const featureWrappers = [];
    for (let index = 0; index < sourceLayer.length; index++) {
        const feature = sourceLayer.feature(index);
        let geometry = feature.loadGeometry();
        // Transform all coordinates to target tile space
        for (const ring of geometry) {
            for (const point of ring) {
                point.x = point.x * scale - offsetX;
                point.y = point.y * scale - offsetY;
            }
        }
        const buffer = 128;
        geometry = symbol_layout.clipGeometry(geometry, feature.type, -buffer, -buffer, extent + buffer, extent + buffer);
        if (geometry.length === 0) {
            continue;
        }
        featureWrappers.push(new VectorTileFeatureOverzoomed(feature.type, geometry, feature.properties, feature.id, extent));
    }
    return new VectorTileLayerOverzoomed(featureWrappers, sourceLayer.name, extent);
}

/**
 * The {@link WorkerSource} implementation that supports {@link VectorTileSource}. This class is
 * used by vector tile sources to perform tile processing operations in a separate worker thread.
 */
class VectorTileWorkerSource {
    constructor(actor, layerIndex, availableImages) {
        this.actor = actor;
        this.layerIndex = layerIndex;
        this.availableImages = availableImages;
        this.tileState = new WorkerTileState();
        this.overzoomedTileResultCache = new symbol_layout.BoundedLRUCache(1000);
    }
    /**
     * Loads a vector tile
     */
    loadVectorTile(params, rawData) {
        try {
            const vectorTile = params.encoding !== 'mlt'
                ? new symbol_layout.VectorTile(new symbol_layout.Pbf(rawData))
                : new symbol_layout.MLTVectorTile(rawData);
            return { vectorTile, rawData };
        }
        catch (ex) {
            const bytes = new Uint8Array(rawData);
            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: ${symbol_layout.ensureError(ex).message}`;
            }
            throw new Error(errorMessage);
        }
    }
    /**
     * Implements {@link WorkerSource.loadTile}.
     */
    loadTile(params) {
        return symbol_layout.__awaiter(this, void 0, void 0, function* () {
            const { uid, overzoomParameters } = params;
            if (overzoomParameters) {
                params.request = overzoomParameters.overzoomRequest;
            }
            const timing = this._startRequestTiming(params);
            const workerTile = new WorkerTile(params);
            this.tileState.startLoading(uid, workerTile);
            const abortController = new AbortController();
            workerTile.abort = abortController;
            try {
                // Download the tile data from the network.
                const tileResponse = yield symbol_layout.getArrayBuffer(params.request, abortController);
                // Tile data hasn't changed (etag support) - return an unmodified result
                if (params.etag && params.etag === tileResponse.etag) {
                    this.tileState.finishLoading(uid);
                    return this._getEtagUnmodifiedResult(tileResponse, timing);
                }
                const tileResult = this.loadVectorTile(params, tileResponse.data);
                this.tileState.finishLoading(uid);
                if (!tileResult)
                    return null;
                let { vectorTile, rawData } = tileResult;
                if (overzoomParameters) {
                    ({ vectorTile, rawData } = this._getOverzoomTile(params, vectorTile));
                }
                const cacheControl = this._getExpiryData(tileResponse);
                const resourceTiming = this._finishRequestTiming(timing);
                workerTile.vectorTile = vectorTile;
                this.tileState.markLoaded(uid, workerTile);
                const parseState = { rawData, cacheControl, resourceTiming }; // Keep data so reloadTile can access if parse is canceled.
                this.tileState.setParsing(uid, parseState);
                try {
                    return yield this._parseWorkerTile(workerTile, params, parseState);
                }
                finally {
                    this.tileState.clearParsing(uid);
                }
            }
            catch (err) {
                this.tileState.finishLoading(uid);
                workerTile.status = 'done';
                this.tileState.markLoaded(uid, workerTile);
                throw err;
            }
        });
    }
    _getEtagUnmodifiedResult(response, timing) {
        const cacheControl = this._getExpiryData(response);
        const resourceTiming = this._finishRequestTiming(timing);
        return symbol_layout.extend({ etagUnmodified: true }, cacheControl, resourceTiming);
    }
    _parseWorkerTile(workerTile, params, parseState) {
        return symbol_layout.__awaiter(this, void 0, void 0, function* () {
            let result = yield workerTile.parse(workerTile.vectorTile, this.layerIndex, this.availableImages, this.actor, params.subdivisionGranularity);
            if (parseState) {
                const { rawData, cacheControl, resourceTiming } = parseState;
                // Transferring a copy of rawTileData because the worker needs to retain its copy.
                result = symbol_layout.extend({ rawTileData: rawData.slice(0), encoding: params.encoding }, result, cacheControl, resourceTiming);
            }
            return result;
        });
    }
    _getExpiryData({ expires, cacheControl, etag }) {
        const data = {};
        if (expires)
            data.expires = expires;
        if (cacheControl)
            data.cacheControl = cacheControl;
        if (etag)
            data.etag = etag;
        return data;
    }
    _startRequestTiming(params) {
        var _a;
        if (!((_a = params.request) === null || _a === void 0 ? void 0 : _a.collectResourceTiming))
            return;
        return new RequestPerformance(params.request.url);
    }
    _finishRequestTiming(timing) {
        const timingData = timing === null || timing === void 0 ? void 0 : timing.finish();
        if (!timingData)
            return {};
        // it's necessary to eval the result of getEntriesByName() here via parse/stringify
        // late evaluation in the main thread causes TypeError: illegal invocation
        return { resourceTiming: JSON.parse(JSON.stringify(timingData)) };
    }
    /**
     * If we are seeking a tile deeper than the source's max available canonical tile, get the overzoomed tile
     * @param params - the worker tile parameters
     * @param maxZoomVectorTile - the original vector tile at the source's max available canonical zoom
     * @returns the overzoomed tile and its raw data
     */
    _getOverzoomTile(params, maxZoomVectorTile) {
        var _a;
        const { tileID, source, overzoomParameters } = params;
        const { maxZoomTileID } = overzoomParameters;
        const cacheKey = `${maxZoomTileID.key}_${tileID.key}_${(_a = params.request) === null || _a === void 0 ? void 0 : _a.url}`;
        const cachedOverzoomTile = this.overzoomedTileResultCache.get(cacheKey);
        if (cachedOverzoomTile) {
            return cachedOverzoomTile;
        }
        const overzoomedVectorTile = new VectorTileOverzoomed();
        const layerFamilies = this.layerIndex.familiesBySource[source];
        for (const sourceLayerId in layerFamilies) {
            const sourceLayer = maxZoomVectorTile.layers[sourceLayerId];
            if (!sourceLayer) {
                continue;
            }
            const slicedTileLayer = sliceVectorTileLayer(sourceLayer, maxZoomTileID, tileID.canonical);
            if (slicedTileLayer.length > 0) {
                overzoomedVectorTile.addLayer(slicedTileLayer);
            }
        }
        const overzoomedVectorTileResult = toVirtualVectorTile(overzoomedVectorTile);
        this.overzoomedTileResultCache.set(cacheKey, overzoomedVectorTileResult);
        return overzoomedVectorTileResult;
    }
    /**
     * Implements {@link WorkerSource.reloadTile}.
     */
    reloadTile(params) {
        return symbol_layout.__awaiter(this, void 0, void 0, function* () {
            const uid = params.uid;
            const workerTile = this.tileState.getLoaded(uid);
            if (!workerTile)
                throw new Error('Should not be trying to reload a tile that was never loaded or has been removed');
            workerTile.showCollisionBoxes = params.showCollisionBoxes;
            if (workerTile.status === 'parsing') {
                // if we are cancelling the original parse, make sure to pass the rawTileData from the original parse
                const parseState = this.tileState.consumeParsing(uid);
                return yield this._parseWorkerTile(workerTile, params, parseState);
            }
            // If there was no vector tile data on the initial load, don't try and reparse the tile.
            // this seems like a missing case where cache control is lost? see #3309
            if (workerTile.status === 'done' && workerTile.vectorTile) {
                return yield this._parseWorkerTile(workerTile, params);
            }
        });
    }
    /**
     * Implements {@link WorkerSource.abortTile}.
     */
    abortTile(params) {
        return symbol_layout.__awaiter(this, void 0, void 0, function* () {
            this.tileState.abort(params.uid);
        });
    }
    /**
     * Implements {@link WorkerSource.removeTile}.
     */
    removeTile(params) {
        return symbol_layout.__awaiter(this, void 0, void 0, function* () {
            this.tileState.removeLoaded(params.uid);
        });
    }
}

class RasterDEMTileWorkerSource {
    constructor() {
        this.loaded = {};
    }
    loadTile(params) {
        return symbol_layout.__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 = symbol_layout.isImageBitmap(rawImageData) ?
                new symbol_layout.RGBAImage({ width, height }, yield symbol_layout.getImageData(rawImageData, -1, -1, width, height)) :
                rawImageData;
            const dem = new symbol_layout.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 === null || loaded === void 0 ? void 0 : loaded[uid]) {
            delete loaded[uid];
        }
    }
}

/**
 * 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 {
    constructor(actor, layerIndex, availableImages, createGeoJSONIndexFunc = createGeoJSONIndex) {
        this.actor = actor;
        this.layerIndex = layerIndex;
        this.availableImages = availableImages;
        this.tileState = new WorkerTileState();
        this._createGeoJSONIndex = createGeoJSONIndexFunc;
    }
    /**
     * Retrieves and sends loaded vector tiles to the main thread.
     */
    loadVectorTile(params) {
        if (!this._geoJSONIndex)
            throw new Error('Unable to parse the data into a cluster or geojson');
        const { z, x, y } = params.tileID.canonical;
        const geoJSONTile = this._geoJSONIndex.getTile(z, x, y);
        if (!geoJSONTile)
            return null;
        const geojsonWrapper = new symbol_layout.GeoJSONWrapper(geoJSONTile.features, { version: 2, extent: symbol_layout.EXTENT });
        return toVirtualVectorTile(geojsonWrapper);
    }
    /**
     * Implements {@link WorkerSource.loadTile}.
     */
    loadTile(params) {
        return symbol_layout.__awaiter(this, void 0, void 0, function* () {
            const { uid } = params;
            const workerTile = new WorkerTile(params);
            workerTile.abort = new AbortController();
            try {
                const loadResult = this.loadVectorTile(params);
                if (!loadResult)
                    return null;
                const { vectorTile, rawData } = loadResult;
                workerTile.vectorTile = vectorTile;
                this.tileState.markLoaded(uid, workerTile);
                const parseState = { rawData };
                this.tileState.setParsing(uid, parseState); // Keep data so reloadTile can access if parse is canceled.
                try {
                    return yield this._parseWorkerTile(workerTile, params, parseState);
                }
                finally {
                    this.tileState.clearParsing(uid);
                }
            }
            catch (err) {
                workerTile.status = 'done';
                this.tileState.markLoaded(uid, workerTile);
                throw err;
            }
        });
    }
    _reloadLoadedTile(params) {
        return symbol_layout.__awaiter(this, void 0, void 0, function* () {
            const uid = params.uid;
            const workerTile = this.tileState.getLoaded(uid);
            if (!workerTile)
                throw new Error('Should not be trying to reload a tile that was never loaded or has been removed');
            workerTile.showCollisionBoxes = params.showCollisionBoxes;
            if (workerTile.status === 'parsing') {
                // If we are cancelling the original parse, make sure to pass the rawData from the original parse.
                const parseState = this.tileState.consumeParsing(uid);
                return yield this._parseWorkerTile(workerTile, params, parseState);
            }
            // If there was no vector tile data on the initial load, don't try and reparse the tile.
            if (workerTile.status === 'done' && workerTile.vectorTile) {
                return yield this._parseWorkerTile(workerTile, params);
            }
        });
    }
    _parseWorkerTile(workerTile, params, parseState) {
        return symbol_layout.__awaiter(this, void 0, void 0, function* () {
            let result = yield workerTile.parse(workerTile.vectorTile, this.layerIndex, this.availableImages, this.actor, params.subdivisionGranularity);
            if (parseState) {
                const { rawData } = parseState;
                // Transferring a copy of rawTileData because the worker needs to retain its copy.
                result = symbol_layout.extend({ rawTileData: rawData.slice(0), encoding: 'mvt' }, result);
            }
            return result;
        });
    }
    /**
     * Implements {@link WorkerSource.abortTile}.
     */
    abortTile(params) {
        return symbol_layout.__awaiter(this, void 0, void 0, function* () {
            this.tileState.abort(params.uid);
        });
    }
    /**
     * Implements {@link WorkerSource.removeTile}.
     */
    removeTile(params) {
        return symbol_layout.__awaiter(this, void 0, void 0, function* () {
            this.tileState.removeLoaded(params.uid);
        });
    }
    /**
     * Fetches (if appropriate), parses and indexes geojson data into tiles. This
     * preparatory method must be called before {@link GeoJSONWorkerSource.loadTile}
     * can correctly serve up tiles. The first call to this method must contain a valid
     * {@link params.data}, {@link params.request} or {@link params.dataDiff}. Subsequent
     * calls may omit these parameters to reprocess the existing data (such as to update
     * clustering options).
     *
     * 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 symbol_layout.__awaiter(this, void 0, void 0, function* () {
            var _a;
            (_a = this._pendingRequest) === null || _a === void 0 ? void 0 : _a.abort();
            const timing = this._startRequestTiming(params);
            this._pendingRequest = new AbortController();
            try {
                yield this.loadAndProcessGeoJSON(params, this._pendingRequest);
                delete this._pendingRequest;
                this.tileState.clearLoaded();
                // Sending a large GeoJSON payload from the worker to the main thread is slow so only do if necessary.
                // Send data only if it was loaded from a URL, otherwise the main thread already has a copy of this data.
                const result = {};
                if (params.request)
                    result.data = params.data;
                this._finishRequestTiming(timing, params, result);
                return result;
            }
            catch (err) {
                delete this._pendingRequest;
                if (!symbol_layout.isAbortError(err))
                    throw err;
                return { abandoned: true };
            }
        });
    }
    _startRequestTiming(params) {
        var _a;
        if (!((_a = params.request) === null || _a === void 0 ? void 0 : _a.collectResourceTiming))
            return;
        return new RequestPerformance(params.request.url);
    }
    _finishRequestTiming(timing, params, result) {
        const timingData = timing === null || timing === void 0 ? void 0 : timing.finish();
        if (!timingData)
            return;
        // it's necessary to eval the result of getEntriesByName() here via parse/stringify
        // late evaluation in the main thread causes TypeError: illegal invocation
        result.resourceTiming = { [params.source]: JSON.parse(JSON.stringify(timingData)) };
    }
    /**
     * Implements {@link WorkerSource.reloadTile}.
     *
     * If the tile is loaded, reload by re-parsing the already available tile data.
     * 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 tile = this.tileState.getLoaded(params.uid);
        if (tile) {
            return this._reloadLoadedTile(params);
        }
        return this.loadTile(params);
    }
    /**
     * Fetch, parse and process GeoJSON according to the given parameters.
     * Defers to {@link GeoJSONWorkerSource._loadGeoJSONFromString} 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 symbol_layout.__awaiter(this, void 0, void 0, function* () {
            var _a;
            if (params.request) {
                params.data = (yield symbol_layout.getJSON(params.request, abortController)).data;
            }
            if (params.data) {
                params.data = this._filterGeoJSON(params.data, params.filter);
                this._geoJSONIndex = this._createGeoJSONIndex(params.data, params);
                return;
            }
            if (params.dataDiff) {
                (_a = this._geoJSONIndex) !== null && _a !== void 0 ? _a : (this._geoJSONIndex = this._createGeoJSONIndex({ type: 'FeatureCollection', features: [] }, params));
                this._geoJSONIndex.updateData(params.dataDiff, this._getFilterPredicate(params.filter));
                return;
            }
            if (params.updateCluster) {
                this._geoJSONIndex.updateClusterOptions(params.geojsonVtOptions.cluster, getSuperclusterOptions(params));
            }
            if (this._geoJSONIndex == null) {
                throw new Error(`Input data given to '${params.source}' is not a valid GeoJSON object.`);
            }
        });
    }
    /**
     * Applies a filter to a GeoJSON object.
     */
    _filterGeoJSON(data, filter) {
        if (data.type !== 'FeatureCollection')
            return data;
        const predicate = this._getFilterPredicate(filter);
        if (!predicate)
            return data;
        return { type: 'FeatureCollection', features: data.features.filter(feature => predicate(feature)) };
    }
    /**
     * Gets a predicate function that can be used to filter GeoJSON features.
     */
    _getFilterPredicate(filter) {
        if (typeof filter !== 'boolean' && !(filter === null || filter === void 0 ? void 0 : filter.length))
            return undefined;
        const compiled = symbol_layout.createExpression(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(', '));
        }
        return (feature) => compiled.value.evaluate({ zoom: 0 }, feature);
    }
    removeSource(_params) {
        return symbol_layout.__awaiter(this, void 0, void 0, function* () {
            var _a;
            (_a = this._pendingRequest) === null || _a === void 0 ? void 0 : _a.abort();
        });
    }
    getClusterExpansionZoom(params) {
        return this._geoJSONIndex.getClusterExpansionZoom(params.clusterId);
    }
    getClusterChildren(params) {
        return this._geoJSONIndex.getClusterChildren(params.clusterId);
    }
    getClusterLeaves(params) {
        return this._geoJSONIndex.getClusterLeaves(params.clusterId, params.limit, params.offset);
    }
}
function createGeoJSONIndex(data, params) {
    const options = symbol_layout.extend(params.geojsonVtOptions || {}, {
        updateable: true,
        clusterOptions: getSuperclusterOptions(params),
    });
    return new symbol_layout.GeoJSONVT(data, options);
}
function getSuperclusterOptions({ geojsonVtOptions, clusterProperties }) {
    if (!clusterProperties || !geojsonVtOptions.clusterOptions)
        return geojsonVtOptions.clusterOptions;
    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 = symbol_layout.createExpression(mapExpression);
        const reduceExpressionParsed = symbol_layout.createExpression(typeof operator === 'string' ? [operator, ['accumulated'], ['get', key]] : operator);
        mapExpressions[key] = mapExpressionParsed.value;
        reduceExpressions[key] = reduceExpressionParsed.value;
    }
    geojsonVtOptions.clusterOptions.map = (pointProperties) => {
        feature.properties = pointProperties;
        const properties = {};
        for (const key of propertyNames) {
            properties[key] = mapExpressions[key].evaluate(globals, feature);
        }
        return properties;
    };
    geojsonVtOptions.clusterOptions.reduce = (accumulated, clusterProperties) => {
        feature.properties = clusterProperties;
        for (const key of propertyNames) {
            globals.accumulated = accumulated[key];
            accumulated[key] = reduceExpressions[key].evaluate(globals, feature);
        }
    };
    return geojsonVtOptions.clusterOptions;
}

/**
 * The Worker class responsible for background thread related execution
 */
class Worker {
    constructor(self) {
        this.self = self;
        this.actor = new symbol_layout.Actor(self);
        this.layerIndexes = {};
        this.availableImages = {};
        this.workerSources = {};
        this.demWorkerSources = {};
        this.externalWorkerSourceTypes = {};
        this.globalStates = new Map();
        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 = symbol_layout.addProtocol;
        this.self.removeProtocol = symbol_layout.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) => {
            symbol_layout.rtlWorkerPlugin.setMethods(rtlTextPlugin);
        };
        this.self.makeRequest = symbol_layout.makeRequest;
        this.actor.registerMessageHandler("LDT" /* MessageType.loadDEMTile */, (mapId, params) => {
            return this._getDEMWorkerSource(mapId, params.source).loadTile(params);
        });
        this.actor.registerMessageHandler("RDT" /* MessageType.removeDEMTile */, (mapId, params) => symbol_layout.__awaiter(this, void 0, void 0, function* () {
            this._getDEMWorkerSource(mapId, params.source).removeTile(params);
        }));
        this.actor.registerMessageHandler("GCEZ" /* MessageType.getClusterExpansionZoom */, (mapId, params) => symbol_layout.__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) => symbol_layout.__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) => symbol_layout.__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("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) => symbol_layout.__awaiter(this, void 0, void 0, function* () {
            var _a, _b;
            if (!((_b = (_a = this.workerSources[mapId]) === null || _a === void 0 ? void 0 : _a[params.type]) === null || _b === void 0 ? void 0 : _b[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) => symbol_layout.__awaiter(this, void 0, void 0, function* () {
            delete this.layerIndexes[mapId];
            delete this.availableImages[mapId];
            delete this.workerSources[mapId];
            delete this.demWorkerSources[mapId];
            this.globalStates.delete(mapId);
        }));
        this.actor.registerMessageHandler("SR" /* MessageType.setReferrer */, (_mapId, params) => symbol_layout.__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) => symbol_layout.__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) => symbol_layout.__awaiter(this, void 0, void 0, function* () {
            this._getLayerIndex(mapId).update(params.layers, params.removedIds, this._getGlobalState(mapId));
        }));
        this.actor.registerMessageHandler("UGS" /* MessageType.updateGlobalState */, (mapId, params) => symbol_layout.__awaiter(this, void 0, void 0, function* () {
            const globalState = this._getGlobalState(mapId);
            for (const key in params) {
                globalState[key] = params[key];
            }
        }));
        this.actor.registerMessageHandler("SL" /* MessageType.setLayers */, (mapId, params) => symbol_layout.__awaiter(this, void 0, void 0, function* () {
            this._getLayerIndex(mapId).replace(params, this._getGlobalState(mapId));
        }));
    }
    _getGlobalState(mapId) {
        let state = this.globalStates.get(mapId);
        if (!state) {
            state = {};
            this.globalStates.set(mapId, state);
        }
        return state;
    }
    _setImages(mapId, images) {
        return symbol_layout.__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 symbol_layout.__awaiter(this, void 0, void 0, function* () {
            return yield symbol_layout.rtlWorkerPlugin.syncState(incomingState, this.self.importScripts);
        });
    }
    _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 (symbol_layout.isWorker(self)) {
    self.worker = new Worker(self);
}

return Worker;

}));

define('index', ['exports', './shared'], (function (exports$1, symbol_layout) { 'use strict';

var name = "maplibre-gl";
var description = "BSD licensed community fork of mapbox-gl, a WebGL interactive maps library";
var version$2 = "5.23.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: "https://github.com/maplibre/maplibre-gl-js"
};
var types = "dist/maplibre-gl.d.ts";
var type = "module";
var dependencies = {
	"@mapbox/jsonlint-lines-primitives": "^2.0.2",
	"@mapbox/point-geometry": "^1.1.0",
	"@mapbox/tiny-sdf": "^2.0.7",
	"@mapbox/unitbezier": "^0.0.1",
	"@mapbox/vector-tile": "^2.0.4",
	"@mapbox/whoots-js": "^3.1.0",
	"@maplibre/geojson-vt": "^6.1.0",
	"@maplibre/maplibre-gl-style-spec": "^24.8.1",
	"@maplibre/mlt": "^1.1.8",
	"@maplibre/vt-pbf": "^4.3.0",
	"@types/geojson": "^7946.0.16",
	earcut: "^3.0.2",
	"gl-matrix": "^3.4.4",
	kdbush: "^4.0.2",
	"murmurhash-js": "^1.0.0",
	pbf: "^4.0.1",
	potpack: "^2.1.0",
	quickselect: "^3.0.0",
	tinyqueue: "^3.0.0"
};
var devDependencies = {
	"@mapbox/mapbox-gl-rtl-text": "^0.4.0",
	"@mapbox/mvt-fixtures": "^3.10.0",
	"@rollup/plugin-commonjs": "^29.0.2",
	"@rollup/plugin-json": "^6.1.0",
	"@rollup/plugin-node-resolve": "^16.0.3",
	"@rollup/plugin-replace": "^6.0.3",
	"@rollup/plugin-terser": "^1.0.0",
	"@rollup/plugin-typescript": "^12.1.4",
	"@stylistic/eslint-plugin": "^5.10.0",
	"@types/benchmark": "^2.1.5",
	"@types/d3": "^7.4.3",
	"@types/earcut": "^3.0.0",
	"@types/eslint": "^9.6.1",
	"@types/gl": "^6.0.5",
	"@types/jsdom": "^28.0.1",
	"@types/minimist": "^1.2.5",
	"@types/murmurhash-js": "^1.0.7",
	"@types/nise": "^1.4.5",
	"@types/node": "^25.5.2",
	"@types/offscreencanvas": "^2019.7.3",
	"@types/pixelmatch": "^5.2.6",
	"@types/pngjs": "^6.0.5",
	"@types/react": "^19.2.14",
	"@types/react-dom": "^19.2.3",
	"@types/request": "^2.48.13",
	"@types/shuffle-seed": "^1.1.3",
	"@types/window-or-global": "^1.0.6",
	"@typescript-eslint/eslint-plugin": "^8.58.0",
	"@typescript-eslint/parser": "^8.57.2",
	"@unicode/unicode-17.0.0": "^1.6.16",
	"@vitest/coverage-v8": "4.1.2",
	"@vitest/eslint-plugin": "^1.6.14",
	"@vitest/ui": "4.1.2",
	address: "^2.0.3",
	autoprefixer: "^10.4.27",
	benchmark: "^2.1.4",
	canvas: "^3.2.3",
	cspell: "^9.8.0",
	cssnano: "^7.1.4",
	d3: "^7.9.0",
	"d3-queue": "^3.0.7",
	"devtools-protocol": "^0.0.1608973",
	diff: "^8.0.4",
	"dts-bundle-generator": "^9.5.1",
	esbuild: "^0.28.0",
	eslint: "^9.39.2",
	"eslint-plugin-html": "^8.1.4",
	"eslint-plugin-import": "^2.32.0",
	"eslint-plugin-react": "^7.37.5",
	"eslint-plugin-tsdoc": "0.5.2",
	expect: "^30.3.0",
	glob: "^13.0.6",
	globals: "^17.4.0",
	"is-builtin-module": "^5.0.0",
	jsdom: "^29.0.2",
	"junit-report-builder": "^5.1.1",
	minimist: "^1.2.8",
	"mock-geolocation": "^1.0.11",
	"monocart-coverage-reports": "^2.12.9",
	nise: "^6.1.4",
	"npm-font-open-sans": "^1.1.0",
	"npm-run-all": "^4.1.5",
	"pdf-merger-js": "^5.1.2",
	pixelmatch: "^7.1.0",
	pngjs: "^7.0.0",
	postcss: "^8.5.8",
	"postcss-cli": "^11.0.1",
	"postcss-inline-svg": "^6.0.0",
	"pretty-bytes": "^7.1.0",
	puppeteer: "^24.40.0",
	react: "^19.2.4",
	"react-dom": "^19.2.4",
	regenerate: "^1.4.2",
	rollup: "^4.60.1",
	"rollup-plugin-sourcemaps2": "^0.5.6",
	"rollup-plugin-visualizer": "^7.0.1",
	rw: "^1.3.3",
	semver: "^7.7.4",
	sharp: "^0.34.5",
	"shuffle-seed": "^1.1.6",
	st: "^3.0.3",
	stylelint: "^17.6.0",
	"stylelint-config-standard": "^40.0.0",
	"ts-node": "^10.9.2",
	tslib: "^2.8.1",
	typedoc: "^0.28.18",
	"typedoc-plugin-markdown": "^4.11.0",
	typescript: "^6.0.2",
	vitest: "4.1.2",
	"vitest-webgl-canvas-mock": "^1.1.0"
};
var scripts = {
	"generate-dist-package": "node --no-warnings --loader ts-node/esm build/generate-dist-package.js",
	"generate-unicode-data": "node --no-warnings --loader ts-node/esm build/generate-unicode-data.ts",
	"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=false --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-unicode-data && npm run generate-typings && npm run generate-shaders && npm run build-dev && npm run build-csp-dev && npm run build-prod && 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",
	"build-csp": "rollup --configPlugin @rollup/plugin-typescript -c rollup.config.csp.ts --environment BUILD:production",
	"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",
	"bundle-stats": "rollup --configPlugin @rollup/plugin-typescript -c --environment BUILD:production,BUNDLE:stats",
	spellcheck: "cspell",
	docs: "npm run generate-docs && docker run --rm -v ${PWD}:/docs zensical/zensical build",
	"start-server": "st --no-cache -H localhost --port 9966 .",
	"start-docs": "docker run --rm -it -p 8000:8000 -v ${PWD}:/docs zensical/zensical serve --open --dev-addr=0.0.0.0:8000",
	start: "run-p watch-css watch-dev start-server",
	"start-bench": "run-p watch-css watch-benchmarks start-server",
	lint: "eslint",
	"lint-css": "stylelint **/*.css verbose",
	test: "run-p lint lint-css test-render test-unit test-integration test-build",
	"test-unit": "vitest run --config vitest.config.unit.ts",
	"test-unit-ci": "vitest run --config vitest.config.unit.ts --coverage",
	"test-integration": "vitest run --config vitest.config.integration.ts",
	"test-integration-ci": "vitest run --config vitest.config.integration.ts --coverage",
	"test-build": "vitest run --config vitest.config.build.ts",
	"test-build-ci": "vitest run --config vitest.config.build.ts --coverage",
	"test-watch-roots": "vitest --config vitest.config.unit.ts --watch",
	"test-render": "node --no-warnings --loader ts-node/esm test/integration/render/run_render_tests.ts",
	codegen: "run-p --print-label generate-dist-package generate-style-code generate-unicode-data 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
};

let linkEl;
let reducedMotionQuery;
let reducedMotionOverride;
/** */
const browser = {
    /**
     * Schedules a callback to be invoked on the next animation frame.
     * @param abortController - Controller to abort the scheduled frame.
     * @param fn - Callback to invoke with the paint start timestamp.
     * @param reject - Callback to invoke if the frame is aborted.
     * @param targetWindow - Optional window to use for requestAnimationFrame.
     *   When the map is rendered in a popup window or iframe, pass the owning
     *   window to ensure animation frames continue even when the main window
     *   is not focused.
     */
    frame(abortController, fn, reject, targetWindow) {
        const win = targetWindow || window;
        const frameId = win.requestAnimationFrame((paintStartTimestamp) => {
            unsubscribe();
            fn(paintStartTimestamp);
        });
        const { unsubscribe } = symbol_layout.subscribe(abortController.signal, 'abort', () => {
            unsubscribe();
            win.cancelAnimationFrame(frameId);
            reject(new symbol_layout.AbortError(abortController.signal.reason));
        }, false);
    },
    /**
     * Returns a promise that resolves on the next animation frame.
     * @param abortController - Controller to abort the scheduled frame.
     * @param targetWindow - Optional window to use for requestAnimationFrame.
     * @see {@link browser.frame}
     */
    frameAsync(abortController, targetWindow) {
        return new Promise((resolve, reject) => {
            this.frame(abortController, resolve, reject, targetWindow);
        });
    },
    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() {
        if (reducedMotionOverride !== undefined)
            return reducedMotionOverride;
        // 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;
    },
    set prefersReducedMotion(value) {
        reducedMotionOverride = value;
    }
};

/**
 * Manages time flow with optional freezing capability for deterministic rendering.
 */
class TimeManager {
    constructor() {
        this._frozenAt = null;
    }
    /**
     * Gets the current time, either real or frozen.
     * @returns Current time in milliseconds
     */
    getCurrentTime() {
        return this._frozenAt !== null ? this._frozenAt : performance.now();
    }
    /**
     * Sets time at a specific timestamp.
     * @param timestamp - Time in milliseconds to set
     */
    setNow(timestamp) {
        this._frozenAt = timestamp;
    }
    /**
     * Restores normal time flow.
     */
    restoreNow() {
        this._frozenAt = null;
    }
    /**
     * Returns whether time is currently frozen.
     * @returns True if time is frozen, false otherwise
     */
    isFrozen() {
        return this._frozenAt !== null;
    }
}
const timeManager = new TimeManager();
/**
 * Returns the current time in milliseconds.
 * When time is frozen via setNow(), returns the frozen timestamp.
 * Otherwise returns real browser time via performance.now().
 *
 * @returns Current time in milliseconds
 * @example
 * ```ts
 * // Measure elapsed time
 * const start = maplibregl.now();
 * // ... later ...
 * const elapsed = maplibregl.now() - start;
 *
 * // During frozen time
 * maplibregl.setNow(16.67);
 * console.log(maplibregl.now()); // 16.67
 * maplibregl.restoreNow();
 * console.log(maplibregl.now()); // real time
 * ```
 */
function now() {
    return timeManager.getCurrentTime();
}
/**
 * Freezes time at a specific timestamp for deterministic rendering.
 * Useful for frame-by-frame video capture where each frame needs
 * a consistent time value.
 *
 * @param timestamp - Time in milliseconds to freeze at
 * @example
 * ```ts
 * // Freeze time for video export at 60fps
 * setNow(0);           // First frame
 * // ... render frame ...
 * setNow(16.67);       // Second frame
 * // ... render frame ...
 * setNow(33.34);       // Third frame
 * // ... done ...
 * restoreNow();        // Resume normal time
 * ```
 */
function setNow(timestamp) {
    timeManager.setNow(timestamp);
}
/**
 * Restores normal time flow after freezing with setNow().
 * Call this after finishing deterministic rendering operations.
 *
 * @example
 * ```ts
 * // After video export, resume normal time
 * setNow(0);
 * // ... export frames ...
 * restoreNow(); // Map animations resume normally
 * ```
 */
function restoreNow() {
    timeManager.restoreNow();
}
/**
 * Returns whether time is currently frozen.
 * @returns True if time is frozen via setNow(), false otherwise
 * @example
 * ```ts
 * setNow(1000);
 * console.log(isTimeFrozen()); // true
 * restoreNow();
 * console.log(isTimeFrozen()); // false
 * ```
 */
function isTimeFrozen() {
    return timeManager.isFrozen();
}

var _a;
class DOM {
    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) {
        return window.document.createElementNS(namespaceURI, tagName);
    }
    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;
        }
    }
    // 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 symbol_layout.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 (const touch of touches) {
            points.push(DOM.getPoint(el, scale, touch));
        }
        return points;
    }
    /**
     * Sanitize an HTML string - this might not be enough to prevent all XSS attacks
     * Base on https://javascriptsource.com/sanitize-an-html-string-to-reduce-the-risk-of-xss-attacks/
     * (c) 2021 Chris Ferdinandi, MIT License, https://gomakethings.com
     */
    static sanitize(str) {
        const parser = new DOMParser();
        const doc = parser.parseFromString(str, 'text/html');
        const html = doc.body || document.createElement('body');
        const scripts = html.querySelectorAll('script');
        for (const script of scripts) {
            script.remove();
        }
        DOM.clean(html);
        return html.innerHTML;
    }
    /**
     * Check if the attribute is potentially dangerous
     */
    static isPossiblyDangerous(name, value) {
        const val = value.replace(/\s+/g, '').toLowerCase();
        if (['src', 'href', 'xlink:href'].includes(name)) {
            if (val.includes('javascript:') || val.includes('data:'))
                return true;
        }
        if (name.startsWith('on'))
            return true;
    }
    /**
     * Remove dangerous stuff from the HTML document's nodes
     * @param html - The HTML document
     */
    static clean(html) {
        const nodes = html.children;
        for (const node of nodes) {
            DOM.removeAttributes(node);
            DOM.clean(node);
        }
    }
    /**
     * Remove potentially dangerous attributes from an element
     * @param elem - The element
     */
    static removeAttributes(elem) {
        for (const { name, value } of elem.attributes) {
            if (!DOM.isPossiblyDangerous(name, value))
                continue;
            elem.removeAttribute(name);
        }
    }
}
DOM.docStyle = typeof window !== 'undefined' && ((_a = window.document) === null || _a === void 0 ? void 0 : _a.documentElement.style);
DOM.selectProp = !DOM.docStyle || 'userSelect' in DOM.docStyle ? 'userSelect' : 'webkitUserSelect';

/**
 * 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 (!requestParameters.headers) {
                requestParameters.headers = {};
            }
            requestParameters.headers.accept = 'image/webp,*/*';
            symbol_layout.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 symbol_layout.arrayBufferToImageBitmap(data);
        }
        else {
            return symbol_layout.arrayBufferToImage(data);
        }
    };
    const doImageRequest = (itemInQueue) => symbol_layout.__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 &&
            !symbol_layout.isWorker(self) &&
            !symbol_layout.getProtocol(requestParameters.url) &&
            (!requestParameters.headers ||
                Object.keys(requestParameters.headers).reduce((acc, item) => acc && item === 'accept', true));
        currentParallelImageRequests++;
        const getImagePromise = canUseHTMLImageElement ?
            getImageUsingHtmlImage(requestParameters, abortController) :
            symbol_layout.makeRequest(requestParameters, abortController);
        try {
            const response = yield getImagePromise;
            delete itemInQueue.abortController;
            itemInQueue.state = 'completed';
            if (response.data instanceof HTMLImageElement || symbol_layout.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(symbol_layout.ensureError(err));
        }
        finally {
            currentParallelImageRequests--;
            processQueue();
        }
    });
    /**
     * Process some number of items in the image request queue.
     */
    const processQueue = () => {
        const maxImageRequests = isThrottled() ?
            symbol_layout.config.MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME :
            symbol_layout.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') || !symbol_layout.sameOrigin(url)) {
                image.crossOrigin = 'anonymous';
            }
            abortController.signal.addEventListener('abort', () => {
                // Set src to '' to actually cancel the request
                image.src = '';
                reject(new symbol_layout.AbortError(abortController.signal.reason));
            });
            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 !== null && transformRequestFn !== void 0 ? transformRequestFn : null;
    }
    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.includes(key)) {
                dedupArray.push(key);
                resultArray.push({ id, url });
            }
        }
    }
    return resultArray;
}

function normalizeSpriteURL(url, format, extension) {
    try {
        const parsed = new URL(url);
        parsed.pathname += `${format}${extension}`;
        return parsed.toString();
    }
    catch (_a) {
        throw new Error(`Invalid sprite URL "${url}", must be absolute. Modify style specification directly or use TransformStyleFunction to correct the issue dynamically`);
    }
}
function loadSprite(originalSprite, requestManager, pixelRatio, abortController) {
    return symbol_layout.__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 = yield requestManager.transformRequest(normalizeSpriteURL(url, format, '.json'), "SpriteJSON" /* ResourceType.SpriteJSON */);
            jsonsMap[id] = symbol_layout.getJSON(jsonRequestParameters, abortController);
            const imageRequestParameters = yield 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 symbol_layout.__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;
    });
}

function renderStyleImage(image) {
    const { userImage } = image;
    if (userImage === null || userImage === void 0 ? void 0 : 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 symbol_layout.Evented {
    constructor() {
        super();
        this.images = {};
        this.updatedImages = {};
        this.callbackDispatchedThisFrame = {};
        this.loaded = false;
        this.requestors = [];
        this.patterns = {};
        this.atlasImage = new symbol_layout.RGBAImage({ width: 1, height: 1 });
        this.dirty = true;
    }
    destroy() {
        // Destroy atlas texture if it exists
        if (this.atlasTexture) {
            this.atlasTexture.destroy();
            this.atlasTexture = null;
        }
        // Remove all images and patterns
        for (const id of Object.keys(this.images)) {
            this.removeImage(id);
        }
        this.patterns = {};
        this.atlasImage = new symbol_layout.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 symbol_layout.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 === null || data === void 0 ? void 0 : data.width)) {
            this.fire(new symbol_layout.ErrorEvent(new Error(`Image "${id}" has invalid "stretchX" value`)));
            valid = false;
        }
        if (!this._validateStretch(image.stretchY, data === null || data === void 0 ? void 0 : data.height)) {
            this.fire(new symbol_layout.ErrorEvent(new Error(`Image "${id}" has invalid "stretchY" value`)));
            valid = false;
        }
        if (!this._validateContent(image.content, image)) {
            this.fire(new symbol_layout.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 === null || spriteData === void 0 ? void 0 : spriteData.width) || image.data.width;
        const height = (spriteData === null || spriteData === void 0 ? void 0 : 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;
        return content[3] >= content[1];
    }
    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) {
        var _a;
        const image = this.images[id];
        delete this.images[id];
        delete this.patterns[id];
        if ((_a = image.userImage) === null || _a === void 0 ? void 0 : _a.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) {
        var _a;
        const response = {};
        for (const id of ids) {
            let image = this.getImage(id);
            if (!image) {
                this.fire(new symbol_layout.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((_a = image.userImage) === null || _a === void 0 ? void 0 : _a.render)
                };
            }
            else {
                symbol_layout.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;
        }
        // eslint-disable-next-line @typescript-eslint/prefer-optional-chain -- pattern?.position.version would be undefined when pattern is nullish, making undefined === undefined true
        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 symbol_layout.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 symbol_layout.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 } = symbol_layout.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;
            symbol_layout.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.
            symbol_layout.RGBAImage.copy(src, dst, { x: 0, y: h - 1 }, { x, y: y - 1 }, { width: w, height: 1 }); // T
            symbol_layout.RGBAImage.copy(src, dst, { x: 0, y: 0 }, { x, y: y + h }, { width: w, height: 1 }); // B
            symbol_layout.RGBAImage.copy(src, dst, { x: w - 1, y: 0 }, { x: x - 1, y }, { width: 1, height: h }); // L
            symbol_layout.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)
                symbol_layout.warnOnce(`Image with ID: "${id}" was not found`);
            const updated = renderStyleImage(image);
            if (updated) {
                this.updateImage(id, image);
            }
        }
    }
    cloneImages() {
        const clonedImages = {};
        for (const id in this.images) {
            const image = this.images[id];
            clonedImages[id] = Object.assign(Object.assign({}, image), { data: image.data ? image.data.clone() : null });
        }
        return clonedImages;
    }
}

function loadGlyphRange(fontstack, range, urlTemplate, requestManager) {
    return symbol_layout.__awaiter(this, void 0, void 0, function* () {
        const begin = range * 256;
        const end = begin + 255;
        const request = yield requestManager.transformRequest(urlTemplate.replace('{fontstack}', fontstack).replace('{range}', `${begin}-${end}`), "Glyphs" /* ResourceType.Glyphs */);
        const response = yield symbol_layout.getArrayBuffer(request, new AbortController());
        if (!(response === null || response === void 0 ? void 0 : response.data)) {
            throw new Error(`Could not load glyph range. range: ${range}, ${begin}-${end}`);
        }
        const glyphs = {};
        for (const glyph of symbol_layout.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',
        lang = null
    } = {}) {
        this.buffer = buffer;
        this.cutoff = cutoff;
        this.radius = radius;
        this.lang = lang;

        // 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;
        if (this.lang) ctx.lang = this.lang;
        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;
    }
}

/**
 * The style specification hard-codes some last resort fonts as a default fontstack.
 */
const defaultStack = symbol_layout.v8.layout_symbol['text-font'].default.join(',');
/**
 * The CSS generic font family closest to `defaultStack`.
 */
const defaultGenericFontFamily = 'sans-serif';
/**
 * Scale factor for client-generated glyphs.
 *
 * Client-generated glyphs are rendered at 2× because CJK glyphs are more detailed than others.
 */
const textureScale = 2;
class GlyphManager {
    constructor(requestManager, localIdeographFontFamily, lang) {
        this.requestManager = requestManager;
        this.localIdeographFontFamily = localIdeographFontFamily;
        this.entries = {};
        this.lang = lang;
    }
    setURL(url) {
        this.url = url;
    }
    getGlyphs(glyphs) {
        return symbol_layout.__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 symbol_layout.__awaiter(this, void 0, void 0, function* () {
            // Create an entry for this fontstack if it doesn’t already exist.
            let entry = this.entries[stack];
            if (!entry) {
                entry = this.entries[stack] = {
                    glyphs: {},
                    requests: {},
                    ranges: {}
                };
            }
            // Try to get the glyph from the cache of client-side glyphs by codepoint.
            let glyph = entry.glyphs[id];
            if (glyph !== undefined) {
                return { stack, id, glyph };
            }
            // If the style hasn’t opted into server-side fonts or this codepoint is CJK, draw the glyph locally and cache it.
            if (!this.url || this._charUsesLocalIdeographFontFamily(id)) {
                glyph = entry.glyphs[id] = this._drawGlyph(entry, stack, id);
                return { stack, id, glyph };
            }
            return yield this._downloadAndCacheRangePromise(stack, id);
        });
    }
    _downloadAndCacheRangePromise(stack, id) {
        return symbol_layout.__awaiter(this, void 0, void 0, function* () {
            // Try to get the glyph from the cache of server-side glyphs by PBF range.
            const entry = this.entries[stack];
            const range = Math.floor(id / 256);
            if (entry.ranges[range]) {
                return { stack, id, glyph: null };
            }
            // Start downloading this range unless we’re currently downloading it.
            if (!entry.requests[range]) {
                entry.requests[range] = GlyphManager.loadGlyphRange(stack, range, this.url, this.requestManager);
            }
            try {
                // Get the response and cache the glyphs from it.
                const response = yield entry.requests[range];
                for (const id in response) {
                    entry.glyphs[+id] = response[+id];
                }
                entry.ranges[range] = true;
                return { stack, id, glyph: response[id] || null };
            }
            catch (e) {
                // Fall back to drawing the glyph locally and caching it.
                const glyph = entry.glyphs[id] = this._drawGlyph(entry, stack, id);
                this._warnOnMissingGlyphRange(glyph, range, id, symbol_layout.ensureError(e));
                return { stack, id, glyph };
            }
        });
    }
    _warnOnMissingGlyphRange(glyph, range, id, err) {
        const begin = range * 256;
        const end = begin + 255;
        const codePoint = id.toString(16).padStart(4, '0').toUpperCase();
        symbol_layout.warnOnce(`Unable to load glyph range ${range}, ${begin}-${end}. Rendering codepoint U+${codePoint} locally instead. ${err}`);
    }
    /**
     * Returns whether the given codepoint should be rendered locally.
     */
    _charUsesLocalIdeographFontFamily(id) {
        return !!this.localIdeographFontFamily && symbol_layout.codePointUsesLocalIdeographFontFamily(id);
    }
    /**
     * Draws a glyph offscreen using TinySDF, creating a TinySDF instance lazily.
     */
    _drawGlyph(entry, stack, id) {
        // The CJK fallback font specified by the developer takes precedence over the last resort fontstack in the style specification.
        const usesLocalIdeographFontFamily = stack === defaultStack && this.localIdeographFontFamily !== '' && this._charUsesLocalIdeographFontFamily(id);
        // Keep a separate TinySDF instance for when we need to apply the localIdeographFontFamily fallback to keep the font selection from bleeding into non-CJK text.
        const tinySDFKey = usesLocalIdeographFontFamily ? 'ideographTinySDF' : 'tinySDF';
        entry[tinySDFKey] || (entry[tinySDFKey] = this._createTinySDF(usesLocalIdeographFontFamily ? this.localIdeographFontFamily : stack));
        const char = entry[tinySDFKey].draw(String.fromCodePoint(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;
        // By definition, control characters are invisible and nonspacing.
        const isControl = /^\p{gc=Cf}+$/u.test(String.fromCodePoint(id));
        return {
            id,
            bitmap: new symbol_layout.AlphaImage({ width: char.width || 30 * textureScale, height: char.height || 30 * textureScale }, char.data),
            metrics: {
                width: isControl ? 0 : (char.glyphWidth / textureScale || 24),
                height: char.glyphHeight / textureScale || 24,
                left: (char.glyphLeft / textureScale + leftAdjustment) || 0,
                top: char.glyphTop / textureScale - topAdjustment || -8,
                advance: isControl ? 0 : (char.glyphAdvance / textureScale || 24),
                isDoubleResolution: true
            }
        };
    }
    _createTinySDF(stack) {
        // Escape and quote the font family list for use in CSS.
        const fontFamilies = stack ? stack.split(',') : [];
        fontFamilies.push(defaultGenericFontFamily);
        const fontFamily = fontFamilies.map(fontName => /[-\w]+/.test(fontName) ? fontName : `'${CSS.escape(fontName)}'`).join(',');
        return new GlyphManager.TinySDF({
            fontSize: 24 * textureScale,
            buffer: 3 * textureScale,
            radius: 8 * textureScale,
            cutoff: 0.25,
            fontFamily,
            fontWeight: this._fontWeight(fontFamilies[0]),
            fontStyle: this._fontStyle(fontFamilies[0]),
            lang: this.lang
        });
    }
    /**
     * Sniffs the font style out of a font family name.
     */
    _fontStyle(fontFamily) {
        if (/italic/i.test(fontFamily)) {
            return 'italic';
        }
        else if (/oblique/i.test(fontFamily)) {
            return 'oblique';
        }
        return 'normal';
    }
    /**
     * Sniffs the font weight out of a font family name.
     */
    _fontWeight(fontFamily) {
        // Based on the OpenType specification
        // https://learn.microsoft.com/en-us/typography/opentype/spec/os2#usweightclass
        const weightsByName = {
            thin: 100, hairline: 100,
            'extra light': 200, 'ultra light': 200,
            light: 300,
            normal: 400, regular: 400,
            medium: 500,
            semibold: 600, demibold: 600,
            bold: 700,
            'extra bold': 800, 'ultra bold': 800,
            black: 900, heavy: 900,
            'extra black': 950, 'ultra black': 950
        };
        let match;
        for (const [name, weight] of Object.entries(weightsByName)) {
            if (new RegExp(`\\b${name}\\b`, 'i').test(fontFamily)) {
                match = `${weight}`;
            }
        }
        return match;
    }
    destroy() {
        for (const stack in this.entries) {
            const entry = this.entries[stack];
            if (entry.tinySDF) {
                entry.tinySDF = null;
            }
            if (entry.ideographTinySDF) {
                entry.ideographTinySDF = null;
            }
            entry.glyphs = {};
            entry.requests = {};
            entry.ranges = {};
        }
        this.entries = {};
    }
}
// exposed as statistics to enable stubbing in unit tests
GlyphManager.loadGlyphRange = loadGlyphRange;
GlyphManager.TinySDF = TinySDF;

class LightPositionProperty {
    constructor() {
        this.specification = symbol_layout.v8Spec.light.position;
    }
    possiblyEvaluate(value, parameters) {
        return symbol_layout.sphericalToCartesian(value.expression.evaluate(parameters));
    }
    interpolate(a, b, t) {
        return {
            x: symbol_layout.interpolateFactory.number(a.x, b.x, t),
            y: symbol_layout.interpolateFactory.number(a.y, b.y, t),
            z: symbol_layout.interpolateFactory.number(a.z, b.z, t),
        };
    }
}
let lightProperties;
/*
 * Represents the light used to light extruded features.
 */
class Light extends symbol_layout.Evented {
    constructor(lightOptions) {
        super();
        lightProperties = lightProperties || new symbol_layout.Properties({
            'anchor': new symbol_layout.DataConstantProperty(symbol_layout.v8Spec.light.anchor),
            'position': new LightPositionProperty(),
            'color': new symbol_layout.DataConstantProperty(symbol_layout.v8Spec.light.color),
            'intensity': new symbol_layout.DataConstantProperty(symbol_layout.v8Spec.light.intensity),
        });
        this._transitionable = new symbol_layout.Transitionable(lightProperties, undefined);
        this.setLight(lightOptions);
        this._transitioning = this._transitionable.untransitioned();
    }
    getLight() {
        return this._transitionable.serialize();
    }
    setLight(light, options = {}) {
        if (this._validate(symbol_layout.validateLight, light, options)) {
            return;
        }
        for (const name in light) {
            const value = light[name];
            if (name.endsWith(symbol_layout.TRANSITION_SUFFIX)) {
                this._transitionable.setTransition(name.slice(0, -symbol_layout.TRANSITION_SUFFIX.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 === null || options === void 0 ? void 0 : options.validate) === false) {
            return false;
        }
        return symbol_layout.emitValidationErrors(this, validate.call(symbol_layout.validateStyle, {
            value,
            // Workaround for https://github.com/mapbox/mapbox-gl-js/issues/2407
            style: { glyphs: true, sprite: true },
            styleSpec: symbol_layout.v8Spec
        }));
    }
}

const properties$1 = new symbol_layout.Properties({
    'sky-color': new symbol_layout.DataConstantProperty(symbol_layout.v8Spec.sky['sky-color']),
    'horizon-color': new symbol_layout.DataConstantProperty(symbol_layout.v8Spec.sky['horizon-color']),
    'fog-color': new symbol_layout.DataConstantProperty(symbol_layout.v8Spec.sky['fog-color']),
    'fog-ground-blend': new symbol_layout.DataConstantProperty(symbol_layout.v8Spec.sky['fog-ground-blend']),
    'horizon-fog-blend': new symbol_layout.DataConstantProperty(symbol_layout.v8Spec.sky['horizon-fog-blend']),
    'sky-horizon-blend': new symbol_layout.DataConstantProperty(symbol_layout.v8Spec.sky['sky-horizon-blend']),
    'atmosphere-blend': new symbol_layout.DataConstantProperty(symbol_layout.v8Spec.sky['atmosphere-blend'])
});
class Sky extends symbol_layout.Evented {
    constructor(sky) {
        super();
        this._transitionable = new symbol_layout.Transitionable(properties$1, undefined);
        this.setSky(sky);
        this._transitioning = this._transitionable.untransitioned();
        this.recalculate(new symbol_layout.EvaluationParameters(0));
    }
    setSky(sky, options = {}) {
        if (this._validate(symbol_layout.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(symbol_layout.TRANSITION_SUFFIX)) {
                this._transitionable.setTransition(name.slice(0, -symbol_layout.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 symbol_layout.emitValidationErrors(this, validate.call(symbol_layout.validateStyle, symbol_layout.extend({
            value,
            // Workaround for https://github.com/mapbox/mapbox-gl-js/issues/2407
            style: { glyphs: true, sprite: true },
            styleSpec: symbol_layout.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) {
            symbol_layout.warnOnce('LineAtlas out of space');
            return null;
        }
        let length = 0;
        for (const dash of dasharray) {
            length += dash;
        }
        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,
            height: 2 * n,
            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(symbol_layout.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) {
            for (const w of this.workers) {
                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 = symbol_layout.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 worker source (usually with the same name).
 */
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 symbol_layout.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) {
        for (const actor of this.actors) {
            actor.remove();
        }
        this.actors = [];
        if (mapRemoved)
            this.workerPool.release(this.id);
    }
    registerMessageHandler(type, handler) {
        for (const actor of this.actors) {
            actor.registerMessageHandler(type, handler);
        }
    }
    unregisterMessageHandler(type) {
        for (const actor of this.actors) {
            actor.unregisterMessageHandler(type);
        }
    }
}
let globalDispatcher;
/**
 * This function is used to get the global dispatcher that is shared across all maps instances.
 * It is used by the main thread to send messages to the workers, and by the workers to send messages back to the main thread.
 * If you import a script into the worker and need to send a message to the workers to pass some parameters for example,
 * you can use this function to get the global dispatcher and send a message to the workers.
 * @returns The global dispatcher instance.
 */
function getGlobalDispatcher() {
    if (!globalDispatcher) {
        globalDispatcher = new Dispatcher(getGlobalWorkerPool(), symbol_layout.GLOBAL_DISPATCHER_ID);
        globalDispatcher.registerMessageHandler("GR" /* MessageType.getResource */, (_mapId, params, abortController) => {
            return symbol_layout.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 = symbol_layout.create();
    symbol_layout.translate(t, t, [1, 1, 0]);
    symbol_layout.scale(t, t, [transform.width * 0.5, transform.height * 0.5, 1]);
    if (transform.calculatePosMatrix) { // Globe: TODO: remove this hack once queryRendererFeatures supports globe properly
        return symbol_layout.multiply(t, t, transform.calculatePosMatrix(tileID.toUnwrapped()));
    }
    else {
        return t;
    }
}
function queryIncludes3DLayer(layers, styleLayers, sourceID) {
    if (layers) {
        for (const layerID of layers) {
            const layer = styleLayers[layerID];
            if ((layer === null || layer === void 0 ? void 0 : 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(tileManager, styleLayers, serializedLayers, queryGeometry, params, transform, getElevation) {
    var _a;
    const has3DLayer = queryIncludes3DLayer((_a = params === null || params === void 0 ? void 0 : params.layers) !== null && _a !== void 0 ? _a : null, styleLayers, tileManager.id);
    const maxPitchScaleFactor = transform.maxPitchScaleFactor();
    const tilesIn = tileManager.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, tileManager.getState(), tileIn.queryGeometry, tileIn.cameraQueryGeometry, tileIn.scale, params, transform, maxPitchScaleFactor, getPixelPosMatrix(transform, tileIn.tileID), getElevation ? (x, y) => getElevation(tileIn.tileID, x, y) : undefined)
        });
    }
    const result = mergeRenderedFeatureLayers(renderedFeatureLayers);
    return convertFeaturesToMapFeatures(result, tileManager);
}
function queryRenderedSymbols(styleLayers, serializedLayers, tileManagers, 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, {
            filterSpec: params.filter,
            globalState: params.globalState
        }, 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);
            }
        }
    }
    return convertFeaturesToMapFeaturesMultiple(result, styleLayers, tileManagers);
}
function querySourceFeatures(tileManager, params) {
    const tiles = tileManager.getRenderableIds().map((id) => {
        return tileManager.getTileByID(id);
    });
    const result = [];
    const dataTiles = {};
    for (const tile of tiles) {
        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 convertFeaturesToMapFeatures(result, tileManager) {
    // Merge state from TileManager into the results
    for (const layerID in result) {
        for (const featureWrapper of result[layerID]) {
            convertFeatureToMapFeature(featureWrapper, tileManager);
        }
        ;
    }
    return result;
}
function convertFeaturesToMapFeaturesMultiple(result, styleLayers, tileManagers) {
    // Merge state from TileManager into the results
    for (const layerName in result) {
        for (const featureWrapper of result[layerName]) {
            const layer = styleLayers[layerName];
            const tileManager = tileManagers[layer.source];
            convertFeatureToMapFeature(featureWrapper, tileManager);
        }
        ;
    }
    return result;
}
function convertFeatureToMapFeature(featureWrapper, tileManager) {
    const feature = featureWrapper.feature;
    const state = tileManager.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;
}

function loadTileJson(options, requestManager, abortController, targetWindow) {
    return symbol_layout.__awaiter(this, void 0, void 0, function* () {
        let tileJSON = options;
        if (options.url) {
            const response = yield symbol_layout.getJSON(yield requestManager.transformRequest(options.url, "Source" /* ResourceType.Source */), abortController);
            tileJSON = response.data;
        }
        else {
            yield browser.frameAsync(abortController, targetWindow);
        }
        if (!tileJSON) {
            return null;
        }
        const result = symbol_layout.pick(
        // explicit source options take precedence over TileJSON
        symbol_layout.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) => 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 MapLibre 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);
 * ```
 * @see [Fit to the bounds of a LineString](https://maplibre.org/maplibre-gl-js/docs/examples/fit-to-the-bounds-of-a-linestring/)
 */
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 symbol_layout.LngLat ? new symbol_layout.LngLat(ne.lng, ne.lat) : symbol_layout.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 symbol_layout.LngLat ? new symbol_layout.LngLat(sw.lng, sw.lat) : symbol_layout.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 symbol_layout.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(symbol_layout.LngLat.convert(lngLatObj));
                }
            }
            else if (obj && ('lng' in obj || 'lon' in obj) && 'lat' in obj) {
                return this.extend(symbol_layout.LngLat.convert(obj));
            }
            return this;
        }
        if (!sw && !ne) {
            this._sw = new symbol_layout.LngLat(sw2.lng, sw2.lat);
            this._ne = new symbol_layout.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 symbol_layout.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 symbol_layout.LngLat(this.getWest(), this.getNorth()); }
    /**
     * Returns the southeast corner of the bounding box.
     *
     * @returns The southeast corner of the bounding box.
     */
    getSouthEast() { return new symbol_layout.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 } = symbol_layout.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;
    }
    /**
     * Checks if this bounding box intersects with another bounding box.
     *
     * Returns true if the bounding boxes share any area, including cases where
     * they only touch along an edge or at a corner.
     *
     * This method properly handles cases where either or both bounding boxes cross
     * the antimeridian (date line).
     */
    intersects(other) {
        other = LngLatBounds.convert(other);
        const latIntersects = other.getNorth() >= this.getSouth() &&
            other.getSouth() <= this.getNorth();
        if (!latIntersects)
            return false;
        // Check if either bound covers the full world (|span| >= 360°)
        // This must be done before wrapping to preserve the span information
        const thisSpan = Math.abs(this.getEast() - this.getWest());
        const otherSpan = Math.abs(other.getEast() - other.getWest());
        if (thisSpan >= 360 || otherSpan >= 360) {
            return true;
        }
        // Normalize longitudes to [-180, 180] range
        const thisWest = symbol_layout.wrap(this.getWest(), -180, 180);
        const thisEast = symbol_layout.wrap(this.getEast(), -180, 180);
        const otherWest = symbol_layout.wrap(other.getWest(), -180, 180);
        const otherEast = symbol_layout.wrap(other.getEast(), -180, 180);
        // Check if either bounds wraps around the antimeridian
        // Use strict inequality: equal values indicate zero-width bounds (e.g., a point), not wrapping
        const thisWraps = thisWest > thisEast;
        const otherWraps = otherWest > otherEast;
        // Both wrap: they always intersect
        if (thisWraps && otherWraps) {
            return true;
        }
        // Only this wraps: intersects if other is outside the gap
        if (thisWraps) {
            return otherEast >= thisWest || otherWest <= thisEast;
        }
        if (otherWraps) {
            // Only other wraps: intersects if this is outside the gap
            return thisEast >= otherWest || thisWest <= otherEast;
        }
        // Neither wraps: standard intersection check
        return otherWest <= thisEast && otherEast >= thisWest;
    }
    /**
     * Converts an array to a `LngLatBounds` object.
     *
     * If a `LngLatBounds` object is passed in, the function returns it unchanged.
     *
     * Internally, the function calls {@link 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 symbol_layout.LngLat(center.lng - lngAccuracy, center.lat - latAccuracy), new symbol_layout.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 symbol_layout.LngLat(this._sw.lng, this._sw.lat);
        const ne = new symbol_layout.LngLat(this._ne.lng, this._ne.lat);
        if (sw.lng > ne.lng) {
            return new LngLatBounds(sw, new symbol_layout.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(symbol_layout.mercatorXfromLng(this.bounds.getWest()) * worldSize),
            minY: Math.floor(symbol_layout.mercatorYfromLat(this.bounds.getNorth()) * worldSize),
            maxX: Math.ceil(symbol_layout.mercatorXfromLng(this.bounds.getEast()) * worldSize),
            maxY: Math.ceil(symbol_layout.mercatorYfromLat(this.bounds.getSouth()) * worldSize)
        };
        return tileID.x >= level.minX && tileID.x < level.maxX && tileID.y >= level.minY && tileID.y < level.maxY;
    }
}

/**
 * A source containing vector tiles in [Maplibre Vector Tile format](https://maplibre.org/maplibre-tile-spec/) or [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/add-a-vector-tile-source/)
 */
class VectorTileSource extends symbol_layout.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;
        symbol_layout.extend(this, symbol_layout.pick(options, ['url', 'scheme', 'tileSize', 'promoteId', 'encoding']));
        this._options = symbol_layout.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 symbol_layout.__awaiter(this, arguments, void 0, function* (sourceDataChanged = false) {
            this._loaded = false;
            this.fire(new symbol_layout.Event('dataloading', { dataType: 'source' }));
            this._tileJSONRequest = new AbortController();
            try {
                const tileJSON = yield loadTileJson(this._options, this.map._requestManager, this._tileJSONRequest, this.map._ownerWindow);
                this._tileJSONRequest = null;
                this._loaded = true;
                if (tileJSON) {
                    symbol_layout.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 symbol_layout.Event('data', { dataType: 'source', sourceDataType: 'metadata' }));
                    this.fire(new symbol_layout.Event('data', { dataType: 'source', sourceDataType: 'content', sourceDataChanged }));
                }
            }
            catch (err) {
                this._tileJSONRequest = null;
                this._loaded = true; // let's pretend it's loaded so the source will be ignored
                // only fire error event if it is not due to aborting the request
                if (!symbol_layout.isAbortError(err)) {
                    this.fire(new symbol_layout.ErrorEvent(symbol_layout.ensureError(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(true);
    }
    /**
     * 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 symbol_layout.extend({}, this._options);
    }
    loadTile(tile) {
        return symbol_layout.__awaiter(this, void 0, void 0, function* () {
            const url = tile.tileID.canonical.url(this.tiles, this.map.getPixelRatio(), this.scheme);
            const params = {
                request: yield 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,
                subdivisionGranularity: this.map.style.projection.subdivisionGranularity,
                encoding: this.encoding,
                overzoomParameters: yield this._getOverzoomParameters(tile),
                etag: tile.etag
            };
            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);
                const result = {};
                if (data === null || data === void 0 ? void 0 : data.etagUnmodified)
                    result.unmodified = true;
                return result;
            }
            catch (err) {
                delete tile.abortController;
                if (tile.aborted) {
                    return;
                }
                if (err && err.status !== 404) {
                    throw err;
                }
                this._afterTileLoadWorkerResponse(tile, null);
            }
        });
    }
    /**
     * When the requested tile has a higher canonical Z than source maxzoom, pass overzoom parameters so worker can load the
     * deepest tile at source max zoom to generate sub tiles using geojsonvt for highest performance on vector overscaling
     */
    _getOverzoomParameters(tile) {
        return symbol_layout.__awaiter(this, void 0, void 0, function* () {
            if (tile.tileID.canonical.z <= this.maxzoom) {
                return undefined;
            }
            if (this.map._zoomLevelsToOverscale === undefined) {
                return undefined;
            }
            const maxZoomTileID = tile.tileID.scaledTo(this.maxzoom).canonical;
            const maxZoomTileUrl = maxZoomTileID.url(this.tiles, this.map.getPixelRatio(), this.scheme);
            return {
                maxZoomTileID,
                overzoomRequest: yield this.map._requestManager.transformRequest(maxZoomTileUrl, "Tile" /* ResourceType.Tile */)
            };
        });
    }
    _afterTileLoadWorkerResponse(tile, data) {
        if (data === null || data === void 0 ? void 0 : data.resourceTiming) {
            tile.resourceTiming = data.resourceTiming;
        }
        if (data && this.map._refreshExpiredTiles) {
            tile.setExpiryData(data);
        }
        tile.etag = data === null || data === void 0 ? void 0 : data.etag;
        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 symbol_layout.__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 symbol_layout.__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 [raster source documentation](https://maplibre.org/maplibre-style-spec/sources/#raster) for detailed documentation of options.)
 *
 * @group Sources
 *
 * \> ℹ️ **Note:** The default `tileSize` is `512`. If your tile provider (such as OpenStreetMap or Stadia Maps) serves 256px tiles, set `tileSize: 256` manually to avoid blurry rendering due to upscaling.
 *
 * @example
 * ```ts
 * map.addSource('raster-source', {
 *     'type': 'raster',
 *     'tiles': ['https://tiles.stadiamaps.com/tiles/stamen_watercolor/{z}/{x}/{y}.jpg'],
 *     'tileSize': 256, // Set this to match tile server output to avoid blurry rendering
 * });
 * ```
 *
 * @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 // Important for WMS if tiles are 256px
 * });
 * ```
 * @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/add-a-wms-source/)
 * @see [Display a satellite map](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-satellite-map/)
 */
class RasterTileSource extends symbol_layout.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 = symbol_layout.extend({ type: 'raster' }, options);
        symbol_layout.extend(this, symbol_layout.pick(options, ['url', 'scheme', 'tileSize']));
    }
    load() {
        return symbol_layout.__awaiter(this, arguments, void 0, function* (sourceDataChanged = false) {
            this._loaded = false;
            this.fire(new symbol_layout.Event('dataloading', { dataType: 'source' }));
            this._tileJSONRequest = new AbortController();
            try {
                const tileJSON = yield loadTileJson(this._options, this.map._requestManager, this._tileJSONRequest, this.map._ownerWindow);
                this._tileJSONRequest = null;
                this._loaded = true;
                if (tileJSON) {
                    symbol_layout.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 symbol_layout.Event('data', { dataType: 'source', sourceDataType: 'metadata' }));
                    this.fire(new symbol_layout.Event('data', { dataType: 'source', sourceDataType: 'content', sourceDataChanged }));
                }
            }
            catch (err) {
                this._tileJSONRequest = null;
                this._loaded = true; // let's pretend it's loaded so the source will be ignored
                // only fire error event if it is not due to aborting the request
                if (!symbol_layout.isAbortError(err)) {
                    this.fire(new symbol_layout.ErrorEvent(symbol_layout.ensureError(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(true);
    }
    /**
     * 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 symbol_layout.extend({}, this._options);
    }
    hasTile(tileID) {
        return !this.tileBounds || this.tileBounds.contains(tileID.canonical);
    }
    loadTile(tile) {
        return symbol_layout.__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(yield 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 === null || response === void 0 ? void 0 : 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 symbol_layout.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 symbol_layout.__awaiter(this, void 0, void 0, function* () {
            if (tile.abortController) {
                tile.abortController.abort();
                delete tile.abortController;
            }
        });
    }
    unloadTile(tile) {
        return symbol_layout.__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 = symbol_layout.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 symbol_layout.__awaiter(this, void 0, void 0, function* () {
            const url = tile.tileID.canonical.url(this.tiles, this.map.getPixelRatio(), this.scheme);
            const request = yield 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 === null || response === void 0 ? void 0 : response.data) {
                    const img = response.data;
                    if (this.map._refreshExpiredTiles && (response.cacheControl || response.expires)) {
                        tile.setExpiryData({ cacheControl: response.cacheControl, expires: response.expires });
                    }
                    const transfer = symbol_layout.isImageBitmap(img) && symbol_layout.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.state !== 'reloading') {
                        return;
                    }
                    if (!tile.actor || tile.state === 'expired') {
                        tile.actor = this.dispatcher.getActor();
                    }
                    tile.dem = yield tile.actor.sendAsync({ type: "LDT" /* MessageType.loadDEMTile */, data: params });
                    tile.needsHillshadePrepare = true;
                    tile.needsTerrainPrepare = true;
                    tile.state = 'loaded';
                }
            }
            catch (err) {
                delete tile.abortController;
                if (tile.aborted) {
                    tile.state = 'unloaded';
                }
                else if (err) {
                    tile.state = 'errored';
                    throw err;
                }
            }
        });
    }
    readImageNow(img) {
        return symbol_layout.__awaiter(this, void 0, void 0, function* () {
            if (typeof VideoFrame !== 'undefined' && symbol_layout.isOffscreenCanvasDistorted()) {
                const width = img.width + 2;
                const height = img.height + 2;
                try {
                    return new symbol_layout.RGBAImage({ width, height }, yield symbol_layout.readImageUsingVideoFrame(img, -1, -1, width, height));
                }
                catch (_a) {
                    // 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 symbol_layout.OverscaledTileID(tileID.overscaledZ, pxw, canonical.z, px, canonical.y).key] = { backfilled: false };
        neighboringTiles[new symbol_layout.OverscaledTileID(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y).key] = { backfilled: false };
        // Add upper neighboringTiles
        if (canonical.y > 0) {
            neighboringTiles[new symbol_layout.OverscaledTileID(tileID.overscaledZ, pxw, canonical.z, px, canonical.y - 1).key] = { backfilled: false };
            neighboringTiles[new symbol_layout.OverscaledTileID(tileID.overscaledZ, tileID.wrap, canonical.z, canonical.x, canonical.y - 1).key] = { backfilled: false };
            neighboringTiles[new symbol_layout.OverscaledTileID(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y - 1).key] = { backfilled: false };
        }
        // Add lower neighboringTiles
        if (canonical.y + 1 < dim) {
            neighboringTiles[new symbol_layout.OverscaledTileID(tileID.overscaledZ, pxw, canonical.z, px, canonical.y + 1).key] = { backfilled: false };
            neighboringTiles[new symbol_layout.OverscaledTileID(tileID.overscaledZ, tileID.wrap, canonical.z, canonical.x, canonical.y + 1).key] = { backfilled: false };
            neighboringTiles[new symbol_layout.OverscaledTileID(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y + 1).key] = { backfilled: false };
        }
        return neighboringTiles;
    }
    unloadTile(tile) {
        return symbol_layout.__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 } });
            }
        });
    }
}

function getFeatureId(feature, promoteId) {
    return promoteId ? feature.properties[promoteId] : feature.id;
}
/**
 * Converts a GeoJSON object into a map of feature IDs to GeoJSON features.
 * @param data - The GeoJSON object to convert.
 * @param promoteId - If set, the feature id will be set to the promoteId property value.
 * @returns A map of feature IDs to GeoJSON features, or `undefined` if the GeoJSON object is not a valid updateable object.
 *
 * Features must have unique identifiers to be updateable. IDs can come from:
 * - The feature's `id` property (standard GeoJSON)
 * - A promoted property specified by `promoteId` (e.g., a "name" property)
 */
function toUpdateable(data, promoteId) {
    const updateable = new Map();
    // null can be updated - empty updateable
    if (data == null) {
        return updateable;
    }
    // {} can be updated - empty updateable
    if (data.type == null) {
        return updateable;
    }
    // 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') {
        const id = getFeatureId(data, promoteId);
        if (id == null)
            return undefined;
        updateable.set(id, data);
        return updateable;
    }
    // a feature collection can be updated if every feature has a unique id, which prevents the silent dropping of features
    if (data.type === 'FeatureCollection') {
        const seenIds = new Set();
        for (const feature of data.features) {
            const id = getFeatureId(feature, promoteId);
            if (id == null)
                return undefined;
            if (seenIds.has(id))
                return undefined;
            seenIds.add(id);
            updateable.set(id, feature);
        }
        return updateable;
    }
    return undefined;
}
/**
 * Mutates updateable and applies a {@link GeoJSONSourceDiff}. Operations are processed in a specific order to ensure predictable behavior:
 * 1. Remove operations (removeAll, remove)
 * 2. Add operations (add)
 * 3. Update operations (update)
 * @returns an array of geometries that were affected by the diff - with the exception of removeAll which does not track any affected geometries.
 */
function applySourceDiff(updateable, diff, promoteId) {
    var _a, _b;
    const affectedGeometries = [];
    if (diff.removeAll) {
        updateable.clear();
    }
    else if (diff.remove) {
        for (const id of diff.remove) {
            const existing = updateable.get(id);
            if (!existing)
                continue;
            affectedGeometries.push(existing.geometry);
            updateable.delete(id);
        }
    }
    if (diff.add) {
        for (const feature of diff.add) {
            const id = getFeatureId(feature, promoteId);
            if (id == null)
                continue;
            const existing = updateable.get(id);
            if (existing)
                affectedGeometries.push(existing.geometry);
            affectedGeometries.push(feature.geometry);
            updateable.set(id, feature);
        }
    }
    if (diff.update) {
        for (const update of diff.update) {
            const existing = updateable.get(update.id);
            if (!existing)
                continue;
            const changeGeometry = !!update.newGeometry;
            const changeProps = 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;
            // nothing to do
            if (!changeGeometry && !changeProps)
                continue;
            // clone once since we'll mutate
            affectedGeometries.push(existing.geometry);
            const feature = Object.assign({}, existing);
            updateable.set(update.id, feature);
            if (changeGeometry) {
                affectedGeometries.push(update.newGeometry);
                feature.geometry = update.newGeometry;
            }
            if (changeProps) {
                if (update.removeAllProperties) {
                    feature.properties = {};
                }
                else {
                    feature.properties = Object.assign({}, feature.properties || {});
                }
                if (update.removeProperties) {
                    for (const key of update.removeProperties) {
                        delete feature.properties[key];
                    }
                }
                if (update.addOrUpdateProperties) {
                    for (const { key, value } of update.addOrUpdateProperties) {
                        feature.properties[key] = value;
                    }
                }
            }
        }
    }
    return affectedGeometries;
}
/**
 * Merge two GeoJSONSourceDiffs, considering the order of operations as specified above (remove, add, update).
 *
 * For `add` features that use promoteId, the feature id will be set to the promoteId value temporarily so that
 * the merge can be completed, then reverted to the original promoteId state after the merge.
 */
function mergeSourceDiffs(prevDiff, nextDiff, promoteId) {
    if (!prevDiff)
        return nextDiff || {};
    if (!nextDiff)
        return prevDiff || {};
    if (promoteId) {
        // Temporarily normalize diff.add for features using promoteId
        promoteFeatureIds(prevDiff.add, promoteId);
        promoteFeatureIds(nextDiff.add, promoteId);
    }
    // Hash for o(1) lookups while creating a mutatable copy of the collections
    const prev = diffToHashed(prevDiff);
    const next = diffToHashed(nextDiff);
    // Resolve merge conflicts
    resolveMergeConflicts(prev, next);
    // Simply merge the two diffs now that conflicts have been resolved
    const merged = {};
    if (prev.removeAll || next.removeAll)
        merged.removeAll = true;
    merged.remove = new Set([...prev.remove, ...next.remove]);
    merged.add = new Map([...prev.add, ...next.add]);
    merged.update = new Map([...prev.update, ...next.update]);
    // Squash the merge - removing then adding the same feature
    if (merged.remove.size && merged.add.size) {
        for (const id of merged.add.keys()) {
            merged.remove.delete(id);
        }
    }
    // Convert back to array-based representation
    const mergedDiff = hashedToDiff(merged);
    if (promoteId) {
        // Revert diff.add for features using promoteId
        demoteFeatureIds(mergedDiff.add, promoteId);
    }
    return mergedDiff;
}
/**
 * Resolve merge conflicts between two GeoJSONSourceDiffs considering the ordering above (remove/add/update).
 *
 * - If you `removeAll` and then `add` features in the same diff, the added features will be kept.
 * - Updates only apply to features that exist after removes and adds have been processed.
 */
function resolveMergeConflicts(prev, next) {
    // Removing all features with added or updated features in previous - and clear no-op removes
    if (next.removeAll) {
        prev.add.clear();
        prev.update.clear();
        prev.remove.clear();
        next.remove.clear();
    }
    // Removing features that were added or updated in previous
    for (const id of next.remove) {
        prev.add.delete(id);
        prev.update.delete(id);
    }
    // Updating features that were updated in previous
    for (const [id, nextUpdate] of next.update) {
        const prevUpdate = prev.update.get(id);
        if (!prevUpdate)
            continue;
        next.update.set(id, mergeFeatureDiffs(prevUpdate, nextUpdate));
        prev.update.delete(id);
    }
}
/**
 * Merge two feature diffs for the same feature id, considering the order of operations as specified above (remove, add/update).
 */
function mergeFeatureDiffs(prev, next) {
    const merged = { id: prev.id };
    // Removing all properties with added or updated properties in previous - and clear no-op removes
    if (next.removeAllProperties) {
        delete prev.removeProperties;
        delete prev.addOrUpdateProperties;
        delete next.removeProperties;
    }
    // Removing properties that were added or updated in previous
    if (next.removeProperties) {
        for (const key of next.removeProperties) {
            const index = prev.addOrUpdateProperties.findIndex(prop => prop.key === key);
            if (index > -1)
                prev.addOrUpdateProperties.splice(index, 1);
        }
    }
    // Merge the two diffs
    if (prev.removeAllProperties || next.removeAllProperties) {
        merged.removeAllProperties = true;
    }
    if (prev.removeProperties || next.removeProperties) {
        merged.removeProperties = [...prev.removeProperties || [], ...next.removeProperties || []];
    }
    if (prev.addOrUpdateProperties || next.addOrUpdateProperties) {
        merged.addOrUpdateProperties = [...prev.addOrUpdateProperties || [], ...next.addOrUpdateProperties || []];
    }
    if (prev.newGeometry || next.newGeometry) {
        merged.newGeometry = next.newGeometry || prev.newGeometry;
    }
    return merged;
}
/**
 * Mutates diff.add and applies a feature id using the promoteId property
 */
function promoteFeatureIds(add, promoteId) {
    if (!add)
        return;
    for (const feature of add) {
        const id = getFeatureId(feature, promoteId);
        if (id != null)
            feature.id = id;
    }
}
/**
 * Mutates diff.add and removes the feature id if using the promoteId property
 */
function demoteFeatureIds(add, promoteId) {
    if (!add)
        return;
    for (const feature of add) {
        const id = getFeatureId(feature, promoteId);
        if (id != null)
            delete feature.id;
    }
}
/**
 * @internal
 * Convert a GeoJSONSourceDiff to an idempotent hashed representation using Sets and Maps
 */
function diffToHashed(diff) {
    var _a, _b;
    if (!diff)
        return {};
    const hashed = {};
    hashed.removeAll = diff.removeAll;
    hashed.remove = new Set(diff.remove || []);
    hashed.add = new Map((_a = diff.add) === null || _a === void 0 ? void 0 : _a.map(feature => [feature.id, feature]));
    hashed.update = new Map((_b = diff.update) === null || _b === void 0 ? void 0 : _b.map(update => [update.id, update]));
    return hashed;
}
/**
 * @internal
 * Convert a hashed GeoJSONSourceDiff back to the array-based representation
 */
function hashedToDiff(hashed) {
    const diff = {};
    if (hashed.removeAll) {
        diff.removeAll = hashed.removeAll;
    }
    if (hashed.remove) {
        diff.remove = Array.from(hashed.remove);
    }
    if (hashed.add) {
        diff.add = Array.from(hashed.add.values());
    }
    if (hashed.update) {
        diff.update = Array.from(hashed.update.values());
    }
    return diff;
}

function extractCoordinates(coords) {
    if (!coords || coords.length === 0)
        return [];
    if (typeof coords[0] === 'number') {
        return [coords];
    }
    return coords.flatMap(c => extractCoordinates(c));
}
function getCoordinatesFromGeometry(geometry) {
    if (geometry.type === 'GeometryCollection') {
        return geometry.geometries.flatMap(g => getCoordinatesFromGeometry(g));
    }
    return extractCoordinates(geometry.coordinates);
}
/**
 * Calculates the bounding box of GeoJSON data.
 * @param data - The GeoJSON data to calculate bounds for
 * @returns The bounding box of the GeoJSON data
 */
function getGeoJSONBounds(data) {
    const bounds = new LngLatBounds();
    let coordinates;
    switch (data.type) {
        case 'FeatureCollection':
            coordinates = data.features.flatMap(f => getCoordinatesFromGeometry(f.geometry));
            break;
        case 'Feature':
            coordinates = getCoordinatesFromGeometry(data.geometry);
            break;
        default:
            coordinates = getCoordinatesFromGeometry(data);
            break;
    }
    if (coordinates.length === 0) {
        return bounds;
    }
    for (const coordinate of coordinates) {
        const [lng, lat] = coordinate;
        bounds.extend([lng, lat]);
    }
    return bounds;
}

function tileIdToLngLatBounds({ x, y, z }, buffer = 0) {
    const lngMin = symbol_layout.lngFromMercatorX((x - buffer) / Math.pow(2, z));
    const latMin = symbol_layout.latFromMercatorY((y + 1 + buffer) / Math.pow(2, z));
    const lngMax = symbol_layout.lngFromMercatorX((x + 1 + buffer) / Math.pow(2, z));
    const latMax = symbol_layout.latFromMercatorY((y - buffer) / Math.pow(2, z));
    return new LngLatBounds([lngMin, latMin], [lngMax, latMax]);
}

/**
 * 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/draw-geojson-points/)
 * @see [Add a GeoJSON line](https://maplibre.org/maplibre-gl-js/docs/examples/add-a-geojson-line/)
 * @see [Create a heatmap from points](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-heatmap-layer/)
 * @see [Create and style clusters](https://maplibre.org/maplibre-gl-js/docs/examples/create-and-style-clusters/)
 */
class GeoJSONSource extends symbol_layout.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._isUpdatingWorker = false;
        this._pendingWorkerUpdate = { data: options.data };
        this.actor = dispatcher.getActor();
        this.setEventedParent(eventedParent);
        this._data = typeof options.data === 'string' ? { url: options.data } : { geojson: options.data };
        this._options = symbol_layout.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;
        if (options.clusterMaxZoom !== undefined && this.maxzoom <= options.clusterMaxZoom) {
            symbol_layout.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 = symbol_layout.extend({
            source: this.id,
            geojsonVtOptions: {
                buffer: this._pixelsToTileUnits(options.buffer !== undefined ? options.buffer : 128),
                tolerance: this._pixelsToTileUnits(options.tolerance !== undefined ? options.tolerance : 0.375),
                extent: symbol_layout.EXTENT,
                maxZoom: this.maxzoom,
                lineMetrics: options.lineMetrics || false,
                generateId: options.generateId || false,
                promoteId: typeof options.promoteId === 'string' ? options.promoteId : undefined,
                cluster: options.cluster || false,
                clusterOptions: {
                    maxZoom: this._getClusterMaxZoom(options.clusterMaxZoom),
                    minPoints: Math.max(2, options.clusterMinPoints || 2),
                    extent: symbol_layout.EXTENT,
                    radius: this._pixelsToTileUnits(options.clusterRadius || 50),
                    log: false,
                    generateId: options.generateId || false
                },
            },
            clusterProperties: options.clusterProperties,
            filter: options.filter
        }, options.workerOptions);
    }
    _hasPendingWorkerUpdate() {
        return this._pendingWorkerUpdate.data !== undefined || this._pendingWorkerUpdate.diff !== undefined || this._pendingWorkerUpdate.updateCluster;
    }
    _pixelsToTileUnits(pixelValue) {
        return pixelValue * (symbol_layout.EXTENT / this.tileSize);
    }
    _getClusterMaxZoom(clusterMaxZoom) {
        const effectiveClusterMaxZoom = clusterMaxZoom ? Math.round(clusterMaxZoom) : this.maxzoom - 1;
        if (!(Number.isInteger(clusterMaxZoom) || clusterMaxZoom === undefined)) {
            symbol_layout.warnOnce(`Integer expected for option 'clusterMaxZoom': provided value "${clusterMaxZoom}" rounded to "${effectiveClusterMaxZoom}"`);
        }
        return effectiveClusterMaxZoom;
    }
    load() {
        return symbol_layout.__awaiter(this, void 0, void 0, function* () {
            yield this._updateWorkerData();
        });
    }
    onAdd(map) {
        this.map = map;
        this.load();
    }
    setData(data, waitForCompletion) {
        this._data = typeof data === 'string' ? { url: data } : { geojson: data };
        this._pendingWorkerUpdate = { data };
        const updatePromise = this._updateWorkerData();
        if (waitForCompletion)
            return updatePromise;
        return this;
    }
    updateData(diff, waitForCompletion) {
        this._pendingWorkerUpdate.diff = mergeSourceDiffs(this._pendingWorkerUpdate.diff, diff);
        const updatePromise = this._updateWorkerData();
        if (waitForCompletion)
            return updatePromise;
        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 symbol_layout.__awaiter(this, void 0, void 0, function* () {
            if (this._data.url) {
                yield this.once('data'); // wait for loading to complete
            }
            if (this._data.geojson) {
                return this._data.geojson;
            }
            return {
                type: 'FeatureCollection',
                features: Array.from(this._data.updateable.values())
            };
        });
    }
    /**
     * Allows getting the source's boundaries.
     * If there's a problem with the source's data, it will return an empty {@link LngLatBounds}.
     * @returns a promise which resolves to the source's boundaries
     */
    getBounds() {
        return symbol_layout.__awaiter(this, void 0, void 0, function* () {
            return getGeoJSONBounds(yield this.getData());
        });
    }
    /**
     * 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.geojsonVtOptions.cluster = options.cluster;
        if (options.clusterRadius !== undefined) {
            this.workerOptions.geojsonVtOptions.clusterOptions.radius = this._pixelsToTileUnits(options.clusterRadius);
        }
        if (options.clusterMaxZoom !== undefined) {
            this.workerOptions.geojsonVtOptions.clusterOptions.maxZoom = this._getClusterMaxZoom(options.clusterMaxZoom);
        }
        this._pendingWorkerUpdate.updateCluster = true;
        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.
     */
    _updateWorkerData() {
        return symbol_layout.__awaiter(this, void 0, void 0, function* () {
            if (this._isUpdatingWorker)
                return;
            if (!this._hasPendingWorkerUpdate()) {
                symbol_layout.warnOnce(`No pending worker updates for GeoJSONSource ${this.id}.`);
                return;
            }
            const { data, diff, updateCluster } = this._pendingWorkerUpdate;
            // delay awaiting params until _isUpdatingWorker is set, otherwise, a race condition could happen
            const params = this._getLoadGeoJSONParameters(data, diff, updateCluster);
            if (data !== undefined) {
                this._pendingWorkerUpdate.data = undefined;
            }
            else if (diff) {
                this._pendingWorkerUpdate.diff = undefined;
            }
            else if (updateCluster) {
                this._pendingWorkerUpdate.updateCluster = undefined;
            }
            yield this._dispatchWorkerUpdate(params);
        });
    }
    /**
     * Create the parameters object that will be sent to the worker and used to load GeoJSON.
     */
    _getLoadGeoJSONParameters(data, diff, updateCluster) {
        return symbol_layout.__awaiter(this, void 0, void 0, function* () {
            const params = symbol_layout.extend({ type: this.type }, this.workerOptions);
            // Data comes from a remote url
            if (typeof data === 'string') {
                params.request = yield this.map._requestManager.transformRequest(browser.resolveURL(data), "Source" /* ResourceType.Source */);
                params.request.collectResourceTiming = this._collectResourceTiming;
                return params;
            }
            // Data is a geojson object
            if (data !== undefined) {
                params.data = data;
                return params;
            }
            // Data is a differential update
            if (diff) {
                params.dataDiff = diff;
                return params;
            }
            // Update supercluster with the latest worker cluster options
            if (updateCluster) {
                params.updateCluster = true;
                return params;
            }
        });
    }
    /**
     * Send the worker update data from the main thread to the worker
     */
    _dispatchWorkerUpdate(optionsPromise) {
        return symbol_layout.__awaiter(this, void 0, void 0, function* () {
            this._isUpdatingWorker = true;
            this.fire(new symbol_layout.Event('dataloading', { dataType: 'source' }));
            try {
                const options = yield optionsPromise;
                const result = yield this.actor.sendAsync({ type: "LD" /* MessageType.loadData */, data: options });
                this._isUpdatingWorker = false;
                if (this._removed || result.abandoned) {
                    this.fire(new symbol_layout.Event('dataabort', { dataType: 'source' }));
                    return;
                }
                // Update the copy of the data in this source with the worker result. (only sent for url based geojson data)
                if (result.data) {
                    this._data = { geojson: result.data };
                }
                const affectedGeometries = this._applyDiffToSource(options.dataDiff);
                const shouldReloadTileOptions = this._getShouldReloadTileOptions(affectedGeometries);
                const eventData = { dataType: 'source' };
                this._applyResourceTiming(eventData, result);
                // Fire the metadata event to let the TileManager know it's ok to start requesting tiles.
                this.fire(new symbol_layout.Event('data', Object.assign(Object.assign({}, eventData), { sourceDataType: 'metadata' })));
                this.fire(new symbol_layout.Event('data', Object.assign(Object.assign({}, eventData), { sourceDataType: 'content', shouldReloadTileOptions })));
            }
            catch (err) {
                this._isUpdatingWorker = false;
                if (this._removed) {
                    this.fire(new symbol_layout.Event('dataabort', { dataType: 'source' }));
                    return;
                }
                this.fire(new symbol_layout.ErrorEvent(symbol_layout.ensureError(err)));
            }
            finally {
                // If there is more pending data, update the worker again.
                if (this._hasPendingWorkerUpdate()) {
                    this._updateWorkerData();
                }
            }
        });
    }
    /**
     * Apply resource timing data to the event object.
     */
    _applyResourceTiming(eventData, result) {
        var _a;
        if (!this._collectResourceTiming)
            return;
        const timingData = (_a = result.resourceTiming) === null || _a === void 0 ? void 0 : _a[this.id];
        if (!timingData)
            return;
        const resourceTiming = timingData.slice(0);
        if (!(resourceTiming === null || resourceTiming === void 0 ? void 0 : resourceTiming.length))
            return;
        symbol_layout.extend(eventData, { resourceTiming });
    }
    /**
     * Apply a diff to this source's data and return the affected feature geometries.
     * @param diff - The {@link GeoJSONSourceDiff} to apply.
     * @returns The affected geometries, or undefined if the diff is not applicable or all geometries are affected.
     */
    _applyDiffToSource(diff) {
        if (!diff) {
            return undefined;
        }
        const promoteId = typeof this.promoteId === 'string' ? this.promoteId : undefined;
        // Lazily convert `this._data` to updateable if it's not already
        if (!this._data.url && !this._data.updateable) {
            const updateable = toUpdateable(this._data.geojson, promoteId);
            if (!updateable)
                throw new Error(`GeoJSONSource "${this.id}": GeoJSON data is not compatible with updateData`);
            this._data = { updateable };
        }
        if (!this._data.updateable) {
            return undefined;
        }
        const affectedGeometries = applySourceDiff(this._data.updateable, diff, promoteId);
        if (diff.removeAll || this._options.cluster) {
            return undefined;
        }
        return affectedGeometries;
    }
    /**
     * Get options for use in determining whether to reload a tile based on the modified features.
     * @param affectedGeometries - The feature geometries affected by the update.
     * @returns A {@link GeoJSONSourceShouldReloadTileOptions} object which contains an array of affected bounds caused by the update.
     */
    _getShouldReloadTileOptions(affectedGeometries) {
        if (!affectedGeometries)
            return undefined;
        const affectedBounds = affectedGeometries
            .filter(Boolean)
            .map(g => getGeoJSONBounds(g));
        return { affectedBounds };
    }
    /**
     * Determine whether a tile should be reloaded based on a set of options associated with a {@link MapSourceDataChangedEvent}.
     * @internal
     */
    shouldReloadTile(tile, { affectedBounds }) {
        if (tile.state === 'loading') {
            return true;
        }
        if (tile.state === 'unloaded') {
            return false;
        }
        // Update the tile if contained or will contain an updated feature.
        const { buffer, extent } = this.workerOptions.geojsonVtOptions;
        const tileBounds = tileIdToLngLatBounds(tile.tileID.canonical, buffer / extent);
        for (const bounds of affectedBounds) {
            if (tileBounds.intersects(bounds)) {
                return true;
            }
        }
        return false;
    }
    loaded() {
        return !this._isUpdatingWorker && !this._hasPendingWorkerUpdate();
    }
    loadTile(tile) {
        return symbol_layout.__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,
                subdivisionGranularity: this.map.style.projection.subdivisionGranularity
            };
            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 symbol_layout.__awaiter(this, void 0, void 0, function* () {
            if (tile.abortController) {
                tile.abortController.abort();
                delete tile.abortController;
            }
            tile.aborted = true;
        });
    }
    unloadTile(tile) {
        return symbol_layout.__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 symbol_layout.extend({}, this._options, {
            type: this.type,
            data: this._data.updateable ?
                {
                    type: 'FeatureCollection',
                    features: Array.from(this._data.updateable.values())
                } :
                this._data.url || this._data.geojson
        });
    }
    hasTransition() {
        return false;
    }
}

/**
 * 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 symbol_layout.Evented {
    /** @internal */
    constructor(id, options, dispatcher, eventedParent) {
        super();
        this.flippedWindingOrder = false;
        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 symbol_layout.__awaiter(this, void 0, void 0, function* () {
            this._loaded = false;
            this.fire(new symbol_layout.Event('dataloading', { dataType: 'source' }));
            this.url = this.options.url;
            this._request = new AbortController();
            try {
                const image = yield ImageRequest.getImage(yield this.map._requestManager.transformRequest(this.url, "Image" /* ResourceType.Image */), this._request);
                this._request = null;
                this._loaded = true;
                if (image === null || image === void 0 ? void 0 : image.data) {
                    this.image = image.data;
                    if (newCoordinates) {
                        this.coordinates = newCoordinates;
                    }
                    this._finishLoading();
                }
            }
            catch (err) {
                this._request = null;
                this._loaded = true;
                if (!symbol_layout.isAbortError(err)) {
                    this.fire(new symbol_layout.ErrorEvent(symbol_layout.ensureError(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 symbol_layout.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(symbol_layout.MercatorCoordinate.fromLngLat);
        // Compute the coordinates of the tile we'll use to hold this image's
        // render data
        this.tileID = getCoordinatesCenterTileID(cornerCoords);
        // Compute tiles overlapping with the image. We need to know for which
        // terrain tiles we have to render the image.
        this.terrainTileRanges = this._getOverlappingTileRanges(cornerCoords);
        // Constrain min/max zoom to our tile's zoom level in order to force
        // TileManager 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.
        this.tileCoords = cornerCoords.map((coord) => this.tileID.getTilePoint(coord)._round());
        this.flippedWindingOrder = hasWrongWindingOrder(this.tileCoords);
        this.fire(new symbol_layout.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.texture) {
            this.texture = new symbol_layout.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 symbol_layout.Event('data', { dataType: 'source', sourceDataType: 'idle', sourceId: this.id }));
        }
    }
    loadTile(tile) {
        return symbol_layout.__awaiter(this, void 0, void 0, function* () {
            var _a;
            // 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 ((_a = this.tileID) === null || _a === void 0 ? void 0 : _a.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, determine overlapping tile ranges for all zoom levels.
     *
     * @returns Overlapping tile ranges for all zoom levels.
     * @internal
     */
    _getOverlappingTileRanges(coords) {
        const { minX, minY, maxX, maxY } = symbol_layout.Bounds.fromPoints(coords);
        const ranges = {};
        for (let z = 0; z <= symbol_layout.MAX_TILE_ZOOM; z++) {
            const tilesAtZoom = Math.pow(2, z);
            const minTileX = Math.floor(minX * tilesAtZoom);
            const minTileY = Math.floor(minY * tilesAtZoom);
            const maxTileX = Math.floor(maxX * tilesAtZoom);
            const maxTileY = Math.floor(maxY * tilesAtZoom);
            const minTileXWrapped = ((minTileX % tilesAtZoom) + tilesAtZoom) % tilesAtZoom;
            const maxTileXWrapped = maxTileX % tilesAtZoom;
            const minWrap = Math.floor(minTileX / tilesAtZoom);
            const maxWrap = Math.floor(maxTileX / tilesAtZoom);
            ranges[z] = {
                minWrap,
                maxWrap,
                minTileXWrapped,
                maxTileXWrapped,
                minTileY,
                maxTileY
            };
        }
        return ranges;
    }
}
/**
 * Given a list of coordinates, get their center as a coordinate.
 *
 * @returns centerpoint
 * @internal
 */
function getCoordinatesCenterTileID(coords) {
    const bounds = symbol_layout.Bounds.fromPoints(coords);
    const dx = bounds.width();
    const dy = bounds.height();
    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 symbol_layout.CanonicalTileID(zoom, Math.floor((bounds.minX + bounds.maxX) / 2 * tilesAtZoom), Math.floor((bounds.minY + bounds.maxY) / 2 * tilesAtZoom));
}
function hasWrongWindingOrder(coords) {
    const e0x = coords[1].x - coords[0].x;
    const e0y = coords[1].y - coords[0].y;
    const e1x = coords[2].x - coords[0].x;
    const e1y = coords[2].y - coords[0].y;
    const crossProduct = e0x * e1y - e0y * e1x;
    return crossProduct < 0;
}

/**
 * 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._onPlayingHandler = () => {
            var _a;
            (_a = this.map) === null || _a === void 0 ? void 0 : _a.triggerRepaint();
        };
        this.roundZoom = true;
        this.type = 'video';
        this.options = options;
    }
    load() {
        return symbol_layout.__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((yield this.map._requestManager.transformRequest(url, "Source" /* ResourceType.Source */)).url);
            }
            try {
                const video = yield symbol_layout.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._onPlayingHandler);
                if (this.map) {
                    this.video.play();
                }
                this._finishLoading();
            }
            catch (err) {
                this.fire(new symbol_layout.ErrorEvent(symbol_layout.ensureError(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 symbol_layout.ErrorEvent(new symbol_layout.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);
        }
    }
    onRemove() {
        super.onRemove();
        if (this.video) {
            this.video.removeEventListener('playing', this._onPlayingHandler);
            this.video.pause();
        }
    }
    /**
     * 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.texture) {
            this.texture = new symbol_layout.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 symbol_layout.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 symbol_layout.ErrorEvent(new symbol_layout.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 symbol_layout.ErrorEvent(new symbol_layout.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 symbol_layout.ErrorEvent(new symbol_layout.ValidationError(`sources.${id}`, null, 'optional "animate" property must be a boolean value')));
        }
        if (!options.canvas) {
            this.fire(new symbol_layout.ErrorEvent(new symbol_layout.ValidationError(`sources.${id}`, null, 'missing required property "canvas"')));
        }
        else if (typeof options.canvas !== 'string' && !(options.canvas instanceof HTMLCanvasElement)) {
            this.fire(new symbol_layout.ErrorEvent(new symbol_layout.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 symbol_layout.__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 symbol_layout.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.texture) {
            this.texture = new symbol_layout.Texture(context, this.canvas, gl.RGBA, { premultiply: true });
            this.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
        }
        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 symbol_layout.Event('data', { dataType: 'source', sourceDataType: 'idle', sourceId: this.id }));
        }
    }
    serialize() {
        return {
            type: 'canvas',
            animate: this.animate,
            canvas: this.options.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) => symbol_layout.__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 symbol_layout.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 symbol_layout.__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 symbol_layout.__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 symbol_layout.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;
var FadingRoles;
(function (FadingRoles) {
    FadingRoles[FadingRoles["Base"] = 0] = "Base";
    FadingRoles[FadingRoles["Parent"] = 1] = "Parent";
})(FadingRoles || (FadingRoles = {}));
var FadingDirections;
(function (FadingDirections) {
    FadingDirections[FadingDirections["Departing"] = 0] = "Departing";
    FadingDirections[FadingDirections["Incoming"] = 1] = "Incoming";
})(FadingDirections || (FadingDirections = {}));
/**
 * 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.fadeOpacity = 1;
        this.tileID = tileID;
        this.uid = symbol_layout.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.rttFingerprint = {};
        // 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';
    }
    isRenderable(symbolLayer) {
        return (this.hasData() &&
            (!this.fadeEndTime || this.fadeOpacity > 0) && // raster fading
            (symbolLayer || !this.holdingForSymbolFade()) // symbol fading
        );
    }
    /**
     * @internal
     * Many-to-one crossfade between a base tile and parent/ancestor tile (when zooming)
     */
    setCrossFadeLogic({ fadingRole, fadingDirection, fadingParentID, fadeEndTime }) {
        this.resetFadeLogic();
        this.fadingRole = fadingRole;
        this.fadingDirection = fadingDirection;
        this.fadingParentID = fadingParentID;
        this.fadeEndTime = fadeEndTime;
    }
    /**
     * Self fading for edge tiles (when panning map)
     */
    setSelfFadeLogic(fadeEndTime) {
        this.resetFadeLogic();
        this.selfFading = true;
        this.fadeEndTime = fadeEndTime;
    }
    resetFadeLogic() {
        this.fadingRole = null;
        this.fadingDirection = null;
        this.fadingParentID = null;
        this.selfFading = false;
        this.timeAdded = now();
        this.fadeEndTime = 0;
        this.fadeOpacity = 1;
    }
    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 ((data === null || data === void 0 ? void 0 : data.etagUnmodified) === true) {
            this.state = 'loaded';
            return;
        }
        if (this.hasData()) {
            this.unloadVectorData();
        }
        this.state = 'loaded';
        // empty GeoJSON tile
        if (!data) {
            this.collisionBoxArray = new symbol_layout.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.latestEncoding = data.encoding;
                this.latestFeatureIndex.rawTileData = data.rawTileData;
                this.latestFeatureIndex.encoding = data.encoding;
            }
            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.latestFeatureIndex.encoding = this.latestEncoding;
            }
        }
        this.collisionBoxArray = data.collisionBoxArray;
        this.buckets = deserialize(data.buckets, painter === null || painter === void 0 ? void 0 : painter.style);
        this.hasSymbolBuckets = false;
        for (const id in this.buckets) {
            const bucket = this.buckets[id];
            if (bucket instanceof symbol_layout.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 symbol_layout.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.glyphAtlasImage) {
            this.glyphAtlasImage = data.glyphAtlasImage;
        }
        this.dashPositions = data.dashPositions;
    }
    /**
     * 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.imageAtlas) {
            this.imageAtlas = null;
        }
        if (this.glyphAtlasTexture) {
            this.glyphAtlasTexture.destroy();
        }
        if (this.dashPositions) {
            this.dashPositions = null;
        }
        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 symbol_layout.Texture(context, this.imageAtlas.image, gl.RGBA);
            this.imageAtlas.uploaded = true;
        }
        if (this.glyphAtlasImage) {
            this.glyphAtlasTexture = new symbol_layout.Texture(context, this.glyphAtlasImage, gl.ALPHA);
            this.glyphAtlasImage = null;
        }
    }
    prepare(imageManager) {
        if (this.imageAtlas) {
            this.imageAtlas.patchUpdatedImages(imageManager, this.imageAtlasTexture);
        }
    }
    // Queries non-symbol features rendered for this tile.
    // Symbol features are queried globally
    queryRenderedFeatures(layers, serializedLayers, sourceFeatureState, queryGeometry, cameraQueryGeometry, scale, params, transform, maxPitchScaleFactor, pixelPosMatrix, getElevation) {
        var _a;
        if (!((_a = this.latestFeatureIndex) === null || _a === void 0 ? void 0 : _a.rawTileData))
            return {};
        return this.latestFeatureIndex.query({
            queryGeometry,
            cameraQueryGeometry,
            scale,
            tileSize: this.tileSize,
            pixelPosMatrix,
            transform,
            params,
            queryPadding: this.queryPadding * maxPitchScaleFactor,
            getElevation
        }, layers, serializedLayers, sourceFeatureState);
    }
    querySourceFeatures(result, params) {
        const featureIndex = this.latestFeatureIndex;
        if (!(featureIndex === null || featureIndex === void 0 ? void 0 : featureIndex.rawTileData))
            return;
        const vtLayers = featureIndex.loadVTLayers();
        const sourceLayer = (params === null || params === void 0 ? void 0 : params.sourceLayer) ? params.sourceLayer : '';
        const layer = vtLayers[symbol_layout.GEOJSON_TILE_LAYER_NAME] || vtLayers[sourceLayer];
        if (!layer)
            return;
        const filter = symbol_layout.featureFilter(params === null || params === void 0 ? void 0 : params.filter, params === null || params === void 0 ? void 0 : params.globalState);
        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 = symbol_layout.toEvaluationFeature(feature, true);
                if (!filter.filter(new symbol_layout.EvaluationParameters(this.tileID.overscaledZ), evaluationFeature, this.tileID.canonical))
                    continue;
            }
            else if (!filter.filter(new symbol_layout.EvaluationParameters(this.tileID.overscaledZ), feature)) {
                continue;
            }
            const id = featureIndex.getId(feature, sourceLayer);
            const geojsonFeature = new symbol_layout.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 = symbol_layout.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) {
        var _a, _b, _c;
        if (!((_a = this.latestFeatureIndex) === null || _a === void 0 ? void 0 : _a.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'] || symbol_layout.GEOJSON_TILE_LAYER_NAME;
            const sourceLayer = vtLayers[sourceLayerId];
            const sourceLayerStates = states[sourceLayerId];
            if (!sourceLayer || !sourceLayerStates || Object.keys(sourceLayerStates).length === 0)
                continue;
            bucket.update(sourceLayerStates, sourceLayer, ((_b = this.imageAtlas) === null || _b === void 0 ? void 0 : _b.patternPositions) || {}, this.dashPositions || {});
            const layer = (_c = painter === null || painter === void 0 ? void 0 : painter.style) === null || _c === void 0 ? void 0 : _c.getLayer(id);
            if (layer) {
                this.queryPadding = Math.max(this.queryPadding, layer.queryRadius(bucket));
            }
        }
    }
    holdingForSymbolFade() {
        return this.symbolFadeHoldUntil !== undefined;
    }
    symbolFadeFinished() {
        return !this.symbolFadeHoldUntil || this.symbolFadeHoldUntil < now();
    }
    clearSymbolFadeHold() {
        this.symbolFadeHoldUntil = undefined;
    }
    setSymbolHoldDuration(duration) {
        this.symbolFadeHoldUntil = 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
 * 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 = {};
        this.revision = 0;
    }
    updateState(sourceLayer, featureId, newState) {
        var _a, _b, _c;
        const feature = String(featureId);
        this.stateChanges[sourceLayer] = this.stateChanges[sourceLayer] || {};
        this.stateChanges[sourceLayer][feature] = this.stateChanges[sourceLayer][feature] || {};
        symbol_layout.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 = ((_a = this.deletedStates[sourceLayer]) === null || _a === void 0 ? void 0 : _a[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 = ((_c = (_b = this.deletedStates[sourceLayer]) === null || _b === void 0 ? void 0 : _b[feature]) === null || _c === void 0 ? void 0 : _c[key]) === null;
                    if (deletionInQueue)
                        delete this.deletedStates[sourceLayer][feature][key];
                }
            }
        }
    }
    removeFeatureState(sourceLayer, featureId, key) {
        var _a;
        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 = (_a = this.stateChanges[sourceLayer]) === null || _a === void 0 ? void 0 : _a[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 = symbol_layout.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(inViewTiles, 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] = {};
                symbol_layout.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] || {};
            symbol_layout.extend(featuresChanged[sourceLayer], layerStates);
        }
        this.stateChanges = {};
        this.deletedStates = {};
        if (Object.keys(featuresChanged).length === 0)
            return;
        this.revision++;
        inViewTiles.setFeatureState(featuresChanged, painter);
    }
}

/*
* The maximum angle to use for the Mercator horizon. This must be less than 90
* to prevent errors in `MercatorTransform::_calcMatrices()`. It shouldn't be too close
* to 90, or the distance to the horizon will become very large, unnecessarily increasing
* the number of tiles needed to render the map.
*/
const maxMercatorHorizonAngle = 89.25;
/**
 * Returns mercator coordinates in range 0..1 for given coordinates inside a specified tile.
 * @param inTileX - X coordinate in tile units - range [0..EXTENT].
 * @param inTileY - Y coordinate in tile units - range [0..EXTENT].
 * @param canonicalTileID - Tile canonical ID - mercator X, Y and zoom.
 * @returns Mercator coordinates of the specified point in range [0..1].
 */
function tileCoordinatesToMercatorCoordinates(inTileX, inTileY, canonicalTileID) {
    const scale = 1.0 / (1 << canonicalTileID.z);
    return new symbol_layout.MercatorCoordinate(inTileX / symbol_layout.EXTENT * scale + canonicalTileID.x * scale, inTileY / symbol_layout.EXTENT * scale + canonicalTileID.y * scale);
}
/**
 * Returns LngLat for given in-tile coordinates and tile ID.
 * @param inTileX - X coordinate in tile units - range [0..EXTENT].
 * @param inTileY - Y coordinate in tile units - range [0..EXTENT].
 * @param canonicalTileID - Tile canonical ID - mercator X, Y and zoom.
 */
function tileCoordinatesToLocation(inTileX, inTileY, canonicalTileID) {
    return tileCoordinatesToMercatorCoordinates(inTileX, inTileY, canonicalTileID).toLngLat();
}
/**
 * Convert from LngLat to world coordinates (Mercator coordinates scaled by world size).
 * @param worldSize - Mercator world size computed from zoom level and tile size.
 * @param lnglat - The location to convert.
 * @returns Point
 */
function projectToWorldCoordinates(worldSize, lnglat) {
    const lat = symbol_layout.clamp(lnglat.lat, -symbol_layout.MAX_VALID_LATITUDE, symbol_layout.MAX_VALID_LATITUDE);
    return new symbol_layout.Point(symbol_layout.mercatorXfromLng(lnglat.lng) * worldSize, symbol_layout.mercatorYfromLat(lat) * worldSize);
}
/**
 * Convert from world coordinates (mercator coordinates scaled by world size) to LngLat.
 * @param worldSize - Mercator world size computed from zoom level and tile size.
 * @param point - World coordinate.
 * @returns LngLat
 */
function unprojectFromWorldCoordinates(worldSize, point) {
    return new symbol_layout.MercatorCoordinate(point.x / worldSize, point.y / worldSize).toLngLat();
}
/**
 * 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.
 */
function getMercatorHorizon(transform) {
    return transform.cameraToCenterDistance * Math.min(Math.tan(symbol_layout.degreesToRadians(90 - transform.pitch)) * 0.85, Math.tan(symbol_layout.degreesToRadians(maxMercatorHorizonAngle - transform.pitch)));
}
function calculateTileMatrix(unwrappedTileID, worldSize) {
    const canonical = unwrappedTileID.canonical;
    const scale = worldSize / symbol_layout.zoomScale(canonical.z);
    const unwrappedX = canonical.x + Math.pow(2, canonical.z) * unwrappedTileID.wrap;
    const worldMatrix = symbol_layout.identity(new Float64Array(16));
    symbol_layout.translate(worldMatrix, worldMatrix, [unwrappedX * scale, canonical.y * scale, 0]);
    symbol_layout.scale(worldMatrix, worldMatrix, [scale / symbol_layout.EXTENT, scale / symbol_layout.EXTENT, 1]);
    return worldMatrix;
}
function cameraMercatorCoordinateFromCenterAndRotation(center, elevation, pitch, bearing, distance) {
    const centerMercator = symbol_layout.MercatorCoordinate.fromLngLat(center, elevation);
    const mercUnitsPerMeter = symbol_layout.mercatorZfromAltitude(1, center.lat);
    const dMercator = distance * mercUnitsPerMeter;
    const { x, y, z } = cameraDirectionFromPitchBearing(pitch, bearing);
    const dxMercator = dMercator * -x;
    const dyMercator = dMercator * -y;
    const dzMercator = dMercator * -z;
    return new symbol_layout.MercatorCoordinate(centerMercator.x + dxMercator, centerMercator.y + dyMercator, centerMercator.z + dzMercator);
}
function cameraDirectionFromPitchBearing(pitch, bearing) {
    const pitchRadians = symbol_layout.degreesToRadians(pitch);
    const bearingRadians = symbol_layout.degreesToRadians(bearing);
    const z = Math.cos(-pitchRadians);
    const h = Math.sin(pitchRadians);
    const x = h * Math.sin(bearingRadians);
    const y = -h * Math.cos(bearingRadians);
    return { x, y, z };
}

/**
 * A simple/heuristic function that returns whether the tile is visible under the current transform.
 * @returns an {@link IntersectionResult}.
 */
function isTileVisible(frustum, tileBoundingVolume, plane) {
    const frustumTest = tileBoundingVolume.intersectsFrustum(frustum);
    if (!plane || frustumTest === 0 /* IntersectionResult.None */) {
        return frustumTest;
    }
    const planeTest = tileBoundingVolume.intersectsPlane(plane);
    if (planeTest === 0 /* IntersectionResult.None */) {
        return 0 /* IntersectionResult.None */;
    }
    if (frustumTest === 2 /* IntersectionResult.Full */ && planeTest === 2 /* IntersectionResult.Full */) {
        return 2 /* IntersectionResult.Full */;
    }
    return 1 /* IntersectionResult.Partial */;
}
/**
 * Definite integral of cos(x)^p. The analytical solution is described in `developer-guides/covering-tiles.md`,
 * but here the integral is evaluated numerically.
 * @param p - the power to raise cos(x) to inside the integral
 * @param x1 - the starting point of the integral.
 * @param x2 - the ending point of the integral.
 * @return the integral of cos(x)^p from x=x1 to x=x2
 */
function integralOfCosXByP(p, x1, x2) {
    const numPoints = 10;
    let sum = 0;
    const dx = (x2 - x1) / numPoints;
    // Midpoint integration
    for (let i = 0; i < numPoints; i++) {
        const x = x1 + (i + 0.5) / numPoints * (x2 - x1);
        sum += dx * Math.pow(Math.cos(x), p);
    }
    return sum;
}
function createCalculateTileZoomFunction(maxZoomLevelsOnScreen, tileCountMaxMinRatio) {
    return function (requestedCenterZoom, distanceToTile2D, distanceToTileZ, distanceToCenter3D, cameraVerticalFOV) {
        /**
        * Controls how tiles are loaded at high pitch angles. Higher numbers cause fewer, lower resolution
        * tiles to be loaded. Calculate the value that will result in the selected number of zoom levels in
        * the worst-case condition (when the horizon is at the top of the screen). For more information, see
        * `developer-guides/covering-tiles.md`
        */
        const pitchTileLoadingBehavior = 2 * ((maxZoomLevelsOnScreen - 1) /
            symbol_layout.scaleZoom(Math.cos(symbol_layout.degreesToRadians(maxMercatorHorizonAngle - cameraVerticalFOV)) /
                Math.cos(symbol_layout.degreesToRadians(maxMercatorHorizonAngle))) - 1);
        const centerPitch = Math.acos(distanceToTileZ / distanceToCenter3D);
        const tileCountPitch0 = 2 * integralOfCosXByP(pitchTileLoadingBehavior - 1, 0, symbol_layout.degreesToRadians(cameraVerticalFOV / 2));
        const highestPitch = Math.min(symbol_layout.degreesToRadians(maxMercatorHorizonAngle), centerPitch + symbol_layout.degreesToRadians(cameraVerticalFOV / 2));
        const lowestPitch = Math.min(highestPitch, centerPitch - symbol_layout.degreesToRadians(cameraVerticalFOV / 2));
        const tileCount = integralOfCosXByP(pitchTileLoadingBehavior - 1, lowestPitch, highestPitch);
        const thisTilePitch = Math.atan(distanceToTile2D / distanceToTileZ);
        const distanceToTile3D = Math.hypot(distanceToTile2D, distanceToTileZ);
        let thisTileDesiredZ = requestedCenterZoom;
        // if distance to candidate tile is a tiny bit farther than distance to center,
        // use the same zoom as the center. This is achieved by the scaling distance ratio by cos(fov/2)
        thisTileDesiredZ = thisTileDesiredZ + symbol_layout.scaleZoom(distanceToCenter3D / distanceToTile3D / Math.max(0.5, Math.cos(symbol_layout.degreesToRadians(cameraVerticalFOV / 2))));
        thisTileDesiredZ += pitchTileLoadingBehavior * symbol_layout.scaleZoom(Math.cos(thisTilePitch)) / 2;
        thisTileDesiredZ -= symbol_layout.scaleZoom(Math.max(1, tileCount / tileCountPitch0 / tileCountMaxMinRatio)) / 2;
        return thisTileDesiredZ;
    };
}
const defaultMaxZoomLevelsOnScreen = 9.314;
const defaultTileCountMaxMinRatio = 3.0;
const defaultCalculateTileZoom = createCalculateTileZoomFunction(defaultMaxZoomLevelsOnScreen, defaultTileCountMaxMinRatio);
/**
 * Return what zoom level of a tile source would most closely cover the tiles displayed by this transform.
 * @param options - The options, most importantly the source's tile size.
 * @returns An integer zoom level at which all tiles will be visible.
 */
function coveringZoomLevel(transform, options) {
    const z = (options.roundZoom ? Math.round : Math.floor)(transform.zoom + symbol_layout.scaleZoom(transform.tileSize / options.tileSize));
    // At negative zoom levels load tiles from z0 because negative tile zoom levels don't exist.
    return Math.max(0, z);
}
/**
 * Returns a list of tiles that optimally covers the screen. Adapted for globe projection.
 * Correctly handles LOD when moving over the antimeridian.
 * @param transform - The transform instance.
 * @param frustum - The covering frustum.
 * @param plane - The clipping plane used by globe transform, or null.
 * @param cameraCoord - The x, y, z position of the camera in MercatorCoordinates.
 * @param centerCoord - The x, y, z position of the center point in MercatorCoordinates.
 * @param options - Additional coveringTiles options.
 * @param details - Interface to define required helper functions.
 * @returns A list of tile coordinates, ordered by ascending distance from camera.
 */
function coveringTiles(transform, options) {
    const frustum = transform.getCameraFrustum();
    const plane = transform.getClippingPlane();
    const cameraCoord = transform.screenPointToMercatorCoordinate(transform.getCameraPoint());
    const centerCoord = symbol_layout.MercatorCoordinate.fromLngLat(transform.center, transform.elevation);
    cameraCoord.z = centerCoord.z + Math.cos(transform.pitchInRadians) * transform.cameraToCenterDistance / transform.worldSize;
    const detailsProvider = transform.getCoveringTilesDetailsProvider();
    const allowVariableZoom = detailsProvider.allowVariableZoom(transform, options);
    const desiredZ = coveringZoomLevel(transform, options);
    const minZoom = options.minzoom || 0;
    const maxZoom = options.maxzoom !== undefined ? options.maxzoom : transform.maxZoom;
    const nominalZ = Math.min(Math.max(0, desiredZ), maxZoom);
    const numTiles = Math.pow(2, nominalZ);
    const cameraPoint = [numTiles * cameraCoord.x, numTiles * cameraCoord.y, 0];
    const centerPoint = [numTiles * centerCoord.x, numTiles * centerCoord.y, 0];
    const distanceToCenter2d = Math.hypot(centerCoord.x - cameraCoord.x, centerCoord.y - cameraCoord.y);
    const distanceZ = Math.abs(centerCoord.z - cameraCoord.z);
    const distanceToCenter3d = Math.hypot(distanceToCenter2d, distanceZ);
    const newRootTile = (wrap) => {
        return {
            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 = [];
    if (transform.renderWorldCopies && detailsProvider.allowWorldCopies()) {
        // 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;
        const tileID = { x, y, z: it.zoom };
        const boundingVolume = detailsProvider.getTileBoundingVolume(tileID, it.wrap, transform.elevation, options);
        // Visibility of a tile is not required if any of its ancestor is fully visible
        if (!fullyVisible) {
            const intersectResult = isTileVisible(frustum, boundingVolume, plane);
            if (intersectResult === 0 /* IntersectionResult.None */)
                continue;
            fullyVisible = intersectResult === 2 /* IntersectionResult.Full */;
        }
        const distToTile2d = detailsProvider.distanceToTile2d(cameraCoord.x, cameraCoord.y, tileID, boundingVolume);
        let thisTileDesiredZ = desiredZ;
        if (allowVariableZoom) {
            const tileZoomFunc = options.calculateTileZoom || defaultCalculateTileZoom;
            thisTileDesiredZ = tileZoomFunc(transform.zoom + symbol_layout.scaleZoom(transform.tileSize / options.tileSize), distToTile2d, distanceZ, distanceToCenter3d, transform.fov);
        }
        thisTileDesiredZ = (options.roundZoom ? Math.round : Math.floor)(thisTileDesiredZ);
        thisTileDesiredZ = Math.max(0, thisTileDesiredZ);
        const z = Math.min(thisTileDesiredZ, maxZoom);
        // We need to compute a valid wrap value for the tile to keep globe compatibility with mercator
        it.wrap = detailsProvider.getWrap(centerCoord, tileID, it.wrap);
        // Have we reached the target depth?
        if (it.zoom >= z) {
            if (it.zoom < minZoom) {
                continue;
            }
            const dz = nominalZ - it.zoom;
            const dx = cameraPoint[0] - 0.5 - (x << dz);
            const dy = cameraPoint[1] - 0.5 - (y << dz);
            const overscaledZ = options.reparseOverscaled ? Math.max(it.zoom, thisTileDesiredZ) : it.zoom;
            result.push({
                tileID: new symbol_layout.OverscaledTileID(it.zoom === maxZoom ? overscaledZ : it.zoom, it.wrap, it.zoom, x, y),
                distanceSq: symbol_layout.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;
            stack.push({ zoom: childZ, x: childX, y: childY, wrap: it.wrap, fullyVisible });
        }
    }
    return result.sort((a, b) => a.distanceSq - b.distanceSq).map(a => a.tileID);
}

/**
 * The bounding box covering the entire extent of a tile.
 */
const EXTENT_BOUNDS = symbol_layout.Bounds.fromPoints([new symbol_layout.Point(0, 0), new symbol_layout.Point(symbol_layout.EXTENT, symbol_layout.EXTENT)]);

function isRasterType(type) {
    return type === 'raster' || type === 'image' || type === 'video';
}
/**
 * Designate fading bases and parents using a many-to-one relationship where the lower children fade in/out
 * with their parents. Raster shaders are not currently designed for a one-to-many fade relationship.
 *
 * Tiles that are candidates for fading out must be loaded and rendered tiles, as loading a tile to then
 * fade it out would not appear smoothly. The first source of truth for tile fading always starts at the
 * ideal tile, which continually changes on map adjustment. The state of the previously rendered ideal
 * tile plane indicates which direction to fade each part of the newer ideal plane (with varying z).
 *
 * For a pitched map, the back of the map can have decreasing zooms while the front can have increasing zooms.
 * Fade logic must therefore adapt dynamically based on the previously rendered ideal tile set.
 */
function updateFadingTiles(inViewTiles, idealTileIDs, retain, maxFadingAncestorLevels, sourceMinZoom, sourceMaxZoom, rasterFadeDuration) {
    const currentTime = now();
    const edgeTileIDs = symbol_layout.getEdgeTiles(idealTileIDs);
    for (const idealID of idealTileIDs) {
        const idealTile = inViewTiles.getTileById(idealID.key);
        // reset any previously departing(ed) tiles that are now ideal tiles
        if (idealTile.fadingDirection === FadingDirections.Departing || idealTile.fadeOpacity === 0) {
            idealTile.resetFadeLogic();
        }
        const parentIsFader = updateFadingAncestor(inViewTiles, idealTile, retain, currentTime, maxFadingAncestorLevels, sourceMinZoom, rasterFadeDuration);
        if (parentIsFader)
            continue;
        const childIsFader = updateFadingDescendents(inViewTiles, idealTile, retain, currentTime, sourceMaxZoom, rasterFadeDuration);
        if (childIsFader)
            continue;
        const edgeIsFader = updateFadingEdge(idealTile, edgeTileIDs, currentTime, rasterFadeDuration);
        if (edgeIsFader)
            continue;
        // for all remaining non-fading ideal tiles reset the fade logic
        idealTile.resetFadeLogic();
    }
}
/**
 * Many-to-one cross-fade. Set 4 ideal tiles as the fading base for a rendered parent tile
 * as the fading parent. Here the parent is fading out and the ideal tile is fading in.
 *
 * Parent tile - fading out                                ■                                -- Fading Parent
 *                                   ┌──────────────┬──────┴───────┬──────────────┐
 * Ideal tiles - fading in           ■              ■              ■              ■         -- Base Role = Incoming
 *                             ┌───┬─┴─┬───┐  ┌───┬─┴─┬───┐  ┌───┬─┴─┬───┐  ┌───┬─┴─┬───┐
 *                             ■   ■   ■   ■  ■   ■   ■   ■  ■   ■   ■   ■  ■   ■   ■   ■
 */
function updateFadingAncestor(inViewTiles, idealTile, retain, now, maxFadingAncestorLevels, sourceMinZoom, rasterFadeDuration) {
    if (!idealTile.hasData())
        return false;
    const { tileID: idealID, fadingRole, fadingDirection, fadingParentID } = idealTile;
    // ideal tile already has fading parent - retain and return
    if (fadingRole === FadingRoles.Base && fadingDirection === FadingDirections.Incoming && fadingParentID) {
        retain[fadingParentID.key] = fadingParentID;
        return true;
    }
    // find a loaded parent tile to fade with the ideal tile
    const minAncestorZ = Math.max(idealID.overscaledZ - maxFadingAncestorLevels, sourceMinZoom);
    for (let ancestorZ = idealID.overscaledZ - 1; ancestorZ >= minAncestorZ; ancestorZ--) {
        const ancestorID = idealID.scaledTo(ancestorZ);
        const ancestorTile = inViewTiles.getLoadedTile(ancestorID);
        if (!ancestorTile)
            continue;
        // ideal tile (base) is fading in
        idealTile.setCrossFadeLogic({
            fadingRole: FadingRoles.Base,
            fadingDirection: FadingDirections.Incoming,
            fadingParentID: ancestorTile.tileID, // fading out
            fadeEndTime: now + rasterFadeDuration
        });
        // ancestor tile (parent) is fading out
        ancestorTile.setCrossFadeLogic({
            fadingRole: FadingRoles.Parent,
            fadingDirection: FadingDirections.Departing,
            fadeEndTime: now + rasterFadeDuration
        });
        retain[ancestorID.key] = ancestorID;
        return true;
    }
    return false;
}
/**
 * Many-to-one cross-fade. Search descendents of ideal tiles as the fading base with the ideal tile
 * as the fading parent. Here the children are fading out and the ideal tile is fading in.
 *
 *                                                         ■
 *                                   ┌──────────────┬──────┴───────┬──────────────┐
 * Ideal tiles - fading in           ■              ■              ■              ■          -- Fading Parent
 *                             ┌───┬─┴─┬───┐  ┌───┬─┴─┬───┐  ┌───┬─┴─┬───┐  ┌───┬─┴─┬───┐
 * Child tiles - fading out    ■   ■   ■   ■  ■   ■   ■   ■  ■   ■   ■   ■  ■   ■   ■   ■    -- Base Role = Departing
 *
 * Try direct children first. If none found, try grandchildren. Stops at the first generation that provides a fader.
 */
function updateFadingDescendents(inViewTiles, idealTile, retain, now, sourceMaxZoom, rasterFadeDuration) {
    if (!idealTile.hasData())
        return false;
    // search first level of descendents (4 tiles)
    const idealChildren = idealTile.tileID.children(sourceMaxZoom);
    let hasFader = updateFadingChildren(inViewTiles, idealTile, idealChildren, retain, now, sourceMaxZoom, rasterFadeDuration);
    if (hasFader)
        return true;
    // search second level of descendents (16 tiles)
    for (const childID of idealChildren) {
        const grandChildIDs = childID.children(sourceMaxZoom);
        if (updateFadingChildren(inViewTiles, idealTile, grandChildIDs, retain, now, sourceMaxZoom, rasterFadeDuration)) {
            hasFader = true;
        }
    }
    return hasFader;
}
function updateFadingChildren(inViewTiles, idealTile, childIDs, retain, now, sourceMaxZoom, rasterFadeDuration) {
    if (childIDs[0].overscaledZ >= sourceMaxZoom)
        return false;
    let foundFader = false;
    // find loaded child tiles to fade with the ideal tile
    for (const childID of childIDs) {
        const childTile = inViewTiles.getLoadedTile(childID);
        if (!childTile)
            continue;
        const { fadingRole, fadingDirection, fadingParentID } = childTile;
        if (fadingRole !== FadingRoles.Base || fadingDirection !== FadingDirections.Departing || !fadingParentID) {
            // child tile (base) is fading out
            childTile.setCrossFadeLogic({
                fadingRole: FadingRoles.Base,
                fadingDirection: FadingDirections.Departing,
                fadingParentID: idealTile.tileID,
                fadeEndTime: now + rasterFadeDuration
            });
            // ideal tile (parent) is fading in
            idealTile.setCrossFadeLogic({
                fadingRole: FadingRoles.Parent,
                fadingDirection: FadingDirections.Incoming,
                fadeEndTime: now + rasterFadeDuration
            });
        }
        retain[childID.key] = childID;
        foundFader = true;
    }
    return foundFader;
}
/**
 * One-to-one self fading for unloaded edge tiles (for panning sideways on map). for loading tiles over gaps it feels
 * more natural for them to fade in, however if they are already loaded/cached then there is no need to fade as map will
 * look cohesive with no gaps. Note that draw_raster determines fade priority, as many-to-one fade supersedes edge fading.
 */
function updateFadingEdge(idealTile, edgeTileIDs, now, rasterFadeDuration) {
    const idealID = idealTile.tileID;
    // tile is already self fading
    if (idealTile.selfFading) {
        return true;
    }
    // fading not needed for tiles that are already loaded
    if (idealTile.hasData()) {
        return false;
    }
    // enable fading for loading edges with no data
    if (edgeTileIDs.has(idealID)) {
        const fadeEndTime = now + rasterFadeDuration;
        idealTile.setSelfFadeLogic(fadeEndTime);
        return true;
    }
    return false;
}
function hasRasterTransition(inViewTiles, rasterFadeDuration) {
    if (rasterFadeDuration <= 0) {
        return false;
    }
    const currentTime = now();
    for (const tile of inViewTiles.getAllTiles()) {
        if (tile.fadeEndTime >= currentTime) {
            return true;
        }
    }
    return false;
}

/**
 * For raster terrain source, backfill DEM to eliminate visible tile boundaries
 */
function backfillDEM(tile, inViewTiles) {
    var _a, _b, _c;
    const renderables = inViewTiles.getRenderableIds();
    for (const borderId of renderables) {
        if (!((_a = tile.neighboringTiles) === null || _a === void 0 ? void 0 : _a[borderId])) {
            continue;
        }
        const borderTile = inViewTiles.getTileById(borderId);
        if (!tile.neighboringTiles[borderId].backfilled) {
            fillBorder(tile, borderTile);
        }
        if ((_c = (_b = borderTile.neighboringTiles) === null || _b === void 0 ? void 0 : _b[tile.tileID.key]) === null || _c === void 0 ? void 0 : _c.backfilled) {
            continue;
        }
        fillBorder(borderTile, tile);
    }
}
function fillBorder(tile, borderTile) {
    var _a;
    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 ((_a = tile.neighboringTiles) === null || _a === void 0 ? void 0 : _a[borderId]) {
        tile.neighboringTiles[borderId].backfilled = true;
    }
}

class InViewTiles {
    constructor() {
        this._tiles = {};
    }
    handleWrapJump(wrapDelta) {
        const tiles = {};
        for (const id in this._tiles) {
            const tile = this._tiles[id];
            tile.tileID = tile.tileID.unwrapTo(tile.tileID.wrap + wrapDelta);
            tiles[tile.tileID.key] = tile;
        }
        this._tiles = tiles;
    }
    setFeatureState(featuresChanged, painter) {
        for (const id in this._tiles) {
            const tile = this._tiles[id];
            tile.setFeatureState(featuresChanged, painter);
        }
    }
    getAllTiles() {
        return Object.values(this._tiles);
    }
    getAllIds(sorted = false) {
        if (sorted) {
            return Object.values(this._tiles).map(tile => tile.tileID).sort(symbol_layout.compareTileId).map(id => id.key);
        }
        return Object.keys(this._tiles);
    }
    getTileById(key) {
        return this._tiles[key];
    }
    setTile(key, tile) {
        this._tiles[key] = tile;
    }
    deleteTileById(key) {
        delete this._tiles[key];
    }
    /**
     * Get a currently loaded tile.
     * - a cached tile is not a loaded tile
     * @returns the tile if it's in view and had data, null otherwise.
     */
    getLoadedTile(tileID) {
        const tile = this.getTileById(tileID.key);
        if (tile === null || tile === void 0 ? void 0 : tile.hasData()) {
            return tile;
        }
        return null;
    }
    isIdRenderable(id, symbolLayer = false) {
        var _a;
        return (_a = this.getTileById(id)) === null || _a === void 0 ? void 0 : _a.isRenderable(symbolLayer);
    }
    getRenderableIds(bearingInRadians = 0, symbolLayer) {
        const renderables = [];
        for (const id of this.getAllIds()) {
            if (this.isIdRenderable(id, symbolLayer)) {
                renderables.push(this.getTileById(id));
            }
        }
        if (symbolLayer) {
            return renderables.sort((a_, b_) => {
                const a = a_.tileID;
                const b = b_.tileID;
                const rotatedA = (new symbol_layout.Point(a.canonical.x, a.canonical.y))._rotate(-bearingInRadians);
                const rotatedB = (new symbol_layout.Point(b.canonical.x, b.canonical.y))._rotate(-bearingInRadians);
                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(symbol_layout.compareTileId).map(id => id.key);
    }
}

/**
 * @internal
 * `TileManager` is responsible for
 *
 *  - creating an instance of `Source`
 *  - caching tiles loaded from an instance of `Source`
 *  - handling incoming source data events events from `Map` and coordinating updates
 *  - providing the current renderable tile coordinates to the `Painter`
 *  - loading the tiles needed to render a given viewport
 *  - retaining the tiles needed as substitutes for pending loading tiles
 *  - retaining the tiles needed for fading between parents and children (for raster sources)
 *  - reloading tiles when source data or dependencies change
 *  - handling tile expiration and refresh timers
 *  - unloading cached tiles not needed to render a given viewport
 *  - managing tile state and feature state
 */
class TileManager extends symbol_layout.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._inViewTiles = new InViewTiles();
        this._outOfViewCache = new symbol_layout.TileCache(0, (tile) => this._unloadTile(tile));
        this._timers = {};
        this._maxTileCacheSize = null;
        this._maxTileCacheZoomLevels = null;
        this._rasterFadeDuration = 0;
        this._maxFadingAncestorLevels = 5;
        this._state = new SourceFeatureState();
        this._didEmitContent = false;
        this._updated = false;
    }
    onAdd(map) {
        var _a;
        this.map = map;
        this._maxTileCacheSize = map ? map._maxTileCacheSize : null;
        this._maxTileCacheZoomLevels = map ? map._maxTileCacheZoomLevels : null;
        if ((_a = this._source) === null || _a === void 0 ? void 0 : _a.onAdd) {
            this._source.onAdd(map);
        }
    }
    onRemove(map) {
        var _a;
        for (const tile of this._inViewTiles.getAllTiles()) {
            tile.unloadVectorData();
        }
        this.clearTiles();
        if ((_a = this._source) === null || _a === void 0 ? void 0 : _a.onRemove) {
            this._source.onRemove(map);
        }
        this._inViewTiles = new InViewTiles();
    }
    /**
     * 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 tile of this._inViewTiles.getAllTiles()) {
            if (tile.state !== 'loaded' && tile.state !== 'errored')
                return false;
        }
        return true;
    }
    getSource() {
        return this._source;
    }
    getState() {
        return this._state;
    }
    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 symbol_layout.__awaiter(this, void 0, void 0, function* () {
            try {
                const result = yield this._source.loadTile(tile);
                this._tileLoaded(tile, id, state, result);
            }
            catch (err) {
                tile.state = 'errored';
                if (err.status !== 404) {
                    this._source.fire(new symbol_layout.ErrorEvent(symbol_layout.ensureError(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 symbol_layout.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._inViewTiles, this.map ? this.map.painter : null);
        for (const tile of this._inViewTiles.getAllTiles()) {
            tile.upload(context);
            tile.prepare(this.map.style.imageManager);
        }
    }
    /**
     * Return all tile ids ordered with z-order, and cast to numbers
     */
    getIds() {
        return this._inViewTiles.getAllIds(true);
    }
    getRenderableIds(symbolLayer) {
        var _a;
        return this._inViewTiles.getRenderableIds((_a = this.transform) === null || _a === void 0 ? void 0 : _a.bearingInRadians, symbolLayer);
    }
    hasRenderableParent(tileID) {
        const parentZ = tileID.overscaledZ - 1;
        if (parentZ >= this._source.minzoom) {
            const parentTile = this.getLoadedTile(tileID.scaledTo(parentZ));
            if (parentTile) {
                return this._inViewTiles.isIdRenderable(parentTile.tileID.key);
            }
        }
        return false;
    }
    /**
     * Reload tiles based on the current state of the source.
     * @param sourceDataChanged - If `true`, reload all tiles using a state of 'expired', otherwise reload only non-errored tiles using state of 'reloading'.
     * @param shouldReloadTileOptions - Set of options associated with a `MapSourceDataChangedEvent` that can be passed back to the associated `Source` determine whether a tile should be reloaded.
     */
    reload(sourceDataChanged, shouldReloadTileOptions = undefined) {
        if (this._paused) {
            this._shouldReloadOnResume = true;
            return;
        }
        this._outOfViewCache.reset();
        for (const id of this._inViewTiles.getAllIds()) {
            const tile = this._inViewTiles.getTileById(id);
            if (shouldReloadTileOptions && !this._source.shouldReloadTile(tile, shouldReloadTileOptions)) {
                continue;
            }
            else if (sourceDataChanged) {
                this._reloadTile(id, 'expired');
            }
            else if (tile.state !== 'errored') {
                this._reloadTile(id, 'reloading');
            }
        }
    }
    _reloadTile(id, state) {
        return symbol_layout.__awaiter(this, void 0, void 0, function* () {
            const tile = this._inViewTiles.getTileById(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, result) {
        tile.timeAdded = now();
        // Since self-fading applies to unloaded tiles, fadeEndTime must be updated upon load
        if (tile.selfFading) {
            tile.fadeEndTime = tile.timeAdded + this._rasterFadeDuration;
        }
        if (previousState === 'expired')
            tile.refreshedUponExpiration = true;
        this._setTileReloadTimer(id, tile);
        if (result === null || result === void 0 ? void 0 : result.unmodified)
            return;
        if (this.getSource().type === 'raster-dem' && tile.dem) {
            backfillDEM(tile, this._inViewTiles);
        }
        this._state.initializeTileState(tile, this.map ? this.map.painter : null);
        if (!tile.aborted) {
            this._source.fire(new symbol_layout.Event('data', { dataType: 'source', tile, coord: tile.tileID }));
        }
    }
    /**
     * Get a specific tile by TileID
     */
    getTile(tileID) {
        return this.getTileByID(tileID.key);
    }
    /**
     * Get a specific tile by id
     */
    getTileByID(id) {
        return this._inViewTiles.getTileById(id);
    }
    /**
     * Retain the uppermost loaded children of each provided target tile, within a variable covering zoom range.
     *
     * On pitched maps, different parts of the screen show different zoom levels simultaneously.
     * Ideal tiles are generated using coveringTiles() above, which returns the ideal tile set for
     * the current pitched plane, which can carry tiles of varying zooms (overscaledZ).
     * See: https://maplibre.org/maplibre-gl-js/docs/examples/level-of-detail-control/
     *
     * A fixed `maxCoveringZoom` on a pitched map would incorrectly intersect with some
     * ideal tiles and cause distant high-pitch tiles to skip their uppermost children.
     *
     * To solve this, we calculate the max covering zoom for each ideal tile separately using its
     * `overscaledZ`. This effectively makes the "max covering zoom plane" parallel to the
     * "ideal tile plane," ensuring that we correctly capture the uppermost children
     * of each ideal tile across the pitched view.
     *
     * Analogy: imagine two sheets of paper in 3D space:
     *   - one sheet = ideal tiles at varying overscaledZ
     *   - the second sheet = maxCoveringZoom
     *
     * @param retainTileMap - this parameters will be updated with the child tiles to keep
     * @param idealTilesWithoutData - which of the ideal tiles currently does not have loaded data
     * @return a set of tiles that need to be loaded
     */
    _retainLoadedChildren(retainTileMap, idealTilesWithoutData) {
        const loadedDescendents = this._getLoadedDescendents(idealTilesWithoutData);
        const incomplete = new Set();
        // retain the uppermost descendents of target tiles
        for (const targetID of idealTilesWithoutData) {
            const descendents = loadedDescendents[targetID.key];
            if (!(descendents === null || descendents === void 0 ? void 0 : descendents.length)) {
                incomplete.add(targetID);
                continue;
            }
            // find descendents within the max covering zoom range
            const maxCoveringZoom = targetID.overscaledZ + TileManager.maxOverzooming;
            const candidates = descendents.filter(t => t.tileID.overscaledZ <= maxCoveringZoom);
            if (!candidates.length) {
                incomplete.add(targetID);
                continue;
            }
            // retain the uppermost descendents in the topmost zoom below the target tile
            const topZoom = Math.min(...candidates.map(t => t.tileID.overscaledZ));
            const topIDs = candidates.filter(t => t.tileID.overscaledZ === topZoom).map(t => t.tileID);
            for (const tileID of topIDs) {
                retainTileMap[tileID.key] = tileID;
            }
            //determine if the retained generation is fully covered
            if (!this._areDescendentsComplete(topIDs, topZoom, targetID.overscaledZ)) {
                incomplete.add(targetID);
            }
        }
        return incomplete;
    }
    /**
     * Return dictionary of qualified loaded descendents for each provided target tile id
     */
    _getLoadedDescendents(targetTileIDs) {
        var _a;
        const loadedDescendents = {};
        // enumerate current tiles and find the loaded descendents of each target tile
        for (const tile of this._inViewTiles.getAllTiles().filter(tile => tile.hasData())) {
            // determine if the loaded tile (hasData) is a qualified descendent of any target tile
            for (const targetID of targetTileIDs) {
                if (tile.tileID.isChildOf(targetID)) {
                    (loadedDescendents[_a = targetID.key] || (loadedDescendents[_a] = [])).push(tile);
                }
            }
        }
        return loadedDescendents;
    }
    /**
     * Determine if tile ids fully cover the current generation.
     * - 1st generation: need 4 children or 1 overscaled child
     * - 2nd generation: need 16 children or 1 overscaled child
     */
    _areDescendentsComplete(generationIDs, generationZ, ancestorZ) {
        //if overscaled, seeking 1 tile at generationZ, otherwise seeking a power of 4 for each descending Z
        if (generationIDs.length === 1 && generationIDs[0].isOverscaled()) {
            return generationIDs[0].overscaledZ === generationZ;
        }
        else {
            const expectedTiles = Math.pow(4, generationZ - ancestorZ); //4, 16, 64 (for first 3 gens)
            return expectedTiles === generationIDs.length;
        }
    }
    /**
     * Get a currently loaded tile.
     * - a cached tile is not a loaded tile
     * @returns the tile if it's in view and had data, null otherwise.
     */
    getLoadedTile(tileID) {
        return this._inViewTiles.getLoadedTile(tileID);
    }
    /**
     * 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 ?
            symbol_layout.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._outOfViewCache.setMaxSize(maxSize);
    }
    handleWrapJump(lng) {
        // On top of the regular z/x/y values, TileIDs have a `wrap` value that specify
        // which copy 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) {
            this._inViewTiles.handleWrapJump(wrapDelta);
            this._resetTileReloadTimers();
        }
    }
    /**
     * 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);
        let idealTileIDs;
        if (!this.used && !this.usedForTerrain) {
            idealTileIDs = [];
        }
        else if (this._source.tileID) { // image source
            idealTileIDs = transform.getVisibleUnwrappedCoordinates(this._source.tileID)
                .map((unwrapped) => new symbol_layout.OverscaledTileID(unwrapped.canonical.z, unwrapped.wrap, unwrapped.canonical.z, unwrapped.canonical.x, unwrapped.canonical.y));
        }
        else {
            idealTileIDs = coveringTiles(transform, {
                tileSize: this.usedForTerrain ? this.tileSize : this._source.tileSize,
                minzoom: this._source.minzoom,
                maxzoom: this._source.type === 'vector' && this.map._zoomLevelsToOverscale !== undefined
                    ? transform.maxZoom - this.map._zoomLevelsToOverscale
                    : this._source.maxzoom,
                roundZoom: this.usedForTerrain ? false : this._source.roundZoom,
                reparseOverscaled: this._source.reparseOverscaled,
                terrain,
                calculateTileZoom: this._source.calculateTileZoom,
            });
            if (this._source.hasTile) { // tile should be in bounds
                idealTileIDs = idealTileIDs.filter((coord) => this._source.hasTile(coord));
            }
        }
        // When tilemanager is used for terrain also load parent tiles for complete rendering of 3d terrain levels
        if (this.usedForTerrain) {
            idealTileIDs = this._addTerrainIdealTiles(idealTileIDs);
        }
        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 symbol_layout.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 zoom = coveringZoomLevel(transform, this._source);
        const retain = this._updateRetainedTiles(idealTileIDs, zoom);
        // enable fading for raster source except when using terrain which doesn't currently support fading
        const isRaster = isRasterType(this._source.type);
        if (isRaster && this._rasterFadeDuration > 0 && !terrain) {
            updateFadingTiles(this._inViewTiles, idealTileIDs, retain, this._maxFadingAncestorLevels, this._source.minzoom, this._source.maxzoom, this._rasterFadeDuration);
        }
        // clean up non-retained tiles that are no longer needed
        if (isRaster) {
            this._cleanUpRasterTiles(retain);
        }
        else {
            this._cleanUpVectorTiles(retain);
        }
    }
    /**
     * Remove raster tiles that are no longer retained
     */
    _cleanUpRasterTiles(retain) {
        for (const id of this._inViewTiles.getAllIds()) {
            if (!retain[id]) {
                this._removeTile(id);
            }
        }
    }
    /**
     * Remove vector tiles that are no longer retained and also not needed for symbol fading
     */
    _cleanUpVectorTiles(retain) {
        for (const id of this._inViewTiles.getAllIds()) {
            const tile = this._inViewTiles.getTileById(id);
            // retained - clear fade hold so if it's removed again fade timer starts fresh.
            if (retain[id]) {
                tile.clearSymbolFadeHold();
                continue;
            }
            // remove non-retained tiles without symbols
            if (!tile.hasSymbolBuckets) {
                this._removeTile(id);
                continue;
            }
            // for tile with symbols - hold for fade - then remove
            if (!tile.holdingForSymbolFade()) {
                tile.setSymbolHoldDuration(this.map._fadeDuration);
            }
            else if (tile.symbolFadeFinished()) {
                this._removeTile(id);
            }
        }
    }
    /**
     * Add ideal tiles needed for 3D terrain rendering
     */
    _addTerrainIdealTiles(idealTileIDs) {
        const ancestors = [];
        for (const tileID of idealTileIDs) {
            if (tileID.canonical.z > this._source.minzoom) {
                const parent = tileID.scaledTo(tileID.canonical.z - 1);
                ancestors.push(parent);
                // load very low zoom to calculate tile visibility in transform.coveringTiles and high zoom levels correct
                const parent2 = tileID.scaledTo(Math.max(this._source.minzoom, Math.min(tileID.canonical.z, 5)));
                ancestors.push(parent2);
            }
        }
        return idealTileIDs.concat(ancestors);
    }
    releaseSymbolFadeTiles() {
        for (const id of this._inViewTiles.getAllIds()) {
            if (this._inViewTiles.getTileById(id).holdingForSymbolFade()) {
                this._removeTile(id);
            }
        }
    }
    /**
     * Set tiles to be retained on update of the source. For ideal tiles that do not have data, retain their loaded
     * children so they can be displayed as substitutes pending load of each ideal tile (to reduce flickering).
     * If no loaded children are available, fallback to seeking loaded parents as an alternative substitute.
     */
    _updateRetainedTiles(idealTileIDs, zoom) {
        var _a;
        const idealTilesWithoutData = new Set();
        for (const idealID of idealTileIDs) {
            const idealTile = this._addTile(idealID);
            if (!idealTile.hasData()) {
                idealTilesWithoutData.add(idealID);
            }
        }
        // retain the tile even if it's not loaded because it's an ideal tile.
        const retainTileMap = idealTileIDs.reduce((acc, t) => { acc[t.key] = t; return acc; }, {});
        const tileIdsWithoutData = this._retainLoadedChildren(retainTileMap, idealTilesWithoutData);
        // for remaining missing tiles with incomplete child coverage, seek a loaded parent tile
        const checked = {};
        const minCoveringZoom = Math.max(zoom - TileManager.maxUnderzooming, this._source.minzoom);
        for (const tileID of tileIdsWithoutData) {
            let tile = this._inViewTiles.getTileById(tileID.key);
            // 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 === null || tile === void 0 ? void 0 : 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) {
                        retainTileMap[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 retainTileMap;
    }
    /**
     * Add a tile, given its coordinate, to the pyramid.
     */
    _addTile(tileID) {
        let tile = this._inViewTiles.getTileById(tileID.key);
        if (tile)
            return tile;
        tile = this._outOfViewCache.getAndRemove(tileID);
        if (tile) {
            //reset fading logic to remove stale fading data from cache
            tile.resetFadeLogic();
            // set timer for the reloading of the tile upon expiration
            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);
        }
        const cached = tile;
        if (!tile) {
            tile = new Tile(tileID, this._source.tileSize * tileID.overscaleFactor());
            this._loadTile(tile, tileID.key, tile.state);
        }
        tile.uses++;
        this._inViewTiles.setTile(tileID.key, tile);
        if (!cached) {
            this._source.fire(new symbol_layout.Event('dataloading', { tile, coord: tile.tileID, dataType: 'source' }));
        }
        return tile;
    }
    /**
     * Set a timeout to reload the tile after it expires
     */
    _setTileReloadTimer(id, tile) {
        this._clearTileReloadTimer(id);
        const expiryTimeout = tile.getExpiryTimeout();
        if (expiryTimeout) {
            const reload = () => {
                this._reloadTile(id, 'expired');
                delete this._timers[id];
            };
            this._timers[id] = setTimeout(reload, expiryTimeout);
        }
    }
    _clearTileReloadTimer(id) {
        const timeout = this._timers[id];
        if (timeout) {
            clearTimeout(timeout);
            delete this._timers[id];
        }
    }
    _resetTileReloadTimers() {
        for (const id in this._timers) {
            clearTimeout(this._timers[id]);
            delete this._timers[id];
        }
        for (const id of this._inViewTiles.getAllIds()) {
            const tile = this._inViewTiles.getTileById(id);
            this._setTileReloadTimer(id, tile);
        }
    }
    /**
     * Reload any currently renderable tiles that are match one of the incoming `tileId` x/y/z
     */
    refreshTiles(tileIds) {
        for (const id of this._inViewTiles.getAllIds()) {
            const tile = this._inViewTiles.getTileById(id);
            if (!this._inViewTiles.isIdRenderable(id) && tile.state != 'errored') {
                continue;
            }
            if (tileIds.some(tid => tid.equals(tile.tileID.canonical))) {
                this._reloadTile(id, 'expired');
            }
        }
    }
    /**
     * Remove a tile, given its id, from the pyramid
     */
    _removeTile(id) {
        const tile = this._inViewTiles.getTileById(id);
        if (!tile)
            return;
        tile.uses--;
        this._inViewTiles.deleteTileById(id);
        this._clearTileReloadTimer(id);
        if (tile.uses > 0)
            return;
        if (tile.hasData() && tile.state !== 'reloading') {
            this._outOfViewCache.add(tile.tileID, tile, tile.getExpiryTimeout());
        }
        else {
            tile.aborted = true;
            this._abortTile(tile);
            this._unloadTile(tile);
        }
    }
    /** @internal
     * Handles incoming source data messages (i.e. after the source has been updated via a worker that has fired
     * to map.ts data event). For sources with mutable data, the 'content' event fires when the underlying data
     * to a source has changed. (i.e. GeoJSONSource.setData and ImageSource.setCoordinates)
     */
    _dataHandler(e) {
        if (e.dataType !== 'source')
            return;
        if (e.sourceDataType === 'metadata') {
            this._sourceLoaded = true;
            return;
        }
        if (e.sourceDataType !== 'content' || !this._sourceLoaded || this._paused) {
            return;
        }
        this.reload(e.sourceDataChanged, e.shouldReloadTileOptions);
        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 of this._inViewTiles.getAllIds()) {
            this._removeTile(id);
        }
        this._outOfViewCache.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 allowWorldCopies = transform.getCoveringTilesDetailsProvider().allowWorldCopies();
        const cameraPointQueryGeometry = has3DLayer ?
            transform.getCameraQueryGeometry(pointQueryGeometry) :
            pointQueryGeometry;
        const project = (point) => transform.screenPointToMercatorCoordinate(point, this.terrain);
        const queryGeometry = this.transformBbox(pointQueryGeometry, project, !allowWorldCopies);
        const cameraQueryGeometry = this.transformBbox(cameraPointQueryGeometry, project, !allowWorldCopies);
        const ids = this.getIds();
        const cameraBounds = symbol_layout.Bounds.fromPoints(cameraQueryGeometry);
        for (const id of ids) {
            const tile = this._inViewTiles.getTileById(id);
            if (tile.holdingForSymbolFade()) {
                // Tiles held for fading are covered by tiles that are closer to ideal
                continue;
            }
            // if the projection does not render world copies then we need to explicitly check for the bounding box crossing the antimeridian
            const tileIDs = allowWorldCopies ? [tile.tileID] : [tile.tileID.unwrapTo(-1), tile.tileID.unwrapTo(0)];
            const scale = Math.pow(2, transform.zoom - tile.tileID.overscaledZ);
            const queryPadding = maxPitchScaleFactor * tile.queryPadding * symbol_layout.EXTENT / tile.tileSize / scale;
            for (const tileID of tileIDs) {
                const tileSpaceBounds = cameraBounds.map(point => tileID.getTilePoint(new symbol_layout.MercatorCoordinate(point.x, point.y)));
                tileSpaceBounds.expandBy(queryPadding);
                if (tileSpaceBounds.intersects(EXTENT_BOUNDS)) {
                    const tileSpaceQueryGeometry = queryGeometry.map((c) => tileID.getTilePoint(c));
                    const tileSpaceCameraQueryGeometry = cameraQueryGeometry.map((c) => tileID.getTilePoint(c));
                    tileResults.push({
                        tile,
                        tileID: allowWorldCopies ? tileID : tileID.unwrapTo(0),
                        queryGeometry: tileSpaceQueryGeometry,
                        cameraQueryGeometry: tileSpaceCameraQueryGeometry,
                        scale
                    });
                }
            }
        }
        return tileResults;
    }
    transformBbox(geom, project, checkWrap) {
        let transformed = geom.map(project);
        if (checkWrap) {
            // If the projection does not allow world copies, then a bounding box may span the antimeridian and
            // instead of a bounding box going from 179°E to 179°W, it goes from 179°W to 179°E and covers the entire
            // planet except for what should be inside it.
            const bounds = symbol_layout.Bounds.fromPoints(geom);
            bounds.shrinkBy(Math.min(bounds.width(), bounds.height()) * 0.001);
            const projected = bounds.map(project);
            const newBounds = symbol_layout.Bounds.fromPoints(transformed);
            if (!newBounds.covers(projected)) {
                transformed = transformed.map((coord) => coord.x > 0.5 ?
                    new symbol_layout.MercatorCoordinate(coord.x - 1, coord.y, coord.z) :
                    coord);
            }
        }
        return transformed;
    }
    getVisibleCoordinates(symbolLayer) {
        const coords = this.getRenderableIds(symbolLayer).map((id) => this._inViewTiles.getTileById(id).tileID);
        if (this.transform) {
            this.transform.populateCache(coords);
        }
        return coords;
    }
    hasTransition() {
        if (this._source.hasTransition()) {
            return true;
        }
        return isRasterType(this._source.type) && hasRasterTransition(this._inViewTiles, this._rasterFadeDuration);
    }
    setRasterFadeDuration(fadeDuration) {
        this._rasterFadeDuration = fadeDuration;
    }
    /**
     * Set the value of a particular state for a feature
     */
    setFeatureState(sourceLayer, featureId, state) {
        sourceLayer = sourceLayer || symbol_layout.GEOJSON_TILE_LAYER_NAME;
        this._state.updateState(sourceLayer, featureId, state);
    }
    /**
     * Resets the value of a particular state key for a feature
     */
    removeFeatureState(sourceLayer, featureId, key) {
        sourceLayer = sourceLayer || symbol_layout.GEOJSON_TILE_LAYER_NAME;
        this._state.removeFeatureState(sourceLayer, featureId, key);
    }
    /**
     * Get the entire state object for a feature
     */
    getFeatureState(sourceLayer, featureId) {
        sourceLayer = sourceLayer || symbol_layout.GEOJSON_TILE_LAYER_NAME;
        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._inViewTiles.getTileById(tileKey);
        if (tile) {
            tile.setDependencies(namespace, dependencies);
        }
    }
    /**
     * Reloads all tiles that depend on the given keys.
     */
    reloadTilesForDependencies(namespaces, keys) {
        for (const id of this._inViewTiles.getAllIds()) {
            const tile = this._inViewTiles.getTileById(id);
            if (tile.hasDependency(namespaces, keys)) {
                this._reloadTile(id, 'reloading');
            }
        }
        this._outOfViewCache.filter(tile => !tile.hasDependency(namespaces, keys));
    }
    areTilesLoaded() {
        for (const tile of this._inViewTiles.getAllTiles()) {
            if (!(tile.state === 'loaded' || tile.state === 'errored')) {
                return false;
            }
        }
        return true;
    }
}
TileManager.maxUnderzooming = 10;
TileManager.maxOverzooming = 3;

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 = symbol_layout.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];
        // Use a small epsilon to account for floating-point imprecision
        // when collision box boundaries are computed via different
        // projection paths (different tiles/sources) but should
        // mathematically produce the same boundary value.
        const epsilon = 1e-6;
        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] + epsilon) &&
                        (y1 <= bboxes[offset + 3] + epsilon) &&
                        (x2 >= bboxes[offset + 0] - epsilon) &&
                        (y2 >= bboxes[offset + 1] - epsilon) &&
                        (!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.
 *
 *
 * # Custom projection handling
 * Note that since MapLibre now supports more than one projection, the transformation
 * to viewport pixel space and GL clip space now *must* go through the projection's (`transform`'s)
 * `projectTileCoordinates` function, since it might do nontrivial transformations.
 *
 * Hence projecting anything to a symbol's label plane can no longer be handled by a simple matrix,
 * since, if the symbol's label plane is viewport pixel space, `projectTileCoordinates` must be used.
 * This is applies both here and in the symbol vertex shaders.
 */
function getPitchedLabelPlaneMatrix(rotateWithMap, transform, pixelsToTileUnits) {
    const m = symbol_layout.create();
    if (!rotateWithMap) {
        const { vecSouth, vecEast } = getTileSkewVectors(transform);
        const skew = symbol_layout.create$1();
        skew[0] = vecEast[0];
        skew[1] = vecEast[1];
        skew[2] = vecSouth[0];
        skew[3] = vecSouth[1];
        symbol_layout.invert(skew, skew);
        m[0] = skew[0];
        m[1] = skew[1];
        m[4] = skew[2];
        m[5] = skew[3];
    }
    symbol_layout.scale(m, m, [1 / pixelsToTileUnits, 1 / pixelsToTileUnits, 1]);
    return m;
}
/*
 * Returns a matrix for either converting from pitched label space to tile space,
 * or for converting from screenspace pixels to clip space.
 */
function getGlCoordMatrix(pitchWithMap, rotateWithMap, transform, pixelsToTileUnits) {
    if (pitchWithMap) {
        const m = symbol_layout.create();
        if (!rotateWithMap) {
            const { vecSouth, vecEast } = getTileSkewVectors(transform);
            m[0] = vecEast[0];
            m[1] = vecEast[1];
            m[4] = vecSouth[0];
            m[5] = vecSouth[1];
        }
        symbol_layout.scale(m, m, [pixelsToTileUnits, pixelsToTileUnits, 1]);
        return m;
    }
    else {
        return transform.pixelsToClipSpaceMatrix;
    }
}
function getTileSkewVectors(transform) {
    const cosRoll = Math.cos(transform.rollInRadians);
    const sinRoll = Math.sin(transform.rollInRadians);
    const cosPitch = Math.cos(transform.pitchInRadians);
    const cosBearing = Math.cos(transform.bearingInRadians);
    const sinBearing = Math.sin(transform.bearingInRadians);
    const vecSouth = symbol_layout.create$2();
    vecSouth[0] = -cosBearing * cosPitch * sinRoll - sinBearing * cosRoll;
    vecSouth[1] = -sinBearing * cosPitch * sinRoll + cosBearing * cosRoll;
    const vecSouthLen = symbol_layout.length(vecSouth);
    if (vecSouthLen < 1.0e-9) {
        symbol_layout.zero(vecSouth);
    }
    else {
        symbol_layout.scale$1(vecSouth, vecSouth, 1 / vecSouthLen);
    }
    const vecEast = symbol_layout.create$2();
    vecEast[0] = cosBearing * cosPitch * cosRoll - sinBearing * sinRoll;
    vecEast[1] = sinBearing * cosPitch * cosRoll + cosBearing * sinRoll;
    const vecEastLen = symbol_layout.length(vecEast);
    if (vecEastLen < 1.0e-9) {
        symbol_layout.zero(vecEast);
    }
    else {
        symbol_layout.scale$1(vecEast, vecEast, 1 / vecEastLen);
    }
    return { vecEast, vecSouth };
}
/**
 * Projects a point using a specified matrix, including the perspective divide.
 * Uses a fast path if `getElevation` is undefined.
 */
function projectWithMatrix(x, y, matrix, getElevation) {
    let pos;
    if (getElevation) { // slow because of handle z-index
        pos = [x, y, getElevation(x, y), 1];
        symbol_layout.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 symbol_layout.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, painter, isText, pitchedLabelPlaneMatrix, pitchedLabelPlaneMatrixInverse, pitchWithMap, keepUpright, rotateToLine, unwrappedTileID, viewportWidth, viewportHeight, translation, getElevation) {
    const sizeData = isText ? bucket.textSizeData : bucket.iconSizeData;
    const partiallyEvaluatedSize = symbol_layout.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 === symbol_layout.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 tileAnchorPoint = new symbol_layout.Point(symbol.anchorX, symbol.anchorY);
        const projectionCache = { projections: {}, offsets: {}, cachedAnchorPoint: undefined, anyProjectionOccluded: false };
        const projectionContext = {
            getElevation,
            pitchedLabelPlaneMatrix,
            lineVertexArray,
            pitchWithMap,
            projectionCache,
            transform: painter.transform,
            tileAnchorPoint,
            unwrappedTileID,
            width: viewportWidth,
            height: viewportHeight,
            translation
        };
        const anchorPos = projectTileCoordinatesToClipSpace(symbol.anchorX, symbol.anchorY, projectionContext);
        // 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 = symbol_layout.evaluateSizeForFeature(sizeData, partiallyEvaluatedSize, symbol);
        const pitchScaledFontSize = pitchWithMap ? (fontSize * painter.transform.getPitchedTextCorrection(symbol.anchorX, symbol.anchorY, unwrappedTileID) / perspectiveRatio) : fontSize * perspectiveRatio;
        const placeUnflipped = placeGlyphsAlongLine({
            projectionContext,
            pitchedLabelPlaneMatrixInverse,
            symbol,
            fontSize: pitchScaledFontSize,
            flip: false,
            keepUpright,
            glyphOffsetArray: bucket.glyphOffsetArray,
            dynamicLayoutVertexArray,
            aspectRatio,
            rotateToLine,
        });
        useVertical = placeUnflipped.useVertical;
        if (placeUnflipped.notEnoughRoom || useVertical ||
            (placeUnflipped.needsFlipping &&
                placeGlyphsAlongLine({
                    projectionContext,
                    pitchedLabelPlaneMatrixInverse,
                    symbol,
                    fontSize: pitchScaledFontSize,
                    flip: true, // flipped
                    keepUpright,
                    glyphOffsetArray: 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 === symbol_layout.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 === symbol_layout.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(args) {
    const { projectionContext, pitchedLabelPlaneMatrixInverse, symbol, fontSize, flip, keepUpright, glyphOffsetArray, dynamicLayoutVertexArray, aspectRatio, rotateToLine } = args;
    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
        // Note: these glyphs are placed onto the label plane
        const firstAndLastGlyph = placeFirstAndLastGlyph(fontScale, glyphOffsetArray, lineOffsetX, lineOffsetY, flip, symbol, rotateToLine, projectionContext);
        if (!firstAndLastGlyph) {
            return { notEnoughRoom: true };
        }
        const firstPoint = projectFromLabelPlaneToClipSpace(firstAndLastGlyph.first.point.x, firstAndLastGlyph.first.point.y, projectionContext, pitchedLabelPlaneMatrixInverse);
        const lastPoint = projectFromLabelPlaneToClipSpace(firstAndLastGlyph.last.point.x, firstAndLastGlyph.last.point.y, projectionContext, pitchedLabelPlaneMatrixInverse);
        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, try placing the rest of the glyphs.
            const placedGlyph = placeGlyphAlongLine(fontScale * glyphOffsetArray.getoffsetX(glyphIndex), lineOffsetX, lineOffsetY, flip, symbol.segment, lineStartIndex, lineEndIndex, projectionContext, rotateToLine);
            if (!placedGlyph) {
                return { notEnoughRoom: true };
            }
            placedGlyphs.push(placedGlyph);
        }
        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 = projectTileCoordinatesToLabelPlane(projectionContext.tileAnchorPoint.x, projectionContext.tileAnchorPoint.y, projectionContext).point;
            const tileVertexIndex = (symbol.lineStartIndex + symbol.segment + 1);
            const tileSegmentEnd = new symbol_layout.Point(projectionContext.lineVertexArray.getx(tileVertexIndex), projectionContext.lineVertexArray.gety(tileVertexIndex));
            const projectedVertex = projectTileCoordinatesToLabelPlane(tileSegmentEnd.x, tileSegmentEnd.y, projectionContext);
            // 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, projectionContext);
            const clipSpaceA = projectFromLabelPlaneToClipSpace(a.x, a.y, projectionContext, pitchedLabelPlaneMatrixInverse);
            const clipSpaceB = projectFromLabelPlaneToClipSpace(b.x, b.y, projectionContext, pitchedLabelPlaneMatrixInverse);
            const orientationChange = requiresOrientationChange(symbol.writingMode, clipSpaceA, clipSpaceB, 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) {
        symbol_layout.addDynamicAttributes(dynamicLayoutVertexArray, glyph.point, glyph.angle);
    }
    return {};
}
/**
 * Takes a line and direction from `previousTilePoint` to `currentTilePoint`, projects it to the correct label plane,
 * and returns a projected point along this projected line that is `minimumLength` distance away from `previousProjectedPoint`.
 * Projects a "virtual" vertex along a line segment.
 * @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 projectionContext - Projection context, used to get terrain's `getElevation`, and to project the points to screen pixels.
 */
function projectTruncatedLineSegmentToLabelPlane(previousTilePoint, currentTilePoint, previousProjectedPoint, minimumLength, 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 = projectTileCoordinatesToLabelPlane(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 projectLineVertexToLabelPlane(index, projectionContext, syntheticVertexArgs) {
    const cache = projectionContext.projectionCache;
    if (cache.projections[index]) {
        return cache.projections[index];
    }
    const currentVertex = new symbol_layout.Point(projectionContext.lineVertexArray.getx(index), projectionContext.lineVertexArray.gety(index));
    const projection = projectTileCoordinatesToLabelPlane(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 symbol_layout.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 projectTruncatedLineSegmentToLabelPlane(previousTilePoint, currentVertex, syntheticVertexArgs.previousVertex, minimumLength, projectionContext);
}
/**
 * Projects the given point in tile coordinates to the correct label plane.
 * If pitchWithMap is true, the (rotated) map plane in pixels is used,
 * otherwise screen pixels are used.
 */
function projectTileCoordinatesToLabelPlane(x, y, projectionContext) {
    const translatedX = x + projectionContext.translation[0];
    const translatedY = y + projectionContext.translation[1];
    let projection;
    if (projectionContext.pitchWithMap) {
        projection = projectWithMatrix(translatedX, translatedY, projectionContext.pitchedLabelPlaneMatrix, projectionContext.getElevation);
        projection.isOccluded = false;
    }
    else {
        projection = projectionContext.transform.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;
    }
    return projection;
}
function projectFromLabelPlaneToClipSpace(x, y, projectionContext, pitchedLabelPlaneMatrixInverse) {
    if (projectionContext.pitchWithMap) {
        const pos = [x, y, 0, 1];
        symbol_layout.transformMat4(pos, pos, pitchedLabelPlaneMatrixInverse);
        return projectionContext.transform.projectTileCoordinates(pos[0] / pos[3], pos[1] / pos[3], projectionContext.unwrappedTileID, projectionContext.getElevation).point;
    }
    else {
        return {
            x: (x / projectionContext.width) * 2.0 - 1.0,
            y: 1.0 - (y / projectionContext.height) * 2.0
        };
    }
}
/**
 * Projects the given point in tile coordinates to the GL clip space (-1..1).
 */
function projectTileCoordinatesToClipSpace(x, y, projectionContext) {
    const projection = projectionContext.transform.projectTileCoordinates(x, y, projectionContext.unwrappedTileID, projectionContext.getElevation);
    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 = projectLineVertexToLabelPlane(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] = symbol_layout.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 viewport and cache it
    let anchorPoint;
    if (projectionContext.projectionCache.cachedAnchorPoint) {
        anchorPoint = projectionContext.projectionCache.cachedAnchorPoint;
    }
    else {
        anchorPoint = projectTileCoordinatesToLabelPlane(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 = projectLineVertexToLabelPlane(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 = projectLineVertexToLabelPlane(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;
}
/**
 * Takes a path of points that was previously projected using the `pitchedLabelPlaneMatrix`
 * and projects it using the map projection's (mercator/globe...) `projectTileCoordinates` function.
 * Returns a new array of the projected points.
 * Does not modify the input array.
 */
function projectPathSpecialProjection(projectedPath, projectionContext) {
    const inverseLabelPlaneMatrix = symbol_layout.create();
    symbol_layout.invert$1(inverseLabelPlaneMatrix, projectionContext.pitchedLabelPlaneMatrix);
    return projectedPath.map(p => {
        const backProjected = projectWithMatrix(p.x, p.y, inverseLabelPlaneMatrix, projectionContext.getElevation);
        const projected = projectionContext.transform.projectTileCoordinates(backProjected.point.x, backProjected.point.y, projectionContext.unwrappedTileID, projectionContext.getElevation);
        projected.point.x = (projected.point.x * 0.5 + 0.5) * projectionContext.width;
        projected.point.y = (-projected.point.y * 0.5 + 0.5) * projectionContext.height;
        return projected;
    });
}
/**
 * Takes a path of points projected to screenspace, finds the longest continuous unoccluded segment of that path
 * and returns it.
 * Does not modify the input array.
 */
function pathSlicedToLongestUnoccluded(path) {
    let longestUnoccludedStart = 0;
    let longestUnoccludedLength = 0;
    let currentUnoccludedStart = 0;
    let currentUnoccludedLength = 0;
    for (let i = 0; i < path.length; i++) {
        if (path[i].isOccluded) {
            currentUnoccludedStart = i + 1;
            currentUnoccludedLength = 0;
        }
        else {
            currentUnoccludedLength++;
            if (currentUnoccludedLength > longestUnoccludedLength) {
                longestUnoccludedLength = currentUnoccludedLength;
                longestUnoccludedStart = currentUnoccludedStart;
            }
        }
    }
    return path.slice(longestUnoccludedStart, longestUnoccludedStart + longestUnoccludedLength);
}

// 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, 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.grid = grid;
        this.ignoredGrid = ignoredGrid;
        this.pitchFactor = Math.cos(transform.pitch * Math.PI / 180.0) * 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, tileID, unwrappedTileID, pitchWithMap, rotateWithMap, translation, collisionGroupPredicate, getElevation, shift, simpleProjectionMatrix) {
        const x = collisionBox.anchorPointX + translation[0];
        const y = collisionBox.anchorPointY + translation[1];
        const projectedPoint = this.projectAndGetPerspectiveRatio(x, y, unwrappedTileID, getElevation, simpleProjectionMatrix);
        const tileToViewport = textPixelRatio * projectedPoint.perspectiveRatio;
        let projectedBox;
        if (!pitchWithMap && !rotateWithMap) {
            // Fast path for common symbols
            const pointX = projectedPoint.x + (shift ? shift.x * tileToViewport : 0);
            const pointY = projectedPoint.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, tileID, unwrappedTileID, pitchWithMap, rotateWithMap, translation, projectedPoint, getElevation, shift, simpleProjectionMatrix);
        }
        const [tlX, tlY, brX, brY] = projectedBox.box;
        // Conditions are ordered from the fastest to evaluate to the slowest.
        const occluded = pitchWithMap ? projectedBox.allPointsOccluded : projectedPoint.isOccluded;
        let unplaceable = occluded;
        unplaceable || (unplaceable = projectedPoint.perspectiveRatio < this.perspectiveRatioCutoff);
        unplaceable || (unplaceable = !this.isInsideGrid(tlX, tlY, brX, brY));
        if (unplaceable ||
            (overlapMode !== 'always' && this.grid.hitTest(tlX, tlY, brX, brY, overlapMode, collisionGroupPredicate))) {
            return {
                box: [tlX, tlY, brX, brY],
                placeable: false,
                offscreen: false,
                occluded
            };
        }
        return {
            box: [tlX, tlY, brX, brY],
            placeable: true,
            offscreen: this.isOffscreen(tlX, tlY, brX, brY),
            occluded
        };
    }
    placeCollisionCircles(overlapMode, symbol, lineVertexArray, glyphOffsetArray, fontSize, unwrappedTileID, pitchedLabelPlaneMatrix, showCollisionCircles, pitchWithMap, collisionGroupPredicate, circlePixelDiameter, textPixelPadding, translation, getElevation) {
        const placedCollisionCircles = [];
        const tileUnitAnchorPoint = new symbol_layout.Point(symbol.anchorX, symbol.anchorY);
        const perspectiveRatio = this.getPerspectiveRatio(tileUnitAnchorPoint.x, tileUnitAnchorPoint.y, unwrappedTileID, getElevation);
        const labelPlaneFontSize = pitchWithMap ? (fontSize * this.transform.getPitchedTextCorrection(symbol.anchorX, symbol.anchorY, unwrappedTileID) / perspectiveRatio) : fontSize * perspectiveRatio;
        const labelPlaneFontScale = labelPlaneFontSize / symbol_layout.ONE_EM;
        const projectionCache = { projections: {}, offsets: {}, cachedAnchorPoint: undefined, anyProjectionOccluded: false };
        const lineOffsetX = symbol.lineOffsetX * labelPlaneFontScale;
        const lineOffsetY = symbol.lineOffsetY * labelPlaneFontScale;
        const projectionContext = {
            getElevation,
            pitchedLabelPlaneMatrix,
            lineVertexArray,
            pitchWithMap,
            projectionCache,
            transform: this.transform,
            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 symbol_layout.Point(-viewportPadding, -viewportPadding);
            const screenPlaneMax = new symbol_layout.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 (pitchWithMap) {
                const screenSpacePath = this.projectPathToScreenSpace(projectedPath, projectionContext);
                // 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 = symbol_layout.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) {
        const screenSpacePath = projectPathSpecialProjection(projectedPath, projectionContext);
        // We don't want to generate screenspace collision circles for parts of the line that
        // are occluded by the planet itself. Find the longest segment of the path that is
        // not occluded, and remove everything else.
        return pathSlicedToLongestUnoccluded(screenSpacePath);
    }
    /**
     * 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 = [];
        const bounds = new symbol_layout.Bounds();
        for (const point of viewportQueryGeometry) {
            const gridPoint = new symbol_layout.Point(point.x + viewportPadding, point.y + viewportPadding);
            bounds.extend(gridPoint);
            query.push(gridPoint);
        }
        const { minX, minY, maxX, maxY } = bounds;
        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 symbol_layout.Point(feature.x1, feature.y1),
                new symbol_layout.Point(feature.x2, feature.y1),
                new symbol_layout.Point(feature.x2, feature.y2),
                new symbol_layout.Point(feature.x1, feature.y2)
            ];
            if (!symbol_layout.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(x, y, unwrappedTileID, getElevation, simpleProjectionMatrix) {
        if (simpleProjectionMatrix) {
            // This branch is a fast-path for mercator transform.
            // The code here is a copy of MercatorTransform.projectTileCoordinates, slightly modified for extra performance.
            // This has a huge impact for some reason.
            let pos;
            if (getElevation) { // slow because of handle z-index
                pos = [x, y, getElevation(x, y), 1];
                symbol_layout.transformMat4(pos, pos, simpleProjectionMatrix);
            }
            else { // fast because of ignore z-index
                pos = [x, y, 0, 1];
                xyTransformMat4(pos, pos, simpleProjectionMatrix);
            }
            const w = pos[3];
            return {
                x: (((pos[0] / w + 1) / 2) * this.transform.width) + viewportPadding,
                y: (((-pos[1] / w + 1) / 2) * this.transform.height) + viewportPadding,
                perspectiveRatio: 0.5 + 0.5 * (this.transform.cameraToCenterDistance / w),
                isOccluded: false,
                signedDistanceFromCamera: w
            };
        }
        else {
            const projected = this.transform.projectTileCoordinates(x, y, unwrappedTileID, getElevation);
            return {
                x: (((projected.point.x + 1) / 2) * this.transform.width) + viewportPadding,
                y: (((-projected.point.y + 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 / projected.signedDistanceFromCamera),
                isOccluded: projected.isOccluded,
                signedDistanceFromCamera: projected.signedDistanceFromCamera
            };
        }
    }
    getPerspectiveRatio(x, y, unwrappedTileID, getElevation) {
        // We don't care about the actual projected point, just its W component.
        const projected = this.transform.projectTileCoordinates(x, y, unwrappedTileID, 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 = symbol_layout.identity([]);
        symbol_layout.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, tileID, unwrappedTileID, pitchWithMap, rotateWithMap, translation, projectedPoint, getElevation, shift, simpleProjectionMatrix) {
        // These vectors are valid both for screen space viewport-rotation-aligned texts and for pitch-align: map texts that are map-rotation-aligned.
        let vecEastX = 1;
        let vecEastY = 0;
        let vecSouthX = 0;
        let vecSouthY = 1;
        const translatedAnchorX = collisionBox.anchorPointX + translation[0];
        const translatedAnchorY = collisionBox.anchorPointY + translation[1];
        if (rotateWithMap && !pitchWithMap) {
            // Handles screen space texts that are always aligned east-west.
            const projectedEast = this.projectAndGetPerspectiveRatio(translatedAnchorX + 1, translatedAnchorY, unwrappedTileID, getElevation, simpleProjectionMatrix);
            const toEastX = projectedEast.x - projectedPoint.x;
            const toEastY = projectedEast.y - projectedPoint.y;
            const angle = Math.atan(toEastY / toEastX) + (toEastX < 0 ? Math.PI : 0);
            const sin = Math.sin(angle);
            const cos = Math.cos(angle);
            vecEastX = cos;
            vecEastY = sin;
            vecSouthX = -sin;
            vecSouthY = cos;
        }
        else if (!rotateWithMap && pitchWithMap) {
            // Handles pitch-align: map texts that are always aligned with the viewport's X axis.
            const skew = getTileSkewVectors(this.transform);
            vecEastX = skew.vecEast[0];
            vecEastY = skew.vecEast[1];
            vecSouthX = skew.vecSouth[0];
            vecSouthY = skew.vecSouth[1];
        }
        // Configuration for screen space offsets
        let basePointX = projectedPoint.x;
        let basePointY = projectedPoint.y;
        let distanceMultiplier = tileToViewport;
        if (pitchWithMap) {
            // Configuration for tile space (map-pitch-aligned) offsets
            basePointX = translatedAnchorX;
            basePointY = translatedAnchorY;
            const zoomFraction = this.transform.zoom - tileID.overscaledZ;
            distanceMultiplier = Math.pow(2, -zoomFraction);
            distanceMultiplier *= this.transform.getPitchedTextCorrection(translatedAnchorX, translatedAnchorY, 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 = symbol_layout.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
            basePointX += vecEastX * shift.x * distanceMultiplier + vecSouthX * shift.y * distanceMultiplier;
            basePointY += vecEastY * shift.x * distanceMultiplier + vecSouthY * 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 symbol_layout.Point(basePointX + vecEastX * offsetX + vecSouthX * offsetY, basePointY + vecEastY * offsetX + vecSouthY * 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(p.x, p.y, unwrappedTileID, getElevation, simpleProjectionMatrix));
            // Is at least one of the projected points NOT behind the horizon?
            anyPointVisible = projected.some(p => !p.isOccluded);
            points = projected.map(p => new symbol_layout.Point(p.x, p.y));
        }
        else {
            // Labels that are not pitchWithMap cannot ever hide behind the horizon.
            anyPointVisible = true;
        }
        return {
            box: symbol_layout.getAABB(points),
            allPointsOccluded: !anyPointVisible
        };
    }
}

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 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 } = symbol_layout.getAnchorAlignment(anchor);
    const shiftX = -(horizontalAlign - 0.5) * width;
    const shiftY = -(verticalAlign - 0.5) * height;
    return new symbol_layout.Point(shiftX + textOffset[0] * textBoxScale, shiftY + textOffset[1] * textBoxScale);
}
class Placement {
    constructor(transform, terrain, fadeDuration, crossSourceCollisions, prevPlacement) {
        this.transform = transform.clone();
        this.terrain = terrain;
        this.collisionIndex = new CollisionIndex(this.transform);
        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;
        if (!terrain)
            return null;
        return (x, y) => terrain.getElevation(tileID, x, y);
    }
    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 / symbol_layout.EXTENT;
        const unwrappedTileID = tile.tileID.toUnwrapped();
        const rotateWithMap = layout.get('text-rotation-alignment') === 'map';
        const pixelsToTiles = symbol_layout.pixelsToTileUnits(tile, 1, this.transform.zoom);
        const translationText = symbol_layout.translatePosition(this.collisionIndex.transform, tile, paint.get('text-translate'), paint.get('text-translate-anchor'));
        const translationIcon = symbol_layout.translatePosition(this.collisionIndex.transform, tile, paint.get('icon-translate'), paint.get('icon-translate-anchor'));
        const pitchedLabelPlaneMatrix = getPitchedLabelPlaneMatrix(rotateWithMap, this.transform, pixelsToTiles);
        // 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,
            unwrappedTileID,
            pitchedLabelPlaneMatrix,
            scale,
            textPixelRatio,
            holdingForFade: tile.holdingForSymbolFade(),
            collisionBoxArray,
            partiallyEvaluatedTextSize: symbol_layout.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, tileID, unwrappedTileID, collisionGroup, textOverlapMode, symbolInstance, bucket, orientation, translationText, translationIcon, iconBox, getElevation, simpleProjectionMatrix) {
        var _a, _b, _c;
        const anchor = symbol_layout.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, tileID, unwrappedTileID, pitchWithMap, rotateWithMap, translationText, collisionGroup.predicate, getElevation, shift, simpleProjectionMatrix);
        if (iconBox) {
            const placedIconBoxes = this.collisionIndex.placeCollisionBox(iconBox, textOverlapMode, textPixelRatio, tileID, unwrappedTileID, pitchWithMap, rotateWithMap, translationIcon, collisionGroup.predicate, getElevation, shift, simpleProjectionMatrix);
            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 (((_a = this.prevPlacement) === null || _a === void 0 ? void 0 : _a.variableOffsets[symbolInstance.crossTileID]) &&
                ((_c = (_b = this.prevPlacement) === null || _b === void 0 ? void 0 : _b.placements[symbolInstance.crossTileID]) === null || _c === void 0 ? void 0 : _c.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, unwrappedTileID, pitchedLabelPlaneMatrix, textPixelRatio, holdingForFade, collisionBoxArray, partiallyEvaluatedTextSize, collisionGroup } = bucketPart.parameters;
        const textOptional = layout.get('text-optional');
        const iconOptional = layout.get('icon-optional');
        const textOverlapMode = symbol_layout.getOverlapMode(layout, 'text-overlap', 'text-allow-overlap');
        const textAlwaysOverlap = textOverlapMode === 'always';
        const iconOverlapMode = symbol_layout.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 simpleProjectionMatrix = this.transform.getFastPathSimpleProjectionMatrix(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, occluded: false };
            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 = symbol_layout.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 === symbol_layout.WritingMode.vertical) {
                                placed = placeVerticalFn();
                                placedVerticalText = placed;
                            }
                            else {
                                placed = placeHorizontalFn();
                            }
                            if (placed === null || placed === void 0 ? void 0 : 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, tileID, unwrappedTileID, pitchWithMap, rotateWithMap, translationText, collisionGroup.predicate, getElevation, undefined, simpleProjectionMatrix);
                        if (placedFeature === null || placedFeature === void 0 ? void 0 : placedFeature.placeable) {
                            this.markUsedOrientation(bucket, orientation, symbolInstance);
                            this.placedOrientations[symbolInstance.crossTileID] = orientation;
                        }
                        return placedFeature;
                    };
                    const placeHorizontal = () => {
                        return placeBox(textBox, symbol_layout.WritingMode.horizontal);
                    };
                    const placeVertical = () => {
                        const verticalTextBox = collisionArrays.verticalTextBox;
                        if (bucket.allowVerticalPlacement && symbolInstance.numVerticalGlyphVertices > 0 && verticalTextBox) {
                            return placeBox(verticalTextBox, symbol_layout.WritingMode.vertical);
                        }
                        return { box: null, offscreen: null };
                    };
                    placeTextForPlacementModes(placeHorizontal, placeVertical);
                    updatePreviousOrientationIfNotPlaced(placed === null || placed === void 0 ? void 0 : placed.placeable);
                }
                else {
                    // If this symbol was in the last placement, prefer placement using same anchor, if it's still available
                    let prevAnchor = symbol_layout.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, tileID, unwrappedTileID, collisionGroup, overlapMode, symbolInstance, bucket, orientation, translationText, translationIcon, variableIconBox, getElevation);
                                if (result) {
                                    placedBox = result.placedGlyphBoxes;
                                    if (placedBox === null || placedBox === void 0 ? void 0 : 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, tileID, unwrappedTileID, pitchWithMap, rotateWithMap, translationText, collisionGroup.predicate, getElevation, undefined, simpleProjectionMatrix);
                            placedBox = {
                                box: placedFakeGlyphBox.box,
                                offscreen: false,
                                placeable: false,
                                occluded: false,
                            };
                        }
                        return placedBox;
                    };
                    const placeHorizontal = () => {
                        return placeBoxForVariableAnchors(textBox, collisionArrays.iconBox, symbol_layout.WritingMode.horizontal);
                    };
                    const placeVertical = () => {
                        const verticalTextBox = collisionArrays.verticalTextBox;
                        const wasPlaced = placed === null || placed === void 0 ? void 0 : placed.placeable;
                        if (bucket.allowVerticalPlacement && !wasPlaced && symbolInstance.numVerticalGlyphVertices > 0 && verticalTextBox) {
                            return placeBoxForVariableAnchors(verticalTextBox, collisionArrays.verticalIconBox, symbol_layout.WritingMode.vertical);
                        }
                        return { box: null, occluded: true, offscreen: null };
                    };
                    placeTextForPlacementModes(placeHorizontal, placeVertical);
                    if (placed) {
                        placeText = placed.placeable;
                        offscreen = placed.offscreen;
                    }
                    const prevOrientation = updatePreviousOrientationIfNotPlaced(placed === null || placed === void 0 ? void 0 : 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 === null || placedGlyphBoxes === void 0 ? void 0 : placedGlyphBoxes.placeable;
            offscreen = placedGlyphBoxes === null || placedGlyphBoxes === void 0 ? void 0 : placedGlyphBoxes.offscreen;
            if (symbolInstance.useRuntimeCollisionCircles && symbolInstance.centerJustifiedTextSymbolIndex >= 0) {
                const placedSymbol = bucket.text.placedSymbolArray.get(symbolInstance.centerJustifiedTextSymbolIndex);
                const fontSize = symbol_layout.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, unwrappedTileID, pitchedLabelPlaneMatrix, showCollisionBoxes, pitchWithMap, collisionGroup.predicate, circlePixelDiameter, textPixelPadding, translationText, getElevation);
                if (placedGlyphCircles.circles.length && placedGlyphCircles.collisionDetected && !showCollisionBoxes) {
                    symbol_layout.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, tileID, unwrappedTileID, pitchWithMap, rotateWithMap, translationIcon, collisionGroup.predicate, getElevation, (hasIconTextFit && shift) ? shift : undefined, simpleProjectionMatrix);
                };
                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');
            // Do not show text or icons that are occluded by the globe, even if overlap mode is 'always'!
            const textVisible = (placeText || alwaysShowText) && !(placedGlyphBoxes === null || placedGlyphBoxes === void 0 ? void 0 : placedGlyphBoxes.occluded);
            const iconVisible = (placeIcon || alwaysShowIcon) && !(placedIconBoxes === null || placedIconBoxes === void 0 ? void 0 : placedIconBoxes.occluded);
            this.placements[symbolInstance.crossTileID] = new JointPlacement(textVisible, iconVisible, 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.bearingInRadians);
            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);
            }
        }
        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] = [];
            for (let i = 0; i < placedGlyphCircles.circles.length; i += 4) {
                circleArray.push(placedGlyphCircles.circles[i + 0] - viewportPadding); // x
                circleArray.push(placedGlyphCircles.circles[i + 1] - viewportPadding); // y
                circleArray.push(placedGlyphCircles.circles[i + 2]); // radius
                circleArray.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 === symbol_layout.WritingMode.vertical) {
            autoIndex = symbolInstance.verticalPlacedTextSymbolIndex;
        }
        else {
            autoIndex = justifications[symbol_layout.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 === symbol_layout.WritingMode.horizontal || orientation === symbol_layout.WritingMode.horizontalOnly) ? orientation : 0;
        const vertical = orientation === symbol_layout.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 === symbol_layout.WritingMode.vertical;
            const verticalHidden = placedOrientation === symbol_layout.WritingMode.horizontal || placedOrientation === symbol_layout.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();
                const textSymbolIndexes = [
                    symbolInstance.rightJustifiedTextSymbolIndex,
                    symbolInstance.centerJustifiedTextSymbolIndex,
                    symbolInstance.leftJustifiedTextSymbolIndex
                ];
                for (const index of textSymbolIndexes) {
                    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 === null || boxArrays === void 0 ? void 0 : 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 symbol_layout.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.bearingInRadians : this.transform.bearingInRadians);
                                }
                            }
                            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.bearingInRadians);
        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) {
            bucket.collisionCircleArray = this.collisionCircleArrays[bucket.bucketInstanceId];
            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;

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, 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 = now();
        const shouldPausePlacement = () => {
            return this._forceFullPlacement ? false : (now() - startTime) > 2;
        };
        while (this._currentPlacementIndex >= 0) {
            const layerId = order[this._currentPlacementIndex];
            const layer = layers[layerId];
            const placementZoom = this.placement.collisionIndex.transform.zoom;
            if (symbol_layout.isSymbolStyleLayer(layer) &&
                layer.layout &&
                (!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 / symbol_layout.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 symbol_layout.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 * symbol_layout.EXTENT + symbolInstance.anchorX) * scale;
        const yWorld = (y * symbol_layout.EXTENT + symbolInstance.anchorY) * scale;
        const xOffset = localX * symbol_layout.EXTENT * roundingFactor;
        const yOffset = localY * symbol_layout.EXTENT * roundingFactor;
        return {
            x: Math.floor(xWorld - xOffset),
            y: Math.floor(yWorld - yOffset)
        };
    }
    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) {
        var _a;
        if ((_a = this.indexes[tileID.overscaledZ]) === null || _a === void 0 ? void 0 : _a[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 (styleLayer.id !== (symbolBucket === null || symbolBucket === void 0 ? void 0 : 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 = {};
        for (const usedLayer of usedLayers) {
            usedLayerMap[usedLayer] = true;
        }
        for (const layerId in this.layerIndexes) {
            if (!usedLayerMap[layerId]) {
                delete this.layerIndexes[layerId];
            }
        }
    }
}

// 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\nout highp vec4 fragColor;';

// 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;}mat3 rotationMatrixFromAxisAngle(vec3 u,float angle) {float c=cos(angle);float s=sin(angle);float c2=1.0-c;return mat3(u.x*u.x*c2+      c,u.x*u.y*c2-u.z*s,u.x*u.z*c2+u.y*s,u.y*u.x*c2+u.z*s,u.y*u.y*c2+    c,u.y*u.z*c2-u.x*s,u.z*u.x*c2-u.y*s,u.z*u.y*c2+u.x*s,u.z*u.z*c2+    c\n);}\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(texture(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=(texture(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\n#ifdef GLOBE\nif ((pos.y <-32767.5) || (pos.y > 32766.5)) {return 0.0;}\n#endif\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}const float PI=3.141592653589793;uniform mat4 u_projection_matrix;';

// 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() {fragColor=u_color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}';

// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.
var backgroundVert = 'in vec2 a_pos;void main() {gl_Position=projectTile(a_pos);}';

// 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;in vec2 v_pos_a;in 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=texture(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=texture(u_image,pos2);fragColor=mix(color1,color2,u_mix)*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}';

// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.
var backgroundPatternVert = '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;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;void main() {gl_Position=projectTile(a_pos);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 = 'in vec3 v_data;in 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);float antialiased_blur=v_data.z;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));fragColor=v_visibility*opacity_t*mix(color*opacity,stroke_color*stroke_opacity,color_t);const float epsilon=0.5/255.0;if (fragColor.r < epsilon && fragColor.g < epsilon && fragColor.b < epsilon && fragColor.a < epsilon) {discard;}\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}';

// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.
var circleVert = 'uniform bool u_scale_with_map;uniform bool u_pitch_with_map;uniform vec2 u_extrude_scale;uniform highp float u_globe_extrude_scale;uniform lowp float u_device_pixel_ratio;uniform highp float u_camera_to_center_distance;uniform vec2 u_translate;in vec2 a_pos;out vec3 v_data;out 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 pos_raw=a_pos+32768.0;vec2 extrude=vec2(mod(pos_raw,8.0)/7.0*2.0-1.0);vec2 circle_center=floor(pos_raw/8.0)+u_translate;float ele=get_elevation(circle_center);v_visibility=calculate_visibility(projectTileWithElevation(circle_center,ele));if (u_pitch_with_map) {\n#ifdef GLOBE\nvec3 center_vector=projectToSphere(circle_center);\n#endif\nfloat angle_scale=u_globe_extrude_scale;vec2 corner_position=circle_center;if (u_scale_with_map) {angle_scale*=(radius+stroke_width);corner_position+=extrude*u_extrude_scale*(radius+stroke_width);} else {\n#ifdef GLOBE\nvec4 projected_center=interpolateProjection(circle_center,center_vector,ele);\n#else\nvec4 projected_center=projectTileWithElevation(circle_center,ele);\n#endif\ncorner_position+=extrude*u_extrude_scale*(radius+stroke_width)*(projected_center.w/u_camera_to_center_distance);angle_scale*=(radius+stroke_width)*(projected_center.w/u_camera_to_center_distance);}\n#ifdef GLOBE\nvec2 angles=extrude*angle_scale;vec3 corner_vector=globeRotateVector(center_vector,angles);gl_Position=interpolateProjection(corner_position,corner_vector,ele);\n#else\ngl_Position=projectTileWithElevation(corner_position,ele);\n#endif\n} else {gl_Position=projectTileWithElevation(circle_center,ele);if (gl_Position.z/gl_Position.w > 1.0) {gl_Position.xy=vec2(10000.0);}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;}}float antialiasblur=-max(1.0/u_device_pixel_ratio/(radius+stroke_width),blur);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() {fragColor=vec4(1.0);}';

// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.
var clippingMaskVert = 'in vec2 a_pos;void main() {gl_Position=projectTile(a_pos);}';

// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.
var heatmapFrag = 'uniform highp float u_intensity;in 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);fragColor=vec4(val,1.0,1.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}';

// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.
var heatmapVert = 'uniform float u_extrude_scale;uniform float u_opacity;uniform float u_intensity;uniform highp float u_globe_extrude_scale;in vec2 a_pos;out 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 pos_raw=a_pos+32768.0;vec2 unscaled_extrude=vec2(mod(pos_raw,8.0)/7.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;vec2 circle_center=floor(pos_raw/8.0);\n#ifdef GLOBE\nvec2 angles=v_extrude*radius*u_globe_extrude_scale;vec3 center_vector=projectToSphere(circle_center);vec3 corner_vector=globeRotateVector(center_vector,angles);gl_Position=interpolateProjection(circle_center+extrude,corner_vector,0.0);\n#else\ngl_Position=projectTileFor3D(circle_center+extrude,get_elevation(circle_center));\n#endif\n}';

// 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;in vec2 v_pos;void main() {float t=texture(u_image,v_pos).r;vec4 color=texture(u_color_ramp,vec2(t,0.5));fragColor=color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=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;in vec2 a_pos;out 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 = 'in float v_placed;in float v_notUsed;void main() {float alpha=0.5;fragColor=vec4(1.0,0.0,0.0,1.0)*alpha;if (v_placed > 0.5) {fragColor=vec4(0.0,0.0,1.0,0.5)*alpha;}if (v_notUsed > 0.5) {fragColor*=.1;}}';

// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.
var collisionBoxVert = 'in vec2 a_anchor_pos;in vec2 a_placed;in vec2 a_box_real;uniform vec2 u_pixel_extrude_scale;out float v_placed;out float v_notUsed;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 = 'in float v_radius;in vec2 v_extrude;in float v_collision;void main() {float alpha=0.5;float stroke_radius=0.9;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);fragColor=color*alpha*opacity_t;}';

// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.
var collisionCircleVert = 'in vec2 a_pos;in float a_radius;in vec2 a_flags;uniform vec2 u_viewport_size;out float v_radius;out vec2 v_extrude;out float v_collision;void main() {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;float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_collision=collision;gl_Position=vec4((a_pos/u_viewport_size*2.0-1.0)*vec2(1.0,-1.0),0.0,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 colorReliefFrag = '#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;uniform vec4 u_unpack;uniform sampler2D u_elevation_stops;uniform sampler2D u_color_stops;uniform int u_color_ramp_size;uniform float u_opacity;in vec2 v_pos;float getElevation(vec2 coord) {vec4 data=texture(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack);}float getElevationStop(int stop) {float x=(float(stop)+0.5)/float(u_color_ramp_size);vec4 data=texture(u_elevation_stops,vec2(x,0))*255.0;data.a=-1.0;return dot(data,u_unpack);}void main() {float el=getElevation(v_pos);int r=(u_color_ramp_size-1);int l=0;float el_l=getElevationStop(l);float el_r=getElevationStop(r);while(r-l > 1){int m=(r+l)/2;float el_m=getElevationStop(m);if(el < el_m){r=m;el_r=el_m;}else\n{l=m;el_l=el_m;}}float x=(float(l)+(el-el_l)/(el_r-el_l)+0.5)/float(u_color_ramp_size);fragColor=u_opacity*texture(u_color_stops,vec2(x,0));\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}';

// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.
var colorReliefVert = 'uniform vec2 u_dimension;in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=projectTile(a_pos,a_pos);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_pos/8192.0)*scale+epsilon;if (a_pos.y <-32767.5) {v_pos.y=0.0;}if (a_pos.y > 32766.5) {v_pos.y=1.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;in vec2 v_uv;void main() {vec4 overlay_color=texture(u_overlay,v_uv);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 = 'in vec2 a_pos;out vec2 v_uv;uniform float u_overlay_scale;void main() {v_uv=a_pos/8192.0;gl_Position=projectTileWithElevation(a_pos*u_overlay_scale,get_elevation(a_pos));}';

// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.
var depthVert = 'in vec2 a_pos;void main() {\n#ifdef GLOBE\ngl_Position=projectTileFor3D(a_pos,0.0);\n#else\ngl_Position=u_projection_matrix*vec4(a_pos,0.0,1.0);\n#endif\n}';

// 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\nfragColor=color*opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}';

// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.
var fillVert = 'uniform vec2 u_fill_translate;in vec2 a_pos;\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=projectTile(a_pos+u_fill_translate,a_pos);}';

// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.
var fillOutlineFrag = 'in vec2 v_pos;\n#ifdef GLOBE\nin float v_depth;\n#endif\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);fragColor=outline_color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}';

// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.
var fillOutlineVert = 'uniform vec2 u_world;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos;\n#ifdef GLOBE\nout float v_depth;\n#endif\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=projectTile(a_pos+u_fill_translate,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n}';

// 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;in vec2 v_pos_a;in vec2 v_pos_b;in vec2 v_pos;\n#ifdef GLOBE\nin float v_depth;\n#endif\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=texture(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=texture(u_image,pos2);float dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);fragColor=mix(color1,color2,u_fade)*alpha*opacity;\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}';

// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.
var fillOutlinePatternVert = 'uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;out vec2 v_pos;\n#ifdef GLOBE\nout float v_depth;\n#endif\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=projectTile(a_pos+u_fill_translate,a_pos);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;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n}';

// 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;in vec2 v_pos_a;in 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=texture(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=texture(u_image,pos2);fragColor=mix(color1,color2,u_fade)*opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}';

// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.
var fillPatternVert = 'uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos_a;out 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=projectTile(a_pos+u_fill_translate,a_pos);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 = 'in vec4 v_color;void main() {fragColor=v_color;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}';

// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.
var fillExtrusionVert = 'uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec2 u_fill_translate;in vec2 a_pos;in vec4 a_normal_ed;\n#ifdef TERRAIN3D\nin vec2 a_centroid;\n#endif\nout 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);float elevation=t > 0.0 ? height : base;vec2 posInTile=a_pos+u_fill_translate;\n#ifdef GLOBE\nvec3 spherePos=projectToSphere(posInTile,a_pos);gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);\n#else\ngl_Position=u_projection_matrix*vec4(posInTile,elevation,1.0);\n#endif\nfloat 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;vec3 normalForLighting=normal/16384.0;float directional=clamp(dot(normalForLighting,u_lightpos),0.0,1.0);\n#ifdef GLOBE\nmat3 rotMatrix=globeGetRotationMatrix(spherePos);normalForLighting=rotMatrix*normalForLighting;directional=mix(directional,clamp(dot(normalForLighting,u_lightpos_globe),0.0,1.0),u_projection_transition);\n#endif\ndirectional=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;in vec2 v_pos_a;in vec2 v_pos_b;in 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=texture(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=texture(u_image,pos2);vec4 mixedColor=mix(color1,color2,u_fade);fragColor=mixedColor*v_lighting;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}';

// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.
var fillExtrusionPatternVert = '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 vec2 u_fill_translate;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;in vec2 a_pos;in vec4 a_normal_ed;\n#ifdef TERRAIN3D\nin vec2 a_centroid;\n#endif\n#ifdef GLOBE\nout vec3 v_sphere_pos;\n#endif\nout vec2 v_pos_a;out vec2 v_pos_b;out 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 elevation=t > 0.0 ? height : base;vec2 posInTile=a_pos+u_fill_translate;\n#ifdef GLOBE\nvec3 spherePos=projectToSphere(posInTile,a_pos);vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);v_sphere_pos=elevatedPos;gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);\n#else\ngl_Position=u_projection_matrix*vec4(posInTile,elevation,1.0);\n#endif\nvec2 pos=normal.x==1.0 && normal.y==0.0 && normal.z==16384.0\n? a_pos\n: vec2(edgedistance,elevation*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;in vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;uniform vec4 u_unpack;float getElevation(vec2 coord,float bias) {vec4 data=texture(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack);}void main() {vec2 epsilon=1.0/u_dimension;float tileSize=u_dimension.x-2.0;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))*tileSize/pow(2.0,exaggeration+(28.2562-u_zoom));fragColor=clamp(vec4(deriv.x/8.0+0.5,deriv.y/8.0+0.5,1.0,1.0),0.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=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;in vec2 a_pos;in vec2 a_texture_pos;out 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;in vec2 v_pos;uniform vec2 u_latrange;uniform float u_exaggeration;uniform vec4 u_accent;uniform int u_method;uniform float u_altitudes[NUM_ILLUMINATION_SOURCES];uniform float u_azimuths[NUM_ILLUMINATION_SOURCES];uniform vec4 u_shadows[NUM_ILLUMINATION_SOURCES];uniform vec4 u_highlights[NUM_ILLUMINATION_SOURCES];\n#define PI 3.141592653589793\n#define STANDARD 0\n#define COMBINED 1\n#define IGOR 2\n#define MULTIDIRECTIONAL 3\n#define BASIC 4\nfloat get_aspect(vec2 deriv){return deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/2.0*(deriv.y > 0.0 ? 1.0 :-1.0);}void igor_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;float aspect=get_aspect(deriv);float azimuth=u_azimuths[0]+PI;float slope_stength=atan(length(deriv))*2.0/PI;float aspect_strength=1.0-abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);float shadow_strength=slope_stength*aspect_strength;float highlight_strength=slope_stength*(1.0-aspect_strength);fragColor=u_shadows[0]*shadow_strength+u_highlights[0]*highlight_strength;}void standard_hillshade(vec2 deriv){float azimuth=u_azimuths[0]+PI;float slope=atan(0.625*length(deriv));float aspect=get_aspect(deriv);float intensity=u_exaggeration;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_shadows[0],u_highlights[0],shade)*sin(scaledSlope)*clamp(intensity*2.0,0.0,1.0);fragColor=accent_color*(1.0-shade_color.a)+shade_color;}void basic_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;float azimuth=u_azimuths[0]+PI;float cos_az=cos(azimuth);float sin_az=sin(azimuth);float cos_alt=cos(u_altitudes[0]);float sin_alt=sin(u_altitudes[0]);float cang=(sin_alt-(deriv.y*cos_az*cos_alt-deriv.x*sin_az*cos_alt))/sqrt(1.0+dot(deriv,deriv));float shade=clamp(cang,0.0,1.0);if(shade > 0.5){fragColor=u_highlights[0]*(2.0*shade-1.0);}else\n{fragColor=u_shadows[0]*(1.0-2.0*shade);}}void multidirectional_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;fragColor=vec4(0,0,0,0);for(int i=0; i < NUM_ILLUMINATION_SOURCES; i++){float cos_alt=cos(u_altitudes[i]);float sin_alt=sin(u_altitudes[i]);float cos_az=-cos(u_azimuths[i]);float sin_az=-sin(u_azimuths[i]);float cang=(sin_alt-(deriv.y*cos_az*cos_alt-deriv.x*sin_az*cos_alt))/sqrt(1.0+dot(deriv,deriv));float shade=clamp(cang,0.0,1.0);if(shade > 0.5){fragColor+=u_highlights[i]*(2.0*shade-1.0)/float(NUM_ILLUMINATION_SOURCES);}else\n{fragColor+=u_shadows[i]*(1.0-2.0*shade)/float(NUM_ILLUMINATION_SOURCES);}}}void combined_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;float azimuth=u_azimuths[0]+PI;float cos_az=cos(azimuth);float sin_az=sin(azimuth);float cos_alt=cos(u_altitudes[0]);float sin_alt=sin(u_altitudes[0]);float cang=acos((sin_alt-(deriv.y*cos_az*cos_alt-deriv.x*sin_az*cos_alt))/sqrt(1.0+dot(deriv,deriv)));cang=clamp(cang,0.0,PI/2.0);float shade=cang*atan(length(deriv))*4.0/PI/PI;float highlight=(PI/2.0-cang)*atan(length(deriv))*4.0/PI/PI;fragColor=u_shadows[0]*shade+u_highlights[0]*highlight;}void main() {vec4 pixel=texture(u_image,v_pos);float scaleFactor=cos(radians((u_latrange[0]-u_latrange[1])*(1.0-v_pos.y)+u_latrange[1]));vec2 deriv=((pixel.rg*8.0)-4.0)/scaleFactor;if (u_method==BASIC) {basic_hillshade(deriv);} else if (u_method==COMBINED) {combined_hillshade(deriv);} else if (u_method==IGOR) {igor_hillshade(deriv);} else if (u_method==MULTIDIRECTIONAL) {multidirectional_hillshade(deriv);} else if (u_method==STANDARD) {standard_hillshade(deriv);} else {standard_hillshade(deriv);}\n#ifdef OVERDRAW_INSPECTOR\nfragColor=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;in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=projectTile(a_pos,a_pos);v_pos=a_pos/8192.0;if (a_pos.y <-32767.5) {v_pos.y=0.0;}if (a_pos.y > 32766.5) {v_pos.y=1.0;}}';

// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.
var lineFrag = 'uniform lowp float u_device_pixel_ratio;in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;\n#ifdef GLOBE\nin float v_depth;\n#endif\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);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=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\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform mediump float u_ratio;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;out vec2 v_normal;out vec2 v_width2;out float v_gamma_scale;out highp float v_linesofar;\n#ifdef GLOBE\nout float v_depth;\n#endif\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);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.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;in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;in highp vec2 v_uv;\n#ifdef GLOBE\nin float v_depth;\n#endif\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=texture(u_image,v_uv);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=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\nin vec2 a_pos_normal;in vec4 a_data;in float a_uv_x;in float a_split_index;uniform vec2 u_translation;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_units_to_pixels;uniform float u_image_height;out vec2 v_normal;out vec2 v_width2;out float v_gamma_scale;out highp vec2 v_uv;\n#ifdef GLOBE\nout float v_depth;\n#endif\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);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.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;in vec2 v_normal;in vec2 v_width2;in float v_linesofar;in float v_gamma_scale;in float v_width;\n#ifdef GLOBE\nin float v_depth;\n#endif\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(texture(u_image,pos_a),texture(u_image,pos_b),u_fade);fragColor=color*alpha*opacity;\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=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\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform vec2 u_units_to_pixels;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;out vec2 v_normal;out vec2 v_width2;out float v_linesofar;out float v_gamma_scale;out float v_width;\n#ifdef GLOBE\nout float v_depth;\n#endif\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);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.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 lowp float u_lineatlas_width;uniform sampler2D u_image;uniform float u_mix;in vec2 v_normal;in vec2 v_width2;in vec2 v_tex_a;in vec2 v_tex_b;in float v_gamma_scale;\n#ifdef GLOBE\nin float v_depth;\n#endif\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\n#pragma mapbox: define mediump vec4 dasharray_from\n#pragma mapbox: define mediump vec4 dasharray_to\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\n#pragma mapbox: initialize mediump vec4 dasharray_from\n#pragma mapbox: initialize mediump vec4 dasharray_to\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=texture(u_image,v_tex_a).a;float sdfdist_b=texture(u_image,v_tex_b).a;float sdfdist=mix(sdfdist_a,sdfdist_b,u_mix);float sdfgamma=(u_lineatlas_width/256.0/u_device_pixel_ratio)/min(dasharray_from.w,dasharray_to.w);alpha*=smoothstep(0.5-sdfgamma/floorwidth,0.5+sdfgamma/floorwidth,sdfdist);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=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\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_units_to_pixels;uniform float u_tileratio;uniform float u_crossfade_from;uniform float u_crossfade_to;uniform float u_lineatlas_height;out vec2 v_normal;out vec2 v_width2;out vec2 v_tex_a;out vec2 v_tex_b;out float v_gamma_scale;\n#ifdef GLOBE\nout float v_depth;\n#endif\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\n#pragma mapbox: define mediump vec4 dasharray_from\n#pragma mapbox: define mediump vec4 dasharray_to\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\n#pragma mapbox: initialize mediump vec4 dasharray_from\n#pragma mapbox: initialize mediump vec4 dasharray_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);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nfloat u_patternscale_a_x=u_tileratio/dasharray_from.w/u_crossfade_from;float u_patternscale_a_y=-dasharray_from.z/2.0/u_lineatlas_height;float u_patternscale_b_x=u_tileratio/dasharray_to.w/u_crossfade_to;float u_patternscale_b_y=-dasharray_to.z/2.0/u_lineatlas_height;v_tex_a=vec2(a_linesofar*u_patternscale_a_x/floorwidth,normal.y*u_patternscale_a_y+(float(dasharray_from.y)+0.5)/u_lineatlas_height);v_tex_b=vec2(a_linesofar*u_patternscale_b_x/floorwidth,normal.y*u_patternscale_b_y+(float(dasharray_to.y)+0.5)/u_lineatlas_height);v_width2=vec2(outset,inset);}';

// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.
var lineGradientSDFFrag = 'uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;uniform sampler2D u_image_dash;uniform float u_mix;uniform lowp float u_lineatlas_width;in vec2 v_normal;in vec2 v_width2;in vec2 v_tex_a;in vec2 v_tex_b;in float v_gamma_scale;in highp vec2 v_uv;\n#ifdef GLOBE\nin float v_depth;\n#endif\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\n#pragma mapbox: define mediump vec4 dasharray_from\n#pragma mapbox: define mediump vec4 dasharray_to\nvoid main() {\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\n#pragma mapbox: initialize mediump vec4 dasharray_from\n#pragma mapbox: initialize mediump vec4 dasharray_to\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=texture(u_image,v_uv);float sdfdist_a=texture(u_image_dash,v_tex_a).a;float sdfdist_b=texture(u_image_dash,v_tex_b).a;float sdfdist=mix(sdfdist_a,sdfdist_b,u_mix);float sdfgamma=(u_lineatlas_width/256.0)/min(dasharray_from.w,dasharray_to.w);float dash_alpha=smoothstep(0.5-sdfgamma/floorwidth,0.5+sdfgamma/floorwidth,sdfdist);fragColor=color*(alpha*dash_alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}';

// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.
var lineGradientSDFVert = '\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nin vec2 a_pos_normal;in vec4 a_data;in float a_uv_x;in float a_split_index;uniform vec2 u_translation;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_units_to_pixels;uniform float u_image_height;uniform float u_tileratio;uniform float u_crossfade_from;uniform float u_crossfade_to;uniform float u_lineatlas_height;out vec2 v_normal;out vec2 v_width2;out float v_gamma_scale;out highp vec2 v_uv;out vec2 v_tex_a;out vec2 v_tex_b;\n#ifdef GLOBE\nout float v_depth;\n#endif\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\n#pragma mapbox: define mediump vec4 dasharray_from\n#pragma mapbox: define mediump vec4 dasharray_to\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\n#pragma mapbox: initialize lowp float floorwidth\n#pragma mapbox: initialize mediump vec4 dasharray_from\n#pragma mapbox: initialize mediump vec4 dasharray_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;float texel_height=1.0/u_image_height;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);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nfloat u_patternscale_a_x=u_tileratio/dasharray_from.w/u_crossfade_from;float u_patternscale_a_y=-dasharray_from.z/2.0/u_lineatlas_height;float u_patternscale_b_x=u_tileratio/dasharray_to.w/u_crossfade_to;float u_patternscale_b_y=-dasharray_to.z/2.0/u_lineatlas_height;v_tex_a=vec2(a_linesofar*u_patternscale_a_x/floorwidth,normal.y*u_patternscale_a_y+(float(dasharray_from.y)+0.5)/u_lineatlas_height);v_tex_b=vec2(a_linesofar*u_patternscale_b_x/floorwidth,normal.y*u_patternscale_b_y+(float(dasharray_to.y)+0.5)/u_lineatlas_height);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;in vec2 v_pos0;in 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=texture(u_image0,v_pos0);vec4 color1=texture(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);fragColor=vec4(mix(u_high_vec,u_low_vec,rgb)*color.a,color.a);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}';

// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.
var rasterVert = 'uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_buffer_scale;uniform vec4 u_coords_top;uniform vec4 u_coords_bottom;in vec2 a_pos;out vec2 v_pos0;out vec2 v_pos1;void main() {vec2 fractionalPos=a_pos/8192.0;vec2 position=mix(mix(u_coords_top.xy,u_coords_top.zw,fractionalPos.x),mix(u_coords_bottom.xy,u_coords_bottom.zw,fractionalPos.x),fractionalPos.y);gl_Position=projectTile(position,position);v_pos0=((fractionalPos-0.5)/u_buffer_scale)+0.5;\n#ifdef GLOBE\nif (a_pos.y <-32767.5) {v_pos0.y=0.0;}if (a_pos.y > 32766.5) {v_pos0.y=1.0;}\n#endif\nv_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;in vec2 v_tex;in float v_total_opacity;void main() {fragColor=texture(u_texture,v_tex)*v_total_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}';

// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.
var symbolIconVert = 'in vec4 a_pos_offset;in vec4 a_data;in vec4 a_pixeloffset;in vec3 a_projected_pos;in 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_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;out vec2 v_tex;out float v_total_opacity;\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);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_total_opacity=opacity*max(0.0,min(visibility,fade_opacity[0]+fade_change));if (v_total_opacity < 0.1){gl_Position=vec4(-2.,-2.,-2.,1.);return;}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;\n#ifdef GLOBE\nif(u_pitch_with_map) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 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;}';

// 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 highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;in vec2 v_data0;in 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 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 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 total_opacity=v_data1[2];float fontScale=u_is_text ? size/24.0 : 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;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=texture(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);}fragColor=color*(alpha*total_opacity);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}';

// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.
var symbolSDFVert = 'in vec4 a_pos_offset;in vec4 a_data;in vec4 a_pixeloffset;in vec3 a_projected_pos;in 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_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;out vec2 v_data0;out 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\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/16.0;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);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));float total_opacity=opacity*interpolated_fade_opacity;if (total_opacity < 0.1){gl_Position=vec4(-2.,-2.,-2.,1.);return;}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;\n#ifdef GLOBE\nif(u_pitch_with_map) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,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;v_data0=a_tex/u_texsize;v_data1=vec3(gamma_scale,size,total_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;in vec4 v_data0;in 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 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 halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat total_opacity=v_data1[2];if (v_data1.w==ICON) {vec2 tex_icon=v_data0.zw;fragColor=texture(u_texture_icon,tex_icon)*total_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=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=texture(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);fragColor=color*(alpha*total_opacity);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}';

// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.
var symbolTextAndIconVert = 'in vec4 a_pos_offset;in vec4 a_data;in vec3 a_projected_pos;in 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_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;out vec4 v_data0;out 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\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);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));float total_opacity=opacity*interpolated_fade_opacity;if (total_opacity < 0.1){gl_Position=vec4(-2.,-2.,-2.,1.);return;}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;\n#ifdef GLOBE\nif(u_pitch_with_map && !u_is_along_line) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 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;v_data0.xy=a_tex/u_texsize;v_data0.zw=a_tex/u_texsize_icon;v_data1=vec4(gamma_scale,size,total_opacity,is_sdf);}';

// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.
var terrainDepthFrag = 'in 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() {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;in vec2 v_texture_pos;void main() {vec4 rgba=texture(u_texture,v_texture_pos);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;uniform bool u_is_globe_mode;in vec2 v_texture_pos;in 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=texture(u_texture,vec2(v_texture_pos.x,1.0-v_texture_pos.y));if (!u_is_globe_mode && 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);fragColor=linearToGamma(mix(surface_color_linear,fog_horizon_color_linear,pow(factor_fog,2.0)*u_fog_ground_blend_opacity));} else {fragColor=surface_color;}}';

// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.
var terrainVert = 'in vec3 a_pos3d;uniform mat4 u_fog_matrix;uniform float u_ele_delta;out vec2 v_texture_pos;out 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=projectTileFor3D(a_pos3d.xy,ele-ele_delta);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 terrainVertDepth = 'in vec3 a_pos3d;uniform float u_ele_delta;out 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=projectTileFor3D(a_pos3d.xy,ele-ele_delta);v_depth=gl_Position.z/gl_Position.w;}';

// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.
var terrainVertCoords = 'in vec3 a_pos3d;uniform float u_ele_delta;out 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=projectTileFor3D(a_pos3d.xy,ele-ele_delta);}';

// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.
var projectionErrorMeasurementVert = 'in vec2 a_pos;uniform highp float u_input;uniform highp float u_output_expected;out vec4 v_output_error_encoded;void main() {float real_output=2.0*atan(exp(PI-(u_input*PI*2.0)))-PI*0.5;float error=real_output-u_output_expected;float abs_error=abs(error)*128.0;v_output_error_encoded.x=min(floor(abs_error*256.0),255.0)/255.0;abs_error-=v_output_error_encoded.x;v_output_error_encoded.y=min(floor(abs_error*65536.0),255.0)/255.0;abs_error-=v_output_error_encoded.x/255.0;v_output_error_encoded.z=min(floor(abs_error*16777216.0),255.0)/255.0;v_output_error_encoded.w=error >=0.0 ? 1.0 : 0.0;gl_Position=vec4(a_pos,0.0,1.0);}';

// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.
var projectionErrorMeasurementFrag = 'in vec4 v_output_error_encoded;void main() {fragColor=v_output_error_encoded;}';

// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.
var projectionMercatorVert = 'float projectLineThickness(float tileY) {return 1.0;}float projectCircleRadius(float tileY) {return 1.0;}vec4 projectTile(vec2 p) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);return result;}vec4 projectTile(vec2 p,vec2 rawPos) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);if (rawPos.y <-32767.5 || rawPos.y > 32766.5) {result.z=-10000000.0;}return result;}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_projection_matrix*vec4(posInTile,elevation,1.0);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {return projectTileWithElevation(posInTile,elevation);}';

// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.
var projectionGlobeVert = '#define GLOBE_RADIUS 6371008.8\nuniform highp vec4 u_projection_tile_mercator_coords;uniform highp vec4 u_projection_clipping_plane;uniform highp float u_projection_transition;uniform mat4 u_projection_fallback_matrix;vec3 globeRotateVector(vec3 vec,vec2 angles) {vec3 axisRight=vec3(vec.z,0.0,-vec.x);vec3 axisUp=cross(axisRight,vec);axisRight=normalize(axisRight);axisUp=normalize(axisUp);vec2 t=tan(angles);return normalize(vec+axisRight*t.x+axisUp*t.y);}mat3 globeGetRotationMatrix(vec3 spherePos) {vec3 axisRight=vec3(spherePos.z,0.0,-spherePos.x);vec3 axisDown=cross(axisRight,spherePos);axisRight=normalize(axisRight);axisDown=normalize(axisDown);return mat3(axisRight,axisDown,spherePos\n);}float circumferenceRatioAtTileY(float tileY) {float mercator_pos_y=u_projection_tile_mercator_coords.y+u_projection_tile_mercator_coords.w*tileY;float spherical_y=2.0*atan(exp(PI-(mercator_pos_y*PI*2.0)))-PI*0.5;return cos(spherical_y);}float projectLineThickness(float tileY) {float thickness=1.0/circumferenceRatioAtTileY(tileY); \nif (u_projection_transition < 0.999) {return mix(1.0,thickness,u_projection_transition);} else {return thickness;}}vec3 projectToSphere(vec2 translatedPos,vec2 rawPos) {vec2 mercator_pos=u_projection_tile_mercator_coords.xy+u_projection_tile_mercator_coords.zw*translatedPos;vec2 spherical;spherical.x=mercator_pos.x*PI*2.0+PI;spherical.y=2.0*atan(exp(PI-(mercator_pos.y*PI*2.0)))-PI*0.5;float len=cos(spherical.y);vec3 pos=vec3(sin(spherical.x)*len,sin(spherical.y),cos(spherical.x)*len\n);if (rawPos.y <-32767.5) {pos=vec3(0.0,1.0,0.0);}if (rawPos.y > 32766.5) {pos=vec3(0.0,-1.0,0.0);}return pos;}vec3 projectToSphere(vec2 posInTile) {return projectToSphere(posInTile,vec2(0.0,0.0));}float globeComputeClippingZ(vec3 spherePos) {return (1.0-(dot(spherePos,u_projection_clipping_plane.xyz)+u_projection_clipping_plane.w));}vec4 interpolateProjection(vec2 posInTile,vec3 spherePos,float elevation) {vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);globePosition.z=globeComputeClippingZ(elevatedPos)*globePosition.w;if (u_projection_transition > 0.999) {return globePosition;}vec4 flatPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);const float z_globeness_threshold=0.2;vec4 result=globePosition;result.z=mix(0.0,globePosition.z,clamp((u_projection_transition-z_globeness_threshold)/(1.0-z_globeness_threshold),0.0,1.0));result.xyw=mix(flatPosition.xyw,globePosition.xyw,u_projection_transition);if ((posInTile.y <-32767.5) || (posInTile.y > 32766.5)) {result=globePosition;const float poles_hidden_anim_percentage=0.02;result.z=mix(globePosition.z,100.0,pow(max((1.0-u_projection_transition)/poles_hidden_anim_percentage,0.0),8.0));}return result;}vec4 interpolateProjectionFor3D(vec2 posInTile,vec3 spherePos,float elevation) {vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);if (u_projection_transition > 0.999) {return globePosition;}vec4 fallbackPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);return mix(fallbackPosition,globePosition,u_projection_transition);}vec4 projectTile(vec2 posInTile) {return interpolateProjection(posInTile,projectToSphere(posInTile),0.0);}vec4 projectTile(vec2 posInTile,vec2 rawPos) {return interpolateProjection(posInTile,projectToSphere(posInTile,rawPos),0.0);}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return interpolateProjection(posInTile,projectToSphere(posInTile),elevation);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {vec3 spherePos=projectToSphere(posInTile,posInTile);return interpolateProjectionFor3D(posInTile,spherePos,elevation);}';

// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.
var atmosphereFrag = '#ifdef GL_ES\nprecision highp float;\n#endif\nin vec3 view_direction;uniform vec3 u_sun_pos;uniform vec3 u_globe_position;uniform float u_globe_radius;uniform float u_atmosphere_blend;/**Shader use from https:*Made some change to adapt to MapLibre Globe geometry*/const float PI=3.141592653589793;const int iSteps=5;const int jSteps=3;/*radius of the planet*/const float EARTH_RADIUS=6371e3;/*radius of the atmosphere*/const float ATMOS_RADIUS=6471e3;vec2 rsi(vec3 r0,vec3 rd,float sr) {float a=dot(rd,rd);float b=2.0*dot(rd,r0);float c=dot(r0,r0)-(sr*sr);float d=(b*b)-4.0*a*c;if (d < 0.0) return vec2(1e5,-1e5);return vec2((-b-sqrt(d))/(2.0*a),(-b+sqrt(d))/(2.0*a));}vec4 atmosphere(vec3 r,vec3 r0,vec3 pSun,float iSun,float rPlanet,float rAtmos,vec3 kRlh,float kMie,float shRlh,float shMie,float g) {pSun=normalize(pSun);r=normalize(r);vec2 p=rsi(r0,r,rAtmos);if (p.x > p.y) {return vec4(0.0,0.0,0.0,1.0);}if (p.x < 0.0) {p.x=0.0;}vec3 pos=r0+r*p.x;vec2 p2=rsi(r0,r,rPlanet);if (p2.x <=p2.y && p2.x > 0.0) {p.y=min(p.y,p2.x);}float iStepSize=(p.y-p.x)/float(iSteps);float iTime=p.x+iStepSize*0.5;vec3 totalRlh=vec3(0,0,0);vec3 totalMie=vec3(0,0,0);float iOdRlh=0.0;float iOdMie=0.0;float mu=dot(r,pSun);float mumu=mu*mu;float gg=g*g;float pRlh=3.0/(16.0*PI)*(1.0+mumu);float pMie=3.0/(8.0*PI)*((1.0-gg)*(mumu+1.0))/(pow(1.0+gg-2.0*mu*g,1.5)*(2.0+gg));for (int i=0; i < iSteps; i++) {vec3 iPos=r0+r*iTime;float iHeight=length(iPos)-rPlanet;float odStepRlh=exp(-iHeight/shRlh)*iStepSize;float odStepMie=exp(-iHeight/shMie)*iStepSize;iOdRlh+=odStepRlh;iOdMie+=odStepMie;float jStepSize=rsi(iPos,pSun,rAtmos).y/float(jSteps);float jTime=jStepSize*0.5;float jOdRlh=0.0;float jOdMie=0.0;for (int j=0; j < jSteps; j++) {vec3 jPos=iPos+pSun*jTime;float jHeight=length(jPos)-rPlanet;jOdRlh+=exp(-jHeight/shRlh)*jStepSize;jOdMie+=exp(-jHeight/shMie)*jStepSize;jTime+=jStepSize;}vec3 attn=exp(-(kMie*(iOdMie+jOdMie)+kRlh*(iOdRlh+jOdRlh)));totalRlh+=odStepRlh*attn;totalMie+=odStepMie*attn;iTime+=iStepSize;}float opacity=exp(-(length(kRlh)*length(totalRlh)+kMie*length(totalMie)));vec3 color=iSun*(pRlh*kRlh*totalRlh+pMie*kMie*totalMie);return vec4(color,opacity);}void main() {vec3 scale_camera_pos=-u_globe_position*EARTH_RADIUS/u_globe_radius;vec4 color=atmosphere(normalize(view_direction),scale_camera_pos,u_sun_pos,22.0,EARTH_RADIUS,ATMOS_RADIUS,vec3(5.5e-6,13.0e-6,22.4e-6),21e-6,8e3,1.2e3,0.758\n);color.rgb=1.0-exp(-1.0*color.rgb);color=pow(color,vec4(1.0/2.2));fragColor=vec4(color.rgb,1.0-color.a)*u_atmosphere_blend;}';

// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.
var atmosphereVert = 'in vec2 a_pos;uniform mat4 u_inv_proj_matrix;out vec3 view_direction;void main() {view_direction=(u_inv_proj_matrix*vec4(a_pos,0.0,1.0)).xyz;gl_Position=vec4(a_pos,0.0,1.0);}';

// 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 vec2 u_horizon;uniform vec2 u_horizon_normal;uniform float u_sky_horizon_blend;uniform float u_sky_blend;void main() {float x=gl_FragCoord.x;float y=gl_FragCoord.y;float blend=(y-u_horizon.y)*u_horizon_normal.y+(x-u_horizon.x)*u_horizon_normal.x;if (blend > 0.0) {if (blend < u_sky_horizon_blend) {fragColor=mix(u_sky_color,u_horizon_color,pow(1.0-blend/u_sky_horizon_blend,2.0));} else {fragColor=u_sky_color;}}fragColor=mix(fragColor,vec4(vec3(0.0),0.0),u_sky_blend);}';

// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`.
var skyVert = 'in 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: prepare(preludeFrag, preludeVert),
    projectionMercator: prepare('', projectionMercatorVert),
    projectionGlobe: prepare('', projectionGlobeVert),
    background: prepare(backgroundFrag, backgroundVert),
    backgroundPattern: prepare(backgroundPatternFrag, backgroundPatternVert),
    circle: prepare(circleFrag, circleVert),
    clippingMask: prepare(clippingMaskFrag, clippingMaskVert),
    heatmap: prepare(heatmapFrag, heatmapVert),
    heatmapTexture: prepare(heatmapTextureFrag, heatmapTextureVert),
    collisionBox: prepare(collisionBoxFrag, collisionBoxVert),
    collisionCircle: prepare(collisionCircleFrag, collisionCircleVert),
    colorRelief: prepare(colorReliefFrag, colorReliefVert),
    debug: prepare(debugFrag, debugVert),
    depth: prepare(clippingMaskFrag, depthVert),
    fill: prepare(fillFrag, fillVert),
    fillOutline: prepare(fillOutlineFrag, fillOutlineVert),
    fillOutlinePattern: prepare(fillOutlinePatternFrag, fillOutlinePatternVert),
    fillPattern: prepare(fillPatternFrag, fillPatternVert),
    fillExtrusion: prepare(fillExtrusionFrag, fillExtrusionVert),
    fillExtrusionPattern: prepare(fillExtrusionPatternFrag, fillExtrusionPatternVert),
    hillshadePrepare: prepare(hillshadePrepareFrag, hillshadePrepareVert),
    hillshade: prepare(hillshadeFrag, hillshadeVert),
    line: prepare(lineFrag, lineVert),
    lineGradient: prepare(lineGradientFrag, lineGradientVert),
    linePattern: prepare(linePatternFrag, linePatternVert),
    lineSDF: prepare(lineSDFFrag, lineSDFVert),
    lineGradientSDF: prepare(lineGradientSDFFrag, lineGradientSDFVert),
    raster: prepare(rasterFrag, rasterVert),
    symbolIcon: prepare(symbolIconFrag, symbolIconVert),
    symbolSDF: prepare(symbolSDFFrag, symbolSDFVert),
    symbolTextAndIcon: prepare(symbolTextAndIconFrag, symbolTextAndIconVert),
    terrain: prepare(terrainFrag, terrainVert),
    terrainDepth: prepare(terrainDepthFrag, terrainVertDepth),
    terrainCoords: prepare(terrainCoordsFrag, terrainVertCoords),
    projectionErrorMeasurement: prepare(projectionErrorMeasurementFrag, projectionErrorMeasurementVert),
    atmosphere: prepare(atmosphereFrag, atmosphereVert),
    sky: prepare(skyFrag, skyVert),
};
/** Expand #pragmas to #ifdefs, extract attributes and uniforms */
function prepare(fragmentSource, vertexSource) {
    const re = /#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g;
    const vertexAttributes = vertexSource.match(/in ([\w]+) ([\w]+)/g);
    const fragmentUniforms = fragmentSource.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g);
    const vertexUniforms = vertexSource.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g);
    const shaderUniforms = 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}
in ${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;
in ${precision} ${attrType} a_${name};
out ${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;
in ${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: vertexAttributes, staticUniforms: shaderUniforms };
}
/** Transpile WebGL2 vertex shader source to WebGL1 */
function transpileVertexShaderToWebGL1(source) {
    return source
        .replace(/\bin\s/g, 'attribute ')
        .replace(/\bout\s/g, 'varying ')
        .replace(/texture\(/g, 'texture2D(');
}
/** Transpile WebGL2 fragment shader source to WebGL1 */
function transpileFragmentShaderToWebGL1(source) {
    return source
        .replace(/\bin\s/g, 'varying ')
        .replace('out highp vec4 fragColor;', '')
        .replace(/fragColor/g, 'gl_FragColor')
        .replace(/texture\(/g, 'texture2D(');
}

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;
    }
}

var posAttributes = symbol_layout.createLayout([
    { name: 'a_pos', type: 'Int16', components: 2 }
]);

const MercatorShaderDefine = '#define PROJECTION_MERCATOR';
const MercatorShaderVariantKey = 'mercator';
class MercatorProjection {
    constructor() {
        this._cachedMesh = null;
    }
    get name() {
        return 'mercator';
    }
    get useSubdivision() {
        // Mercator never uses subdivision.
        return false;
    }
    get shaderVariantName() {
        return MercatorShaderVariantKey;
    }
    get shaderDefine() {
        return MercatorShaderDefine;
    }
    get shaderPreludeCode() {
        return shaders.projectionMercator;
    }
    get vertexShaderPreludeCode() {
        return shaders.projectionMercator.vertexSource;
    }
    get subdivisionGranularity() {
        return symbol_layout.SubdivisionGranularitySetting.noSubdivision;
    }
    get useGlobeControls() {
        return false;
    }
    get transitionState() {
        return 0;
    }
    get latitudeErrorCorrectionRadians() {
        return 0;
    }
    destroy() {
        // Do nothing.
    }
    updateGPUdependent(_) {
        // Do nothing.
    }
    getMeshFromTileID(context, _tileID, _hasBorder, _allowPoles, _usage) {
        if (this._cachedMesh) {
            return this._cachedMesh;
        }
        // The parameters tileID, hasBorder and allowPoles are all ignored on purpose for mercator meshes.
        const tileExtentArray = new symbol_layout.PosArray();
        tileExtentArray.emplaceBack(0, 0);
        tileExtentArray.emplaceBack(symbol_layout.EXTENT, 0);
        tileExtentArray.emplaceBack(0, symbol_layout.EXTENT);
        tileExtentArray.emplaceBack(symbol_layout.EXTENT, symbol_layout.EXTENT);
        const tileExtentBuffer = context.createVertexBuffer(tileExtentArray, posAttributes.members);
        const tileExtentSegments = symbol_layout.SegmentVector.simpleSegment(0, 0, 4, 2);
        const quadTriangleIndices = new symbol_layout.TriangleIndexArray();
        quadTriangleIndices.emplaceBack(1, 0, 2);
        quadTriangleIndices.emplaceBack(1, 2, 3);
        const quadTriangleIndexBuffer = context.createIndexBuffer(quadTriangleIndices);
        this._cachedMesh = new Mesh(tileExtentBuffer, quadTriangleIndexBuffer, tileExtentSegments);
        return this._cachedMesh;
    }
    recalculate() {
        // Do nothing.
    }
    hasTransition() {
        return false;
    }
    setErrorQueryLatitudeDegrees(_value) {
        // Do nothing.
    }
}

/**
 * An `EdgeInset` object represents screen space padding applied to the edges of the viewport.
 * This shifts the apparent 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 = symbol_layout.interpolateFactory.number(start.top, target.top, t);
        if (target.bottom != null && start.bottom != null)
            this.bottom = symbol_layout.interpolateFactory.number(start.bottom, target.bottom, t);
        if (target.left != null && start.left != null)
            this.left = symbol_layout.interpolateFactory.number(start.left, target.left, t);
        if (target.right != null && start.right != null)
            this.right = symbol_layout.interpolateFactory.number(start.right, target.right, t);
        return this;
    }
    /**
     * Utility method that computes the new apparent 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 = symbol_layout.clamp((this.left + width - this.right) / 2, 0, width);
        const y = symbol_layout.clamp((this.top + height - this.bottom) / 2, 0, height);
        return new symbol_layout.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
        };
    }
}

/**
 * If a path crossing the antimeridian would be shorter, extend the final coordinate so that
 * interpolating between the two endpoints will cross it.
 * @param center - The LngLat object of the desired center. This object will be mutated.
 */
function normalizeCenter(tr, center) {
    if (!tr.renderWorldCopies || tr.lngRange)
        return;
    const delta = center.lng - tr.center.lng;
    center.lng +=
        delta > 180 ? -360 :
            delta < -180 ? 360 : 0;
}
function getTileZoom(zoom) {
    return Math.max(0, Math.floor(zoom));
}
/**
 * @internal
 * This class stores all values that define a transform's state,
 * such as center, zoom, minZoom, etc.
 * This can be used as a helper for implementing the ITransform interface.
 */
class TransformHelper {
    constructor(callbacks, options) {
        var _a;
        this.applyConstrain = (lngLat, zoom) => {
            if (this._constrainOverride !== null) {
                return this._constrainOverride(lngLat, zoom);
            }
            else {
                return this._callbacks.defaultConstrain(lngLat, zoom);
            }
        };
        this._callbacks = callbacks;
        this._tileSize = 512; // constant
        this._renderWorldCopies = (options === null || options === void 0 ? void 0 : options.renderWorldCopies) === undefined ? true : !!(options === null || options === void 0 ? void 0 : options.renderWorldCopies);
        this._minZoom = (options === null || options === void 0 ? void 0 : options.minZoom) || 0;
        this._maxZoom = (options === null || options === void 0 ? void 0 : options.maxZoom) || 22;
        this._minPitch = ((options === null || options === void 0 ? void 0 : options.minPitch) === undefined || (options === null || options === void 0 ? void 0 : options.minPitch) === null) ? 0 : options === null || options === void 0 ? void 0 : options.minPitch;
        this._maxPitch = ((options === null || options === void 0 ? void 0 : options.maxPitch) === undefined || (options === null || options === void 0 ? void 0 : options.maxPitch) === null) ? 60 : options === null || options === void 0 ? void 0 : options.maxPitch;
        this._constrainOverride = (_a = options === null || options === void 0 ? void 0 : options.constrainOverride) !== null && _a !== void 0 ? _a : null;
        this.setMaxBounds();
        this._width = 0;
        this._height = 0;
        this._center = new symbol_layout.LngLat(0, 0);
        this._elevation = 0;
        this._zoom = 0;
        this._tileZoom = getTileZoom(this._zoom);
        this._scale = symbol_layout.zoomScale(this._zoom);
        this._bearingInRadians = 0;
        this._fovInRadians = 0.6435011087932844;
        this._pitchInRadians = 0;
        this._rollInRadians = 0;
        this._unmodified = true;
        this._edgeInsets = new EdgeInsets();
        this._minElevationForCurrentTile = 0;
        this._autoCalculateNearFarZ = true;
    }
    apply(thatI, constrain, forceOverrideZ) {
        this._constrainOverride = thatI.constrainOverride;
        this._latRange = thatI.latRange;
        this._lngRange = thatI.lngRange;
        this._width = thatI.width;
        this._height = thatI.height;
        this._center = thatI.center;
        this._elevation = thatI.elevation;
        this._minElevationForCurrentTile = thatI.minElevationForCurrentTile;
        this._zoom = thatI.zoom;
        this._tileZoom = getTileZoom(this._zoom);
        this._scale = symbol_layout.zoomScale(this._zoom);
        this._bearingInRadians = thatI.bearingInRadians;
        this._fovInRadians = thatI.fovInRadians;
        this._pitchInRadians = thatI.pitchInRadians;
        this._rollInRadians = thatI.rollInRadians;
        this._unmodified = thatI.unmodified;
        this._edgeInsets = new EdgeInsets(thatI.padding.top, thatI.padding.bottom, thatI.padding.left, thatI.padding.right);
        this._minZoom = thatI.minZoom;
        this._maxZoom = thatI.maxZoom;
        this._minPitch = thatI.minPitch;
        this._maxPitch = thatI.maxPitch;
        this._renderWorldCopies = thatI.renderWorldCopies;
        this._cameraToCenterDistance = thatI.cameraToCenterDistance;
        this._nearZ = thatI.nearZ;
        this._farZ = thatI.farZ;
        this._autoCalculateNearFarZ = !forceOverrideZ && thatI.autoCalculateNearFarZ;
        if (constrain) {
            this.constrainInternal();
        }
        this._calcMatrices();
    }
    get pixelsToClipSpaceMatrix() { return this._pixelsToClipSpaceMatrix; }
    get clipSpaceToPixelsMatrix() { return this._clipSpaceToPixelsMatrix; }
    get minElevationForCurrentTile() { return this._minElevationForCurrentTile; }
    setMinElevationForCurrentTile(ele) {
        this._minElevationForCurrentTile = ele;
    }
    get tileSize() { return this._tileSize; }
    get tileZoom() { return this._tileZoom; }
    get scale() { return this._scale; }
    /**
     * Gets the transform's width in pixels. Use {@link resize} to set the transform's size.
     */
    get width() { return this._width; }
    /**
     * Gets the transform's height in pixels. Use {@link resize} to set the transform's size.
     */
    get height() { return this._height; }
    /**
     * Gets the transform's bearing in radians.
     */
    get bearingInRadians() { return this._bearingInRadians; }
    get lngRange() { return this._lngRange; }
    get latRange() { return this._latRange; }
    get pixelsToGLUnits() { return this._pixelsToGLUnits; }
    get minZoom() { return this._minZoom; }
    setMinZoom(zoom) {
        if (this._minZoom === zoom)
            return;
        this._minZoom = zoom;
        this.setZoom(this.applyConstrain(this._center, this.zoom).zoom);
    }
    get maxZoom() { return this._maxZoom; }
    setMaxZoom(zoom) {
        if (this._maxZoom === zoom)
            return;
        this._maxZoom = zoom;
        this.setZoom(this.applyConstrain(this._center, this.zoom).zoom);
    }
    get minPitch() { return this._minPitch; }
    setMinPitch(pitch) {
        if (this._minPitch === pitch)
            return;
        this._minPitch = pitch;
        this.setPitch(Math.max(this.pitch, pitch));
    }
    get maxPitch() { return this._maxPitch; }
    setMaxPitch(pitch) {
        if (this._maxPitch === pitch)
            return;
        this._maxPitch = pitch;
        this.setPitch(Math.min(this.pitch, pitch));
    }
    get renderWorldCopies() { return this._renderWorldCopies; }
    setRenderWorldCopies(renderWorldCopies) {
        if (renderWorldCopies === undefined) {
            renderWorldCopies = true;
        }
        else if (renderWorldCopies === null) {
            renderWorldCopies = false;
        }
        this._renderWorldCopies = renderWorldCopies;
    }
    get constrainOverride() { return this._constrainOverride; }
    setConstrainOverride(constrain) {
        if (constrain === undefined)
            constrain = null;
        if (this._constrainOverride === constrain)
            return;
        this._constrainOverride = constrain;
        this.constrainInternal();
        this._calcMatrices();
    }
    get worldSize() {
        return this._tileSize * this._scale;
    }
    get centerOffset() {
        return this.centerPoint._sub(this.size._div(2));
    }
    /**
     * Gets the transform's dimensions packed into a Point object.
     */
    get size() {
        return new symbol_layout.Point(this._width, this._height);
    }
    get bearing() {
        return this._bearingInRadians / Math.PI * 180;
    }
    setBearing(bearing) {
        const b = symbol_layout.wrap(bearing, -180, 180) * Math.PI / 180;
        if (this._bearingInRadians === b)
            return;
        this._unmodified = false;
        this._bearingInRadians = b;
        this._calcMatrices();
        // 2x2 matrix for rotating points
        this._rotationMatrix = symbol_layout.create$1();
        symbol_layout.rotate(this._rotationMatrix, this._rotationMatrix, -this._bearingInRadians);
    }
    get rotationMatrix() { return this._rotationMatrix; }
    get pitchInRadians() {
        return this._pitchInRadians;
    }
    get pitch() {
        return this._pitchInRadians / Math.PI * 180;
    }
    setPitch(pitch) {
        const p = symbol_layout.clamp(pitch, this.minPitch, this.maxPitch) / 180 * Math.PI;
        if (this._pitchInRadians === p)
            return;
        this._unmodified = false;
        this._pitchInRadians = p;
        this._calcMatrices();
    }
    get rollInRadians() {
        return this._rollInRadians;
    }
    get roll() {
        return this._rollInRadians / Math.PI * 180;
    }
    setRoll(roll) {
        const r = roll / 180 * Math.PI;
        if (this._rollInRadians === r)
            return;
        this._unmodified = false;
        this._rollInRadians = r;
        this._calcMatrices();
    }
    get fovInRadians() {
        return this._fovInRadians;
    }
    get fov() {
        return symbol_layout.radiansToDegrees(this._fovInRadians);
    }
    setFov(fov) {
        fov = symbol_layout.clamp(fov, 0.1, 150);
        if (this.fov === fov)
            return;
        this._unmodified = false;
        this._fovInRadians = symbol_layout.degreesToRadians(fov);
        this._calcMatrices();
    }
    get zoom() { return this._zoom; }
    setZoom(zoom) {
        const constrainedZoom = this.applyConstrain(this._center, zoom).zoom;
        if (this._zoom === constrainedZoom)
            return;
        this._unmodified = false;
        this._zoom = constrainedZoom;
        this._tileZoom = Math.max(0, Math.floor(constrainedZoom));
        this._scale = symbol_layout.zoomScale(constrainedZoom);
        this.constrainInternal();
        this._calcMatrices();
    }
    get center() { return this._center; }
    setCenter(center) {
        if (center.lat === this._center.lat && center.lng === this._center.lng)
            return;
        this._unmodified = false;
        this._center = center;
        this.constrainInternal();
        this._calcMatrices();
    }
    /**
     * Elevation at current center point, meters above sea level
     */
    get elevation() { return this._elevation; }
    setElevation(elevation) {
        if (elevation === this._elevation)
            return;
        this._elevation = elevation;
        this.constrainInternal();
        this._calcMatrices();
    }
    get padding() { return this._edgeInsets.toJSON(); }
    setPadding(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);
    }
    /**
     * @internal
     */
    get pixelsPerMeter() { return this._pixelPerMeter; }
    get unmodified() { return this._unmodified; }
    get cameraToCenterDistance() { return this._cameraToCenterDistance; }
    get nearZ() { return this._nearZ; }
    get farZ() { return this._farZ; }
    get autoCalculateNearFarZ() { return this._autoCalculateNearFarZ; }
    overrideNearFarZ(nearZ, farZ) {
        this._autoCalculateNearFarZ = false;
        this._nearZ = nearZ;
        this._farZ = farZ;
        this._calcMatrices();
    }
    clearNearFarZOverride() {
        this._autoCalculateNearFarZ = true;
        this._calcMatrices();
    }
    /**
     * 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.constrainInternal();
        this._calcMatrices();
    }
    resize(width, height, constrain = true) {
        this._width = width;
        this._height = height;
        if (constrain)
            this.constrainInternal();
        this._calcMatrices();
    }
    /**
     * Returns the maximum geographical bounds the map is constrained to, or `null` if none set.
     * @returns max bounds
     */
    getMaxBounds() {
        var _a, _b;
        if (((_a = this._latRange) === null || _a === void 0 ? void 0 : _a.length) !== 2 ||
            ((_b = this._lngRange) === null || _b === void 0 ? void 0 : _b.length) !== 2)
            return null;
        return new LngLatBounds([this._lngRange[0], this._latRange[0]], [this._lngRange[1], this._latRange[1]]);
    }
    /**
     * 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.constrainInternal();
        }
        else {
            this._lngRange = null;
            this._latRange = [-symbol_layout.MAX_VALID_LATITUDE, symbol_layout.MAX_VALID_LATITUDE];
        }
    }
    /**
     * 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(cameraPoint, queryGeometry) {
        if (queryGeometry.length === 1) {
            return [queryGeometry[0], cameraPoint];
        }
        else {
            const { minX, minY, maxX, maxY } = symbol_layout.Bounds.fromPoints(queryGeometry).extend(cameraPoint);
            return [
                new symbol_layout.Point(minX, minY),
                new symbol_layout.Point(maxX, minY),
                new symbol_layout.Point(maxX, maxY),
                new symbol_layout.Point(minX, maxY),
                new symbol_layout.Point(minX, minY)
            ];
        }
    }
    /**
     * @internal
     * Snaps the transform's center, zoom, etc. into the valid range.
     */
    constrainInternal() {
        if (!this.center || !this._width || !this._height || this._constraining)
            return;
        this._constraining = true;
        const unmodified = this._unmodified;
        const { center, zoom } = this.applyConstrain(this.center, this.zoom);
        this.setCenter(center);
        this.setZoom(zoom);
        this._unmodified = unmodified;
        this._constraining = false;
    }
    /**
     * This function is called every time one of the transform's defining properties (center, pitch, etc.) changes.
     * This function should update the transform's internal data, such as matrices.
     * Any derived `_calcMatrices` function should also call the base function first. The base function only depends on the `_width` and `_height` fields.
     */
    _calcMatrices() {
        if (this._width && this._height) {
            this._pixelsToGLUnits = [2 / this._width, -2 / this._height];
            let m = symbol_layout.identity(new Float64Array(16));
            symbol_layout.scale(m, m, [this._width / 2, -this._height / 2, 1]);
            symbol_layout.translate(m, m, [1, -1, 0]);
            this._clipSpaceToPixelsMatrix = m;
            m = symbol_layout.identity(new Float64Array(16));
            symbol_layout.scale(m, m, [1, -1, 1]);
            symbol_layout.translate(m, m, [-1, -1, 0]);
            symbol_layout.scale(m, m, [2 / this._width, 2 / this._height, 1]);
            this._pixelsToClipSpaceMatrix = m;
            const halfFov = this.fovInRadians / 2;
            this._cameraToCenterDistance = 0.5 / Math.tan(halfFov) * this._height;
        }
        this._callbacks.calcMatrices();
    }
    calculateCenterFromCameraLngLatAlt(lnglat, alt, bearing, pitch) {
        const cameraBearing = bearing !== undefined ? bearing : this.bearing;
        const cameraPitch = pitch = pitch !== undefined ? pitch : this.pitch;
        const { distanceToCenter, clampedElevation } = this._distanceToCenterFromAltElevationPitch(alt, this.elevation, cameraPitch);
        const { x, y } = cameraDirectionFromPitchBearing(cameraPitch, cameraBearing);
        // The mercator transform scale changes with latitude. At high latitudes, there are more "Merc units" per meter
        // than at the equator. We treat the center point as our fundamental quantity. This means we want to convert
        // elevation to Mercator Z using the scale factor at the center point (not the camera point). Since the center point is
        // initially unknown, we compute it using the scale factor at the camera point. This gives us a better estimate of the
        // center point scale factor, which we use to recompute the center point. We repeat until the error is very small.
        // This typically takes about 5 iterations.
        const camMercator = symbol_layout.MercatorCoordinate.fromLngLat(lnglat, alt);
        let metersPerMercUnit = symbol_layout.altitudeFromMercatorZ(1, camMercator.y);
        let centerMercator;
        let dMercator;
        let iter = 0;
        const maxIter = 10;
        do {
            iter += 1;
            if (iter > maxIter) {
                break;
            }
            dMercator = distanceToCenter / metersPerMercUnit;
            const dx = x * dMercator;
            const dy = y * dMercator;
            centerMercator = new symbol_layout.MercatorCoordinate(camMercator.x + dx, camMercator.y + dy);
            metersPerMercUnit = 1 / centerMercator.meterInMercatorCoordinateUnits();
        } while (Math.abs(distanceToCenter - dMercator * metersPerMercUnit) > 1.0e-12);
        const center = centerMercator.toLngLat();
        const zoom = symbol_layout.scaleZoom(this.height / 2 / Math.tan(this.fovInRadians / 2) / dMercator / this.tileSize);
        return { center, elevation: clampedElevation, zoom };
    }
    recalculateZoomAndCenter(elevation) {
        if (this.elevation - elevation === 0)
            return;
        // Critical: Stay in pixels and use original center to avoid instability at extreme latitudes when using Mercator-LngLat
        const mercUnitsPerPixel = 1 / this.worldSize;
        const originalMercUnitsPerMeter = symbol_layout.mercatorZfromAltitude(1, this.center.lat);
        const originalPixelsPerMeter = originalMercUnitsPerMeter * this.worldSize;
        // Determine camera
        const originalCenterMercator = symbol_layout.MercatorCoordinate.fromLngLat(this.center, this.elevation);
        const originalCenterPixelX = originalCenterMercator.x / mercUnitsPerPixel;
        const originalCenterPixelY = originalCenterMercator.y / mercUnitsPerPixel;
        const originalCenterPixelZ = originalCenterMercator.z / mercUnitsPerPixel;
        const cameraPitch = this.pitch;
        const cameraBearing = this.bearing;
        const { x, y, z } = cameraDirectionFromPitchBearing(cameraPitch, cameraBearing);
        const dCamPixel = this.cameraToCenterDistance;
        const camPixelX = originalCenterPixelX + dCamPixel * -x;
        const camPixelY = originalCenterPixelY + dCamPixel * -y;
        const camPixelZ = originalCenterPixelZ + dCamPixel * z;
        // Determine corresponding center
        const { distanceToCenter, clampedElevation } = this._distanceToCenterFromAltElevationPitch(camPixelZ / originalPixelsPerMeter, elevation, cameraPitch);
        const distanceToCenterPixels = distanceToCenter * originalPixelsPerMeter;
        const centerPixelX = camPixelX + x * distanceToCenterPixels;
        const centerPixelY = camPixelY + y * distanceToCenterPixels;
        const center = new symbol_layout.MercatorCoordinate(centerPixelX * mercUnitsPerPixel, centerPixelY * mercUnitsPerPixel, 0).toLngLat();
        const mercUnitsPerMeter = symbol_layout.mercatorZfromAltitude(1, center.lat);
        const zoom = symbol_layout.scaleZoom(this.height / 2 / Math.tan(this.fovInRadians / 2) / distanceToCenter / mercUnitsPerMeter / this.tileSize);
        // Update matrices
        this._elevation = clampedElevation;
        this._center = center;
        this.setZoom(zoom);
    }
    _distanceToCenterFromAltElevationPitch(alt, elevation, pitch) {
        const dzNormalized = -Math.cos(symbol_layout.degreesToRadians(pitch));
        const altitudeAGL = alt - elevation;
        let distanceToCenter;
        let clampedElevation = elevation;
        if (dzNormalized * altitudeAGL >= 0.0 || Math.abs(dzNormalized) < 0.1) {
            distanceToCenter = 10000;
            clampedElevation = alt + distanceToCenter * dzNormalized;
        }
        else {
            distanceToCenter = -altitudeAGL / dzNormalized;
        }
        return { distanceToCenter, clampedElevation };
    }
    getCameraPoint() {
        const pitch = this.pitchInRadians;
        const offset = Math.tan(pitch) * (this.cameraToCenterDistance || 1);
        return this.centerPoint.add(new symbol_layout.Point(offset * Math.sin(this.rollInRadians), offset * Math.cos(this.rollInRadians)));
    }
    getCameraAltitude() {
        const altitude = Math.cos(this.pitchInRadians) * this._cameraToCenterDistance / this._pixelPerMeter;
        return altitude + this.elevation;
    }
    getCameraLngLat() {
        const pixelPerMeter = symbol_layout.mercatorZfromAltitude(1, this.center.lat) * this.worldSize;
        const cameraToCenterDistanceMeters = this.cameraToCenterDistance / pixelPerMeter;
        const camMercator = cameraMercatorCoordinateFromCenterAndRotation(this.center, this.elevation, this.pitch, this.bearing, cameraToCenterDistanceMeters);
        return camMercator.toLngLat();
    }
    getMercatorTileCoordinates(overscaledTileID) {
        if (!overscaledTileID) {
            return [0, 0, 1, 1];
        }
        const scale = (overscaledTileID.canonical.z >= 0) ? (1 << overscaledTileID.canonical.z) : Math.pow(2.0, overscaledTileID.canonical.z);
        return [
            overscaledTileID.canonical.x / scale,
            overscaledTileID.canonical.y / scale,
            1.0 / scale / symbol_layout.EXTENT,
            1.0 / scale / symbol_layout.EXTENT
        ];
    }
}

class Aabb {
    constructor(min_, max_) {
        this.min = min_;
        this.max = max_;
        this.center = symbol_layout.scale$2([], symbol_layout.add([], this.min, this.max), 0.5);
    }
    quadrant(index) {
        const split = [(index % 2) === 0, index < 2];
        const qMin = symbol_layout.clone(this.min);
        const qMax = symbol_layout.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.
     */
    intersectsFrustum(frustum) {
        // Execute separating axis test between two convex objects to find intersections
        // Each frustum plane together with 3 major axes define the separating axes
        let fullyInside = true;
        for (const plane of frustum.planes) {
            const planeIntersection = this.intersectsPlane(plane);
            if (planeIntersection === 0 /* IntersectionResult.None */) {
                return 0 /* IntersectionResult.None */;
            }
            if (planeIntersection === 1 /* IntersectionResult.Partial */) {
                fullyInside = false;
            }
        }
        if (fullyInside) {
            return 2 /* IntersectionResult.Full */;
        }
        if (frustum.aabb.min[0] > this.max[0] || frustum.aabb.min[1] > this.max[1] || frustum.aabb.min[2] > this.max[2] ||
            frustum.aabb.max[0] < this.min[0] || frustum.aabb.max[1] < this.min[1] || frustum.aabb.max[2] < this.min[2]) {
            return 0 /* IntersectionResult.None */;
        }
        return 1 /* IntersectionResult.Partial */;
    }
    /**
     * Performs a halfspace-aabb intersection test.
     */
    intersectsPlane(plane) {
        let distMin = plane[3];
        let distMax = plane[3];
        for (let i = 0; i < 3; i++) {
            if (plane[i] > 0) {
                distMin += plane[i] * this.min[i];
                distMax += plane[i] * this.max[i];
            }
            else {
                distMax += plane[i] * this.min[i];
                distMin += plane[i] * this.max[i];
            }
        }
        if (distMin >= 0) {
            return 2 /* IntersectionResult.Full */;
        }
        if (distMax < 0) {
            return 0 /* IntersectionResult.None */;
        }
        return 1 /* IntersectionResult.Partial */;
    }
}

class MercatorCoveringTilesDetailsProvider {
    distanceToTile2d(pointX, pointY, _tileID, boundingVolume) {
        const aabb = boundingVolume;
        const distanceX = aabb.distanceX([pointX, pointY]);
        const distanceY = aabb.distanceY([pointX, pointY]);
        return Math.hypot(distanceX, distanceY);
    }
    /**
     * Returns the wrap value for a given tile, computed so that tiles will remain loaded when crossing the antimeridian.
     */
    getWrap(centerCoord, tileID, parentWrap) {
        return parentWrap;
    }
    /**
     * Returns the AABB of the specified tile.
     * @param tileID - Tile x, y and z for zoom.
     */
    getTileBoundingVolume(tileID, wrap, elevation, options) {
        var _a, _b;
        let minElevation = 0;
        let maxElevation = 0;
        if (options === null || options === void 0 ? void 0 : options.terrain) {
            const overscaledTileID = new symbol_layout.OverscaledTileID(tileID.z, wrap, tileID.z, tileID.x, tileID.y);
            const minMax = options.terrain.getMinMaxElevation(overscaledTileID);
            minElevation = (_a = minMax.minElevation) !== null && _a !== void 0 ? _a : Math.min(0, elevation);
            maxElevation = (_b = minMax.maxElevation) !== null && _b !== void 0 ? _b : Math.max(0, elevation);
        }
        const numTiles = 1 << tileID.z;
        return new Aabb([wrap + tileID.x / numTiles, tileID.y / numTiles, minElevation], [wrap + (tileID.x + 1) / numTiles, (tileID.y + 1) / numTiles, maxElevation]);
    }
    allowVariableZoom(transform, options) {
        const zfov = transform.fov * (Math.abs(Math.cos(transform.rollInRadians)) * transform.height + Math.abs(Math.sin(transform.rollInRadians)) * transform.width) / transform.height;
        const maxConstantZoomPitch = symbol_layout.clamp(78.5 - zfov / 2, 0.0, 60.0);
        return (!!options.terrain || transform.pitch > maxConstantZoomPitch);
    }
    allowWorldCopies() {
        return true;
    }
    prepareNextFrame() {
        // Do nothing
    }
}

class Frustum {
    constructor(points, planes, aabb) {
        this.points = points;
        this.planes = planes;
        this.aabb = aabb;
    }
    static fromInvProjectionMatrix(invProj, worldSize = 1, zoom = 0, horizonPlane, flippedNearFar) {
        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]
        ];
        // Globe and mercator projection matrices have different Y directions, hence we need different sets of indices.
        // This should be fixed in the future.
        const frustumPlanePointIndices = flippedNearFar ? [
            [6, 5, 4], // near
            [0, 1, 2], // far
            [0, 3, 7], // left
            [2, 1, 5], // right
            [3, 2, 6], // bottom
            [0, 4, 5] // top
        ] : [
            [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 scale = Math.pow(2, zoom);
        // Transform frustum corner points from clip space to tile space, Z to meters
        const frustumCoords = clipSpaceCorners.map(v => unprojectClipSpacePoint(v, invProj, worldSize, scale));
        if (horizonPlane) {
            // A horizon clipping plane was supplied.
            adjustFarPlaneByHorizonPlane(frustumCoords, frustumPlanePointIndices[0], horizonPlane, flippedNearFar);
        }
        const frustumPlanes = frustumPlanePointIndices.map((p) => {
            const a = symbol_layout.sub([], frustumCoords[p[0]], frustumCoords[p[1]]);
            const b = symbol_layout.sub([], frustumCoords[p[2]], frustumCoords[p[1]]);
            const n = symbol_layout.normalize([], symbol_layout.cross([], a, b));
            const d = -symbol_layout.dot(n, frustumCoords[p[1]]);
            return n.concat(d);
        });
        const min = [Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY];
        const max = [Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY];
        for (const p of frustumCoords) {
            for (let i = 0; i < 3; i++) {
                min[i] = Math.min(min[i], p[i]);
                max[i] = Math.max(max[i], p[i]);
            }
        }
        return new Frustum(frustumCoords, frustumPlanes, new Aabb(min, max));
    }
}
function unprojectClipSpacePoint(point, invProj, worldSize, scale) {
    const v = symbol_layout.transformMat4([], point, invProj);
    const s = 1.0 / v[3] / worldSize * scale;
    return symbol_layout.mul(v, v, [s, s, 1.0 / v[3], s]);
}
/**
 * Modifies points in the supplied `frustumCoords` array so that the frustum's far plane only lies as far as the horizon,
 * which improves frustum culling effectiveness.
 * @param frustumCoords - Points of the frustum.
 * @param nearPlanePointsIndices - Which indices in the `frustumCoords` form the near plane.
 * @param horizonPlane - The horizon plane.
 */
function adjustFarPlaneByHorizonPlane(frustumCoords, nearPlanePointsIndices, horizonPlane, flippedNearFar) {
    // For each of the 4 edges from near to far plane,
    // we find at which distance these edges intersect the given clipping plane,
    // select the maximal value from these distances and then we move
    // the frustum's far plane so that it is at most as far away from the near plane
    // as this maximal distance.
    const nearPlanePointsOffset = flippedNearFar ? 4 : 0;
    const farPlanePointsOffset = flippedNearFar ? 0 : 4;
    let maxDist = 0;
    const cornerRayLengths = [];
    const cornerRayNormalizedDirections = [];
    for (let i = 0; i < 4; i++) {
        const dir = symbol_layout.sub([], frustumCoords[i + farPlanePointsOffset], frustumCoords[i + nearPlanePointsOffset]);
        const len = symbol_layout.length$1(dir);
        symbol_layout.scale$2(dir, dir, 1.0 / len); // normalize
        cornerRayLengths.push(len);
        cornerRayNormalizedDirections.push(dir);
    }
    for (let i = 0; i < 4; i++) {
        const dist = symbol_layout.rayPlaneIntersection(frustumCoords[i + nearPlanePointsOffset], cornerRayNormalizedDirections[i], horizonPlane);
        if (dist !== null && dist >= 0) {
            maxDist = Math.max(maxDist, dist);
        }
        else {
            // Use the original ray length for rays parallel to the horizon plane, or for rays pointing away from it.
            maxDist = Math.max(maxDist, cornerRayLengths[i]);
        }
    }
    // Compute the near plane.
    // We use its normal as the "view vector" - direction in which the camera is looking.
    const nearPlaneNormalized = getNormalizedNearPlane(frustumCoords, nearPlanePointsIndices);
    // We also try to adjust the far plane position so that it exactly intersects the point on the horizon
    // that is most distant from the near plane.
    const idealFarPlaneDistanceFromNearPlane = getIdealNearFarPlaneDistance(horizonPlane, nearPlaneNormalized);
    if (idealFarPlaneDistanceFromNearPlane !== null) {
        const idealCornerRayLength = idealFarPlaneDistanceFromNearPlane / symbol_layout.dot(cornerRayNormalizedDirections[0], nearPlaneNormalized); // dot(near plane, ray dir) is the same for all 4 corners
        maxDist = Math.min(maxDist, idealCornerRayLength);
    }
    for (let i = 0; i < 4; i++) {
        const targetLength = Math.min(maxDist, cornerRayLengths[i]);
        frustumCoords[i + farPlanePointsOffset] = [
            frustumCoords[i + nearPlanePointsOffset][0] + cornerRayNormalizedDirections[i][0] * targetLength,
            frustumCoords[i + nearPlanePointsOffset][1] + cornerRayNormalizedDirections[i][1] * targetLength,
            frustumCoords[i + nearPlanePointsOffset][2] + cornerRayNormalizedDirections[i][2] * targetLength,
            1,
        ];
    }
}
/**
 * Returns the near plane equation with unit length direction.
 * @param frustumCoords - Points of the frustum.
 * @param nearPlanePointsIndices - Which indices in the `frustumCoords` form the near plane.
 */
function getNormalizedNearPlane(frustumCoords, nearPlanePointsIndices) {
    const nearPlaneA = symbol_layout.sub([], frustumCoords[nearPlanePointsIndices[0]], frustumCoords[nearPlanePointsIndices[1]]);
    const nearPlaneB = symbol_layout.sub([], frustumCoords[nearPlanePointsIndices[2]], frustumCoords[nearPlanePointsIndices[1]]);
    const nearPlaneNormalized = [0, 0, 0, 0];
    symbol_layout.normalize(nearPlaneNormalized, symbol_layout.cross([], nearPlaneA, nearPlaneB));
    nearPlaneNormalized[3] = -symbol_layout.dot(nearPlaneNormalized, frustumCoords[nearPlanePointsIndices[0]]);
    return nearPlaneNormalized;
}
/**
 * Returns the ideal distance between the frustum's near and far plane so that the far plane only lies as far as the horizon.
 */
function getIdealNearFarPlaneDistance(horizonPlane, nearPlaneNormalized) {
    // Normalize the horizon plane to unit direction
    const horizonPlaneLen = symbol_layout.len(horizonPlane);
    const normalizedHorizonPlane = symbol_layout.scale$3([], horizonPlane, 1 / horizonPlaneLen);
    // Project the view vector onto the horizon plane
    const projectedViewDirection = symbol_layout.sub([], nearPlaneNormalized, symbol_layout.scale$2([], normalizedHorizonPlane, symbol_layout.dot(nearPlaneNormalized, normalizedHorizonPlane)));
    const projectedViewLength = symbol_layout.len(projectedViewDirection);
    // projectedViewLength will be 0 if the camera is looking straight down
    if (projectedViewLength > 0) {
        // Find the radius and center of the horizon circle (the horizon circle is the intersection of the planet's sphere and the horizon plane).
        const horizonCircleRadius = Math.sqrt(1 - normalizedHorizonPlane[3] * normalizedHorizonPlane[3]);
        const horizonCircleCenter = symbol_layout.scale$2([], normalizedHorizonPlane, -normalizedHorizonPlane[3]); // The horizon plane normal always points towards the camera.
        // Find the furthest point on the horizon circle from the near plane.
        const pointFurthestOnHorizonCircle = symbol_layout.add([], horizonCircleCenter, symbol_layout.scale$2([], projectedViewDirection, horizonCircleRadius / projectedViewLength));
        // Compute this point's distance from the near plane.
        return symbol_layout.pointPlaneSignedDistance(nearPlaneNormalized, pointFurthestOnHorizonCircle);
    }
    else {
        return null;
    }
}

class MercatorTransform {
    //
    // Implementation of transform getters and setters
    //
    get pixelsToClipSpaceMatrix() {
        return this._helper.pixelsToClipSpaceMatrix;
    }
    get clipSpaceToPixelsMatrix() {
        return this._helper.clipSpaceToPixelsMatrix;
    }
    get pixelsToGLUnits() {
        return this._helper.pixelsToGLUnits;
    }
    get centerOffset() {
        return this._helper.centerOffset;
    }
    get size() {
        return this._helper.size;
    }
    get rotationMatrix() {
        return this._helper.rotationMatrix;
    }
    get centerPoint() {
        return this._helper.centerPoint;
    }
    get pixelsPerMeter() {
        return this._helper.pixelsPerMeter;
    }
    setMinZoom(zoom) {
        this._helper.setMinZoom(zoom);
    }
    setMaxZoom(zoom) {
        this._helper.setMaxZoom(zoom);
    }
    setMinPitch(pitch) {
        this._helper.setMinPitch(pitch);
    }
    setMaxPitch(pitch) {
        this._helper.setMaxPitch(pitch);
    }
    setRenderWorldCopies(renderWorldCopies) {
        this._helper.setRenderWorldCopies(renderWorldCopies);
    }
    setBearing(bearing) {
        this._helper.setBearing(bearing);
    }
    setPitch(pitch) {
        this._helper.setPitch(pitch);
    }
    setRoll(roll) {
        this._helper.setRoll(roll);
    }
    setFov(fov) {
        this._helper.setFov(fov);
    }
    setZoom(zoom) {
        this._helper.setZoom(zoom);
    }
    setCenter(center) {
        this._helper.setCenter(center);
    }
    setElevation(elevation) {
        this._helper.setElevation(elevation);
    }
    setMinElevationForCurrentTile(elevation) {
        this._helper.setMinElevationForCurrentTile(elevation);
    }
    setPadding(padding) {
        this._helper.setPadding(padding);
    }
    interpolatePadding(start, target, t) {
        this._helper.interpolatePadding(start, target, t);
    }
    isPaddingEqual(padding) {
        return this._helper.isPaddingEqual(padding);
    }
    resize(width, height, constrain = true) {
        this._helper.resize(width, height, constrain);
    }
    getMaxBounds() {
        return this._helper.getMaxBounds();
    }
    setMaxBounds(bounds) {
        this._helper.setMaxBounds(bounds);
    }
    setConstrainOverride(constrain) {
        this._helper.setConstrainOverride(constrain);
    }
    overrideNearFarZ(nearZ, farZ) {
        this._helper.overrideNearFarZ(nearZ, farZ);
    }
    clearNearFarZOverride() {
        this._helper.clearNearFarZOverride();
    }
    getCameraQueryGeometry(queryGeometry) {
        return this._helper.getCameraQueryGeometry(this.getCameraPoint(), queryGeometry);
    }
    get tileSize() {
        return this._helper.tileSize;
    }
    get tileZoom() {
        return this._helper.tileZoom;
    }
    get scale() {
        return this._helper.scale;
    }
    get worldSize() {
        return this._helper.worldSize;
    }
    get width() {
        return this._helper.width;
    }
    get height() {
        return this._helper.height;
    }
    get lngRange() {
        return this._helper.lngRange;
    }
    get latRange() {
        return this._helper.latRange;
    }
    get minZoom() {
        return this._helper.minZoom;
    }
    get maxZoom() {
        return this._helper.maxZoom;
    }
    get zoom() {
        return this._helper.zoom;
    }
    get center() {
        return this._helper.center;
    }
    get minPitch() {
        return this._helper.minPitch;
    }
    get maxPitch() {
        return this._helper.maxPitch;
    }
    get pitch() {
        return this._helper.pitch;
    }
    get pitchInRadians() {
        return this._helper.pitchInRadians;
    }
    get roll() {
        return this._helper.roll;
    }
    get rollInRadians() {
        return this._helper.rollInRadians;
    }
    get bearing() {
        return this._helper.bearing;
    }
    get bearingInRadians() {
        return this._helper.bearingInRadians;
    }
    get fov() {
        return this._helper.fov;
    }
    get fovInRadians() {
        return this._helper.fovInRadians;
    }
    get elevation() {
        return this._helper.elevation;
    }
    get minElevationForCurrentTile() {
        return this._helper.minElevationForCurrentTile;
    }
    get padding() {
        return this._helper.padding;
    }
    get unmodified() {
        return this._helper.unmodified;
    }
    get renderWorldCopies() {
        return this._helper.renderWorldCopies;
    }
    get cameraToCenterDistance() {
        return this._helper.cameraToCenterDistance;
    }
    get constrainOverride() {
        return this._helper.constrainOverride;
    }
    get nearZ() {
        return this._helper.nearZ;
    }
    get farZ() {
        return this._helper.farZ;
    }
    get autoCalculateNearFarZ() {
        return this._helper.autoCalculateNearFarZ;
    }
    setTransitionState(_value, _error) {
        // Do nothing
    }
    constructor(options) {
        this._posMatrixCache = new Map();
        this._alignedPosMatrixCache = new Map();
        this._fogMatrixCacheF32 = new Map();
        /**
         * This mercator implementation returns 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.
         */
        this.defaultConstrain = (lngLat, zoom) => {
            zoom = symbol_layout.clamp(+zoom, this.minZoom, this.maxZoom);
            const result = {
                center: new symbol_layout.LngLat(lngLat.lng, lngLat.lat),
                zoom
            };
            let lngRange = this._helper._lngRange;
            if (!this._helper._renderWorldCopies && lngRange === null) {
                const almost180 = 180 - 1e-10;
                lngRange = [-almost180, almost180];
            }
            const worldSize = this.tileSize * symbol_layout.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._helper._latRange) {
                const latRange = this._helper._latRange;
                minY = symbol_layout.mercatorYfromLat(latRange[1]) * worldSize;
                maxY = symbol_layout.mercatorYfromLat(latRange[0]) * worldSize;
                const shouldZoomIn = maxY - minY < screenHeight;
                if (shouldZoomIn)
                    scaleY = screenHeight / (maxY - minY);
            }
            if (lngRange) {
                minX = symbol_layout.wrap(symbol_layout.mercatorXfromLng(lngRange[0]) * worldSize, 0, worldSize);
                maxX = symbol_layout.wrap(symbol_layout.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 } = projectToWorldCoordinates(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 symbol_layout.Point(scaleX ? (maxX + minX) / 2 : originalX, scaleY ? (maxY + minY) / 2 : originalY);
                result.center = unprojectFromWorldCoordinates(worldSize, newPoint).wrap();
                result.zoom += symbol_layout.scaleZoom(scale);
                return result;
            }
            if (this._helper._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._helper._renderWorldCopies) {
                    wrappedX = symbol_layout.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 symbol_layout.Point(modifiedX !== null && modifiedX !== void 0 ? modifiedX : originalX, modifiedY !== null && modifiedY !== void 0 ? modifiedY : originalY);
                result.center = unprojectFromWorldCoordinates(worldSize, newPoint).wrap();
            }
            return result;
        };
        this.applyConstrain = (lngLat, zoom) => {
            return this._helper.applyConstrain(lngLat, zoom);
        };
        this._helper = new TransformHelper({
            calcMatrices: () => this._calcMatrices(),
            defaultConstrain: (center, zoom) => { return this.defaultConstrain(center, zoom); }
        }, options);
        this._coveringTilesDetailsProvider = new MercatorCoveringTilesDetailsProvider();
    }
    clone() {
        const clone = new MercatorTransform();
        clone.apply(this, false);
        return clone;
    }
    apply(that, constrain, forceOverrideZ) {
        this._helper.apply(that, constrain, forceOverrideZ);
    }
    get cameraPosition() { return this._cameraPosition; }
    get projectionMatrix() { return this._projectionMatrix; }
    get modelViewProjectionMatrix() { return this._viewProjMatrix; }
    get inverseProjectionMatrix() { return this._invProjMatrix; }
    get mercatorMatrix() { return this._mercatorMatrix; } // Not part of ITransform interface
    getVisibleUnwrappedCoordinates(tileID) {
        const result = [new symbol_layout.UnwrappedTileID(0, tileID)];
        if (this._helper._renderWorldCopies) {
            const utl = this.screenPointToMercatorCoordinate(new symbol_layout.Point(0, 0));
            const utr = this.screenPointToMercatorCoordinate(new symbol_layout.Point(this._helper._width, 0));
            const ubl = this.screenPointToMercatorCoordinate(new symbol_layout.Point(this._helper._width, this._helper._height));
            const ubr = this.screenPointToMercatorCoordinate(new symbol_layout.Point(0, this._helper._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 symbol_layout.UnwrappedTileID(w, tileID));
            }
        }
        return result;
    }
    getCameraFrustum() {
        return Frustum.fromInvProjectionMatrix(this._invViewProjMatrix, this.worldSize);
    }
    getClippingPlane() {
        return null;
    }
    getCoveringTilesDetailsProvider() {
        return this._coveringTilesDetailsProvider;
    }
    recalculateZoomAndCenter(terrain) {
        // find position the camera is looking on
        const center = this.screenPointToLocation(this.centerPoint, terrain);
        const elevation = terrain ? terrain.getElevationForLngLatZoom(center, this._helper._tileZoom) : 0;
        this._helper.recalculateZoomAndCenter(elevation);
    }
    setLocationAtPoint(lnglat, point) {
        const z = symbol_layout.mercatorZfromAltitude(this.elevation, this.center.lat);
        const a = this.screenPointToMercatorCoordinateAtZ(point, z);
        const b = this.screenPointToMercatorCoordinateAtZ(this.centerPoint, z);
        const loc = symbol_layout.MercatorCoordinate.fromLngLat(lnglat);
        const newCenter = new symbol_layout.MercatorCoordinate(loc.x - (a.x - b.x), loc.y - (a.y - b.y));
        this.setCenter(newCenter === null || newCenter === void 0 ? void 0 : newCenter.toLngLat());
        if (this._helper._renderWorldCopies) {
            this.setCenter(this.center.wrap());
        }
    }
    locationToScreenPoint(lnglat, terrain) {
        return terrain ?
            this.coordinatePoint(symbol_layout.MercatorCoordinate.fromLngLat(lnglat), terrain.getElevationForLngLat(lnglat, this), this._pixelMatrix3D) :
            this.coordinatePoint(symbol_layout.MercatorCoordinate.fromLngLat(lnglat));
    }
    screenPointToLocation(p, terrain) {
        var _a;
        return (_a = this.screenPointToMercatorCoordinate(p, terrain)) === null || _a === void 0 ? void 0 : _a.toLngLat();
    }
    screenPointToMercatorCoordinate(p, terrain) {
        // get point-coordinate from terrain coordinates framebuffer
        if (terrain) {
            const coordinate = terrain.pointCoordinate(p);
            if (coordinate != null) {
                return coordinate;
            }
        }
        return this.screenPointToMercatorCoordinateAtZ(p);
    }
    screenPointToMercatorCoordinateAtZ(p, mercatorZ) {
        // calculate point-coordinate on flat earth
        const targetZ = mercatorZ ? mercatorZ : 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];
        symbol_layout.transformMat4(coord0, coord0, this._pixelMatrixInverse);
        symbol_layout.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 symbol_layout.MercatorCoordinate(symbol_layout.interpolateFactory.number(x0, x1, t) / this.worldSize, symbol_layout.interpolateFactory.number(y0, y1, t) / this.worldSize, targetZ);
    }
    /**
     * 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];
        symbol_layout.transformMat4(p, p, pixelMatrix);
        return new symbol_layout.Point(p[0] / p[3], p[1] / p[3]);
    }
    getBounds() {
        const top = Math.max(0, this._helper._height / 2 - getMercatorHorizon(this));
        return new LngLatBounds()
            .extend(this.screenPointToLocation(new symbol_layout.Point(0, top)))
            .extend(this.screenPointToLocation(new symbol_layout.Point(this._helper._width, top)))
            .extend(this.screenPointToLocation(new symbol_layout.Point(this._helper._width, this._helper._height)))
            .extend(this.screenPointToLocation(new symbol_layout.Point(0, this._helper._height)));
    }
    isPointOnMapSurface(p, terrain) {
        if (terrain) {
            const coordinate = terrain.pointCoordinate(p);
            return coordinate != null;
        }
        return (p.y > this.height / 2 - getMercatorHorizon(this));
    }
    /**
     * Calculate the posMatrix that, given a tile coordinate, would be used to display the tile on a map.
     * This function is specific to the mercator projection.
     * @param tileID - the tile ID
     * @param aligned - whether to use a pixel-aligned matrix variant, intended for rendering raster tiles
     * @param useFloat32 - when true, returns a float32 matrix instead of float64. Use float32 for matrices that are passed to shaders, use float64 for everything else.
     */
    calculatePosMatrix(tileID, aligned = false, useFloat32) {
        var _a;
        const posMatrixKey = (_a = tileID.key) !== null && _a !== void 0 ? _a : symbol_layout.calculateTileKey(tileID.wrap, tileID.canonical.z, tileID.canonical.z, tileID.canonical.x, tileID.canonical.y);
        const cache = aligned ? this._alignedPosMatrixCache : this._posMatrixCache;
        if (cache.has(posMatrixKey)) {
            const matrices = cache.get(posMatrixKey);
            return useFloat32 ? matrices.f32 : matrices.f64;
        }
        const tileMatrix = calculateTileMatrix(tileID, this.worldSize);
        symbol_layout.multiply(tileMatrix, aligned ? this._alignedProjMatrix : this._viewProjMatrix, tileMatrix);
        const matrices = {
            f64: tileMatrix,
            f32: new Float32Array(tileMatrix), // Must have a 32 bit float version for WebGL, otherwise WebGL calls in Chrome get very slow.
        };
        cache.set(posMatrixKey, matrices);
        // Make sure to return the correct precision
        return useFloat32 ? matrices.f32 : matrices.f64;
    }
    calculateFogMatrix(unwrappedTileID) {
        const posMatrixKey = unwrappedTileID.key;
        const cache = this._fogMatrixCacheF32;
        if (cache.has(posMatrixKey)) {
            return cache.get(posMatrixKey);
        }
        const fogMatrix = calculateTileMatrix(unwrappedTileID, this.worldSize);
        symbol_layout.multiply(fogMatrix, this._fogMatrix, fogMatrix);
        cache.set(posMatrixKey, new Float32Array(fogMatrix)); // Must be 32 bit floats, otherwise WebGL calls in Chrome get very slow.
        return cache.get(posMatrixKey);
    }
    calculateCenterFromCameraLngLatAlt(lnglat, alt, bearing, pitch) {
        return this._helper.calculateCenterFromCameraLngLatAlt(lnglat, alt, bearing, pitch);
    }
    _calculateNearFarZIfNeeded(cameraToSeaLevelDistance, limitedPitchRadians, offset) {
        if (!this._helper.autoCalculateNearFarZ) {
            return;
        }
        // In case of negative minimum elevation (e.g. the dead see, under the sea maps) use a lower plane for calculation
        const minRenderDistanceBelowCameraInMeters = 100;
        const minElevation = Math.min(this.elevation, this.minElevationForCurrentTile, this.getCameraAltitude() - minRenderDistanceBelowCameraInMeters);
        const cameraToLowestPointDistance = cameraToSeaLevelDistance - minElevation * this._helper._pixelPerMeter / Math.cos(limitedPitchRadians);
        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.pitchInRadians;
        const zfov = symbol_layout.degreesToRadians(this.fov) * (Math.abs(Math.cos(symbol_layout.degreesToRadians(this.roll))) * this.height + Math.abs(Math.sin(symbol_layout.degreesToRadians(this.roll))) * this.width) / this.height;
        const fovAboveCenter = zfov * (0.5 + offset.y / this.height);
        const topHalfSurfaceDistance = Math.sin(fovAboveCenter) * lowestPlane / Math.sin(symbol_layout.clamp(Math.PI - groundAngle - fovAboveCenter, 0.01, Math.PI - 0.01));
        // Find the distance from the center point to the horizon
        const horizon = getMercatorHorizon(this);
        const horizonAngle = Math.atan(horizon / this._helper.cameraToCenterDistance);
        const minFovCenterToHorizonRadians = symbol_layout.degreesToRadians(90 - maxMercatorHorizonAngle);
        const fovCenterToHorizon = horizonAngle > minFovCenterToHorizonRadians ? 2 * horizonAngle * (0.5 + offset.y / (horizon * 2)) : minFovCenterToHorizonRadians;
        const topHalfSurfaceDistanceHorizon = Math.sin(fovCenterToHorizon) * lowestPlane / Math.sin(symbol_layout.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._helper._farZ = (Math.cos(Math.PI / 2 - limitedPitchRadians) * 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._helper._nearZ = this._helper._height / 50;
    }
    _calcMatrices() {
        if (!this._helper._height)
            return;
        const offset = this.centerOffset;
        const point = projectToWorldCoordinates(this.worldSize, this.center);
        const x = point.x, y = point.y;
        this._helper._pixelPerMeter = symbol_layout.mercatorZfromAltitude(1, this.center.lat) * this.worldSize;
        // Calculate the camera to sea-level distance in pixel in respect of terrain
        const limitedPitchRadians = symbol_layout.degreesToRadians(Math.min(this.pitch, maxMercatorHorizonAngle));
        const cameraToSeaLevelDistance = Math.max(this._helper.cameraToCenterDistance / 2, this._helper.cameraToCenterDistance + this._helper._elevation * this._helper._pixelPerMeter / Math.cos(limitedPitchRadians));
        this._calculateNearFarZIfNeeded(cameraToSeaLevelDistance, limitedPitchRadians, offset);
        // matrix for conversion from location to clip space(-1 .. 1)
        let m;
        m = new Float64Array(16);
        symbol_layout.perspective(m, this.fovInRadians, this._helper._width / this._helper._height, this._helper._nearZ, this._helper._farZ);
        this._invProjMatrix = new Float64Array(16);
        symbol_layout.invert$1(this._invProjMatrix, m);
        // Apply center of perspective offset
        m[8] = -offset.x * 2 / this._helper._width;
        m[9] = offset.y * 2 / this._helper._height;
        this._projectionMatrix = symbol_layout.clone$1(m);
        symbol_layout.scale(m, m, [1, -1, 1]);
        symbol_layout.translate(m, m, [0, 0, -this._helper.cameraToCenterDistance]);
        symbol_layout.rotateZ(m, m, -this.rollInRadians);
        symbol_layout.rotateX(m, m, this.pitchInRadians);
        symbol_layout.rotateZ(m, m, -this.bearingInRadians);
        symbol_layout.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 = symbol_layout.scale([], m, [this.worldSize, this.worldSize, this.worldSize]);
        // scale vertically to meters per pixel (inverse of ground resolution):
        symbol_layout.scale(m, m, [1, 1, this._helper._pixelPerMeter]);
        // matrix for conversion from world space to screen coordinates in 2D
        this._pixelMatrix = symbol_layout.multiply(new Float64Array(16), this.clipSpaceToPixelsMatrix, m);
        // matrix for conversion from world space to clip space (-1 .. 1)
        symbol_layout.translate(m, m, [0, 0, -this.elevation]); // elevate camera over terrain
        this._viewProjMatrix = m;
        this._invViewProjMatrix = symbol_layout.invert$1([], m);
        const cameraPos = [0, 0, -1, 1];
        symbol_layout.transformMat4(cameraPos, cameraPos, this._invViewProjMatrix);
        this._cameraPosition = [
            cameraPos[0] / cameraPos[3],
            cameraPos[1] / cameraPos[3],
            cameraPos[2] / cameraPos[3]
        ];
        // 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);
        symbol_layout.perspective(this._fogMatrix, this.fovInRadians, this.width / this.height, cameraToSeaLevelDistance, this._helper._farZ);
        this._fogMatrix[8] = -offset.x * 2 / this.width;
        this._fogMatrix[9] = offset.y * 2 / this.height;
        symbol_layout.scale(this._fogMatrix, this._fogMatrix, [1, -1, 1]);
        symbol_layout.translate(this._fogMatrix, this._fogMatrix, [0, 0, -this.cameraToCenterDistance]);
        symbol_layout.rotateZ(this._fogMatrix, this._fogMatrix, -this.rollInRadians);
        symbol_layout.rotateX(this._fogMatrix, this._fogMatrix, this.pitchInRadians);
        symbol_layout.rotateZ(this._fogMatrix, this._fogMatrix, -this.bearingInRadians);
        symbol_layout.translate(this._fogMatrix, this._fogMatrix, [-x, -y, 0]);
        symbol_layout.scale(this._fogMatrix, this._fogMatrix, [1, 1, this._helper._pixelPerMeter]);
        symbol_layout.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 = symbol_layout.multiply(new Float64Array(16), this.clipSpaceToPixelsMatrix, 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._helper._width % 2) / 2, yShift = (this._helper._height % 2) / 2, angleCos = Math.cos(this.bearingInRadians), angleSin = Math.sin(-this.bearingInRadians), dx = x - Math.round(x) + angleCos * xShift + angleSin * yShift, dy = y - Math.round(y) + angleCos * yShift + angleSin * xShift;
        const alignedM = new Float64Array(m);
        symbol_layout.translate(alignedM, alignedM, [dx > 0.5 ? dx - 1 : dx, dy > 0.5 ? dy - 1 : dy, 0]);
        this._alignedProjMatrix = alignedM;
        // inverse matrix for conversion from screen coordinates to location
        m = symbol_layout.invert$1(new Float64Array(16), this._pixelMatrix);
        if (!m)
            throw new Error('failed to invert matrix');
        this._pixelMatrixInverse = m;
        this._clearMatrixCaches();
    }
    _clearMatrixCaches() {
        this._posMatrixCache.clear();
        this._alignedPosMatrixCache.clear();
        this._fogMatrixCacheF32.clear();
    }
    maxPitchScaleFactor() {
        // calcMatrices hasn't run yet
        if (!this._pixelMatrixInverse)
            return 1;
        const coord = this.screenPointToMercatorCoordinate(new symbol_layout.Point(0, 0));
        const p = [coord.x * this.worldSize, coord.y * this.worldSize, 0, 1];
        const topPoint = symbol_layout.transformMat4(p, p, this._pixelMatrix);
        return topPoint[3] / this._helper.cameraToCenterDistance;
    }
    getCameraPoint() {
        return this._helper.getCameraPoint();
    }
    getCameraAltitude() {
        return this._helper.getCameraAltitude();
    }
    getCameraLngLat() {
        const pixelPerMeter = symbol_layout.mercatorZfromAltitude(1, this.center.lat) * this.worldSize;
        const cameraToCenterDistanceMeters = this._helper.cameraToCenterDistance / pixelPerMeter;
        const camMercator = cameraMercatorCoordinateFromCenterAndRotation(this.center, this.elevation, this.pitch, this.bearing, cameraToCenterDistanceMeters);
        return camMercator.toLngLat();
    }
    lngLatToCameraDepth(lngLat, elevation) {
        const coord = symbol_layout.MercatorCoordinate.fromLngLat(lngLat);
        const p = [coord.x * this.worldSize, coord.y * this.worldSize, elevation, 1];
        symbol_layout.transformMat4(p, p, this._viewProjMatrix);
        return (p[2] / p[3]);
    }
    getProjectionData(params) {
        const { overscaledTileID, aligned, applyTerrainMatrix } = params;
        const mercatorTileCoordinates = this._helper.getMercatorTileCoordinates(overscaledTileID);
        const tilePosMatrix = overscaledTileID ? this.calculatePosMatrix(overscaledTileID, aligned, true) : null;
        let mainMatrix;
        if ((overscaledTileID === null || overscaledTileID === void 0 ? void 0 : overscaledTileID.terrainRttPosMatrix32f) && applyTerrainMatrix) {
            mainMatrix = overscaledTileID.terrainRttPosMatrix32f;
        }
        else if (tilePosMatrix) {
            mainMatrix = tilePosMatrix; // This matrix should be float32
        }
        else {
            mainMatrix = symbol_layout.createIdentityMat4f32();
        }
        return {
            mainMatrix, // Might be set to a custom matrix by different projections.
            tileMercatorCoords: mercatorTileCoordinates,
            clippingPlane: [0, 0, 0, 0],
            projectionTransition: 0.0, // Range 0..1, where 0 is mercator, 1 is another projection, mostly globe.
            fallbackMatrix: mainMatrix,
        };
    }
    isLocationOccluded(_) {
        return false;
    }
    getPixelScale() {
        return 1.0;
    }
    getCircleRadiusCorrection() {
        return 1.0;
    }
    getPitchedTextCorrection(_textAnchorX, _textAnchorY, _tileID) {
        return 1.0;
    }
    transformLightDirection(dir) {
        return symbol_layout.clone(dir);
    }
    getRayDirectionFromPixel(_p) {
        throw new Error('Not implemented.'); // No need for this in mercator transform
    }
    projectTileCoordinates(x, y, unwrappedTileID, getElevation) {
        const matrix = this.calculatePosMatrix(unwrappedTileID);
        let pos;
        if (getElevation) { // slow because of handle z-index
            pos = [x, y, getElevation(x, y), 1];
            symbol_layout.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 symbol_layout.Point(pos[0] / w, pos[1] / w),
            signedDistanceFromCamera: w,
            isOccluded: false
        };
    }
    populateCache(coords) {
        for (const coord of coords) {
            // Return value is thrown away, but this function will still
            // place the pos matrix into the transform's internal cache.
            this.calculatePosMatrix(coord);
        }
    }
    getMatrixForModel(location, altitude) {
        const modelAsMercatorCoordinate = symbol_layout.MercatorCoordinate.fromLngLat(location, altitude);
        const scale = modelAsMercatorCoordinate.meterInMercatorCoordinateUnits();
        const m = symbol_layout.createIdentityMat4f64();
        symbol_layout.translate(m, m, [modelAsMercatorCoordinate.x, modelAsMercatorCoordinate.y, modelAsMercatorCoordinate.z]);
        symbol_layout.rotateZ(m, m, Math.PI);
        symbol_layout.rotateX(m, m, Math.PI / 2);
        symbol_layout.scale(m, m, [-scale, scale, scale]);
        return m;
    }
    getProjectionDataForCustomLayer(applyGlobeMatrix = true) {
        const tileID = new symbol_layout.OverscaledTileID(0, 0, 0, 0, 0);
        const projectionData = this.getProjectionData({ overscaledTileID: tileID, applyGlobeMatrix });
        const tileMatrix = calculateTileMatrix(tileID, this.worldSize);
        symbol_layout.multiply(tileMatrix, this._viewProjMatrix, tileMatrix);
        projectionData.tileMercatorCoords = [0, 0, 1, 1];
        // Even though we requested projection data for the mercator base tile which covers the entire mercator range,
        // the shader projection machinery still expects inputs to be in tile units range [0..EXTENT].
        // Since custom layers are expected to supply mercator coordinates [0..1], we need to rescale
        // both matrices by EXTENT. We also need to rescale Z.
        const scale = [symbol_layout.EXTENT, symbol_layout.EXTENT, this.worldSize / this._helper.pixelsPerMeter];
        // We pass full-precision 64bit float matrices to custom layers to prevent precision loss in case the user wants to do further transformations.
        // Otherwise we get very visible precision-artifacts and twitching for objects that are bulding-scale.
        const projectionMatrixScaled = symbol_layout.createMat4f64();
        symbol_layout.scale(projectionMatrixScaled, tileMatrix, scale);
        projectionData.fallbackMatrix = projectionMatrixScaled;
        projectionData.mainMatrix = projectionMatrixScaled;
        return projectionData;
    }
    getFastPathSimpleProjectionMatrix(tileID) {
        return this.calculatePosMatrix(tileID);
    }
}

/**
 * @internal
 */
function cameraBoundsWarning() {
    symbol_layout.warnOnce('Map cannot fit within canvas with the given bounds, padding, and/or offset.');
}
/**
 * @internal
 * Set a transform's rotation to a value interpolated between startEulerAngles and endEulerAngles
 */
function updateRotation(args) {
    if (args.useSlerp) {
        // At pitch ==0, the Euler angle representation is ambiguous. In this case, set the Euler angles
        // to the representation requested by the caller
        if (args.k < 1) {
            const startRotation = symbol_layout.rollPitchBearingToQuat(args.startEulerAngles.roll, args.startEulerAngles.pitch, args.startEulerAngles.bearing);
            const endRotation = symbol_layout.rollPitchBearingToQuat(args.endEulerAngles.roll, args.endEulerAngles.pitch, args.endEulerAngles.bearing);
            const rotation = new Float64Array(4);
            symbol_layout.slerp(rotation, startRotation, endRotation, args.k);
            const eulerAngles = symbol_layout.getRollPitchBearing(rotation);
            args.tr.setRoll(eulerAngles.roll);
            args.tr.setPitch(eulerAngles.pitch);
            args.tr.setBearing(eulerAngles.bearing);
        }
        else {
            args.tr.setRoll(args.endEulerAngles.roll);
            args.tr.setPitch(args.endEulerAngles.pitch);
            args.tr.setBearing(args.endEulerAngles.bearing);
        }
    }
    else {
        args.tr.setRoll(symbol_layout.interpolateFactory.number(args.startEulerAngles.roll, args.endEulerAngles.roll, args.k));
        args.tr.setPitch(symbol_layout.interpolateFactory.number(args.startEulerAngles.pitch, args.endEulerAngles.pitch, args.k));
        args.tr.setBearing(symbol_layout.interpolateFactory.number(args.startEulerAngles.bearing, args.endEulerAngles.bearing, args.k));
    }
}
function cameraForBoxAndBearing(options, padding, bounds, bearing, tr) {
    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 nwWorld = projectToWorldCoordinates(tr.worldSize, bounds.getNorthWest());
    const neWorld = projectToWorldCoordinates(tr.worldSize, bounds.getNorthEast());
    const seWorld = projectToWorldCoordinates(tr.worldSize, bounds.getSouthEast());
    const swWorld = projectToWorldCoordinates(tr.worldSize, bounds.getSouthWest());
    const bearingRadians = symbol_layout.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 symbol_layout.Point(Math.max(nwRotatedWorld.x, neRotatedWorld.x, swRotatedWorld.x, seRotatedWorld.x), Math.max(nwRotatedWorld.y, neRotatedWorld.y, swRotatedWorld.y, seRotatedWorld.y));
    const lowerLeft = new symbol_layout.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 availableWidth = (tr.width - (edgePadding.left + edgePadding.right + padding.left + padding.right));
    const availableHeight = (tr.height - (edgePadding.top + edgePadding.bottom + padding.top + padding.bottom));
    const scaleX = availableWidth / size.x;
    const scaleY = availableHeight / size.y;
    if (scaleY < 0 || scaleX < 0) {
        cameraBoundsWarning();
        return undefined;
    }
    const zoom = Math.min(symbol_layout.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 = symbol_layout.Point.convert(options.offset);
    const paddingOffsetX = (padding.left - padding.right) / 2;
    const paddingOffsetY = (padding.top - padding.bottom) / 2;
    const paddingOffset = new symbol_layout.Point(paddingOffsetX, paddingOffsetY);
    const rotatedPaddingOffset = paddingOffset.rotate(symbol_layout.degreesToRadians(bearing));
    const offsetAtInitialZoom = offset.add(rotatedPaddingOffset);
    const offsetAtFinalZoom = offsetAtInitialZoom.mult(tr.scale / symbol_layout.zoomScale(zoom));
    const center = unprojectFromWorldCoordinates(tr.worldSize, 
    // either world diagonal can be used (NW-SE or NE-SW)
    nwWorld.add(seWorld).div(2).sub(offsetAtFinalZoom));
    return {
        center,
        zoom,
        bearing
    };
}

/**
 * @internal
 */
class MercatorCameraHelper {
    get useGlobeControls() { return false; }
    handlePanInertia(pan, transform) {
        // Reduce the offset so that it never goes past the horizon. If it goes past
        // the horizon, the pan direction is opposite of the intended direction.
        const offsetLength = pan.mag();
        const pixelsToHorizon = Math.abs(getMercatorHorizon(transform));
        const horizonFactor = 0.75; // Must be < 1 to prevent the offset from crossing the horizon
        const offsetAsPoint = pan.mult(Math.min(pixelsToHorizon * horizonFactor / offsetLength, 1.0));
        return {
            easingOffset: offsetAsPoint,
            easingCenter: transform.center,
        };
    }
    handleMapControlsRollPitchBearingZoom(deltas, tr) {
        if (deltas.bearingDelta)
            tr.setBearing(tr.bearing + deltas.bearingDelta);
        if (deltas.pitchDelta)
            tr.setPitch(tr.pitch + deltas.pitchDelta);
        if (deltas.rollDelta)
            tr.setRoll(tr.roll + deltas.rollDelta);
        if (deltas.zoomDelta)
            tr.setZoom(tr.zoom + deltas.zoomDelta);
    }
    handleMapControlsPan(deltas, tr, preZoomAroundLoc) {
        // If we are rotating about the center point, there is no need to update the transform center. Doing so causes
        // a small amount of drift of the center point, especially when pitch is close to 90 degrees.
        // In this case, return early.
        if (deltas.around.distSqr(tr.centerPoint) < 1.0e-2) {
            return;
        }
        tr.setLocationAtPoint(preZoomAroundLoc, deltas.around);
    }
    cameraForBoxAndBearing(options, padding, bounds, bearing, tr) {
        return cameraForBoxAndBearing(options, padding, bounds, bearing, tr);
    }
    handleJumpToCenterZoom(tr, options) {
        // Mercator zoom & center handling.
        const optionsZoom = typeof options.zoom !== 'undefined';
        const zoom = optionsZoom ? +options.zoom : tr.zoom;
        if (tr.zoom !== zoom) {
            tr.setZoom(+options.zoom);
        }
        if (options.center !== undefined) {
            tr.setCenter(symbol_layout.LngLat.convert(options.center));
        }
    }
    handleEaseTo(tr, options) {
        const startZoom = tr.zoom;
        const startPadding = tr.padding;
        const startEulerAngles = { roll: tr.roll, pitch: tr.pitch, bearing: tr.bearing };
        const endRoll = options.roll === undefined ? tr.roll : options.roll;
        const endPitch = options.pitch === undefined ? tr.pitch : options.pitch;
        const endBearing = options.bearing === undefined ? tr.bearing : options.bearing;
        const endEulerAngles = { roll: endRoll, pitch: endPitch, bearing: endBearing };
        const optionsZoom = typeof options.zoom !== 'undefined';
        const doPadding = !tr.isPaddingEqual(options.padding);
        let isZooming = false;
        const zoom = optionsZoom ? +options.zoom : tr.zoom;
        let pointAtOffset = tr.centerPoint.add(options.offsetAsPoint);
        const locationAtOffset = tr.screenPointToLocation(pointAtOffset);
        const { center, zoom: endZoom } = tr.applyConstrain(symbol_layout.LngLat.convert(options.center || locationAtOffset), zoom !== null && zoom !== void 0 ? zoom : startZoom);
        normalizeCenter(tr, center);
        const from = projectToWorldCoordinates(tr.worldSize, locationAtOffset);
        const delta = projectToWorldCoordinates(tr.worldSize, center).sub(from);
        const finalScale = symbol_layout.zoomScale(endZoom - startZoom);
        isZooming = (endZoom !== startZoom);
        const easeFunc = (k) => {
            if (isZooming) {
                tr.setZoom(symbol_layout.interpolateFactory.number(startZoom, endZoom, k));
            }
            if (!symbol_layout.rollPitchBearingEqual(startEulerAngles, endEulerAngles)) {
                updateRotation({
                    startEulerAngles,
                    endEulerAngles,
                    tr,
                    k,
                    useSlerp: startEulerAngles.roll != endEulerAngles.roll
                });
            }
            if (doPadding) {
                tr.interpolatePadding(startPadding, options.padding, k);
                // When padding is being applied, Transform.centerPoint is changing continuously,
                // thus we need to recalculate offsetPoint every frame
                pointAtOffset = tr.centerPoint.add(options.offsetAsPoint);
            }
            if (options.around) {
                tr.setLocationAtPoint(options.around, options.aroundPoint);
            }
            else {
                const scale = symbol_layout.zoomScale(tr.zoom - startZoom);
                const base = endZoom > startZoom ?
                    Math.min(2, finalScale) :
                    Math.max(0.5, finalScale);
                const speedup = Math.pow(base, 1 - k);
                const newCenter = unprojectFromWorldCoordinates(tr.worldSize, from.add(delta.mult(k * speedup)).mult(scale));
                tr.setLocationAtPoint(tr.renderWorldCopies ? newCenter.wrap() : newCenter, pointAtOffset);
            }
        };
        return {
            easeFunc,
            isZooming,
            elevationCenter: center,
        };
    }
    handleFlyTo(tr, options) {
        const optionsZoom = typeof options.zoom !== 'undefined';
        const startZoom = tr.zoom;
        // Obtain target center and zoom
        const constrained = tr.applyConstrain(symbol_layout.LngLat.convert(options.center || options.locationAtOffset), optionsZoom ? +options.zoom : startZoom);
        const targetCenter = constrained.center;
        const targetZoom = constrained.zoom;
        normalizeCenter(tr, targetCenter);
        const from = projectToWorldCoordinates(tr.worldSize, options.locationAtOffset);
        const delta = projectToWorldCoordinates(tr.worldSize, targetCenter).sub(from);
        const pixelPathLength = delta.mag();
        const scaleOfZoom = symbol_layout.zoomScale(targetZoom - startZoom);
        const optionsMinZoom = typeof options.minZoom !== 'undefined';
        let scaleOfMinZoom;
        if (optionsMinZoom) {
            const minZoomPreConstrain = Math.min(+options.minZoom, startZoom, targetZoom);
            const minZoom = tr.applyConstrain(targetCenter, minZoomPreConstrain).zoom;
            scaleOfMinZoom = symbol_layout.zoomScale(minZoom - startZoom);
        }
        const easeFunc = (k, scale, centerFactor, pointAtOffset) => {
            tr.setZoom(k === 1 ? targetZoom : startZoom + symbol_layout.scaleZoom(scale));
            const newCenter = k === 1 ? targetCenter : unprojectFromWorldCoordinates(tr.worldSize, from.add(delta.mult(centerFactor)).mult(scale));
            tr.setLocationAtPoint(tr.renderWorldCopies ? newCenter.wrap() : newCenter, pointAtOffset);
        };
        return {
            easeFunc,
            scaleOfZoom,
            targetCenter,
            scaleOfMinZoom,
            pixelPathLength,
        };
    }
}

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, symbol_layout.Color.transparent, [false, false, false, false]);
ColorMode.unblended = new ColorMode(ColorMode.Replace, symbol_layout.Color.transparent, [true, true, true, true]);
ColorMode.alphaBlended = new ColorMode([ONE, ONE_MINUS_SRC_ALPHA], symbol_layout.Color.transparent, [true, true, true, true]);

const FRONT = 0x0404;
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);
CullFaceMode.frontCCW = new CullFaceMode(true, FRONT, CCW);

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 projectionErrorMeasurementUniforms = (context, locations) => ({
    'u_input': new symbol_layout.Uniform1f(context, locations.u_input),
    'u_output_expected': new symbol_layout.Uniform1f(context, locations.u_output_expected),
});
const projectionErrorMeasurementUniformValues = (input, outputExpected) => ({
    'u_input': input,
    'u_output_expected': outputExpected,
});

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;
    }
}

/**
 * For vector globe the vertex shader projects mercator coordinates to angular coordinates on a sphere.
 * This projection requires some inverse trigonometry `atan(exp(...))`, which is inaccurate on some GPUs (mainly on AMD and Nvidia).
 * The inaccuracy is severe enough to require a workaround. The uncorrected map is shifted north-south by up to several hundred meters in some latitudes.
 * Since the inaccuracy is hardware-dependant and may change in the future, we need to measure the error at runtime.
 *
 * Our approach relies on several assumptions:
 *
 * - the error is only present in the "latitude" component (longitude doesn't need any inverse trigonometry)
 * - the error is continuous and changes slowly with latitude
 * - at zoom levels where the error is noticeable, the error is more-or-less the same across the entire visible map area (and thus can be described with a single number)
 *
 * Solution:
 *
 * Every few frames, launch a GPU shader that measures the error for the current map center latitude, and writes it to a 1x1 texture.
 * Read back that texture, and offset the globe projection matrix according to the error (interpolating smoothly from old error to new error if needed).
 * The texture readback is done asynchronously using Pixel Pack Buffers (WebGL2) when possible, and has a few frames of latency, but that should not be a problem.
 *
 * General operation of this class each frame is:
 *
 * - render the error shader into a fbo, read that pixel into a PBO, place a fence
 * - wait a few frames to allow the GPU (and driver) to actually execute the shader
 * - wait for the fence to be signalled (guaranteeing the shader to actually be executed)
 * - read back the PBO's contents
 * - wait a few more frames
 * - repeat
 */
class ProjectionErrorMeasurement {
    get awaitingQuery() {
        return !!this._readbackQueue;
    }
    constructor(renderContext) {
        // We wait at least this many frames after measuring until we read back the value.
        // After this period, we might wait more frames until a fence is signalled to make sure the rendering is completed.
        this._readbackWaitFrames = 4;
        // We wait this many frames after *reading back* a measurement until we trigger measure again.
        // We could in theory render the measurement pixel immediately, but we wait to make sure
        // no pipeline stall happens.
        this._measureWaitFrames = 6;
        this._texWidth = 1;
        this._texHeight = 1;
        this._measuredError = 0; // Result of last measurement
        this._updateCount = 0;
        this._lastReadbackFrame = -1000;
        // There is never more than one readback waiting
        this._readbackQueue = null;
        this._cachedRenderContext = renderContext;
        const context = renderContext.context;
        const gl = context.gl;
        this._texFormat = gl.RGBA;
        this._texType = gl.UNSIGNED_BYTE;
        const vertexArray = new symbol_layout.PosArray();
        vertexArray.emplaceBack(-1, -1);
        vertexArray.emplaceBack(2, -1);
        vertexArray.emplaceBack(-1, 2);
        const indexArray = new symbol_layout.TriangleIndexArray();
        indexArray.emplaceBack(0, 1, 2);
        this._fullscreenTriangle = new Mesh(context.createVertexBuffer(vertexArray, posAttributes.members), context.createIndexBuffer(indexArray), symbol_layout.SegmentVector.simpleSegment(0, 0, vertexArray.length, indexArray.length));
        this._resultBuffer = new Uint8Array(4);
        context.activeTexture.set(gl.TEXTURE1);
        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.NEAREST);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
        gl.texImage2D(gl.TEXTURE_2D, 0, this._texFormat, this._texWidth, this._texHeight, 0, this._texFormat, this._texType, null);
        this._fbo = context.createFramebuffer(this._texWidth, this._texHeight, false, false);
        this._fbo.colorAttachment.set(texture);
        if (isWebGL2(gl)) {
            this._pbo = gl.createBuffer();
            gl.bindBuffer(gl.PIXEL_PACK_BUFFER, this._pbo);
            gl.bufferData(gl.PIXEL_PACK_BUFFER, 4, gl.STREAM_READ);
            gl.bindBuffer(gl.PIXEL_PACK_BUFFER, null);
        }
    }
    destroy() {
        const gl = this._cachedRenderContext.context.gl;
        this._fullscreenTriangle.destroy();
        this._fbo.destroy();
        gl.deleteBuffer(this._pbo);
        this._fullscreenTriangle = null;
        this._fbo = null;
        this._pbo = null;
        this._resultBuffer = null;
    }
    updateErrorLoop(normalizedMercatorY, expectedAngleY) {
        const currentFrame = this._updateCount;
        if (this._readbackQueue) {
            // Try to read back if enough frames elapsed. Otherwise do nothing, just wait another frame.
            if (currentFrame >= this._readbackQueue.frameNumberIssued + this._readbackWaitFrames) {
                // Try to read back - it is possible that this method does nothing, then
                // the readback queue will not be cleared and we will retry next frame.
                this._tryReadback();
            }
        }
        else {
            if (currentFrame >= this._lastReadbackFrame + this._measureWaitFrames) {
                this._renderErrorTexture(normalizedMercatorY, expectedAngleY);
            }
        }
        this._updateCount++;
        return this._measuredError;
    }
    _bindFramebuffer() {
        const context = this._cachedRenderContext.context;
        const gl = context.gl;
        context.activeTexture.set(gl.TEXTURE1);
        gl.bindTexture(gl.TEXTURE_2D, this._fbo.colorAttachment.get());
        context.bindFramebuffer.set(this._fbo.framebuffer);
    }
    _renderErrorTexture(input, outputExpected) {
        const context = this._cachedRenderContext.context;
        const gl = context.gl;
        // Update framebuffer contents
        this._bindFramebuffer();
        context.viewport.set([0, 0, this._texWidth, this._texHeight]);
        context.clear({ color: symbol_layout.Color.transparent });
        const program = this._cachedRenderContext.useProgram('projectionErrorMeasurement');
        program.draw(context, gl.TRIANGLES, DepthMode.disabled, StencilMode.disabled, ColorMode.unblended, CullFaceMode.disabled, projectionErrorMeasurementUniformValues(input, outputExpected), null, null, '$clipping', this._fullscreenTriangle.vertexBuffer, this._fullscreenTriangle.indexBuffer, this._fullscreenTriangle.segments);
        if (this._pbo && isWebGL2(gl)) {
            // Read back into PBO
            gl.bindBuffer(gl.PIXEL_PACK_BUFFER, this._pbo);
            gl.readBuffer(gl.COLOR_ATTACHMENT0);
            gl.readPixels(0, 0, this._texWidth, this._texHeight, this._texFormat, this._texType, 0);
            gl.bindBuffer(gl.PIXEL_PACK_BUFFER, null);
            const sync = gl.fenceSync(gl.SYNC_GPU_COMMANDS_COMPLETE, 0);
            gl.flush();
            this._readbackQueue = {
                frameNumberIssued: this._updateCount,
                sync,
            };
        }
        else {
            // Read it back later.
            this._readbackQueue = {
                frameNumberIssued: this._updateCount,
                sync: null,
            };
        }
    }
    _tryReadback() {
        const gl = this._cachedRenderContext.context.gl;
        if (this._pbo && this._readbackQueue && isWebGL2(gl)) {
            // WebGL 2 path
            const waitResult = gl.clientWaitSync(this._readbackQueue.sync, 0, 0);
            if (waitResult === gl.WAIT_FAILED) {
                symbol_layout.warnOnce('WebGL2 clientWaitSync failed.');
                this._readbackQueue = null;
                this._lastReadbackFrame = this._updateCount;
                return;
            }
            if (waitResult === gl.TIMEOUT_EXPIRED) {
                return; // Wait one more frame
            }
            gl.bindBuffer(gl.PIXEL_PACK_BUFFER, this._pbo);
            gl.getBufferSubData(gl.PIXEL_PACK_BUFFER, 0, this._resultBuffer, 0, 4);
            gl.bindBuffer(gl.PIXEL_PACK_BUFFER, null);
        }
        else {
            // WebGL1 compatible
            this._bindFramebuffer();
            gl.readPixels(0, 0, this._texWidth, this._texHeight, this._texFormat, this._texType, this._resultBuffer);
        }
        // If we made it here, _resultBuffer contains the new measurement
        this._readbackQueue = null;
        this._measuredError = ProjectionErrorMeasurement._parseRGBA8float(this._resultBuffer);
        this._lastReadbackFrame = this._updateCount;
    }
    static _parseRGBA8float(buffer) {
        let result = 0;
        result += buffer[0] / 256.0;
        result += buffer[1] / 65536.0;
        result += buffer[2] / 16777216.0;
        if (buffer[3] < 127.0) {
            result = -result;
        }
        return result / 128.0;
    }
}

/**
 * The size of border region for stencil masks, in internal tile coordinates.
 * Used for globe rendering.
 */
const EXTENT_STENCIL_BORDER = symbol_layout.EXTENT / 128;
/**
 * @internal
 * Creates a mesh of a quad that covers the entire tile (covering positions in range 0..EXTENT),
 * is optionally subdivided into finer quads, optionally includes a border
 * and optionally extends to the north and/or special pole vertices.
 * Also allocates and populates WebGL buffers for the mesh.
 * Forces 16 bit indices that are used throughout MapLibre.
 * @param context - The WebGL context wrapper.
 * @param options - Specify options for tile mesh creation such as granularity or border.
 * @returns The mesh vertices and indices, already allocated and uploaded into WebGL buffers.
 */
function createTileMeshWithBuffers(context, options) {
    const tileMesh = createTileMesh(options, '16bit');
    const vertices = symbol_layout.PosArray.deserialize({
        arrayBuffer: tileMesh.vertices,
        length: tileMesh.vertices.byteLength / 2 / 2, // Two values per vertex, 16 bit
    });
    const indices = symbol_layout.TriangleIndexArray.deserialize({
        arrayBuffer: tileMesh.indices,
        length: tileMesh.indices.byteLength / 2 / 3, // Three values per triangle, 16 bit
    });
    return new Mesh(context.createVertexBuffer(vertices, posAttributes.members), context.createIndexBuffer(indices), symbol_layout.SegmentVector.simpleSegment(0, 0, vertices.length, indices.length));
}
/**
 * Creates a mesh of a quad that covers the entire tile (covering positions in range 0..EXTENT),
 * is optionally subdivided into finer quads, optionally includes a border
 * and optionally extends to the north and/or special pole vertices.
 * Additionally the resulting mesh indices type can be specified using `forceIndicesSize`.
 * @example
 * ```
 * // Creating a mesh for a tile that can be used for raster layers, hillshade, etc.
 * const meshBuffers = createTileMesh({
 *     granularity: map.style.projection.subdivisionGranularity.tile.getGranularityForZoomLevel(tileID.z),
 *     generateBorders: true,
 *     extendToNorthPole: tileID.y === 0,
 *     extendToSouthPole: tileID.y === (1 << tileID.z) - 1,
 * }, '16bit');
 * ```
 * @see [Add a custom layer with tiles to a globe](https://maplibre.org/maplibre-gl-js/docs/examples/add-a-custom-layer-with-tiles-to-a-globe/)
 * @param options - Specify options for tile mesh creation such as granularity or border.
 * @param forceIndicesSize - Specifies what indices type to use. The values '32bit' and '16bit' force their respective indices size. If undefined, the mesh may use either size, and will pick 16 bit indices if possible. If '16bit' is specified and the mesh exceeds 65536 vertices, an exception is thrown.
 * @returns Typed arrays of the mesh vertices and indices.
 */
function createTileMesh(options, forceIndicesSize) {
    // We only want to generate the north/south border if the tile
    // does NOT border the north/south edge of the mercator range.
    const granularity = options.granularity !== undefined ? Math.max(options.granularity, 1) : 1;
    const quadsPerAxisX = granularity + (options.generateBorders ? 2 : 0); // two extra quads for border
    const quadsPerAxisY = granularity + ((options.extendToNorthPole || options.generateBorders) ? 1 : 0) + (options.extendToSouthPole || options.generateBorders ? 1 : 0);
    const verticesPerAxisX = quadsPerAxisX + 1; // one more vertex than quads
    const verticesPerAxisY = quadsPerAxisY + 1; // one more vertex than quads
    const offsetX = options.generateBorders ? -1 : 0;
    const offsetY = (options.generateBorders || options.extendToNorthPole) ? -1 : 0;
    const endX = granularity + (options.generateBorders ? 1 : 0);
    const endY = granularity + ((options.generateBorders || options.extendToSouthPole) ? 1 : 0);
    const vertexCount = verticesPerAxisX * verticesPerAxisY;
    const indexCount = quadsPerAxisX * quadsPerAxisY * 6;
    const overflows16bitIndices = verticesPerAxisX * verticesPerAxisY > (1 << 16);
    if (overflows16bitIndices && forceIndicesSize === '16bit') {
        throw new Error('Granularity is too large and meshes would not fit inside 16 bit vertex indices.');
    }
    const use32bitIndices = overflows16bitIndices || forceIndicesSize === '32bit';
    const vertices = new Int16Array(vertexCount * 2);
    let vertexId = 0;
    for (let y = offsetY; y <= endY; y++) {
        for (let x = offsetX; x <= endX; x++) {
            let vx = x / granularity * symbol_layout.EXTENT;
            if (x === -1) {
                vx = -EXTENT_STENCIL_BORDER;
            }
            if (x === granularity + 1) {
                vx = symbol_layout.EXTENT + EXTENT_STENCIL_BORDER;
            }
            let vy = y / granularity * symbol_layout.EXTENT;
            if (y === -1) {
                vy = options.extendToNorthPole ? symbol_layout.NORTH_POLE_Y : (-EXTENT_STENCIL_BORDER);
            }
            if (y === granularity + 1) {
                vy = options.extendToSouthPole ? symbol_layout.SOUTH_POLE_Y : symbol_layout.EXTENT + EXTENT_STENCIL_BORDER;
            }
            vertices[vertexId++] = vx;
            vertices[vertexId++] = vy;
        }
    }
    const indices = use32bitIndices ? new Uint32Array(indexCount) : new Uint16Array(indexCount);
    let indexId = 0;
    for (let y = 0; y < quadsPerAxisY; y++) {
        for (let x = 0; x < quadsPerAxisX; x++) {
            const v0 = x + y * verticesPerAxisX;
            const v1 = (x + 1) + y * verticesPerAxisX;
            const v2 = x + (y + 1) * verticesPerAxisX;
            const v3 = (x + 1) + (y + 1) * verticesPerAxisX;
            // v0----v1
            //  |  / |
            //  | /  |
            // v2----v3
            indices[indexId++] = v0;
            indices[indexId++] = v2;
            indices[indexId++] = v1;
            indices[indexId++] = v1;
            indices[indexId++] = v2;
            indices[indexId++] = v3;
        }
    }
    return {
        vertices: vertices.buffer.slice(0),
        indices: indices.buffer.slice(0),
        uses32bitIndices: use32bitIndices,
    };
}

const VerticalPerspectiveShaderDefine = '#define GLOBE';
const VerticalPerspectiveShaderVariantKey = 'globe';
const globeConstants = {
    errorTransitionTimeSeconds: 0.5
};
const granularitySettingsGlobe = new symbol_layout.SubdivisionGranularitySetting({
    fill: new symbol_layout.SubdivisionGranularityExpression(128, 2),
    line: new symbol_layout.SubdivisionGranularityExpression(512, 0),
    // Always keep at least some subdivision on raster tiles, etc,
    // otherwise they will be visibly warped at high zooms (before mercator transition).
    // This si not needed on fill, because fill geometry tends to already be
    // highly tessellated and granular at high zooms.
    tile: new symbol_layout.SubdivisionGranularityExpression(128, 32),
    // Stencil granularity must never be higher than fill granularity,
    // otherwise we would get seams in the oceans at zoom levels where
    // stencil has higher granularity than fill.
    stencil: new symbol_layout.SubdivisionGranularityExpression(128, 1),
    circle: 3
});
class VerticalPerspectiveProjection {
    constructor() {
        this._tileMeshCache = {};
        this._errorCorrectionUsable = 0.0;
        this._errorMeasurementLastValue = 0.0;
        this._errorCorrectionPreviousValue = 0.0;
        this._errorMeasurementLastChangeTime = -1000.0;
    }
    get name() {
        return 'vertical-perspective';
    }
    get transitionState() {
        return 1;
    }
    get useSubdivision() {
        return true;
    }
    get shaderVariantName() {
        return VerticalPerspectiveShaderVariantKey;
    }
    get shaderDefine() {
        return VerticalPerspectiveShaderDefine;
    }
    get shaderPreludeCode() {
        return shaders.projectionGlobe;
    }
    get vertexShaderPreludeCode() {
        return shaders.projectionMercator.vertexSource;
    }
    get subdivisionGranularity() {
        return granularitySettingsGlobe;
    }
    get useGlobeControls() {
        return true;
    }
    /**
     * @internal
     * Globe projection periodically measures the error of the GPU's
     * projection from mercator to globe and computes how much to correct
     * the globe's latitude alignment.
     * This stores the correction that should be applied to the projection matrix.
     */
    get latitudeErrorCorrectionRadians() { return this._errorCorrectionUsable; }
    destroy() {
        if (this._errorMeasurement) {
            this._errorMeasurement.destroy();
        }
    }
    updateGPUdependent(renderContext) {
        if (!this._errorMeasurement) {
            this._errorMeasurement = new ProjectionErrorMeasurement(renderContext);
        }
        const mercatorY = symbol_layout.mercatorYfromLat(this._errorQueryLatitudeDegrees);
        const expectedResult = 2.0 * Math.atan(Math.exp(Math.PI - (mercatorY * Math.PI * 2.0))) - Math.PI * 0.5;
        const newValue = this._errorMeasurement.updateErrorLoop(mercatorY, expectedResult);
        const currentTime = now();
        if (newValue !== this._errorMeasurementLastValue) {
            this._errorCorrectionPreviousValue = this._errorCorrectionUsable; // store the interpolated value
            this._errorMeasurementLastValue = newValue;
            this._errorMeasurementLastChangeTime = currentTime;
        }
        const sinceUpdateSeconds = (currentTime - this._errorMeasurementLastChangeTime) / 1000.0;
        const mix = Math.min(Math.max(sinceUpdateSeconds / globeConstants.errorTransitionTimeSeconds, 0.0), 1.0);
        const newCorrection = -this._errorMeasurementLastValue; // Note the negation
        this._errorCorrectionUsable = symbol_layout.lerp(this._errorCorrectionPreviousValue, newCorrection, symbol_layout.easeCubicInOut(mix));
    }
    _getMeshKey(options) {
        return `${options.granularity.toString(36)}_${options.generateBorders ? 'b' : ''}${options.extendToNorthPole ? 'n' : ''}${options.extendToSouthPole ? 's' : ''}`;
    }
    getMeshFromTileID(context, canonical, hasBorder, allowPoles, usage) {
        // Stencil granularity must match fill granularity
        const granularityConfig = usage === 'stencil' ? granularitySettingsGlobe.stencil : granularitySettingsGlobe.tile;
        const granularity = granularityConfig.getGranularityForZoomLevel(canonical.z);
        const north = (canonical.y === 0) && allowPoles;
        const south = (canonical.y === (1 << canonical.z) - 1) && allowPoles;
        return this._getMesh(context, {
            granularity,
            generateBorders: hasBorder,
            extendToNorthPole: north,
            extendToSouthPole: south,
        });
    }
    _getMesh(context, options) {
        const key = this._getMeshKey(options);
        if (key in this._tileMeshCache) {
            return this._tileMeshCache[key];
        }
        const mesh = createTileMeshWithBuffers(context, options);
        this._tileMeshCache[key] = mesh;
        return mesh;
    }
    recalculate(_params) {
        // Do nothing.
    }
    hasTransition() {
        var _a;
        const currentTime = now();
        let dirty = false;
        // Error correction transition
        dirty = dirty || (currentTime - this._errorMeasurementLastChangeTime) / 1000.0 < (globeConstants.errorTransitionTimeSeconds + 0.2);
        // Error correction query in flight
        dirty = dirty || ((_a = this._errorMeasurement) === null || _a === void 0 ? void 0 : _a.awaitingQuery);
        return dirty;
    }
    setErrorQueryLatitudeDegrees(value) {
        this._errorQueryLatitudeDegrees = value;
    }
}

const properties = new symbol_layout.Properties({
    'type': new symbol_layout.DataConstantProperty(symbol_layout.v8Spec.projection.type)
});
class GlobeProjection extends symbol_layout.Evented {
    constructor(projection) {
        super();
        this._transitionable = new symbol_layout.Transitionable(properties, undefined);
        this.setProjection(projection);
        this._transitioning = this._transitionable.untransitioned();
        this.recalculate(new symbol_layout.EvaluationParameters(0));
        this._mercatorProjection = new MercatorProjection();
        this._verticalPerspectiveProjection = new VerticalPerspectiveProjection();
    }
    get transitionState() {
        const currentProjectionSpecValue = this.properties.get('type');
        if (typeof currentProjectionSpecValue === 'string' && currentProjectionSpecValue === 'mercator') {
            return 0;
        }
        if (typeof currentProjectionSpecValue === 'string' && currentProjectionSpecValue === 'vertical-perspective') {
            return 1;
        }
        if (currentProjectionSpecValue instanceof symbol_layout.ProjectionDefinition) {
            if (currentProjectionSpecValue.from === 'vertical-perspective' && currentProjectionSpecValue.to === 'mercator') {
                return 1 - currentProjectionSpecValue.transition;
            }
            if (currentProjectionSpecValue.from === 'mercator' && currentProjectionSpecValue.to === 'vertical-perspective') {
                return currentProjectionSpecValue.transition;
            }
        }
        ;
        return 1;
    }
    get useGlobeRendering() {
        return this.transitionState > 0;
    }
    get latitudeErrorCorrectionRadians() { return this._verticalPerspectiveProjection.latitudeErrorCorrectionRadians; }
    get currentProjection() {
        return this.useGlobeRendering ? this._verticalPerspectiveProjection : this._mercatorProjection;
    }
    get name() {
        return 'globe';
    }
    get useSubdivision() {
        return this.currentProjection.useSubdivision;
    }
    get shaderVariantName() {
        return this.currentProjection.shaderVariantName;
    }
    get shaderDefine() {
        return this.currentProjection.shaderDefine;
    }
    get shaderPreludeCode() {
        return this.currentProjection.shaderPreludeCode;
    }
    get vertexShaderPreludeCode() {
        return this.currentProjection.vertexShaderPreludeCode;
    }
    get subdivisionGranularity() {
        return this.currentProjection.subdivisionGranularity;
    }
    get useGlobeControls() {
        return this.transitionState > 0;
    }
    destroy() {
        this._mercatorProjection.destroy();
        this._verticalPerspectiveProjection.destroy();
    }
    updateGPUdependent(context) {
        this._mercatorProjection.updateGPUdependent(context);
        this._verticalPerspectiveProjection.updateGPUdependent(context);
    }
    getMeshFromTileID(context, _tileID, _hasBorder, _allowPoles, _usage) {
        return this.currentProjection.getMeshFromTileID(context, _tileID, _hasBorder, _allowPoles, _usage);
    }
    setProjection(projection) {
        this._transitionable.setValue('type', (projection === null || projection === void 0 ? void 0 : projection.type) || 'mercator');
    }
    updateTransitions(parameters) {
        this._transitioning = this._transitionable.transitioned(parameters, this._transitioning);
    }
    hasTransition() {
        return this._transitioning.hasTransition() || this.currentProjection.hasTransition();
    }
    recalculate(parameters) {
        this.properties = this._transitioning.possiblyEvaluate(parameters);
    }
    setErrorQueryLatitudeDegrees(value) {
        this._verticalPerspectiveProjection.setErrorQueryLatitudeDegrees(value);
        this._mercatorProjection.setErrorQueryLatitudeDegrees(value);
    }
}

function getGlobeCircumferencePixels(transform) {
    const radius = getGlobeRadiusPixels(transform.worldSize, transform.center.lat);
    return 2.0 * Math.PI * radius;
}
function globeDistanceOfLocationsPixels(transform, a, b) {
    const vecA = angularCoordinatesToSurfaceVector(a);
    const vecB = angularCoordinatesToSurfaceVector(b);
    const dot = symbol_layout.dot(vecA, vecB);
    const radians = Math.acos(dot);
    const circumference = getGlobeCircumferencePixels(transform);
    return radians / (2.0 * Math.PI) * circumference;
}
/**
 * For given mercator coordinates in range 0..1, returns the angular coordinates on the sphere's surface, in radians.
 */
function mercatorCoordinatesToAngularCoordinatesRadians(mercatorX, mercatorY) {
    const sphericalX = symbol_layout.mod(mercatorX * Math.PI * 2.0 + Math.PI, Math.PI * 2);
    const sphericalY = 2.0 * Math.atan(Math.exp(Math.PI - (mercatorY * Math.PI * 2.0))) - Math.PI * 0.5;
    return [sphericalX, sphericalY];
}
/**
 * For a given longitude and latitude (note: in radians) returns the normalized vector from the planet center to the specified place on the surface.
 * @param lngRadians - Longitude in radians.
 * @param latRadians - Latitude in radians.
 */
function angularCoordinatesRadiansToVector(lngRadians, latRadians) {
    const len = Math.cos(latRadians);
    const vec = new Float64Array(3);
    vec[0] = Math.sin(lngRadians) * len;
    vec[1] = Math.sin(latRadians);
    vec[2] = Math.cos(lngRadians) * len;
    return vec;
}
/**
 * Projects a point within a tile to the surface of the unit sphere globe.
 * @param inTileX - X coordinate inside the tile in range [0 .. 8192].
 * @param inTileY - Y coordinate inside the tile in range [0 .. 8192].
 * @param tileIdX - Tile's X coordinate in range [0 .. 2^zoom - 1].
 * @param tileIdY - Tile's Y coordinate in range [0 .. 2^zoom - 1].
 * @param tileIdZ - Tile's zoom.
 * @returns A 3D vector - coordinates of the projected point on a unit sphere.
 */
function projectTileCoordinatesToSphere(inTileX, inTileY, tileIdX, tileIdY, tileIdZ) {
    // This code could be assembled from 3 functions, but this is a hot path for symbol placement,
    // so for optimization purposes everything is inlined by hand.
    //
    // Non-inlined variant of this function would be this:
    //     const mercator = tileCoordinatesToMercatorCoordinates(inTileX, inTileY, tileID);
    //     const angular = mercatorCoordinatesToAngularCoordinatesRadians(mercator.x, mercator.y);
    //     const sphere = angularCoordinatesRadiansToVector(angular[0], angular[1]);
    //     return sphere;
    const scale = 1.0 / (1 << tileIdZ);
    const mercatorX = inTileX / symbol_layout.EXTENT * scale + tileIdX * scale;
    const mercatorY = inTileY / symbol_layout.EXTENT * scale + tileIdY * scale;
    const sphericalX = symbol_layout.mod(mercatorX * Math.PI * 2.0 + Math.PI, Math.PI * 2);
    const sphericalY = 2.0 * Math.atan(Math.exp(Math.PI - (mercatorY * Math.PI * 2.0))) - Math.PI * 0.5;
    const len = Math.cos(sphericalY);
    const vec = new Float64Array(3);
    vec[0] = Math.sin(sphericalX) * len;
    vec[1] = Math.sin(sphericalY);
    vec[2] = Math.cos(sphericalX) * len;
    return vec;
}
/**
 * For a given longitude and latitude (note: in degrees) returns the normalized vector from the planet center to the specified place on the surface.
 */
function angularCoordinatesToSurfaceVector(lngLat) {
    return angularCoordinatesRadiansToVector(lngLat.lng * Math.PI / 180, lngLat.lat * Math.PI / 180);
}
function getGlobeRadiusPixels(worldSize, latitudeDegrees) {
    // We want zoom levels to be consistent between globe and flat views.
    // This means that the pixel size of features at the map center point
    // should be the same for both globe and flat view.
    // For this reason we scale the globe up when map center is nearer to the poles.
    return worldSize / (2.0 * Math.PI) / Math.cos(latitudeDegrees * Math.PI / 180);
}
/**
 * Given a 3D point on the surface of a unit sphere, returns its angular coordinates in degrees.
 * The input vector must be normalized.
 */
function sphereSurfacePointToCoordinates(surface) {
    const latRadians = Math.asin(surface[1]);
    const latDegrees = latRadians / Math.PI * 180.0;
    const lengthXZ = Math.sqrt(surface[0] * surface[0] + surface[2] * surface[2]);
    if (lengthXZ > 1e-6) {
        const projX = surface[0] / lengthXZ;
        const projZ = surface[2] / lengthXZ;
        const acosZ = Math.acos(projZ);
        const lngRadians = (projX > 0) ? acosZ : -acosZ;
        const lngDegrees = lngRadians / Math.PI * 180.0;
        return new symbol_layout.LngLat(symbol_layout.wrap(lngDegrees, -180, 180), latDegrees);
    }
    else {
        return new symbol_layout.LngLat(0.0, latDegrees);
    }
}
/**
 * Given a normalized horizon plane in Ax+By+Cz+D=0 format, compute the center and radius of
 * the circle in that plain that contains the entire visible portion of the unit sphere from horizon
 * to horizon.
 * @param horizonPlane - The plane that passes through visible horizon in Ax + By + Cz + D = 0 format where mag(A,B,C)=1
 * @returns the center point and radius of the disc that passes through the entire visible horizon
 */
function horizonPlaneToCenterAndRadius(horizonPlane) {
    const center = symbol_layout.createVec3f64();
    center[0] = horizonPlane[0] * -horizonPlane[3];
    center[1] = horizonPlane[1] * -horizonPlane[3];
    center[2] = horizonPlane[2] * -horizonPlane[3];
    /*
                     .*******
                 ****|\
               **    | \
             **      |  1
            * radius |   \
           *         |    \
           *  center +--D--+(0,0,0)
     */
    const radius = Math.sqrt(1 - horizonPlane[3] * horizonPlane[3]);
    return { center, radius };
}
/**
 * Computes the closest point on a sphere to `point`.
 * @param center - Center of the sphere
 * @param radius - Radius of the sphere
 * @param point - Point inside or outside the sphere
 * @returns A 3d vector of the point on the sphere closest to `point`
 */
function clampToSphere(center, radius, point) {
    const relativeToCenter = symbol_layout.createVec3f64();
    symbol_layout.sub(relativeToCenter, point, center);
    const clamped = symbol_layout.createVec3f64();
    symbol_layout.scaleAndAdd(clamped, center, relativeToCenter, radius / symbol_layout.len(relativeToCenter));
    return clamped;
}
function planetScaleAtLatitude(latitudeDegrees) {
    return Math.cos(latitudeDegrees * Math.PI / 180);
}
/**
 * Computes how much to modify zoom to keep the globe size constant when changing latitude.
 * @param transform - An instance of any transform. Does not have any relation on the computed values.
 * @param oldLat - Latitude before change, in degrees.
 * @param newLat - Latitude after change, in degrees.
 * @returns A value to add to zoom level used for old latitude to keep same planet radius at new latitude.
 */
function getZoomAdjustment(oldLat, newLat) {
    const oldCircumference = planetScaleAtLatitude(oldLat);
    const newCircumference = planetScaleAtLatitude(newLat);
    return symbol_layout.scaleZoom(newCircumference / oldCircumference);
}
function getDegreesPerPixel(worldSize, lat) {
    return 360.0 / getGlobeCircumferencePixels({ worldSize, center: { lat } });
}
/**
 * Returns transform's new center rotation after applying panning.
 * @param panDelta - Panning delta, in same units as what is supplied to {@link HandlerManager}.
 * @param tr - Current transform. This object is not modified by the function.
 * @returns New center location to set to the map's transform to apply the specified panning.
 */
function computeGlobePanCenter(panDelta, tr) {
    // Apply map bearing to the panning vector
    const rotatedPanDelta = panDelta.rotate(tr.bearingInRadians);
    // Compute what the current zoom would be if the transform center would be moved to latitude 0.
    const normalizedGlobeZoom = tr.zoom + getZoomAdjustment(tr.center.lat, 0);
    // Note: we divide longitude speed by planet width at the given latitude. But we diminish this effect when the globe is zoomed out a lot.
    const lngSpeed = symbol_layout.lerp(1.0 / planetScaleAtLatitude(tr.center.lat), // speed adjusted by latitude
    1.0 / planetScaleAtLatitude(Math.min(Math.abs(tr.center.lat), 60)), // also adjusted, but latitude is clamped to 60° to avoid too large speeds near poles
    symbol_layout.remapSaturate(normalizedGlobeZoom, 7, 3, 0, 1.0) // Values chosen so that globe interactions feel good. Not scientific by any means.
    );
    const panningDegreesPerPixel = getDegreesPerPixel(tr.worldSize, tr.center.lat);
    return new symbol_layout.LngLat(tr.center.lng - rotatedPanDelta.x * panningDegreesPerPixel * lngSpeed, symbol_layout.clamp(tr.center.lat + rotatedPanDelta.y * panningDegreesPerPixel, -symbol_layout.MAX_VALID_LATITUDE, symbol_layout.MAX_VALID_LATITUDE));
}
/**
 * Integration of `1 / cos(x)`.
 */
function integrateSecX(x) {
    const xHalf = 0.5 * x;
    const sin = Math.sin(xHalf);
    const cos = Math.cos(xHalf);
    return Math.log(sin + cos) - Math.log(cos - sin);
}
/**
 * Interpolates globe center between two locations while preserving apparent rotation speed during interpolation.
 * @param start - The starting location of the interpolation.
 * @param deltaLng - Longitude delta to the end of the interpolation.
 * @param deltaLat - Latitude delta to the end of the interpolation.
 * @param t - The interpolation point in [0..1], where 0 is starting location, 1 is end location and other values are in between.
 * @returns The interpolated location.
 */
function interpolateLngLatForGlobe(start, deltaLng, deltaLat, t) {
    // Rate of change of longitude when moving the globe should be roughly 1/cos(latitude)
    // We want to use this rate of change, even for interpolation during easing.
    // Thus we know the derivative of our interpolation function: 1/cos(x)
    // To get our interpolation function, we need to integrate that.
    const interpolatedLat = start.lat + deltaLat * t;
    if (Math.abs(deltaLat) > 1) {
        const endLat = start.lat + deltaLat;
        const onDifferentHemispheres = Math.sign(endLat) !== Math.sign(start.lat);
        // Where do we sample the integrated speed curve?
        const samplePointStart = (onDifferentHemispheres ? -Math.abs(start.lat) : Math.abs(start.lat)) * Math.PI / 180;
        const samplePointEnd = Math.abs(start.lat + deltaLat) * Math.PI / 180;
        // Read the integrated speed curve at those points, and at the interpolation value "t".
        const valueT = integrateSecX(samplePointStart + t * (samplePointEnd - samplePointStart));
        const valueStart = integrateSecX(samplePointStart);
        const valueEnd = integrateSecX(samplePointEnd);
        // Compute new interpolation factor based on the speed curve
        const newT = (valueT - valueStart) / (valueEnd - valueStart);
        // Interpolate using that factor
        const interpolatedLng = start.lng + deltaLng * newT;
        return new symbol_layout.LngLat(interpolatedLng, interpolatedLat);
    }
    else {
        // Fall back to simple interpolation when latitude doesn't change much.
        const interpolatedLng = start.lng + deltaLng * t;
        return new symbol_layout.LngLat(interpolatedLng, interpolatedLat);
    }
}

class BoundingVolumeCache {
    constructor(boundingVolumeFactory) {
        this._cachePrevious = new Map();
        this._cache = new Map();
        this._hadAnyChanges = false;
        this._boundingVolumeFactory = boundingVolumeFactory;
    }
    /**
     * Prepares bounding volume cache for next frame. Call at the beginning of a frame.
     * Bounding volume of any tile accesses in the last frame is kept in the cache, other (unaccessed) bounding volumes are deleted.
     */
    swapBuffers() {
        if (!this._hadAnyChanges) {
            // If no new bounding volumes were added this frame, no need to conserve memory, do not clear caches.
            return;
        }
        const oldCache = this._cachePrevious;
        this._cachePrevious = this._cache;
        this._cache = oldCache;
        this._cache.clear();
        this._hadAnyChanges = false;
    }
    /**
     * Returns the bounding volume of the specified tile, fetching it from cache or creating it using the factory function if needed.
     * @param tileID - Tile x, y and z for zoom.
     */
    getTileBoundingVolume(tileID, wrap, elevation, options) {
        const key = `${tileID.z}_${tileID.x}_${tileID.y}_${(options === null || options === void 0 ? void 0 : options.terrain) ? 't' : ''}`;
        const cached = this._cache.get(key);
        if (cached) {
            return cached;
        }
        const cachedPrevious = this._cachePrevious.get(key);
        if (cachedPrevious) {
            this._cache.set(key, cachedPrevious);
            return cachedPrevious;
        }
        const boundingVolume = this._boundingVolumeFactory(tileID, wrap, elevation, options);
        this._cache.set(key, boundingVolume);
        this._hadAnyChanges = true;
        return boundingVolume;
    }
}

/**
 * A general convex bounding volume, defined by a set of points.
 */
class ConvexVolume {
    /**
     * Creates an instance of a general convex bounding volume.
     * Note that the provided points array is used *as is*, its contents are not copied!
     *
     * Additionally, an AABB must be provided for rejecting frustum intersections.
     * This AABB does not need to bound this convex volume (it may be smaller),
     * but it *must* accurately bound the actual shape this volume is approximating.
     * @param points - Points forming the convex shape. Note that this array reference is used *as is*, its contents are not copied!
     * @param min - The bounding AABB's min point.
     * @param max - The bounding AABB's min point.
     */
    constructor(points, planes, min, max) {
        this.min = min;
        this.max = max;
        this.points = points;
        this.planes = planes;
    }
    /**
     * Creates a convex BV equivalent to the specified AABB.
     * @param min - The AABB's min point.
     * @param max - The AABB's max point.
     */
    static fromAabb(min, max) {
        const points = [];
        for (let i = 0; i < 8; i++) {
            points.push([
                ((i >> 0) & 1) === 1 ? max[0] : min[0],
                ((i >> 1) & 1) === 1 ? max[1] : min[1],
                ((i >> 2) & 1) === 1 ? max[2] : min[2]
            ]);
        }
        return new ConvexVolume(points, [
            [-1, 0, 0, max[0]],
            [1, 0, 0, -min[0]],
            [0, -1, 0, max[1]],
            [0, 1, 0, -min[1]],
            [0, 0, -1, max[2]],
            [0, 0, 1, -min[2]]
        ], min, max);
    }
    /**
     * Creates a convex bounding volume that is actually an oriented bounding box created from the specified center, half-size and rotation angles.
     * @param center - Center of the OBB.
     * @param halfSize - The half-size of the OBB in each axis. The box will extend by this value in each direction for the given axis.
     * @param angles - The rotation of the box. Euler angles, in degrees.
     */
    static fromCenterSizeAngles(center, halfSize, angles) {
        const q = symbol_layout.fromEuler([], angles[0], angles[1], angles[2]);
        const axisX = symbol_layout.transformQuat([], [halfSize[0], 0, 0], q);
        const axisY = symbol_layout.transformQuat([], [0, halfSize[1], 0], q);
        const axisZ = symbol_layout.transformQuat([], [0, 0, halfSize[2]], q);
        // Find the AABB min/max
        const min = [...center];
        const max = [...center];
        for (let i = 0; i < 8; i++) {
            for (let axis = 0; axis < 3; axis++) {
                const point = center[axis]
                    + axisX[axis] * ((((i >> 0) & 1) === 1) ? 1 : -1)
                    + axisY[axis] * ((((i >> 1) & 1) === 1) ? 1 : -1)
                    + axisZ[axis] * ((((i >> 2) & 1) === 1) ? 1 : -1);
                min[axis] = Math.min(min[axis], point);
                max[axis] = Math.max(max[axis], point);
            }
        }
        const points = [];
        for (let i = 0; i < 8; i++) {
            const p = [...center];
            symbol_layout.add(p, p, symbol_layout.scale$2([], axisX, ((i >> 0) & 1) === 1 ? 1 : -1));
            symbol_layout.add(p, p, symbol_layout.scale$2([], axisY, ((i >> 1) & 1) === 1 ? 1 : -1));
            symbol_layout.add(p, p, symbol_layout.scale$2([], axisZ, ((i >> 2) & 1) === 1 ? 1 : -1));
            points.push(p);
        }
        return new ConvexVolume(points, [
            [...axisX, -symbol_layout.dot(axisX, points[0])],
            [...axisY, -symbol_layout.dot(axisY, points[0])],
            [...axisZ, -symbol_layout.dot(axisZ, points[0])],
            [-axisX[0], -axisX[1], -axisX[2], -symbol_layout.dot(axisX, points[7])],
            [-axisY[0], -axisY[1], -axisY[2], -symbol_layout.dot(axisY, points[7])],
            [-axisZ[0], -axisZ[1], -axisZ[2], -symbol_layout.dot(axisZ, points[7])],
        ], min, max);
    }
    /**
     * Performs an approximate frustum-obb intersection test.
     */
    intersectsFrustum(frustum) {
        // Performance-critical
        let fullyInside = true;
        const boxPointCount = this.points.length;
        const boxPlaneCount = this.planes.length;
        const frustumPlaneCount = frustum.planes.length;
        const frustumPointCount = frustum.points.length;
        // Test whether this volume's points are inside the frustum
        for (let i = 0; i < frustumPlaneCount; i++) {
            const plane = frustum.planes[i];
            let boxPointsPassed = 0;
            for (let j = 0; j < boxPointCount; j++) {
                const point = this.points[j];
                // Get point-plane distance sign
                if (plane[0] * point[0] + plane[1] * point[1] + plane[2] * point[2] + plane[3] >= 0) {
                    boxPointsPassed++;
                }
            }
            if (boxPointsPassed === 0) {
                return 0 /* IntersectionResult.None */;
            }
            if (boxPointsPassed < boxPointCount) {
                fullyInside = false;
            }
        }
        if (fullyInside) {
            return 2 /* IntersectionResult.Full */;
        }
        // Test whether the frustum's points are inside this volume.
        for (let i = 0; i < boxPlaneCount; i++) {
            const plane = this.planes[i];
            let frustumPointsPassed = 0;
            for (let j = 0; j < frustumPointCount; j++) {
                const point = frustum.points[j];
                if (plane[0] * point[0] + plane[1] * point[1] + plane[2] * point[2] + plane[3] >= 0) {
                    frustumPointsPassed++;
                }
            }
            if (frustumPointsPassed === 0) {
                return 0 /* IntersectionResult.None */;
            }
        }
        return 1 /* IntersectionResult.Partial */;
    }
    /**
     * Performs an intersection test with a halfspace.
     */
    intersectsPlane(plane) {
        const pointCount = this.points.length;
        let positivePoints = 0;
        for (let i = 0; i < pointCount; i++) {
            const point = this.points[i];
            if (plane[0] * point[0] + plane[1] * point[1] + plane[2] * point[2] + plane[3] >= 0) {
                positivePoints++;
            }
        }
        if (positivePoints === pointCount) {
            return 2 /* IntersectionResult.Full */;
        }
        if (positivePoints === 0) {
            return 0 /* IntersectionResult.None */;
        }
        return 1 /* IntersectionResult.Partial */;
    }
}

/**
 * Computes distance of a point to a tile in an arbitrary axis.
 * World is assumed to have size 1, distance returned is to the nearer tile edge.
 * @param point - Point position.
 * @param tile - Tile position.
 * @param tileSize - Tile size.
 */
function distanceToTileSimple(point, tile, tileSize) {
    const delta = point - tile;
    return (delta < 0) ? -delta : Math.max(0, delta - tileSize);
}
function distanceToTileWrapX(pointX, pointY, tileCornerX, tileCornerY, tileSize) {
    const tileCornerToPointX = pointX - tileCornerX;
    let distanceX;
    if (tileCornerToPointX < 0) {
        // Point is left of tile
        distanceX = Math.min(-tileCornerToPointX, 1.0 + tileCornerToPointX - tileSize);
    }
    else if (tileCornerToPointX > tileSize) {
        // Point is right of tile
        distanceX = Math.min(Math.max(tileCornerToPointX - tileSize, 0), 1.0 - tileCornerToPointX);
    }
    else {
        // Point is inside tile in the X axis.
        distanceX = 0;
    }
    return Math.max(distanceX, distanceToTileSimple(pointY, tileCornerY, tileSize));
}
class GlobeCoveringTilesDetailsProvider {
    constructor() {
        this._boundingVolumeCache = new BoundingVolumeCache(this._computeTileBoundingVolume);
    }
    /**
     * Prepares the internal bounding volume cache for the next frame.
     */
    prepareNextFrame() {
        this._boundingVolumeCache.swapBuffers();
    }
    /**
     * Returns the distance of a point to a square tile. If the point is inside the tile, returns 0.
     * Assumes the world to be of size 1.
     * Handles distances on a sphere correctly: X is wrapped when crossing the antimeridian,
     * when crossing the poles Y is mirrored and X is shifted by half world size.
     */
    distanceToTile2d(pointX, pointY, tileID, _bv) {
        const scale = 1 << tileID.z;
        const tileMercatorSize = 1.0 / scale;
        const tileCornerX = tileID.x / scale; // In range 0..1
        const tileCornerY = tileID.y / scale; // In range 0..1
        const worldSize = 1.0;
        const halfWorld = 0.5 * worldSize;
        let smallestDistance = 2.0 * worldSize;
        // Original tile
        smallestDistance = Math.min(smallestDistance, distanceToTileWrapX(pointX, pointY, tileCornerX, tileCornerY, tileMercatorSize));
        // Up
        smallestDistance = Math.min(smallestDistance, distanceToTileWrapX(pointX, pointY, tileCornerX + halfWorld, -tileCornerY - tileMercatorSize, tileMercatorSize));
        // Down
        smallestDistance = Math.min(smallestDistance, distanceToTileWrapX(pointX, pointY, tileCornerX + halfWorld, worldSize + worldSize - tileCornerY - tileMercatorSize, tileMercatorSize));
        return smallestDistance;
    }
    /**
     * Returns the wrap value for a given tile, computed so that tiles will remain loaded when crossing the antimeridian.
     */
    getWrap(centerCoord, tileID, _parentWrap) {
        const scale = 1 << tileID.z;
        const tileMercatorSize = 1.0 / scale;
        const tileX = tileID.x / scale; // In range 0..1
        const distanceCurrent = distanceToTileSimple(centerCoord.x, tileX, tileMercatorSize);
        const distanceLeft = distanceToTileSimple(centerCoord.x, tileX - 1.0, tileMercatorSize);
        const distanceRight = distanceToTileSimple(centerCoord.x, tileX + 1.0, tileMercatorSize);
        const distanceSmallest = Math.min(distanceCurrent, distanceLeft, distanceRight);
        if (distanceSmallest === distanceRight) {
            return 1;
        }
        if (distanceSmallest === distanceLeft) {
            return -1;
        }
        return 0;
    }
    allowVariableZoom(transform, options) {
        return coveringZoomLevel(transform, options) > 4;
    }
    allowWorldCopies() {
        return false;
    }
    getTileBoundingVolume(tileID, wrap, elevation, options) {
        return this._boundingVolumeCache.getTileBoundingVolume(tileID, wrap, elevation, options);
    }
    _computeTileBoundingVolume(tileID, wrap, elevation, options) {
        var _a, _b;
        let minElevation = 0;
        let maxElevation = 0;
        if (options === null || options === void 0 ? void 0 : options.terrain) {
            const overscaledTileID = new symbol_layout.OverscaledTileID(tileID.z, wrap, tileID.z, tileID.x, tileID.y);
            const minMax = options.terrain.getMinMaxElevation(overscaledTileID);
            minElevation = (_a = minMax.minElevation) !== null && _a !== void 0 ? _a : Math.min(0, elevation);
            maxElevation = (_b = minMax.maxElevation) !== null && _b !== void 0 ? _b : Math.max(0, elevation);
        }
        // Convert elevation to distances from center of a unit sphere planet (so that 1 is surface)
        minElevation /= symbol_layout.earthRadius;
        maxElevation /= symbol_layout.earthRadius;
        minElevation += 1;
        maxElevation += 1;
        if (tileID.z <= 0) {
            // Tile covers the entire sphere.
            return ConvexVolume.fromAabb(// We return an AABB in this case.
            [-maxElevation, -maxElevation, -maxElevation], [maxElevation, maxElevation, maxElevation]);
        }
        else if (tileID.z === 1) {
            // Tile covers a quarter of the sphere.
            // X is 1 at lng=E90°
            // Y is 1 at **north** pole
            // Z is 1 at null island
            return ConvexVolume.fromAabb(// We also just use AABBs for this zoom level.
            [tileID.x === 0 ? -maxElevation : 0, tileID.y === 0 ? 0 : -maxElevation, -maxElevation], [tileID.x === 0 ? 0 : maxElevation, tileID.y === 0 ? maxElevation : 0, maxElevation]);
        }
        else {
            const corners = [
                projectTileCoordinatesToSphere(0, 0, tileID.x, tileID.y, tileID.z),
                projectTileCoordinatesToSphere(symbol_layout.EXTENT, 0, tileID.x, tileID.y, tileID.z),
                projectTileCoordinatesToSphere(symbol_layout.EXTENT, symbol_layout.EXTENT, tileID.x, tileID.y, tileID.z),
                projectTileCoordinatesToSphere(0, symbol_layout.EXTENT, tileID.x, tileID.y, tileID.z),
            ];
            const extremesPoints = [];
            for (const c of corners) {
                extremesPoints.push(symbol_layout.scale$2([], c, maxElevation));
            }
            if (maxElevation !== minElevation) {
                // Only add additional points if terrain is enabled and is not flat.
                for (const c of corners) {
                    extremesPoints.push(symbol_layout.scale$2([], c, minElevation));
                }
            }
            // Special handling of poles - we need to extend the tile AABB
            // to include the pole for tiles that border mercator north/south edge.
            if (tileID.y === 0) {
                extremesPoints.push([0, 1, 0]); // North pole
            }
            if (tileID.y === (1 << tileID.z) - 1) {
                extremesPoints.push([0, -1, 0]); // South pole
            }
            // Compute a best-fit AABB for the frustum rejection test
            const aabbMin = [1, 1, 1];
            const aabbMax = [-1, -1, -1];
            for (const c of extremesPoints) {
                for (let i = 0; i < 3; i++) {
                    aabbMin[i] = Math.min(aabbMin[i], c[i]);
                    aabbMax[i] = Math.max(aabbMax[i], c[i]);
                }
            }
            // Now we compute the actual bounding volume.
            // The up/down plane will be normal to the tile's center.
            // The north/south plane will be used for the tile's north and south edge and will be orthogonal to the up/down plane.
            // The left and right planes will be determined by the tile's east/west edges and will differ slightly - we are not creating a box!
            // We will find the min and max extents for the up/down and north/south planes using the set of points
            // where the extremes are likely to lie.
            // Vector "center" (from planet center to tile center) will be our up/down axis.
            const center = projectTileCoordinatesToSphere(symbol_layout.EXTENT / 2, symbol_layout.EXTENT / 2, tileID.x, tileID.y, tileID.z);
            // Vector to the east of "center".
            const centerEast = symbol_layout.cross([], [0, 1, 0], center);
            symbol_layout.normalize(centerEast, centerEast);
            // Vector to the north of "center" will be our north/south axis.
            const north = symbol_layout.cross([], center, centerEast);
            symbol_layout.normalize(north, north);
            // Axes for the east and west edge of our bounding volume.
            // These axes are NOT opposites of each other, they differ!
            // They are also not orthogonal to the up/down and north/south axes.
            const axisEast = symbol_layout.cross([], corners[2], corners[1]);
            symbol_layout.normalize(axisEast, axisEast);
            const axisWest = symbol_layout.cross([], corners[0], corners[3]);
            symbol_layout.normalize(axisWest, axisWest);
            // Now we will expand the extremes point set for bounding volume creation.
            // We will also include the tile center point, since it will always be an extreme for the "center" axis.
            extremesPoints.push(symbol_layout.scale$2([], center, maxElevation));
            // No need to include a minElevation-scaled center, since we already have minElevation corners in the set and these will always lie lower than the center.
            // The extremes might also lie on the midpoint of the north or south edge.
            // For tiles in the north hemisphere, only the south edge can contain an extreme,
            // since when we imagine the tile's actual shape projected onto the plane normal to "center" vector,
            // the tile's north edge will curve towards the tile center, thus its extremes are accounted for by the
            // corners, however the south edge will curve away from the center point, extending beyond the tile's edges,
            // thus it must be included.
            // The poles are an exception - they must always be included in the extremes, if the tile touches the north/south mercator range edge.
            //
            // A tile's exaggerated shape on the northern hemisphere, projected onto the normal plane of "center".
            // The "c" is the tile's center point. The "m" is the edge mid point we are looking for.
            //
            //      /--       --\
            //     /   -------   \
            //    /               \
            //   /        c        \
            //  /                   \
            // /--                 --\
            //    -----       -----
            //         ---m---
            if (tileID.y >= (1 << tileID.z) / 2) {
                // South hemisphere - include the tile's north edge midpoint
                extremesPoints.push(symbol_layout.scale$2([], projectTileCoordinatesToSphere(symbol_layout.EXTENT / 2, 0, tileID.x, tileID.y, tileID.z), maxElevation));
                // No need to include minElevation variant of this point, for the same reason why we don't include minElevation center.
            }
            if (tileID.y < (1 << tileID.z) / 2) {
                // North hemisphere - include the tile's south edge midpoint
                extremesPoints.push(symbol_layout.scale$2([], projectTileCoordinatesToSphere(symbol_layout.EXTENT / 2, symbol_layout.EXTENT, tileID.x, tileID.y, tileID.z), maxElevation));
                // No need to include minElevation variant of this point, for the same reason why we don't include minElevation center.
            }
            // Find the min and max extends and the midpoints along each axis,
            // using the set of extreme points.
            const upDownMinMax = findAxisMinMax(center, extremesPoints);
            const northSouthMinMax = findAxisMinMax(north, extremesPoints);
            const planeUp = [-center[0], -center[1], -center[2], upDownMinMax.max];
            const planeDown = [center[0], center[1], center[2], -upDownMinMax.min];
            const planeNorth = [-north[0], -north[1], -north[2], northSouthMinMax.max];
            const planeSouth = [north[0], north[1], north[2], -northSouthMinMax.min];
            const planeEast = [...axisEast, 0];
            const planeWest = [...axisWest, 0];
            const points = [];
            // North points
            if (tileID.y === 0) {
                // If the tile borders a pole, then 
                points.push(symbol_layout.threePlaneIntersection(planeWest, planeEast, planeUp), symbol_layout.threePlaneIntersection(planeWest, planeEast, planeDown));
            }
            else {
                points.push(symbol_layout.threePlaneIntersection(planeNorth, planeEast, planeUp), symbol_layout.threePlaneIntersection(planeNorth, planeEast, planeDown), symbol_layout.threePlaneIntersection(planeNorth, planeWest, planeUp), symbol_layout.threePlaneIntersection(planeNorth, planeWest, planeDown));
            }
            // South points
            if (tileID.y === (1 << tileID.z) - 1) {
                points.push(symbol_layout.threePlaneIntersection(planeWest, planeEast, planeUp), symbol_layout.threePlaneIntersection(planeWest, planeEast, planeDown));
            }
            else {
                points.push(symbol_layout.threePlaneIntersection(planeSouth, planeEast, planeUp), symbol_layout.threePlaneIntersection(planeSouth, planeEast, planeDown), symbol_layout.threePlaneIntersection(planeSouth, planeWest, planeUp), symbol_layout.threePlaneIntersection(planeSouth, planeWest, planeDown));
            }
            return new ConvexVolume(points, [
                planeUp,
                planeDown,
                planeNorth,
                planeSouth,
                planeEast,
                planeWest
            ], aabbMin, aabbMax);
        }
    }
}
function findAxisMinMax(axis, points) {
    let min = +Infinity;
    let max = -Infinity;
    for (const c of points) {
        const dot = symbol_layout.dot(axis, c);
        min = Math.min(min, dot);
        max = Math.max(max, dot);
    }
    return {
        min,
        max
    };
}

class VerticalPerspectiveTransform {
    //
    // Implementation of transform getters and setters
    //
    get pixelsToClipSpaceMatrix() {
        return this._helper.pixelsToClipSpaceMatrix;
    }
    get clipSpaceToPixelsMatrix() {
        return this._helper.clipSpaceToPixelsMatrix;
    }
    get pixelsToGLUnits() {
        return this._helper.pixelsToGLUnits;
    }
    get centerOffset() {
        return this._helper.centerOffset;
    }
    get size() {
        return this._helper.size;
    }
    get rotationMatrix() {
        return this._helper.rotationMatrix;
    }
    get centerPoint() {
        return this._helper.centerPoint;
    }
    get pixelsPerMeter() {
        return this._helper.pixelsPerMeter;
    }
    setMinZoom(zoom) {
        this._helper.setMinZoom(zoom);
    }
    setMaxZoom(zoom) {
        this._helper.setMaxZoom(zoom);
    }
    setMinPitch(pitch) {
        this._helper.setMinPitch(pitch);
    }
    setMaxPitch(pitch) {
        this._helper.setMaxPitch(pitch);
    }
    setRenderWorldCopies(renderWorldCopies) {
        this._helper.setRenderWorldCopies(renderWorldCopies);
    }
    setBearing(bearing) {
        this._helper.setBearing(bearing);
    }
    setPitch(pitch) {
        this._helper.setPitch(pitch);
    }
    setRoll(roll) {
        this._helper.setRoll(roll);
    }
    setFov(fov) {
        this._helper.setFov(fov);
    }
    setZoom(zoom) {
        this._helper.setZoom(zoom);
    }
    setCenter(center) {
        this._helper.setCenter(center);
    }
    setElevation(elevation) {
        this._helper.setElevation(elevation);
    }
    setMinElevationForCurrentTile(elevation) {
        this._helper.setMinElevationForCurrentTile(elevation);
    }
    setPadding(padding) {
        this._helper.setPadding(padding);
    }
    interpolatePadding(start, target, t) {
        this._helper.interpolatePadding(start, target, t);
    }
    isPaddingEqual(padding) {
        return this._helper.isPaddingEqual(padding);
    }
    resize(width, height) {
        this._helper.resize(width, height);
    }
    getMaxBounds() {
        return this._helper.getMaxBounds();
    }
    setMaxBounds(bounds) {
        this._helper.setMaxBounds(bounds);
    }
    setConstrainOverride(constrain) {
        this._helper.setConstrainOverride(constrain);
    }
    overrideNearFarZ(nearZ, farZ) {
        this._helper.overrideNearFarZ(nearZ, farZ);
    }
    clearNearFarZOverride() {
        this._helper.clearNearFarZOverride();
    }
    getCameraQueryGeometry(queryGeometry) {
        return this._helper.getCameraQueryGeometry(this.getCameraPoint(), queryGeometry);
    }
    get tileSize() {
        return this._helper.tileSize;
    }
    get tileZoom() {
        return this._helper.tileZoom;
    }
    get scale() {
        return this._helper.scale;
    }
    get worldSize() {
        return this._helper.worldSize;
    }
    get width() {
        return this._helper.width;
    }
    get height() {
        return this._helper.height;
    }
    get lngRange() {
        return this._helper.lngRange;
    }
    get latRange() {
        return this._helper.latRange;
    }
    get minZoom() {
        return this._helper.minZoom;
    }
    get maxZoom() {
        return this._helper.maxZoom;
    }
    get zoom() {
        return this._helper.zoom;
    }
    get center() {
        return this._helper.center;
    }
    get minPitch() {
        return this._helper.minPitch;
    }
    get maxPitch() {
        return this._helper.maxPitch;
    }
    get pitch() {
        return this._helper.pitch;
    }
    get pitchInRadians() {
        return this._helper.pitchInRadians;
    }
    get roll() {
        return this._helper.roll;
    }
    get rollInRadians() {
        return this._helper.rollInRadians;
    }
    get bearing() {
        return this._helper.bearing;
    }
    get bearingInRadians() {
        return this._helper.bearingInRadians;
    }
    get fov() {
        return this._helper.fov;
    }
    get fovInRadians() {
        return this._helper.fovInRadians;
    }
    get elevation() {
        return this._helper.elevation;
    }
    get minElevationForCurrentTile() {
        return this._helper.minElevationForCurrentTile;
    }
    get padding() {
        return this._helper.padding;
    }
    get unmodified() {
        return this._helper.unmodified;
    }
    get renderWorldCopies() {
        return this._helper.renderWorldCopies;
    }
    get constrainOverride() {
        return this._helper.constrainOverride;
    }
    get nearZ() {
        return this._helper.nearZ;
    }
    get farZ() {
        return this._helper.farZ;
    }
    get autoCalculateNearFarZ() {
        return this._helper.autoCalculateNearFarZ;
    }
    setTransitionState(_value) {
        // Do nothing
    }
    constructor(options) {
        //
        // Implementation of globe transform
        //
        this._cachedClippingPlane = symbol_layout.createVec4f64();
        this._projectionMatrix = symbol_layout.createIdentityMat4f64();
        this._globeViewProjMatrix32f = symbol_layout.createIdentityMat4f32(); // Must be 32 bit floats, otherwise WebGL calls in Chrome get very slow.
        this._globeViewProjMatrixNoCorrection = symbol_layout.createIdentityMat4f64();
        this._globeViewProjMatrixNoCorrectionInverted = symbol_layout.createIdentityMat4f64();
        this._globeProjMatrixInverted = symbol_layout.createIdentityMat4f64();
        this._cameraPosition = symbol_layout.createVec3f64();
        this._globeLatitudeErrorCorrectionRadians = 0;
        this.defaultConstrain = (lngLat, zoom) => {
            // Globe: TODO: respect _lngRange, _latRange
            // It is possible to implement exact constrain for globe, but I don't think it is worth the effort.
            const constrainedLat = symbol_layout.clamp(lngLat.lat, -symbol_layout.MAX_VALID_LATITUDE, symbol_layout.MAX_VALID_LATITUDE);
            const constrainedZoom = symbol_layout.clamp(+zoom, this.minZoom + getZoomAdjustment(0, constrainedLat), this.maxZoom);
            return {
                center: new symbol_layout.LngLat(lngLat.lng, constrainedLat),
                zoom: constrainedZoom
            };
        };
        this.applyConstrain = (lngLat, zoom) => {
            return this._helper.applyConstrain(lngLat, zoom);
        };
        this._helper = new TransformHelper({
            calcMatrices: () => this._calcMatrices(),
            defaultConstrain: (center, zoom) => { return this.defaultConstrain(center, zoom); }
        }, options);
        this._coveringTilesDetailsProvider = new GlobeCoveringTilesDetailsProvider();
    }
    clone() {
        const clone = new VerticalPerspectiveTransform();
        clone.apply(this, false);
        return clone;
    }
    apply(that, constrain, globeLatitudeErrorCorrectionRadians) {
        this._globeLatitudeErrorCorrectionRadians = globeLatitudeErrorCorrectionRadians || 0;
        this._helper.apply(that, constrain);
    }
    get projectionMatrix() { return this._projectionMatrix; }
    get modelViewProjectionMatrix() { return this._globeViewProjMatrixNoCorrection; }
    get inverseProjectionMatrix() { return this._globeProjMatrixInverted; }
    get cameraPosition() {
        // Return a copy - don't let outside code mutate our precomputed camera position.
        const copy = symbol_layout.createVec3f64(); // Ensure the resulting vector is float64s
        copy[0] = this._cameraPosition[0];
        copy[1] = this._cameraPosition[1];
        copy[2] = this._cameraPosition[2];
        return copy;
    }
    get cameraToCenterDistance() {
        // Globe uses the same cameraToCenterDistance as mercator.
        return this._helper.cameraToCenterDistance;
    }
    getProjectionData(params) {
        const { overscaledTileID, applyGlobeMatrix } = params;
        const mercatorTileCoordinates = this._helper.getMercatorTileCoordinates(overscaledTileID);
        return {
            mainMatrix: this._globeViewProjMatrix32f,
            tileMercatorCoords: mercatorTileCoordinates,
            clippingPlane: this._cachedClippingPlane,
            projectionTransition: applyGlobeMatrix ? 1 : 0,
            fallbackMatrix: this._globeViewProjMatrix32f,
        };
    }
    _computeClippingPlane(globeRadiusPixels) {
        // We want to compute a plane equation that, when applied to the unit sphere generated
        // in the vertex shader, places all visible parts of the sphere into the positive half-space
        // and all the non-visible parts in the negative half-space.
        // We can then use that to accurately clip all non-visible geometry.
        // cam....------------A
        //        ....        |
        //            ....    |
        //                ....B
        //                ggggggggg
        //          gggggg    |   .gggggg
        //       ggg          |       ...ggg    ^
        //     gg             |                 |
        //    g               |                 y
        //    g               |                 |
        //   g                C                 #---x--->
        //
        // Notes:
        // - note the coordinate axes
        // - "g" marks the globe edge
        // - the dotted line is the camera center "ray" - we are looking in this direction
        // - "cam" is camera origin
        // - "C" is globe center
        // - "B" is the point on "top" of the globe - camera is looking at B - "B" is the intersection between the camera center ray and the globe
        // - this._pitchInRadians is the angle at B between points cam,B,A
        // - this.cameraToCenterDistance is the distance from camera to "B"
        // - globe radius is (0.5 * this.worldSize)
        // - "T" is any point where a tangent line from "cam" touches the globe surface
        // - elevation is assumed to be zero - globe rendering must be separate from terrain rendering anyway
        const pitch = this.pitchInRadians;
        // scale things so that the globe radius is 1
        const distanceCameraToB = this.cameraToCenterDistance / globeRadiusPixels;
        const radius = 1;
        // Distance from camera to "A" - the point at the same elevation as camera, right above center point on globe
        const distanceCameraToA = Math.sin(pitch) * distanceCameraToB;
        // Distance from "A" to "C"
        const distanceAtoC = (Math.cos(pitch) * distanceCameraToB + radius);
        // Distance from camera to "C" - the globe center
        const distanceCameraToC = Math.sqrt(distanceCameraToA * distanceCameraToA + distanceAtoC * distanceAtoC);
        // cam - C - T angle cosine (at C)
        const camCTcosine = radius / distanceCameraToC;
        // Distance from globe center to the plane defined by all possible "T" points
        const tangentPlaneDistanceToC = camCTcosine * radius;
        let vectorCtoCamX = -distanceCameraToA;
        let vectorCtoCamY = distanceAtoC;
        // Normalize the vector
        const vectorCtoCamLength = Math.sqrt(vectorCtoCamX * vectorCtoCamX + vectorCtoCamY * vectorCtoCamY);
        vectorCtoCamX /= vectorCtoCamLength;
        vectorCtoCamY /= vectorCtoCamLength;
        // Note the swizzled components
        const planeVector = [0, vectorCtoCamX, vectorCtoCamY];
        // Apply transforms - lat, lng and angle (NOT pitch - already accounted for, as it affects the tangent plane)
        symbol_layout.rotateZ$1(planeVector, planeVector, [0, 0, 0], -this.bearingInRadians);
        symbol_layout.rotateX$1(planeVector, planeVector, [0, 0, 0], -1 * this.center.lat * Math.PI / 180.0);
        symbol_layout.rotateY(planeVector, planeVector, [0, 0, 0], this.center.lng * Math.PI / 180.0);
        // Normalize the plane vector
        const scale = 1 / symbol_layout.length$1(planeVector);
        symbol_layout.scale$2(planeVector, planeVector, scale);
        return [...planeVector, -tangentPlaneDistanceToC * scale];
    }
    isLocationOccluded(location) {
        return !this.isSurfacePointVisible(angularCoordinatesToSurfaceVector(location));
    }
    transformLightDirection(dir) {
        const sphereX = this._helper._center.lng * Math.PI / 180.0;
        const sphereY = this._helper._center.lat * Math.PI / 180.0;
        const len = Math.cos(sphereY);
        const spherePos = [
            Math.sin(sphereX) * len,
            Math.sin(sphereY),
            Math.cos(sphereX) * len
        ];
        const axisRight = [spherePos[2], 0.0, -spherePos[0]]; // Equivalent to cross(vec3(0.0, 1.0, 0.0), vec)
        const axisDown = [0, 0, 0];
        symbol_layout.cross(axisDown, axisRight, spherePos);
        symbol_layout.normalize(axisRight, axisRight);
        symbol_layout.normalize(axisDown, axisDown);
        const transformed = [
            axisRight[0] * dir[0] + axisDown[0] * dir[1] + spherePos[0] * dir[2],
            axisRight[1] * dir[0] + axisDown[1] * dir[1] + spherePos[1] * dir[2],
            axisRight[2] * dir[0] + axisDown[2] * dir[1] + spherePos[2] * dir[2]
        ];
        const normalized = [0, 0, 0];
        symbol_layout.normalize(normalized, transformed);
        return normalized;
    }
    getPixelScale() {
        return 1.0 / Math.cos(this._helper._center.lat * Math.PI / 180);
    }
    getCircleRadiusCorrection() {
        return Math.cos(this._helper._center.lat * Math.PI / 180);
    }
    getPitchedTextCorrection(textAnchorX, textAnchorY, tileID) {
        const mercator = tileCoordinatesToMercatorCoordinates(textAnchorX, textAnchorY, tileID.canonical);
        const angular = mercatorCoordinatesToAngularCoordinatesRadians(mercator.x, mercator.y);
        return this.getCircleRadiusCorrection() / Math.cos(angular[1]);
    }
    projectTileCoordinates(x, y, unwrappedTileID, getElevation) {
        const canonical = unwrappedTileID.canonical;
        const spherePos = projectTileCoordinatesToSphere(x, y, canonical.x, canonical.y, canonical.z);
        const elevation = getElevation ? getElevation(x, y) : 0.0;
        const vectorMultiplier = 1.0 + elevation / symbol_layout.earthRadius;
        const pos = [spherePos[0] * vectorMultiplier, spherePos[1] * vectorMultiplier, spherePos[2] * vectorMultiplier, 1];
        symbol_layout.transformMat4(pos, pos, this._globeViewProjMatrixNoCorrection);
        // Also check whether the point projects to the backfacing side of the sphere.
        const plane = this._cachedClippingPlane;
        // dot(position on sphere, occlusion plane equation)
        const dotResult = plane[0] * spherePos[0] + plane[1] * spherePos[1] + plane[2] * spherePos[2] + plane[3];
        const isOccluded = dotResult < 0.0;
        return {
            point: new symbol_layout.Point(pos[0] / pos[3], pos[1] / pos[3]),
            signedDistanceFromCamera: pos[3],
            isOccluded
        };
    }
    _calcMatrices() {
        if (!this._helper._width || !this._helper._height) {
            return;
        }
        const globeRadiusPixels = getGlobeRadiusPixels(this.worldSize, this.center.lat);
        // Construct a completely separate matrix for globe view
        const globeMatrix = symbol_layout.createMat4f64();
        const globeMatrixUncorrected = symbol_layout.createMat4f64();
        if (this._helper.autoCalculateNearFarZ) {
            this._helper._nearZ = 0.5;
            this._helper._farZ = this.cameraToCenterDistance + globeRadiusPixels * 2.0; // just set the far plane far enough - we will calculate our own z in the vertex shader anyway
        }
        symbol_layout.perspective(globeMatrix, this.fovInRadians, this.width / this.height, this._helper._nearZ, this._helper._farZ);
        // Apply center of perspective offset
        const offset = this.centerOffset;
        globeMatrix[8] = -offset.x * 2 / this._helper._width;
        globeMatrix[9] = offset.y * 2 / this._helper._height;
        this._projectionMatrix = symbol_layout.clone$1(globeMatrix);
        this._globeProjMatrixInverted = symbol_layout.createMat4f64();
        symbol_layout.invert$1(this._globeProjMatrixInverted, globeMatrix);
        symbol_layout.translate(globeMatrix, globeMatrix, [0, 0, -this.cameraToCenterDistance]);
        symbol_layout.rotateZ(globeMatrix, globeMatrix, this.rollInRadians);
        symbol_layout.rotateX(globeMatrix, globeMatrix, -this.pitchInRadians);
        symbol_layout.rotateZ(globeMatrix, globeMatrix, this.bearingInRadians);
        symbol_layout.translate(globeMatrix, globeMatrix, [0.0, 0, -globeRadiusPixels]);
        // Rotate the sphere to center it on viewed coordinates
        const scaleVec = symbol_layout.createVec3f64();
        scaleVec[0] = globeRadiusPixels;
        scaleVec[1] = globeRadiusPixels;
        scaleVec[2] = globeRadiusPixels;
        // Keep a atan-correction-free matrix for transformations done on the CPU with accurate math
        symbol_layout.rotateX(globeMatrixUncorrected, globeMatrix, this.center.lat * Math.PI / 180.0);
        symbol_layout.rotateY$1(globeMatrixUncorrected, globeMatrixUncorrected, -this.center.lng * Math.PI / 180.0);
        symbol_layout.scale(globeMatrixUncorrected, globeMatrixUncorrected, scaleVec); // Scale the unit sphere to a sphere with diameter of 1
        this._globeViewProjMatrixNoCorrection = globeMatrixUncorrected;
        symbol_layout.rotateX(globeMatrix, globeMatrix, this.center.lat * Math.PI / 180.0 - this._globeLatitudeErrorCorrectionRadians);
        symbol_layout.rotateY$1(globeMatrix, globeMatrix, -this.center.lng * Math.PI / 180.0);
        symbol_layout.scale(globeMatrix, globeMatrix, scaleVec); // Scale the unit sphere to a sphere with diameter of 1
        this._globeViewProjMatrix32f = new Float32Array(globeMatrix);
        this._globeViewProjMatrixNoCorrectionInverted = symbol_layout.createMat4f64();
        symbol_layout.invert$1(this._globeViewProjMatrixNoCorrectionInverted, globeMatrixUncorrected);
        const zero = symbol_layout.createVec3f64();
        this._cameraPosition = symbol_layout.createVec3f64();
        this._cameraPosition[2] = this.cameraToCenterDistance / globeRadiusPixels;
        symbol_layout.rotateZ$1(this._cameraPosition, this._cameraPosition, zero, -this.rollInRadians);
        symbol_layout.rotateX$1(this._cameraPosition, this._cameraPosition, zero, this.pitchInRadians);
        symbol_layout.rotateZ$1(this._cameraPosition, this._cameraPosition, zero, -this.bearingInRadians);
        symbol_layout.add(this._cameraPosition, this._cameraPosition, [0, 0, 1]);
        symbol_layout.rotateX$1(this._cameraPosition, this._cameraPosition, zero, -this.center.lat * Math.PI / 180.0);
        symbol_layout.rotateY(this._cameraPosition, this._cameraPosition, zero, this.center.lng * Math.PI / 180.0);
        this._cachedClippingPlane = this._computeClippingPlane(globeRadiusPixels);
        const matrix = symbol_layout.clone$1(this._globeViewProjMatrixNoCorrectionInverted);
        symbol_layout.scale(matrix, matrix, [1, 1, -1]);
        this._cachedFrustum = Frustum.fromInvProjectionMatrix(matrix, 1, 0, this._cachedClippingPlane, true);
    }
    calculateFogMatrix(_unwrappedTileID) {
        symbol_layout.warnOnce('calculateFogMatrix is not supported on globe projection.');
        const m = symbol_layout.createMat4f64();
        symbol_layout.identity(m);
        return m;
    }
    getVisibleUnwrappedCoordinates(tileID) {
        // Globe has no wrap.
        return [new symbol_layout.UnwrappedTileID(0, tileID)];
    }
    getCameraFrustum() {
        return this._cachedFrustum;
    }
    getClippingPlane() {
        return this._cachedClippingPlane;
    }
    getCoveringTilesDetailsProvider() {
        return this._coveringTilesDetailsProvider;
    }
    recalculateZoomAndCenter(terrain) {
        if (terrain) {
            symbol_layout.warnOnce('terrain is not fully supported on vertical perspective projection.');
        }
        this._helper.recalculateZoomAndCenter(0);
    }
    maxPitchScaleFactor() {
        // In mercaltor it uses the pixelMatrix, but this is not available here...
        return 1;
    }
    getCameraPoint() {
        return this._helper.getCameraPoint();
    }
    getCameraAltitude() {
        return this._helper.getCameraAltitude();
    }
    getCameraLngLat() {
        return this._helper.getCameraLngLat();
    }
    lngLatToCameraDepth(lngLat, elevation) {
        if (!this._globeViewProjMatrixNoCorrection) {
            return 1.0; // _calcMatrices hasn't run yet
        }
        const vec = angularCoordinatesToSurfaceVector(lngLat);
        symbol_layout.scale$2(vec, vec, (1.0 + elevation / symbol_layout.earthRadius));
        const result = symbol_layout.createVec4f64();
        symbol_layout.transformMat4(result, [vec[0], vec[1], vec[2], 1], this._globeViewProjMatrixNoCorrection);
        return result[2] / result[3];
    }
    populateCache(_coords) {
        // Do nothing
    }
    getBounds() {
        const xMid = this.width * 0.5;
        const yMid = this.height * 0.5;
        // LngLat extremes will probably tend to be in screen corners or in middle of screen edges.
        // These test points should result in a pretty good approximation.
        const testPoints = [
            new symbol_layout.Point(0, 0),
            new symbol_layout.Point(xMid, 0),
            new symbol_layout.Point(this.width, 0),
            new symbol_layout.Point(this.width, yMid),
            new symbol_layout.Point(this.width, this.height),
            new symbol_layout.Point(xMid, this.height),
            new symbol_layout.Point(0, this.height),
            new symbol_layout.Point(0, yMid),
        ];
        const projectedPoints = [];
        for (const p of testPoints) {
            projectedPoints.push(this.unprojectScreenPoint(p));
        }
        // We can't construct a simple min/max aabb, since points might lie on either side of the antimeridian.
        // We will instead compute the furthest points relative to map center.
        // We also take advantage of the fact that `unprojectScreenPoint` will snap pixels
        // outside the planet to the closest point on the planet's horizon.
        let mostEast = 0, mostWest = 0, mostNorth = 0, mostSouth = 0; // We will store these values signed.
        const center = this.center;
        for (const p of projectedPoints) {
            const dLng = symbol_layout.differenceOfAnglesDegrees(center.lng, p.lng);
            const dLat = symbol_layout.differenceOfAnglesDegrees(center.lat, p.lat);
            if (dLng < mostWest) {
                mostWest = dLng;
            }
            if (dLng > mostEast) {
                mostEast = dLng;
            }
            if (dLat < mostSouth) {
                mostSouth = dLat;
            }
            if (dLat > mostNorth) {
                mostNorth = dLat;
            }
        }
        const boundsArray = [
            center.lng + mostWest, // west
            center.lat + mostSouth, // south
            center.lng + mostEast, // east
            center.lat + mostNorth // north
        ];
        // Sometimes the poles might end up not being on the horizon,
        // thus not being detected as the northernmost/southernmost points.
        // We fix that here.
        if (this.isSurfacePointOnScreen([0, 1, 0])) {
            // North pole is visible
            // This also means that the entire longitude range must be visible
            boundsArray[3] = 90;
            boundsArray[0] = -180;
            boundsArray[2] = 180;
        }
        if (this.isSurfacePointOnScreen([0, -1, 0])) {
            // South pole is visible
            boundsArray[1] = -90;
            boundsArray[0] = -180;
            boundsArray[2] = 180;
        }
        return new LngLatBounds(boundsArray);
    }
    calculateCenterFromCameraLngLatAlt(lngLat, alt, bearing, pitch) {
        return this._helper.calculateCenterFromCameraLngLatAlt(lngLat, alt, bearing, pitch);
    }
    /**
     * Note: automatically adjusts zoom to keep planet size consistent
     * (same size before and after a {@link setLocationAtPoint} call).
     */
    setLocationAtPoint(lnglat, point) {
        // This returns some fake coordinates for pixels that do not lie on the planet.
        // Whatever uses this `setLocationAtPoint` function will need to account for that.
        const pointLngLat = this.unprojectScreenPoint(point);
        const vecToPixelCurrent = angularCoordinatesToSurfaceVector(pointLngLat);
        const vecToTarget = angularCoordinatesToSurfaceVector(lnglat);
        const zero = symbol_layout.createVec3f64();
        symbol_layout.zero$1(zero);
        const rotatedPixelVector = symbol_layout.createVec3f64();
        symbol_layout.rotateY(rotatedPixelVector, vecToPixelCurrent, zero, -this.center.lng * Math.PI / 180.0);
        symbol_layout.rotateX$1(rotatedPixelVector, rotatedPixelVector, zero, this.center.lat * Math.PI / 180.0);
        // We are looking for the lng,lat that will rotate `vecToTarget`
        // so that it is equal to `rotatedPixelVector`.
        // The second rotation around X axis cannot change the X component,
        // so we first must find the longitude such that rotating `vecToTarget` with it
        // will place it so its X component is equal to X component of `rotatedPixelVector`.
        // There will exist zero, one or two longitudes that satisfy this.
        //      x  |
        //     /   |
        //    /    | the line is the target X - rotatedPixelVector.x
        //   /     | the x is vecToTarget projected to x,z plane
        //  .      | the dot is origin
        //
        // We need to rotate vecToTarget so that it intersects the line.
        // If vecToTarget is shorter than the distance to the line from origin, it is impossible.
        // Otherwise, we compute the intersection of the line with a ring with radius equal to
        // length of vecToTarget projected to XZ plane.
        const vecToTargetXZLengthSquared = vecToTarget[0] * vecToTarget[0] + vecToTarget[2] * vecToTarget[2];
        const targetXSquared = rotatedPixelVector[0] * rotatedPixelVector[0];
        if (vecToTargetXZLengthSquared < targetXSquared) {
            // Zero solutions - setLocationAtPoint is impossible.
            return;
        }
        // The intersection's Z coordinates
        const intersectionA = Math.sqrt(vecToTargetXZLengthSquared - targetXSquared);
        const intersectionB = -intersectionA; // the second solution
        const lngA = symbol_layout.angleToRotateBetweenVectors2D(vecToTarget[0], vecToTarget[2], rotatedPixelVector[0], intersectionA);
        const lngB = symbol_layout.angleToRotateBetweenVectors2D(vecToTarget[0], vecToTarget[2], rotatedPixelVector[0], intersectionB);
        const vecToTargetLngA = symbol_layout.createVec3f64();
        symbol_layout.rotateY(vecToTargetLngA, vecToTarget, zero, -lngA);
        const latA = symbol_layout.angleToRotateBetweenVectors2D(vecToTargetLngA[1], vecToTargetLngA[2], rotatedPixelVector[1], rotatedPixelVector[2]);
        const vecToTargetLngB = symbol_layout.createVec3f64();
        symbol_layout.rotateY(vecToTargetLngB, vecToTarget, zero, -lngB);
        const latB = symbol_layout.angleToRotateBetweenVectors2D(vecToTargetLngB[1], vecToTargetLngB[2], rotatedPixelVector[1], rotatedPixelVector[2]);
        // Is at least one of the needed latitudes valid?
        const limit = Math.PI * 0.5;
        const isValidA = latA >= -limit && latA <= limit;
        const isValidB = latB >= -limit && latB <= limit;
        let validLng;
        let validLat;
        if (isValidA && isValidB) {
            // Pick the solution that is closer to current map center.
            const centerLngRadians = this.center.lng * Math.PI / 180.0;
            const centerLatRadians = this.center.lat * Math.PI / 180.0;
            const lngDistA = symbol_layout.distanceOfAnglesRadians(lngA, centerLngRadians);
            const latDistA = symbol_layout.distanceOfAnglesRadians(latA, centerLatRadians);
            const lngDistB = symbol_layout.distanceOfAnglesRadians(lngB, centerLngRadians);
            const latDistB = symbol_layout.distanceOfAnglesRadians(latB, centerLatRadians);
            if ((lngDistA + latDistA) < (lngDistB + latDistB)) {
                validLng = lngA;
                validLat = latA;
            }
            else {
                validLng = lngB;
                validLat = latB;
            }
        }
        else if (isValidA) {
            validLng = lngA;
            validLat = latA;
        }
        else if (isValidB) {
            validLng = lngB;
            validLat = latB;
        }
        else {
            // No solution.
            return;
        }
        const newLng = validLng / Math.PI * 180;
        const newLat = validLat / Math.PI * 180;
        const oldLat = this.center.lat;
        this.setCenter(new symbol_layout.LngLat(newLng, symbol_layout.clamp(newLat, -90, 90)));
        this.setZoom(this.zoom + getZoomAdjustment(oldLat, this.center.lat));
    }
    locationToScreenPoint(lnglat, terrain) {
        const pos = angularCoordinatesToSurfaceVector(lnglat);
        if (terrain) {
            const elevation = terrain.getElevationForLngLatZoom(lnglat, this._helper._tileZoom);
            symbol_layout.scale$2(pos, pos, 1.0 + elevation / symbol_layout.earthRadius);
        }
        return this._projectSurfacePointToScreen(pos);
    }
    /**
     * Projects a given vector on the surface of a unit sphere (or possible above the surface)
     * and returns its coordinates on screen in pixels.
     */
    _projectSurfacePointToScreen(pos) {
        const projected = symbol_layout.createVec4f64();
        symbol_layout.transformMat4(projected, [...pos, 1], this._globeViewProjMatrixNoCorrection);
        projected[0] /= projected[3];
        projected[1] /= projected[3];
        return new symbol_layout.Point((projected[0] * 0.5 + 0.5) * this.width, (-projected[1] * 0.5 + 0.5) * this.height);
    }
    screenPointToMercatorCoordinate(p, terrain) {
        if (terrain) {
            // Mercator has terrain handling implemented properly and since terrain
            // simply draws tile coordinates into a special framebuffer, this works well even for globe.
            const coordinate = terrain.pointCoordinate(p);
            if (coordinate) {
                return coordinate;
            }
        }
        return symbol_layout.MercatorCoordinate.fromLngLat(this.unprojectScreenPoint(p));
    }
    screenPointToLocation(p, terrain) {
        var _a;
        return (_a = this.screenPointToMercatorCoordinate(p, terrain)) === null || _a === void 0 ? void 0 : _a.toLngLat();
    }
    isPointOnMapSurface(p, _terrain) {
        const rayOrigin = this._cameraPosition;
        const rayDirection = this.getRayDirectionFromPixel(p);
        const intersection = this.rayPlanetIntersection(rayOrigin, rayDirection);
        return !!intersection;
    }
    /**
     * Computes normalized direction of a ray from the camera to the given screen pixel.
     */
    getRayDirectionFromPixel(p) {
        const pos = symbol_layout.createVec4f64();
        pos[0] = (p.x / this.width) * 2.0 - 1.0;
        pos[1] = ((p.y / this.height) * 2.0 - 1.0) * -1.0;
        pos[2] = 1;
        pos[3] = 1;
        symbol_layout.transformMat4(pos, pos, this._globeViewProjMatrixNoCorrectionInverted);
        pos[0] /= pos[3];
        pos[1] /= pos[3];
        pos[2] /= pos[3];
        const ray = symbol_layout.createVec3f64();
        ray[0] = pos[0] - this._cameraPosition[0];
        ray[1] = pos[1] - this._cameraPosition[1];
        ray[2] = pos[2] - this._cameraPosition[2];
        const rayNormalized = symbol_layout.createVec3f64();
        symbol_layout.normalize(rayNormalized, ray);
        return rayNormalized;
    }
    /**
     * For a given point on the unit sphere of the planet, returns whether it is visible from
     * camera's position (not taking into account camera rotation at all).
     */
    isSurfacePointVisible(p) {
        const plane = this._cachedClippingPlane;
        // dot(position on sphere, occlusion plane equation)
        const dotResult = plane[0] * p[0] + plane[1] * p[1] + plane[2] * p[2] + plane[3];
        return dotResult >= 0.0;
    }
    /**
     * Returns whether surface point is visible on screen.
     * It must both project to a pixel in screen bounds and not be occluded by the planet.
     */
    isSurfacePointOnScreen(vec) {
        if (!this.isSurfacePointVisible(vec)) {
            return false;
        }
        const projected = symbol_layout.createVec4f64();
        symbol_layout.transformMat4(projected, [...vec, 1], this._globeViewProjMatrixNoCorrection);
        projected[0] /= projected[3];
        projected[1] /= projected[3];
        projected[2] /= projected[3];
        return projected[0] > -1 && projected[0] < 1 &&
            projected[1] > -1 && projected[1] < 1 &&
            projected[2] > -1 && projected[2] < 1;
    }
    /**
     * Returns the two intersection points of the ray and the planet's sphere,
     * or null if no intersection occurs.
     * The intersections are encoded as the parameter for parametric ray equation,
     * with `tMin` being the first intersection and `tMax` being the second.
     * Eg. the nearer intersection point can then be computed as `origin + direction * tMin`.
     * @param origin - The ray origin.
     * @param direction - The normalized ray direction.
     */
    rayPlanetIntersection(origin, direction) {
        const originDotDirection = symbol_layout.dot(origin, direction);
        const planetRadiusSquared = 1.0; // planet is a unit sphere, so its radius squared is 1
        // Ray-sphere intersection involves a quadratic equation.
        // However solving it in the traditional schoolbook way leads to floating point precision issues.
        // Here we instead use the approach suggested in the book Ray Tracing Gems, chapter 7.
        // https://www.realtimerendering.com/raytracinggems/rtg/index.html
        const inner = symbol_layout.createVec3f64();
        const scaledDir = symbol_layout.createVec3f64();
        symbol_layout.scale$2(scaledDir, direction, originDotDirection);
        symbol_layout.sub(inner, origin, scaledDir);
        const discriminant = planetRadiusSquared - symbol_layout.dot(inner, inner);
        if (discriminant < 0) {
            return null;
        }
        const c = symbol_layout.dot(origin, origin) - planetRadiusSquared;
        const q = -originDotDirection + (originDotDirection < 0 ? 1 : -1) * Math.sqrt(discriminant);
        const t0 = c / q;
        const t1 = q;
        // Assume the ray origin is never inside the sphere
        const tMin = Math.min(t0, t1);
        const tMax = Math.max(t0, t1);
        return {
            tMin,
            tMax
        };
    }
    /**
     * @internal
     * Returns a {@link LngLat} representing geographical coordinates that correspond to the specified pixel coordinates.
     * Note: if the point does not lie on the globe, returns a location on the visible globe horizon (edge) that is
     * as close to the point as possible.
     * @param p - Screen point in pixels to unproject.
     * @param terrain - Optional terrain.
     */
    unprojectScreenPoint(p) {
        // Here we compute the intersection of the ray towards the pixel at `p` and the planet sphere.
        // As always, we assume that the planet is centered at 0,0,0 and has radius 1.
        // Ray origin is `_cameraPosition` and direction is `rayNormalized`.
        const rayOrigin = this._cameraPosition;
        const rayDirection = this.getRayDirectionFromPixel(p);
        const intersection = this.rayPlanetIntersection(rayOrigin, rayDirection);
        if (intersection) {
            // Ray intersects the sphere -> compute intersection LngLat.
            // Assume the ray origin is never inside the sphere - just use tMin
            const intersectionPoint = symbol_layout.createVec3f64();
            symbol_layout.add(intersectionPoint, rayOrigin, [
                rayDirection[0] * intersection.tMin,
                rayDirection[1] * intersection.tMin,
                rayDirection[2] * intersection.tMin
            ]);
            const sphereSurface = symbol_layout.createVec3f64();
            symbol_layout.normalize(sphereSurface, intersectionPoint);
            return sphereSurfacePointToCoordinates(sphereSurface);
        }
        // Ray does not intersect the sphere -> find the closest point on the horizon to the ray.
        // Intersect the ray with the clipping plane, since we know that the intersection of the clipping plane and the sphere is the horizon.
        const horizonPlane = this._cachedClippingPlane;
        const directionDotPlaneXyz = horizonPlane[0] * rayDirection[0] + horizonPlane[1] * rayDirection[1] + horizonPlane[2] * rayDirection[2];
        const originToPlaneDistance = symbol_layout.pointPlaneSignedDistance(horizonPlane, rayOrigin);
        const distanceToIntersection = -originToPlaneDistance / directionDotPlaneXyz;
        const maxRayLength = 2.0; // One globe diameter
        const planeIntersection = symbol_layout.createVec3f64();
        if (distanceToIntersection > 0) {
            symbol_layout.add(planeIntersection, rayOrigin, [
                rayDirection[0] * distanceToIntersection,
                rayDirection[1] * distanceToIntersection,
                rayDirection[2] * distanceToIntersection
            ]);
        }
        else {
            // When the ray takes too long to hit the plane (>maxRayLength), or if the plane intersection is behind the camera, handle things differently.
            // Take a point along the ray at distance maxRayLength, project it to clipping plane, then continue as normal to find the horizon point.
            const distantPoint = symbol_layout.createVec3f64();
            symbol_layout.add(distantPoint, rayOrigin, [
                rayDirection[0] * maxRayLength,
                rayDirection[1] * maxRayLength,
                rayDirection[2] * maxRayLength
            ]);
            const distanceFromPlane = symbol_layout.pointPlaneSignedDistance(this._cachedClippingPlane, distantPoint);
            symbol_layout.sub(planeIntersection, distantPoint, [
                this._cachedClippingPlane[0] * distanceFromPlane,
                this._cachedClippingPlane[1] * distanceFromPlane,
                this._cachedClippingPlane[2] * distanceFromPlane
            ]);
        }
        const horizonDisk = horizonPlaneToCenterAndRadius(horizonPlane);
        const closestOnHorizon = clampToSphere(horizonDisk.center, horizonDisk.radius, planeIntersection);
        return sphereSurfacePointToCoordinates(closestOnHorizon);
    }
    getMatrixForModel(location, altitude) {
        const lnglat = symbol_layout.LngLat.convert(location);
        const scale = 1.0 / symbol_layout.earthRadius;
        const m = symbol_layout.createIdentityMat4f64();
        symbol_layout.rotateY$1(m, m, lnglat.lng / 180.0 * Math.PI);
        symbol_layout.rotateX(m, m, -lnglat.lat / 180.0 * Math.PI);
        symbol_layout.translate(m, m, [0, 0, 1 + altitude / symbol_layout.earthRadius]);
        symbol_layout.rotateX(m, m, Math.PI * 0.5);
        symbol_layout.scale(m, m, [scale, scale, scale]);
        return m;
    }
    getProjectionDataForCustomLayer(applyGlobeMatrix = true) {
        const globeData = this.getProjectionData({ overscaledTileID: new symbol_layout.OverscaledTileID(0, 0, 0, 0, 0), applyGlobeMatrix });
        globeData.tileMercatorCoords = [0, 0, 1, 1];
        return globeData;
    }
    getFastPathSimpleProjectionMatrix(_tileID) {
        return undefined;
    }
}

/**
 * Globe transform is a transform that moves between vertical perspective and mercator projections.
 */
class GlobeTransform {
    //
    // Implementation of transform getters and setters
    //
    get pixelsToClipSpaceMatrix() {
        return this._helper.pixelsToClipSpaceMatrix;
    }
    get clipSpaceToPixelsMatrix() {
        return this._helper.clipSpaceToPixelsMatrix;
    }
    get pixelsToGLUnits() {
        return this._helper.pixelsToGLUnits;
    }
    get centerOffset() {
        return this._helper.centerOffset;
    }
    get size() {
        return this._helper.size;
    }
    get rotationMatrix() {
        return this._helper.rotationMatrix;
    }
    get centerPoint() {
        return this._helper.centerPoint;
    }
    get pixelsPerMeter() {
        return this._helper.pixelsPerMeter;
    }
    setMinZoom(zoom) {
        this._helper.setMinZoom(zoom);
    }
    setMaxZoom(zoom) {
        this._helper.setMaxZoom(zoom);
    }
    setMinPitch(pitch) {
        this._helper.setMinPitch(pitch);
    }
    setMaxPitch(pitch) {
        this._helper.setMaxPitch(pitch);
    }
    setRenderWorldCopies(renderWorldCopies) {
        this._helper.setRenderWorldCopies(renderWorldCopies);
    }
    setBearing(bearing) {
        this._helper.setBearing(bearing);
    }
    setPitch(pitch) {
        this._helper.setPitch(pitch);
    }
    setRoll(roll) {
        this._helper.setRoll(roll);
    }
    setFov(fov) {
        this._helper.setFov(fov);
    }
    setZoom(zoom) {
        this._helper.setZoom(zoom);
    }
    setCenter(center) {
        this._helper.setCenter(center);
    }
    setElevation(elevation) {
        this._helper.setElevation(elevation);
    }
    setMinElevationForCurrentTile(elevation) {
        this._helper.setMinElevationForCurrentTile(elevation);
    }
    setPadding(padding) {
        this._helper.setPadding(padding);
    }
    interpolatePadding(start, target, t) {
        this._helper.interpolatePadding(start, target, t);
    }
    isPaddingEqual(padding) {
        return this._helper.isPaddingEqual(padding);
    }
    resize(width, height, constrainTransform = true) {
        this._helper.resize(width, height, constrainTransform);
    }
    getMaxBounds() {
        return this._helper.getMaxBounds();
    }
    setMaxBounds(bounds) {
        this._helper.setMaxBounds(bounds);
    }
    setConstrainOverride(constrain) {
        this._helper.setConstrainOverride(constrain);
    }
    overrideNearFarZ(nearZ, farZ) {
        this._helper.overrideNearFarZ(nearZ, farZ);
    }
    clearNearFarZOverride() {
        this._helper.clearNearFarZOverride();
    }
    getCameraQueryGeometry(queryGeometry) {
        return this._helper.getCameraQueryGeometry(this.getCameraPoint(), queryGeometry);
    }
    get tileSize() {
        return this._helper.tileSize;
    }
    get tileZoom() {
        return this._helper.tileZoom;
    }
    get scale() {
        return this._helper.scale;
    }
    get worldSize() {
        return this._helper.worldSize;
    }
    get width() {
        return this._helper.width;
    }
    get height() {
        return this._helper.height;
    }
    get lngRange() {
        return this._helper.lngRange;
    }
    get latRange() {
        return this._helper.latRange;
    }
    get minZoom() {
        return this._helper.minZoom;
    }
    get maxZoom() {
        return this._helper.maxZoom;
    }
    get zoom() {
        return this._helper.zoom;
    }
    get center() {
        return this._helper.center;
    }
    get minPitch() {
        return this._helper.minPitch;
    }
    get maxPitch() {
        return this._helper.maxPitch;
    }
    get pitch() {
        return this._helper.pitch;
    }
    get pitchInRadians() {
        return this._helper.pitchInRadians;
    }
    get roll() {
        return this._helper.roll;
    }
    get rollInRadians() {
        return this._helper.rollInRadians;
    }
    get bearing() {
        return this._helper.bearing;
    }
    get bearingInRadians() {
        return this._helper.bearingInRadians;
    }
    get fov() {
        return this._helper.fov;
    }
    get fovInRadians() {
        return this._helper.fovInRadians;
    }
    get elevation() {
        return this._helper.elevation;
    }
    get minElevationForCurrentTile() {
        return this._helper.minElevationForCurrentTile;
    }
    get padding() {
        return this._helper.padding;
    }
    get unmodified() {
        return this._helper.unmodified;
    }
    get renderWorldCopies() {
        return this._helper.renderWorldCopies;
    }
    get cameraToCenterDistance() {
        return this._helper.cameraToCenterDistance;
    }
    get constrainOverride() {
        return this._helper.constrainOverride;
    }
    get nearZ() {
        return this._helper.nearZ;
    }
    get farZ() {
        return this._helper.farZ;
    }
    get autoCalculateNearFarZ() {
        return this._helper.autoCalculateNearFarZ;
    }
    /**
     * True when globe render path should be used instead of the old but simpler mercator rendering.
     * Globe automatically transitions to mercator at high zoom levels, which causes a switch from
     * globe to mercator render path.
     */
    get isGlobeRendering() {
        return this._globeness > 0;
    }
    setTransitionState(globeness, errorCorrectionValue) {
        this._globeness = globeness;
        this._globeLatitudeErrorCorrectionRadians = errorCorrectionValue;
        this._calcMatrices();
        this._verticalPerspectiveTransform.getCoveringTilesDetailsProvider().prepareNextFrame();
        this._mercatorTransform.getCoveringTilesDetailsProvider().prepareNextFrame();
    }
    get currentTransform() {
        return this.isGlobeRendering ? this._verticalPerspectiveTransform : this._mercatorTransform;
    }
    constructor(options) {
        //
        // Implementation of globe transform
        //
        this._globeLatitudeErrorCorrectionRadians = 0;
        /**
         * Globe projection can smoothly interpolate between globe view and mercator. This variable controls this interpolation.
         * Value 0 is mercator, value 1 is globe, anything between is an interpolation between the two projections.
         */
        this._globeness = 1.0;
        this.defaultConstrain = (lngLat, zoom) => {
            return this.currentTransform.defaultConstrain(lngLat, zoom);
        };
        this.applyConstrain = (lngLat, zoom) => {
            return this._helper.applyConstrain(lngLat, zoom);
        };
        this._helper = new TransformHelper({
            calcMatrices: () => this._calcMatrices(),
            defaultConstrain: (center, zoom) => { return this.defaultConstrain(center, zoom); }
        }, options);
        this._globeness = 1; // When transform is cloned for use in symbols, `_updateAnimation` function which usually sets this value never gets called.
        this._mercatorTransform = new MercatorTransform();
        this._verticalPerspectiveTransform = new VerticalPerspectiveTransform();
    }
    clone() {
        const clone = new GlobeTransform();
        clone._globeness = this._globeness;
        clone._globeLatitudeErrorCorrectionRadians = this._globeLatitudeErrorCorrectionRadians;
        clone.apply(this, false);
        return clone;
    }
    apply(that, constrain) {
        this._helper.apply(that, constrain);
        this._mercatorTransform.apply(this, false);
        this._verticalPerspectiveTransform.apply(this, false, this._globeLatitudeErrorCorrectionRadians);
    }
    get projectionMatrix() { return this.currentTransform.projectionMatrix; }
    get modelViewProjectionMatrix() { return this.currentTransform.modelViewProjectionMatrix; }
    get inverseProjectionMatrix() { return this.currentTransform.inverseProjectionMatrix; }
    get cameraPosition() { return this.currentTransform.cameraPosition; }
    getProjectionData(params) {
        const mercatorProjectionData = this._mercatorTransform.getProjectionData(params);
        const verticalPerspectiveProjectionData = this._verticalPerspectiveTransform.getProjectionData(params);
        return {
            mainMatrix: this.isGlobeRendering ? verticalPerspectiveProjectionData.mainMatrix : mercatorProjectionData.mainMatrix,
            clippingPlane: verticalPerspectiveProjectionData.clippingPlane,
            tileMercatorCoords: verticalPerspectiveProjectionData.tileMercatorCoords,
            projectionTransition: params.applyGlobeMatrix ? this._globeness : 0,
            fallbackMatrix: mercatorProjectionData.fallbackMatrix,
        };
    }
    isLocationOccluded(location) {
        return this.currentTransform.isLocationOccluded(location);
    }
    transformLightDirection(dir) {
        return this.currentTransform.transformLightDirection(dir);
    }
    getPixelScale() {
        return symbol_layout.lerp(this._mercatorTransform.getPixelScale(), this._verticalPerspectiveTransform.getPixelScale(), this._globeness);
    }
    getCircleRadiusCorrection() {
        return symbol_layout.lerp(this._mercatorTransform.getCircleRadiusCorrection(), this._verticalPerspectiveTransform.getCircleRadiusCorrection(), this._globeness);
    }
    getPitchedTextCorrection(textAnchorX, textAnchorY, tileID) {
        const mercatorCorrection = this._mercatorTransform.getPitchedTextCorrection(textAnchorX, textAnchorY, tileID);
        const verticalCorrection = this._verticalPerspectiveTransform.getPitchedTextCorrection(textAnchorX, textAnchorY, tileID);
        return symbol_layout.lerp(mercatorCorrection, verticalCorrection, this._globeness);
    }
    projectTileCoordinates(x, y, unwrappedTileID, getElevation) {
        return this.currentTransform.projectTileCoordinates(x, y, unwrappedTileID, getElevation);
    }
    _calcMatrices() {
        if (!this._helper._width || !this._helper._height) {
            return;
        }
        // VerticalPerspective reads our near/farZ values and autoCalculateNearFarZ:
        // - if autoCalculateNearFarZ is true then it computes globe Z values
        // - if autoCalculateNearFarZ is false then it inherits our Z values
        // In either case, its Z values are consistent with out settings and we want to copy its Z values to our helper.
        this._verticalPerspectiveTransform.apply(this, false, this._globeLatitudeErrorCorrectionRadians);
        this._helper._nearZ = this._verticalPerspectiveTransform.nearZ;
        this._helper._farZ = this._verticalPerspectiveTransform.farZ;
        // When transitioning between globe and mercator, we need to synchronize the depth values in both transforms.
        // For this reason we first update vertical perspective and then sync our Z values to its result.
        // Now if globe rendering, we always want to force mercator transform to adapt our Z values.
        // If not, it will either compute its own (autoCalculateNearFarZ=false) or adapt our (autoCalculateNearFarZ=true).
        // In either case we want to (again) sync our Z values, this time with
        this._mercatorTransform.apply(this, true, this.isGlobeRendering);
        this._helper._nearZ = this._mercatorTransform.nearZ;
        this._helper._farZ = this._mercatorTransform.farZ;
    }
    calculateFogMatrix(unwrappedTileID) {
        return this.currentTransform.calculateFogMatrix(unwrappedTileID);
    }
    getVisibleUnwrappedCoordinates(tileID) {
        return this.currentTransform.getVisibleUnwrappedCoordinates(tileID);
    }
    getCameraFrustum() {
        return this.currentTransform.getCameraFrustum();
    }
    getClippingPlane() {
        return this.currentTransform.getClippingPlane();
    }
    getCoveringTilesDetailsProvider() {
        return this.currentTransform.getCoveringTilesDetailsProvider();
    }
    recalculateZoomAndCenter(terrain) {
        this._mercatorTransform.recalculateZoomAndCenter(terrain);
        this._verticalPerspectiveTransform.recalculateZoomAndCenter(terrain);
    }
    maxPitchScaleFactor() {
        // Using mercator version of this should be good enough approximation for globe.
        return this._mercatorTransform.maxPitchScaleFactor();
    }
    getCameraPoint() {
        return this._helper.getCameraPoint();
    }
    getCameraAltitude() {
        return this._helper.getCameraAltitude();
    }
    getCameraLngLat() {
        return this._helper.getCameraLngLat();
    }
    lngLatToCameraDepth(lngLat, elevation) {
        return this.currentTransform.lngLatToCameraDepth(lngLat, elevation);
    }
    populateCache(coords) {
        this._mercatorTransform.populateCache(coords);
        this._verticalPerspectiveTransform.populateCache(coords);
    }
    getBounds() {
        return this.currentTransform.getBounds();
    }
    calculateCenterFromCameraLngLatAlt(lngLat, alt, bearing, pitch) {
        return this._helper.calculateCenterFromCameraLngLatAlt(lngLat, alt, bearing, pitch);
    }
    /**
     * Note: automatically adjusts zoom to keep planet size consistent
     * (same size before and after a {@link setLocationAtPoint} call).
     */
    setLocationAtPoint(lnglat, point) {
        if (!this.isGlobeRendering) {
            this._mercatorTransform.setLocationAtPoint(lnglat, point);
            this.apply(this._mercatorTransform, false);
            return;
        }
        this._verticalPerspectiveTransform.setLocationAtPoint(lnglat, point);
        this.apply(this._verticalPerspectiveTransform, false);
        return;
    }
    locationToScreenPoint(lnglat, terrain) {
        return this.currentTransform.locationToScreenPoint(lnglat, terrain);
    }
    screenPointToMercatorCoordinate(p, terrain) {
        return this.currentTransform.screenPointToMercatorCoordinate(p, terrain);
    }
    screenPointToLocation(p, terrain) {
        return this.currentTransform.screenPointToLocation(p, terrain);
    }
    isPointOnMapSurface(p, terrain) {
        return this.currentTransform.isPointOnMapSurface(p, terrain);
    }
    /**
     * Computes normalized direction of a ray from the camera to the given screen pixel.
     */
    getRayDirectionFromPixel(p) {
        return this._verticalPerspectiveTransform.getRayDirectionFromPixel(p);
    }
    getMatrixForModel(location, altitude) {
        return this.currentTransform.getMatrixForModel(location, altitude);
    }
    getProjectionDataForCustomLayer(applyGlobeMatrix = true) {
        const mercatorData = this._mercatorTransform.getProjectionDataForCustomLayer(applyGlobeMatrix);
        if (!this.isGlobeRendering) {
            return mercatorData;
        }
        const globeData = this._verticalPerspectiveTransform.getProjectionDataForCustomLayer(applyGlobeMatrix);
        globeData.fallbackMatrix = mercatorData.mainMatrix;
        return globeData;
    }
    getFastPathSimpleProjectionMatrix(tileID) {
        return this.currentTransform.getFastPathSimpleProjectionMatrix(tileID);
    }
}

/**
 * @internal
 */
class VerticalPerspectiveCameraHelper {
    get useGlobeControls() { return true; }
    handlePanInertia(pan, transform) {
        const panCenter = computeGlobePanCenter(pan, transform);
        if (Math.abs(panCenter.lng - transform.center.lng) > 180) {
            // If easeTo target would be over 180° distant, the animation would move
            // in the opposite direction that what the user intended.
            // Thus we clamp the movement to 179.5°.
            panCenter.lng = transform.center.lng + 179.5 * Math.sign(panCenter.lng - transform.center.lng);
        }
        return {
            easingCenter: panCenter,
            easingOffset: new symbol_layout.Point(0, 0),
        };
    }
    handleMapControlsRollPitchBearingZoom(deltas, tr) {
        const zoomPixel = deltas.around;
        const zoomLoc = tr.screenPointToLocation(zoomPixel);
        if (deltas.bearingDelta)
            tr.setBearing(tr.bearing + deltas.bearingDelta);
        if (deltas.pitchDelta)
            tr.setPitch(tr.pitch + deltas.pitchDelta);
        if (deltas.rollDelta)
            tr.setRoll(tr.roll + deltas.rollDelta);
        const oldZoomPreZoomDelta = tr.zoom;
        if (deltas.zoomDelta)
            tr.setZoom(tr.zoom + deltas.zoomDelta);
        const actualZoomDelta = tr.zoom - oldZoomPreZoomDelta;
        if (actualZoomDelta === 0) {
            return;
        }
        // Problem: `setLocationAtPoint` for globe works when it is called a single time, but is a little glitchy in practice when used repeatedly for zooming.
        // - `setLocationAtPoint` repeatedly called at a location behind a pole will eventually glitch out
        // - `setLocationAtPoint` at location the longitude of which is more than 90° different from current center will eventually glitch out
        // But otherwise works fine at higher zooms, or when the target is somewhat near the current map center.
        // Solution: use a heuristic zooming in the problematic cases and interpolate to `setLocationAtPoint` when possible.
        // Magic numbers that control:
        // - when zoom movement slowing starts for cursor not on globe (avoid unnatural map movements)
        // - when we interpolate from exact zooming to heuristic zooming based on longitude difference of target location to current center
        // - when we interpolate from exact zooming to heuristic zooming based on globe being too small on screen
        // - when zoom movement slowing starts for globe being too small on viewport (avoids unnatural/unwanted map movements when map is zoomed out a lot)
        const raySurfaceDistanceForSlowingStart = 0.3; // Zoom movement slowing will start when the planet surface to ray distance is greater than this number (globe radius is 1, so 0.3 is ~2000km form the surface).
        const slowingMultiplier = 0.5; // The lower this value, the slower will the "zoom movement slowing" occur.
        const interpolateToHeuristicStartLng = 45; // When zoom location longitude is this many degrees away from map center, we start interpolating from exact zooming to heuristic zooming.
        const interpolateToHeuristicEndLng = 85; // Longitude difference at which interpolation to heuristic zooming ends.
        const interpolateToHeuristicExponent = 0.25; // Makes interpolation smoother.
        const interpolateToHeuristicStartRadius = 0.75; // When globe is this many times larger than the smaller viewport dimension, we start interpolating from exact zooming to heuristic zooming.
        const interpolateToHeuristicEndRadius = 0.35; // Globe size at which interpolation to heuristic zooming ends.
        const slowingRadiusStart = 0.9; // If globe is this many times larger than the smaller viewport dimension, start inhibiting map movement while zooming
        const slowingRadiusStop = 0.5;
        const slowingRadiusSlowFactor = 0.25; // How much is movement slowed when globe is too small
        const dLngRaw = symbol_layout.differenceOfAnglesDegrees(tr.center.lng, zoomLoc.lng);
        const dLng = dLngRaw / (Math.abs(dLngRaw / 180) + 1.0); // This gradually reduces the amount of longitude change if the zoom location is very far, eg. on the other side of the pole (possible when looking at a pole).
        const dLat = symbol_layout.differenceOfAnglesDegrees(tr.center.lat, zoomLoc.lat);
        // Slow zoom movement down if the mouse ray is far from the planet.
        const rayDirection = tr.getRayDirectionFromPixel(zoomPixel);
        const rayOrigin = tr.cameraPosition;
        const distanceToClosestPoint = symbol_layout.dot(rayOrigin, rayDirection) * -1; // Globe center relative to ray origin is equal to -rayOrigin and rayDirection is normalized, thus we want to compute dot(-rayOrigin, rayDirection).
        const closestPoint = symbol_layout.createVec3f64();
        symbol_layout.add(closestPoint, rayOrigin, [
            rayDirection[0] * distanceToClosestPoint,
            rayDirection[1] * distanceToClosestPoint,
            rayDirection[2] * distanceToClosestPoint
        ]);
        const distanceFromSurface = symbol_layout.length$1(closestPoint) - 1;
        const distanceFactor = Math.exp(-Math.max(distanceFromSurface - raySurfaceDistanceForSlowingStart, 0) * slowingMultiplier);
        // Slow zoom movement down if the globe is too small on viewport
        const radius = getGlobeRadiusPixels(tr.worldSize, tr.center.lat) / Math.min(tr.width, tr.height); // Radius relative to larger viewport dimension
        const radiusFactor = symbol_layout.remapSaturate(radius, slowingRadiusStart, slowingRadiusStop, 1.0, slowingRadiusSlowFactor);
        // Compute how much to move towards the zoom location
        const factor = (1.0 - symbol_layout.zoomScale(-actualZoomDelta)) * Math.min(distanceFactor, radiusFactor);
        const oldCenterLat = tr.center.lat;
        const oldZoom = tr.zoom;
        const heuristicCenter = new symbol_layout.LngLat(tr.center.lng + dLng * factor, symbol_layout.clamp(tr.center.lat + dLat * factor, -symbol_layout.MAX_VALID_LATITUDE, symbol_layout.MAX_VALID_LATITUDE));
        // Now compute the map center exact zoom
        tr.setLocationAtPoint(zoomLoc, zoomPixel);
        const exactCenter = tr.center;
        // Interpolate between exact zooming and heuristic zooming depending on the longitude difference between current center and zoom location.
        const interpolationFactorLongitude = symbol_layout.remapSaturate(Math.abs(dLngRaw), interpolateToHeuristicStartLng, interpolateToHeuristicEndLng, 0, 1);
        const interpolationFactorRadius = symbol_layout.remapSaturate(radius, interpolateToHeuristicStartRadius, interpolateToHeuristicEndRadius, 0, 1);
        const heuristicFactor = Math.pow(Math.max(interpolationFactorLongitude, interpolationFactorRadius), interpolateToHeuristicExponent);
        const lngExactToHeuristic = symbol_layout.differenceOfAnglesDegrees(exactCenter.lng, heuristicCenter.lng);
        const latExactToHeuristic = symbol_layout.differenceOfAnglesDegrees(exactCenter.lat, heuristicCenter.lat);
        tr.setCenter(new symbol_layout.LngLat(exactCenter.lng + lngExactToHeuristic * heuristicFactor, exactCenter.lat + latExactToHeuristic * heuristicFactor).wrap());
        tr.setZoom(oldZoom + getZoomAdjustment(oldCenterLat, tr.center.lat));
    }
    handleMapControlsPan(deltas, tr, _preZoomAroundLoc) {
        if (!deltas.panDelta) {
            return;
        }
        // These are actually very similar to mercator controls, and should converge to them at high zooms.
        // We avoid using the "grab a place and move it around" approach from mercator here,
        // since it is not a very pleasant way to pan a globe.
        const oldLat = tr.center.lat;
        const oldZoom = tr.zoom;
        tr.setCenter(computeGlobePanCenter(deltas.panDelta, tr).wrap());
        // Setting the center might adjust zoom to keep globe size constant, we need to avoid adding this adjustment a second time
        tr.setZoom(oldZoom + getZoomAdjustment(oldLat, tr.center.lat));
    }
    cameraForBoxAndBearing(options, padding, bounds, bearing, tr) {
        const result = cameraForBoxAndBearing(options, padding, bounds, bearing, tr);
        // If globe is enabled, we use the parameters computed for mercator, and just update the zoom to fit the bounds.
        // Get clip space bounds including padding
        const xLeft = (padding.left) / tr.width * 2.0 - 1.0;
        const xRight = (tr.width - padding.right) / tr.width * 2.0 - 1.0;
        const yTop = (padding.top) / tr.height * -2.0 + 1.0;
        const yBottom = (tr.height - padding.bottom) / tr.height * -2.0 + 1.0;
        // Get camera bounds
        const flipEastWest = symbol_layout.differenceOfAnglesDegrees(bounds.getWest(), bounds.getEast()) < 0;
        const lngWest = flipEastWest ? bounds.getEast() : bounds.getWest();
        const lngEast = flipEastWest ? bounds.getWest() : bounds.getEast();
        const latNorth = Math.max(bounds.getNorth(), bounds.getSouth()); // "getNorth" doesn't always return north...
        const latSouth = Math.min(bounds.getNorth(), bounds.getSouth());
        // Additional vectors will be tested for the rectangle midpoints
        const lngMid = lngWest + symbol_layout.differenceOfAnglesDegrees(lngWest, lngEast) * 0.5;
        const latMid = latNorth + symbol_layout.differenceOfAnglesDegrees(latNorth, latSouth) * 0.5;
        // Obtain a globe projection matrix that does not include pitch (unsupported)
        const clonedTr = tr.clone();
        clonedTr.setCenter(result.center);
        clonedTr.setBearing(result.bearing);
        clonedTr.setPitch(0);
        clonedTr.setRoll(0);
        clonedTr.setZoom(result.zoom);
        const matrix = clonedTr.modelViewProjectionMatrix;
        // Vectors to test - the bounds' corners and edge midpoints
        const testVectors = [
            angularCoordinatesToSurfaceVector(bounds.getNorthWest()),
            angularCoordinatesToSurfaceVector(bounds.getNorthEast()),
            angularCoordinatesToSurfaceVector(bounds.getSouthWest()),
            angularCoordinatesToSurfaceVector(bounds.getSouthEast()),
            // Also test edge midpoints
            angularCoordinatesToSurfaceVector(new symbol_layout.LngLat(lngEast, latMid)),
            angularCoordinatesToSurfaceVector(new symbol_layout.LngLat(lngWest, latMid)),
            angularCoordinatesToSurfaceVector(new symbol_layout.LngLat(lngMid, latNorth)),
            angularCoordinatesToSurfaceVector(new symbol_layout.LngLat(lngMid, latSouth))
        ];
        const vecToCenter = angularCoordinatesToSurfaceVector(result.center);
        // Test each vector, measure how much to scale down the globe to satisfy all tested points that they are inside clip space.
        let smallestNeededScale = Number.POSITIVE_INFINITY;
        for (const vec of testVectors) {
            if (xLeft < 0)
                smallestNeededScale = VerticalPerspectiveCameraHelper.getLesserNonNegativeNonNull(smallestNeededScale, VerticalPerspectiveCameraHelper.solveVectorScale(vec, vecToCenter, matrix, 'x', xLeft));
            if (xRight > 0)
                smallestNeededScale = VerticalPerspectiveCameraHelper.getLesserNonNegativeNonNull(smallestNeededScale, VerticalPerspectiveCameraHelper.solveVectorScale(vec, vecToCenter, matrix, 'x', xRight));
            if (yTop > 0)
                smallestNeededScale = VerticalPerspectiveCameraHelper.getLesserNonNegativeNonNull(smallestNeededScale, VerticalPerspectiveCameraHelper.solveVectorScale(vec, vecToCenter, matrix, 'y', yTop));
            if (yBottom < 0)
                smallestNeededScale = VerticalPerspectiveCameraHelper.getLesserNonNegativeNonNull(smallestNeededScale, VerticalPerspectiveCameraHelper.solveVectorScale(vec, vecToCenter, matrix, 'y', yBottom));
        }
        if (!Number.isFinite(smallestNeededScale) || smallestNeededScale === 0) {
            cameraBoundsWarning();
            return undefined;
        }
        // Compute target zoom from the obtained scale.
        result.zoom = Math.min(clonedTr.zoom + symbol_layout.scaleZoom(smallestNeededScale), options.maxZoom);
        return result;
    }
    /**
     * Handles the zoom and center change during camera jumpTo.
     */
    handleJumpToCenterZoom(tr, options) {
        // Special zoom & center handling for globe:
        // Globe constrained center isn't dependent on zoom level
        const startingLat = tr.center.lat;
        const constrainedCenter = tr.applyConstrain(options.center ? symbol_layout.LngLat.convert(options.center) : tr.center, tr.zoom).center;
        tr.setCenter(constrainedCenter.wrap());
        // Make sure to compute correct target zoom level if no zoom is specified
        const targetZoom = (typeof options.zoom !== 'undefined') ? +options.zoom : (tr.zoom + getZoomAdjustment(startingLat, constrainedCenter.lat));
        if (tr.zoom !== targetZoom) {
            tr.setZoom(targetZoom);
        }
    }
    handleEaseTo(tr, options) {
        const startZoom = tr.zoom;
        const startCenter = tr.center;
        const startPadding = tr.padding;
        const startEulerAngles = { roll: tr.roll, pitch: tr.pitch, bearing: tr.bearing };
        const endRoll = options.roll === undefined ? tr.roll : options.roll;
        const endPitch = options.pitch === undefined ? tr.pitch : options.pitch;
        const endBearing = options.bearing === undefined ? tr.bearing : options.bearing;
        const endEulerAngles = { roll: endRoll, pitch: endPitch, bearing: endBearing };
        const optionsZoom = typeof options.zoom !== 'undefined';
        const doPadding = !tr.isPaddingEqual(options.padding);
        let isZooming = false;
        // Globe needs special handling for how zoom should be animated.
        // 1) if zoom is set, ease to the given mercator zoom
        // 2) if neither is set, assume constant apparent zoom (constant planet size) is to be kept
        const preConstrainCenter = options.center ?
            symbol_layout.LngLat.convert(options.center) :
            startCenter;
        const constrainedCenter = tr.applyConstrain(preConstrainCenter, startZoom // zoom can be whatever at this stage, it should not affect anything if globe is enabled
        ).center;
        normalizeCenter(tr, constrainedCenter);
        const clonedTr = tr.clone();
        clonedTr.setCenter(constrainedCenter);
        clonedTr.setZoom(optionsZoom ?
            +options.zoom :
            startZoom + getZoomAdjustment(startCenter.lat, preConstrainCenter.lat));
        clonedTr.setBearing(options.bearing);
        const clampedPoint = new symbol_layout.Point(symbol_layout.clamp(tr.centerPoint.x + options.offsetAsPoint.x, 0, tr.width), symbol_layout.clamp(tr.centerPoint.y + options.offsetAsPoint.y, 0, tr.height));
        clonedTr.setLocationAtPoint(constrainedCenter, clampedPoint);
        // Find final animation targets
        const endCenterWithShift = (options.offset && options.offsetAsPoint.mag()) > 0 ? clonedTr.center : constrainedCenter;
        const endZoomWithShift = optionsZoom ?
            +options.zoom :
            startZoom + getZoomAdjustment(startCenter.lat, endCenterWithShift.lat);
        // Planet radius for a given zoom level differs according to latitude
        // Convert zooms to what they would be at equator for the given planet radius
        const normalizedStartZoom = startZoom + getZoomAdjustment(startCenter.lat, 0);
        const normalizedEndZoom = endZoomWithShift + getZoomAdjustment(endCenterWithShift.lat, 0);
        const deltaLng = symbol_layout.differenceOfAnglesDegrees(startCenter.lng, endCenterWithShift.lng);
        const deltaLat = symbol_layout.differenceOfAnglesDegrees(startCenter.lat, endCenterWithShift.lat);
        const finalScale = symbol_layout.zoomScale(normalizedEndZoom - normalizedStartZoom);
        isZooming = (endZoomWithShift !== startZoom);
        const easeFunc = (k) => {
            if (!symbol_layout.rollPitchBearingEqual(startEulerAngles, endEulerAngles)) {
                updateRotation({
                    startEulerAngles,
                    endEulerAngles,
                    tr,
                    k,
                    useSlerp: startEulerAngles.roll != endEulerAngles.roll
                });
            }
            if (doPadding) {
                tr.interpolatePadding(startPadding, options.padding, k);
            }
            if (options.around) {
                symbol_layout.warnOnce('Easing around a point is not supported under globe projection.');
                tr.setLocationAtPoint(options.around, options.aroundPoint);
            }
            else {
                const base = normalizedEndZoom > normalizedStartZoom ?
                    Math.min(2, finalScale) :
                    Math.max(0.5, finalScale);
                const speedup = Math.pow(base, 1 - k);
                const factor = k * speedup;
                // Spherical lerp might be used here instead, but that was tested and it leads to very weird paths when the interpolated arc gets near the poles.
                // Instead we interpolate LngLat almost directly, but taking into account that
                // one degree of longitude gets progressively smaller relative to latitude towards the poles.
                const newCenter = interpolateLngLatForGlobe(startCenter, deltaLng, deltaLat, factor);
                tr.setCenter(newCenter.wrap());
            }
            if (isZooming) {
                const normalizedInterpolatedZoom = symbol_layout.interpolateFactory.number(normalizedStartZoom, normalizedEndZoom, k);
                const interpolatedZoom = normalizedInterpolatedZoom + getZoomAdjustment(0, tr.center.lat);
                tr.setZoom(interpolatedZoom);
            }
        };
        return {
            easeFunc,
            isZooming,
            elevationCenter: endCenterWithShift,
        };
    }
    handleFlyTo(tr, options) {
        const optionsZoom = typeof options.zoom !== 'undefined';
        const startCenter = tr.center;
        const startZoom = tr.zoom;
        const startPadding = tr.padding;
        const doPadding = !tr.isPaddingEqual(options.padding);
        // Obtain target center and zoom
        const constrainedCenter = tr.applyConstrain(symbol_layout.LngLat.convert(options.center || options.locationAtOffset), startZoom).center;
        const targetZoom = optionsZoom ? +options.zoom : tr.zoom + getZoomAdjustment(tr.center.lat, constrainedCenter.lat);
        // Compute target center that respects offset by creating a temporary transform and calling its `setLocationAtPoint`.
        const clonedTr = tr.clone();
        clonedTr.setCenter(constrainedCenter);
        clonedTr.setZoom(targetZoom);
        clonedTr.setBearing(options.bearing);
        const clampedPoint = new symbol_layout.Point(symbol_layout.clamp(tr.centerPoint.x + options.offsetAsPoint.x, 0, tr.width), symbol_layout.clamp(tr.centerPoint.y + options.offsetAsPoint.y, 0, tr.height));
        clonedTr.setLocationAtPoint(constrainedCenter, clampedPoint);
        const targetCenter = clonedTr.center;
        normalizeCenter(tr, targetCenter);
        const pixelPathLength = globeDistanceOfLocationsPixels(tr, startCenter, targetCenter);
        const normalizedStartZoom = startZoom + getZoomAdjustment(startCenter.lat, 0);
        const normalizedTargetZoom = targetZoom + getZoomAdjustment(targetCenter.lat, 0);
        const scaleOfZoom = symbol_layout.zoomScale(normalizedTargetZoom - normalizedStartZoom);
        const optionsMinZoom = typeof options.minZoom === 'number';
        let scaleOfMinZoom;
        if (optionsMinZoom) {
            const normalizedOptionsMinZoom = +options.minZoom + getZoomAdjustment(targetCenter.lat, 0);
            const normalizedMinZoomPreConstrain = Math.min(normalizedOptionsMinZoom, normalizedStartZoom, normalizedTargetZoom);
            const minZoomPreConstrain = normalizedMinZoomPreConstrain + getZoomAdjustment(0, targetCenter.lat);
            const minZoom = tr.applyConstrain(targetCenter, minZoomPreConstrain).zoom;
            const normalizedMinZoom = minZoom + getZoomAdjustment(targetCenter.lat, 0);
            scaleOfMinZoom = symbol_layout.zoomScale(normalizedMinZoom - normalizedStartZoom);
        }
        const deltaLng = symbol_layout.differenceOfAnglesDegrees(startCenter.lng, targetCenter.lng);
        const deltaLat = symbol_layout.differenceOfAnglesDegrees(startCenter.lat, targetCenter.lat);
        const easeFunc = (k, scale, centerFactor, _pointAtOffset) => {
            const interpolatedCenter = interpolateLngLatForGlobe(startCenter, deltaLng, deltaLat, centerFactor);
            if (doPadding) {
                tr.interpolatePadding(startPadding, options.padding, k);
            }
            const newCenter = k === 1 ? targetCenter : interpolatedCenter;
            tr.setCenter(newCenter.wrap());
            const interpolatedZoom = normalizedStartZoom + symbol_layout.scaleZoom(scale);
            tr.setZoom(k === 1 ? targetZoom : (interpolatedZoom + getZoomAdjustment(0, newCenter.lat)));
        };
        return {
            easeFunc,
            scaleOfZoom,
            targetCenter,
            scaleOfMinZoom,
            pixelPathLength,
        };
    }
    /**
     * Computes how much to scale the globe in order for a given point on its surface (a location) to project to a given clip space coordinate in either the X or the Y axis.
     * @param vector - Position of the queried location on the surface of the unit sphere globe.
     * @param toCenter - Position of current transform center on the surface of the unit sphere globe.
     * This is needed because zooming the globe not only changes its scale,
     * but also moves the camera closer or further away along this vector (pitch is disregarded).
     * @param projection - The globe projection matrix.
     * @param targetDimension - The dimension in which the scaled vector must match the target value in clip space.
     * @param targetValue - The target clip space value in the specified dimension to which the queried vector must project.
     * @returns How much to scale the globe.
     */
    static solveVectorScale(vector, toCenter, projection, targetDimension, targetValue) {
        // We want to compute how much to scale the sphere in order for the input `vector` to project to `targetValue` in the given `targetDimension` (X or Y).
        const k = targetValue;
        const columnXorY = targetDimension === 'x' ?
            [projection[0], projection[4], projection[8], projection[12]] : // X
            [projection[1], projection[5], projection[9], projection[13]]; // Y
        const columnZ = [projection[3], projection[7], projection[11], projection[15]];
        const vecDotXY = vector[0] * columnXorY[0] + vector[1] * columnXorY[1] + vector[2] * columnXorY[2];
        const vecDotZ = vector[0] * columnZ[0] + vector[1] * columnZ[1] + vector[2] * columnZ[2];
        const toCenterDotXY = toCenter[0] * columnXorY[0] + toCenter[1] * columnXorY[1] + toCenter[2] * columnXorY[2];
        const toCenterDotZ = toCenter[0] * columnZ[0] + toCenter[1] * columnZ[1] + toCenter[2] * columnZ[2];
        // The following can be derived from writing down what happens to a vector scaled by a parameter ("V * t") when it is multiplied by a projection matrix, then solving for "t".
        // Or rather, we derive it for a vector "V * t + (1-t) * C". Where V is `vector` and C is `toCenter`. The extra addition is needed because zooming out also moves the camera along "C".
        const t = (toCenterDotXY + columnXorY[3] - k * toCenterDotZ - k * columnZ[3]) / (toCenterDotXY - vecDotXY - k * toCenterDotZ + k * vecDotZ);
        if (toCenterDotXY + k * vecDotZ === vecDotXY + k * toCenterDotZ ||
            columnZ[3] * (vecDotXY - toCenterDotXY) + columnXorY[3] * (toCenterDotZ - vecDotZ) + vecDotXY * toCenterDotZ === toCenterDotXY * vecDotZ) {
            // The computed result is invalid.
            return null;
        }
        return t;
    }
    /**
     * Returns `newValue` if it is:
     *
     * - not null AND
     * - not negative AND
     * - smaller than `newValue`,
     *
     * ...otherwise returns `oldValue`.
     */
    static getLesserNonNegativeNonNull(oldValue, newValue) {
        if (newValue !== null && newValue >= 0 && newValue < oldValue) {
            return newValue;
        }
        else {
            return oldValue;
        }
    }
}

/**
 * @internal
 */
class GlobeCameraHelper {
    constructor(globe) {
        this._globe = globe;
        this._mercatorCameraHelper = new MercatorCameraHelper();
        this._verticalPerspectiveCameraHelper = new VerticalPerspectiveCameraHelper();
    }
    get useGlobeControls() { return this._globe.useGlobeRendering; }
    get currentHelper() {
        return this.useGlobeControls ? this._verticalPerspectiveCameraHelper : this._mercatorCameraHelper;
    }
    handlePanInertia(pan, transform) {
        return this.currentHelper.handlePanInertia(pan, transform);
    }
    handleMapControlsRollPitchBearingZoom(deltas, tr) {
        this.currentHelper.handleMapControlsRollPitchBearingZoom(deltas, tr);
    }
    handleMapControlsPan(deltas, tr, preZoomAroundLoc) {
        this.currentHelper.handleMapControlsPan(deltas, tr, preZoomAroundLoc);
    }
    cameraForBoxAndBearing(options, padding, bounds, bearing, tr) {
        return this.currentHelper.cameraForBoxAndBearing(options, padding, bounds, bearing, tr);
    }
    /**
     * Handles the zoom and center change during camera jumpTo.
     */
    handleJumpToCenterZoom(tr, options) {
        this.currentHelper.handleJumpToCenterZoom(tr, options);
    }
    handleEaseTo(tr, options) {
        return this.currentHelper.handleEaseTo(tr, options);
    }
    handleFlyTo(tr, options) {
        return this.currentHelper.handleFlyTo(tr, options);
    }
}

function createProjectionFromName(name, transformConstrain) {
    const transformOptions = { constrainOverride: transformConstrain };
    if (Array.isArray(name)) {
        const globeProjection = new GlobeProjection({ type: name });
        return {
            projection: globeProjection,
            transform: new GlobeTransform(transformOptions),
            cameraHelper: new GlobeCameraHelper(globeProjection),
        };
    }
    switch (name) {
        case 'mercator':
            {
                return {
                    projection: new MercatorProjection(),
                    transform: new MercatorTransform(transformOptions),
                    cameraHelper: new MercatorCameraHelper(),
                };
            }
        case 'globe':
            {
                const globeProjection = new GlobeProjection({ type: [
                        'interpolate',
                        ['linear'],
                        ['zoom'],
                        11,
                        'vertical-perspective',
                        12,
                        'mercator'
                    ] });
                return {
                    projection: globeProjection,
                    transform: new GlobeTransform(transformOptions),
                    cameraHelper: new GlobeCameraHelper(globeProjection),
                };
            }
        case 'vertical-perspective':
            {
                return {
                    projection: new VerticalPerspectiveProjection(),
                    transform: new VerticalPerspectiveTransform(transformOptions),
                    cameraHelper: new VerticalPerspectiveCameraHelper(),
                };
            }
        default:
            {
                symbol_layout.warnOnce(`Unknown projection name: ${name}. Falling back to mercator projection.`);
                return {
                    projection: new MercatorProjection(),
                    transform: new MercatorTransform(transformOptions),
                    cameraHelper: new MercatorCameraHelper(),
                };
            }
    }
}

// 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) => symbol_layout.emitValidationErrors(evented, errors === null || errors === void 0 ? void 0 : errors.filter(error => error.identifier !== 'source.canvas'));
const empty = symbol_layout.emptyStyle();
/**
 * The Style base class
 */
class Style extends symbol_layout.Evented {
    constructor(map, options = {}) {
        var _a, _b;
        super();
        this._rtlPluginLoaded = () => {
            for (const id in this.tileManagers) {
                const sourceType = this.tileManagers[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.tileManagers[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.dispatcher.registerMessageHandler("GDA" /* MessageType.getDashes */, (mapId, params) => {
            return this.getDashes(mapId, params);
        });
        this.imageManager = new ImageManager();
        this.imageManager.setEventedParent(this);
        const glyphLang = ((_a = map._container) === null || _a === void 0 ? void 0 : _a.lang) || (typeof document !== 'undefined' && ((_b = document.documentElement) === null || _b === void 0 ? void 0 : _b.lang)) || undefined;
        this.glyphManager = new GlyphManager(map._requestManager, options.localIdeographFontFamily, glyphLang);
        this.lineAtlas = new LineAtlas(256, 512);
        this.crossTileSymbolIndex = new CrossTileSymbolIndex();
        this._setInitialValues();
        this._resetUpdates();
        this.dispatcher.broadcast("SR" /* MessageType.setReferrer */, symbol_layout.getReferrer());
        rtlMainThreadPluginFactory().on(RTLPluginLoadedEventName, this._rtlPluginLoaded);
        this.on('data', (event) => {
            if (event.dataType !== 'source' || event.sourceDataType !== 'metadata') {
                return;
            }
            const tileManager = this.tileManagers[event.sourceId];
            if (!tileManager) {
                return;
            }
            const source = tileManager.getSource();
            if (!(source === null || source === void 0 ? void 0 : source.vectorLayerIds)) {
                return;
            }
            for (const layerId in this._layers) {
                const layer = this._layers[layerId];
                if (layer.source === source.id) {
                    this._validateLayer(layer);
                }
            }
        });
    }
    _setInitialValues() {
        var _a;
        this._spritesImagesIds = {};
        this._layers = {};
        this._order = [];
        this.tileManagers = {};
        this.zoomHistory = new symbol_layout.ZoomHistory();
        this._availableImages = [];
        this._globalState = {};
        this._serializedLayers = {};
        this.stylesheet = null;
        this.light = null;
        this.sky = null;
        if (this.projection) {
            this.projection.destroy();
            delete this.projection;
        }
        this._loaded = false;
        this._changed = false;
        this._updatedLayers = {};
        this._updatedSources = {};
        this._changedImages = {};
        this._glyphsDidChange = false;
        this._updatedPaintProps = {};
        this._layerOrderChanged = false;
        this.crossTileSymbolIndex = new (((_a = this.crossTileSymbolIndex) === null || _a === void 0 ? void 0 : _a.constructor) || Object)();
        this.pauseablePlacement = undefined;
        this.placement = undefined;
        this.z = 0;
    }
    setGlobalStateProperty(name, value) {
        var _a, _b, _c;
        this._checkLoaded();
        const newValue = value === null ?
            (_c = (_b = (_a = this.stylesheet.state) === null || _a === void 0 ? void 0 : _a[name]) === null || _b === void 0 ? void 0 : _b.default) !== null && _c !== void 0 ? _c : null :
            value;
        if (symbol_layout.deepEqual(newValue, this._globalState[name])) {
            return this;
        }
        this._globalState[name] = newValue;
        this._applyGlobalStateChanges([name]);
    }
    getGlobalState() {
        return this._globalState;
    }
    setGlobalState(newStylesheetState) {
        this._checkLoaded();
        const changedGlobalStateRefs = [];
        for (const propertyName in newStylesheetState) {
            const didChange = !symbol_layout.deepEqual(this._globalState[propertyName], newStylesheetState[propertyName].default);
            if (didChange) {
                changedGlobalStateRefs.push(propertyName);
                this._globalState[propertyName] = newStylesheetState[propertyName].default;
            }
        }
        this._applyGlobalStateChanges(changedGlobalStateRefs);
    }
    /**
     * @internal
     * Find all sources that are affected by the global state changes and reload them.
     * Find all paint properties that are affected by the global state changes and update them.
     * For example, if a layer filter uses global-state expression, this function will find the source id of that layer.
     */
    _applyGlobalStateChanges(globalStateRefs) {
        if (globalStateRefs.length === 0) {
            return;
        }
        const sourceIdsToReload = new Set();
        const globalStateChange = {};
        for (const ref of globalStateRefs) {
            globalStateChange[ref] = this._globalState[ref];
            for (const layerId in this._layers) {
                const layer = this._layers[layerId];
                const layoutAffectingGlobalStateRefs = layer.getLayoutAffectingGlobalStateRefs();
                const paintAffectingGlobalStateRefs = layer.getPaintAffectingGlobalStateRefs();
                const visibilityAffectingGlobalStateRefs = layer.getVisibilityAffectingGlobalStateRefs();
                if (layoutAffectingGlobalStateRefs.has(ref)) {
                    sourceIdsToReload.add(layer.source);
                }
                if (paintAffectingGlobalStateRefs.has(ref)) {
                    for (const { name, value } of paintAffectingGlobalStateRefs.get(ref)) {
                        this._updatePaintProperty(layer, name, value);
                    }
                }
                if (visibilityAffectingGlobalStateRefs === null || visibilityAffectingGlobalStateRefs === void 0 ? void 0 : visibilityAffectingGlobalStateRefs.has(ref)) {
                    layer.recalculateVisibility();
                    this._updateLayer(layer);
                }
            }
        }
        // Propagate global state changes to workers
        this.dispatcher.broadcast("UGS" /* MessageType.updateGlobalState */, globalStateChange);
        for (const id in this.tileManagers) {
            if (sourceIdsToReload.has(id)) {
                this._reloadSource(id);
                this._changed = true;
            }
        }
    }
    loadURL(url_1) {
        return symbol_layout.__awaiter(this, arguments, void 0, function* (url, options = {}, previousStyle) {
            this.fire(new symbol_layout.Event('dataloading', { dataType: 'style' }));
            options.validate = typeof options.validate === 'boolean' ?
                options.validate : true;
            this._loadStyleRequest = new AbortController();
            const abortController = this._loadStyleRequest;
            try {
                const request = yield this.map._requestManager.transformRequest(url, "Style" /* ResourceType.Style */);
                symbol_layout.throwIfAborted(abortController.signal);
                const response = yield symbol_layout.getJSON(request, abortController);
                if (this._loadStyleRequest === abortController) {
                    // Clear this request only if it is still the active style load. A stale
                    // request can finish after a newer loadURL() call has already installed
                    // another controller, and must not clear that newer abort handle.
                    this._loadStyleRequest = null;
                }
                this._load(response.data, options, previousStyle);
            }
            catch (error) {
                if (this._loadStyleRequest === abortController) {
                    this._loadStyleRequest = null;
                }
                if (error && !abortController.signal.aborted) { // ignore abort
                    this.fire(new symbol_layout.ErrorEvent(symbol_layout.ensureError(error)));
                }
            }
        });
    }
    loadJSON(json, options = {}, previousStyle) {
        this.fire(new symbol_layout.Event('dataloading', { dataType: 'style' }));
        this._frameRequest = new AbortController();
        browser.frameAsync(this._frameRequest, this.map._ownerWindow).then(() => {
            this._frameRequest = null;
            options.validate = options.validate !== false;
            this._load(json, options, previousStyle);
        }).catch(() => { }); // ignore abort
    }
    loadEmpty() {
        this.fire(new symbol_layout.Event('dataloading', { dataType: 'style' }));
        this._load(empty, { validate: false });
    }
    _load(json, options, previousStyle) {
        var _a, _b;
        let nextState = options.transformStyle ? options.transformStyle(previousStyle, json) : json;
        if (options.validate && emitValidationErrors(this, symbol_layout.validateStyle(nextState))) {
            return;
        }
        nextState = Object.assign({}, nextState);
        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._setProjectionInternal(((_a = this.stylesheet.projection) === null || _a === void 0 ? void 0 : _a.type) || 'mercator');
        this.sky = new Sky(this.stylesheet.sky);
        this.map.setTerrain((_b = this.stylesheet.terrain) !== null && _b !== void 0 ? _b : null);
        this.fire(new symbol_layout.Event('data', { dataType: 'style' }));
        this.fire(new symbol_layout.Event('style.load'));
    }
    _createLayers() {
        var _a, _b, _c;
        const dereferencedLayers = symbol_layout.derefLayers(this.stylesheet.layers);
        this.setGlobalState((_a = this.stylesheet.state) !== null && _a !== void 0 ? _a : null);
        // 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 = symbol_layout.createStyleLayer(layer, this._globalState);
            styledLayer.setEventedParent(this, { layer: { id: layer.id } });
            this._layers[layer.id] = styledLayer;
            if (symbol_layout.isRasterStyleLayer(styledLayer) && this.tileManagers[styledLayer.source]) {
                const rasterFadeDuration = (_c = (_b = layer.paint) === null || _b === void 0 ? void 0 : _b['raster-fade-duration']) !== null && _c !== void 0 ? _c : styledLayer.paint.get('raster-fade-duration');
                this.tileManagers[styledLayer.source].setRasterFadeDuration(rasterFadeDuration);
            }
        }
    }
    _loadSprite(sprite, isUpdate = false, completion = undefined) {
        this.imageManager.setLoaded(false);
        const abortController = new AbortController();
        this._spriteRequest = 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;
            if (!abortController.signal.aborted) { // ignore abort
                this.fire(new symbol_layout.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 symbol_layout.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 symbol_layout.Event('data', { dataType: 'style' }));
    }
    _validateLayer(layer) {
        const tileManager = this.tileManagers[layer.source];
        if (!tileManager) {
            return;
        }
        const sourceLayer = layer.sourceLayer;
        if (!sourceLayer) {
            return;
        }
        const source = tileManager.getSource();
        if (source.type === 'geojson' || (source.vectorLayerIds && !source.vectorLayerIds.includes(sourceLayer))) {
            this.fire(new symbol_layout.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.tileManagers)
            if (!this.tileManagers[id].loaded())
                return false;
        return this.imageManager.isLoaded();
    }
    /**
     * @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 returnClone - 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(symbol_layout.clone$2(serializedLayersDictionary)) : Object.values(serializedLayersDictionary);
        }
        const serializedLayers = [];
        for (const id of ids) {
            // this check will skip all custom layers
            if (serializedLayersDictionary[id]) {
                const toPush = returnClone ? symbol_layout.clone$2(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() {
        var _a, _b, _c;
        if ((_a = this.light) === null || _a === void 0 ? void 0 : _a.hasTransition()) {
            return true;
        }
        if ((_b = this.sky) === null || _b === void 0 ? void 0 : _b.hasTransition()) {
            return true;
        }
        if ((_c = this.projection) === null || _c === void 0 ? void 0 : _c.hasTransition()) {
            return true;
        }
        for (const id in this.tileManagers) {
            if (this.tileManagers[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 managersUsedBefore = {};
        // save 'used' status to managersUsedBefore object and reset all tileManagers 'used' field to false
        for (const id in this.tileManagers) {
            const tileManager = this.tileManagers[id];
            // tileManager.used could be undefined, and managersUsedBefore[id] is also 'undefined'
            managersUsedBefore[id] = tileManager.used;
            tileManager.used = false;
        }
        // loop all layers and find layers that are not hidden at parameters.zoom
        // and set used to true in tileManagers 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.tileManagers[layer.source].used = true;
            }
        }
        // cross check managersUsedBefore against updated this.tileManagers dictionary
        // if "used" field is different fire visibility event
        for (const id in managersUsedBefore) {
            const tileManager = this.tileManagers[id];
            // (undefine !== false) will evaluate to true and fire an useless visibility event
            // need force "falsy" values to boolean to avoid the case above
            if (!!managersUsedBefore[id] !== !!tileManager.used) {
                tileManager.fire(new symbol_layout.Event('data', {
                    sourceDataType: 'visibility',
                    dataType: 'source',
                    sourceId: id
                }));
            }
        }
        this.light.recalculate(parameters);
        this.sky.recalculate(parameters);
        this.projection.recalculate(parameters);
        this.z = parameters.zoom;
        if (changed) {
            this.fire(new symbol_layout.Event('data', { dataType: 'style' }));
        }
    }
    /*
     * Apply any queued image changes.
     */
    _updateTilesForChangedImages() {
        const changedImages = Object.keys(this._changedImages);
        if (changedImages.length) {
            for (const name in this.tileManagers) {
                this.tileManagers[name].reloadTilesForDependencies(['icons', 'patterns'], changedImages);
            }
            this._changedImages = {};
        }
    }
    _updateTilesForChangedGlyphs() {
        if (this._glyphsDidChange) {
            for (const name in this.tileManagers) {
                this.tileManagers[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, symbol_layout.validateStyle(nextState)))
            return false;
        nextState = symbol_layout.clone$2(nextState);
        nextState.layers = symbol_layout.derefLayers(nextState.layers);
        const changes = symbol_layout.diff(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;
        this.fire(new symbol_layout.Event('style.load', { style: this }));
        return true;
    }
    _getOperationsToPerform(diff) {
        const operations = [];
        const unimplemented = [];
        for (const op of diff) {
            switch (op.command) {
                case 'setCenter':
                case 'setZoom':
                case 'setBearing':
                case 'setPitch':
                case 'setRoll':
                    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 'setTerrain':
                    operations.push(() => this.map.setTerrain.apply(this, op.args));
                    break;
                case 'setSky':
                    operations.push(() => this.setSky.apply(this, op.args));
                    break;
                case 'setProjection':
                    this.setProjection.apply(this, op.args);
                    break;
                case 'setGlobalState':
                    operations.push(() => this.setGlobalState.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 symbol_layout.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 symbol_layout.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 symbol_layout.Event('data', { dataType: 'style' }));
    }
    listImages() {
        this._checkLoaded();
        return this.imageManager.listImages();
    }
    addSource(id, source, options = {}) {
        var _a;
        this._checkLoaded();
        if (this.tileManagers[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.includes(source.type);
        if (shouldValidate && this._validate(symbol_layout.validateStyle.source, `sources.${id}`, source, null, options))
            return;
        if ((_a = this.map) === null || _a === void 0 ? void 0 : _a._collectResourceTiming)
            source.collectResourceTiming = true;
        const tileManager = this.tileManagers[id] = new TileManager(id, source, this.dispatcher);
        tileManager.style = this;
        tileManager.setEventedParent(this, () => ({
            isSourceLoaded: tileManager.loaded(),
            source: tileManager.serialize(),
            sourceId: id
        }));
        tileManager.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.tileManagers[id] === undefined) {
            throw new Error(`There is no source with this ID=${id}`);
        }
        for (const layerId in this._layers) {
            if (this._layers[layerId].source === id) {
                return this.fire(new symbol_layout.ErrorEvent(new Error(`Source "${id}" cannot be removed while layer "${layerId}" is using it.`)));
            }
        }
        const tileManager = this.tileManagers[id];
        delete this.tileManagers[id];
        delete this._updatedSources[id];
        tileManager.fire(new symbol_layout.Event('data', { sourceDataType: 'metadata', dataType: 'source', sourceId: id }));
        tileManager.setEventedParent(null);
        tileManager.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.tileManagers[id] === undefined)
            throw new Error(`There is no source with this ID=${id}`);
        const geojsonSource = this.tileManagers[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) {
        var _a;
        return (_a = this.tileManagers[id]) === null || _a === void 0 ? void 0 : _a.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 symbol_layout.ErrorEvent(new Error(`Layer "${id}" already exists on this map.`)));
            return;
        }
        let layer;
        if (layerObject.type === 'custom') {
            if (emitValidationErrors(this, symbol_layout.validateCustomStyleLayer(layerObject)))
                return;
            layer = symbol_layout.createStyleLayer(layerObject, this._globalState);
        }
        else {
            if ('source' in layerObject && typeof layerObject.source === 'object') {
                this.addSource(id, layerObject.source);
                layerObject = symbol_layout.clone$2(layerObject);
                layerObject = symbol_layout.extend(layerObject, { source: id });
            }
            // this layer is not in the style.layers array, so we pass an impossible array index
            if (this._validate(symbol_layout.validateStyle.layer, `layers.${id}`, layerObject, { arrayIndex: -1 }, options))
                return;
            layer = symbol_layout.createStyleLayer(layerObject, this._globalState);
            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 symbol_layout.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.tileManagers[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 symbol_layout.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 symbol_layout.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 symbol_layout.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 symbol_layout.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 symbol_layout.ErrorEvent(new Error(`Cannot filter non-existing layer "${layerId}".`)));
            return;
        }
        if (symbol_layout.deepEqual(layer.filter, filter)) {
            return;
        }
        if (filter === null || filter === undefined) {
            layer.setFilter(undefined);
            this._updateLayer(layer);
            return;
        }
        if (this._validate(symbol_layout.validateStyle.filter, `layers.${layer.id}.filter`, filter, null, options)) {
            return;
        }
        layer.setFilter(symbol_layout.clone$2(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 symbol_layout.clone$2(this.getLayer(layer).filter);
    }
    setLayoutProperty(layerId, name, value, options = {}) {
        this._checkLoaded();
        const layer = this.getLayer(layerId);
        if (!layer) {
            this.fire(new symbol_layout.ErrorEvent(new Error(`Cannot style non-existing layer "${layerId}".`)));
            return;
        }
        if (symbol_layout.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 symbol_layout.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 symbol_layout.ErrorEvent(new Error(`Cannot style non-existing layer "${layerId}".`)));
            return;
        }
        if (symbol_layout.deepEqual(layer.getPaintProperty(name), value))
            return;
        this._updatePaintProperty(layer, name, value, options);
    }
    _updatePaintProperty(layer, name, value, options = {}) {
        const requiresRelayout = layer.setPaintProperty(name, value, options);
        if (requiresRelayout) {
            this._updateLayer(layer);
        }
        if (symbol_layout.isRasterStyleLayer(layer) && name === 'raster-fade-duration') {
            this.tileManagers[layer.source].setRasterFadeDuration(value);
        }
        this._changed = true;
        this._updatedPaintProps[layer.id] = 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 tileManager = this.tileManagers[sourceId];
        if (tileManager === undefined) {
            this.fire(new symbol_layout.ErrorEvent(new Error(`The source '${sourceId}' does not exist in the map's style.`)));
            return;
        }
        const sourceType = tileManager.getSource().type;
        if (sourceType === 'geojson' && sourceLayer) {
            this.fire(new symbol_layout.ErrorEvent(new Error('GeoJSON sources cannot have a sourceLayer parameter.')));
            return;
        }
        if (sourceType === 'vector' && !sourceLayer) {
            this.fire(new symbol_layout.ErrorEvent(new Error('The sourceLayer parameter must be provided for vector source types.')));
            return;
        }
        if (target.id === undefined) {
            this.fire(new symbol_layout.ErrorEvent(new Error('The feature id parameter must be provided.')));
        }
        tileManager.setFeatureState(sourceLayer, target.id, state);
    }
    removeFeatureState(target, key) {
        this._checkLoaded();
        const sourceId = target.source;
        const tileManager = this.tileManagers[sourceId];
        if (tileManager === undefined) {
            this.fire(new symbol_layout.ErrorEvent(new Error(`The source '${sourceId}' does not exist in the map's style.`)));
            return;
        }
        const sourceType = tileManager.getSource().type;
        const sourceLayer = sourceType === 'vector' ? target.sourceLayer : undefined;
        if (sourceType === 'vector' && !sourceLayer) {
            this.fire(new symbol_layout.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 symbol_layout.ErrorEvent(new Error('A feature id is required to remove its specific state property.')));
            return;
        }
        tileManager.removeFeatureState(sourceLayer, target.id, key);
    }
    getFeatureState(target) {
        this._checkLoaded();
        const sourceId = target.source;
        const sourceLayer = target.sourceLayer;
        const tileManager = this.tileManagers[sourceId];
        if (tileManager === undefined) {
            this.fire(new symbol_layout.ErrorEvent(new Error(`The source '${sourceId}' does not exist in the map's style.`)));
            return;
        }
        const sourceType = tileManager.getSource().type;
        if (sourceType === 'vector' && !sourceLayer) {
            this.fire(new symbol_layout.ErrorEvent(new Error('The sourceLayer parameter must be provided for vector source types.')));
            return;
        }
        if (target.id === undefined) {
            this.fire(new symbol_layout.ErrorEvent(new Error('The feature id parameter must be provided.')));
        }
        return tileManager.getFeatureState(sourceLayer, target.id);
    }
    getTransition() {
        var _a;
        return symbol_layout.extend({ duration: 300, delay: 0 }, (_a = this.stylesheet) === null || _a === void 0 ? void 0 : _a.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 = symbol_layout.mapObject(this.tileManagers, (source) => source.serialize());
        const layers = this._serializeByIds(this._order, true);
        const terrain = this.map.getTerrain() || undefined;
        const myStyleSheet = this.stylesheet;
        return symbol_layout.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,
            projection: myStyleSheet.projection,
            sources,
            layers,
            terrain
        }, (value) => 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.tileManagers[layer.source].getSource().type !== 'raster') {
            this._updatedSources[layer.source] = 'reload';
            this.tileManagers[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 === null || params === void 0 ? void 0 : params.filter) {
            this._validate(symbol_layout.validateStyle.filter, 'queryRenderedFeatures.filter', params.filter, null, params);
        }
        const includedSources = {};
        if (params === null || params === void 0 ? void 0 : params.layers) {
            const isArrayOrSet = Array.isArray(params.layers) || params.layers instanceof Set;
            if (!isArrayOrSet) {
                this.fire(new symbol_layout.ErrorEvent(new Error('parameters.layers must be an Array or a Set of strings')));
                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 symbol_layout.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();
        const layersAsSet = params.layers instanceof Set ? params.layers : Array.isArray(params.layers) ? new Set(params.layers) : null;
        const paramsStrict = Object.assign(Object.assign({}, params), { layers: layersAsSet, globalState: this._globalState });
        for (const id in this.tileManagers) {
            if (params.layers && !includedSources[id])
                continue;
            sourceResults.push(queryRenderedFeatures(this.tileManagers[id], this._layers, serializedLayers, queryGeometry, paramsStrict, transform, this.map.terrain ?
                (id, x, y) => this.map.terrain.getElevation(id, x, y) :
                undefined));
        }
        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.tileManagers, queryGeometry, paramsStrict, this.placement.collisionIndex, this.placement.retainedQueryData));
        }
        return this._flattenAndSortRenderedFeatures(sourceResults);
    }
    querySourceFeatures(sourceID, params) {
        if (params === null || params === void 0 ? void 0 : params.filter) {
            this._validate(symbol_layout.validateStyle.filter, 'querySourceFeatures.filter', params.filter, null, params);
        }
        const tileManager = this.tileManagers[sourceID];
        return tileManager ? querySourceFeatures(tileManager, params ? Object.assign(Object.assign({}, params), { globalState: this._globalState }) : { globalState: this._globalState }) : [];
    }
    getLight() {
        return this.light.getLight();
    }
    setLight(lightOptions, options = {}) {
        this._checkLoaded();
        const light = this.light.getLight();
        let _update = false;
        for (const key in lightOptions) {
            if (!symbol_layout.deepEqual(lightOptions[key], light[key])) {
                _update = true;
                break;
            }
        }
        if (!_update)
            return;
        const parameters = {
            now: now(),
            transition: symbol_layout.extend({
                duration: 300,
                delay: 0
            }, this.stylesheet.transition)
        };
        this.light.setLight(lightOptions, options);
        this.light.updateTransitions(parameters);
    }
    getProjection() {
        var _a;
        return (_a = this.stylesheet) === null || _a === void 0 ? void 0 : _a.projection;
    }
    setProjection(projection) {
        this._checkLoaded();
        const resolvedProjection = projection !== null && projection !== void 0 ? projection : { type: 'mercator' };
        this.stylesheet.projection = projection;
        if (this.projection) {
            if (this.projection.name === resolvedProjection.type) {
                return;
            }
            this.projection.destroy();
            delete this.projection;
        }
        this._setProjectionInternal(resolvedProjection.type);
    }
    getSky() {
        var _a;
        return (_a = this.stylesheet) === null || _a === void 0 ? void 0 : _a.sky;
    }
    setSky(skyOptions, options = {}) {
        this._checkLoaded();
        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 (!symbol_layout.deepEqual(skyOptions[key], sky[key])) {
                    update = true;
                    break;
                }
            }
        }
        if (!update)
            return;
        const parameters = {
            now: now(),
            transition: symbol_layout.extend({
                duration: 300,
                delay: 0
            }, this.stylesheet.transition)
        };
        this.stylesheet.sky = skyOptions;
        this.sky.setSky(skyOptions, options);
        this.sky.updateTransitions(parameters);
    }
    _setProjectionInternal(name) {
        const projectionObjects = createProjectionFromName(name, this.map.transformConstrain);
        this.projection = projectionObjects.projection;
        this.map.migrateProjection(projectionObjects.transform, projectionObjects.cameraHelper);
        for (const key in this.tileManagers) {
            this.tileManagers[key].reload();
        }
    }
    _validate(validate, key, value, props, options = {}) {
        if ((options === null || options === void 0 ? void 0 : options.validate) === false) {
            return false;
        }
        return emitValidationErrors(this, validate.call(symbol_layout.validateStyle, symbol_layout.extend({
            key,
            style: this.serialize(),
            value,
            styleSpec: symbol_layout.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.tileManagers) {
            const tileManager = this.tileManagers[id];
            tileManager.setEventedParent(null);
            tileManager.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.tileManagers[id].clearTiles();
    }
    _reloadSource(id) {
        this.tileManagers[id].resume();
        this.tileManagers[id].reload();
    }
    _updateSources(transform) {
        for (const id in this.tileManagers) {
            this.tileManagers[id].update(transform, this.map.terrain);
        }
    }
    _generateCollisionBoxes() {
        for (const id in this.tileManagers) {
            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 tileManager = this.tileManagers[styleLayer.source];
                layerTiles[styleLayer.source] = tileManager.getRenderableIds(true)
                    .map((id) => tileManager.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(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(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]);
            }
        }
        // false when we have just finished a placement that didn't change the visibility of any symbols
        return !this.pauseablePlacement.isDone() || this.placement.hasTransitions(now());
    }
    _releaseSymbolFadeTiles() {
        for (const id in this.tileManagers) {
            this.tileManagers[id].releaseSymbolFadeTiles();
        }
    }
    // Callbacks from web workers
    getImages(mapId, params) {
        return symbol_layout.__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 tileManager = this.tileManagers[params.source];
            if (tileManager) {
                tileManager.setDependencies(params.tileID.key, params.type, params.icons);
            }
            return images;
        });
    }
    getGlyphs(mapId, params) {
        return symbol_layout.__awaiter(this, void 0, void 0, function* () {
            const glyphs = yield this.glyphManager.getGlyphs(params.stacks);
            const tileManager = this.tileManagers[params.source];
            if (tileManager) {
                // we are not setting stacks as dependencies since for now
                // we just need to know which tiles have glyph dependencies
                tileManager.setDependencies(params.tileID.key, params.type, ['']);
            }
            return glyphs;
        });
    }
    getGlyphsUrl() {
        return this.stylesheet.glyphs || null;
    }
    setGlyphs(glyphsUrl, options = {}) {
        this._checkLoaded();
        if (glyphsUrl && this._validate(symbol_layout.validateStyle.glyphs, 'glyphs', glyphsUrl, null, options)) {
            return;
        }
        this._glyphsDidChange = true;
        this.stylesheet.glyphs = glyphsUrl;
        this.glyphManager.entries = {};
        this.glyphManager.setURL(glyphsUrl);
    }
    getDashes(mapId, params) {
        return symbol_layout.__awaiter(this, void 0, void 0, function* () {
            const result = {};
            for (const [key, dash] of Object.entries(params.dashes)) {
                result[key] = this.lineAtlas.getDash(dash.dasharray, dash.round);
            }
            return result;
        });
    }
    /**
     * 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(symbol_layout.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 symbol_layout.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 symbol_layout.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(symbol_layout.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);
            }
        }
    }
    /**
     * Destroys all internal resources of the style (sources, images, layers, etc.)
     */
    destroy() {
        // cancel any pending requests
        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;
        }
        // remove sourcecaches
        for (const id in this.tileManagers) {
            const tileManager = this.tileManagers[id];
            tileManager.setEventedParent(null);
            tileManager.onRemove(this.map);
        }
        this.tileManagers = {};
        // Destroy imageManager and clear images
        if (this.imageManager) {
            this.imageManager.setEventedParent(null);
            this.imageManager.destroy();
            this._availableImages = [];
            this._spritesImagesIds = {};
        }
        // Destroy glyphManager
        if (this.glyphManager) {
            this.glyphManager.destroy();
        }
        // Remove layers
        for (const layerId in this._layers) {
            const layer = this._layers[layerId];
            layer.setEventedParent(null);
            if (layer.onRemove)
                layer.onRemove(this.map);
        }
        // reset internal state
        this._setInitialValues();
        // Remove event listeners
        this.setEventedParent(null);
        this.dispatcher.unregisterMessageHandler("GG" /* MessageType.getGlyphs */);
        this.dispatcher.unregisterMessageHandler("GI" /* MessageType.getImages */);
        this.dispatcher.unregisterMessageHandler("GDA" /* MessageType.getDashes */);
        this.dispatcher.remove(true);
        this._listeners = {};
        this._oneTimeListeners = {};
    }
}

var rasterBoundsAttributes = symbol_layout.createLayout([
    { name: 'a_pos', type: 'Int16', components: 2 },
    { name: 'a_texture_pos', type: 'Int16', components: 2 }
]);

/**
 * @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 === null || indexBuffer === void 0 ? void 0 : 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 symbol_layout.Uniform1i(context, locations.u_depth),
    'u_terrain': new symbol_layout.Uniform1i(context, locations.u_terrain),
    'u_terrain_dim': new symbol_layout.Uniform1f(context, locations.u_terrain_dim),
    'u_terrain_matrix': new symbol_layout.UniformMatrix4f(context, locations.u_terrain_matrix),
    'u_terrain_unpack': new symbol_layout.Uniform4f(context, locations.u_terrain_unpack),
    'u_terrain_exaggeration': new symbol_layout.Uniform1f(context, locations.u_terrain_exaggeration)
});
const terrainUniforms = (context, locations) => ({
    'u_texture': new symbol_layout.Uniform1i(context, locations.u_texture),
    'u_ele_delta': new symbol_layout.Uniform1f(context, locations.u_ele_delta),
    'u_fog_matrix': new symbol_layout.UniformMatrix4f(context, locations.u_fog_matrix),
    'u_fog_color': new symbol_layout.UniformColor(context, locations.u_fog_color),
    'u_fog_ground_blend': new symbol_layout.Uniform1f(context, locations.u_fog_ground_blend),
    'u_fog_ground_blend_opacity': new symbol_layout.Uniform1f(context, locations.u_fog_ground_blend_opacity),
    'u_horizon_color': new symbol_layout.UniformColor(context, locations.u_horizon_color),
    'u_horizon_fog_blend': new symbol_layout.Uniform1f(context, locations.u_horizon_fog_blend),
    'u_is_globe_mode': new symbol_layout.Uniform1f(context, locations.u_is_globe_mode)
});
const terrainDepthUniforms = (context, locations) => ({
    'u_ele_delta': new symbol_layout.Uniform1f(context, locations.u_ele_delta)
});
const terrainCoordsUniforms = (context, locations) => ({
    'u_texture': new symbol_layout.Uniform1i(context, locations.u_texture),
    'u_terrain_coords_id': new symbol_layout.Uniform1f(context, locations.u_terrain_coords_id),
    'u_ele_delta': new symbol_layout.Uniform1f(context, locations.u_ele_delta)
});
const terrainUniformValues = (eleDelta, fogMatrix, sky, pitch, isGlobeMode) => ({
    'u_texture': 0,
    'u_ele_delta': eleDelta,
    'u_fog_matrix': fogMatrix,
    'u_fog_color': sky ? sky.properties.get('fog-color') : symbol_layout.Color.white,
    'u_fog_ground_blend': sky ? sky.properties.get('fog-ground-blend') : 1,
    // Set opacity to 0 when in globe mode to disable fog
    'u_fog_ground_blend_opacity': isGlobeMode ? 0 : (sky ? sky.calculateFogBlendOpacity(pitch) : 0),
    'u_horizon_color': sky ? sky.properties.get('horizon-color') : symbol_layout.Color.white,
    'u_horizon_fog_blend': sky ? sky.properties.get('horizon-fog-blend') : 1,
    'u_is_globe_mode': isGlobeMode ? 1 : 0
});
const terrainDepthUniformValues = (eleDelta) => ({
    'u_ele_delta': eleDelta
});
const terrainCoordsUniformValues = (coordsId, eleDelta) => ({
    'u_terrain_coords_id': coordsId / 255,
    'u_texture': 0,
    'u_ele_delta': eleDelta
});

const projectionUniforms = (context, locations) => ({
    'u_projection_matrix': new symbol_layout.UniformMatrix4f(context, locations.u_projection_matrix),
    'u_projection_tile_mercator_coords': new symbol_layout.Uniform4f(context, locations.u_projection_tile_mercator_coords),
    'u_projection_clipping_plane': new symbol_layout.Uniform4f(context, locations.u_projection_clipping_plane),
    'u_projection_transition': new symbol_layout.Uniform1f(context, locations.u_projection_transition),
    'u_projection_fallback_matrix': new symbol_layout.UniformMatrix4f(context, locations.u_projection_fallback_matrix),
});
/**
 * Maps a field name in {@link ProjectionData} to its corresponding uniform name in {@link ProjectionPreludeUniformsType}.
 */
const projectionObjectToUniformMap = {
    mainMatrix: 'u_projection_matrix',
    tileMercatorCoords: 'u_projection_tile_mercator_coords',
    clippingPlane: 'u_projection_clipping_plane',
    projectionTransition: 'u_projection_transition',
    fallbackMatrix: 'u_projection_fallback_matrix',
};

function getTokenizedAttributesAndUniforms(array) {
    const result = [];
    for (const entry of array) {
        if (entry === null)
            continue;
        const token = entry.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, hasTerrain, projectionPrelude, projectionDefine, extraDefines = []) {
        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 projectionPreludeUniformsInfo = projectionPrelude.staticUniforms ? getTokenizedAttributesAndUniforms(projectionPrelude.staticUniforms) : [];
        const staticUniformsInfo = source.staticUniforms ? getTokenizedAttributesAndUniforms(source.staticUniforms) : [];
        const dynamicUniformsInfo = configuration ? configuration.getBinderUniforms() : [];
        // remove duplicate uniforms
        const uniformList = preludeUniformsInfo.concat(projectionPreludeUniformsInfo).concat(staticUniformsInfo).concat(dynamicUniformsInfo);
        const allUniformsInfo = [];
        for (const uniform of uniformList) {
            if (!allUniformsInfo.includes(uniform))
                allUniformsInfo.push(uniform);
        }
        const defines = configuration ? configuration.defines() : [];
        if (isWebGL2(gl)) {
            defines.unshift('#version 300 es');
        }
        if (showOverdrawInspector) {
            defines.push('#define OVERDRAW_INSPECTOR;');
        }
        if (hasTerrain) {
            defines.push('#define TERRAIN3D;');
        }
        if (projectionDefine) {
            defines.push(projectionDefine);
        }
        if (extraDefines) {
            defines.push(...extraDefines);
        }
        let fragmentSource = defines.concat(shaders.prelude.fragmentSource, projectionPrelude.fragmentSource, source.fragmentSource).join('\n');
        let vertexSource = defines.concat(shaders.prelude.vertexSource, projectionPrelude.vertexSource, source.vertexSource).join('\n');
        if (!isWebGL2(gl)) {
            fragmentSource = transpileFragmentShaderToWebGL1(fragmentSource);
            vertexSource = transpileVertexShaderToWebGL1(vertexSource);
        }
        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)) {
            throw new Error(`Could not compile fragment shader: ${gl.getShaderInfoLog(fragmentShader)}`);
        }
        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)) {
            throw new Error(`Program failed to link: ${gl.getProgramInfoLog(this.program)}`);
        }
        gl.deleteShader(vertexShader);
        gl.deleteShader(fragmentShader);
        for (const uniform of allUniformsInfo) {
            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.projectionUniforms = projectionUniforms(context, uniformLocations);
        this.binderUniforms = configuration ? configuration.getUniforms(context, uniformLocations) : [];
    }
    draw(context, drawMode, depthMode, stencilMode, colorMode, cullFaceMode, uniformValues, terrain, projectionData, 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]);
            }
        }
        if (projectionData) {
            for (const fieldName in projectionData) {
                const uniformName = projectionObjectToUniformMap[fieldName];
                this.projectionUniforms[uniformName].set(projectionData[fieldName]);
            }
        }
        if (uniformValues) {
            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 / symbol_layout.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 / symbol_layout.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_lightpos': new symbol_layout.Uniform3f(context, locations.u_lightpos),
    'u_lightpos_globe': new symbol_layout.Uniform3f(context, locations.u_lightpos_globe),
    'u_lightintensity': new symbol_layout.Uniform1f(context, locations.u_lightintensity),
    'u_lightcolor': new symbol_layout.Uniform3f(context, locations.u_lightcolor),
    'u_vertical_gradient': new symbol_layout.Uniform1f(context, locations.u_vertical_gradient),
    'u_opacity': new symbol_layout.Uniform1f(context, locations.u_opacity),
    'u_fill_translate': new symbol_layout.Uniform2f(context, locations.u_fill_translate),
});
const fillExtrusionPatternUniforms = (context, locations) => ({
    'u_lightpos': new symbol_layout.Uniform3f(context, locations.u_lightpos),
    'u_lightpos_globe': new symbol_layout.Uniform3f(context, locations.u_lightpos_globe),
    'u_lightintensity': new symbol_layout.Uniform1f(context, locations.u_lightintensity),
    'u_lightcolor': new symbol_layout.Uniform3f(context, locations.u_lightcolor),
    'u_vertical_gradient': new symbol_layout.Uniform1f(context, locations.u_vertical_gradient),
    'u_height_factor': new symbol_layout.Uniform1f(context, locations.u_height_factor),
    'u_opacity': new symbol_layout.Uniform1f(context, locations.u_opacity),
    'u_fill_translate': new symbol_layout.Uniform2f(context, locations.u_fill_translate),
    // pattern uniforms
    'u_image': new symbol_layout.Uniform1i(context, locations.u_image),
    'u_texsize': new symbol_layout.Uniform2f(context, locations.u_texsize),
    'u_pixel_coord_upper': new symbol_layout.Uniform2f(context, locations.u_pixel_coord_upper),
    'u_pixel_coord_lower': new symbol_layout.Uniform2f(context, locations.u_pixel_coord_lower),
    'u_scale': new symbol_layout.Uniform3f(context, locations.u_scale),
    'u_fade': new symbol_layout.Uniform1f(context, locations.u_fade)
});
const fillExtrusionUniformValues = (painter, shouldUseVerticalGradient, opacity, translate) => {
    const light = painter.style.light;
    const _lp = light.properties.get('position');
    const lightPos = [_lp.x, _lp.y, _lp.z];
    const lightMat = symbol_layout.create$3();
    if (light.properties.get('anchor') === 'viewport') {
        symbol_layout.fromRotation(lightMat, painter.transform.bearingInRadians);
    }
    symbol_layout.transformMat3(lightPos, lightPos, lightMat);
    const transformedLightPos = painter.transform.transformLightDirection(lightPos);
    const lightColor = light.properties.get('color');
    return {
        'u_lightpos': lightPos,
        'u_lightpos_globe': transformedLightPos,
        'u_lightintensity': light.properties.get('intensity'),
        'u_lightcolor': [lightColor.r, lightColor.g, lightColor.b],
        'u_vertical_gradient': +shouldUseVerticalGradient,
        'u_opacity': opacity,
        'u_fill_translate': translate,
    };
};
const fillExtrusionPatternUniformValues = (painter, shouldUseVerticalGradient, opacity, translate, coord, crossfade, tile) => {
    return symbol_layout.extend(fillExtrusionUniformValues(painter, shouldUseVerticalGradient, opacity, translate), patternUniformValues(crossfade, painter, tile), {
        'u_height_factor': -Math.pow(2, coord.overscaledZ) / tile.tileSize / 8
    });
};

const fillUniforms = (context, locations) => ({
    'u_fill_translate': new symbol_layout.Uniform2f(context, locations.u_fill_translate)
});
const fillPatternUniforms = (context, locations) => ({
    'u_image': new symbol_layout.Uniform1i(context, locations.u_image),
    'u_texsize': new symbol_layout.Uniform2f(context, locations.u_texsize),
    'u_pixel_coord_upper': new symbol_layout.Uniform2f(context, locations.u_pixel_coord_upper),
    'u_pixel_coord_lower': new symbol_layout.Uniform2f(context, locations.u_pixel_coord_lower),
    'u_scale': new symbol_layout.Uniform3f(context, locations.u_scale),
    'u_fade': new symbol_layout.Uniform1f(context, locations.u_fade),
    'u_fill_translate': new symbol_layout.Uniform2f(context, locations.u_fill_translate)
});
const fillOutlineUniforms = (context, locations) => ({
    'u_world': new symbol_layout.Uniform2f(context, locations.u_world),
    'u_fill_translate': new symbol_layout.Uniform2f(context, locations.u_fill_translate)
});
const fillOutlinePatternUniforms = (context, locations) => ({
    'u_world': new symbol_layout.Uniform2f(context, locations.u_world),
    'u_image': new symbol_layout.Uniform1i(context, locations.u_image),
    'u_texsize': new symbol_layout.Uniform2f(context, locations.u_texsize),
    'u_pixel_coord_upper': new symbol_layout.Uniform2f(context, locations.u_pixel_coord_upper),
    'u_pixel_coord_lower': new symbol_layout.Uniform2f(context, locations.u_pixel_coord_lower),
    'u_scale': new symbol_layout.Uniform3f(context, locations.u_scale),
    'u_fade': new symbol_layout.Uniform1f(context, locations.u_fade),
    'u_fill_translate': new symbol_layout.Uniform2f(context, locations.u_fill_translate)
});
const fillPatternUniformValues = (painter, crossfade, tile, translate) => symbol_layout.extend(patternUniformValues(crossfade, painter, tile), {
    'u_fill_translate': translate,
});
const fillUniformValues = (translate) => ({
    'u_fill_translate': translate,
});
const fillOutlineUniformValues = (drawingBufferSize, translate) => ({
    'u_world': drawingBufferSize,
    'u_fill_translate': translate,
});
const fillOutlinePatternUniformValues = (painter, crossfade, tile, drawingBufferSize, translate) => symbol_layout.extend(fillPatternUniformValues(painter, crossfade, tile, translate), {
    'u_world': drawingBufferSize
});

const circleUniforms = (context, locations) => ({
    'u_camera_to_center_distance': new symbol_layout.Uniform1f(context, locations.u_camera_to_center_distance),
    'u_scale_with_map': new symbol_layout.Uniform1i(context, locations.u_scale_with_map),
    'u_pitch_with_map': new symbol_layout.Uniform1i(context, locations.u_pitch_with_map),
    'u_extrude_scale': new symbol_layout.Uniform2f(context, locations.u_extrude_scale),
    'u_device_pixel_ratio': new symbol_layout.Uniform1f(context, locations.u_device_pixel_ratio),
    'u_globe_extrude_scale': new symbol_layout.Uniform1f(context, locations.u_globe_extrude_scale),
    'u_translate': new symbol_layout.Uniform2f(context, locations.u_translate),
});
const circleUniformValues = (painter, tile, layer, translate, radiusCorrectionFactor) => {
    const transform = painter.transform;
    let pitchWithMap, extrudeScale;
    let globeExtrudeScale = 0;
    if (layer.paint.get('circle-pitch-alignment') === 'map') {
        const pixelRatio = symbol_layout.pixelsToTileUnits(tile, 1, transform.zoom);
        pitchWithMap = true;
        extrudeScale = [pixelRatio, pixelRatio];
        // For globe rendering we need to know how much to extrude the circle as an *angle*.
        // The calculation: (one pixel in tile units) / (earth circumference in tile units) * (2PI radians) * radiusCorrectionFactor
        globeExtrudeScale = pixelRatio / (symbol_layout.EXTENT * Math.pow(2, tile.tileID.overscaledZ)) * 2.0 * Math.PI * radiusCorrectionFactor;
    }
    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_pitch_with_map': +(pitchWithMap),
        'u_device_pixel_ratio': painter.pixelRatio,
        'u_extrude_scale': extrudeScale,
        'u_globe_extrude_scale': globeExtrudeScale,
        'u_translate': translate,
    };
};

const collisionUniforms = (context, locations) => ({
    'u_pixel_extrude_scale': new symbol_layout.Uniform2f(context, locations.u_pixel_extrude_scale)
});
const collisionCircleUniforms = (context, locations) => ({
    'u_viewport_size': new symbol_layout.Uniform2f(context, locations.u_viewport_size)
});
const collisionUniformValues = (transform) => {
    return {
        'u_pixel_extrude_scale': [1.0 / transform.width, 1.0 / transform.height],
    };
};
const collisionCircleUniformValues = (transform) => {
    return {
        'u_viewport_size': [transform.width, transform.height]
    };
};

const debugUniforms = (context, locations) => ({
    'u_color': new symbol_layout.UniformColor(context, locations.u_color),
    'u_overlay': new symbol_layout.Uniform1i(context, locations.u_overlay),
    'u_overlay_scale': new symbol_layout.Uniform1f(context, locations.u_overlay_scale)
});
const debugUniformValues = (color, scaleRatio = 1) => ({
    'u_color': color,
    'u_overlay': 0,
    'u_overlay_scale': scaleRatio
});

const heatmapUniforms = (context, locations) => ({
    'u_extrude_scale': new symbol_layout.Uniform1f(context, locations.u_extrude_scale),
    'u_intensity': new symbol_layout.Uniform1f(context, locations.u_intensity),
    'u_globe_extrude_scale': new symbol_layout.Uniform1f(context, locations.u_globe_extrude_scale)
});
const heatmapTextureUniforms = (context, locations) => ({
    'u_matrix': new symbol_layout.UniformMatrix4f(context, locations.u_matrix),
    'u_world': new symbol_layout.Uniform2f(context, locations.u_world),
    'u_image': new symbol_layout.Uniform1i(context, locations.u_image),
    'u_color_ramp': new symbol_layout.Uniform1i(context, locations.u_color_ramp),
    'u_opacity': new symbol_layout.Uniform1f(context, locations.u_opacity)
});
const heatmapUniformValues = (tile, zoom, intensity, radiusCorrectionFactor) => {
    const pixelRatio = symbol_layout.pixelsToTileUnits(tile, 1, zoom);
    // See comment in circle_program.ts
    const globeExtrudeScale = pixelRatio / (symbol_layout.EXTENT * Math.pow(2, tile.tileID.overscaledZ)) * 2.0 * Math.PI * radiusCorrectionFactor;
    return {
        'u_extrude_scale': symbol_layout.pixelsToTileUnits(tile, 1, zoom),
        'u_intensity': intensity,
        'u_globe_extrude_scale': globeExtrudeScale
    };
};
const heatmapTextureUniformValues = (painter, layer, textureUnit, colorRampUnit) => {
    const matrix = symbol_layout.create();
    symbol_layout.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_image': new symbol_layout.Uniform1i(context, locations.u_image),
    'u_latrange': new symbol_layout.Uniform2f(context, locations.u_latrange),
    'u_exaggeration': new symbol_layout.Uniform1f(context, locations.u_exaggeration),
    'u_altitudes': new symbol_layout.UniformFloatArray(context, locations.u_altitudes),
    'u_azimuths': new symbol_layout.UniformFloatArray(context, locations.u_azimuths),
    'u_accent': new symbol_layout.UniformColor(context, locations.u_accent),
    'u_method': new symbol_layout.Uniform1i(context, locations.u_method),
    'u_shadows': new symbol_layout.UniformColorArray(context, locations.u_shadows),
    'u_highlights': new symbol_layout.UniformColorArray(context, locations.u_highlights)
});
const hillshadePrepareUniforms = (context, locations) => ({
    'u_matrix': new symbol_layout.UniformMatrix4f(context, locations.u_matrix),
    'u_image': new symbol_layout.Uniform1i(context, locations.u_image),
    'u_dimension': new symbol_layout.Uniform2f(context, locations.u_dimension),
    'u_zoom': new symbol_layout.Uniform1f(context, locations.u_zoom),
    'u_unpack': new symbol_layout.Uniform4f(context, locations.u_unpack)
});
const hillshadeUniformValues = (painter, tile, layer) => {
    const accent = layer.paint.get('hillshade-accent-color');
    let method;
    switch (layer.paint.get('hillshade-method')) {
        case 'basic':
            method = 4;
            break;
        case 'combined':
            method = 1;
            break;
        case 'igor':
            method = 2;
            break;
        case 'multidirectional':
            method = 3;
            break;
        case 'standard':
        default:
            method = 0;
            break;
    }
    const illumination = layer.getIlluminationProperties();
    for (let i = 0; i < illumination.directionRadians.length; i++) {
        // modify azimuthal angle by map rotation if light is anchored at the viewport
        if (layer.paint.get('hillshade-illumination-anchor') === 'viewport') {
            illumination.directionRadians[i] += painter.transform.bearingInRadians;
        }
    }
    return {
        'u_image': 0,
        'u_latrange': getTileLatRange(painter, tile.tileID),
        'u_exaggeration': layer.paint.get('hillshade-exaggeration'),
        'u_altitudes': illumination.altitudeRadians,
        'u_azimuths': illumination.directionRadians,
        'u_accent': accent,
        'u_method': method,
        'u_highlights': illumination.highlightColor,
        'u_shadows': illumination.shadowColor
    };
};
const hillshadeUniformPrepareValues = (tileID, dem) => {
    const stride = dem.stride;
    const matrix = symbol_layout.create();
    // Flip rendering at y axis.
    symbol_layout.ortho(matrix, 0, symbol_layout.EXTENT, -symbol_layout.EXTENT, 0, 0, 1);
    symbol_layout.translate(matrix, matrix, [0, -symbol_layout.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 symbol_layout.MercatorCoordinate(0, y / tilesAtZoom).toLngLat().lat,
        new symbol_layout.MercatorCoordinate(0, (y + 1) / tilesAtZoom).toLngLat().lat
    ];
}

const colorReliefUniforms = (context, locations) => ({
    'u_image': new symbol_layout.Uniform1i(context, locations.u_image),
    'u_unpack': new symbol_layout.Uniform4f(context, locations.u_unpack),
    'u_dimension': new symbol_layout.Uniform2f(context, locations.u_dimension),
    'u_elevation_stops': new symbol_layout.Uniform1i(context, locations.u_elevation_stops),
    'u_color_stops': new symbol_layout.Uniform1i(context, locations.u_color_stops),
    'u_color_ramp_size': new symbol_layout.Uniform1i(context, locations.u_color_ramp_size),
    'u_opacity': new symbol_layout.Uniform1f(context, locations.u_opacity)
});
const colorReliefUniformValues = (layer, dem, colorRampSize = 0) => {
    return {
        'u_image': 0,
        'u_unpack': dem.getUnpackVector(),
        'u_dimension': [dem.stride, dem.stride],
        'u_elevation_stops': 1,
        'u_color_stops': 4,
        'u_color_ramp_size': colorRampSize,
        'u_opacity': layer.paint.get('color-relief-opacity')
    };
};

const lineUniforms = (context, locations) => ({
    'u_translation': new symbol_layout.Uniform2f(context, locations.u_translation),
    'u_ratio': new symbol_layout.Uniform1f(context, locations.u_ratio),
    'u_device_pixel_ratio': new symbol_layout.Uniform1f(context, locations.u_device_pixel_ratio),
    'u_units_to_pixels': new symbol_layout.Uniform2f(context, locations.u_units_to_pixels)
});
const lineGradientUniforms = (context, locations) => ({
    'u_translation': new symbol_layout.Uniform2f(context, locations.u_translation),
    'u_ratio': new symbol_layout.Uniform1f(context, locations.u_ratio),
    'u_device_pixel_ratio': new symbol_layout.Uniform1f(context, locations.u_device_pixel_ratio),
    'u_units_to_pixels': new symbol_layout.Uniform2f(context, locations.u_units_to_pixels),
    'u_image': new symbol_layout.Uniform1i(context, locations.u_image),
    'u_image_height': new symbol_layout.Uniform1f(context, locations.u_image_height)
});
const linePatternUniforms = (context, locations) => ({
    'u_translation': new symbol_layout.Uniform2f(context, locations.u_translation),
    'u_texsize': new symbol_layout.Uniform2f(context, locations.u_texsize),
    'u_ratio': new symbol_layout.Uniform1f(context, locations.u_ratio),
    'u_device_pixel_ratio': new symbol_layout.Uniform1f(context, locations.u_device_pixel_ratio),
    'u_image': new symbol_layout.Uniform1i(context, locations.u_image),
    'u_units_to_pixels': new symbol_layout.Uniform2f(context, locations.u_units_to_pixels),
    'u_scale': new symbol_layout.Uniform3f(context, locations.u_scale),
    'u_fade': new symbol_layout.Uniform1f(context, locations.u_fade)
});
const lineSDFUniforms = (context, locations) => ({
    'u_translation': new symbol_layout.Uniform2f(context, locations.u_translation),
    'u_ratio': new symbol_layout.Uniform1f(context, locations.u_ratio),
    'u_device_pixel_ratio': new symbol_layout.Uniform1f(context, locations.u_device_pixel_ratio),
    'u_units_to_pixels': new symbol_layout.Uniform2f(context, locations.u_units_to_pixels),
    'u_image': new symbol_layout.Uniform1i(context, locations.u_image),
    'u_mix': new symbol_layout.Uniform1f(context, locations.u_mix),
    'u_tileratio': new symbol_layout.Uniform1f(context, locations.u_tileratio),
    'u_crossfade_from': new symbol_layout.Uniform1f(context, locations.u_crossfade_from),
    'u_crossfade_to': new symbol_layout.Uniform1f(context, locations.u_crossfade_to),
    'u_lineatlas_width': new symbol_layout.Uniform1f(context, locations.u_lineatlas_width),
    'u_lineatlas_height': new symbol_layout.Uniform1f(context, locations.u_lineatlas_height)
});
const lineGradientSDFUniforms = (context, locations) => ({
    'u_translation': new symbol_layout.Uniform2f(context, locations.u_translation),
    'u_ratio': new symbol_layout.Uniform1f(context, locations.u_ratio),
    'u_device_pixel_ratio': new symbol_layout.Uniform1f(context, locations.u_device_pixel_ratio),
    'u_units_to_pixels': new symbol_layout.Uniform2f(context, locations.u_units_to_pixels),
    'u_image': new symbol_layout.Uniform1i(context, locations.u_image),
    'u_image_height': new symbol_layout.Uniform1f(context, locations.u_image_height),
    'u_tileratio': new symbol_layout.Uniform1f(context, locations.u_tileratio),
    'u_crossfade_from': new symbol_layout.Uniform1f(context, locations.u_crossfade_from),
    'u_crossfade_to': new symbol_layout.Uniform1f(context, locations.u_crossfade_to),
    'u_image_dash': new symbol_layout.Uniform1i(context, locations.u_image_dash),
    'u_mix': new symbol_layout.Uniform1f(context, locations.u_mix),
    'u_lineatlas_width': new symbol_layout.Uniform1f(context, locations.u_lineatlas_width),
    'u_lineatlas_height': new symbol_layout.Uniform1f(context, locations.u_lineatlas_height)
});
const lineUniformValues = (painter, tile, layer, ratioScale) => {
    const transform = painter.transform;
    return {
        'u_translation': calculateTranslation(painter, tile, layer),
        'u_ratio': ratioScale / symbol_layout.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, ratioScale, imageHeight) => {
    return symbol_layout.extend(lineUniformValues(painter, tile, layer, ratioScale), {
        'u_image': 0,
        'u_image_height': imageHeight,
    });
};
const linePatternUniformValues = (painter, tile, layer, ratioScale, crossfade) => {
    const transform = painter.transform;
    const tileZoomRatio = calculateTileRatio(tile, transform);
    return {
        'u_translation': calculateTranslation(painter, tile, layer),
        'u_texsize': tile.imageAtlasTexture.size,
        // camera zoom ratio
        'u_ratio': ratioScale / symbol_layout.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, ratioScale, crossfade) => {
    const transform = painter.transform;
    const tileRatio = calculateTileRatio(tile, transform);
    return symbol_layout.extend(lineUniformValues(painter, tile, layer, ratioScale), {
        'u_tileratio': tileRatio,
        'u_crossfade_from': crossfade.fromScale,
        'u_crossfade_to': crossfade.toScale,
        'u_image': 0,
        'u_mix': crossfade.t,
        'u_lineatlas_width': painter.lineAtlas.width,
        'u_lineatlas_height': painter.lineAtlas.height,
    });
};
const lineGradientSDFUniformValues = (painter, tile, layer, ratioScale, crossfade, imageHeight) => {
    const transform = painter.transform;
    const tileRatio = calculateTileRatio(tile, transform);
    return symbol_layout.extend(lineUniformValues(painter, tile, layer, ratioScale), {
        'u_image': 0,
        'u_image_height': imageHeight,
        'u_tileratio': tileRatio,
        'u_crossfade_from': crossfade.fromScale,
        'u_crossfade_to': crossfade.toScale,
        'u_image_dash': 1,
        'u_mix': crossfade.t,
        'u_lineatlas_width': painter.lineAtlas.width,
        'u_lineatlas_height': painter.lineAtlas.height,
    });
};
function calculateTileRatio(tile, transform) {
    return 1 / symbol_layout.pixelsToTileUnits(tile, 1, transform.tileZoom);
}
function calculateTranslation(painter, tile, layer) {
    // Translate line points prior to any transformation
    return symbol_layout.translatePosition(painter.transform, tile, layer.paint.get('line-translate'), layer.paint.get('line-translate-anchor'));
}

const rasterUniforms = (context, locations) => ({
    'u_tl_parent': new symbol_layout.Uniform2f(context, locations.u_tl_parent),
    'u_scale_parent': new symbol_layout.Uniform1f(context, locations.u_scale_parent),
    'u_buffer_scale': new symbol_layout.Uniform1f(context, locations.u_buffer_scale),
    'u_fade_t': new symbol_layout.Uniform1f(context, locations.u_fade_t),
    'u_opacity': new symbol_layout.Uniform1f(context, locations.u_opacity),
    'u_image0': new symbol_layout.Uniform1i(context, locations.u_image0),
    'u_image1': new symbol_layout.Uniform1i(context, locations.u_image1),
    'u_brightness_low': new symbol_layout.Uniform1f(context, locations.u_brightness_low),
    'u_brightness_high': new symbol_layout.Uniform1f(context, locations.u_brightness_high),
    'u_saturation_factor': new symbol_layout.Uniform1f(context, locations.u_saturation_factor),
    'u_contrast_factor': new symbol_layout.Uniform1f(context, locations.u_contrast_factor),
    'u_spin_weights': new symbol_layout.Uniform3f(context, locations.u_spin_weights),
    'u_coords_top': new symbol_layout.Uniform4f(context, locations.u_coords_top),
    'u_coords_bottom': new symbol_layout.Uniform4f(context, locations.u_coords_bottom)
});
const rasterUniformValues = (parentTL, parentScaleBy, fade, layer, cornerCoords) => ({
    'u_tl_parent': parentTL,
    'u_scale_parent': parentScaleBy,
    // If u_buffer_scale is ever something else than a constant 1,
    // the north/south pole handling in the vertex shader might need modification
    // so that the texture coordinares for poles always lie beyond the edge of the texture.
    // Right now the coordinates are placed right at the texture border.
    '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')),
    'u_coords_top': [cornerCoords[0].x, cornerCoords[0].y, cornerCoords[1].x, cornerCoords[1].y],
    'u_coords_bottom': [cornerCoords[3].x, cornerCoords[3].y, cornerCoords[2].x, cornerCoords[2].y]
});
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 symbol_layout.Uniform1i(context, locations.u_is_size_zoom_constant),
    'u_is_size_feature_constant': new symbol_layout.Uniform1i(context, locations.u_is_size_feature_constant),
    'u_size_t': new symbol_layout.Uniform1f(context, locations.u_size_t),
    'u_size': new symbol_layout.Uniform1f(context, locations.u_size),
    'u_camera_to_center_distance': new symbol_layout.Uniform1f(context, locations.u_camera_to_center_distance),
    'u_pitch': new symbol_layout.Uniform1f(context, locations.u_pitch),
    'u_rotate_symbol': new symbol_layout.Uniform1i(context, locations.u_rotate_symbol),
    'u_aspect_ratio': new symbol_layout.Uniform1f(context, locations.u_aspect_ratio),
    'u_fade_change': new symbol_layout.Uniform1f(context, locations.u_fade_change),
    'u_label_plane_matrix': new symbol_layout.UniformMatrix4f(context, locations.u_label_plane_matrix),
    'u_coord_matrix': new symbol_layout.UniformMatrix4f(context, locations.u_coord_matrix),
    'u_is_text': new symbol_layout.Uniform1i(context, locations.u_is_text),
    'u_pitch_with_map': new symbol_layout.Uniform1i(context, locations.u_pitch_with_map),
    'u_is_along_line': new symbol_layout.Uniform1i(context, locations.u_is_along_line),
    'u_is_variable_anchor': new symbol_layout.Uniform1i(context, locations.u_is_variable_anchor),
    'u_texsize': new symbol_layout.Uniform2f(context, locations.u_texsize),
    'u_texture': new symbol_layout.Uniform1i(context, locations.u_texture),
    'u_translation': new symbol_layout.Uniform2f(context, locations.u_translation),
    'u_pitched_scale': new symbol_layout.Uniform1f(context, locations.u_pitched_scale),
});
const symbolSDFUniforms = (context, locations) => ({
    'u_is_size_zoom_constant': new symbol_layout.Uniform1i(context, locations.u_is_size_zoom_constant),
    'u_is_size_feature_constant': new symbol_layout.Uniform1i(context, locations.u_is_size_feature_constant),
    'u_size_t': new symbol_layout.Uniform1f(context, locations.u_size_t),
    'u_size': new symbol_layout.Uniform1f(context, locations.u_size),
    'u_camera_to_center_distance': new symbol_layout.Uniform1f(context, locations.u_camera_to_center_distance),
    'u_pitch': new symbol_layout.Uniform1f(context, locations.u_pitch),
    'u_rotate_symbol': new symbol_layout.Uniform1i(context, locations.u_rotate_symbol),
    'u_aspect_ratio': new symbol_layout.Uniform1f(context, locations.u_aspect_ratio),
    'u_fade_change': new symbol_layout.Uniform1f(context, locations.u_fade_change),
    'u_label_plane_matrix': new symbol_layout.UniformMatrix4f(context, locations.u_label_plane_matrix),
    'u_coord_matrix': new symbol_layout.UniformMatrix4f(context, locations.u_coord_matrix),
    'u_is_text': new symbol_layout.Uniform1i(context, locations.u_is_text),
    'u_pitch_with_map': new symbol_layout.Uniform1i(context, locations.u_pitch_with_map),
    'u_is_along_line': new symbol_layout.Uniform1i(context, locations.u_is_along_line),
    'u_is_variable_anchor': new symbol_layout.Uniform1i(context, locations.u_is_variable_anchor),
    'u_texsize': new symbol_layout.Uniform2f(context, locations.u_texsize),
    'u_texture': new symbol_layout.Uniform1i(context, locations.u_texture),
    'u_gamma_scale': new symbol_layout.Uniform1f(context, locations.u_gamma_scale),
    'u_device_pixel_ratio': new symbol_layout.Uniform1f(context, locations.u_device_pixel_ratio),
    'u_is_halo': new symbol_layout.Uniform1i(context, locations.u_is_halo),
    'u_translation': new symbol_layout.Uniform2f(context, locations.u_translation),
    'u_pitched_scale': new symbol_layout.Uniform1f(context, locations.u_pitched_scale),
});
const symbolTextAndIconUniforms = (context, locations) => ({
    'u_is_size_zoom_constant': new symbol_layout.Uniform1i(context, locations.u_is_size_zoom_constant),
    'u_is_size_feature_constant': new symbol_layout.Uniform1i(context, locations.u_is_size_feature_constant),
    'u_size_t': new symbol_layout.Uniform1f(context, locations.u_size_t),
    'u_size': new symbol_layout.Uniform1f(context, locations.u_size),
    'u_camera_to_center_distance': new symbol_layout.Uniform1f(context, locations.u_camera_to_center_distance),
    'u_pitch': new symbol_layout.Uniform1f(context, locations.u_pitch),
    'u_rotate_symbol': new symbol_layout.Uniform1i(context, locations.u_rotate_symbol),
    'u_aspect_ratio': new symbol_layout.Uniform1f(context, locations.u_aspect_ratio),
    'u_fade_change': new symbol_layout.Uniform1f(context, locations.u_fade_change),
    'u_label_plane_matrix': new symbol_layout.UniformMatrix4f(context, locations.u_label_plane_matrix),
    'u_coord_matrix': new symbol_layout.UniformMatrix4f(context, locations.u_coord_matrix),
    'u_is_text': new symbol_layout.Uniform1i(context, locations.u_is_text),
    'u_pitch_with_map': new symbol_layout.Uniform1i(context, locations.u_pitch_with_map),
    'u_is_along_line': new symbol_layout.Uniform1i(context, locations.u_is_along_line),
    'u_is_variable_anchor': new symbol_layout.Uniform1i(context, locations.u_is_variable_anchor),
    'u_texsize': new symbol_layout.Uniform2f(context, locations.u_texsize),
    'u_texsize_icon': new symbol_layout.Uniform2f(context, locations.u_texsize_icon),
    'u_texture': new symbol_layout.Uniform1i(context, locations.u_texture),
    'u_texture_icon': new symbol_layout.Uniform1i(context, locations.u_texture_icon),
    'u_gamma_scale': new symbol_layout.Uniform1f(context, locations.u_gamma_scale),
    'u_device_pixel_ratio': new symbol_layout.Uniform1f(context, locations.u_device_pixel_ratio),
    'u_is_halo': new symbol_layout.Uniform1i(context, locations.u_is_halo),
    'u_translation': new symbol_layout.Uniform2f(context, locations.u_translation),
    'u_pitched_scale': new symbol_layout.Uniform1f(context, locations.u_pitched_scale),
});
const symbolIconUniformValues = (functionType, size, rotateInShader, pitchWithMap, isAlongLine, isVariableAnchor, painter, 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_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, labelPlaneMatrix, glCoordMatrix, translation, isText, texSize, isHalo, pitchedScale) => {
    const transform = painter.transform;
    return symbol_layout.extend(symbolIconUniformValues(functionType, size, rotateInShader, pitchWithMap, isAlongLine, isVariableAnchor, painter, labelPlaneMatrix, glCoordMatrix, translation, isText, texSize, pitchedScale), {
        'u_gamma_scale': (pitchWithMap ? Math.cos(transform.pitch * Math.PI / 180.0) * transform.cameraToCenterDistance : 1),
        'u_device_pixel_ratio': painter.pixelRatio,
        'u_is_halo': +isHalo
    });
};
const symbolTextAndIconUniformValues = (functionType, size, rotateInShader, pitchWithMap, isAlongLine, isVariableAnchor, painter, labelPlaneMatrix, glCoordMatrix, translation, texSizeSDF, texSizeIcon, pitchedScale) => {
    return symbol_layout.extend(symbolSDFUniformValues(functionType, size, rotateInShader, pitchWithMap, isAlongLine, isVariableAnchor, painter, labelPlaneMatrix, glCoordMatrix, translation, true, texSizeSDF, true, pitchedScale), {
        'u_texsize_icon': texSizeIcon,
        'u_texture_icon': 1
    });
};

const backgroundUniforms = (context, locations) => ({
    'u_opacity': new symbol_layout.Uniform1f(context, locations.u_opacity),
    'u_color': new symbol_layout.UniformColor(context, locations.u_color)
});
const backgroundPatternUniforms = (context, locations) => ({
    'u_opacity': new symbol_layout.Uniform1f(context, locations.u_opacity),
    'u_image': new symbol_layout.Uniform1i(context, locations.u_image),
    'u_pattern_tl_a': new symbol_layout.Uniform2f(context, locations.u_pattern_tl_a),
    'u_pattern_br_a': new symbol_layout.Uniform2f(context, locations.u_pattern_br_a),
    'u_pattern_tl_b': new symbol_layout.Uniform2f(context, locations.u_pattern_tl_b),
    'u_pattern_br_b': new symbol_layout.Uniform2f(context, locations.u_pattern_br_b),
    'u_texsize': new symbol_layout.Uniform2f(context, locations.u_texsize),
    'u_mix': new symbol_layout.Uniform1f(context, locations.u_mix),
    'u_pattern_size_a': new symbol_layout.Uniform2f(context, locations.u_pattern_size_a),
    'u_pattern_size_b': new symbol_layout.Uniform2f(context, locations.u_pattern_size_b),
    'u_scale_a': new symbol_layout.Uniform1f(context, locations.u_scale_a),
    'u_scale_b': new symbol_layout.Uniform1f(context, locations.u_scale_b),
    'u_pixel_coord_upper': new symbol_layout.Uniform2f(context, locations.u_pixel_coord_upper),
    'u_pixel_coord_lower': new symbol_layout.Uniform2f(context, locations.u_pixel_coord_lower),
    'u_tile_units_to_pixels': new symbol_layout.Uniform1f(context, locations.u_tile_units_to_pixels)
});
const backgroundUniformValues = (opacity, color) => ({
    'u_opacity': opacity,
    'u_color': color
});
const backgroundPatternUniformValues = (opacity, painter, image, tile, crossfade) => symbol_layout.extend(bgPatternUniformValues(image, crossfade, painter, tile), {
    'u_opacity': opacity
});

const atmosphereUniforms = (context, locations) => ({
    'u_sun_pos': new symbol_layout.Uniform3f(context, locations.u_sun_pos),
    'u_atmosphere_blend': new symbol_layout.Uniform1f(context, locations.u_atmosphere_blend),
    'u_globe_position': new symbol_layout.Uniform3f(context, locations.u_globe_position),
    'u_globe_radius': new symbol_layout.Uniform1f(context, locations.u_globe_radius),
    'u_inv_proj_matrix': new symbol_layout.UniformMatrix4f(context, locations.u_inv_proj_matrix),
});
const atmosphereUniformValues = (sunPos, atmosphereBlend, globePosition, globeRadius, invProjMatrix) => ({
    'u_sun_pos': sunPos,
    'u_atmosphere_blend': atmosphereBlend,
    'u_globe_position': globePosition,
    'u_globe_radius': globeRadius,
    'u_inv_proj_matrix': invProjMatrix,
});

const skyUniforms = (context, locations) => ({
    'u_sky_color': new symbol_layout.UniformColor(context, locations.u_sky_color),
    'u_horizon_color': new symbol_layout.UniformColor(context, locations.u_horizon_color),
    'u_horizon': new symbol_layout.Uniform2f(context, locations.u_horizon),
    'u_horizon_normal': new symbol_layout.Uniform2f(context, locations.u_horizon_normal),
    'u_sky_horizon_blend': new symbol_layout.Uniform1f(context, locations.u_sky_horizon_blend),
    'u_sky_blend': new symbol_layout.Uniform1f(context, locations.u_sky_blend),
});
const skyUniformValues = (sky, transform, pixelRatio) => {
    const cosRoll = Math.cos(transform.rollInRadians);
    const sinRoll = Math.sin(transform.rollInRadians);
    const mercatorHorizon = getMercatorHorizon(transform);
    const projectionData = transform.getProjectionData({ overscaledTileID: null, applyGlobeMatrix: true, applyTerrainMatrix: true });
    const skyBlend = projectionData.projectionTransition;
    return {
        'u_sky_color': sky.properties.get('sky-color'),
        'u_horizon_color': sky.properties.get('horizon-color'),
        'u_horizon': [(transform.width / 2 - mercatorHorizon * sinRoll) * pixelRatio,
            (transform.height / 2 + mercatorHorizon * cosRoll) * pixelRatio],
        'u_horizon_normal': [-sinRoll, cosRoll],
        'u_sky_horizon_blend': (sky.properties.get('sky-horizon-blend') * transform.height / 2) * pixelRatio,
        'u_sky_blend': skyBlend,
    };
};

const emptyUniforms = (_, __) => { };
const programUniforms = {
    fillExtrusion: fillExtrusionUniforms,
    fillExtrusionPattern: fillExtrusionPatternUniforms,
    fill: fillUniforms,
    fillPattern: fillPatternUniforms,
    fillOutline: fillOutlineUniforms,
    fillOutlinePattern: fillOutlinePatternUniforms,
    circle: circleUniforms,
    collisionBox: collisionUniforms,
    collisionCircle: collisionCircleUniforms,
    debug: debugUniforms,
    depth: emptyUniforms,
    clippingMask: emptyUniforms,
    heatmap: heatmapUniforms,
    heatmapTexture: heatmapTextureUniforms,
    hillshade: hillshadeUniforms,
    hillshadePrepare: hillshadePrepareUniforms,
    colorRelief: colorReliefUniforms,
    line: lineUniforms,
    lineGradient: lineGradientUniforms,
    linePattern: linePatternUniforms,
    lineSDF: lineSDFUniforms,
    lineGradientSDF: lineGradientSDFUniforms,
    raster: rasterUniforms,
    symbolIcon: symbolIconUniforms,
    symbolSDF: symbolSDFUniforms,
    symbolTextAndIcon: symbolTextAndIconUniforms,
    background: backgroundUniforms,
    backgroundPattern: backgroundPatternUniforms,
    terrain: terrainUniforms,
    terrainDepth: terrainDepthUniforms,
    terrainCoords: terrainCoordsUniforms,
    projectionErrorMeasurement: projectionErrorMeasurementUniforms,
    atmosphere: atmosphereUniforms,
    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) {
            array.freeBufferAfterUpload();
        }
    }
    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) {
            array.freeBufferAfterUpload();
        }
    }
    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 (const member of this.attributes) {
            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 (const member of this.attributes) {
            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;
        }
    }
}

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 symbol_layout.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 symbol_layout.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;
    }
}

/**
 * Error message to use when framebuffer is incomplete
 */
const FRAMEBUFFER_NOT_COMPLETE_ERROR = 'Framebuffer is not complete';
/**
 * Check if an error is a framebuffer not complete error
 * @param error - An error object
 * @returns - true if the error is a framebuffer not complete error
 */
function isFramebufferNotCompleteError(error) {
    return error.message === FRAMEBUFFER_NOT_COMPLETE_ERROR;
}
/**
 * Use this when you need to create a framebuffer not complete error.
 * @returns An error object with the message "Framebuffer is not complete"
 */
function createFramebufferNotCompleteError() {
    return new Error(FRAMEBUFFER_NOT_COMPLETE_ERROR);
}

/**
 * @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 createFramebufferNotCompleteError();
        }
    }
    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);
    }
}

/**
 * @internal
 * A webgl wrapper class to allow injection, mocking and abstraction
 */
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');
        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 (symbol_layout.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)) {
            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);
    }
}

let quadTriangles;
function drawCollisionDebug(painter, tileManager, layer, coords, isText) {
    var _a, _b;
    const context = painter.context;
    const transform = painter.transform;
    const gl = context.gl;
    const program = painter.useProgram('collisionBox');
    const tileBatches = [];
    let circleCount = 0;
    let circleOffset = 0;
    for (const coord of coords) {
        const tile = tileManager.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) {
            tileBatches.push({
                circleArray,
                circleOffset,
                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), (_a = painter.style.map.terrain) === null || _a === void 0 ? void 0 : _a.getTerrainData(coord), transform.getProjectionData({ overscaledTileID: coord, applyGlobeMatrix: true, applyTerrainMatrix: true }), 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 symbol_layout.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, symbol_layout.collisionCircleLayout.members, true);
    // Render batches
    for (const batch of tileBatches) {
        const uniforms = collisionCircleUniformValues(painter.transform);
        circleProgram.draw(context, gl.TRIANGLES, DepthMode.disabled, StencilMode.disabled, painter.colorModeForRenderPass(), CullFaceMode.disabled, uniforms, (_b = painter.style.map.terrain) === null || _b === void 0 ? void 0 : _b.getTerrainData(batch.coord), null, layer.id, vertexBuffer, indexBuffer, symbol_layout.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 symbol_layout.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 = symbol_layout.identity(new Float32Array(16));
function drawSymbols(painter, tileManager, layer, coords, variableOffsets, renderOptions) {
    if (painter.renderPass !== 'translucent')
        return;
    const { isRenderingToTexture } = renderOptions;
    // 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, tileManager, 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, tileManager, 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, isRenderingToTexture);
    }
    if (layer.paint.get('text-opacity').constantOr(1) !== 0) {
        drawLayerSymbols(painter, tileManager, 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, isRenderingToTexture);
    }
    if (tileManager.map.showCollisionBoxes) {
        drawCollisionDebug(painter, tileManager, layer, coords, true);
        drawCollisionDebug(painter, tileManager, layer, coords, false);
    }
}
function calculateVariableRenderShift(anchor, width, height, textOffset, textBoxScale, renderTextSize) {
    const { horizontalAlign, verticalAlign } = symbol_layout.getAnchorAlignment(anchor);
    const shiftX = -(horizontalAlign - 0.5) * width;
    const shiftY = -(verticalAlign - 0.5) * height;
    return new symbol_layout.Point((shiftX / textBoxScale + textOffset[0]) * renderTextSize, (shiftY / textBoxScale + textOffset[1]) * renderTextSize);
}
function updateVariableAnchors(coords, painter, layer, tileManager, rotationAlignment, pitchAlignment, translate, translateAnchor, variableOffsets) {
    var _a;
    const transform = painter.transform;
    const terrain = painter.style.map.terrain;
    const rotateWithMap = rotationAlignment === 'map';
    const pitchWithMap = pitchAlignment === 'map';
    for (const coord of coords) {
        const tile = tileManager.getTile(coord);
        const bucket = tile.getBucket(layer);
        if (!((_a = bucket === null || bucket === void 0 ? void 0 : bucket.text) === null || _a === void 0 ? void 0 : _a.segments.get().length))
            continue;
        const sizeData = bucket.textSizeData;
        const size = symbol_layout.evaluateSizeForZoom(sizeData, transform.zoom);
        const pixelToTileScale = symbol_layout.pixelsToTileUnits(tile, 1, painter.transform.zoom);
        const pitchedLabelPlaneMatrix = getPitchedLabelPlaneMatrix(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 = terrain ? (x, y) => terrain.getElevation(coord, x, y) : null;
            const translation = symbol_layout.translatePosition(transform, tile, translate, translateAnchor);
            updateVariableAnchorsForBucket(bucket, rotateWithMap, pitchWithMap, variableOffsets, transform, pitchedLabelPlaneMatrix, tileScale, size, updateTextFitIcon, 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 symbol_layout.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 projectWithMatrix(tileAnchorShifted.x, tileAnchorShifted.y, projectionContext.pitchedLabelPlaneMatrix, 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.
            // Note that the label plane must be screen pixels here.
            const projectedAnchorRight = projectTileCoordinatesToLabelPlane(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, pitchedLabelPlaneMatrix, tileScale, size, updateTextFitIcon, 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 symbol_layout.Point(symbol.anchorX, symbol.anchorY);
            const projectionContext = {
                getElevation,
                width: transform.width,
                height: transform.height,
                pitchedLabelPlaneMatrix,
                lineVertexArray: null,
                pitchWithMap,
                transform,
                projectionCache: null,
                tileAnchorPoint: tileAnchor,
                translation,
                unwrappedTileID
            };
            const projectedAnchor = pitchWithMap ?
                projectTileCoordinatesToClipSpace(tileAnchor.x, tileAnchor.y, projectionContext) :
                projectTileCoordinatesToLabelPlane(tileAnchor.x, tileAnchor.y, projectionContext);
            const perspectiveRatio = getPerspectiveRatio(transform.cameraToCenterDistance, projectedAnchor.signedDistanceFromCamera);
            let renderTextSize = symbol_layout.evaluateSizeForFeature(bucket.textSizeData, size, symbol) * perspectiveRatio / symbol_layout.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 = transform.getPitchedTextCorrection(tileAnchor.x + translation[0], tileAnchor.y + translation[1], unwrappedTileID);
            const shiftedAnchor = getShiftedAnchor(projectedAnchor.point, projectionContext, rotateWithMap, shift, -transform.bearingInRadians, pitchedTextCorrection);
            const angle = (bucket.allowVerticalPlacement && symbol.placedOrientation === symbol_layout.WritingMode.vertical) ? Math.PI / 2 : 0;
            for (let g = 0; g < symbol.numGlyphs; g++) {
                symbol_layout.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++) {
                        symbol_layout.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, tileManager, layer, coords, isText, translate, translateAnchor, rotationAlignment, pitchAlignment, keepUpright, stencilMode, colorMode, isRenderingToTexture) {
    var _a;
    const context = painter.context;
    const gl = context.gl;
    const transform = painter.transform;
    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 pitchedLabelPlaneMatrix projection
    // Unpitched point labels need to have their rotation applied after projection
    const rotateInShader = rotateWithMap && !pitchWithMap && !alongLine;
    const hasSortKey = !layer.layout.get('symbol-sort-key').isConstant();
    let sortFeaturesByKey = false;
    const depthMode = painter.getDepthModeForSublayer(0, DepthMode.ReadOnly);
    const hasVariablePlacement = layer._unevaluatedLayout.hasValue('text-variable-anchor') || layer._unevaluatedLayout.hasValue('text-variable-anchor-offset');
    const tileRenderState = [];
    const pitchedTextRescaling = transform.getCircleRadiusCorrection();
    for (const coord of coords) {
        const tile = tileManager.getTile(coord);
        const bucket = tile.getBucket(layer);
        if (!bucket)
            continue;
        const buffers = isText ? bucket.text : bucket.icon;
        if (!(buffers === null || buffers === void 0 ? void 0 : 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 || transform.pitch !== 0;
        const program = painter.useProgram(getSymbolProgramName(isSDF, isText, bucket), programConfiguration);
        const size = symbol_layout.evaluateSizeForZoom(sizeData, transform.zoom);
        const terrainData = (_a = painter.style.map.terrain) === null || _a === void 0 ? void 0 : _a.getTerrainData(coord);
        let texSize;
        let texSizeIcon = [0, 0];
        let atlasTexture;
        let atlasInterpolation;
        let atlasTextureIcon = null;
        let atlasInterpolationIcon;
        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;
            atlasInterpolation = isSDF || painter.options.rotating || painter.options.zooming || iconScaled || transformed ?
                gl.LINEAR :
                gl.NEAREST;
            texSize = tile.imageAtlasTexture.size;
        }
        // See the comment at the beginning of src/symbol/projection.ts for an overview of the symbol projection process
        const s = symbol_layout.pixelsToTileUnits(tile, 1, painter.transform.zoom);
        const pitchedLabelPlaneMatrix = getPitchedLabelPlaneMatrix(rotateWithMap, painter.transform, s);
        const pitchedLabelPlaneMatrixInverse = symbol_layout.create();
        symbol_layout.invert$1(pitchedLabelPlaneMatrixInverse, pitchedLabelPlaneMatrix);
        const glCoordMatrixForShader = getGlCoordMatrix(pitchWithMap, rotateWithMap, painter.transform, s);
        const translation = symbol_layout.translatePosition(transform, tile, translate, translateAnchor);
        const projectionData = transform.getProjectionData({ overscaledTileID: coord, applyGlobeMatrix: !isRenderingToTexture, applyTerrainMatrix: true });
        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, painter, isText, pitchedLabelPlaneMatrix, pitchedLabelPlaneMatrixInverse, pitchWithMap, keepUpright, rotateToLine, coord.toUnwrapped(), transform.width, transform.height, translation, getElevation);
        }
        const shaderVariableAnchor = (isText && hasVariablePlacement) || updateTextFitIcon;
        // If the label plane matrix is used, it transforms either map-pitch-aligned pixels, or to screenspace pixels
        const combinedLabelPlaneMatrix = pitchWithMap ? pitchedLabelPlaneMatrix : painter.transform.clipSpaceToPixelsMatrix;
        // Label plane matrix is unused in the shader if variable anchors are used or the text is placed along a line
        const noLabelPlane = (alongLine || shaderVariableAnchor);
        const uLabelPlaneMatrix = noLabelPlane ? identityMat4 : combinedLabelPlaneMatrix;
        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, uLabelPlaneMatrix, glCoordMatrixForShader, translation, isText, texSize, true, pitchedTextRescaling);
            }
            else {
                uniformValues = symbolTextAndIconUniformValues(sizeData.kind, size, rotateInShader, pitchWithMap, alongLine, shaderVariableAnchor, painter, uLabelPlaneMatrix, glCoordMatrixForShader, translation, texSize, texSizeIcon, pitchedTextRescaling);
            }
        }
        else {
            uniformValues = symbolIconUniformValues(sizeData.kind, size, rotateInShader, pitchWithMap, alongLine, shaderVariableAnchor, painter, uLabelPlaneMatrix, glCoordMatrixForShader, translation, isText, texSize, pitchedTextRescaling);
        }
        const state = {
            program,
            buffers,
            uniformValues,
            projectionData,
            atlasTexture,
            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 symbol_layout.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) {
            context.activeTexture.set(gl.TEXTURE1);
            if (state.atlasTextureIcon) {
                state.atlasTextureIcon.bind(state.atlasInterpolationIcon, 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, state.projectionData, segmentState.terrainData);
            }
            uniformValues['u_is_halo'] = 0;
        }
        drawSymbolElements(state.buffers, segmentState.segments, layer, painter, state.program, depthMode, stencilMode, colorMode, state.uniformValues, state.projectionData, segmentState.terrainData);
    }
}
function drawSymbolElements(buffers, segments, layer, painter, program, depthMode, stencilMode, colorMode, uniformValues, projectionData, terrainData) {
    const context = painter.context;
    const gl = context.gl;
    program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.backCCW, uniformValues, terrainData, projectionData, layer.id, buffers.layoutVertexBuffer, buffers.indexBuffer, segments, layer.paint, painter.transform.zoom, buffers.programConfigurations.get(layer.id), buffers.dynamicLayoutVertexBuffer, buffers.opacityVertexBuffer);
}

function drawCircles(painter, tileManager, layer, coords, renderOptions) {
    var _a;
    if (painter.renderPass !== 'translucent')
        return;
    const { isRenderingToTexture } = renderOptions;
    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 transform = painter.transform;
    const depthMode = painter.getDepthModeForSublayer(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 = [];
    // Note: due to how the shader is written, this value only has effect when globe rendering is enabled and `circle-pitch-alignment` is set to 'map'.
    const radiusCorrectionFactor = transform.getCircleRadiusCorrection();
    for (const coord of coords) {
        const tile = tileManager.getTile(coord);
        const bucket = tile.getBucket(layer);
        if (!bucket)
            continue;
        const styleTranslate = layer.paint.get('circle-translate');
        const styleTranslateAnchor = layer.paint.get('circle-translate-anchor');
        const translateForUniforms = symbol_layout.translatePosition(transform, tile, styleTranslate, styleTranslateAnchor);
        const programConfiguration = bucket.programConfigurations.get(layer.id);
        const program = painter.useProgram('circle', programConfiguration);
        const layoutVertexBuffer = bucket.layoutVertexBuffer;
        const indexBuffer = bucket.indexBuffer;
        const terrainData = (_a = painter.style.map.terrain) === null || _a === void 0 ? void 0 : _a.getTerrainData(coord);
        const uniformValues = circleUniformValues(painter, tile, layer, translateForUniforms, radiusCorrectionFactor);
        const projectionData = transform.getProjectionData({ overscaledTileID: coord, applyGlobeMatrix: !isRenderingToTexture, applyTerrainMatrix: true });
        const state = {
            programConfiguration,
            program,
            layoutVertexBuffer,
            indexBuffer,
            uniformValues,
            terrainData,
            projectionData
        };
        if (sortFeaturesByKey) {
            const oldSegments = bucket.segments.get();
            for (const segment of oldSegments) {
                segmentsRenderStates.push({
                    segments: new symbol_layout.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, projectionData } = segmentsState.state;
        const segments = segmentsState.segments;
        program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.backCCW, uniformValues, terrainData, projectionData, layer.id, layoutVertexBuffer, indexBuffer, segments, layer.paint, painter.transform.zoom, programConfiguration);
    }
}

function drawHeatmap(painter, tileManager, layer, tileIDs, renderOptions) {
    if (layer.paint.get('heatmap-opacity') === 0) {
        return;
    }
    const context = painter.context;
    const { isRenderingToTexture, isRenderingGlobe } = renderOptions;
    if (painter.style.map.terrain) {
        for (const coord of tileIDs) {
            const tile = tileManager.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 (tileManager.hasRenderableParent(coord))
                continue;
            if (painter.renderPass === 'offscreen') {
                prepareHeatmapTerrain(painter, tile, layer, coord, isRenderingGlobe);
            }
            else if (painter.renderPass === 'translucent') {
                renderHeatmapTerrain(painter, layer, coord, isRenderingToTexture, isRenderingGlobe);
            }
        }
        context.viewport.set([0, 0, painter.width, painter.height]);
    }
    else {
        if (painter.renderPass === 'offscreen') {
            prepareHeatmapFlat(painter, tileManager, layer, tileIDs);
        }
        else if (painter.renderPass === 'translucent') {
            renderHeatmapFlat(painter, layer);
        }
    }
}
function prepareHeatmapFlat(painter, tileManager, layer, coords) {
    const context = painter.context;
    const gl = context.gl;
    const transform = painter.transform;
    // 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], symbol_layout.Color.transparent, [true, true, true, true]);
    bindFramebuffer(context, painter, layer);
    context.clear({ color: symbol_layout.Color.transparent });
    for (const coord of coords) {
        // 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 (tileManager.hasRenderableParent(coord))
            continue;
        const tile = tileManager.getTile(coord);
        const bucket = tile.getBucket(layer);
        if (!bucket)
            continue;
        const programConfiguration = bucket.programConfigurations.get(layer.id);
        const program = painter.useProgram('heatmap', programConfiguration);
        const projectionData = transform.getProjectionData({ overscaledTileID: coord, applyGlobeMatrix: true, applyTerrainMatrix: false });
        const radiusCorrectionFactor = transform.getCircleRadiusCorrection();
        program.draw(context, gl.TRIANGLES, DepthMode.disabled, stencilMode, colorMode, CullFaceMode.backCCW, heatmapUniformValues(tile, transform.zoom, layer.paint.get('heatmap-intensity'), radiusCorrectionFactor), null, projectionData, layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer, bucket.segments, layer.paint, 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(symbol_layout.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, null, layer.id, painter.viewportBuffer, painter.quadTriangleIndexBuffer, painter.viewportSegments, layer.paint, painter.transform.zoom);
}
function prepareHeatmapTerrain(painter, tile, layer, coord, isRenderingGlobe) {
    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], symbol_layout.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: symbol_layout.Color.transparent });
    const programConfiguration = bucket.programConfigurations.get(layer.id);
    const program = painter.useProgram('heatmap', programConfiguration, !isRenderingGlobe);
    const projectionData = painter.transform.getProjectionData({ overscaledTileID: tile.tileID, applyGlobeMatrix: true, applyTerrainMatrix: true });
    const terrainData = painter.style.map.terrain.getTerrainData(coord);
    program.draw(context, gl.TRIANGLES, DepthMode.disabled, stencilMode, colorMode, CullFaceMode.disabled, heatmapUniformValues(tile, painter.transform.zoom, layer.paint.get('heatmap-intensity'), 1.0), terrainData, projectionData, layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer, bucket.segments, layer.paint, painter.transform.zoom, programConfiguration);
}
function renderHeatmapTerrain(painter, layer, coord, isRenderingToTexture, isRenderingGlobe) {
    const context = painter.context;
    const gl = context.gl;
    const transform = painter.transform;
    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);
    const projectionData = transform.getProjectionData({ overscaledTileID: coord, applyTerrainMatrix: isRenderingGlobe, applyGlobeMatrix: !isRenderingToTexture });
    painter.useProgram('heatmapTexture').draw(context, gl.TRIANGLES, DepthMode.disabled, StencilMode.disabled, painter.colorModeForRenderPass(), CullFaceMode.disabled, heatmapTextureUniformValues(painter, layer, 0, 1), null, projectionData, layer.id, painter.rasterBoundsBuffer, painter.quadTriangleIndexBuffer, painter.rasterBoundsSegments, layer.paint, 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(symbol_layout.HEATMAP_FULL_RENDER_FBO_KEY);
    if (!fbo) {
        fbo = createHeatmapFbo(context, painter.width / 4, painter.height / 4);
        layer.heatmapFbos.set(symbol_layout.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 symbol_layout.Texture(context, layer.colorRamp, context.gl.RGBA);
    }
    return layer.colorRampTexture;
}

function updateGradientTexture(painter, tileManager, context, gl, layer, bucket, coord, layerGradient) {
    let textureResolution = 256;
    if (layer.stepInterpolant) {
        const sourceMaxZoom = tileManager.getSource().maxzoom;
        const potentialOverzoom = coord.canonical.z === sourceMaxZoom ?
            Math.ceil(1 << (painter.transform.maxZoom - coord.canonical.z)) : 1;
        const lineLength = bucket.maxLineLength / symbol_layout.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 = symbol_layout.clamp(symbol_layout.nextPowerOfTwo(maxTextureCoverage), 256, context.maxTextureSize);
    }
    layerGradient.gradient = symbol_layout.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 symbol_layout.Texture(context, layerGradient.gradient, gl.RGBA);
    }
    layerGradient.version = layer.gradientVersion;
    return layerGradient.texture;
}
function bindImagePatternTextures(context, gl, tile, programConfiguration, crossfade) {
    context.activeTexture.set(gl.TEXTURE0);
    tile.imageAtlasTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
    programConfiguration.updatePaintBuffers(crossfade);
}
function bindDasharrayTextures(painter, context, gl, programConfiguration, programChanged, crossfade) {
    if (programChanged || painter.lineAtlas.dirty) {
        context.activeTexture.set(gl.TEXTURE0);
        painter.lineAtlas.bind(context);
    }
    programConfiguration.updatePaintBuffers(crossfade);
}
function bindGradientTextures(painter, tileManager, context, gl, layer, bucket, coord) {
    const layerGradient = bucket.gradients[layer.id];
    let gradientTexture = layerGradient.texture;
    if (layer.gradientVersion !== layerGradient.version) {
        gradientTexture = updateGradientTexture(painter, tileManager, context, gl, layer, bucket, coord, layerGradient);
    }
    context.activeTexture.set(gl.TEXTURE0);
    gradientTexture.bind(layer.stepInterpolant ? gl.NEAREST : gl.LINEAR, gl.CLAMP_TO_EDGE);
}
function bindGradientAndDashTextures(painter, tileManager, context, gl, layer, bucket, coord, programConfiguration, crossfade) {
    // Bind gradient texture to TEXTURE0
    const layerGradient = bucket.gradients[layer.id];
    let gradientTexture = layerGradient.texture;
    if (layer.gradientVersion !== layerGradient.version) {
        gradientTexture = updateGradientTexture(painter, tileManager, context, gl, layer, bucket, coord, layerGradient);
    }
    context.activeTexture.set(gl.TEXTURE0);
    gradientTexture.bind(layer.stepInterpolant ? gl.NEAREST : gl.LINEAR, gl.CLAMP_TO_EDGE);
    // Bind dash atlas to TEXTURE1
    context.activeTexture.set(gl.TEXTURE1);
    painter.lineAtlas.bind(context);
    programConfiguration.updatePaintBuffers(crossfade);
}
function drawLine(painter, tileManager, layer, coords, renderOptions) {
    var _a;
    if (painter.renderPass !== 'translucent')
        return;
    const { isRenderingToTexture } = renderOptions;
    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.getDepthModeForSublayer(0, DepthMode.ReadOnly);
    const colorMode = painter.colorModeForRenderPass();
    const dasharrayProperty = layer.paint.get('line-dasharray');
    const dasharray = dasharrayProperty.constantOr(1);
    const patternProperty = layer.paint.get('line-pattern');
    const image = patternProperty.constantOr(1);
    const gradient = layer.paint.get('line-gradient');
    const crossfade = layer.getCrossfadeParameters();
    let programId;
    if (image)
        programId = 'linePattern';
    else if (dasharray && gradient)
        programId = 'lineGradientSDF';
    else if (dasharray)
        programId = 'lineSDF';
    else if (gradient)
        programId = 'lineGradient';
    else
        programId = 'line';
    const context = painter.context;
    const gl = context.gl;
    const transform = painter.transform;
    let firstTile = true;
    for (const coord of coords) {
        const tile = tileManager.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 = (_a = painter.style.map.terrain) === null || _a === void 0 ? void 0 : _a.getTerrainData(coord);
        const constantPattern = patternProperty.constantOr(null);
        const constantDasharray = dasharrayProperty === null || dasharrayProperty === void 0 ? void 0 : dasharrayProperty.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);
        }
        else if (constantDasharray) {
            const round = layer.layout.get('line-cap').constantOr(null) === 'round';
            const dashTo = painter.lineAtlas.getDash(constantDasharray.to, round);
            const dashFrom = painter.lineAtlas.getDash(constantDasharray.from, round);
            programConfiguration.setConstantDashPositions(dashTo, dashFrom);
        }
        const projectionData = transform.getProjectionData({
            overscaledTileID: coord,
            applyGlobeMatrix: !isRenderingToTexture,
            applyTerrainMatrix: true
        });
        const pixelRatio = transform.getPixelScale();
        let uniformValues;
        if (image) {
            uniformValues = linePatternUniformValues(painter, tile, layer, pixelRatio, crossfade);
            bindImagePatternTextures(context, gl, tile, programConfiguration, crossfade);
        }
        else if (dasharray && gradient) {
            uniformValues = lineGradientSDFUniformValues(painter, tile, layer, pixelRatio, crossfade, bucket.lineClipsArray.length);
            bindGradientAndDashTextures(painter, tileManager, context, gl, layer, bucket, coord, programConfiguration, crossfade);
        }
        else if (dasharray) {
            uniformValues = lineSDFUniformValues(painter, tile, layer, pixelRatio, crossfade);
            bindDasharrayTextures(painter, context, gl, programConfiguration, programChanged, crossfade);
        }
        else if (gradient) {
            uniformValues = lineGradientUniformValues(painter, tile, layer, pixelRatio, bucket.lineClipsArray.length);
            bindGradientTextures(painter, tileManager, context, gl, layer, bucket, coord);
        }
        else {
            uniformValues = lineUniformValues(painter, tile, layer, pixelRatio);
        }
        const stencil = painter.stencilModeForClipping(coord);
        program.draw(context, gl.TRIANGLES, depthMode, stencil, colorMode, CullFaceMode.disabled, uniformValues, terrainData, projectionData, 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 === null || tile === void 0 ? void 0 : 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, tileManager, layer, coords, renderOptions) {
    const color = layer.paint.get('fill-color');
    const opacity = layer.paint.get('fill-opacity');
    if (opacity.constantOr(1) === 0) {
        return;
    }
    const { isRenderingToTexture } = renderOptions;
    const colorMode = painter.colorModeForRenderPass();
    const pattern = layer.paint.get('fill-pattern');
    const pass = painter.opaquePassEnabledForLayer() &&
        (!pattern.constantOr(1) &&
            color.constantOr(symbol_layout.Color.transparent).a === 1 &&
            opacity.constantOr(0) === 1) ? 'opaque' : 'translucent';
    // Draw fill
    if (painter.renderPass === pass) {
        const depthMode = painter.getDepthModeForSublayer(1, painter.renderPass === 'opaque' ? DepthMode.ReadWrite : DepthMode.ReadOnly);
        drawFillTiles(painter, tileManager, layer, coords, depthMode, colorMode, false, isRenderingToTexture);
    }
    // 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.getDepthModeForSublayer(layer.getPaintProperty('fill-outline-color') ? 2 : 0, DepthMode.ReadOnly);
        drawFillTiles(painter, tileManager, layer, coords, depthMode, colorMode, true, isRenderingToTexture);
    }
}
function drawFillTiles(painter, tileManager, layer, coords, depthMode, colorMode, isOutline, isRenderingToTexture) {
    var _a;
    const gl = painter.context.gl;
    const fillPropertyName = 'fill-pattern';
    const patternProperty = layer.paint.get(fillPropertyName);
    const image = patternProperty === null || patternProperty === void 0 ? void 0 : patternProperty.constantOr(1);
    const crossfade = layer.getCrossfadeParameters();
    let drawMode, programName, uniformValues, indexBuffer, segments;
    const transform = painter.transform;
    const propertyFillTranslate = layer.paint.get('fill-translate');
    const propertyFillTranslateAnchor = layer.paint.get('fill-translate-anchor');
    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 = tileManager.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 = (_a = painter.style.map.terrain) === null || _a === void 0 ? void 0 : _a.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 projectionData = transform.getProjectionData({
            overscaledTileID: coord,
            applyGlobeMatrix: !isRenderingToTexture,
            applyTerrainMatrix: true
        });
        const translateForUniforms = symbol_layout.translatePosition(transform, tile, propertyFillTranslate, propertyFillTranslateAnchor);
        if (!isOutline) {
            indexBuffer = bucket.indexBuffer;
            segments = bucket.segments;
            uniformValues = image ? fillPatternUniformValues(painter, crossfade, tile, translateForUniforms) : fillUniformValues(translateForUniforms);
        }
        else {
            indexBuffer = bucket.indexBuffer2;
            segments = bucket.segments2;
            const drawingBufferSize = [gl.drawingBufferWidth, gl.drawingBufferHeight];
            uniformValues = (programName === 'fillOutlinePattern' && image) ?
                fillOutlinePatternUniformValues(painter, crossfade, tile, drawingBufferSize, translateForUniforms) :
                fillOutlineUniformValues(drawingBufferSize, translateForUniforms);
        }
        const stencil = painter.stencilModeForClipping(coord);
        program.draw(painter.context, drawMode, depthMode, stencil, colorMode, CullFaceMode.backCCW, uniformValues, terrainData, projectionData, layer.id, bucket.layoutVertexBuffer, indexBuffer, segments, layer.paint, painter.transform.zoom, programConfiguration);
    }
}

function drawFillExtrusion(painter, tileManager, layer, coords, renderOptions) {
    const opacity = layer.paint.get('fill-extrusion-opacity');
    if (opacity === 0) {
        return;
    }
    const { isRenderingToTexture } = renderOptions;
    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, tileManager, layer, coords, depthMode, StencilMode.disabled, colorMode, isRenderingToTexture);
        }
        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, tileManager, layer, coords, depthMode, StencilMode.disabled, ColorMode.disabled, isRenderingToTexture);
            // 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, tileManager, layer, coords, depthMode, painter.stencilModeFor3D(), painter.colorModeForRenderPass(), isRenderingToTexture);
        }
    }
}
function drawExtrusionTiles(painter, tileManager, layer, coords, depthMode, stencilMode, colorMode, isRenderingToTexture) {
    var _a;
    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);
    const transform = painter.transform;
    for (const coord of coords) {
        const tile = tileManager.getTile(coord);
        const bucket = tile.getBucket(layer);
        if (!bucket)
            continue;
        const terrainData = (_a = painter.style.map.terrain) === null || _a === void 0 ? void 0 : _a.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);
        }
        const projectionData = transform.getProjectionData({ overscaledTileID: coord, applyGlobeMatrix: !isRenderingToTexture, applyTerrainMatrix: true });
        updatePatternPositionsInProgram(programConfiguration, fillPropertyName, constantPattern, tile, layer);
        const translate = symbol_layout.translatePosition(transform, 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(painter, shouldUseVerticalGradient, opacity, translate, coord, crossfade, tile) :
            fillExtrusionUniformValues(painter, shouldUseVerticalGradient, opacity, translate);
        program.draw(context, context.gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.backCCW, uniformValues, terrainData, projectionData, layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer, bucket.segments, layer.paint, painter.transform.zoom, programConfiguration, painter.style.map.terrain && bucket.centroidVertexBuffer);
    }
}

function drawHillshade(painter, tileManager, layer, tileIDs, renderOptions) {
    if (painter.renderPass !== 'offscreen' && painter.renderPass !== 'translucent')
        return;
    const { isRenderingToTexture } = renderOptions;
    const context = painter.context;
    const projection = painter.style.projection;
    const useSubdivision = projection.useSubdivision;
    const depthMode = painter.getDepthModeForSublayer(0, DepthMode.ReadOnly);
    const colorMode = painter.colorModeForRenderPass();
    if (painter.renderPass === 'offscreen') {
        // Prepare tiles
        prepareHillshade(painter, tileManager, tileIDs, layer, depthMode, StencilMode.disabled, colorMode);
        context.viewport.set([0, 0, painter.width, painter.height]);
    }
    else if (painter.renderPass === 'translucent') {
        // Globe (or any projection with subdivision) needs two-pass rendering to avoid artifacts when rendering texture tiles.
        // See comments in draw_raster.ts for more details.
        if (useSubdivision) {
            // Two-pass rendering
            const [stencilBorderless, stencilBorders, coords] = painter.stencilConfigForOverlapTwoPass(tileIDs);
            renderHillshade(painter, tileManager, layer, coords, stencilBorderless, depthMode, colorMode, false, isRenderingToTexture); // draw without borders
            renderHillshade(painter, tileManager, layer, coords, stencilBorders, depthMode, colorMode, true, isRenderingToTexture); // draw with borders
        }
        else {
            // Simple rendering
            const [stencil, coords] = painter.getStencilConfigForOverlapAndUpdateStencilID(tileIDs);
            renderHillshade(painter, tileManager, layer, coords, stencil, depthMode, colorMode, false, isRenderingToTexture);
        }
    }
}
function renderHillshade(painter, tileManager, layer, coords, stencilModes, depthMode, colorMode, useBorder, isRenderingToTexture) {
    var _a;
    const projection = painter.style.projection;
    const context = painter.context;
    const transform = painter.transform;
    const gl = context.gl;
    const defines = [`#define NUM_ILLUMINATION_SOURCES ${layer.paint.get('hillshade-highlight-color').values.length}`];
    const program = painter.useProgram('hillshade', null, false, defines);
    const align = !painter.options.moving;
    for (const coord of coords) {
        const tile = tileManager.getTile(coord);
        const fbo = tile.fbo;
        if (!fbo) {
            continue;
        }
        const mesh = projection.getMeshFromTileID(context, coord.canonical, useBorder, true, 'raster');
        const terrainData = (_a = painter.style.map.terrain) === null || _a === void 0 ? void 0 : _a.getTerrainData(coord);
        context.activeTexture.set(gl.TEXTURE0);
        gl.bindTexture(gl.TEXTURE_2D, fbo.colorAttachment.get());
        const projectionData = transform.getProjectionData({
            overscaledTileID: coord,
            aligned: align,
            applyGlobeMatrix: !isRenderingToTexture,
            applyTerrainMatrix: true
        });
        program.draw(context, gl.TRIANGLES, depthMode, stencilModes[coord.overscaledZ], colorMode, CullFaceMode.backCCW, hillshadeUniformValues(painter, tile, layer), terrainData, projectionData, layer.id, mesh.vertexBuffer, mesh.indexBuffer, mesh.segments);
    }
}
// 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, tileManager, tileIDs, layer, depthMode, stencilMode, colorMode) {
    const context = painter.context;
    const gl = context.gl;
    const textureFilter = layer.paint.get('resampling') === 'nearest' ? gl.NEAREST : gl.LINEAR;
    for (const coord of tileIDs) {
        const tile = tileManager.getTile(coord);
        const dem = tile.dem;
        if (!(dem === null || dem === void 0 ? void 0 : dem.data)) {
            continue;
        }
        if (!tile.needsHillshadePrepare) {
            continue;
        }
        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 symbol_layout.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 symbol_layout.Texture(context, { width: tileSize, height: tileSize, data: null }, gl.RGBA);
            renderTexture.bind(textureFilter, 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, null, layer.id, painter.rasterBoundsBuffer, painter.quadTriangleIndexBuffer, painter.rasterBoundsSegments);
        tile.needsHillshadePrepare = false;
    }
}

function drawColorRelief(painter, tileManager, layer, tileIDs, renderOptions) {
    if (painter.renderPass !== 'translucent')
        return;
    if (!tileIDs.length)
        return;
    const { isRenderingToTexture } = renderOptions;
    const projection = painter.style.projection;
    const useSubdivision = projection.useSubdivision;
    const depthMode = painter.getDepthModeForSublayer(0, DepthMode.ReadOnly);
    const colorMode = painter.colorModeForRenderPass();
    // Globe (or any projection with subdivision) needs two-pass rendering to avoid artifacts when rendering texture tiles.
    // See comments in draw_raster.ts for more details.
    if (useSubdivision) {
        // Two-pass rendering
        const [stencilBorderless, stencilBorders, coords] = painter.stencilConfigForOverlapTwoPass(tileIDs);
        renderColorRelief(painter, tileManager, layer, coords, stencilBorderless, depthMode, colorMode, false, isRenderingToTexture); // draw without borders
        renderColorRelief(painter, tileManager, layer, coords, stencilBorders, depthMode, colorMode, true, isRenderingToTexture); // draw with borders
    }
    else {
        // Simple rendering
        const [stencil, coords] = painter.getStencilConfigForOverlapAndUpdateStencilID(tileIDs);
        renderColorRelief(painter, tileManager, layer, coords, stencil, depthMode, colorMode, false, isRenderingToTexture);
    }
}
function renderColorRelief(painter, tileManager, layer, coords, stencilModes, depthMode, colorMode, useBorder, isRenderingToTexture) {
    var _a;
    const projection = painter.style.projection;
    const context = painter.context;
    const transform = painter.transform;
    const gl = context.gl;
    const program = painter.useProgram('colorRelief');
    const align = !painter.options.moving;
    const textureFilter = layer.paint.get('resampling') === 'nearest' ? gl.NEAREST : gl.LINEAR;
    let firstTile = true;
    let colorRampSize = 0;
    for (const coord of coords) {
        const tile = tileManager.getTile(coord);
        const dem = tile.dem;
        if (firstTile) {
            const maxLength = gl.getParameter(gl.MAX_TEXTURE_SIZE);
            const { elevationTexture, colorTexture } = layer.getColorRampTextures(context, maxLength, dem.getUnpackVector());
            context.activeTexture.set(gl.TEXTURE1);
            elevationTexture.bind(gl.NEAREST, gl.CLAMP_TO_EDGE);
            context.activeTexture.set(gl.TEXTURE4);
            colorTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
            firstTile = false;
            colorRampSize = elevationTexture.size[0];
        }
        if (!(dem === null || dem === void 0 ? void 0 : dem.data)) {
            continue;
        }
        const textureStride = dem.stride;
        const pixelData = dem.getPixels();
        context.activeTexture.set(gl.TEXTURE0);
        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(textureFilter, gl.CLAMP_TO_EDGE);
        }
        else {
            tile.demTexture = new symbol_layout.Texture(context, pixelData, gl.RGBA, { premultiply: false });
            tile.demTexture.bind(textureFilter, gl.CLAMP_TO_EDGE);
        }
        const mesh = projection.getMeshFromTileID(context, coord.canonical, useBorder, true, 'raster');
        const terrainData = (_a = painter.style.map.terrain) === null || _a === void 0 ? void 0 : _a.getTerrainData(coord);
        const projectionData = transform.getProjectionData({
            overscaledTileID: coord,
            aligned: align,
            applyGlobeMatrix: !isRenderingToTexture,
            applyTerrainMatrix: true
        });
        program.draw(context, gl.TRIANGLES, depthMode, stencilModes[coord.overscaledZ], colorMode, CullFaceMode.backCCW, colorReliefUniformValues(layer, tile.dem, colorRampSize), terrainData, projectionData, layer.id, mesh.vertexBuffer, mesh.indexBuffer, mesh.segments);
    }
}

const cornerCoords = [
    new symbol_layout.Point(0, 0),
    new symbol_layout.Point(symbol_layout.EXTENT, 0),
    new symbol_layout.Point(symbol_layout.EXTENT, symbol_layout.EXTENT),
    new symbol_layout.Point(0, symbol_layout.EXTENT),
];
function drawRaster(painter, tileManager, layer, tileIDs, renderOptions) {
    if (painter.renderPass !== 'translucent')
        return;
    if (layer.paint.get('raster-opacity') === 0)
        return;
    if (!tileIDs.length)
        return;
    const { isRenderingToTexture } = renderOptions;
    const source = tileManager.getSource();
    const projection = painter.style.projection;
    const useSubdivision = projection.useSubdivision;
    // When rendering globe (or any other subdivided projection), two passes are needed.
    // Subdivided tiles with different granularities might have tiny gaps between them.
    // To combat this, tile meshes for globe have a slight border region.
    // However tiles borders will overlap, and a part of a tile often
    // gets hidden by its neighbour's border, which displays an ugly stretched texture.
    // To both hide the border stretch and avoid tiny gaps, tiles are first drawn without borders (with gaps),
    // and then any missing pixels (gaps, not marked in stencil) get overdrawn with tile borders.
    // This approach also avoids pixel shader overdraw, as any pixel is drawn at most once.
    // Stencil mask and two-pass is not used for ImageSource sources regardless of projection.
    if (source instanceof ImageSource) {
        // Image source - no stencil is used
        drawTiles(painter, tileManager, layer, tileIDs, null, false, false, source.tileCoords, source.flippedWindingOrder, isRenderingToTexture);
    }
    else if (useSubdivision) {
        // Two-pass rendering
        const [stencilBorderless, stencilBorders, coords] = painter.stencilConfigForOverlapTwoPass(tileIDs);
        drawTiles(painter, tileManager, layer, coords, stencilBorderless, false, true, cornerCoords, false, isRenderingToTexture); // draw without borders
        drawTiles(painter, tileManager, layer, coords, stencilBorders, true, true, cornerCoords, false, isRenderingToTexture); // draw with borders
    }
    else {
        // Simple rendering
        const [stencil, coords] = painter.getStencilConfigForOverlapAndUpdateStencilID(tileIDs);
        drawTiles(painter, tileManager, layer, coords, stencil, false, true, cornerCoords, false, isRenderingToTexture);
    }
}
function drawTiles(painter, tileManager, layer, coords, stencilModes, useBorder, allowPoles, corners, flipCullfaceMode = false, isRenderingToTexture = false) {
    var _a;
    const minTileZ = coords[coords.length - 1].overscaledZ;
    const context = painter.context;
    const gl = context.gl;
    const program = painter.useProgram('raster');
    const transform = painter.transform;
    const projection = painter.style.projection;
    const colorMode = painter.colorModeForRenderPass();
    const align = !painter.options.moving;
    const rasterOpacity = layer.paint.get('raster-opacity');
    const useNearest = layer.paint.get('resampling') === 'nearest' || layer.paint.get('raster-resampling') === 'nearest';
    const textureFilter = useNearest ? gl.NEAREST : gl.LINEAR;
    const fadeDuration = layer.paint.get('raster-fade-duration');
    const isTerrain = !!painter.style.map.terrain;
    // Draw all tiles
    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.getDepthModeForSublayer(coord.overscaledZ - minTileZ, rasterOpacity === 1 ? DepthMode.ReadWrite : DepthMode.ReadOnly, gl.LESS);
        const tile = tileManager.getTile(coord);
        // create and bind first texture
        context.activeTexture.set(gl.TEXTURE0);
        tile.texture.bind(textureFilter, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_NEAREST);
        // create second texture - use either the current tile or fade tile to bind second texture below
        context.activeTexture.set(gl.TEXTURE1);
        const { parentTile, parentScaleBy, parentTopLeft, fadeValues } = getFadeProperties(tile, tileManager, fadeDuration, isTerrain);
        tile.fadeOpacity = fadeValues.tileOpacity;
        if (parentTile) {
            parentTile.fadeOpacity = fadeValues.parentTileOpacity;
            parentTile.texture.bind(textureFilter, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_NEAREST);
        }
        else {
            tile.texture.bind(textureFilter, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_NEAREST);
        }
        // Enable anisotropic filtering only when the pitch is greater than the threshold pitch.
        // The default threshold is 20 degrees to preserve image sharpness on flat or slightly tilted maps.
        if (tile.texture.useMipmap && context.extTextureFilterAnisotropic && painter.transform.pitch > painter.options.anisotropicFilterPitch) {
            gl.texParameterf(gl.TEXTURE_2D, context.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, context.extTextureFilterAnisotropicMax);
        }
        const terrainData = (_a = painter.style.map.terrain) === null || _a === void 0 ? void 0 : _a.getTerrainData(coord);
        const projectionData = transform.getProjectionData({ overscaledTileID: coord, aligned: align, applyGlobeMatrix: !isRenderingToTexture, applyTerrainMatrix: true });
        const uniformValues = rasterUniformValues(parentTopLeft, parentScaleBy, fadeValues.fadeMix, layer, corners);
        const mesh = projection.getMeshFromTileID(context, coord.canonical, useBorder, allowPoles, 'raster');
        const stencilMode = stencilModes ? stencilModes[coord.overscaledZ] : StencilMode.disabled;
        program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, flipCullfaceMode ? CullFaceMode.frontCCW : CullFaceMode.backCCW, uniformValues, terrainData, projectionData, layer.id, mesh.vertexBuffer, mesh.indexBuffer, mesh.segments);
    }
}
/**
 * Get fade properties for current tile - either cross-fading or self-fading properties.
 */
function getFadeProperties(tile, tileManager, fadeDuration, isTerrain) {
    const defaults = {
        parentTile: null,
        parentScaleBy: 1,
        parentTopLeft: [0, 0],
        fadeValues: { tileOpacity: 1, parentTileOpacity: 1, fadeMix: { opacity: 1, mix: 0 } }
    };
    if (fadeDuration === 0 || isTerrain)
        return defaults;
    // cross-fade with parent first if available
    if (tile.fadingParentID) {
        const parentTile = tileManager.getLoadedTile(tile.fadingParentID);
        if (!parentTile)
            return defaults;
        const parentScaleBy = Math.pow(2, parentTile.tileID.overscaledZ - tile.tileID.overscaledZ);
        const parentTopLeft = [
            (tile.tileID.canonical.x * parentScaleBy) % 1,
            (tile.tileID.canonical.y * parentScaleBy) % 1
        ];
        const fadeValues = getCrossFadeValues(tile, parentTile, fadeDuration);
        return { parentTile, parentScaleBy, parentTopLeft, fadeValues };
    }
    // self-fade for edge tiles
    if (tile.selfFading) {
        const fadeValues = getSelfFadeValues(tile, fadeDuration);
        return { parentTile: null, parentScaleBy: 1, parentTopLeft: [0, 0], fadeValues };
    }
    return defaults;
}
/**
 * Cross-fade values for a base tile with a parent tile (for zooming in/out)
 */
function getCrossFadeValues(tile, parentTile, fadeDuration) {
    const currentTime = now();
    const timeSinceTile = (currentTime - tile.timeAdded) / fadeDuration;
    const timeSinceParent = (currentTime - parentTile.timeAdded) / fadeDuration;
    // get fading opacity based on current fade direction
    const doFadeIn = (tile.fadingDirection === FadingDirections.Incoming);
    const opacity1 = symbol_layout.clamp(timeSinceTile, 0, 1);
    const opacity2 = symbol_layout.clamp(1 - timeSinceParent, 0, 1);
    const tileOpacity = doFadeIn ? opacity1 : opacity2;
    const parentTileOpacity = doFadeIn ? opacity2 : opacity1;
    const fadeMix = {
        opacity: 1,
        mix: 1 - tileOpacity
    };
    return { tileOpacity, parentTileOpacity, fadeMix };
}
/**
 * Simple fade-in values for tile without a parent (i.e. edge tiles)
 */
function getSelfFadeValues(tile, fadeDuration) {
    const currentTime = now();
    const timeSinceTile = (currentTime - tile.timeAdded) / fadeDuration;
    const tileOpacity = symbol_layout.clamp(timeSinceTile, 0, 1);
    const fadeMix = {
        opacity: tileOpacity,
        mix: 0
    };
    return { tileOpacity, fadeMix };
}

function drawBackground(painter, tileManager, layer, coords, renderOptions) {
    var _a;
    const color = layer.paint.get('background-color');
    const opacity = layer.paint.get('background-opacity');
    if (opacity === 0)
        return;
    const { isRenderingToTexture } = renderOptions;
    const context = painter.context;
    const gl = context.gl;
    const projection = painter.style.projection;
    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.getDepthModeForSublayer(0, pass === 'opaque' ? DepthMode.ReadWrite : DepthMode.ReadOnly);
    const colorMode = painter.colorModeForRenderPass();
    const program = painter.useProgram(image ? 'backgroundPattern' : 'background');
    const tileIDs = coords ? coords : coveringTiles(transform, { 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 projectionData = transform.getProjectionData({
            overscaledTileID: tileID,
            applyGlobeMatrix: !isRenderingToTexture,
            applyTerrainMatrix: true
        });
        const uniformValues = image ?
            backgroundPatternUniformValues(opacity, painter, image, { tileID, tileSize }, crossfade) :
            backgroundUniformValues(opacity, color);
        const terrainData = (_a = painter.style.map.terrain) === null || _a === void 0 ? void 0 : _a.getTerrainData(tileID);
        // For globe rendering, background uses tile meshes *without* borders and no stencil clipping.
        // This works assuming the tileIDs list contains only tiles of the same zoom level.
        // This seems to always be the case for background layers, but I'm leaving this comment
        // here in case this assumption is false in the future.
        // In case background starts having tiny holes at tile boundaries, switch to meshes with borders
        // and also enable stencil clipping. Make sure to render a proper tile clipping mask into stencil
        // first though, as that doesn't seem to happen for background layers as of writing this.
        const mesh = projection.getMeshFromTileID(context, tileID.canonical, false, true, 'raster');
        program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.backCCW, uniformValues, terrainData, projectionData, layer.id, mesh.vertexBuffer, mesh.indexBuffer, mesh.segments);
    }
}

const topColor = new symbol_layout.Color(1, 0, 0, 1);
const btmColor = new symbol_layout.Color(0, 1, 0, 1);
const leftColor = new symbol_layout.Color(0, 0, 1, 1);
const rightColor = new symbol_layout.Color(1, 0, 1, 1);
const centerColor = new symbol_layout.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, tileManager, coords) {
    for (const coord of coords) {
        drawDebugTile(painter, tileManager, coord);
    }
}
function drawDebugTile(painter, tileManager, coord) {
    var _a;
    const context = painter.context;
    const gl = context.gl;
    const program = painter.useProgram('debug');
    const depthMode = DepthMode.disabled;
    const stencilMode = StencilMode.disabled;
    const colorMode = painter.colorModeForRenderPass();
    const id = '$debug';
    const terrainData = (_a = painter.style.map.terrain) === null || _a === void 0 ? void 0 : _a.getTerrainData(coord);
    context.activeTexture.set(gl.TEXTURE0);
    const tileRawData = tileManager.getTileByID(coord.key).latestRawTileData;
    const tileByteLength = (tileRawData === null || tileRawData === void 0 ? void 0 : tileRawData.byteLength) || 0;
    const tileSizeKb = Math.floor(tileByteLength / 1024);
    const tileSize = tileManager.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);
    const projectionData = painter.transform.getProjectionData({ overscaledTileID: coord, applyGlobeMatrix: true, applyTerrainMatrix: true });
    program.draw(context, gl.TRIANGLES, depthMode, stencilMode, ColorMode.alphaBlended, CullFaceMode.disabled, debugUniformValues(symbol_layout.Color.transparent, scaleRatio), null, projectionData, id, painter.debugBuffer, painter.quadTriangleIndexBuffer, painter.debugSegments);
    program.draw(context, gl.LINE_STRIP, depthMode, stencilMode, colorMode, CullFaceMode.disabled, debugUniformValues(symbol_layout.Color.red), terrainData, projectionData, 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 tileManager = style.tileManagers[layer.source];
            return [tileManager];
        }
        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;
        }
    };
    for (const source of vectorSources) {
        considerSource(source);
    }
    if (!selectedSource) {
        for (const source of otherSources) {
            considerSource(source);
        }
    }
    return selectedSource;
}

function drawCustom(painter, tileManager, layer, renderOptions) {
    const { isRenderingGlobe } = renderOptions;
    const context = painter.context;
    const implementation = layer.implementation;
    const projection = painter.style.projection;
    const transform = painter.transform;
    const projectionData = transform.getProjectionDataForCustomLayer(isRenderingGlobe);
    const customLayerArgs = {
        farZ: transform.farZ,
        nearZ: transform.nearZ,
        fov: transform.fov * Math.PI / 180, // fov converted to radians
        modelViewProjectionMatrix: transform.modelViewProjectionMatrix,
        projectionMatrix: transform.projectionMatrix,
        shaderData: {
            variantName: projection.shaderVariantName,
            vertexShaderPrelude: `const float PI = 3.141592653589793;\nuniform mat4 u_projection_matrix;\n${projection.shaderPreludeCode.vertexSource}`,
            define: projection.shaderDefine,
        },
        defaultProjectionData: projectionData,
    };
    const renderingMode = implementation.renderingMode ? implementation.renderingMode : '2d';
    if (painter.renderPass === 'offscreen') {
        const prerender = implementation.prerender;
        if (prerender) {
            painter.setCustomLayerDefaults();
            context.setColorMode(painter.colorModeForRenderPass());
            prerender.call(implementation, context.gl, customLayerArgs);
            context.setDirty();
            painter.setBaseState();
        }
    }
    else if (painter.renderPass === 'translucent') {
        painter.setCustomLayerDefaults();
        context.setColorMode(painter.colorModeForRenderPass());
        context.setStencilMode(StencilMode.disabled);
        const depthMode = renderingMode === '3d' ?
            painter.getDepthModeFor3D() :
            painter.getDepthModeForSublayer(0, DepthMode.ReadOnly);
        context.setDepthMode(depthMode);
        implementation.render(context.gl, customLayerArgs);
        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 tr = painter.transform;
    const colorMode = ColorMode.unblended;
    const depthMode = new DepthMode(gl.LEQUAL, DepthMode.ReadWrite, [0, 1]);
    const tiles = terrain.tileManager.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: symbol_layout.Color.transparent, depth: 1 });
    for (const tile of tiles) {
        const mesh = terrain.getTerrainMesh(tile.tileID);
        const terrainData = terrain.getTerrainData(tile.tileID);
        const projectionData = tr.getProjectionData({ overscaledTileID: tile.tileID, applyTerrainMatrix: false, applyGlobeMatrix: true });
        const uniformValues = terrainDepthUniformValues(terrain.getMeshFrameDelta(tr.zoom));
        program.draw(context, gl.TRIANGLES, depthMode, StencilMode.disabled, colorMode, CullFaceMode.backCCW, uniformValues, terrainData, projectionData, '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 tr = painter.transform;
    const colorMode = ColorMode.unblended;
    const depthMode = new DepthMode(gl.LEQUAL, DepthMode.ReadWrite, [0, 1]);
    const coords = terrain.getCoordsTexture();
    const tiles = terrain.tileManager.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: symbol_layout.Color.transparent, depth: 1 });
    terrain.coordsIndex = [];
    for (const tile of tiles) {
        const mesh = terrain.getTerrainMesh(tile.tileID);
        const terrainData = terrain.getTerrainData(tile.tileID);
        context.activeTexture.set(gl.TEXTURE0);
        gl.bindTexture(gl.TEXTURE_2D, coords.texture);
        const uniformValues = terrainCoordsUniformValues(255 - terrain.coordsIndex.length, terrain.getMeshFrameDelta(tr.zoom));
        const projectionData = tr.getProjectionData({ overscaledTileID: tile.tileID, applyTerrainMatrix: false, applyGlobeMatrix: true });
        program.draw(context, gl.TRIANGLES, depthMode, StencilMode.disabled, colorMode, CullFaceMode.backCCW, uniformValues, terrainData, projectionData, '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, renderOptions) {
    const { isRenderingGlobe } = renderOptions;
    const context = painter.context;
    const gl = context.gl;
    const tr = painter.transform;
    const colorMode = painter.colorModeForRenderPass();
    const depthMode = painter.getDepthModeFor3D();
    const program = painter.useProgram('terrain');
    context.bindFramebuffer.set(null);
    context.viewport.set([0, 0, painter.width, painter.height]);
    for (const tile of tiles) {
        const mesh = terrain.getTerrainMesh(tile.tileID);
        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 eleDelta = terrain.getMeshFrameDelta(tr.zoom);
        const fogMatrix = tr.calculateFogMatrix(tile.tileID.toUnwrapped());
        const uniformValues = terrainUniformValues(eleDelta, fogMatrix, painter.style.sky, tr.pitch, isRenderingGlobe);
        const projectionData = tr.getProjectionData({ overscaledTileID: tile.tileID, applyTerrainMatrix: false, applyGlobeMatrix: true });
        program.draw(context, gl.TRIANGLES, depthMode, StencilMode.disabled, colorMode, CullFaceMode.backCCW, uniformValues, terrainData, projectionData, 'terrain', mesh.vertexBuffer, mesh.indexBuffer, mesh.segments);
    }
}

function getMesh(context, sky) {
    // Create the Sky mesh the first time we need it
    if (!sky.mesh) {
        const vertexArray = new symbol_layout.PosArray();
        vertexArray.emplaceBack(-1, -1);
        vertexArray.emplaceBack(1, -1);
        vertexArray.emplaceBack(1, 1);
        vertexArray.emplaceBack(-1, 1);
        const indexArray = new symbol_layout.TriangleIndexArray();
        indexArray.emplaceBack(0, 1, 2);
        indexArray.emplaceBack(0, 2, 3);
        sky.mesh = new Mesh(context.createVertexBuffer(vertexArray, posAttributes.members), context.createIndexBuffer(indexArray), symbol_layout.SegmentVector.simpleSegment(0, 0, vertexArray.length, indexArray.length));
    }
    return sky.mesh;
}
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');
    const mesh = getMesh(context, sky);
    program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled, skyUniforms, null, undefined, 'sky', mesh.vertexBuffer, mesh.indexBuffer, mesh.segments);
}
function getSunPos(light, transform) {
    const _lp = light.properties.get('position');
    const lightPos = [-_lp.x, -_lp.y, -_lp.z];
    const lightMat = symbol_layout.identity(new Float64Array(16));
    if (light.properties.get('anchor') === 'map') {
        symbol_layout.rotateZ(lightMat, lightMat, transform.rollInRadians);
        symbol_layout.rotateX(lightMat, lightMat, -transform.pitchInRadians);
        symbol_layout.rotateZ(lightMat, lightMat, transform.bearingInRadians);
        symbol_layout.rotateX(lightMat, lightMat, transform.center.lat * Math.PI / 180.0);
        symbol_layout.rotateY$1(lightMat, lightMat, -transform.center.lng * Math.PI / 180.0);
    }
    symbol_layout.transformMat4$1(lightPos, lightPos, lightMat);
    return lightPos;
}
function drawAtmosphere(painter, sky, light) {
    const context = painter.context;
    const gl = context.gl;
    const program = painter.useProgram('atmosphere');
    const depthMode = new DepthMode(gl.LEQUAL, DepthMode.ReadOnly, [0, 1]);
    const transform = painter.transform;
    const sunPos = getSunPos(light, painter.transform);
    const projectionData = transform.getProjectionData({ overscaledTileID: null, applyGlobeMatrix: true, applyTerrainMatrix: true });
    const atmosphereBlend = sky.properties.get('atmosphere-blend') * projectionData.projectionTransition;
    if (atmosphereBlend === 0) {
        // Don't draw anything if atmosphere is fully transparent
        return;
    }
    const globeRadius = getGlobeRadiusPixels(transform.worldSize, transform.center.lat);
    const invProjMatrix = transform.inverseProjectionMatrix;
    const vec = new Float64Array(4);
    vec[3] = 1;
    symbol_layout.transformMat4(vec, vec, transform.modelViewProjectionMatrix);
    vec[0] /= vec[3];
    vec[1] /= vec[3];
    vec[2] /= vec[3];
    vec[3] = 1;
    symbol_layout.transformMat4(vec, vec, invProjMatrix);
    vec[0] /= vec[3];
    vec[1] /= vec[3];
    vec[2] /= vec[3];
    vec[3] = 1;
    const globePosition = [vec[0], vec[1], vec[2]];
    const uniformValues = atmosphereUniformValues(sunPos, atmosphereBlend, globePosition, globeRadius, invProjMatrix);
    const mesh = getMesh(context, sky);
    program.draw(context, gl.TRIANGLES, depthMode, StencilMode.disabled, ColorMode.alphaBlended, CullFaceMode.disabled, uniformValues, null, null, 'atmosphere', mesh.vertexBuffer, mesh.indexBuffer, mesh.segments);
}

const webglDrawFunctions = {
    symbol: drawSymbols,
    circle: drawCircles,
    heatmap: drawHeatmap,
    line: drawLine,
    fill: drawFill,
    fillExtrusion: drawFillExtrusion,
    hillshade: drawHillshade,
    colorRelief: drawColorRelief,
    raster: drawRaster,
    background: drawBackground,
    sky: drawSky,
    atmosphere: drawAtmosphere,
    custom: drawCustom,
    debug: drawDebug,
    debugPadding: drawDebugPadding,
    terrainDepth: drawDepth,
    terrainCoords: drawCoords,
};

/**
 * @internal
 * Initialize a new painter object.
 */
class Painter {
    constructor(gl, transform) {
        this.drawFunctions = webglDrawFunctions;
        this.context = new Context(gl);
        this.transform = transform;
        this._tileTextures = {};
        this.terrainFacilitator = { depthDirty: true, coordsDirty: false, matrix: symbol_layout.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 = TileManager.maxOverzooming + TileManager.maxUnderzooming + 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 symbol_layout.PosArray();
        tileExtentArray.emplaceBack(0, 0);
        tileExtentArray.emplaceBack(symbol_layout.EXTENT, 0);
        tileExtentArray.emplaceBack(0, symbol_layout.EXTENT);
        tileExtentArray.emplaceBack(symbol_layout.EXTENT, symbol_layout.EXTENT);
        this.tileExtentBuffer = context.createVertexBuffer(tileExtentArray, posAttributes.members);
        this.tileExtentSegments = symbol_layout.SegmentVector.simpleSegment(0, 0, 4, 2);
        const debugArray = new symbol_layout.PosArray();
        debugArray.emplaceBack(0, 0);
        debugArray.emplaceBack(symbol_layout.EXTENT, 0);
        debugArray.emplaceBack(0, symbol_layout.EXTENT);
        debugArray.emplaceBack(symbol_layout.EXTENT, symbol_layout.EXTENT);
        this.debugBuffer = context.createVertexBuffer(debugArray, posAttributes.members);
        this.debugSegments = symbol_layout.SegmentVector.simpleSegment(0, 0, 4, 5);
        const rasterBoundsArray = new symbol_layout.RasterBoundsArray();
        rasterBoundsArray.emplaceBack(0, 0, 0, 0);
        rasterBoundsArray.emplaceBack(symbol_layout.EXTENT, 0, symbol_layout.EXTENT, 0);
        rasterBoundsArray.emplaceBack(0, symbol_layout.EXTENT, 0, symbol_layout.EXTENT);
        rasterBoundsArray.emplaceBack(symbol_layout.EXTENT, symbol_layout.EXTENT, symbol_layout.EXTENT, symbol_layout.EXTENT);
        this.rasterBoundsBuffer = context.createVertexBuffer(rasterBoundsArray, rasterBoundsAttributes.members);
        this.rasterBoundsSegments = symbol_layout.SegmentVector.simpleSegment(0, 0, 4, 2);
        const rasterBoundsArrayPosOnly = new symbol_layout.PosArray();
        rasterBoundsArrayPosOnly.emplaceBack(0, 0);
        rasterBoundsArrayPosOnly.emplaceBack(symbol_layout.EXTENT, 0);
        rasterBoundsArrayPosOnly.emplaceBack(0, symbol_layout.EXTENT);
        rasterBoundsArrayPosOnly.emplaceBack(symbol_layout.EXTENT, symbol_layout.EXTENT);
        this.rasterBoundsBufferPosOnly = context.createVertexBuffer(rasterBoundsArrayPosOnly, posAttributes.members);
        this.rasterBoundsSegmentsPosOnly = symbol_layout.SegmentVector.simpleSegment(0, 0, 4, 5);
        const viewportArray = new symbol_layout.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 = symbol_layout.SegmentVector.simpleSegment(0, 0, 4, 2);
        const tileLineStripIndices = new symbol_layout.LineStripIndexArray();
        tileLineStripIndices.emplaceBack(0);
        tileLineStripIndices.emplaceBack(1);
        tileLineStripIndices.emplaceBack(3);
        tileLineStripIndices.emplaceBack(2);
        tileLineStripIndices.emplaceBack(0);
        this.tileBorderIndexBuffer = context.createIndexBuffer(tileLineStripIndices);
        const quadTriangleIndices = new symbol_layout.TriangleIndexArray();
        quadTriangleIndices.emplaceBack(1, 0, 2);
        quadTriangleIndices.emplaceBack(1, 2, 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);
        this.tileExtentMesh = new Mesh(this.tileExtentBuffer, this.quadTriangleIndexBuffer, this.tileExtentSegments);
    }
    /*
     * 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 = symbol_layout.create();
        symbol_layout.ortho(matrix, 0, this.width, this.height, 0, 0, 1);
        symbol_layout.scale(matrix, matrix, [gl.drawingBufferWidth, gl.drawingBufferHeight, 0]);
        const projectionData = {
            mainMatrix: matrix,
            tileMercatorCoords: [0, 0, 1, 1],
            clippingPlane: [0, 0, 0, 0],
            projectionTransition: 0.0,
            fallbackMatrix: matrix,
        };
        // Note: we force a simple mercator projection for the shader, since we want to draw a fullscreen quad.
        this.useProgram('clippingMask', null, true).draw(context, gl.TRIANGLES, DepthMode.disabled, this.stencilClearMode, ColorMode.disabled, CullFaceMode.disabled, null, null, projectionData, '$clipping', this.viewportBuffer, this.quadTriangleIndexBuffer, this.viewportSegments);
    }
    _renderTileClippingMasks(layer, tileIDs, renderToTexture) {
        if (this.currentStencilSource === layer.source || !layer.isTileClipped() || !(tileIDs === null || tileIDs === void 0 ? void 0 : tileIDs.length)) {
            return;
        }
        this.currentStencilSource = layer.source;
        if (this.nextStencilID + tileIDs.length > 256) {
            // we'll run out of fresh IDs so we need to clear and start from scratch
            this.clearStencil();
        }
        const context = this.context;
        context.setColorMode(ColorMode.disabled);
        context.setDepthMode(DepthMode.disabled);
        const stencilRefs = {};
        // Set stencil ref values for all tiles
        for (const tileID of tileIDs) {
            stencilRefs[tileID.key] = this.nextStencilID++;
        }
        // A two-pass approach is needed. See comment in draw_raster.ts for more details.
        // However, we use a simpler approach because we don't care about overdraw here.
        // First pass - draw tiles with borders and with GL_ALWAYS
        this._renderTileMasks(stencilRefs, tileIDs, renderToTexture, true);
        // Second pass - draw borderless tiles with GL_ALWAYS
        this._renderTileMasks(stencilRefs, tileIDs, renderToTexture, false);
        this._tileClippingMaskIDs = stencilRefs;
    }
    _renderTileMasks(tileStencilRefs, tileIDs, renderToTexture, useBorders) {
        var _a;
        const context = this.context;
        const gl = context.gl;
        const projection = this.style.projection;
        const transform = this.transform;
        const program = this.useProgram('clippingMask');
        // tiles are usually supplied in ascending order of z, then y, then x
        for (const tileID of tileIDs) {
            const stencilRef = tileStencilRefs[tileID.key];
            const terrainData = (_a = this.style.map.terrain) === null || _a === void 0 ? void 0 : _a.getTerrainData(tileID);
            const mesh = projection.getMeshFromTileID(this.context, tileID.canonical, useBorders, true, 'stencil');
            const projectionData = transform.getProjectionData({ overscaledTileID: tileID, applyGlobeMatrix: !renderToTexture, applyTerrainMatrix: true });
            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 }, stencilRef, 0xFF, gl.KEEP, gl.KEEP, gl.REPLACE), ColorMode.disabled, renderToTexture ? CullFaceMode.disabled : CullFaceMode.backCCW, null, terrainData, projectionData, '$clipping', mesh.vertexBuffer, mesh.indexBuffer, mesh.segments);
        }
    }
    /**
     * Fills the depth buffer with the geometry of all supplied tiles.
     * Does not change the color buffer or the stencil buffer.
     */
    _renderTilesDepthBuffer() {
        var _a;
        const context = this.context;
        const gl = context.gl;
        const projection = this.style.projection;
        const transform = this.transform;
        const program = this.useProgram('depth');
        const depthMode = this.getDepthModeFor3D();
        const tileIDs = coveringTiles(transform, { tileSize: transform.tileSize });
        // tiles are usually supplied in ascending order of z, then y, then x
        for (const tileID of tileIDs) {
            const terrainData = (_a = this.style.map.terrain) === null || _a === void 0 ? void 0 : _a.getTerrainData(tileID);
            const mesh = projection.getMeshFromTileID(this.context, tileID.canonical, true, true, 'raster');
            const projectionData = transform.getProjectionData({ overscaledTileID: tileID, applyGlobeMatrix: true, applyTerrainMatrix: true });
            program.draw(context, gl.TRIANGLES, depthMode, StencilMode.disabled, ColorMode.disabled, CullFaceMode.backCCW, null, terrainData, projectionData, '$clipping', mesh.vertexBuffer, mesh.indexBuffer, mesh.segments);
        }
    }
    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.
     *
     * Attention: This function changes this.nextStencilID even if the result of it
     * is not used, which might cause problems when rendering due to invalid stencil
     * values.
     * Returns [StencilMode for tile overscaleZ map, sortedCoords].
     */
    getStencilConfigForOverlapAndUpdateStencilID(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];
    }
    stencilConfigForOverlapTwoPass(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;
        this.clearStencil();
        if (stencilValues > 1) {
            const zToStencilModeHigh = {};
            const zToStencilModeLow = {};
            for (let i = 0; i < stencilValues; i++) {
                zToStencilModeHigh[i + minTileZ] = new StencilMode({ func: gl.GREATER, mask: 0xFF }, stencilValues + 1 + i, 0xFF, gl.KEEP, gl.KEEP, gl.REPLACE);
                zToStencilModeLow[i + minTileZ] = new StencilMode({ func: gl.GREATER, mask: 0xFF }, 1 + i, 0xFF, gl.KEEP, gl.KEEP, gl.REPLACE);
            }
            this.nextStencilID = stencilValues * 2 + 1;
            return [
                zToStencilModeHigh,
                zToStencilModeLow,
                coords
            ];
        }
        else {
            this.nextStencilID = 3;
            return [
                { [minTileZ]: new StencilMode({ func: gl.GREATER, mask: 0xFF }, 2, 0xFF, gl.KEEP, gl.KEEP, gl.REPLACE) },
                { [minTileZ]: new StencilMode({ func: gl.GREATER, mask: 0xFF }, 1, 0xFF, gl.KEEP, gl.KEEP, gl.REPLACE) },
                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 symbol_layout.Color(a, a, a, 0), [true, true, true, true]);
        }
        else if (this.renderPass === 'opaque') {
            return ColorMode.unblended;
        }
        else {
            return ColorMode.alphaBlended;
        }
    }
    getDepthModeForSublayer(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]);
    }
    getDepthModeFor3D() {
        return new DepthMode(this.context.gl.LEQUAL, DepthMode.ReadWrite, this.depthRangeFor3D);
    }
    /*
     * 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) {
        var _a, _b, _c;
        this.style = style;
        this.options = options;
        this.lineAtlas = style.lineAtlas;
        this.imageManager = style.imageManager;
        this.glyphManager = style.glyphManager;
        this.symbolFadeChange = style.placement.symbolFadeChange(now());
        this.imageManager.beginFrame();
        const layerIds = this.style._order;
        const tileManagers = this.style.tileManagers;
        const coordsAscending = {};
        const coordsDescending = {};
        const coordsDescendingSymbol = {};
        const renderOptions = { isRenderingToTexture: false, isRenderingGlobe: ((_a = style.projection) === null || _a === void 0 ? void 0 : _a.transitionState) > 0 };
        for (const id in tileManagers) {
            const tileManager = tileManagers[id];
            if (tileManager.used) {
                tileManager.prepare(this.context);
            }
            coordsAscending[id] = tileManager.getVisibleCoordinates(false);
            coordsDescending[id] = coordsAscending[id].slice().reverse();
            coordsDescendingSymbol[id] = tileManager.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.maybeDrawDepth(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, tileManagers[layer.source], layer, coords, renderOptions);
        }
        // Execute offscreen GPU tasks of the projection manager
        (_b = this.style.projection) === null || _b === void 0 ? void 0 : _b.updateGPUdependent({
            context: this.context,
            useProgram: (name) => this.useProgram(name)
        });
        // Rebind the main framebuffer now that all offscreen layers have been rendered:
        this.context.viewport.set([0, 0, this.width, this.height]);
        this.context.bindFramebuffer.set(null);
        // Clear buffers in preparation for drawing to the main framebuffer
        this.context.clear({ color: options.showOverdrawInspector ? symbol_layout.Color.black : symbol_layout.Color.transparent, depth: 1 });
        this.clearStencil();
        // draw sky first to not overwrite symbols
        if (this.style.sky)
            this.drawFunctions.sky(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 tileManager = tileManagers[layer.source];
                const coords = coordsAscending[layer.source];
                this._renderTileClippingMasks(layer, coords, false);
                this.renderLayer(this, tileManager, layer, coords, renderOptions);
            }
        }
        // Translucent pass ===============================================
        // Draw all other layers bottom-to-top.
        this.renderPass = 'translucent';
        let globeDepthRendered = false;
        for (this.currentLayer = 0; this.currentLayer < layerIds.length; this.currentLayer++) {
            const layer = this.style._layers[layerIds[this.currentLayer]];
            const tileManager = tileManagers[layer.source];
            if ((_c = this.renderToTexture) === null || _c === void 0 ? void 0 : _c.renderLayer(layer, renderOptions))
                continue;
            if (!this.opaquePassEnabledForLayer() && !globeDepthRendered) {
                globeDepthRendered = true;
                // Render the globe sphere into the depth buffer - but only if globe is enabled and terrain is disabled.
                // There should be no need for explicitly writing tile depths when terrain is enabled.
                if (renderOptions.isRenderingGlobe && !this.style.map.terrain) {
                    this._renderTilesDepthBuffer();
                }
            }
            // 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.renderToTexture);
            this.renderLayer(this, tileManager, layer, coords, renderOptions);
        }
        // Render atmosphere, only for Globe projection
        if (renderOptions.isRenderingGlobe) {
            this.drawFunctions.atmosphere(this, this.style.sky, this.style.light);
        }
        if (this.options.showTileBoundaries) {
            const selectedSource = selectDebugSource(this.style, this.transform.zoom);
            if (selectedSource) {
                this.drawFunctions.debug(this, selectedSource, selectedSource.getVisibleCoordinates());
            }
        }
        if (this.options.showPadding) {
            this.drawFunctions.debugPadding(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 framebuffer if the camera has moved or tiles have reloaded.
     * Marks coords as depthDirty so they are re-rendered on next demand.
     */
    maybeDrawDepth(requireExact) {
        var _a, _b;
        if (!((_b = (_a = this.style) === null || _a === void 0 ? void 0 : _a.map) === null || _b === void 0 ? void 0 : _b.terrain)) {
            return;
        }
        const prevMatrix = this.terrainFacilitator.matrix;
        const currMatrix = this.transform.modelViewProjectionMatrix;
        // Update depth-framebuffer on camera movement, or tile reloading
        let doUpdate = this.terrainFacilitator.depthDirty;
        doUpdate || (doUpdate = requireExact ? !symbol_layout.exactEquals(prevMatrix, currMatrix) : !symbol_layout.equals(prevMatrix, currMatrix));
        doUpdate || (doUpdate = this.style.map.terrain.tileManager.anyTilesAfterTime(this.terrainFacilitator.renderTime));
        if (!doUpdate) {
            return;
        }
        symbol_layout.copy(prevMatrix, currMatrix);
        this.terrainFacilitator.renderTime = Date.now();
        this.terrainFacilitator.depthDirty = false;
        this.terrainFacilitator.coordsDirty = true;
        this.drawFunctions.terrainDepth(this, this.style.map.terrain);
    }
    /**
     * Render the coords framebuffer if it is coordsDirty
     */
    maybeDrawCoords() {
        var _a, _b;
        if (!((_b = (_a = this.style) === null || _a === void 0 ? void 0 : _a.map) === null || _b === void 0 ? void 0 : _b.terrain) || !this.terrainFacilitator.coordsDirty) {
            return;
        }
        this.terrainFacilitator.coordsDirty = false;
        this.drawFunctions.terrainCoords(this, this.style.map.terrain);
    }
    renderLayer(painter, tileManager, layer, coords, renderOptions) {
        if (layer.isHidden(this.transform.zoom))
            return;
        if (layer.type !== 'background' && layer.type !== 'custom' && !(coords || []).length)
            return;
        this.id = layer.id;
        const draw = this.drawFunctions;
        if (symbol_layout.isSymbolStyleLayer(layer)) {
            draw.symbol(painter, tileManager, layer, coords, this.style.placement.variableOffsets, renderOptions);
        }
        else if (symbol_layout.isCircleStyleLayer(layer)) {
            draw.circle(painter, tileManager, layer, coords, renderOptions);
        }
        else if (symbol_layout.isHeatmapStyleLayer(layer)) {
            draw.heatmap(painter, tileManager, layer, coords, renderOptions);
        }
        else if (symbol_layout.isLineStyleLayer(layer)) {
            draw.line(painter, tileManager, layer, coords, renderOptions);
        }
        else if (symbol_layout.isFillStyleLayer(layer)) {
            draw.fill(painter, tileManager, layer, coords, renderOptions);
        }
        else if (symbol_layout.isFillExtrusionStyleLayer(layer)) {
            draw.fillExtrusion(painter, tileManager, layer, coords, renderOptions);
        }
        else if (symbol_layout.isHillshadeStyleLayer(layer)) {
            draw.hillshade(painter, tileManager, layer, coords, renderOptions);
        }
        else if (symbol_layout.isColorReliefStyleLayer(layer)) {
            draw.colorRelief(painter, tileManager, layer, coords, renderOptions);
        }
        else if (symbol_layout.isRasterStyleLayer(layer)) {
            draw.raster(painter, tileManager, layer, coords, renderOptions);
        }
        else if (symbol_layout.isBackgroundStyleLayer(layer)) {
            draw.background(painter, tileManager, layer, coords, renderOptions);
        }
        else if (symbol_layout.isCustomStyleLayer(layer)) {
            draw.custom(painter, tileManager, layer, renderOptions);
        }
    }
    saveTileTexture(texture) {
        const textures = this._tileTextures[texture.size[0]];
        if (!textures) {
            this._tileTextures[texture.size[0]] = [texture];
        }
        else if (textures.length < Painter.MAX_TEXTURE_POOL_SIZE_PER_BUCKET) {
            textures.push(texture);
        }
        else {
            texture.destroy();
        }
    }
    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;
    }
    /**
     * Finds the required shader and its variant (base/terrain/globe, etc.) and binds it, compiling a new shader if required.
     * @param name - Name of the desired shader.
     * @param programConfiguration - Configuration of shader's inputs.
     * @param forceSimpleProjection - Whether to force the use of a shader variant with simple mercator projection vertex shader.
     * @param defines - Additional macros to be injected at the beginning of the shader. Expected format is `['#define XYZ']`, etc.
     * False by default. Use true when drawing with a simple projection matrix is desired, eg. when drawing a fullscreen quad.
     * @returns
     */
    useProgram(name, programConfiguration, forceSimpleProjection = false, defines = []) {
        this.cache = this.cache || {};
        const useTerrain = !!this.style.map.terrain;
        const projection = this.style.projection;
        const projectionPrelude = forceSimpleProjection ? shaders.projectionMercator : projection.shaderPreludeCode;
        const projectionDefine = forceSimpleProjection ? MercatorShaderDefine : projection.shaderDefine;
        const projectionKey = `/${forceSimpleProjection ? MercatorShaderVariantKey : projection.shaderVariantName}`;
        const configurationKey = (programConfiguration ? programConfiguration.cacheKey : '');
        const overdrawKey = (this._showOverdrawInspector ? '/overdraw' : '');
        const terrainKey = (useTerrain ? '/terrain' : '');
        const definesKey = (defines ? `/${defines.join('/')}` : '');
        const key = name + configurationKey + projectionKey + overdrawKey + terrainKey + definesKey;
        if (!this.cache[key]) {
            this.cache[key] = new Program(this.context, shaders[name], programConfiguration, programUniforms[name], this._showOverdrawInspector, useTerrain, projectionPrelude, projectionDefine, defines);
        }
        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 symbol_layout.Texture(this.context, this.debugOverlayCanvas, gl.RGBA);
        }
    }
    destroy() {
        var _a, _b;
        if (this._tileTextures) {
            for (const size in this._tileTextures) {
                const textures = this._tileTextures[size];
                if (textures) {
                    for (const texture of textures) {
                        texture.destroy();
                    }
                }
            }
            this._tileTextures = {};
        }
        if (this.tileExtentBuffer)
            this.tileExtentBuffer.destroy();
        if (this.debugBuffer)
            this.debugBuffer.destroy();
        if (this.rasterBoundsBuffer)
            this.rasterBoundsBuffer.destroy();
        if (this.rasterBoundsBufferPosOnly)
            this.rasterBoundsBufferPosOnly.destroy();
        if (this.viewportBuffer)
            this.viewportBuffer.destroy();
        if (this.tileBorderIndexBuffer)
            this.tileBorderIndexBuffer.destroy();
        if (this.quadTriangleIndexBuffer)
            this.quadTriangleIndexBuffer.destroy();
        if (this.tileExtentMesh)
            (_a = this.tileExtentMesh.vertexBuffer) === null || _a === void 0 ? void 0 : _a.destroy();
        if (this.tileExtentMesh)
            (_b = this.tileExtentMesh.indexBuffer) === null || _b === void 0 ? void 0 : _b.destroy();
        if (this.debugOverlayTexture) {
            this.debugOverlayTexture.destroy();
        }
        if (this.cache) {
            for (const key in this.cache) {
                const program = this.cache[key];
                if (program === null || program === void 0 ? void 0 : program.program) {
                    this.context.gl.deleteProgram(program.program);
                }
            }
            this.cache = {};
        }
        if (this.context) {
            this.context.setDefault();
        }
    }
    /*
     * 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;
    }
}
Painter.MAX_TEXTURE_POOL_SIZE_PER_BUCKET = 50;

/**
 * Throttle the given function to run at most every `period` milliseconds.
 */
function throttle(fn, time) {
    let pending = false;
    let timerId = null;
    let lastCallArgs;
    const later = () => {
        timerId = null;
        if (pending) {
            fn(...lastCallArgs);
            timerId = setTimeout(later, time);
            pending = false;
        }
    };
    return (...args) => {
        pending = true;
        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;
                const parts = hash.split('&').map(part => part.split('='));
                for (const part of parts) {
                    if (part[0] === this._hashName) {
                        keyval = part;
                    }
                }
                return (keyval ? keyval[1] || '' : '').split('/');
            }
            return hash.split('/');
        };
        this._onHashChange = () => {
            const hash = this._getCurrentHash();
            if (!this._isValidHash(hash)) {
                return false;
            }
            const bearing = this._map.dragRotate.isEnabled() && this._map.touchZoomRotate.isEnabled() ? +(hash[3] || 0) : this._map.getBearing();
            this._map.jumpTo({
                center: [+hash[2], +hash[1]],
                zoom: +hash[0],
                bearing,
                pitch: +(hash[4] || 0)
            });
            return true;
        };
        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}`;
    }
    _isValidHash(hash) {
        if (hash.length < 3 || hash.some(isNaN)) {
            return false;
        }
        // LngLat() throws error if latitude is out of range, and it's valid if it succeeds.
        try {
            new symbol_layout.LngLat(+hash[2], +hash[1]);
        }
        catch (_a) {
            return false;
        }
        const zoom = +hash[0];
        const bearing = +(hash[3] || 0);
        const pitch = +(hash[4] || 0);
        return zoom >= this._map.getMinZoom() && zoom <= this._map.getMaxZoom() &&
            bearing >= -180 && bearing <= 180 &&
            pitch >= this._map.getMinPitch() && pitch <= this._map.getMaxPitch();
    }
    ;
}

const defaultInertiaOptions = {
    linearity: 0.3,
    easing: symbol_layout.bezier(0, 0, 0.3, 1),
};
const defaultPanInertiaOptions = symbol_layout.extend({
    deceleration: 2500,
    maxSpeed: 1400
}, defaultInertiaOptions);
const defaultZoomInertiaOptions = symbol_layout.extend({
    deceleration: 20,
    maxSpeed: 1400
}, defaultInertiaOptions);
const defaultBearingInertiaOptions = symbol_layout.extend({
    deceleration: 1000,
    maxSpeed: 360
}, defaultInertiaOptions);
const defaultPitchInertiaOptions = symbol_layout.extend({
    deceleration: 1000,
    maxSpeed: 90
}, defaultInertiaOptions);
const defaultRollInertiaOptions = symbol_layout.extend({
    deceleration: 1000,
    maxSpeed: 360
}, defaultInertiaOptions);
class HandlerInertia {
    constructor(map) {
        this._map = map;
        this.clear();
    }
    clear() {
        this._inertiaBuffer = [];
    }
    record(settings) {
        this._drainInertiaBuffer();
        this._inertiaBuffer.push({ time: now(), settings });
    }
    _drainInertiaBuffer() {
        const inertia = this._inertiaBuffer, currentTime = now(), cutoff = 160; //msec
        while (inertia.length > 0 && currentTime - inertia[0].time > cutoff)
            inertia.shift();
    }
    _onMoveEnd(panInertiaOptions) {
        this._drainInertiaBuffer();
        if (this._inertiaBuffer.length < 2) {
            return;
        }
        const deltas = {
            zoom: 0,
            bearing: 0,
            pitch: 0,
            roll: 0,
            pan: new symbol_layout.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;
            deltas.roll += settings.rollDelta || 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, symbol_layout.extend({}, defaultPanInertiaOptions, panInertiaOptions || {}));
            const finalPan = deltas.pan.mult(result.amount / deltas.pan.mag());
            const computedEaseOptions = this._map.cameraHelper.handlePanInertia(finalPan, this._map.transform);
            easeOptions.center = computedEaseOptions.easingCenter;
            easeOptions.offset = computedEaseOptions.easingOffset;
            extendDuration(easeOptions, result);
        }
        if (deltas.zoom) {
            const result = calculateEasing(deltas.zoom, duration, defaultZoomInertiaOptions);
            easeOptions.zoom = symbol_layout.evaluateZoomSnap(this._map.transform.zoom + result.amount, this._map.getZoomSnap(), result.amount);
            extendDuration(easeOptions, result);
        }
        if (deltas.bearing) {
            const result = calculateEasing(deltas.bearing, duration, defaultBearingInertiaOptions);
            easeOptions.bearing = this._map.transform.bearing + symbol_layout.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 (deltas.roll) {
            const result = calculateEasing(deltas.roll, duration, defaultRollInertiaOptions);
            easeOptions.roll = this._map.transform.roll + symbol_layout.clamp(result.amount, -179, 179);
            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 symbol_layout.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 = symbol_layout.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 symbol_layout.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 = {}) {
        originalEvent = originalEvent instanceof MouseEvent ? originalEvent : new MouseEvent(type, originalEvent);
        const point = DOM.mousePos(map.getCanvas(), originalEvent);
        const lngLat = map.unproject(point);
        super(type, symbol_layout.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 symbol_layout.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 symbol_layout.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 symbol_layout.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.screenPointToLocation(symbol_layout.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;
        if (options.boxZoom && typeof options.boxZoom === 'object') {
            this._boxZoomEnd = options.boxZoom.boxZoomEnd;
        }
    }
    /**
     * 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);
        this._box.style.transform = `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 symbol_layout.Event('boxzoomend', { originalEvent: e }));
            if (this._boxZoomEnd) {
                this._boxZoomEnd(this._map, p0, p1, e);
                return;
            }
            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) {
            this._box.remove();
            this._box = null;
        }
        DOM.enableDrag();
        delete this._startPos;
        delete this._lastPos;
    }
    _fireEvent(type, e) {
        return this._map.fire(new symbol_layout.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 symbol_layout.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: symbol_layout.evaluateZoomSnap(tr.zoom + 1, map.getZoomSnap()),
                    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: symbol_layout.evaluateZoomSnap(tr.zoom - 1, map.getZoomSnap()),
                    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.rollDelta || 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 = Array.isArray(point) ? 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 = Array.isArray(point) ? 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) {
        this._eventButton = e.button;
    }
    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 = e.button;
        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) {
        this._firstTouch = e.targetTouches[0].identifier;
    }
    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);
    }
}
class MouseOrTouchMoveStateManager {
    constructor(mouseMoveStateManager = new MouseMoveStateManager({ checkCorrectEvent: () => true }), oneFingerTouchMoveStateManager = new OneFingerTouchMoveStateManager()) {
        this.mouseMoveStateManager = mouseMoveStateManager;
        this.oneFingerTouchMoveStateManager = oneFingerTouchMoveStateManager;
    }
    _executeRelevantHandler(e, onMouseEvent, onTouchEvent) {
        if (e instanceof MouseEvent)
            return onMouseEvent(e);
        if (typeof TouchEvent !== 'undefined' && e instanceof TouchEvent)
            return onTouchEvent(e);
    }
    startMove(e) {
        this._executeRelevantHandler(e, e => { this.mouseMoveStateManager.startMove(e); }, e => { this.oneFingerTouchMoveStateManager.startMove(e); });
    }
    endMove(e) {
        this._executeRelevantHandler(e, e => { this.mouseMoveStateManager.endMove(e); }, e => { this.oneFingerTouchMoveStateManager.endMove(e); });
    }
    isValidStartEvent(e) {
        return this._executeRelevantHandler(e, e => this.mouseMoveStateManager.isValidStartEvent(e), e => this.oneFingerTouchMoveStateManager.isValidStartEvent(e));
    }
    isValidMoveEvent(e) {
        return this._executeRelevantHandler(e, e => this.mouseMoveStateManager.isValidMoveEvent(e), e => this.oneFingerTouchMoveStateManager.isValidMoveEvent(e));
    }
    isValidEndEvent(e) {
        return this._executeRelevantHandler(e, e => this.mouseMoveStateManager.isValidEndEvent(e), e => this.oneFingerTouchMoveStateManager.isValidEndEvent(e));
    }
}

const LEFT_BUTTON = 0;
const RIGHT_BUTTON = 2;
const assignEvents = (handler) => {
    handler.mousedown = handler.dragStart;
    handler.mousemoveWindow = handler.dragMove;
    handler.mouseup = handler.dragEnd;
    handler.contextmenu = (e) => {
        e.preventDefault();
    };
};
function generateMousePanHandler({ enable, clickTolerance }) {
    const mouseMoveStateManager = new MouseMoveStateManager({
        checkCorrectEvent: (e) => e.button === LEFT_BUTTON && !e.ctrlKey,
    });
    return new DragHandler({
        clickTolerance,
        move: (lastPoint, point) => ({ around: point, panDelta: point.sub(lastPoint) }),
        activateOnStart: true,
        moveStateManager: mouseMoveStateManager,
        enable,
        assignEvents,
    });
}
;
function generateMouseRotationHandler({ enable, clickTolerance, aroundCenter = true, minPixelCenterThreshold = 100, rotateDegreesPerPixelMoved = 0.8 }, getCenter) {
    const mouseMoveStateManager = new MouseMoveStateManager({
        checkCorrectEvent: (e) => (e.button === LEFT_BUTTON && e.ctrlKey) ||
            (e.button === RIGHT_BUTTON && !e.ctrlKey),
    });
    return new DragHandler({
        clickTolerance,
        move: (lastPoint, currentPoint) => {
            const center = getCenter();
            if (aroundCenter && Math.abs(center.y - lastPoint.y) > minPixelCenterThreshold) {
                // Avoid rotation related to y axis since it is "saved" for pitch
                return { bearingDelta: symbol_layout.getAngleDelta(new symbol_layout.Point(lastPoint.x, currentPoint.y), currentPoint, center) };
            }
            let bearingDelta = (currentPoint.x - lastPoint.x) * rotateDegreesPerPixelMoved;
            if (aroundCenter && currentPoint.y < center.y) {
                bearingDelta = -bearingDelta;
            }
            return { bearingDelta };
        },
        // 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,
    });
}
;
function generateMousePitchHandler({ enable, clickTolerance, pitchDegreesPerPixelMoved = -0.5 }) {
    const mouseMoveStateManager = new MouseMoveStateManager({
        checkCorrectEvent: (e) => (e.button === LEFT_BUTTON && e.ctrlKey) ||
            (e.button === 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,
    });
}
;
function generateMouseRollHandler({ enable, clickTolerance, rollDegreesPerPixelMoved = 0.3 }, getCenter) {
    const mouseMoveStateManager = new MouseMoveStateManager({
        checkCorrectEvent: (e) => (e.button === RIGHT_BUTTON && e.ctrlKey),
    });
    return new DragHandler({
        clickTolerance,
        move: (lastPoint, currentPoint) => {
            const center = getCenter();
            let rollDelta = (currentPoint.x - lastPoint.x) * rollDegreesPerPixelMoved;
            if (currentPoint.y < center.y) {
                rollDelta = -rollDelta;
            }
            return { rollDelta };
        },
        // prevent browser context menu when necessary; we don't allow it with roll
        // because we can't discern roll gesture start from contextmenu on Mac
        moveStateManager: mouseMoveStateManager,
        enable,
        assignEvents,
    });
}
;

/**
 * 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 symbol_layout.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 symbol_layout.Point(0, 0);
        const touchDeltaSum = new symbol_layout.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) {
        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 defaultZoomRate$2 = 1;
const defaultZoomThreshold = 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 {
    constructor() {
        super();
        this._zoomRate = defaultZoomRate$2;
        this._zoomThreshold = defaultZoomThreshold;
    }
    /**
     * Sets the zoom rate of touch gestures.
     * @param zoomRate - 1 The rate used to scale touch movement to a zoom value. Set to `undefined` to restore the default.
     * @example
     * Slow down touch zoom
     * ```ts
     * map.touchZoomRotate.setZoomRate(0.5);
     * ```
     */
    setZoomRate(zoomRate) {
        this._zoomRate = zoomRate !== null && zoomRate !== void 0 ? zoomRate : defaultZoomRate$2;
    }
    /**
     * Sets the threshold before a pinch gesture starts zooming.
     * @param zoomThreshold - 0.1 The minimum zoom delta before the pinch gesture becomes active. Set to `undefined` to restore the default.
     * @example
     * Make pinch zoom less sensitive
     * ```ts
     * map.touchZoomRotate.setZoomThreshold(0.3);
     * ```
     */
    setZoomThreshold(zoomThreshold) {
        this._zoomThreshold = zoomThreshold !== null && zoomThreshold !== void 0 ? zoomThreshold : defaultZoomThreshold;
    }
    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)) < this._zoomThreshold)
            return;
        this._active = true;
        return {
            zoomDelta: getZoomDelta(this._distance, lastDistance) * this._zoomRate,
            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 ? symbol_layout.evaluateZoomSnap(tr.zoom + zoomDir * (e.shiftKey ? 2 : 1), map.getZoomSnap()) : 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 = 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;
// Minimum time difference value to be used for calculating zoom easing in renderFrame();
// this is used to normalise very fast (typically 0 to 0.3ms) repeating lastWheelEventTimeDiff
// values generated by Chromium based browsers during fast scrolling wheel events.
const wheelEventTimeDiffAdjustment = 5;
/**
 * 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$1;
        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 currentTime = now(), timeDelta = currentTime - (this._lastWheelEventTime || 0);
        this._lastWheelEventTime = currentTime;
        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;
        // Whether aroundPoint is actually unprojectable is not a problem to be solved here, but in handler_manager.ts instead.
        if (this._aroundCenter) {
            this._aroundPoint = tr.transform.locationToScreenPoint(symbol_layout.LngLat.convert(tr.center));
        }
        else {
            this._aroundPoint = pos;
        }
        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;
        // When globe is enabled zoom might be modified by the map center latitude being changes (either by panning or by zoom moving the map)
        if (typeof this._lastExpectedZoom === 'number') {
            const externalZoomChange = tr.zoom - this._lastExpectedZoom;
            if (typeof this._startZoom === 'number') {
                this._startZoom += externalZoomChange;
            }
            if (typeof this._targetZoom === 'number') {
                this._targetZoom += externalZoomChange;
            }
        }
        // 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 so the map responds to small scrolls and compresses large scrolls
            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.scale : symbol_layout.zoomScale(this._targetZoom);
            const target = tr.applyConstrain(tr.getCameraLngLat(), symbol_layout.scaleZoom(fromScale * scale)).zoom;
            const zoomSnap = this._map.getZoomSnap();
            if (this._type === 'wheel' && zoomSnap > 0) {
                const currentSnapped = symbol_layout.evaluateZoomSnap(tr.zoom, zoomSnap);
                this._targetZoom = symbol_layout.evaluateZoomSnap(target, zoomSnap, target - currentSnapped);
            }
            else {
                this._targetZoom = target;
            }
            // 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' ? tr.zoom : this._targetZoom;
        const startZoom = this._startZoom;
        const easing = this._easing;
        let finished = false;
        let zoom;
        if (this._type === 'wheel' && startZoom && easing) {
            const lastWheelEventTimeDiff = now() - this._lastWheelEventTime;
            const t = Math.min((lastWheelEventTimeDiff + wheelEventTimeDiffAdjustment) / 200, 1);
            const k = easing(t);
            zoom = symbol_layout.interpolateFactory.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._lastExpectedZoom;
                delete this._finishTimeout;
            }, 200);
        }
        this._lastExpectedZoom = zoom;
        return {
            noInertia: true,
            needsRenderFrame: !finished,
            zoomDelta: zoom - tr.zoom,
            around: this._aroundPoint,
            originalEvent: this._lastWheelEvent
        };
    }
    _smoothOutEasing(duration) {
        let easing = symbol_layout.defaultEasing;
        if (this._prevEase) {
            const currentEase = this._prevEase;
            const t = (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 = symbol_layout.bezier(x, y, 0.25, 1);
        }
        this._prevEase = {
            start: now(),
            duration,
            easing
        };
        return easing;
    }
    reset() {
        this._active = false;
        this._zooming = false;
        delete this._targetZoom;
        delete this._lastExpectedZoom;
        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: symbol_layout.evaluateZoomSnap(this._tr.zoom + (e.shiftKey ? -1 : 1), map.getZoomSnap()),
                    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;
    }
}

const defaultZoomRate = 1;
/**
 * 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._zoomRate = defaultZoomRate;
        this.reset();
    }
    setZoomRate(zoomRate) {
        this._zoomRate = zoomRate !== null && zoomRate !== void 0 ? zoomRate : defaultZoomRate;
    }
    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 * this._zoomRate
            };
        }
    }
    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, mouseRoll) {
        this._pitchWithRotate = options.pitchWithRotate;
        this._rollEnabled = options.rollEnabled;
        this._mouseRotate = mouseRotate;
        this._mousePitch = mousePitch;
        this._mouseRoll = mouseRoll;
    }
    /**
     * Enables the "drag to rotate" interaction.
     *
     * @example
     * ```ts
     * map.dragRotate.enable();
     * ```
     */
    enable() {
        this._mouseRotate.enable();
        if (this._pitchWithRotate)
            this._mousePitch.enable();
        if (this._rollEnabled)
            this._mouseRoll.enable();
    }
    /**
     * Disables the "drag to rotate" interaction.
     *
     * @example
     * ```ts
     * map.dragRotate.disable();
     * ```
     */
    disable() {
        this._mouseRotate.disable();
        this._mousePitch.disable();
        this._mouseRoll.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()) && (!this._rollEnabled || this._mouseRoll.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() || this._mouseRoll.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();
    }
    /**
     * Sets the zoom rate of touch gestures.
     * @param zoomRate - 1 The rate used to scale touch movement to a zoom value. Set to `undefined` to restore the default.
     * @example
     * Slow down touch zoom
     * ```ts
     * map.touchZoomRotate.setZoomRate(0.5);
     * ```
     */
    setZoomRate(zoomRate) {
        this._touchZoom.setZoomRate(zoomRate);
        this._tapDragZoom.setZoomRate(zoomRate);
    }
    /**
     * Sets the threshold before a pinch gesture starts zooming.
     * @param zoomThreshold - 0.1 The minimum zoom delta before the pinch gesture becomes active. Set to `undefined` to restore the default.
     * @example
     * Make pinch zoom less sensitive
     * ```ts
     * map.touchZoomRotate.setZoomThreshold(0.3);
     * ```
     */
    setZoomThreshold(zoomThreshold) {
        this._touchZoom.setZoomThreshold(zoomThreshold);
    }
    /**
     * 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.includes('Mac') ? '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) {
            this._container.remove();
            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 symbol_layout.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.roll || p.pitch || p.rotate;
class RenderFrameEvent extends symbol_layout.Event {
}
function hasChange(result) {
    var _a;
    return ((_a = result.panDelta) === null || _a === void 0 ? void 0 : _a.mag()) || result.zoomDelta || result.bearingDelta || result.pitchDelta || result.rollDelta;
}
class HandlerManager {
    /**
     * @internal
     * The document that contains the map container element, for cross-window support.
     */
    get _ownerDocument() {
        var _a;
        return ((_a = this._el) === null || _a === void 0 ? void 0 : _a.ownerDocument) || document;
    }
    /**
     * @internal
     * The window that contains the map container element, for cross-window support.
     */
    get _ownerWindow() {
        var _a, _b;
        return ((_b = (_a = this._el) === null || _a === void 0 ? void 0 : _a.ownerDocument) === null || _b === void 0 ? void 0 : _b.defaultView) || window;
    }
    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 = {};
            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]) {
                        if (symbol_layout.isPointableEvent(e, eventName || e.type)) {
                            const point = DOM.mousePos(this._map.getCanvas(), e);
                            data = handler[eventName || e.type](e, point);
                        }
                        else if (symbol_layout.isTouchableEvent(e, eventName || e.type)) {
                            const eventTouches = e.touches;
                            const mapTouches = this._getMapTouches(eventTouches);
                            const points = DOM.touchPos(this._map.getCanvas(), mapTouches);
                            data = handler[eventName || e.type](e, points, mapTouches);
                        }
                        else if (!symbol_layout.isTouchableOrPointableType(eventName || e.type)) {
                            data = handler[eventName || e.type](e);
                        }
                        this.mergeHandlerResult(mergedHandlerResult, eventsInProgress, data, handlerName, inputEvent);
                        if (data === null || data === void 0 ? void 0 : 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.
            [this._ownerDocument, 'mousemove', { capture: true }],
            [this._ownerDocument, '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],
            [this._ownerWindow, 'blur', undefined]
        ];
        for (const [target, type, listenerOptions] of this._listeners) {
            target.addEventListener(type, target === this._ownerDocument ? this.handleWindowEvent : this.handleEvent, listenerOptions);
        }
    }
    destroy() {
        for (const [target, type, listenerOptions] of this._listeners) {
            target.removeEventListener(type, target === this._ownerDocument ? 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 getCenter = () => map.project(map.getCenter());
        const mouseRotate = generateMouseRotationHandler(options, getCenter);
        const mousePitch = generateMousePitchHandler(options);
        const mouseRoll = generateMouseRollHandler(options, getCenter);
        map.dragRotate = new DragRotateHandler(options, mouseRotate, mousePitch, mouseRoll);
        this._add('mouseRotate', mouseRotate, ['mousePitch']);
        this._add('mousePitch', mousePitch, ['mouseRotate', 'mouseRoll']);
        this._add('mouseRoll', mouseRoll, ['mousePitch']);
        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);
        }
        this._add('blockableMapEvent', new BlockableMapEventHandler(map));
        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();
        }
    }
    _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 === null || allowed === void 0 ? void 0 : allowed.includes(name))) {
                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;
        symbol_layout.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.rollDelta !== undefined) {
            eventsInProgress.roll = 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 symbol_layout.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.rollDelta)
                combined.rollDelta = (combined.rollDelta || 0) + change.rollDelta;
            if (change.around !== undefined)
                combined.around = change.around;
            if (change.pinchAround !== undefined)
                combined.pinchAround = change.pinchAround;
            if (change.noInertia)
                combined.noInertia = change.noInertia;
            symbol_layout.extend(combinedEventsInProgress, eventsInProgress);
            symbol_layout.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)) {
            this._fireEvents(combinedEventsInProgress, deactivatedHandlers, true);
            return;
        }
        // stop any ongoing camera animations (easeTo, flyTo)
        map._stop(true);
        let { panDelta, zoomDelta, bearingDelta, pitchDelta, rollDelta, around, pinchAround } = combinedResult;
        if (pinchAround !== undefined) {
            around = pinchAround;
        }
        around = around || map.transform.centerPoint;
        if (terrain && !tr.isPointOnMapSurface(around)) {
            around = tr.centerPoint;
        }
        const deltasForHelper = {
            panDelta,
            zoomDelta,
            rollDelta,
            pitchDelta,
            bearingDelta,
            around,
        };
        // Pre-zoom location under the mouse cursor is required for accurate mercator panning and zooming
        if (this._map.cameraHelper.useGlobeControls && !tr.isPointOnMapSurface(around)) {
            around = tr.centerPoint;
        }
        // If we are rotating about the center point, avoid numerical issues near the horizon by using the transform's
        // center directly, instead of computing it from the screen point
        const preZoomAroundLoc = around.distSqr(tr.centerPoint) < 1.0e-2 ?
            tr.center :
            tr.screenPointToLocation(panDelta ? around.sub(panDelta) : around);
        this._handleMapControls({
            terrain,
            tr,
            deltasForHelper,
            preZoomAroundLoc,
            combinedEventsInProgress,
            panDelta,
        });
        map._applyUpdatedTransform(tr);
        this._map._update();
        if (!combinedResult.noInertia)
            this._inertia.record(combinedResult);
        this._fireEvents(combinedEventsInProgress, deactivatedHandlers, true);
    }
    _handleMapControls({ terrain, tr, deltasForHelper, preZoomAroundLoc, combinedEventsInProgress, panDelta }) {
        const cameraHelper = this._map.cameraHelper;
        cameraHelper.handleMapControlsRollPitchBearingZoom(deltasForHelper, tr);
        if (!terrain) {
            cameraHelper.handleMapControlsPan(deltasForHelper, tr, preZoomAroundLoc);
            return;
        }
        if (cameraHelper.useGlobeControls) {
            if (!this._terrainMovement && (combinedEventsInProgress.drag || combinedEventsInProgress.zoom)) {
                this._terrainMovement = true;
                this._map._elevationFreeze = true;
            }
            cameraHelper.handleMapControlsPan(deltasForHelper, tr, preZoomAroundLoc);
            return;
        }
        if (!this._terrainMovement && (combinedEventsInProgress.drag || combinedEventsInProgress.zoom)) {
            this._terrainMovement = true;
            this._map._elevationFreeze = true;
            cameraHelper.handleMapControlsPan(deltasForHelper, tr, preZoomAroundLoc);
            return;
        }
        if (combinedEventsInProgress.drag && this._terrainMovement && panDelta) {
            tr.setCenter(tr.screenPointToLocation(tr.centerPoint.sub(panDelta)));
            return;
        }
        cameraHelper.handleMapControlsPan(deltasForHelper, tr, preZoomAroundLoc);
    }
    _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();
            if (this._map.getCenterClampedToGround()) {
                tr.recalculateZoomAndCenter(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 symbol_layout.Event('moveend', { originalEvent: originalEndEvent }));
                if (shouldSnapToNorth(this._map.getBearing())) {
                    this._map.resetNorth();
                }
            }
            this._updatingCamera = false;
        }
    }
    _fireEvent(type, e) {
        this._map.fire(new symbol_layout.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 symbol_layout.Evented {
    constructor(transform, cameraHelper, options) {
        super();
        // Callback for map._requestRenderFrame
        this._renderFrameCallback = () => {
            const t = Math.min((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._zoomSnap = options.zoomSnap;
        this.cameraHelper = cameraHelper;
        this.on('moveend', () => {
            delete this._requestedCameraState;
        });
    }
    /**
     * @internal
     * Creates a new specialized transform instance from a projection instance and migrates
     * to this new transform, carrying over all the properties of the old transform (center, pitch, etc.).
     * When the style's projection is changed (or first set), this function should be called.
     */
    migrateProjection(newTransform, newCameraHelper) {
        newTransform.apply(this.transform, true);
        this.transform = newTransform;
        this.cameraHelper = newCameraHelper;
    }
    /**
     * 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 symbol_layout.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);
    }
    /**
     * Returns the elevation of the map's center point.
     *
     * @returns The elevation of the map's center point, in meters above sea level.
     */
    getCenterElevation() { return this.transform.elevation; }
    /**
     * Sets the elevation of the map's center point, in meters above sea level. Equivalent to `jumpTo({elevation: elevation})`.
     *
     * Triggers the following events: `movestart` and `moveend`.
     *
     * @param elevation - The elevation to set, in meters above sea level.
     * @param eventData - Additional properties to be added to event objects of events triggered by this method.
     */
    setCenterElevation(elevation, eventData) {
        this.jumpTo({ elevation }, eventData);
        return this;
    }
    /**
     * Returns the value of `centerClampedToGround`.
     *
     * If true, the elevation of the center point will automatically be set to the terrain elevation
     * (or zero if terrain is not enabled). If false, the elevation of the center point will default
     * to sea level and will not automatically update. Defaults to true. Needs to be set to false to
     * keep the camera above ground when pitch \> 90 degrees.
     */
    getCenterClampedToGround() { return this._centerClampedToGround; }
    /**
     * Sets the value of `centerClampedToGround`.
     *
     * If true, the elevation of the center point will automatically be set to the terrain elevation
     * (or zero if terrain is not enabled). If false, the elevation of the center point will default
     * to sea level and will not automatically update. Defaults to true. Needs to be set to false to
     * keep the camera above ground when pitch \> 90 degrees.
     */
    setCenterClampedToGround(centerClampedToGround) {
        this._centerClampedToGround = centerClampedToGround;
    }
    /**
     * 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/navigate-the-map-with-game-like-controls/)
     */
    panBy(offset, options, eventData) {
        offset = symbol_layout.Point.convert(offset).mult(-1);
        return this.panTo(this.transform.center, symbol_layout.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/update-a-feature-in-realtime/)
     */
    panTo(lnglat, options, eventData) {
        return this.easeTo(symbol_layout.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(symbol_layout.extend({
            zoom
        }, options), eventData);
    }
    /**
     * Incrementally increases the map's zoom level by 1, first snapping to the nearest `zoomSnap` increment.
     *
     * 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(symbol_layout.evaluateZoomSnap(this.getZoom() + 1, this._zoomSnap), options, eventData);
        return this;
    }
    /**
     * Decreases the map's zoom level by 1, first snapping to the nearest `zoomSnap` increment.
     *
     * 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(symbol_layout.evaluateZoomSnap(this.getZoom() - 1, this._zoomSnap), options, eventData);
        return this;
    }
    /**
     * Returns the map's current vertical field of view, in degrees.
     *
     * @returns The map's current vertical field of view.
     * @defaultValue 36.87
     * @example
     * ```ts
     * const verticalFieldOfView = map.getVerticalFieldOfView();
     * ```
     */
    getVerticalFieldOfView() { return this.transform.fov; }
    /**
     * Sets the map's vertical field of view, in degrees.
     *
     * Triggers the following events: `movestart`, `move`, and `moveend`.
     *
     * @param fov - The vertical field of view to set, in degrees (0-180).
     * @param eventData - Additional properties to be added to event objects of events triggered by this method.
     * @defaultValue 36.87
     * @example
     * Change vertical field of view to 30 degrees
     * ```ts
     * map.setVerticalFieldOfView(30);
     * ```
     */
    setVerticalFieldOfView(fov, eventData) {
        if (fov != this.transform.fov) {
            this.transform.setFov(fov);
            this.fire(new symbol_layout.Event('movestart', eventData))
                .fire(new symbol_layout.Event('move', eventData))
                .fire(new symbol_layout.Event('moveend', 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/navigate-the-map-with-game-like-controls/)
     */
    getBearing() { return this.transform.bearing; }
    /**
     * Sets the map's zoom snap level.
     *
     * @param snap - The zoom snap level to set.
     */
    setZoomSnap(snap) {
        this._zoomSnap = snap;
        return this;
    }
    /**
     * Returns the map's current zoom snap level.
     *
     * @returns The map's current zoom snap level.
     */
    getZoomSnap() {
        return this._zoomSnap;
    }
    /**
     * 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(symbol_layout.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, symbol_layout.extend({ duration: 1000 }, options), eventData);
        return this;
    }
    /**
     * Rotates and pitches the map so that north is up (0° bearing) and pitch and roll are 0°, with an animated transition.
     *
     * Triggers the following events: `movestart`, `move`, `moveend`, `pitchstart`, `pitch`, `pitchend`, `rollstart`, `roll`, `rollend`, 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(symbol_layout.extend({
            bearing: 0,
            pitch: 0,
            roll: 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;
    }
    /**
     * Returns the map's current roll angle.
     *
     * @returns The map's current roll, measured in degrees about the camera boresight.
     */
    getRoll() { return this.transform.roll; }
    /**
     * Sets the map's roll angle. Equivalent to `jumpTo({roll: roll})`.
     *
     * Triggers the following events: `movestart`, `moveend`, `rollstart`, and `rollend`.
     *
     * @param roll - The roll to set, measured in degrees about the camera boresight
     * @param eventData - Additional properties to be added to event objects of events triggered by this method.
     */
    setRoll(roll, eventData) {
        this.jumpTo({ roll }, eventData);
        return this;
    }
    /**
     * @param bounds - Calculate the center for these bounds in the viewport and use
     * the highest zoom level up to and including {@link 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 === null || options === void 0 ? void 0 : 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 {@link Map.getMaxZoom} that fits
     * the AABB defined by these 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 = symbol_layout.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
            };
        }
        const padding = symbol_layout.extend(defaultPadding, options.padding);
        options.padding = padding;
        const tr = this.transform;
        const bounds = new LngLatBounds(p0, p1);
        const result = this.cameraHelper.cameraForBoxAndBearing(options, padding, bounds, bearing, tr);
        if (result && this._zoomSnap) {
            result.zoom = symbol_layout.evaluateZoomSnap(result.zoom, this._zoomSnap, -1);
        }
        return result;
    }
    /**
     * 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 {@link 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/fit-a-map-to-a-bounding-box/)
     */
    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.screenPointToLocation(symbol_layout.Point.convert(p0)), this.transform.screenPointToLocation(symbol_layout.Point.convert(p1)), bearing, options), options, eventData);
    }
    _fitInternal(calculatedOptions, options, eventData) {
        // cameraForBounds warns + returns undefined if unable to fit:
        if (!calculatedOptions)
            return this;
        options = symbol_layout.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, pitch, and roll, 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`, `rollstart`, `roll`, `rollend` 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-a-series-of-locations/)
     * @see [Update a feature in realtime](https://maplibre.org/maplibre-gl-js/docs/examples/update-a-feature-in-realtime/)
     */
    jumpTo(options, eventData) {
        this.stop();
        if ('zoom' in options && this._zoomSnap) {
            options.zoom = symbol_layout.evaluateZoomSnap(options.zoom, this._zoomSnap);
        }
        const tr = this._getTransformForUpdate();
        let bearingChanged = false, pitchChanged = false;
        let rollChanged = false;
        const oldZoom = tr.zoom;
        if (this.terrain) {
            tr.setElevation(this.terrain.getElevationForLngLatZoom(options.center ? symbol_layout.LngLat.convert(options.center) : tr.center, options.zoom || tr.tileZoom));
        }
        this.cameraHelper.handleJumpToCenterZoom(tr, options);
        const zoomChanged = tr.zoom !== oldZoom;
        if ('elevation' in options && tr.elevation !== +options.elevation) {
            tr.setElevation(+options.elevation);
        }
        if ('bearing' in options && tr.bearing !== +options.bearing) {
            bearingChanged = true;
            tr.setBearing(+options.bearing);
        }
        if ('pitch' in options && tr.pitch !== +options.pitch) {
            pitchChanged = true;
            tr.setPitch(+options.pitch);
        }
        if ('roll' in options && tr.roll !== +options.roll) {
            rollChanged = true;
            tr.setRoll(+options.roll);
        }
        if (options.padding != null && !tr.isPaddingEqual(options.padding)) {
            tr.setPadding(options.padding);
        }
        this._applyUpdatedTransform(tr);
        this.fire(new symbol_layout.Event('movestart', eventData))
            .fire(new symbol_layout.Event('move', eventData));
        if (zoomChanged) {
            this.fire(new symbol_layout.Event('zoomstart', eventData))
                .fire(new symbol_layout.Event('zoom', eventData))
                .fire(new symbol_layout.Event('zoomend', eventData));
        }
        if (bearingChanged) {
            this.fire(new symbol_layout.Event('rotatestart', eventData))
                .fire(new symbol_layout.Event('rotate', eventData))
                .fire(new symbol_layout.Event('rotateend', eventData));
        }
        if (pitchChanged) {
            this.fire(new symbol_layout.Event('pitchstart', eventData))
                .fire(new symbol_layout.Event('pitch', eventData))
                .fire(new symbol_layout.Event('pitchend', eventData));
        }
        if (rollChanged) {
            this.fire(new symbol_layout.Event('rollstart', eventData))
                .fire(new symbol_layout.Event('roll', eventData))
                .fire(new symbol_layout.Event('rollend', eventData));
        }
        return this.fire(new symbol_layout.Event('moveend', eventData));
    }
    /**
     * Given a camera 'from' position and a position to look at (`to`), calculates zoom and camera rotation 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
     * @example
     * ```ts
     * // Calculate options to look from (1°, 0°, 1000m) to (1°, 1°, 0m)
     * const cameraLngLat = new LngLat(1, 0);
     * const cameraAltitude = 1000;
     * const targetLngLat = new LngLat(1, 1);
     * const targetAltitude = 0;
     * const cameraOptions = map.calculateCameraOptionsFromTo(cameraLngLat, cameraAltitude, targetLngLat, targetAltitude);
     * // Apply calculated options
     * map.jumpTo(cameraOptions);
     * ```
     */
    calculateCameraOptionsFromTo(from, altitudeFrom, to, altitudeTo = 0) {
        const fromMercator = symbol_layout.MercatorCoordinate.fromLngLat(from, altitudeFrom);
        const toMercator = symbol_layout.MercatorCoordinate.fromLngLat(to, altitudeTo);
        const dx = toMercator.x - fromMercator.x;
        const dy = toMercator.y - fromMercator.y;
        const dz = toMercator.z - fromMercator.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 = symbol_layout.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: toMercator.toLngLat(),
            elevation: altitudeTo,
            zoom,
            pitch,
            bearing
        };
    }
    /**
     * Given a camera position and rotation, calculates zoom and center point and returns them as {@link CameraOptions}.
     * @param cameraLngLat - The lng, lat of the camera to look from
     * @param cameraAlt - The altitude of the camera to look from, in meters above sea level
     * @param bearing - Bearing of the camera, in degrees
     * @param pitch - Pitch of the camera, in degrees
     * @param roll - Roll of the camera, in degrees
     * @returns the calculated camera options
     * @example
     * ```ts
     * // Calculate options to look from camera position(1°, 0°, 1000m) with bearing = 90°, pitch = 30°, and roll = 45°
     * const cameraLngLat = new LngLat(1, 0);
     * const cameraAltitude = 1000;
     * const bearing = 90;
     * const pitch = 30;
     * const roll = 45;
     * const cameraOptions = map.calculateCameraOptionsFromCameraLngLatAltRotation(cameraLngLat, cameraAltitude, bearing, pitch, roll);
     * // Apply calculated options
     * map.jumpTo(cameraOptions);
     * ```
     */
    calculateCameraOptionsFromCameraLngLatAltRotation(cameraLngLat, cameraAlt, bearing, pitch, roll) {
        const centerInfo = this.transform.calculateCenterFromCameraLngLatAlt(cameraLngLat, cameraAlt, bearing, pitch);
        return {
            center: centerInfo.center,
            elevation: centerInfo.elevation,
            zoom: centerInfo.zoom,
            bearing,
            pitch,
            roll
        };
    }
    /**
     * Changes any combination of `center`, `zoom`, `bearing`, `pitch`, `roll`, 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 "Reduced Motion"
     *     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`, `rollstart`, `roll`, `rollend`, 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/navigate-the-map-with-game-like-controls/)
     */
    easeTo(options, eventData) {
        this._stop(false, options.easeId);
        options = symbol_layout.extend({
            offset: [0, 0],
            duration: 500,
            easing: symbol_layout.defaultEasing
        }, options);
        if ('zoom' in options && this._zoomSnap) {
            options.zoom = symbol_layout.evaluateZoomSnap(options.zoom, this._zoomSnap);
        }
        if (options.animate === false || (!options.essential && browser.prefersReducedMotion)) {
            options.duration = 0;
        }
        const tr = this._getTransformForUpdate();
        const startBearing = this.getBearing(), startPitch = tr.pitch, startRoll = tr.roll, bearing = 'bearing' in options ? this._normalizeBearing(options.bearing, startBearing) : startBearing, pitch = 'pitch' in options ? +options.pitch : startPitch, roll = 'roll' in options ? this._normalizeBearing(options.roll, startRoll) : startRoll, padding = ('padding' in options ? options.padding : tr.padding);
        const offsetAsPoint = symbol_layout.Point.convert(options.offset);
        let around, aroundPoint;
        if (options.around) {
            around = symbol_layout.LngLat.convert(options.around);
            aroundPoint = tr.locationToScreenPoint(around);
        }
        const currently = {
            moving: this._moving,
            zooming: this._zooming,
            rotating: this._rotating,
            pitching: this._pitching,
            rolling: this._rolling
        };
        const easeHandler = this.cameraHelper.handleEaseTo(tr, {
            bearing,
            pitch,
            roll,
            padding,
            around,
            aroundPoint,
            offsetAsPoint,
            offset: options.offset,
            zoom: options.zoom,
            center: options.center,
        });
        this._rotating = this._rotating || (startBearing !== bearing);
        this._pitching = this._pitching || (pitch !== startPitch);
        this._rolling = this._rolling || (roll !== startRoll);
        this._padding = !tr.isPaddingEqual(padding);
        this._zooming = this._zooming || easeHandler.isZooming;
        this._easeId = options.easeId;
        this._prepareEase(eventData, options.noMoveStart, currently);
        if (this.terrain) {
            this._prepareElevation(easeHandler.elevationCenter);
        }
        this._ease((k) => {
            easeHandler.easeFunc(k);
            if (this.terrain && !options.freezeElevation)
                this._updateElevation(k);
            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 symbol_layout.Event('movestart', eventData));
        }
        if (this._zooming && !currently.zooming) {
            this.fire(new symbol_layout.Event('zoomstart', eventData));
        }
        if (this._rotating && !currently.rotating) {
            this.fire(new symbol_layout.Event('rotatestart', eventData));
        }
        if (this._pitching && !currently.pitching) {
            this.fire(new symbol_layout.Event('pitchstart', eventData));
        }
        if (this._rolling && !currently.rolling) {
            this.fire(new symbol_layout.Event('rollstart', 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) {
        if (this._elevationStart === undefined || this._elevationCenter === undefined) {
            this._prepareElevation(this.transform.center);
        }
        this.transform.setMinElevationForCurrentTile(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.setElevation(symbol_layout.interpolateFactory.number(this._elevationStart, this._elevationTarget, k));
    }
    _finalizeElevation() {
        this._elevationFreeze = false;
        if (this.getCenterClampedToGround()) {
            this.transform.recalculateZoomAndCenter(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) {
        if (!this.terrain && tr.elevation >= 0 && tr.pitch <= 90) {
            return {};
        }
        const cameraLngLat = tr.getCameraLngLat();
        const cameraAltitude = tr.getCameraAltitude();
        const minAltitude = this.terrain ? this.terrain.getElevationForLngLatZoom(cameraLngLat, tr.zoom) : 0;
        if (cameraAltitude < minAltitude) {
            const newCamera = this.calculateCameraOptionsFromTo(cameraLngLat, 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 = [];
        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, roll, pitch, bearing, elevation } = modifier(nextTransform);
            if (center)
                nextTransform.setCenter(center);
            if (elevation !== undefined)
                nextTransform.setElevation(elevation);
            if (zoom !== undefined)
                nextTransform.setZoom(zoom);
            if (roll !== undefined)
                nextTransform.setRoll(roll);
            if (pitch !== undefined)
                nextTransform.setPitch(pitch);
            if (bearing !== undefined)
                nextTransform.setBearing(bearing);
            finalTransform.apply(nextTransform, false);
        }
        this.transform.apply(finalTransform, false);
    }
    _fireMoveEvents(eventData) {
        this.fire(new symbol_layout.Event('move', eventData));
        if (this._zooming) {
            this.fire(new symbol_layout.Event('zoom', eventData));
        }
        if (this._rotating) {
            this.fire(new symbol_layout.Event('rotate', eventData));
        }
        if (this._pitching) {
            this.fire(new symbol_layout.Event('pitch', eventData));
        }
        if (this._rolling) {
            this.fire(new symbol_layout.Event('roll', 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;
        const wasRolling = this._rolling;
        this._moving = false;
        this._zooming = false;
        this._rotating = false;
        this._pitching = false;
        this._rolling = false;
        this._padding = false;
        if (wasZooming) {
            this.fire(new symbol_layout.Event('zoomend', eventData));
        }
        if (wasRotating) {
            this.fire(new symbol_layout.Event('rotateend', eventData));
        }
        if (wasPitching) {
            this.fire(new symbol_layout.Event('pitchend', eventData));
        }
        if (wasRolling) {
            this.fire(new symbol_layout.Event('rollend', eventData));
        }
        this.fire(new symbol_layout.Event('moveend', eventData));
    }
    /**
     * Changes any combination of center, zoom, bearing, pitch, and roll, 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 "Reduced Motion"
     *     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`, `rollstart`, `roll`, `rollend`, 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/fly-to-a-location/)
     * @see [Slowly fly to a location](https://maplibre.org/maplibre-gl-js/docs/examples/slowly-fly-to-a-location/)
     * @see [Fly to a location based on scroll position](https://maplibre.org/maplibre-gl-js/docs/examples/fly-to-a-location-based-on-scroll-position/)
     */
    flyTo(options, eventData) {
        // Fall through to jumpTo if user has set prefers-reduced-motion
        if (!options.essential && browser.prefersReducedMotion) {
            const coercedOptions = symbol_layout.pick(options, ['center', 'zoom', 'bearing', 'pitch', 'roll', 'elevation', 'padding']);
            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. <https://www.win.tue.nl/~vanwijk/zoompan.pdf#page=5>.
        //
        // Where applicable, local variable documentation begins with the associated variable or
        // function in van Wijk (2003).
        this.stop();
        options = symbol_layout.extend({
            offset: [0, 0],
            speed: 1.2,
            curve: 1.42,
            easing: symbol_layout.defaultEasing
        }, options);
        if ('zoom' in options && this._zoomSnap) {
            options.zoom = symbol_layout.evaluateZoomSnap(options.zoom, this._zoomSnap);
        }
        const tr = this._getTransformForUpdate(), startBearing = tr.bearing, startPitch = tr.pitch, startRoll = tr.roll, startPadding = tr.padding;
        const bearing = 'bearing' in options ? this._normalizeBearing(options.bearing, startBearing) : startBearing;
        const pitch = 'pitch' in options ? +options.pitch : startPitch;
        const roll = 'roll' in options ? this._normalizeBearing(options.roll, startRoll) : startRoll;
        const padding = ('padding' in options ? options.padding : tr.padding);
        const offsetAsPoint = symbol_layout.Point.convert(options.offset);
        let pointAtOffset = tr.centerPoint.add(offsetAsPoint);
        const locationAtOffset = tr.screenPointToLocation(pointAtOffset);
        const flyToHandler = this.cameraHelper.handleFlyTo(tr, {
            bearing,
            pitch,
            roll,
            padding,
            locationAtOffset,
            offsetAsPoint,
            center: options.center,
            minZoom: options.minZoom,
            zoom: options.zoom,
        });
        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.
        const w1 = w0 / flyToHandler.scaleOfZoom;
        // Length of the flight path as projected onto the ground plane, measured in pixels from
        // the world image origin at the initial scale.
        const u1 = flyToHandler.pixelPathLength;
        if (typeof flyToHandler.scaleOfMinZoom === 'number') {
            // w<sub>m</sub>: Maximum visible span, measured in pixels with respect to the initial
            // scale.
            const wMax = w0 / flyToHandler.scaleOfMinZoom;
            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. Uses the current vertical field of view setting.
        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 ρ-screenfulls.
        let S = (zoomOutFactor(true) - r0) / rho;
        // When u₀ = u₁, the optimal path doesn’t require both ascent and descent.
        if (Math.abs(u1) < 0.000002 || !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._rolling = (roll !== startRoll);
        this._padding = !tr.isPaddingEqual(padding);
        this._prepareEase(eventData, false);
        if (this.terrain)
            this._prepareElevation(flyToHandler.targetCenter);
        this._ease((k) => {
            // s: The distance traveled along the flight path, measured in ρ-screenfulls.
            const s = k * S;
            const scale = 1 / w(s);
            const centerFactor = u(s);
            if (this._rotating) {
                tr.setBearing(symbol_layout.interpolateFactory.number(startBearing, bearing, k));
            }
            if (this._pitching) {
                tr.setPitch(symbol_layout.interpolateFactory.number(startPitch, pitch, k));
            }
            if (this._rolling) {
                tr.setRoll(symbol_layout.interpolateFactory.number(startRoll, roll, 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);
            }
            flyToHandler.easeFunc(k, scale, centerFactor, pointAtOffset);
            if (this.terrain && !options.freezeElevation)
                this._updateElevation(k);
            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 = 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 = symbol_layout.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;
    }
    /**
     * Gets the elevation at a given location, in meters above sea level.
     * Returns null if terrain is not enabled.
     * If terrain is enabled with some exaggeration value, the value returned here will be reflective of (multiplied by) that exaggeration value.
     * This method should be used for proper positioning of custom 3d objects, as explained [here](https://maplibre.org/maplibre-gl-js/docs/examples/adding-3d-models-using-threejs-on-terrain/)
     * @param lngLatLike - [x,y] or LngLat coordinates of the location
     * @returns elevation in meters
     */
    queryTerrainElevation(lngLatLike) {
        if (!this.terrain) {
            return null;
        }
        return this.terrain.getElevationForLngLat(symbol_layout.LngLat.convert(lngLatLike), this.transform);
    }
}

const defaultAttributionControlOptions = {
    compact: true,
    customAttribution: '<a href="https://maplibre.org/" target="_blank">MapLibre</a>'
};
/**
 * 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
 *     }));
 * ```
 * @see [Change the default position for attribution](https://maplibre.org/maplibre-gl-js/docs/examples/change-the-default-position-for-attribution/)
 */
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() {
        this._container.remove();
        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 tileManagers = this._map.style.tileManagers;
        for (const id in tileManagers) {
            const tileManager = tileManagers[id];
            if (tileManager.used || tileManager.usedForTerrain) {
                const source = tileManager.getSource();
                if (source.attribution && !attributions.includes(source.attribution)) {
                    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].includes(attrib)) {
                    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 = DOM.sanitize(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) {
        var _a;
        this._map = map;
        this._compact = (_a = this.options) === null || _a === void 0 ? void 0 : _a.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() {
        this._container.remove();
        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 = symbol_layout.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 TerrainTileManager extends symbol_layout.Evented {
    constructor(tileManager) {
        super();
        /**
         * used to determine whether depth & coord framebuffers need updating
         */
        this._lastTilesetChange = now();
        this.tileManager = tileManager;
        this._tiles = {};
        this._renderableTilesKeys = [];
        this._sourceTileCache = {};
        this.minzoom = 0;
        this.maxzoom = 22;
        this.deltaZoom = 1;
        this.tileSize = tileManager._source.tileSize * 2 ** this.deltaZoom;
        tileManager.usedForTerrain = true;
        tileManager.tileSize = this.tileSize;
    }
    destruct() {
        this.tileManager.usedForTerrain = false;
        this.tileManager.tileSize = null;
    }
    getSource() {
        return this.tileManager._source;
    }
    /**
     * 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.tileManager.update(transform, terrain);
        // create internal render-to-texture tiles for the current scene.
        this._renderableTilesKeys = [];
        const keys = {};
        for (const tileID of coveringTiles(transform, {
            tileSize: this.tileSize,
            minzoom: this.minzoom,
            maxzoom: this.maxzoom,
            reparseOverscaled: false,
            terrain,
            calculateTileZoom: this.tileManager._source.calculateTileZoom
        })) {
            keys[tileID.key] = true;
            this._renderableTilesKeys.push(tileID.key);
            if (!this._tiles[tileID.key]) {
                tileID.terrainRttPosMatrix32f = new Float64Array(16);
                symbol_layout.ortho(tileID.terrainRttPosMatrix32f, 0, symbol_layout.EXTENT, symbol_layout.EXTENT, 0, 0, 1);
                this._tiles[tileID.key] = new Tile(tileID, this.tileSize);
                this._lastTilesetChange = now();
            }
        }
        // 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, terrainTileRanges) {
        if (terrainTileRanges) {
            return this._getTerrainCoordsForTileRanges(tileID, terrainTileRanges);
        }
        else {
            return this._getTerrainCoordsForRegularTile(tileID);
        }
    }
    /**
     * Searches for the corresponding current renderable terrain-tiles.
     * Includes terrain tiles that are either:
     * - the same as the tileID
     * - a parent of the tileID
     * - a child of the tileID
     * @param tileID - the tile to look for
     * @returns the tiles that were found
     */
    _getTerrainCoordsForRegularTile(tileID) {
        const coords = {};
        for (const key of this._renderableTilesKeys) {
            const terrainTileID = this._tiles[key].tileID;
            const coord = tileID.clone();
            const mat = symbol_layout.createMat4f64();
            if (terrainTileID.canonical.equals(tileID.canonical)) {
                symbol_layout.ortho(mat, 0, symbol_layout.EXTENT, symbol_layout.EXTENT, 0, 0, 1);
            }
            else if (terrainTileID.canonical.isChildOf(tileID.canonical)) {
                const dz = terrainTileID.canonical.z - tileID.canonical.z;
                const dx = terrainTileID.canonical.x - (terrainTileID.canonical.x >> dz << dz);
                const dy = terrainTileID.canonical.y - (terrainTileID.canonical.y >> dz << dz);
                const size = symbol_layout.EXTENT >> dz;
                symbol_layout.ortho(mat, 0, size, size, 0, 0, 1); // Note: we are using `size` instead of `EXTENT` here
                symbol_layout.translate(mat, mat, [-dx * size, -dy * size, 0]);
            }
            else if (tileID.canonical.isChildOf(terrainTileID.canonical)) {
                const dz = tileID.canonical.z - terrainTileID.canonical.z;
                const dx = tileID.canonical.x - (tileID.canonical.x >> dz << dz);
                const dy = tileID.canonical.y - (tileID.canonical.y >> dz << dz);
                const size = symbol_layout.EXTENT >> dz;
                symbol_layout.ortho(mat, 0, symbol_layout.EXTENT, symbol_layout.EXTENT, 0, 0, 1);
                symbol_layout.translate(mat, mat, [dx * size, dy * size, 0]);
                symbol_layout.scale(mat, mat, [1 / (2 ** dz), 1 / (2 ** dz), 0]);
            }
            else {
                continue;
            }
            coord.terrainRttPosMatrix32f = new Float32Array(mat);
            coords[key] = coord;
        }
        return coords;
    }
    /**
     * Searches for the corresponding current renderable terrain-tiles.
     * Includes terrain tiles that are within terrain tile ranges.
     * @param tileID - the tile to look for
     * @returns the tiles that were found
     */
    _getTerrainCoordsForTileRanges(tileID, terrainTileRanges) {
        const coords = {};
        for (const key of this._renderableTilesKeys) {
            const terrainTileID = this._tiles[key].tileID;
            if (!this._isWithinTileRanges(terrainTileID, terrainTileRanges)) {
                continue;
            }
            const coord = tileID.clone();
            const mat = symbol_layout.createMat4f64();
            if (terrainTileID.canonical.z === tileID.canonical.z) {
                const dx = tileID.canonical.x - terrainTileID.canonical.x
                    + tileID.wrap * (1 << tileID.canonical.z); // include wrap shift
                const dy = tileID.canonical.y - terrainTileID.canonical.y;
                symbol_layout.ortho(mat, 0, symbol_layout.EXTENT, symbol_layout.EXTENT, 0, 0, 1);
                symbol_layout.translate(mat, mat, [dx * symbol_layout.EXTENT, dy * symbol_layout.EXTENT, 0]);
            }
            else if (terrainTileID.canonical.z > tileID.canonical.z) {
                const dz = terrainTileID.canonical.z - tileID.canonical.z;
                // this translation is needed to project tileID to terrainTileID zoom level
                const dx = terrainTileID.canonical.x - (terrainTileID.canonical.x >> dz << dz)
                    + tileID.wrap * (1 << terrainTileID.canonical.z); // include wrap shift
                const dy = terrainTileID.canonical.y - (terrainTileID.canonical.y >> dz << dz);
                // this translation is needed if terrainTileID is not a parent of tileID
                const dx2 = tileID.canonical.x - (terrainTileID.canonical.x >> dz);
                const dy2 = tileID.canonical.y - (terrainTileID.canonical.y >> dz);
                const size = symbol_layout.EXTENT >> dz;
                symbol_layout.ortho(mat, 0, size, size, 0, 0, 1);
                symbol_layout.translate(mat, mat, [-dx * size + dx2 * symbol_layout.EXTENT, -dy * size + dy2 * symbol_layout.EXTENT, 0]);
            }
            else { // terrainTileID.canonical.z < tileID.canonical.z
                const dz = tileID.canonical.z - terrainTileID.canonical.z;
                // this translation is needed to project tileID to terrainTileID zoom level
                const dx = tileID.canonical.x - (tileID.canonical.x >> dz << dz)
                    + tileID.wrap * (1 << tileID.canonical.z); // include wrap shift
                const dy = tileID.canonical.y - (tileID.canonical.y >> dz << dz);
                // this translation is needed if terrainTileID is not a parent of tileID
                const dx2 = (tileID.canonical.x >> dz) - terrainTileID.canonical.x;
                const dy2 = (tileID.canonical.y >> dz) - terrainTileID.canonical.y;
                const size = symbol_layout.EXTENT << dz;
                symbol_layout.ortho(mat, 0, size, size, 0, 0, 1);
                symbol_layout.translate(mat, mat, [dx * symbol_layout.EXTENT + dx2 * size, dy * symbol_layout.EXTENT + dy2 * size, 0]);
            }
            coord.terrainRttPosMatrix32f = new Float32Array(mat);
            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) source tiles with loaded dem.
     * @returns the tile
     */
    getSourceTile(tileID, searchForDEM) {
        const source = this.tileManager._source;
        let z = tileID.overscaledZ - this.deltaZoom;
        if (z > source.maxzoom)
            z = source.maxzoom;
        if (z < source.minzoom)
            return undefined;
        // cache for tileID to terrain-tileID
        if (!this._sourceTileCache[tileID.key])
            this._sourceTileCache[tileID.key] = tileID.scaledTo(z).key;
        let tile = this.findTileInCaches(this._sourceTileCache[tileID.key]);
        // during tile-loading phase look if parent tiles (with loaded dem) are available.
        if (!(tile === null || tile === void 0 ? void 0 : tile.dem) && searchForDEM) {
            while (z >= source.minzoom && !(tile === null || tile === void 0 ? void 0 : tile.dem))
                tile = this.findTileInCaches(tileID.scaledTo(z--).key);
        }
        return tile;
    }
    findTileInCaches(key) {
        let tile = this.tileManager.getTileByID(key);
        if (tile) {
            return tile;
        }
        tile = this.tileManager._outOfViewCache.getByKey(key);
        return tile;
    }
    /**
     * gets whether any tiles were loaded after a specific time. This is used to update depth & coords framebuffers.
     * @param time - the time
     * @returns true if any tiles came into view at or after the specified time
     */
    anyTilesAfterTime(time = Date.now()) {
        return this._lastTilesetChange >= time;
    }
    /**
     * Checks whether a tile is within the canonical tile ranges.
     * @param tileID - Tile to check
     * @param canonicalTileRanges - Canonical tile ranges
     * @returns
     */
    _isWithinTileRanges(tileID, canonicalTileRanges) {
        const range = canonicalTileRanges[tileID.canonical.z];
        return !!range && (tileID.wrap > range.minWrap || tileID.wrap < range.maxWrap ||
            tileID.canonical.x >= range.minTileXWrapped &&
                tileID.canonical.x <= range.maxTileXWrapped &&
                tileID.canonical.y >= range.minTileY &&
                tileID.canonical.y <= range.maxTileY);
    }
}

/**
 * @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 tileManager this.tileManager
 * 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.tileManager._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, tileManager, options) {
        /**
         * GL Objects for the terrain-mesh
         * The mesh is a regular mesh, which has the advantage that it can be reused for all tiles.
         */
        this._meshCache = {};
        this.painter = painter;
        this.tileManager = new TerrainTileManager(tileManager);
        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;
    }
    destroy() {
        if (this._fbo) {
            this._fbo.destroy();
            this._fbo = null;
        }
        if (this._fboCoordsTexture) {
            this._fboCoordsTexture.destroy();
            this._fboCoordsTexture = null;
        }
        if (this._fboDepthTexture) {
            this._fboDepthTexture.destroy();
            this._fboDepthTexture = null;
        }
        if (this._emptyDemTexture) {
            this._emptyDemTexture.destroy();
            this._emptyDemTexture = null;
        }
        if (this._emptyDepthTexture) {
            this._emptyDepthTexture.destroy();
            this._emptyDepthTexture = null;
        }
        if (this._coordsTexture) {
            this._coordsTexture.destroy();
            this._coordsTexture = null;
        }
        for (const key in this._meshCache) {
            this._meshCache[key].destroy();
        }
        this._meshCache = {};
        this.tileManager.destruct();
    }
    /**
     * Get the elevation-value from original dem-data for a given tile-coordinate.
     * Coordinates that fall outside `[0, extent)` are normalized to the
     * appropriate neighbor tile before lookup.
     * @param tileID - the tile to get the elevation for
     * @param x - x coordinate relative to the tile, may be outside `[0, extent)`
     * @param y - y coordinate relative to the tile, may be outside `[0, extent)`
     * @param extent - optional, default 8192
     * @returns the elevation
     */
    getDEMElevation(tileID, x, y, extent = symbol_layout.EXTENT) {
        var _a;
        const normalized = tileID.normalizeCoordinates(x, y, extent);
        if (!normalized)
            return 0;
        const terrain = this.getTerrainData(normalized.tileID);
        const dem = (_a = terrain.tile) === null || _a === void 0 ? void 0 : _a.dem;
        if (!dem)
            return 0;
        const pos = symbol_layout.transformMat4$2([], [normalized.x / extent * symbol_layout.EXTENT, normalized.y / extent * symbol_layout.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, use {@link getElevationForLngLat} if you don't want a specific zoom level, but more accurate results.
     * @returns the elevation
     */
    getElevationForLngLatZoom(lnglat, zoom) {
        if (!symbol_layout.isInBoundsForZoomLngLat(zoom, lnglat.wrap()))
            return 0;
        const { tileID, mercatorX, mercatorY } = this._getOverscaledTileIDFromLngLatZoom(lnglat, zoom);
        return this.getElevation(tileID, mercatorX % symbol_layout.EXTENT, mercatorY % symbol_layout.EXTENT, symbol_layout.EXTENT);
    }
    /**
     * Get the elevation for given {@link LngLat} in respect of exaggeration.
     * This will traverse up the zoom levels to find the first tile with data to return.
     * @param lnglat - the location
     * @returns the elevation
     */
    getElevationForLngLat(lnglat, transform) {
        const terrainCoveringTiles = coveringTiles(transform, { maxzoom: this.tileManager.maxzoom, minzoom: this.tileManager.minzoom, tileSize: 512, terrain: this });
        let zoom = 0;
        for (const tile of terrainCoveringTiles) {
            if (tile.canonical.z > zoom) {
                zoom = Math.min(tile.canonical.z, this.tileManager.maxzoom);
            }
        }
        return this.getElevationForLngLatZoom(lnglat, zoom);
    }
    /**
     * Get the elevation for given coordinate in respect of exaggeration.
     * @param tileID - the tile id
     * @param x - x coordinate relative to the tile, may be outside `[0, extent)`
     * @param y - y coordinate relative to the tile, may be outside `[0, extent)`
     * @param extent - optional, default 8192
     * @returns the elevation
     */
    getElevation(tileID, x, y, extent = symbol_layout.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) {
        var _a, _b;
        // 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 symbol_layout.RGBAImage({ width: 1, height: 1 }, new Uint8Array(1 * 4));
            this._emptyDepthTexture = new symbol_layout.Texture(context, image, context.gl.RGBA, { premultiply: false });
            this._emptyDemUnpack = [0, 0, 0, 0];
            this._emptyDemTexture = new symbol_layout.Texture(context, new symbol_layout.RGBAImage({ width: 1, height: 1 }), context.gl.RGBA, { premultiply: false });
            this._emptyDemTexture.bind(context.gl.NEAREST, context.gl.CLAMP_TO_EDGE);
            this._emptyDemMatrix = symbol_layout.identity([]);
        }
        // find covering dem tile and prepare demTexture
        const sourceTile = this.tileManager.getSourceTile(tileID, true);
        if ((sourceTile === null || sourceTile === void 0 ? void 0 : 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 symbol_layout.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.toString() + sourceTile.tileID.key + tileID.key;
        if (matrixKey && !this._demMatrixCache[matrixKey]) {
            const maxzoom = this.tileManager.getSource().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
                    symbol_layout.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 = symbol_layout.fromScaling(new Float64Array(16), [1 / (symbol_layout.EXTENT << dz), 1 / (symbol_layout.EXTENT << dz), 0]);
            symbol_layout.translate(demMatrix, demMatrix, [dx * symbol_layout.EXTENT, dy * symbol_layout.EXTENT, 0]);
            this._demMatrixCache[matrixKey] = { matrix: demMatrix, coord: tileID };
        }
        // return uniform values & textures
        return {
            'u_depth': 2,
            'u_terrain': 3,
            'u_terrain_dim': ((_a = sourceTile === null || sourceTile === void 0 ? void 0 : sourceTile.dem) === null || _a === void 0 ? void 0 : _a.dim) || 1,
            'u_terrain_matrix': matrixKey ? this._demMatrixCache[matrixKey].matrix : this._emptyDemMatrix,
            'u_terrain_unpack': ((_b = sourceTile === null || sourceTile === void 0 ? void 0 : sourceTile.dem) === null || _b === void 0 ? void 0 : _b.getUnpackVector()) || this._emptyDemUnpack,
            'u_terrain_exaggeration': this.exaggeration,
            texture: ((sourceTile === null || sourceTile === void 0 ? void 0 : 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 symbol_layout.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 symbol_layout.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 set 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 symbol_layout.RGBAImage({ width: this._coordsTextureSize, height: this._coordsTextureSize }, new Uint8Array(data.buffer));
        const texture = new symbol_layout.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, or null, if the pixel doesn't lie on the terrain's surface (but the sky instead).
     * @param p - Screen-Coordinate
     * @returns Mercator coordinate for a screen pixel, or null, if the pixel is not covered by terrain (is in the sky).
     */
    pointCoordinate(p) {
        // First, ensure the coords framebuffer is up to date.
        this.painter.maybeDrawDepth(true);
        this.painter.maybeDrawCoords();
        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.tileManager.getTileByID(tileID);
        if (!tile) {
            return null;
        }
        const coordsSize = this._coordsTextureSize;
        const worldSize = (1 << tile.tileID.canonical.z) * coordsSize;
        return new symbol_layout.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)
        return (rgba[0] / (256 * 256 * 256) + rgba[1] / (256 * 256) + rgba[2] / 256 + rgba[3]) / 256;
    }
    /**
     * create a regular mesh which will be used by all terrain-tiles
     * @returns the created regular mesh
     */
    getTerrainMesh(tileId) {
        var _a;
        const globeEnabled = ((_a = this.painter.style.projection) === null || _a === void 0 ? void 0 : _a.transitionState) > 0;
        const northPole = globeEnabled && tileId.canonical.y === 0;
        const southPole = globeEnabled && tileId.canonical.y === (1 << tileId.canonical.z) - 1;
        const key = `m_${northPole ? 'n' : ''}_${southPole ? 's' : ''}`;
        if (this._meshCache[key]) {
            return this._meshCache[key];
        }
        const context = this.painter.context;
        const vertexArray = new symbol_layout.Pos3dArray();
        const indexArray = new symbol_layout.TriangleIndexArray();
        const meshSize = this.meshSize;
        const delta = symbol_layout.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 stitching on tile boundaries with different zoomlevels
        // top-bottom frame + pole vertices, if needed
        const offsetTop = vertexArray.length;
        const offsetTopEdge = 0;
        const offsetBottom = offsetTop + (meshSize + 1);
        const offsetBottomEdge = (meshSize + 1) * meshSize;
        const northY = northPole ? symbol_layout.NORTH_POLE_Y : 0;
        const northZ = northPole ? 0 : 1;
        const southY = southPole ? symbol_layout.SOUTH_POLE_Y : symbol_layout.EXTENT;
        const southZ = southPole ? 0 : 1;
        for (let x = 0; x <= meshSize; x++) {
            vertexArray.emplaceBack(x * delta, northY, northZ);
        }
        for (let x = 0; x <= meshSize; x++) {
            vertexArray.emplaceBack(x * delta, southY, southZ);
        }
        for (let x = 0; x < meshSize; x++) {
            indexArray.emplaceBack(offsetBottomEdge + x, offsetBottom + x, offsetBottom + x + 1);
            indexArray.emplaceBack(offsetBottomEdge + x, offsetBottom + x + 1, offsetBottomEdge + x + 1);
            indexArray.emplaceBack(offsetTopEdge + x, offsetTop + x + 1, offsetTop + x);
            indexArray.emplaceBack(offsetTopEdge + x, offsetTopEdge + x + 1, offsetTop + x + 1);
        }
        // left-right frame
        const offsetLeft = vertexArray.length;
        const 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 * symbol_layout.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);
        }
        const mesh = new Mesh(context.createVertexBuffer(vertexArray, pos3dAttributes.members), context.createIndexBuffer(indexArray), symbol_layout.SegmentVector.simpleSegment(0, 0, vertexArray.length, indexArray.length));
        this._meshCache[key] = mesh;
        return mesh;
    }
    /**
     * Calculates a height of the frame around the terrain-mesh to avoid stitching 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 * symbol_layout.earthRadius / Math.pow(2, Math.max(zoom, 0)) / 5;
    }
    getMinTileElevationForLngLatZoom(lnglat, zoom) {
        var _a;
        if (!symbol_layout.isInBoundsForZoomLngLat(zoom, lnglat.wrap()))
            return 0;
        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 === null || tile === void 0 ? void 0 : tile.dem) {
            minMax.minElevation = tile.dem.min * this.exaggeration;
            minMax.maxElevation = tile.dem.max * this.exaggeration;
        }
        return minMax;
    }
    _getOverscaledTileIDFromLngLatZoom(lnglat, zoom) {
        const mercatorCoordinate = symbol_layout.MercatorCoordinate.fromLngLat(lnglat.wrap());
        const worldSize = (1 << zoom) * symbol_layout.EXTENT;
        const mercatorX = mercatorCoordinate.x * worldSize;
        const mercatorY = mercatorCoordinate.y * worldSize;
        const tileX = Math.floor(mercatorX / symbol_layout.EXTENT), tileY = Math.floor(mercatorY / symbol_layout.EXTENT);
        const tileID = new symbol_layout.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 symbol_layout.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);
        if (this._context.extTextureFilterAnisotropic) {
            this._context.gl.texParameterf(this._context.gl.TEXTURE_2D, this._context.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, this._context.extTextureFilterAnisotropicMax);
        }
        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_TO_TEXTURES = {
    background: true,
    fill: true,
    line: true,
    raster: true,
    hillshade: true,
    'color-relief': 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.tileManager.tileSize * terrain.qualityFactor);
    }
    destruct() {
        this.pool.destruct();
    }
    getTexture(tile) {
        return this.pool.getObjectForId(tile.rtt[this._stacks.length - 1].id).texture;
    }
    prepareForRender(style, zoom) {
        var _a, _b;
        this._stacks = [];
        this._prevType = null;
        this._rttTiles = [];
        this._renderableTiles = this.terrain.tileManager.getRenderableTiles();
        this._renderableLayerIds = style._order.filter(id => !style._layers[id].isHidden(zoom));
        this._coordsAscending = {};
        for (const id in style.tileManagers) {
            this._coordsAscending[id] = {};
            const tileIDs = style.tileManagers[id].getVisibleCoordinates();
            const source = style.tileManagers[id].getSource();
            const terrainTileRanges = source instanceof ImageSource ? source.terrainTileRanges : null;
            for (const tileID of tileIDs) {
                const keys = this.terrain.tileManager.getTerrainCoords(tileID, terrainTileRanges);
                for (const key in keys) {
                    if (!this._coordsAscending[id][key])
                        this._coordsAscending[id][key] = [];
                    this._coordsAscending[id][key].push(keys[key]);
                }
            }
        }
        this._rttFingerprints = {};
        for (const id of style._order) {
            const layer = style._layers[id];
            const source = layer.source;
            const shouldRenderToTexture = LAYERS_TO_TEXTURES[layer.type];
            if (shouldRenderToTexture && !this._rttFingerprints[source]) {
                this._rttFingerprints[source] = {};
                const revision = (_b = (_a = style.tileManagers[source]) === null || _a === void 0 ? void 0 : _a.getState().revision) !== null && _b !== void 0 ? _b : 0;
                for (const key in this._coordsAscending[source])
                    this._rttFingerprints[source][key] = `${this._coordsAscending[source][key].map(c => c.key).sort().join()}#${revision}`;
            }
        }
        // check tiles to render
        for (const tile of this._renderableTiles) {
            for (const source in this._rttFingerprints) {
                // rerender if there are different coords to render than in the last rendering
                // or if the source revision has changed
                const fingerprint = this._rttFingerprints[source][tile.tileID.key];
                if (fingerprint && fingerprint !== tile.rttFingerprint[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
     * @param renderOptions - flags describing how to render the layer
     * @returns if true layer is rendered to texture, otherwise false
     */
    renderLayer(layer, renderOptions) {
        if (layer.isHidden(this.painter.transform.zoom))
            return false;
        const options = Object.assign(Object.assign({}, renderOptions), { isRenderingToTexture: true });
        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_TO_TEXTURES[type]) {
            // create a new stack if previous layer was not rendered to texture (f.e. symbols)
            if (!this._prevType || !LAYERS_TO_TEXTURES[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_TO_TEXTURES[this._prevType] || (LAYERS_TO_TEXTURES[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, options);
                    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: symbol_layout.Color.transparent, stencil: 0 });
                painter.currentStencilSource = undefined;
                for (const layerId of layers) {
                    const layer = painter.style._layers[layerId];
                    const coords = layer.source ? this._coordsAscending[layer.source][tile.tileID.key] : [tile.tileID];
                    painter.context.viewport.set([0, 0, obj.fbo.width, obj.fbo.height]);
                    painter._renderTileClippingMasks(layer, coords, true);
                    painter.renderLayer(painter, painter.style.tileManagers[layer.source], layer, coords, options);
                    if (layer.source)
                        tile.rttFingerprint[layer.source] = this._rttFingerprints[layer.source][tile.tileID.key];
                }
            }
            drawTerrain(this.painter, this.terrain, this._rttTiles, options);
            this._rttTiles = [];
            this.pool.freeAllObjects();
            return LAYERS_TO_TEXTURES[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': 'Drag to rotate map, click to reset 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',
    'GlobeControl.Enable': 'Enable globe',
    'GlobeControl.Disable': 'Disable globe',
    '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;
const defaultAnisotropicFilterPitch = 20;
// use this variable to check maxPitch and anisotropicFilterPitch for validity
const maxPitchThreshold = 180;
const defaultOptions$4 = {
    hash: false,
    interactive: true,
    bearingSnap: 7,
    zoomSnap: 0,
    attributionControl: defaultAttributionControlOptions,
    maplibreLogo: false,
    refreshExpiredTiles: true,
    canvasContextAttributes: {
        antialias: false,
        preserveDrawingBuffer: false,
        powerPreference: 'high-performance',
        failIfMajorPerformanceCaveat: false,
        desynchronized: false,
        contextType: undefined
    },
    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],
    elevation: 0,
    zoom: 0,
    bearing: 0,
    pitch: 0,
    roll: 0,
    renderWorldCopies: true,
    maxTileCacheSize: null,
    maxTileCacheZoomLevels: symbol_layout.config.MAX_TILE_CACHE_ZOOM_LEVELS,
    transformRequest: null,
    transformCameraUpdate: null,
    transformConstrain: null,
    fadeDuration: 300,
    crossSourceCollisions: true,
    clickTolerance: 3,
    localIdeographFontFamily: 'sans-serif',
    pitchWithRotate: true,
    rollEnabled: false,
    reduceMotion: undefined,
    validateStyle: true,
    /**Because GL MAX_TEXTURE_SIZE is usually at least 4096px. */
    maxCanvasSize: [4096, 4096],
    cancelPendingTileRequestsWhileZooming: true,
    centerClampedToGround: true,
    experimentalZoomLevelsToOverscale: undefined,
    anisotropicFilterPitch: defaultAnisotropicFilterPitch,
};
/**
 * 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/display-a-map/)
 */
let Map$1 = class Map extends Camera {
    /**
     * @internal
     * The window that owns the map container element, for cross-window support.
     * Returns `typeof window` to include global constructors like ResizeObserver.
     */
    get _ownerWindow() {
        var _a, _b;
        return ((_b = (_a = this._container) === null || _a === void 0 ? void 0 : _a.ownerDocument) === null || _b === void 0 ? void 0 : _b.defaultView) || window;
    }
    constructor(options) {
        var _a, _b, _c;
        const resolvedOptions = Object.assign(Object.assign(Object.assign({}, defaultOptions$4), options), { canvasContextAttributes: Object.assign(Object.assign({}, defaultOptions$4.canvasContextAttributes), options.canvasContextAttributes) });
        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}`);
        }
        // For now we will use a temporary MercatorTransform instance.
        // Transform specialization will later be set by style when it creates its projection instance.
        // When this happens, the new transform will inherit all properties of this temporary transform.
        const transform = new MercatorTransform();
        const cameraHelper = new MercatorCameraHelper();
        if (resolvedOptions.minZoom !== undefined) {
            transform.setMinZoom(resolvedOptions.minZoom);
        }
        if (resolvedOptions.maxZoom !== undefined) {
            transform.setMaxZoom(resolvedOptions.maxZoom);
        }
        if (resolvedOptions.minPitch !== undefined) {
            transform.setMinPitch(resolvedOptions.minPitch);
        }
        if (resolvedOptions.maxPitch !== undefined) {
            transform.setMaxPitch(resolvedOptions.maxPitch);
        }
        if (resolvedOptions.renderWorldCopies !== undefined) {
            transform.setRenderWorldCopies(resolvedOptions.renderWorldCopies);
        }
        if (resolvedOptions.transformConstrain !== null) {
            transform.setConstrainOverride(resolvedOptions.transformConstrain);
        }
        super(transform, cameraHelper, {
            bearingSnap: resolvedOptions.bearingSnap,
            zoomSnap: resolvedOptions.zoomSnap
        });
        this._idleTriggered = false;
        this._crossFadingFactor = 1;
        this._renderTaskQueue = new TaskQueue();
        this._controls = [];
        this._mapId = symbol_layout.uniqueId();
        /**
         * @internal
         * Used to store the previous style and images when a context loss occurs, so they can be restored.
         */
        this._lostContextStyle = {
            style: null,
            images: null
        };
        this._contextLost = (event) => {
            event.preventDefault();
            if (this._frameRequest) {
                this._frameRequest.abort();
                this._frameRequest = null;
            }
            this.painter.destroy();
            this._lostContextStyle = this._getStyleAndImages();
            if (!this.style) {
                this.fire(new symbol_layout.Event('webglcontextlost', { originalEvent: event }));
                return;
            }
            // check if style contains custom layers to warn user that they can't be restored automatically
            for (const layer of Object.values(this.style._layers)) {
                if (layer.type === 'custom') {
                    console.warn(`Custom layer with id '${layer.id}' cannot be restored after WebGL context loss. You will need to re-add it manually after context restoration.`);
                }
                if (layer._listeners) {
                    for (const [event] of Object.entries(layer._listeners)) {
                        console.warn(`Custom layer with id '${layer.id}' had event listeners for event '${event}' which cannot be restored after WebGL context loss. You will need to re-add them manually after context restoration.`);
                    }
                }
            }
            this.style.destroy();
            this.style = null;
            this.fire(new symbol_layout.Event('webglcontextlost', { originalEvent: event }));
        };
        this._contextRestored = (event) => {
            if (this._lostContextStyle.style) {
                this.setStyle(this._lostContextStyle.style, { diff: false });
            }
            if (this._lostContextStyle.images && this.style) {
                this.style.imageManager.images = this._lostContextStyle.images;
            }
            this._lostContextStyle = { style: null, images: null };
            this._setupPainter();
            this.resize();
            this._update();
            this._resizeInternal();
            this.fire(new symbol_layout.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._canvasContextAttributes = Object.assign({}, resolvedOptions.canvasContextAttributes);
        this._trackResize = resolvedOptions.trackResize === true;
        this._bearingSnap = resolvedOptions.bearingSnap;
        this._zoomSnap = resolvedOptions.zoomSnap;
        this._centerClampedToGround = resolvedOptions.centerClampedToGround;
        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._zoomLevelsToOverscale = resolvedOptions.experimentalZoomLevelsToOverscale;
        this.transformCameraUpdate = resolvedOptions.transformCameraUpdate;
        this.transformConstrain = resolvedOptions.transformConstrain;
        this.cancelPendingTileRequestsWhileZooming = resolvedOptions.cancelPendingTileRequestsWhileZooming === true;
        this.setAnisotropicFilterPitch(resolvedOptions.anisotropicFilterPitch);
        if (resolvedOptions.reduceMotion !== undefined) {
            browser.prefersReducedMotion = resolvedOptions.reduceMotion;
        }
        this._imageQueueHandle = ImageRequest.addThrottleControl(() => this.isMoving());
        this._requestManager = new RequestManager(resolvedOptions.transformRequest);
        this._container = this._resolveContainer(resolvedOptions.container);
        if (resolvedOptions.maxBounds) {
            this.setMaxBounds(resolvedOptions.maxBounds);
        }
        this._setupContainer();
        this._setupPainter();
        this.on('move', () => this._update(false));
        this.on('moveend', () => this._update(false));
        this.on('zoom', () => this._update(true));
        this.on('terrain', () => {
            this.painter.terrainFacilitator.depthDirty = true;
            this._update(true);
        });
        this.once('idle', () => this._idleTriggered = true);
        if (typeof window !== 'undefined') {
            this._ownerWindow.addEventListener('online', this._onWindowOnline, false);
            this._setupResizeObserver();
        }
        this.handlers = new HandlerManager(this, resolvedOptions);
        const hashName = (typeof resolvedOptions.hash === 'string' && resolvedOptions.hash) || undefined;
        this._hash = resolvedOptions.hash ? (new Hash(hashName)).addTo(this) : undefined;
        // don't set position from options if set through hash
        if (!((_a = this._hash) === null || _a === void 0 ? void 0 : _a._onHashChange())) {
            this.jumpTo({
                center: resolvedOptions.center,
                elevation: resolvedOptions.elevation,
                zoom: resolvedOptions.zoom,
                bearing: resolvedOptions.bearing,
                pitch: resolvedOptions.pitch,
                roll: resolvedOptions.roll
            });
            if (resolvedOptions.bounds) {
                this.resize();
                this.fitBounds(resolvedOptions.bounds, symbol_layout.extend({}, resolvedOptions.fitBoundsOptions, { duration: 0 }));
            }
        }
        // When no style is set or it's using something other than the globe projection, we can constrain the camera.
        // When a style is set with other projections though, we can't constrain the camera until the style is loaded
        // and the correct transform is used. Otherwise, valid points in the desired projection could be rejected
        const shouldConstrainUsingMercatorTransform = typeof resolvedOptions.style === 'string' || !(((_c = (_b = resolvedOptions.style) === null || _b === void 0 ? void 0 : _b.projection) === null || _c === void 0 ? void 0 : _c.type) === 'globe');
        this.resize(null, shouldConstrainUsingMercatorTransform);
        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 we didn't constrain the camera before, we do it now
            if (!shouldConstrainUsingMercatorTransform)
                this._resizeTransform();
            if (this.transform.unmodified) {
                const coercedOptions = symbol_layout.pick(this.style.stylesheet, ['center', 'zoom', 'bearing', 'pitch', 'roll']);
                this.jumpTo(coercedOptions);
            }
        });
        this.on('data', (event) => {
            this._update(event.dataType === 'style');
            this.fire(new symbol_layout.Event(`${event.dataType}data`, event));
        });
        this.on('dataloading', (event) => {
            this.fire(new symbol_layout.Event(`${event.dataType}dataloading`, event));
        });
        this.on('dataabort', (event) => {
            this.fire(new symbol_layout.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;
    }
    /**
     * Sets a global state property that can be retrieved with the [`global-state` expression](https://maplibre.org/maplibre-style-spec/expressions/#global-state).
     * If the value is null, it resets the property to its default value defined in the [`state` style property](https://maplibre.org/maplibre-style-spec/root/#state).
     *
     * @param propertyName - The name of the state property to set.
     * @param value - The value of the state property to set.
     */
    setGlobalStateProperty(propertyName, value) {
        this.style.setGlobalStateProperty(propertyName, value);
        return this._update(true);
    }
    /**
     * Returns the global map state
     *
     * @returns The map state object.
    */
    getGlobalState() {
        return this.style.getGlobalState();
    }
    /**
     * Adds an {@link IControl} to the map, calling `control.onAdd(this)`.
     *
     * An {@link ErrorEvent} will be fired if the control is invalid.
     *
     * @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/display-map-navigation-controls/)
     */
    addControl(control, position) {
        if (position === undefined) {
            if (control.getDefaultPosition) {
                position = control.getDefaultPosition();
            }
            else {
                position = 'top-right';
            }
        }
        if (!(control === null || control === void 0 ? void 0 : control.onAdd)) {
            return this.fire(new symbol_layout.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.includes('bottom')) {
            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 control is invalid.
     *
     * @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 === null || control === void 0 ? void 0 : control.onRemove)) {
            return this.fire(new symbol_layout.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.includes(control);
    }
    /**
    * Returns an array of `OverscaledTileID` objects that cover the current viewport for a given tile size.
    * This method is useful for determining which tiles are visible in the current viewport.
    *
    * @param options - Options for calculating the covering tiles.
    * @returns An array of `OverscaledTileID` objects.
    * @example
    * ```ts
    * // Get the tiles to cover the view for a 512x512px tile source
    * const tiles = map.coveringTiles({tileSize: 512});
    * ```
    */
    coveringTiles(options) {
        return coveringTiles(this.transform, options);
    }
    calculateCameraOptionsFromTo(from, altitudeFrom, to, altitudeTo) {
        if (altitudeTo == null && this.terrain) {
            altitudeTo = this.terrain.getElevationForLngLat(to, this.transform);
        }
        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, constrainTransform = true) {
        // Early out if the context is lost
        // causes a blank map otherwise
        const isContextLost = this._lostContextStyle.style !== null;
        if (isContextLost)
            return this;
        this._resizeInternal(constrainTransform);
        const fireMoving = !this._moving;
        if (fireMoving) {
            this.stop();
            this.fire(new symbol_layout.Event('movestart', eventData))
                .fire(new symbol_layout.Event('move', eventData));
        }
        this.fire(new symbol_layout.Event('resize', eventData));
        if (fireMoving)
            this.fire(new symbol_layout.Event('moveend', eventData));
        return this;
    }
    /**
     * Resizes the map according to the dimensions of its
     * `container` element.
     *
     * It does not trigger any events, and does not check for context loss.
     *
     * It is used internally and by {@link Map.resize}.
     *
     * @internal
     *
     * @param constrainTransform - whether to constrain the transform after resizing.
     */
    _resizeInternal(constrainTransform = true) {
        const [width, height] = this._containerDimensions();
        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._resizeTransform(constrainTransform);
    }
    _resizeTransform(constrainTransform = true) {
        var _a;
        const [width, height] = this._containerDimensions();
        this.transform.resize(width, height, constrainTransform);
        (_a = this._requestedCameraState) === null || _a === void 0 ? void 0 : _a.resize(width, height, constrainTransform);
    }
    /**
     * @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 and trigger the following events:
     * `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`.
     *
     * 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) {
            const zoomBefore = this.transform.zoom;
            const tr = this._getTransformForUpdate();
            tr.setMinZoom(minZoom);
            this._applyUpdatedTransform(tr);
            this._update();
            if (zoomBefore !== this.transform.zoom) {
                this.fire(new symbol_layout.Event('zoomstart'))
                    .fire(new symbol_layout.Event('zoom'))
                    .fire(new symbol_layout.Event('zoomend'))
                    .fire(new symbol_layout.Event('movestart'))
                    .fire(new symbol_layout.Event('move'))
                    .fire(new symbol_layout.Event('moveend'));
            }
            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 and trigger the following events:
     * `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`.
     *
     * 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) {
            const zoomBefore = this.transform.zoom;
            const tr = this._getTransformForUpdate();
            tr.setMaxZoom(maxZoom);
            this._applyUpdatedTransform(tr);
            this._update();
            if (zoomBefore !== this.transform.zoom) {
                this.fire(new symbol_layout.Event('zoomstart'))
                    .fire(new symbol_layout.Event('zoom'))
                    .fire(new symbol_layout.Event('zoomend'))
                    .fire(new symbol_layout.Event('movestart'))
                    .fire(new symbol_layout.Event('move'))
                    .fire(new symbol_layout.Event('moveend'));
            }
            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 and trigger the following events:
     * `movestart`, `move`, `moveend`, `pitchstart`, `pitch`, and `pitchend`.
     *
     * A {@link ErrorEvent} event will be fired if minPitch is out of bounds.
     *
     * @param minPitch - The minimum pitch to set (0-180). 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) {
            const pitchBefore = this.transform.pitch;
            const tr = this._getTransformForUpdate();
            tr.setMinPitch(minPitch);
            this._applyUpdatedTransform(tr);
            this._update();
            if (pitchBefore !== this.transform.pitch) {
                this.fire(new symbol_layout.Event('pitchstart'))
                    .fire(new symbol_layout.Event('pitch'))
                    .fire(new symbol_layout.Event('pitchend'))
                    .fire(new symbol_layout.Event('movestart'))
                    .fire(new symbol_layout.Event('move'))
                    .fire(new symbol_layout.Event('moveend'));
            }
            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 and trigger the following events:
     * `movestart`, `move`, `moveend`, `pitchstart`, `pitch`, and `pitchend`.
     *
     * A {@link ErrorEvent} event will be fired if maxPitch is out of bounds.
     *
     * @param maxPitch - The maximum pitch to set (0-180). 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) {
            const pitchBefore = this.transform.pitch;
            const tr = this._getTransformForUpdate();
            tr.setMaxPitch(maxPitch);
            this._applyUpdatedTransform(tr);
            this._update();
            if (pitchBefore !== this.transform.pitch) {
                this.fire(new symbol_layout.Event('pitchstart'))
                    .fire(new symbol_layout.Event('pitch'))
                    .fire(new symbol_layout.Event('pitchend'))
                    .fire(new symbol_layout.Event('movestart'))
                    .fire(new symbol_layout.Event('move'))
                    .fire(new symbol_layout.Event('moveend'));
            }
            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 map's anisotropic filter pitch.
     * If the map is pitched beyond this threshold, anisotropic filtering will be applied to all raster layers.
     *
     * @returns The anisotropicFilterPitch
     * @example
     * ```ts
     * let anisotropicFilterPitch = map.getAnisotropicFilterPitch();
     * ```
     */
    getAnisotropicFilterPitch() { return this._anisotropicFilterPitch; }
    /**
     * Sets the map's anisotropic filter pitch or reverts it to its default.
     *
     * A {@link ErrorEvent} event will be fired if anisotropicFilterPitch is out of bounds.
     *
     * @param anisotropicFilterPitch - The pitch above which to apply anisotropic filtering to the map's raster layers (0-180).
     * If `null` or `undefined` is provided, the function reverts to the default pitch threshold (20).
     *
     *
     * @example
     * ```ts
     * map.setAnisotropicFilterPitch(85);
     * ```
     */
    setAnisotropicFilterPitch(anisotropicFilterPitch) {
        anisotropicFilterPitch = anisotropicFilterPitch === null || anisotropicFilterPitch === undefined ? defaultAnisotropicFilterPitch : anisotropicFilterPitch;
        if (anisotropicFilterPitch > maxPitchThreshold) {
            throw new Error(`anisotropicFilterPitch must be less than or equal to ${maxPitchThreshold}`);
        }
        if (anisotropicFilterPitch < defaultMinPitch) {
            throw new Error(`anisotropicFilterPitch must be greater than or equal to ${defaultMinPitch}`);
        }
        this._anisotropicFilterPitch = anisotropicFilterPitch;
        return this._update();
    }
    /**
     * 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.setRenderWorldCopies(renderWorldCopies);
        return this._update();
    }
    /** Sets or clears the callback overriding how the map constrains the viewport's lnglat and zoom to respect the longitude and latitude bounds.
     *
     * @param constrain - A {@link TransformConstrainFunction} callback defining how the viewport should respect the bounds.
     *
     * `null` clears the callback and reverts the constrain to the map transform's default constrain function.
     * @example
     * ```ts
     * function customTransformConstrain(lngLat, zoom) {
     *   return {center: lngLat, zoom: zoom ?? 0};
     * };
     * map.setTransformConstrain(customTransformConstrain);
     * ```
     * @see [Customize the map transform constrain](https://maplibre.org/maplibre-gl-js/docs/examples/customize-the-map-transform-constrain/)
     */
    setTransformConstrain(constrain) {
        this.transform.setConstrainOverride(constrain);
        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.locationToScreenPoint(symbol_layout.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.screenPointToLocation(symbol_layout.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) {
        var _a;
        if (!((_a = this._delegatedListeners) === null || _a === void 0 ? void 0 : _a[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 {
            unsubscribe: () => {
                this._removeDelegatedListener(type, layerIds, listener);
            }
        };
    }
    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 in pixel points within the map viewport:
     * either a single pixel point or a pair of top-left and bottom-right pixel points describing a bounding box.
     * The origin of the pixel points is at the top-left of the map viewport.
     * 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/get-features-under-the-mouse-pointer/)
     */
    queryRenderedFeatures(geometryOrOptions, options) {
        if (!this.style) {
            return [];
        }
        let queryGeometry;
        const isGeometry = geometryOrOptions instanceof symbol_layout.Point || Array.isArray(geometryOrOptions);
        const geometry = isGeometry ? geometryOrOptions : [[0, 0], [this.transform.width, this.transform.height]];
        options = options || (isGeometry ? {} : geometryOrOptions) || {};
        if (geometry instanceof symbol_layout.Point || typeof geometry[0] === 'number') {
            queryGeometry = [symbol_layout.Point.convert(geometry)];
        }
        else {
            const tl = symbol_layout.Point.convert(geometry[0]);
            const br = symbol_layout.Point.convert(geometry[1]);
            queryGeometry = [tl, new symbol_layout.Point(br.x, tl.y), br, new symbol_layout.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 = symbol_layout.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) {
        var _a, _b, _c;
        (_a = this._diffStyleRequest) === null || _a === void 0 ? void 0 : _a.abort();
        this._diffStyleRequest = null;
        // 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) {
            if (this._frameRequest) {
                this._frameRequest.abort();
                this._frameRequest = null;
            }
            (_c = (_b = this.style) === null || _b === void 0 ? void 0 : _b.projection) === null || _c === void 0 ? void 0 : _c.destroy();
            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) {
        return symbol_layout.__awaiter(this, void 0, void 0, function* () {
            var _a;
            (_a = this._diffStyleRequest) === null || _a === void 0 ? void 0 : _a.abort();
            if (typeof style === 'string') {
                const url = style;
                this._diffStyleRequest = new AbortController();
                const abortController = this._diffStyleRequest;
                try {
                    const request = yield this._requestManager.transformRequest(url, "Style" /* ResourceType.Style */);
                    if (abortController.signal.aborted) {
                        this._diffStyleRequest = null;
                        return;
                    }
                    const response = yield symbol_layout.getJSON(request, abortController);
                    this._diffStyleRequest = null;
                    this._updateDiff(response.data, options);
                }
                catch (error) {
                    this._diffStyleRequest = null;
                    if (!symbol_layout.isAbortError(error)) {
                        this.fire(new symbol_layout.ErrorEvent(symbol_layout.ensureError(error)));
                    }
                }
            }
            else if (typeof style === 'object') {
                this._diffStyleRequest = null;
                this._updateDiff(style, options);
            }
        });
    }
    _updateDiff(style, options) {
        try {
            if (this.style.setState(style, options)) {
                this._update(true);
            }
        }
        catch (e) {
            symbol_layout.warnOnce(`Unable to perform style diff: ${symbol_layout.ensureError(e).message}.  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();
        }
    }
    /**
     * @internal
     * Returns the map's style and cloned images to restore context.
     * @returns An object containing the style and images.
     */
    _getStyleAndImages() {
        if (this.style) {
            return {
                style: this.style.serialize(),
                images: this.style.imageManager.cloneImages()
            };
        }
        return { style: null, images: {} };
    }
    /**
     * 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) {
            symbol_layout.warnOnce('There is no style added to the map.');
            return;
        }
        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/add-live-realtime-data/)
     */
    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 with 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) {
        var _a;
        const tileManager = (_a = this.style) === null || _a === void 0 ? void 0 : _a.tileManagers[id];
        if (tileManager === undefined) {
            this.fire(new symbol_layout.ErrorEvent(new Error(`There is no tile manager with ID '${id}'`)));
            return;
        }
        return tileManager.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.destroy();
            }
            this.terrain = null;
            if (this.painter.renderToTexture)
                this.painter.renderToTexture.destruct();
            this.painter.renderToTexture = null;
            this.transform.setMinElevationForCurrentTile(0);
            if (this._centerClampedToGround) {
                this.transform.setElevation(0);
            }
        }
        else {
            // add terrain
            const tileManager = this.style.tileManagers[options.source];
            if (!tileManager)
                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)
                tileManager.reload();
            // Warn once if user is using the same source for hillshade/color-relief and terrain
            for (const index in this.style._layers) {
                const thisLayer = this.style._layers[index];
                if (thisLayer.type === 'hillshade' && thisLayer.source === options.source) {
                    symbol_layout.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.');
                }
                if (thisLayer.type === 'color-relief' && thisLayer.source === options.source) {
                    symbol_layout.warnOnce('You are using the same source for a color-relief layer and for 3D terrain. Please consider using two separate sources to improve rendering quality.');
                }
            }
            this.terrain = new Terrain(this.painter, tileManager, options);
            this.painter.renderToTexture = new RenderToTexture(this.painter, this.terrain);
            this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center, this.transform.tileZoom));
            this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center, this.transform.tileZoom));
            this._terrainDataCallback = e => {
                var _a;
                if (e.dataType === 'style') {
                    this.terrain.tileManager.freeRtt();
                }
                else if (e.dataType === 'source' && e.tile) {
                    if (e.sourceId === options.source && !this._elevationFreeze) {
                        this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center, this.transform.tileZoom));
                        if (this._centerClampedToGround) {
                            this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center, this.transform.tileZoom));
                        }
                    }
                    if (((_a = e.source) === null || _a === void 0 ? void 0 : _a.type) === 'image') {
                        this.terrain.tileManager.freeRtt();
                    }
                    else {
                        this.terrain.tileManager.freeRtt(e.tile.tileID);
                    }
                }
            };
            this.style.on('data', this._terrainDataCallback);
        }
        this.fire(new symbol_layout.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() {
        var _a;
        const tileManagers = (_a = this.style) === null || _a === void 0 ? void 0 : _a.tileManagers;
        for (const tileManager of Object.values(tileManagers)) {
            if (!tileManager.areTilesLoaded()) {
                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/create-a-draggable-point/)
     * @see [Animate a point](https://maplibre.org/maplibre-gl-js/docs/examples/animate-a-point/)
     * @see [Add live realtime data](https://maplibre.org/maplibre-gl-js/docs/examples/add-live-realtime-data/)
     */
    getSource(id) {
        return this.style.getSource(id);
    }
    /**
     * Change the tile Level of Detail behavior of the specified source. These parameters have no effect when
     * pitch == 0, and the largest effect when the horizon is visible on screen.
     *
     * @param maxZoomLevelsOnScreen - The maximum number of distinct zoom levels allowed on screen at a time.
     * There will generally be fewer zoom levels on the screen, the maximum can only be reached when the horizon
     * is at the top of the screen. Increasing the maximum number of zoom levels causes the zoom level to decay
     * faster toward the horizon.
     * @param tileCountMaxMinRatio - The ratio of the maximum number of tiles loaded (at high pitch) to the minimum
     * number of tiles loaded. Increasing this ratio allows more tiles to be loaded at high pitch angles. If the ratio
     * would otherwise be exceeded, the zoom level is reduced uniformly to keep the number of tiles within the limit.
     * @param sourceId - The ID of the source to set tile LOD parameters for. All sources will be updated if unspecified.
     * If `sourceId` is specified but a corresponding source does not exist, an error is thrown.
     * @example
     * ```ts
     * map.setSourceTileLodParams(4.0, 3.0, 'terrain');
     * ```
     * @see [Modify Level of Detail behavior](https://maplibre.org/maplibre-gl-js/docs/examples/level-of-detail-control/)

     */
    setSourceTileLodParams(maxZoomLevelsOnScreen, tileCountMaxMinRatio, sourceId) {
        if (sourceId) {
            const source = this.getSource(sourceId);
            if (!source) {
                throw new Error(`There is no source with ID "${sourceId}", cannot set LOD parameters`);
            }
            source.calculateTileZoom = createCalculateTileZoomFunction(Math.max(1, maxZoomLevelsOnScreen), Math.max(1, tileCountMaxMinRatio));
        }
        else {
            for (const id in this.style.tileManagers) {
                this.style.tileManagers[id].getSource().calculateTileZoom = createCalculateTileZoomFunction(Math.max(1, maxZoomLevelsOnScreen), Math.max(1, tileCountMaxMinRatio));
            }
        }
        this._update(true);
        return this;
    }
    /**
     * Triggers a reload of the selected tiles
     *
     * @param sourceId - The ID of the source
     * @param tileIds - An array of tile IDs to be reloaded. If not defined, all tiles will be reloaded.
     * @example
     * ```ts
     * map.refreshTiles('satellite', [{x:1024, y: 1023, z: 11}, {x:1023, y: 1023, z: 11}]);
     * ```
     */
    refreshTiles(sourceId, tileIds) {
        const tileManager = this.style.tileManagers[sourceId];
        if (!tileManager) {
            throw new Error(`There is no tile manager with ID "${sourceId}", cannot refresh tile`);
        }
        if (tileIds === undefined) {
            tileManager.reload(true);
        }
        else {
            tileManager.refreshTiles(tileIds.map((tileId) => { return new symbol_layout.CanonicalTileID(tileId.z, tileId.x, tileId.y); }));
        }
    }
    /**
     * 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-an-icon-to-the-map/)
     * @see Use `ImageData`: [Add a generated icon to the map](https://maplibre.org/maplibre-gl-js/docs/examples/add-a-generated-icon-to-the-map/)
     */
    addImage(id, image, options = {}) {
        const { pixelRatio = 1, sdf = false, stretchX, stretchY, content, textFitWidth, textFitHeight } = options;
        this._lazyInitEmptyStyle();
        const version = 0;
        if (image instanceof HTMLImageElement || symbol_layout.isImageBitmap(image)) {
            const { width, height, data } = browser.getImageData(image);
            this.style.addImage(id, { data: new symbol_layout.RGBAImage({ width, height }, data), pixelRatio, stretchX, stretchY, content, textFitWidth, textFitHeight, sdf, version });
        }
        else if (image.width === undefined || image.height === undefined) {
            return this.fire(new symbol_layout.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 symbol_layout.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 invalid.
     *
     * @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 symbol_layout.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 || symbol_layout.isImageBitmap(image)) ?
            browser.getImageData(image) :
            image;
        const { width, height, data } = imageData;
        if (width === undefined || height === undefined) {
            return this.fire(new symbol_layout.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 symbol_layout.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 || symbol_layout.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 ID is missing.
     *
     * @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 symbol_layout.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-an-icon-to-the-map/)
     */
    loadImage(url) {
        return symbol_layout.__awaiter(this, void 0, void 0, function* () {
            return ImageRequest.getImage(yield 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/create-and-style-clusters/)
     * @see [Add a vector tile source](https://maplibre.org/maplibre-gl-js/docs/examples/add-a-vector-tile-source/)
     * @see [Add a WMS source](https://maplibre.org/maplibre-gl-js/docs/examples/add-a-wms-source/)
     */
    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 no such layer exists.
     *
     * @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-symbols-by-toggling-a-list/)
     * @see [Filter symbols by text input](https://maplibre.org/maplibre-gl-js/docs/examples/filter-symbols-by-text-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/create-a-time-slider/)
     */
    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/change-a-layers-color-with-buttons/)
     * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-draggable-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. Pass a falsy value (null or undefined)
    * to unset glyphs.
     *
     * @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, or `null` if glyphs are unset.
     */
    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();
    }
    /**
     * Sets the value of style's sky properties.
     *
     * @param sky - Sky properties to set. Must conform to the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/sky/).
     * @param options - Options object.
     *
     * @example
     * ```ts
     * map.setSky({'atmosphere-blend': 1.0});
     * ```
     */
    setSky(sky, options = {}) {
        this._lazyInitEmptyStyle();
        this.style.setSky(sky, options);
        return this._update(true);
    }
    /**
     * Returns the value of the style's sky.
     *
     * @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/#promoteid) option at the time the source is defined.
     * - For GeoJSON sources, using the [`generateId`](https://maplibre.org/maplibre-style-spec/sources/#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/create-a-hover-effect/)
     */
    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 `<canvas>` 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 `<canvas>`, but not from
     * map controls.
     *
     * @returns The container of the map's `<canvas>`.
     * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-draggable-point/)
     */
    getCanvasContainer() {
        return this._canvasContainer;
    }
    /**
     * Returns the map's `<canvas>` element.
     *
     * @returns The map's `<canvas>` element.
     * @see [Measure distances](https://maplibre.org/maplibre-gl-js/docs/examples/measure-distances/)
     * @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-popup-on-hover/)
     * @see [Center the map on a clicked symbol](https://maplibre.org/maplibre-gl-js/docs/examples/center-the-map-on-a-clicked-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];
    }
    /**
     * @internal
     * Sets up the ResizeObserver to track container size changes.
     * Uses the owning window's ResizeObserver for cross-window support.
     */
    _setupResizeObserver() {
        var _a;
        let initialResizeEventCaptured = false;
        const throttledResizeCallback = throttle((entries) => {
            if (this._trackResize && !this._removed) {
                this.resize(entries);
                this.redraw();
            }
        }, 50);
        // Use owning window's ResizeObserver for cross-window support
        const ResizeObserverClass = (_a = this._ownerWindow.ResizeObserver) !== null && _a !== void 0 ? _a : ResizeObserver;
        this._resizeObserver = new ResizeObserverClass((entries) => {
            if (!initialResizeEventCaptured) {
                initialResizeEventCaptured = true;
                return;
            }
            throttledResizeCallback(entries);
        });
        this._resizeObserver.observe(this._container);
    }
    /**
     * @internal
     * Resolves the container option to an HTMLElement.
     * Supports string ID, HTMLElement, or cross-window elements (using nodeType check).
     */
    _resolveContainer(container) {
        if (typeof container === 'string') {
            const element = document.getElementById(container);
            if (!element) {
                throw new Error(`Container '${container}' not found.`);
            }
            return element;
        }
        if (container instanceof HTMLElement) {
            return container;
        }
        // Cross-window support: use nodeType check as instanceof fails across windows
        if (container && typeof container === 'object' && container.nodeType === 1) {
            return container;
        }
        throw new Error('Invalid type: \'container\' must be a String or HTMLElement.');
    }
    _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 = {};
        for (const positionName of ['top-left', 'top-right', 'bottom-left', 'bottom-right']) {
            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() {
        // Maplibre WebGL context requires alpha, depth and stencil buffers. It also forces premultipliedAlpha: true.
        // We use the values provided in the map constructor for the rest of context attributes
        const attributes = Object.assign(Object.assign({}, this._canvasContextAttributes), { alpha: true, depth: true, stencil: true, premultipliedAlpha: true });
        let webglcontextcreationerrorDetailObject = null;
        this._canvas.addEventListener('webglcontextcreationerror', (args) => {
            webglcontextcreationerrorDetailObject = { requestedAttributes: attributes };
            if (args) {
                webglcontextcreationerrorDetailObject.statusMessage = args.statusMessage;
                webglcontextcreationerrorDetailObject.type = args.type;
            }
        }, { once: true });
        let gl = null;
        if (this._canvasContextAttributes.contextType) {
            gl = this._canvas.getContext(this._canvasContextAttributes.contextType, attributes);
        }
        else {
            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);
    }
    migrateProjection(newTransform, newCameraHelper) {
        super.migrateProjection(newTransform, newCameraHelper);
        this.painter.transform = newTransform;
        this.fire(new symbol_layout.Event('projectiontransition', {
            newProjection: this.style.projection.name,
        }));
    }
    /**
     * 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) {
        var _a;
        if (!((_a = this.style) === null || _a === void 0 ? void 0 : _a._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) {
        var _a, _b, _c, _d, _e, _f;
        const fadeDuration = this._idleTriggered ? this._fadeDuration : 0;
        const isGlobeRendering = ((_a = this.style.projection) === null || _a === void 0 ? void 0 : _a.transitionState) > 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 currentTime = now();
            this.style.zoomHistory.update(zoom, currentTime);
            const parameters = new symbol_layout.EvaluationParameters(zoom, {
                now: currentTime,
                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);
        }
        const globeRenderingChanged = ((_b = this.style.projection) === null || _b === void 0 ? void 0 : _b.transitionState) > 0 !== isGlobeRendering;
        (_c = this.style.projection) === null || _c === void 0 ? void 0 : _c.setErrorQueryLatitudeDegrees(this.transform.center.lat);
        this.transform.setTransitionState((_d = this.style.projection) === null || _d === void 0 ? void 0 : _d.transitionState, (_e = this.style.projection) === null || _e === void 0 ? void 0 : _e.latitudeErrorCorrectionRadians);
        // If we are in _render for any reason other than an in-progress paint
        // transition, update tile managers to check for and load any tiles we
        // need for the current transform
        if (this.style && (this._sourcesDirty || globeRenderingChanged)) {
            this._sourcesDirty = false;
            this.style._updateSources(this.transform);
        }
        // update terrain stuff
        if (this.terrain) {
            this.terrain.tileManager.update(this.transform, this.terrain);
            this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center, this.transform.tileZoom));
            if (!this._elevationFreeze && this._centerClampedToGround) {
                this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center, this.transform.tileZoom));
            }
        }
        else {
            this.transform.setMinElevationForCurrentTile(0);
            if (this._centerClampedToGround) {
                this.transform.setElevation(0);
            }
        }
        this._placementDirty = (_f = this.style) === null || _f === void 0 ? void 0 : _f._updatePlacement(this.transform, this.showCollisionBoxes, fadeDuration, this._crossSourceCollisions, globeRenderingChanged);
        // 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,
            anisotropicFilterPitch: this.getAnisotropicFilterPitch(),
        });
        this.fire(new symbol_layout.Event('render'));
        if (this.loaded() && !this._loaded) {
            this._loaded = true;
            this.fire(new symbol_layout.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 TileManagers 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 symbol_layout.Event('idle'));
        }
        if (this._loaded && !this._fullyLoaded && !somethingDirty) {
            this._fullyLoaded = true;
        }
        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, _b;
        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();
        (_a = this._diffStyleRequest) === null || _a === void 0 ? void 0 : _a.abort();
        this.painter.destroy();
        this.handlers.destroy();
        delete this.handlers;
        this.setStyle(null);
        if (typeof window !== 'undefined') {
            this._ownerWindow.removeEventListener('online', this._onWindowOnline, false);
        }
        ImageRequest.removeThrottleControl(this._imageQueueHandle);
        (_b = this._resizeObserver) === null || _b === void 0 ? void 0 : _b.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);
        this._canvasContainer.remove();
        this._controlContainer.remove();
        this._container.removeEventListener('scroll', this._onMapScroll, false);
        this._container.classList.remove('maplibregl-map');
        this._removed = true;
        this.fire(new symbol_layout.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-a-3d-model-using-threejs/)
     * @see [Add an animated icon to the map](https://maplibre.org/maplibre-gl-js/docs/examples/add-an-animated-icon-to-the-map/)
     */
    triggerRepaint() {
        if (this.style && !this._frameRequest) {
            this._frameRequest = new AbortController();
            browser.frame(this._frameRequest, (paintStartTimeStamp) => {
                this._frameRequest = null;
                try {
                    this._render(paintStartTimeStamp);
                }
                catch (error) {
                    if (!symbol_layout.isAbortError(error) && !isFramebufferNotCompleteError(error)) {
                        throw error;
                    }
                }
            }, () => { }, this._ownerWindow);
        }
    }
    /**
     * 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;
    }
    /**
     * Gets the {@link ProjectionSpecification}.
     * @returns the projection specification.
     * @example
     * ```ts
     * let projection = map.getProjection();
     * ```
     */
    getProjection() { return this.style.getProjection(); }
    /**
     * Sets the {@link ProjectionSpecification}.
     * @param projection - the projection specification to set
     * @returns
     */
    setProjection(projection) {
        this._lazyInitEmptyStyle();
        this.style.setProjection(projection);
        return this._update(true);
    }
};

const defaultOptions$3 = {
    showCompass: true,
    showZoom: true,
    visualizePitch: false,
    visualizeRoll: true
};
/**
 * 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/display-map-navigation-controls/)
 */
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 = () => {
            if (this.options.visualizePitch && this.options.visualizeRoll) {
                this._compassIcon.style.transform = `scale(${1 / Math.pow(Math.cos(this._map.transform.pitchInRadians), 0.5)}) rotateZ(${-this._map.transform.roll}deg) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`;
                return;
            }
            if (this.options.visualizePitch) {
                this._compassIcon.style.transform = `scale(${1 / Math.pow(Math.cos(this._map.transform.pitchInRadians), 0.5)}) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`;
                return;
            }
            if (this.options.visualizeRoll) {
                this._compassIcon.style.transform = `rotate(${-this._map.transform.bearing - this._map.transform.roll}deg)`;
                return;
            }
            this._compassIcon.style.transform = `rotate(${-this._map.transform.bearing}deg)`;
        };
        this._setButtonTitle = (button, title) => {
            const str = this._map._getUIString(`NavigationControl.${title}`);
            button.title = str;
            button.setAttribute('aria-label', str);
        };
        this.options = symbol_layout.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);
            }
            if (this.options.visualizeRoll) {
                this._map.on('roll', 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() {
        this._container.remove();
        if (this.options.showZoom) {
            this._map.off('zoom', this._updateZoomButtons);
        }
        if (this.options.showCompass) {
            if (this.options.visualizePitch) {
                this._map.off('pitch', this._rotateCompassArrow);
            }
            if (this.options.visualizeRoll) {
                this._map.off('roll', 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.startMove(e, DOM.mousePos(this.element, e));
            window.addEventListener('mousemove', this.mousemove);
            window.addEventListener('mouseup', this.mouseup);
        };
        this.mousemove = (e) => {
            this.move(e, DOM.mousePos(this.element, e));
        };
        this.mouseup = (e) => {
            this._rotatePitchHandler.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.startMove(e, this._startPos);
                window.addEventListener('touchmove', this.touchmove, { passive: false });
                window.addEventListener('touchend', this.touchend);
            }
        };
        this.touchmove = (e) => {
            if (e.targetTouches.length !== 1) {
                this.reset();
            }
            else {
                this._lastPos = DOM.touchPos(this.element, e.targetTouches)[0];
                this.move(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._rotatePitchHandler.reset();
            delete this._startPos;
            delete this._lastPos;
            this.offTemp();
        };
        this._clickTolerance = 10;
        this.element = element;
        const moveStateManager = new MouseOrTouchMoveStateManager();
        this._rotatePitchHandler = new DragHandler({
            clickTolerance: 3,
            move: (lastPoint, currentPoint) => {
                const rect = element.getBoundingClientRect();
                const center = new symbol_layout.Point((rect.bottom - rect.top) / 2, (rect.right - rect.left) / 2);
                const bearingDelta = symbol_layout.getAngleDelta(new symbol_layout.Point(lastPoint.x, currentPoint.y), currentPoint, center);
                const pitchDelta = pitch ? (currentPoint.y - lastPoint.y) * -0.5 : undefined;
                return { bearingDelta, pitchDelta };
            },
            moveStateManager,
            enable: true,
            assignEvents: () => { },
        });
        this.map = map;
        element.addEventListener('mousedown', this.mousedown);
        element.addEventListener('touchstart', this.touchstart, { passive: false });
        element.addEventListener('touchcancel', this.reset);
    }
    startMove(e, point) {
        this._rotatePitchHandler.dragStart(e, point);
        DOM.disableDrag();
    }
    move(e, point) {
        const map = this.map;
        const { bearingDelta, pitchDelta } = this._rotatePitchHandler.dragMove(e, point) || {};
        if (bearingDelta)
            map.setBearing(map.getBearing() + bearingDelta);
        if (pitchDelta)
            map.setPitch(map.getPitch() + pitchDelta);
    }
    off() {
        const element = this.element;
        element.removeEventListener('mousedown', this.mousedown);
        element.removeEventListener('touchstart', this.touchstart);
        window.removeEventListener('touchmove', this.touchmove);
        window.removeEventListener('touchend', this.touchend);
        element.removeEventListener('touchcancel', this.reset);
        this.offTemp();
    }
    offTemp() {
        DOM.enableDrag();
        window.removeEventListener('mousemove', this.mousemove);
        window.removeEventListener('mouseup', this.mouseup);
        window.removeEventListener('touchmove', this.touchmove);
        window.removeEventListener('touchend', this.touchend);
    }
}

let supportsGeolocation;
function checkGeolocationSupport() {
    return symbol_layout.__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';
        }
        catch (_a) {
            // Fix for iOS16 which rejects query but still supports geolocation
            supportsGeolocation = !!window.navigator.geolocation;
        }
        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, useNormalWrap = false) {
    if (useNormalWrap || !transform.getCoveringTilesDetailsProvider().allowWorldCopies()) {
        return lngLat === null || lngLat === void 0 ? void 0 : lngLat.wrap();
    }
    const originalLngLat = new symbol_layout.LngLat(lngLat.lng, lngLat.lat);
    lngLat = new symbol_layout.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 symbol_layout.LngLat(lngLat.lng - 360, lngLat.lat);
        const right = new symbol_layout.LngLat(lngLat.lng + 360, lngLat.lat);
        const delta = transform.locationToScreenPoint(lngLat).distSqr(priorPos);
        if (transform.locationToScreenPoint(left).distSqr(priorPos) < delta) {
            lngLat = left;
        }
        else if (transform.locationToScreenPoint(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.locationToScreenPoint(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.isPointOnMapSurface(transform.locationToScreenPoint(lngLat))) {
        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 a default marker](https://maplibre.org/maplibre-gl-js/docs/examples/add-a-default-marker/)
 * @see [Add custom icons with Markers](https://maplibre.org/maplibre-gl-js/docs/examples/add-custom-icons-with-markers/)
 * @see [Create a draggable Marker](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-draggable-marker/)
 * @see [Animate a marker](https://maplibre.org/maplibre-gl-js/docs/examples/animate-a-marker/)
 * @see [Attach a popup to a marker instance](https://maplibre.org/maplibre-gl-js/docs/examples/attach-a-popup-to-a-marker-instance/)
 *
 * ## 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.
 *
 * **Event** `click` of type {@link Event} will be fired when the marker is clicked.
 *
 * ## CSS Classes
 *
 * **CSS class** `maplibregl-marker-covered` is toggled on the marker element when the marker
 * is hidden behind 3D terrain or on the back of a globe.
 * Use this class to apply custom styles to covered markers.
 *
 * @example
 * ```css
 * .maplibregl-marker-covered {
 *     pointer-events: none;
 *     cursor: default;
 * }
 * ```
 */
class Marker extends symbol_layout.Evented {
    /**
     * @param options - the options
     */
    constructor(options) {
        super();
        this._onClick = (e) => {
            this.fire(new symbol_layout.Event('click', { originalEvent: e }));
        };
        this._onKeyPress = (e) => {
            if (e.code === 'Space' || e.code === '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) => {
            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);
            }
            this._lngLat = smartWrap(this._lngLat, this._flatPos, this._map.transform);
            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.locationToScreenPoint(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();
            }
            this._element.style.transform = `${anchorTranslate[this._anchor]} translate(${this._pos.x}px, ${this._pos.y}px) ${pitch} ${rotation}`;
            browser.frameAsync(new AbortController(), this._map._ownerWindow).then(() => {
                this._updateOpacity((e === null || e === void 0 ? void 0 : 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 symbol_layout.Event('dragstart'));
            }
            this.fire(new symbol_layout.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 symbol_layout.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 === null || options === void 0 ? void 0 : options.anchor) || 'center';
        this._color = (options === null || options === void 0 ? void 0 : options.color) || '#3FB1CE';
        this._scale = (options === null || options === void 0 ? void 0 : options.scale) || 1;
        this._draggable = (options === null || options === void 0 ? void 0 : options.draggable) || false;
        this._clickTolerance = (options === null || options === void 0 ? void 0 : options.clickTolerance) || 0;
        this._subpixelPositioning = (options === null || options === void 0 ? void 0 : options.subpixelPositioning) || false;
        this._isDragging = false;
        this._state = 'inactive';
        this._rotation = (options === null || options === void 0 ? void 0 : options.rotation) || 0;
        this._rotationAlignment = (options === null || options === void 0 ? void 0 : options.rotationAlignment) || 'auto';
        this._pitchAlignment = (options === null || options === void 0 ? void 0 : options.pitchAlignment) && options.pitchAlignment !== 'auto' ? options.pitchAlignment : this._rotationAlignment;
        this.setOpacity(options === null || options === void 0 ? void 0 : options.opacity, options === null || options === void 0 ? void 0 : options.opacityWhenCovered);
        if (!(options === null || options === void 0 ? void 0 : 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 = symbol_layout.Point.convert((options === null || options === void 0 ? void 0 : options.offset) || [0, -14]);
        }
        else {
            this._element = options.element;
            this._offset = symbol_layout.Point.convert((options === null || options === void 0 ? void 0 : 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 === null || options === void 0 ? void 0 : 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;
        if (!this._element.hasAttribute('aria-label')) {
            this._element.setAttribute('aria-label', map._getUIString('Marker.Title'));
        }
        // aria-label is set either by user or above default, so set role
        // since div is interactive and cannot have aria-label without a role
        if (!this._element.hasAttribute('role')) {
            this._element.setAttribute('role', 'button');
        }
        map.getCanvasContainer().appendChild(this._element);
        map.on('move', this._update);
        map.on('moveend', this._update);
        map.on('terrain', this._update);
        map.on('projectiontransition', this._update);
        this._element.addEventListener('click', this._onClick);
        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('projectiontransition', 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;
        }
        this._element.removeEventListener('click', this._onClick);
        this._element.remove();
        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/create-a-draggable-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/add-custom-icons-with-markers/)
     * @see [Create a draggable Marker](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-draggable-marker/)
     */
    setLngLat(lnglat) {
        this._lngLat = symbol_layout.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("<h1>Hello World!</h1>")) // add popup
     *  .addTo(map);
     * ```
     * @see [Attach a popup to a marker instance](https://maplibre.org/maplibre-gl-js/docs/examples/attach-a-popup-to-a-marker-instance/)
     */
    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("<h1>Hello World!</h1>"))
     *  .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("<h1>Hello World!</h1>"))
     *  .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;
        const occluded = this._map.transform.isLocationOccluded(this._lngLat);
        if (!terrain || occluded) {
            const targetOpacity = occluded ? this._opacityWhenCovered : this._opacity;
            if (this._element.style.opacity !== targetOpacity) {
                this._element.style.opacity = targetOpacity;
                this._element.classList.toggle('maplibregl-marker-covered', occluded);
            }
            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.getElevationForLngLat(this._lngLat, map.transform);
        const markerDistance = map.transform.lngLatToCameraDepth(this._lngLat, elevation);
        const forgiveness = .006;
        if (markerDistance - terrainDistance < forgiveness) {
            this._element.style.opacity = this._opacity;
            this._element.classList.remove('maplibregl-marker-covered');
            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.pixelsPerMeter;
        const elevationToCenter = Math.sin(map.getPitch() * Math.PI / 180) * metersToCenter;
        const terrainDistanceCenter = map.terrain.depthAtPoint(new symbol_layout.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;
        this._element.classList.toggle('maplibregl-marker-covered', centerIsInvisible);
    }
    /**
     * 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 = symbol_layout.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) {
        // Reset opacity when called without params or from constructor
        if (this._opacity === undefined || (opacity === undefined && opacityWhenCovered === undefined)) {
            this._opacity = '1';
            this._opacityWhenCovered = '0.2';
        }
        if (opacity !== undefined) {
            this._opacity = String(opacity);
        }
        if (opacityWhenCovered !== undefined) {
            this._opacityWhenCovered = String(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-the-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 symbol_layout.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 symbol_layout.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 symbol_layout.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 symbol_layout.LngLat(position.coords.longitude, position.coords.latitude);
            const radius = position.coords.accuracy;
            const bearing = this._map.getBearing();
            const options = symbol_layout.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 symbol_layout.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;
                this._updateCircleRadiusIfNeeded();
            }
            else {
                this._userLocationDotMarker.remove();
                this._accuracyCircleMarker.remove();
            }
        };
        this._onUpdate = () => {
            this._updateCircleRadiusIfNeeded();
        };
        this._onError = (error) => {
            if (!this._map) {
                // control has since been removed
                return;
            }
            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 symbol_layout.Event('error', error));
            this._finish();
        };
        this._finish = () => {
            if (this._timeoutId) {
                clearTimeout(this._timeoutId);
            }
            this._timeoutId = undefined;
        };
        this._onMoveStart = (event) => {
            if (!this._map)
                return;
            const fromResize = (event === null || event === void 0 ? void 0 : event[0]) instanceof ResizeObserverEntry;
            if (!event.geolocateSource && this._watchState === 'ACTIVE_LOCK' && !fromResize && !this._map.isZooming()) {
                this._watchState = 'BACKGROUND';
                this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-background');
                this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active');
                this.fire(new symbol_layout.Event('trackuserlocationend'));
                this.fire(new symbol_layout.Event('userlocationlostfocus'));
            }
        };
        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) {
                symbol_layout.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._onUpdate);
                this._map.on('move', this._onUpdate);
                this._map.on('rotate', this._onUpdate);
                this._map.on('pitch', this._onUpdate);
            }
            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', this._onMoveStart);
            }
        };
        this.options = symbol_layout.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();
        }
        this._container.remove();
        this._map.off('movestart', this._onMoveStart);
        this._map.off('zoom', this._onUpdate);
        this._map.off('move', this._onUpdate);
        this._map.off('rotate', this._onUpdate);
        this._map.off('pitch', this._onUpdate);
        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':
            case 'BACKGROUND_ERROR':
                // already in error state
                break;
            case 'OFF':
            case undefined:
                // when trackUserLocation is false, watchState is undefined
                // when trackUserLocation is true but not activated, watchState is 'OFF'
                // in both cases, no error state transition is needed
                break;
            default:
                throw new Error(`Unexpected watchState ${this._watchState}`);
        }
    }
    _updateCircleRadiusIfNeeded() {
        const userLocation = this._userLocationDotMarker.getLngLat();
        if (!this.options.showUserLocation || !this.options.showAccuracyCircle || !this._accuracy || !userLocation) {
            return;
        }
        const screenPosition = this._map.project(userLocation);
        const userLocationWith100Px = this._map.unproject([screenPosition.x + 100, screenPosition.y]);
        const pixelsToMeters = userLocation.distanceTo(userLocationWith100Px) / 100;
        const circleDiameter = 2 * this._accuracy / pixelsToMeters;
        this._circleElement.style.width = `${circleDiameter.toFixed(2)}px`;
        this._circleElement.style.height = `${circleDiameter.toFixed(2)}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) {
            symbol_layout.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 symbol_layout.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 symbol_layout.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 symbol_layout.Event('trackuserlocationstart'));
                    this.fire(new symbol_layout.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() {
        this._container.remove();
        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.
    // Minimum maxWidth is calculated for the scale box.
    const optWidth = (options === null || options === void 0 ? void 0 : options.maxWidth) || 100;
    const y = map._container.clientHeight / 2;
    const x = map._container.clientWidth / 2;
    const left = map.unproject([x - optWidth / 2, y]);
    const right = map.unproject([x + optWidth / 2, y]);
    const globeWidth = Math.round(map.project(right).x - map.project(left).x);
    const maxWidth = Math.min(optWidth, globeWidth, map._container.clientWidth);
    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 === null || options === void 0 ? void 0 : 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 === null || options === void 0 ? void 0 : 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}&nbsp;${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/view-a-fullscreen-map/)
 *
 * ## 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 symbol_layout.Evented {
    /**
     * @param options - the control's options
     */
    constructor(options = {}) {
        var _a;
        super();
        this._onFullscreenChange = () => {
            var _a;
            // WebKit due to https://caniuse.com/mdn-api_document_fullscreenelement
            let fullscreenElement = window.document.fullscreenElement ||
                window.document.webkitFullscreenElement;
            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;
        this._pseudo = (_a = options.pseudo) !== null && _a !== void 0 ? _a : false;
        if (options === null || options === void 0 ? void 0 : options.container) {
            if (options.container instanceof HTMLElement) {
                this._container = options.container;
            }
            else {
                symbol_layout.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() {
        this._controlContainer.remove();
        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 symbol_layout.Event('fullscreenstart'));
            this._prevCooperativeGesturesEnabled = this._map.cooperativeGestures.isEnabled();
            this._map.cooperativeGestures.disable();
        }
        else {
            this.fire(new symbol_layout.Event('fullscreenend'));
            if (this._prevCooperativeGesturesEnabled) {
                this._map.cooperativeGestures.enable();
            }
        }
    }
    _exitFullscreen() {
        if (this._pseudo) {
            this._togglePseudoFullScreen();
        }
        else if (window.document.exitFullscreen) {
            window.document.exitFullscreen();
        }
        else if (window.document.webkitCancelFullScreen) {
            // due to https://caniuse.com/mdn-api_document_exitfullscreen
            window.document.webkitCancelFullScreen();
        }
        else {
            this._togglePseudoFullScreen();
        }
    }
    _requestFullscreen() {
        if (this._pseudo) {
            this._togglePseudoFullScreen();
        }
        else if (this._container.requestFullscreen) {
            this._container.requestFullscreen();
        }
        else if (this._container.webkitRequestFullscreen) {
            // due to https://caniuse.com/mdn-api_element_requestfullscreen
            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"
 *     }));
 * ```
 * @see [3D Terrain](https://maplibre.org/maplibre-gl-js/docs/examples/3d-terrain/)
 * @see [Create a Heatmap layer on a globe with terrain elevation](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-heatmap-layer-on-a-globe-with-terrain-elevation/)
 * @see [Display a hybrid satellite map with terrain elevation](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-hybrid-satellite-map-with-terrain-elevation/)
 * @see [Sky, Fog, Terrain](https://maplibre.org/maplibre-gl-js/docs/examples/sky-fog-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() {
        this._container.remove();
        this._map.off('terrain', this._updateTerrainIcon);
        this._map = undefined;
    }
}

/**
 * A `GlobeControl` control contains a button for toggling the map projection between "mercator" and "globe".
 *
 * @group Markers and Controls
 *
 * @example
 * ```ts
 * let map = new Map()
 *     .addControl(new GlobeControl());
 * ```
 *
 * @see [Display a globe with a fill extrusion layer](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-globe-with-a-fill-extrusion-layer/)
 * @see [Sky, Fog, Terrain](https://maplibre.org/maplibre-gl-js/docs/examples/sky-fog-terrain/)
 */
class GlobeControl {
    constructor() {
        this._toggleProjection = () => {
            var _a;
            const currentProjection = (_a = this._map.getProjection()) === null || _a === void 0 ? void 0 : _a.type;
            if (currentProjection === 'mercator' || !currentProjection) {
                this._map.setProjection({ type: 'globe' });
            }
            else {
                this._map.setProjection({ type: 'mercator' });
            }
            this._updateGlobeIcon();
        };
        this._updateGlobeIcon = () => {
            var _a;
            this._globeButton.classList.remove('maplibregl-ctrl-globe');
            this._globeButton.classList.remove('maplibregl-ctrl-globe-enabled');
            if (((_a = this._map.getProjection()) === null || _a === void 0 ? void 0 : _a.type) === 'globe') {
                this._globeButton.classList.add('maplibregl-ctrl-globe-enabled');
                this._globeButton.title = this._map._getUIString('GlobeControl.Disable');
            }
            else {
                this._globeButton.classList.add('maplibregl-ctrl-globe');
                this._globeButton.title = this._map._getUIString('GlobeControl.Enable');
            }
        };
    }
    /** {@inheritDoc IControl.onAdd} */
    onAdd(map) {
        this._map = map;
        this._container = DOM.create('div', 'maplibregl-ctrl maplibregl-ctrl-group');
        this._globeButton = DOM.create('button', 'maplibregl-ctrl-globe', this._container);
        DOM.create('span', 'maplibregl-ctrl-icon', this._globeButton).setAttribute('aria-hidden', 'true');
        this._globeButton.type = 'button';
        this._globeButton.addEventListener('click', this._toggleProjection);
        this._updateGlobeIcon();
        this._map.on('styledata', this._updateGlobeIcon);
        this._map.on('projectiontransition', this._updateGlobeIcon);
        return this._container;
    }
    /** {@inheritDoc IControl.onRemove} */
    onRemove() {
        this._container.remove();
        this._map.off('styledata', this._updateGlobeIcon);
        this._map.off('projectiontransition', this._updateGlobeIcon);
        this._globeButton.removeEventListener('click', this._toggleProjection);
        this._map = undefined;
    }
}

const defaultOptions = {
    closeButton: true,
    closeOnClick: true,
    focusAfterOpen: true,
    className: '',
    maxWidth: '240px',
    subpixelPositioning: false,
    locationOccludedOpacity: undefined,
    padding: undefined,
};
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("<h1>Hello World!</h1>")
 *   .setMaxWidth("300px")
 *   .addTo(map);
 * ```
 * @see [Display a popup](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-popup/)
 * @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-popup-on-hover/)
 * @see [Display a popup on click](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-popup-on-click/)
 * @see [Attach a popup to a marker instance](https://maplibre.org/maplibre-gl-js/docs/examples/attach-a-popup-to-a-marker-instance/)
 * @see [Show polygon information on click](https://maplibre.org/maplibre-gl-js/docs/examples/show-polygon-information-on-click/)
 *
 * ## 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 symbol_layout.Evented {
    /**
     * @param options - the options
     */
    constructor(options) {
        super();
        /**
         * Add opacity to popup if in globe projection and location is behind view
         */
        this._updateOpacity = () => {
            if (this.options.locationOccludedOpacity === undefined) {
                return;
            }
            if (this._map.transform.isLocationOccluded(this.getLngLat())) {
                this._container.style.opacity = `${this.options.locationOccludedOpacity}`;
            }
            else {
                this._container.style.opacity = '';
            }
        };
        /**
         * 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) {
                this._content.remove();
            }
            if (this._container) {
                this._container.remove();
                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._update);
                this._map.off('mouseup', this._update);
                this._map.off('drag', this._update);
                this._map._canvasContainer.classList.remove('maplibregl-track-pointer');
                delete this._map;
                this.fire(new symbol_layout.Event('close'));
            }
            return this;
        };
        this._update = (event) => {
            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;
            }
            this._lngLat = smartWrap(this._lngLat, this._flatPos, this._map.transform, this._trackPointer);
            let cursor;
            if (event && 'point' in event && event.point) {
                cursor = event.point;
            }
            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.locationToScreenPoint(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;
                const padding = normalizePadding(this.options.padding);
                let anchorComponents;
                if (pos.y + offset.bottom.y < height + padding.top) {
                    anchorComponents = ['top'];
                }
                else if (pos.y > this._map.transform.height - height - padding.bottom) {
                    anchorComponents = ['bottom'];
                }
                else {
                    anchorComponents = [];
                }
                if (pos.x < width / 2 + padding.left) {
                    anchorComponents.push('left');
                }
                else if (pos.x > this._map.transform.width - width / 2 - padding.right) {
                    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();
            }
            this._container.style.transform = `${anchorTranslate[anchor]} translate(${offsetedPos.x}px,${offsetedPos.y}px)`;
            applyAnchorClass(this._container, anchor, 'popup');
            this._updateOpacity();
        };
        this._onClose = () => {
            this.remove();
        };
        this.options = symbol_layout.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("<h1>Null Island</h1>")
     *   .addTo(map);
     * ```
     * @see [Display a popup](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-popup/)
     * @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-popup-on-hover/)
     * @see [Display a popup on click](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-popup-on-click/)
     * @see [Show polygon information on click](https://maplibre.org/maplibre-gl-js/docs/examples/show-polygon-information-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._update);
            this._map.on('mouseup', this._update);
            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 symbol_layout.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 = symbol_layout.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._update);
            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("<h1>Hello World!</h1>")
     *   .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._update);
            this._map.on('drag', this._update);
            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("<p>Hello World!</p>")
     *   .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("<h1>Hello World!</h1>")
     *   .addTo(map);
     * ```
     * @see [Display a popup](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-popup/)
     * @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-popup-on-hover/)
     * @see [Display a popup on click](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-popup-on-click/)
     * @see [Attach a popup to a marker instance](https://maplibre.org/maplibre-gl-js/docs/examples/attach-a-popup-to-a-marker-instance/)
     */
    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;
    }
    /**
     * Sets the popup's padding constraints for positioning.
     *
     * @param padding - The padding to apply as a {@link PaddingOptions} object.
     * @example
     * ```ts
     * popup.setPadding({ top: 10, right: 20, bottom: 30, left: 40 });
     * ```
     */
    setPadding(padding) {
        this.options.padding = padding;
        this._update();
    }
    _createCloseButton() {
        if (this.options.closeButton) {
            this._closeButton = DOM.create('button', 'maplibregl-popup-close-button', this._content);
            this._closeButton.type = 'button';
            this._closeButton.innerHTML = '&#215;';
            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 symbol_layout.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 symbol_layout.Point(0, 0),
            'top': new symbol_layout.Point(0, offset),
            'top-left': new symbol_layout.Point(cornerOffset, cornerOffset),
            'top-right': new symbol_layout.Point(-cornerOffset, cornerOffset),
            'bottom': new symbol_layout.Point(0, -offset),
            'bottom-left': new symbol_layout.Point(cornerOffset, -cornerOffset),
            'bottom-right': new symbol_layout.Point(-cornerOffset, -cornerOffset),
            'left': new symbol_layout.Point(offset, 0),
            'right': new symbol_layout.Point(-offset, 0)
        };
    }
    else if (offset instanceof symbol_layout.Point || Array.isArray(offset)) {
        // input specifies a single offset to be applied to all positions
        const convertedOffset = symbol_layout.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': symbol_layout.Point.convert(offset['center'] || [0, 0]),
            'top': symbol_layout.Point.convert(offset['top'] || [0, 0]),
            'top-left': symbol_layout.Point.convert(offset['top-left'] || [0, 0]),
            'top-right': symbol_layout.Point.convert(offset['top-right'] || [0, 0]),
            'bottom': symbol_layout.Point.convert(offset['bottom'] || [0, 0]),
            'bottom-left': symbol_layout.Point.convert(offset['bottom-left'] || [0, 0]),
            'bottom-right': symbol_layout.Point.convert(offset['bottom-right'] || [0, 0]),
            'left': symbol_layout.Point.convert(offset['left'] || [0, 0]),
            'right': symbol_layout.Point.convert(offset['right'] || [0, 0])
        };
    }
}
function normalizePadding(padding) {
    var _a, _b, _c, _d;
    if (!padding) {
        return { top: 0, right: 0, bottom: 0, left: 0 };
    }
    return {
        top: (_a = padding.top) !== null && _a !== void 0 ? _a : 0,
        right: (_b = padding.right) !== null && _b !== void 0 ? _b : 0,
        bottom: (_c = padding.bottom) !== null && _c !== void 0 ? _c : 0,
        left: (_d = padding.left) !== null && _d !== void 0 ? _d : 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.3.0/dist/mapbox-gl-rtl-text.js', false);
 * ```
 * @see [Add support for right-to-left scripts](https://maplibre.org/maplibre-gl-js/docs/examples/add-support-for-right-to-left-scripts/)
 * @see [Display and style rich text labels](https://maplibre.org/maplibre-gl-js/docs/examples/display-and-style-rich-text-labels/)
 */
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 symbol_layout.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) { symbol_layout.config.MAX_PARALLEL_IMAGE_REQUESTS = numRequests; }
/**
 * Gets the worker url
 * @returns The worker url
 */
function getWorkerUrl() { return symbol_layout.config.WORKER_URL; }
/**
 * Sets the worker url
 */
function setWorkerUrl(value) { symbol_layout.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$1.AJAXError = symbol_layout.AJAXError;
exports$1.EXTENT = symbol_layout.EXTENT;
exports$1.Event = symbol_layout.Event;
exports$1.Evented = symbol_layout.Evented;
exports$1.LngLat = symbol_layout.LngLat;
exports$1.MercatorCoordinate = symbol_layout.MercatorCoordinate;
exports$1.Point = symbol_layout.Point;
exports$1.addProtocol = symbol_layout.addProtocol;
exports$1.config = symbol_layout.config;
exports$1.removeProtocol = symbol_layout.removeProtocol;
exports$1.AttributionControl = AttributionControl;
exports$1.BoxZoomHandler = BoxZoomHandler;
exports$1.CanvasSource = CanvasSource;
exports$1.CooperativeGesturesHandler = CooperativeGesturesHandler;
exports$1.DoubleClickZoomHandler = DoubleClickZoomHandler;
exports$1.DragPanHandler = DragPanHandler;
exports$1.DragRotateHandler = DragRotateHandler;
exports$1.EdgeInsets = EdgeInsets;
exports$1.FullscreenControl = FullscreenControl;
exports$1.GeoJSONSource = GeoJSONSource;
exports$1.GeolocateControl = GeolocateControl;
exports$1.GlobeControl = GlobeControl;
exports$1.Hash = Hash;
exports$1.ImageSource = ImageSource;
exports$1.KeyboardHandler = KeyboardHandler;
exports$1.LngLatBounds = LngLatBounds;
exports$1.LogoControl = LogoControl;
exports$1.Map = Map$1;
exports$1.MapLibreMap = Map$1;
exports$1.MapMouseEvent = MapMouseEvent;
exports$1.MapTouchEvent = MapTouchEvent;
exports$1.MapWheelEvent = MapWheelEvent;
exports$1.Marker = Marker;
exports$1.NavigationControl = NavigationControl;
exports$1.Popup = Popup;
exports$1.RasterDEMTileSource = RasterDEMTileSource;
exports$1.RasterTileSource = RasterTileSource;
exports$1.ScaleControl = ScaleControl;
exports$1.ScrollZoomHandler = ScrollZoomHandler;
exports$1.Style = Style;
exports$1.TerrainControl = TerrainControl;
exports$1.TwoFingersTouchPitchHandler = TwoFingersTouchPitchHandler;
exports$1.TwoFingersTouchRotateHandler = TwoFingersTouchRotateHandler;
exports$1.TwoFingersTouchZoomHandler = TwoFingersTouchZoomHandler;
exports$1.TwoFingersTouchZoomRotateHandler = TwoFingersTouchZoomRotateHandler;
exports$1.VectorTileSource = VectorTileSource;
exports$1.VideoSource = VideoSource;
exports$1.addSourceType = addSourceType;
exports$1.clearPrewarmedResources = clearPrewarmedResources;
exports$1.createTileMesh = createTileMesh;
exports$1.getGlobalDispatcher = getGlobalDispatcher;
exports$1.getMaxParallelImageRequests = getMaxParallelImageRequests;
exports$1.getRTLTextPluginStatus = getRTLTextPluginStatus;
exports$1.getVersion = getVersion;
exports$1.getWorkerCount = getWorkerCount;
exports$1.getWorkerUrl = getWorkerUrl;
exports$1.importScriptInWorkers = importScriptInWorkers;
exports$1.isTimeFrozen = isTimeFrozen;
exports$1.now = now;
exports$1.prewarm = prewarm;
exports$1.restoreNow = restoreNow;
exports$1.setMaxParallelImageRequests = setMaxParallelImageRequests;
exports$1.setNow = setNow;
exports$1.setRTLTextPlugin = setRTLTextPlugin;
exports$1.setWorkerCount = setWorkerCount;
exports$1.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
