(function webpackUniversalModuleDefinition(root, factory) { if (typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if (typeof define === 'function' && define.amd) define([], factory); else if (typeof exports === 'object') exports['deck'] = factory(); else root['deck'] = factory();})(globalThis, function () { "use strict"; var __exports__ = (() => { var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __require = /* @__PURE__ */ ((x2) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x2, { get: (a2, b) => (typeof require !== "undefined" ? require : a2)[b] }) : x2)(function(x2) { if (typeof require !== "undefined") return require.apply(this, arguments); throw new Error('Dynamic require of "' + x2 + '" is not supported'); }); var __commonJS = (cb, mod2) => function __require2() { return mod2 || (0, cb[__getOwnPropNames(cb)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports; }; var __export = (target, all) => { for (var name12 in all) __defProp(target, name12, { get: all[name12], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __reExport = (target, mod2, secondTarget) => (__copyProps(target, mod2, "default"), secondTarget && __copyProps(secondTarget, mod2, "default")); var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps( isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target, mod2 )); var __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2); var __publicField = (obj, key, value) => { __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; // external-global-plugin:@deck.gl/layers var require_layers = __commonJS({ "external-global-plugin:@deck.gl/layers"(exports, module) { module.exports = globalThis.deck; } }); // external-global-plugin:@deck.gl/core var require_core = __commonJS({ "external-global-plugin:@deck.gl/core"(exports, module) { module.exports = globalThis.deck; } }); // ../../node_modules/fast-xml-parser/src/util.js var require_util = __commonJS({ "../../node_modules/fast-xml-parser/src/util.js"(exports) { "use strict"; var nameStartChar = ":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD"; var nameChar = nameStartChar + "\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040"; var nameRegexp = "[" + nameStartChar + "][" + nameChar + "]*"; var regexName = new RegExp("^" + nameRegexp + "$"); var getAllMatches = function(string, regex) { const matches3 = []; let match = regex.exec(string); while (match) { const allmatches = []; allmatches.startIndex = regex.lastIndex - match[0].length; const len2 = match.length; for (let index = 0; index < len2; index++) { allmatches.push(match[index]); } matches3.push(allmatches); match = regex.exec(string); } return matches3; }; var isName = function(string) { const match = regexName.exec(string); return !(match === null || typeof match === "undefined"); }; exports.isExist = function(v) { return typeof v !== "undefined"; }; exports.isEmptyObject = function(obj) { return Object.keys(obj).length === 0; }; exports.merge = function(target, a2, arrayMode) { if (a2) { const keys = Object.keys(a2); const len2 = keys.length; for (let i3 = 0; i3 < len2; i3++) { if (arrayMode === "strict") { target[keys[i3]] = [a2[keys[i3]]]; } else { target[keys[i3]] = a2[keys[i3]]; } } } }; exports.getValue = function(v) { if (exports.isExist(v)) { return v; } else { return ""; } }; exports.isName = isName; exports.getAllMatches = getAllMatches; exports.nameRegexp = nameRegexp; } }); // ../../node_modules/fast-xml-parser/src/validator.js var require_validator = __commonJS({ "../../node_modules/fast-xml-parser/src/validator.js"(exports) { "use strict"; var util = require_util(); var defaultOptions = { allowBooleanAttributes: false, unpairedTags: [] }; exports.validate = function(xmlData, options) { options = Object.assign({}, defaultOptions, options); const tags = []; let tagFound = false; let reachedRoot = false; if (xmlData[0] === "\uFEFF") { xmlData = xmlData.substr(1); } for (let i3 = 0; i3 < xmlData.length; i3++) { if (xmlData[i3] === "<" && xmlData[i3 + 1] === "?") { i3 += 2; i3 = readPI(xmlData, i3); if (i3.err) return i3; } else if (xmlData[i3] === "<") { let tagStartPos = i3; i3++; if (xmlData[i3] === "!") { i3 = readCommentAndCDATA(xmlData, i3); continue; } else { let closingTag = false; if (xmlData[i3] === "/") { closingTag = true; i3++; } let tagName = ""; for (; i3 < xmlData.length && xmlData[i3] !== ">" && xmlData[i3] !== " " && xmlData[i3] !== " " && xmlData[i3] !== "\n" && xmlData[i3] !== "\r"; i3++) { tagName += xmlData[i3]; } tagName = tagName.trim(); if (tagName[tagName.length - 1] === "/") { tagName = tagName.substring(0, tagName.length - 1); i3--; } if (!validateTagName(tagName)) { let msg; if (tagName.trim().length === 0) { msg = "Invalid space after '<'."; } else { msg = "Tag '" + tagName + "' is an invalid name."; } return getErrorObject("InvalidTag", msg, getLineNumberForPosition(xmlData, i3)); } const result = readAttributeStr(xmlData, i3); if (result === false) { return getErrorObject("InvalidAttr", "Attributes for '" + tagName + "' have open quote.", getLineNumberForPosition(xmlData, i3)); } let attrStr = result.value; i3 = result.index; if (attrStr[attrStr.length - 1] === "/") { const attrStrStart = i3 - attrStr.length; attrStr = attrStr.substring(0, attrStr.length - 1); const isValid = validateAttributeString(attrStr, options); if (isValid === true) { tagFound = true; } else { return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line)); } } else if (closingTag) { if (!result.tagClosed) { return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' doesn't have proper closing.", getLineNumberForPosition(xmlData, i3)); } else if (attrStr.trim().length > 0) { return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos)); } else { const otg = tags.pop(); if (tagName !== otg.tagName) { let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos); return getErrorObject( "InvalidTag", "Expected closing tag '" + otg.tagName + "' (opened in line " + openPos.line + ", col " + openPos.col + ") instead of closing tag '" + tagName + "'.", getLineNumberForPosition(xmlData, tagStartPos) ); } if (tags.length == 0) { reachedRoot = true; } } } else { const isValid = validateAttributeString(attrStr, options); if (isValid !== true) { return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i3 - attrStr.length + isValid.err.line)); } if (reachedRoot === true) { return getErrorObject("InvalidXml", "Multiple possible root nodes found.", getLineNumberForPosition(xmlData, i3)); } else if (options.unpairedTags.indexOf(tagName) !== -1) { } else { tags.push({ tagName, tagStartPos }); } tagFound = true; } for (i3++; i3 < xmlData.length; i3++) { if (xmlData[i3] === "<") { if (xmlData[i3 + 1] === "!") { i3++; i3 = readCommentAndCDATA(xmlData, i3); continue; } else if (xmlData[i3 + 1] === "?") { i3 = readPI(xmlData, ++i3); if (i3.err) return i3; } else { break; } } else if (xmlData[i3] === "&") { const afterAmp = validateAmpersand(xmlData, i3); if (afterAmp == -1) return getErrorObject("InvalidChar", "char '&' is not expected.", getLineNumberForPosition(xmlData, i3)); i3 = afterAmp; } else { if (reachedRoot === true && !isWhiteSpace(xmlData[i3])) { return getErrorObject("InvalidXml", "Extra text at the end", getLineNumberForPosition(xmlData, i3)); } } } if (xmlData[i3] === "<") { i3--; } } } else { if (isWhiteSpace(xmlData[i3])) { continue; } return getErrorObject("InvalidChar", "char '" + xmlData[i3] + "' is not expected.", getLineNumberForPosition(xmlData, i3)); } } if (!tagFound) { return getErrorObject("InvalidXml", "Start tag expected.", 1); } else if (tags.length == 1) { return getErrorObject("InvalidTag", "Unclosed tag '" + tags[0].tagName + "'.", getLineNumberForPosition(xmlData, tags[0].tagStartPos)); } else if (tags.length > 0) { return getErrorObject("InvalidXml", "Invalid '" + JSON.stringify(tags.map((t2) => t2.tagName), null, 4).replace(/\r?\n/g, "") + "' found.", { line: 1, col: 1 }); } return true; }; function isWhiteSpace(char) { return char === " " || char === " " || char === "\n" || char === "\r"; } function readPI(xmlData, i3) { const start = i3; for (; i3 < xmlData.length; i3++) { if (xmlData[i3] == "?" || xmlData[i3] == " ") { const tagname = xmlData.substr(start, i3 - start); if (i3 > 5 && tagname === "xml") { return getErrorObject("InvalidXml", "XML declaration allowed only at the start of the document.", getLineNumberForPosition(xmlData, i3)); } else if (xmlData[i3] == "?" && xmlData[i3 + 1] == ">") { i3++; break; } else { continue; } } } return i3; } function readCommentAndCDATA(xmlData, i3) { if (xmlData.length > i3 + 5 && xmlData[i3 + 1] === "-" && xmlData[i3 + 2] === "-") { for (i3 += 3; i3 < xmlData.length; i3++) { if (xmlData[i3] === "-" && xmlData[i3 + 1] === "-" && xmlData[i3 + 2] === ">") { i3 += 2; break; } } } else if (xmlData.length > i3 + 8 && xmlData[i3 + 1] === "D" && xmlData[i3 + 2] === "O" && xmlData[i3 + 3] === "C" && xmlData[i3 + 4] === "T" && xmlData[i3 + 5] === "Y" && xmlData[i3 + 6] === "P" && xmlData[i3 + 7] === "E") { let angleBracketsCount = 1; for (i3 += 8; i3 < xmlData.length; i3++) { if (xmlData[i3] === "<") { angleBracketsCount++; } else if (xmlData[i3] === ">") { angleBracketsCount--; if (angleBracketsCount === 0) { break; } } } } else if (xmlData.length > i3 + 9 && xmlData[i3 + 1] === "[" && xmlData[i3 + 2] === "C" && xmlData[i3 + 3] === "D" && xmlData[i3 + 4] === "A" && xmlData[i3 + 5] === "T" && xmlData[i3 + 6] === "A" && xmlData[i3 + 7] === "[") { for (i3 += 8; i3 < xmlData.length; i3++) { if (xmlData[i3] === "]" && xmlData[i3 + 1] === "]" && xmlData[i3 + 2] === ">") { i3 += 2; break; } } } return i3; } var doubleQuote = '"'; var singleQuote = "'"; function readAttributeStr(xmlData, i3) { let attrStr = ""; let startChar = ""; let tagClosed = false; for (; i3 < xmlData.length; i3++) { if (xmlData[i3] === doubleQuote || xmlData[i3] === singleQuote) { if (startChar === "") { startChar = xmlData[i3]; } else if (startChar !== xmlData[i3]) { } else { startChar = ""; } } else if (xmlData[i3] === ">") { if (startChar === "") { tagClosed = true; break; } } attrStr += xmlData[i3]; } if (startChar !== "") { return false; } return { value: attrStr, index: i3, tagClosed }; } var validAttrStrRegxp = new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`, "g"); function validateAttributeString(attrStr, options) { const matches3 = util.getAllMatches(attrStr, validAttrStrRegxp); const attrNames = {}; for (let i3 = 0; i3 < matches3.length; i3++) { if (matches3[i3][1].length === 0) { return getErrorObject("InvalidAttr", "Attribute '" + matches3[i3][2] + "' has no space in starting.", getPositionFromMatch(matches3[i3])); } else if (matches3[i3][3] !== void 0 && matches3[i3][4] === void 0) { return getErrorObject("InvalidAttr", "Attribute '" + matches3[i3][2] + "' is without value.", getPositionFromMatch(matches3[i3])); } else if (matches3[i3][3] === void 0 && !options.allowBooleanAttributes) { return getErrorObject("InvalidAttr", "boolean attribute '" + matches3[i3][2] + "' is not allowed.", getPositionFromMatch(matches3[i3])); } const attrName = matches3[i3][2]; if (!validateAttrName(attrName)) { return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is an invalid name.", getPositionFromMatch(matches3[i3])); } if (!attrNames.hasOwnProperty(attrName)) { attrNames[attrName] = 1; } else { return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is repeated.", getPositionFromMatch(matches3[i3])); } } return true; } function validateNumberAmpersand(xmlData, i3) { let re = /\d/; if (xmlData[i3] === "x") { i3++; re = /[\da-fA-F]/; } for (; i3 < xmlData.length; i3++) { if (xmlData[i3] === ";") return i3; if (!xmlData[i3].match(re)) break; } return -1; } function validateAmpersand(xmlData, i3) { i3++; if (xmlData[i3] === ";") return -1; if (xmlData[i3] === "#") { i3++; return validateNumberAmpersand(xmlData, i3); } let count = 0; for (; i3 < xmlData.length; i3++, count++) { if (xmlData[i3].match(/\w/) && count < 20) continue; if (xmlData[i3] === ";") break; return -1; } return i3; } function getErrorObject(code, message, lineNumber) { return { err: { code, msg: message, line: lineNumber.line || lineNumber, col: lineNumber.col } }; } function validateAttrName(attrName) { return util.isName(attrName); } function validateTagName(tagname) { return util.isName(tagname); } function getLineNumberForPosition(xmlData, index) { const lines = xmlData.substring(0, index).split(/\r?\n/); return { line: lines.length, col: lines[lines.length - 1].length + 1 }; } function getPositionFromMatch(match) { return match.startIndex + match[1].length; } } }); // ../../node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js var require_OptionsBuilder = __commonJS({ "../../node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(exports) { var defaultOptions = { preserveOrder: false, attributeNamePrefix: "@_", attributesGroupName: false, textNodeName: "#text", ignoreAttributes: true, removeNSPrefix: false, allowBooleanAttributes: false, parseTagValue: true, parseAttributeValue: false, trimValues: true, cdataPropName: false, numberParseOptions: { hex: true, leadingZeros: true, eNotation: true }, tagValueProcessor: function(tagName, val2) { return val2; }, attributeValueProcessor: function(attrName, val2) { return val2; }, stopNodes: [], alwaysCreateTextNode: false, isArray: () => false, commentPropName: false, unpairedTags: [], processEntities: true, htmlEntities: false, ignoreDeclaration: false, ignorePiTags: false, transformTagName: false, transformAttributeName: false, updateTag: function(tagName, jPath, attrs) { return tagName; } }; var buildOptions = function(options) { return Object.assign({}, defaultOptions, options); }; exports.buildOptions = buildOptions; exports.defaultOptions = defaultOptions; } }); // ../../node_modules/fast-xml-parser/src/xmlparser/xmlNode.js var require_xmlNode = __commonJS({ "../../node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(exports, module) { "use strict"; var XmlNode = class { constructor(tagname) { this.tagname = tagname; this.child = []; this[":@"] = {}; } add(key, val2) { if (key === "__proto__") key = "#__proto__"; this.child.push({ [key]: val2 }); } addChild(node) { if (node.tagname === "__proto__") node.tagname = "#__proto__"; if (node[":@"] && Object.keys(node[":@"]).length > 0) { this.child.push({ [node.tagname]: node.child, [":@"]: node[":@"] }); } else { this.child.push({ [node.tagname]: node.child }); } } }; module.exports = XmlNode; } }); // ../../node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js var require_DocTypeReader = __commonJS({ "../../node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(exports, module) { var util = require_util(); function readDocType(xmlData, i3) { const entities = {}; if (xmlData[i3 + 3] === "O" && xmlData[i3 + 4] === "C" && xmlData[i3 + 5] === "T" && xmlData[i3 + 6] === "Y" && xmlData[i3 + 7] === "P" && xmlData[i3 + 8] === "E") { i3 = i3 + 9; let angleBracketsCount = 1; let hasBody = false, comment = false; let exp = ""; for (; i3 < xmlData.length; i3++) { if (xmlData[i3] === "<" && !comment) { if (hasBody && isEntity(xmlData, i3)) { i3 += 7; [entityName, val, i3] = readEntityExp(xmlData, i3 + 1); if (val.indexOf("&") === -1) entities[validateEntityName(entityName)] = { regx: RegExp(`&${entityName};`, "g"), val }; } else if (hasBody && isElement(xmlData, i3)) i3 += 8; else if (hasBody && isAttlist(xmlData, i3)) i3 += 8; else if (hasBody && isNotation(xmlData, i3)) i3 += 9; else if (isComment) comment = true; else throw new Error("Invalid DOCTYPE"); angleBracketsCount++; exp = ""; } else if (xmlData[i3] === ">") { if (comment) { if (xmlData[i3 - 1] === "-" && xmlData[i3 - 2] === "-") { comment = false; angleBracketsCount--; } } else { angleBracketsCount--; } if (angleBracketsCount === 0) { break; } } else if (xmlData[i3] === "[") { hasBody = true; } else { exp += xmlData[i3]; } } if (angleBracketsCount !== 0) { throw new Error(`Unclosed DOCTYPE`); } } else { throw new Error(`Invalid Tag instead of DOCTYPE`); } return { entities, i: i3 }; } function readEntityExp(xmlData, i3) { let entityName2 = ""; for (; i3 < xmlData.length && (xmlData[i3] !== "'" && xmlData[i3] !== '"'); i3++) { entityName2 += xmlData[i3]; } entityName2 = entityName2.trim(); if (entityName2.indexOf(" ") !== -1) throw new Error("External entites are not supported"); const startChar = xmlData[i3++]; let val2 = ""; for (; i3 < xmlData.length && xmlData[i3] !== startChar; i3++) { val2 += xmlData[i3]; } return [entityName2, val2, i3]; } function isComment(xmlData, i3) { if (xmlData[i3 + 1] === "!" && xmlData[i3 + 2] === "-" && xmlData[i3 + 3] === "-") return true; return false; } function isEntity(xmlData, i3) { if (xmlData[i3 + 1] === "!" && xmlData[i3 + 2] === "E" && xmlData[i3 + 3] === "N" && xmlData[i3 + 4] === "T" && xmlData[i3 + 5] === "I" && xmlData[i3 + 6] === "T" && xmlData[i3 + 7] === "Y") return true; return false; } function isElement(xmlData, i3) { if (xmlData[i3 + 1] === "!" && xmlData[i3 + 2] === "E" && xmlData[i3 + 3] === "L" && xmlData[i3 + 4] === "E" && xmlData[i3 + 5] === "M" && xmlData[i3 + 6] === "E" && xmlData[i3 + 7] === "N" && xmlData[i3 + 8] === "T") return true; return false; } function isAttlist(xmlData, i3) { if (xmlData[i3 + 1] === "!" && xmlData[i3 + 2] === "A" && xmlData[i3 + 3] === "T" && xmlData[i3 + 4] === "T" && xmlData[i3 + 5] === "L" && xmlData[i3 + 6] === "I" && xmlData[i3 + 7] === "S" && xmlData[i3 + 8] === "T") return true; return false; } function isNotation(xmlData, i3) { if (xmlData[i3 + 1] === "!" && xmlData[i3 + 2] === "N" && xmlData[i3 + 3] === "O" && xmlData[i3 + 4] === "T" && xmlData[i3 + 5] === "A" && xmlData[i3 + 6] === "T" && xmlData[i3 + 7] === "I" && xmlData[i3 + 8] === "O" && xmlData[i3 + 9] === "N") return true; return false; } function validateEntityName(name12) { if (util.isName(name12)) return name12; else throw new Error(`Invalid entity name ${name12}`); } module.exports = readDocType; } }); // ../../node_modules/strnum/strnum.js var require_strnum = __commonJS({ "../../node_modules/strnum/strnum.js"(exports, module) { var hexRegex = /^[-+]?0x[a-fA-F0-9]+$/; var numRegex = /^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/; if (!Number.parseInt && window.parseInt) { Number.parseInt = window.parseInt; } if (!Number.parseFloat && window.parseFloat) { Number.parseFloat = window.parseFloat; } var consider = { hex: true, leadingZeros: true, decimalPoint: ".", eNotation: true }; function toNumber2(str3, options = {}) { options = Object.assign({}, consider, options); if (!str3 || typeof str3 !== "string") return str3; let trimmedStr = str3.trim(); if (options.skipLike !== void 0 && options.skipLike.test(trimmedStr)) return str3; else if (options.hex && hexRegex.test(trimmedStr)) { return Number.parseInt(trimmedStr, 16); } else { const match = numRegex.exec(trimmedStr); if (match) { const sign2 = match[1]; const leadingZeros = match[2]; let numTrimmedByZeros = trimZeros(match[3]); const eNotation = match[4] || match[6]; if (!options.leadingZeros && leadingZeros.length > 0 && sign2 && trimmedStr[2] !== ".") return str3; else if (!options.leadingZeros && leadingZeros.length > 0 && !sign2 && trimmedStr[1] !== ".") return str3; else { const num = Number(trimmedStr); const numStr = "" + num; if (numStr.search(/[eE]/) !== -1) { if (options.eNotation) return num; else return str3; } else if (eNotation) { if (options.eNotation) return num; else return str3; } else if (trimmedStr.indexOf(".") !== -1) { if (numStr === "0" && numTrimmedByZeros === "") return num; else if (numStr === numTrimmedByZeros) return num; else if (sign2 && numStr === "-" + numTrimmedByZeros) return num; else return str3; } if (leadingZeros) { if (numTrimmedByZeros === numStr) return num; else if (sign2 + numTrimmedByZeros === numStr) return num; else return str3; } if (trimmedStr === numStr) return num; else if (trimmedStr === sign2 + numStr) return num; return str3; } } else { return str3; } } } function trimZeros(numStr) { if (numStr && numStr.indexOf(".") !== -1) { numStr = numStr.replace(/0+$/, ""); if (numStr === ".") numStr = "0"; else if (numStr[0] === ".") numStr = "0" + numStr; else if (numStr[numStr.length - 1] === ".") numStr = numStr.substr(0, numStr.length - 1); return numStr; } return numStr; } module.exports = toNumber2; } }); // ../../node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js var require_OrderedObjParser = __commonJS({ "../../node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(exports, module) { "use strict"; var util = require_util(); var xmlNode = require_xmlNode(); var readDocType = require_DocTypeReader(); var toNumber2 = require_strnum(); var OrderedObjParser = class { constructor(options) { this.options = options; this.currentNode = null; this.tagsNodeStack = []; this.docTypeEntities = {}; this.lastEntities = { "apos": { regex: /&(apos|#39|#x27);/g, val: "'" }, "gt": { regex: /&(gt|#62|#x3E);/g, val: ">" }, "lt": { regex: /&(lt|#60|#x3C);/g, val: "<" }, "quot": { regex: /&(quot|#34|#x22);/g, val: '"' } }; this.ampEntity = { regex: /&(amp|#38|#x26);/g, val: "&" }; this.htmlEntities = { "space": { regex: /&(nbsp|#160);/g, val: " " }, "cent": { regex: /&(cent|#162);/g, val: "\xA2" }, "pound": { regex: /&(pound|#163);/g, val: "\xA3" }, "yen": { regex: /&(yen|#165);/g, val: "\xA5" }, "euro": { regex: /&(euro|#8364);/g, val: "\u20AC" }, "copyright": { regex: /&(copy|#169);/g, val: "\xA9" }, "reg": { regex: /&(reg|#174);/g, val: "\xAE" }, "inr": { regex: /&(inr|#8377);/g, val: "\u20B9" }, "num_dec": { regex: /&#([0-9]{1,7});/g, val: (_, str3) => String.fromCharCode(Number.parseInt(str3, 10)) }, "num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val: (_, str3) => String.fromCharCode(Number.parseInt(str3, 16)) } }; this.addExternalEntities = addExternalEntities; this.parseXml = parseXml; this.parseTextData = parseTextData; this.resolveNameSpace = resolveNameSpace; this.buildAttributesMap = buildAttributesMap; this.isItStopNode = isItStopNode; this.replaceEntitiesValue = replaceEntitiesValue; this.readStopNodeData = readStopNodeData; this.saveTextToParentTag = saveTextToParentTag; this.addChild = addChild; } }; function addExternalEntities(externalEntities) { const entKeys = Object.keys(externalEntities); for (let i3 = 0; i3 < entKeys.length; i3++) { const ent = entKeys[i3]; this.lastEntities[ent] = { regex: new RegExp("&" + ent + ";", "g"), val: externalEntities[ent] }; } } function parseTextData(val2, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) { if (val2 !== void 0) { if (this.options.trimValues && !dontTrim) { val2 = val2.trim(); } if (val2.length > 0) { if (!escapeEntities) val2 = this.replaceEntitiesValue(val2); const newval = this.options.tagValueProcessor(tagName, val2, jPath, hasAttributes, isLeafNode); if (newval === null || newval === void 0) { return val2; } else if (typeof newval !== typeof val2 || newval !== val2) { return newval; } else if (this.options.trimValues) { return parseValue(val2, this.options.parseTagValue, this.options.numberParseOptions); } else { const trimmedVal = val2.trim(); if (trimmedVal === val2) { return parseValue(val2, this.options.parseTagValue, this.options.numberParseOptions); } else { return val2; } } } } } function resolveNameSpace(tagname) { if (this.options.removeNSPrefix) { const tags = tagname.split(":"); const prefix = tagname.charAt(0) === "/" ? "/" : ""; if (tags[0] === "xmlns") { return ""; } if (tags.length === 2) { tagname = prefix + tags[1]; } } return tagname; } var attrsRegx = new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`, "gm"); function buildAttributesMap(attrStr, jPath, tagName) { if (!this.options.ignoreAttributes && typeof attrStr === "string") { const matches3 = util.getAllMatches(attrStr, attrsRegx); const len2 = matches3.length; const attrs = {}; for (let i3 = 0; i3 < len2; i3++) { const attrName = this.resolveNameSpace(matches3[i3][1]); let oldVal = matches3[i3][4]; let aName = this.options.attributeNamePrefix + attrName; if (attrName.length) { if (this.options.transformAttributeName) { aName = this.options.transformAttributeName(aName); } if (aName === "__proto__") aName = "#__proto__"; if (oldVal !== void 0) { if (this.options.trimValues) { oldVal = oldVal.trim(); } oldVal = this.replaceEntitiesValue(oldVal); const newVal = this.options.attributeValueProcessor(attrName, oldVal, jPath); if (newVal === null || newVal === void 0) { attrs[aName] = oldVal; } else if (typeof newVal !== typeof oldVal || newVal !== oldVal) { attrs[aName] = newVal; } else { attrs[aName] = parseValue( oldVal, this.options.parseAttributeValue, this.options.numberParseOptions ); } } else if (this.options.allowBooleanAttributes) { attrs[aName] = true; } } } if (!Object.keys(attrs).length) { return; } if (this.options.attributesGroupName) { const attrCollection = {}; attrCollection[this.options.attributesGroupName] = attrs; return attrCollection; } return attrs; } } var parseXml = function(xmlData) { xmlData = xmlData.replace(/\r\n?/g, "\n"); const xmlObj = new xmlNode("!xml"); let currentNode = xmlObj; let textData = ""; let jPath = ""; for (let i3 = 0; i3 < xmlData.length; i3++) { const ch = xmlData[i3]; if (ch === "<") { if (xmlData[i3 + 1] === "/") { const closeIndex = findClosingIndex(xmlData, ">", i3, "Closing Tag is not closed."); let tagName = xmlData.substring(i3 + 2, closeIndex).trim(); if (this.options.removeNSPrefix) { const colonIndex = tagName.indexOf(":"); if (colonIndex !== -1) { tagName = tagName.substr(colonIndex + 1); } } if (this.options.transformTagName) { tagName = this.options.transformTagName(tagName); } if (currentNode) { textData = this.saveTextToParentTag(textData, currentNode, jPath); } const lastTagName = jPath.substring(jPath.lastIndexOf(".") + 1); if (tagName && this.options.unpairedTags.indexOf(tagName) !== -1) { throw new Error(`Unpaired tag can not be used as closing tag: `); } let propIndex = 0; if (lastTagName && this.options.unpairedTags.indexOf(lastTagName) !== -1) { propIndex = jPath.lastIndexOf(".", jPath.lastIndexOf(".") - 1); this.tagsNodeStack.pop(); } else { propIndex = jPath.lastIndexOf("."); } jPath = jPath.substring(0, propIndex); currentNode = this.tagsNodeStack.pop(); textData = ""; i3 = closeIndex; } else if (xmlData[i3 + 1] === "?") { let tagData = readTagExp(xmlData, i3, false, "?>"); if (!tagData) throw new Error("Pi Tag is not closed."); textData = this.saveTextToParentTag(textData, currentNode, jPath); if (this.options.ignoreDeclaration && tagData.tagName === "?xml" || this.options.ignorePiTags) { } else { const childNode = new xmlNode(tagData.tagName); childNode.add(this.options.textNodeName, ""); if (tagData.tagName !== tagData.tagExp && tagData.attrExpPresent) { childNode[":@"] = this.buildAttributesMap(tagData.tagExp, jPath, tagData.tagName); } this.addChild(currentNode, childNode, jPath); } i3 = tagData.closeIndex + 1; } else if (xmlData.substr(i3 + 1, 3) === "!--") { const endIndex = findClosingIndex(xmlData, "-->", i3 + 4, "Comment is not closed."); if (this.options.commentPropName) { const comment = xmlData.substring(i3 + 4, endIndex - 2); textData = this.saveTextToParentTag(textData, currentNode, jPath); currentNode.add(this.options.commentPropName, [{ [this.options.textNodeName]: comment }]); } i3 = endIndex; } else if (xmlData.substr(i3 + 1, 2) === "!D") { const result = readDocType(xmlData, i3); this.docTypeEntities = result.entities; i3 = result.i; } else if (xmlData.substr(i3 + 1, 2) === "![") { const closeIndex = findClosingIndex(xmlData, "]]>", i3, "CDATA is not closed.") - 2; const tagExp = xmlData.substring(i3 + 9, closeIndex); textData = this.saveTextToParentTag(textData, currentNode, jPath); let val2 = this.parseTextData(tagExp, currentNode.tagname, jPath, true, false, true, true); if (val2 == void 0) val2 = ""; if (this.options.cdataPropName) { currentNode.add(this.options.cdataPropName, [{ [this.options.textNodeName]: tagExp }]); } else { currentNode.add(this.options.textNodeName, val2); } i3 = closeIndex + 2; } else { let result = readTagExp(xmlData, i3, this.options.removeNSPrefix); let tagName = result.tagName; const rawTagName = result.rawTagName; let tagExp = result.tagExp; let attrExpPresent = result.attrExpPresent; let closeIndex = result.closeIndex; if (this.options.transformTagName) { tagName = this.options.transformTagName(tagName); } if (currentNode && textData) { if (currentNode.tagname !== "!xml") { textData = this.saveTextToParentTag(textData, currentNode, jPath, false); } } const lastTag = currentNode; if (lastTag && this.options.unpairedTags.indexOf(lastTag.tagname) !== -1) { currentNode = this.tagsNodeStack.pop(); jPath = jPath.substring(0, jPath.lastIndexOf(".")); } if (tagName !== xmlObj.tagname) { jPath += jPath ? "." + tagName : tagName; } if (this.isItStopNode(this.options.stopNodes, jPath, tagName)) { let tagContent = ""; if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1) { i3 = result.closeIndex; } else if (this.options.unpairedTags.indexOf(tagName) !== -1) { i3 = result.closeIndex; } else { const result2 = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1); if (!result2) throw new Error(`Unexpected end of ${rawTagName}`); i3 = result2.i; tagContent = result2.tagContent; } const childNode = new xmlNode(tagName); if (tagName !== tagExp && attrExpPresent) { childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); } if (tagContent) { tagContent = this.parseTextData(tagContent, tagName, jPath, true, attrExpPresent, true, true); } jPath = jPath.substr(0, jPath.lastIndexOf(".")); childNode.add(this.options.textNodeName, tagContent); this.addChild(currentNode, childNode, jPath); } else { if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1) { if (tagName[tagName.length - 1] === "/") { tagName = tagName.substr(0, tagName.length - 1); jPath = jPath.substr(0, jPath.length - 1); tagExp = tagName; } else { tagExp = tagExp.substr(0, tagExp.length - 1); } if (this.options.transformTagName) { tagName = this.options.transformTagName(tagName); } const childNode = new xmlNode(tagName); if (tagName !== tagExp && attrExpPresent) { childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); } this.addChild(currentNode, childNode, jPath); jPath = jPath.substr(0, jPath.lastIndexOf(".")); } else { const childNode = new xmlNode(tagName); this.tagsNodeStack.push(currentNode); if (tagName !== tagExp && attrExpPresent) { childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); } this.addChild(currentNode, childNode, jPath); currentNode = childNode; } textData = ""; i3 = closeIndex; } } } else { textData += xmlData[i3]; } } return xmlObj.child; }; function addChild(currentNode, childNode, jPath) { const result = this.options.updateTag(childNode.tagname, jPath, childNode[":@"]); if (result === false) { } else if (typeof result === "string") { childNode.tagname = result; currentNode.addChild(childNode); } else { currentNode.addChild(childNode); } } var replaceEntitiesValue = function(val2) { if (this.options.processEntities) { for (let entityName2 in this.docTypeEntities) { const entity = this.docTypeEntities[entityName2]; val2 = val2.replace(entity.regx, entity.val); } for (let entityName2 in this.lastEntities) { const entity = this.lastEntities[entityName2]; val2 = val2.replace(entity.regex, entity.val); } if (this.options.htmlEntities) { for (let entityName2 in this.htmlEntities) { const entity = this.htmlEntities[entityName2]; val2 = val2.replace(entity.regex, entity.val); } } val2 = val2.replace(this.ampEntity.regex, this.ampEntity.val); } return val2; }; function saveTextToParentTag(textData, currentNode, jPath, isLeafNode) { if (textData) { if (isLeafNode === void 0) isLeafNode = Object.keys(currentNode.child).length === 0; textData = this.parseTextData( textData, currentNode.tagname, jPath, false, currentNode[":@"] ? Object.keys(currentNode[":@"]).length !== 0 : false, isLeafNode ); if (textData !== void 0 && textData !== "") currentNode.add(this.options.textNodeName, textData); textData = ""; } return textData; } function isItStopNode(stopNodes, jPath, currentTagName) { const allNodesExp = "*." + currentTagName; for (const stopNodePath in stopNodes) { const stopNodeExp = stopNodes[stopNodePath]; if (allNodesExp === stopNodeExp || jPath === stopNodeExp) return true; } return false; } function tagExpWithClosingIndex(xmlData, i3, closingChar = ">") { let attrBoundary; let tagExp = ""; for (let index = i3; index < xmlData.length; index++) { let ch = xmlData[index]; if (attrBoundary) { if (ch === attrBoundary) attrBoundary = ""; } else if (ch === '"' || ch === "'") { attrBoundary = ch; } else if (ch === closingChar[0]) { if (closingChar[1]) { if (xmlData[index + 1] === closingChar[1]) { return { data: tagExp, index }; } } else { return { data: tagExp, index }; } } else if (ch === " ") { ch = " "; } tagExp += ch; } } function findClosingIndex(xmlData, str3, i3, errMsg) { const closingIndex = xmlData.indexOf(str3, i3); if (closingIndex === -1) { throw new Error(errMsg); } else { return closingIndex + str3.length - 1; } } function readTagExp(xmlData, i3, removeNSPrefix, closingChar = ">") { const result = tagExpWithClosingIndex(xmlData, i3 + 1, closingChar); if (!result) return; let tagExp = result.data; const closeIndex = result.index; const separatorIndex = tagExp.search(/\s/); let tagName = tagExp; let attrExpPresent = true; if (separatorIndex !== -1) { tagName = tagExp.substring(0, separatorIndex); tagExp = tagExp.substring(separatorIndex + 1).trimStart(); } const rawTagName = tagName; if (removeNSPrefix) { const colonIndex = tagName.indexOf(":"); if (colonIndex !== -1) { tagName = tagName.substr(colonIndex + 1); attrExpPresent = tagName !== result.data.substr(colonIndex + 1); } } return { tagName, tagExp, closeIndex, attrExpPresent, rawTagName }; } function readStopNodeData(xmlData, tagName, i3) { const startIndex = i3; let openTagCount = 1; for (; i3 < xmlData.length; i3++) { if (xmlData[i3] === "<") { if (xmlData[i3 + 1] === "/") { const closeIndex = findClosingIndex(xmlData, ">", i3, `${tagName} is not closed`); let closeTagName = xmlData.substring(i3 + 2, closeIndex).trim(); if (closeTagName === tagName) { openTagCount--; if (openTagCount === 0) { return { tagContent: xmlData.substring(startIndex, i3), i: closeIndex }; } } i3 = closeIndex; } else if (xmlData[i3 + 1] === "?") { const closeIndex = findClosingIndex(xmlData, "?>", i3 + 1, "StopNode is not closed."); i3 = closeIndex; } else if (xmlData.substr(i3 + 1, 3) === "!--") { const closeIndex = findClosingIndex(xmlData, "-->", i3 + 3, "StopNode is not closed."); i3 = closeIndex; } else if (xmlData.substr(i3 + 1, 2) === "![") { const closeIndex = findClosingIndex(xmlData, "]]>", i3, "StopNode is not closed.") - 2; i3 = closeIndex; } else { const tagData = readTagExp(xmlData, i3, ">"); if (tagData) { const openTagName = tagData && tagData.tagName; if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length - 1] !== "/") { openTagCount++; } i3 = tagData.closeIndex; } } } } } function parseValue(val2, shouldParse, options) { if (shouldParse && typeof val2 === "string") { const newval = val2.trim(); if (newval === "true") return true; else if (newval === "false") return false; else return toNumber2(val2, options); } else { if (util.isExist(val2)) { return val2; } else { return ""; } } } module.exports = OrderedObjParser; } }); // ../../node_modules/fast-xml-parser/src/xmlparser/node2json.js var require_node2json = __commonJS({ "../../node_modules/fast-xml-parser/src/xmlparser/node2json.js"(exports) { "use strict"; function prettify(node, options) { return compress(node, options); } function compress(arr, options, jPath) { let text; const compressedObj = {}; for (let i3 = 0; i3 < arr.length; i3++) { const tagObj = arr[i3]; const property = propName(tagObj); let newJpath = ""; if (jPath === void 0) newJpath = property; else newJpath = jPath + "." + property; if (property === options.textNodeName) { if (text === void 0) text = tagObj[property]; else text += "" + tagObj[property]; } else if (property === void 0) { continue; } else if (tagObj[property]) { let val2 = compress(tagObj[property], options, newJpath); const isLeaf = isLeafTag(val2, options); if (tagObj[":@"]) { assignAttributes(val2, tagObj[":@"], newJpath, options); } else if (Object.keys(val2).length === 1 && val2[options.textNodeName] !== void 0 && !options.alwaysCreateTextNode) { val2 = val2[options.textNodeName]; } else if (Object.keys(val2).length === 0) { if (options.alwaysCreateTextNode) val2[options.textNodeName] = ""; else val2 = ""; } if (compressedObj[property] !== void 0 && compressedObj.hasOwnProperty(property)) { if (!Array.isArray(compressedObj[property])) { compressedObj[property] = [compressedObj[property]]; } compressedObj[property].push(val2); } else { if (options.isArray(property, newJpath, isLeaf)) { compressedObj[property] = [val2]; } else { compressedObj[property] = val2; } } } } if (typeof text === "string") { if (text.length > 0) compressedObj[options.textNodeName] = text; } else if (text !== void 0) compressedObj[options.textNodeName] = text; return compressedObj; } function propName(obj) { const keys = Object.keys(obj); for (let i3 = 0; i3 < keys.length; i3++) { const key = keys[i3]; if (key !== ":@") return key; } } function assignAttributes(obj, attrMap, jpath, options) { if (attrMap) { const keys = Object.keys(attrMap); const len2 = keys.length; for (let i3 = 0; i3 < len2; i3++) { const atrrName = keys[i3]; if (options.isArray(atrrName, jpath + "." + atrrName, true, true)) { obj[atrrName] = [attrMap[atrrName]]; } else { obj[atrrName] = attrMap[atrrName]; } } } } function isLeafTag(obj, options) { const { textNodeName } = options; const propCount = Object.keys(obj).length; if (propCount === 0) { return true; } if (propCount === 1 && (obj[textNodeName] || typeof obj[textNodeName] === "boolean" || obj[textNodeName] === 0)) { return true; } return false; } exports.prettify = prettify; } }); // ../../node_modules/fast-xml-parser/src/xmlparser/XMLParser.js var require_XMLParser = __commonJS({ "../../node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(exports, module) { var { buildOptions } = require_OptionsBuilder(); var OrderedObjParser = require_OrderedObjParser(); var { prettify } = require_node2json(); var validator = require_validator(); var XMLParser = class { constructor(options) { this.externalEntities = {}; this.options = buildOptions(options); } parse(xmlData, validationOption) { if (typeof xmlData === "string") { } else if (xmlData.toString) { xmlData = xmlData.toString(); } else { throw new Error("XML data is accepted in String or Bytes[] form."); } if (validationOption) { if (validationOption === true) validationOption = {}; const result = validator.validate(xmlData, validationOption); if (result !== true) { throw Error(`${result.err.msg}:${result.err.line}:${result.err.col}`); } } const orderedObjParser = new OrderedObjParser(this.options); orderedObjParser.addExternalEntities(this.externalEntities); const orderedResult = orderedObjParser.parseXml(xmlData); if (this.options.preserveOrder || orderedResult === void 0) return orderedResult; else return prettify(orderedResult, this.options); } addEntity(key, value) { if (value.indexOf("&") !== -1) { throw new Error("Entity value can't have '&'"); } else if (key.indexOf("&") !== -1 || key.indexOf(";") !== -1) { throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for ' '"); } else if (value === "&") { throw new Error("An entity with value '&' is not permitted"); } else { this.externalEntities[key] = value; } } }; module.exports = XMLParser; } }); // ../../node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js var require_orderedJs2Xml = __commonJS({ "../../node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js"(exports, module) { var EOL = "\n"; function toXml(jArray, options) { let indentation = ""; if (options.format && options.indentBy.length > 0) { indentation = EOL; } return arrToStr(jArray, options, "", indentation); } function arrToStr(arr, options, jPath, indentation) { let xmlStr = ""; let isPreviousElementTag = false; for (let i3 = 0; i3 < arr.length; i3++) { const tagObj = arr[i3]; const tagName = propName(tagObj); if (tagName === void 0) continue; let newJPath = ""; if (jPath.length === 0) newJPath = tagName; else newJPath = `${jPath}.${tagName}`; if (tagName === options.textNodeName) { let tagText = tagObj[tagName]; if (!isStopNode(newJPath, options)) { tagText = options.tagValueProcessor(tagName, tagText); tagText = replaceEntitiesValue(tagText, options); } if (isPreviousElementTag) { xmlStr += indentation; } xmlStr += tagText; isPreviousElementTag = false; continue; } else if (tagName === options.cdataPropName) { if (isPreviousElementTag) { xmlStr += indentation; } xmlStr += ``; isPreviousElementTag = false; continue; } else if (tagName === options.commentPropName) { xmlStr += indentation + ``; isPreviousElementTag = true; continue; } else if (tagName[0] === "?") { const attStr2 = attr_to_str(tagObj[":@"], options); const tempInd = tagName === "?xml" ? "" : indentation; let piTextNodeName = tagObj[tagName][0][options.textNodeName]; piTextNodeName = piTextNodeName.length !== 0 ? " " + piTextNodeName : ""; xmlStr += tempInd + `<${tagName}${piTextNodeName}${attStr2}?>`; isPreviousElementTag = true; continue; } let newIdentation = indentation; if (newIdentation !== "") { newIdentation += options.indentBy; } const attStr = attr_to_str(tagObj[":@"], options); const tagStart = indentation + `<${tagName}${attStr}`; const tagValue = arrToStr(tagObj[tagName], options, newJPath, newIdentation); if (options.unpairedTags.indexOf(tagName) !== -1) { if (options.suppressUnpairedNode) xmlStr += tagStart + ">"; else xmlStr += tagStart + "/>"; } else if ((!tagValue || tagValue.length === 0) && options.suppressEmptyNode) { xmlStr += tagStart + "/>"; } else if (tagValue && tagValue.endsWith(">")) { xmlStr += tagStart + `>${tagValue}${indentation}`; } else { xmlStr += tagStart + ">"; if (tagValue && indentation !== "" && (tagValue.includes("/>") || tagValue.includes("`; } isPreviousElementTag = true; } return xmlStr; } function propName(obj) { const keys = Object.keys(obj); for (let i3 = 0; i3 < keys.length; i3++) { const key = keys[i3]; if (!obj.hasOwnProperty(key)) continue; if (key !== ":@") return key; } } function attr_to_str(attrMap, options) { let attrStr = ""; if (attrMap && !options.ignoreAttributes) { for (let attr in attrMap) { if (!attrMap.hasOwnProperty(attr)) continue; let attrVal = options.attributeValueProcessor(attr, attrMap[attr]); attrVal = replaceEntitiesValue(attrVal, options); if (attrVal === true && options.suppressBooleanAttributes) { attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`; } else { attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}="${attrVal}"`; } } } return attrStr; } function isStopNode(jPath, options) { jPath = jPath.substr(0, jPath.length - options.textNodeName.length - 1); let tagName = jPath.substr(jPath.lastIndexOf(".") + 1); for (let index in options.stopNodes) { if (options.stopNodes[index] === jPath || options.stopNodes[index] === "*." + tagName) return true; } return false; } function replaceEntitiesValue(textValue, options) { if (textValue && textValue.length > 0 && options.processEntities) { for (let i3 = 0; i3 < options.entities.length; i3++) { const entity = options.entities[i3]; textValue = textValue.replace(entity.regex, entity.val); } } return textValue; } module.exports = toXml; } }); // ../../node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js var require_json2xml = __commonJS({ "../../node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js"(exports, module) { "use strict"; var buildFromOrderedJs = require_orderedJs2Xml(); var defaultOptions = { attributeNamePrefix: "@_", attributesGroupName: false, textNodeName: "#text", ignoreAttributes: true, cdataPropName: false, format: false, indentBy: " ", suppressEmptyNode: false, suppressUnpairedNode: true, suppressBooleanAttributes: true, tagValueProcessor: function(key, a2) { return a2; }, attributeValueProcessor: function(attrName, a2) { return a2; }, preserveOrder: false, commentPropName: false, unpairedTags: [], entities: [ { regex: new RegExp("&", "g"), val: "&" }, { regex: new RegExp(">", "g"), val: ">" }, { regex: new RegExp("<", "g"), val: "<" }, { regex: new RegExp("'", "g"), val: "'" }, { regex: new RegExp('"', "g"), val: """ } ], processEntities: true, stopNodes: [], oneListGroup: false }; function Builder(options) { this.options = Object.assign({}, defaultOptions, options); if (this.options.ignoreAttributes || this.options.attributesGroupName) { this.isAttribute = function() { return false; }; } else { this.attrPrefixLen = this.options.attributeNamePrefix.length; this.isAttribute = isAttribute; } this.processTextOrObjNode = processTextOrObjNode; if (this.options.format) { this.indentate = indentate; this.tagEndChar = ">\n"; this.newLine = "\n"; } else { this.indentate = function() { return ""; }; this.tagEndChar = ">"; this.newLine = ""; } } Builder.prototype.build = function(jObj) { if (this.options.preserveOrder) { return buildFromOrderedJs(jObj, this.options); } else { if (Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1) { jObj = { [this.options.arrayNodeName]: jObj }; } return this.j2x(jObj, 0).val; } }; Builder.prototype.j2x = function(jObj, level) { let attrStr = ""; let val2 = ""; for (let key in jObj) { if (!Object.prototype.hasOwnProperty.call(jObj, key)) continue; if (typeof jObj[key] === "undefined") { if (this.isAttribute(key)) { val2 += ""; } } else if (jObj[key] === null) { if (this.isAttribute(key)) { val2 += ""; } else if (key[0] === "?") { val2 += this.indentate(level) + "<" + key + "?" + this.tagEndChar; } else { val2 += this.indentate(level) + "<" + key + "/" + this.tagEndChar; } } else if (jObj[key] instanceof Date) { val2 += this.buildTextValNode(jObj[key], key, "", level); } else if (typeof jObj[key] !== "object") { const attr = this.isAttribute(key); if (attr) { attrStr += this.buildAttrPairStr(attr, "" + jObj[key]); } else { if (key === this.options.textNodeName) { let newval = this.options.tagValueProcessor(key, "" + jObj[key]); val2 += this.replaceEntitiesValue(newval); } else { val2 += this.buildTextValNode(jObj[key], key, "", level); } } } else if (Array.isArray(jObj[key])) { const arrLen = jObj[key].length; let listTagVal = ""; for (let j = 0; j < arrLen; j++) { const item = jObj[key][j]; if (typeof item === "undefined") { } else if (item === null) { if (key[0] === "?") val2 += this.indentate(level) + "<" + key + "?" + this.tagEndChar; else val2 += this.indentate(level) + "<" + key + "/" + this.tagEndChar; } else if (typeof item === "object") { if (this.options.oneListGroup) { listTagVal += this.j2x(item, level + 1).val; } else { listTagVal += this.processTextOrObjNode(item, key, level); } } else { listTagVal += this.buildTextValNode(item, key, "", level); } } if (this.options.oneListGroup) { listTagVal = this.buildObjectNode(listTagVal, key, "", level); } val2 += listTagVal; } else { if (this.options.attributesGroupName && key === this.options.attributesGroupName) { const Ks = Object.keys(jObj[key]); const L = Ks.length; for (let j = 0; j < L; j++) { attrStr += this.buildAttrPairStr(Ks[j], "" + jObj[key][Ks[j]]); } } else { val2 += this.processTextOrObjNode(jObj[key], key, level); } } } return { attrStr, val: val2 }; }; Builder.prototype.buildAttrPairStr = function(attrName, val2) { val2 = this.options.attributeValueProcessor(attrName, "" + val2); val2 = this.replaceEntitiesValue(val2); if (this.options.suppressBooleanAttributes && val2 === "true") { return " " + attrName; } else return " " + attrName + '="' + val2 + '"'; }; function processTextOrObjNode(object, key, level) { const result = this.j2x(object, level + 1); if (object[this.options.textNodeName] !== void 0 && Object.keys(object).length === 1) { return this.buildTextValNode(object[this.options.textNodeName], key, result.attrStr, level); } else { return this.buildObjectNode(result.val, key, result.attrStr, level); } } Builder.prototype.buildObjectNode = function(val2, key, attrStr, level) { if (val2 === "") { if (key[0] === "?") return this.indentate(level) + "<" + key + attrStr + "?" + this.tagEndChar; else { return this.indentate(level) + "<" + key + attrStr + this.closeTag(key) + this.tagEndChar; } } else { let tagEndExp = "" + val2 + tagEndExp; } else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) { return this.indentate(level) + `` + this.newLine; } else { return this.indentate(level) + "<" + key + attrStr + piClosingChar + this.tagEndChar + val2 + this.indentate(level) + tagEndExp; } } }; Builder.prototype.closeTag = function(key) { let closeTag = ""; if (this.options.unpairedTags.indexOf(key) !== -1) { if (!this.options.suppressUnpairedNode) closeTag = "/"; } else if (this.options.suppressEmptyNode) { closeTag = "/"; } else { closeTag = `>` + this.newLine; } else if (this.options.commentPropName !== false && key === this.options.commentPropName) { return this.indentate(level) + `` + this.newLine; } else if (key[0] === "?") { return this.indentate(level) + "<" + key + attrStr + "?" + this.tagEndChar; } else { let textValue = this.options.tagValueProcessor(key, val2); textValue = this.replaceEntitiesValue(textValue); if (textValue === "") { return this.indentate(level) + "<" + key + attrStr + this.closeTag(key) + this.tagEndChar; } else { return this.indentate(level) + "<" + key + attrStr + ">" + textValue + " 0 && this.options.processEntities) { for (let i3 = 0; i3 < this.options.entities.length; i3++) { const entity = this.options.entities[i3]; textValue = textValue.replace(entity.regex, entity.val); } } return textValue; }; function indentate(level) { return this.options.indentBy.repeat(level); } function isAttribute(name12) { if (name12.startsWith(this.options.attributeNamePrefix) && name12 !== this.options.textNodeName) { return name12.substr(this.attrPrefixLen); } else { return false; } } module.exports = Builder; } }); // ../../node_modules/fast-xml-parser/src/fxp.js var require_fxp = __commonJS({ "../../node_modules/fast-xml-parser/src/fxp.js"(exports, module) { "use strict"; var validator = require_validator(); var XMLParser = require_XMLParser(); var XMLBuilder = require_json2xml(); module.exports = { XMLParser, XMLValidator: validator, XMLBuilder }; } }); // ../../node_modules/long/dist/long.js var require_long = __commonJS({ "../../node_modules/long/dist/long.js"(exports, module) { (function(global2, factory) { if (typeof define === "function" && define["amd"]) define([], factory); else if (typeof __require === "function" && typeof module === "object" && module && module["exports"]) module["exports"] = factory(); else (global2["dcodeIO"] = global2["dcodeIO"] || {})["Long"] = factory(); })(exports, function() { "use strict"; function Long4(low, high, unsigned) { this.low = low | 0; this.high = high | 0; this.unsigned = !!unsigned; } Long4.prototype.__isLong__; Object.defineProperty(Long4.prototype, "__isLong__", { value: true, enumerable: false, configurable: false }); function isLong2(obj) { return (obj && obj["__isLong__"]) === true; } Long4.isLong = isLong2; var INT_CACHE2 = {}; var UINT_CACHE2 = {}; function fromInt2(value, unsigned) { var obj, cachedObj, cache2; if (unsigned) { value >>>= 0; if (cache2 = 0 <= value && value < 256) { cachedObj = UINT_CACHE2[value]; if (cachedObj) return cachedObj; } obj = fromBits2(value, (value | 0) < 0 ? -1 : 0, true); if (cache2) UINT_CACHE2[value] = obj; return obj; } else { value |= 0; if (cache2 = -128 <= value && value < 128) { cachedObj = INT_CACHE2[value]; if (cachedObj) return cachedObj; } obj = fromBits2(value, value < 0 ? -1 : 0, false); if (cache2) INT_CACHE2[value] = obj; return obj; } } Long4.fromInt = fromInt2; function fromNumber2(value, unsigned) { if (isNaN(value) || !isFinite(value)) return unsigned ? UZERO2 : ZERO5; if (unsigned) { if (value < 0) return UZERO2; if (value >= TWO_PWR_64_DBL2) return MAX_UNSIGNED_VALUE2; } else { if (value <= -TWO_PWR_63_DBL2) return MIN_VALUE2; if (value + 1 >= TWO_PWR_63_DBL2) return MAX_VALUE2; } if (value < 0) return fromNumber2(-value, unsigned).neg(); return fromBits2(value % TWO_PWR_32_DBL2 | 0, value / TWO_PWR_32_DBL2 | 0, unsigned); } Long4.fromNumber = fromNumber2; function fromBits2(lowBits, highBits, unsigned) { return new Long4(lowBits, highBits, unsigned); } Long4.fromBits = fromBits2; var pow_dbl2 = Math.pow; function fromString2(str3, unsigned, radix) { if (str3.length === 0) throw Error("empty string"); if (str3 === "NaN" || str3 === "Infinity" || str3 === "+Infinity" || str3 === "-Infinity") return ZERO5; if (typeof unsigned === "number") { radix = unsigned, unsigned = false; } else { unsigned = !!unsigned; } radix = radix || 10; if (radix < 2 || 36 < radix) throw RangeError("radix"); var p2; if ((p2 = str3.indexOf("-")) > 0) throw Error("interior hyphen"); else if (p2 === 0) { return fromString2(str3.substring(1), unsigned, radix).neg(); } var radixToPower = fromNumber2(pow_dbl2(radix, 8)); var result = ZERO5; for (var i3 = 0; i3 < str3.length; i3 += 8) { var size = Math.min(8, str3.length - i3), value = parseInt(str3.substring(i3, i3 + size), radix); if (size < 8) { var power = fromNumber2(pow_dbl2(radix, size)); result = result.mul(power).add(fromNumber2(value)); } else { result = result.mul(radixToPower); result = result.add(fromNumber2(value)); } } result.unsigned = unsigned; return result; } Long4.fromString = fromString2; function fromValue2(val2) { if (val2 instanceof Long4) return val2; if (typeof val2 === "number") return fromNumber2(val2); if (typeof val2 === "string") return fromString2(val2); return fromBits2(val2.low, val2.high, val2.unsigned); } Long4.fromValue = fromValue2; var TWO_PWR_16_DBL2 = 1 << 16; var TWO_PWR_24_DBL2 = 1 << 24; var TWO_PWR_32_DBL2 = TWO_PWR_16_DBL2 * TWO_PWR_16_DBL2; var TWO_PWR_64_DBL2 = TWO_PWR_32_DBL2 * TWO_PWR_32_DBL2; var TWO_PWR_63_DBL2 = TWO_PWR_64_DBL2 / 2; var TWO_PWR_242 = fromInt2(TWO_PWR_24_DBL2); var ZERO5 = fromInt2(0); Long4.ZERO = ZERO5; var UZERO2 = fromInt2(0, true); Long4.UZERO = UZERO2; var ONE2 = fromInt2(1); Long4.ONE = ONE2; var UONE2 = fromInt2(1, true); Long4.UONE = UONE2; var NEG_ONE2 = fromInt2(-1); Long4.NEG_ONE = NEG_ONE2; var MAX_VALUE2 = fromBits2(4294967295 | 0, 2147483647 | 0, false); Long4.MAX_VALUE = MAX_VALUE2; var MAX_UNSIGNED_VALUE2 = fromBits2(4294967295 | 0, 4294967295 | 0, true); Long4.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE2; var MIN_VALUE2 = fromBits2(0, 2147483648 | 0, false); Long4.MIN_VALUE = MIN_VALUE2; var LongPrototype2 = Long4.prototype; LongPrototype2.toInt = function toInt2() { return this.unsigned ? this.low >>> 0 : this.low; }; LongPrototype2.toNumber = function toNumber2() { if (this.unsigned) return (this.high >>> 0) * TWO_PWR_32_DBL2 + (this.low >>> 0); return this.high * TWO_PWR_32_DBL2 + (this.low >>> 0); }; LongPrototype2.toString = function toString2(radix) { radix = radix || 10; if (radix < 2 || 36 < radix) throw RangeError("radix"); if (this.isZero()) return "0"; if (this.isNegative()) { if (this.eq(MIN_VALUE2)) { var radixLong = fromNumber2(radix), div2 = this.div(radixLong), rem1 = div2.mul(radixLong).sub(this); return div2.toString(radix) + rem1.toInt().toString(radix); } else return "-" + this.neg().toString(radix); } var radixToPower = fromNumber2(pow_dbl2(radix, 6), this.unsigned), rem = this; var result = ""; while (true) { var remDiv = rem.div(radixToPower), intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0, digits = intval.toString(radix); rem = remDiv; if (rem.isZero()) return digits + result; else { while (digits.length < 6) digits = "0" + digits; result = "" + digits + result; } } }; LongPrototype2.getHighBits = function getHighBits2() { return this.high; }; LongPrototype2.getHighBitsUnsigned = function getHighBitsUnsigned2() { return this.high >>> 0; }; LongPrototype2.getLowBits = function getLowBits2() { return this.low; }; LongPrototype2.getLowBitsUnsigned = function getLowBitsUnsigned2() { return this.low >>> 0; }; LongPrototype2.getNumBitsAbs = function getNumBitsAbs2() { if (this.isNegative()) return this.eq(MIN_VALUE2) ? 64 : this.neg().getNumBitsAbs(); var val2 = this.high != 0 ? this.high : this.low; for (var bit = 31; bit > 0; bit--) if ((val2 & 1 << bit) != 0) break; return this.high != 0 ? bit + 33 : bit + 1; }; LongPrototype2.isZero = function isZero2() { return this.high === 0 && this.low === 0; }; LongPrototype2.isNegative = function isNegative2() { return !this.unsigned && this.high < 0; }; LongPrototype2.isPositive = function isPositive2() { return this.unsigned || this.high >= 0; }; LongPrototype2.isOdd = function isOdd2() { return (this.low & 1) === 1; }; LongPrototype2.isEven = function isEven2() { return (this.low & 1) === 0; }; LongPrototype2.equals = function equals6(other) { if (!isLong2(other)) other = fromValue2(other); if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1) return false; return this.high === other.high && this.low === other.low; }; LongPrototype2.eq = LongPrototype2.equals; LongPrototype2.notEquals = function notEquals2(other) { return !this.eq(other); }; LongPrototype2.neq = LongPrototype2.notEquals; LongPrototype2.lessThan = function lessThan2(other) { return this.comp(other) < 0; }; LongPrototype2.lt = LongPrototype2.lessThan; LongPrototype2.lessThanOrEqual = function lessThanOrEqual2(other) { return this.comp(other) <= 0; }; LongPrototype2.lte = LongPrototype2.lessThanOrEqual; LongPrototype2.greaterThan = function greaterThan2(other) { return this.comp(other) > 0; }; LongPrototype2.gt = LongPrototype2.greaterThan; LongPrototype2.greaterThanOrEqual = function greaterThanOrEqual2(other) { return this.comp(other) >= 0; }; LongPrototype2.gte = LongPrototype2.greaterThanOrEqual; LongPrototype2.compare = function compare2(other) { if (!isLong2(other)) other = fromValue2(other); if (this.eq(other)) return 0; var thisNeg = this.isNegative(), otherNeg = other.isNegative(); if (thisNeg && !otherNeg) return -1; if (!thisNeg && otherNeg) return 1; if (!this.unsigned) return this.sub(other).isNegative() ? -1 : 1; return other.high >>> 0 > this.high >>> 0 || other.high === this.high && other.low >>> 0 > this.low >>> 0 ? -1 : 1; }; LongPrototype2.comp = LongPrototype2.compare; LongPrototype2.negate = function negate3() { if (!this.unsigned && this.eq(MIN_VALUE2)) return MIN_VALUE2; return this.not().add(ONE2); }; LongPrototype2.neg = LongPrototype2.negate; LongPrototype2.add = function add6(addend) { if (!isLong2(addend)) addend = fromValue2(addend); var a48 = this.high >>> 16; var a32 = this.high & 65535; var a16 = this.low >>> 16; var a00 = this.low & 65535; var b48 = addend.high >>> 16; var b32 = addend.high & 65535; var b16 = addend.low >>> 16; var b00 = addend.low & 65535; var c48 = 0, c32 = 0, c16 = 0, c00 = 0; c00 += a00 + b00; c16 += c00 >>> 16; c00 &= 65535; c16 += a16 + b16; c32 += c16 >>> 16; c16 &= 65535; c32 += a32 + b32; c48 += c32 >>> 16; c32 &= 65535; c48 += a48 + b48; c48 &= 65535; return fromBits2(c16 << 16 | c00, c48 << 16 | c32, this.unsigned); }; LongPrototype2.subtract = function subtract4(subtrahend) { if (!isLong2(subtrahend)) subtrahend = fromValue2(subtrahend); return this.add(subtrahend.neg()); }; LongPrototype2.sub = LongPrototype2.subtract; LongPrototype2.multiply = function multiply6(multiplier) { if (this.isZero()) return ZERO5; if (!isLong2(multiplier)) multiplier = fromValue2(multiplier); if (multiplier.isZero()) return ZERO5; if (this.eq(MIN_VALUE2)) return multiplier.isOdd() ? MIN_VALUE2 : ZERO5; if (multiplier.eq(MIN_VALUE2)) return this.isOdd() ? MIN_VALUE2 : ZERO5; if (this.isNegative()) { if (multiplier.isNegative()) return this.neg().mul(multiplier.neg()); else return this.neg().mul(multiplier).neg(); } else if (multiplier.isNegative()) return this.mul(multiplier.neg()).neg(); if (this.lt(TWO_PWR_242) && multiplier.lt(TWO_PWR_242)) return fromNumber2(this.toNumber() * multiplier.toNumber(), this.unsigned); var a48 = this.high >>> 16; var a32 = this.high & 65535; var a16 = this.low >>> 16; var a00 = this.low & 65535; var b48 = multiplier.high >>> 16; var b32 = multiplier.high & 65535; var b16 = multiplier.low >>> 16; var b00 = multiplier.low & 65535; var c48 = 0, c32 = 0, c16 = 0, c00 = 0; c00 += a00 * b00; c16 += c00 >>> 16; c00 &= 65535; c16 += a16 * b00; c32 += c16 >>> 16; c16 &= 65535; c16 += a00 * b16; c32 += c16 >>> 16; c16 &= 65535; c32 += a32 * b00; c48 += c32 >>> 16; c32 &= 65535; c32 += a16 * b16; c48 += c32 >>> 16; c32 &= 65535; c32 += a00 * b32; c48 += c32 >>> 16; c32 &= 65535; c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; c48 &= 65535; return fromBits2(c16 << 16 | c00, c48 << 16 | c32, this.unsigned); }; LongPrototype2.mul = LongPrototype2.multiply; LongPrototype2.divide = function divide3(divisor) { if (!isLong2(divisor)) divisor = fromValue2(divisor); if (divisor.isZero()) throw Error("division by zero"); if (this.isZero()) return this.unsigned ? UZERO2 : ZERO5; var approx, rem, res; if (!this.unsigned) { if (this.eq(MIN_VALUE2)) { if (divisor.eq(ONE2) || divisor.eq(NEG_ONE2)) return MIN_VALUE2; else if (divisor.eq(MIN_VALUE2)) return ONE2; else { var halfThis = this.shr(1); approx = halfThis.div(divisor).shl(1); if (approx.eq(ZERO5)) { return divisor.isNegative() ? ONE2 : NEG_ONE2; } else { rem = this.sub(divisor.mul(approx)); res = approx.add(rem.div(divisor)); return res; } } } else if (divisor.eq(MIN_VALUE2)) return this.unsigned ? UZERO2 : ZERO5; if (this.isNegative()) { if (divisor.isNegative()) return this.neg().div(divisor.neg()); return this.neg().div(divisor).neg(); } else if (divisor.isNegative()) return this.div(divisor.neg()).neg(); res = ZERO5; } else { if (!divisor.unsigned) divisor = divisor.toUnsigned(); if (divisor.gt(this)) return UZERO2; if (divisor.gt(this.shru(1))) return UONE2; res = UZERO2; } rem = this; while (rem.gte(divisor)) { approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); var log22 = Math.ceil(Math.log(approx) / Math.LN2), delta = log22 <= 48 ? 1 : pow_dbl2(2, log22 - 48), approxRes = fromNumber2(approx), approxRem = approxRes.mul(divisor); while (approxRem.isNegative() || approxRem.gt(rem)) { approx -= delta; approxRes = fromNumber2(approx, this.unsigned); approxRem = approxRes.mul(divisor); } if (approxRes.isZero()) approxRes = ONE2; res = res.add(approxRes); rem = rem.sub(approxRem); } return res; }; LongPrototype2.div = LongPrototype2.divide; LongPrototype2.modulo = function modulo2(divisor) { if (!isLong2(divisor)) divisor = fromValue2(divisor); return this.sub(this.div(divisor).mul(divisor)); }; LongPrototype2.mod = LongPrototype2.modulo; LongPrototype2.not = function not2() { return fromBits2(~this.low, ~this.high, this.unsigned); }; LongPrototype2.and = function and2(other) { if (!isLong2(other)) other = fromValue2(other); return fromBits2(this.low & other.low, this.high & other.high, this.unsigned); }; LongPrototype2.or = function or2(other) { if (!isLong2(other)) other = fromValue2(other); return fromBits2(this.low | other.low, this.high | other.high, this.unsigned); }; LongPrototype2.xor = function xor2(other) { if (!isLong2(other)) other = fromValue2(other); return fromBits2(this.low ^ other.low, this.high ^ other.high, this.unsigned); }; LongPrototype2.shiftLeft = function shiftLeft2(numBits) { if (isLong2(numBits)) numBits = numBits.toInt(); if ((numBits &= 63) === 0) return this; else if (numBits < 32) return fromBits2(this.low << numBits, this.high << numBits | this.low >>> 32 - numBits, this.unsigned); else return fromBits2(0, this.low << numBits - 32, this.unsigned); }; LongPrototype2.shl = LongPrototype2.shiftLeft; LongPrototype2.shiftRight = function shiftRight2(numBits) { if (isLong2(numBits)) numBits = numBits.toInt(); if ((numBits &= 63) === 0) return this; else if (numBits < 32) return fromBits2(this.low >>> numBits | this.high << 32 - numBits, this.high >> numBits, this.unsigned); else return fromBits2(this.high >> numBits - 32, this.high >= 0 ? 0 : -1, this.unsigned); }; LongPrototype2.shr = LongPrototype2.shiftRight; LongPrototype2.shiftRightUnsigned = function shiftRightUnsigned2(numBits) { if (isLong2(numBits)) numBits = numBits.toInt(); numBits &= 63; if (numBits === 0) return this; else { var high = this.high; if (numBits < 32) { var low = this.low; return fromBits2(low >>> numBits | high << 32 - numBits, high >>> numBits, this.unsigned); } else if (numBits === 32) return fromBits2(high, 0, this.unsigned); else return fromBits2(high >>> numBits - 32, 0, this.unsigned); } }; LongPrototype2.shru = LongPrototype2.shiftRightUnsigned; LongPrototype2.toSigned = function toSigned2() { if (!this.unsigned) return this; return fromBits2(this.low, this.high, false); }; LongPrototype2.toUnsigned = function toUnsigned2() { if (this.unsigned) return this; return fromBits2(this.low, this.high, true); }; LongPrototype2.toBytes = function(le) { return le ? this.toBytesLE() : this.toBytesBE(); }; LongPrototype2.toBytesLE = function() { var hi = this.high, lo = this.low; return [ lo & 255, lo >>> 8 & 255, lo >>> 16 & 255, lo >>> 24 & 255, hi & 255, hi >>> 8 & 255, hi >>> 16 & 255, hi >>> 24 & 255 ]; }; LongPrototype2.toBytesBE = function() { var hi = this.high, lo = this.low; return [ hi >>> 24 & 255, hi >>> 16 & 255, hi >>> 8 & 255, hi & 255, lo >>> 24 & 255, lo >>> 16 & 255, lo >>> 8 & 255, lo & 255 ]; }; return Long4; }); } }); // external-global-plugin:h3-js var require_h3_js = __commonJS({ "external-global-plugin:h3-js"(exports, module) { module.exports = globalThis.h3 || {}; } }); // external-global-plugin:@luma.gl/engine var require_engine = __commonJS({ "external-global-plugin:@luma.gl/engine"(exports, module) { module.exports = globalThis.luma; } }); // external-global-plugin:@deck.gl/mesh-layers var require_mesh_layers = __commonJS({ "external-global-plugin:@deck.gl/mesh-layers"(exports, module) { module.exports = globalThis.deck; } }); // external-global-plugin:@luma.gl/core var require_core2 = __commonJS({ "external-global-plugin:@luma.gl/core"(exports, module) { module.exports = globalThis.luma; } }); // external-global-plugin:@loaders.gl/core var require_core3 = __commonJS({ "external-global-plugin:@loaders.gl/core"(exports, module) { module.exports = globalThis.loaders; } }); // external-global-plugin:@deck.gl/extensions var require_extensions = __commonJS({ "external-global-plugin:@deck.gl/extensions"(exports, module) { module.exports = globalThis.deck; } }); // ../../node_modules/ieee754/index.js var require_ieee754 = __commonJS({ "../../node_modules/ieee754/index.js"(exports) { exports.read = function(buffer, offset, isLE, mLen, nBytes) { var e, m; var eLen = nBytes * 8 - mLen - 1; var eMax = (1 << eLen) - 1; var eBias = eMax >> 1; var nBits = -7; var i3 = isLE ? nBytes - 1 : 0; var d = isLE ? -1 : 1; var s2 = buffer[offset + i3]; i3 += d; e = s2 & (1 << -nBits) - 1; s2 >>= -nBits; nBits += eLen; for (; nBits > 0; e = e * 256 + buffer[offset + i3], i3 += d, nBits -= 8) { } m = e & (1 << -nBits) - 1; e >>= -nBits; nBits += mLen; for (; nBits > 0; m = m * 256 + buffer[offset + i3], i3 += d, nBits -= 8) { } if (e === 0) { e = 1 - eBias; } else if (e === eMax) { return m ? NaN : (s2 ? -1 : 1) * Infinity; } else { m = m + Math.pow(2, mLen); e = e - eBias; } return (s2 ? -1 : 1) * m * Math.pow(2, e - mLen); }; exports.write = function(buffer, value, offset, isLE, mLen, nBytes) { var e, m, c; var eLen = nBytes * 8 - mLen - 1; var eMax = (1 << eLen) - 1; var eBias = eMax >> 1; var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; var i3 = isLE ? 0 : nBytes - 1; var d = isLE ? 1 : -1; var s2 = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; value = Math.abs(value); if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0; e = eMax; } else { e = Math.floor(Math.log(value) / Math.LN2); if (value * (c = Math.pow(2, -e)) < 1) { e--; c *= 2; } if (e + eBias >= 1) { value += rt / c; } else { value += rt * Math.pow(2, 1 - eBias); } if (value * c >= 2) { e++; c /= 2; } if (e + eBias >= eMax) { m = 0; e = eMax; } else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen); e = e + eBias; } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); e = 0; } } for (; mLen >= 8; buffer[offset + i3] = m & 255, i3 += d, m /= 256, mLen -= 8) { } e = e << mLen | m; eLen += mLen; for (; eLen > 0; buffer[offset + i3] = e & 255, i3 += d, e /= 256, eLen -= 8) { } buffer[offset + i3 - d] |= s2 * 128; }; } }); // ../../node_modules/pbf/index.js var require_pbf = __commonJS({ "../../node_modules/pbf/index.js"(exports, module) { "use strict"; module.exports = Pbf; var ieee754 = require_ieee754(); function Pbf(buf) { this.buf = ArrayBuffer.isView && ArrayBuffer.isView(buf) ? buf : new Uint8Array(buf || 0); this.pos = 0; this.type = 0; this.length = this.buf.length; } Pbf.Varint = 0; Pbf.Fixed64 = 1; Pbf.Bytes = 2; Pbf.Fixed32 = 5; var SHIFT_LEFT_32 = (1 << 16) * (1 << 16); var SHIFT_RIGHT_32 = 1 / SHIFT_LEFT_32; var TEXT_DECODER_MIN_LENGTH = 12; var utf8TextDecoder = typeof TextDecoder === "undefined" ? null : new TextDecoder("utf8"); Pbf.prototype = { destroy: function() { this.buf = null; }, readFields: function(readField, result, end) { end = end || this.length; while (this.pos < end) { var val2 = this.readVarint(), tag = val2 >> 3, startPos = this.pos; this.type = val2 & 7; readField(tag, result, this); if (this.pos === startPos) this.skip(val2); } return result; }, readMessage: function(readField, result) { return this.readFields(readField, result, this.readVarint() + this.pos); }, readFixed32: function() { var val2 = readUInt32(this.buf, this.pos); this.pos += 4; return val2; }, readSFixed32: function() { var val2 = readInt32(this.buf, this.pos); this.pos += 4; return val2; }, readFixed64: function() { var val2 = readUInt32(this.buf, this.pos) + readUInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32; this.pos += 8; return val2; }, readSFixed64: function() { var val2 = readUInt32(this.buf, this.pos) + readInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32; this.pos += 8; return val2; }, readFloat: function() { var val2 = ieee754.read(this.buf, this.pos, true, 23, 4); this.pos += 4; return val2; }, readDouble: function() { var val2 = ieee754.read(this.buf, this.pos, true, 52, 8); this.pos += 8; return val2; }, readVarint: function(isSigned) { var buf = this.buf, val2, b; b = buf[this.pos++]; val2 = b & 127; if (b < 128) return val2; b = buf[this.pos++]; val2 |= (b & 127) << 7; if (b < 128) return val2; b = buf[this.pos++]; val2 |= (b & 127) << 14; if (b < 128) return val2; b = buf[this.pos++]; val2 |= (b & 127) << 21; if (b < 128) return val2; b = buf[this.pos]; val2 |= (b & 15) << 28; return readVarintRemainder(val2, isSigned, this); }, readVarint64: function() { return this.readVarint(true); }, readSVarint: function() { var num = this.readVarint(); return num % 2 === 1 ? (num + 1) / -2 : num / 2; }, readBoolean: function() { return Boolean(this.readVarint()); }, readString: function() { var end = this.readVarint() + this.pos; var pos = this.pos; this.pos = end; if (end - pos >= TEXT_DECODER_MIN_LENGTH && utf8TextDecoder) { return readUtf8TextDecoder(this.buf, pos, end); } return readUtf8(this.buf, pos, end); }, readBytes: function() { var end = this.readVarint() + this.pos, buffer = this.buf.subarray(this.pos, end); this.pos = end; return buffer; }, readPackedVarint: function(arr, isSigned) { if (this.type !== Pbf.Bytes) return arr.push(this.readVarint(isSigned)); var end = readPackedEnd(this); arr = arr || []; while (this.pos < end) arr.push(this.readVarint(isSigned)); return arr; }, readPackedSVarint: function(arr) { if (this.type !== Pbf.Bytes) return arr.push(this.readSVarint()); var end = readPackedEnd(this); arr = arr || []; while (this.pos < end) arr.push(this.readSVarint()); return arr; }, readPackedBoolean: function(arr) { if (this.type !== Pbf.Bytes) return arr.push(this.readBoolean()); var end = readPackedEnd(this); arr = arr || []; while (this.pos < end) arr.push(this.readBoolean()); return arr; }, readPackedFloat: function(arr) { if (this.type !== Pbf.Bytes) return arr.push(this.readFloat()); var end = readPackedEnd(this); arr = arr || []; while (this.pos < end) arr.push(this.readFloat()); return arr; }, readPackedDouble: function(arr) { if (this.type !== Pbf.Bytes) return arr.push(this.readDouble()); var end = readPackedEnd(this); arr = arr || []; while (this.pos < end) arr.push(this.readDouble()); return arr; }, readPackedFixed32: function(arr) { if (this.type !== Pbf.Bytes) return arr.push(this.readFixed32()); var end = readPackedEnd(this); arr = arr || []; while (this.pos < end) arr.push(this.readFixed32()); return arr; }, readPackedSFixed32: function(arr) { if (this.type !== Pbf.Bytes) return arr.push(this.readSFixed32()); var end = readPackedEnd(this); arr = arr || []; while (this.pos < end) arr.push(this.readSFixed32()); return arr; }, readPackedFixed64: function(arr) { if (this.type !== Pbf.Bytes) return arr.push(this.readFixed64()); var end = readPackedEnd(this); arr = arr || []; while (this.pos < end) arr.push(this.readFixed64()); return arr; }, readPackedSFixed64: function(arr) { if (this.type !== Pbf.Bytes) return arr.push(this.readSFixed64()); var end = readPackedEnd(this); arr = arr || []; while (this.pos < end) arr.push(this.readSFixed64()); return arr; }, skip: function(val2) { var type = val2 & 7; if (type === Pbf.Varint) while (this.buf[this.pos++] > 127) { } 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); }, writeTag: function(tag, type) { this.writeVarint(tag << 3 | type); }, realloc: function(min2) { var length5 = this.length || 16; while (length5 < this.pos + min2) length5 *= 2; if (length5 !== this.length) { var buf = new Uint8Array(length5); buf.set(this.buf); this.buf = buf; this.length = length5; } }, finish: function() { this.length = this.pos; this.pos = 0; return this.buf.subarray(0, this.length); }, writeFixed32: function(val2) { this.realloc(4); writeInt32(this.buf, val2, this.pos); this.pos += 4; }, writeSFixed32: function(val2) { this.realloc(4); writeInt32(this.buf, val2, this.pos); this.pos += 4; }, writeFixed64: function(val2) { this.realloc(8); writeInt32(this.buf, val2 & -1, this.pos); writeInt32(this.buf, Math.floor(val2 * SHIFT_RIGHT_32), this.pos + 4); this.pos += 8; }, writeSFixed64: function(val2) { this.realloc(8); writeInt32(this.buf, val2 & -1, this.pos); writeInt32(this.buf, Math.floor(val2 * SHIFT_RIGHT_32), this.pos + 4); this.pos += 8; }, writeVarint: function(val2) { val2 = +val2 || 0; if (val2 > 268435455 || val2 < 0) { writeBigVarint(val2, this); return; } this.realloc(4); this.buf[this.pos++] = val2 & 127 | (val2 > 127 ? 128 : 0); if (val2 <= 127) return; this.buf[this.pos++] = (val2 >>>= 7) & 127 | (val2 > 127 ? 128 : 0); if (val2 <= 127) return; this.buf[this.pos++] = (val2 >>>= 7) & 127 | (val2 > 127 ? 128 : 0); if (val2 <= 127) return; this.buf[this.pos++] = val2 >>> 7 & 127; }, writeSVarint: function(val2) { this.writeVarint(val2 < 0 ? -val2 * 2 - 1 : val2 * 2); }, writeBoolean: function(val2) { this.writeVarint(Boolean(val2)); }, writeString: function(str3) { str3 = String(str3); this.realloc(str3.length * 4); this.pos++; var startPos = this.pos; this.pos = writeUtf8(this.buf, str3, this.pos); var len2 = this.pos - startPos; if (len2 >= 128) makeRoomForExtraLength(startPos, len2, this); this.pos = startPos - 1; this.writeVarint(len2); this.pos += len2; }, writeFloat: function(val2) { this.realloc(4); ieee754.write(this.buf, val2, this.pos, true, 23, 4); this.pos += 4; }, writeDouble: function(val2) { this.realloc(8); ieee754.write(this.buf, val2, this.pos, true, 52, 8); this.pos += 8; }, writeBytes: function(buffer) { var len2 = buffer.length; this.writeVarint(len2); this.realloc(len2); for (var i3 = 0; i3 < len2; i3++) this.buf[this.pos++] = buffer[i3]; }, writeRawMessage: function(fn, obj) { this.pos++; var startPos = this.pos; fn(obj, this); var len2 = this.pos - startPos; if (len2 >= 128) makeRoomForExtraLength(startPos, len2, this); this.pos = startPos - 1; this.writeVarint(len2); this.pos += len2; }, writeMessage: function(tag, fn, obj) { this.writeTag(tag, Pbf.Bytes); this.writeRawMessage(fn, obj); }, writePackedVarint: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedVarint, arr); }, writePackedSVarint: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedSVarint, arr); }, writePackedBoolean: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedBoolean, arr); }, writePackedFloat: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedFloat, arr); }, writePackedDouble: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedDouble, arr); }, writePackedFixed32: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedFixed32, arr); }, writePackedSFixed32: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedSFixed32, arr); }, writePackedFixed64: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedFixed64, arr); }, writePackedSFixed64: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedSFixed64, arr); }, writeBytesField: function(tag, buffer) { this.writeTag(tag, Pbf.Bytes); this.writeBytes(buffer); }, writeFixed32Field: function(tag, val2) { this.writeTag(tag, Pbf.Fixed32); this.writeFixed32(val2); }, writeSFixed32Field: function(tag, val2) { this.writeTag(tag, Pbf.Fixed32); this.writeSFixed32(val2); }, writeFixed64Field: function(tag, val2) { this.writeTag(tag, Pbf.Fixed64); this.writeFixed64(val2); }, writeSFixed64Field: function(tag, val2) { this.writeTag(tag, Pbf.Fixed64); this.writeSFixed64(val2); }, writeVarintField: function(tag, val2) { this.writeTag(tag, Pbf.Varint); this.writeVarint(val2); }, writeSVarintField: function(tag, val2) { this.writeTag(tag, Pbf.Varint); this.writeSVarint(val2); }, writeStringField: function(tag, str3) { this.writeTag(tag, Pbf.Bytes); this.writeString(str3); }, writeFloatField: function(tag, val2) { this.writeTag(tag, Pbf.Fixed32); this.writeFloat(val2); }, writeDoubleField: function(tag, val2) { this.writeTag(tag, Pbf.Fixed64); this.writeDouble(val2); }, writeBooleanField: function(tag, val2) { this.writeVarintField(tag, Boolean(val2)); } }; function readVarintRemainder(l2, s2, p2) { var buf = p2.buf, h, b; b = buf[p2.pos++]; h = (b & 112) >> 4; if (b < 128) return toNum(l2, h, s2); b = buf[p2.pos++]; h |= (b & 127) << 3; if (b < 128) return toNum(l2, h, s2); b = buf[p2.pos++]; h |= (b & 127) << 10; if (b < 128) return toNum(l2, h, s2); b = buf[p2.pos++]; h |= (b & 127) << 17; if (b < 128) return toNum(l2, h, s2); b = buf[p2.pos++]; h |= (b & 127) << 24; if (b < 128) return toNum(l2, h, s2); b = buf[p2.pos++]; h |= (b & 1) << 31; if (b < 128) return toNum(l2, h, s2); throw new Error("Expected varint not more than 10 bytes"); } function readPackedEnd(pbf) { return pbf.type === Pbf.Bytes ? pbf.readVarint() + pbf.pos : pbf.pos + 1; } function toNum(low, high, isSigned) { if (isSigned) { return high * 4294967296 + (low >>> 0); } return (high >>> 0) * 4294967296 + (low >>> 0); } function writeBigVarint(val2, pbf) { var low, high; if (val2 >= 0) { low = val2 % 4294967296 | 0; high = val2 / 4294967296 | 0; } else { low = ~(-val2 % 4294967296); high = ~(-val2 / 4294967296); if (low ^ 4294967295) { low = low + 1 | 0; } else { low = 0; high = high + 1 | 0; } } if (val2 >= 18446744073709552e3 || val2 < -18446744073709552e3) { throw new Error("Given varint doesn't fit into 10 bytes"); } pbf.realloc(10); writeBigVarintLow(low, high, pbf); writeBigVarintHigh(high, pbf); } function writeBigVarintLow(low, high, pbf) { pbf.buf[pbf.pos++] = low & 127 | 128; low >>>= 7; pbf.buf[pbf.pos++] = low & 127 | 128; low >>>= 7; pbf.buf[pbf.pos++] = low & 127 | 128; low >>>= 7; pbf.buf[pbf.pos++] = low & 127 | 128; low >>>= 7; pbf.buf[pbf.pos] = low & 127; } function writeBigVarintHigh(high, pbf) { var lsb2 = (high & 7) << 4; pbf.buf[pbf.pos++] |= lsb2 | ((high >>>= 3) ? 128 : 0); if (!high) return; pbf.buf[pbf.pos++] = high & 127 | ((high >>>= 7) ? 128 : 0); if (!high) return; pbf.buf[pbf.pos++] = high & 127 | ((high >>>= 7) ? 128 : 0); if (!high) return; pbf.buf[pbf.pos++] = high & 127 | ((high >>>= 7) ? 128 : 0); if (!high) return; pbf.buf[pbf.pos++] = high & 127 | ((high >>>= 7) ? 128 : 0); if (!high) return; pbf.buf[pbf.pos++] = high & 127; } function makeRoomForExtraLength(startPos, len2, pbf) { var extraLen = len2 <= 16383 ? 1 : len2 <= 2097151 ? 2 : len2 <= 268435455 ? 3 : Math.floor(Math.log(len2) / (Math.LN2 * 7)); pbf.realloc(extraLen); for (var i3 = pbf.pos - 1; i3 >= startPos; i3--) pbf.buf[i3 + extraLen] = pbf.buf[i3]; } function writePackedVarint(arr, pbf) { for (var i3 = 0; i3 < arr.length; i3++) pbf.writeVarint(arr[i3]); } function writePackedSVarint(arr, pbf) { for (var i3 = 0; i3 < arr.length; i3++) pbf.writeSVarint(arr[i3]); } function writePackedFloat(arr, pbf) { for (var i3 = 0; i3 < arr.length; i3++) pbf.writeFloat(arr[i3]); } function writePackedDouble(arr, pbf) { for (var i3 = 0; i3 < arr.length; i3++) pbf.writeDouble(arr[i3]); } function writePackedBoolean(arr, pbf) { for (var i3 = 0; i3 < arr.length; i3++) pbf.writeBoolean(arr[i3]); } function writePackedFixed32(arr, pbf) { for (var i3 = 0; i3 < arr.length; i3++) pbf.writeFixed32(arr[i3]); } function writePackedSFixed32(arr, pbf) { for (var i3 = 0; i3 < arr.length; i3++) pbf.writeSFixed32(arr[i3]); } function writePackedFixed64(arr, pbf) { for (var i3 = 0; i3 < arr.length; i3++) pbf.writeFixed64(arr[i3]); } function writePackedSFixed64(arr, pbf) { for (var i3 = 0; i3 < arr.length; i3++) pbf.writeSFixed64(arr[i3]); } function readUInt32(buf, pos) { return (buf[pos] | buf[pos + 1] << 8 | buf[pos + 2] << 16) + buf[pos + 3] * 16777216; } function writeInt32(buf, val2, pos) { buf[pos] = val2; buf[pos + 1] = val2 >>> 8; buf[pos + 2] = val2 >>> 16; buf[pos + 3] = val2 >>> 24; } function readInt32(buf, pos) { return (buf[pos] | buf[pos + 1] << 8 | buf[pos + 2] << 16) + (buf[pos + 3] << 24); } function readUtf8(buf, pos, end) { var str3 = ""; var i3 = pos; while (i3 < end) { var b0 = buf[i3]; var c = null; var bytesPerSequence = b0 > 239 ? 4 : b0 > 223 ? 3 : b0 > 191 ? 2 : 1; if (i3 + bytesPerSequence > end) break; var b1, b2, b3; if (bytesPerSequence === 1) { if (b0 < 128) { c = b0; } } else if (bytesPerSequence === 2) { b1 = buf[i3 + 1]; if ((b1 & 192) === 128) { c = (b0 & 31) << 6 | b1 & 63; if (c <= 127) { c = null; } } } else if (bytesPerSequence === 3) { b1 = buf[i3 + 1]; b2 = buf[i3 + 2]; if ((b1 & 192) === 128 && (b2 & 192) === 128) { c = (b0 & 15) << 12 | (b1 & 63) << 6 | b2 & 63; if (c <= 2047 || c >= 55296 && c <= 57343) { c = null; } } } else if (bytesPerSequence === 4) { b1 = buf[i3 + 1]; b2 = buf[i3 + 2]; b3 = buf[i3 + 3]; if ((b1 & 192) === 128 && (b2 & 192) === 128 && (b3 & 192) === 128) { c = (b0 & 15) << 18 | (b1 & 63) << 12 | (b2 & 63) << 6 | b3 & 63; if (c <= 65535 || c >= 1114112) { c = null; } } } if (c === null) { c = 65533; bytesPerSequence = 1; } else if (c > 65535) { c -= 65536; str3 += String.fromCharCode(c >>> 10 & 1023 | 55296); c = 56320 | c & 1023; } str3 += String.fromCharCode(c); i3 += bytesPerSequence; } return str3; } function readUtf8TextDecoder(buf, pos, end) { return utf8TextDecoder.decode(buf.subarray(pos, end)); } function writeUtf8(buf, str3, pos) { for (var i3 = 0, c, lead; i3 < str3.length; i3++) { c = str3.charCodeAt(i3); if (c > 55295 && c < 57344) { if (lead) { if (c < 56320) { buf[pos++] = 239; buf[pos++] = 191; buf[pos++] = 189; lead = c; continue; } else { c = lead - 55296 << 10 | c - 56320 | 65536; lead = null; } } else { if (c > 56319 || i3 + 1 === str3.length) { buf[pos++] = 239; buf[pos++] = 191; buf[pos++] = 189; } else { lead = c; } continue; } } else if (lead) { buf[pos++] = 239; buf[pos++] = 191; buf[pos++] = 189; lead = null; } if (c < 128) { buf[pos++] = c; } else { if (c < 2048) { buf[pos++] = c >> 6 | 192; } else { if (c < 65536) { buf[pos++] = c >> 12 | 224; } else { buf[pos++] = c >> 18 | 240; buf[pos++] = c >> 12 & 63 | 128; } buf[pos++] = c >> 6 & 63 | 128; } buf[pos++] = c & 63 | 128; } } return pos; } } }); // bundle.ts var bundle_exports = {}; __export(bundle_exports, { GeohashLayer: () => GeohashLayer, GreatCircleLayer: () => GreatCircleLayer, H3ClusterLayer: () => H3ClusterLayer, H3HexagonLayer: () => H3HexagonLayer, MVTLayer: () => MVTLayer, QuadkeyLayer: () => QuadkeyLayer, S2Layer: () => S2Layer, TerrainLayer: () => TerrainLayer, Tile3DLayer: () => Tile3DLayer, TileLayer: () => TileLayer, TripsLayer: () => TripsLayer, _GeoCellLayer: () => GeoCellLayer, _Tile2DHeader: () => Tile2DHeader, _Tileset2D: () => Tileset2D, _WMSLayer: () => WMSLayer, _getURLFromTemplate: () => getURLFromTemplate }); // ../layers/bundle/peer-dependency.ts var peer_dependency_exports = {}; var import_layers = __toESM(require_layers(), 1); __reExport(peer_dependency_exports, __toESM(require_layers(), 1)); if (!import_layers.GeoJsonLayer) { throw new Error("@deck.gl/layers is not found"); } // bundle.ts __reExport(bundle_exports, peer_dependency_exports); // src/wms-layer/wms-layer.ts var import_core = __toESM(require_core(), 1); var import_layers2 = __toESM(require_layers(), 1); // ../../node_modules/@loaders.gl/xml/dist/lib/xml-utils/uncapitalize.js function uncapitalize(str3) { return typeof str3 === "string" ? str3.charAt(0).toLowerCase() + str3.slice(1) : str3; } function uncapitalizeKeys(object) { if (Array.isArray(object)) { return object.map((element) => uncapitalizeKeys(element)); } if (object && typeof object === "object") { const newObject = {}; for (const [key, value] of Object.entries(object)) { newObject[uncapitalize(key)] = uncapitalizeKeys(value); } return newObject; } return object; } // ../../node_modules/@loaders.gl/xml/dist/lib/parsers/parse-xml.js var import_fast_xml_parser = __toESM(require_fxp(), 1); function parseXMLSync(text, options) { if (options?._parser && options._parser !== "fast-xml-parser") { throw new Error(options?._parser); } const fastXMLOptions = { allowBooleanAttributes: true, ignoreDeclaration: true, removeNSPrefix: options?.removeNSPrefix, textNodeName: options?.textNodeName, isArray: (name12, jpath, isLeafNode, isAttribute) => { const array = Boolean(options?.arrayPaths?.some((path) => jpath === path)); return array; }, ...options?._fastXML }; const xml = fastParseXML(text, fastXMLOptions); return options?.uncapitalizeKeys ? uncapitalizeKeys(xml) : xml; } function fastParseXML(text, options) { const parser = new import_fast_xml_parser.XMLParser({ ignoreAttributes: false, attributeNamePrefix: "", ...options }); const parsedXML = parser.parse(text); return parsedXML; } // ../../node_modules/@loaders.gl/xml/dist/xml-loader.js var VERSION = true ? "4.2.0-beta.2" : "latest"; var XMLLoader = { dataType: null, batchType: null, name: "XML", id: "xml", module: "xml", version: VERSION, worker: false, extensions: ["xml"], mimeTypes: ["application/xml", "text/xml"], testText: testXMLFile, options: { xml: { _parser: "fast-xml-parser", uncapitalizeKeys: false, removeNSPrefix: false, textNodeName: "value", arrayPaths: [] } }, parse: async (arrayBuffer, options) => parseXMLSync(new TextDecoder().decode(arrayBuffer), { ...XMLLoader.options.xml, ...options?.xml }), parseTextSync: (text, options) => parseXMLSync(text, { ...XMLLoader.options.xml, ...options?.xml }) }; function testXMLFile(text) { return text.startsWith("= 0); } // ../../node_modules/@probe.gl/env/dist/lib/is-browser.js function isBrowser2() { const isNode = typeof process === "object" && String(process) === "[object process]" && !process?.browser; return !isNode || isElectron(); } // ../../node_modules/@probe.gl/env/dist/index.js var VERSION2 = true ? "4.0.7" : "untranspiled source"; // ../../node_modules/@probe.gl/log/dist/utils/local-storage.js function getStorage(type) { try { const storage = window[type]; const x2 = "__storage_test__"; storage.setItem(x2, x2); storage.removeItem(x2); return storage; } catch (e) { return null; } } var LocalStorage = class { constructor(id, defaultConfig, type = "sessionStorage") { this.storage = getStorage(type); this.id = id; this.config = defaultConfig; this._loadConfiguration(); } getConfiguration() { return this.config; } setConfiguration(configuration) { Object.assign(this.config, configuration); if (this.storage) { const serialized = JSON.stringify(this.config); this.storage.setItem(this.id, serialized); } } _loadConfiguration() { let configuration = {}; if (this.storage) { const serializedConfiguration = this.storage.getItem(this.id); configuration = serializedConfiguration ? JSON.parse(serializedConfiguration) : {}; } Object.assign(this.config, configuration); return this; } }; // ../../node_modules/@probe.gl/log/dist/utils/formatters.js function formatTime(ms) { let formatted; if (ms < 10) { formatted = `${ms.toFixed(2)}ms`; } else if (ms < 100) { formatted = `${ms.toFixed(1)}ms`; } else if (ms < 1e3) { formatted = `${ms.toFixed(0)}ms`; } else { formatted = `${(ms / 1e3).toFixed(2)}s`; } return formatted; } function leftPad(string, length5 = 8) { const padLength = Math.max(length5 - string.length, 0); return `${" ".repeat(padLength)}${string}`; } // ../../node_modules/@probe.gl/log/dist/utils/color.js var COLOR; (function(COLOR2) { COLOR2[COLOR2["BLACK"] = 30] = "BLACK"; COLOR2[COLOR2["RED"] = 31] = "RED"; COLOR2[COLOR2["GREEN"] = 32] = "GREEN"; COLOR2[COLOR2["YELLOW"] = 33] = "YELLOW"; COLOR2[COLOR2["BLUE"] = 34] = "BLUE"; COLOR2[COLOR2["MAGENTA"] = 35] = "MAGENTA"; COLOR2[COLOR2["CYAN"] = 36] = "CYAN"; COLOR2[COLOR2["WHITE"] = 37] = "WHITE"; COLOR2[COLOR2["BRIGHT_BLACK"] = 90] = "BRIGHT_BLACK"; COLOR2[COLOR2["BRIGHT_RED"] = 91] = "BRIGHT_RED"; COLOR2[COLOR2["BRIGHT_GREEN"] = 92] = "BRIGHT_GREEN"; COLOR2[COLOR2["BRIGHT_YELLOW"] = 93] = "BRIGHT_YELLOW"; COLOR2[COLOR2["BRIGHT_BLUE"] = 94] = "BRIGHT_BLUE"; COLOR2[COLOR2["BRIGHT_MAGENTA"] = 95] = "BRIGHT_MAGENTA"; COLOR2[COLOR2["BRIGHT_CYAN"] = 96] = "BRIGHT_CYAN"; COLOR2[COLOR2["BRIGHT_WHITE"] = 97] = "BRIGHT_WHITE"; })(COLOR || (COLOR = {})); var BACKGROUND_INCREMENT = 10; function getColor(color) { if (typeof color !== "string") { return color; } color = color.toUpperCase(); return COLOR[color] || COLOR.WHITE; } function addColor(string, color, background) { if (!isBrowser2 && typeof string === "string") { if (color) { const colorCode = getColor(color); string = `\x1B[${colorCode}m${string}\x1B[39m`; } if (background) { const colorCode = getColor(background); string = `\x1B[${colorCode + BACKGROUND_INCREMENT}m${string}\x1B[49m`; } } return string; } // ../../node_modules/@probe.gl/log/dist/utils/autobind.js function autobind(obj, predefined = ["constructor"]) { const proto = Object.getPrototypeOf(obj); const propNames = Object.getOwnPropertyNames(proto); const object = obj; for (const key of propNames) { const value = object[key]; if (typeof value === "function") { if (!predefined.find((name12) => key === name12)) { object[key] = value.bind(obj); } } } } // ../../node_modules/@probe.gl/log/dist/utils/assert.js function assert3(condition, message) { if (!condition) { throw new Error(message || "Assertion failed"); } } // ../../node_modules/@probe.gl/log/dist/utils/hi-res-timestamp.js function getHiResTimestamp() { let timestamp; if (isBrowser2() && window_2.performance) { timestamp = window_2?.performance?.now?.(); } else if ("hrtime" in process_) { const timeParts = process_?.hrtime?.(); timestamp = timeParts[0] * 1e3 + timeParts[1] / 1e6; } else { timestamp = Date.now(); } return timestamp; } // ../../node_modules/@probe.gl/log/dist/log.js var originalConsole = { debug: isBrowser2() ? console.debug || console.log : console.log, log: console.log, info: console.info, warn: console.warn, error: console.error }; var DEFAULT_LOG_CONFIGURATION = { enabled: true, level: 0 }; function noop() { } var cache = {}; var ONCE = { once: true }; var Log = class { constructor({ id } = { id: "" }) { this.VERSION = VERSION2; this._startTs = getHiResTimestamp(); this._deltaTs = getHiResTimestamp(); this.userData = {}; this.LOG_THROTTLE_TIMEOUT = 0; this.id = id; this.userData = {}; this._storage = new LocalStorage(`__probe-${this.id}__`, DEFAULT_LOG_CONFIGURATION); this.timeStamp(`${this.id} started`); autobind(this); Object.seal(this); } set level(newLevel) { this.setLevel(newLevel); } get level() { return this.getLevel(); } isEnabled() { return this._storage.config.enabled; } getLevel() { return this._storage.config.level; } getTotal() { return Number((getHiResTimestamp() - this._startTs).toPrecision(10)); } getDelta() { return Number((getHiResTimestamp() - this._deltaTs).toPrecision(10)); } set priority(newPriority) { this.level = newPriority; } get priority() { return this.level; } getPriority() { return this.level; } enable(enabled = true) { this._storage.setConfiguration({ enabled }); return this; } setLevel(level) { this._storage.setConfiguration({ level }); return this; } get(setting) { return this._storage.config[setting]; } set(setting, value) { this._storage.setConfiguration({ [setting]: value }); } settings() { if (console.table) { console.table(this._storage.config); } else { console.log(this._storage.config); } } assert(condition, message) { if (!condition) { throw new Error(message || "Assertion failed"); } } warn(message) { return this._getLogFunction(0, message, originalConsole.warn, arguments, ONCE); } error(message) { return this._getLogFunction(0, message, originalConsole.error, arguments); } deprecated(oldUsage, newUsage) { return this.warn(`\`${oldUsage}\` is deprecated and will be removed in a later version. Use \`${newUsage}\` instead`); } removed(oldUsage, newUsage) { return this.error(`\`${oldUsage}\` has been removed. Use \`${newUsage}\` instead`); } probe(logLevel, message) { return this._getLogFunction(logLevel, message, originalConsole.log, arguments, { time: true, once: true }); } log(logLevel, message) { return this._getLogFunction(logLevel, message, originalConsole.debug, arguments); } info(logLevel, message) { return this._getLogFunction(logLevel, message, console.info, arguments); } once(logLevel, message) { return this._getLogFunction(logLevel, message, originalConsole.debug || originalConsole.info, arguments, ONCE); } table(logLevel, table, columns) { if (table) { return this._getLogFunction(logLevel, table, console.table || noop, columns && [columns], { tag: getTableHeader(table) }); } return noop; } time(logLevel, message) { return this._getLogFunction(logLevel, message, console.time ? console.time : console.info); } timeEnd(logLevel, message) { return this._getLogFunction(logLevel, message, console.timeEnd ? console.timeEnd : console.info); } timeStamp(logLevel, message) { return this._getLogFunction(logLevel, message, console.timeStamp || noop); } group(logLevel, message, opts = { collapsed: false }) { const options = normalizeArguments({ logLevel, message, opts }); const { collapsed } = opts; options.method = (collapsed ? console.groupCollapsed : console.group) || console.info; return this._getLogFunction(options); } groupCollapsed(logLevel, message, opts = {}) { return this.group(logLevel, message, Object.assign({}, opts, { collapsed: true })); } groupEnd(logLevel) { return this._getLogFunction(logLevel, "", console.groupEnd || noop); } withGroup(logLevel, message, func) { this.group(logLevel, message)(); try { func(); } finally { this.groupEnd(logLevel)(); } } trace() { if (console.trace) { console.trace(); } } _shouldLog(logLevel) { return this.isEnabled() && this.getLevel() >= normalizeLogLevel(logLevel); } _getLogFunction(logLevel, message, method, args, opts) { if (this._shouldLog(logLevel)) { opts = normalizeArguments({ logLevel, message, args, opts }); method = method || opts.method; assert3(method); opts.total = this.getTotal(); opts.delta = this.getDelta(); this._deltaTs = getHiResTimestamp(); const tag = opts.tag || opts.message; if (opts.once && tag) { if (!cache[tag]) { cache[tag] = getHiResTimestamp(); } else { return noop; } } message = decorateMessage(this.id, opts.message, opts); return method.bind(console, message, ...opts.args); } return noop; } }; Log.VERSION = VERSION2; function normalizeLogLevel(logLevel) { if (!logLevel) { return 0; } let resolvedLevel; switch (typeof logLevel) { case "number": resolvedLevel = logLevel; break; case "object": resolvedLevel = logLevel.logLevel || logLevel.priority || 0; break; default: return 0; } assert3(Number.isFinite(resolvedLevel) && resolvedLevel >= 0); return resolvedLevel; } function normalizeArguments(opts) { const { logLevel, message } = opts; opts.logLevel = normalizeLogLevel(logLevel); const args = opts.args ? Array.from(opts.args) : []; while (args.length && args.shift() !== message) { } switch (typeof logLevel) { case "string": case "function": if (message !== void 0) { args.unshift(message); } opts.message = logLevel; break; case "object": Object.assign(opts, logLevel); break; default: } if (typeof opts.message === "function") { opts.message = opts.message(); } const messageType = typeof opts.message; assert3(messageType === "string" || messageType === "object"); return Object.assign(opts, { args }, opts.opts); } function decorateMessage(id, message, opts) { if (typeof message === "string") { const time = opts.time ? leftPad(formatTime(opts.total)) : ""; message = opts.time ? `${id}: ${time} ${message}` : `${id}: ${message}`; message = addColor(message, opts.color, opts.background); } return message; } function getTableHeader(table) { for (const key in table) { for (const title in table[key]) { return title || "untitled"; } } return "empty"; } // ../../node_modules/@probe.gl/log/dist/init.js globalThis.probe = {}; // ../../node_modules/@probe.gl/log/dist/index.js var dist_default = new Log({ id: "@probe.gl/log" }); // ../../node_modules/@loaders.gl/loader-utils/dist/lib/option-utils/merge-loader-options.js function mergeLoaderOptions(baseOptions, newOptions) { return mergeOptionsRecursively(baseOptions || {}, newOptions); } function mergeOptionsRecursively(baseOptions, newOptions, level = 0) { if (level > 3) { return newOptions; } const options = { ...baseOptions }; for (const [key, newValue] of Object.entries(newOptions)) { if (newValue && typeof newValue === "object" && !Array.isArray(newValue)) { options[key] = mergeOptionsRecursively(options[key] || {}, newOptions[key], level + 1); } else { options[key] = newOptions[key]; } } return options; } // ../../node_modules/@loaders.gl/loader-utils/dist/lib/module-utils/js-module-utils.js function registerJSModules(modules) { globalThis.loaders ||= {}; globalThis.loaders.modules ||= {}; Object.assign(globalThis.loaders.modules, modules); } function getJSModuleOrNull(name12) { const module = globalThis.loaders?.modules?.[name12]; return module || null; } // ../../node_modules/@loaders.gl/worker-utils/dist/lib/env-utils/version.js function getVersion() { if (!globalThis._loadersgl_?.version) { globalThis._loadersgl_ = globalThis._loadersgl_ || {}; if (false) { console.warn("loaders.gl: The __VERSION__ variable is not injected using babel plugin. Latest unstable workers would be fetched from the CDN."); globalThis._loadersgl_.version = NPM_TAG; } else { globalThis._loadersgl_.version = "4.2.0-beta.2"; } } return globalThis._loadersgl_.version; } var VERSION3 = getVersion(); // ../../node_modules/@loaders.gl/worker-utils/dist/lib/env-utils/assert.js function assert4(condition, message) { if (!condition) { throw new Error(message || "loaders.gl assertion failed."); } } // ../../node_modules/@loaders.gl/worker-utils/dist/lib/env-utils/globals.js var globals2 = { self: typeof self !== "undefined" && self, window: typeof window !== "undefined" && window, global: typeof global !== "undefined" && global, document: typeof document !== "undefined" && document }; var self_2 = globals2.self || globals2.window || globals2.global || {}; var window_3 = globals2.window || globals2.self || globals2.global || {}; var global_3 = globals2.global || globals2.self || globals2.window || {}; var document_3 = globals2.document || {}; var isBrowser3 = typeof process !== "object" || String(process) !== "[object process]" || process.browser; var isWorker = typeof importScripts === "function"; var isMobile = typeof window !== "undefined" && typeof window.orientation !== "undefined"; var matches2 = typeof process !== "undefined" && process.version && /v([0-9]*)/.exec(process.version); var nodeVersion2 = matches2 && parseFloat(matches2[1]) || 0; // ../../node_modules/@loaders.gl/worker-utils/dist/lib/library-utils/library-utils.js var loadLibraryPromises = {}; async function loadLibrary(libraryUrl, moduleName = null, options = {}, libraryName = null) { if (moduleName) { libraryUrl = getLibraryUrl(libraryUrl, moduleName, options, libraryName); } loadLibraryPromises[libraryUrl] = loadLibraryPromises[libraryUrl] || loadLibraryFromFile(libraryUrl); return await loadLibraryPromises[libraryUrl]; } function getLibraryUrl(library, moduleName, options = {}, libraryName = null) { if (!options.useLocalLibraries && library.startsWith("http")) { return library; } libraryName = libraryName || library; const modules = options.modules || {}; if (modules[libraryName]) { return modules[libraryName]; } if (!isBrowser3) { return `modules/${moduleName}/dist/libs/${libraryName}`; } if (options.CDN) { assert4(options.CDN.startsWith("http")); return `${options.CDN}/${moduleName}@${VERSION3}/dist/libs/${libraryName}`; } if (isWorker) { return `../src/libs/${libraryName}`; } return `modules/${moduleName}/src/libs/${libraryName}`; } async function loadLibraryFromFile(libraryUrl) { if (libraryUrl.endsWith("wasm")) { return await loadAsArrayBuffer(libraryUrl); } if (!isBrowser3) { try { const { requireFromFile } = globalThis.loaders || {}; return await requireFromFile?.(libraryUrl); } catch (error) { console.error(error); return null; } } if (isWorker) { return importScripts(libraryUrl); } const scriptSource = await loadAsText(libraryUrl); return loadLibraryFromString(scriptSource, libraryUrl); } function loadLibraryFromString(scriptSource, id) { if (!isBrowser3) { const { requireFromString } = globalThis.loaders || {}; return requireFromString?.(scriptSource, id); } if (isWorker) { eval.call(globalThis, scriptSource); return null; } const script = document.createElement("script"); script.id = id; try { script.appendChild(document.createTextNode(scriptSource)); } catch (e) { script.text = scriptSource; } document.body.appendChild(script); return null; } async function loadAsArrayBuffer(url) { const { readFileAsArrayBuffer } = globalThis.loaders || {}; if (isBrowser3 || !readFileAsArrayBuffer || url.startsWith("http")) { const response = await fetch(url); return await response.arrayBuffer(); } return await readFileAsArrayBuffer(url); } async function loadAsText(url) { const { readFileAsText } = globalThis.loaders || {}; if (isBrowser3 || !readFileAsText || url.startsWith("http")) { const response = await fetch(url); return await response.text(); } return await readFileAsText(url); } // ../../node_modules/@loaders.gl/loader-utils/dist/lib/binary-utils/get-first-characters.js function getFirstCharacters(data, length5 = 5) { if (typeof data === "string") { return data.slice(0, length5); } else if (ArrayBuffer.isView(data)) { return getMagicString(data.buffer, data.byteOffset, length5); } else if (data instanceof ArrayBuffer) { const byteOffset = 0; return getMagicString(data, byteOffset, length5); } return ""; } function getMagicString(arrayBuffer, byteOffset, length5) { if (arrayBuffer.byteLength <= byteOffset + length5) { return ""; } const dataView = new DataView(arrayBuffer); let magic = ""; for (let i3 = 0; i3 < length5; i3++) { magic += String.fromCharCode(dataView.getUint8(byteOffset + i3)); } return magic; } // ../../node_modules/@loaders.gl/loader-utils/dist/lib/parser-utils/parse-json.js function parseJSON(string) { try { return JSON.parse(string); } catch (_) { throw new Error(`Failed to parse JSON from data starting with "${getFirstCharacters(string)}"`); } } // ../../node_modules/@loaders.gl/loader-utils/dist/lib/binary-utils/array-buffer-utils.js function concatenateTypedArrays(...typedArrays) { const arrays = typedArrays; const TypedArrayConstructor = arrays && arrays.length > 1 && arrays[0].constructor || null; if (!TypedArrayConstructor) { throw new Error('"concatenateTypedArrays" - incorrect quantity of arguments or arguments have incompatible data types'); } const sumLength = arrays.reduce((acc, value) => acc + value.length, 0); const result = new TypedArrayConstructor(sumLength); let offset = 0; for (const array of arrays) { result.set(array, offset); offset += array.length; } return result; } function sliceArrayBuffer(arrayBuffer, byteOffset, byteLength) { const subArray = byteLength !== void 0 ? new Uint8Array(arrayBuffer).subarray(byteOffset, byteOffset + byteLength) : new Uint8Array(arrayBuffer).subarray(byteOffset); const arrayCopy = new Uint8Array(subArray); return arrayCopy.buffer; } // ../../node_modules/@loaders.gl/loader-utils/dist/lib/binary-utils/memory-copy-utils.js function padToNBytes(byteLength, padding) { assert2(byteLength >= 0); assert2(padding > 0); return byteLength + (padding - 1) & ~(padding - 1); } function copyToArray(source, target, targetOffset) { let sourceArray; if (source instanceof ArrayBuffer) { sourceArray = new Uint8Array(source); } else { const srcByteOffset = source.byteOffset; const srcByteLength = source.byteLength; sourceArray = new Uint8Array(source.buffer || source.arrayBuffer, srcByteOffset, srcByteLength); } target.set(sourceArray, targetOffset); return targetOffset + padToNBytes(sourceArray.byteLength, 4); } // ../../node_modules/@probe.gl/stats/dist/utils/hi-res-timestamp.js function getHiResTimestamp2() { let timestamp; if (typeof window !== "undefined" && window.performance) { timestamp = window.performance.now(); } else if (typeof process !== "undefined" && process.hrtime) { const timeParts = process.hrtime(); timestamp = timeParts[0] * 1e3 + timeParts[1] / 1e6; } else { timestamp = Date.now(); } return timestamp; } // ../../node_modules/@probe.gl/stats/dist/lib/stat.js var Stat = class { constructor(name12, type) { this.sampleSize = 1; this.time = 0; this.count = 0; this.samples = 0; this.lastTiming = 0; this.lastSampleTime = 0; this.lastSampleCount = 0; this._count = 0; this._time = 0; this._samples = 0; this._startTime = 0; this._timerPending = false; this.name = name12; this.type = type; this.reset(); } reset() { this.time = 0; this.count = 0; this.samples = 0; this.lastTiming = 0; this.lastSampleTime = 0; this.lastSampleCount = 0; this._count = 0; this._time = 0; this._samples = 0; this._startTime = 0; this._timerPending = false; return this; } setSampleSize(samples) { this.sampleSize = samples; return this; } incrementCount() { this.addCount(1); return this; } decrementCount() { this.subtractCount(1); return this; } addCount(value) { this._count += value; this._samples++; this._checkSampling(); return this; } subtractCount(value) { this._count -= value; this._samples++; this._checkSampling(); return this; } addTime(time) { this._time += time; this.lastTiming = time; this._samples++; this._checkSampling(); return this; } timeStart() { this._startTime = getHiResTimestamp2(); this._timerPending = true; return this; } timeEnd() { if (!this._timerPending) { return this; } this.addTime(getHiResTimestamp2() - this._startTime); this._timerPending = false; this._checkSampling(); return this; } getSampleAverageCount() { return this.sampleSize > 0 ? this.lastSampleCount / this.sampleSize : 0; } getSampleAverageTime() { return this.sampleSize > 0 ? this.lastSampleTime / this.sampleSize : 0; } getSampleHz() { return this.lastSampleTime > 0 ? this.sampleSize / (this.lastSampleTime / 1e3) : 0; } getAverageCount() { return this.samples > 0 ? this.count / this.samples : 0; } getAverageTime() { return this.samples > 0 ? this.time / this.samples : 0; } getHz() { return this.time > 0 ? this.samples / (this.time / 1e3) : 0; } _checkSampling() { if (this._samples === this.sampleSize) { this.lastSampleTime = this._time; this.lastSampleCount = this._count; this.count += this._count; this.time += this._time; this.samples += this._samples; this._time = 0; this._count = 0; this._samples = 0; } } }; // ../../node_modules/@probe.gl/stats/dist/lib/stats.js var Stats = class { constructor(options) { this.stats = {}; this.id = options.id; this.stats = {}; this._initializeStats(options.stats); Object.seal(this); } get(name12, type = "count") { return this._getOrCreate({ name: name12, type }); } get size() { return Object.keys(this.stats).length; } reset() { for (const stat of Object.values(this.stats)) { stat.reset(); } return this; } forEach(fn) { for (const stat of Object.values(this.stats)) { fn(stat); } } getTable() { const table = {}; this.forEach((stat) => { table[stat.name] = { time: stat.time || 0, count: stat.count || 0, average: stat.getAverageTime() || 0, hz: stat.getHz() || 0 }; }); return table; } _initializeStats(stats = []) { stats.forEach((stat) => this._getOrCreate(stat)); } _getOrCreate(stat) { const { name: name12, type } = stat; let result = this.stats[name12]; if (!result) { if (stat instanceof Stat) { result = stat; } else { result = new Stat(name12, type); } this.stats[name12] = result; } return result; } }; // ../../node_modules/@loaders.gl/loader-utils/dist/lib/request-utils/request-scheduler.js var STAT_QUEUED_REQUESTS = "Queued Requests"; var STAT_ACTIVE_REQUESTS = "Active Requests"; var STAT_CANCELLED_REQUESTS = "Cancelled Requests"; var STAT_QUEUED_REQUESTS_EVER = "Queued Requests Ever"; var STAT_ACTIVE_REQUESTS_EVER = "Active Requests Ever"; var DEFAULT_PROPS = { id: "request-scheduler", throttleRequests: true, maxRequests: 6, debounceTime: 0 }; var RequestScheduler = class { props; stats; activeRequestCount = 0; requestQueue = []; requestMap = /* @__PURE__ */ new Map(); updateTimer = null; constructor(props = {}) { this.props = { ...DEFAULT_PROPS, ...props }; this.stats = new Stats({ id: this.props.id }); this.stats.get(STAT_QUEUED_REQUESTS); this.stats.get(STAT_ACTIVE_REQUESTS); this.stats.get(STAT_CANCELLED_REQUESTS); this.stats.get(STAT_QUEUED_REQUESTS_EVER); this.stats.get(STAT_ACTIVE_REQUESTS_EVER); } scheduleRequest(handle, getPriority = () => 0) { if (!this.props.throttleRequests) { return Promise.resolve({ done: () => { } }); } if (this.requestMap.has(handle)) { return this.requestMap.get(handle); } const request = { handle, priority: 0, getPriority }; const promise = new Promise((resolve2) => { request.resolve = resolve2; return request; }); this.requestQueue.push(request); this.requestMap.set(handle, promise); this._issueNewRequests(); return promise; } _issueRequest(request) { const { handle, resolve: resolve2 } = request; let isDone = false; const done = () => { if (!isDone) { isDone = true; this.requestMap.delete(handle); this.activeRequestCount--; this._issueNewRequests(); } }; this.activeRequestCount++; return resolve2 ? resolve2({ done }) : Promise.resolve({ done }); } _issueNewRequests() { if (this.updateTimer !== null) { clearTimeout(this.updateTimer); } this.updateTimer = setTimeout(() => this._issueNewRequestsAsync(), this.props.debounceTime); } _issueNewRequestsAsync() { if (this.updateTimer !== null) { clearTimeout(this.updateTimer); } this.updateTimer = null; const freeSlots = Math.max(this.props.maxRequests - this.activeRequestCount, 0); if (freeSlots === 0) { return; } this._updateAllRequests(); for (let i3 = 0; i3 < freeSlots; ++i3) { const request = this.requestQueue.shift(); if (request) { this._issueRequest(request); } } } _updateAllRequests() { const requestQueue = this.requestQueue; for (let i3 = 0; i3 < requestQueue.length; ++i3) { const request = requestQueue[i3]; if (!this._updateRequest(request)) { requestQueue.splice(i3, 1); this.requestMap.delete(request.handle); i3--; } } requestQueue.sort((a2, b) => a2.priority - b.priority); } _updateRequest(request) { request.priority = request.getPriority(request.handle); if (request.priority < 0) { request.resolve(null); return false; } return true; } }; // ../../node_modules/@loaders.gl/loader-utils/dist/lib/path-utils/path.js var path_exports = {}; __export(path_exports, { dirname: () => dirname, filename: () => filename, join: () => join, resolve: () => resolve }); // ../../node_modules/@loaders.gl/loader-utils/dist/lib/path-utils/get-cwd.js function getCWD() { if (typeof process !== "undefined" && typeof process.cwd !== "undefined") { return process.cwd(); } const pathname = window.location?.pathname; return pathname?.slice(0, pathname.lastIndexOf("/") + 1) || ""; } // ../../node_modules/@loaders.gl/loader-utils/dist/lib/path-utils/path.js function filename(url) { const slashIndex = url ? url.lastIndexOf("/") : -1; return slashIndex >= 0 ? url.substr(slashIndex + 1) : ""; } function dirname(url) { const slashIndex = url ? url.lastIndexOf("/") : -1; return slashIndex >= 0 ? url.substr(0, slashIndex) : ""; } function join(...parts) { const separator = "/"; parts = parts.map((part, index) => { if (index) { part = part.replace(new RegExp(`^${separator}`), ""); } if (index !== parts.length - 1) { part = part.replace(new RegExp(`${separator}$`), ""); } return part; }); return parts.join(separator); } function resolve(...components) { const paths = []; for (let _i = 0; _i < components.length; _i++) { paths[_i] = components[_i]; } let resolvedPath = ""; let resolvedAbsolute = false; let cwd; for (let i3 = paths.length - 1; i3 >= -1 && !resolvedAbsolute; i3--) { let path; if (i3 >= 0) { path = paths[i3]; } else { if (cwd === void 0) { cwd = getCWD(); } path = cwd; } if (path.length === 0) { continue; } resolvedPath = `${path}/${resolvedPath}`; resolvedAbsolute = path.charCodeAt(0) === SLASH; } resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute); if (resolvedAbsolute) { return `/${resolvedPath}`; } else if (resolvedPath.length > 0) { return resolvedPath; } return "."; } var SLASH = 47; var DOT = 46; function normalizeStringPosix(path, allowAboveRoot) { let res = ""; let lastSlash = -1; let dots = 0; let code; let isAboveRoot = false; for (let i3 = 0; i3 <= path.length; ++i3) { if (i3 < path.length) { code = path.charCodeAt(i3); } else if (code === SLASH) { break; } else { code = SLASH; } if (code === SLASH) { if (lastSlash === i3 - 1 || dots === 1) { } else if (lastSlash !== i3 - 1 && dots === 2) { if (res.length < 2 || !isAboveRoot || res.charCodeAt(res.length - 1) !== DOT || res.charCodeAt(res.length - 2) !== DOT) { if (res.length > 2) { const start = res.length - 1; let j = start; for (; j >= 0; --j) { if (res.charCodeAt(j) === SLASH) { break; } } if (j !== start) { res = j === -1 ? "" : res.slice(0, j); lastSlash = i3; dots = 0; isAboveRoot = false; continue; } } else if (res.length === 2 || res.length === 1) { res = ""; lastSlash = i3; dots = 0; isAboveRoot = false; continue; } } if (allowAboveRoot) { if (res.length > 0) { res += "/.."; } else { res = ".."; } isAboveRoot = true; } } else { const slice = path.slice(lastSlash + 1, i3); if (res.length > 0) { res += `/${slice}`; } else { res = slice; } isAboveRoot = false; } lastSlash = i3; dots = 0; } else if (code === DOT && dots !== -1) { ++dots; } else { dots = -1; } } return res; } // ../../node_modules/@loaders.gl/loader-utils/dist/lib/sources/data-source.js var DataSource = class { fetch; loadOptions; _needsRefresh = true; props; constructor(props) { this.props = { ...props }; this.loadOptions = { ...props.loadOptions }; this.fetch = getFetchFunction(this.loadOptions); } setProps(props) { this.props = Object.assign(this.props, props); this.setNeedsRefresh(); } setNeedsRefresh() { this._needsRefresh = true; } getNeedsRefresh(clear = true) { const needsRefresh = this._needsRefresh; if (clear) { this._needsRefresh = false; } return needsRefresh; } }; function getFetchFunction(options) { const fetchFunction = options?.fetch; if (fetchFunction && typeof fetchFunction === "function") { return (url, fetchOptions2) => fetchFunction(url, fetchOptions2); } const fetchOptions = options?.fetch; if (fetchOptions && typeof fetchOptions !== "function") { return (url) => fetch(url, fetchOptions); } return (url) => fetch(url); } // ../../node_modules/@loaders.gl/loader-utils/dist/lib/sources/image-source.js var ImageSource = class extends DataSource { }; __publicField(ImageSource, "type", "template"); __publicField(ImageSource, "testURL", (url) => false); // ../../node_modules/@loaders.gl/wms/dist/lib/parsers/wms/parse-wms-error.js function parseWMSError(text, options) { const parsedXML = XMLLoader.parseTextSync?.(text, options); const serviceExceptionXML = parsedXML?.ServiceExceptionReport?.ServiceException || parsedXML?.["ogc:ServiceExceptionReport"]?.["ogc:ServiceException"]; const message = typeof serviceExceptionXML === "string" ? serviceExceptionXML : serviceExceptionXML.value || serviceExceptionXML.code || "Unknown error"; return message; } // ../../node_modules/@loaders.gl/wms/dist/wms-error-loader.js var VERSION4 = true ? "4.2.0-beta.2" : "latest"; var WMSErrorLoader = { dataType: null, batchType: null, id: "wms-error", name: "WMS Error", module: "wms", version: VERSION4, worker: false, extensions: ["xml"], mimeTypes: ["application/vnd.ogc.se_xml", "application/xml", "text/xml"], testText: testXMLFile2, options: { wms: { throwOnError: false } }, parse: async (arrayBuffer, options) => parseTextSync(new TextDecoder().decode(arrayBuffer), options), parseSync: (arrayBuffer, options) => parseTextSync(new TextDecoder().decode(arrayBuffer), options), parseTextSync: (text, options) => parseTextSync(text, options) }; function testXMLFile2(text) { return text.startsWith(" 0 && xmlArray.every((_) => typeof _ === "string")) { return xmlArray; } return []; } function getXMLFloat(xmlValue, defaultValue2 = void 0) { switch (typeof xmlValue) { case "number": return xmlValue; case "string": return parseFloat(xmlValue); default: return void 0; } } function getXMLInteger(xmlValue, defaultValue2 = void 0) { switch (typeof xmlValue) { case "number": return xmlValue; case "string": return parseInt(xmlValue, 10); default: return void 0; } } function getXMLBoolean(xmlValue) { switch (xmlValue) { case "true": return true; case "false": return false; case "1": return true; case "0": return false; default: return false; } } // ../../node_modules/@loaders.gl/wms/dist/lib/parsers/wms/parse-wms-capabilities.js function parseWMSCapabilities(xmlText, options) { const parsedXML = XMLLoader.parseTextSync?.(xmlText, options); const xmlCapabilities = parsedXML.WMT_MS_Capabilities || parsedXML.WMS_Capabilities || parsedXML; const capabilities = extractCapabilities(xmlCapabilities); if (options?.inheritedLayerProps) { for (const layer of capabilities.layers) { addInheritedLayerProps(layer, null); } } if (options?.includeRawJSON) { capabilities.json = xmlCapabilities; } if (options?.includeXMLText) { capabilities.xml = xmlText; } return capabilities; } function extractCapabilities(xml) { const capabilities = { version: String(xml.version || ""), name: String(xml.Service?.Name || "unnamed"), title: xml.Service?.Title ? String(xml.Service?.Title) : void 0, abstract: xml.Service?.Abstract ? String(xml.Service?.Abstract) : void 0, keywords: getXMLStringArray(xml.Service?.KeywordList?.Keyword), fees: xml.Service?.Fees ? JSON.stringify(xml.Service?.Fees) : void 0, accessConstraints: xml.Service?.AccessConstraints ? JSON.stringify(xml.Service?.AccessConstraints) : void 0, layerLimit: getXMLInteger(xml.Service?.LayerLimit), maxWidth: getXMLInteger(xml.Service?.maxWidth), maxHeight: getXMLInteger(xml.Service?.maxHeight), layers: [], requests: extractRequests(xml.Capability?.Request), exceptions: extractExceptions(xml.Exception) }; const xmlLayers = getXMLArray(xml.Capability?.Layer); for (const xmlSubLayer of xmlLayers) { capabilities.layers.push(extractLayer(xmlSubLayer)); } for (const [key, value] of Object.entries(capabilities)) { if (value === void 0) { delete capabilities[key]; } } return capabilities; } function extractRequests(xmlRequests) { const requests = {}; for (const [name12, xmlRequest] of Object.entries(xmlRequests || {})) { const mimeTypes = getXMLStringArray(xmlRequest?.Format); requests[name12] = { mimeTypes }; } return requests; } function extractExceptions(xmlException) { const xmlExceptionFormats = getXMLArray(xmlException?.Format); if (xmlExceptionFormats.length > 0) { return { mimeTypes: getXMLStringArray(xmlException) }; } return void 0; } function extractLayer(xmlLayer) { const layer = { title: String(xmlLayer?.Title || ""), name: xmlLayer?.Name && String(xmlLayer?.Name), abstract: xmlLayer?.Name && String(xmlLayer?.Abstract), keywords: getXMLStringArray(xmlLayer.KeywordList?.Keyword) }; const crs = xmlLayer?.CRS || xmlLayer?.SRS; if (crs && Array.isArray(crs) && crs.every((_) => typeof _ === "string")) { layer.crs = crs; } let geographicBoundingBox = xmlLayer?.EX_GeographicBoundingBox && extractEXBoundingBox(xmlLayer?.EX_GeographicBoundingBox); if (geographicBoundingBox) { layer.geographicBoundingBox = geographicBoundingBox; } geographicBoundingBox = xmlLayer?.LatLonBoundingBox && extractLatLonBoundingBox(xmlLayer?.LatLonBoundingBox); if (geographicBoundingBox) { layer.geographicBoundingBox = geographicBoundingBox; } const boundingBoxes = xmlLayer?.BoundingBox && extractWMSBoundingBoxes(xmlLayer?.BoundingBox); if (boundingBoxes && boundingBoxes.length > 0) { layer.boundingBoxes = boundingBoxes; } const xmlDimensions = getXMLArray(xmlLayer?.Dimension); const dimensions = xmlDimensions.map((xml) => extractDimension(xml)); if (dimensions.length) { layer.dimensions = dimensions; } if (xmlLayer?.opaque) { layer.opaque = getXMLBoolean(xmlLayer?.opaque); } if (xmlLayer?.cascaded) { layer.cascaded = getXMLBoolean(xmlLayer?.cascaded); } if (xmlLayer?.queryable) { layer.queryable = getXMLBoolean(xmlLayer?.queryable); } const xmlLayers = getXMLArray(xmlLayer?.Layer); const layers = []; for (const xmlSubLayer of xmlLayers) { layers.push(extractLayer(xmlSubLayer)); } if (layers.length > 0) { layer.layers = layers; } for (const [key, value] of Object.entries(layer)) { if (value === void 0) { delete layer[key]; } } return layer; } function extractEXBoundingBox(xmlBoundingBox) { const { westBoundLongitude: w, northBoundLatitude: n2, eastBoundLongitude: e, southBoundLatitude: s2 } = xmlBoundingBox; return [ [w, s2], [e, n2] ]; } function extractLatLonBoundingBox(xmlBoundingBox) { const { minx, miny, maxx, maxy } = xmlBoundingBox; return [ [minx, miny], [maxx, maxy] ]; } function extractWMSBoundingBoxes(xmlBoundingBoxes) { const xmlBoxes = getXMLArray(xmlBoundingBoxes); return xmlBoxes.map((xmlBox) => extractWMSBoundingBox(xmlBox)); } function extractWMSBoundingBox(xmlBoundingBox) { const { CRS, SRS, minx, miny, maxx, maxy, resx, resy } = xmlBoundingBox; const boundingBox = { crs: CRS || SRS, boundingBox: [ [getXMLFloat(minx), getXMLFloat(miny)], [getXMLFloat(maxx), getXMLFloat(maxy)] ] }; if (resx) { boundingBox.xResolution = resx; } if (resy) { boundingBox.yResolution = resy; } return boundingBox; } function extractDimension(xmlDimension) { const { name: name12, units, value: extent } = xmlDimension; const dimension = { name: name12, units, extent }; if (xmlDimension.unitSymbol) { dimension.unitSymbol = xmlDimension.unitSymbol; } if (xmlDimension.default) { dimension.defaultValue = xmlDimension.default; } if (xmlDimension.multipleValues) { dimension.multipleValues = getXMLBoolean(xmlDimension.multipleValues); } if (xmlDimension.nearestValue) { dimension.nearestValue = getXMLBoolean(xmlDimension.nearestValue); } if (xmlDimension.current) { dimension.current = getXMLBoolean(xmlDimension.current); } return dimension; } function addInheritedLayerProps(layer, parent) { if (parent?.geographicBoundingBox && !layer.geographicBoundingBox) { layer.geographicBoundingBox = [...parent.geographicBoundingBox]; } if (parent?.crs && !layer.crs) { layer.crs = [...parent.crs]; } if (parent?.boundingBoxes && !layer.boundingBoxes) { layer.boundingBoxes = [...parent.boundingBoxes]; } if (parent?.dimensions && !layer.dimensions) { layer.dimensions = [...parent.dimensions]; } for (const subLayer of layer.layers || []) { addInheritedLayerProps(subLayer, layer); } } // ../../node_modules/@loaders.gl/wms/dist/wms-capabilities-loader.js var VERSION5 = true ? "4.2.0-beta.2" : "latest"; var WMSCapabilitiesLoader = { dataType: null, batchType: null, id: "wms-capabilities", name: "WMS Capabilities", module: "wms", version: VERSION5, worker: false, extensions: ["xml"], mimeTypes: ["application/vnd.ogc.wms_xml", "application/xml", "text/xml"], testText: testXMLFile3, options: { wms: {} }, parse: async (arrayBuffer, options) => parseWMSCapabilities(new TextDecoder().decode(arrayBuffer), options?.wms), parseTextSync: (text, options) => parseWMSCapabilities(text, options?.wms) }; function testXMLFile3(text) { return text.startsWith(" extractFeature(xmlFeature)) }; } function extractFeature(xmlFeature) { const xmlFields = xmlFeature || {}; return { attributes: xmlFields, type: "", bounds: { bottom: 0, top: 0, left: 0, right: 0 } }; } // ../../node_modules/@loaders.gl/wms/dist/wip/wms-feature-info-loader.js var WMSFeatureInfoLoader = { ...WMSCapabilitiesLoader, dataType: null, id: "wms-feature-info", name: "WMS FeatureInfo", parse: async (arrayBuffer, options) => parseWMSFeatureInfo(new TextDecoder().decode(arrayBuffer), options), parseTextSync: (text, options) => parseWMSFeatureInfo(text, options) }; // ../../node_modules/@loaders.gl/wms/dist/lib/parsers/wms/parse-wms-layer-description.js function parseWMSLayerDescription(text, options) { const parsedXML = XMLLoader.parseTextSync?.(text, options); return parsedXML; } // ../../node_modules/@loaders.gl/wms/dist/wip/wms-layer-description-loader.js var WMSLayerDescriptionLoader = { ...WMSCapabilitiesLoader, dataType: null, id: "wms-layer-description", name: "WMS DescribeLayer", parse: async (arrayBuffer, options) => parseWMSLayerDescription(new TextDecoder().decode(arrayBuffer), options), parseTextSync: (text, options) => parseWMSLayerDescription(text, options) }; // ../../node_modules/@loaders.gl/wms/dist/lib/services/create-image-service.js function createImageService(props, services) { const { type = "auto" } = props; const service = type === "auto" ? guessServiceType(props.url, services) : getServiceOfType(type, services); if (!service) { throw new Error("Not a valid image source type"); } return service.create(props); } function getServiceOfType(type, services) { for (const service of services) { if (service.type === type) { return service; } } return null; } function guessServiceType(url, services) { for (const service of services) { if (service.testURL && service.testURL(url)) { return service; } } return null; } // ../../node_modules/@loaders.gl/images/dist/lib/utils/version.js var VERSION6 = true ? "4.2.0-beta.2" : "latest"; // ../../node_modules/@loaders.gl/images/dist/lib/category-api/image-type.js var parseImageNode = globalThis.loaders?.parseImageNode; var IMAGE_SUPPORTED = typeof Image !== "undefined"; var IMAGE_BITMAP_SUPPORTED = typeof ImageBitmap !== "undefined"; var NODE_IMAGE_SUPPORTED = Boolean(parseImageNode); var DATA_SUPPORTED = isBrowser ? true : NODE_IMAGE_SUPPORTED; function isImageTypeSupported(type) { switch (type) { case "auto": return IMAGE_BITMAP_SUPPORTED || IMAGE_SUPPORTED || DATA_SUPPORTED; case "imagebitmap": return IMAGE_BITMAP_SUPPORTED; case "image": return IMAGE_SUPPORTED; case "data": return DATA_SUPPORTED; default: throw new Error(`@loaders.gl/images: image ${type} not supported in this environment`); } } function getDefaultImageType() { if (IMAGE_BITMAP_SUPPORTED) { return "imagebitmap"; } if (IMAGE_SUPPORTED) { return "image"; } if (DATA_SUPPORTED) { return "data"; } throw new Error("Install '@loaders.gl/polyfills' to parse images under Node.js"); } // ../../node_modules/@loaders.gl/images/dist/lib/category-api/parsed-image-api.js function getImageType(image) { const format = getImageTypeOrNull(image); if (!format) { throw new Error("Not an image"); } return format; } function getImageData(image) { switch (getImageType(image)) { case "data": return image; case "image": case "imagebitmap": const canvas = document.createElement("canvas"); const context = canvas.getContext("2d"); if (!context) { throw new Error("getImageData"); } canvas.width = image.width; canvas.height = image.height; context.drawImage(image, 0, 0); return context.getImageData(0, 0, image.width, image.height); default: throw new Error("getImageData"); } } function getImageTypeOrNull(image) { if (typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) { return "imagebitmap"; } if (typeof Image !== "undefined" && image instanceof Image) { return "image"; } if (image && typeof image === "object" && image.data && image.width && image.height) { return "data"; } return null; } // ../../node_modules/@loaders.gl/images/dist/lib/parsers/svg-utils.js var SVG_DATA_URL_PATTERN = /^data:image\/svg\+xml/; var SVG_URL_PATTERN = /\.svg((\?|#).*)?$/; function isSVG(url) { return url && (SVG_DATA_URL_PATTERN.test(url) || SVG_URL_PATTERN.test(url)); } function getBlobOrSVGDataUrl(arrayBuffer, url) { if (isSVG(url)) { const textDecoder = new TextDecoder(); let xmlText = textDecoder.decode(arrayBuffer); try { if (typeof unescape === "function" && typeof encodeURIComponent === "function") { xmlText = unescape(encodeURIComponent(xmlText)); } } catch (error) { throw new Error(error.message); } const src = `data:image/svg+xml;base64,${btoa(xmlText)}`; return src; } return getBlob(arrayBuffer, url); } function getBlob(arrayBuffer, url) { if (isSVG(url)) { throw new Error("SVG cannot be parsed directly to imagebitmap"); } return new Blob([new Uint8Array(arrayBuffer)]); } // ../../node_modules/@loaders.gl/images/dist/lib/parsers/parse-to-image.js async function parseToImage(arrayBuffer, options, url) { const blobOrDataUrl = getBlobOrSVGDataUrl(arrayBuffer, url); const URL2 = self.URL || self.webkitURL; const objectUrl = typeof blobOrDataUrl !== "string" && URL2.createObjectURL(blobOrDataUrl); try { return await loadToImage(objectUrl || blobOrDataUrl, options); } finally { if (objectUrl) { URL2.revokeObjectURL(objectUrl); } } } async function loadToImage(url, options) { const image = new Image(); image.src = url; if (options.image && options.image.decode && image.decode) { await image.decode(); return image; } return await new Promise((resolve2, reject) => { try { image.onload = () => resolve2(image); image.onerror = (error) => { const message = error instanceof Error ? error.message : "error"; reject(new Error(message)); }; } catch (error) { reject(error); } }); } // ../../node_modules/@loaders.gl/images/dist/lib/parsers/parse-to-image-bitmap.js var EMPTY_OBJECT = {}; var imagebitmapOptionsSupported = true; async function parseToImageBitmap(arrayBuffer, options, url) { let blob; if (isSVG(url)) { const image = await parseToImage(arrayBuffer, options, url); blob = image; } else { blob = getBlob(arrayBuffer, url); } const imagebitmapOptions = options && options.imagebitmap; return await safeCreateImageBitmap(blob, imagebitmapOptions); } async function safeCreateImageBitmap(blob, imagebitmapOptions = null) { if (isEmptyObject(imagebitmapOptions) || !imagebitmapOptionsSupported) { imagebitmapOptions = null; } if (imagebitmapOptions) { try { return await createImageBitmap(blob, imagebitmapOptions); } catch (error) { console.warn(error); imagebitmapOptionsSupported = false; } } return await createImageBitmap(blob); } function isEmptyObject(object) { for (const key in object || EMPTY_OBJECT) { return false; } return true; } // ../../node_modules/@loaders.gl/images/dist/lib/category-api/parse-isobmff-binary.js function getISOBMFFMediaType(buffer) { if (!checkString(buffer, "ftyp", 4)) { return null; } if ((buffer[8] & 96) === 0) { return null; } return decodeMajorBrand(buffer); } function decodeMajorBrand(buffer) { const brandMajor = getUTF8String(buffer, 8, 12).replace("\0", " ").trim(); switch (brandMajor) { case "avif": case "avis": return { extension: "avif", mimeType: "image/avif" }; default: return null; } } function getUTF8String(array, start, end) { return String.fromCharCode(...array.slice(start, end)); } function stringToBytes(string) { return [...string].map((character) => character.charCodeAt(0)); } function checkString(buffer, header, offset = 0) { const headerBytes = stringToBytes(header); for (let i3 = 0; i3 < headerBytes.length; ++i3) { if (headerBytes[i3] !== buffer[i3 + offset]) { return false; } } return true; } // ../../node_modules/@loaders.gl/images/dist/lib/category-api/binary-image-api.js var BIG_ENDIAN = false; var LITTLE_ENDIAN = true; function getBinaryImageMetadata(binaryData) { const dataView = toDataView(binaryData); return getPngMetadata(dataView) || getJpegMetadata(dataView) || getGifMetadata(dataView) || getBmpMetadata(dataView) || getISOBMFFMetadata(dataView); } function getISOBMFFMetadata(binaryData) { const buffer = new Uint8Array(binaryData instanceof DataView ? binaryData.buffer : binaryData); const mediaType = getISOBMFFMediaType(buffer); if (!mediaType) { return null; } return { mimeType: mediaType.mimeType, width: 0, height: 0 }; } function getPngMetadata(binaryData) { const dataView = toDataView(binaryData); const isPng = dataView.byteLength >= 24 && dataView.getUint32(0, BIG_ENDIAN) === 2303741511; if (!isPng) { return null; } return { mimeType: "image/png", width: dataView.getUint32(16, BIG_ENDIAN), height: dataView.getUint32(20, BIG_ENDIAN) }; } function getGifMetadata(binaryData) { const dataView = toDataView(binaryData); const isGif = dataView.byteLength >= 10 && dataView.getUint32(0, BIG_ENDIAN) === 1195984440; if (!isGif) { return null; } return { mimeType: "image/gif", width: dataView.getUint16(6, LITTLE_ENDIAN), height: dataView.getUint16(8, LITTLE_ENDIAN) }; } function getBmpMetadata(binaryData) { const dataView = toDataView(binaryData); const isBmp = dataView.byteLength >= 14 && dataView.getUint16(0, BIG_ENDIAN) === 16973 && dataView.getUint32(2, LITTLE_ENDIAN) === dataView.byteLength; if (!isBmp) { return null; } return { mimeType: "image/bmp", width: dataView.getUint32(18, LITTLE_ENDIAN), height: dataView.getUint32(22, LITTLE_ENDIAN) }; } function getJpegMetadata(binaryData) { const dataView = toDataView(binaryData); const isJpeg = dataView.byteLength >= 3 && dataView.getUint16(0, BIG_ENDIAN) === 65496 && dataView.getUint8(2) === 255; if (!isJpeg) { return null; } const { tableMarkers, sofMarkers } = getJpegMarkers(); let i3 = 2; while (i3 + 9 < dataView.byteLength) { const marker2 = dataView.getUint16(i3, BIG_ENDIAN); if (sofMarkers.has(marker2)) { return { mimeType: "image/jpeg", height: dataView.getUint16(i3 + 5, BIG_ENDIAN), width: dataView.getUint16(i3 + 7, BIG_ENDIAN) }; } if (!tableMarkers.has(marker2)) { return null; } i3 += 2; i3 += dataView.getUint16(i3, BIG_ENDIAN); } return null; } function getJpegMarkers() { const tableMarkers = /* @__PURE__ */ new Set([65499, 65476, 65484, 65501, 65534]); for (let i3 = 65504; i3 < 65520; ++i3) { tableMarkers.add(i3); } const sofMarkers = /* @__PURE__ */ new Set([ 65472, 65473, 65474, 65475, 65477, 65478, 65479, 65481, 65482, 65483, 65485, 65486, 65487, 65502 ]); return { tableMarkers, sofMarkers }; } function toDataView(data) { if (data instanceof DataView) { return data; } if (ArrayBuffer.isView(data)) { return new DataView(data.buffer); } if (data instanceof ArrayBuffer) { return new DataView(data); } throw new Error("toDataView"); } // ../../node_modules/@loaders.gl/images/dist/lib/parsers/parse-to-node-image.js async function parseToNodeImage(arrayBuffer, options) { const { mimeType } = getBinaryImageMetadata(arrayBuffer) || {}; const parseImageNode2 = globalThis.loaders?.parseImageNode; assert2(parseImageNode2); return await parseImageNode2(arrayBuffer, mimeType); } // ../../node_modules/@loaders.gl/images/dist/lib/parsers/parse-image.js async function parseImage(arrayBuffer, options, context) { options = options || {}; const imageOptions = options.image || {}; const imageType = imageOptions.type || "auto"; const { url } = context || {}; const loadType = getLoadableImageType(imageType); let image; switch (loadType) { case "imagebitmap": image = await parseToImageBitmap(arrayBuffer, options, url); break; case "image": image = await parseToImage(arrayBuffer, options, url); break; case "data": image = await parseToNodeImage(arrayBuffer, options); break; default: assert2(false); } if (imageType === "data") { image = getImageData(image); } return image; } function getLoadableImageType(type) { switch (type) { case "auto": case "data": return getDefaultImageType(); default: isImageTypeSupported(type); return type; } } // ../../node_modules/@loaders.gl/images/dist/image-loader.js var EXTENSIONS = ["png", "jpg", "jpeg", "gif", "webp", "bmp", "ico", "svg", "avif"]; var MIME_TYPES = [ "image/png", "image/jpeg", "image/gif", "image/webp", "image/avif", "image/bmp", "image/vnd.microsoft.icon", "image/svg+xml" ]; var DEFAULT_IMAGE_LOADER_OPTIONS = { image: { type: "auto", decode: true } }; var ImageLoader = { dataType: null, batchType: null, id: "image", module: "images", name: "Images", version: VERSION6, mimeTypes: MIME_TYPES, extensions: EXTENSIONS, parse: parseImage, tests: [(arrayBuffer) => Boolean(getBinaryImageMetadata(new DataView(arrayBuffer)))], options: DEFAULT_IMAGE_LOADER_OPTIONS }; // ../../node_modules/@loaders.gl/images/dist/lib/category-api/image-format.js var mimeTypeSupportedSync = {}; function isImageFormatSupported(mimeType) { if (mimeTypeSupportedSync[mimeType] === void 0) { const supported = isBrowser ? checkBrowserImageFormatSupport(mimeType) : checkNodeImageFormatSupport(mimeType); mimeTypeSupportedSync[mimeType] = supported; } return mimeTypeSupportedSync[mimeType]; } function checkNodeImageFormatSupport(mimeType) { const NODE_FORMAT_SUPPORT = ["image/png", "image/jpeg", "image/gif"]; const imageFormatsNode = globalThis.loaders?.imageFormatsNode || NODE_FORMAT_SUPPORT; const parseImageNode2 = globalThis.loaders?.parseImageNode; return Boolean(parseImageNode2) && imageFormatsNode.includes(mimeType); } function checkBrowserImageFormatSupport(mimeType) { switch (mimeType) { case "image/avif": case "image/webp": return testBrowserImageFormatSupport(mimeType); default: return true; } } function testBrowserImageFormatSupport(mimeType) { try { const element = document.createElement("canvas"); const dataURL = element.toDataURL(mimeType); return dataURL.indexOf(`data:${mimeType}`) === 0; } catch { return false; } } // ../../node_modules/@loaders.gl/wms/dist/services/ogc/wms-service.js var WMSService = { type: "wms", testURL: (url) => url.toLowerCase().includes("wms"), create: (props) => new WMSSource(props) }; var WMSSource = class extends ImageSource { url; data; substituteCRS84; flipCRS; wmsParameters; vendorParameters; capabilities = null; constructor(props) { super(props); this.url = props.url; this.data = props.url; this.substituteCRS84 = props.substituteCRS84 ?? false; this.flipCRS = ["EPSG:4326"]; this.wmsParameters = { layers: void 0, query_layers: void 0, styles: void 0, version: "1.3.0", crs: "EPSG:4326", format: "image/png", info_format: "text/plain", transparent: void 0, time: void 0, elevation: void 0, ...props.wmsParameters }; this.vendorParameters = props.vendorParameters || {}; } async getMetadata() { const capabilities = await this.getCapabilities(); return this.normalizeMetadata(capabilities); } async getImage(parameters) { const { boundingBox, bbox, ...rest } = parameters; const wmsParameters = { bbox: boundingBox ? [...boundingBox[0], ...boundingBox[1]] : bbox, ...rest }; return await this.getMap(wmsParameters); } normalizeMetadata(capabilities) { return capabilities; } async getCapabilities(wmsParameters, vendorParameters) { const url = this.getCapabilitiesURL(wmsParameters, vendorParameters); const response = await this.fetch(url); const arrayBuffer = await response.arrayBuffer(); this._checkResponse(response, arrayBuffer); const capabilities = await WMSCapabilitiesLoader.parse(arrayBuffer, this.loadOptions); this.capabilities = capabilities; return capabilities; } async getMap(wmsParameters, vendorParameters) { const url = this.getMapURL(wmsParameters, vendorParameters); const response = await this.fetch(url); const arrayBuffer = await response.arrayBuffer(); this._checkResponse(response, arrayBuffer); try { return await ImageLoader.parse(arrayBuffer, this.loadOptions); } catch { throw this._parseError(arrayBuffer); } } async getFeatureInfo(wmsParameters, vendorParameters) { const url = this.getFeatureInfoURL(wmsParameters, vendorParameters); const response = await this.fetch(url); const arrayBuffer = await response.arrayBuffer(); this._checkResponse(response, arrayBuffer); return await WMSFeatureInfoLoader.parse(arrayBuffer, this.loadOptions); } async getFeatureInfoText(wmsParameters, vendorParameters) { const url = this.getFeatureInfoURL(wmsParameters, vendorParameters); const response = await this.fetch(url); const arrayBuffer = await response.arrayBuffer(); this._checkResponse(response, arrayBuffer); return new TextDecoder().decode(arrayBuffer); } async describeLayer(wmsParameters, vendorParameters) { const url = this.describeLayerURL(wmsParameters, vendorParameters); const response = await this.fetch(url); const arrayBuffer = await response.arrayBuffer(); this._checkResponse(response, arrayBuffer); return await WMSLayerDescriptionLoader.parse(arrayBuffer, this.loadOptions); } async getLegendGraphic(wmsParameters, vendorParameters) { const url = this.getLegendGraphicURL(wmsParameters, vendorParameters); const response = await this.fetch(url); const arrayBuffer = await response.arrayBuffer(); this._checkResponse(response, arrayBuffer); try { return await ImageLoader.parse(arrayBuffer, this.loadOptions); } catch { throw this._parseError(arrayBuffer); } } getCapabilitiesURL(wmsParameters, vendorParameters) { const options = { version: this.wmsParameters.version, ...wmsParameters }; return this._getWMSUrl("GetCapabilities", options, vendorParameters); } getMapURL(wmsParameters, vendorParameters) { wmsParameters = this._getWMS130Parameters(wmsParameters); const options = { version: this.wmsParameters.version, format: this.wmsParameters.format, transparent: this.wmsParameters.transparent, time: this.wmsParameters.time, elevation: this.wmsParameters.elevation, layers: this.wmsParameters.layers, styles: this.wmsParameters.styles, crs: this.wmsParameters.crs, ...wmsParameters }; return this._getWMSUrl("GetMap", options, vendorParameters); } getFeatureInfoURL(wmsParameters, vendorParameters) { wmsParameters = this._getWMS130Parameters(wmsParameters); const { boundingBox, bbox } = wmsParameters; wmsParameters.bbox = boundingBox ? [...boundingBox[0], ...boundingBox[1]] : bbox; const options = { version: this.wmsParameters.version, info_format: this.wmsParameters.info_format, layers: this.wmsParameters.layers, query_layers: this.wmsParameters.query_layers, styles: this.wmsParameters.styles, crs: this.wmsParameters.crs, ...wmsParameters }; return this._getWMSUrl("GetFeatureInfo", options, vendorParameters); } describeLayerURL(wmsParameters, vendorParameters) { const options = { version: this.wmsParameters.version, ...wmsParameters }; return this._getWMSUrl("DescribeLayer", options, vendorParameters); } getLegendGraphicURL(wmsParameters, vendorParameters) { const options = { version: this.wmsParameters.version, ...wmsParameters }; return this._getWMSUrl("GetLegendGraphic", options, vendorParameters); } _parseWMSUrl(url) { const [baseUrl, search] = url.split("?"); const searchParams = search.split("&"); const parameters = {}; for (const parameter of searchParams) { const [key, value] = parameter.split("="); parameters[key] = value; } return { url: baseUrl, parameters }; } _getWMSUrl(request, wmsParameters, vendorParameters) { let url = this.url; let first = true; const allParameters = { service: "WMS", version: wmsParameters.version, request, ...wmsParameters, ...this.vendorParameters, ...vendorParameters }; const IGNORE_EMPTY_KEYS = ["transparent", "time", "elevation"]; for (const [key, value] of Object.entries(allParameters)) { if (!IGNORE_EMPTY_KEYS.includes(key) || value) { url += first ? "?" : "&"; first = false; url += this._getURLParameter(key, value, wmsParameters); } } return encodeURI(url); } _getWMS130Parameters(wmsParameters) { const newParameters = { ...wmsParameters }; if (newParameters.srs) { newParameters.crs = newParameters.crs || newParameters.srs; delete newParameters.srs; } return newParameters; } _getURLParameter(key, value, wmsParameters) { switch (key) { case "crs": if (wmsParameters.version !== "1.3.0") { key = "srs"; } else if (this.substituteCRS84 && value === "EPSG:4326") { value = "CRS:84"; } break; case "srs": if (wmsParameters.version === "1.3.0") { key = "crs"; } break; case "bbox": const bbox = this._flipBoundingBox(value, wmsParameters); if (bbox) { value = bbox; } break; case "x": if (wmsParameters.version === "1.3.0") { key = "i"; } break; case "y": if (wmsParameters.version === "1.3.0") { key = "j"; } break; default: } key = key.toUpperCase(); return Array.isArray(value) ? `${key}=${value.join(",")}` : `${key}=${value ? String(value) : ""}`; } _flipBoundingBox(bboxValue, wmsParameters) { if (!Array.isArray(bboxValue) || bboxValue.length !== 4) { return null; } const flipCoordinates = wmsParameters.version === "1.3.0" && this.flipCRS.includes(wmsParameters.crs || "") && !(this.substituteCRS84 && wmsParameters.crs === "EPSG:4326"); const bbox = bboxValue; return flipCoordinates ? [bbox[1], bbox[0], bbox[3], bbox[2]] : bbox; } async _fetchArrayBuffer(url) { const response = await this.fetch(url); const arrayBuffer = await response.arrayBuffer(); this._checkResponse(response, arrayBuffer); return arrayBuffer; } _checkResponse(response, arrayBuffer) { const contentType = response.headers["content-type"]; if (!response.ok || WMSErrorLoader.mimeTypes.includes(contentType)) { const loadOptions = mergeLoaderOptions(this.loadOptions, { wms: { throwOnError: true } }); const error = WMSErrorLoader.parseSync?.(arrayBuffer, loadOptions); throw new Error(error); } } _parseError(arrayBuffer) { const error = WMSErrorLoader.parseSync?.(arrayBuffer, this.loadOptions); return new Error(error); } }; // ../../node_modules/@loaders.gl/wms/dist/lib/services/image-service.js var ImageService = class extends ImageSource { constructor(props) { super(props); } async getMetadata() { throw new Error("ImageSource.getMetadata not implemented"); } async getImage(parameters) { const granularParameters = this.getGranularParameters(parameters); const url = this.getURLFromTemplate(granularParameters); const response = await this.fetch(url); const arrayBuffer = await response.arrayBuffer(); return await ImageLoader.parse(arrayBuffer); } getGranularParameters(parameters) { const [[east, north], [west, south]] = parameters.boundingBox; return { ...parameters, east, north, south, west }; } getURLFromTemplate(parameters) { let url = this.props.url; for (const [key, value] of Object.entries(parameters)) { url = url.replace(`\${${key}}`, String(value)); url = url.replace(`{${key}}`, String(value)); } return url; } }; __publicField(ImageService, "type", "template"); __publicField(ImageService, "testURL", (url) => url.toLowerCase().includes("{")); // ../../node_modules/@loaders.gl/wms/dist/services/arcgis/arcgis-image-service.js var ArcGISImageSource = class extends ImageService { data; constructor(props) { super(props); this.data = props.url; } async getMetadata() { return await this.metadata(); } async getImage(parameters) { throw new Error("not implemented"); } async metadata() { throw new Error("not implemented"); } exportImage(options) { throw new Error("not implemented"); } metadataURL(options) { return `${this.props.url}?f=pjson`; } exportImageURL(options) { const bbox = `bbox=${options.bbox[0]},${options.bbox[1]},${options.bbox[2]},${options.bbox[3]}`; const size = `size=${options.width},${options.height}`; const arcgisOptions = { ...options, bbox, size }; delete arcgisOptions.width; delete arcgisOptions.height; return this.getUrl("exportImage", arcgisOptions); } getUrl(path, options, extra) { let url = `${this.props.url}/${path}`; let first = true; for (const [key, value] of Object.entries(options)) { url += first ? "?" : "&"; first = false; if (Array.isArray(value)) { url += `${key.toUpperCase()}=${value.join(",")}`; } else { url += `${key.toUpperCase()}=${value ? String(value) : ""}`; } } return url; } async checkResponse(response) { if (!response.ok) { throw new Error("error"); } } }; var ArcGISImageService = { type: "arcgis-image-server", testURL: (url) => url.toLowerCase().includes("ImageServer"), create: (props) => new ArcGISImageSource(props) }; // ../../node_modules/@loaders.gl/wms/dist/services/create-image-source.js var SERVICES = [WMSService, ArcGISImageService]; function createImageSource(props) { return createImageService(props, SERVICES); } // ../../node_modules/@math.gl/core/dist/lib/common.js var RADIANS_TO_DEGREES = 1 / Math.PI * 180; var DEGREES_TO_RADIANS = 1 / 180 * Math.PI; var DEFAULT_CONFIG = { EPSILON: 1e-12, debug: false, precision: 4, printTypes: false, printDegrees: false, printRowMajor: true, _cartographicRadians: false }; globalThis.mathgl = globalThis.mathgl || { config: { ...DEFAULT_CONFIG } }; var config = globalThis.mathgl.config; function formatValue(value, { precision = config.precision } = {}) { value = round(value); return `${parseFloat(value.toPrecision(precision))}`; } function isArray(value) { return Array.isArray(value) || ArrayBuffer.isView(value) && !(value instanceof DataView); } function toRadians(degrees2) { return radians(degrees2); } function toDegrees(radians2) { return degrees(radians2); } function radians(degrees2, result) { return map(degrees2, (degrees3) => degrees3 * DEGREES_TO_RADIANS, result); } function degrees(radians2, result) { return map(radians2, (radians3) => radians3 * RADIANS_TO_DEGREES, result); } function clamp(value, min2, max2) { return map(value, (value2) => Math.max(min2, Math.min(max2, value2))); } function lerp(a2, b, t2) { if (isArray(a2)) { return a2.map((ai, i3) => lerp(ai, b[i3], t2)); } return t2 * b + (1 - t2) * a2; } function equals(a2, b, epsilon) { const oldEpsilon = config.EPSILON; if (epsilon) { config.EPSILON = epsilon; } try { if (a2 === b) { return true; } if (isArray(a2) && isArray(b)) { if (a2.length !== b.length) { return false; } for (let i3 = 0; i3 < a2.length; ++i3) { if (!equals(a2[i3], b[i3])) { return false; } } return true; } if (a2 && a2.equals) { return a2.equals(b); } if (b && b.equals) { return b.equals(a2); } if (typeof a2 === "number" && typeof b === "number") { return Math.abs(a2 - b) <= config.EPSILON * Math.max(1, Math.abs(a2), Math.abs(b)); } return false; } finally { config.EPSILON = oldEpsilon; } } function round(value) { return Math.round(value / config.EPSILON) * config.EPSILON; } function duplicateArray(array) { return array.clone ? array.clone() : new Array(array.length); } function map(value, func, result) { if (isArray(value)) { const array = value; result = result || duplicateArray(array); for (let i3 = 0; i3 < result.length && i3 < array.length; ++i3) { const val2 = typeof value === "number" ? value : value[i3]; result[i3] = func(val2, i3, result); } return result; } return func(value); } // ../../node_modules/@math.gl/core/dist/classes/base/math-array.js var MathArray = class extends Array { clone() { return new this.constructor().copy(this); } fromArray(array, offset = 0) { for (let i3 = 0; i3 < this.ELEMENTS; ++i3) { this[i3] = array[i3 + offset]; } return this.check(); } toArray(targetArray = [], offset = 0) { for (let i3 = 0; i3 < this.ELEMENTS; ++i3) { targetArray[offset + i3] = this[i3]; } return targetArray; } toObject(targetObject) { return targetObject; } from(arrayOrObject) { return Array.isArray(arrayOrObject) ? this.copy(arrayOrObject) : this.fromObject(arrayOrObject); } to(arrayOrObject) { if (arrayOrObject === this) { return this; } return isArray(arrayOrObject) ? this.toArray(arrayOrObject) : this.toObject(arrayOrObject); } toTarget(target) { return target ? this.to(target) : this; } toFloat32Array() { return new Float32Array(this); } toString() { return this.formatString(config); } formatString(opts) { let string = ""; for (let i3 = 0; i3 < this.ELEMENTS; ++i3) { string += (i3 > 0 ? ", " : "") + formatValue(this[i3], opts); } return `${opts.printTypes ? this.constructor.name : ""}[${string}]`; } equals(array) { if (!array || this.length !== array.length) { return false; } for (let i3 = 0; i3 < this.ELEMENTS; ++i3) { if (!equals(this[i3], array[i3])) { return false; } } return true; } exactEquals(array) { if (!array || this.length !== array.length) { return false; } for (let i3 = 0; i3 < this.ELEMENTS; ++i3) { if (this[i3] !== array[i3]) { return false; } } return true; } negate() { for (let i3 = 0; i3 < this.ELEMENTS; ++i3) { this[i3] = -this[i3]; } return this.check(); } lerp(a2, b, t2) { if (t2 === void 0) { return this.lerp(this, a2, b); } for (let i3 = 0; i3 < this.ELEMENTS; ++i3) { const ai = a2[i3]; const endValue = typeof b === "number" ? b : b[i3]; this[i3] = ai + t2 * (endValue - ai); } return this.check(); } min(vector) { for (let i3 = 0; i3 < this.ELEMENTS; ++i3) { this[i3] = Math.min(vector[i3], this[i3]); } return this.check(); } max(vector) { for (let i3 = 0; i3 < this.ELEMENTS; ++i3) { this[i3] = Math.max(vector[i3], this[i3]); } return this.check(); } clamp(minVector, maxVector) { for (let i3 = 0; i3 < this.ELEMENTS; ++i3) { this[i3] = Math.min(Math.max(this[i3], minVector[i3]), maxVector[i3]); } return this.check(); } add(...vectors) { for (const vector of vectors) { for (let i3 = 0; i3 < this.ELEMENTS; ++i3) { this[i3] += vector[i3]; } } return this.check(); } subtract(...vectors) { for (const vector of vectors) { for (let i3 = 0; i3 < this.ELEMENTS; ++i3) { this[i3] -= vector[i3]; } } return this.check(); } scale(scale6) { if (typeof scale6 === "number") { for (let i3 = 0; i3 < this.ELEMENTS; ++i3) { this[i3] *= scale6; } } else { for (let i3 = 0; i3 < this.ELEMENTS && i3 < scale6.length; ++i3) { this[i3] *= scale6[i3]; } } return this.check(); } multiplyByScalar(scalar) { for (let i3 = 0; i3 < this.ELEMENTS; ++i3) { this[i3] *= scalar; } return this.check(); } check() { if (config.debug && !this.validate()) { throw new Error(`math.gl: ${this.constructor.name} some fields set to invalid numbers'`); } return this; } validate() { let valid = this.length === this.ELEMENTS; for (let i3 = 0; i3 < this.ELEMENTS; ++i3) { valid = valid && Number.isFinite(this[i3]); } return valid; } sub(a2) { return this.subtract(a2); } setScalar(a2) { for (let i3 = 0; i3 < this.ELEMENTS; ++i3) { this[i3] = a2; } return this.check(); } addScalar(a2) { for (let i3 = 0; i3 < this.ELEMENTS; ++i3) { this[i3] += a2; } return this.check(); } subScalar(a2) { return this.addScalar(-a2); } multiplyScalar(scalar) { for (let i3 = 0; i3 < this.ELEMENTS; ++i3) { this[i3] *= scalar; } return this.check(); } divideScalar(a2) { return this.multiplyByScalar(1 / a2); } clampScalar(min2, max2) { for (let i3 = 0; i3 < this.ELEMENTS; ++i3) { this[i3] = Math.min(Math.max(this[i3], min2), max2); } return this.check(); } get elements() { return this; } }; // ../../node_modules/@math.gl/core/dist/lib/validators.js function validateVector(v, length5) { if (v.length !== length5) { return false; } for (let i3 = 0; i3 < v.length; ++i3) { if (!Number.isFinite(v[i3])) { return false; } } return true; } function checkNumber(value) { if (!Number.isFinite(value)) { throw new Error(`Invalid number ${JSON.stringify(value)}`); } return value; } function checkVector(v, length5, callerName = "") { if (config.debug && !validateVector(v, length5)) { throw new Error(`math.gl: ${callerName} some fields set to invalid numbers'`); } return v; } // ../../node_modules/@math.gl/core/dist/lib/assert.js function assert5(condition, message) { if (!condition) { throw new Error(`math.gl assertion ${message}`); } } // ../../node_modules/@math.gl/core/dist/classes/base/vector.js var Vector = class extends MathArray { get x() { return this[0]; } set x(value) { this[0] = checkNumber(value); } get y() { return this[1]; } set y(value) { this[1] = checkNumber(value); } len() { return Math.sqrt(this.lengthSquared()); } magnitude() { return this.len(); } lengthSquared() { let length5 = 0; for (let i3 = 0; i3 < this.ELEMENTS; ++i3) { length5 += this[i3] * this[i3]; } return length5; } magnitudeSquared() { return this.lengthSquared(); } distance(mathArray) { return Math.sqrt(this.distanceSquared(mathArray)); } distanceSquared(mathArray) { let length5 = 0; for (let i3 = 0; i3 < this.ELEMENTS; ++i3) { const dist2 = this[i3] - mathArray[i3]; length5 += dist2 * dist2; } return checkNumber(length5); } dot(mathArray) { let product = 0; for (let i3 = 0; i3 < this.ELEMENTS; ++i3) { product += this[i3] * mathArray[i3]; } return checkNumber(product); } normalize() { const length5 = this.magnitude(); if (length5 !== 0) { for (let i3 = 0; i3 < this.ELEMENTS; ++i3) { this[i3] /= length5; } } return this.check(); } multiply(...vectors) { for (const vector of vectors) { for (let i3 = 0; i3 < this.ELEMENTS; ++i3) { this[i3] *= vector[i3]; } } return this.check(); } divide(...vectors) { for (const vector of vectors) { for (let i3 = 0; i3 < this.ELEMENTS; ++i3) { this[i3] /= vector[i3]; } } return this.check(); } lengthSq() { return this.lengthSquared(); } distanceTo(vector) { return this.distance(vector); } distanceToSquared(vector) { return this.distanceSquared(vector); } getComponent(i3) { assert5(i3 >= 0 && i3 < this.ELEMENTS, "index is out of range"); return checkNumber(this[i3]); } setComponent(i3, value) { assert5(i3 >= 0 && i3 < this.ELEMENTS, "index is out of range"); this[i3] = value; return this.check(); } addVectors(a2, b) { return this.copy(a2).add(b); } subVectors(a2, b) { return this.copy(a2).subtract(b); } multiplyVectors(a2, b) { return this.copy(a2).multiply(b); } addScaledVector(a2, b) { return this.add(new this.constructor(a2).multiplyScalar(b)); } }; // ../../node_modules/@math.gl/core/dist/gl-matrix/common.js var EPSILON = 1e-6; var ARRAY_TYPE = typeof Float32Array !== "undefined" ? Float32Array : Array; var RANDOM = Math.random; function round2(a2) { if (a2 >= 0) return Math.round(a2); return a2 % 0.5 === 0 ? Math.floor(a2) : Math.round(a2); } var degree = Math.PI / 180; // ../../node_modules/@math.gl/core/dist/gl-matrix/vec2.js function create() { const out = new ARRAY_TYPE(2); if (ARRAY_TYPE != Float32Array) { out[0] = 0; out[1] = 0; } return out; } function transformMat2(out, a2, m) { const x2 = a2[0]; const y2 = a2[1]; out[0] = m[0] * x2 + m[2] * y2; out[1] = m[1] * x2 + m[3] * y2; return out; } function transformMat2d(out, a2, m) { const x2 = a2[0]; const y2 = a2[1]; out[0] = m[0] * x2 + m[2] * y2 + m[4]; out[1] = m[1] * x2 + m[3] * y2 + m[5]; return out; } function transformMat3(out, a2, m) { const x2 = a2[0]; const y2 = a2[1]; out[0] = m[0] * x2 + m[3] * y2 + m[6]; out[1] = m[1] * x2 + m[4] * y2 + m[7]; return out; } function transformMat4(out, a2, m) { const x2 = a2[0]; const y2 = a2[1]; out[0] = m[0] * x2 + m[4] * y2 + m[12]; out[1] = m[1] * x2 + m[5] * y2 + m[13]; return out; } var forEach = function() { const vec = create(); return function(a2, stride, offset, count, fn, arg) { let i3; let l2; if (!stride) { stride = 2; } if (!offset) { offset = 0; } if (count) { l2 = Math.min(count * stride + offset, a2.length); } else { l2 = a2.length; } for (i3 = offset; i3 < l2; i3 += stride) { vec[0] = a2[i3]; vec[1] = a2[i3 + 1]; fn(vec, vec, arg); a2[i3] = vec[0]; a2[i3 + 1] = vec[1]; } return a2; }; }(); // ../../node_modules/@math.gl/core/dist/lib/gl-matrix-extras.js function vec2_transformMat4AsVector(out, a2, m) { const x2 = a2[0]; const y2 = a2[1]; const w = m[3] * x2 + m[7] * y2 || 1; out[0] = (m[0] * x2 + m[4] * y2) / w; out[1] = (m[1] * x2 + m[5] * y2) / w; return out; } function vec3_transformMat4AsVector(out, a2, m) { const x2 = a2[0]; const y2 = a2[1]; const z = a2[2]; const w = m[3] * x2 + m[7] * y2 + m[11] * z || 1; out[0] = (m[0] * x2 + m[4] * y2 + m[8] * z) / w; out[1] = (m[1] * x2 + m[5] * y2 + m[9] * z) / w; out[2] = (m[2] * x2 + m[6] * y2 + m[10] * z) / w; return out; } function vec3_transformMat2(out, a2, m) { const x2 = a2[0]; const y2 = a2[1]; out[0] = m[0] * x2 + m[2] * y2; out[1] = m[1] * x2 + m[3] * y2; out[2] = a2[2]; return out; } function vec4_transformMat2(out, a2, m) { const x2 = a2[0]; const y2 = a2[1]; out[0] = m[0] * x2 + m[2] * y2; out[1] = m[1] * x2 + m[3] * y2; out[2] = a2[2]; out[3] = a2[3]; return out; } function vec4_transformMat3(out, a2, m) { const x2 = a2[0]; const y2 = a2[1]; const z = a2[2]; out[0] = m[0] * x2 + m[3] * y2 + m[6] * z; out[1] = m[1] * x2 + m[4] * y2 + m[7] * z; out[2] = m[2] * x2 + m[5] * y2 + m[8] * z; out[3] = a2[3]; return out; } // ../../node_modules/@math.gl/core/dist/classes/vector2.js var Vector2 = class extends Vector { constructor(x2 = 0, y2 = 0) { super(2); if (isArray(x2) && arguments.length === 1) { this.copy(x2); } else { if (config.debug) { checkNumber(x2); checkNumber(y2); } this[0] = x2; this[1] = y2; } } set(x2, y2) { this[0] = x2; this[1] = y2; return this.check(); } copy(array) { this[0] = array[0]; this[1] = array[1]; return this.check(); } fromObject(object) { if (config.debug) { checkNumber(object.x); checkNumber(object.y); } this[0] = object.x; this[1] = object.y; return this.check(); } toObject(object) { object.x = this[0]; object.y = this[1]; return object; } get ELEMENTS() { return 2; } horizontalAngle() { return Math.atan2(this.y, this.x); } verticalAngle() { return Math.atan2(this.x, this.y); } transform(matrix4) { return this.transformAsPoint(matrix4); } transformAsPoint(matrix4) { transformMat4(this, this, matrix4); return this.check(); } transformAsVector(matrix4) { vec2_transformMat4AsVector(this, this, matrix4); return this.check(); } transformByMatrix3(matrix3) { transformMat3(this, this, matrix3); return this.check(); } transformByMatrix2x3(matrix2x3) { transformMat2d(this, this, matrix2x3); return this.check(); } transformByMatrix2(matrix2) { transformMat2(this, this, matrix2); return this.check(); } }; // ../../node_modules/@math.gl/core/dist/gl-matrix/vec3.js var vec3_exports = {}; __export(vec3_exports, { add: () => add, angle: () => angle, bezier: () => bezier, ceil: () => ceil, clone: () => clone, copy: () => copy, create: () => create2, cross: () => cross, dist: () => dist, distance: () => distance, div: () => div, divide: () => divide, dot: () => dot, equals: () => equals2, exactEquals: () => exactEquals, floor: () => floor, forEach: () => forEach2, fromValues: () => fromValues, hermite: () => hermite, inverse: () => inverse, len: () => len, length: () => length, lerp: () => lerp2, max: () => max, min: () => min, mul: () => mul, multiply: () => multiply, negate: () => negate, normalize: () => normalize, random: () => random, rotateX: () => rotateX, rotateY: () => rotateY, rotateZ: () => rotateZ, round: () => round3, scale: () => scale, scaleAndAdd: () => scaleAndAdd, set: () => set, slerp: () => slerp, sqrDist: () => sqrDist, sqrLen: () => sqrLen, squaredDistance: () => squaredDistance, squaredLength: () => squaredLength, str: () => str, sub: () => sub, subtract: () => subtract, transformMat3: () => transformMat32, transformMat4: () => transformMat42, transformQuat: () => transformQuat, zero: () => zero }); function create2() { const out = new ARRAY_TYPE(3); if (ARRAY_TYPE != Float32Array) { out[0] = 0; out[1] = 0; out[2] = 0; } return out; } function clone(a2) { const out = new ARRAY_TYPE(3); out[0] = a2[0]; out[1] = a2[1]; out[2] = a2[2]; return out; } function length(a2) { const x2 = a2[0]; const y2 = a2[1]; const z = a2[2]; return Math.sqrt(x2 * x2 + y2 * y2 + z * z); } function fromValues(x2, y2, z) { const out = new ARRAY_TYPE(3); out[0] = x2; out[1] = y2; out[2] = z; return out; } function copy(out, a2) { out[0] = a2[0]; out[1] = a2[1]; out[2] = a2[2]; return out; } function set(out, x2, y2, z) { out[0] = x2; out[1] = y2; out[2] = z; return out; } function add(out, a2, b) { out[0] = a2[0] + b[0]; out[1] = a2[1] + b[1]; out[2] = a2[2] + b[2]; return out; } function subtract(out, a2, b) { out[0] = a2[0] - b[0]; out[1] = a2[1] - b[1]; out[2] = a2[2] - b[2]; return out; } function multiply(out, a2, b) { out[0] = a2[0] * b[0]; out[1] = a2[1] * b[1]; out[2] = a2[2] * b[2]; return out; } function divide(out, a2, b) { out[0] = a2[0] / b[0]; out[1] = a2[1] / b[1]; out[2] = a2[2] / b[2]; return out; } function ceil(out, a2) { out[0] = Math.ceil(a2[0]); out[1] = Math.ceil(a2[1]); out[2] = Math.ceil(a2[2]); return out; } function floor(out, a2) { out[0] = Math.floor(a2[0]); out[1] = Math.floor(a2[1]); out[2] = Math.floor(a2[2]); return out; } function min(out, a2, b) { out[0] = Math.min(a2[0], b[0]); out[1] = Math.min(a2[1], b[1]); out[2] = Math.min(a2[2], b[2]); return out; } function max(out, a2, b) { out[0] = Math.max(a2[0], b[0]); out[1] = Math.max(a2[1], b[1]); out[2] = Math.max(a2[2], b[2]); return out; } function round3(out, a2) { out[0] = round2(a2[0]); out[1] = round2(a2[1]); out[2] = round2(a2[2]); return out; } function scale(out, a2, b) { out[0] = a2[0] * b; out[1] = a2[1] * b; out[2] = a2[2] * b; return out; } function scaleAndAdd(out, a2, b, scale6) { out[0] = a2[0] + b[0] * scale6; out[1] = a2[1] + b[1] * scale6; out[2] = a2[2] + b[2] * scale6; return out; } function distance(a2, b) { const x2 = b[0] - a2[0]; const y2 = b[1] - a2[1]; const z = b[2] - a2[2]; return Math.sqrt(x2 * x2 + y2 * y2 + z * z); } function squaredDistance(a2, b) { const x2 = b[0] - a2[0]; const y2 = b[1] - a2[1]; const z = b[2] - a2[2]; return x2 * x2 + y2 * y2 + z * z; } function squaredLength(a2) { const x2 = a2[0]; const y2 = a2[1]; const z = a2[2]; return x2 * x2 + y2 * y2 + z * z; } function negate(out, a2) { out[0] = -a2[0]; out[1] = -a2[1]; out[2] = -a2[2]; return out; } function inverse(out, a2) { out[0] = 1 / a2[0]; out[1] = 1 / a2[1]; out[2] = 1 / a2[2]; return out; } function normalize(out, a2) { const x2 = a2[0]; const y2 = a2[1]; const z = a2[2]; let len2 = x2 * x2 + y2 * y2 + z * z; if (len2 > 0) { len2 = 1 / Math.sqrt(len2); } out[0] = a2[0] * len2; out[1] = a2[1] * len2; out[2] = a2[2] * len2; return out; } function dot(a2, b) { return a2[0] * b[0] + a2[1] * b[1] + a2[2] * b[2]; } function cross(out, a2, b) { const ax = a2[0]; const ay = a2[1]; const az = a2[2]; const bx = b[0]; const by = b[1]; const bz = b[2]; out[0] = ay * bz - az * by; out[1] = az * bx - ax * bz; out[2] = ax * by - ay * bx; return out; } function lerp2(out, a2, b, t2) { const ax = a2[0]; const ay = a2[1]; const az = a2[2]; out[0] = ax + t2 * (b[0] - ax); out[1] = ay + t2 * (b[1] - ay); out[2] = az + t2 * (b[2] - az); return out; } function slerp(out, a2, b, t2) { const angle2 = Math.acos(Math.min(Math.max(dot(a2, b), -1), 1)); const sinTotal = Math.sin(angle2); const ratioA = Math.sin((1 - t2) * angle2) / sinTotal; const ratioB = Math.sin(t2 * angle2) / sinTotal; out[0] = ratioA * a2[0] + ratioB * b[0]; out[1] = ratioA * a2[1] + ratioB * b[1]; out[2] = ratioA * a2[2] + ratioB * b[2]; return out; } function hermite(out, a2, b, c, d, t2) { const factorTimes2 = t2 * t2; const factor1 = factorTimes2 * (2 * t2 - 3) + 1; const factor2 = factorTimes2 * (t2 - 2) + t2; const factor3 = factorTimes2 * (t2 - 1); const factor4 = factorTimes2 * (3 - 2 * t2); out[0] = a2[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4; out[1] = a2[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4; out[2] = a2[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4; return out; } function bezier(out, a2, b, c, d, t2) { const inverseFactor = 1 - t2; const inverseFactorTimesTwo = inverseFactor * inverseFactor; const factorTimes2 = t2 * t2; const factor1 = inverseFactorTimesTwo * inverseFactor; const factor2 = 3 * t2 * inverseFactorTimesTwo; const factor3 = 3 * factorTimes2 * inverseFactor; const factor4 = factorTimes2 * t2; out[0] = a2[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4; out[1] = a2[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4; out[2] = a2[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4; return out; } function random(out, scale6) { scale6 = scale6 === void 0 ? 1 : scale6; const r2 = RANDOM() * 2 * Math.PI; const z = RANDOM() * 2 - 1; const zScale = Math.sqrt(1 - z * z) * scale6; out[0] = Math.cos(r2) * zScale; out[1] = Math.sin(r2) * zScale; out[2] = z * scale6; return out; } function transformMat42(out, a2, m) { const x2 = a2[0]; const y2 = a2[1]; const z = a2[2]; let w = m[3] * x2 + m[7] * y2 + m[11] * z + m[15]; w = w || 1; out[0] = (m[0] * x2 + m[4] * y2 + m[8] * z + m[12]) / w; out[1] = (m[1] * x2 + m[5] * y2 + m[9] * z + m[13]) / w; out[2] = (m[2] * x2 + m[6] * y2 + m[10] * z + m[14]) / w; return out; } function transformMat32(out, a2, m) { const x2 = a2[0]; const y2 = a2[1]; const z = a2[2]; out[0] = x2 * m[0] + y2 * m[3] + z * m[6]; out[1] = x2 * m[1] + y2 * m[4] + z * m[7]; out[2] = x2 * m[2] + y2 * m[5] + z * m[8]; return out; } function transformQuat(out, a2, q) { const qx = q[0]; const qy = q[1]; const qz = q[2]; const qw = q[3]; const x2 = a2[0]; const y2 = a2[1]; const z = a2[2]; let uvx = qy * z - qz * y2; let uvy = qz * x2 - qx * z; let uvz = qx * y2 - qy * x2; let uuvx = qy * uvz - qz * uvy; let uuvy = qz * uvx - qx * uvz; let uuvz = qx * uvy - qy * uvx; const w2 = qw * 2; uvx *= w2; uvy *= w2; uvz *= w2; uuvx *= 2; uuvy *= 2; uuvz *= 2; out[0] = x2 + uvx + uuvx; out[1] = y2 + uvy + uuvy; out[2] = z + uvz + uuvz; return out; } function rotateX(out, a2, b, rad) { const p2 = []; const r2 = []; p2[0] = a2[0] - b[0]; p2[1] = a2[1] - b[1]; p2[2] = a2[2] - b[2]; r2[0] = p2[0]; r2[1] = p2[1] * Math.cos(rad) - p2[2] * Math.sin(rad); r2[2] = p2[1] * Math.sin(rad) + p2[2] * Math.cos(rad); out[0] = r2[0] + b[0]; out[1] = r2[1] + b[1]; out[2] = r2[2] + b[2]; return out; } function rotateY(out, a2, b, rad) { const p2 = []; const r2 = []; p2[0] = a2[0] - b[0]; p2[1] = a2[1] - b[1]; p2[2] = a2[2] - b[2]; r2[0] = p2[2] * Math.sin(rad) + p2[0] * Math.cos(rad); r2[1] = p2[1]; r2[2] = p2[2] * Math.cos(rad) - p2[0] * Math.sin(rad); out[0] = r2[0] + b[0]; out[1] = r2[1] + b[1]; out[2] = r2[2] + b[2]; return out; } function rotateZ(out, a2, b, rad) { const p2 = []; const r2 = []; p2[0] = a2[0] - b[0]; p2[1] = a2[1] - b[1]; p2[2] = a2[2] - b[2]; r2[0] = p2[0] * Math.cos(rad) - p2[1] * Math.sin(rad); r2[1] = p2[0] * Math.sin(rad) + p2[1] * Math.cos(rad); r2[2] = p2[2]; out[0] = r2[0] + b[0]; out[1] = r2[1] + b[1]; out[2] = r2[2] + b[2]; return out; } function angle(a2, b) { const ax = a2[0]; const ay = a2[1]; const az = a2[2]; const bx = b[0]; const by = b[1]; const bz = b[2]; const mag = Math.sqrt((ax * ax + ay * ay + az * az) * (bx * bx + by * by + bz * bz)); const cosine = mag && dot(a2, b) / mag; return Math.acos(Math.min(Math.max(cosine, -1), 1)); } function zero(out) { out[0] = 0; out[1] = 0; out[2] = 0; return out; } function str(a2) { return `vec3(${a2[0]}, ${a2[1]}, ${a2[2]})`; } function exactEquals(a2, b) { return a2[0] === b[0] && a2[1] === b[1] && a2[2] === b[2]; } function equals2(a2, b) { const a0 = a2[0]; const a1 = a2[1]; const a22 = a2[2]; const b0 = b[0]; const b1 = b[1]; const b2 = b[2]; return Math.abs(a0 - b0) <= EPSILON * Math.max(1, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1, Math.abs(a1), Math.abs(b1)) && Math.abs(a22 - b2) <= EPSILON * Math.max(1, Math.abs(a22), Math.abs(b2)); } var sub = subtract; var mul = multiply; var div = divide; var dist = distance; var sqrDist = squaredDistance; var len = length; var sqrLen = squaredLength; var forEach2 = function() { const vec = create2(); return function(a2, stride, offset, count, fn, arg) { let i3; let l2; if (!stride) { stride = 3; } if (!offset) { offset = 0; } if (count) { l2 = Math.min(count * stride + offset, a2.length); } else { l2 = a2.length; } for (i3 = offset; i3 < l2; i3 += stride) { vec[0] = a2[i3]; vec[1] = a2[i3 + 1]; vec[2] = a2[i3 + 2]; fn(vec, vec, arg); a2[i3] = vec[0]; a2[i3 + 1] = vec[1]; a2[i3 + 2] = vec[2]; } return a2; }; }(); // ../../node_modules/@math.gl/core/dist/classes/vector3.js var ORIGIN = [0, 0, 0]; var ZERO; var Vector3 = class extends Vector { static get ZERO() { if (!ZERO) { ZERO = new Vector3(0, 0, 0); Object.freeze(ZERO); } return ZERO; } constructor(x2 = 0, y2 = 0, z = 0) { super(-0, -0, -0); if (arguments.length === 1 && isArray(x2)) { this.copy(x2); } else { if (config.debug) { checkNumber(x2); checkNumber(y2); checkNumber(z); } this[0] = x2; this[1] = y2; this[2] = z; } } set(x2, y2, z) { this[0] = x2; this[1] = y2; this[2] = z; return this.check(); } copy(array) { this[0] = array[0]; this[1] = array[1]; this[2] = array[2]; return this.check(); } fromObject(object) { if (config.debug) { checkNumber(object.x); checkNumber(object.y); checkNumber(object.z); } this[0] = object.x; this[1] = object.y; this[2] = object.z; return this.check(); } toObject(object) { object.x = this[0]; object.y = this[1]; object.z = this[2]; return object; } get ELEMENTS() { return 3; } get z() { return this[2]; } set z(value) { this[2] = checkNumber(value); } angle(vector) { return angle(this, vector); } cross(vector) { cross(this, this, vector); return this.check(); } rotateX({ radians: radians2, origin = ORIGIN }) { rotateX(this, this, origin, radians2); return this.check(); } rotateY({ radians: radians2, origin = ORIGIN }) { rotateY(this, this, origin, radians2); return this.check(); } rotateZ({ radians: radians2, origin = ORIGIN }) { rotateZ(this, this, origin, radians2); return this.check(); } transform(matrix4) { return this.transformAsPoint(matrix4); } transformAsPoint(matrix4) { transformMat42(this, this, matrix4); return this.check(); } transformAsVector(matrix4) { vec3_transformMat4AsVector(this, this, matrix4); return this.check(); } transformByMatrix3(matrix3) { transformMat32(this, this, matrix3); return this.check(); } transformByMatrix2(matrix2) { vec3_transformMat2(this, this, matrix2); return this.check(); } transformByQuaternion(quaternion) { transformQuat(this, this, quaternion); return this.check(); } }; // ../../node_modules/@math.gl/core/dist/classes/vector4.js var ZERO2; var Vector4 = class extends Vector { static get ZERO() { if (!ZERO2) { ZERO2 = new Vector4(0, 0, 0, 0); Object.freeze(ZERO2); } return ZERO2; } constructor(x2 = 0, y2 = 0, z = 0, w = 0) { super(-0, -0, -0, -0); if (isArray(x2) && arguments.length === 1) { this.copy(x2); } else { if (config.debug) { checkNumber(x2); checkNumber(y2); checkNumber(z); checkNumber(w); } this[0] = x2; this[1] = y2; this[2] = z; this[3] = w; } } set(x2, y2, z, w) { this[0] = x2; this[1] = y2; this[2] = z; this[3] = w; return this.check(); } copy(array) { this[0] = array[0]; this[1] = array[1]; this[2] = array[2]; this[3] = array[3]; return this.check(); } fromObject(object) { if (config.debug) { checkNumber(object.x); checkNumber(object.y); checkNumber(object.z); checkNumber(object.w); } this[0] = object.x; this[1] = object.y; this[2] = object.z; this[3] = object.w; return this; } toObject(object) { object.x = this[0]; object.y = this[1]; object.z = this[2]; object.w = this[3]; return object; } get ELEMENTS() { return 4; } get z() { return this[2]; } set z(value) { this[2] = checkNumber(value); } get w() { return this[3]; } set w(value) { this[3] = checkNumber(value); } transform(matrix4) { transformMat42(this, this, matrix4); return this.check(); } transformByMatrix3(matrix3) { vec4_transformMat3(this, this, matrix3); return this.check(); } transformByMatrix2(matrix2) { vec4_transformMat2(this, this, matrix2); return this.check(); } transformByQuaternion(quaternion) { transformQuat(this, this, quaternion); return this.check(); } applyMatrix4(m) { m.transform(this, this); return this; } }; // ../../node_modules/@math.gl/core/dist/classes/base/matrix.js var Matrix = class extends MathArray { toString() { let string = "["; if (config.printRowMajor) { string += "row-major:"; for (let row = 0; row < this.RANK; ++row) { for (let col = 0; col < this.RANK; ++col) { string += ` ${this[col * this.RANK + row]}`; } } } else { string += "column-major:"; for (let i3 = 0; i3 < this.ELEMENTS; ++i3) { string += ` ${this[i3]}`; } } string += "]"; return string; } getElementIndex(row, col) { return col * this.RANK + row; } getElement(row, col) { return this[col * this.RANK + row]; } setElement(row, col, value) { this[col * this.RANK + row] = checkNumber(value); return this; } getColumn(columnIndex, result = new Array(this.RANK).fill(-0)) { const firstIndex = columnIndex * this.RANK; for (let i3 = 0; i3 < this.RANK; ++i3) { result[i3] = this[firstIndex + i3]; } return result; } setColumn(columnIndex, columnVector) { const firstIndex = columnIndex * this.RANK; for (let i3 = 0; i3 < this.RANK; ++i3) { this[firstIndex + i3] = columnVector[i3]; } return this; } }; // ../../node_modules/@math.gl/core/dist/gl-matrix/mat3.js function create3() { const 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; } function transpose(out, a2) { if (out === a2) { const a01 = a2[1]; const a02 = a2[2]; const a12 = a2[5]; out[1] = a2[3]; out[2] = a2[6]; out[3] = a01; out[5] = a2[7]; out[6] = a02; out[7] = a12; } else { out[0] = a2[0]; out[1] = a2[3]; out[2] = a2[6]; out[3] = a2[1]; out[4] = a2[4]; out[5] = a2[7]; out[6] = a2[2]; out[7] = a2[5]; out[8] = a2[8]; } return out; } function invert(out, a2) { const a00 = a2[0]; const a01 = a2[1]; const a02 = a2[2]; const a10 = a2[3]; const a11 = a2[4]; const a12 = a2[5]; const a20 = a2[6]; const a21 = a2[7]; const a22 = a2[8]; const b01 = a22 * a11 - a12 * a21; const b11 = -a22 * a10 + a12 * a20; const b21 = a21 * a10 - a11 * a20; let det = a00 * b01 + a01 * b11 + a02 * b21; if (!det) { return null; } det = 1 / 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; } function determinant(a2) { const a00 = a2[0]; const a01 = a2[1]; const a02 = a2[2]; const a10 = a2[3]; const a11 = a2[4]; const a12 = a2[5]; const a20 = a2[6]; const a21 = a2[7]; const a22 = a2[8]; return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20); } function multiply2(out, a2, b) { const a00 = a2[0]; const a01 = a2[1]; const a02 = a2[2]; const a10 = a2[3]; const a11 = a2[4]; const a12 = a2[5]; const a20 = a2[6]; const a21 = a2[7]; const a22 = a2[8]; const b00 = b[0]; const b01 = b[1]; const b02 = b[2]; const b10 = b[3]; const b11 = b[4]; const b12 = b[5]; const b20 = b[6]; const b21 = b[7]; const 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; } function translate(out, a2, v) { const a00 = a2[0]; const a01 = a2[1]; const a02 = a2[2]; const a10 = a2[3]; const a11 = a2[4]; const a12 = a2[5]; const a20 = a2[6]; const a21 = a2[7]; const a22 = a2[8]; const x2 = v[0]; const y2 = v[1]; out[0] = a00; out[1] = a01; out[2] = a02; out[3] = a10; out[4] = a11; out[5] = a12; out[6] = x2 * a00 + y2 * a10 + a20; out[7] = x2 * a01 + y2 * a11 + a21; out[8] = x2 * a02 + y2 * a12 + a22; return out; } function rotate(out, a2, rad) { const a00 = a2[0]; const a01 = a2[1]; const a02 = a2[2]; const a10 = a2[3]; const a11 = a2[4]; const a12 = a2[5]; const a20 = a2[6]; const a21 = a2[7]; const a22 = a2[8]; const s2 = Math.sin(rad); const c = Math.cos(rad); out[0] = c * a00 + s2 * a10; out[1] = c * a01 + s2 * a11; out[2] = c * a02 + s2 * a12; out[3] = c * a10 - s2 * a00; out[4] = c * a11 - s2 * a01; out[5] = c * a12 - s2 * a02; out[6] = a20; out[7] = a21; out[8] = a22; return out; } function scale2(out, a2, v) { const x2 = v[0]; const y2 = v[1]; out[0] = x2 * a2[0]; out[1] = x2 * a2[1]; out[2] = x2 * a2[2]; out[3] = y2 * a2[3]; out[4] = y2 * a2[4]; out[5] = y2 * a2[5]; out[6] = a2[6]; out[7] = a2[7]; out[8] = a2[8]; return out; } function fromQuat(out, q) { const x2 = q[0]; const y2 = q[1]; const z = q[2]; const w = q[3]; const x22 = x2 + x2; const y22 = y2 + y2; const z2 = z + z; const xx = x2 * x22; const yx = y2 * x22; const yy = y2 * y22; const zx = z * x22; const zy = z * y22; const zz = z * z2; const wx = w * x22; const wy = w * y22; const 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; } // ../../node_modules/@math.gl/core/dist/classes/matrix3.js var INDICES; (function(INDICES3) { INDICES3[INDICES3["COL0ROW0"] = 0] = "COL0ROW0"; INDICES3[INDICES3["COL0ROW1"] = 1] = "COL0ROW1"; INDICES3[INDICES3["COL0ROW2"] = 2] = "COL0ROW2"; INDICES3[INDICES3["COL1ROW0"] = 3] = "COL1ROW0"; INDICES3[INDICES3["COL1ROW1"] = 4] = "COL1ROW1"; INDICES3[INDICES3["COL1ROW2"] = 5] = "COL1ROW2"; INDICES3[INDICES3["COL2ROW0"] = 6] = "COL2ROW0"; INDICES3[INDICES3["COL2ROW1"] = 7] = "COL2ROW1"; INDICES3[INDICES3["COL2ROW2"] = 8] = "COL2ROW2"; })(INDICES || (INDICES = {})); var IDENTITY_MATRIX = Object.freeze([1, 0, 0, 0, 1, 0, 0, 0, 1]); var Matrix3 = class extends Matrix { static get IDENTITY() { return getIdentityMatrix(); } static get ZERO() { return getZeroMatrix(); } get ELEMENTS() { return 9; } get RANK() { return 3; } get INDICES() { return INDICES; } constructor(array, ...args) { super(-0, -0, -0, -0, -0, -0, -0, -0, -0); if (arguments.length === 1 && Array.isArray(array)) { this.copy(array); } else if (args.length > 0) { this.copy([array, ...args]); } else { this.identity(); } } copy(array) { this[0] = array[0]; this[1] = array[1]; this[2] = array[2]; this[3] = array[3]; this[4] = array[4]; this[5] = array[5]; this[6] = array[6]; this[7] = array[7]; this[8] = array[8]; return this.check(); } identity() { return this.copy(IDENTITY_MATRIX); } fromObject(object) { return this.check(); } fromQuaternion(q) { fromQuat(this, q); return this.check(); } set(m00, m10, m20, m01, m11, m21, m02, m12, m22) { this[0] = m00; this[1] = m10; this[2] = m20; this[3] = m01; this[4] = m11; this[5] = m21; this[6] = m02; this[7] = m12; this[8] = m22; return this.check(); } setRowMajor(m00, m01, m02, m10, m11, m12, m20, m21, m22) { this[0] = m00; this[1] = m10; this[2] = m20; this[3] = m01; this[4] = m11; this[5] = m21; this[6] = m02; this[7] = m12; this[8] = m22; return this.check(); } determinant() { return determinant(this); } transpose() { transpose(this, this); return this.check(); } invert() { invert(this, this); return this.check(); } multiplyLeft(a2) { multiply2(this, a2, this); return this.check(); } multiplyRight(a2) { multiply2(this, this, a2); return this.check(); } rotate(radians2) { rotate(this, this, radians2); return this.check(); } scale(factor) { if (Array.isArray(factor)) { scale2(this, this, factor); } else { scale2(this, this, [factor, factor]); } return this.check(); } translate(vec) { translate(this, this, vec); return this.check(); } transform(vector, result) { let out; switch (vector.length) { case 2: out = transformMat3(result || [-0, -0], vector, this); break; case 3: out = transformMat32(result || [-0, -0, -0], vector, this); break; case 4: out = vec4_transformMat3(result || [-0, -0, -0, -0], vector, this); break; default: throw new Error("Illegal vector"); } checkVector(out, vector.length); return out; } transformVector(vector, result) { return this.transform(vector, result); } transformVector2(vector, result) { return this.transform(vector, result); } transformVector3(vector, result) { return this.transform(vector, result); } }; var ZERO_MATRIX3; var IDENTITY_MATRIX3 = null; function getZeroMatrix() { if (!ZERO_MATRIX3) { ZERO_MATRIX3 = new Matrix3([0, 0, 0, 0, 0, 0, 0, 0, 0]); Object.freeze(ZERO_MATRIX3); } return ZERO_MATRIX3; } function getIdentityMatrix() { if (!IDENTITY_MATRIX3) { IDENTITY_MATRIX3 = new Matrix3(); Object.freeze(IDENTITY_MATRIX3); } return IDENTITY_MATRIX3; } // ../../node_modules/@math.gl/core/dist/gl-matrix/mat4.js var mat4_exports = {}; __export(mat4_exports, { add: () => add2, adjoint: () => adjoint, clone: () => clone2, copy: () => copy2, create: () => create4, decompose: () => decompose, determinant: () => determinant2, equals: () => equals3, exactEquals: () => exactEquals2, frob: () => frob, fromQuat: () => fromQuat3, fromQuat2: () => fromQuat2, fromRotation: () => fromRotation, fromRotationTranslation: () => fromRotationTranslation, fromRotationTranslationScale: () => fromRotationTranslationScale, fromRotationTranslationScaleOrigin: () => fromRotationTranslationScaleOrigin, fromScaling: () => fromScaling, fromTranslation: () => fromTranslation, fromValues: () => fromValues2, fromXRotation: () => fromXRotation, fromYRotation: () => fromYRotation, fromZRotation: () => fromZRotation, frustum: () => frustum, getRotation: () => getRotation, getScaling: () => getScaling, getTranslation: () => getTranslation, identity: () => identity, invert: () => invert2, lookAt: () => lookAt, mul: () => mul2, multiply: () => multiply3, multiplyScalar: () => multiplyScalar, multiplyScalarAndAdd: () => multiplyScalarAndAdd, ortho: () => ortho, orthoNO: () => orthoNO, orthoZO: () => orthoZO, perspective: () => perspective, perspectiveFromFieldOfView: () => perspectiveFromFieldOfView, perspectiveNO: () => perspectiveNO, perspectiveZO: () => perspectiveZO, rotate: () => rotate2, rotateX: () => rotateX2, rotateY: () => rotateY2, rotateZ: () => rotateZ2, scale: () => scale3, set: () => set2, str: () => str2, sub: () => sub2, subtract: () => subtract2, targetTo: () => targetTo, translate: () => translate2, transpose: () => transpose2 }); function create4() { const 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; } function clone2(a2) { const out = new ARRAY_TYPE(16); out[0] = a2[0]; out[1] = a2[1]; out[2] = a2[2]; out[3] = a2[3]; out[4] = a2[4]; out[5] = a2[5]; out[6] = a2[6]; out[7] = a2[7]; out[8] = a2[8]; out[9] = a2[9]; out[10] = a2[10]; out[11] = a2[11]; out[12] = a2[12]; out[13] = a2[13]; out[14] = a2[14]; out[15] = a2[15]; return out; } function copy2(out, a2) { out[0] = a2[0]; out[1] = a2[1]; out[2] = a2[2]; out[3] = a2[3]; out[4] = a2[4]; out[5] = a2[5]; out[6] = a2[6]; out[7] = a2[7]; out[8] = a2[8]; out[9] = a2[9]; out[10] = a2[10]; out[11] = a2[11]; out[12] = a2[12]; out[13] = a2[13]; out[14] = a2[14]; out[15] = a2[15]; return out; } function fromValues2(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) { const 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; } function set2(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; } function identity(out) { out[0] = 1; out[1] = 0; out[2] = 0; out[3] = 0; out[4] = 0; out[5] = 1; out[6] = 0; out[7] = 0; out[8] = 0; out[9] = 0; out[10] = 1; out[11] = 0; out[12] = 0; out[13] = 0; out[14] = 0; out[15] = 1; return out; } function transpose2(out, a2) { if (out === a2) { const a01 = a2[1]; const a02 = a2[2]; const a03 = a2[3]; const a12 = a2[6]; const a13 = a2[7]; const a23 = a2[11]; out[1] = a2[4]; out[2] = a2[8]; out[3] = a2[12]; out[4] = a01; out[6] = a2[9]; out[7] = a2[13]; out[8] = a02; out[9] = a12; out[11] = a2[14]; out[12] = a03; out[13] = a13; out[14] = a23; } else { out[0] = a2[0]; out[1] = a2[4]; out[2] = a2[8]; out[3] = a2[12]; out[4] = a2[1]; out[5] = a2[5]; out[6] = a2[9]; out[7] = a2[13]; out[8] = a2[2]; out[9] = a2[6]; out[10] = a2[10]; out[11] = a2[14]; out[12] = a2[3]; out[13] = a2[7]; out[14] = a2[11]; out[15] = a2[15]; } return out; } function invert2(out, a2) { const a00 = a2[0]; const a01 = a2[1]; const a02 = a2[2]; const a03 = a2[3]; const a10 = a2[4]; const a11 = a2[5]; const a12 = a2[6]; const a13 = a2[7]; const a20 = a2[8]; const a21 = a2[9]; const a22 = a2[10]; const a23 = a2[11]; const a30 = a2[12]; const a31 = a2[13]; const a32 = a2[14]; const a33 = a2[15]; const b00 = a00 * a11 - a01 * a10; const b01 = a00 * a12 - a02 * a10; const b02 = a00 * a13 - a03 * a10; const b03 = a01 * a12 - a02 * a11; const b04 = a01 * a13 - a03 * a11; const b05 = a02 * a13 - a03 * a12; const b06 = a20 * a31 - a21 * a30; const b07 = a20 * a32 - a22 * a30; const b08 = a20 * a33 - a23 * a30; const b09 = a21 * a32 - a22 * a31; const b10 = a21 * a33 - a23 * a31; const b11 = a22 * a33 - a23 * a32; let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; if (!det) { return null; } det = 1 / 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; } function adjoint(out, a2) { const a00 = a2[0]; const a01 = a2[1]; const a02 = a2[2]; const a03 = a2[3]; const a10 = a2[4]; const a11 = a2[5]; const a12 = a2[6]; const a13 = a2[7]; const a20 = a2[8]; const a21 = a2[9]; const a22 = a2[10]; const a23 = a2[11]; const a30 = a2[12]; const a31 = a2[13]; const a32 = a2[14]; const a33 = a2[15]; const b00 = a00 * a11 - a01 * a10; const b01 = a00 * a12 - a02 * a10; const b02 = a00 * a13 - a03 * a10; const b03 = a01 * a12 - a02 * a11; const b04 = a01 * a13 - a03 * a11; const b05 = a02 * a13 - a03 * a12; const b06 = a20 * a31 - a21 * a30; const b07 = a20 * a32 - a22 * a30; const b08 = a20 * a33 - a23 * a30; const b09 = a21 * a32 - a22 * a31; const b10 = a21 * a33 - a23 * a31; const 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; } function determinant2(a2) { const a00 = a2[0]; const a01 = a2[1]; const a02 = a2[2]; const a03 = a2[3]; const a10 = a2[4]; const a11 = a2[5]; const a12 = a2[6]; const a13 = a2[7]; const a20 = a2[8]; const a21 = a2[9]; const a22 = a2[10]; const a23 = a2[11]; const a30 = a2[12]; const a31 = a2[13]; const a32 = a2[14]; const a33 = a2[15]; const b0 = a00 * a11 - a01 * a10; const b1 = a00 * a12 - a02 * a10; const b2 = a01 * a12 - a02 * a11; const b3 = a20 * a31 - a21 * a30; const b4 = a20 * a32 - a22 * a30; const b5 = a21 * a32 - a22 * a31; const b6 = a00 * b5 - a01 * b4 + a02 * b3; const b7 = a10 * b5 - a11 * b4 + a12 * b3; const b8 = a20 * b2 - a21 * b1 + a22 * b0; const b9 = a30 * b2 - a31 * b1 + a32 * b0; return a13 * b6 - a03 * b7 + a33 * b8 - a23 * b9; } function multiply3(out, a2, b) { const a00 = a2[0]; const a01 = a2[1]; const a02 = a2[2]; const a03 = a2[3]; const a10 = a2[4]; const a11 = a2[5]; const a12 = a2[6]; const a13 = a2[7]; const a20 = a2[8]; const a21 = a2[9]; const a22 = a2[10]; const a23 = a2[11]; const a30 = a2[12]; const a31 = a2[13]; const a32 = a2[14]; const a33 = a2[15]; let b0 = b[0]; let b1 = b[1]; let b2 = b[2]; let 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; } function translate2(out, a2, v) { const x2 = v[0]; const y2 = v[1]; const z = v[2]; let a00; let a01; let a02; let a03; let a10; let a11; let a12; let a13; let a20; let a21; let a22; let a23; if (a2 === out) { out[12] = a2[0] * x2 + a2[4] * y2 + a2[8] * z + a2[12]; out[13] = a2[1] * x2 + a2[5] * y2 + a2[9] * z + a2[13]; out[14] = a2[2] * x2 + a2[6] * y2 + a2[10] * z + a2[14]; out[15] = a2[3] * x2 + a2[7] * y2 + a2[11] * z + a2[15]; } else { a00 = a2[0]; a01 = a2[1]; a02 = a2[2]; a03 = a2[3]; a10 = a2[4]; a11 = a2[5]; a12 = a2[6]; a13 = a2[7]; a20 = a2[8]; a21 = a2[9]; a22 = a2[10]; a23 = a2[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 * x2 + a10 * y2 + a20 * z + a2[12]; out[13] = a01 * x2 + a11 * y2 + a21 * z + a2[13]; out[14] = a02 * x2 + a12 * y2 + a22 * z + a2[14]; out[15] = a03 * x2 + a13 * y2 + a23 * z + a2[15]; } return out; } function scale3(out, a2, v) { const x2 = v[0]; const y2 = v[1]; const z = v[2]; out[0] = a2[0] * x2; out[1] = a2[1] * x2; out[2] = a2[2] * x2; out[3] = a2[3] * x2; out[4] = a2[4] * y2; out[5] = a2[5] * y2; out[6] = a2[6] * y2; out[7] = a2[7] * y2; out[8] = a2[8] * z; out[9] = a2[9] * z; out[10] = a2[10] * z; out[11] = a2[11] * z; out[12] = a2[12]; out[13] = a2[13]; out[14] = a2[14]; out[15] = a2[15]; return out; } function rotate2(out, a2, rad, axis) { let x2 = axis[0]; let y2 = axis[1]; let z = axis[2]; let len2 = Math.sqrt(x2 * x2 + y2 * y2 + z * z); let c; let s2; let t2; let a00; let a01; let a02; let a03; let a10; let a11; let a12; let a13; let a20; let a21; let a22; let a23; let b00; let b01; let b02; let b10; let b11; let b12; let b20; let b21; let b22; if (len2 < EPSILON) { return null; } len2 = 1 / len2; x2 *= len2; y2 *= len2; z *= len2; s2 = Math.sin(rad); c = Math.cos(rad); t2 = 1 - c; a00 = a2[0]; a01 = a2[1]; a02 = a2[2]; a03 = a2[3]; a10 = a2[4]; a11 = a2[5]; a12 = a2[6]; a13 = a2[7]; a20 = a2[8]; a21 = a2[9]; a22 = a2[10]; a23 = a2[11]; b00 = x2 * x2 * t2 + c; b01 = y2 * x2 * t2 + z * s2; b02 = z * x2 * t2 - y2 * s2; b10 = x2 * y2 * t2 - z * s2; b11 = y2 * y2 * t2 + c; b12 = z * y2 * t2 + x2 * s2; b20 = x2 * z * t2 + y2 * s2; b21 = y2 * z * t2 - x2 * s2; b22 = z * z * t2 + c; 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 (a2 !== out) { out[12] = a2[12]; out[13] = a2[13]; out[14] = a2[14]; out[15] = a2[15]; } return out; } function rotateX2(out, a2, rad) { const s2 = Math.sin(rad); const c = Math.cos(rad); const a10 = a2[4]; const a11 = a2[5]; const a12 = a2[6]; const a13 = a2[7]; const a20 = a2[8]; const a21 = a2[9]; const a22 = a2[10]; const a23 = a2[11]; if (a2 !== out) { out[0] = a2[0]; out[1] = a2[1]; out[2] = a2[2]; out[3] = a2[3]; out[12] = a2[12]; out[13] = a2[13]; out[14] = a2[14]; out[15] = a2[15]; } out[4] = a10 * c + a20 * s2; out[5] = a11 * c + a21 * s2; out[6] = a12 * c + a22 * s2; out[7] = a13 * c + a23 * s2; out[8] = a20 * c - a10 * s2; out[9] = a21 * c - a11 * s2; out[10] = a22 * c - a12 * s2; out[11] = a23 * c - a13 * s2; return out; } function rotateY2(out, a2, rad) { const s2 = Math.sin(rad); const c = Math.cos(rad); const a00 = a2[0]; const a01 = a2[1]; const a02 = a2[2]; const a03 = a2[3]; const a20 = a2[8]; const a21 = a2[9]; const a22 = a2[10]; const a23 = a2[11]; if (a2 !== out) { out[4] = a2[4]; out[5] = a2[5]; out[6] = a2[6]; out[7] = a2[7]; out[12] = a2[12]; out[13] = a2[13]; out[14] = a2[14]; out[15] = a2[15]; } out[0] = a00 * c - a20 * s2; out[1] = a01 * c - a21 * s2; out[2] = a02 * c - a22 * s2; out[3] = a03 * c - a23 * s2; out[8] = a00 * s2 + a20 * c; out[9] = a01 * s2 + a21 * c; out[10] = a02 * s2 + a22 * c; out[11] = a03 * s2 + a23 * c; return out; } function rotateZ2(out, a2, rad) { const s2 = Math.sin(rad); const c = Math.cos(rad); const a00 = a2[0]; const a01 = a2[1]; const a02 = a2[2]; const a03 = a2[3]; const a10 = a2[4]; const a11 = a2[5]; const a12 = a2[6]; const a13 = a2[7]; if (a2 !== out) { out[8] = a2[8]; out[9] = a2[9]; out[10] = a2[10]; out[11] = a2[11]; out[12] = a2[12]; out[13] = a2[13]; out[14] = a2[14]; out[15] = a2[15]; } out[0] = a00 * c + a10 * s2; out[1] = a01 * c + a11 * s2; out[2] = a02 * c + a12 * s2; out[3] = a03 * c + a13 * s2; out[4] = a10 * c - a00 * s2; out[5] = a11 * c - a01 * s2; out[6] = a12 * c - a02 * s2; out[7] = a13 * c - a03 * s2; return out; } function fromTranslation(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; } 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; } function fromRotation(out, rad, axis) { let x2 = axis[0]; let y2 = axis[1]; let z = axis[2]; let len2 = Math.sqrt(x2 * x2 + y2 * y2 + z * z); let c; let s2; let t2; if (len2 < EPSILON) { return null; } len2 = 1 / len2; x2 *= len2; y2 *= len2; z *= len2; s2 = Math.sin(rad); c = Math.cos(rad); t2 = 1 - c; out[0] = x2 * x2 * t2 + c; out[1] = y2 * x2 * t2 + z * s2; out[2] = z * x2 * t2 - y2 * s2; out[3] = 0; out[4] = x2 * y2 * t2 - z * s2; out[5] = y2 * y2 * t2 + c; out[6] = z * y2 * t2 + x2 * s2; out[7] = 0; out[8] = x2 * z * t2 + y2 * s2; out[9] = y2 * z * t2 - x2 * s2; out[10] = z * z * t2 + c; out[11] = 0; out[12] = 0; out[13] = 0; out[14] = 0; out[15] = 1; return out; } function fromXRotation(out, rad) { const s2 = Math.sin(rad); const c = Math.cos(rad); out[0] = 1; out[1] = 0; out[2] = 0; out[3] = 0; out[4] = 0; out[5] = c; out[6] = s2; out[7] = 0; out[8] = 0; out[9] = -s2; out[10] = c; out[11] = 0; out[12] = 0; out[13] = 0; out[14] = 0; out[15] = 1; return out; } function fromYRotation(out, rad) { const s2 = Math.sin(rad); const c = Math.cos(rad); out[0] = c; out[1] = 0; out[2] = -s2; out[3] = 0; out[4] = 0; out[5] = 1; out[6] = 0; out[7] = 0; out[8] = s2; out[9] = 0; out[10] = c; out[11] = 0; out[12] = 0; out[13] = 0; out[14] = 0; out[15] = 1; return out; } function fromZRotation(out, rad) { const s2 = Math.sin(rad); const c = Math.cos(rad); out[0] = c; out[1] = s2; out[2] = 0; out[3] = 0; out[4] = -s2; 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; } function fromRotationTranslation(out, q, v) { const x2 = q[0]; const y2 = q[1]; const z = q[2]; const w = q[3]; const x22 = x2 + x2; const y22 = y2 + y2; const z2 = z + z; const xx = x2 * x22; const xy = x2 * y22; const xz = x2 * z2; const yy = y2 * y22; const yz = y2 * z2; const zz = z * z2; const wx = w * x22; const wy = w * y22; const 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; } function fromQuat2(out, a2) { const translation = new ARRAY_TYPE(3); const bx = -a2[0]; const by = -a2[1]; const bz = -a2[2]; const bw = a2[3]; const ax = a2[4]; const ay = a2[5]; const az = a2[6]; const aw = a2[7]; const magnitude = bx * bx + by * by + bz * bz + bw * bw; 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(out, a2, translation); return out; } function getTranslation(out, mat) { out[0] = mat[12]; out[1] = mat[13]; out[2] = mat[14]; return out; } function getScaling(out, mat) { const m11 = mat[0]; const m12 = mat[1]; const m13 = mat[2]; const m21 = mat[4]; const m22 = mat[5]; const m23 = mat[6]; const m31 = mat[8]; const m32 = mat[9]; const 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; } function getRotation(out, mat) { const scaling = new ARRAY_TYPE(3); getScaling(scaling, mat); const is1 = 1 / scaling[0]; const is2 = 1 / scaling[1]; const is3 = 1 / scaling[2]; const sm11 = mat[0] * is1; const sm12 = mat[1] * is2; const sm13 = mat[2] * is3; const sm21 = mat[4] * is1; const sm22 = mat[5] * is2; const sm23 = mat[6] * is3; const sm31 = mat[8] * is1; const sm32 = mat[9] * is2; const sm33 = mat[10] * is3; const trace = sm11 + sm22 + sm33; let S = 0; if (trace > 0) { S = Math.sqrt(trace + 1) * 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 + 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 + 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 + 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; } function decompose(out_r, out_t, out_s, mat) { out_t[0] = mat[12]; out_t[1] = mat[13]; out_t[2] = mat[14]; const m11 = mat[0]; const m12 = mat[1]; const m13 = mat[2]; const m21 = mat[4]; const m22 = mat[5]; const m23 = mat[6]; const m31 = mat[8]; const m32 = mat[9]; const 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); const is1 = 1 / out_s[0]; const is2 = 1 / out_s[1]; const is3 = 1 / out_s[2]; const sm11 = m11 * is1; const sm12 = m12 * is2; const sm13 = m13 * is3; const sm21 = m21 * is1; const sm22 = m22 * is2; const sm23 = m23 * is3; const sm31 = m31 * is1; const sm32 = m32 * is2; const sm33 = m33 * is3; const trace = sm11 + sm22 + sm33; let S = 0; if (trace > 0) { S = Math.sqrt(trace + 1) * 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 + 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 + 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 + 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; } function fromRotationTranslationScale(out, q, v, s2) { const x2 = q[0]; const y2 = q[1]; const z = q[2]; const w = q[3]; const x22 = x2 + x2; const y22 = y2 + y2; const z2 = z + z; const xx = x2 * x22; const xy = x2 * y22; const xz = x2 * z2; const yy = y2 * y22; const yz = y2 * z2; const zz = z * z2; const wx = w * x22; const wy = w * y22; const wz = w * z2; const sx = s2[0]; const sy = s2[1]; const sz = s2[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; } function fromRotationTranslationScaleOrigin(out, q, v, s2, o2) { const x2 = q[0]; const y2 = q[1]; const z = q[2]; const w = q[3]; const x22 = x2 + x2; const y22 = y2 + y2; const z2 = z + z; const xx = x2 * x22; const xy = x2 * y22; const xz = x2 * z2; const yy = y2 * y22; const yz = y2 * z2; const zz = z * z2; const wx = w * x22; const wy = w * y22; const wz = w * z2; const sx = s2[0]; const sy = s2[1]; const sz = s2[2]; const ox = o2[0]; const oy = o2[1]; const oz = o2[2]; const out0 = (1 - (yy + zz)) * sx; const out1 = (xy + wz) * sx; const out2 = (xz - wy) * sx; const out4 = (xy - wz) * sy; const out5 = (1 - (xx + zz)) * sy; const out6 = (yz + wx) * sy; const out8 = (xz + wy) * sz; const out9 = (yz - wx) * sz; const 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; } function fromQuat3(out, q) { const x2 = q[0]; const y2 = q[1]; const z = q[2]; const w = q[3]; const x22 = x2 + x2; const y22 = y2 + y2; const z2 = z + z; const xx = x2 * x22; const yx = y2 * x22; const yy = y2 * y22; const zx = z * x22; const zy = z * y22; const zz = z * z2; const wx = w * x22; const wy = w * y22; const 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; } function frustum(out, left, right, bottom, top, near, far) { const rl = 1 / (right - left); const tb = 1 / (top - bottom); const 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; } function perspectiveNO(out, fovy, aspect, near, far) { const f2 = 1 / Math.tan(fovy / 2); out[0] = f2 / aspect; out[1] = 0; out[2] = 0; out[3] = 0; out[4] = 0; out[5] = f2; 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) { const 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; } var perspective = perspectiveNO; function perspectiveZO(out, fovy, aspect, near, far) { const f2 = 1 / Math.tan(fovy / 2); out[0] = f2 / aspect; out[1] = 0; out[2] = 0; out[3] = 0; out[4] = 0; out[5] = f2; 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) { const nf = 1 / (near - far); out[10] = far * nf; out[14] = far * near * nf; } else { out[10] = -1; out[14] = -near; } return out; } function perspectiveFromFieldOfView(out, fov, near, far) { const upTan = Math.tan(fov.upDegrees * Math.PI / 180); const downTan = Math.tan(fov.downDegrees * Math.PI / 180); const leftTan = Math.tan(fov.leftDegrees * Math.PI / 180); const rightTan = Math.tan(fov.rightDegrees * Math.PI / 180); const xScale = 2 / (leftTan + rightTan); const yScale = 2 / (upTan + downTan); out[0] = xScale; out[1] = 0; out[2] = 0; out[3] = 0; out[4] = 0; out[5] = yScale; out[6] = 0; out[7] = 0; out[8] = -((leftTan - rightTan) * xScale * 0.5); out[9] = (upTan - downTan) * yScale * 0.5; out[10] = far / (near - far); out[11] = -1; out[12] = 0; out[13] = 0; out[14] = far * near / (near - far); out[15] = 0; return out; } function orthoNO(out, left, right, bottom, top, near, far) { const lr = 1 / (left - right); const bt = 1 / (bottom - top); const 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; } var ortho = orthoNO; function orthoZO(out, left, right, bottom, top, near, far) { const lr = 1 / (left - right); const bt = 1 / (bottom - top); const 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; } function lookAt(out, eye, center, up) { let len2; let x0; let x1; let x2; let y0; let y1; let y2; let z0; let z1; let z2; const eyex = eye[0]; const eyey = eye[1]; const eyez = eye[2]; const upx = up[0]; const upy = up[1]; const upz = up[2]; const centerx = center[0]; const centery = center[1]; const centerz = center[2]; if (Math.abs(eyex - centerx) < EPSILON && Math.abs(eyey - centery) < EPSILON && Math.abs(eyez - centerz) < EPSILON) { return identity(out); } z0 = eyex - centerx; z1 = eyey - centery; z2 = eyez - centerz; len2 = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2); z0 *= len2; z1 *= len2; z2 *= len2; x0 = upy * z2 - upz * z1; x1 = upz * z0 - upx * z2; x2 = upx * z1 - upy * z0; len2 = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2); if (!len2) { x0 = 0; x1 = 0; x2 = 0; } else { len2 = 1 / len2; x0 *= len2; x1 *= len2; x2 *= len2; } y0 = z1 * x2 - z2 * x1; y1 = z2 * x0 - z0 * x2; y2 = z0 * x1 - z1 * x0; len2 = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2); if (!len2) { y0 = 0; y1 = 0; y2 = 0; } else { len2 = 1 / len2; y0 *= len2; y1 *= len2; y2 *= len2; } 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; } function targetTo(out, eye, target, up) { const eyex = eye[0]; const eyey = eye[1]; const eyez = eye[2]; const upx = up[0]; const upy = up[1]; const upz = up[2]; let z0 = eyex - target[0]; let z1 = eyey - target[1]; let z2 = eyez - target[2]; let len2 = z0 * z0 + z1 * z1 + z2 * z2; if (len2 > 0) { len2 = 1 / Math.sqrt(len2); z0 *= len2; z1 *= len2; z2 *= len2; } let x0 = upy * z2 - upz * z1; let x1 = upz * z0 - upx * z2; let x2 = upx * z1 - upy * z0; len2 = x0 * x0 + x1 * x1 + x2 * x2; if (len2 > 0) { len2 = 1 / Math.sqrt(len2); x0 *= len2; x1 *= len2; x2 *= len2; } 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; } function str2(a2) { return `mat4(${a2[0]}, ${a2[1]}, ${a2[2]}, ${a2[3]}, ${a2[4]}, ${a2[5]}, ${a2[6]}, ${a2[7]}, ${a2[8]}, ${a2[9]}, ${a2[10]}, ${a2[11]}, ${a2[12]}, ${a2[13]}, ${a2[14]}, ${a2[15]})`; } function frob(a2) { return Math.sqrt(a2[0] * a2[0] + a2[1] * a2[1] + a2[2] * a2[2] + a2[3] * a2[3] + a2[4] * a2[4] + a2[5] * a2[5] + a2[6] * a2[6] + a2[7] * a2[7] + a2[8] * a2[8] + a2[9] * a2[9] + a2[10] * a2[10] + a2[11] * a2[11] + a2[12] * a2[12] + a2[13] * a2[13] + a2[14] * a2[14] + a2[15] * a2[15]); } function add2(out, a2, b) { out[0] = a2[0] + b[0]; out[1] = a2[1] + b[1]; out[2] = a2[2] + b[2]; out[3] = a2[3] + b[3]; out[4] = a2[4] + b[4]; out[5] = a2[5] + b[5]; out[6] = a2[6] + b[6]; out[7] = a2[7] + b[7]; out[8] = a2[8] + b[8]; out[9] = a2[9] + b[9]; out[10] = a2[10] + b[10]; out[11] = a2[11] + b[11]; out[12] = a2[12] + b[12]; out[13] = a2[13] + b[13]; out[14] = a2[14] + b[14]; out[15] = a2[15] + b[15]; return out; } function subtract2(out, a2, b) { out[0] = a2[0] - b[0]; out[1] = a2[1] - b[1]; out[2] = a2[2] - b[2]; out[3] = a2[3] - b[3]; out[4] = a2[4] - b[4]; out[5] = a2[5] - b[5]; out[6] = a2[6] - b[6]; out[7] = a2[7] - b[7]; out[8] = a2[8] - b[8]; out[9] = a2[9] - b[9]; out[10] = a2[10] - b[10]; out[11] = a2[11] - b[11]; out[12] = a2[12] - b[12]; out[13] = a2[13] - b[13]; out[14] = a2[14] - b[14]; out[15] = a2[15] - b[15]; return out; } function multiplyScalar(out, a2, b) { out[0] = a2[0] * b; out[1] = a2[1] * b; out[2] = a2[2] * b; out[3] = a2[3] * b; out[4] = a2[4] * b; out[5] = a2[5] * b; out[6] = a2[6] * b; out[7] = a2[7] * b; out[8] = a2[8] * b; out[9] = a2[9] * b; out[10] = a2[10] * b; out[11] = a2[11] * b; out[12] = a2[12] * b; out[13] = a2[13] * b; out[14] = a2[14] * b; out[15] = a2[15] * b; return out; } function multiplyScalarAndAdd(out, a2, b, scale6) { out[0] = a2[0] + b[0] * scale6; out[1] = a2[1] + b[1] * scale6; out[2] = a2[2] + b[2] * scale6; out[3] = a2[3] + b[3] * scale6; out[4] = a2[4] + b[4] * scale6; out[5] = a2[5] + b[5] * scale6; out[6] = a2[6] + b[6] * scale6; out[7] = a2[7] + b[7] * scale6; out[8] = a2[8] + b[8] * scale6; out[9] = a2[9] + b[9] * scale6; out[10] = a2[10] + b[10] * scale6; out[11] = a2[11] + b[11] * scale6; out[12] = a2[12] + b[12] * scale6; out[13] = a2[13] + b[13] * scale6; out[14] = a2[14] + b[14] * scale6; out[15] = a2[15] + b[15] * scale6; return out; } function exactEquals2(a2, b) { return a2[0] === b[0] && a2[1] === b[1] && a2[2] === b[2] && a2[3] === b[3] && a2[4] === b[4] && a2[5] === b[5] && a2[6] === b[6] && a2[7] === b[7] && a2[8] === b[8] && a2[9] === b[9] && a2[10] === b[10] && a2[11] === b[11] && a2[12] === b[12] && a2[13] === b[13] && a2[14] === b[14] && a2[15] === b[15]; } function equals3(a2, b) { const a0 = a2[0]; const a1 = a2[1]; const a22 = a2[2]; const a3 = a2[3]; const a4 = a2[4]; const a5 = a2[5]; const a6 = a2[6]; const a7 = a2[7]; const a8 = a2[8]; const a9 = a2[9]; const a10 = a2[10]; const a11 = a2[11]; const a12 = a2[12]; const a13 = a2[13]; const a14 = a2[14]; const a15 = a2[15]; const b0 = b[0]; const b1 = b[1]; const b2 = b[2]; const b3 = b[3]; const b4 = b[4]; const b5 = b[5]; const b6 = b[6]; const b7 = b[7]; const b8 = b[8]; const b9 = b[9]; const b10 = b[10]; const b11 = b[11]; const b12 = b[12]; const b13 = b[13]; const b14 = b[14]; const b15 = b[15]; return Math.abs(a0 - b0) <= EPSILON * Math.max(1, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1, Math.abs(a1), Math.abs(b1)) && Math.abs(a22 - b2) <= EPSILON * Math.max(1, Math.abs(a22), Math.abs(b2)) && Math.abs(a3 - b3) <= EPSILON * Math.max(1, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= EPSILON * Math.max(1, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= EPSILON * Math.max(1, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= EPSILON * Math.max(1, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= EPSILON * Math.max(1, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= EPSILON * Math.max(1, Math.abs(a8), Math.abs(b8)) && Math.abs(a9 - b9) <= EPSILON * Math.max(1, Math.abs(a9), Math.abs(b9)) && Math.abs(a10 - b10) <= EPSILON * Math.max(1, Math.abs(a10), Math.abs(b10)) && Math.abs(a11 - b11) <= EPSILON * Math.max(1, Math.abs(a11), Math.abs(b11)) && Math.abs(a12 - b12) <= EPSILON * Math.max(1, Math.abs(a12), Math.abs(b12)) && Math.abs(a13 - b13) <= EPSILON * Math.max(1, Math.abs(a13), Math.abs(b13)) && Math.abs(a14 - b14) <= EPSILON * Math.max(1, Math.abs(a14), Math.abs(b14)) && Math.abs(a15 - b15) <= EPSILON * Math.max(1, Math.abs(a15), Math.abs(b15)); } var mul2 = multiply3; var sub2 = subtract2; // ../../node_modules/@math.gl/core/dist/gl-matrix/vec4.js function create5() { const out = new ARRAY_TYPE(4); if (ARRAY_TYPE != Float32Array) { out[0] = 0; out[1] = 0; out[2] = 0; out[3] = 0; } return out; } function add3(out, a2, b) { out[0] = a2[0] + b[0]; out[1] = a2[1] + b[1]; out[2] = a2[2] + b[2]; out[3] = a2[3] + b[3]; return out; } function scale4(out, a2, b) { out[0] = a2[0] * b; out[1] = a2[1] * b; out[2] = a2[2] * b; out[3] = a2[3] * b; return out; } function length2(a2) { const x2 = a2[0]; const y2 = a2[1]; const z = a2[2]; const w = a2[3]; return Math.sqrt(x2 * x2 + y2 * y2 + z * z + w * w); } function squaredLength2(a2) { const x2 = a2[0]; const y2 = a2[1]; const z = a2[2]; const w = a2[3]; return x2 * x2 + y2 * y2 + z * z + w * w; } function normalize2(out, a2) { const x2 = a2[0]; const y2 = a2[1]; const z = a2[2]; const w = a2[3]; let len2 = x2 * x2 + y2 * y2 + z * z + w * w; if (len2 > 0) { len2 = 1 / Math.sqrt(len2); } out[0] = x2 * len2; out[1] = y2 * len2; out[2] = z * len2; out[3] = w * len2; return out; } function dot2(a2, b) { return a2[0] * b[0] + a2[1] * b[1] + a2[2] * b[2] + a2[3] * b[3]; } function lerp3(out, a2, b, t2) { const ax = a2[0]; const ay = a2[1]; const az = a2[2]; const aw = a2[3]; out[0] = ax + t2 * (b[0] - ax); out[1] = ay + t2 * (b[1] - ay); out[2] = az + t2 * (b[2] - az); out[3] = aw + t2 * (b[3] - aw); return out; } function transformMat43(out, a2, m) { const x2 = a2[0]; const y2 = a2[1]; const z = a2[2]; const w = a2[3]; out[0] = m[0] * x2 + m[4] * y2 + m[8] * z + m[12] * w; out[1] = m[1] * x2 + m[5] * y2 + m[9] * z + m[13] * w; out[2] = m[2] * x2 + m[6] * y2 + m[10] * z + m[14] * w; out[3] = m[3] * x2 + m[7] * y2 + m[11] * z + m[15] * w; return out; } function transformQuat2(out, a2, q) { const x2 = a2[0]; const y2 = a2[1]; const z = a2[2]; const qx = q[0]; const qy = q[1]; const qz = q[2]; const qw = q[3]; const ix = qw * x2 + qy * z - qz * y2; const iy = qw * y2 + qz * x2 - qx * z; const iz = qw * z + qx * y2 - qy * x2; const iw = -qx * x2 - qy * y2 - qz * z; out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy; out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz; out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx; out[3] = a2[3]; return out; } var forEach3 = function() { const vec = create5(); return function(a2, stride, offset, count, fn, arg) { let i3; let l2; if (!stride) { stride = 4; } if (!offset) { offset = 0; } if (count) { l2 = Math.min(count * stride + offset, a2.length); } else { l2 = a2.length; } for (i3 = offset; i3 < l2; i3 += stride) { vec[0] = a2[i3]; vec[1] = a2[i3 + 1]; vec[2] = a2[i3 + 2]; vec[3] = a2[i3 + 3]; fn(vec, vec, arg); a2[i3] = vec[0]; a2[i3 + 1] = vec[1]; a2[i3 + 2] = vec[2]; a2[i3 + 3] = vec[3]; } return a2; }; }(); // ../../node_modules/@math.gl/core/dist/classes/matrix4.js var INDICES2; (function(INDICES3) { INDICES3[INDICES3["COL0ROW0"] = 0] = "COL0ROW0"; INDICES3[INDICES3["COL0ROW1"] = 1] = "COL0ROW1"; INDICES3[INDICES3["COL0ROW2"] = 2] = "COL0ROW2"; INDICES3[INDICES3["COL0ROW3"] = 3] = "COL0ROW3"; INDICES3[INDICES3["COL1ROW0"] = 4] = "COL1ROW0"; INDICES3[INDICES3["COL1ROW1"] = 5] = "COL1ROW1"; INDICES3[INDICES3["COL1ROW2"] = 6] = "COL1ROW2"; INDICES3[INDICES3["COL1ROW3"] = 7] = "COL1ROW3"; INDICES3[INDICES3["COL2ROW0"] = 8] = "COL2ROW0"; INDICES3[INDICES3["COL2ROW1"] = 9] = "COL2ROW1"; INDICES3[INDICES3["COL2ROW2"] = 10] = "COL2ROW2"; INDICES3[INDICES3["COL2ROW3"] = 11] = "COL2ROW3"; INDICES3[INDICES3["COL3ROW0"] = 12] = "COL3ROW0"; INDICES3[INDICES3["COL3ROW1"] = 13] = "COL3ROW1"; INDICES3[INDICES3["COL3ROW2"] = 14] = "COL3ROW2"; INDICES3[INDICES3["COL3ROW3"] = 15] = "COL3ROW3"; })(INDICES2 || (INDICES2 = {})); var DEFAULT_FOVY = 45 * Math.PI / 180; var DEFAULT_ASPECT = 1; var DEFAULT_NEAR = 0.1; var DEFAULT_FAR = 500; var IDENTITY_MATRIX2 = Object.freeze([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); var Matrix4 = class extends Matrix { static get IDENTITY() { return getIdentityMatrix2(); } static get ZERO() { return getZeroMatrix2(); } get ELEMENTS() { return 16; } get RANK() { return 4; } get INDICES() { return INDICES2; } constructor(array) { super(-0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0); if (arguments.length === 1 && Array.isArray(array)) { this.copy(array); } else { this.identity(); } } copy(array) { this[0] = array[0]; this[1] = array[1]; this[2] = array[2]; this[3] = array[3]; this[4] = array[4]; this[5] = array[5]; this[6] = array[6]; this[7] = array[7]; this[8] = array[8]; this[9] = array[9]; this[10] = array[10]; this[11] = array[11]; this[12] = array[12]; this[13] = array[13]; this[14] = array[14]; this[15] = array[15]; return this.check(); } set(m00, m10, m20, m30, m01, m11, m21, m31, m02, m12, m22, m32, m03, m13, m23, m33) { this[0] = m00; this[1] = m10; this[2] = m20; this[3] = m30; this[4] = m01; this[5] = m11; this[6] = m21; this[7] = m31; this[8] = m02; this[9] = m12; this[10] = m22; this[11] = m32; this[12] = m03; this[13] = m13; this[14] = m23; this[15] = m33; return this.check(); } setRowMajor(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) { this[0] = m00; this[1] = m10; this[2] = m20; this[3] = m30; this[4] = m01; this[5] = m11; this[6] = m21; this[7] = m31; this[8] = m02; this[9] = m12; this[10] = m22; this[11] = m32; this[12] = m03; this[13] = m13; this[14] = m23; this[15] = m33; return this.check(); } toRowMajor(result) { result[0] = this[0]; result[1] = this[4]; result[2] = this[8]; result[3] = this[12]; result[4] = this[1]; result[5] = this[5]; result[6] = this[9]; result[7] = this[13]; result[8] = this[2]; result[9] = this[6]; result[10] = this[10]; result[11] = this[14]; result[12] = this[3]; result[13] = this[7]; result[14] = this[11]; result[15] = this[15]; return result; } identity() { return this.copy(IDENTITY_MATRIX2); } fromObject(object) { return this.check(); } fromQuaternion(quaternion) { fromQuat3(this, quaternion); return this.check(); } frustum(view) { const { left, right, bottom, top, near = DEFAULT_NEAR, far = DEFAULT_FAR } = view; if (far === Infinity) { computeInfinitePerspectiveOffCenter(this, left, right, bottom, top, near); } else { frustum(this, left, right, bottom, top, near, far); } return this.check(); } lookAt(view) { const { eye, center = [0, 0, 0], up = [0, 1, 0] } = view; lookAt(this, eye, center, up); return this.check(); } ortho(view) { const { left, right, bottom, top, near = DEFAULT_NEAR, far = DEFAULT_FAR } = view; ortho(this, left, right, bottom, top, near, far); return this.check(); } orthographic(view) { const { fovy = DEFAULT_FOVY, aspect = DEFAULT_ASPECT, focalDistance = 1, near = DEFAULT_NEAR, far = DEFAULT_FAR } = view; checkRadians(fovy); const halfY = fovy / 2; const top = focalDistance * Math.tan(halfY); const right = top * aspect; return this.ortho({ left: -right, right, bottom: -top, top, near, far }); } perspective(view) { const { fovy = 45 * Math.PI / 180, aspect = 1, near = 0.1, far = 500 } = view; checkRadians(fovy); perspective(this, fovy, aspect, near, far); return this.check(); } determinant() { return determinant2(this); } getScale(result = [-0, -0, -0]) { result[0] = Math.sqrt(this[0] * this[0] + this[1] * this[1] + this[2] * this[2]); result[1] = Math.sqrt(this[4] * this[4] + this[5] * this[5] + this[6] * this[6]); result[2] = Math.sqrt(this[8] * this[8] + this[9] * this[9] + this[10] * this[10]); return result; } getTranslation(result = [-0, -0, -0]) { result[0] = this[12]; result[1] = this[13]; result[2] = this[14]; return result; } getRotation(result, scaleResult) { result = result || [-0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0]; scaleResult = scaleResult || [-0, -0, -0]; const scale6 = this.getScale(scaleResult); const inverseScale0 = 1 / scale6[0]; const inverseScale1 = 1 / scale6[1]; const inverseScale2 = 1 / scale6[2]; result[0] = this[0] * inverseScale0; result[1] = this[1] * inverseScale1; result[2] = this[2] * inverseScale2; result[3] = 0; result[4] = this[4] * inverseScale0; result[5] = this[5] * inverseScale1; result[6] = this[6] * inverseScale2; result[7] = 0; result[8] = this[8] * inverseScale0; result[9] = this[9] * inverseScale1; result[10] = this[10] * inverseScale2; result[11] = 0; result[12] = 0; result[13] = 0; result[14] = 0; result[15] = 1; return result; } getRotationMatrix3(result, scaleResult) { result = result || [-0, -0, -0, -0, -0, -0, -0, -0, -0]; scaleResult = scaleResult || [-0, -0, -0]; const scale6 = this.getScale(scaleResult); const inverseScale0 = 1 / scale6[0]; const inverseScale1 = 1 / scale6[1]; const inverseScale2 = 1 / scale6[2]; result[0] = this[0] * inverseScale0; result[1] = this[1] * inverseScale1; result[2] = this[2] * inverseScale2; result[3] = this[4] * inverseScale0; result[4] = this[5] * inverseScale1; result[5] = this[6] * inverseScale2; result[6] = this[8] * inverseScale0; result[7] = this[9] * inverseScale1; result[8] = this[10] * inverseScale2; return result; } transpose() { transpose2(this, this); return this.check(); } invert() { invert2(this, this); return this.check(); } multiplyLeft(a2) { multiply3(this, a2, this); return this.check(); } multiplyRight(a2) { multiply3(this, this, a2); return this.check(); } rotateX(radians2) { rotateX2(this, this, radians2); return this.check(); } rotateY(radians2) { rotateY2(this, this, radians2); return this.check(); } rotateZ(radians2) { rotateZ2(this, this, radians2); return this.check(); } rotateXYZ(angleXYZ) { return this.rotateX(angleXYZ[0]).rotateY(angleXYZ[1]).rotateZ(angleXYZ[2]); } rotateAxis(radians2, axis) { rotate2(this, this, radians2, axis); return this.check(); } scale(factor) { scale3(this, this, Array.isArray(factor) ? factor : [factor, factor, factor]); return this.check(); } translate(vector) { translate2(this, this, vector); return this.check(); } transform(vector, result) { if (vector.length === 4) { result = transformMat43(result || [-0, -0, -0, -0], vector, this); checkVector(result, 4); return result; } return this.transformAsPoint(vector, result); } transformAsPoint(vector, result) { const { length: length5 } = vector; let out; switch (length5) { case 2: out = transformMat4(result || [-0, -0], vector, this); break; case 3: out = transformMat42(result || [-0, -0, -0], vector, this); break; default: throw new Error("Illegal vector"); } checkVector(out, vector.length); return out; } transformAsVector(vector, result) { let out; switch (vector.length) { case 2: out = vec2_transformMat4AsVector(result || [-0, -0], vector, this); break; case 3: out = vec3_transformMat4AsVector(result || [-0, -0, -0], vector, this); break; default: throw new Error("Illegal vector"); } checkVector(out, vector.length); return out; } transformPoint(vector, result) { return this.transformAsPoint(vector, result); } transformVector(vector, result) { return this.transformAsPoint(vector, result); } transformDirection(vector, result) { return this.transformAsVector(vector, result); } makeRotationX(radians2) { return this.identity().rotateX(radians2); } makeTranslation(x2, y2, z) { return this.identity().translate([x2, y2, z]); } }; var ZERO3; var IDENTITY; function getZeroMatrix2() { if (!ZERO3) { ZERO3 = new Matrix4([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); Object.freeze(ZERO3); } return ZERO3; } function getIdentityMatrix2() { if (!IDENTITY) { IDENTITY = new Matrix4(); Object.freeze(IDENTITY); } return IDENTITY; } function checkRadians(possiblyDegrees) { if (possiblyDegrees > Math.PI * 2) { throw Error("expected radians"); } } function computeInfinitePerspectiveOffCenter(result, left, right, bottom, top, near) { const column0Row0 = 2 * near / (right - left); const column1Row1 = 2 * near / (top - bottom); const column2Row0 = (right + left) / (right - left); const column2Row1 = (top + bottom) / (top - bottom); const column2Row2 = -1; const column2Row3 = -1; const column3Row2 = -2 * near; result[0] = column0Row0; result[1] = 0; result[2] = 0; result[3] = 0; result[4] = 0; result[5] = column1Row1; result[6] = 0; result[7] = 0; result[8] = column2Row0; result[9] = column2Row1; result[10] = column2Row2; result[11] = column2Row3; result[12] = 0; result[13] = 0; result[14] = column3Row2; result[15] = 0; return result; } // ../../node_modules/@math.gl/core/dist/gl-matrix/quat.js function create6() { const out = new ARRAY_TYPE(4); if (ARRAY_TYPE != Float32Array) { out[0] = 0; out[1] = 0; out[2] = 0; } out[3] = 1; return out; } function identity2(out) { out[0] = 0; out[1] = 0; out[2] = 0; out[3] = 1; return out; } function setAxisAngle(out, axis, rad) { rad = rad * 0.5; const s2 = Math.sin(rad); out[0] = s2 * axis[0]; out[1] = s2 * axis[1]; out[2] = s2 * axis[2]; out[3] = Math.cos(rad); return out; } function multiply4(out, a2, b) { const ax = a2[0]; const ay = a2[1]; const az = a2[2]; const aw = a2[3]; const bx = b[0]; const by = b[1]; const bz = b[2]; const 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; } function rotateX3(out, a2, rad) { rad *= 0.5; const ax = a2[0]; const ay = a2[1]; const az = a2[2]; const aw = a2[3]; const bx = Math.sin(rad); const 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; } function rotateY3(out, a2, rad) { rad *= 0.5; const ax = a2[0]; const ay = a2[1]; const az = a2[2]; const aw = a2[3]; const by = Math.sin(rad); const 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; } function rotateZ3(out, a2, rad) { rad *= 0.5; const ax = a2[0]; const ay = a2[1]; const az = a2[2]; const aw = a2[3]; const bz = Math.sin(rad); const 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; } function calculateW(out, a2) { const x2 = a2[0]; const y2 = a2[1]; const z = a2[2]; out[0] = x2; out[1] = y2; out[2] = z; out[3] = Math.sqrt(Math.abs(1 - x2 * x2 - y2 * y2 - z * z)); return out; } function slerp2(out, a2, b, t2) { const ax = a2[0]; const ay = a2[1]; const az = a2[2]; const aw = a2[3]; let bx = b[0]; let by = b[1]; let bz = b[2]; let bw = b[3]; let cosom; let omega; let scale0; let scale1; let sinom; cosom = ax * bx + ay * by + az * bz + aw * bw; if (cosom < 0) { cosom = -cosom; bx = -bx; by = -by; bz = -bz; bw = -bw; } if (1 - cosom > EPSILON) { omega = Math.acos(cosom); sinom = Math.sin(omega); scale0 = Math.sin((1 - t2) * omega) / sinom; scale1 = Math.sin(t2 * omega) / sinom; } else { scale0 = 1 - t2; scale1 = t2; } 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; } function invert3(out, a2) { const a0 = a2[0]; const a1 = a2[1]; const a22 = a2[2]; const a3 = a2[3]; const dot4 = a0 * a0 + a1 * a1 + a22 * a22 + a3 * a3; const invDot = dot4 ? 1 / dot4 : 0; out[0] = -a0 * invDot; out[1] = -a1 * invDot; out[2] = -a22 * invDot; out[3] = a3 * invDot; return out; } function conjugate(out, a2) { out[0] = -a2[0]; out[1] = -a2[1]; out[2] = -a2[2]; out[3] = a2[3]; return out; } function fromMat3(out, m) { const fTrace = m[0] + m[4] + m[8]; let fRoot; if (fTrace > 0) { fRoot = Math.sqrt(fTrace + 1); out[3] = 0.5 * fRoot; fRoot = 0.5 / fRoot; out[0] = (m[5] - m[7]) * fRoot; out[1] = (m[6] - m[2]) * fRoot; out[2] = (m[1] - m[3]) * fRoot; } else { let i3 = 0; if (m[4] > m[0]) i3 = 1; if (m[8] > m[i3 * 3 + i3]) i3 = 2; const j = (i3 + 1) % 3; const k = (i3 + 2) % 3; fRoot = Math.sqrt(m[i3 * 3 + i3] - m[j * 3 + j] - m[k * 3 + k] + 1); out[i3] = 0.5 * fRoot; fRoot = 0.5 / fRoot; out[3] = (m[j * 3 + k] - m[k * 3 + j]) * fRoot; out[j] = (m[j * 3 + i3] + m[i3 * 3 + j]) * fRoot; out[k] = (m[k * 3 + i3] + m[i3 * 3 + k]) * fRoot; } return out; } var add4 = add3; var scale5 = scale4; var dot3 = dot2; var lerp4 = lerp3; var length3 = length2; var squaredLength3 = squaredLength2; var normalize3 = normalize2; var rotationTo = function() { const tmpvec3 = create2(); const xUnitVec3 = fromValues(1, 0, 0); const yUnitVec3 = fromValues(0, 1, 0); return function(out, a2, b) { const dot4 = dot(a2, b); if (dot4 < -0.999999) { cross(tmpvec3, xUnitVec3, a2); if (len(tmpvec3) < 1e-6) cross(tmpvec3, yUnitVec3, a2); normalize(tmpvec3, tmpvec3); setAxisAngle(out, tmpvec3, Math.PI); return out; } else if (dot4 > 0.999999) { out[0] = 0; out[1] = 0; out[2] = 0; out[3] = 1; return out; } cross(tmpvec3, a2, b); out[0] = tmpvec3[0]; out[1] = tmpvec3[1]; out[2] = tmpvec3[2]; out[3] = 1 + dot4; return normalize3(out, out); }; }(); var sqlerp = function() { const temp1 = create6(); const temp2 = create6(); return function(out, a2, b, c, d, t2) { slerp2(temp1, a2, d, t2); slerp2(temp2, b, c, t2); slerp2(out, temp1, temp2, 2 * t2 * (1 - t2)); return out; }; }(); var setAxes = function() { const matr = create3(); 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 normalize3(out, fromMat3(out, matr)); }; }(); // ../../node_modules/@math.gl/core/dist/classes/quaternion.js var IDENTITY_QUATERNION = [0, 0, 0, 1]; var Quaternion = class extends MathArray { constructor(x2 = 0, y2 = 0, z = 0, w = 1) { super(-0, -0, -0, -0); if (Array.isArray(x2) && arguments.length === 1) { this.copy(x2); } else { this.set(x2, y2, z, w); } } copy(array) { this[0] = array[0]; this[1] = array[1]; this[2] = array[2]; this[3] = array[3]; return this.check(); } set(x2, y2, z, w) { this[0] = x2; this[1] = y2; this[2] = z; this[3] = w; return this.check(); } fromObject(object) { this[0] = object.x; this[1] = object.y; this[2] = object.z; this[3] = object.w; return this.check(); } fromMatrix3(m) { fromMat3(this, m); return this.check(); } fromAxisRotation(axis, rad) { setAxisAngle(this, axis, rad); return this.check(); } identity() { identity2(this); return this.check(); } setAxisAngle(axis, rad) { return this.fromAxisRotation(axis, rad); } get ELEMENTS() { return 4; } get x() { return this[0]; } set x(value) { this[0] = checkNumber(value); } get y() { return this[1]; } set y(value) { this[1] = checkNumber(value); } get z() { return this[2]; } set z(value) { this[2] = checkNumber(value); } get w() { return this[3]; } set w(value) { this[3] = checkNumber(value); } len() { return length3(this); } lengthSquared() { return squaredLength3(this); } dot(a2) { return dot3(this, a2); } rotationTo(vectorA, vectorB) { rotationTo(this, vectorA, vectorB); return this.check(); } add(a2) { add4(this, this, a2); return this.check(); } calculateW() { calculateW(this, this); return this.check(); } conjugate() { conjugate(this, this); return this.check(); } invert() { invert3(this, this); return this.check(); } lerp(a2, b, t2) { if (t2 === void 0) { return this.lerp(this, a2, b); } lerp4(this, a2, b, t2); return this.check(); } multiplyRight(a2) { multiply4(this, this, a2); return this.check(); } multiplyLeft(a2) { multiply4(this, a2, this); return this.check(); } normalize() { const length5 = this.len(); const l2 = length5 > 0 ? 1 / length5 : 0; this[0] = this[0] * l2; this[1] = this[1] * l2; this[2] = this[2] * l2; this[3] = this[3] * l2; if (length5 === 0) { this[3] = 1; } return this.check(); } rotateX(rad) { rotateX3(this, this, rad); return this.check(); } rotateY(rad) { rotateY3(this, this, rad); return this.check(); } rotateZ(rad) { rotateZ3(this, this, rad); return this.check(); } scale(b) { scale5(this, this, b); return this.check(); } slerp(arg0, arg1, arg2) { let start; let target; let ratio; switch (arguments.length) { case 1: ({ start = IDENTITY_QUATERNION, target, ratio } = arg0); break; case 2: start = this; target = arg0; ratio = arg1; break; default: start = arg0; target = arg1; ratio = arg2; } slerp2(this, start, target, ratio); return this.check(); } transformVector4(vector, result = new Vector4()) { transformQuat2(result, vector, this); return checkVector(result, 4); } lengthSq() { return this.lengthSquared(); } setFromAxisAngle(axis, rad) { return this.setAxisAngle(axis, rad); } premultiply(a2) { return this.multiplyLeft(a2); } multiply(a2) { return this.multiplyRight(a2); } }; // ../../node_modules/@math.gl/core/dist/lib/math-utils.js var math_utils_exports = {}; __export(math_utils_exports, { EPSILON1: () => EPSILON1, EPSILON10: () => EPSILON10, EPSILON11: () => EPSILON11, EPSILON12: () => EPSILON12, EPSILON13: () => EPSILON13, EPSILON14: () => EPSILON14, EPSILON15: () => EPSILON15, EPSILON16: () => EPSILON16, EPSILON17: () => EPSILON17, EPSILON18: () => EPSILON18, EPSILON19: () => EPSILON19, EPSILON2: () => EPSILON2, EPSILON20: () => EPSILON20, EPSILON3: () => EPSILON3, EPSILON4: () => EPSILON4, EPSILON5: () => EPSILON5, EPSILON6: () => EPSILON6, EPSILON7: () => EPSILON7, EPSILON8: () => EPSILON8, EPSILON9: () => EPSILON9, PI_OVER_FOUR: () => PI_OVER_FOUR, PI_OVER_SIX: () => PI_OVER_SIX, PI_OVER_TWO: () => PI_OVER_TWO, TWO_PI: () => TWO_PI }); var EPSILON1 = 0.1; var EPSILON2 = 0.01; var EPSILON3 = 1e-3; var EPSILON4 = 1e-4; var EPSILON5 = 1e-5; var EPSILON6 = 1e-6; var EPSILON7 = 1e-7; var EPSILON8 = 1e-8; var EPSILON9 = 1e-9; var EPSILON10 = 1e-10; var EPSILON11 = 1e-11; var EPSILON12 = 1e-12; var EPSILON13 = 1e-13; var EPSILON14 = 1e-14; var EPSILON15 = 1e-15; var EPSILON16 = 1e-16; var EPSILON17 = 1e-17; var EPSILON18 = 1e-18; var EPSILON19 = 1e-19; var EPSILON20 = 1e-20; var PI_OVER_TWO = Math.PI / 2; var PI_OVER_FOUR = Math.PI / 4; var PI_OVER_SIX = Math.PI / 6; var TWO_PI = Math.PI * 2; // ../../node_modules/@math.gl/web-mercator/dist/assert.js function assert6(condition, message) { if (!condition) { throw new Error(message || "@math.gl/web-mercator: assertion failed."); } } // ../../node_modules/@math.gl/web-mercator/dist/web-mercator-utils.js var PI = Math.PI; var PI_4 = PI / 4; var DEGREES_TO_RADIANS2 = PI / 180; var RADIANS_TO_DEGREES2 = 180 / PI; var TILE_SIZE = 512; function lngLatToWorld(lngLat) { const [lng, lat] = lngLat; assert6(Number.isFinite(lng)); assert6(Number.isFinite(lat) && lat >= -90 && lat <= 90, "invalid latitude"); const lambda2 = lng * DEGREES_TO_RADIANS2; const phi2 = lat * DEGREES_TO_RADIANS2; const x2 = TILE_SIZE * (lambda2 + PI) / (2 * PI); const y2 = TILE_SIZE * (PI + Math.log(Math.tan(PI_4 + phi2 * 0.5))) / (2 * PI); return [x2, y2]; } function worldToLngLat(xy) { const [x2, y2] = xy; const lambda2 = x2 / TILE_SIZE * (2 * PI) - PI; const phi2 = 2 * (Math.atan(Math.exp(y2 / TILE_SIZE * (2 * PI) - PI)) - PI_4); return [lambda2 * RADIANS_TO_DEGREES2, phi2 * RADIANS_TO_DEGREES2]; } // ../../node_modules/@math.gl/web-mercator/dist/get-bounds.js var DEGREES_TO_RADIANS3 = Math.PI / 180; // src/wms-layer/utils.ts var HALF_EARTH_CIRCUMFERENCE = 6378137 * Math.PI; function WGS84ToPseudoMercator(coord) { const mercator = lngLatToWorld(coord); mercator[0] = (mercator[0] / 256 - 1) * HALF_EARTH_CIRCUMFERENCE; mercator[1] = (mercator[1] / 256 - 1) * HALF_EARTH_CIRCUMFERENCE; return mercator; } // src/wms-layer/wms-layer.ts var defaultProps = { id: "imagery-layer", data: "", serviceType: "auto", srs: "auto", layers: { type: "array", compare: true, value: [] }, onMetadataLoad: { type: "function", value: () => { } }, onMetadataLoadError: { type: "function", value: console.error }, onImageLoadStart: { type: "function", value: () => { } }, onImageLoad: { type: "function", value: () => { } }, onImageLoadError: { type: "function", compare: false, value: (requestId, error) => console.error(error, requestId) } }; var WMSLayer = class extends import_core.CompositeLayer { get isLoaded() { return this.state?.loadCounter === 0 && super.isLoaded; } shouldUpdateState() { return true; } initializeState() { this.state._nextRequestId = 0; this.state.lastRequestId = -1; this.state.loadCounter = 0; } updateState({ changeFlags, props, oldProps }) { const { viewport } = this.context; if (changeFlags.dataChanged || props.serviceType !== oldProps.serviceType) { this.state.imageSource = this._createImageSource(props); this._loadMetadata(); this.debounce(() => this.loadImage(viewport, "image source changed"), 0); } else if (!(0, import_core._deepEqual)(props.layers, oldProps.layers, 1)) { this.debounce(() => this.loadImage(viewport, "layers changed"), 0); } else if (changeFlags.viewportChanged) { this.debounce(() => this.loadImage(viewport, "viewport changed")); } } finalizeState() { } renderLayers() { const { bounds, image, lastRequestParameters } = this.state; return image && new import_layers2.BitmapLayer({ ...this.getSubLayerProps({ id: "bitmap" }), _imageCoordinateSystem: lastRequestParameters.srs === "EPSG:4326" ? import_core.COORDINATE_SYSTEM.LNGLAT : import_core.COORDINATE_SYSTEM.CARTESIAN, bounds, image }); } async getFeatureInfoText(x2, y2) { const { lastRequestParameters } = this.state; if (lastRequestParameters) { const featureInfo = await this.state.imageSource.getFeatureInfoText?.({ ...lastRequestParameters, query_layers: lastRequestParameters.layers, x: x2, y: y2, info_format: "application/vnd.ogc.gml" }); return featureInfo; } return ""; } _createImageSource(props) { if (props.data instanceof ImageSource) { return props.data; } if (typeof props.data === "string") { return createImageSource({ url: props.data, loadOptions: props.loadOptions, type: props.serviceType }); } throw new Error("invalid image source in props.data"); } async _loadMetadata() { const { imageSource } = this.state; try { this.state.loadCounter++; const metadata = await imageSource.getMetadata(); if (this.state.imageSource === imageSource) { this.getCurrentLayer()?.props.onMetadataLoad(metadata); } } catch (error) { this.getCurrentLayer()?.props.onMetadataLoadError(error); } finally { this.state.loadCounter--; } } async loadImage(viewport, reason) { const { layers, serviceType } = this.props; if (serviceType === "wms" && layers.length === 0) { return; } const bounds = viewport.getBounds(); const { width, height } = viewport; const requestId = this.getRequestId(); let { srs } = this.props; if (srs === "auto") { srs = viewport.resolution ? "EPSG:4326" : "EPSG:3857"; } const requestParams = { width, height, boundingBox: [ [bounds[0], bounds[1]], [bounds[2], bounds[3]] ], layers, crs: srs }; if (srs === "EPSG:3857") { const min2 = WGS84ToPseudoMercator([bounds[0], bounds[1]]); const max2 = WGS84ToPseudoMercator([bounds[2], bounds[3]]); requestParams.boundingBox = [min2, max2]; } try { this.state.loadCounter++; this.props.onImageLoadStart(requestId); const image = await this.state.imageSource.getImage(requestParams); if (this.state.lastRequestId < requestId) { this.getCurrentLayer()?.props.onImageLoad(requestId); this.setState({ image, bounds, lastRequestParameters: requestParams, lastRequestId: requestId }); } } catch (error) { this.raiseError(error, "Load image"); this.getCurrentLayer()?.props.onImageLoadError(requestId, error); } finally { this.state.loadCounter--; } } getRequestId() { return this.state._nextRequestId++; } debounce(fn, ms = 500) { clearTimeout(this.state._timeoutId); this.state._timeoutId = setTimeout(() => fn(), ms); } }; WMSLayer.layerName = "WMSLayer"; WMSLayer.defaultProps = defaultProps; // src/great-circle-layer/great-circle-layer.ts var import_layers3 = __toESM(require_layers(), 1); var defaultProps2 = { getHeight: { type: "accessor", value: 0 }, greatCircle: true }; var GreatCircleLayer = class extends import_layers3.ArcLayer { }; GreatCircleLayer.layerName = "GreatCircleLayer"; GreatCircleLayer.defaultProps = defaultProps2; // src/geo-cell-layer/GeoCellLayer.ts var import_core2 = __toESM(require_core(), 1); var import_layers4 = __toESM(require_layers(), 1); var defaultProps3 = { ...import_layers4.PolygonLayer.defaultProps }; var GeoCellLayer = class extends import_core2.CompositeLayer { indexToBounds() { return null; } renderLayers() { const { elevationScale, extruded, wireframe, filled, stroked, lineWidthUnits, lineWidthScale, lineWidthMinPixels, lineWidthMaxPixels, lineJointRounded, lineMiterLimit, lineDashJustified, getElevation, getFillColor, getLineColor, getLineWidth } = this.props; const { updateTriggers, material, transitions } = this.props; const CellLayer = this.getSubLayerClass("cell", import_layers4.PolygonLayer); const { updateTriggers: boundsUpdateTriggers, ...boundsProps } = this.indexToBounds() || {}; return new CellLayer( { filled, wireframe, extruded, elevationScale, stroked, lineWidthUnits, lineWidthScale, lineWidthMinPixels, lineWidthMaxPixels, lineJointRounded, lineMiterLimit, lineDashJustified, material, transitions, getElevation, getFillColor, getLineColor, getLineWidth }, this.getSubLayerProps({ id: "cell", updateTriggers: updateTriggers && { ...boundsUpdateTriggers, getElevation: updateTriggers.getElevation, getFillColor: updateTriggers.getFillColor, getLineColor: updateTriggers.getLineColor, getLineWidth: updateTriggers.getLineWidth } }), boundsProps ); } }; GeoCellLayer.layerName = "GeoCellLayer"; GeoCellLayer.defaultProps = defaultProps3; // src/s2-layer/s2-geometry.ts var import_long = __toESM(require_long(), 1); var FACE_BITS = 3; var MAX_LEVEL = 30; var POS_BITS = 2 * MAX_LEVEL + 1; var RADIAN_TO_DEGREE = 180 / Math.PI; function IJToST(ij, order, offsets) { const maxSize = 1 << order; return [(ij[0] + offsets[0]) / maxSize, (ij[1] + offsets[1]) / maxSize]; } function singleSTtoUV(st) { if (st >= 0.5) { return 1 / 3 * (4 * st * st - 1); } return 1 / 3 * (1 - 4 * (1 - st) * (1 - st)); } function STToUV(st) { return [singleSTtoUV(st[0]), singleSTtoUV(st[1])]; } function FaceUVToXYZ(face, [u, v]) { switch (face) { case 0: return [1, u, v]; case 1: return [-u, 1, v]; case 2: return [-u, -v, 1]; case 3: return [-1, -v, -u]; case 4: return [v, -1, -u]; case 5: return [v, u, -1]; default: throw new Error("Invalid face"); } } function XYZToLngLat([x2, y2, z]) { const lat = Math.atan2(z, Math.sqrt(x2 * x2 + y2 * y2)); const lng = Math.atan2(y2, x2); return [lng * RADIAN_TO_DEGREE, lat * RADIAN_TO_DEGREE]; } function toHilbertQuadkey(idS) { let bin = import_long.default.fromString(idS, true, 10).toString(2); while (bin.length < FACE_BITS + POS_BITS) { bin = "0" + bin; } const lsbIndex = bin.lastIndexOf("1"); const faceB = bin.substring(0, 3); const posB = bin.substring(3, lsbIndex); const levelN = posB.length / 2; const faceS = import_long.default.fromString(faceB, true, 2).toString(10); let posS = import_long.default.fromString(posB, true, 2).toString(4); while (posS.length < levelN) { posS = "0" + posS; } return `${faceS}/${posS}`; } function rotateAndFlipQuadrant(n2, point, rx, ry) { if (ry === 0) { if (rx === 1) { point[0] = n2 - 1 - point[0]; point[1] = n2 - 1 - point[1]; } const x2 = point[0]; point[0] = point[1]; point[1] = x2; } } function FromHilbertQuadKey(hilbertQuadkey) { const parts = hilbertQuadkey.split("/"); const face = parseInt(parts[0], 10); const position = parts[1]; const maxLevel = position.length; const point = [0, 0]; let level; for (let i3 = maxLevel - 1; i3 >= 0; i3--) { level = maxLevel - i3; const bit = position[i3]; let rx = 0; let ry = 0; if (bit === "1") { ry = 1; } else if (bit === "2") { rx = 1; ry = 1; } else if (bit === "3") { rx = 1; } const val2 = Math.pow(2, level - 1); rotateAndFlipQuadrant(val2, point, rx, ry); point[0] += val2 * rx; point[1] += val2 * ry; } if (face % 2 === 1) { const t2 = point[0]; point[0] = point[1]; point[1] = t2; } return { face, ij: point, level }; } // src/s2-layer/s2-utils.ts var import_long2 = __toESM(require_long(), 1); function getIdFromToken(token) { const paddedToken = token.padEnd(16, "0"); return import_long2.default.fromString(paddedToken, 16); } var MAX_RESOLUTION = 100; function getGeoBounds({ face, ij, level }) { const offsets = [ [0, 0], [0, 1], [1, 1], [1, 0], [0, 0] ]; const resolution = Math.max(1, Math.ceil(MAX_RESOLUTION * Math.pow(2, -level))); const result = new Float64Array(4 * resolution * 2 + 2); let ptIndex = 0; let prevLng = 0; for (let i3 = 0; i3 < 4; i3++) { const offset = offsets[i3].slice(0); const nextOffset = offsets[i3 + 1]; const stepI = (nextOffset[0] - offset[0]) / resolution; const stepJ = (nextOffset[1] - offset[1]) / resolution; for (let j = 0; j < resolution; j++) { offset[0] += stepI; offset[1] += stepJ; const st = IJToST(ij, level, offset); const uv = STToUV(st); const xyz = FaceUVToXYZ(face, uv); const lngLat = XYZToLngLat(xyz); if (Math.abs(lngLat[1]) > 89.999) { lngLat[0] = prevLng; } const deltaLng = lngLat[0] - prevLng; lngLat[0] += deltaLng > 180 ? -360 : deltaLng < -180 ? 360 : 0; result[ptIndex++] = lngLat[0]; result[ptIndex++] = lngLat[1]; prevLng = lngLat[0]; } } result[ptIndex++] = result[0]; result[ptIndex++] = result[1]; return result; } function getS2QuadKey(token) { if (typeof token === "string") { if (token.indexOf("/") > 0) { return token; } token = getIdFromToken(token); } return toHilbertQuadkey(token.toString()); } function getS2Polygon(token) { const key = getS2QuadKey(token); const s2cell = FromHilbertQuadKey(key); return getGeoBounds(s2cell); } // src/s2-layer/s2-layer.ts var defaultProps4 = { getS2Token: { type: "accessor", value: (d) => d.token } }; var S2Layer = class extends GeoCellLayer { indexToBounds() { const { data, getS2Token } = this.props; return { data, _normalize: false, positionFormat: "XY", getPolygon: (x2, objectInfo) => getS2Polygon(getS2Token(x2, objectInfo)) }; } }; S2Layer.layerName = "S2Layer"; S2Layer.defaultProps = defaultProps4; // src/quadkey-layer/quadkey-utils.ts var TILE_SIZE2 = 512; function quadkeyToWorldBounds(quadkey, coverage) { let x2 = 0; let y2 = 0; let mask = 1 << quadkey.length; const scale6 = mask / TILE_SIZE2; for (let i3 = 0; i3 < quadkey.length; i3++) { mask >>= 1; const q = parseInt(quadkey[i3]); if (q % 2) x2 |= mask; if (q > 1) y2 |= mask; } return [ [x2 / scale6, TILE_SIZE2 - y2 / scale6], [(x2 + coverage) / scale6, TILE_SIZE2 - (y2 + coverage) / scale6] ]; } function getQuadkeyPolygon(quadkey, coverage = 1) { const [topLeft, bottomRight] = quadkeyToWorldBounds(quadkey, coverage); const [w, n2] = worldToLngLat(topLeft); const [e, s2] = worldToLngLat(bottomRight); return [e, n2, e, s2, w, s2, w, n2, e, n2]; } // src/quadkey-layer/quadkey-layer.ts var defaultProps5 = { getQuadkey: { type: "accessor", value: (d) => d.quadkey } }; var QuadkeyLayer = class extends GeoCellLayer { indexToBounds() { const { data, extruded, getQuadkey } = this.props; const coverage = extruded ? 0.99 : 1; return { data, _normalize: false, positionFormat: "XY", getPolygon: (x2, objectInfo) => getQuadkeyPolygon(getQuadkey(x2, objectInfo), coverage), updateTriggers: { getPolygon: coverage } }; } }; QuadkeyLayer.layerName = "QuadkeyLayer"; QuadkeyLayer.defaultProps = defaultProps5; // src/tile-layer/tile-layer.ts var import_core14 = __toESM(require_core(), 1); var import_layers5 = __toESM(require_layers(), 1); // src/tileset-2d/tile-2d-header.ts var Tile2DHeader = class { constructor(index) { this.index = index; this.isVisible = false; this.isSelected = false; this.parent = null; this.children = []; this.content = null; this._loader = void 0; this._abortController = null; this._loaderId = 0; this._isLoaded = false; this._isCancelled = false; this._needsReload = false; } get bbox() { return this._bbox; } set bbox(value) { if (this._bbox) return; this._bbox = value; if ("west" in value) { this.boundingBox = [ [value.west, value.south], [value.east, value.north] ]; } else { this.boundingBox = [ [value.left, value.top], [value.right, value.bottom] ]; } } get data() { return this.isLoading && this._loader ? this._loader.then(() => this.data) : this.content; } get isLoaded() { return this._isLoaded && !this._needsReload; } get isLoading() { return Boolean(this._loader) && !this._isCancelled; } get needsReload() { return this._needsReload || this._isCancelled; } get byteLength() { const result = this.content ? this.content.byteLength : 0; if (!Number.isFinite(result)) { console.error("byteLength not defined in tile data"); } return result; } async _loadData({ getData, requestScheduler, onLoad, onError }) { const { index, id, bbox, userData, zoom } = this; const loaderId = this._loaderId; this._abortController = new AbortController(); const { signal } = this._abortController; const requestToken = await requestScheduler.scheduleRequest(this, (tile) => { return tile.isSelected ? 1 : -1; }); if (!requestToken) { this._isCancelled = true; return; } if (this._isCancelled) { requestToken.done(); return; } let tileData = null; let error; try { tileData = await getData({ index, id, bbox, userData, zoom, signal }); } catch (err) { error = err || true; } finally { requestToken.done(); } if (loaderId !== this._loaderId) { return; } this._loader = void 0; this.content = tileData; if (this._isCancelled && !tileData) { this._isLoaded = false; return; } this._isLoaded = true; this._isCancelled = false; if (error) { onError(error, this); } else { onLoad(this); } } loadData(opts) { this._isLoaded = false; this._isCancelled = false; this._needsReload = false; this._loaderId++; this._loader = this._loadData(opts); return this._loader; } setNeedsReload() { if (this.isLoading) { this.abort(); this._loader = void 0; } this._needsReload = true; } abort() { if (this.isLoaded) { return; } this._isCancelled = true; this._abortController?.abort(); } }; // src/tileset-2d/tile-2d-traversal.ts var import_core12 = __toESM(require_core(), 1); // ../../node_modules/@math.gl/culling/dist/constants.js var INTERSECTION = { OUTSIDE: -1, INTERSECTING: 0, INSIDE: 1 }; // ../../node_modules/@math.gl/culling/dist/lib/bounding-volumes/axis-aligned-bounding-box.js var scratchVector = new Vector3(); var scratchNormal = new Vector3(); var AxisAlignedBoundingBox = class { constructor(minimum = [0, 0, 0], maximum = [0, 0, 0], center) { center = center || scratchVector.copy(minimum).add(maximum).scale(0.5); this.center = new Vector3(center); this.halfDiagonal = new Vector3(maximum).subtract(this.center); this.minimum = new Vector3(minimum); this.maximum = new Vector3(maximum); } clone() { return new AxisAlignedBoundingBox(this.minimum, this.maximum, this.center); } equals(right) { return this === right || Boolean(right) && this.minimum.equals(right.minimum) && this.maximum.equals(right.maximum); } transform(transform2) { this.center.transformAsPoint(transform2); this.halfDiagonal.transform(transform2); this.minimum.transform(transform2); this.maximum.transform(transform2); return this; } intersectPlane(plane) { const { halfDiagonal } = this; const normal = scratchNormal.from(plane.normal); const e = halfDiagonal.x * Math.abs(normal.x) + halfDiagonal.y * Math.abs(normal.y) + halfDiagonal.z * Math.abs(normal.z); const s2 = this.center.dot(normal) + plane.distance; if (s2 - e > 0) { return INTERSECTION.INSIDE; } if (s2 + e < 0) { return INTERSECTION.OUTSIDE; } return INTERSECTION.INTERSECTING; } distanceTo(point) { return Math.sqrt(this.distanceSquaredTo(point)); } distanceSquaredTo(point) { const offset = scratchVector.from(point).subtract(this.center); const { halfDiagonal } = this; let distanceSquared = 0; let d; d = Math.abs(offset.x) - halfDiagonal.x; if (d > 0) { distanceSquared += d * d; } d = Math.abs(offset.y) - halfDiagonal.y; if (d > 0) { distanceSquared += d * d; } d = Math.abs(offset.z) - halfDiagonal.z; if (d > 0) { distanceSquared += d * d; } return distanceSquared; } }; // ../../node_modules/@math.gl/culling/dist/lib/bounding-volumes/bounding-sphere.js var scratchVector2 = new Vector3(); var scratchVector22 = new Vector3(); var BoundingSphere = class { constructor(center = [0, 0, 0], radius = 0) { this.radius = -0; this.center = new Vector3(); this.fromCenterRadius(center, radius); } fromCenterRadius(center, radius) { this.center.from(center); this.radius = radius; return this; } fromCornerPoints(corner, oppositeCorner) { oppositeCorner = scratchVector2.from(oppositeCorner); this.center = new Vector3().from(corner).add(oppositeCorner).scale(0.5); this.radius = this.center.distance(oppositeCorner); return this; } equals(right) { return this === right || Boolean(right) && this.center.equals(right.center) && this.radius === right.radius; } clone() { return new BoundingSphere(this.center, this.radius); } union(boundingSphere) { const leftCenter = this.center; const leftRadius = this.radius; const rightCenter = boundingSphere.center; const rightRadius = boundingSphere.radius; const toRightCenter = scratchVector2.copy(rightCenter).subtract(leftCenter); const centerSeparation = toRightCenter.magnitude(); if (leftRadius >= centerSeparation + rightRadius) { return this.clone(); } if (rightRadius >= centerSeparation + leftRadius) { return boundingSphere.clone(); } const halfDistanceBetweenTangentPoints = (leftRadius + centerSeparation + rightRadius) * 0.5; scratchVector22.copy(toRightCenter).scale((-leftRadius + halfDistanceBetweenTangentPoints) / centerSeparation).add(leftCenter); this.center.copy(scratchVector22); this.radius = halfDistanceBetweenTangentPoints; return this; } expand(point) { const scratchPoint2 = scratchVector2.from(point); const radius = scratchPoint2.subtract(this.center).magnitude(); if (radius > this.radius) { this.radius = radius; } return this; } transform(transform2) { this.center.transform(transform2); const scale6 = mat4_exports.getScaling(scratchVector2, transform2); this.radius = Math.max(scale6[0], Math.max(scale6[1], scale6[2])) * this.radius; return this; } distanceSquaredTo(point) { const d = this.distanceTo(point); return d * d; } distanceTo(point) { const scratchPoint2 = scratchVector2.from(point); const delta = scratchPoint2.subtract(this.center); return Math.max(0, delta.len() - this.radius); } intersectPlane(plane) { const center = this.center; const radius = this.radius; const normal = plane.normal; const distanceToPlane = normal.dot(center) + plane.distance; if (distanceToPlane < -radius) { return INTERSECTION.OUTSIDE; } if (distanceToPlane < radius) { return INTERSECTION.INTERSECTING; } return INTERSECTION.INSIDE; } }; // ../../node_modules/@math.gl/culling/dist/lib/bounding-volumes/oriented-bounding-box.js var scratchVector3 = new Vector3(); var scratchOffset = new Vector3(); var scratchVectorU = new Vector3(); var scratchVectorV = new Vector3(); var scratchVectorW = new Vector3(); var scratchCorner = new Vector3(); var scratchToCenter = new Vector3(); var MATRIX3 = { COLUMN0ROW0: 0, COLUMN0ROW1: 1, COLUMN0ROW2: 2, COLUMN1ROW0: 3, COLUMN1ROW1: 4, COLUMN1ROW2: 5, COLUMN2ROW0: 6, COLUMN2ROW1: 7, COLUMN2ROW2: 8 }; var OrientedBoundingBox = class { constructor(center = [0, 0, 0], halfAxes = [0, 0, 0, 0, 0, 0, 0, 0, 0]) { this.center = new Vector3().from(center); this.halfAxes = new Matrix3(halfAxes); } get halfSize() { const xAxis = this.halfAxes.getColumn(0); const yAxis = this.halfAxes.getColumn(1); const zAxis = this.halfAxes.getColumn(2); return [new Vector3(xAxis).len(), new Vector3(yAxis).len(), new Vector3(zAxis).len()]; } get quaternion() { const xAxis = this.halfAxes.getColumn(0); const yAxis = this.halfAxes.getColumn(1); const zAxis = this.halfAxes.getColumn(2); const normXAxis = new Vector3(xAxis).normalize(); const normYAxis = new Vector3(yAxis).normalize(); const normZAxis = new Vector3(zAxis).normalize(); return new Quaternion().fromMatrix3(new Matrix3([...normXAxis, ...normYAxis, ...normZAxis])); } fromCenterHalfSizeQuaternion(center, halfSize, quaternion) { const quaternionObject = new Quaternion(quaternion); const directionsMatrix = new Matrix3().fromQuaternion(quaternionObject); directionsMatrix[0] = directionsMatrix[0] * halfSize[0]; directionsMatrix[1] = directionsMatrix[1] * halfSize[0]; directionsMatrix[2] = directionsMatrix[2] * halfSize[0]; directionsMatrix[3] = directionsMatrix[3] * halfSize[1]; directionsMatrix[4] = directionsMatrix[4] * halfSize[1]; directionsMatrix[5] = directionsMatrix[5] * halfSize[1]; directionsMatrix[6] = directionsMatrix[6] * halfSize[2]; directionsMatrix[7] = directionsMatrix[7] * halfSize[2]; directionsMatrix[8] = directionsMatrix[8] * halfSize[2]; this.center = new Vector3().from(center); this.halfAxes = directionsMatrix; return this; } clone() { return new OrientedBoundingBox(this.center, this.halfAxes); } equals(right) { return this === right || Boolean(right) && this.center.equals(right.center) && this.halfAxes.equals(right.halfAxes); } getBoundingSphere(result = new BoundingSphere()) { const halfAxes = this.halfAxes; const u = halfAxes.getColumn(0, scratchVectorU); const v = halfAxes.getColumn(1, scratchVectorV); const w = halfAxes.getColumn(2, scratchVectorW); const cornerVector = scratchVector3.copy(u).add(v).add(w); result.center.copy(this.center); result.radius = cornerVector.magnitude(); return result; } intersectPlane(plane) { const center = this.center; const normal = plane.normal; const halfAxes = this.halfAxes; const normalX = normal.x; const normalY = normal.y; const normalZ = normal.z; const radEffective = Math.abs(normalX * halfAxes[MATRIX3.COLUMN0ROW0] + normalY * halfAxes[MATRIX3.COLUMN0ROW1] + normalZ * halfAxes[MATRIX3.COLUMN0ROW2]) + Math.abs(normalX * halfAxes[MATRIX3.COLUMN1ROW0] + normalY * halfAxes[MATRIX3.COLUMN1ROW1] + normalZ * halfAxes[MATRIX3.COLUMN1ROW2]) + Math.abs(normalX * halfAxes[MATRIX3.COLUMN2ROW0] + normalY * halfAxes[MATRIX3.COLUMN2ROW1] + normalZ * halfAxes[MATRIX3.COLUMN2ROW2]); const distanceToPlane = normal.dot(center) + plane.distance; if (distanceToPlane <= -radEffective) { return INTERSECTION.OUTSIDE; } else if (distanceToPlane >= radEffective) { return INTERSECTION.INSIDE; } return INTERSECTION.INTERSECTING; } distanceTo(point) { return Math.sqrt(this.distanceSquaredTo(point)); } distanceSquaredTo(point) { const offset = scratchOffset.from(point).subtract(this.center); const halfAxes = this.halfAxes; const u = halfAxes.getColumn(0, scratchVectorU); const v = halfAxes.getColumn(1, scratchVectorV); const w = halfAxes.getColumn(2, scratchVectorW); const uHalf = u.magnitude(); const vHalf = v.magnitude(); const wHalf = w.magnitude(); u.normalize(); v.normalize(); w.normalize(); let distanceSquared = 0; let d; d = Math.abs(offset.dot(u)) - uHalf; if (d > 0) { distanceSquared += d * d; } d = Math.abs(offset.dot(v)) - vHalf; if (d > 0) { distanceSquared += d * d; } d = Math.abs(offset.dot(w)) - wHalf; if (d > 0) { distanceSquared += d * d; } return distanceSquared; } computePlaneDistances(position, direction, result = [-0, -0]) { let minDist = Number.POSITIVE_INFINITY; let maxDist = Number.NEGATIVE_INFINITY; const center = this.center; const halfAxes = this.halfAxes; const u = halfAxes.getColumn(0, scratchVectorU); const v = halfAxes.getColumn(1, scratchVectorV); const w = halfAxes.getColumn(2, scratchVectorW); const corner = scratchCorner.copy(u).add(v).add(w).add(center); const toCenter = scratchToCenter.copy(corner).subtract(position); let mag = direction.dot(toCenter); minDist = Math.min(mag, minDist); maxDist = Math.max(mag, maxDist); corner.copy(center).add(u).add(v).subtract(w); toCenter.copy(corner).subtract(position); mag = direction.dot(toCenter); minDist = Math.min(mag, minDist); maxDist = Math.max(mag, maxDist); corner.copy(center).add(u).subtract(v).add(w); toCenter.copy(corner).subtract(position); mag = direction.dot(toCenter); minDist = Math.min(mag, minDist); maxDist = Math.max(mag, maxDist); corner.copy(center).add(u).subtract(v).subtract(w); toCenter.copy(corner).subtract(position); mag = direction.dot(toCenter); minDist = Math.min(mag, minDist); maxDist = Math.max(mag, maxDist); center.copy(corner).subtract(u).add(v).add(w); toCenter.copy(corner).subtract(position); mag = direction.dot(toCenter); minDist = Math.min(mag, minDist); maxDist = Math.max(mag, maxDist); center.copy(corner).subtract(u).add(v).subtract(w); toCenter.copy(corner).subtract(position); mag = direction.dot(toCenter); minDist = Math.min(mag, minDist); maxDist = Math.max(mag, maxDist); center.copy(corner).subtract(u).subtract(v).add(w); toCenter.copy(corner).subtract(position); mag = direction.dot(toCenter); minDist = Math.min(mag, minDist); maxDist = Math.max(mag, maxDist); center.copy(corner).subtract(u).subtract(v).subtract(w); toCenter.copy(corner).subtract(position); mag = direction.dot(toCenter); minDist = Math.min(mag, minDist); maxDist = Math.max(mag, maxDist); result[0] = minDist; result[1] = maxDist; return result; } transform(transformation) { this.center.transformAsPoint(transformation); const xAxis = this.halfAxes.getColumn(0, scratchVectorU); xAxis.transformAsPoint(transformation); const yAxis = this.halfAxes.getColumn(1, scratchVectorV); yAxis.transformAsPoint(transformation); const zAxis = this.halfAxes.getColumn(2, scratchVectorW); zAxis.transformAsPoint(transformation); this.halfAxes = new Matrix3([...xAxis, ...yAxis, ...zAxis]); return this; } getTransform() { throw new Error("not implemented"); } }; // ../../node_modules/@math.gl/culling/dist/lib/plane.js var scratchPosition = new Vector3(); var scratchNormal2 = new Vector3(); var Plane = class { constructor(normal = [0, 0, 1], distance2 = 0) { this.normal = new Vector3(); this.distance = -0; this.fromNormalDistance(normal, distance2); } fromNormalDistance(normal, distance2) { assert5(Number.isFinite(distance2)); this.normal.from(normal).normalize(); this.distance = distance2; return this; } fromPointNormal(point, normal) { point = scratchPosition.from(point); this.normal.from(normal).normalize(); const distance2 = -this.normal.dot(point); this.distance = distance2; return this; } fromCoefficients(a2, b, c, d) { this.normal.set(a2, b, c); assert5(equals(this.normal.len(), 1)); this.distance = d; return this; } clone() { return new Plane(this.normal, this.distance); } equals(right) { return equals(this.distance, right.distance) && equals(this.normal, right.normal); } getPointDistance(point) { return this.normal.dot(point) + this.distance; } transform(matrix4) { const normal = scratchNormal2.copy(this.normal).transformAsVector(matrix4).normalize(); const point = this.normal.scale(-this.distance).transform(matrix4); return this.fromPointNormal(point, normal); } projectPointOntoPlane(point, result = [0, 0, 0]) { const scratchPoint2 = scratchPosition.from(point); const pointDistance = this.getPointDistance(scratchPoint2); const scaledNormal = scratchNormal2.copy(this.normal).scale(pointDistance); return scratchPoint2.subtract(scaledNormal).to(result); } }; // ../../node_modules/@math.gl/culling/dist/lib/culling-volume.js var faces = [new Vector3([1, 0, 0]), new Vector3([0, 1, 0]), new Vector3([0, 0, 1])]; var scratchPlaneCenter = new Vector3(); var scratchPlaneNormal = new Vector3(); var CullingVolume = class { constructor(planes = []) { this.planes = planes; } fromBoundingSphere(boundingSphere) { this.planes.length = 2 * faces.length; const center = boundingSphere.center; const radius = boundingSphere.radius; let planeIndex = 0; for (const faceNormal of faces) { let plane0 = this.planes[planeIndex]; let plane1 = this.planes[planeIndex + 1]; if (!plane0) { plane0 = this.planes[planeIndex] = new Plane(); } if (!plane1) { plane1 = this.planes[planeIndex + 1] = new Plane(); } const plane0Center = scratchPlaneCenter.copy(faceNormal).scale(-radius).add(center); plane0.fromPointNormal(plane0Center, faceNormal); const plane1Center = scratchPlaneCenter.copy(faceNormal).scale(radius).add(center); const negatedFaceNormal = scratchPlaneNormal.copy(faceNormal).negate(); plane1.fromPointNormal(plane1Center, negatedFaceNormal); planeIndex += 2; } return this; } computeVisibility(boundingVolume) { let intersect2 = INTERSECTION.INSIDE; for (const plane of this.planes) { const result = boundingVolume.intersectPlane(plane); switch (result) { case INTERSECTION.OUTSIDE: return INTERSECTION.OUTSIDE; case INTERSECTION.INTERSECTING: intersect2 = INTERSECTION.INTERSECTING; break; default: } } return intersect2; } computeVisibilityWithPlaneMask(boundingVolume, parentPlaneMask) { assert5(Number.isFinite(parentPlaneMask), "parentPlaneMask is required."); if (parentPlaneMask === CullingVolume.MASK_OUTSIDE || parentPlaneMask === CullingVolume.MASK_INSIDE) { return parentPlaneMask; } let mask = CullingVolume.MASK_INSIDE; const planes = this.planes; for (let k = 0; k < this.planes.length; ++k) { const flag = k < 31 ? 1 << k : 0; if (k < 31 && (parentPlaneMask & flag) === 0) { continue; } const plane = planes[k]; const result = boundingVolume.intersectPlane(plane); if (result === INTERSECTION.OUTSIDE) { return CullingVolume.MASK_OUTSIDE; } else if (result === INTERSECTION.INTERSECTING) { mask |= flag; } } return mask; } }; CullingVolume.MASK_OUTSIDE = 4294967295; CullingVolume.MASK_INSIDE = 0; CullingVolume.MASK_INDETERMINATE = 2147483647; // ../../node_modules/@math.gl/culling/dist/lib/perspective-off-center-frustum.js var scratchPlaneUpVector = new Vector3(); var scratchPlaneRightVector = new Vector3(); var scratchPlaneNearCenter = new Vector3(); var scratchPlaneFarCenter = new Vector3(); var scratchPlaneNormal2 = new Vector3(); // ../../node_modules/@math.gl/culling/dist/lib/algorithms/bounding-sphere-from-points.js var fromPointsXMin = new Vector3(); var fromPointsYMin = new Vector3(); var fromPointsZMin = new Vector3(); var fromPointsXMax = new Vector3(); var fromPointsYMax = new Vector3(); var fromPointsZMax = new Vector3(); var fromPointsCurrentPos = new Vector3(); var fromPointsScratch = new Vector3(); var fromPointsRitterCenter = new Vector3(); var fromPointsMinBoxPt = new Vector3(); var fromPointsMaxBoxPt = new Vector3(); var fromPointsNaiveCenterScratch = new Vector3(); // ../../node_modules/@math.gl/culling/dist/lib/algorithms/compute-eigen-decomposition.js var scratchMatrix = new Matrix3(); var scratchUnitary = new Matrix3(); var scratchDiagonal = new Matrix3(); var jMatrix = new Matrix3(); var jMatrixTranspose = new Matrix3(); function computeEigenDecomposition(matrix, result = {}) { const EIGEN_TOLERANCE = math_utils_exports.EPSILON20; const EIGEN_MAX_SWEEPS = 10; let count = 0; let sweep = 0; const unitaryMatrix = scratchUnitary; const diagonalMatrix = scratchDiagonal; unitaryMatrix.identity(); diagonalMatrix.copy(matrix); const epsilon = EIGEN_TOLERANCE * computeFrobeniusNorm(diagonalMatrix); while (sweep < EIGEN_MAX_SWEEPS && offDiagonalFrobeniusNorm(diagonalMatrix) > epsilon) { shurDecomposition(diagonalMatrix, jMatrix); jMatrixTranspose.copy(jMatrix).transpose(); diagonalMatrix.multiplyRight(jMatrix); diagonalMatrix.multiplyLeft(jMatrixTranspose); unitaryMatrix.multiplyRight(jMatrix); if (++count > 2) { ++sweep; count = 0; } } result.unitary = unitaryMatrix.toTarget(result.unitary); result.diagonal = diagonalMatrix.toTarget(result.diagonal); return result; } function computeFrobeniusNorm(matrix) { let norm = 0; for (let i3 = 0; i3 < 9; ++i3) { const temp = matrix[i3]; norm += temp * temp; } return Math.sqrt(norm); } var rowVal = [1, 0, 0]; var colVal = [2, 2, 1]; function offDiagonalFrobeniusNorm(matrix) { let norm = 0; for (let i3 = 0; i3 < 3; ++i3) { const temp = matrix[scratchMatrix.getElementIndex(colVal[i3], rowVal[i3])]; norm += 2 * temp * temp; } return Math.sqrt(norm); } function shurDecomposition(matrix, result) { const tolerance = math_utils_exports.EPSILON15; let maxDiagonal = 0; let rotAxis = 1; for (let i3 = 0; i3 < 3; ++i3) { const temp = Math.abs(matrix[scratchMatrix.getElementIndex(colVal[i3], rowVal[i3])]); if (temp > maxDiagonal) { rotAxis = i3; maxDiagonal = temp; } } const p2 = rowVal[rotAxis]; const q = colVal[rotAxis]; let c = 1; let s2 = 0; if (Math.abs(matrix[scratchMatrix.getElementIndex(q, p2)]) > tolerance) { const qq = matrix[scratchMatrix.getElementIndex(q, q)]; const pp = matrix[scratchMatrix.getElementIndex(p2, p2)]; const qp = matrix[scratchMatrix.getElementIndex(q, p2)]; const tau = (qq - pp) / 2 / qp; let t2; if (tau < 0) { t2 = -1 / (-tau + Math.sqrt(1 + tau * tau)); } else { t2 = 1 / (tau + Math.sqrt(1 + tau * tau)); } c = 1 / Math.sqrt(1 + t2 * t2); s2 = t2 * c; } Matrix3.IDENTITY.to(result); result[scratchMatrix.getElementIndex(p2, p2)] = result[scratchMatrix.getElementIndex(q, q)] = c; result[scratchMatrix.getElementIndex(q, p2)] = s2; result[scratchMatrix.getElementIndex(p2, q)] = -s2; return result; } // ../../node_modules/@math.gl/culling/dist/lib/algorithms/bounding-box-from-points.js var scratchVector23 = new Vector3(); var scratchVector32 = new Vector3(); var scratchVector4 = new Vector3(); var scratchVector5 = new Vector3(); var scratchVector6 = new Vector3(); var scratchCovarianceResult = new Matrix3(); var scratchEigenResult = { diagonal: new Matrix3(), unitary: new Matrix3() }; function makeOrientedBoundingBoxFromPoints(positions, result = new OrientedBoundingBox()) { if (!positions || positions.length === 0) { result.halfAxes = new Matrix3([0, 0, 0, 0, 0, 0, 0, 0, 0]); result.center = new Vector3(); return result; } const length5 = positions.length; const meanPoint = new Vector3(0, 0, 0); for (const position of positions) { meanPoint.add(position); } const invLength = 1 / length5; meanPoint.multiplyByScalar(invLength); let exx = 0; let exy = 0; let exz = 0; let eyy = 0; let eyz = 0; let ezz = 0; for (const position of positions) { const p2 = scratchVector23.copy(position).subtract(meanPoint); exx += p2.x * p2.x; exy += p2.x * p2.y; exz += p2.x * p2.z; eyy += p2.y * p2.y; eyz += p2.y * p2.z; ezz += p2.z * p2.z; } exx *= invLength; exy *= invLength; exz *= invLength; eyy *= invLength; eyz *= invLength; ezz *= invLength; const covarianceMatrix = scratchCovarianceResult; covarianceMatrix[0] = exx; covarianceMatrix[1] = exy; covarianceMatrix[2] = exz; covarianceMatrix[3] = exy; covarianceMatrix[4] = eyy; covarianceMatrix[5] = eyz; covarianceMatrix[6] = exz; covarianceMatrix[7] = eyz; covarianceMatrix[8] = ezz; const { unitary } = computeEigenDecomposition(covarianceMatrix, scratchEigenResult); const rotation = result.halfAxes.copy(unitary); let v1 = rotation.getColumn(0, scratchVector4); let v2 = rotation.getColumn(1, scratchVector5); let v3 = rotation.getColumn(2, scratchVector6); let u1 = -Number.MAX_VALUE; let u2 = -Number.MAX_VALUE; let u3 = -Number.MAX_VALUE; let l1 = Number.MAX_VALUE; let l2 = Number.MAX_VALUE; let l3 = Number.MAX_VALUE; for (const position of positions) { scratchVector23.copy(position); u1 = Math.max(scratchVector23.dot(v1), u1); u2 = Math.max(scratchVector23.dot(v2), u2); u3 = Math.max(scratchVector23.dot(v3), u3); l1 = Math.min(scratchVector23.dot(v1), l1); l2 = Math.min(scratchVector23.dot(v2), l2); l3 = Math.min(scratchVector23.dot(v3), l3); } v1 = v1.multiplyByScalar(0.5 * (l1 + u1)); v2 = v2.multiplyByScalar(0.5 * (l2 + u2)); v3 = v3.multiplyByScalar(0.5 * (l3 + u3)); result.center.copy(v1).add(v2).add(v3); const scale6 = scratchVector32.set(u1 - l1, u2 - l2, u3 - l3).multiplyByScalar(0.5); const scaleMatrix = new Matrix3([scale6[0], 0, 0, 0, scale6[1], 0, 0, 0, scale6[2]]); result.halfAxes.multiplyRight(scaleMatrix); return result; } // src/tileset-2d/tile-2d-traversal.ts var TILE_SIZE3 = 512; var MAX_MAPS = 3; var REF_POINTS_5 = [ [0.5, 0.5], [0, 0], [0, 1], [1, 0], [1, 1] ]; var REF_POINTS_9 = REF_POINTS_5.concat([ [0, 0.5], [0.5, 0], [1, 0.5], [0.5, 1] ]); var REF_POINTS_11 = REF_POINTS_9.concat([ [0.25, 0.5], [0.75, 0.5] ]); var OSMNode = class { constructor(x2, y2, z) { this.x = x2; this.y = y2; this.z = z; } get children() { if (!this._children) { const x2 = this.x * 2; const y2 = this.y * 2; const z = this.z + 1; this._children = [ new OSMNode(x2, y2, z), new OSMNode(x2, y2 + 1, z), new OSMNode(x2 + 1, y2, z), new OSMNode(x2 + 1, y2 + 1, z) ]; } return this._children; } update(params) { const { viewport, cullingVolume: cullingVolume2, elevationBounds, minZ, maxZ, bounds, offset, project: project2 } = params; const boundingVolume = this.getBoundingVolume(elevationBounds, offset, project2); if (bounds && !this.insideBounds(bounds)) { return false; } const isInside = cullingVolume2.computeVisibility(boundingVolume); if (isInside < 0) { return false; } if (!this.childVisible) { let { z } = this; if (z < maxZ && z >= minZ) { const distance2 = boundingVolume.distanceTo(viewport.cameraPosition) * viewport.scale / viewport.height; z += Math.floor(Math.log2(distance2)); } if (z >= maxZ) { this.selected = true; return true; } } this.selected = false; this.childVisible = true; for (const child of this.children) { child.update(params); } return true; } getSelected(result = []) { if (this.selected) { result.push(this); } if (this._children) { for (const node of this._children) { node.getSelected(result); } } return result; } insideBounds([minX, minY, maxX, maxY]) { const scale6 = Math.pow(2, this.z); const extent = TILE_SIZE3 / scale6; return this.x * extent < maxX && this.y * extent < maxY && (this.x + 1) * extent > minX && (this.y + 1) * extent > minY; } getBoundingVolume(zRange, worldOffset, project2) { if (project2) { const refPoints = this.z < 1 ? REF_POINTS_11 : this.z < 2 ? REF_POINTS_9 : REF_POINTS_5; const refPointPositions = []; for (const p2 of refPoints) { const lngLat = osmTile2lngLat(this.x + p2[0], this.y + p2[1], this.z); lngLat[2] = zRange[0]; refPointPositions.push(project2(lngLat)); if (zRange[0] !== zRange[1]) { lngLat[2] = zRange[1]; refPointPositions.push(project2(lngLat)); } } return makeOrientedBoundingBoxFromPoints(refPointPositions); } const scale6 = Math.pow(2, this.z); const extent = TILE_SIZE3 / scale6; const originX = this.x * extent + worldOffset * TILE_SIZE3; const originY = TILE_SIZE3 - (this.y + 1) * extent; return new AxisAlignedBoundingBox( [originX, originY, zRange[0]], [originX + extent, originY + extent, zRange[1]] ); } }; function getOSMTileIndices(viewport, maxZ, zRange, bounds) { const project2 = viewport instanceof import_core12._GlobeViewport && viewport.resolution ? viewport.projectPosition : null; const planes = Object.values(viewport.getFrustumPlanes()).map( ({ normal, distance: distance2 }) => new Plane(normal.clone().negate(), distance2) ); const cullingVolume2 = new CullingVolume(planes); const unitsPerMeter2 = viewport.distanceScales.unitsPerMeter[2]; const elevationMin = zRange && zRange[0] * unitsPerMeter2 || 0; const elevationMax = zRange && zRange[1] * unitsPerMeter2 || 0; const minZ = viewport instanceof import_core12.WebMercatorViewport && viewport.pitch <= 60 ? maxZ : 0; if (bounds) { const [minLng, minLat, maxLng, maxLat] = bounds; const topLeft = lngLatToWorld([minLng, maxLat]); const bottomRight = lngLatToWorld([maxLng, minLat]); bounds = [topLeft[0], TILE_SIZE3 - topLeft[1], bottomRight[0], TILE_SIZE3 - bottomRight[1]]; } const root = new OSMNode(0, 0, 0); const traversalParams = { viewport, project: project2, cullingVolume: cullingVolume2, elevationBounds: [elevationMin, elevationMax], minZ, maxZ, bounds, offset: 0 }; root.update(traversalParams); if (viewport instanceof import_core12.WebMercatorViewport && viewport.subViewports && viewport.subViewports.length > 1) { traversalParams.offset = -1; while (root.update(traversalParams)) { if (--traversalParams.offset < -MAX_MAPS) { break; } } traversalParams.offset = 1; while (root.update(traversalParams)) { if (++traversalParams.offset > MAX_MAPS) { break; } } } return root.getSelected(); } // src/tileset-2d/utils.ts var TILE_SIZE4 = 512; var DEFAULT_EXTENT = [-Infinity, -Infinity, Infinity, Infinity]; var urlType = { type: "object", value: null, validate: (value, propType) => propType.optional && value === null || typeof value === "string" || Array.isArray(value) && value.every((url) => typeof url === "string"), equal: (value1, value2) => { if (value1 === value2) { return true; } if (!Array.isArray(value1) || !Array.isArray(value2)) { return false; } const len2 = value1.length; if (len2 !== value2.length) { return false; } for (let i3 = 0; i3 < len2; i3++) { if (value1[i3] !== value2[i3]) { return false; } } return true; } }; function transformBox(bbox, modelMatrix) { const transformedCoords = [ modelMatrix.transformAsPoint([bbox[0], bbox[1]]), modelMatrix.transformAsPoint([bbox[2], bbox[1]]), modelMatrix.transformAsPoint([bbox[0], bbox[3]]), modelMatrix.transformAsPoint([bbox[2], bbox[3]]) ]; const transformedBox = [ Math.min(...transformedCoords.map((i3) => i3[0])), Math.min(...transformedCoords.map((i3) => i3[1])), Math.max(...transformedCoords.map((i3) => i3[0])), Math.max(...transformedCoords.map((i3) => i3[1])) ]; return transformedBox; } function stringHash(s2) { return Math.abs(s2.split("").reduce((a2, b) => (a2 << 5) - a2 + b.charCodeAt(0) | 0, 0)); } function getURLFromTemplate(template, tile) { if (!template || !template.length) { return null; } const { index, id } = tile; if (Array.isArray(template)) { const i3 = stringHash(id) % template.length; template = template[i3]; } let url = template; for (const key of Object.keys(index)) { const regex = new RegExp(`{${key}}`, "g"); url = url.replace(regex, String(index[key])); } if (Number.isInteger(index.y) && Number.isInteger(index.z)) { url = url.replace(/\{-y\}/g, String(Math.pow(2, index.z) - index.y - 1)); } return url; } function getBoundingBox(viewport, zRange, extent) { let bounds; if (zRange && zRange.length === 2) { const [minZ, maxZ] = zRange; const bounds0 = viewport.getBounds({ z: minZ }); const bounds1 = viewport.getBounds({ z: maxZ }); bounds = [ Math.min(bounds0[0], bounds1[0]), Math.min(bounds0[1], bounds1[1]), Math.max(bounds0[2], bounds1[2]), Math.max(bounds0[3], bounds1[3]) ]; } else { bounds = viewport.getBounds(); } if (!viewport.isGeospatial) { return [ Math.max(Math.min(bounds[0], extent[2]), extent[0]), Math.max(Math.min(bounds[1], extent[3]), extent[1]), Math.min(Math.max(bounds[2], extent[0]), extent[2]), Math.min(Math.max(bounds[3], extent[1]), extent[3]) ]; } return [ Math.max(bounds[0], extent[0]), Math.max(bounds[1], extent[1]), Math.min(bounds[2], extent[2]), Math.min(bounds[3], extent[3]) ]; } function getCullBounds({ viewport, z, cullRect }) { const subViewports = viewport.subViewports || [viewport]; return subViewports.map((v) => getCullBoundsInViewport(v, z || 0, cullRect)); } function getCullBoundsInViewport(viewport, z, cullRect) { if (!Array.isArray(z)) { const x2 = cullRect.x - viewport.x; const y2 = cullRect.y - viewport.y; const { width, height } = cullRect; const unprojectOption = { targetZ: z }; const topLeft = viewport.unproject([x2, y2], unprojectOption); const topRight = viewport.unproject([x2 + width, y2], unprojectOption); const bottomLeft = viewport.unproject([x2, y2 + height], unprojectOption); const bottomRight = viewport.unproject([x2 + width, y2 + height], unprojectOption); return [ Math.min(topLeft[0], topRight[0], bottomLeft[0], bottomRight[0]), Math.min(topLeft[1], topRight[1], bottomLeft[1], bottomRight[1]), Math.max(topLeft[0], topRight[0], bottomLeft[0], bottomRight[0]), Math.max(topLeft[1], topRight[1], bottomLeft[1], bottomRight[1]) ]; } const bounds0 = getCullBoundsInViewport(viewport, z[0], cullRect); const bounds1 = getCullBoundsInViewport(viewport, z[1], cullRect); return [ Math.min(bounds0[0], bounds1[0]), Math.min(bounds0[1], bounds1[1]), Math.max(bounds0[2], bounds1[2]), Math.max(bounds0[3], bounds1[3]) ]; } function getIndexingCoords(bbox, scale6, modelMatrixInverse) { if (modelMatrixInverse) { const transformedTileIndex = transformBox(bbox, modelMatrixInverse).map( (i3) => i3 * scale6 / TILE_SIZE4 ); return transformedTileIndex; } return bbox.map((i3) => i3 * scale6 / TILE_SIZE4); } function getScale(z, tileSize) { return Math.pow(2, z) * TILE_SIZE4 / tileSize; } function osmTile2lngLat(x2, y2, z) { const scale6 = getScale(z, TILE_SIZE4); const lng = x2 / scale6 * 360 - 180; const n2 = Math.PI - 2 * Math.PI * y2 / scale6; const lat = 180 / Math.PI * Math.atan(0.5 * (Math.exp(n2) - Math.exp(-n2))); return [lng, lat]; } function tile2XY(x2, y2, z, tileSize) { const scale6 = getScale(z, tileSize); return [x2 / scale6 * TILE_SIZE4, y2 / scale6 * TILE_SIZE4]; } function tileToBoundingBox(viewport, x2, y2, z, tileSize = TILE_SIZE4) { if (viewport.isGeospatial) { const [west, north] = osmTile2lngLat(x2, y2, z); const [east, south] = osmTile2lngLat(x2 + 1, y2 + 1, z); return { west, north, east, south }; } const [left, top] = tile2XY(x2, y2, z, tileSize); const [right, bottom] = tile2XY(x2 + 1, y2 + 1, z, tileSize); return { left, top, right, bottom }; } function getIdentityTileIndices(viewport, z, tileSize, extent, modelMatrixInverse) { const bbox = getBoundingBox(viewport, null, extent); const scale6 = getScale(z, tileSize); const [minX, minY, maxX, maxY] = getIndexingCoords(bbox, scale6, modelMatrixInverse); const indices = []; for (let x2 = Math.floor(minX); x2 < maxX; x2++) { for (let y2 = Math.floor(minY); y2 < maxY; y2++) { indices.push({ x: x2, y: y2, z }); } } return indices; } function getTileIndices({ viewport, maxZoom, minZoom, zRange, extent, tileSize = TILE_SIZE4, modelMatrix, modelMatrixInverse, zoomOffset = 0 }) { let z = viewport.isGeospatial ? Math.round(viewport.zoom + Math.log2(TILE_SIZE4 / tileSize)) + zoomOffset : Math.ceil(viewport.zoom) + zoomOffset; if (typeof minZoom === "number" && Number.isFinite(minZoom) && z < minZoom) { if (!extent) { return []; } z = minZoom; } if (typeof maxZoom === "number" && Number.isFinite(maxZoom) && z > maxZoom) { z = maxZoom; } let transformedExtent = extent; if (modelMatrix && modelMatrixInverse && extent && !viewport.isGeospatial) { transformedExtent = transformBox(extent, modelMatrix); } return viewport.isGeospatial ? getOSMTileIndices(viewport, z, zRange, extent) : getIdentityTileIndices( viewport, z, tileSize, transformedExtent || DEFAULT_EXTENT, modelMatrixInverse ); } function isURLTemplate(s2) { return /(?=.*{z})(?=.*{x})(?=.*({y}|{-y}))/.test(s2); } function isGeoBoundingBox(v) { return Number.isFinite(v.west) && Number.isFinite(v.north) && Number.isFinite(v.east) && Number.isFinite(v.south); } // src/tileset-2d/memoize.ts function memoize(compute) { let cachedArgs = {}; let cachedResult; return (args) => { for (const key in args) { if (!isEqual(args[key], cachedArgs[key])) { cachedResult = compute(args); cachedArgs = args; break; } } return cachedResult; }; } function isEqual(a2, b) { if (a2 === b) { return true; } if (Array.isArray(a2)) { const len2 = a2.length; if (!b || b.length !== len2) { return false; } for (let i3 = 0; i3 < len2; i3++) { if (a2[i3] !== b[i3]) { return false; } } return true; } return false; } // src/tileset-2d/tileset-2d.ts var TILE_STATE_VISITED = 1; var TILE_STATE_VISIBLE = 2; var STRATEGY_NEVER = "never"; var STRATEGY_REPLACE = "no-overlap"; var STRATEGY_DEFAULT = "best-available"; var DEFAULT_CACHE_SCALE = 5; var STRATEGIES = { [STRATEGY_DEFAULT]: updateTileStateDefault, [STRATEGY_REPLACE]: updateTileStateReplace, [STRATEGY_NEVER]: () => { } }; var DEFAULT_TILESET2D_PROPS = { extent: null, tileSize: 512, maxZoom: null, minZoom: null, maxCacheSize: null, maxCacheByteSize: null, refinementStrategy: "best-available", zRange: null, maxRequests: 6, debounceTime: 0, zoomOffset: 0, onTileLoad: () => { }, onTileUnload: () => { }, onTileError: () => { } }; var Tileset2D = class { constructor(opts) { this._getCullBounds = memoize(getCullBounds); this.opts = { ...DEFAULT_TILESET2D_PROPS, ...opts }; this.setOptions(this.opts); this.onTileLoad = (tile) => { this.opts.onTileLoad?.(tile); if (this.opts.maxCacheByteSize != null) { this._cacheByteSize += tile.byteLength; this._resizeCache(); } }; this._requestScheduler = new RequestScheduler({ throttleRequests: this.opts.maxRequests > 0 || this.opts.debounceTime > 0, maxRequests: this.opts.maxRequests, debounceTime: this.opts.debounceTime }); this._cache = /* @__PURE__ */ new Map(); this._tiles = []; this._dirty = false; this._cacheByteSize = 0; this._viewport = null; this._zRange = null; this._selectedTiles = null; this._frameNumber = 0; this._modelMatrix = new Matrix4(); this._modelMatrixInverse = new Matrix4(); } get tiles() { return this._tiles; } get selectedTiles() { return this._selectedTiles; } get isLoaded() { return this._selectedTiles !== null && this._selectedTiles.every((tile) => tile.isLoaded); } get needsReload() { return this._selectedTiles !== null && this._selectedTiles.some((tile) => tile.needsReload); } setOptions(opts) { Object.assign(this.opts, opts); if (Number.isFinite(opts.maxZoom)) { this._maxZoom = Math.floor(opts.maxZoom); } if (Number.isFinite(opts.minZoom)) { this._minZoom = Math.ceil(opts.minZoom); } } finalize() { for (const tile of this._cache.values()) { if (tile.isLoading) { tile.abort(); } } this._cache.clear(); this._tiles = []; this._selectedTiles = null; } reloadAll() { for (const id of this._cache.keys()) { const tile = this._cache.get(id); if (!this._selectedTiles || !this._selectedTiles.includes(tile)) { this._cache.delete(id); } else { tile.setNeedsReload(); } } } update(viewport, { zRange, modelMatrix } = { zRange: null, modelMatrix: null }) { const modelMatrixAsMatrix4 = modelMatrix ? new Matrix4(modelMatrix) : new Matrix4(); const isModelMatrixNew = !modelMatrixAsMatrix4.equals(this._modelMatrix); if (!this._viewport || !viewport.equals(this._viewport) || !equals(this._zRange, zRange) || isModelMatrixNew) { if (isModelMatrixNew) { this._modelMatrixInverse = modelMatrixAsMatrix4.clone().invert(); this._modelMatrix = modelMatrixAsMatrix4; } this._viewport = viewport; this._zRange = zRange; const tileIndices = this.getTileIndices({ viewport, maxZoom: this._maxZoom, minZoom: this._minZoom, zRange, modelMatrix: this._modelMatrix, modelMatrixInverse: this._modelMatrixInverse }); this._selectedTiles = tileIndices.map((index) => this._getTile(index, true)); if (this._dirty) { this._rebuildTree(); } } else if (this.needsReload) { this._selectedTiles = this._selectedTiles.map((tile) => this._getTile(tile.index, true)); } const changed = this.updateTileStates(); this._pruneRequests(); if (this._dirty) { this._resizeCache(); } if (changed) { this._frameNumber++; } return this._frameNumber; } isTileVisible(tile, cullRect) { if (!tile.isVisible) { return false; } if (cullRect && this._viewport) { const boundsArr = this._getCullBounds({ viewport: this._viewport, z: this._zRange, cullRect }); const { bbox } = tile; for (const [minX, minY, maxX, maxY] of boundsArr) { let overlaps; if ("west" in bbox) { overlaps = bbox.west < maxX && bbox.east > minX && bbox.south < maxY && bbox.north > minY; } else { const y0 = Math.min(bbox.top, bbox.bottom); const y1 = Math.max(bbox.top, bbox.bottom); overlaps = bbox.left < maxX && bbox.right > minX && y0 < maxY && y1 > minY; } if (overlaps) { return true; } } return false; } return true; } getTileIndices({ viewport, maxZoom, minZoom, zRange, modelMatrix, modelMatrixInverse }) { const { tileSize, extent, zoomOffset } = this.opts; return getTileIndices({ viewport, maxZoom, minZoom, zRange, tileSize, extent, modelMatrix, modelMatrixInverse, zoomOffset }); } getTileId(index) { return `${index.x}-${index.y}-${index.z}`; } getTileZoom(index) { return index.z; } getTileMetadata(index) { const { tileSize } = this.opts; return { bbox: tileToBoundingBox(this._viewport, index.x, index.y, index.z, tileSize) }; } getParentIndex(index) { const x2 = Math.floor(index.x / 2); const y2 = Math.floor(index.y / 2); const z = index.z - 1; return { x: x2, y: y2, z }; } updateTileStates() { const refinementStrategy = this.opts.refinementStrategy || STRATEGY_DEFAULT; const visibilities = new Array(this._cache.size); let i3 = 0; for (const tile of this._cache.values()) { visibilities[i3++] = tile.isVisible; tile.isSelected = false; tile.isVisible = false; } for (const tile of this._selectedTiles) { tile.isSelected = true; tile.isVisible = true; } (typeof refinementStrategy === "function" ? refinementStrategy : STRATEGIES[refinementStrategy])(Array.from(this._cache.values())); i3 = 0; for (const tile of this._cache.values()) { if (visibilities[i3++] !== tile.isVisible) { return true; } } return false; } _pruneRequests() { const { maxRequests = 0 } = this.opts; const abortCandidates = []; let ongoingRequestCount = 0; for (const tile of this._cache.values()) { if (tile.isLoading) { ongoingRequestCount++; if (!tile.isSelected && !tile.isVisible) { abortCandidates.push(tile); } } } while (maxRequests > 0 && ongoingRequestCount > maxRequests && abortCandidates.length > 0) { const tile = abortCandidates.shift(); tile.abort(); ongoingRequestCount--; } } _rebuildTree() { const { _cache } = this; for (const tile of _cache.values()) { tile.parent = null; if (tile.children) { tile.children.length = 0; } } for (const tile of _cache.values()) { const parent = this._getNearestAncestor(tile); tile.parent = parent; if (parent?.children) { parent.children.push(tile); } } } _resizeCache() { const { _cache, opts } = this; const maxCacheSize = opts.maxCacheSize ?? (opts.maxCacheByteSize != null ? Infinity : DEFAULT_CACHE_SCALE * this.selectedTiles.length); const maxCacheByteSize = opts.maxCacheByteSize ?? Infinity; const overflown = _cache.size > maxCacheSize || this._cacheByteSize > maxCacheByteSize; if (overflown) { for (const [id, tile] of _cache) { if (!tile.isVisible && !tile.isSelected) { this._cacheByteSize -= opts.maxCacheByteSize != null ? tile.byteLength : 0; _cache.delete(id); this.opts.onTileUnload?.(tile); } if (_cache.size <= maxCacheSize && this._cacheByteSize <= maxCacheByteSize) { break; } } this._rebuildTree(); this._dirty = true; } if (this._dirty) { this._tiles = Array.from(this._cache.values()).sort((t1, t2) => t1.zoom - t2.zoom); this._dirty = false; } } _getTile(index, create7) { const id = this.getTileId(index); let tile = this._cache.get(id); let needsReload = false; if (!tile && create7) { tile = new Tile2DHeader(index); Object.assign(tile, this.getTileMetadata(tile.index)); Object.assign(tile, { id, zoom: this.getTileZoom(tile.index) }); needsReload = true; this._cache.set(id, tile); this._dirty = true; } else if (tile && tile.needsReload) { needsReload = true; } if (tile && needsReload) { tile.loadData({ getData: this.opts.getTileData, requestScheduler: this._requestScheduler, onLoad: this.onTileLoad, onError: this.opts.onTileError }); } return tile; } _getNearestAncestor(tile) { const { _minZoom = 0 } = this; let index = tile.index; while (this.getTileZoom(index) > _minZoom) { index = this.getParentIndex(index); const parent = this._getTile(index); if (parent) { return parent; } } return null; } }; function updateTileStateDefault(allTiles) { for (const tile of allTiles) { tile.state = 0; } for (const tile of allTiles) { if (tile.isSelected && !getPlaceholderInAncestors(tile)) { getPlaceholderInChildren(tile); } } for (const tile of allTiles) { tile.isVisible = Boolean(tile.state & TILE_STATE_VISIBLE); } } function updateTileStateReplace(allTiles) { for (const tile of allTiles) { tile.state = 0; } for (const tile of allTiles) { if (tile.isSelected) { getPlaceholderInAncestors(tile); } } const sortedTiles = Array.from(allTiles).sort((t1, t2) => t1.zoom - t2.zoom); for (const tile of sortedTiles) { tile.isVisible = Boolean(tile.state & TILE_STATE_VISIBLE); if (tile.children && (tile.isVisible || tile.state & TILE_STATE_VISITED)) { for (const child of tile.children) { child.state = TILE_STATE_VISITED; } } else if (tile.isSelected) { getPlaceholderInChildren(tile); } } } function getPlaceholderInAncestors(startTile) { let tile = startTile; while (tile) { if (tile.isLoaded || tile.content) { tile.state |= TILE_STATE_VISIBLE; return true; } tile = tile.parent; } return false; } function getPlaceholderInChildren(tile) { for (const child of tile.children) { if (child.isLoaded || child.content) { child.state |= TILE_STATE_VISIBLE; } else { getPlaceholderInChildren(child); } } } // src/tile-layer/tile-layer.ts var defaultProps6 = { TilesetClass: Tileset2D, data: { type: "data", value: [] }, dataComparator: urlType.equal, renderSubLayers: { type: "function", value: (props) => new import_layers5.GeoJsonLayer(props) }, getTileData: { type: "function", optional: true, value: null }, onViewportLoad: { type: "function", optional: true, value: null }, onTileLoad: { type: "function", value: (tile) => { } }, onTileUnload: { type: "function", value: (tile) => { } }, onTileError: { type: "function", value: (err) => console.error(err) }, extent: { type: "array", optional: true, value: null, compare: true }, tileSize: 512, maxZoom: null, minZoom: 0, maxCacheSize: null, maxCacheByteSize: null, refinementStrategy: STRATEGY_DEFAULT, zRange: null, maxRequests: 6, debounceTime: 0, zoomOffset: 0 }; var TileLayer = class extends import_core14.CompositeLayer { initializeState() { this.state = { tileset: null, isLoaded: false }; } finalizeState() { this.state?.tileset?.finalize(); } get isLoaded() { return Boolean( this.state?.tileset?.selectedTiles?.every( (tile) => tile.isLoaded && tile.layers && tile.layers.every((layer) => layer.isLoaded) ) ); } shouldUpdateState({ changeFlags }) { return changeFlags.somethingChanged; } updateState({ changeFlags }) { let { tileset } = this.state; const propsChanged = changeFlags.propsOrDataChanged || changeFlags.updateTriggersChanged; const dataChanged = changeFlags.dataChanged || changeFlags.updateTriggersChanged && (changeFlags.updateTriggersChanged.all || changeFlags.updateTriggersChanged.getTileData); if (!tileset) { tileset = new this.props.TilesetClass(this._getTilesetOptions()); this.setState({ tileset }); } else if (propsChanged) { tileset.setOptions(this._getTilesetOptions()); if (dataChanged) { tileset.reloadAll(); } else { tileset.tiles.forEach((tile) => { tile.layers = null; }); } } this._updateTileset(); } _getTilesetOptions() { const { tileSize, maxCacheSize, maxCacheByteSize, refinementStrategy, extent, maxZoom, minZoom, maxRequests, debounceTime, zoomOffset } = this.props; return { maxCacheSize, maxCacheByteSize, maxZoom, minZoom, tileSize, refinementStrategy, extent, maxRequests, debounceTime, zoomOffset, getTileData: this.getTileData.bind(this), onTileLoad: this._onTileLoad.bind(this), onTileError: this._onTileError.bind(this), onTileUnload: this._onTileUnload.bind(this) }; } _updateTileset() { const tileset = this.state.tileset; const { zRange, modelMatrix } = this.props; const frameNumber = tileset.update(this.context.viewport, { zRange, modelMatrix }); const { isLoaded } = tileset; const loadingStateChanged = this.state.isLoaded !== isLoaded; const tilesetChanged = this.state.frameNumber !== frameNumber; if (isLoaded && (loadingStateChanged || tilesetChanged)) { this._onViewportLoad(); } if (tilesetChanged) { this.setState({ frameNumber }); } this.state.isLoaded = isLoaded; } _onViewportLoad() { const { tileset } = this.state; const { onViewportLoad } = this.props; if (onViewportLoad) { onViewportLoad(tileset.selectedTiles); } } _onTileLoad(tile) { this.props.onTileLoad(tile); tile.layers = null; this.setNeedsUpdate(); } _onTileError(error, tile) { this.props.onTileError(error); tile.layers = null; this.setNeedsUpdate(); } _onTileUnload(tile) { this.props.onTileUnload(tile); } getTileData(tile) { const { data, getTileData, fetch: fetch2 } = this.props; const { signal } = tile; tile.url = typeof data === "string" || Array.isArray(data) ? getURLFromTemplate(data, tile) : null; if (getTileData) { return getTileData(tile); } if (fetch2 && tile.url) { return fetch2(tile.url, { propName: "data", layer: this, signal }); } return null; } renderSubLayers(props) { return this.props.renderSubLayers(props); } getSubLayerPropsByTile(tile) { return null; } getPickingInfo(params) { const sourceLayer = params.sourceLayer; const sourceTile = sourceLayer.props.tile; const info = params.info; if (info.picked) { info.tile = sourceTile; } info.sourceTile = sourceTile; info.sourceTileSubLayer = sourceLayer; return info; } _updateAutoHighlight(info) { info.sourceTileSubLayer.updateAutoHighlight(info); } renderLayers() { return this.state.tileset.tiles.map((tile) => { const subLayerProps = this.getSubLayerPropsByTile(tile); if (!tile.isLoaded && !tile.content) { } else if (!tile.layers) { const layers = this.renderSubLayers({ ...this.props, ...this.getSubLayerProps({ id: tile.id, updateTriggers: this.props.updateTriggers }), data: tile.content, _offset: 0, tile }); tile.layers = (0, import_core14._flatten)(layers, Boolean).map( (layer) => layer.clone({ tile, ...subLayerProps }) ); } else if (subLayerProps && tile.layers[0] && Object.keys(subLayerProps).some( (propName) => tile.layers[0].props[propName] !== subLayerProps[propName] )) { tile.layers = tile.layers.map((layer) => layer.clone(subLayerProps)); } return tile.layers; }); } filterSubLayer({ layer, cullRect }) { const { tile } = layer.props; return this.state.tileset.isTileVisible(tile, cullRect); } }; TileLayer.defaultProps = defaultProps6; TileLayer.layerName = "TileLayer"; // src/trips-layer/trips-layer.ts var import_layers6 = __toESM(require_layers(), 1); var defaultProps7 = { fadeTrail: true, trailLength: { type: "number", value: 120, min: 0 }, currentTime: { type: "number", value: 0, min: 0 }, getTimestamps: { type: "accessor", value: (d) => d.timestamps } }; var TripsLayer = class extends import_layers6.PathLayer { getShaders() { const shaders = super.getShaders(); shaders.inject = { "vs:#decl": `uniform float trailLength; in float instanceTimestamps; in float instanceNextTimestamps; out float vTime; `, "vs:#main-end": `vTime = instanceTimestamps + (instanceNextTimestamps - instanceTimestamps) * vPathPosition.y / vPathLength; `, "fs:#decl": `uniform bool fadeTrail; uniform float trailLength; uniform float currentTime; in float vTime; `, "fs:#main-start": `if(vTime > currentTime || (fadeTrail && (vTime < currentTime - trailLength))) { discard; } `, "fs:DECKGL_FILTER_COLOR": `if(fadeTrail) { color.a *= 1.0 - (currentTime - vTime) / trailLength; } ` }; return shaders; } initializeState() { super.initializeState(); const attributeManager = this.getAttributeManager(); attributeManager.addInstanced({ timestamps: { size: 1, accessor: "getTimestamps", shaderAttributes: { instanceTimestamps: { vertexOffset: 0 }, instanceNextTimestamps: { vertexOffset: 1 } } } }); } draw(params) { const { fadeTrail, trailLength, currentTime } = this.props; params.uniforms = { ...params.uniforms, fadeTrail, trailLength, currentTime }; super.draw(params); } }; TripsLayer.layerName = "TripsLayer"; TripsLayer.defaultProps = defaultProps7; // src/h3-layers/h3-cluster-layer.ts var import_h3_js3 = __toESM(require_h3_js(), 1); var import_core17 = __toESM(require_core(), 1); // src/h3-layers/h3-hexagon-layer.ts var import_h3_js2 = __toESM(require_h3_js(), 1); var import_core16 = __toESM(require_core(), 1); var import_layers7 = __toESM(require_layers(), 1); // src/h3-layers/h3-utils.ts var import_h3_js = __toESM(require_h3_js(), 1); function normalizeLongitudes(vertices, refLng) { refLng = refLng === void 0 ? vertices[0][0] : refLng; for (const pt of vertices) { const deltaLng = pt[0] - refLng; if (deltaLng > 180) { pt[0] -= 360; } else if (deltaLng < -180) { pt[0] += 360; } } } function scalePolygon(hexId, vertices, factor) { const [lat, lng] = (0, import_h3_js.cellToLatLng)(hexId); const actualCount = vertices.length; normalizeLongitudes(vertices, lng); const vertexCount = vertices[0] === vertices[actualCount - 1] ? actualCount - 1 : actualCount; for (let i3 = 0; i3 < vertexCount; i3++) { vertices[i3][0] = lerp(lng, vertices[i3][0], factor); vertices[i3][1] = lerp(lat, vertices[i3][1], factor); } } function getHexagonCentroid(getHexagon, object, objectInfo) { const hexagonId = getHexagon(object, objectInfo); const [lat, lng] = (0, import_h3_js.cellToLatLng)(hexagonId); return [lng, lat]; } function h3ToPolygon(hexId, coverage = 1) { const vertices = (0, import_h3_js.cellToBoundary)(hexId, true); if (coverage !== 1) { scalePolygon(hexId, vertices, coverage); } else { normalizeLongitudes(vertices); } return vertices; } function flattenPolygon(vertices) { const positions = new Float64Array(vertices.length * 2); let i3 = 0; for (const pt of vertices) { positions[i3++] = pt[0]; positions[i3++] = pt[1]; } return positions; } // src/h3-layers/h3-hexagon-layer.ts var UPDATE_THRESHOLD_KM = 10; function mergeTriggers(getHexagon, coverage) { let trigger; if (getHexagon === void 0 || getHexagon === null) { trigger = coverage; } else if (typeof getHexagon === "object") { trigger = { ...getHexagon, coverage }; } else { trigger = { getHexagon, coverage }; } return trigger; } var defaultProps8 = { ...import_layers7.PolygonLayer.defaultProps, highPrecision: "auto", coverage: { type: "number", min: 0, max: 1, value: 1 }, centerHexagon: null, getHexagon: { type: "accessor", value: (x2) => x2.hexagon }, extruded: true }; var _H3HexagonLayer = class extends import_core16.CompositeLayer { initializeState() { _H3HexagonLayer._checkH3Lib(); this.state = { edgeLengthKM: 0, resolution: -1 }; } shouldUpdateState({ changeFlags }) { return this._shouldUseHighPrecision() ? changeFlags.propsOrDataChanged : changeFlags.somethingChanged; } updateState({ props, changeFlags }) { if (props.highPrecision !== true && (changeFlags.dataChanged || changeFlags.updateTriggersChanged && changeFlags.updateTriggersChanged.getHexagon)) { const dataProps = this._calculateH3DataProps(); this.setState(dataProps); } this._updateVertices(this.context.viewport); } _calculateH3DataProps() { let resolution = -1; let hasPentagon = false; let hasMultipleRes = false; const { iterable, objectInfo } = (0, import_core16.createIterable)(this.props.data); for (const object of iterable) { objectInfo.index++; const hexId = this.props.getHexagon(object, objectInfo); const hexResolution = (0, import_h3_js2.getResolution)(hexId); if (resolution < 0) { resolution = hexResolution; if (!this.props.highPrecision) break; } else if (resolution !== hexResolution) { hasMultipleRes = true; break; } if ((0, import_h3_js2.isPentagon)(hexId)) { hasPentagon = true; break; } } return { resolution, edgeLengthKM: resolution >= 0 ? (0, import_h3_js2.getHexagonEdgeLengthAvg)(resolution, "km") : 0, hasMultipleRes, hasPentagon }; } _shouldUseHighPrecision() { if (this.props.highPrecision === "auto") { const { resolution, hasPentagon, hasMultipleRes } = this.state; const { viewport } = this.context; return Boolean(viewport?.resolution) || hasMultipleRes || hasPentagon || resolution >= 0 && resolution <= 5; } return this.props.highPrecision; } _updateVertices(viewport) { if (this._shouldUseHighPrecision()) { return; } const { resolution, edgeLengthKM, centerHex } = this.state; if (resolution < 0) { return; } const hex = this.props.centerHexagon || (0, import_h3_js2.latLngToCell)(viewport.latitude, viewport.longitude, resolution); if (centerHex === hex) { return; } if (centerHex) { try { const distance2 = (0, import_h3_js2.gridDistance)(centerHex, hex); if (distance2 * edgeLengthKM < UPDATE_THRESHOLD_KM) { return; } } catch { } } const { unitsPerMeter: unitsPerMeter2 } = viewport.distanceScales; let vertices = h3ToPolygon(hex); const [centerLat, centerLng] = (0, import_h3_js2.cellToLatLng)(hex); const [centerX, centerY] = viewport.projectFlat([centerLng, centerLat]); vertices = vertices.map((p2) => { const worldPosition = viewport.projectFlat(p2); return [ (worldPosition[0] - centerX) / unitsPerMeter2[0], (worldPosition[1] - centerY) / unitsPerMeter2[1] ]; }); this.setState({ centerHex: hex, vertices }); } renderLayers() { return this._shouldUseHighPrecision() ? this._renderPolygonLayer() : this._renderColumnLayer(); } _getForwardProps() { const { elevationScale, material, coverage, extruded, wireframe, stroked, filled, lineWidthUnits, lineWidthScale, lineWidthMinPixels, lineWidthMaxPixels, getFillColor, getElevation, getLineColor, getLineWidth, transitions, updateTriggers } = this.props; return { elevationScale, extruded, coverage, wireframe, stroked, filled, lineWidthUnits, lineWidthScale, lineWidthMinPixels, lineWidthMaxPixels, material, getElevation, getFillColor, getLineColor, getLineWidth, transitions, updateTriggers: { getFillColor: updateTriggers.getFillColor, getElevation: updateTriggers.getElevation, getLineColor: updateTriggers.getLineColor, getLineWidth: updateTriggers.getLineWidth } }; } _renderPolygonLayer() { const { data, getHexagon, updateTriggers, coverage } = this.props; const SubLayerClass = this.getSubLayerClass("hexagon-cell-hifi", import_layers7.PolygonLayer); const forwardProps = this._getForwardProps(); forwardProps.updateTriggers.getPolygon = mergeTriggers(updateTriggers.getHexagon, coverage); return new SubLayerClass( forwardProps, this.getSubLayerProps({ id: "hexagon-cell-hifi", updateTriggers: forwardProps.updateTriggers }), { data, _normalize: false, _windingOrder: "CCW", positionFormat: "XY", getPolygon: (object, objectInfo) => { const hexagonId = getHexagon(object, objectInfo); return flattenPolygon(h3ToPolygon(hexagonId, coverage)); } } ); } _renderColumnLayer() { const { data, getHexagon, updateTriggers } = this.props; const SubLayerClass = this.getSubLayerClass("hexagon-cell", import_layers7.ColumnLayer); const forwardProps = this._getForwardProps(); forwardProps.updateTriggers.getPosition = updateTriggers.getHexagon; return new SubLayerClass( forwardProps, this.getSubLayerProps({ id: "hexagon-cell", flatShading: true, updateTriggers: forwardProps.updateTriggers }), { data, diskResolution: 6, radius: 1, vertices: this.state.vertices, getPosition: getHexagonCentroid.bind(null, getHexagon) } ); } }; var H3HexagonLayer = _H3HexagonLayer; H3HexagonLayer.defaultProps = defaultProps8; H3HexagonLayer.layerName = "H3HexagonLayer"; H3HexagonLayer._checkH3Lib = () => { }; // src/h3-layers/h3-cluster-layer.ts var defaultProps9 = { getHexagons: { type: "accessor", value: (d) => d.hexagons } }; var H3ClusterLayer = class extends GeoCellLayer { initializeState() { H3HexagonLayer._checkH3Lib(); } updateState({ props, changeFlags }) { if (changeFlags.dataChanged || changeFlags.updateTriggersChanged && changeFlags.updateTriggersChanged.getHexagons) { const { data, getHexagons } = props; const polygons = []; const { iterable, objectInfo } = (0, import_core17.createIterable)(data); for (const object of iterable) { objectInfo.index++; const hexagons = getHexagons(object, objectInfo); const multiPolygon = (0, import_h3_js3.cellsToMultiPolygon)(hexagons, true); for (const polygon of multiPolygon) { for (const ring of polygon) { normalizeLongitudes(ring); } polygons.push(this.getSubLayerRow({ polygon }, object, objectInfo.index)); } } this.setState({ polygons }); } } indexToBounds() { const { getElevation, getFillColor, getLineColor, getLineWidth } = this.props; return { data: this.state.polygons, getPolygon: (d) => d.polygon, getElevation: this.getSubLayerAccessor(getElevation), getFillColor: this.getSubLayerAccessor(getFillColor), getLineColor: this.getSubLayerAccessor(getLineColor), getLineWidth: this.getSubLayerAccessor(getLineWidth) }; } }; H3ClusterLayer.layerName = "H3ClusterLayer"; H3ClusterLayer.defaultProps = defaultProps9; // src/tile-3d-layer/tile-3d-layer.ts var import_engine2 = __toESM(require_engine(), 1); var import_core43 = __toESM(require_core(), 1); var import_layers8 = __toESM(require_layers(), 1); var import_mesh_layers2 = __toESM(require_mesh_layers(), 1); // ../../node_modules/@luma.gl/gltf/dist/pbr/parse-pbr-material.js var import_core18 = __toESM(require_core2(), 1); var GLEnum; (function(GLEnum2) { GLEnum2[GLEnum2["FUNC_ADD"] = 32774] = "FUNC_ADD"; GLEnum2[GLEnum2["ONE"] = 1] = "ONE"; GLEnum2[GLEnum2["SRC_ALPHA"] = 770] = "SRC_ALPHA"; GLEnum2[GLEnum2["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA"; GLEnum2[GLEnum2["TEXTURE_MIN_FILTER"] = 10241] = "TEXTURE_MIN_FILTER"; GLEnum2[GLEnum2["LINEAR"] = 9729] = "LINEAR"; GLEnum2[GLEnum2["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST"; GLEnum2[GLEnum2["UNPACK_FLIP_Y_WEBGL"] = 37440] = "UNPACK_FLIP_Y_WEBGL"; })(GLEnum || (GLEnum = {})); function parsePBRMaterial(device, material, attributes, options) { const parsedMaterial = { defines: { MANUAL_SRGB: 1, SRGB_FAST_APPROXIMATION: 1 }, bindings: {}, uniforms: { u_Camera: [0, 0, 0], u_MetallicRoughnessValues: [1, 1] }, parameters: {}, glParameters: {}, generatedTextures: [] }; parsedMaterial.defines.USE_TEX_LOD = 1; const { imageBasedLightingEnvironment } = options; if (imageBasedLightingEnvironment) { parsedMaterial.bindings.u_DiffuseEnvSampler = imageBasedLightingEnvironment.diffuseEnvSampler; parsedMaterial.bindings.u_SpecularEnvSampler = imageBasedLightingEnvironment.specularEnvSampler; parsedMaterial.bindings.u_brdfLUT = imageBasedLightingEnvironment.brdfLutTexture; parsedMaterial.uniforms.u_ScaleIBLAmbient = [1, 1]; } if (options?.pbrDebug) { parsedMaterial.defines.PBR_DEBUG = 1; parsedMaterial.uniforms.u_ScaleDiffBaseMR = [0, 0, 0, 0]; parsedMaterial.uniforms.u_ScaleFGDSpec = [0, 0, 0, 0]; } if (attributes.NORMAL) parsedMaterial.defines.HAS_NORMALS = 1; if (attributes.TANGENT && options?.useTangents) parsedMaterial.defines.HAS_TANGENTS = 1; if (attributes.TEXCOORD_0) parsedMaterial.defines.HAS_UV = 1; if (options?.imageBasedLightingEnvironment) parsedMaterial.defines.USE_IBL = 1; if (options?.lights) parsedMaterial.defines.USE_LIGHTS = 1; if (material) { parseMaterial(device, material, parsedMaterial); } return parsedMaterial; } function parseMaterial(device, material, parsedMaterial) { parsedMaterial.uniforms.pbr_uUnlit = Boolean(material.unlit); if (material.pbrMetallicRoughness) { parsePbrMetallicRoughness(device, material.pbrMetallicRoughness, parsedMaterial); } if (material.normalTexture) { addTexture(device, material.normalTexture, "u_NormalSampler", "HAS_NORMALMAP", parsedMaterial); const { scale: scale6 = 1 } = material.normalTexture; parsedMaterial.uniforms.u_NormalScale = scale6; } if (material.occlusionTexture) { addTexture(device, material.occlusionTexture, "u_OcclusionSampler", "HAS_OCCLUSIONMAP", parsedMaterial); const { strength = 1 } = material.occlusionTexture; parsedMaterial.uniforms.u_OcclusionStrength = strength; } if (material.emissiveTexture) { addTexture(device, material.emissiveTexture, "u_EmissiveSampler", "HAS_EMISSIVEMAP", parsedMaterial); parsedMaterial.uniforms.u_EmissiveFactor = material.emissiveFactor || [0, 0, 0]; } switch (material.alphaMode) { case "MASK": const { alphaCutoff = 0.5 } = material; parsedMaterial.defines.ALPHA_CUTOFF = 1; parsedMaterial.uniforms.u_AlphaCutoff = alphaCutoff; break; case "BLEND": import_core18.log.warn("glTF BLEND alphaMode might not work well because it requires mesh sorting")(); parsedMaterial.parameters.blendColorOperation = "add"; parsedMaterial.parameters.blendColorSrcFactor = "src-alpha"; parsedMaterial.parameters.blendColorDstFactor = "one-minus-src-alpha"; parsedMaterial.parameters.blendAlphaOperation = "add"; parsedMaterial.parameters.blendAlphaSrcFactor = "one"; parsedMaterial.parameters.blendAlphaDstFactor = "one-minus-src-alpha"; parsedMaterial.glParameters.blend = true; parsedMaterial.glParameters.blendEquation = GLEnum.FUNC_ADD; parsedMaterial.glParameters.blendFunc = [ GLEnum.SRC_ALPHA, GLEnum.ONE_MINUS_SRC_ALPHA, GLEnum.ONE, GLEnum.ONE_MINUS_SRC_ALPHA ]; break; } } function parsePbrMetallicRoughness(device, pbrMetallicRoughness, parsedMaterial) { if (pbrMetallicRoughness.baseColorTexture) { addTexture(device, pbrMetallicRoughness.baseColorTexture, "u_BaseColorSampler", "HAS_BASECOLORMAP", parsedMaterial); } parsedMaterial.uniforms.u_BaseColorFactor = pbrMetallicRoughness.baseColorFactor || [1, 1, 1, 1]; if (pbrMetallicRoughness.metallicRoughnessTexture) { addTexture(device, pbrMetallicRoughness.metallicRoughnessTexture, "u_MetallicRoughnessSampler", "HAS_METALROUGHNESSMAP", parsedMaterial); } const { metallicFactor = 1, roughnessFactor = 1 } = pbrMetallicRoughness; parsedMaterial.uniforms.u_MetallicRoughnessValues = [metallicFactor, roughnessFactor]; } function addTexture(device, gltfTexture, uniformName, define2 = null, parsedMaterial) { const parameters = gltfTexture?.texture?.sampler?.parameters || {}; const image = gltfTexture.texture.source.image; let textureOptions; let specialTextureParameters = {}; if (image.compressed) { textureOptions = image; specialTextureParameters = { [GLEnum.TEXTURE_MIN_FILTER]: image.data.length > 1 ? GLEnum.LINEAR_MIPMAP_NEAREST : GLEnum.LINEAR }; } else { textureOptions = { data: image }; } const texture = device.createTexture({ id: gltfTexture.uniformName || gltfTexture.id, parameters: { ...parameters, ...specialTextureParameters }, pixelStore: { [GLEnum.UNPACK_FLIP_Y_WEBGL]: false }, ...textureOptions }); parsedMaterial.bindings[uniformName] = texture; if (define2) parsedMaterial.defines[define2] = 1; parsedMaterial.generatedTextures.push(texture); } // ../../node_modules/@loaders.gl/textures/dist/lib/utils/version.js var VERSION7 = true ? "4.2.0-beta.2" : "latest"; // ../../node_modules/@loaders.gl/textures/dist/lib/parsers/basis-module-loader.js var BASIS_EXTERNAL_LIBRARIES = { TRANSCODER: "basis_transcoder.js", TRANSCODER_WASM: "basis_transcoder.wasm", ENCODER: "basis_encoder.js", ENCODER_WASM: "basis_encoder.wasm" }; var loadBasisTranscoderPromise; async function loadBasisTranscoderModule(options) { registerJSModules(options.modules); const basis = getJSModuleOrNull("basis"); if (basis) { return basis; } loadBasisTranscoderPromise ||= loadBasisTranscoder(options); return await loadBasisTranscoderPromise; } async function loadBasisTranscoder(options) { let BASIS = null; let wasmBinary = null; [BASIS, wasmBinary] = await Promise.all([ await loadLibrary(BASIS_EXTERNAL_LIBRARIES.TRANSCODER, "textures", options), await loadLibrary(BASIS_EXTERNAL_LIBRARIES.TRANSCODER_WASM, "textures", options) ]); BASIS = BASIS || globalThis.BASIS; return await initializeBasisTranscoderModule(BASIS, wasmBinary); } function initializeBasisTranscoderModule(BasisModule, wasmBinary) { const options = {}; if (wasmBinary) { options.wasmBinary = wasmBinary; } return new Promise((resolve2) => { BasisModule(options).then((module) => { const { BasisFile, initializeBasis } = module; initializeBasis(); resolve2({ BasisFile }); }); }); } var loadBasisEncoderPromise; async function loadBasisEncoderModule(options) { const modules = options.modules || {}; if (modules.basisEncoder) { return modules.basisEncoder; } loadBasisEncoderPromise = loadBasisEncoderPromise || loadBasisEncoder(options); return await loadBasisEncoderPromise; } async function loadBasisEncoder(options) { let BASIS_ENCODER = null; let wasmBinary = null; [BASIS_ENCODER, wasmBinary] = await Promise.all([ await loadLibrary(BASIS_EXTERNAL_LIBRARIES.ENCODER, "textures", options), await loadLibrary(BASIS_EXTERNAL_LIBRARIES.ENCODER_WASM, "textures", options) ]); BASIS_ENCODER = BASIS_ENCODER || globalThis.BASIS; return await initializeBasisEncoderModule(BASIS_ENCODER, wasmBinary); } function initializeBasisEncoderModule(BasisEncoderModule, wasmBinary) { const options = {}; if (wasmBinary) { options.wasmBinary = wasmBinary; } return new Promise((resolve2) => { BasisEncoderModule(options).then((module) => { const { BasisFile, KTX2File, initializeBasis, BasisEncoder } = module; initializeBasis(); resolve2({ BasisFile, KTX2File, BasisEncoder }); }); }); } // ../../node_modules/@loaders.gl/textures/dist/lib/gl-extensions.js var GL_EXTENSIONS_CONSTANTS = { COMPRESSED_RGB_S3TC_DXT1_EXT: 33776, COMPRESSED_RGBA_S3TC_DXT1_EXT: 33777, COMPRESSED_RGBA_S3TC_DXT3_EXT: 33778, COMPRESSED_RGBA_S3TC_DXT5_EXT: 33779, COMPRESSED_R11_EAC: 37488, COMPRESSED_SIGNED_R11_EAC: 37489, COMPRESSED_RG11_EAC: 37490, COMPRESSED_SIGNED_RG11_EAC: 37491, COMPRESSED_RGB8_ETC2: 37492, COMPRESSED_RGBA8_ETC2_EAC: 37493, COMPRESSED_SRGB8_ETC2: 37494, COMPRESSED_SRGB8_ALPHA8_ETC2_EAC: 37495, COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2: 37496, COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2: 37497, COMPRESSED_RGB_PVRTC_4BPPV1_IMG: 35840, COMPRESSED_RGBA_PVRTC_4BPPV1_IMG: 35842, COMPRESSED_RGB_PVRTC_2BPPV1_IMG: 35841, COMPRESSED_RGBA_PVRTC_2BPPV1_IMG: 35843, COMPRESSED_RGB_ETC1_WEBGL: 36196, COMPRESSED_RGB_ATC_WEBGL: 35986, COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL: 35987, COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL: 34798, COMPRESSED_RGBA_ASTC_4X4_KHR: 37808, COMPRESSED_RGBA_ASTC_5X4_KHR: 37809, COMPRESSED_RGBA_ASTC_5X5_KHR: 37810, COMPRESSED_RGBA_ASTC_6X5_KHR: 37811, COMPRESSED_RGBA_ASTC_6X6_KHR: 37812, COMPRESSED_RGBA_ASTC_8X5_KHR: 37813, COMPRESSED_RGBA_ASTC_8X6_KHR: 37814, COMPRESSED_RGBA_ASTC_8X8_KHR: 37815, COMPRESSED_RGBA_ASTC_10X5_KHR: 37816, COMPRESSED_RGBA_ASTC_10X6_KHR: 37817, COMPRESSED_RGBA_ASTC_10X8_KHR: 37818, COMPRESSED_RGBA_ASTC_10X10_KHR: 37819, COMPRESSED_RGBA_ASTC_12X10_KHR: 37820, COMPRESSED_RGBA_ASTC_12X12_KHR: 37821, COMPRESSED_SRGB8_ALPHA8_ASTC_4X4_KHR: 37840, COMPRESSED_SRGB8_ALPHA8_ASTC_5X4_KHR: 37841, COMPRESSED_SRGB8_ALPHA8_ASTC_5X5_KHR: 37842, COMPRESSED_SRGB8_ALPHA8_ASTC_6X5_KHR: 37843, COMPRESSED_SRGB8_ALPHA8_ASTC_6X6_KHR: 37844, COMPRESSED_SRGB8_ALPHA8_ASTC_8X5_KHR: 37845, COMPRESSED_SRGB8_ALPHA8_ASTC_8X6_KHR: 37846, COMPRESSED_SRGB8_ALPHA8_ASTC_8X8_KHR: 37847, COMPRESSED_SRGB8_ALPHA8_ASTC_10X5_KHR: 37848, COMPRESSED_SRGB8_ALPHA8_ASTC_10X6_KHR: 37849, COMPRESSED_SRGB8_ALPHA8_ASTC_10X8_KHR: 37850, COMPRESSED_SRGB8_ALPHA8_ASTC_10X10_KHR: 37851, COMPRESSED_SRGB8_ALPHA8_ASTC_12X10_KHR: 37852, COMPRESSED_SRGB8_ALPHA8_ASTC_12X12_KHR: 37853, COMPRESSED_RED_RGTC1_EXT: 36283, COMPRESSED_SIGNED_RED_RGTC1_EXT: 36284, COMPRESSED_RED_GREEN_RGTC2_EXT: 36285, COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT: 36286, COMPRESSED_SRGB_S3TC_DXT1_EXT: 35916, COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: 35917, COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: 35918, COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: 35919 }; // ../../node_modules/@loaders.gl/textures/dist/lib/utils/texture-formats.js var BROWSER_PREFIXES = ["", "WEBKIT_", "MOZ_"]; var WEBGL_EXTENSIONS = { WEBGL_compressed_texture_s3tc: "dxt", WEBGL_compressed_texture_s3tc_srgb: "dxt-srgb", WEBGL_compressed_texture_etc1: "etc1", WEBGL_compressed_texture_etc: "etc2", WEBGL_compressed_texture_pvrtc: "pvrtc", WEBGL_compressed_texture_atc: "atc", WEBGL_compressed_texture_astc: "astc", EXT_texture_compression_rgtc: "rgtc" }; var formats = null; function getSupportedGPUTextureFormats(gl) { if (!formats) { gl = gl || getWebGLContext() || void 0; formats = /* @__PURE__ */ new Set(); for (const prefix of BROWSER_PREFIXES) { for (const extension in WEBGL_EXTENSIONS) { if (gl && gl.getExtension(`${prefix}${extension}`)) { const gpuTextureFormat = WEBGL_EXTENSIONS[extension]; formats.add(gpuTextureFormat); } } } } return formats; } function getWebGLContext() { try { const canvas = document.createElement("canvas"); return canvas.getContext("webgl"); } catch (error) { return null; } } // ../../node_modules/ktx-parse/dist/ktx-parse.modern.js var t = new Uint8Array([0]); var n; var i; var s; var a; var r; var o; var l; var f; !function(t2) { t2[t2.NONE = 0] = "NONE", t2[t2.BASISLZ = 1] = "BASISLZ", t2[t2.ZSTD = 2] = "ZSTD", t2[t2.ZLIB = 3] = "ZLIB"; }(n || (n = {})), function(t2) { t2[t2.BASICFORMAT = 0] = "BASICFORMAT"; }(i || (i = {})), function(t2) { t2[t2.UNSPECIFIED = 0] = "UNSPECIFIED", t2[t2.ETC1S = 163] = "ETC1S", t2[t2.UASTC = 166] = "UASTC"; }(s || (s = {})), function(t2) { t2[t2.UNSPECIFIED = 0] = "UNSPECIFIED", t2[t2.SRGB = 1] = "SRGB"; }(a || (a = {})), function(t2) { t2[t2.UNSPECIFIED = 0] = "UNSPECIFIED", t2[t2.LINEAR = 1] = "LINEAR", t2[t2.SRGB = 2] = "SRGB", t2[t2.ITU = 3] = "ITU", t2[t2.NTSC = 4] = "NTSC", t2[t2.SLOG = 5] = "SLOG", t2[t2.SLOG2 = 6] = "SLOG2"; }(r || (r = {})), function(t2) { t2[t2.ALPHA_STRAIGHT = 0] = "ALPHA_STRAIGHT", t2[t2.ALPHA_PREMULTIPLIED = 1] = "ALPHA_PREMULTIPLIED"; }(o || (o = {})), function(t2) { t2[t2.RGB = 0] = "RGB", t2[t2.RRR = 3] = "RRR", t2[t2.GGG = 4] = "GGG", t2[t2.AAA = 15] = "AAA"; }(l || (l = {})), function(t2) { t2[t2.RGB = 0] = "RGB", t2[t2.RGBA = 3] = "RGBA", t2[t2.RRR = 4] = "RRR", t2[t2.RRRG = 5] = "RRRG"; }(f || (f = {})); // ../../node_modules/@loaders.gl/textures/dist/lib/parsers/parse-ktx.js var KTX2_ID = [ 171, 75, 84, 88, 32, 50, 48, 187, 13, 10, 26, 10 ]; function isKTX(data) { const id = new Uint8Array(data); const notKTX = id.byteLength < KTX2_ID.length || id[0] !== KTX2_ID[0] || id[1] !== KTX2_ID[1] || id[2] !== KTX2_ID[2] || id[3] !== KTX2_ID[3] || id[4] !== KTX2_ID[4] || id[5] !== KTX2_ID[5] || id[6] !== KTX2_ID[6] || id[7] !== KTX2_ID[7] || id[8] !== KTX2_ID[8] || id[9] !== KTX2_ID[9] || id[10] !== KTX2_ID[10] || id[11] !== KTX2_ID[11]; return !notKTX; } // ../../node_modules/@loaders.gl/textures/dist/lib/parsers/parse-basis.js var OutputFormat = { etc1: { basisFormat: 0, compressed: true, format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB_ETC1_WEBGL }, etc2: { basisFormat: 1, compressed: true }, bc1: { basisFormat: 2, compressed: true, format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB_S3TC_DXT1_EXT }, bc3: { basisFormat: 3, compressed: true, format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_S3TC_DXT5_EXT }, bc4: { basisFormat: 4, compressed: true }, bc5: { basisFormat: 5, compressed: true }, "bc7-m6-opaque-only": { basisFormat: 6, compressed: true }, "bc7-m5": { basisFormat: 7, compressed: true }, "pvrtc1-4-rgb": { basisFormat: 8, compressed: true, format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB_PVRTC_4BPPV1_IMG }, "pvrtc1-4-rgba": { basisFormat: 9, compressed: true, format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG }, "astc-4x4": { basisFormat: 10, compressed: true, format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_ASTC_4X4_KHR }, "atc-rgb": { basisFormat: 11, compressed: true }, "atc-rgba-interpolated-alpha": { basisFormat: 12, compressed: true }, rgba32: { basisFormat: 13, compressed: false }, rgb565: { basisFormat: 14, compressed: false }, bgr565: { basisFormat: 15, compressed: false }, rgba4444: { basisFormat: 16, compressed: false } }; async function parseBasis(data, options) { if (options.basis.containerFormat === "auto") { if (isKTX(data)) { const fileConstructors = await loadBasisEncoderModule(options); return parseKTX2File(fileConstructors.KTX2File, data, options); } const { BasisFile } = await loadBasisTranscoderModule(options); return parseBasisFile(BasisFile, data, options); } switch (options.basis.module) { case "encoder": const fileConstructors = await loadBasisEncoderModule(options); switch (options.basis.containerFormat) { case "ktx2": return parseKTX2File(fileConstructors.KTX2File, data, options); case "basis": default: return parseBasisFile(fileConstructors.BasisFile, data, options); } case "transcoder": default: const { BasisFile } = await loadBasisTranscoderModule(options); return parseBasisFile(BasisFile, data, options); } } function parseBasisFile(BasisFile, data, options) { const basisFile = new BasisFile(new Uint8Array(data)); try { if (!basisFile.startTranscoding()) { throw new Error("Failed to start basis transcoding"); } const imageCount = basisFile.getNumImages(); const images = []; for (let imageIndex = 0; imageIndex < imageCount; imageIndex++) { const levelsCount = basisFile.getNumLevels(imageIndex); const levels = []; for (let levelIndex = 0; levelIndex < levelsCount; levelIndex++) { levels.push(transcodeImage(basisFile, imageIndex, levelIndex, options)); } images.push(levels); } return images; } finally { basisFile.close(); basisFile.delete(); } } function transcodeImage(basisFile, imageIndex, levelIndex, options) { const width = basisFile.getImageWidth(imageIndex, levelIndex); const height = basisFile.getImageHeight(imageIndex, levelIndex); const hasAlpha = basisFile.getHasAlpha(); const { compressed, format, basisFormat } = getBasisOptions(options, hasAlpha); const decodedSize = basisFile.getImageTranscodedSizeInBytes(imageIndex, levelIndex, basisFormat); const decodedData = new Uint8Array(decodedSize); if (!basisFile.transcodeImage(decodedData, imageIndex, levelIndex, basisFormat, 0, 0)) { throw new Error("failed to start Basis transcoding"); } return { width, height, data: decodedData, compressed, format, hasAlpha }; } function parseKTX2File(KTX2File, data, options) { const ktx2File = new KTX2File(new Uint8Array(data)); try { if (!ktx2File.startTranscoding()) { throw new Error("failed to start KTX2 transcoding"); } const levelsCount = ktx2File.getLevels(); const levels = []; for (let levelIndex = 0; levelIndex < levelsCount; levelIndex++) { levels.push(transcodeKTX2Image(ktx2File, levelIndex, options)); break; } return [levels]; } finally { ktx2File.close(); ktx2File.delete(); } } function transcodeKTX2Image(ktx2File, levelIndex, options) { const { alphaFlag, height, width } = ktx2File.getImageLevelInfo(levelIndex, 0, 0); const { compressed, format, basisFormat } = getBasisOptions(options, alphaFlag); const decodedSize = ktx2File.getImageTranscodedSizeInBytes(levelIndex, 0, 0, basisFormat); const decodedData = new Uint8Array(decodedSize); if (!ktx2File.transcodeImage(decodedData, levelIndex, 0, 0, basisFormat, 0, -1, -1)) { throw new Error("Failed to transcode KTX2 image"); } return { width, height, data: decodedData, compressed, levelSize: decodedSize, hasAlpha: alphaFlag, format }; } function getBasisOptions(options, hasAlpha) { let format = options && options.basis && options.basis.format; if (format === "auto") { format = selectSupportedBasisFormat(); } if (typeof format === "object") { format = hasAlpha ? format.alpha : format.noAlpha; } format = format.toLowerCase(); return OutputFormat[format]; } function selectSupportedBasisFormat() { const supportedFormats = getSupportedGPUTextureFormats(); if (supportedFormats.has("astc")) { return "astc-4x4"; } else if (supportedFormats.has("dxt")) { return { alpha: "bc3", noAlpha: "bc1" }; } else if (supportedFormats.has("pvrtc")) { return { alpha: "pvrtc1-4-rgba", noAlpha: "pvrtc1-4-rgb" }; } else if (supportedFormats.has("etc1")) { return "etc1"; } else if (supportedFormats.has("etc2")) { return "etc2"; } return "rgb565"; } // ../../node_modules/@loaders.gl/textures/dist/basis-loader.js var BasisWorkerLoader = { dataType: null, batchType: null, name: "Basis", id: "basis", module: "textures", version: VERSION7, worker: true, extensions: ["basis", "ktx2"], mimeTypes: ["application/octet-stream", "image/ktx2"], tests: ["sB"], binary: true, options: { basis: { format: "auto", libraryPath: "libs/", containerFormat: "auto", module: "transcoder" } } }; var BasisLoader = { ...BasisWorkerLoader, parse: parseBasis }; // ../../node_modules/@luma.gl/shadertools/dist/modules-webgl1/lighting/lights/lights-glsl.js var lightingShader = `#if (defined(SHADER_TYPE_FRAGMENT) && defined(LIGHTING_FRAGMENT)) || (defined(SHADER_TYPE_VERTEX) && defined(LIGHTING_VERTEX)) struct AmbientLight { vec3 color; }; struct PointLight { vec3 color; vec3 position; vec3 attenuation; }; struct DirectionalLight { vec3 color; vec3 direction; }; uniform AmbientLight lighting_uAmbientLight; uniform PointLight lighting_uPointLight[MAX_LIGHTS]; uniform DirectionalLight lighting_uDirectionalLight[MAX_LIGHTS]; uniform int lighting_uPointLightCount; uniform int lighting_uDirectionalLightCount; uniform bool lighting_uEnabled; float getPointLightAttenuation(PointLight pointLight, float distance) { return pointLight.attenuation.x + pointLight.attenuation.y * distance + pointLight.attenuation.z * distance * distance; } #endif `; // ../../node_modules/@luma.gl/shadertools/dist/modules-webgl1/lighting/lights/lights.js var INITIAL_MODULE_OPTIONS = { lightSources: {} }; function convertColor(colorDef = {}) { const { color = [0, 0, 0], intensity = 1 } = colorDef; return color.map((component) => component * intensity / 255); } function getLightSourceUniforms({ ambientLight, pointLights = [], directionalLights = [] }) { const lightSourceUniforms = {}; if (ambientLight) { lightSourceUniforms["lighting_uAmbientLight.color"] = convertColor(ambientLight); } else { lightSourceUniforms["lighting_uAmbientLight.color"] = [0, 0, 0]; } pointLights.forEach((pointLight, index) => { lightSourceUniforms[`lighting_uPointLight[${index}].color`] = convertColor(pointLight); lightSourceUniforms[`lighting_uPointLight[${index}].position`] = pointLight.position; lightSourceUniforms[`lighting_uPointLight[${index}].attenuation`] = pointLight.attenuation || [ 1, 0, 0 ]; }); lightSourceUniforms.lighting_uPointLightCount = pointLights.length; directionalLights.forEach((directionalLight, index) => { lightSourceUniforms[`lighting_uDirectionalLight[${index}].color`] = convertColor(directionalLight); lightSourceUniforms[`lighting_uDirectionalLight[${index}].direction`] = directionalLight.direction; }); lightSourceUniforms.lighting_uDirectionalLightCount = directionalLights.length; return lightSourceUniforms; } function getUniforms(opts = INITIAL_MODULE_OPTIONS) { if ("lightSources" in opts) { const { ambientLight, pointLights, directionalLights } = opts.lightSources || {}; const hasLights = ambientLight || pointLights && pointLights.length > 0 || directionalLights && directionalLights.length > 0; if (!hasLights) { return { lighting_uEnabled: false }; } return Object.assign({}, getLightSourceUniforms({ ambientLight, pointLights, directionalLights }), { lighting_uEnabled: true }); } if ("lights" in opts) { const lightSources = { pointLights: [], directionalLights: [] }; for (const light of opts.lights || []) { switch (light.type) { case "ambient": lightSources.ambientLight = light; break; case "directional": lightSources.directionalLights?.push(light); break; case "point": lightSources.pointLights?.push(light); break; default: } } return getUniforms({ lightSources }); } return {}; } var lights = { name: "lights", vs: lightingShader, fs: lightingShader, getUniforms, defines: { MAX_LIGHTS: 3 } }; // ../../node_modules/@luma.gl/shadertools/dist/modules-webgl1/lighting/pbr/pbr-vertex-glsl.js var vs = `uniform mat4 u_MVPMatrix; uniform mat4 u_ModelMatrix; uniform mat4 u_NormalMatrix; out vec3 pbr_vPosition; out vec2 pbr_vUV; #ifdef HAS_NORMALS # ifdef HAS_TANGENTS out mat3 pbr_vTBN; # else out vec3 pbr_vNormal; # endif #endif void pbr_setPositionNormalTangentUV(vec4 position, vec4 normal, vec4 tangent, vec2 uv) { vec4 pos = u_ModelMatrix * position; pbr_vPosition = vec3(pos.xyz) / pos.w; #ifdef HAS_NORMALS #ifdef HAS_TANGENTS vec3 normalW = normalize(vec3(u_NormalMatrix * vec4(normal.xyz, 0.0))); vec3 tangentW = normalize(vec3(u_ModelMatrix * vec4(tangent.xyz, 0.0))); vec3 bitangentW = cross(normalW, tangentW) * tangent.w; pbr_vTBN = mat3(tangentW, bitangentW, normalW); #else pbr_vNormal = normalize(vec3(u_ModelMatrix * vec4(normal.xyz, 0.0))); #endif #endif #ifdef HAS_UV pbr_vUV = uv; #else pbr_vUV = vec2(0.,0.); #endif } `; // ../../node_modules/@luma.gl/shadertools/dist/modules-webgl1/lighting/pbr/pbr-fragment-glsl.js var fs = `precision highp float; uniform bool pbr_uUnlit; #ifdef USE_IBL uniform samplerCube u_DiffuseEnvSampler; uniform samplerCube u_SpecularEnvSampler; uniform sampler2D u_brdfLUT; uniform vec2 u_ScaleIBLAmbient; #endif #ifdef HAS_BASECOLORMAP uniform sampler2D u_BaseColorSampler; #endif #ifdef HAS_NORMALMAP uniform sampler2D u_NormalSampler; uniform float u_NormalScale; #endif #ifdef HAS_EMISSIVEMAP uniform sampler2D u_EmissiveSampler; uniform vec3 u_EmissiveFactor; #endif #ifdef HAS_METALROUGHNESSMAP uniform sampler2D u_MetallicRoughnessSampler; #endif #ifdef HAS_OCCLUSIONMAP uniform sampler2D u_OcclusionSampler; uniform float u_OcclusionStrength; #endif #ifdef ALPHA_CUTOFF uniform float u_AlphaCutoff; #endif uniform vec2 u_MetallicRoughnessValues; uniform vec4 u_BaseColorFactor; uniform vec3 u_Camera; #ifdef PBR_DEBUG uniform vec4 u_ScaleDiffBaseMR; uniform vec4 u_ScaleFGDSpec; #endif in vec3 pbr_vPosition; in vec2 pbr_vUV; #ifdef HAS_NORMALS #ifdef HAS_TANGENTS in mat3 pbr_vTBN; #else in vec3 pbr_vNormal; #endif #endif struct PBRInfo { float NdotL; float NdotV; float NdotH; float LdotH; float VdotH; float perceptualRoughness; float metalness; vec3 reflectance0; vec3 reflectance90; float alphaRoughness; vec3 diffuseColor; vec3 specularColor; vec3 n; vec3 v; }; const float M_PI = 3.141592653589793; const float c_MinRoughness = 0.04; vec4 SRGBtoLINEAR(vec4 srgbIn) { #ifdef MANUAL_SRGB #ifdef SRGB_FAST_APPROXIMATION vec3 linOut = pow(srgbIn.xyz,vec3(2.2)); #else vec3 bLess = step(vec3(0.04045),srgbIn.xyz); vec3 linOut = mix( srgbIn.xyz/vec3(12.92), pow((srgbIn.xyz+vec3(0.055))/vec3(1.055),vec3(2.4)), bLess ); #endif return vec4(linOut,srgbIn.w);; #else return srgbIn; #endif } vec3 getNormal() { #ifndef HAS_TANGENTS vec3 pos_dx = dFdx(pbr_vPosition); vec3 pos_dy = dFdy(pbr_vPosition); vec3 tex_dx = dFdx(vec3(pbr_vUV, 0.0)); vec3 tex_dy = dFdy(vec3(pbr_vUV, 0.0)); vec3 t = (tex_dy.t * pos_dx - tex_dx.t * pos_dy) / (tex_dx.s * tex_dy.t - tex_dy.s * tex_dx.t); #ifdef HAS_NORMALS vec3 ng = normalize(pbr_vNormal); #else vec3 ng = cross(pos_dx, pos_dy); #endif t = normalize(t - ng * dot(ng, t)); vec3 b = normalize(cross(ng, t)); mat3 tbn = mat3(t, b, ng); #else mat3 tbn = pbr_vTBN; #endif #ifdef HAS_NORMALMAP vec3 n = texture(u_NormalSampler, pbr_vUV).rgb; n = normalize(tbn * ((2.0 * n - 1.0) * vec3(u_NormalScale, u_NormalScale, 1.0))); #else vec3 n = normalize(tbn[2].xyz); #endif return n; } #ifdef USE_IBL vec3 getIBLContribution(PBRInfo pbrInputs, vec3 n, vec3 reflection) { float mipCount = 9.0; float lod = (pbrInputs.perceptualRoughness * mipCount); vec3 brdf = SRGBtoLINEAR(texture(u_brdfLUT, vec2(pbrInputs.NdotV, 1.0 - pbrInputs.perceptualRoughness))).rgb; vec3 diffuseLight = SRGBtoLINEAR(textureCube(u_DiffuseEnvSampler, n)).rgb; #ifdef USE_TEX_LOD vec3 specularLight = SRGBtoLINEAR(textureCubeLod(u_SpecularEnvSampler, reflection, lod)).rgb; #else vec3 specularLight = SRGBtoLINEAR(textureCube(u_SpecularEnvSampler, reflection)).rgb; #endif vec3 diffuse = diffuseLight * pbrInputs.diffuseColor; vec3 specular = specularLight * (pbrInputs.specularColor * brdf.x + brdf.y); diffuse *= u_ScaleIBLAmbient.x; specular *= u_ScaleIBLAmbient.y; return diffuse + specular; } #endif vec3 diffuse(PBRInfo pbrInputs) { return pbrInputs.diffuseColor / M_PI; } vec3 specularReflection(PBRInfo pbrInputs) { return pbrInputs.reflectance0 + (pbrInputs.reflectance90 - pbrInputs.reflectance0) * pow(clamp(1.0 - pbrInputs.VdotH, 0.0, 1.0), 5.0); } float geometricOcclusion(PBRInfo pbrInputs) { float NdotL = pbrInputs.NdotL; float NdotV = pbrInputs.NdotV; float r = pbrInputs.alphaRoughness; float attenuationL = 2.0 * NdotL / (NdotL + sqrt(r * r + (1.0 - r * r) * (NdotL * NdotL))); float attenuationV = 2.0 * NdotV / (NdotV + sqrt(r * r + (1.0 - r * r) * (NdotV * NdotV))); return attenuationL * attenuationV; } float microfacetDistribution(PBRInfo pbrInputs) { float roughnessSq = pbrInputs.alphaRoughness * pbrInputs.alphaRoughness; float f = (pbrInputs.NdotH * roughnessSq - pbrInputs.NdotH) * pbrInputs.NdotH + 1.0; return roughnessSq / (M_PI * f * f); } void PBRInfo_setAmbientLight(inout PBRInfo pbrInputs) { pbrInputs.NdotL = 1.0; pbrInputs.NdotH = 0.0; pbrInputs.LdotH = 0.0; pbrInputs.VdotH = 1.0; } void PBRInfo_setDirectionalLight(inout PBRInfo pbrInputs, vec3 lightDirection) { vec3 n = pbrInputs.n; vec3 v = pbrInputs.v; vec3 l = normalize(lightDirection); vec3 h = normalize(l+v); pbrInputs.NdotL = clamp(dot(n, l), 0.001, 1.0); pbrInputs.NdotH = clamp(dot(n, h), 0.0, 1.0); pbrInputs.LdotH = clamp(dot(l, h), 0.0, 1.0); pbrInputs.VdotH = clamp(dot(v, h), 0.0, 1.0); } void PBRInfo_setPointLight(inout PBRInfo pbrInputs, PointLight pointLight) { vec3 light_direction = normalize(pointLight.position - pbr_vPosition); PBRInfo_setDirectionalLight(pbrInputs, light_direction); } vec3 calculateFinalColor(PBRInfo pbrInputs, vec3 lightColor) { vec3 F = specularReflection(pbrInputs); float G = geometricOcclusion(pbrInputs); float D = microfacetDistribution(pbrInputs); vec3 diffuseContrib = (1.0 - F) * diffuse(pbrInputs); vec3 specContrib = F * G * D / (4.0 * pbrInputs.NdotL * pbrInputs.NdotV); return pbrInputs.NdotL * lightColor * (diffuseContrib + specContrib); } vec4 pbr_filterColor(vec4 colorUnused) { #ifdef HAS_BASECOLORMAP vec4 baseColor = SRGBtoLINEAR(texture(u_BaseColorSampler, pbr_vUV)) * u_BaseColorFactor; #else vec4 baseColor = u_BaseColorFactor; #endif #ifdef ALPHA_CUTOFF if (baseColor.a < u_AlphaCutoff) { discard; } #endif vec3 color = vec3(0, 0, 0); if(pbr_uUnlit){ color.rgb = baseColor.rgb; } else{ float perceptualRoughness = u_MetallicRoughnessValues.y; float metallic = u_MetallicRoughnessValues.x; #ifdef HAS_METALROUGHNESSMAP vec4 mrSample = texture(u_MetallicRoughnessSampler, pbr_vUV); perceptualRoughness = mrSample.g * perceptualRoughness; metallic = mrSample.b * metallic; #endif perceptualRoughness = clamp(perceptualRoughness, c_MinRoughness, 1.0); metallic = clamp(metallic, 0.0, 1.0); float alphaRoughness = perceptualRoughness * perceptualRoughness; vec3 f0 = vec3(0.04); vec3 diffuseColor = baseColor.rgb * (vec3(1.0) - f0); diffuseColor *= 1.0 - metallic; vec3 specularColor = mix(f0, baseColor.rgb, metallic); float reflectance = max(max(specularColor.r, specularColor.g), specularColor.b); float reflectance90 = clamp(reflectance * 25.0, 0.0, 1.0); vec3 specularEnvironmentR0 = specularColor.rgb; vec3 specularEnvironmentR90 = vec3(1.0, 1.0, 1.0) * reflectance90; vec3 n = getNormal(); vec3 v = normalize(u_Camera - pbr_vPosition); float NdotV = clamp(abs(dot(n, v)), 0.001, 1.0); vec3 reflection = -normalize(reflect(v, n)); PBRInfo pbrInputs = PBRInfo( 0.0, NdotV, 0.0, 0.0, 0.0, perceptualRoughness, metallic, specularEnvironmentR0, specularEnvironmentR90, alphaRoughness, diffuseColor, specularColor, n, v ); #ifdef USE_LIGHTS PBRInfo_setAmbientLight(pbrInputs); color += calculateFinalColor(pbrInputs, lighting_uAmbientLight.color); for(int i = 0; i < lighting_uDirectionalLightCount; i++) { if (i < lighting_uDirectionalLightCount) { PBRInfo_setDirectionalLight(pbrInputs, lighting_uDirectionalLight[i].direction); color += calculateFinalColor(pbrInputs, lighting_uDirectionalLight[i].color); } } for(int i = 0; i < lighting_uPointLightCount; i++) { if (i < lighting_uPointLightCount) { PBRInfo_setPointLight(pbrInputs, lighting_uPointLight[i]); float attenuation = getPointLightAttenuation(lighting_uPointLight[i], distance(lighting_uPointLight[i].position, pbr_vPosition)); color += calculateFinalColor(pbrInputs, lighting_uPointLight[i].color / attenuation); } } #endif #ifdef USE_IBL color += getIBLContribution(pbrInputs, n, reflection); #endif #ifdef HAS_OCCLUSIONMAP float ao = texture(u_OcclusionSampler, pbr_vUV).r; color = mix(color, color * ao, u_OcclusionStrength); #endif #ifdef HAS_EMISSIVEMAP vec3 emissive = SRGBtoLINEAR(texture(u_EmissiveSampler, pbr_vUV)).rgb * u_EmissiveFactor; color += emissive; #endif #ifdef PBR_DEBUG color = mix(color, baseColor.rgb, u_ScaleDiffBaseMR.y); color = mix(color, vec3(metallic), u_ScaleDiffBaseMR.z); color = mix(color, vec3(perceptualRoughness), u_ScaleDiffBaseMR.w); #endif } return vec4(pow(color,vec3(1.0/2.2)), baseColor.a); } `; // ../../node_modules/@luma.gl/shadertools/dist/modules-webgl1/lighting/pbr/pbr.js var pbr = { name: "pbr", vs, fs, defines: { LIGHTING_FRAGMENT: 1 }, dependencies: [lights] }; // src/mesh-layer/mesh-layer.ts var import_engine = __toESM(require_engine(), 1); var import_mesh_layers = __toESM(require_mesh_layers(), 1); // src/mesh-layer/mesh-layer-vertex.glsl.ts var mesh_layer_vertex_glsl_default = `#version 300 es #define SHADER_NAME simple-mesh-layer-vs // Scale the model uniform float sizeScale; uniform bool composeModelMatrix; uniform bool pickFeatureIds; // Primitive attributes in vec3 positions; in vec3 normals; in vec3 colors; in vec2 texCoords; in vec4 uvRegions; in vec3 featureIdsPickingColors; // Instance attributes in vec4 instanceColors; in vec3 instancePickingColors; in vec3 instanceModelMatrixCol0; in vec3 instanceModelMatrixCol1; in vec3 instanceModelMatrixCol2; // Outputs to fragment shader out vec2 vTexCoord; out vec3 cameraPosition; out vec3 normals_commonspace; out vec4 position_commonspace; out vec4 vColor; vec2 applyUVRegion(vec2 uv) { #ifdef HAS_UV_REGIONS // https://github.com/Esri/i3s-spec/blob/master/docs/1.7/geometryUVRegion.cmn.md return fract(uv) * (uvRegions.zw - uvRegions.xy) + uvRegions.xy; #else return uv; #endif } void main(void) { vec2 uv = applyUVRegion(texCoords); geometry.uv = uv; if (pickFeatureIds) { geometry.pickingColor = featureIdsPickingColors; } else { geometry.pickingColor = instancePickingColors; } mat3 instanceModelMatrix = mat3(instanceModelMatrixCol0, instanceModelMatrixCol1, instanceModelMatrixCol2); vTexCoord = uv; cameraPosition = project_uCameraPosition; vColor = vec4(colors * instanceColors.rgb, instanceColors.a); vec3 pos = (instanceModelMatrix * positions) * sizeScale; vec3 projectedPosition = project_position(positions); position_commonspace = vec4(projectedPosition, 1.0); gl_Position = project_common_position_to_clipspace(position_commonspace); geometry.position = position_commonspace; normals_commonspace = project_normal(instanceModelMatrix * normals); geometry.normal = normals_commonspace; DECKGL_FILTER_GL_POSITION(gl_Position, geometry); #ifdef MODULE_PBR // set PBR data pbr_vPosition = geometry.position.xyz; #ifdef HAS_NORMALS pbr_vNormal = geometry.normal; #endif #ifdef HAS_UV pbr_vUV = uv; #else pbr_vUV = vec2(0., 0.); #endif geometry.uv = pbr_vUV; #endif DECKGL_FILTER_COLOR(vColor, geometry); } `; // src/mesh-layer/mesh-layer-fragment.glsl.ts var mesh_layer_fragment_glsl_default = `#version 300 es #define SHADER_NAME simple-mesh-layer-fs precision highp float; uniform bool hasTexture; uniform sampler2D sampler; uniform bool flatShading; uniform float opacity; in vec2 vTexCoord; in vec3 cameraPosition; in vec3 normals_commonspace; in vec4 position_commonspace; in vec4 vColor; out vec4 fragColor; void main(void) { #ifdef MODULE_PBR fragColor = vColor * pbr_filterColor(vec4(0)); geometry.uv = pbr_vUV; fragColor.a *= opacity; #else geometry.uv = vTexCoord; vec3 normal; if (flatShading) { normal = normalize(cross(dFdx(position_commonspace.xyz), dFdy(position_commonspace.xyz))); } else { normal = normals_commonspace; } vec4 color = hasTexture ? texture(sampler, vTexCoord) : vColor; vec3 lightColor = lighting_getLightColor(color.rgb, cameraPosition, position_commonspace.xyz, normal); fragColor = vec4(lightColor, color.a * opacity); #endif DECKGL_FILTER_COLOR(fragColor, geometry); } `; // src/mesh-layer/mesh-layer.ts function validateGeometryAttributes(attributes) { const positionAttribute = attributes.positions || attributes.POSITION; const vertexCount = positionAttribute.value.length / positionAttribute.size; const hasColorAttribute = attributes.COLOR_0 || attributes.colors; if (!hasColorAttribute) { attributes.colors = { size: 4, value: new Uint8Array(vertexCount * 4).fill(255), normalized: true }; } } var defaultProps10 = { pbrMaterial: { type: "object", value: null }, featureIds: { type: "array", value: null, optional: true } }; var MeshLayer = class extends import_mesh_layers.SimpleMeshLayer { getShaders() { const shaders = super.getShaders(); const modules = shaders.modules; modules.push(pbr); return { ...shaders, vs: mesh_layer_vertex_glsl_default, fs: mesh_layer_fragment_glsl_default }; } initializeState() { const { featureIds } = this.props; super.initializeState(); const attributeManager = this.getAttributeManager(); if (featureIds) { attributeManager.add({ featureIdsPickingColors: { type: "uint8", size: 3, noAlloc: true, update: this.calculateFeatureIdsPickingColors } }); } } updateState(params) { super.updateState(params); const { props, oldProps } = params; if (props.pbrMaterial !== oldProps.pbrMaterial) { this.updatePbrMaterialUniforms(props.pbrMaterial); } } draw(opts) { const { featureIds } = this.props; if (!this.state.model) { return; } this.state.model.setUniforms({ u_Camera: this.state.model.uniforms.project_uCameraPosition, pickFeatureIds: Boolean(featureIds) }); super.draw(opts); } getModel(mesh) { const { id, pbrMaterial } = this.props; const parsedPBRMaterial = this.parseMaterial(pbrMaterial, mesh); this.setState({ parsedPBRMaterial }); const shaders = this.getShaders(); validateGeometryAttributes(mesh.attributes); const model = new import_engine.Model(this.context.device, { ...this.getShaders(), id, geometry: mesh, bufferLayout: this.getAttributeManager().getBufferLayouts(), defines: { ...shaders.defines, ...parsedPBRMaterial?.defines, HAS_UV_REGIONS: mesh.attributes.uvRegions ? 1 : 0 }, parameters: parsedPBRMaterial?.parameters, isInstanced: true }); return model; } updatePbrMaterialUniforms(pbrMaterial) { const { model } = this.state; if (model) { const { mesh } = this.props; const parsedPBRMaterial = this.parseMaterial(pbrMaterial, mesh); this.setState({ parsedPBRMaterial }); model.setBindings(parsedPBRMaterial.bindings); model.setUniforms(parsedPBRMaterial.uniforms); } } parseMaterial(pbrMaterial, mesh) { const unlit = Boolean( pbrMaterial.pbrMetallicRoughness && pbrMaterial.pbrMetallicRoughness.baseColorTexture ); return parsePBRMaterial( this.context.device, { unlit, ...pbrMaterial }, { NORMAL: mesh.attributes.normals, TEXCOORD_0: mesh.attributes.texCoords }, { pbrDebug: false, lights: true, useTangents: false } ); } calculateFeatureIdsPickingColors(attribute) { const featureIds = this.props.featureIds; const value = new Uint8ClampedArray(featureIds.length * attribute.size); const pickingColor = []; for (let index = 0; index < featureIds.length; index++) { this.encodePickingColor(featureIds[index], pickingColor); value[index * 3] = pickingColor[0]; value[index * 3 + 1] = pickingColor[1]; value[index * 3 + 2] = pickingColor[2]; } attribute.value = value; } finalizeState(context) { super.finalizeState(context); this.state.parsedPBRMaterial?.generatedTextures.forEach((texture) => texture.destroy()); this.setState({ parsedPBRMaterial: null }); } }; MeshLayer.layerName = "MeshLayer"; MeshLayer.defaultProps = defaultProps10; // src/tile-3d-layer/tile-3d-layer.ts var import_core44 = __toESM(require_core3(), 1); // ../../node_modules/@math.gl/geospatial/dist/constants.js var WGS84_RADIUS_X = 6378137; var WGS84_RADIUS_Y = 6378137; var WGS84_RADIUS_Z = 6356752314245179e-9; var WGS84_CONSTANTS = { radii: [WGS84_RADIUS_X, WGS84_RADIUS_Y, WGS84_RADIUS_Z], radiiSquared: [ WGS84_RADIUS_X * WGS84_RADIUS_X, WGS84_RADIUS_Y * WGS84_RADIUS_Y, WGS84_RADIUS_Z * WGS84_RADIUS_Z ], oneOverRadii: [1 / WGS84_RADIUS_X, 1 / WGS84_RADIUS_Y, 1 / WGS84_RADIUS_Z], oneOverRadiiSquared: [ 1 / (WGS84_RADIUS_X * WGS84_RADIUS_X), 1 / (WGS84_RADIUS_Y * WGS84_RADIUS_Y), 1 / (WGS84_RADIUS_Z * WGS84_RADIUS_Z) ], maximumRadius: Math.max(WGS84_RADIUS_X, WGS84_RADIUS_Y, WGS84_RADIUS_Z), centerToleranceSquared: 0.1 }; // ../../node_modules/@math.gl/geospatial/dist/type-utils.js function identity3(x2) { return x2; } var scratchVector7 = new Vector3(); function fromCartographic(cartographic, result = [], map2 = identity3) { if ("longitude" in cartographic) { result[0] = map2(cartographic.longitude); result[1] = map2(cartographic.latitude); result[2] = cartographic.height; } else if ("x" in cartographic) { result[0] = map2(cartographic.x); result[1] = map2(cartographic.y); result[2] = cartographic.z; } else { result[0] = map2(cartographic[0]); result[1] = map2(cartographic[1]); result[2] = cartographic[2]; } return result; } function fromCartographicToRadians(cartographic, vector = []) { return fromCartographic(cartographic, vector, config._cartographicRadians ? identity3 : toRadians); } function toCartographic(vector, cartographic, map2 = identity3) { if ("longitude" in cartographic) { cartographic.longitude = map2(vector[0]); cartographic.latitude = map2(vector[1]); cartographic.height = vector[2]; } else if ("x" in cartographic) { cartographic.x = map2(vector[0]); cartographic.y = map2(vector[1]); cartographic.z = vector[2]; } else { cartographic[0] = map2(vector[0]); cartographic[1] = map2(vector[1]); cartographic[2] = vector[2]; } return cartographic; } function toCartographicFromRadians(vector, cartographic) { return toCartographic(vector, cartographic, config._cartographicRadians ? identity3 : toDegrees); } // ../../node_modules/@math.gl/geospatial/dist/ellipsoid/helpers/ellipsoid-transform.js var EPSILON142 = 1e-14; var scratchOrigin = new Vector3(); var VECTOR_PRODUCT_LOCAL_FRAME = { up: { south: "east", north: "west", west: "south", east: "north" }, down: { south: "west", north: "east", west: "north", east: "south" }, south: { up: "west", down: "east", west: "down", east: "up" }, north: { up: "east", down: "west", west: "up", east: "down" }, west: { up: "north", down: "south", north: "down", south: "up" }, east: { up: "south", down: "north", north: "up", south: "down" } }; var degeneratePositionLocalFrame = { north: [-1, 0, 0], east: [0, 1, 0], up: [0, 0, 1], south: [1, 0, 0], west: [0, -1, 0], down: [0, 0, -1] }; var scratchAxisVectors = { east: new Vector3(), north: new Vector3(), up: new Vector3(), west: new Vector3(), south: new Vector3(), down: new Vector3() }; var scratchVector1 = new Vector3(); var scratchVector24 = new Vector3(); var scratchVector33 = new Vector3(); function localFrameToFixedFrame(ellipsoid, firstAxis, secondAxis, thirdAxis, cartesianOrigin, result) { const thirdAxisInferred = VECTOR_PRODUCT_LOCAL_FRAME[firstAxis] && VECTOR_PRODUCT_LOCAL_FRAME[firstAxis][secondAxis]; assert5(thirdAxisInferred && (!thirdAxis || thirdAxis === thirdAxisInferred)); let firstAxisVector; let secondAxisVector; let thirdAxisVector; const origin = scratchOrigin.copy(cartesianOrigin); const atPole = equals(origin.x, 0, EPSILON142) && equals(origin.y, 0, EPSILON142); if (atPole) { const sign2 = Math.sign(origin.z); firstAxisVector = scratchVector1.fromArray(degeneratePositionLocalFrame[firstAxis]); if (firstAxis !== "east" && firstAxis !== "west") { firstAxisVector.scale(sign2); } secondAxisVector = scratchVector24.fromArray(degeneratePositionLocalFrame[secondAxis]); if (secondAxis !== "east" && secondAxis !== "west") { secondAxisVector.scale(sign2); } thirdAxisVector = scratchVector33.fromArray(degeneratePositionLocalFrame[thirdAxis]); if (thirdAxis !== "east" && thirdAxis !== "west") { thirdAxisVector.scale(sign2); } } else { const { up, east, north } = scratchAxisVectors; east.set(-origin.y, origin.x, 0).normalize(); ellipsoid.geodeticSurfaceNormal(origin, up); north.copy(up).cross(east); const { down, west, south } = scratchAxisVectors; down.copy(up).scale(-1); west.copy(east).scale(-1); south.copy(north).scale(-1); firstAxisVector = scratchAxisVectors[firstAxis]; secondAxisVector = scratchAxisVectors[secondAxis]; thirdAxisVector = scratchAxisVectors[thirdAxis]; } result[0] = firstAxisVector.x; result[1] = firstAxisVector.y; result[2] = firstAxisVector.z; result[3] = 0; result[4] = secondAxisVector.x; result[5] = secondAxisVector.y; result[6] = secondAxisVector.z; result[7] = 0; result[8] = thirdAxisVector.x; result[9] = thirdAxisVector.y; result[10] = thirdAxisVector.z; result[11] = 0; result[12] = origin.x; result[13] = origin.y; result[14] = origin.z; result[15] = 1; return result; } // ../../node_modules/@math.gl/geospatial/dist/ellipsoid/helpers/scale-to-geodetic-surface.js var scratchVector8 = new Vector3(); var scaleToGeodeticSurfaceIntersection = new Vector3(); var scaleToGeodeticSurfaceGradient = new Vector3(); function scaleToGeodeticSurface(cartesian, ellipsoid, result = []) { const { oneOverRadii, oneOverRadiiSquared, centerToleranceSquared } = ellipsoid; scratchVector8.from(cartesian); const positionX = scratchVector8.x; const positionY = scratchVector8.y; const positionZ = scratchVector8.z; const oneOverRadiiX = oneOverRadii.x; const oneOverRadiiY = oneOverRadii.y; const oneOverRadiiZ = oneOverRadii.z; const x2 = positionX * positionX * oneOverRadiiX * oneOverRadiiX; const y2 = positionY * positionY * oneOverRadiiY * oneOverRadiiY; const z2 = positionZ * positionZ * oneOverRadiiZ * oneOverRadiiZ; const squaredNorm = x2 + y2 + z2; const ratio = Math.sqrt(1 / squaredNorm); if (!Number.isFinite(ratio)) { return void 0; } const intersection = scaleToGeodeticSurfaceIntersection; intersection.copy(cartesian).scale(ratio); if (squaredNorm < centerToleranceSquared) { return intersection.to(result); } const oneOverRadiiSquaredX = oneOverRadiiSquared.x; const oneOverRadiiSquaredY = oneOverRadiiSquared.y; const oneOverRadiiSquaredZ = oneOverRadiiSquared.z; const gradient = scaleToGeodeticSurfaceGradient; gradient.set(intersection.x * oneOverRadiiSquaredX * 2, intersection.y * oneOverRadiiSquaredY * 2, intersection.z * oneOverRadiiSquaredZ * 2); let lambda = (1 - ratio) * scratchVector8.len() / (0.5 * gradient.len()); let correction = 0; let xMultiplier; let yMultiplier; let zMultiplier; let func; do { lambda -= correction; xMultiplier = 1 / (1 + lambda * oneOverRadiiSquaredX); yMultiplier = 1 / (1 + lambda * oneOverRadiiSquaredY); zMultiplier = 1 / (1 + lambda * oneOverRadiiSquaredZ); const xMultiplier2 = xMultiplier * xMultiplier; const yMultiplier2 = yMultiplier * yMultiplier; const zMultiplier2 = zMultiplier * zMultiplier; const xMultiplier3 = xMultiplier2 * xMultiplier; const yMultiplier3 = yMultiplier2 * yMultiplier; const zMultiplier3 = zMultiplier2 * zMultiplier; func = x2 * xMultiplier2 + y2 * yMultiplier2 + z2 * zMultiplier2 - 1; const denominator = x2 * xMultiplier3 * oneOverRadiiSquaredX + y2 * yMultiplier3 * oneOverRadiiSquaredY + z2 * zMultiplier3 * oneOverRadiiSquaredZ; const derivative = -2 * denominator; correction = func / derivative; } while (Math.abs(func) > math_utils_exports.EPSILON12); return scratchVector8.scale([xMultiplier, yMultiplier, zMultiplier]).to(result); } // ../../node_modules/@math.gl/geospatial/dist/ellipsoid/ellipsoid.js var scratchVector9 = new Vector3(); var scratchNormal3 = new Vector3(); var scratchK = new Vector3(); var scratchPosition2 = new Vector3(); var scratchHeight = new Vector3(); var scratchCartesian = new Vector3(); var Ellipsoid = class { constructor(x2 = 0, y2 = 0, z = 0) { this.centerToleranceSquared = math_utils_exports.EPSILON1; assert5(x2 >= 0); assert5(y2 >= 0); assert5(z >= 0); this.radii = new Vector3(x2, y2, z); this.radiiSquared = new Vector3(x2 * x2, y2 * y2, z * z); this.radiiToTheFourth = new Vector3(x2 * x2 * x2 * x2, y2 * y2 * y2 * y2, z * z * z * z); this.oneOverRadii = new Vector3(x2 === 0 ? 0 : 1 / x2, y2 === 0 ? 0 : 1 / y2, z === 0 ? 0 : 1 / z); this.oneOverRadiiSquared = new Vector3(x2 === 0 ? 0 : 1 / (x2 * x2), y2 === 0 ? 0 : 1 / (y2 * y2), z === 0 ? 0 : 1 / (z * z)); this.minimumRadius = Math.min(x2, y2, z); this.maximumRadius = Math.max(x2, y2, z); if (this.radiiSquared.z !== 0) { this.squaredXOverSquaredZ = this.radiiSquared.x / this.radiiSquared.z; } Object.freeze(this); } equals(right) { return this === right || Boolean(right && this.radii.equals(right.radii)); } toString() { return this.radii.toString(); } cartographicToCartesian(cartographic, result = [0, 0, 0]) { const normal = scratchNormal3; const k = scratchK; const [, , height] = cartographic; this.geodeticSurfaceNormalCartographic(cartographic, normal); k.copy(this.radiiSquared).scale(normal); const gamma = Math.sqrt(normal.dot(k)); k.scale(1 / gamma); normal.scale(height); k.add(normal); return k.to(result); } cartesianToCartographic(cartesian, result = [0, 0, 0]) { scratchCartesian.from(cartesian); const point = this.scaleToGeodeticSurface(scratchCartesian, scratchPosition2); if (!point) { return void 0; } const normal = this.geodeticSurfaceNormal(point, scratchNormal3); const h = scratchHeight; h.copy(scratchCartesian).subtract(point); const longitude = Math.atan2(normal.y, normal.x); const latitude = Math.asin(normal.z); const height = Math.sign(vec3_exports.dot(h, scratchCartesian)) * vec3_exports.length(h); return toCartographicFromRadians([longitude, latitude, height], result); } eastNorthUpToFixedFrame(origin, result = new Matrix4()) { return localFrameToFixedFrame(this, "east", "north", "up", origin, result); } localFrameToFixedFrame(firstAxis, secondAxis, thirdAxis, origin, result = new Matrix4()) { return localFrameToFixedFrame(this, firstAxis, secondAxis, thirdAxis, origin, result); } geocentricSurfaceNormal(cartesian, result = [0, 0, 0]) { return scratchVector9.from(cartesian).normalize().to(result); } geodeticSurfaceNormalCartographic(cartographic, result = [0, 0, 0]) { const cartographicVectorRadians = fromCartographicToRadians(cartographic); const longitude = cartographicVectorRadians[0]; const latitude = cartographicVectorRadians[1]; const cosLatitude = Math.cos(latitude); scratchVector9.set(cosLatitude * Math.cos(longitude), cosLatitude * Math.sin(longitude), Math.sin(latitude)).normalize(); return scratchVector9.to(result); } geodeticSurfaceNormal(cartesian, result = [0, 0, 0]) { return scratchVector9.from(cartesian).scale(this.oneOverRadiiSquared).normalize().to(result); } scaleToGeodeticSurface(cartesian, result) { return scaleToGeodeticSurface(cartesian, this, result); } scaleToGeocentricSurface(cartesian, result = [0, 0, 0]) { scratchPosition2.from(cartesian); const positionX = scratchPosition2.x; const positionY = scratchPosition2.y; const positionZ = scratchPosition2.z; const oneOverRadiiSquared = this.oneOverRadiiSquared; const beta = 1 / Math.sqrt(positionX * positionX * oneOverRadiiSquared.x + positionY * positionY * oneOverRadiiSquared.y + positionZ * positionZ * oneOverRadiiSquared.z); return scratchPosition2.multiplyScalar(beta).to(result); } transformPositionToScaledSpace(position, result = [0, 0, 0]) { return scratchPosition2.from(position).scale(this.oneOverRadii).to(result); } transformPositionFromScaledSpace(position, result = [0, 0, 0]) { return scratchPosition2.from(position).scale(this.radii).to(result); } getSurfaceNormalIntersectionWithZAxis(position, buffer = 0, result = [0, 0, 0]) { assert5(equals(this.radii.x, this.radii.y, math_utils_exports.EPSILON15)); assert5(this.radii.z > 0); scratchPosition2.from(position); const z = scratchPosition2.z * (1 - this.squaredXOverSquaredZ); if (Math.abs(z) >= this.radii.z - buffer) { return void 0; } return scratchPosition2.set(0, 0, z).to(result); } }; Ellipsoid.WGS84 = new Ellipsoid(WGS84_RADIUS_X, WGS84_RADIUS_Y, WGS84_RADIUS_Z); // ../../node_modules/@loaders.gl/tiles/dist/utils/doubly-linked-list-node.js var DoublyLinkedListNode = class { item; previous; next; constructor(item, previous, next) { this.item = item; this.previous = previous; this.next = next; } }; // ../../node_modules/@loaders.gl/tiles/dist/utils/doubly-linked-list.js var DoublyLinkedList = class { head = null; tail = null; _length = 0; get length() { return this._length; } add(item) { const node = new DoublyLinkedListNode(item, this.tail, null); if (this.tail) { this.tail.next = node; this.tail = node; } else { this.head = node; this.tail = node; } ++this._length; return node; } remove(node) { if (!node) { return; } if (node.previous && node.next) { node.previous.next = node.next; node.next.previous = node.previous; } else if (node.previous) { node.previous.next = null; this.tail = node.previous; } else if (node.next) { node.next.previous = null; this.head = node.next; } else { this.head = null; this.tail = null; } node.next = null; node.previous = null; --this._length; } splice(node, nextNode) { if (node === nextNode) { return; } this.remove(nextNode); this._insert(node, nextNode); } _insert(node, nextNode) { const oldNodeNext = node.next; node.next = nextNode; if (this.tail === node) { this.tail = nextNode; } else { oldNodeNext.previous = nextNode; } nextNode.next = oldNodeNext; nextNode.previous = node; ++this._length; } }; // ../../node_modules/@loaders.gl/tiles/dist/tileset/tileset-cache.js var TilesetCache = class { _list; _sentinel; _trimTiles; constructor() { this._list = new DoublyLinkedList(); this._sentinel = this._list.add("sentinel"); this._trimTiles = false; } reset() { this._list.splice(this._list.tail, this._sentinel); } touch(tile) { const node = tile._cacheNode; if (node) { this._list.splice(this._sentinel, node); } } add(tileset, tile, addCallback) { if (!tile._cacheNode) { tile._cacheNode = this._list.add(tile); if (addCallback) { addCallback(tileset, tile); } } } unloadTile(tileset, tile, unloadCallback) { const node = tile._cacheNode; if (!node) { return; } this._list.remove(node); tile._cacheNode = null; if (unloadCallback) { unloadCallback(tileset, tile); } } unloadTiles(tileset, unloadCallback) { const trimTiles = this._trimTiles; this._trimTiles = false; const list = this._list; const maximumMemoryUsageInBytes = tileset.maximumMemoryUsage * 1024 * 1024; const sentinel = this._sentinel; let node = list.head; while (node !== sentinel && (tileset.gpuMemoryUsageInBytes > maximumMemoryUsageInBytes || trimTiles)) { const tile = node.item; node = node.next; this.unloadTile(tileset, tile, unloadCallback); } } trim() { this._trimTiles = true; } }; // ../../node_modules/@loaders.gl/tiles/dist/tileset/helpers/transform-utils.js function calculateTransformProps(tileHeader, tile) { assert2(tileHeader); assert2(tile); const { rtcCenter, gltfUpAxis } = tile; const { computedTransform, boundingVolume: { center } } = tileHeader; let modelMatrix = new Matrix4(computedTransform); if (rtcCenter) { modelMatrix.translate(rtcCenter); } switch (gltfUpAxis) { case "Z": break; case "Y": const rotationY = new Matrix4().rotateX(Math.PI / 2); modelMatrix = modelMatrix.multiplyRight(rotationY); break; case "X": const rotationX = new Matrix4().rotateY(-Math.PI / 2); modelMatrix = modelMatrix.multiplyRight(rotationX); break; default: break; } if (tile.isQuantized) { modelMatrix.translate(tile.quantizedVolumeOffset).scale(tile.quantizedVolumeScale); } const cartesianOrigin = new Vector3(center); tile.cartesianModelMatrix = modelMatrix; tile.cartesianOrigin = cartesianOrigin; const cartographicOrigin = Ellipsoid.WGS84.cartesianToCartographic(cartesianOrigin, new Vector3()); const fromFixedFrameMatrix = Ellipsoid.WGS84.eastNorthUpToFixedFrame(cartesianOrigin); const toFixedFrameMatrix = fromFixedFrameMatrix.invert(); tile.cartographicModelMatrix = toFixedFrameMatrix.multiplyRight(modelMatrix); tile.cartographicOrigin = cartographicOrigin; if (!tile.coordinateSystem) { tile.modelMatrix = tile.cartographicModelMatrix; } } // ../../node_modules/@loaders.gl/tiles/dist/tileset/helpers/frame-state.js var scratchVector10 = new Vector3(); var scratchPosition3 = new Vector3(); var cullingVolume = new CullingVolume([ new Plane(), new Plane(), new Plane(), new Plane(), new Plane(), new Plane() ]); function getFrameState(viewport, frameNumber) { const { cameraDirection, cameraUp, height } = viewport; const { metersPerUnit } = viewport.distanceScales; const viewportCenterCartesian = worldToCartesian(viewport, viewport.center); const enuToFixedTransform = Ellipsoid.WGS84.eastNorthUpToFixedFrame(viewportCenterCartesian); const cameraPositionCartographic = viewport.unprojectPosition(viewport.cameraPosition); const cameraPositionCartesian2 = Ellipsoid.WGS84.cartographicToCartesian(cameraPositionCartographic, new Vector3()); const cameraDirectionCartesian = new Vector3( enuToFixedTransform.transformAsVector(new Vector3(cameraDirection).scale(metersPerUnit)) ).normalize(); const cameraUpCartesian = new Vector3( enuToFixedTransform.transformAsVector(new Vector3(cameraUp).scale(metersPerUnit)) ).normalize(); commonSpacePlanesToWGS84(viewport); const ViewportClass = viewport.constructor; const { longitude, latitude, width, bearing, zoom } = viewport; const topDownViewport = new ViewportClass({ longitude, latitude, height, width, bearing, zoom, pitch: 0 }); return { camera: { position: cameraPositionCartesian2, direction: cameraDirectionCartesian, up: cameraUpCartesian }, viewport, topDownViewport, height, cullingVolume, frameNumber, sseDenominator: 1.15 }; } function limitSelectedTiles(tiles, frameState, maximumTilesSelected) { if (maximumTilesSelected === 0 || tiles.length <= maximumTilesSelected) { return [tiles, []]; } const tuples = []; const { longitude: viewportLongitude, latitude: viewportLatitude } = frameState.viewport; for (const [index, tile] of tiles.entries()) { const [longitude, latitude] = tile.header.mbs; const deltaLon = Math.abs(viewportLongitude - longitude); const deltaLat = Math.abs(viewportLatitude - latitude); const distance2 = Math.sqrt(deltaLat * deltaLat + deltaLon * deltaLon); tuples.push([index, distance2]); } const tuplesSorted = tuples.sort((a2, b) => a2[1] - b[1]); const selectedTiles = []; for (let i3 = 0; i3 < maximumTilesSelected; i3++) { selectedTiles.push(tiles[tuplesSorted[i3][0]]); } const unselectedTiles = []; for (let i3 = maximumTilesSelected; i3 < tuplesSorted.length; i3++) { unselectedTiles.push(tiles[tuplesSorted[i3][0]]); } return [selectedTiles, unselectedTiles]; } function commonSpacePlanesToWGS84(viewport) { const frustumPlanes = viewport.getFrustumPlanes(); const nearCenterCommon = closestPointOnPlane(frustumPlanes.near, viewport.cameraPosition); const nearCenterCartesian = worldToCartesian(viewport, nearCenterCommon); const cameraCartesian = worldToCartesian(viewport, viewport.cameraPosition, scratchPosition3); let i3 = 0; cullingVolume.planes[i3++].fromPointNormal(nearCenterCartesian, scratchVector10.copy(nearCenterCartesian).subtract(cameraCartesian)); for (const dir in frustumPlanes) { if (dir === "near") { continue; } const plane = frustumPlanes[dir]; const posCommon = closestPointOnPlane(plane, nearCenterCommon, scratchPosition3); const cartesianPos = worldToCartesian(viewport, posCommon, scratchPosition3); cullingVolume.planes[i3++].fromPointNormal( cartesianPos, scratchVector10.copy(nearCenterCartesian).subtract(cartesianPos) ); } } function closestPointOnPlane(plane, refPoint, out = new Vector3()) { const distanceToRef = plane.normal.dot(refPoint); out.copy(plane.normal).scale(plane.distance - distanceToRef).add(refPoint); return out; } function worldToCartesian(viewport, point, out = new Vector3()) { const cartographicPos = viewport.unprojectPosition(point); return Ellipsoid.WGS84.cartographicToCartesian(cartographicPos, out); } // ../../node_modules/@loaders.gl/tiles/dist/tileset/helpers/zoom.js var WGS84_RADIUS_X2 = 6378137; var WGS84_RADIUS_Y2 = 6378137; var WGS84_RADIUS_Z2 = 6356752314245179e-9; var scratchVector11 = new Vector3(); function getZoomFromBoundingVolume(boundingVolume, cartorgraphicCenter) { if (boundingVolume instanceof OrientedBoundingBox) { const { halfAxes } = boundingVolume; const obbSize = getObbSize(halfAxes); return Math.log2(WGS84_RADIUS_Z2 / (obbSize + cartorgraphicCenter[2])); } else if (boundingVolume instanceof BoundingSphere) { const { radius } = boundingVolume; return Math.log2(WGS84_RADIUS_Z2 / (radius + cartorgraphicCenter[2])); } else if (boundingVolume.width && boundingVolume.height) { const { width, height } = boundingVolume; const zoomX = Math.log2(WGS84_RADIUS_X2 / width); const zoomY = Math.log2(WGS84_RADIUS_Y2 / height); return (zoomX + zoomY) / 2; } return 1; } function getZoomFromFullExtent(fullExtent, cartorgraphicCenter, cartesianCenter) { Ellipsoid.WGS84.cartographicToCartesian([fullExtent.xmax, fullExtent.ymax, fullExtent.zmax], scratchVector11); const extentSize = Math.sqrt(Math.pow(scratchVector11[0] - cartesianCenter[0], 2) + Math.pow(scratchVector11[1] - cartesianCenter[1], 2) + Math.pow(scratchVector11[2] - cartesianCenter[2], 2)); return Math.log2(WGS84_RADIUS_Z2 / (extentSize + cartorgraphicCenter[2])); } function getZoomFromExtent(extent, cartorgraphicCenter, cartesianCenter) { const [xmin, ymin, xmax, ymax] = extent; return getZoomFromFullExtent({ xmin, xmax, ymin, ymax, zmin: 0, zmax: 0 }, cartorgraphicCenter, cartesianCenter); } function getObbSize(halfAxes) { halfAxes.getColumn(0, scratchVector11); const axeY = halfAxes.getColumn(1); const axeZ = halfAxes.getColumn(2); const farthestVertex = scratchVector11.add(axeY).add(axeZ); const size = farthestVertex.len(); return size; } // ../../node_modules/@loaders.gl/tiles/dist/tileset/tile-3d.js var import_core30 = __toESM(require_core3(), 1); // ../../node_modules/@loaders.gl/tiles/dist/constants.js var TILE_CONTENT_STATE = { UNLOADED: 0, LOADING: 1, PROCESSING: 2, READY: 3, EXPIRED: 4, FAILED: 5 }; var TILE_REFINEMENT; (function(TILE_REFINEMENT2) { TILE_REFINEMENT2[TILE_REFINEMENT2["ADD"] = 1] = "ADD"; TILE_REFINEMENT2[TILE_REFINEMENT2["REPLACE"] = 2] = "REPLACE"; })(TILE_REFINEMENT || (TILE_REFINEMENT = {})); var TILE_TYPE; (function(TILE_TYPE2) { TILE_TYPE2["EMPTY"] = "empty"; TILE_TYPE2["SCENEGRAPH"] = "scenegraph"; TILE_TYPE2["POINTCLOUD"] = "pointcloud"; TILE_TYPE2["MESH"] = "mesh"; })(TILE_TYPE || (TILE_TYPE = {})); var TILESET_TYPE; (function(TILESET_TYPE2) { TILESET_TYPE2["I3S"] = "I3S"; TILESET_TYPE2["TILES3D"] = "TILES3D"; })(TILESET_TYPE || (TILESET_TYPE = {})); var LOD_METRIC_TYPE; (function(LOD_METRIC_TYPE2) { LOD_METRIC_TYPE2["GEOMETRIC_ERROR"] = "geometricError"; LOD_METRIC_TYPE2["MAX_SCREEN_THRESHOLD"] = "maxScreenThreshold"; })(LOD_METRIC_TYPE || (LOD_METRIC_TYPE = {})); var TILE3D_OPTIMIZATION_HINT = { NOT_COMPUTED: -1, USE_OPTIMIZATION: 1, SKIP_OPTIMIZATION: 0 }; // ../../node_modules/@loaders.gl/tiles/dist/tileset/helpers/bounding-volume.js function defined(x2) { return x2 !== void 0 && x2 !== null; } var scratchPoint = new Vector3(); var scratchScale = new Vector3(); var scratchNorthWest = new Vector3(); var scratchSouthEast = new Vector3(); var scratchCenter = new Vector3(); var scratchXAxis = new Vector3(); var scratchYAxis = new Vector3(); var scratchZAxis = new Vector3(); function createBoundingVolume(boundingVolumeHeader, transform2, result) { assert2(boundingVolumeHeader, "3D Tile: boundingVolume must be defined"); if (boundingVolumeHeader.box) { return createBox(boundingVolumeHeader.box, transform2, result); } if (boundingVolumeHeader.region) { return createObbFromRegion(boundingVolumeHeader.region); } if (boundingVolumeHeader.sphere) { return createSphere(boundingVolumeHeader.sphere, transform2, result); } throw new Error("3D Tile: boundingVolume must contain a sphere, region, or box"); } function getCartographicBounds(boundingVolumeHeader, boundingVolume) { if (boundingVolumeHeader.box) { return orientedBoundingBoxToCartographicBounds(boundingVolume); } if (boundingVolumeHeader.region) { const [west, south, east, north, minHeight, maxHeight] = boundingVolumeHeader.region; return [ [degrees(west), degrees(south), minHeight], [degrees(east), degrees(north), maxHeight] ]; } if (boundingVolumeHeader.sphere) { return boundingSphereToCartographicBounds(boundingVolume); } throw new Error("Unkown boundingVolume type"); } function createBox(box, transform2, result) { const center = new Vector3(box[0], box[1], box[2]); transform2.transform(center, center); let origin = []; if (box.length === 10) { const halfSize = box.slice(3, 6); const quaternion = new Quaternion(); quaternion.fromArray(box, 6); const x2 = new Vector3([1, 0, 0]); const y2 = new Vector3([0, 1, 0]); const z = new Vector3([0, 0, 1]); x2.transformByQuaternion(quaternion); x2.scale(halfSize[0]); y2.transformByQuaternion(quaternion); y2.scale(halfSize[1]); z.transformByQuaternion(quaternion); z.scale(halfSize[2]); origin = [...x2.toArray(), ...y2.toArray(), ...z.toArray()]; } else { origin = [...box.slice(3, 6), ...box.slice(6, 9), ...box.slice(9, 12)]; } const xAxis = transform2.transformAsVector(origin.slice(0, 3)); const yAxis = transform2.transformAsVector(origin.slice(3, 6)); const zAxis = transform2.transformAsVector(origin.slice(6, 9)); const halfAxes = new Matrix3([ xAxis[0], xAxis[1], xAxis[2], yAxis[0], yAxis[1], yAxis[2], zAxis[0], zAxis[1], zAxis[2] ]); if (defined(result)) { result.center = center; result.halfAxes = halfAxes; return result; } return new OrientedBoundingBox(center, halfAxes); } function createSphere(sphere, transform2, result) { const center = new Vector3(sphere[0], sphere[1], sphere[2]); transform2.transform(center, center); const scale6 = transform2.getScale(scratchScale); const uniformScale = Math.max(Math.max(scale6[0], scale6[1]), scale6[2]); const radius = sphere[3] * uniformScale; if (defined(result)) { result.center = center; result.radius = radius; return result; } return new BoundingSphere(center, radius); } function createObbFromRegion(region) { const [west, south, east, north, minHeight, maxHeight] = region; const northWest = Ellipsoid.WGS84.cartographicToCartesian([degrees(west), degrees(north), minHeight], scratchNorthWest); const southEast = Ellipsoid.WGS84.cartographicToCartesian([degrees(east), degrees(south), maxHeight], scratchSouthEast); const centerInCartesian = new Vector3().addVectors(northWest, southEast).multiplyByScalar(0.5); Ellipsoid.WGS84.cartesianToCartographic(centerInCartesian, scratchCenter); Ellipsoid.WGS84.cartographicToCartesian([degrees(east), scratchCenter[1], scratchCenter[2]], scratchXAxis); Ellipsoid.WGS84.cartographicToCartesian([scratchCenter[0], degrees(north), scratchCenter[2]], scratchYAxis); Ellipsoid.WGS84.cartographicToCartesian([scratchCenter[0], scratchCenter[1], maxHeight], scratchZAxis); return createBox([ ...centerInCartesian, ...scratchXAxis.subtract(centerInCartesian), ...scratchYAxis.subtract(centerInCartesian), ...scratchZAxis.subtract(centerInCartesian) ], new Matrix4()); } function orientedBoundingBoxToCartographicBounds(boundingVolume) { const result = emptyCartographicBounds(); const { halfAxes } = boundingVolume; const xAxis = new Vector3(halfAxes.getColumn(0)); const yAxis = new Vector3(halfAxes.getColumn(1)); const zAxis = new Vector3(halfAxes.getColumn(2)); for (let x2 = 0; x2 < 2; x2++) { for (let y2 = 0; y2 < 2; y2++) { for (let z = 0; z < 2; z++) { scratchPoint.copy(boundingVolume.center); scratchPoint.add(xAxis); scratchPoint.add(yAxis); scratchPoint.add(zAxis); addToCartographicBounds(result, scratchPoint); zAxis.negate(); } yAxis.negate(); } xAxis.negate(); } return result; } function boundingSphereToCartographicBounds(boundingVolume) { const result = emptyCartographicBounds(); const { center, radius } = boundingVolume; const point = Ellipsoid.WGS84.scaleToGeodeticSurface(center, scratchPoint); let zAxis; if (point) { zAxis = Ellipsoid.WGS84.geodeticSurfaceNormal(point); } else { zAxis = new Vector3(0, 0, 1); } let xAxis = new Vector3(zAxis[2], -zAxis[1], 0); if (xAxis.len() > 0) { xAxis.normalize(); } else { xAxis = new Vector3(0, 1, 0); } const yAxis = xAxis.clone().cross(zAxis); for (const axis of [xAxis, yAxis, zAxis]) { scratchScale.copy(axis).scale(radius); for (let dir = 0; dir < 2; dir++) { scratchPoint.copy(center); scratchPoint.add(scratchScale); addToCartographicBounds(result, scratchPoint); scratchScale.negate(); } } return result; } function emptyCartographicBounds() { return [ [Infinity, Infinity, Infinity], [-Infinity, -Infinity, -Infinity] ]; } function addToCartographicBounds(target, cartesian) { Ellipsoid.WGS84.cartesianToCartographic(cartesian, scratchPoint); target[0][0] = Math.min(target[0][0], scratchPoint[0]); target[0][1] = Math.min(target[0][1], scratchPoint[1]); target[0][2] = Math.min(target[0][2], scratchPoint[2]); target[1][0] = Math.max(target[1][0], scratchPoint[0]); target[1][1] = Math.max(target[1][1], scratchPoint[1]); target[1][2] = Math.max(target[1][2], scratchPoint[2]); } // ../../node_modules/@loaders.gl/tiles/dist/tileset/helpers/tiles-3d-lod.js var scratchPositionNormal = new Vector3(); var scratchCartographic = new Vector3(); var scratchMatrix2 = new Matrix4(); var scratchCenter2 = new Vector3(); var scratchPosition4 = new Vector3(); var scratchDirection = new Vector3(); function fog(distanceToCamera, density) { const scalar = distanceToCamera * density; return 1 - Math.exp(-(scalar * scalar)); } function getDynamicScreenSpaceError(tileset, distanceToCamera) { if (tileset.dynamicScreenSpaceError && tileset.dynamicScreenSpaceErrorComputedDensity) { const density = tileset.dynamicScreenSpaceErrorComputedDensity; const factor = tileset.dynamicScreenSpaceErrorFactor; const dynamicError = fog(distanceToCamera, density) * factor; return dynamicError; } return 0; } function getTiles3DScreenSpaceError(tile, frameState, useParentLodMetric) { const tileset = tile.tileset; const parentLodMetricValue = tile.parent && tile.parent.lodMetricValue || tile.lodMetricValue; const lodMetricValue = useParentLodMetric ? parentLodMetricValue : tile.lodMetricValue; if (lodMetricValue === 0) { return 0; } const distance2 = Math.max(tile._distanceToCamera, 1e-7); const { height, sseDenominator } = frameState; const { viewDistanceScale } = tileset.options; let error = lodMetricValue * height * (viewDistanceScale || 1) / (distance2 * sseDenominator); error -= getDynamicScreenSpaceError(tileset, distance2); return error; } // ../../node_modules/@loaders.gl/tiles/dist/tileset/helpers/i3s-lod.js var cameraPositionCartesian = new Vector3(); var toEye = new Vector3(); var cameraPositionEnu = new Vector3(); var extraVertexEnu = new Vector3(); var projectedOriginVector = new Vector3(); var enuToCartesianMatrix = new Matrix4(); var cartesianToEnuMatrix = new Matrix4(); function getLodStatus(tile, frameState) { if (tile.lodMetricValue === 0 || isNaN(tile.lodMetricValue)) { return "DIG"; } const screenSize = 2 * getProjectedRadius(tile, frameState); if (screenSize < 2) { return "OUT"; } if (!tile.header.children || screenSize <= tile.lodMetricValue) { return "DRAW"; } else if (tile.header.children) { return "DIG"; } return "OUT"; } function getProjectedRadius(tile, frameState) { const { topDownViewport: viewport } = frameState; const mbsLat = tile.header.mbs[1]; const mbsLon = tile.header.mbs[0]; const mbsZ = tile.header.mbs[2]; const mbsR = tile.header.mbs[3]; const mbsCenterCartesian = [...tile.boundingVolume.center]; const cameraPositionCartographic = viewport.unprojectPosition(viewport.cameraPosition); Ellipsoid.WGS84.cartographicToCartesian(cameraPositionCartographic, cameraPositionCartesian); toEye.copy(cameraPositionCartesian).subtract(mbsCenterCartesian).normalize(); Ellipsoid.WGS84.eastNorthUpToFixedFrame(mbsCenterCartesian, enuToCartesianMatrix); cartesianToEnuMatrix.copy(enuToCartesianMatrix).invert(); cameraPositionEnu.copy(cameraPositionCartesian).transform(cartesianToEnuMatrix); const projection = Math.sqrt(cameraPositionEnu[0] * cameraPositionEnu[0] + cameraPositionEnu[1] * cameraPositionEnu[1]); const extraZ = projection * projection / cameraPositionEnu[2]; extraVertexEnu.copy([cameraPositionEnu[0], cameraPositionEnu[1], extraZ]); const extraVertexCartesian = extraVertexEnu.transform(enuToCartesianMatrix); const extraVectorCartesian = extraVertexCartesian.subtract(mbsCenterCartesian).normalize(); const radiusVector = toEye.cross(extraVectorCartesian).normalize().scale(mbsR); const sphereMbsBorderVertexCartesian = radiusVector.add(mbsCenterCartesian); const sphereMbsBorderVertexCartographic = Ellipsoid.WGS84.cartesianToCartographic(sphereMbsBorderVertexCartesian); const projectedOrigin = viewport.project([mbsLon, mbsLat, mbsZ]); const projectedMbsBorderVertex = viewport.project(sphereMbsBorderVertexCartographic); const projectedRadius = projectedOriginVector.copy(projectedOrigin).subtract(projectedMbsBorderVertex).magnitude(); return projectedRadius; } // ../../node_modules/@loaders.gl/tiles/dist/tileset/helpers/3d-tiles-options.js function get3dTilesOptions(tileset) { return { assetGltfUpAxis: tileset.asset && tileset.asset.gltfUpAxis || "Y" }; } // ../../node_modules/@loaders.gl/tiles/dist/utils/managed-array.js var ManagedArray = class { _map = /* @__PURE__ */ new Map(); _array; _length; constructor(length5 = 0) { this._array = new Array(length5); this._length = length5; } get length() { return this._length; } set length(length5) { this._length = length5; if (length5 > this._array.length) { this._array.length = length5; } } get values() { return this._array; } get(index) { assert2(index < this._array.length); return this._array[index]; } set(index, element) { assert2(index >= 0); if (index >= this.length) { this.length = index + 1; } if (this._map.has(this._array[index])) { this._map.delete(this._array[index]); } this._array[index] = element; this._map.set(element, index); } delete(element) { const index = this._map.get(element); if (index >= 0) { this._array.splice(index, 1); this._map.delete(element); this.length--; } } peek() { return this._array[this._length - 1]; } push(element) { if (!this._map.has(element)) { const index = this.length++; this._array[index] = element; this._map.set(element, index); } } pop() { const element = this._array[--this.length]; this._map.delete(element); return element; } reserve(length5) { assert2(length5 >= 0); if (length5 > this._array.length) { this._array.length = length5; } } resize(length5) { assert2(length5 >= 0); this.length = length5; } trim(length5) { if (length5 === null || length5 === void 0) { length5 = this.length; } this._array.length = length5; } reset() { this._array = []; this._map = /* @__PURE__ */ new Map(); this._length = 0; } find(target) { return this._map.has(target); } }; // ../../node_modules/@loaders.gl/tiles/dist/tileset/tileset-traverser.js var DEFAULT_PROPS2 = { loadSiblings: false, skipLevelOfDetail: false, updateTransforms: true, onTraversalEnd: () => { }, viewportTraversersMap: {}, basePath: "" }; var TilesetTraverser = class { options; root = null; selectedTiles = {}; requestedTiles = {}; emptyTiles = {}; lastUpdate = new Date().getTime(); updateDebounceTime = 1e3; _traversalStack = new ManagedArray(); _emptyTraversalStack = new ManagedArray(); _frameNumber = null; traversalFinished(frameState) { return true; } constructor(options) { this.options = { ...DEFAULT_PROPS2, ...options }; } traverse(root, frameState, options) { this.root = root; this.options = { ...this.options, ...options }; this.reset(); this.updateTile(root, frameState); this._frameNumber = frameState.frameNumber; this.executeTraversal(root, frameState); } reset() { this.requestedTiles = {}; this.selectedTiles = {}; this.emptyTiles = {}; this._traversalStack.reset(); this._emptyTraversalStack.reset(); } executeTraversal(root, frameState) { const stack2 = this._traversalStack; root._selectionDepth = 1; stack2.push(root); while (stack2.length > 0) { const tile = stack2.pop(); let shouldRefine = false; if (this.canTraverse(tile, frameState)) { this.updateChildTiles(tile, frameState); shouldRefine = this.updateAndPushChildren(tile, frameState, stack2, tile.hasRenderContent ? tile._selectionDepth + 1 : tile._selectionDepth); } const parent = tile.parent; const parentRefines = Boolean(!parent || parent._shouldRefine); const stoppedRefining = !shouldRefine; if (!tile.hasRenderContent) { this.emptyTiles[tile.id] = tile; this.loadTile(tile, frameState); if (stoppedRefining) { this.selectTile(tile, frameState); } } else if (tile.refine === TILE_REFINEMENT.ADD) { this.loadTile(tile, frameState); this.selectTile(tile, frameState); } else if (tile.refine === TILE_REFINEMENT.REPLACE) { this.loadTile(tile, frameState); if (stoppedRefining) { this.selectTile(tile, frameState); } } this.touchTile(tile, frameState); tile._shouldRefine = shouldRefine && parentRefines; } const newTime = new Date().getTime(); if (this.traversalFinished(frameState) || newTime - this.lastUpdate > this.updateDebounceTime) { this.lastUpdate = newTime; this.options.onTraversalEnd(frameState); } } updateChildTiles(tile, frameState) { const children = tile.children; for (const child of children) { this.updateTile(child, frameState); } } updateAndPushChildren(tile, frameState, stack2, depth) { const { loadSiblings, skipLevelOfDetail } = this.options; const children = tile.children; children.sort(this.compareDistanceToCamera.bind(this)); const checkRefines = tile.refine === TILE_REFINEMENT.REPLACE && tile.hasRenderContent && !skipLevelOfDetail; let hasVisibleChild = false; let refines = true; for (const child of children) { child._selectionDepth = depth; if (child.isVisibleAndInRequestVolume) { if (stack2.find(child)) { stack2.delete(child); } stack2.push(child); hasVisibleChild = true; } else if (checkRefines || loadSiblings) { this.loadTile(child, frameState); this.touchTile(child, frameState); } if (checkRefines) { let childRefines; if (!child._inRequestVolume) { childRefines = false; } else if (!child.hasRenderContent) { childRefines = this.executeEmptyTraversal(child, frameState); } else { childRefines = child.contentAvailable; } refines = refines && childRefines; if (!refines) { return false; } } } if (!hasVisibleChild) { refines = false; } return refines; } updateTile(tile, frameState) { this.updateTileVisibility(tile, frameState); } selectTile(tile, frameState) { if (this.shouldSelectTile(tile)) { tile._selectedFrame = frameState.frameNumber; this.selectedTiles[tile.id] = tile; } } loadTile(tile, frameState) { if (this.shouldLoadTile(tile)) { tile._requestedFrame = frameState.frameNumber; tile._priority = tile._getPriority(); this.requestedTiles[tile.id] = tile; } } touchTile(tile, frameState) { tile.tileset._cache.touch(tile); tile._touchedFrame = frameState.frameNumber; } canTraverse(tile, frameState, useParentMetric = false, ignoreVisibility = false) { if (!tile.hasChildren) { return false; } if (tile.hasTilesetContent) { return !tile.contentExpired; } if (!ignoreVisibility && !tile.isVisibleAndInRequestVolume) { return false; } return this.shouldRefine(tile, frameState, useParentMetric); } shouldLoadTile(tile) { return tile.hasUnloadedContent || tile.contentExpired; } shouldSelectTile(tile) { return tile.contentAvailable && !this.options.skipLevelOfDetail; } shouldRefine(tile, frameState, useParentMetric = false) { let screenSpaceError = tile._screenSpaceError; if (useParentMetric) { screenSpaceError = tile.getScreenSpaceError(frameState, true); } return screenSpaceError > tile.tileset.memoryAdjustedScreenSpaceError; } updateTileVisibility(tile, frameState) { const viewportIds = []; if (this.options.viewportTraversersMap) { for (const key in this.options.viewportTraversersMap) { const value = this.options.viewportTraversersMap[key]; if (value === frameState.viewport.id) { viewportIds.push(key); } } } else { viewportIds.push(frameState.viewport.id); } tile.updateVisibility(frameState, viewportIds); } compareDistanceToCamera(b, a2) { return b._distanceToCamera - a2._distanceToCamera; } anyChildrenVisible(tile, frameState) { let anyVisible = false; for (const child of tile.children) { child.updateVisibility(frameState); anyVisible = anyVisible || child.isVisibleAndInRequestVolume; } return anyVisible; } executeEmptyTraversal(root, frameState) { let allDescendantsLoaded = true; const stack2 = this._emptyTraversalStack; stack2.push(root); while (stack2.length > 0) { const tile = stack2.pop(); const traverse = !tile.hasRenderContent && this.canTraverse(tile, frameState, false, false); const emptyLeaf = !tile.hasRenderContent && tile.children.length === 0; if (!traverse && !tile.contentAvailable && !emptyLeaf) { allDescendantsLoaded = false; } this.updateTile(tile, frameState); if (!tile.isVisibleAndInRequestVolume) { this.loadTile(tile, frameState); this.touchTile(tile, frameState); } if (traverse) { const children = tile.children; for (const child of children) { stack2.push(child); } } } return allDescendantsLoaded; } }; // ../../node_modules/@loaders.gl/tiles/dist/tileset/tile-3d.js var scratchVector12 = new Vector3(); function defined2(x2) { return x2 !== void 0 && x2 !== null; } var Tile3D = class { tileset; header; id; url; parent; refine; type; contentUrl; lodMetricType = "geometricError"; lodMetricValue = 0; boundingVolume = null; content = null; contentState = TILE_CONTENT_STATE.UNLOADED; gpuMemoryUsageInBytes = 0; children = []; depth = 0; viewportIds = []; transform = new Matrix4(); extensions = null; implicitTiling = null; userData = {}; computedTransform; hasEmptyContent = false; hasTilesetContent = false; traverser = new TilesetTraverser({}); _cacheNode = null; _frameNumber = null; _expireDate = null; _expiredContent = null; _boundingBox = void 0; _distanceToCamera = 0; _screenSpaceError = 0; _visibilityPlaneMask; _visible = void 0; _contentBoundingVolume; _viewerRequestVolume; _initialTransform = new Matrix4(); _priority = 0; _selectedFrame = 0; _requestedFrame = 0; _selectionDepth = 0; _touchedFrame = 0; _centerZDepth = 0; _shouldRefine = false; _stackLength = 0; _visitedFrame = 0; _inRequestVolume = false; _lodJudge = null; constructor(tileset, header, parentHeader, extendedId = "") { this.header = header; this.tileset = tileset; this.id = extendedId || header.id; this.url = header.url; this.parent = parentHeader; this.refine = this._getRefine(header.refine); this.type = header.type; this.contentUrl = header.contentUrl; this._initializeLodMetric(header); this._initializeTransforms(header); this._initializeBoundingVolumes(header); this._initializeContent(header); this._initializeRenderingState(header); Object.seal(this); } destroy() { this.header = null; } isDestroyed() { return this.header === null; } get selected() { return this._selectedFrame === this.tileset._frameNumber; } get isVisible() { return this._visible; } get isVisibleAndInRequestVolume() { return this._visible && this._inRequestVolume; } get hasRenderContent() { return !this.hasEmptyContent && !this.hasTilesetContent; } get hasChildren() { return this.children.length > 0 || this.header.children && this.header.children.length > 0; } get contentReady() { return this.contentState === TILE_CONTENT_STATE.READY || this.hasEmptyContent; } get contentAvailable() { return Boolean(this.contentReady && this.hasRenderContent || this._expiredContent && !this.contentFailed); } get hasUnloadedContent() { return this.hasRenderContent && this.contentUnloaded; } get contentUnloaded() { return this.contentState === TILE_CONTENT_STATE.UNLOADED; } get contentExpired() { return this.contentState === TILE_CONTENT_STATE.EXPIRED; } get contentFailed() { return this.contentState === TILE_CONTENT_STATE.FAILED; } get distanceToCamera() { return this._distanceToCamera; } get screenSpaceError() { return this._screenSpaceError; } get boundingBox() { if (!this._boundingBox) { this._boundingBox = getCartographicBounds(this.header.boundingVolume, this.boundingVolume); } return this._boundingBox; } getScreenSpaceError(frameState, useParentLodMetric) { switch (this.tileset.type) { case TILESET_TYPE.I3S: return getProjectedRadius(this, frameState); case TILESET_TYPE.TILES3D: return getTiles3DScreenSpaceError(this, frameState, useParentLodMetric); default: throw new Error("Unsupported tileset type"); } } unselect() { this._selectedFrame = 0; } _getGpuMemoryUsageInBytes() { return this.content.gpuMemoryUsageInBytes || this.content.byteLength || 0; } _getPriority() { const traverser = this.tileset._traverser; const { skipLevelOfDetail } = traverser.options; const maySkipTile = this.refine === TILE_REFINEMENT.ADD || skipLevelOfDetail; if (maySkipTile && !this.isVisible && this._visible !== void 0) { return -1; } if (this.tileset._frameNumber - this._touchedFrame >= 1) { return -1; } if (this.contentState === TILE_CONTENT_STATE.UNLOADED) { return -1; } const parent = this.parent; const useParentScreenSpaceError = parent && (!maySkipTile || this._screenSpaceError === 0 || parent.hasTilesetContent); const screenSpaceError = useParentScreenSpaceError ? parent._screenSpaceError : this._screenSpaceError; const rootScreenSpaceError = traverser.root ? traverser.root._screenSpaceError : 0; return Math.max(rootScreenSpaceError - screenSpaceError, 0); } async loadContent() { if (this.hasEmptyContent) { return false; } if (this.content) { return true; } const expired = this.contentExpired; if (expired) { this._expireDate = null; } this.contentState = TILE_CONTENT_STATE.LOADING; const requestToken = await this.tileset._requestScheduler.scheduleRequest(this.id, this._getPriority.bind(this)); if (!requestToken) { this.contentState = TILE_CONTENT_STATE.UNLOADED; return false; } try { const contentUrl = this.tileset.getTileUrl(this.contentUrl); const loader = this.tileset.loader; const options = { ...this.tileset.loadOptions, [loader.id]: { ...this.tileset.loadOptions[loader.id], isTileset: this.type === "json", ...this._getLoaderSpecificOptions(loader.id) } }; this.content = await (0, import_core30.load)(contentUrl, loader, options); if (this.tileset.options.contentLoader) { await this.tileset.options.contentLoader(this); } if (this._isTileset()) { this.tileset._initializeTileHeaders(this.content, this); } this.contentState = TILE_CONTENT_STATE.READY; this._onContentLoaded(); return true; } catch (error) { this.contentState = TILE_CONTENT_STATE.FAILED; throw error; } finally { requestToken.done(); } } unloadContent() { if (this.content && this.content.destroy) { this.content.destroy(); } this.content = null; if (this.header.content && this.header.content.destroy) { this.header.content.destroy(); } this.header.content = null; this.contentState = TILE_CONTENT_STATE.UNLOADED; return true; } updateVisibility(frameState, viewportIds) { if (this._frameNumber === frameState.frameNumber) { return; } const parent = this.parent; const parentVisibilityPlaneMask = parent ? parent._visibilityPlaneMask : CullingVolume.MASK_INDETERMINATE; if (this.tileset._traverser.options.updateTransforms) { const parentTransform = parent ? parent.computedTransform : this.tileset.modelMatrix; this._updateTransform(parentTransform); } this._distanceToCamera = this.distanceToTile(frameState); this._screenSpaceError = this.getScreenSpaceError(frameState, false); this._visibilityPlaneMask = this.visibility(frameState, parentVisibilityPlaneMask); this._visible = this._visibilityPlaneMask !== CullingVolume.MASK_OUTSIDE; this._inRequestVolume = this.insideViewerRequestVolume(frameState); this._frameNumber = frameState.frameNumber; this.viewportIds = viewportIds; } visibility(frameState, parentVisibilityPlaneMask) { const { cullingVolume: cullingVolume2 } = frameState; const { boundingVolume } = this; return cullingVolume2.computeVisibilityWithPlaneMask(boundingVolume, parentVisibilityPlaneMask); } contentVisibility() { return true; } distanceToTile(frameState) { const boundingVolume = this.boundingVolume; return Math.sqrt(Math.max(boundingVolume.distanceSquaredTo(frameState.camera.position), 0)); } cameraSpaceZDepth({ camera }) { const boundingVolume = this.boundingVolume; scratchVector12.subVectors(boundingVolume.center, camera.position); return camera.direction.dot(scratchVector12); } insideViewerRequestVolume(frameState) { const viewerRequestVolume = this._viewerRequestVolume; return !viewerRequestVolume || viewerRequestVolume.distanceSquaredTo(frameState.camera.position) <= 0; } updateExpiration() { if (defined2(this._expireDate) && this.contentReady && !this.hasEmptyContent) { const now = Date.now(); if (Date.lessThan(this._expireDate, now)) { this.contentState = TILE_CONTENT_STATE.EXPIRED; this._expiredContent = this.content; } } } get extras() { return this.header.extras; } _initializeLodMetric(header) { if ("lodMetricType" in header) { this.lodMetricType = header.lodMetricType; } else { this.lodMetricType = this.parent && this.parent.lodMetricType || this.tileset.lodMetricType; console.warn(`3D Tile: Required prop lodMetricType is undefined. Using parent lodMetricType`); } if ("lodMetricValue" in header) { this.lodMetricValue = header.lodMetricValue; } else { this.lodMetricValue = this.parent && this.parent.lodMetricValue || this.tileset.lodMetricValue; console.warn("3D Tile: Required prop lodMetricValue is undefined. Using parent lodMetricValue"); } } _initializeTransforms(tileHeader) { this.transform = tileHeader.transform ? new Matrix4(tileHeader.transform) : new Matrix4(); const parent = this.parent; const tileset = this.tileset; const parentTransform = parent && parent.computedTransform ? parent.computedTransform.clone() : tileset.modelMatrix.clone(); this.computedTransform = new Matrix4(parentTransform).multiplyRight(this.transform); const parentInitialTransform = parent && parent._initialTransform ? parent._initialTransform.clone() : new Matrix4(); this._initialTransform = new Matrix4(parentInitialTransform).multiplyRight(this.transform); } _initializeBoundingVolumes(tileHeader) { this._contentBoundingVolume = null; this._viewerRequestVolume = null; this._updateBoundingVolume(tileHeader); } _initializeContent(tileHeader) { this.content = { _tileset: this.tileset, _tile: this }; this.hasEmptyContent = true; this.contentState = TILE_CONTENT_STATE.UNLOADED; this.hasTilesetContent = false; if (tileHeader.contentUrl) { this.content = null; this.hasEmptyContent = false; } } _initializeRenderingState(header) { this.depth = header.level || (this.parent ? this.parent.depth + 1 : 0); this._shouldRefine = false; this._distanceToCamera = 0; this._centerZDepth = 0; this._screenSpaceError = 0; this._visibilityPlaneMask = CullingVolume.MASK_INDETERMINATE; this._visible = void 0; this._inRequestVolume = false; this._stackLength = 0; this._selectionDepth = 0; this._frameNumber = 0; this._touchedFrame = 0; this._visitedFrame = 0; this._selectedFrame = 0; this._requestedFrame = 0; this._priority = 0; } _getRefine(refine) { return refine || this.parent && this.parent.refine || TILE_REFINEMENT.REPLACE; } _isTileset() { return this.contentUrl.indexOf(".json") !== -1; } _onContentLoaded() { switch (this.content && this.content.type) { case "vctr": case "geom": this.tileset._traverser.disableSkipLevelOfDetail = true; break; default: } if (this._isTileset()) { this.hasTilesetContent = true; } else { this.gpuMemoryUsageInBytes = this._getGpuMemoryUsageInBytes(); } } _updateBoundingVolume(header) { this.boundingVolume = createBoundingVolume(header.boundingVolume, this.computedTransform, this.boundingVolume); const content = header.content; if (!content) { return; } if (content.boundingVolume) { this._contentBoundingVolume = createBoundingVolume(content.boundingVolume, this.computedTransform, this._contentBoundingVolume); } if (header.viewerRequestVolume) { this._viewerRequestVolume = createBoundingVolume(header.viewerRequestVolume, this.computedTransform, this._viewerRequestVolume); } } _updateTransform(parentTransform = new Matrix4()) { const computedTransform = parentTransform.clone().multiplyRight(this.transform); const didTransformChange = !computedTransform.equals(this.computedTransform); if (!didTransformChange) { return; } this.computedTransform = computedTransform; this._updateBoundingVolume(this.header); } _getLoaderSpecificOptions(loaderId) { switch (loaderId) { case "i3s": return { ...this.tileset.options.i3s, _tileOptions: { attributeUrls: this.header.attributeUrls, textureUrl: this.header.textureUrl, textureFormat: this.header.textureFormat, textureLoaderOptions: this.header.textureLoaderOptions, materialDefinition: this.header.materialDefinition, isDracoGeometry: this.header.isDracoGeometry, mbs: this.header.mbs }, _tilesetOptions: { store: this.tileset.tileset.store, attributeStorageInfo: this.tileset.tileset.attributeStorageInfo, fields: this.tileset.tileset.fields }, isTileHeader: false }; case "3d-tiles": case "cesium-ion": default: return get3dTilesOptions(this.tileset.tileset); } } }; // ../../node_modules/@loaders.gl/tiles/dist/tileset/format-3d-tiles/tileset-3d-traverser.js var Tileset3DTraverser = class extends TilesetTraverser { compareDistanceToCamera(a2, b) { return b._distanceToCamera === 0 && a2._distanceToCamera === 0 ? b._centerZDepth - a2._centerZDepth : b._distanceToCamera - a2._distanceToCamera; } updateTileVisibility(tile, frameState) { super.updateTileVisibility(tile, frameState); if (!tile.isVisibleAndInRequestVolume) { return; } const hasChildren = tile.children.length > 0; if (tile.hasTilesetContent && hasChildren) { const firstChild = tile.children[0]; this.updateTileVisibility(firstChild, frameState); tile._visible = firstChild._visible; return; } if (this.meetsScreenSpaceErrorEarly(tile, frameState)) { tile._visible = false; return; } const replace = tile.refine === TILE_REFINEMENT.REPLACE; const useOptimization = tile._optimChildrenWithinParent === TILE3D_OPTIMIZATION_HINT.USE_OPTIMIZATION; if (replace && useOptimization && hasChildren) { if (!this.anyChildrenVisible(tile, frameState)) { tile._visible = false; return; } } } meetsScreenSpaceErrorEarly(tile, frameState) { const { parent } = tile; if (!parent || parent.hasTilesetContent || parent.refine !== TILE_REFINEMENT.ADD) { return false; } return !this.shouldRefine(tile, frameState, true); } }; // ../../node_modules/@loaders.gl/tiles/dist/tileset/format-i3s/i3s-tileset-traverser.js var import_core31 = __toESM(require_core3(), 1); // ../../node_modules/@loaders.gl/tiles/dist/tileset/format-i3s/i3s-pending-tiles-register.js var I3SPendingTilesRegister = class { frameNumberMap = /* @__PURE__ */ new Map(); register(viewportId, frameNumber) { const viewportMap = this.frameNumberMap.get(viewportId) || /* @__PURE__ */ new Map(); const oldCount = viewportMap.get(frameNumber) || 0; viewportMap.set(frameNumber, oldCount + 1); this.frameNumberMap.set(viewportId, viewportMap); } deregister(viewportId, frameNumber) { const viewportMap = this.frameNumberMap.get(viewportId); if (!viewportMap) { return; } const oldCount = viewportMap.get(frameNumber) || 1; viewportMap.set(frameNumber, oldCount - 1); } isZero(viewportId, frameNumber) { const count = this.frameNumberMap.get(viewportId)?.get(frameNumber) || 0; return count === 0; } }; // ../../node_modules/@loaders.gl/tiles/dist/tileset/format-i3s/i3s-tile-manager.js var STATUS = { REQUESTED: "REQUESTED", COMPLETED: "COMPLETED", ERROR: "ERROR" }; var I3STileManager = class { _statusMap; pendingTilesRegister = new I3SPendingTilesRegister(); constructor() { this._statusMap = {}; } add(request, key, callback, frameState) { if (!this._statusMap[key]) { const { frameNumber, viewport: { id } } = frameState; this._statusMap[key] = { request, callback, key, frameState, status: STATUS.REQUESTED }; this.pendingTilesRegister.register(id, frameNumber); request().then((data) => { this._statusMap[key].status = STATUS.COMPLETED; const { frameNumber: actualFrameNumber, viewport: { id: id2 } } = this._statusMap[key].frameState; this.pendingTilesRegister.deregister(id2, actualFrameNumber); this._statusMap[key].callback(data, frameState); }).catch((error) => { this._statusMap[key].status = STATUS.ERROR; const { frameNumber: actualFrameNumber, viewport: { id: id2 } } = this._statusMap[key].frameState; this.pendingTilesRegister.deregister(id2, actualFrameNumber); callback(error); }); } } update(key, frameState) { if (this._statusMap[key]) { const { frameNumber, viewport: { id } } = this._statusMap[key].frameState; this.pendingTilesRegister.deregister(id, frameNumber); const { frameNumber: newFrameNumber, viewport: { id: newViewportId } } = frameState; this.pendingTilesRegister.register(newViewportId, newFrameNumber); this._statusMap[key].frameState = frameState; } } find(key) { return this._statusMap[key]; } hasPendingTiles(viewportId, frameNumber) { return !this.pendingTilesRegister.isZero(viewportId, frameNumber); } }; // ../../node_modules/@loaders.gl/tiles/dist/tileset/format-i3s/i3s-tileset-traverser.js var I3STilesetTraverser = class extends TilesetTraverser { _tileManager; constructor(options) { super(options); this._tileManager = new I3STileManager(); } traversalFinished(frameState) { return !this._tileManager.hasPendingTiles(frameState.viewport.id, this._frameNumber || 0); } shouldRefine(tile, frameState) { tile._lodJudge = getLodStatus(tile, frameState); return tile._lodJudge === "DIG"; } updateChildTiles(tile, frameState) { const children = tile.header.children || []; const childTiles = tile.children; const tileset = tile.tileset; for (const child of children) { const extendedId = `${child.id}-${frameState.viewport.id}`; const childTile = childTiles && childTiles.find((t2) => t2.id === extendedId); if (!childTile) { let request = () => this._loadTile(child.id, tileset); const cachedRequest = this._tileManager.find(extendedId); if (!cachedRequest) { if (tileset.tileset.nodePages) { request = () => tileset.tileset.nodePagesTile.formTileFromNodePages(child.id); } this._tileManager.add(request, extendedId, (header) => this._onTileLoad(header, tile, extendedId), frameState); } else { this._tileManager.update(extendedId, frameState); } } else if (childTile) { this.updateTile(childTile, frameState); } } return false; } async _loadTile(nodeId, tileset) { const { loader } = tileset; const nodeUrl = tileset.getTileUrl(`${tileset.url}/nodes/${nodeId}`); const options = { ...tileset.loadOptions, i3s: { ...tileset.loadOptions.i3s, isTileHeader: true } }; return await (0, import_core31.load)(nodeUrl, loader, options); } _onTileLoad(header, tile, extendedId) { const childTile = new Tile3D(tile.tileset, header, tile, extendedId); tile.children.push(childTile); const frameState = this._tileManager.find(childTile.id).frameState; this.updateTile(childTile, frameState); if (this._frameNumber === frameState.frameNumber && (this.traversalFinished(frameState) || new Date().getTime() - this.lastUpdate > this.updateDebounceTime)) { this.executeTraversal(childTile, frameState); } } }; // ../../node_modules/@loaders.gl/tiles/dist/tileset/tileset-3d.js var DEFAULT_PROPS3 = { description: "", ellipsoid: Ellipsoid.WGS84, modelMatrix: new Matrix4(), throttleRequests: true, maxRequests: 64, maximumMemoryUsage: 32, memoryCacheOverflow: 1, maximumTilesSelected: 0, debounceTime: 0, onTileLoad: () => { }, onTileUnload: () => { }, onTileError: () => { }, onTraversalComplete: (selectedTiles) => selectedTiles, contentLoader: void 0, viewDistanceScale: 1, maximumScreenSpaceError: 8, memoryAdjustedScreenSpaceError: false, loadTiles: true, updateTransforms: true, viewportTraversersMap: null, loadOptions: { fetch: {} }, attributions: [], basePath: "", i3s: {} }; var TILES_TOTAL = "Tiles In Tileset(s)"; var TILES_IN_MEMORY = "Tiles In Memory"; var TILES_IN_VIEW = "Tiles In View"; var TILES_RENDERABLE = "Tiles To Render"; var TILES_LOADED = "Tiles Loaded"; var TILES_LOADING = "Tiles Loading"; var TILES_UNLOADED = "Tiles Unloaded"; var TILES_LOAD_FAILED = "Failed Tile Loads"; var POINTS_COUNT = "Points/Vertices"; var TILES_GPU_MEMORY = "Tile Memory Use"; var MAXIMUM_SSE = "Maximum Screen Space Error"; var Tileset3D = class { options; loadOptions; type; tileset; loader; url; basePath; modelMatrix; ellipsoid; lodMetricType; lodMetricValue; refine; root = null; roots = {}; asset = {}; description = ""; properties; extras = null; attributions = {}; credits = {}; stats; contentFormats = { draco: false, meshopt: false, dds: false, ktx2: false }; cartographicCenter = null; cartesianCenter = null; zoom = 1; boundingVolume = null; dynamicScreenSpaceErrorComputedDensity = 0; maximumMemoryUsage = 32; gpuMemoryUsageInBytes = 0; memoryAdjustedScreenSpaceError = 0; _cacheBytes = 0; _cacheOverflowBytes = 0; _frameNumber = 0; _queryParams = {}; _extensionsUsed = []; _tiles = {}; _pendingCount = 0; selectedTiles = []; traverseCounter = 0; geometricError = 0; lastUpdatedVieports = null; _requestedTiles = []; _emptyTiles = []; frameStateData = {}; _traverser; _cache = new TilesetCache(); _requestScheduler; updatePromise = null; tilesetInitializationPromise; constructor(tileset, options) { this.options = { ...DEFAULT_PROPS3, ...options }; this.tileset = tileset; this.loader = tileset.loader; this.type = tileset.type; this.url = tileset.url; this.basePath = tileset.basePath || path_exports.dirname(this.url); this.modelMatrix = this.options.modelMatrix; this.ellipsoid = this.options.ellipsoid; this.lodMetricType = tileset.lodMetricType; this.lodMetricValue = tileset.lodMetricValue; this.refine = tileset.root.refine; this.loadOptions = this.options.loadOptions || {}; this._traverser = this._initializeTraverser(); this._requestScheduler = new RequestScheduler({ throttleRequests: this.options.throttleRequests, maxRequests: this.options.maxRequests }); this.memoryAdjustedScreenSpaceError = this.options.maximumScreenSpaceError; this._cacheBytes = this.options.maximumMemoryUsage * 1024 * 1024; this._cacheOverflowBytes = this.options.memoryCacheOverflow * 1024 * 1024; this.stats = new Stats({ id: this.url }); this._initializeStats(); this.tilesetInitializationPromise = this._initializeTileSet(tileset); } destroy() { this._destroy(); } isLoaded() { return this._pendingCount === 0 && this._frameNumber !== 0 && this._requestedTiles.length === 0; } get tiles() { return Object.values(this._tiles); } get frameNumber() { return this._frameNumber; } get queryParams() { return new URLSearchParams(this._queryParams).toString(); } setProps(props) { this.options = { ...this.options, ...props }; } getTileUrl(tilePath) { const isDataUrl = tilePath.startsWith("data:"); if (isDataUrl) { return tilePath; } let tileUrl = tilePath; if (this.queryParams.length) { tileUrl = `${tilePath}${tilePath.includes("?") ? "&" : "?"}${this.queryParams}`; } return tileUrl; } hasExtension(extensionName) { return Boolean(this._extensionsUsed.indexOf(extensionName) > -1); } update(viewports = null) { this.tilesetInitializationPromise.then(() => { if (!viewports && this.lastUpdatedVieports) { viewports = this.lastUpdatedVieports; } else { this.lastUpdatedVieports = viewports; } if (viewports) { this.doUpdate(viewports); } }); } async selectTiles(viewports = null) { await this.tilesetInitializationPromise; if (viewports) { this.lastUpdatedVieports = viewports; } if (!this.updatePromise) { this.updatePromise = new Promise((resolve2) => { setTimeout(() => { if (this.lastUpdatedVieports) { this.doUpdate(this.lastUpdatedVieports); } resolve2(this._frameNumber); this.updatePromise = null; }, this.options.debounceTime); }); } return this.updatePromise; } adjustScreenSpaceError() { if (this.gpuMemoryUsageInBytes < this._cacheBytes) { this.memoryAdjustedScreenSpaceError = Math.max(this.memoryAdjustedScreenSpaceError / 1.02, this.options.maximumScreenSpaceError); } else if (this.gpuMemoryUsageInBytes > this._cacheBytes + this._cacheOverflowBytes) { this.memoryAdjustedScreenSpaceError *= 1.02; } } doUpdate(viewports) { if ("loadTiles" in this.options && !this.options.loadTiles) { return; } if (this.traverseCounter > 0) { return; } const preparedViewports = viewports instanceof Array ? viewports : [viewports]; this._cache.reset(); this._frameNumber++; this.traverseCounter = preparedViewports.length; const viewportsToTraverse = []; for (const viewport of preparedViewports) { const id = viewport.id; if (this._needTraverse(id)) { viewportsToTraverse.push(id); } else { this.traverseCounter--; } } for (const viewport of preparedViewports) { const id = viewport.id; if (!this.roots[id]) { this.roots[id] = this._initializeTileHeaders(this.tileset, null); } if (!viewportsToTraverse.includes(id)) { continue; } const frameState = getFrameState(viewport, this._frameNumber); this._traverser.traverse(this.roots[id], frameState, this.options); } } _needTraverse(viewportId) { let traverserId = viewportId; if (this.options.viewportTraversersMap) { traverserId = this.options.viewportTraversersMap[viewportId]; } if (traverserId !== viewportId) { return false; } return true; } _onTraversalEnd(frameState) { const id = frameState.viewport.id; if (!this.frameStateData[id]) { this.frameStateData[id] = { selectedTiles: [], _requestedTiles: [], _emptyTiles: [] }; } const currentFrameStateData = this.frameStateData[id]; const selectedTiles = Object.values(this._traverser.selectedTiles); const [filteredSelectedTiles, unselectedTiles] = limitSelectedTiles(selectedTiles, frameState, this.options.maximumTilesSelected); currentFrameStateData.selectedTiles = filteredSelectedTiles; for (const tile of unselectedTiles) { tile.unselect(); } currentFrameStateData._requestedTiles = Object.values(this._traverser.requestedTiles); currentFrameStateData._emptyTiles = Object.values(this._traverser.emptyTiles); this.traverseCounter--; if (this.traverseCounter > 0) { return; } this._updateTiles(); } _updateTiles() { this.selectedTiles = []; this._requestedTiles = []; this._emptyTiles = []; for (const frameStateKey in this.frameStateData) { const frameStateDataValue = this.frameStateData[frameStateKey]; this.selectedTiles = this.selectedTiles.concat(frameStateDataValue.selectedTiles); this._requestedTiles = this._requestedTiles.concat(frameStateDataValue._requestedTiles); this._emptyTiles = this._emptyTiles.concat(frameStateDataValue._emptyTiles); } this.selectedTiles = this.options.onTraversalComplete(this.selectedTiles); for (const tile of this.selectedTiles) { this._tiles[tile.id] = tile; } this._loadTiles(); this._unloadTiles(); this._updateStats(); } _tilesChanged(oldSelectedTiles, selectedTiles) { if (oldSelectedTiles.length !== selectedTiles.length) { return true; } const set1 = new Set(oldSelectedTiles.map((t2) => t2.id)); const set22 = new Set(selectedTiles.map((t2) => t2.id)); let changed = oldSelectedTiles.filter((x2) => !set22.has(x2.id)).length > 0; changed = changed || selectedTiles.filter((x2) => !set1.has(x2.id)).length > 0; return changed; } _loadTiles() { for (const tile of this._requestedTiles) { if (tile.contentUnloaded) { this._loadTile(tile); } } } _unloadTiles() { this._cache.unloadTiles(this, (tileset, tile) => tileset._unloadTile(tile)); } _updateStats() { let tilesRenderable = 0; let pointsRenderable = 0; for (const tile of this.selectedTiles) { if (tile.contentAvailable && tile.content) { tilesRenderable++; if (tile.content.pointCount) { pointsRenderable += tile.content.pointCount; } else { pointsRenderable += tile.content.vertexCount; } } } this.stats.get(TILES_IN_VIEW).count = this.selectedTiles.length; this.stats.get(TILES_RENDERABLE).count = tilesRenderable; this.stats.get(POINTS_COUNT).count = pointsRenderable; this.stats.get(MAXIMUM_SSE).count = this.memoryAdjustedScreenSpaceError; } async _initializeTileSet(tilesetJson) { if (this.type === TILESET_TYPE.I3S) { this.calculateViewPropsI3S(); tilesetJson.root = await tilesetJson.root; } this.root = this._initializeTileHeaders(tilesetJson, null); if (this.type === TILESET_TYPE.TILES3D) { this._initializeTiles3DTileset(tilesetJson); this.calculateViewPropsTiles3D(); } if (this.type === TILESET_TYPE.I3S) { this._initializeI3STileset(); } } calculateViewPropsI3S() { const fullExtent = this.tileset.fullExtent; if (fullExtent) { const { xmin, xmax, ymin, ymax, zmin, zmax } = fullExtent; this.cartographicCenter = new Vector3(xmin + (xmax - xmin) / 2, ymin + (ymax - ymin) / 2, zmin + (zmax - zmin) / 2); this.cartesianCenter = new Vector3(); Ellipsoid.WGS84.cartographicToCartesian(this.cartographicCenter, this.cartesianCenter); this.zoom = getZoomFromFullExtent(fullExtent, this.cartographicCenter, this.cartesianCenter); return; } const extent = this.tileset.store?.extent; if (extent) { const [xmin, ymin, xmax, ymax] = extent; this.cartographicCenter = new Vector3(xmin + (xmax - xmin) / 2, ymin + (ymax - ymin) / 2, 0); this.cartesianCenter = new Vector3(); Ellipsoid.WGS84.cartographicToCartesian(this.cartographicCenter, this.cartesianCenter); this.zoom = getZoomFromExtent(extent, this.cartographicCenter, this.cartesianCenter); return; } console.warn("Extent is not defined in the tileset header"); this.cartographicCenter = new Vector3(); this.zoom = 1; return; } calculateViewPropsTiles3D() { const root = this.root; const { center } = root.boundingVolume; if (!center) { console.warn("center was not pre-calculated for the root tile"); this.cartographicCenter = new Vector3(); this.zoom = 1; return; } if (center[0] !== 0 || center[1] !== 0 || center[2] !== 0) { this.cartographicCenter = new Vector3(); Ellipsoid.WGS84.cartesianToCartographic(center, this.cartographicCenter); } else { this.cartographicCenter = new Vector3(0, 0, -Ellipsoid.WGS84.radii[0]); } this.cartesianCenter = center; this.zoom = getZoomFromBoundingVolume(root.boundingVolume, this.cartographicCenter); } _initializeStats() { this.stats.get(TILES_TOTAL); this.stats.get(TILES_LOADING); this.stats.get(TILES_IN_MEMORY); this.stats.get(TILES_IN_VIEW); this.stats.get(TILES_RENDERABLE); this.stats.get(TILES_LOADED); this.stats.get(TILES_UNLOADED); this.stats.get(TILES_LOAD_FAILED); this.stats.get(POINTS_COUNT); this.stats.get(TILES_GPU_MEMORY, "memory"); this.stats.get(MAXIMUM_SSE); } _initializeTileHeaders(tilesetJson, parentTileHeader) { const rootTile = new Tile3D(this, tilesetJson.root, parentTileHeader); if (parentTileHeader) { parentTileHeader.children.push(rootTile); rootTile.depth = parentTileHeader.depth + 1; } if (this.type === TILESET_TYPE.TILES3D) { const stack2 = []; stack2.push(rootTile); while (stack2.length > 0) { const tile = stack2.pop(); this.stats.get(TILES_TOTAL).incrementCount(); const children = tile.header.children || []; for (const childHeader of children) { const childTile = new Tile3D(this, childHeader, tile); if (childTile.contentUrl?.includes("?session=")) { const url = new URL(childTile.contentUrl); const session = url.searchParams.get("session"); if (session) { this._queryParams.session = session; } } tile.children.push(childTile); childTile.depth = tile.depth + 1; stack2.push(childTile); } } } return rootTile; } _initializeTraverser() { let TraverserClass; const type = this.type; switch (type) { case TILESET_TYPE.TILES3D: TraverserClass = Tileset3DTraverser; break; case TILESET_TYPE.I3S: TraverserClass = I3STilesetTraverser; break; default: TraverserClass = TilesetTraverser; } return new TraverserClass({ basePath: this.basePath, onTraversalEnd: this._onTraversalEnd.bind(this) }); } _destroyTileHeaders(parentTile) { this._destroySubtree(parentTile); } async _loadTile(tile) { let loaded; try { this._onStartTileLoading(); loaded = await tile.loadContent(); } catch (error) { this._onTileLoadError(tile, error instanceof Error ? error : new Error("load failed")); } finally { this._onEndTileLoading(); this._onTileLoad(tile, loaded); } } _onTileLoadError(tile, error) { this.stats.get(TILES_LOAD_FAILED).incrementCount(); const message = error.message || error.toString(); const url = tile.url; console.error(`A 3D tile failed to load: ${tile.url} ${message}`); this.options.onTileError(tile, message, url); } _onTileLoad(tile, loaded) { if (!loaded) { return; } if (this.type === TILESET_TYPE.I3S) { const nodesInNodePages = this.tileset?.nodePagesTile?.nodesInNodePages || 0; this.stats.get(TILES_TOTAL).reset(); this.stats.get(TILES_TOTAL).addCount(nodesInNodePages); } if (tile && tile.content) { calculateTransformProps(tile, tile.content); } this.updateContentTypes(tile); this._addTileToCache(tile); this.options.onTileLoad(tile); } updateContentTypes(tile) { if (this.type === TILESET_TYPE.I3S) { if (tile.header.isDracoGeometry) { this.contentFormats.draco = true; } switch (tile.header.textureFormat) { case "dds": this.contentFormats.dds = true; break; case "ktx2": this.contentFormats.ktx2 = true; break; default: } } else if (this.type === TILESET_TYPE.TILES3D) { const { extensionsRemoved = [] } = tile.content?.gltf || {}; if (extensionsRemoved.includes("KHR_draco_mesh_compression")) { this.contentFormats.draco = true; } if (extensionsRemoved.includes("EXT_meshopt_compression")) { this.contentFormats.meshopt = true; } if (extensionsRemoved.includes("KHR_texture_basisu")) { this.contentFormats.ktx2 = true; } } } _onStartTileLoading() { this._pendingCount++; this.stats.get(TILES_LOADING).incrementCount(); } _onEndTileLoading() { this._pendingCount--; this.stats.get(TILES_LOADING).decrementCount(); } _addTileToCache(tile) { this._cache.add(this, tile, (tileset) => tileset._updateCacheStats(tile)); } _updateCacheStats(tile) { this.stats.get(TILES_LOADED).incrementCount(); this.stats.get(TILES_IN_MEMORY).incrementCount(); this.gpuMemoryUsageInBytes += tile.gpuMemoryUsageInBytes || 0; this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes; if (this.options.memoryAdjustedScreenSpaceError) { this.adjustScreenSpaceError(); } } _unloadTile(tile) { this.gpuMemoryUsageInBytes -= tile.gpuMemoryUsageInBytes || 0; this.stats.get(TILES_IN_MEMORY).decrementCount(); this.stats.get(TILES_UNLOADED).incrementCount(); this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes; this.options.onTileUnload(tile); tile.unloadContent(); } _destroy() { const stack2 = []; if (this.root) { stack2.push(this.root); } while (stack2.length > 0) { const tile = stack2.pop(); for (const child of tile.children) { stack2.push(child); } this._destroyTile(tile); } this.root = null; } _destroySubtree(tile) { const root = tile; const stack2 = []; stack2.push(root); while (stack2.length > 0) { tile = stack2.pop(); for (const child of tile.children) { stack2.push(child); } if (tile !== root) { this._destroyTile(tile); } } root.children = []; } _destroyTile(tile) { this._cache.unloadTile(this, tile); this._unloadTile(tile); tile.destroy(); } _initializeTiles3DTileset(tilesetJson) { if (tilesetJson.queryString) { const searchParams = new URLSearchParams(tilesetJson.queryString); const queryParams = Object.fromEntries(searchParams.entries()); this._queryParams = { ...this._queryParams, ...queryParams }; } this.asset = tilesetJson.asset; if (!this.asset) { throw new Error("Tileset must have an asset property."); } if (this.asset.version !== "0.0" && this.asset.version !== "1.0" && this.asset.version !== "1.1") { throw new Error("The tileset must be 3D Tiles version either 0.0 or 1.0 or 1.1."); } if ("tilesetVersion" in this.asset) { this._queryParams.v = this.asset.tilesetVersion; } this.credits = { attributions: this.options.attributions || [] }; this.description = this.options.description || ""; this.properties = tilesetJson.properties; this.geometricError = tilesetJson.geometricError; this._extensionsUsed = tilesetJson.extensionsUsed || []; this.extras = tilesetJson.extras; } _initializeI3STileset() { if (this.loadOptions.i3s && "token" in this.loadOptions.i3s) { this._queryParams.token = this.loadOptions.i3s.token; } } }; // ../../node_modules/@loaders.gl/3d-tiles/dist/lib/utils/version.js var VERSION8 = true ? "4.2.0-beta.2" : "latest"; // ../../node_modules/@loaders.gl/3d-tiles/dist/lib/constants.js var TILE3D_TYPE = { COMPOSITE: "cmpt", POINT_CLOUD: "pnts", BATCHED_3D_MODEL: "b3dm", INSTANCED_3D_MODEL: "i3dm", GEOMETRY: "geom", VECTOR: "vect", GLTF: "glTF" }; var TILE3D_TYPES = Object.keys(TILE3D_TYPE); // ../../node_modules/@loaders.gl/3d-tiles/dist/lib/parsers/helpers/parse-utils.js function getStringFromArrayBuffer(arrayBuffer, byteOffset, byteLength) { assert2(arrayBuffer instanceof ArrayBuffer); const textDecoder = new TextDecoder("utf8"); const typedArray = new Uint8Array(arrayBuffer, byteOffset, byteLength); const string = textDecoder.decode(typedArray); return string; } function getMagicString2(arrayBuffer, byteOffset = 0) { const dataView = new DataView(arrayBuffer); return `${String.fromCharCode(dataView.getUint8(byteOffset + 0))}${String.fromCharCode(dataView.getUint8(byteOffset + 1))}${String.fromCharCode(dataView.getUint8(byteOffset + 2))}${String.fromCharCode(dataView.getUint8(byteOffset + 3))}`; } // ../../node_modules/@loaders.gl/draco/dist/lib/utils/version.js var VERSION9 = true ? "4.2.0-beta.2" : "latest"; // ../../node_modules/@loaders.gl/draco/dist/draco-loader.js var DracoLoader = { dataType: null, batchType: null, name: "Draco", id: "draco", module: "draco", version: VERSION9, worker: true, extensions: ["drc"], mimeTypes: ["application/octet-stream"], binary: true, tests: ["DRACO"], options: { draco: { decoderType: typeof WebAssembly === "object" ? "wasm" : "js", libraryPath: "libs/", extraAttributes: {}, attributeNameEntry: void 0 } } }; // ../../node_modules/@loaders.gl/schema/dist/lib/table/simple-table/data-type.js function getDataTypeFromTypedArray(array) { switch (array.constructor) { case Int8Array: return "int8"; case Uint8Array: case Uint8ClampedArray: return "uint8"; case Int16Array: return "int16"; case Uint16Array: return "uint16"; case Int32Array: return "int32"; case Uint32Array: return "uint32"; case Float32Array: return "float32"; case Float64Array: return "float64"; default: return "null"; } } // ../../node_modules/@loaders.gl/schema/dist/lib/mesh/mesh-utils.js function getMeshBoundingBox(attributes) { let minX = Infinity; let minY = Infinity; let minZ = Infinity; let maxX = -Infinity; let maxY = -Infinity; let maxZ = -Infinity; const positions = attributes.POSITION ? attributes.POSITION.value : []; const len2 = positions && positions.length; for (let i3 = 0; i3 < len2; i3 += 3) { const x2 = positions[i3]; const y2 = positions[i3 + 1]; const z = positions[i3 + 2]; minX = x2 < minX ? x2 : minX; minY = y2 < minY ? y2 : minY; minZ = z < minZ ? z : minZ; maxX = x2 > maxX ? x2 : maxX; maxY = y2 > maxY ? y2 : maxY; maxZ = z > maxZ ? z : maxZ; } return [ [minX, minY, minZ], [maxX, maxY, maxZ] ]; } // ../../node_modules/@loaders.gl/schema/dist/lib/mesh/deduce-mesh-schema.js function deduceMeshField(name12, attribute, optionalMetadata) { const type = getDataTypeFromTypedArray(attribute.value); const metadata = optionalMetadata ? optionalMetadata : makeMeshAttributeMetadata(attribute); return { name: name12, type: { type: "fixed-size-list", listSize: attribute.size, children: [{ name: "value", type }] }, nullable: false, metadata }; } function makeMeshAttributeMetadata(attribute) { const result = {}; if ("byteOffset" in attribute) { result.byteOffset = attribute.byteOffset.toString(10); } if ("byteStride" in attribute) { result.byteStride = attribute.byteStride.toString(10); } if ("normalized" in attribute) { result.normalized = attribute.normalized.toString(); } return result; } // ../../node_modules/@loaders.gl/draco/dist/lib/utils/get-draco-schema.js function getDracoSchema(attributes, loaderData, indices) { const metadata = makeMetadata(loaderData.metadata); const fields = []; const namedLoaderDataAttributes = transformAttributesLoaderData(loaderData.attributes); for (const attributeName in attributes) { const attribute = attributes[attributeName]; const field = getArrowFieldFromAttribute(attributeName, attribute, namedLoaderDataAttributes[attributeName]); fields.push(field); } if (indices) { const indicesField = getArrowFieldFromAttribute("indices", indices); fields.push(indicesField); } return { fields, metadata }; } function transformAttributesLoaderData(loaderData) { const result = {}; for (const key in loaderData) { const dracoAttribute = loaderData[key]; result[dracoAttribute.name || "undefined"] = dracoAttribute; } return result; } function getArrowFieldFromAttribute(attributeName, attribute, loaderData) { const metadataMap = loaderData ? makeMetadata(loaderData.metadata) : void 0; const field = deduceMeshField(attributeName, attribute, metadataMap); return field; } function makeMetadata(metadata) { Object.entries(metadata); const serializedMetadata = {}; for (const key in metadata) { serializedMetadata[`${key}.string`] = JSON.stringify(metadata[key]); } return serializedMetadata; } // ../../node_modules/@loaders.gl/draco/dist/lib/draco-parser.js var DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP = { POSITION: "POSITION", NORMAL: "NORMAL", COLOR: "COLOR_0", TEX_COORD: "TEXCOORD_0" }; var DRACO_DATA_TYPE_TO_TYPED_ARRAY_MAP = { 1: Int8Array, 2: Uint8Array, 3: Int16Array, 4: Uint16Array, 5: Int32Array, 6: Uint32Array, 9: Float32Array }; var INDEX_ITEM_SIZE = 4; var DracoParser = class { draco; decoder; metadataQuerier; constructor(draco) { this.draco = draco; this.decoder = new this.draco.Decoder(); this.metadataQuerier = new this.draco.MetadataQuerier(); } destroy() { this.draco.destroy(this.decoder); this.draco.destroy(this.metadataQuerier); } parseSync(arrayBuffer, options = {}) { const buffer = new this.draco.DecoderBuffer(); buffer.Init(new Int8Array(arrayBuffer), arrayBuffer.byteLength); this._disableAttributeTransforms(options); const geometry_type = this.decoder.GetEncodedGeometryType(buffer); const dracoGeometry = geometry_type === this.draco.TRIANGULAR_MESH ? new this.draco.Mesh() : new this.draco.PointCloud(); try { let dracoStatus; switch (geometry_type) { case this.draco.TRIANGULAR_MESH: dracoStatus = this.decoder.DecodeBufferToMesh(buffer, dracoGeometry); break; case this.draco.POINT_CLOUD: dracoStatus = this.decoder.DecodeBufferToPointCloud(buffer, dracoGeometry); break; default: throw new Error("DRACO: Unknown geometry type."); } if (!dracoStatus.ok() || !dracoGeometry.ptr) { const message = `DRACO decompression failed: ${dracoStatus.error_msg()}`; throw new Error(message); } const loaderData = this._getDracoLoaderData(dracoGeometry, geometry_type, options); const geometry = this._getMeshData(dracoGeometry, loaderData, options); const boundingBox = getMeshBoundingBox(geometry.attributes); const schema = getDracoSchema(geometry.attributes, loaderData, geometry.indices); const data = { loader: "draco", loaderData, header: { vertexCount: dracoGeometry.num_points(), boundingBox }, ...geometry, schema }; return data; } finally { this.draco.destroy(buffer); if (dracoGeometry) { this.draco.destroy(dracoGeometry); } } } _getDracoLoaderData(dracoGeometry, geometry_type, options) { const metadata = this._getTopLevelMetadata(dracoGeometry); const attributes = this._getDracoAttributes(dracoGeometry, options); return { geometry_type, num_attributes: dracoGeometry.num_attributes(), num_points: dracoGeometry.num_points(), num_faces: dracoGeometry instanceof this.draco.Mesh ? dracoGeometry.num_faces() : 0, metadata, attributes }; } _getDracoAttributes(dracoGeometry, options) { const dracoAttributes = {}; for (let attributeId = 0; attributeId < dracoGeometry.num_attributes(); attributeId++) { const dracoAttribute = this.decoder.GetAttribute(dracoGeometry, attributeId); const metadata = this._getAttributeMetadata(dracoGeometry, attributeId); dracoAttributes[dracoAttribute.unique_id()] = { unique_id: dracoAttribute.unique_id(), attribute_type: dracoAttribute.attribute_type(), data_type: dracoAttribute.data_type(), num_components: dracoAttribute.num_components(), byte_offset: dracoAttribute.byte_offset(), byte_stride: dracoAttribute.byte_stride(), normalized: dracoAttribute.normalized(), attribute_index: attributeId, metadata }; const quantization = this._getQuantizationTransform(dracoAttribute, options); if (quantization) { dracoAttributes[dracoAttribute.unique_id()].quantization_transform = quantization; } const octahedron = this._getOctahedronTransform(dracoAttribute, options); if (octahedron) { dracoAttributes[dracoAttribute.unique_id()].octahedron_transform = octahedron; } } return dracoAttributes; } _getMeshData(dracoGeometry, loaderData, options) { const attributes = this._getMeshAttributes(loaderData, dracoGeometry, options); const positionAttribute = attributes.POSITION; if (!positionAttribute) { throw new Error("DRACO: No position attribute found."); } if (dracoGeometry instanceof this.draco.Mesh) { switch (options.topology) { case "triangle-strip": return { topology: "triangle-strip", mode: 4, attributes, indices: { value: this._getTriangleStripIndices(dracoGeometry), size: 1 } }; case "triangle-list": default: return { topology: "triangle-list", mode: 5, attributes, indices: { value: this._getTriangleListIndices(dracoGeometry), size: 1 } }; } } return { topology: "point-list", mode: 0, attributes }; } _getMeshAttributes(loaderData, dracoGeometry, options) { const attributes = {}; for (const loaderAttribute of Object.values(loaderData.attributes)) { const attributeName = this._deduceAttributeName(loaderAttribute, options); loaderAttribute.name = attributeName; const values = this._getAttributeValues(dracoGeometry, loaderAttribute); if (values) { const { value, size } = values; attributes[attributeName] = { value, size, byteOffset: loaderAttribute.byte_offset, byteStride: loaderAttribute.byte_stride, normalized: loaderAttribute.normalized }; } } return attributes; } _getTriangleListIndices(dracoGeometry) { const numFaces = dracoGeometry.num_faces(); const numIndices = numFaces * 3; const byteLength = numIndices * INDEX_ITEM_SIZE; const ptr = this.draco._malloc(byteLength); try { this.decoder.GetTrianglesUInt32Array(dracoGeometry, byteLength, ptr); return new Uint32Array(this.draco.HEAPF32.buffer, ptr, numIndices).slice(); } finally { this.draco._free(ptr); } } _getTriangleStripIndices(dracoGeometry) { const dracoArray = new this.draco.DracoInt32Array(); try { this.decoder.GetTriangleStripsFromMesh(dracoGeometry, dracoArray); return getUint32Array(dracoArray); } finally { this.draco.destroy(dracoArray); } } _getAttributeValues(dracoGeometry, attribute) { const TypedArrayCtor = DRACO_DATA_TYPE_TO_TYPED_ARRAY_MAP[attribute.data_type]; if (!TypedArrayCtor) { console.warn(`DRACO: Unsupported attribute type ${attribute.data_type}`); return null; } const numComponents = attribute.num_components; const numPoints = dracoGeometry.num_points(); const numValues = numPoints * numComponents; const byteLength = numValues * TypedArrayCtor.BYTES_PER_ELEMENT; const dataType = getDracoDataType(this.draco, TypedArrayCtor); let value; const ptr = this.draco._malloc(byteLength); try { const dracoAttribute = this.decoder.GetAttribute(dracoGeometry, attribute.attribute_index); this.decoder.GetAttributeDataArrayForAllPoints(dracoGeometry, dracoAttribute, dataType, byteLength, ptr); value = new TypedArrayCtor(this.draco.HEAPF32.buffer, ptr, numValues).slice(); } finally { this.draco._free(ptr); } return { value, size: numComponents }; } _deduceAttributeName(attribute, options) { const uniqueId = attribute.unique_id; for (const [attributeName, attributeUniqueId] of Object.entries(options.extraAttributes || {})) { if (attributeUniqueId === uniqueId) { return attributeName; } } const thisAttributeType = attribute.attribute_type; for (const dracoAttributeConstant in DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP) { const attributeType = this.draco[dracoAttributeConstant]; if (attributeType === thisAttributeType) { return DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP[dracoAttributeConstant]; } } const entryName = options.attributeNameEntry || "name"; if (attribute.metadata[entryName]) { return attribute.metadata[entryName].string; } return `CUSTOM_ATTRIBUTE_${uniqueId}`; } _getTopLevelMetadata(dracoGeometry) { const dracoMetadata = this.decoder.GetMetadata(dracoGeometry); return this._getDracoMetadata(dracoMetadata); } _getAttributeMetadata(dracoGeometry, attributeId) { const dracoMetadata = this.decoder.GetAttributeMetadata(dracoGeometry, attributeId); return this._getDracoMetadata(dracoMetadata); } _getDracoMetadata(dracoMetadata) { if (!dracoMetadata || !dracoMetadata.ptr) { return {}; } const result = {}; const numEntries = this.metadataQuerier.NumEntries(dracoMetadata); for (let entryIndex = 0; entryIndex < numEntries; entryIndex++) { const entryName = this.metadataQuerier.GetEntryName(dracoMetadata, entryIndex); result[entryName] = this._getDracoMetadataField(dracoMetadata, entryName); } return result; } _getDracoMetadataField(dracoMetadata, entryName) { const dracoArray = new this.draco.DracoInt32Array(); try { this.metadataQuerier.GetIntEntryArray(dracoMetadata, entryName, dracoArray); const intArray = getInt32Array(dracoArray); return { int: this.metadataQuerier.GetIntEntry(dracoMetadata, entryName), string: this.metadataQuerier.GetStringEntry(dracoMetadata, entryName), double: this.metadataQuerier.GetDoubleEntry(dracoMetadata, entryName), intArray }; } finally { this.draco.destroy(dracoArray); } } _disableAttributeTransforms(options) { const { quantizedAttributes = [], octahedronAttributes = [] } = options; const skipAttributes = [...quantizedAttributes, ...octahedronAttributes]; for (const dracoAttributeName of skipAttributes) { this.decoder.SkipAttributeTransform(this.draco[dracoAttributeName]); } } _getQuantizationTransform(dracoAttribute, options) { const { quantizedAttributes = [] } = options; const attribute_type = dracoAttribute.attribute_type(); const skip = quantizedAttributes.map((type) => this.decoder[type]).includes(attribute_type); if (skip) { const transform2 = new this.draco.AttributeQuantizationTransform(); try { if (transform2.InitFromAttribute(dracoAttribute)) { return { quantization_bits: transform2.quantization_bits(), range: transform2.range(), min_values: new Float32Array([1, 2, 3]).map((i3) => transform2.min_value(i3)) }; } } finally { this.draco.destroy(transform2); } } return null; } _getOctahedronTransform(dracoAttribute, options) { const { octahedronAttributes = [] } = options; const attribute_type = dracoAttribute.attribute_type(); const octahedron = octahedronAttributes.map((type) => this.decoder[type]).includes(attribute_type); if (octahedron) { const transform2 = new this.draco.AttributeQuantizationTransform(); try { if (transform2.InitFromAttribute(dracoAttribute)) { return { quantization_bits: transform2.quantization_bits() }; } } finally { this.draco.destroy(transform2); } } return null; } }; function getDracoDataType(draco, attributeType) { switch (attributeType) { case Float32Array: return draco.DT_FLOAT32; case Int8Array: return draco.DT_INT8; case Int16Array: return draco.DT_INT16; case Int32Array: return draco.DT_INT32; case Uint8Array: return draco.DT_UINT8; case Uint16Array: return draco.DT_UINT16; case Uint32Array: return draco.DT_UINT32; default: return draco.DT_INVALID; } } function getInt32Array(dracoArray) { const numValues = dracoArray.size(); const intArray = new Int32Array(numValues); for (let i3 = 0; i3 < numValues; i3++) { intArray[i3] = dracoArray.GetValue(i3); } return intArray; } function getUint32Array(dracoArray) { const numValues = dracoArray.size(); const intArray = new Int32Array(numValues); for (let i3 = 0; i3 < numValues; i3++) { intArray[i3] = dracoArray.GetValue(i3); } return intArray; } // ../../node_modules/@loaders.gl/draco/dist/lib/draco-module-loader.js var DRACO_DECODER_VERSION = "1.5.6"; var DRACO_ENCODER_VERSION = "1.4.1"; var STATIC_DECODER_URL = `https://www.gstatic.com/draco/versioned/decoders/${DRACO_DECODER_VERSION}`; var DRACO_EXTERNAL_LIBRARIES = { DECODER: "draco_wasm_wrapper.js", DECODER_WASM: "draco_decoder.wasm", FALLBACK_DECODER: "draco_decoder.js", ENCODER: "draco_encoder.js" }; var DRACO_EXTERNAL_LIBRARY_URLS = { [DRACO_EXTERNAL_LIBRARIES.DECODER]: `${STATIC_DECODER_URL}/${DRACO_EXTERNAL_LIBRARIES.DECODER}`, [DRACO_EXTERNAL_LIBRARIES.DECODER_WASM]: `${STATIC_DECODER_URL}/${DRACO_EXTERNAL_LIBRARIES.DECODER_WASM}`, [DRACO_EXTERNAL_LIBRARIES.FALLBACK_DECODER]: `${STATIC_DECODER_URL}/${DRACO_EXTERNAL_LIBRARIES.FALLBACK_DECODER}`, [DRACO_EXTERNAL_LIBRARIES.ENCODER]: `https://raw.githubusercontent.com/google/draco/${DRACO_ENCODER_VERSION}/javascript/${DRACO_EXTERNAL_LIBRARIES.ENCODER}` }; var loadDecoderPromise; async function loadDracoDecoderModule(options) { const modules = options.modules || {}; if (modules.draco3d) { loadDecoderPromise ||= modules.draco3d.createDecoderModule({}).then((draco) => { return { draco }; }); } else { loadDecoderPromise ||= loadDracoDecoder(options); } return await loadDecoderPromise; } async function loadDracoDecoder(options) { let DracoDecoderModule; let wasmBinary; switch (options.draco && options.draco.decoderType) { case "js": DracoDecoderModule = await loadLibrary(DRACO_EXTERNAL_LIBRARY_URLS[DRACO_EXTERNAL_LIBRARIES.FALLBACK_DECODER], "draco", options, DRACO_EXTERNAL_LIBRARIES.FALLBACK_DECODER); break; case "wasm": default: [DracoDecoderModule, wasmBinary] = await Promise.all([ await loadLibrary(DRACO_EXTERNAL_LIBRARY_URLS[DRACO_EXTERNAL_LIBRARIES.DECODER], "draco", options, DRACO_EXTERNAL_LIBRARIES.DECODER), await loadLibrary(DRACO_EXTERNAL_LIBRARY_URLS[DRACO_EXTERNAL_LIBRARIES.DECODER_WASM], "draco", options, DRACO_EXTERNAL_LIBRARIES.DECODER_WASM) ]); } DracoDecoderModule = DracoDecoderModule || globalThis.DracoDecoderModule; return await initializeDracoDecoder(DracoDecoderModule, wasmBinary); } function initializeDracoDecoder(DracoDecoderModule, wasmBinary) { const options = {}; if (wasmBinary) { options.wasmBinary = wasmBinary; } return new Promise((resolve2) => { DracoDecoderModule({ ...options, onModuleLoaded: (draco) => resolve2({ draco }) }); }); } // ../../node_modules/@loaders.gl/draco/dist/index.js var DracoLoader2 = { ...DracoLoader, parse }; async function parse(arrayBuffer, options) { const { draco } = await loadDracoDecoderModule(options); const dracoParser = new DracoParser(draco); try { return dracoParser.parseSync(arrayBuffer, options?.draco); } finally { dracoParser.destroy(); } } // ../../node_modules/@loaders.gl/math/dist/geometry/constants.js var GL_PRIMITIVE_MODE = { POINTS: 0, LINES: 1, LINE_LOOP: 2, LINE_STRIP: 3, TRIANGLES: 4, TRIANGLE_STRIP: 5, TRIANGLE_FAN: 6 }; var GL_TYPE = { BYTE: 5120, UNSIGNED_BYTE: 5121, SHORT: 5122, UNSIGNED_SHORT: 5123, INT: 5124, UNSIGNED_INT: 5125, FLOAT: 5126, DOUBLE: 5130 }; var GL2 = { ...GL_PRIMITIVE_MODE, ...GL_TYPE }; // ../../node_modules/@loaders.gl/math/dist/geometry/gl/gl-type.js var GL_TYPE_TO_ARRAY_TYPE = { [GL_TYPE.DOUBLE]: Float64Array, [GL_TYPE.FLOAT]: Float32Array, [GL_TYPE.UNSIGNED_SHORT]: Uint16Array, [GL_TYPE.UNSIGNED_INT]: Uint32Array, [GL_TYPE.UNSIGNED_BYTE]: Uint8Array, [GL_TYPE.BYTE]: Int8Array, [GL_TYPE.SHORT]: Int16Array, [GL_TYPE.INT]: Int32Array }; var NAME_TO_GL_TYPE = { DOUBLE: GL_TYPE.DOUBLE, FLOAT: GL_TYPE.FLOAT, UNSIGNED_SHORT: GL_TYPE.UNSIGNED_SHORT, UNSIGNED_INT: GL_TYPE.UNSIGNED_INT, UNSIGNED_BYTE: GL_TYPE.UNSIGNED_BYTE, BYTE: GL_TYPE.BYTE, SHORT: GL_TYPE.SHORT, INT: GL_TYPE.INT }; var ERR_TYPE_CONVERSION = "Failed to convert GL type"; var GLType = class { static fromTypedArray(arrayOrType) { arrayOrType = ArrayBuffer.isView(arrayOrType) ? arrayOrType.constructor : arrayOrType; for (const glType in GL_TYPE_TO_ARRAY_TYPE) { const ArrayType = GL_TYPE_TO_ARRAY_TYPE[glType]; if (ArrayType === arrayOrType) { return glType; } } throw new Error(ERR_TYPE_CONVERSION); } static fromName(name12) { const glType = NAME_TO_GL_TYPE[name12]; if (!glType) { throw new Error(ERR_TYPE_CONVERSION); } return glType; } static getArrayType(glType) { switch (glType) { case GL_TYPE.UNSIGNED_SHORT_5_6_5: case GL_TYPE.UNSIGNED_SHORT_4_4_4_4: case GL_TYPE.UNSIGNED_SHORT_5_5_5_1: return Uint16Array; default: const ArrayType = GL_TYPE_TO_ARRAY_TYPE[glType]; if (!ArrayType) { throw new Error(ERR_TYPE_CONVERSION); } return ArrayType; } } static getByteSize(glType) { const ArrayType = GLType.getArrayType(glType); return ArrayType.BYTES_PER_ELEMENT; } static validate(glType) { return Boolean(GLType.getArrayType(glType)); } static createTypedArray(glType, buffer, byteOffset = 0, length5) { if (length5 === void 0) { length5 = (buffer.byteLength - byteOffset) / GLType.getByteSize(glType); } const ArrayType = GLType.getArrayType(glType); return new ArrayType(buffer, byteOffset, length5); } }; // ../../node_modules/@loaders.gl/math/dist/geometry/utils/assert.js function assert7(condition, message) { if (!condition) { throw new Error(`math.gl assertion failed. ${message}`); } } // ../../node_modules/@loaders.gl/math/dist/geometry/colors/rgb565.js function decodeRGB565(rgb565, target = [0, 0, 0]) { const r5 = rgb565 >> 11 & 31; const g6 = rgb565 >> 5 & 63; const b5 = rgb565 & 31; target[0] = r5 << 3; target[1] = g6 << 2; target[2] = b5 << 3; return target; } // ../../node_modules/@loaders.gl/math/dist/geometry/compression/attribute-compression.js var RIGHT_SHIFT = 1 / 256; var scratchVector25 = new Vector2(); var scratchVector34 = new Vector3(); var scratchEncodeVector2 = new Vector2(); var octEncodeScratch = new Vector2(); var uint8ForceArray = new Uint8Array(1); function fromSNorm(value, rangeMaximum = 255) { return clamp(value, 0, rangeMaximum) / rangeMaximum * 2 - 1; } function signNotZero(value) { return value < 0 ? -1 : 1; } function octDecodeInRange(x2, y2, rangeMax, result) { assert7(result); if (x2 < 0 || x2 > rangeMax || y2 < 0 || y2 > rangeMax) { throw new Error(`x and y must be unsigned normalized integers between 0 and ${rangeMax}`); } result.x = fromSNorm(x2, rangeMax); result.y = fromSNorm(y2, rangeMax); result.z = 1 - (Math.abs(result.x) + Math.abs(result.y)); if (result.z < 0) { const oldVX = result.x; result.x = (1 - Math.abs(result.y)) * signNotZero(oldVX); result.y = (1 - Math.abs(oldVX)) * signNotZero(result.y); } return result.normalize(); } function octDecode(x2, y2, result) { return octDecodeInRange(x2, y2, 255, result); } // ../../node_modules/@loaders.gl/3d-tiles/dist/lib/classes/tile-3d-feature-table.js var Tile3DFeatureTable = class { json; buffer; featuresLength = 0; _cachedTypedArrays = {}; constructor(featureTableJson, featureTableBinary) { this.json = featureTableJson; this.buffer = featureTableBinary; } getExtension(extensionName) { return this.json.extensions && this.json.extensions[extensionName]; } hasProperty(propertyName) { return Boolean(this.json[propertyName]); } getGlobalProperty(propertyName, componentType = GL2.UNSIGNED_INT, componentLength = 1) { const jsonValue = this.json[propertyName]; if (jsonValue && Number.isFinite(jsonValue.byteOffset)) { return this._getTypedArrayFromBinary(propertyName, componentType, componentLength, 1, jsonValue.byteOffset); } return jsonValue; } getPropertyArray(propertyName, componentType, componentLength) { const jsonValue = this.json[propertyName]; if (jsonValue && Number.isFinite(jsonValue.byteOffset)) { if ("componentType" in jsonValue) { componentType = GLType.fromName(jsonValue.componentType); } return this._getTypedArrayFromBinary(propertyName, componentType, componentLength, this.featuresLength, jsonValue.byteOffset); } return this._getTypedArrayFromArray(propertyName, componentType, jsonValue); } getProperty(propertyName, componentType, componentLength, featureId, result) { const jsonValue = this.json[propertyName]; if (!jsonValue) { return jsonValue; } const typedArray = this.getPropertyArray(propertyName, componentType, componentLength); if (componentLength === 1) { return typedArray[featureId]; } for (let i3 = 0; i3 < componentLength; ++i3) { result[i3] = typedArray[componentLength * featureId + i3]; } return result; } _getTypedArrayFromBinary(propertyName, componentType, componentLength, count, byteOffset) { const cachedTypedArrays = this._cachedTypedArrays; let typedArray = cachedTypedArrays[propertyName]; if (!typedArray) { typedArray = GLType.createTypedArray(componentType, this.buffer.buffer, this.buffer.byteOffset + byteOffset, count * componentLength); cachedTypedArrays[propertyName] = typedArray; } return typedArray; } _getTypedArrayFromArray(propertyName, componentType, array) { const cachedTypedArrays = this._cachedTypedArrays; let typedArray = cachedTypedArrays[propertyName]; if (!typedArray) { typedArray = GLType.createTypedArray(componentType, array); cachedTypedArrays[propertyName] = typedArray; } return typedArray; } }; // ../../node_modules/@loaders.gl/3d-tiles/dist/lib/classes/helpers/tile-3d-accessor-utils.js var COMPONENTS_PER_ATTRIBUTE = { SCALAR: 1, VEC2: 2, VEC3: 3, VEC4: 4, MAT2: 4, MAT3: 9, MAT4: 16 }; var UNPACKER = { SCALAR: (values, i3) => values[i3], VEC2: (values, i3) => [values[2 * i3 + 0], values[2 * i3 + 1]], VEC3: (values, i3) => [values[3 * i3 + 0], values[3 * i3 + 1], values[3 * i3 + 2]], VEC4: (values, i3) => [values[4 * i3 + 0], values[4 * i3 + 1], values[4 * i3 + 2], values[4 * i3 + 3]], MAT2: (values, i3) => [ values[4 * i3 + 0], values[4 * i3 + 1], values[4 * i3 + 2], values[4 * i3 + 3] ], MAT3: (values, i3) => [ values[9 * i3 + 0], values[9 * i3 + 1], values[9 * i3 + 2], values[9 * i3 + 3], values[9 * i3 + 4], values[9 * i3 + 5], values[9 * i3 + 6], values[9 * i3 + 7], values[9 * i3 + 8] ], MAT4: (values, i3) => [ values[16 * i3 + 0], values[16 * i3 + 1], values[16 * i3 + 2], values[16 * i3 + 3], values[16 * i3 + 4], values[16 * i3 + 5], values[16 * i3 + 6], values[16 * i3 + 7], values[16 * i3 + 8], values[16 * i3 + 9], values[16 * i3 + 10], values[16 * i3 + 11], values[16 * i3 + 12], values[16 * i3 + 13], values[16 * i3 + 14], values[16 * i3 + 15] ] }; var PACKER = { SCALAR: (x2, values, i3) => { values[i3] = x2; }, VEC2: (x2, values, i3) => { values[2 * i3 + 0] = x2[0]; values[2 * i3 + 1] = x2[1]; }, VEC3: (x2, values, i3) => { values[3 * i3 + 0] = x2[0]; values[3 * i3 + 1] = x2[1]; values[3 * i3 + 2] = x2[2]; }, VEC4: (x2, values, i3) => { values[4 * i3 + 0] = x2[0]; values[4 * i3 + 1] = x2[1]; values[4 * i3 + 2] = x2[2]; values[4 * i3 + 3] = x2[3]; }, MAT2: (x2, values, i3) => { values[4 * i3 + 0] = x2[0]; values[4 * i3 + 1] = x2[1]; values[4 * i3 + 2] = x2[2]; values[4 * i3 + 3] = x2[3]; }, MAT3: (x2, values, i3) => { values[9 * i3 + 0] = x2[0]; values[9 * i3 + 1] = x2[1]; values[9 * i3 + 2] = x2[2]; values[9 * i3 + 3] = x2[3]; values[9 * i3 + 4] = x2[4]; values[9 * i3 + 5] = x2[5]; values[9 * i3 + 6] = x2[6]; values[9 * i3 + 7] = x2[7]; values[9 * i3 + 8] = x2[8]; values[9 * i3 + 9] = x2[9]; }, MAT4: (x2, values, i3) => { values[16 * i3 + 0] = x2[0]; values[16 * i3 + 1] = x2[1]; values[16 * i3 + 2] = x2[2]; values[16 * i3 + 3] = x2[3]; values[16 * i3 + 4] = x2[4]; values[16 * i3 + 5] = x2[5]; values[16 * i3 + 6] = x2[6]; values[16 * i3 + 7] = x2[7]; values[16 * i3 + 8] = x2[8]; values[16 * i3 + 9] = x2[9]; values[16 * i3 + 10] = x2[10]; values[16 * i3 + 11] = x2[11]; values[16 * i3 + 12] = x2[12]; values[16 * i3 + 13] = x2[13]; values[16 * i3 + 14] = x2[14]; values[16 * i3 + 15] = x2[15]; } }; function createTypedArrayFromAccessor(tile3DAccessor, buffer, byteOffset, length5) { const { componentType } = tile3DAccessor; assert2(tile3DAccessor.componentType); const type = typeof componentType === "string" ? GLType.fromName(componentType) : componentType; const size = COMPONENTS_PER_ATTRIBUTE[tile3DAccessor.type]; const unpacker = UNPACKER[tile3DAccessor.type]; const packer = PACKER[tile3DAccessor.type]; byteOffset += tile3DAccessor.byteOffset; const values = GLType.createTypedArray(type, buffer, byteOffset, size * length5); return { values, type, size, unpacker, packer }; } // ../../node_modules/@loaders.gl/3d-tiles/dist/lib/classes/tile-3d-batch-table-hierarchy.js var defined3 = (x2) => x2 !== void 0; function initializeHierarchy(batchTable, jsonHeader, binaryBody) { if (!jsonHeader) { return null; } let hierarchy = batchTable.getExtension("3DTILES_batch_table_hierarchy"); const legacyHierarchy = jsonHeader.HIERARCHY; if (legacyHierarchy) { console.warn("3D Tile Parser: HIERARCHY is deprecated. Use 3DTILES_batch_table_hierarchy."); jsonHeader.extensions = jsonHeader.extensions || {}; jsonHeader.extensions["3DTILES_batch_table_hierarchy"] = legacyHierarchy; hierarchy = legacyHierarchy; } if (!hierarchy) { return null; } return initializeHierarchyValues(hierarchy, binaryBody); } function initializeHierarchyValues(hierarchyJson, binaryBody) { let i3; let classId; let binaryAccessor; const instancesLength = hierarchyJson.instancesLength; const classes = hierarchyJson.classes; let classIds = hierarchyJson.classIds; let parentCounts = hierarchyJson.parentCounts; let parentIds = hierarchyJson.parentIds; let parentIdsLength = instancesLength; if (defined3(classIds.byteOffset)) { classIds.componentType = defaultValue(classIds.componentType, GL.UNSIGNED_SHORT); classIds.type = AttributeType.SCALAR; binaryAccessor = getBinaryAccessor(classIds); classIds = binaryAccessor.createArrayBufferView(binaryBody.buffer, binaryBody.byteOffset + classIds.byteOffset, instancesLength); } let parentIndexes; if (defined3(parentCounts)) { if (defined3(parentCounts.byteOffset)) { parentCounts.componentType = defaultValue(parentCounts.componentType, GL.UNSIGNED_SHORT); parentCounts.type = AttributeType.SCALAR; binaryAccessor = getBinaryAccessor(parentCounts); parentCounts = binaryAccessor.createArrayBufferView(binaryBody.buffer, binaryBody.byteOffset + parentCounts.byteOffset, instancesLength); } parentIndexes = new Uint16Array(instancesLength); parentIdsLength = 0; for (i3 = 0; i3 < instancesLength; ++i3) { parentIndexes[i3] = parentIdsLength; parentIdsLength += parentCounts[i3]; } } if (defined3(parentIds) && defined3(parentIds.byteOffset)) { parentIds.componentType = defaultValue(parentIds.componentType, GL.UNSIGNED_SHORT); parentIds.type = AttributeType.SCALAR; binaryAccessor = getBinaryAccessor(parentIds); parentIds = binaryAccessor.createArrayBufferView(binaryBody.buffer, binaryBody.byteOffset + parentIds.byteOffset, parentIdsLength); } const classesLength = classes.length; for (i3 = 0; i3 < classesLength; ++i3) { const classInstancesLength = classes[i3].length; const properties = classes[i3].instances; const binaryProperties = getBinaryProperties(classInstancesLength, properties, binaryBody); classes[i3].instances = combine(binaryProperties, properties); } const classCounts = new Array(classesLength).fill(0); const classIndexes = new Uint16Array(instancesLength); for (i3 = 0; i3 < instancesLength; ++i3) { classId = classIds[i3]; classIndexes[i3] = classCounts[classId]; ++classCounts[classId]; } const hierarchy = { classes, classIds, classIndexes, parentCounts, parentIndexes, parentIds }; validateHierarchy(hierarchy); return hierarchy; } function traverseHierarchy(hierarchy, instanceIndex, endConditionCallback) { if (!hierarchy) { return; } const parentCounts = hierarchy.parentCounts; const parentIds = hierarchy.parentIds; if (parentIds) { return endConditionCallback(hierarchy, instanceIndex); } if (parentCounts > 0) { return traverseHierarchyMultipleParents(hierarchy, instanceIndex, endConditionCallback); } return traverseHierarchySingleParent(hierarchy, instanceIndex, endConditionCallback); } function traverseHierarchyMultipleParents(hierarchy, instanceIndex, endConditionCallback) { const classIds = hierarchy.classIds; const parentCounts = hierarchy.parentCounts; const parentIds = hierarchy.parentIds; const parentIndexes = hierarchy.parentIndexes; const instancesLength = classIds.length; const visited = scratchVisited; visited.length = Math.max(visited.length, instancesLength); const visitedMarker = ++marker; const stack2 = scratchStack; stack2.length = 0; stack2.push(instanceIndex); while (stack2.length > 0) { instanceIndex = stack2.pop(); if (visited[instanceIndex] === visitedMarker) { continue; } visited[instanceIndex] = visitedMarker; const result = endConditionCallback(hierarchy, instanceIndex); if (defined3(result)) { return result; } const parentCount = parentCounts[instanceIndex]; const parentIndex = parentIndexes[instanceIndex]; for (let i3 = 0; i3 < parentCount; ++i3) { const parentId = parentIds[parentIndex + i3]; if (parentId !== instanceIndex) { stack2.push(parentId); } } } return null; } function traverseHierarchySingleParent(hierarchy, instanceIndex, endConditionCallback) { let hasParent = true; while (hasParent) { const result = endConditionCallback(hierarchy, instanceIndex); if (defined3(result)) { return result; } const parentId = hierarchy.parentIds[instanceIndex]; hasParent = parentId !== instanceIndex; instanceIndex = parentId; } throw new Error("traverseHierarchySingleParent"); } function validateHierarchy(hierarchy) { const scratchValidateStack = []; const classIds = hierarchy.classIds; const instancesLength = classIds.length; for (let i3 = 0; i3 < instancesLength; ++i3) { validateInstance(hierarchy, i3, stack); } } function validateInstance(hierarchy, instanceIndex, stack2) { const parentCounts = hierarchy.parentCounts; const parentIds = hierarchy.parentIds; const parentIndexes = hierarchy.parentIndexes; const classIds = hierarchy.classIds; const instancesLength = classIds.length; if (!defined3(parentIds)) { return; } assert(instanceIndex < instancesLength, `Parent index ${instanceIndex} exceeds the total number of instances: ${instancesLength}`); assert(stack2.indexOf(instanceIndex) === -1, "Circular dependency detected in the batch table hierarchy."); stack2.push(instanceIndex); const parentCount = defined3(parentCounts) ? parentCounts[instanceIndex] : 1; const parentIndex = defined3(parentCounts) ? parentIndexes[instanceIndex] : instanceIndex; for (let i3 = 0; i3 < parentCount; ++i3) { const parentId = parentIds[parentIndex + i3]; if (parentId !== instanceIndex) { validateInstance(hierarchy, parentId, stack2); } } stack2.pop(instanceIndex); } // ../../node_modules/@loaders.gl/3d-tiles/dist/lib/classes/tile-3d-batch-table.js function defined4(x2) { return x2 !== void 0 && x2 !== null; } var clone5 = (x2, y2) => x2; var IGNORED_PROPERTY_FIELDS = { HIERARCHY: true, extensions: true, extras: true }; var Tile3DBatchTableParser = class { json; binary; featureCount; _extensions; _properties; _binaryProperties; _hierarchy; constructor(json, binary, featureCount, options = {}) { assert2(featureCount >= 0); this.json = json || {}; this.binary = binary; this.featureCount = featureCount; this._extensions = this.json?.extensions || {}; this._properties = {}; for (const propertyName in this.json) { if (!IGNORED_PROPERTY_FIELDS[propertyName]) { this._properties[propertyName] = this.json[propertyName]; } } this._binaryProperties = this._initializeBinaryProperties(); if (options["3DTILES_batch_table_hierarchy"]) { this._hierarchy = initializeHierarchy(this, this.json, this.binary); } } getExtension(extensionName) { return this.json && this.json.extensions && this.json.extensions[extensionName]; } memorySizeInBytes() { return 0; } isClass(batchId, className) { this._checkBatchId(batchId); assert2(typeof className === "string", className); if (this._hierarchy) { const result = traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => { const classId = hierarchy.classIds[instanceIndex]; const instanceClass = hierarchy.classes[classId]; return instanceClass.name === className; }); return defined4(result); } return false; } isExactClass(batchId, className) { assert2(typeof className === "string", className); return this.getExactClassName(batchId) === className; } getExactClassName(batchId) { this._checkBatchId(batchId); if (this._hierarchy) { const classId = this._hierarchy.classIds[batchId]; const instanceClass = this._hierarchy.classes[classId]; return instanceClass.name; } return void 0; } hasProperty(batchId, name12) { this._checkBatchId(batchId); assert2(typeof name12 === "string", name12); return defined4(this._properties[name12]) || this._hasPropertyInHierarchy(batchId, name12); } getPropertyNames(batchId, results) { this._checkBatchId(batchId); results = defined4(results) ? results : []; results.length = 0; const propertyNames = Object.keys(this._properties); results.push(...propertyNames); if (this._hierarchy) { this._getPropertyNamesInHierarchy(batchId, results); } return results; } getProperty(batchId, name12) { this._checkBatchId(batchId); assert2(typeof name12 === "string", name12); if (this._binaryProperties) { const binaryProperty = this._binaryProperties[name12]; if (defined4(binaryProperty)) { return this._getBinaryProperty(binaryProperty, batchId); } } const propertyValues = this._properties[name12]; if (defined4(propertyValues)) { return clone5(propertyValues[batchId], true); } if (this._hierarchy) { const hierarchyProperty = this._getHierarchyProperty(batchId, name12); if (defined4(hierarchyProperty)) { return hierarchyProperty; } } return void 0; } setProperty(batchId, name12, value) { const featureCount = this.featureCount; this._checkBatchId(batchId); assert2(typeof name12 === "string", name12); if (this._binaryProperties) { const binaryProperty = this._binaryProperties[name12]; if (binaryProperty) { this._setBinaryProperty(binaryProperty, batchId, value); return; } } if (this._hierarchy) { if (this._setHierarchyProperty(this, batchId, name12, value)) { return; } } let propertyValues = this._properties[name12]; if (!defined4(propertyValues)) { this._properties[name12] = new Array(featureCount); propertyValues = this._properties[name12]; } propertyValues[batchId] = clone5(value, true); } _checkBatchId(batchId) { const valid = batchId >= 0 && batchId < this.featureCount; if (!valid) { throw new Error("batchId not in range [0, featureCount - 1]."); } } _getBinaryProperty(binaryProperty, index) { return binaryProperty.unpack(binaryProperty.typedArray, index); } _setBinaryProperty(binaryProperty, index, value) { binaryProperty.pack(value, binaryProperty.typedArray, index); } _initializeBinaryProperties() { let binaryProperties = null; for (const name12 in this._properties) { const property = this._properties[name12]; const binaryProperty = this._initializeBinaryProperty(name12, property); if (binaryProperty) { binaryProperties = binaryProperties || {}; binaryProperties[name12] = binaryProperty; } } return binaryProperties; } _initializeBinaryProperty(name12, property) { if ("byteOffset" in property) { const tile3DAccessor = property; assert2(this.binary, `Property ${name12} requires a batch table binary.`); assert2(tile3DAccessor.type, `Property ${name12} requires a type.`); const accessor = createTypedArrayFromAccessor(tile3DAccessor, this.binary.buffer, this.binary.byteOffset | 0, this.featureCount); return { typedArray: accessor.values, componentCount: accessor.size, unpack: accessor.unpacker, pack: accessor.packer }; } return null; } _hasPropertyInHierarchy(batchId, name12) { if (!this._hierarchy) { return false; } const result = traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => { const classId = hierarchy.classIds[instanceIndex]; const instances = hierarchy.classes[classId].instances; return defined4(instances[name12]); }); return defined4(result); } _getPropertyNamesInHierarchy(batchId, results) { traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => { const classId = hierarchy.classIds[instanceIndex]; const instances = hierarchy.classes[classId].instances; for (const name12 in instances) { if (instances.hasOwnProperty(name12)) { if (results.indexOf(name12) === -1) { results.push(name12); } } } }); } _getHierarchyProperty(batchId, name12) { return traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => { const classId = hierarchy.classIds[instanceIndex]; const instanceClass = hierarchy.classes[classId]; const indexInClass = hierarchy.classIndexes[instanceIndex]; const propertyValues = instanceClass.instances[name12]; if (defined4(propertyValues)) { if (defined4(propertyValues.typedArray)) { return this._getBinaryProperty(propertyValues, indexInClass); } return clone5(propertyValues[indexInClass], true); } return null; }); } _setHierarchyProperty(batchTable, batchId, name12, value) { const result = traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => { const classId = hierarchy.classIds[instanceIndex]; const instanceClass = hierarchy.classes[classId]; const indexInClass = hierarchy.classIndexes[instanceIndex]; const propertyValues = instanceClass.instances[name12]; if (defined4(propertyValues)) { assert2(instanceIndex === batchId, `Inherited property "${name12}" is read-only.`); if (defined4(propertyValues.typedArray)) { this._setBinaryProperty(propertyValues, indexInClass, value); } else { propertyValues[indexInClass] = clone5(value, true); } return true; } return false; }); return defined4(result); } }; // ../../node_modules/@loaders.gl/3d-tiles/dist/lib/parsers/helpers/parse-3d-tile-header.js var SIZEOF_UINT32 = 4; function parse3DTileHeaderSync(tile, arrayBuffer, byteOffset = 0) { const view = new DataView(arrayBuffer); tile.magic = view.getUint32(byteOffset, true); byteOffset += SIZEOF_UINT32; tile.version = view.getUint32(byteOffset, true); byteOffset += SIZEOF_UINT32; tile.byteLength = view.getUint32(byteOffset, true); byteOffset += SIZEOF_UINT32; if (tile.version !== 1) { throw new Error(`3D Tile Version ${tile.version} not supported`); } return byteOffset; } // ../../node_modules/@loaders.gl/3d-tiles/dist/lib/parsers/helpers/parse-3d-tile-tables.js var SIZEOF_UINT322 = 4; var DEPRECATION_WARNING = "b3dm tile in legacy format."; function parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset) { const view = new DataView(arrayBuffer); let batchLength; tile.header = tile.header || {}; let featureTableJsonByteLength = view.getUint32(byteOffset, true); byteOffset += SIZEOF_UINT322; let featureTableBinaryByteLength = view.getUint32(byteOffset, true); byteOffset += SIZEOF_UINT322; let batchTableJsonByteLength = view.getUint32(byteOffset, true); byteOffset += SIZEOF_UINT322; let batchTableBinaryByteLength = view.getUint32(byteOffset, true); byteOffset += SIZEOF_UINT322; if (batchTableJsonByteLength >= 570425344) { byteOffset -= SIZEOF_UINT322 * 2; batchLength = featureTableJsonByteLength; batchTableJsonByteLength = featureTableBinaryByteLength; batchTableBinaryByteLength = 0; featureTableJsonByteLength = 0; featureTableBinaryByteLength = 0; console.warn(DEPRECATION_WARNING); } else if (batchTableBinaryByteLength >= 570425344) { byteOffset -= SIZEOF_UINT322; batchLength = batchTableJsonByteLength; batchTableJsonByteLength = featureTableJsonByteLength; batchTableBinaryByteLength = featureTableBinaryByteLength; featureTableJsonByteLength = 0; featureTableBinaryByteLength = 0; console.warn(DEPRECATION_WARNING); } tile.header.featureTableJsonByteLength = featureTableJsonByteLength; tile.header.featureTableBinaryByteLength = featureTableBinaryByteLength; tile.header.batchTableJsonByteLength = batchTableJsonByteLength; tile.header.batchTableBinaryByteLength = batchTableBinaryByteLength; tile.header.batchLength = batchLength; return byteOffset; } function parse3DTileTablesSync(tile, arrayBuffer, byteOffset, options) { byteOffset = parse3DTileFeatureTable(tile, arrayBuffer, byteOffset, options); byteOffset = parse3DTileBatchTable(tile, arrayBuffer, byteOffset, options); return byteOffset; } function parse3DTileFeatureTable(tile, arrayBuffer, byteOffset, options) { const { featureTableJsonByteLength, featureTableBinaryByteLength, batchLength } = tile.header || {}; tile.featureTableJson = { BATCH_LENGTH: batchLength || 0 }; if (featureTableJsonByteLength && featureTableJsonByteLength > 0) { const featureTableString = getStringFromArrayBuffer(arrayBuffer, byteOffset, featureTableJsonByteLength); tile.featureTableJson = JSON.parse(featureTableString); } byteOffset += featureTableJsonByteLength || 0; tile.featureTableBinary = new Uint8Array(arrayBuffer, byteOffset, featureTableBinaryByteLength); byteOffset += featureTableBinaryByteLength || 0; return byteOffset; } function parse3DTileBatchTable(tile, arrayBuffer, byteOffset, options) { const { batchTableJsonByteLength, batchTableBinaryByteLength } = tile.header || {}; if (batchTableJsonByteLength && batchTableJsonByteLength > 0) { const batchTableString = getStringFromArrayBuffer(arrayBuffer, byteOffset, batchTableJsonByteLength); tile.batchTableJson = JSON.parse(batchTableString); byteOffset += batchTableJsonByteLength; if (batchTableBinaryByteLength && batchTableBinaryByteLength > 0) { tile.batchTableBinary = new Uint8Array(arrayBuffer, byteOffset, batchTableBinaryByteLength); tile.batchTableBinary = new Uint8Array(tile.batchTableBinary); byteOffset += batchTableBinaryByteLength; } } return byteOffset; } // ../../node_modules/@loaders.gl/3d-tiles/dist/lib/parsers/helpers/normalize-3d-tile-colors.js function normalize3DTileColorAttribute(tile, colors, batchTable) { if (!colors && (!tile || !tile.batchIds || !batchTable)) { return null; } const { batchIds, isRGB565, pointCount = 0 } = tile; if (batchIds && batchTable) { const colorArray = new Uint8ClampedArray(pointCount * 3); for (let i3 = 0; i3 < pointCount; i3++) { const batchId = batchIds[i3]; const dimensions = batchTable.getProperty(batchId, "dimensions"); const color = dimensions.map((d) => d * 255); colorArray[i3 * 3] = color[0]; colorArray[i3 * 3 + 1] = color[1]; colorArray[i3 * 3 + 2] = color[2]; } return { type: GL2.UNSIGNED_BYTE, value: colorArray, size: 3, normalized: true }; } if (colors && isRGB565) { const colorArray = new Uint8ClampedArray(pointCount * 3); for (let i3 = 0; i3 < pointCount; i3++) { const color = decodeRGB565(colors[i3]); colorArray[i3 * 3] = color[0]; colorArray[i3 * 3 + 1] = color[1]; colorArray[i3 * 3 + 2] = color[2]; } return { type: GL2.UNSIGNED_BYTE, value: colorArray, size: 3, normalized: true }; } if (colors && colors.length === pointCount * 3) { return { type: GL2.UNSIGNED_BYTE, value: colors, size: 3, normalized: true }; } return { type: GL2.UNSIGNED_BYTE, value: colors || new Uint8ClampedArray(), size: 4, normalized: true }; } // ../../node_modules/@loaders.gl/3d-tiles/dist/lib/parsers/helpers/normalize-3d-tile-normals.js var scratchNormal4 = new Vector3(); function normalize3DTileNormalAttribute(tile, normals) { if (!normals) { return null; } if (tile.isOctEncoded16P) { const decodedArray = new Float32Array((tile.pointsLength || 0) * 3); for (let i3 = 0; i3 < (tile.pointsLength || 0); i3++) { octDecode(normals[i3 * 2], normals[i3 * 2 + 1], scratchNormal4); scratchNormal4.toArray(decodedArray, i3 * 3); } return { type: GL2.FLOAT, size: 2, value: decodedArray }; } return { type: GL2.FLOAT, size: 2, value: normals }; } // ../../node_modules/@loaders.gl/3d-tiles/dist/lib/parsers/helpers/normalize-3d-tile-positions.js function normalize3DTilePositionAttribute(tile, positions, options) { if (!tile.isQuantized) { return positions; } if (options["3d-tiles"] && options["3d-tiles"].decodeQuantizedPositions) { tile.isQuantized = false; return decodeQuantizedPositions(tile, positions); } return { type: GL2.UNSIGNED_SHORT, value: positions, size: 3, normalized: true }; } function decodeQuantizedPositions(tile, positions) { const scratchPosition5 = new Vector3(); const decodedArray = new Float32Array(tile.pointCount * 3); for (let i3 = 0; i3 < tile.pointCount; i3++) { scratchPosition5.set(positions[i3 * 3], positions[i3 * 3 + 1], positions[i3 * 3 + 2]).scale(1 / tile.quantizedRange).multiply(tile.quantizedVolumeScale).add(tile.quantizedVolumeOffset).toArray(decodedArray, i3 * 3); } return decodedArray; } // ../../node_modules/@loaders.gl/3d-tiles/dist/lib/parsers/parse-3d-tile-point-cloud.js async function parsePointCloud3DTile(tile, arrayBuffer, byteOffset, options, context) { byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset); byteOffset = parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset); byteOffset = parse3DTileTablesSync(tile, arrayBuffer, byteOffset, options); initializeTile(tile); const { featureTable, batchTable } = parsePointCloudTables(tile); await parseDraco(tile, featureTable, batchTable, options, context); parsePositions(tile, featureTable, options); parseColors(tile, featureTable, batchTable); parseNormals(tile, featureTable); return byteOffset; } function initializeTile(tile) { tile.attributes = { positions: null, colors: null, normals: null, batchIds: null }; tile.isQuantized = false; tile.isTranslucent = false; tile.isRGB565 = false; tile.isOctEncoded16P = false; } function parsePointCloudTables(tile) { const featureTable = new Tile3DFeatureTable(tile.featureTableJson, tile.featureTableBinary); const pointsLength = featureTable.getGlobalProperty("POINTS_LENGTH"); if (!Number.isFinite(pointsLength)) { throw new Error("POINTS_LENGTH must be defined"); } featureTable.featuresLength = pointsLength; tile.featuresLength = pointsLength; tile.pointsLength = pointsLength; tile.pointCount = pointsLength; tile.rtcCenter = featureTable.getGlobalProperty("RTC_CENTER", GL2.FLOAT, 3); const batchTable = parseBatchIds(tile, featureTable); return { featureTable, batchTable }; } function parsePositions(tile, featureTable, options) { tile.attributes = tile.attributes || { positions: null, colors: null, normals: null, batchIds: null }; if (!tile.attributes.positions) { if (featureTable.hasProperty("POSITION")) { tile.attributes.positions = featureTable.getPropertyArray("POSITION", GL2.FLOAT, 3); } else if (featureTable.hasProperty("POSITION_QUANTIZED")) { const positions = featureTable.getPropertyArray("POSITION_QUANTIZED", GL2.UNSIGNED_SHORT, 3); tile.isQuantized = true; tile.quantizedRange = (1 << 16) - 1; tile.quantizedVolumeScale = featureTable.getGlobalProperty("QUANTIZED_VOLUME_SCALE", GL2.FLOAT, 3); if (!tile.quantizedVolumeScale) { throw new Error("QUANTIZED_VOLUME_SCALE must be defined for quantized positions."); } tile.quantizedVolumeOffset = featureTable.getGlobalProperty("QUANTIZED_VOLUME_OFFSET", GL2.FLOAT, 3); if (!tile.quantizedVolumeOffset) { throw new Error("QUANTIZED_VOLUME_OFFSET must be defined for quantized positions."); } tile.attributes.positions = normalize3DTilePositionAttribute(tile, positions, options); } } if (!tile.attributes.positions) { throw new Error("Either POSITION or POSITION_QUANTIZED must be defined."); } } function parseColors(tile, featureTable, batchTable) { tile.attributes = tile.attributes || { positions: null, colors: null, normals: null, batchIds: null }; if (!tile.attributes.colors) { let colors = null; if (featureTable.hasProperty("RGBA")) { colors = featureTable.getPropertyArray("RGBA", GL2.UNSIGNED_BYTE, 4); tile.isTranslucent = true; } else if (featureTable.hasProperty("RGB")) { colors = featureTable.getPropertyArray("RGB", GL2.UNSIGNED_BYTE, 3); } else if (featureTable.hasProperty("RGB565")) { colors = featureTable.getPropertyArray("RGB565", GL2.UNSIGNED_SHORT, 1); tile.isRGB565 = true; } tile.attributes.colors = normalize3DTileColorAttribute(tile, colors, batchTable); } if (featureTable.hasProperty("CONSTANT_RGBA")) { tile.constantRGBA = featureTable.getGlobalProperty("CONSTANT_RGBA", GL2.UNSIGNED_BYTE, 4); } } function parseNormals(tile, featureTable) { tile.attributes = tile.attributes || { positions: null, colors: null, normals: null, batchIds: null }; if (!tile.attributes.normals) { let normals = null; if (featureTable.hasProperty("NORMAL")) { normals = featureTable.getPropertyArray("NORMAL", GL2.FLOAT, 3); } else if (featureTable.hasProperty("NORMAL_OCT16P")) { normals = featureTable.getPropertyArray("NORMAL_OCT16P", GL2.UNSIGNED_BYTE, 2); tile.isOctEncoded16P = true; } tile.attributes.normals = normalize3DTileNormalAttribute(tile, normals); } } function parseBatchIds(tile, featureTable) { let batchTable = null; if (!tile.batchIds && featureTable.hasProperty("BATCH_ID")) { tile.batchIds = featureTable.getPropertyArray("BATCH_ID", GL2.UNSIGNED_SHORT, 1); if (tile.batchIds) { const batchFeatureLength = featureTable.getGlobalProperty("BATCH_LENGTH"); if (!batchFeatureLength) { throw new Error("Global property: BATCH_LENGTH must be defined when BATCH_ID is defined."); } const { batchTableJson, batchTableBinary } = tile; batchTable = new Tile3DBatchTableParser(batchTableJson, batchTableBinary, batchFeatureLength); } } return batchTable; } async function parseDraco(tile, featureTable, batchTable, options, context) { let dracoBuffer; let dracoFeatureTableProperties; let dracoBatchTableProperties; const batchTableDraco = tile.batchTableJson && tile.batchTableJson.extensions && tile.batchTableJson.extensions["3DTILES_draco_point_compression"]; if (batchTableDraco) { dracoBatchTableProperties = batchTableDraco.properties; } const featureTableDraco = featureTable.getExtension("3DTILES_draco_point_compression"); if (featureTableDraco) { dracoFeatureTableProperties = featureTableDraco.properties; const dracoByteOffset = featureTableDraco.byteOffset; const dracoByteLength = featureTableDraco.byteLength; if (!dracoFeatureTableProperties || !Number.isFinite(dracoByteOffset) || !dracoByteLength) { throw new Error("Draco properties, byteOffset, and byteLength must be defined"); } dracoBuffer = (tile.featureTableBinary || []).slice(dracoByteOffset, dracoByteOffset + dracoByteLength); tile.hasPositions = Number.isFinite(dracoFeatureTableProperties.POSITION); tile.hasColors = Number.isFinite(dracoFeatureTableProperties.RGB) || Number.isFinite(dracoFeatureTableProperties.RGBA); tile.hasNormals = Number.isFinite(dracoFeatureTableProperties.NORMAL); tile.hasBatchIds = Number.isFinite(dracoFeatureTableProperties.BATCH_ID); tile.isTranslucent = Number.isFinite(dracoFeatureTableProperties.RGBA); } if (!dracoBuffer) { return true; } const dracoData = { buffer: dracoBuffer, properties: { ...dracoFeatureTableProperties, ...dracoBatchTableProperties }, featureTableProperties: dracoFeatureTableProperties, batchTableProperties: dracoBatchTableProperties, dequantizeInShader: false }; return await loadDraco(tile, dracoData, options, context); } async function loadDraco(tile, dracoData, options, context) { if (!context) { return; } const dracoOptions = { ...options, draco: { ...options?.draco, extraAttributes: dracoData.batchTableProperties || {} } }; delete dracoOptions["3d-tiles"]; const data = await parseFromContext(dracoData.buffer, DracoLoader2, dracoOptions, context); const decodedPositions = data.attributes.POSITION && data.attributes.POSITION.value; const decodedColors = data.attributes.COLOR_0 && data.attributes.COLOR_0.value; const decodedNormals = data.attributes.NORMAL && data.attributes.NORMAL.value; const decodedBatchIds = data.attributes.BATCH_ID && data.attributes.BATCH_ID.value; const isQuantizedDraco = decodedPositions && data.attributes.POSITION.value.quantization; const isOctEncodedDraco = decodedNormals && data.attributes.NORMAL.value.quantization; if (isQuantizedDraco) { const quantization = data.POSITION.data.quantization; const range = quantization.range; tile.quantizedVolumeScale = new Vector3(range, range, range); tile.quantizedVolumeOffset = new Vector3(quantization.minValues); tile.quantizedRange = (1 << quantization.quantizationBits) - 1; tile.isQuantizedDraco = true; } if (isOctEncodedDraco) { tile.octEncodedRange = (1 << data.NORMAL.data.quantization.quantizationBits) - 1; tile.isOctEncodedDraco = true; } const batchTableAttributes = {}; if (dracoData.batchTableProperties) { for (const attributeName of Object.keys(dracoData.batchTableProperties)) { if (data.attributes[attributeName] && data.attributes[attributeName].value) { batchTableAttributes[attributeName.toLowerCase()] = data.attributes[attributeName].value; } } } tile.attributes = { positions: decodedPositions, colors: normalize3DTileColorAttribute(tile, decodedColors, void 0), normals: decodedNormals, batchIds: decodedBatchIds, ...batchTableAttributes }; } // ../../node_modules/@loaders.gl/gltf/dist/lib/extensions/EXT_mesh_features.js var EXT_mesh_features_exports = {}; __export(EXT_mesh_features_exports, { decode: () => decode, name: () => name }); // ../../node_modules/@loaders.gl/gltf/dist/lib/utils/assert.js function assert8(condition, message) { if (!condition) { throw new Error(message || "assert failed: gltf"); } } // ../../node_modules/@loaders.gl/gltf/dist/lib/gltf-utils/gltf-constants.js var COMPONENTS = { SCALAR: 1, VEC2: 2, VEC3: 3, VEC4: 4, MAT2: 4, MAT3: 9, MAT4: 16 }; var BYTES = { 5120: 1, 5121: 1, 5122: 2, 5123: 2, 5125: 4, 5126: 4 }; // ../../node_modules/@loaders.gl/gltf/dist/lib/gltf-utils/gltf-utils.js var MIPMAP_FACTOR = 1.33; var TYPES = ["SCALAR", "VEC2", "VEC3", "VEC4"]; var ARRAY_CONSTRUCTOR_TO_WEBGL_CONSTANT = [ [Int8Array, 5120], [Uint8Array, 5121], [Int16Array, 5122], [Uint16Array, 5123], [Uint32Array, 5125], [Float32Array, 5126], [Float64Array, 5130] ]; var ARRAY_TO_COMPONENT_TYPE = new Map(ARRAY_CONSTRUCTOR_TO_WEBGL_CONSTANT); var ATTRIBUTE_TYPE_TO_COMPONENTS = { SCALAR: 1, VEC2: 2, VEC3: 3, VEC4: 4, MAT2: 4, MAT3: 9, MAT4: 16 }; var ATTRIBUTE_COMPONENT_TYPE_TO_BYTE_SIZE = { 5120: 1, 5121: 1, 5122: 2, 5123: 2, 5125: 4, 5126: 4 }; var ATTRIBUTE_COMPONENT_TYPE_TO_ARRAY = { 5120: Int8Array, 5121: Uint8Array, 5122: Int16Array, 5123: Uint16Array, 5125: Uint32Array, 5126: Float32Array }; function getAccessorTypeFromSize(size) { const type = TYPES[size - 1]; return type || TYPES[0]; } function getComponentTypeFromArray(typedArray) { const componentType = ARRAY_TO_COMPONENT_TYPE.get(typedArray.constructor); if (!componentType) { throw new Error("Illegal typed array"); } return componentType; } function getAccessorArrayTypeAndLength(accessor, bufferView) { const ArrayType = ATTRIBUTE_COMPONENT_TYPE_TO_ARRAY[accessor.componentType]; const components = ATTRIBUTE_TYPE_TO_COMPONENTS[accessor.type]; const bytesPerComponent = ATTRIBUTE_COMPONENT_TYPE_TO_BYTE_SIZE[accessor.componentType]; const length5 = accessor.count * components; const byteLength = accessor.count * components * bytesPerComponent; assert8(byteLength >= 0 && byteLength <= bufferView.byteLength); const componentByteSize = BYTES[accessor.componentType]; const numberOfComponentsInElement = COMPONENTS[accessor.type]; return { ArrayType, length: length5, byteLength, componentByteSize, numberOfComponentsInElement }; } function getMemoryUsageGLTF(gltf) { let { images, bufferViews } = gltf; images = images || []; bufferViews = bufferViews || []; const imageBufferViews = images.map((i3) => i3.bufferView); bufferViews = bufferViews.filter((view) => !imageBufferViews.includes(view)); const bufferMemory = bufferViews.reduce((acc, view) => acc + view.byteLength, 0); const pixelCount = images.reduce((acc, image) => { const { width, height } = image.image; return acc + width * height; }, 0); return bufferMemory + Math.ceil(4 * pixelCount * MIPMAP_FACTOR); } // ../../node_modules/@loaders.gl/gltf/dist/lib/gltf-utils/get-typed-array.js function getTypedArrayForBufferView(json, buffers, bufferViewIndex) { const bufferView = json.bufferViews[bufferViewIndex]; assert8(bufferView); const bufferIndex = bufferView.buffer; const binChunk = buffers[bufferIndex]; assert8(binChunk); const byteOffset = (bufferView.byteOffset || 0) + binChunk.byteOffset; return new Uint8Array(binChunk.arrayBuffer, byteOffset, bufferView.byteLength); } function getTypedArrayForAccessor(json, buffers, accessor) { const gltfAccessor = typeof accessor === "number" ? json.accessors?.[accessor] : accessor; if (!gltfAccessor) { throw new Error(`No gltf accessor ${JSON.stringify(accessor)}`); } const bufferView = json.bufferViews?.[gltfAccessor.bufferView || 0]; if (!bufferView) { throw new Error(`No gltf buffer view for accessor ${bufferView}`); } const { arrayBuffer, byteOffset: bufferByteOffset } = buffers[bufferView.buffer]; const byteOffset = (bufferByteOffset || 0) + (gltfAccessor.byteOffset || 0) + (bufferView.byteOffset || 0); const { ArrayType, length: length5, componentByteSize, numberOfComponentsInElement } = getAccessorArrayTypeAndLength(gltfAccessor, bufferView); const elementByteSize = componentByteSize * numberOfComponentsInElement; const elementAddressScale = bufferView.byteStride || elementByteSize; if (typeof bufferView.byteStride === "undefined" || bufferView.byteStride === elementByteSize) { const result2 = new ArrayType(arrayBuffer, byteOffset, length5); return result2; } const result = new ArrayType(length5); for (let i3 = 0; i3 < gltfAccessor.count; i3++) { const values = new ArrayType(arrayBuffer, byteOffset + i3 * elementAddressScale, numberOfComponentsInElement); result.set(values, i3 * numberOfComponentsInElement); } return result; } // ../../node_modules/@loaders.gl/gltf/dist/lib/api/gltf-scenegraph.js function makeDefaultGLTFJson() { return { asset: { version: "2.0", generator: "loaders.gl" }, buffers: [], extensions: {}, extensionsRequired: [], extensionsUsed: [] }; } var GLTFScenegraph = class { gltf; sourceBuffers; byteLength; constructor(gltf) { this.gltf = { json: gltf?.json || makeDefaultGLTFJson(), buffers: gltf?.buffers || [], images: gltf?.images || [] }; this.sourceBuffers = []; this.byteLength = 0; if (this.gltf.buffers && this.gltf.buffers[0]) { this.byteLength = this.gltf.buffers[0].byteLength; this.sourceBuffers = [this.gltf.buffers[0]]; } } get json() { return this.gltf.json; } getApplicationData(key) { const data = this.json[key]; return data; } getExtraData(key) { const extras = this.json.extras || {}; return extras[key]; } hasExtension(extensionName) { const isUsedExtension = this.getUsedExtensions().find((name12) => name12 === extensionName); const isRequiredExtension = this.getRequiredExtensions().find((name12) => name12 === extensionName); return typeof isUsedExtension === "string" || typeof isRequiredExtension === "string"; } getExtension(extensionName) { const isExtension = this.getUsedExtensions().find((name12) => name12 === extensionName); const extensions = this.json.extensions || {}; return isExtension ? extensions[extensionName] : null; } getRequiredExtension(extensionName) { const isRequired = this.getRequiredExtensions().find((name12) => name12 === extensionName); return isRequired ? this.getExtension(extensionName) : null; } getRequiredExtensions() { return this.json.extensionsRequired || []; } getUsedExtensions() { return this.json.extensionsUsed || []; } getRemovedExtensions() { return this.json.extensionsRemoved || []; } getObjectExtension(object, extensionName) { const extensions = object.extensions || {}; return extensions[extensionName]; } getScene(index) { return this.getObject("scenes", index); } getNode(index) { return this.getObject("nodes", index); } getSkin(index) { return this.getObject("skins", index); } getMesh(index) { return this.getObject("meshes", index); } getMaterial(index) { return this.getObject("materials", index); } getAccessor(index) { return this.getObject("accessors", index); } getTexture(index) { return this.getObject("textures", index); } getSampler(index) { return this.getObject("samplers", index); } getImage(index) { return this.getObject("images", index); } getBufferView(index) { return this.getObject("bufferViews", index); } getBuffer(index) { return this.getObject("buffers", index); } getObject(array, index) { if (typeof index === "object") { return index; } const object = this.json[array] && this.json[array][index]; if (!object) { throw new Error(`glTF file error: Could not find ${array}[${index}]`); } return object; } getTypedArrayForBufferView(bufferView) { bufferView = this.getBufferView(bufferView); const bufferIndex = bufferView.buffer; const binChunk = this.gltf.buffers[bufferIndex]; assert8(binChunk); const byteOffset = (bufferView.byteOffset || 0) + binChunk.byteOffset; return new Uint8Array(binChunk.arrayBuffer, byteOffset, bufferView.byteLength); } getTypedArrayForAccessor(accessor) { const gltfAccessor = this.getAccessor(accessor); return getTypedArrayForAccessor(this.gltf.json, this.gltf.buffers, gltfAccessor); } getTypedArrayForImageData(image) { image = this.getAccessor(image); const bufferView = this.getBufferView(image.bufferView); const buffer = this.getBuffer(bufferView.buffer); const arrayBuffer = buffer.data; const byteOffset = bufferView.byteOffset || 0; return new Uint8Array(arrayBuffer, byteOffset, bufferView.byteLength); } addApplicationData(key, data) { this.json[key] = data; return this; } addExtraData(key, data) { this.json.extras = this.json.extras || {}; this.json.extras[key] = data; return this; } addObjectExtension(object, extensionName, data) { object.extensions = object.extensions || {}; object.extensions[extensionName] = data; this.registerUsedExtension(extensionName); return this; } setObjectExtension(object, extensionName, data) { const extensions = object.extensions || {}; extensions[extensionName] = data; } removeObjectExtension(object, extensionName) { const extensions = object?.extensions || {}; if (extensions[extensionName]) { this.json.extensionsRemoved = this.json.extensionsRemoved || []; const extensionsRemoved = this.json.extensionsRemoved; if (!extensionsRemoved.includes(extensionName)) { extensionsRemoved.push(extensionName); } } delete extensions[extensionName]; } addExtension(extensionName, extensionData = {}) { assert8(extensionData); this.json.extensions = this.json.extensions || {}; this.json.extensions[extensionName] = extensionData; this.registerUsedExtension(extensionName); return extensionData; } addRequiredExtension(extensionName, extensionData = {}) { assert8(extensionData); this.addExtension(extensionName, extensionData); this.registerRequiredExtension(extensionName); return extensionData; } registerUsedExtension(extensionName) { this.json.extensionsUsed = this.json.extensionsUsed || []; if (!this.json.extensionsUsed.find((ext) => ext === extensionName)) { this.json.extensionsUsed.push(extensionName); } } registerRequiredExtension(extensionName) { this.registerUsedExtension(extensionName); this.json.extensionsRequired = this.json.extensionsRequired || []; if (!this.json.extensionsRequired.find((ext) => ext === extensionName)) { this.json.extensionsRequired.push(extensionName); } } removeExtension(extensionName) { if (this.json.extensions?.[extensionName]) { this.json.extensionsRemoved = this.json.extensionsRemoved || []; const extensionsRemoved = this.json.extensionsRemoved; if (!extensionsRemoved.includes(extensionName)) { extensionsRemoved.push(extensionName); } } if (this.json.extensions) { delete this.json.extensions[extensionName]; } if (this.json.extensionsRequired) { this._removeStringFromArray(this.json.extensionsRequired, extensionName); } if (this.json.extensionsUsed) { this._removeStringFromArray(this.json.extensionsUsed, extensionName); } } setDefaultScene(sceneIndex) { this.json.scene = sceneIndex; } addScene(scene) { const { nodeIndices } = scene; this.json.scenes = this.json.scenes || []; this.json.scenes.push({ nodes: nodeIndices }); return this.json.scenes.length - 1; } addNode(node) { const { meshIndex, matrix } = node; this.json.nodes = this.json.nodes || []; const nodeData = { mesh: meshIndex }; if (matrix) { nodeData.matrix = matrix; } this.json.nodes.push(nodeData); return this.json.nodes.length - 1; } addMesh(mesh) { const { attributes, indices, material, mode = 4 } = mesh; const accessors = this._addAttributes(attributes); const glTFMesh = { primitives: [ { attributes: accessors, mode } ] }; if (indices) { const indicesAccessor = this._addIndices(indices); glTFMesh.primitives[0].indices = indicesAccessor; } if (Number.isFinite(material)) { glTFMesh.primitives[0].material = material; } this.json.meshes = this.json.meshes || []; this.json.meshes.push(glTFMesh); return this.json.meshes.length - 1; } addPointCloud(attributes) { const accessorIndices = this._addAttributes(attributes); const glTFMesh = { primitives: [ { attributes: accessorIndices, mode: 0 } ] }; this.json.meshes = this.json.meshes || []; this.json.meshes.push(glTFMesh); return this.json.meshes.length - 1; } addImage(imageData, mimeTypeOpt) { const metadata = getBinaryImageMetadata(imageData); const mimeType = mimeTypeOpt || metadata?.mimeType; const bufferViewIndex = this.addBufferView(imageData); const glTFImage = { bufferView: bufferViewIndex, mimeType }; this.json.images = this.json.images || []; this.json.images.push(glTFImage); return this.json.images.length - 1; } addBufferView(buffer, bufferIndex = 0, byteOffset = this.byteLength) { const byteLength = buffer.byteLength; assert8(Number.isFinite(byteLength)); this.sourceBuffers = this.sourceBuffers || []; this.sourceBuffers.push(buffer); const glTFBufferView = { buffer: bufferIndex, byteOffset, byteLength }; this.byteLength += padToNBytes(byteLength, 4); this.json.bufferViews = this.json.bufferViews || []; this.json.bufferViews.push(glTFBufferView); return this.json.bufferViews.length - 1; } addAccessor(bufferViewIndex, accessor) { const glTFAccessor = { bufferView: bufferViewIndex, type: getAccessorTypeFromSize(accessor.size), componentType: accessor.componentType, count: accessor.count, max: accessor.max, min: accessor.min }; this.json.accessors = this.json.accessors || []; this.json.accessors.push(glTFAccessor); return this.json.accessors.length - 1; } addBinaryBuffer(sourceBuffer, accessor = { size: 3 }) { const bufferViewIndex = this.addBufferView(sourceBuffer); let minMax = { min: accessor.min, max: accessor.max }; if (!minMax.min || !minMax.max) { minMax = this._getAccessorMinMax(sourceBuffer, accessor.size); } const accessorDefaults = { size: accessor.size, componentType: getComponentTypeFromArray(sourceBuffer), count: Math.round(sourceBuffer.length / accessor.size), min: minMax.min, max: minMax.max }; return this.addAccessor(bufferViewIndex, Object.assign(accessorDefaults, accessor)); } addTexture(texture) { const { imageIndex } = texture; const glTFTexture = { source: imageIndex }; this.json.textures = this.json.textures || []; this.json.textures.push(glTFTexture); return this.json.textures.length - 1; } addMaterial(pbrMaterialInfo) { this.json.materials = this.json.materials || []; this.json.materials.push(pbrMaterialInfo); return this.json.materials.length - 1; } createBinaryChunk() { this.gltf.buffers = []; const totalByteLength = this.byteLength; const arrayBuffer = new ArrayBuffer(totalByteLength); const targetArray = new Uint8Array(arrayBuffer); let dstByteOffset = 0; for (const sourceBuffer of this.sourceBuffers || []) { dstByteOffset = copyToArray(sourceBuffer, targetArray, dstByteOffset); } if (this.json?.buffers?.[0]) { this.json.buffers[0].byteLength = totalByteLength; } else { this.json.buffers = [{ byteLength: totalByteLength }]; } this.gltf.binary = arrayBuffer; this.sourceBuffers = [arrayBuffer]; } _removeStringFromArray(array, string) { let found = true; while (found) { const index = array.indexOf(string); if (index > -1) { array.splice(index, 1); } else { found = false; } } } _addAttributes(attributes = {}) { const result = {}; for (const attributeKey in attributes) { const attributeData = attributes[attributeKey]; const attrName = this._getGltfAttributeName(attributeKey); const accessor = this.addBinaryBuffer(attributeData.value, attributeData); result[attrName] = accessor; } return result; } _addIndices(indices) { return this.addBinaryBuffer(indices, { size: 1 }); } _getGltfAttributeName(attributeName) { switch (attributeName.toLowerCase()) { case "position": case "positions": case "vertices": return "POSITION"; case "normal": case "normals": return "NORMAL"; case "color": case "colors": return "COLOR_0"; case "texcoord": case "texcoords": return "TEXCOORD_0"; default: return attributeName; } } _getAccessorMinMax(buffer, size) { const result = { min: null, max: null }; if (buffer.length < size) { return result; } result.min = []; result.max = []; const initValues = buffer.subarray(0, size); for (const value of initValues) { result.min.push(value); result.max.push(value); } for (let index = size; index < buffer.length; index += size) { for (let componentIndex = 0; componentIndex < size; componentIndex++) { result.min[0 + componentIndex] = Math.min( result.min[0 + componentIndex], buffer[index + componentIndex] ); result.max[0 + componentIndex] = Math.max( result.max[0 + componentIndex], buffer[index + componentIndex] ); } } return result; } }; // ../../node_modules/@loaders.gl/gltf/dist/lib/extensions/utils/3d-tiles-utils.js function emod(n2) { return (n2 % 1 + 1) % 1; } var ATTRIBUTE_TYPE_TO_COMPONENTS2 = { SCALAR: 1, VEC2: 2, VEC3: 3, VEC4: 4, MAT2: 4, MAT3: 9, MAT4: 16, BOOLEAN: 1, STRING: 1, ENUM: 1 }; var ATTRIBUTE_COMPONENT_TYPE_TO_ARRAY2 = { INT8: Int8Array, UINT8: Uint8Array, INT16: Int16Array, UINT16: Uint16Array, INT32: Int32Array, UINT32: Uint32Array, INT64: BigInt64Array, UINT64: BigUint64Array, FLOAT32: Float32Array, FLOAT64: Float64Array }; var ATTRIBUTE_COMPONENT_TYPE_TO_BYTE_SIZE2 = { INT8: 1, UINT8: 1, INT16: 2, UINT16: 2, INT32: 4, UINT32: 4, INT64: 8, UINT64: 8, FLOAT32: 4, FLOAT64: 8 }; function getArrayElementByteSize(attributeType, componentType) { return ATTRIBUTE_COMPONENT_TYPE_TO_BYTE_SIZE2[componentType] * ATTRIBUTE_TYPE_TO_COMPONENTS2[attributeType]; } function getOffsetsForProperty(scenegraph, bufferViewIndex, offsetType, numberOfElements) { if (offsetType !== "UINT8" && offsetType !== "UINT16" && offsetType !== "UINT32" && offsetType !== "UINT64") { return null; } const arrayOffsetsBytes = scenegraph.getTypedArrayForBufferView(bufferViewIndex); const arrayOffsets = convertRawBufferToMetadataArray( arrayOffsetsBytes, "SCALAR", offsetType, numberOfElements + 1 ); if (arrayOffsets instanceof BigInt64Array || arrayOffsets instanceof BigUint64Array) { return null; } return arrayOffsets; } function convertRawBufferToMetadataArray(data, attributeType, componentType, elementCount = 1) { const numberOfComponents = ATTRIBUTE_TYPE_TO_COMPONENTS2[attributeType]; const ArrayType = ATTRIBUTE_COMPONENT_TYPE_TO_ARRAY2[componentType]; const size = ATTRIBUTE_COMPONENT_TYPE_TO_BYTE_SIZE2[componentType]; const length5 = elementCount * numberOfComponents; const byteLength = length5 * size; let buffer = data.buffer; let offset = data.byteOffset; if (offset % size !== 0) { const bufferArray = new Uint8Array(buffer); buffer = bufferArray.slice(offset, offset + byteLength).buffer; offset = 0; } return new ArrayType(buffer, offset, length5); } function getPrimitiveTextureData(scenegraph, textureInfo, primitive) { const texCoordAccessorKey = `TEXCOORD_${textureInfo.texCoord || 0}`; const texCoordAccessorIndex = primitive.attributes[texCoordAccessorKey]; const textureCoordinates = scenegraph.getTypedArrayForAccessor(texCoordAccessorIndex); const json = scenegraph.gltf.json; const textureIndex = textureInfo.index; const imageIndex = json.textures?.[textureIndex]?.source; if (typeof imageIndex !== "undefined") { const mimeType = json.images?.[imageIndex]?.mimeType; const parsedImage = scenegraph.gltf.images?.[imageIndex]; if (parsedImage && typeof parsedImage.width !== "undefined") { const textureData = []; for (let index = 0; index < textureCoordinates.length; index += 2) { const value = getImageValueByCoordinates(parsedImage, mimeType, textureCoordinates, index, textureInfo.channels); textureData.push(value); } return textureData; } } return []; } function primitivePropertyDataToAttributes(scenegraph, attributeName, propertyData, featureTable, primitive) { if (!propertyData?.length) { return; } const featureIndices = []; for (const texelData of propertyData) { let index = featureTable.findIndex((item) => item === texelData); if (index === -1) { index = featureTable.push(texelData) - 1; } featureIndices.push(index); } const typedArray = new Uint32Array(featureIndices); const bufferIndex = scenegraph.gltf.buffers.push({ arrayBuffer: typedArray.buffer, byteOffset: typedArray.byteOffset, byteLength: typedArray.byteLength }) - 1; const bufferViewIndex = scenegraph.addBufferView(typedArray, bufferIndex, 0); const accessorIndex = scenegraph.addAccessor(bufferViewIndex, { size: 1, componentType: getComponentTypeFromArray(typedArray), count: typedArray.length }); primitive.attributes[attributeName] = accessorIndex; } function getImageValueByCoordinates(parsedImage, mimeType, textureCoordinates, index, channels = [0]) { const CHANNELS_MAP = { r: { offset: 0, shift: 0 }, g: { offset: 1, shift: 8 }, b: { offset: 2, shift: 16 }, a: { offset: 3, shift: 24 } }; const u = textureCoordinates[index]; const v = textureCoordinates[index + 1]; let components = 1; if (mimeType && (mimeType.indexOf("image/jpeg") !== -1 || mimeType.indexOf("image/png") !== -1)) components = 4; const offset = coordinatesToOffset(u, v, parsedImage, components); let value = 0; for (const c of channels) { const map2 = typeof c === "number" ? Object.values(CHANNELS_MAP)[c] : CHANNELS_MAP[c]; const imageOffset = offset + map2.offset; const imageData = getImageData(parsedImage); if (imageData.data.length <= imageOffset) { throw new Error(`${imageData.data.length} <= ${imageOffset}`); } const imageValue = imageData.data[imageOffset]; value |= imageValue << map2.shift; } return value; } function coordinatesToOffset(u, v, parsedImage, componentsCount = 1) { const w = parsedImage.width; const iX = emod(u) * (w - 1); const indX = Math.round(iX); const h = parsedImage.height; const iY = emod(v) * (h - 1); const indY = Math.round(iY); const components = parsedImage.components ? parsedImage.components : componentsCount; const offset = (indY * w + indX) * components; return offset; } function parseVariableLengthArrayNumeric(valuesData, numberOfElements, arrayOffsets, valuesDataBytesLength, valueSize) { const attributeValueArray = []; for (let index = 0; index < numberOfElements; index++) { const arrayOffset = arrayOffsets[index]; const arrayByteSize = arrayOffsets[index + 1] - arrayOffsets[index]; if (arrayByteSize + arrayOffset > valuesDataBytesLength) { break; } const typedArrayOffset = arrayOffset / valueSize; const elementCount = arrayByteSize / valueSize; attributeValueArray.push(valuesData.slice(typedArrayOffset, typedArrayOffset + elementCount)); } return attributeValueArray; } function parseFixedLengthArrayNumeric(valuesData, numberOfElements, arrayCount) { const attributeValueArray = []; for (let index = 0; index < numberOfElements; index++) { const elementOffset = index * arrayCount; attributeValueArray.push(valuesData.slice(elementOffset, elementOffset + arrayCount)); } return attributeValueArray; } function getPropertyDataString(numberOfElements, valuesDataBytes, arrayOffsets, stringOffsets) { if (arrayOffsets) { throw new Error("Not implemented - arrayOffsets for strings is specified"); } if (stringOffsets) { const stringsArray = []; const textDecoder = new TextDecoder("utf8"); let stringOffset = 0; for (let index = 0; index < numberOfElements; index++) { const stringByteSize = stringOffsets[index + 1] - stringOffsets[index]; if (stringByteSize + stringOffset <= valuesDataBytes.length) { const stringData = valuesDataBytes.subarray(stringOffset, stringByteSize + stringOffset); const stringAttribute = textDecoder.decode(stringData); stringsArray.push(stringAttribute); stringOffset += stringByteSize; } } return stringsArray; } return []; } // ../../node_modules/@loaders.gl/gltf/dist/lib/extensions/EXT_mesh_features.js var EXT_MESH_FEATURES_NAME = "EXT_mesh_features"; var name = EXT_MESH_FEATURES_NAME; async function decode(gltfData, options) { const scenegraph = new GLTFScenegraph(gltfData); decodeExtMeshFeatures(scenegraph, options); } function decodeExtMeshFeatures(scenegraph, options) { const json = scenegraph.gltf.json; if (!json.meshes) { return; } for (const mesh of json.meshes) { for (const primitive of mesh.primitives) { processMeshPrimitiveFeatures(scenegraph, primitive, options); } } } function processMeshPrimitiveFeatures(scenegraph, primitive, options) { if (!options?.gltf?.loadBuffers) { return; } const extension = primitive.extensions?.[EXT_MESH_FEATURES_NAME]; const featureIds = extension?.featureIds; if (!featureIds) { return; } for (const featureId of featureIds) { let featureIdData; if (typeof featureId.attribute !== "undefined") { const accessorKey = `_FEATURE_ID_${featureId.attribute}`; const accessorIndex = primitive.attributes[accessorKey]; featureIdData = scenegraph.getTypedArrayForAccessor(accessorIndex); } else if (typeof featureId.texture !== "undefined" && options?.gltf?.loadImages) { featureIdData = getPrimitiveTextureData(scenegraph, featureId.texture, primitive); } else { featureIdData = []; } featureId.data = featureIdData; } } // ../../node_modules/@loaders.gl/gltf/dist/lib/extensions/EXT_structural_metadata.js var EXT_structural_metadata_exports = {}; __export(EXT_structural_metadata_exports, { decode: () => decode2, name: () => name2 }); var EXT_STRUCTURAL_METADATA_NAME = "EXT_structural_metadata"; var name2 = EXT_STRUCTURAL_METADATA_NAME; async function decode2(gltfData, options) { const scenegraph = new GLTFScenegraph(gltfData); decodeExtStructuralMetadata(scenegraph, options); } function decodeExtStructuralMetadata(scenegraph, options) { if (!options.gltf?.loadBuffers) { return; } const extension = scenegraph.getExtension(EXT_STRUCTURAL_METADATA_NAME); if (!extension) { return; } if (options.gltf?.loadImages) { decodePropertyTextures(scenegraph, extension); } decodePropertyTables(scenegraph, extension); } function decodePropertyTextures(scenegraph, extension) { const propertyTextures = extension.propertyTextures; const json = scenegraph.gltf.json; if (propertyTextures && json.meshes) { for (const mesh of json.meshes) { for (const primitive of mesh.primitives) { processPrimitivePropertyTextures(scenegraph, propertyTextures, primitive, extension); } } } } function decodePropertyTables(scenegraph, extension) { const schema = extension.schema; if (!schema) { return; } const schemaClasses = schema.classes; const propertyTables = extension.propertyTables; if (schemaClasses && propertyTables) { for (const schemaName in schemaClasses) { const propertyTable = findPropertyTableByClass(propertyTables, schemaName); if (propertyTable) { processPropertyTable(scenegraph, schema, propertyTable); } } } } function findPropertyTableByClass(propertyTables, schemaClassName) { for (const propertyTable of propertyTables) { if (propertyTable.class === schemaClassName) { return propertyTable; } } return null; } function processPrimitivePropertyTextures(scenegraph, propertyTextures, primitive, extension) { if (!propertyTextures) { return; } const primitiveExtension = primitive.extensions?.[EXT_STRUCTURAL_METADATA_NAME]; const primitivePropertyTextureIndices = primitiveExtension?.propertyTextures; if (!primitivePropertyTextureIndices) { return; } for (const primitivePropertyTextureIndex of primitivePropertyTextureIndices) { const propertyTexture = propertyTextures[primitivePropertyTextureIndex]; processPrimitivePropertyTexture(scenegraph, propertyTexture, primitive, extension); } } function processPrimitivePropertyTexture(scenegraph, propertyTexture, primitive, extension) { if (!propertyTexture.properties) { return; } if (!extension.dataAttributeNames) { extension.dataAttributeNames = []; } const className = propertyTexture.class; for (const propertyName in propertyTexture.properties) { const attributeName = `${className}_${propertyName}`; const textureInfoTopLevel = propertyTexture.properties?.[propertyName]; if (!textureInfoTopLevel) { continue; } if (!textureInfoTopLevel.data) { textureInfoTopLevel.data = []; } const featureTextureTable = textureInfoTopLevel.data; const propertyData = getPrimitiveTextureData(scenegraph, textureInfoTopLevel, primitive); if (propertyData === null) { continue; } primitivePropertyDataToAttributes(scenegraph, attributeName, propertyData, featureTextureTable, primitive); textureInfoTopLevel.data = featureTextureTable; extension.dataAttributeNames.push(attributeName); } } function processPropertyTable(scenegraph, schema, propertyTable) { const schemaClass = schema.classes?.[propertyTable.class]; if (!schemaClass) { throw new Error(`Incorrect data in the EXT_structural_metadata extension: no schema class with name ${propertyTable.class}`); } const numberOfElements = propertyTable.count; for (const propertyName in schemaClass.properties) { const classProperty = schemaClass.properties[propertyName]; const propertyTableProperty = propertyTable.properties?.[propertyName]; if (propertyTableProperty) { const data = getPropertyDataFromBinarySource(scenegraph, schema, classProperty, numberOfElements, propertyTableProperty); propertyTableProperty.data = data; } } } function getPropertyDataFromBinarySource(scenegraph, schema, classProperty, numberOfElements, propertyTableProperty) { let data = []; const valuesBufferView = propertyTableProperty.values; const valuesDataBytes = scenegraph.getTypedArrayForBufferView(valuesBufferView); const arrayOffsets = getArrayOffsetsForProperty(scenegraph, classProperty, propertyTableProperty, numberOfElements); const stringOffsets = getStringOffsetsForProperty(scenegraph, propertyTableProperty, numberOfElements); switch (classProperty.type) { case "SCALAR": case "VEC2": case "VEC3": case "VEC4": case "MAT2": case "MAT3": case "MAT4": { data = getPropertyDataNumeric(classProperty, numberOfElements, valuesDataBytes, arrayOffsets); break; } case "BOOLEAN": { throw new Error(`Not implemented - classProperty.type=${classProperty.type}`); } case "STRING": { data = getPropertyDataString(numberOfElements, valuesDataBytes, arrayOffsets, stringOffsets); break; } case "ENUM": { data = getPropertyDataENUM(schema, classProperty, numberOfElements, valuesDataBytes, arrayOffsets); break; } default: throw new Error(`Unknown classProperty type ${classProperty.type}`); } return data; } function getArrayOffsetsForProperty(scenegraph, classProperty, propertyTableProperty, numberOfElements) { if (classProperty.array && typeof classProperty.count === "undefined" && typeof propertyTableProperty.arrayOffsets !== "undefined") { return getOffsetsForProperty(scenegraph, propertyTableProperty.arrayOffsets, propertyTableProperty.arrayOffsetType || "UINT32", numberOfElements); } return null; } function getStringOffsetsForProperty(scenegraph, propertyTableProperty, numberOfElements) { if (typeof propertyTableProperty.stringOffsets !== "undefined") { return getOffsetsForProperty(scenegraph, propertyTableProperty.stringOffsets, propertyTableProperty.stringOffsetType || "UINT32", numberOfElements); } return null; } function getPropertyDataNumeric(classProperty, numberOfElements, valuesDataBytes, arrayOffsets) { const isArray2 = classProperty.array; const arrayCount = classProperty.count; const elementSize = getArrayElementByteSize(classProperty.type, classProperty.componentType); const elementCount = valuesDataBytes.byteLength / elementSize; let valuesData; if (classProperty.componentType) { valuesData = convertRawBufferToMetadataArray( valuesDataBytes, classProperty.type, classProperty.componentType, elementCount ); } else { valuesData = valuesDataBytes; } if (isArray2) { if (arrayOffsets) { return parseVariableLengthArrayNumeric(valuesData, numberOfElements, arrayOffsets, valuesDataBytes.length, elementSize); } if (arrayCount) { return parseFixedLengthArrayNumeric(valuesData, numberOfElements, arrayCount); } return []; } return valuesData; } function getPropertyDataENUM(schema, classProperty, numberOfElements, valuesDataBytes, arrayOffsets) { const enumType = classProperty.enumType; if (!enumType) { throw new Error("Incorrect data in the EXT_structural_metadata extension: classProperty.enumType is not set for type ENUM"); } const enumEntry = schema.enums?.[enumType]; if (!enumEntry) { throw new Error(`Incorrect data in the EXT_structural_metadata extension: schema.enums does't contain ${enumType}`); } const enumValueType = enumEntry.valueType || "UINT16"; const elementSize = getArrayElementByteSize(classProperty.type, enumValueType); const elementCount = valuesDataBytes.byteLength / elementSize; let valuesData = convertRawBufferToMetadataArray(valuesDataBytes, classProperty.type, enumValueType, elementCount); if (!valuesData) { valuesData = valuesDataBytes; } if (classProperty.array) { if (arrayOffsets) { return parseVariableLengthArrayENUM({ valuesData, numberOfElements, arrayOffsets, valuesDataBytesLength: valuesDataBytes.length, elementSize, enumEntry }); } const arrayCount = classProperty.count; if (arrayCount) { return parseFixedLengthArrayENUM(valuesData, numberOfElements, arrayCount, enumEntry); } return []; } return getEnumsArray(valuesData, 0, numberOfElements, enumEntry); } function parseVariableLengthArrayENUM(params) { const { valuesData, numberOfElements, arrayOffsets, valuesDataBytesLength, elementSize, enumEntry } = params; const attributeValueArray = []; for (let index = 0; index < numberOfElements; index++) { const arrayOffset = arrayOffsets[index]; const arrayByteSize = arrayOffsets[index + 1] - arrayOffsets[index]; if (arrayByteSize + arrayOffset > valuesDataBytesLength) { break; } const typedArrayOffset = arrayOffset / elementSize; const elementCount = arrayByteSize / elementSize; const array = getEnumsArray(valuesData, typedArrayOffset, elementCount, enumEntry); attributeValueArray.push(array); } return attributeValueArray; } function parseFixedLengthArrayENUM(valuesData, numberOfElements, arrayCount, enumEntry) { const attributeValueArray = []; for (let index = 0; index < numberOfElements; index++) { const elementOffset = arrayCount * index; const array = getEnumsArray(valuesData, elementOffset, arrayCount, enumEntry); attributeValueArray.push(array); } return attributeValueArray; } function getEnumsArray(valuesData, offset, count, enumEntry) { const array = []; for (let i3 = 0; i3 < count; i3++) { if (valuesData instanceof BigInt64Array || valuesData instanceof BigUint64Array) { array.push(""); } else { const value = valuesData[offset + i3]; const enumObject = getEnumByValue(enumEntry, value); if (enumObject) { array.push(enumObject.name); } else { array.push(""); } } } return array; } function getEnumByValue(enumEntry, value) { for (const enumValue of enumEntry.values) { if (enumValue.value === value) { return enumValue; } } return null; } // ../../node_modules/@loaders.gl/gltf/dist/lib/extensions/deprecated/EXT_feature_metadata.js var EXT_feature_metadata_exports = {}; __export(EXT_feature_metadata_exports, { decode: () => decode3, name: () => name3 }); var EXT_FEATURE_METADATA_NAME = "EXT_feature_metadata"; var name3 = EXT_FEATURE_METADATA_NAME; async function decode3(gltfData, options) { const scenegraph = new GLTFScenegraph(gltfData); decodeExtFeatureMetadata(scenegraph, options); } function decodeExtFeatureMetadata(scenegraph, options) { if (!options.gltf?.loadBuffers) { return; } const extension = scenegraph.getExtension(EXT_FEATURE_METADATA_NAME); if (!extension) { return; } if (options.gltf?.loadImages) { decodePropertyTextures2(scenegraph, extension); } decodePropertyTables2(scenegraph, extension); } function decodePropertyTextures2(scenegraph, extension) { const schema = extension.schema; if (!schema) { return; } const schemaClasses = schema.classes; const { featureTextures } = extension; if (schemaClasses && featureTextures) { for (const schemaName in schemaClasses) { const schemaClass = schemaClasses[schemaName]; const featureTexture = findFeatureTextureByClass(featureTextures, schemaName); if (featureTexture) { handleFeatureTextureProperties(scenegraph, featureTexture, schemaClass); } } } } function decodePropertyTables2(scenegraph, extension) { const schema = extension.schema; if (!schema) { return; } const schemaClasses = schema.classes; const propertyTables = extension.featureTables; if (schemaClasses && propertyTables) { for (const schemaName in schemaClasses) { const propertyTable = findPropertyTableByClass2(propertyTables, schemaName); if (propertyTable) { processPropertyTable2(scenegraph, schema, propertyTable); } } } } function findPropertyTableByClass2(propertyTables, schemaClassName) { for (const propertyTableName in propertyTables) { const propertyTable = propertyTables[propertyTableName]; if (propertyTable.class === schemaClassName) { return propertyTable; } } return null; } function findFeatureTextureByClass(featureTextures, schemaClassName) { for (const featureTexturesName in featureTextures) { const featureTable = featureTextures[featureTexturesName]; if (featureTable.class === schemaClassName) { return featureTable; } } return null; } function processPropertyTable2(scenegraph, schema, propertyTable) { if (!propertyTable.class) { return; } const schemaClass = schema.classes?.[propertyTable.class]; if (!schemaClass) { throw new Error(`Incorrect data in the EXT_structural_metadata extension: no schema class with name ${propertyTable.class}`); } const numberOfElements = propertyTable.count; for (const propertyName in schemaClass.properties) { const classProperty = schemaClass.properties[propertyName]; const propertyTableProperty = propertyTable.properties?.[propertyName]; if (propertyTableProperty) { const data = getPropertyDataFromBinarySource2(scenegraph, schema, classProperty, numberOfElements, propertyTableProperty); propertyTableProperty.data = data; } } } function handleFeatureTextureProperties(scenegraph, featureTexture, schemaClass) { const attributeName = featureTexture.class; for (const propertyName in schemaClass.properties) { const featureTextureProperty = featureTexture?.properties?.[propertyName]; if (featureTextureProperty) { const data = getPropertyDataFromTexture(scenegraph, featureTextureProperty, attributeName); featureTextureProperty.data = data; } } } function getPropertyDataFromBinarySource2(scenegraph, schema, classProperty, numberOfFeatures, featureTableProperty) { let data = []; const bufferView = featureTableProperty.bufferView; const dataArray = scenegraph.getTypedArrayForBufferView(bufferView); const arrayOffsets = getArrayOffsetsForProperty2(scenegraph, classProperty, featureTableProperty, numberOfFeatures); const stringOffsets = getStringOffsetsForProperty2(scenegraph, classProperty, featureTableProperty, numberOfFeatures); if (classProperty.type === "STRING" || classProperty.componentType === "STRING") { data = getPropertyDataString(numberOfFeatures, dataArray, arrayOffsets, stringOffsets); } else if (isNumericProperty(classProperty)) { data = getPropertyDataNumeric2(classProperty, numberOfFeatures, dataArray, arrayOffsets); } return data; } function getArrayOffsetsForProperty2(scenegraph, classProperty, propertyTableProperty, numberOfElements) { if (classProperty.type === "ARRAY" && typeof classProperty.componentCount === "undefined" && typeof propertyTableProperty.arrayOffsetBufferView !== "undefined") { return getOffsetsForProperty( scenegraph, propertyTableProperty.arrayOffsetBufferView, propertyTableProperty.offsetType || "UINT32", numberOfElements ); } return null; } function getStringOffsetsForProperty2(scenegraph, classProperty, propertyTableProperty, numberOfElements) { if (typeof propertyTableProperty.stringOffsetBufferView !== "undefined") { return getOffsetsForProperty( scenegraph, propertyTableProperty.stringOffsetBufferView, propertyTableProperty.offsetType || "UINT32", numberOfElements ); } return null; } function isNumericProperty(schemaProperty) { const types = [ "UINT8", "INT16", "UINT16", "INT32", "UINT32", "INT64", "UINT64", "FLOAT32", "FLOAT64" ]; return types.includes(schemaProperty.type) || typeof schemaProperty.componentType !== "undefined" && types.includes(schemaProperty.componentType); } function getPropertyDataNumeric2(classProperty, numberOfElements, valuesDataBytes, arrayOffsets) { const isArray2 = classProperty.type === "ARRAY"; const arrayCount = classProperty.componentCount; const attributeType = "SCALAR"; const componentType = classProperty.componentType || classProperty.type; const elementSize = getArrayElementByteSize(attributeType, componentType); const elementCount = valuesDataBytes.byteLength / elementSize; const valuesData = convertRawBufferToMetadataArray(valuesDataBytes, attributeType, componentType, elementCount); if (isArray2) { if (arrayOffsets) { return parseVariableLengthArrayNumeric(valuesData, numberOfElements, arrayOffsets, valuesDataBytes.length, elementSize); } if (arrayCount) { return parseFixedLengthArrayNumeric(valuesData, numberOfElements, arrayCount); } return []; } return valuesData; } function getPropertyDataFromTexture(scenegraph, featureTextureProperty, attributeName) { const json = scenegraph.gltf.json; if (!json.meshes) { return []; } const featureTextureTable = []; for (const mesh of json.meshes) { for (const primitive of mesh.primitives) { processPrimitiveTextures(scenegraph, attributeName, featureTextureProperty, featureTextureTable, primitive); } } return featureTextureTable; } function processPrimitiveTextures(scenegraph, attributeName, featureTextureProperty, featureTextureTable, primitive) { const textureInfoTopLevel = { channels: featureTextureProperty.channels, ...featureTextureProperty.texture }; const propertyData = getPrimitiveTextureData(scenegraph, textureInfoTopLevel, primitive); if (!propertyData) { return; } primitivePropertyDataToAttributes(scenegraph, attributeName, propertyData, featureTextureTable, primitive); } // ../../node_modules/@loaders.gl/gltf/dist/lib/utils/version.js var VERSION10 = true ? "4.2.0-beta.2" : "latest"; // ../../node_modules/@loaders.gl/gltf/dist/lib/parsers/parse-glb.js var LITTLE_ENDIAN2 = true; var MAGIC_glTF = 1735152710; var GLB_FILE_HEADER_SIZE = 12; var GLB_CHUNK_HEADER_SIZE = 8; var GLB_CHUNK_TYPE_JSON = 1313821514; var GLB_CHUNK_TYPE_BIN = 5130562; var GLB_V1_CONTENT_FORMAT_JSON = 0; var GLB_CHUNK_TYPE_JSON_XVIZ_DEPRECATED = 0; var GLB_CHUNK_TYPE_BIX_XVIZ_DEPRECATED = 1; function getMagicString3(dataView, byteOffset = 0) { return `${String.fromCharCode(dataView.getUint8(byteOffset + 0))}${String.fromCharCode(dataView.getUint8(byteOffset + 1))}${String.fromCharCode(dataView.getUint8(byteOffset + 2))}${String.fromCharCode(dataView.getUint8(byteOffset + 3))}`; } function isGLB(arrayBuffer, byteOffset = 0, options = {}) { const dataView = new DataView(arrayBuffer); const { magic = MAGIC_glTF } = options; const magic1 = dataView.getUint32(byteOffset, false); return magic1 === magic || magic1 === MAGIC_glTF; } function parseGLBSync(glb, arrayBuffer, byteOffset = 0, options = {}) { const dataView = new DataView(arrayBuffer); const type = getMagicString3(dataView, byteOffset + 0); const version = dataView.getUint32(byteOffset + 4, LITTLE_ENDIAN2); const byteLength = dataView.getUint32(byteOffset + 8, LITTLE_ENDIAN2); Object.assign(glb, { header: { byteOffset, byteLength, hasBinChunk: false }, type, version, json: {}, binChunks: [] }); byteOffset += GLB_FILE_HEADER_SIZE; switch (glb.version) { case 1: return parseGLBV1(glb, dataView, byteOffset); case 2: return parseGLBV2(glb, dataView, byteOffset, options = {}); default: throw new Error(`Invalid GLB version ${glb.version}. Only supports version 1 and 2.`); } } function parseGLBV1(glb, dataView, byteOffset) { assert2(glb.header.byteLength > GLB_FILE_HEADER_SIZE + GLB_CHUNK_HEADER_SIZE); const contentLength = dataView.getUint32(byteOffset + 0, LITTLE_ENDIAN2); const contentFormat = dataView.getUint32(byteOffset + 4, LITTLE_ENDIAN2); byteOffset += GLB_CHUNK_HEADER_SIZE; assert2(contentFormat === GLB_V1_CONTENT_FORMAT_JSON); parseJSONChunk(glb, dataView, byteOffset, contentLength); byteOffset += contentLength; byteOffset += parseBINChunk(glb, dataView, byteOffset, glb.header.byteLength); return byteOffset; } function parseGLBV2(glb, dataView, byteOffset, options) { assert2(glb.header.byteLength > GLB_FILE_HEADER_SIZE + GLB_CHUNK_HEADER_SIZE); parseGLBChunksSync(glb, dataView, byteOffset, options); return byteOffset + glb.header.byteLength; } function parseGLBChunksSync(glb, dataView, byteOffset, options) { while (byteOffset + 8 <= glb.header.byteLength) { const chunkLength = dataView.getUint32(byteOffset + 0, LITTLE_ENDIAN2); const chunkFormat = dataView.getUint32(byteOffset + 4, LITTLE_ENDIAN2); byteOffset += GLB_CHUNK_HEADER_SIZE; switch (chunkFormat) { case GLB_CHUNK_TYPE_JSON: parseJSONChunk(glb, dataView, byteOffset, chunkLength); break; case GLB_CHUNK_TYPE_BIN: parseBINChunk(glb, dataView, byteOffset, chunkLength); break; case GLB_CHUNK_TYPE_JSON_XVIZ_DEPRECATED: if (!options.strict) { parseJSONChunk(glb, dataView, byteOffset, chunkLength); } break; case GLB_CHUNK_TYPE_BIX_XVIZ_DEPRECATED: if (!options.strict) { parseBINChunk(glb, dataView, byteOffset, chunkLength); } break; default: break; } byteOffset += padToNBytes(chunkLength, 4); } return byteOffset; } function parseJSONChunk(glb, dataView, byteOffset, chunkLength) { const jsonChunk = new Uint8Array(dataView.buffer, byteOffset, chunkLength); const textDecoder = new TextDecoder("utf8"); const jsonText = textDecoder.decode(jsonChunk); glb.json = JSON.parse(jsonText); return padToNBytes(chunkLength, 4); } function parseBINChunk(glb, dataView, byteOffset, chunkLength) { glb.header.hasBinChunk = true; glb.binChunks.push({ byteOffset, byteLength: chunkLength, arrayBuffer: dataView.buffer }); return padToNBytes(chunkLength, 4); } // ../../node_modules/@loaders.gl/gltf/dist/lib/gltf-utils/resolve-url.js function resolveUrl(url, options) { const absolute = url.startsWith("data:") || url.startsWith("http:") || url.startsWith("https:"); if (absolute) { return url; } const baseUrl = options.baseUri || options.uri; if (!baseUrl) { throw new Error(`'baseUri' must be provided to resolve relative url ${url}`); } return baseUrl.substr(0, baseUrl.lastIndexOf("/") + 1) + url; } // ../../node_modules/@loaders.gl/gltf/dist/lib/extensions/EXT_meshopt_compression.js var EXT_meshopt_compression_exports = {}; __export(EXT_meshopt_compression_exports, { decode: () => decode5, name: () => name4 }); // ../../node_modules/@loaders.gl/gltf/dist/meshopt/meshopt-decoder.js var wasm_base = "B9h9z9tFBBBF8fL9gBB9gLaaaaaFa9gEaaaB9gFaFa9gEaaaFaEMcBFFFGGGEIIILF9wFFFLEFBFKNFaFCx/IFMO/LFVK9tv9t9vq95GBt9f9f939h9z9t9f9j9h9s9s9f9jW9vq9zBBp9tv9z9o9v9wW9f9kv9j9v9kv9WvqWv94h919m9mvqBF8Z9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv94h919m9mvqBGy9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv949TvZ91v9u9jvBEn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9P9jWBIi9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9R919hWBLn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9F949wBKI9z9iqlBOc+x8ycGBM/qQFTa8jUUUUBCU/EBlHL8kUUUUBC9+RKGXAGCFJAI9LQBCaRKAE2BBC+gF9HQBALAEAIJHOAGlAGTkUUUBRNCUoBAG9uC/wgBZHKCUGAKCUG9JyRVAECFJRICBRcGXEXAcAF9PQFAVAFAclAcAVJAF9JyRMGXGXAG9FQBAMCbJHKC9wZRSAKCIrCEJCGrRQANCUGJRfCBRbAIRTEXGXAOATlAQ9PQBCBRISEMATAQJRIGXAS9FQBCBRtCBREEXGXAOAIlCi9PQBCBRISLMANCU/CBJAEJRKGXGXGXGXGXATAECKrJ2BBAtCKZrCEZfIBFGEBMAKhB83EBAKCNJhB83EBSEMAKAI2BIAI2BBHmCKrHYAYCE6HYy86BBAKCFJAICIJAYJHY2BBAmCIrCEZHPAPCE6HPy86BBAKCGJAYAPJHY2BBAmCGrCEZHPAPCE6HPy86BBAKCEJAYAPJHY2BBAmCEZHmAmCE6Hmy86BBAKCIJAYAmJHY2BBAI2BFHmCKrHPAPCE6HPy86BBAKCLJAYAPJHY2BBAmCIrCEZHPAPCE6HPy86BBAKCKJAYAPJHY2BBAmCGrCEZHPAPCE6HPy86BBAKCOJAYAPJHY2BBAmCEZHmAmCE6Hmy86BBAKCNJAYAmJHY2BBAI2BGHmCKrHPAPCE6HPy86BBAKCVJAYAPJHY2BBAmCIrCEZHPAPCE6HPy86BBAKCcJAYAPJHY2BBAmCGrCEZHPAPCE6HPy86BBAKCMJAYAPJHY2BBAmCEZHmAmCE6Hmy86BBAKCSJAYAmJHm2BBAI2BEHICKrHYAYCE6HYy86BBAKCQJAmAYJHm2BBAICIrCEZHYAYCE6HYy86BBAKCfJAmAYJHm2BBAICGrCEZHYAYCE6HYy86BBAKCbJAmAYJHK2BBAICEZHIAICE6HIy86BBAKAIJRISGMAKAI2BNAI2BBHmCIrHYAYCb6HYy86BBAKCFJAICNJAYJHY2BBAmCbZHmAmCb6Hmy86BBAKCGJAYAmJHm2BBAI2BFHYCIrHPAPCb6HPy86BBAKCEJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCIJAmAYJHm2BBAI2BGHYCIrHPAPCb6HPy86BBAKCLJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCKJAmAYJHm2BBAI2BEHYCIrHPAPCb6HPy86BBAKCOJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCNJAmAYJHm2BBAI2BIHYCIrHPAPCb6HPy86BBAKCVJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCcJAmAYJHm2BBAI2BLHYCIrHPAPCb6HPy86BBAKCMJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCSJAmAYJHm2BBAI2BKHYCIrHPAPCb6HPy86BBAKCQJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCfJAmAYJHm2BBAI2BOHICIrHYAYCb6HYy86BBAKCbJAmAYJHK2BBAICbZHIAICb6HIy86BBAKAIJRISFMAKAI8pBB83BBAKCNJAICNJ8pBB83BBAICTJRIMAtCGJRtAECTJHEAS9JQBMMGXAIQBCBRISEMGXAM9FQBANAbJ2BBRtCBRKAfREEXAEANCU/CBJAKJ2BBHTCFrCBATCFZl9zAtJHt86BBAEAGJREAKCFJHKAM9HQBMMAfCFJRfAIRTAbCFJHbAG9HQBMMABAcAG9sJANCUGJAMAG9sTkUUUBpANANCUGJAMCaJAG9sJAGTkUUUBpMAMCBAIyAcJRcAIQBMC9+RKSFMCBC99AOAIlAGCAAGCA9Ly6yRKMALCU/EBJ8kUUUUBAKM+OmFTa8jUUUUBCoFlHL8kUUUUBC9+RKGXAFCE9uHOCtJAI9LQBCaRKAE2BBHNC/wFZC/gF9HQBANCbZHVCF9LQBALCoBJCgFCUFT+JUUUBpALC84Jha83EBALC8wJha83EBALC8oJha83EBALCAJha83EBALCiJha83EBALCTJha83EBALha83ENALha83EBAEAIJC9wJRcAECFJHNAOJRMGXAF9FQBCQCbAVCF6yRSABRECBRVCBRQCBRfCBRICBRKEXGXAMAcuQBC9+RKSEMGXGXAN2BBHOC/vF9LQBALCoBJAOCIrCa9zAKJCbZCEWJHb8oGIRTAb8oGBRtGXAOCbZHbAS9PQBALAOCa9zAIJCbZCGWJ8oGBAVAbyROAb9FRbGXGXAGCG9HQBABAt87FBABCIJAO87FBABCGJAT87FBSFMAEAtjGBAECNJAOjGBAECIJATjGBMAVAbJRVALCoBJAKCEWJHmAOjGBAmATjGIALAICGWJAOjGBALCoBJAKCFJCbZHKCEWJHTAtjGBATAOjGIAIAbJRIAKCFJRKSGMGXGXAbCb6QBAQAbJAbC989zJCFJRQSFMAM1BBHbCgFZROGXGXAbCa9MQBAMCFJRMSFMAM1BFHbCgBZCOWAOCgBZqROGXAbCa9MQBAMCGJRMSFMAM1BGHbCgBZCfWAOqROGXAbCa9MQBAMCEJRMSFMAM1BEHbCgBZCdWAOqROGXAbCa9MQBAMCIJRMSFMAM2BIC8cWAOqROAMCLJRMMAOCFrCBAOCFZl9zAQJRQMGXGXAGCG9HQBABAt87FBABCIJAQ87FBABCGJAT87FBSFMAEAtjGBAECNJAQjGBAECIJATjGBMALCoBJAKCEWJHOAQjGBAOATjGIALAICGWJAQjGBALCoBJAKCFJCbZHKCEWJHOAtjGBAOAQjGIAICFJRIAKCFJRKSFMGXAOCDF9LQBALAIAcAOCbZJ2BBHbCIrHTlCbZCGWJ8oGBAVCFJHtATyROALAIAblCbZCGWJ8oGBAtAT9FHmJHtAbCbZHTyRbAT9FRTGXGXAGCG9HQBABAV87FBABCIJAb87FBABCGJAO87FBSFMAEAVjGBAECNJAbjGBAECIJAOjGBMALAICGWJAVjGBALCoBJAKCEWJHYAOjGBAYAVjGIALAICFJHICbZCGWJAOjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAIAmJCbZHICGWJAbjGBALCoBJAKCGJCbZHKCEWJHOAVjGBAOAbjGIAKCFJRKAIATJRIAtATJRVSFMAVCBAM2BBHYyHTAOC/+F6HPJROAYCbZRtGXGXAYCIrHmQBAOCFJRbSFMAORbALAIAmlCbZCGWJ8oGBROMGXGXAtQBAbCFJRVSFMAbRVALAIAYlCbZCGWJ8oGBRbMGXGXAP9FQBAMCFJRYSFMAM1BFHYCgFZRTGXGXAYCa9MQBAMCGJRYSFMAM1BGHYCgBZCOWATCgBZqRTGXAYCa9MQBAMCEJRYSFMAM1BEHYCgBZCfWATqRTGXAYCa9MQBAMCIJRYSFMAM1BIHYCgBZCdWATqRTGXAYCa9MQBAMCLJRYSFMAMCKJRYAM2BLC8cWATqRTMATCFrCBATCFZl9zAQJHQRTMGXGXAmCb6QBAYRPSFMAY1BBHMCgFZROGXGXAMCa9MQBAYCFJRPSFMAY1BFHMCgBZCOWAOCgBZqROGXAMCa9MQBAYCGJRPSFMAY1BGHMCgBZCfWAOqROGXAMCa9MQBAYCEJRPSFMAY1BEHMCgBZCdWAOqROGXAMCa9MQBAYCIJRPSFMAYCLJRPAY2BIC8cWAOqROMAOCFrCBAOCFZl9zAQJHQROMGXGXAtCb6QBAPRMSFMAP1BBHMCgFZRbGXGXAMCa9MQBAPCFJRMSFMAP1BFHMCgBZCOWAbCgBZqRbGXAMCa9MQBAPCGJRMSFMAP1BGHMCgBZCfWAbqRbGXAMCa9MQBAPCEJRMSFMAP1BEHMCgBZCdWAbqRbGXAMCa9MQBAPCIJRMSFMAPCLJRMAP2BIC8cWAbqRbMAbCFrCBAbCFZl9zAQJHQRbMGXGXAGCG9HQBABAT87FBABCIJAb87FBABCGJAO87FBSFMAEATjGBAECNJAbjGBAECIJAOjGBMALCoBJAKCEWJHYAOjGBAYATjGIALAICGWJATjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAICFJHICbZCGWJAOjGBALCoBJAKCGJCbZCEWJHOATjGBAOAbjGIALAIAm9FAmCb6qJHICbZCGWJAbjGBAIAt9FAtCb6qJRIAKCEJRKMANCFJRNABCKJRBAECSJREAKCbZRKAICbZRIAfCEJHfAF9JQBMMCBC99AMAc6yRKMALCoFJ8kUUUUBAKM/tIFGa8jUUUUBCTlRLC9+RKGXAFCLJAI9LQBCaRKAE2BBC/+FZC/QF9HQBALhB83ENAECFJRKAEAIJC98JREGXAF9FQBGXAGCG6QBEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMALCNJAICFZCGWqHGAICGrCBAICFrCFZl9zAG8oGBJHIjGBABAIjGBABCIJRBAFCaJHFQBSGMMEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMABAICGrCBAICFrCFZl9zALCNJAICFZCGWqHI8oGBJHG87FBAIAGjGBABCGJRBAFCaJHFQBMMCBC99AKAE6yRKMAKM+lLKFaF99GaG99FaG99GXGXAGCI9HQBAF9FQFEXGXGX9DBBB8/9DBBB+/ABCGJHG1BB+yAB1BBHE+yHI+L+TABCFJHL1BBHK+yHO+L+THN9DBBBB9gHVyAN9DBB/+hANAN+U9DBBBBANAVyHcAc+MHMAECa3yAI+SHIAI+UAcAMAKCa3yAO+SHcAc+U+S+S+R+VHO+U+SHN+L9DBBB9P9d9FQBAN+oRESFMCUUUU94REMAGAE86BBGXGX9DBBB8/9DBBB+/Ac9DBBBB9gyAcAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMALAG86BBGXGX9DBBB8/9DBBB+/AI9DBBBB9gyAIAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMABAG86BBABCIJRBAFCaJHFQBSGMMAF9FQBEXGXGX9DBBB8/9DBBB+/ABCIJHG8uFB+yAB8uFBHE+yHI+L+TABCGJHL8uFBHK+yHO+L+THN9DBBBB9gHVyAN9DB/+g6ANAN+U9DBBBBANAVyHcAc+MHMAECa3yAI+SHIAI+UAcAMAKCa3yAO+SHcAc+U+S+S+R+VHO+U+SHN+L9DBBB9P9d9FQBAN+oRESFMCUUUU94REMAGAE87FBGXGX9DBBB8/9DBBB+/Ac9DBBBB9gyAcAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMALAG87FBGXGX9DBBB8/9DBBB+/AI9DBBBB9gyAIAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMABAG87FBABCNJRBAFCaJHFQBMMM/SEIEaE99EaF99GXAF9FQBCBREABRIEXGXGX9D/zI818/AICKJ8uFBHLCEq+y+VHKAI8uFB+y+UHO9DB/+g6+U9DBBB8/9DBBB+/AO9DBBBB9gy+SHN+L9DBBB9P9d9FQBAN+oRVSFMCUUUU94RVMAICIJ8uFBRcAICGJ8uFBRMABALCFJCEZAEqCFWJAV87FBGXGXAKAM+y+UHN9DB/+g6+U9DBBB8/9DBBB+/AN9DBBBB9gy+SHS+L9DBBB9P9d9FQBAS+oRMSFMCUUUU94RMMABALCGJCEZAEqCFWJAM87FBGXGXAKAc+y+UHK9DB/+g6+U9DBBB8/9DBBB+/AK9DBBBB9gy+SHS+L9DBBB9P9d9FQBAS+oRcSFMCUUUU94RcMABALCaJCEZAEqCFWJAc87FBGXGX9DBBU8/AOAO+U+TANAN+U+TAKAK+U+THO9DBBBBAO9DBBBB9gy+R9DB/+g6+U9DBBB8/+SHO+L9DBBB9P9d9FQBAO+oRcSFMCUUUU94RcMABALCEZAEqCFWJAc87FBAICNJRIAECIJREAFCaJHFQBMMM9JBGXAGCGrAF9sHF9FQBEXABAB8oGBHGCNWCN91+yAGCi91CnWCUUU/8EJ+++U84GBABCIJRBAFCaJHFQBMMM9TFEaCBCB8oGUkUUBHFABCEJC98ZJHBjGUkUUBGXGXAB8/BCTWHGuQBCaREABAGlCggEJCTrXBCa6QFMAFREMAEM/lFFFaGXGXAFABqCEZ9FQBABRESFMGXGXAGCT9PQBABRESFMABREEXAEAF8oGBjGBAECIJAFCIJ8oGBjGBAECNJAFCNJ8oGBjGBAECSJAFCSJ8oGBjGBAECTJREAFCTJRFAGC9wJHGCb9LQBMMAGCI9JQBEXAEAF8oGBjGBAFCIJRFAECIJREAGC98JHGCE9LQBMMGXAG9FQBEXAEAF2BB86BBAECFJREAFCFJRFAGCaJHGQBMMABMoFFGaGXGXABCEZ9FQBABRESFMAFCgFZC+BwsN9sRIGXGXAGCT9PQBABRESFMABREEXAEAIjGBAECSJAIjGBAECNJAIjGBAECIJAIjGBAECTJREAGC9wJHGCb9LQBMMAGCI9JQBEXAEAIjGBAECIJREAGC98JHGCE9LQBMMGXAG9FQBEXAEAF86BBAECFJREAGCaJHGQBMMABMMMFBCUNMIT9kBB"; var wasm_simd = "B9h9z9tFBBBF8dL9gBB9gLaaaaaFa9gEaaaB9gGaaB9gFaFaEQSBBFBFFGEGEGIILF9wFFFLEFBFKNFaFCx/aFMO/LFVK9tv9t9vq95GBt9f9f939h9z9t9f9j9h9s9s9f9jW9vq9zBBp9tv9z9o9v9wW9f9kv9j9v9kv9WvqWv94h919m9mvqBG8Z9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv94h919m9mvqBIy9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv949TvZ91v9u9jvBLn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9P9jWBKi9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9R919hWBNn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9F949wBcI9z9iqlBMc/j9JSIBTEM9+FLa8jUUUUBCTlRBCBRFEXCBRGCBREEXABCNJAGJAECUaAFAGrCFZHIy86BBAEAIJREAGCFJHGCN9HQBMAFCx+YUUBJAE86BBAFCEWCxkUUBJAB8pEN83EBAFCFJHFCUG9HQBMMkRIbaG97FaK978jUUUUBCU/KBlHL8kUUUUBC9+RKGXAGCFJAI9LQBCaRKAE2BBC+gF9HQBALAEAIJHOAGlAG/8cBBCUoBAG9uC/wgBZHKCUGAKCUG9JyRNAECFJRKCBRVGXEXAVAF9PQFANAFAVlAVANJAF9JyRcGXGXAG9FQBAcCbJHIC9wZHMCE9sRSAMCFWRQAICIrCEJCGrRfCBRbEXAKRTCBRtGXEXGXAOATlAf9PQBCBRKSLMALCU/CBJAtAM9sJRmATAfJRKCBREGXAMCoB9JQBAOAKlC/gB9JQBCBRIEXAmAIJREGXGXGXGXGXATAICKrJ2BBHYCEZfIBFGEBMAECBDtDMIBSEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCIJAnDeBJAeCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCNJAnDeBJAeCx+YUUBJ2BBJRKSFMAEAKDBBBDMIBAKCTJRKMGXGXGXGXGXAYCGrCEZfIBFGEBMAECBDtDMITSEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMITAKCIJAnDeBJAeCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMITAKCNJAnDeBJAeCx+YUUBJ2BBJRKSFMAEAKDBBBDMITAKCTJRKMGXGXGXGXGXAYCIrCEZfIBFGEBMAECBDtDMIASEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIAAKCIJAnDeBJAeCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIAAKCNJAnDeBJAeCx+YUUBJ2BBJRKSFMAEAKDBBBDMIAAKCTJRKMGXGXGXGXGXAYCKrfIBFGEBMAECBDtDMI8wSEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HYCEWCxkUUBJDBEBAYCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HYCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMI8wAKCIJAnDeBJAYCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HYCEWCxkUUBJDBEBAYCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HYCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMI8wAKCNJAnDeBJAYCx+YUUBJ2BBJRKSFMAEAKDBBBDMI8wAKCTJRKMAICoBJREAICUFJAM9LQFAERIAOAKlC/fB9LQBMMGXAEAM9PQBAECErRIEXGXAOAKlCi9PQBCBRKSOMAmAEJRYGXGXGXGXGXATAECKrJ2BBAICKZrCEZfIBFGEBMAYCBDtDMIBSEMAYAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCIJAnDeBJAeCx+YUUBJ2BBJRKSGMAYAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCNJAnDeBJAeCx+YUUBJ2BBJRKSFMAYAKDBBBDMIBAKCTJRKMAICGJRIAECTJHEAM9JQBMMGXAK9FQBAKRTAtCFJHtCI6QGSFMMCBRKSEMGXAM9FQBALCUGJAbJREALAbJDBGBRnCBRYEXAEALCU/CBJAYJHIDBIBHdCFD9tAdCFDbHPD9OD9hD9RHdAIAMJDBIBHiCFD9tAiAPD9OD9hD9RHiDQBTFtGmEYIPLdKeOnH8ZAIAQJDBIBHpCFD9tApAPD9OD9hD9RHpAIASJDBIBHyCFD9tAyAPD9OD9hD9RHyDQBTFtGmEYIPLdKeOnH8cDQBFTtGEmYILPdKOenHPAPDQBFGEBFGEBFGEBFGEAnD9uHnDyBjGBAEAGJHIAnAPAPDQILKOILKOILKOILKOD9uHnDyBjGBAIAGJHIAnAPAPDQNVcMNVcMNVcMNVcMD9uHnDyBjGBAIAGJHIAnAPAPDQSQfbSQfbSQfbSQfbD9uHnDyBjGBAIAGJHIAnA8ZA8cDQNVi8ZcMpySQ8c8dfb8e8fHPAPDQBFGEBFGEBFGEBFGED9uHnDyBjGBAIAGJHIAnAPAPDQILKOILKOILKOILKOD9uHnDyBjGBAIAGJHIAnAPAPDQNVcMNVcMNVcMNVcMD9uHnDyBjGBAIAGJHIAnAPAPDQSQfbSQfbSQfbSQfbD9uHnDyBjGBAIAGJHIAnAdAiDQNiV8ZcpMyS8cQ8df8eb8fHdApAyDQNiV8ZcpMyS8cQ8df8eb8fHiDQBFTtGEmYILPdKOenHPAPDQBFGEBFGEBFGEBFGED9uHnDyBjGBAIAGJHIAnAPAPDQILKOILKOILKOILKOD9uHnDyBjGBAIAGJHIAnAPAPDQNVcMNVcMNVcMNVcMD9uHnDyBjGBAIAGJHIAnAPAPDQSQfbSQfbSQfbSQfbD9uHnDyBjGBAIAGJHIAnAdAiDQNVi8ZcMpySQ8c8dfb8e8fHPAPDQBFGEBFGEBFGEBFGED9uHnDyBjGBAIAGJHIAnAPAPDQILKOILKOILKOILKOD9uHnDyBjGBAIAGJHIAnAPAPDQNVcMNVcMNVcMNVcMD9uHnDyBjGBAIAGJHIAnAPAPDQSQfbSQfbSQfbSQfbD9uHnDyBjGBAIAGJREAYCTJHYAM9JQBMMAbCIJHbAG9JQBMMABAVAG9sJALCUGJAcAG9s/8cBBALALCUGJAcCaJAG9sJAG/8cBBMAcCBAKyAVJRVAKQBMC9+RKSFMCBC99AOAKlAGCAAGCA9Ly6yRKMALCU/KBJ8kUUUUBAKMNBT+BUUUBM+KmFTa8jUUUUBCoFlHL8kUUUUBC9+RKGXAFCE9uHOCtJAI9LQBCaRKAE2BBHNC/wFZC/gF9HQBANCbZHVCF9LQBALCoBJCgFCUF/8MBALC84Jha83EBALC8wJha83EBALC8oJha83EBALCAJha83EBALCiJha83EBALCTJha83EBALha83ENALha83EBAEAIJC9wJRcAECFJHNAOJRMGXAF9FQBCQCbAVCF6yRSABRECBRVCBRQCBRfCBRICBRKEXGXAMAcuQBC9+RKSEMGXGXAN2BBHOC/vF9LQBALCoBJAOCIrCa9zAKJCbZCEWJHb8oGIRTAb8oGBRtGXAOCbZHbAS9PQBALAOCa9zAIJCbZCGWJ8oGBAVAbyROAb9FRbGXGXAGCG9HQBABAt87FBABCIJAO87FBABCGJAT87FBSFMAEAtjGBAECNJAOjGBAECIJATjGBMAVAbJRVALCoBJAKCEWJHmAOjGBAmATjGIALAICGWJAOjGBALCoBJAKCFJCbZHKCEWJHTAtjGBATAOjGIAIAbJRIAKCFJRKSGMGXGXAbCb6QBAQAbJAbC989zJCFJRQSFMAM1BBHbCgFZROGXGXAbCa9MQBAMCFJRMSFMAM1BFHbCgBZCOWAOCgBZqROGXAbCa9MQBAMCGJRMSFMAM1BGHbCgBZCfWAOqROGXAbCa9MQBAMCEJRMSFMAM1BEHbCgBZCdWAOqROGXAbCa9MQBAMCIJRMSFMAM2BIC8cWAOqROAMCLJRMMAOCFrCBAOCFZl9zAQJRQMGXGXAGCG9HQBABAt87FBABCIJAQ87FBABCGJAT87FBSFMAEAtjGBAECNJAQjGBAECIJATjGBMALCoBJAKCEWJHOAQjGBAOATjGIALAICGWJAQjGBALCoBJAKCFJCbZHKCEWJHOAtjGBAOAQjGIAICFJRIAKCFJRKSFMGXAOCDF9LQBALAIAcAOCbZJ2BBHbCIrHTlCbZCGWJ8oGBAVCFJHtATyROALAIAblCbZCGWJ8oGBAtAT9FHmJHtAbCbZHTyRbAT9FRTGXGXAGCG9HQBABAV87FBABCIJAb87FBABCGJAO87FBSFMAEAVjGBAECNJAbjGBAECIJAOjGBMALAICGWJAVjGBALCoBJAKCEWJHYAOjGBAYAVjGIALAICFJHICbZCGWJAOjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAIAmJCbZHICGWJAbjGBALCoBJAKCGJCbZHKCEWJHOAVjGBAOAbjGIAKCFJRKAIATJRIAtATJRVSFMAVCBAM2BBHYyHTAOC/+F6HPJROAYCbZRtGXGXAYCIrHmQBAOCFJRbSFMAORbALAIAmlCbZCGWJ8oGBROMGXGXAtQBAbCFJRVSFMAbRVALAIAYlCbZCGWJ8oGBRbMGXGXAP9FQBAMCFJRYSFMAM1BFHYCgFZRTGXGXAYCa9MQBAMCGJRYSFMAM1BGHYCgBZCOWATCgBZqRTGXAYCa9MQBAMCEJRYSFMAM1BEHYCgBZCfWATqRTGXAYCa9MQBAMCIJRYSFMAM1BIHYCgBZCdWATqRTGXAYCa9MQBAMCLJRYSFMAMCKJRYAM2BLC8cWATqRTMATCFrCBATCFZl9zAQJHQRTMGXGXAmCb6QBAYRPSFMAY1BBHMCgFZROGXGXAMCa9MQBAYCFJRPSFMAY1BFHMCgBZCOWAOCgBZqROGXAMCa9MQBAYCGJRPSFMAY1BGHMCgBZCfWAOqROGXAMCa9MQBAYCEJRPSFMAY1BEHMCgBZCdWAOqROGXAMCa9MQBAYCIJRPSFMAYCLJRPAY2BIC8cWAOqROMAOCFrCBAOCFZl9zAQJHQROMGXGXAtCb6QBAPRMSFMAP1BBHMCgFZRbGXGXAMCa9MQBAPCFJRMSFMAP1BFHMCgBZCOWAbCgBZqRbGXAMCa9MQBAPCGJRMSFMAP1BGHMCgBZCfWAbqRbGXAMCa9MQBAPCEJRMSFMAP1BEHMCgBZCdWAbqRbGXAMCa9MQBAPCIJRMSFMAPCLJRMAP2BIC8cWAbqRbMAbCFrCBAbCFZl9zAQJHQRbMGXGXAGCG9HQBABAT87FBABCIJAb87FBABCGJAO87FBSFMAEATjGBAECNJAbjGBAECIJAOjGBMALCoBJAKCEWJHYAOjGBAYATjGIALAICGWJATjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAICFJHICbZCGWJAOjGBALCoBJAKCGJCbZCEWJHOATjGBAOAbjGIALAIAm9FAmCb6qJHICbZCGWJAbjGBAIAt9FAtCb6qJRIAKCEJRKMANCFJRNABCKJRBAECSJREAKCbZRKAICbZRIAfCEJHfAF9JQBMMCBC99AMAc6yRKMALCoFJ8kUUUUBAKM/tIFGa8jUUUUBCTlRLC9+RKGXAFCLJAI9LQBCaRKAE2BBC/+FZC/QF9HQBALhB83ENAECFJRKAEAIJC98JREGXAF9FQBGXAGCG6QBEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMALCNJAICFZCGWqHGAICGrCBAICFrCFZl9zAG8oGBJHIjGBABAIjGBABCIJRBAFCaJHFQBSGMMEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMABAICGrCBAICFrCFZl9zALCNJAICFZCGWqHI8oGBJHG87FBAIAGjGBABCGJRBAFCaJHFQBMMCBC99AKAE6yRKMAKM/xLGEaK978jUUUUBCAlHE8kUUUUBGXGXAGCI9HQBGXAFC98ZHI9FQBABRGCBRLEXAGAGDBBBHKCiD+rFCiD+sFD/6FHOAKCND+rFCiD+sFD/6FAOD/gFAKCTD+rFCiD+sFD/6FHND/gFD/kFD/lFHVCBDtD+2FHcAOCUUUU94DtHMD9OD9RD/kFHO9DBB/+hDYAOAOD/mFAVAVD/mFANAcANAMD9OD9RD/kFHOAOD/mFD/kFD/kFD/jFD/nFHND/mF9DBBX9LDYHcD/kFCgFDtD9OAKCUUU94DtD9OD9QAOAND/mFAcD/kFCND+rFCU/+EDtD9OD9QAVAND/mFAcD/kFCTD+rFCUU/8ODtD9OD9QDMBBAGCTJRGALCIJHLAI9JQBMMAIAF9PQFAEAFCEZHLCGWHGqCBCTAGl/8MBAEABAICGWJHIAG/8cBBGXAL9FQBAEAEDBIBHKCiD+rFCiD+sFD/6FHOAKCND+rFCiD+sFD/6FAOD/gFAKCTD+rFCiD+sFD/6FHND/gFD/kFD/lFHVCBDtD+2FHcAOCUUUU94DtHMD9OD9RD/kFHO9DBB/+hDYAOAOD/mFAVAVD/mFANAcANAMD9OD9RD/kFHOAOD/mFD/kFD/kFD/jFD/nFHND/mF9DBBX9LDYHcD/kFCgFDtD9OAKCUUU94DtD9OD9QAOAND/mFAcD/kFCND+rFCU/+EDtD9OD9QAVAND/mFAcD/kFCTD+rFCUU/8ODtD9OD9QDMIBMAIAEAG/8cBBSFMABAFC98ZHGT+HUUUBAGAF9PQBAEAFCEZHICEWHLJCBCAALl/8MBAEABAGCEWJHGAL/8cBBAEAIT+HUUUBAGAEAL/8cBBMAECAJ8kUUUUBM+yEGGaO97GXAF9FQBCBRGEXABCTJHEAEDBBBHICBDtHLCUU98D8cFCUU98D8cEHKD9OABDBBBHOAIDQILKOSQfbPden8c8d8e8fCggFDtD9OD/6FAOAIDQBFGENVcMTtmYi8ZpyHICTD+sFD/6FHND/gFAICTD+rFCTD+sFD/6FHVD/gFD/kFD/lFHI9DB/+g6DYAVAIALD+2FHLAVCUUUU94DtHcD9OD9RD/kFHVAVD/mFAIAID/mFANALANAcD9OD9RD/kFHIAID/mFD/kFD/kFD/jFD/nFHND/mF9DBBX9LDYHLD/kFCTD+rFAVAND/mFALD/kFCggEDtD9OD9QHVAIAND/mFALD/kFCaDbCBDnGCBDnECBDnKCBDnOCBDncCBDnMCBDnfCBDnbD9OHIDQNVi8ZcMpySQ8c8dfb8e8fD9QDMBBABAOAKD9OAVAIDQBFTtGEmYILPdKOenD9QDMBBABCAJRBAGCIJHGAF9JQBMMM94FEa8jUUUUBCAlHE8kUUUUBABAFC98ZHIT+JUUUBGXAIAF9PQBAEAFCEZHLCEWHFJCBCAAFl/8MBAEABAICEWJHBAF/8cBBAEALT+JUUUBABAEAF/8cBBMAECAJ8kUUUUBM/hEIGaF97FaL978jUUUUBCTlRGGXAF9FQBCBREEXAGABDBBBHIABCTJHLDBBBHKDQILKOSQfbPden8c8d8e8fHOCTD+sFHNCID+rFDMIBAB9DBBU8/DY9D/zI818/DYANCEDtD9QD/6FD/nFHNAIAKDQBFGENVcMTtmYi8ZpyHICTD+rFCTD+sFD/6FD/mFHKAKD/mFANAICTD+sFD/6FD/mFHVAVD/mFANAOCTD+rFCTD+sFD/6FD/mFHOAOD/mFD/kFD/kFD/lFCBDtD+4FD/jF9DB/+g6DYHND/mF9DBBX9LDYHID/kFCggEDtHcD9OAVAND/mFAID/kFCTD+rFD9QHVAOAND/mFAID/kFCTD+rFAKAND/mFAID/kFAcD9OD9QHNDQBFTtGEmYILPdKOenHID8dBAGDBIBDyB+t+J83EBABCNJAID8dFAGDBIBDyF+t+J83EBALAVANDQNVi8ZcMpySQ8c8dfb8e8fHND8dBAGDBIBDyG+t+J83EBABCiJAND8dFAGDBIBDyE+t+J83EBABCAJRBAECIJHEAF9JQBMMM/3FGEaF978jUUUUBCoBlREGXAGCGrAF9sHIC98ZHL9FQBCBRGABRFEXAFAFDBBBHKCND+rFCND+sFD/6FAKCiD+sFCnD+rFCUUU/8EDtD+uFD/mFDMBBAFCTJRFAGCIJHGAL9JQBMMGXALAI9PQBAEAICEZHGCGWHFqCBCoBAFl/8MBAEABALCGWJHLAF/8cBBGXAG9FQBAEAEDBIBHKCND+rFCND+sFD/6FAKCiD+sFCnD+rFCUUU/8EDtD+uFD/mFDMIBMALAEAF/8cBBMM9TFEaCBCB8oGUkUUBHFABCEJC98ZJHBjGUkUUBGXGXAB8/BCTWHGuQBCaREABAGlCggEJCTrXBCa6QFMAFREMAEMMMFBCUNMIT9tBB"; var detector = new Uint8Array([ 0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 3, 2, 0, 0, 5, 3, 1, 0, 1, 12, 1, 0, 10, 22, 2, 12, 0, 65, 0, 65, 0, 65, 0, 252, 10, 0, 0, 11, 7, 0, 65, 0, 253, 15, 26, 11 ]); var wasmpack = new Uint8Array([ 32, 0, 65, 253, 3, 1, 2, 34, 4, 106, 6, 5, 11, 8, 7, 20, 13, 33, 12, 16, 128, 9, 116, 64, 19, 113, 127, 15, 10, 21, 22, 14, 255, 66, 24, 54, 136, 107, 18, 23, 192, 26, 114, 118, 132, 17, 77, 101, 130, 144, 27, 87, 131, 44, 45, 74, 156, 154, 70, 167 ]); var FILTERS = { 0: "", 1: "meshopt_decodeFilterOct", 2: "meshopt_decodeFilterQuat", 3: "meshopt_decodeFilterExp", NONE: "", OCTAHEDRAL: "meshopt_decodeFilterOct", QUATERNION: "meshopt_decodeFilterQuat", EXPONENTIAL: "meshopt_decodeFilterExp" }; var DECODERS = { 0: "meshopt_decodeVertexBuffer", 1: "meshopt_decodeIndexBuffer", 2: "meshopt_decodeIndexSequence", ATTRIBUTES: "meshopt_decodeVertexBuffer", TRIANGLES: "meshopt_decodeIndexBuffer", INDICES: "meshopt_decodeIndexSequence" }; async function meshoptDecodeGltfBuffer(target, count, size, source, mode, filter = "NONE") { const instance = await loadWasmInstance(); decode4(instance, instance.exports[DECODERS[mode]], target, count, size, source, instance.exports[FILTERS[filter || "NONE"]]); } var wasmPromise; async function loadWasmInstance() { if (!wasmPromise) { wasmPromise = loadWasmModule(); } return wasmPromise; } async function loadWasmModule() { let wasm2 = wasm_base; if (WebAssembly.validate(detector)) { wasm2 = wasm_simd; console.log("Warning: meshopt_decoder is using experimental SIMD support"); } const result = await WebAssembly.instantiate(unpack(wasm2), {}); await result.instance.exports.__wasm_call_ctors(); return result.instance; } function unpack(data) { const result = new Uint8Array(data.length); for (let i3 = 0; i3 < data.length; ++i3) { const ch = data.charCodeAt(i3); result[i3] = ch > 96 ? ch - 71 : ch > 64 ? ch - 65 : ch > 47 ? ch + 4 : ch > 46 ? 63 : 62; } let write = 0; for (let i3 = 0; i3 < data.length; ++i3) { result[write++] = result[i3] < 60 ? wasmpack[result[i3]] : (result[i3] - 60) * 64 + result[++i3]; } return result.buffer.slice(0, write); } function decode4(instance, fun, target, count, size, source, filter) { const sbrk = instance.exports.sbrk; const count4 = count + 3 & ~3; const tp = sbrk(count4 * size); const sp = sbrk(source.length); const heap = new Uint8Array(instance.exports.memory.buffer); heap.set(source, sp); const res = fun(tp, count, size, sp, source.length); if (res === 0 && filter) { filter(tp, count4, size); } target.set(heap.subarray(tp, tp + count * size)); sbrk(tp - sbrk(0)); if (res !== 0) { throw new Error(`Malformed buffer data: ${res}`); } } // ../../node_modules/@loaders.gl/gltf/dist/lib/extensions/EXT_meshopt_compression.js var EXT_MESHOPT_COMPRESSION = "EXT_meshopt_compression"; var name4 = EXT_MESHOPT_COMPRESSION; async function decode5(gltfData, options) { const scenegraph = new GLTFScenegraph(gltfData); if (!options?.gltf?.decompressMeshes || !options.gltf?.loadBuffers) { return; } const promises = []; for (const bufferViewIndex of gltfData.json.bufferViews || []) { promises.push(decodeMeshoptBufferView(scenegraph, bufferViewIndex)); } await Promise.all(promises); scenegraph.removeExtension(EXT_MESHOPT_COMPRESSION); } async function decodeMeshoptBufferView(scenegraph, bufferView) { const meshoptExtension = scenegraph.getObjectExtension(bufferView, EXT_MESHOPT_COMPRESSION); if (meshoptExtension) { const { byteOffset = 0, byteLength = 0, byteStride, count, mode, filter = "NONE", buffer: bufferIndex } = meshoptExtension; const buffer = scenegraph.gltf.buffers[bufferIndex]; const source = new Uint8Array(buffer.arrayBuffer, buffer.byteOffset + byteOffset, byteLength); const result = new Uint8Array(scenegraph.gltf.buffers[bufferView.buffer].arrayBuffer, bufferView.byteOffset, bufferView.byteLength); await meshoptDecodeGltfBuffer(result, count, byteStride, source, mode, filter); scenegraph.removeObjectExtension(bufferView, EXT_MESHOPT_COMPRESSION); } } // ../../node_modules/@loaders.gl/gltf/dist/lib/extensions/EXT_texture_webp.js var EXT_texture_webp_exports = {}; __export(EXT_texture_webp_exports, { name: () => name5, preprocess: () => preprocess }); var EXT_TEXTURE_WEBP = "EXT_texture_webp"; var name5 = EXT_TEXTURE_WEBP; function preprocess(gltfData, options) { const scenegraph = new GLTFScenegraph(gltfData); if (!isImageFormatSupported("image/webp")) { if (scenegraph.getRequiredExtensions().includes(EXT_TEXTURE_WEBP)) { throw new Error(`gltf: Required extension ${EXT_TEXTURE_WEBP} not supported by browser`); } return; } const { json } = scenegraph; for (const texture of json.textures || []) { const extension = scenegraph.getObjectExtension(texture, EXT_TEXTURE_WEBP); if (extension) { texture.source = extension.source; } scenegraph.removeObjectExtension(texture, EXT_TEXTURE_WEBP); } scenegraph.removeExtension(EXT_TEXTURE_WEBP); } // ../../node_modules/@loaders.gl/gltf/dist/lib/extensions/KHR_texture_basisu.js var KHR_texture_basisu_exports = {}; __export(KHR_texture_basisu_exports, { name: () => name6, preprocess: () => preprocess2 }); var KHR_TEXTURE_BASISU = "KHR_texture_basisu"; var name6 = KHR_TEXTURE_BASISU; function preprocess2(gltfData, options) { const scene = new GLTFScenegraph(gltfData); const { json } = scene; for (const texture of json.textures || []) { const extension = scene.getObjectExtension(texture, KHR_TEXTURE_BASISU); if (extension) { texture.source = extension.source; scene.removeObjectExtension(texture, KHR_TEXTURE_BASISU); } } scene.removeExtension(KHR_TEXTURE_BASISU); } // ../../node_modules/@loaders.gl/gltf/dist/lib/extensions/KHR_draco_mesh_compression.js var KHR_draco_mesh_compression_exports = {}; __export(KHR_draco_mesh_compression_exports, { decode: () => decode6, encode: () => encode, name: () => name7, preprocess: () => preprocess3 }); // ../../node_modules/@loaders.gl/gltf/dist/lib/gltf-utils/gltf-attribute-utils.js function getGLTFAccessors(attributes) { const accessors = {}; for (const name12 in attributes) { const attribute = attributes[name12]; if (name12 !== "indices") { const glTFAccessor = getGLTFAccessor(attribute); accessors[name12] = glTFAccessor; } } return accessors; } function getGLTFAccessor(attribute) { const { buffer, size, count } = getAccessorData(attribute); const glTFAccessor = { value: buffer, size, byteOffset: 0, count, type: getAccessorTypeFromSize(size), componentType: getComponentTypeFromArray(buffer) }; return glTFAccessor; } function getAccessorData(attribute) { let buffer = attribute; let size = 1; let count = 0; if (attribute && attribute.value) { buffer = attribute.value; size = attribute.size || 1; } if (buffer) { if (!ArrayBuffer.isView(buffer)) { buffer = toTypedArray(buffer, Float32Array); } count = buffer.length / size; } return { buffer, size, count }; } function toTypedArray(array, ArrayType, convertTypedArrays = false) { if (!array) { return null; } if (Array.isArray(array)) { return new ArrayType(array); } if (convertTypedArrays && !(array instanceof ArrayType)) { return new ArrayType(array); } return array; } // ../../node_modules/@loaders.gl/gltf/dist/lib/extensions/KHR_draco_mesh_compression.js var KHR_DRACO_MESH_COMPRESSION = "KHR_draco_mesh_compression"; var name7 = KHR_DRACO_MESH_COMPRESSION; function preprocess3(gltfData, options, context) { const scenegraph = new GLTFScenegraph(gltfData); for (const primitive of makeMeshPrimitiveIterator(scenegraph)) { if (scenegraph.getObjectExtension(primitive, KHR_DRACO_MESH_COMPRESSION)) { } } } async function decode6(gltfData, options, context) { if (!options?.gltf?.decompressMeshes) { return; } const scenegraph = new GLTFScenegraph(gltfData); const promises = []; for (const primitive of makeMeshPrimitiveIterator(scenegraph)) { if (scenegraph.getObjectExtension(primitive, KHR_DRACO_MESH_COMPRESSION)) { promises.push(decompressPrimitive(scenegraph, primitive, options, context)); } } await Promise.all(promises); scenegraph.removeExtension(KHR_DRACO_MESH_COMPRESSION); } function encode(gltfData, options = {}) { const scenegraph = new GLTFScenegraph(gltfData); for (const mesh of scenegraph.json.meshes || []) { compressMesh(mesh, options); scenegraph.addRequiredExtension(KHR_DRACO_MESH_COMPRESSION); } } async function decompressPrimitive(scenegraph, primitive, options, context) { const dracoExtension = scenegraph.getObjectExtension(primitive, KHR_DRACO_MESH_COMPRESSION); if (!dracoExtension) { return; } const buffer = scenegraph.getTypedArrayForBufferView(dracoExtension.bufferView); const bufferCopy = sliceArrayBuffer(buffer.buffer, buffer.byteOffset); const dracoOptions = { ...options }; delete dracoOptions["3d-tiles"]; const decodedData = await parseFromContext(bufferCopy, DracoLoader2, dracoOptions, context); const decodedAttributes = getGLTFAccessors(decodedData.attributes); for (const [attributeName, decodedAttribute] of Object.entries(decodedAttributes)) { if (attributeName in primitive.attributes) { const accessorIndex = primitive.attributes[attributeName]; const accessor = scenegraph.getAccessor(accessorIndex); if (accessor?.min && accessor?.max) { decodedAttribute.min = accessor.min; decodedAttribute.max = accessor.max; } } } primitive.attributes = decodedAttributes; if (decodedData.indices) { primitive.indices = getGLTFAccessor(decodedData.indices); } scenegraph.removeObjectExtension(primitive, KHR_DRACO_MESH_COMPRESSION); checkPrimitive(primitive); } function compressMesh(attributes, indices, mode = 4, options, context) { if (!options.DracoWriter) { throw new Error("options.gltf.DracoWriter not provided"); } const compressedData = options.DracoWriter.encodeSync({ attributes }); const decodedData = context?.parseSync?.({ attributes }); const fauxAccessors = options._addFauxAttributes(decodedData.attributes); const bufferViewIndex = options.addBufferView(compressedData); const glTFMesh = { primitives: [ { attributes: fauxAccessors, mode, extensions: { [KHR_DRACO_MESH_COMPRESSION]: { bufferView: bufferViewIndex, attributes: fauxAccessors } } } ] }; return glTFMesh; } function checkPrimitive(primitive) { if (!primitive.attributes && Object.keys(primitive.attributes).length > 0) { throw new Error("glTF: Empty primitive detected: Draco decompression failure?"); } } function* makeMeshPrimitiveIterator(scenegraph) { for (const mesh of scenegraph.json.meshes || []) { for (const primitive of mesh.primitives) { yield primitive; } } } // ../../node_modules/@loaders.gl/gltf/dist/lib/extensions/KHR_texture_transform.js var KHR_texture_transform_exports = {}; __export(KHR_texture_transform_exports, { decode: () => decode7, name: () => name8 }); var KHR_TEXTURE_TRANSFORM = "KHR_texture_transform"; var name8 = KHR_TEXTURE_TRANSFORM; var scratchVector13 = new Vector3(); var scratchRotationMatrix = new Matrix3(); var scratchScaleMatrix = new Matrix3(); async function decode7(gltfData, options) { const gltfScenegraph = new GLTFScenegraph(gltfData); const hasExtension = gltfScenegraph.hasExtension(KHR_TEXTURE_TRANSFORM); if (!hasExtension || !options.gltf?.loadBuffers) { return; } const materials = gltfData.json.materials || []; for (let i3 = 0; i3 < materials.length; i3++) { transformTexCoords(i3, gltfData); } } function transformTexCoords(materialIndex, gltfData) { const material = gltfData.json.materials?.[materialIndex]; const materialTextures = [ material?.pbrMetallicRoughness?.baseColorTexture, material?.emissiveTexture, material?.normalTexture, material?.occlusionTexture, material?.pbrMetallicRoughness?.metallicRoughnessTexture ]; const processedTexCoords = []; for (const textureInfo of materialTextures) { if (textureInfo && textureInfo?.extensions?.[KHR_TEXTURE_TRANSFORM]) { transformPrimitives(gltfData, materialIndex, textureInfo, processedTexCoords); } } } function transformPrimitives(gltfData, materialIndex, texture, processedTexCoords) { const transformParameters = getTransformParameters(texture, processedTexCoords); if (!transformParameters) { return; } const meshes = gltfData.json.meshes || []; for (const mesh of meshes) { for (const primitive of mesh.primitives) { const material = primitive.material; if (Number.isFinite(material) && materialIndex === material) { transformPrimitive(gltfData, primitive, transformParameters); } } } } function getTransformParameters(texture, processedTexCoords) { const textureInfo = texture.extensions?.[KHR_TEXTURE_TRANSFORM]; const { texCoord: originalTexCoord = 0 } = texture; const { texCoord = originalTexCoord } = textureInfo; const isProcessed = processedTexCoords.findIndex(([original, newTexCoord]) => original === originalTexCoord && newTexCoord === texCoord) !== -1; if (!isProcessed) { const matrix = makeTransformationMatrix(textureInfo); if (originalTexCoord !== texCoord) { texture.texCoord = texCoord; } processedTexCoords.push([originalTexCoord, texCoord]); return { originalTexCoord, texCoord, matrix }; } return null; } function transformPrimitive(gltfData, primitive, transformParameters) { const { originalTexCoord, texCoord, matrix } = transformParameters; const texCoordAccessor = primitive.attributes[`TEXCOORD_${originalTexCoord}`]; if (Number.isFinite(texCoordAccessor)) { const accessor = gltfData.json.accessors?.[texCoordAccessor]; if (accessor && accessor.bufferView) { const bufferView = gltfData.json.bufferViews?.[accessor.bufferView]; if (bufferView) { const { arrayBuffer, byteOffset: bufferByteOffset } = gltfData.buffers[bufferView.buffer]; const byteOffset = (bufferByteOffset || 0) + (accessor.byteOffset || 0) + (bufferView.byteOffset || 0); const { ArrayType, length: length5 } = getAccessorArrayTypeAndLength(accessor, bufferView); const bytes = BYTES[accessor.componentType]; const components = COMPONENTS[accessor.type]; const elementAddressScale = bufferView.byteStride || bytes * components; const result = new Float32Array(length5); for (let i3 = 0; i3 < accessor.count; i3++) { const uv = new ArrayType(arrayBuffer, byteOffset + i3 * elementAddressScale, 2); scratchVector13.set(uv[0], uv[1], 1); scratchVector13.transformByMatrix3(matrix); result.set([scratchVector13[0], scratchVector13[1]], i3 * components); } if (originalTexCoord === texCoord) { updateGltf(accessor, bufferView, gltfData.buffers, result); } else { createAttribute(texCoord, accessor, primitive, gltfData, result); } } } } } function updateGltf(accessor, bufferView, buffers, newTexCoordArray) { accessor.componentType = 5126; buffers.push({ arrayBuffer: newTexCoordArray.buffer, byteOffset: 0, byteLength: newTexCoordArray.buffer.byteLength }); bufferView.buffer = buffers.length - 1; bufferView.byteLength = newTexCoordArray.buffer.byteLength; bufferView.byteOffset = 0; delete bufferView.byteStride; } function createAttribute(newTexCoord, originalAccessor, primitive, gltfData, newTexCoordArray) { gltfData.buffers.push({ arrayBuffer: newTexCoordArray.buffer, byteOffset: 0, byteLength: newTexCoordArray.buffer.byteLength }); const bufferViews = gltfData.json.bufferViews; if (!bufferViews) { return; } bufferViews.push({ buffer: gltfData.buffers.length - 1, byteLength: newTexCoordArray.buffer.byteLength, byteOffset: 0 }); const accessors = gltfData.json.accessors; if (!accessors) { return; } accessors.push({ bufferView: bufferViews?.length - 1, byteOffset: 0, componentType: 5126, count: originalAccessor.count, type: "VEC2" }); primitive.attributes[`TEXCOORD_${newTexCoord}`] = accessors.length - 1; } function makeTransformationMatrix(extensionData) { const { offset = [0, 0], rotation = 0, scale: scale6 = [1, 1] } = extensionData; const translationMatrix = new Matrix3().set(1, 0, 0, 0, 1, 0, offset[0], offset[1], 1); const rotationMatrix = scratchRotationMatrix.set(Math.cos(rotation), Math.sin(rotation), 0, -Math.sin(rotation), Math.cos(rotation), 0, 0, 0, 1); const scaleMatrix = scratchScaleMatrix.set(scale6[0], 0, 0, 0, scale6[1], 0, 0, 0, 1); return translationMatrix.multiplyRight(rotationMatrix).multiplyRight(scaleMatrix); } // ../../node_modules/@loaders.gl/gltf/dist/lib/extensions/deprecated/KHR_lights_punctual.js var KHR_lights_punctual_exports = {}; __export(KHR_lights_punctual_exports, { decode: () => decode8, encode: () => encode2, name: () => name9 }); var KHR_LIGHTS_PUNCTUAL = "KHR_lights_punctual"; var name9 = KHR_LIGHTS_PUNCTUAL; async function decode8(gltfData) { const gltfScenegraph = new GLTFScenegraph(gltfData); const { json } = gltfScenegraph; const extension = gltfScenegraph.getExtension(KHR_LIGHTS_PUNCTUAL); if (extension) { gltfScenegraph.json.lights = extension.lights; gltfScenegraph.removeExtension(KHR_LIGHTS_PUNCTUAL); } for (const node of json.nodes || []) { const nodeExtension = gltfScenegraph.getObjectExtension(node, KHR_LIGHTS_PUNCTUAL); if (nodeExtension) { node.light = nodeExtension.light; } gltfScenegraph.removeObjectExtension(node, KHR_LIGHTS_PUNCTUAL); } } async function encode2(gltfData) { const gltfScenegraph = new GLTFScenegraph(gltfData); const { json } = gltfScenegraph; if (json.lights) { const extension = gltfScenegraph.addExtension(KHR_LIGHTS_PUNCTUAL); assert8(!extension.lights); extension.lights = json.lights; delete json.lights; } if (gltfScenegraph.json.lights) { for (const light of gltfScenegraph.json.lights) { const node = light.node; gltfScenegraph.addObjectExtension(node, KHR_LIGHTS_PUNCTUAL, light); } delete gltfScenegraph.json.lights; } } // ../../node_modules/@loaders.gl/gltf/dist/lib/extensions/deprecated/KHR_materials_unlit.js var KHR_materials_unlit_exports = {}; __export(KHR_materials_unlit_exports, { decode: () => decode9, encode: () => encode3, name: () => name10 }); var KHR_MATERIALS_UNLIT = "KHR_materials_unlit"; var name10 = KHR_MATERIALS_UNLIT; async function decode9(gltfData) { const gltfScenegraph = new GLTFScenegraph(gltfData); const { json } = gltfScenegraph; for (const material of json.materials || []) { const extension = material.extensions && material.extensions.KHR_materials_unlit; if (extension) { material.unlit = true; } gltfScenegraph.removeObjectExtension(material, KHR_MATERIALS_UNLIT); } gltfScenegraph.removeExtension(KHR_MATERIALS_UNLIT); } function encode3(gltfData) { const gltfScenegraph = new GLTFScenegraph(gltfData); const { json } = gltfScenegraph; if (gltfScenegraph.materials) { for (const material of json.materials || []) { if (material.unlit) { delete material.unlit; gltfScenegraph.addObjectExtension(material, KHR_MATERIALS_UNLIT, {}); gltfScenegraph.addExtension(KHR_MATERIALS_UNLIT); } } } } // ../../node_modules/@loaders.gl/gltf/dist/lib/extensions/deprecated/KHR_techniques_webgl.js var KHR_techniques_webgl_exports = {}; __export(KHR_techniques_webgl_exports, { decode: () => decode10, encode: () => encode4, name: () => name11 }); var KHR_TECHNIQUES_WEBGL = "KHR_techniques_webgl"; var name11 = KHR_TECHNIQUES_WEBGL; async function decode10(gltfData) { const gltfScenegraph = new GLTFScenegraph(gltfData); const { json } = gltfScenegraph; const extension = gltfScenegraph.getExtension(KHR_TECHNIQUES_WEBGL); if (extension) { const techniques = resolveTechniques(extension, gltfScenegraph); for (const material of json.materials || []) { const materialExtension = gltfScenegraph.getObjectExtension(material, KHR_TECHNIQUES_WEBGL); if (materialExtension) { material.technique = Object.assign( {}, materialExtension, techniques[materialExtension.technique] ); material.technique.values = resolveValues(material.technique, gltfScenegraph); } gltfScenegraph.removeObjectExtension(material, KHR_TECHNIQUES_WEBGL); } gltfScenegraph.removeExtension(KHR_TECHNIQUES_WEBGL); } } async function encode4(gltfData, options) { } function resolveTechniques(techniquesExtension, gltfScenegraph) { const { programs = [], shaders = [], techniques = [] } = techniquesExtension; const textDecoder = new TextDecoder(); shaders.forEach((shader) => { if (Number.isFinite(shader.bufferView)) { shader.code = textDecoder.decode(gltfScenegraph.getTypedArrayForBufferView(shader.bufferView)); } else { throw new Error("KHR_techniques_webgl: no shader code"); } }); programs.forEach((program) => { program.fragmentShader = shaders[program.fragmentShader]; program.vertexShader = shaders[program.vertexShader]; }); techniques.forEach((technique) => { technique.program = programs[technique.program]; }); return techniques; } function resolveValues(technique, gltfScenegraph) { const values = Object.assign({}, technique.values); Object.keys(technique.uniforms || {}).forEach((uniform) => { if (technique.uniforms[uniform].value && !(uniform in values)) { values[uniform] = technique.uniforms[uniform].value; } }); Object.keys(values).forEach((uniform) => { if (typeof values[uniform] === "object" && values[uniform].index !== void 0) { values[uniform].texture = gltfScenegraph.getTexture(values[uniform].index); } }); return values; } // ../../node_modules/@loaders.gl/gltf/dist/lib/api/gltf-extensions.js var EXTENSIONS2 = [ EXT_structural_metadata_exports, EXT_mesh_features_exports, EXT_meshopt_compression_exports, EXT_texture_webp_exports, KHR_texture_basisu_exports, KHR_draco_mesh_compression_exports, KHR_lights_punctual_exports, KHR_materials_unlit_exports, KHR_techniques_webgl_exports, KHR_texture_transform_exports, EXT_feature_metadata_exports ]; function preprocessExtensions(gltf, options = {}, context) { const extensions = EXTENSIONS2.filter((extension) => useExtension(extension.name, options)); for (const extension of extensions) { extension.preprocess?.(gltf, options, context); } } async function decodeExtensions(gltf, options = {}, context) { const extensions = EXTENSIONS2.filter((extension) => useExtension(extension.name, options)); for (const extension of extensions) { await extension.decode?.(gltf, options, context); } } function useExtension(extensionName, options) { const excludes = options?.gltf?.excludeExtensions || {}; const exclude = extensionName in excludes && !excludes[extensionName]; return !exclude; } // ../../node_modules/@loaders.gl/gltf/dist/lib/extensions/KHR_binary_gltf.js var KHR_BINARY_GLTF = "KHR_binary_glTF"; function preprocess4(gltfData) { const gltfScenegraph = new GLTFScenegraph(gltfData); const { json } = gltfScenegraph; for (const image of json.images || []) { const extension = gltfScenegraph.getObjectExtension(image, KHR_BINARY_GLTF); if (extension) { Object.assign(image, extension); } gltfScenegraph.removeObjectExtension(image, KHR_BINARY_GLTF); } if (json.buffers && json.buffers[0]) { delete json.buffers[0].uri; } gltfScenegraph.removeExtension(KHR_BINARY_GLTF); } // ../../node_modules/@loaders.gl/gltf/dist/lib/api/normalize-gltf-v1.js var GLTF_ARRAYS = { accessors: "accessor", animations: "animation", buffers: "buffer", bufferViews: "bufferView", images: "image", materials: "material", meshes: "mesh", nodes: "node", samplers: "sampler", scenes: "scene", skins: "skin", textures: "texture" }; var GLTF_KEYS = { accessor: "accessors", animations: "animation", buffer: "buffers", bufferView: "bufferViews", image: "images", material: "materials", mesh: "meshes", node: "nodes", sampler: "samplers", scene: "scenes", skin: "skins", texture: "textures" }; var GLTFV1Normalizer = class { idToIndexMap = { animations: {}, accessors: {}, buffers: {}, bufferViews: {}, images: {}, materials: {}, meshes: {}, nodes: {}, samplers: {}, scenes: {}, skins: {}, textures: {} }; json; normalize(gltf, options) { this.json = gltf.json; const json = gltf.json; switch (json.asset && json.asset.version) { case "2.0": return; case void 0: case "1.0": break; default: console.warn(`glTF: Unknown version ${json.asset.version}`); return; } if (!options.normalize) { throw new Error("glTF v1 is not supported."); } console.warn("Converting glTF v1 to glTF v2 format. This is experimental and may fail."); this._addAsset(json); this._convertTopLevelObjectsToArrays(json); preprocess4(gltf); this._convertObjectIdsToArrayIndices(json); this._updateObjects(json); this._updateMaterial(json); } _addAsset(json) { json.asset = json.asset || {}; json.asset.version = "2.0"; json.asset.generator = json.asset.generator || "Normalized to glTF 2.0 by loaders.gl"; } _convertTopLevelObjectsToArrays(json) { for (const arrayName in GLTF_ARRAYS) { this._convertTopLevelObjectToArray(json, arrayName); } } _convertTopLevelObjectToArray(json, mapName) { const objectMap = json[mapName]; if (!objectMap || Array.isArray(objectMap)) { return; } json[mapName] = []; for (const id in objectMap) { const object = objectMap[id]; object.id = object.id || id; const index = json[mapName].length; json[mapName].push(object); this.idToIndexMap[mapName][id] = index; } } _convertObjectIdsToArrayIndices(json) { for (const arrayName in GLTF_ARRAYS) { this._convertIdsToIndices(json, arrayName); } if ("scene" in json) { json.scene = this._convertIdToIndex(json.scene, "scene"); } for (const texture of json.textures) { this._convertTextureIds(texture); } for (const mesh of json.meshes) { this._convertMeshIds(mesh); } for (const node of json.nodes) { this._convertNodeIds(node); } for (const node of json.scenes) { this._convertSceneIds(node); } } _convertTextureIds(texture) { if (texture.source) { texture.source = this._convertIdToIndex(texture.source, "image"); } } _convertMeshIds(mesh) { for (const primitive of mesh.primitives) { const { attributes, indices, material } = primitive; for (const attributeName in attributes) { attributes[attributeName] = this._convertIdToIndex(attributes[attributeName], "accessor"); } if (indices) { primitive.indices = this._convertIdToIndex(indices, "accessor"); } if (material) { primitive.material = this._convertIdToIndex(material, "material"); } } } _convertNodeIds(node) { if (node.children) { node.children = node.children.map((child) => this._convertIdToIndex(child, "node")); } if (node.meshes) { node.meshes = node.meshes.map((mesh) => this._convertIdToIndex(mesh, "mesh")); } } _convertSceneIds(scene) { if (scene.nodes) { scene.nodes = scene.nodes.map((node) => this._convertIdToIndex(node, "node")); } } _convertIdsToIndices(json, topLevelArrayName) { if (!json[topLevelArrayName]) { console.warn(`gltf v1: json doesn't contain attribute ${topLevelArrayName}`); json[topLevelArrayName] = []; } for (const object of json[topLevelArrayName]) { for (const key in object) { const id = object[key]; const index = this._convertIdToIndex(id, key); object[key] = index; } } } _convertIdToIndex(id, key) { const arrayName = GLTF_KEYS[key]; if (arrayName in this.idToIndexMap) { const index = this.idToIndexMap[arrayName][id]; if (!Number.isFinite(index)) { throw new Error(`gltf v1: failed to resolve ${key} with id ${id}`); } return index; } return id; } _updateObjects(json) { for (const buffer of this.json.buffers) { delete buffer.type; } } _updateMaterial(json) { for (const material of json.materials) { material.pbrMetallicRoughness = { baseColorFactor: [1, 1, 1, 1], metallicFactor: 1, roughnessFactor: 1 }; const textureId = material.values?.tex || material.values?.texture2d_0 || material.values?.diffuseTex; const textureIndex = json.textures.findIndex((texture) => texture.id === textureId); if (textureIndex !== -1) { material.pbrMetallicRoughness.baseColorTexture = { index: textureIndex }; } } } }; function normalizeGLTFV1(gltf, options = {}) { return new GLTFV1Normalizer().normalize(gltf, options); } // ../../node_modules/@loaders.gl/gltf/dist/lib/parsers/parse-gltf.js async function parseGLTF(gltf, arrayBufferOrString, byteOffset = 0, options, context) { parseGLTFContainerSync(gltf, arrayBufferOrString, byteOffset, options); normalizeGLTFV1(gltf, { normalize: options?.gltf?.normalize }); preprocessExtensions(gltf, options, context); if (options?.gltf?.loadBuffers && gltf.json.buffers) { await loadBuffers(gltf, options, context); } if (options?.gltf?.loadImages) { await loadImages(gltf, options, context); } await decodeExtensions(gltf, options, context); return gltf; } function parseGLTFContainerSync(gltf, data, byteOffset, options) { if (options.uri) { gltf.baseUri = options.uri; } if (data instanceof ArrayBuffer && !isGLB(data, byteOffset, options)) { const textDecoder = new TextDecoder(); data = textDecoder.decode(data); } if (typeof data === "string") { gltf.json = parseJSON(data); } else if (data instanceof ArrayBuffer) { const glb = {}; byteOffset = parseGLBSync(glb, data, byteOffset, options.glb); assert8(glb.type === "glTF", `Invalid GLB magic string ${glb.type}`); gltf._glb = glb; gltf.json = glb.json; } else { assert8(false, "GLTF: must be ArrayBuffer or string"); } const buffers = gltf.json.buffers || []; gltf.buffers = new Array(buffers.length).fill(null); if (gltf._glb && gltf._glb.header.hasBinChunk) { const { binChunks } = gltf._glb; gltf.buffers[0] = { arrayBuffer: binChunks[0].arrayBuffer, byteOffset: binChunks[0].byteOffset, byteLength: binChunks[0].byteLength }; } const images = gltf.json.images || []; gltf.images = new Array(images.length).fill({}); } async function loadBuffers(gltf, options, context) { const buffers = gltf.json.buffers || []; for (let i3 = 0; i3 < buffers.length; ++i3) { const buffer = buffers[i3]; if (buffer.uri) { const { fetch: fetch2 } = context; assert8(fetch2); const uri = resolveUrl(buffer.uri, options); const response = await context?.fetch?.(uri); const arrayBuffer = await response?.arrayBuffer?.(); gltf.buffers[i3] = { arrayBuffer, byteOffset: 0, byteLength: arrayBuffer.byteLength }; delete buffer.uri; } else if (gltf.buffers[i3] === null) { gltf.buffers[i3] = { arrayBuffer: new ArrayBuffer(buffer.byteLength), byteOffset: 0, byteLength: buffer.byteLength }; } } } async function loadImages(gltf, options, context) { const imageIndices = getReferencesImageIndices(gltf); const images = gltf.json.images || []; const promises = []; for (const imageIndex of imageIndices) { promises.push(loadImage(gltf, images[imageIndex], imageIndex, options, context)); } return await Promise.all(promises); } function getReferencesImageIndices(gltf) { const imageIndices = /* @__PURE__ */ new Set(); const textures = gltf.json.textures || []; for (const texture of textures) { if (texture.source !== void 0) { imageIndices.add(texture.source); } } return Array.from(imageIndices).sort(); } async function loadImage(gltf, image, index, options, context) { let arrayBuffer; if (image.uri && !image.hasOwnProperty("bufferView")) { const uri = resolveUrl(image.uri, options); const { fetch: fetch2 } = context; const response = await fetch2(uri); arrayBuffer = await response.arrayBuffer(); image.bufferView = { data: arrayBuffer }; } if (Number.isFinite(image.bufferView)) { const array = getTypedArrayForBufferView(gltf.json, gltf.buffers, image.bufferView); arrayBuffer = sliceArrayBuffer(array.buffer, array.byteOffset, array.byteLength); } assert8(arrayBuffer, "glTF image has no data"); let parsedImage = await parseFromContext(arrayBuffer, [ImageLoader, BasisLoader], { ...options, mimeType: image.mimeType, basis: options.basis || { format: selectSupportedBasisFormat() } }, context); if (parsedImage && parsedImage[0]) { parsedImage = { compressed: true, mipmaps: false, width: parsedImage[0].width, height: parsedImage[0].height, data: parsedImage[0] }; } gltf.images = gltf.images || []; gltf.images[index] = parsedImage; } // ../../node_modules/@loaders.gl/gltf/dist/gltf-loader.js var GLTFLoader = { dataType: null, batchType: null, name: "glTF", id: "gltf", module: "gltf", version: VERSION10, extensions: ["gltf", "glb"], mimeTypes: ["model/gltf+json", "model/gltf-binary"], text: true, binary: true, tests: ["glTF"], parse: parse2, options: { gltf: { normalize: true, loadBuffers: true, loadImages: true, decompressMeshes: true }, log: console } }; async function parse2(arrayBuffer, options = {}, context) { options = { ...GLTFLoader.options, ...options }; options.gltf = { ...GLTFLoader.options.gltf, ...options.gltf }; const { byteOffset = 0 } = options; const gltf = {}; return await parseGLTF(gltf, arrayBuffer, byteOffset, options, context); } // ../../node_modules/@loaders.gl/gltf/dist/lib/api/post-process-gltf.js var COMPONENTS2 = { SCALAR: 1, VEC2: 2, VEC3: 3, VEC4: 4, MAT2: 4, MAT3: 9, MAT4: 16 }; var BYTES2 = { 5120: 1, 5121: 1, 5122: 2, 5123: 2, 5125: 4, 5126: 4 }; var GL_SAMPLER = { TEXTURE_MAG_FILTER: 10240, TEXTURE_MIN_FILTER: 10241, TEXTURE_WRAP_S: 10242, TEXTURE_WRAP_T: 10243, REPEAT: 10497, LINEAR: 9729, NEAREST_MIPMAP_LINEAR: 9986 }; var SAMPLER_PARAMETER_GLTF_TO_GL = { magFilter: GL_SAMPLER.TEXTURE_MAG_FILTER, minFilter: GL_SAMPLER.TEXTURE_MIN_FILTER, wrapS: GL_SAMPLER.TEXTURE_WRAP_S, wrapT: GL_SAMPLER.TEXTURE_WRAP_T }; var DEFAULT_SAMPLER_PARAMETERS = { [GL_SAMPLER.TEXTURE_MAG_FILTER]: GL_SAMPLER.LINEAR, [GL_SAMPLER.TEXTURE_MIN_FILTER]: GL_SAMPLER.NEAREST_MIPMAP_LINEAR, [GL_SAMPLER.TEXTURE_WRAP_S]: GL_SAMPLER.REPEAT, [GL_SAMPLER.TEXTURE_WRAP_T]: GL_SAMPLER.REPEAT }; function makeDefaultSampler() { return { id: "default-sampler", parameters: DEFAULT_SAMPLER_PARAMETERS }; } function getBytesFromComponentType(componentType) { return BYTES2[componentType]; } function getSizeFromAccessorType(type) { return COMPONENTS2[type]; } var GLTFPostProcessor = class { baseUri = ""; jsonUnprocessed; json; buffers = []; images = []; postProcess(gltf, options = {}) { const { json, buffers = [], images = [] } = gltf; const { baseUri = "" } = gltf; assert8(json); this.baseUri = baseUri; this.buffers = buffers; this.images = images; this.jsonUnprocessed = json; this.json = this._resolveTree(gltf.json, options); return this.json; } _resolveTree(gltf, options = {}) { const json = { ...gltf }; this.json = json; if (gltf.bufferViews) { json.bufferViews = gltf.bufferViews.map((bufView, i3) => this._resolveBufferView(bufView, i3)); } if (gltf.images) { json.images = gltf.images.map((image, i3) => this._resolveImage(image, i3)); } if (gltf.samplers) { json.samplers = gltf.samplers.map((sampler, i3) => this._resolveSampler(sampler, i3)); } if (gltf.textures) { json.textures = gltf.textures.map((texture, i3) => this._resolveTexture(texture, i3)); } if (gltf.accessors) { json.accessors = gltf.accessors.map((accessor, i3) => this._resolveAccessor(accessor, i3)); } if (gltf.materials) { json.materials = gltf.materials.map((material, i3) => this._resolveMaterial(material, i3)); } if (gltf.meshes) { json.meshes = gltf.meshes.map((mesh, i3) => this._resolveMesh(mesh, i3)); } if (gltf.nodes) { json.nodes = gltf.nodes.map((node, i3) => this._resolveNode(node, i3)); json.nodes = json.nodes.map((node, i3) => this._resolveNodeChildren(node)); } if (gltf.skins) { json.skins = gltf.skins.map((skin, i3) => this._resolveSkin(skin, i3)); } if (gltf.scenes) { json.scenes = gltf.scenes.map((scene, i3) => this._resolveScene(scene, i3)); } if (typeof this.json.scene === "number" && json.scenes) { json.scene = json.scenes[this.json.scene]; } return json; } getScene(index) { return this._get(this.json.scenes, index); } getNode(index) { return this._get(this.json.nodes, index); } getSkin(index) { return this._get(this.json.skins, index); } getMesh(index) { return this._get(this.json.meshes, index); } getMaterial(index) { return this._get(this.json.materials, index); } getAccessor(index) { return this._get(this.json.accessors, index); } getCamera(index) { return this._get(this.json.cameras, index); } getTexture(index) { return this._get(this.json.textures, index); } getSampler(index) { return this._get(this.json.samplers, index); } getImage(index) { return this._get(this.json.images, index); } getBufferView(index) { return this._get(this.json.bufferViews, index); } getBuffer(index) { return this._get(this.json.buffers, index); } _get(array, index) { if (typeof index === "object") { return index; } const object = array && array[index]; if (!object) { console.warn(`glTF file error: Could not find ${array}[${index}]`); } return object; } _resolveScene(scene, index) { return { ...scene, id: scene.id || `scene-${index}`, nodes: (scene.nodes || []).map((node) => this.getNode(node)) }; } _resolveNode(gltfNode, index) { const node = { ...gltfNode, id: gltfNode?.id || `node-${index}` }; if (gltfNode.mesh !== void 0) { node.mesh = this.getMesh(gltfNode.mesh); } if (gltfNode.camera !== void 0) { node.camera = this.getCamera(gltfNode.camera); } if (gltfNode.skin !== void 0) { node.skin = this.getSkin(gltfNode.skin); } if (gltfNode.meshes !== void 0 && gltfNode.meshes.length) { node.mesh = gltfNode.meshes.reduce((accum, meshIndex) => { const mesh = this.getMesh(meshIndex); accum.id = mesh.id; accum.primitives = accum.primitives.concat(mesh.primitives); return accum; }, { primitives: [] }); } return node; } _resolveNodeChildren(node) { if (node.children) { node.children = node.children.map((child) => this.getNode(child)); } return node; } _resolveSkin(gltfSkin, index) { const inverseBindMatrices = typeof gltfSkin.inverseBindMatrices === "number" ? this.getAccessor(gltfSkin.inverseBindMatrices) : void 0; return { ...gltfSkin, id: gltfSkin.id || `skin-${index}`, inverseBindMatrices }; } _resolveMesh(gltfMesh, index) { const mesh = { ...gltfMesh, id: gltfMesh.id || `mesh-${index}`, primitives: [] }; if (gltfMesh.primitives) { mesh.primitives = gltfMesh.primitives.map((gltfPrimitive) => { const primitive = { ...gltfPrimitive, attributes: {}, indices: void 0, material: void 0 }; const attributes = gltfPrimitive.attributes; for (const attribute in attributes) { primitive.attributes[attribute] = this.getAccessor(attributes[attribute]); } if (gltfPrimitive.indices !== void 0) { primitive.indices = this.getAccessor(gltfPrimitive.indices); } if (gltfPrimitive.material !== void 0) { primitive.material = this.getMaterial(gltfPrimitive.material); } return primitive; }); } return mesh; } _resolveMaterial(gltfMaterial, index) { const material = { ...gltfMaterial, id: gltfMaterial.id || `material-${index}` }; if (material.normalTexture) { material.normalTexture = { ...material.normalTexture }; material.normalTexture.texture = this.getTexture(material.normalTexture.index); } if (material.occlusionTexture) { material.occlusionTexture = { ...material.occlusionTexture }; material.occlusionTexture.texture = this.getTexture(material.occlusionTexture.index); } if (material.emissiveTexture) { material.emissiveTexture = { ...material.emissiveTexture }; material.emissiveTexture.texture = this.getTexture(material.emissiveTexture.index); } if (!material.emissiveFactor) { material.emissiveFactor = material.emissiveTexture ? [1, 1, 1] : [0, 0, 0]; } if (material.pbrMetallicRoughness) { material.pbrMetallicRoughness = { ...material.pbrMetallicRoughness }; const mr = material.pbrMetallicRoughness; if (mr.baseColorTexture) { mr.baseColorTexture = { ...mr.baseColorTexture }; mr.baseColorTexture.texture = this.getTexture(mr.baseColorTexture.index); } if (mr.metallicRoughnessTexture) { mr.metallicRoughnessTexture = { ...mr.metallicRoughnessTexture }; mr.metallicRoughnessTexture.texture = this.getTexture(mr.metallicRoughnessTexture.index); } } return material; } _resolveAccessor(gltfAccessor, index) { const bytesPerComponent = getBytesFromComponentType(gltfAccessor.componentType); const components = getSizeFromAccessorType(gltfAccessor.type); const bytesPerElement = bytesPerComponent * components; const accessor = { ...gltfAccessor, id: gltfAccessor.id || `accessor-${index}`, bytesPerComponent, components, bytesPerElement, value: void 0, bufferView: void 0, sparse: void 0 }; if (gltfAccessor.bufferView !== void 0) { accessor.bufferView = this.getBufferView(gltfAccessor.bufferView); } if (accessor.bufferView) { const buffer = accessor.bufferView.buffer; const { ArrayType, byteLength } = getAccessorArrayTypeAndLength(accessor, accessor.bufferView); const byteOffset = (accessor.bufferView.byteOffset || 0) + (accessor.byteOffset || 0) + buffer.byteOffset; let cutBuffer = buffer.arrayBuffer.slice(byteOffset, byteOffset + byteLength); if (accessor.bufferView.byteStride) { cutBuffer = this._getValueFromInterleavedBuffer(buffer, byteOffset, accessor.bufferView.byteStride, accessor.bytesPerElement, accessor.count); } accessor.value = new ArrayType(cutBuffer); } return accessor; } _getValueFromInterleavedBuffer(buffer, byteOffset, byteStride, bytesPerElement, count) { const result = new Uint8Array(count * bytesPerElement); for (let i3 = 0; i3 < count; i3++) { const elementOffset = byteOffset + i3 * byteStride; result.set(new Uint8Array(buffer.arrayBuffer.slice(elementOffset, elementOffset + bytesPerElement)), i3 * bytesPerElement); } return result.buffer; } _resolveTexture(gltfTexture, index) { return { ...gltfTexture, id: gltfTexture.id || `texture-${index}`, sampler: typeof gltfTexture.sampler === "number" ? this.getSampler(gltfTexture.sampler) : makeDefaultSampler(), source: typeof gltfTexture.source === "number" ? this.getImage(gltfTexture.source) : void 0 }; } _resolveSampler(gltfSampler, index) { const sampler = { id: gltfSampler.id || `sampler-${index}`, ...gltfSampler, parameters: {} }; for (const key in sampler) { const glEnum = this._enumSamplerParameter(key); if (glEnum !== void 0) { sampler.parameters[glEnum] = sampler[key]; } } return sampler; } _enumSamplerParameter(key) { return SAMPLER_PARAMETER_GLTF_TO_GL[key]; } _resolveImage(gltfImage, index) { const image = { ...gltfImage, id: gltfImage.id || `image-${index}`, image: null, bufferView: gltfImage.bufferView !== void 0 ? this.getBufferView(gltfImage.bufferView) : void 0 }; const preloadedImage = this.images[index]; if (preloadedImage) { image.image = preloadedImage; } return image; } _resolveBufferView(gltfBufferView, index) { const bufferIndex = gltfBufferView.buffer; const arrayBuffer = this.buffers[bufferIndex].arrayBuffer; let byteOffset = this.buffers[bufferIndex].byteOffset || 0; if (gltfBufferView.byteOffset) { byteOffset += gltfBufferView.byteOffset; } const bufferView = { id: `bufferView-${index}`, ...gltfBufferView, buffer: this.buffers[bufferIndex], data: new Uint8Array(arrayBuffer, byteOffset, gltfBufferView.byteLength) }; return bufferView; } _resolveCamera(gltfCamera, index) { const camera = { ...gltfCamera, id: gltfCamera.id || `camera-${index}` }; if (camera.perspective) { } if (camera.orthographic) { } return camera; } }; function postProcessGLTF(gltf, options) { return new GLTFPostProcessor().postProcess(gltf, options); } // ../../node_modules/@loaders.gl/3d-tiles/dist/lib/parsers/helpers/parse-3d-tile-gltf-view.js var GLTF_FORMAT = { URI: 0, EMBEDDED: 1 }; function parse3DTileGLTFViewSync(tile, arrayBuffer, byteOffset, options) { tile.rotateYtoZ = true; const gltfByteLength = (tile.byteOffset || 0) + (tile.byteLength || 0) - byteOffset; if (gltfByteLength === 0) { throw new Error("glTF byte length must be greater than 0."); } tile.gltfUpAxis = options?.["3d-tiles"] && options["3d-tiles"].assetGltfUpAxis ? options["3d-tiles"].assetGltfUpAxis : "Y"; tile.gltfArrayBuffer = sliceArrayBuffer(arrayBuffer, byteOffset, gltfByteLength); tile.gltfByteOffset = 0; tile.gltfByteLength = gltfByteLength; if (byteOffset % 4 === 0) { } else { console.warn(`${tile.type}: embedded glb is not aligned to a 4-byte boundary.`); } return (tile.byteOffset || 0) + (tile.byteLength || 0); } async function extractGLTF(tile, gltfFormat, options, context) { const tile3DOptions = options?.["3d-tiles"] || {}; extractGLTFBufferOrURL(tile, gltfFormat, options); if (tile3DOptions.loadGLTF) { if (!context) { return; } if (tile.gltfUrl) { const { fetch: fetch2 } = context; const response = await fetch2(tile.gltfUrl, options); tile.gltfArrayBuffer = await response.arrayBuffer(); tile.gltfByteOffset = 0; } if (tile.gltfArrayBuffer) { const gltfWithBuffers = await parseFromContext(tile.gltfArrayBuffer, GLTFLoader, options, context); tile.gltf = postProcessGLTF(gltfWithBuffers); tile.gpuMemoryUsageInBytes = getMemoryUsageGLTF(tile.gltf); delete tile.gltfArrayBuffer; delete tile.gltfByteOffset; delete tile.gltfByteLength; } } } function extractGLTFBufferOrURL(tile, gltfFormat, options) { switch (gltfFormat) { case GLTF_FORMAT.URI: if (tile.gltfArrayBuffer) { const gltfUrlBytes = new Uint8Array(tile.gltfArrayBuffer, tile.gltfByteOffset); const textDecoder = new TextDecoder(); const gltfUrl = textDecoder.decode(gltfUrlBytes); tile.gltfUrl = gltfUrl.replace(/[\s\0]+$/, ""); } delete tile.gltfArrayBuffer; delete tile.gltfByteOffset; delete tile.gltfByteLength; break; case GLTF_FORMAT.EMBEDDED: break; default: throw new Error("b3dm: Illegal glTF format field"); } } // ../../node_modules/@loaders.gl/3d-tiles/dist/lib/parsers/parse-3d-tile-batched-model.js async function parseBatchedModel3DTile(tile, arrayBuffer, byteOffset, options, context) { byteOffset = parseBatchedModel(tile, arrayBuffer, byteOffset, options, context); await extractGLTF(tile, GLTF_FORMAT.EMBEDDED, options, context); const extensions = tile?.gltf?.extensions; if (extensions && extensions.CESIUM_RTC) { tile.rtcCenter = extensions.CESIUM_RTC.center; } return byteOffset; } function parseBatchedModel(tile, arrayBuffer, byteOffset, options, context) { byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset); byteOffset = parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset); byteOffset = parse3DTileTablesSync(tile, arrayBuffer, byteOffset, options); byteOffset = parse3DTileGLTFViewSync(tile, arrayBuffer, byteOffset, options); const featureTable = new Tile3DFeatureTable(tile.featureTableJson, tile.featureTableBinary); tile.rtcCenter = featureTable.getGlobalProperty("RTC_CENTER", GL2.FLOAT, 3); return byteOffset; } // ../../node_modules/@loaders.gl/3d-tiles/dist/lib/parsers/parse-3d-tile-instanced-model.js async function parseInstancedModel3DTile(tile, arrayBuffer, byteOffset, options, context) { byteOffset = parseInstancedModel(tile, arrayBuffer, byteOffset, options, context); await extractGLTF(tile, tile.gltfFormat || 0, options, context); return byteOffset; } function parseInstancedModel(tile, arrayBuffer, byteOffset, options, context) { byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset); if (tile.version !== 1) { throw new Error(`Instanced 3D Model version ${tile.version} is not supported`); } byteOffset = parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset); const view = new DataView(arrayBuffer); tile.gltfFormat = view.getUint32(byteOffset, true); byteOffset += 4; byteOffset = parse3DTileTablesSync(tile, arrayBuffer, byteOffset, options); byteOffset = parse3DTileGLTFViewSync(tile, arrayBuffer, byteOffset, options); if (!tile?.header?.featureTableJsonByteLength || tile.header.featureTableJsonByteLength === 0) { throw new Error("i3dm parser: featureTableJsonByteLength is zero."); } const featureTable = new Tile3DFeatureTable(tile.featureTableJson, tile.featureTableBinary); const instancesLength = featureTable.getGlobalProperty("INSTANCES_LENGTH"); featureTable.featuresLength = instancesLength; if (!Number.isFinite(instancesLength)) { throw new Error("i3dm parser: INSTANCES_LENGTH must be defined"); } tile.eastNorthUp = featureTable.getGlobalProperty("EAST_NORTH_UP"); tile.rtcCenter = featureTable.getGlobalProperty("RTC_CENTER", GL2.FLOAT, 3); const batchTable = new Tile3DBatchTableParser(tile.batchTableJson, tile.batchTableBinary, instancesLength); extractInstancedAttributes(tile, featureTable, batchTable, instancesLength); return byteOffset; } function extractInstancedAttributes(tile, featureTable, batchTable, instancesLength) { const instances = new Array(instancesLength); const instancePosition = new Vector3(); const instanceNormalRight = new Vector3(); const instanceNormalUp = new Vector3(); const instanceNormalForward = new Vector3(); const instanceRotation = new Matrix3(); const instanceQuaternion = new Quaternion(); const instanceScale = new Vector3(); const instanceTranslationRotationScale = {}; const instanceTransform = new Matrix4(); const scratch1 = []; const scratch2 = []; const scratch3 = []; const scratch4 = []; for (let i3 = 0; i3 < instancesLength; i3++) { let position; if (featureTable.hasProperty("POSITION")) { position = featureTable.getProperty("POSITION", GL2.FLOAT, 3, i3, instancePosition); } else if (featureTable.hasProperty("POSITION_QUANTIZED")) { position = featureTable.getProperty("POSITION_QUANTIZED", GL2.UNSIGNED_SHORT, 3, i3, instancePosition); const quantizedVolumeOffset = featureTable.getGlobalProperty("QUANTIZED_VOLUME_OFFSET", GL2.FLOAT, 3); if (!quantizedVolumeOffset) { throw new Error("i3dm parser: QUANTIZED_VOLUME_OFFSET must be defined for quantized positions."); } const quantizedVolumeScale = featureTable.getGlobalProperty("QUANTIZED_VOLUME_SCALE", GL2.FLOAT, 3); if (!quantizedVolumeScale) { throw new Error("i3dm parser: QUANTIZED_VOLUME_SCALE must be defined for quantized positions."); } const MAX_UNSIGNED_SHORT = 65535; for (let j = 0; j < 3; j++) { position[j] = position[j] / MAX_UNSIGNED_SHORT * quantizedVolumeScale[j] + quantizedVolumeOffset[j]; } } if (!position) { throw new Error("i3dm: POSITION or POSITION_QUANTIZED must be defined for each instance."); } instancePosition.copy(position); instanceTranslationRotationScale.translation = instancePosition; tile.normalUp = featureTable.getProperty("NORMAL_UP", GL2.FLOAT, 3, i3, scratch1); tile.normalRight = featureTable.getProperty("NORMAL_RIGHT", GL2.FLOAT, 3, i3, scratch2); const hasCustomOrientation = false; if (tile.normalUp) { if (!tile.normalRight) { throw new Error("i3dm: Custom orientation requires both NORMAL_UP and NORMAL_RIGHT."); } tile.hasCustomOrientation = true; } else { tile.octNormalUp = featureTable.getProperty("NORMAL_UP_OCT32P", GL2.UNSIGNED_SHORT, 2, i3, scratch1); tile.octNormalRight = featureTable.getProperty("NORMAL_RIGHT_OCT32P", GL2.UNSIGNED_SHORT, 2, i3, scratch2); if (tile.octNormalUp) { if (!tile.octNormalRight) { throw new Error("i3dm: oct-encoded orientation requires NORMAL_UP_OCT32P and NORMAL_RIGHT_OCT32P"); } throw new Error("i3dm: oct-encoded orientation not implemented"); } else if (tile.eastNorthUp) { Ellipsoid.WGS84.eastNorthUpToFixedFrame(instancePosition, instanceTransform); instanceTransform.getRotationMatrix3(instanceRotation); } else { instanceRotation.identity(); } } if (hasCustomOrientation) { instanceNormalForward.copy(instanceNormalRight).cross(instanceNormalUp).normalize(); instanceRotation.setColumn(0, instanceNormalRight); instanceRotation.setColumn(1, instanceNormalUp); instanceRotation.setColumn(2, instanceNormalForward); } instanceQuaternion.fromMatrix3(instanceRotation); instanceTranslationRotationScale.rotation = instanceQuaternion; instanceScale.set(1, 1, 1); const scale6 = featureTable.getProperty("SCALE", GL2.FLOAT, 1, i3, scratch3); if (Number.isFinite(scale6)) { instanceScale.multiplyByScalar(scale6); } const nonUniformScale = featureTable.getProperty("SCALE_NON_UNIFORM", GL2.FLOAT, 3, i3, scratch1); if (nonUniformScale) { instanceScale.scale(nonUniformScale); } instanceTranslationRotationScale.scale = instanceScale; let batchId = featureTable.getProperty("BATCH_ID", GL2.UNSIGNED_SHORT, 1, i3, scratch4); if (batchId === void 0) { batchId = i3; } const rotationMatrix = new Matrix4().fromQuaternion(instanceTranslationRotationScale.rotation); instanceTransform.identity(); instanceTransform.translate(instanceTranslationRotationScale.translation); instanceTransform.multiplyRight(rotationMatrix); instanceTransform.scale(instanceTranslationRotationScale.scale); const modelMatrix = instanceTransform.clone(); instances[i3] = { modelMatrix, batchId }; } tile.instances = instances; } // ../../node_modules/@loaders.gl/3d-tiles/dist/lib/parsers/parse-3d-tile-composite.js async function parseComposite3DTile(tile, arrayBuffer, byteOffset, options, context, parse3DTile2) { byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset); const view = new DataView(arrayBuffer); tile.tilesLength = view.getUint32(byteOffset, true); byteOffset += 4; tile.tiles = []; while (tile.tiles.length < tile.tilesLength && (tile.byteLength || 0) - byteOffset > 12) { const subtile = { shape: "tile3d" }; tile.tiles.push(subtile); byteOffset = await parse3DTile2(arrayBuffer, byteOffset, options, context, subtile); } return byteOffset; } // ../../node_modules/@loaders.gl/3d-tiles/dist/lib/parsers/parse-3d-tile-gltf.js async function parseGltf3DTile(tile, arrayBuffer, options, context) { tile.rotateYtoZ = true; tile.gltfUpAxis = options?.["3d-tiles"]?.assetGltfUpAxis ? options["3d-tiles"].assetGltfUpAxis : "Y"; if (options?.["3d-tiles"]?.loadGLTF) { if (!context) { return arrayBuffer.byteLength; } const gltfWithBuffers = await parseFromContext(arrayBuffer, GLTFLoader, options, context); tile.gltf = postProcessGLTF(gltfWithBuffers); tile.gpuMemoryUsageInBytes = getMemoryUsageGLTF(tile.gltf); } else { tile.gltfArrayBuffer = arrayBuffer; } return arrayBuffer.byteLength; } // ../../node_modules/@loaders.gl/3d-tiles/dist/lib/parsers/parse-3d-tile.js async function parse3DTile(arrayBuffer, byteOffset = 0, options, context, tile = { shape: "tile3d" }) { tile.byteOffset = byteOffset; tile.type = getMagicString2(arrayBuffer, byteOffset); switch (tile.type) { case TILE3D_TYPE.COMPOSITE: return await parseComposite3DTile(tile, arrayBuffer, byteOffset, options, context, parse3DTile); case TILE3D_TYPE.BATCHED_3D_MODEL: return await parseBatchedModel3DTile(tile, arrayBuffer, byteOffset, options, context); case TILE3D_TYPE.GLTF: return await parseGltf3DTile(tile, arrayBuffer, options, context); case TILE3D_TYPE.INSTANCED_3D_MODEL: return await parseInstancedModel3DTile(tile, arrayBuffer, byteOffset, options, context); case TILE3D_TYPE.POINT_CLOUD: return await parsePointCloud3DTile(tile, arrayBuffer, byteOffset, options, context); default: throw new Error(`3DTileLoader: unknown type ${tile.type}`); } } // ../../node_modules/@loaders.gl/3d-tiles/dist/lib/parsers/helpers/parse-3d-tile-subtree.js var SUBTREE_FILE_MAGIC = 1952609651; var SUBTREE_FILE_VERSION = 1; async function parse3DTilesSubtree(data, options, context) { const magic = new Uint32Array(data.slice(0, 4)); if (magic[0] !== SUBTREE_FILE_MAGIC) { throw new Error("Wrong subtree file magic number"); } const version = new Uint32Array(data.slice(4, 8)); if (version[0] !== SUBTREE_FILE_VERSION) { throw new Error("Wrong subtree file verson, must be 1"); } const jsonByteLength = parseUint64Value(data.slice(8, 16)); const stringAttribute = new Uint8Array(data, 24, jsonByteLength); const textDecoder = new TextDecoder("utf8"); const string = textDecoder.decode(stringAttribute); const subtree = JSON.parse(string); const binaryByteLength = parseUint64Value(data.slice(16, 24)); let internalBinaryBuffer = new ArrayBuffer(0); if (binaryByteLength) { internalBinaryBuffer = data.slice(24 + jsonByteLength); } await loadExplicitBitstream(subtree, subtree.tileAvailability, internalBinaryBuffer, context); if (Array.isArray(subtree.contentAvailability)) { for (const contentAvailability of subtree.contentAvailability) { await loadExplicitBitstream(subtree, contentAvailability, internalBinaryBuffer, context); } } else { await loadExplicitBitstream(subtree, subtree.contentAvailability, internalBinaryBuffer, context); } await loadExplicitBitstream(subtree, subtree.childSubtreeAvailability, internalBinaryBuffer, context); return subtree; } async function loadExplicitBitstream(subtree, availabilityObject, internalBinaryBuffer, context) { const bufferViewIndex = Number.isFinite(availabilityObject.bitstream) ? availabilityObject.bitstream : availabilityObject.bufferView; if (typeof bufferViewIndex !== "number") { return; } const bufferView = subtree.bufferViews[bufferViewIndex]; const buffer = subtree.buffers[bufferView.buffer]; if (!context?.baseUrl) { throw new Error("Url is not provided"); } if (!context.fetch) { throw new Error("fetch is not provided"); } if (buffer.uri) { const bufferUri = `${context?.baseUrl || ""}/${buffer.uri}`; const response = await context.fetch(bufferUri); const data = await response.arrayBuffer(); availabilityObject.explicitBitstream = new Uint8Array(data, bufferView.byteOffset, bufferView.byteLength); return; } const bufferStart = subtree.buffers.slice(0, bufferView.buffer).reduce((offset, buf) => offset + buf.byteLength, 0); availabilityObject.explicitBitstream = new Uint8Array(internalBinaryBuffer.slice(bufferStart, bufferStart + buffer.byteLength), bufferView.byteOffset, bufferView.byteLength); } function parseUint64Value(buffer) { const dataView = new DataView(buffer); const left = dataView.getUint32(0, true); const right = dataView.getUint32(4, true); return left + 2 ** 32 * right; } // ../../node_modules/@loaders.gl/3d-tiles/dist/tile-3d-subtree-loader.js var Tile3DSubtreeLoader = { dataType: null, batchType: null, id: "3d-tiles-subtree", name: "3D Tiles Subtree", module: "3d-tiles", version: VERSION8, extensions: ["subtree"], mimeTypes: ["application/octet-stream"], tests: ["subtree"], parse: parse3DTilesSubtree, options: {} }; // ../../node_modules/@loaders.gl/3d-tiles/dist/lib/parsers/parse-3d-tile-header.js var import_core42 = __toESM(require_core3(), 1); // ../../node_modules/@loaders.gl/3d-tiles/dist/lib/parsers/helpers/parse-3d-implicit-tiles.js var import_core41 = __toESM(require_core3(), 1); // ../../node_modules/@loaders.gl/3d-tiles/node_modules/long/index.js var wasm = null; try { wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([ 0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11 ])), {}).exports; } catch (e) { } function Long3(low, high, unsigned) { this.low = low | 0; this.high = high | 0; this.unsigned = !!unsigned; } Long3.prototype.__isLong__; Object.defineProperty(Long3.prototype, "__isLong__", { value: true }); function isLong(obj) { return (obj && obj["__isLong__"]) === true; } function ctz32(value) { var c = Math.clz32(value & -value); return value ? 31 - c : c; } Long3.isLong = isLong; var INT_CACHE = {}; var UINT_CACHE = {}; function fromInt(value, unsigned) { var obj, cachedObj, cache2; if (unsigned) { value >>>= 0; if (cache2 = 0 <= value && value < 256) { cachedObj = UINT_CACHE[value]; if (cachedObj) return cachedObj; } obj = fromBits(value, 0, true); if (cache2) UINT_CACHE[value] = obj; return obj; } else { value |= 0; if (cache2 = -128 <= value && value < 128) { cachedObj = INT_CACHE[value]; if (cachedObj) return cachedObj; } obj = fromBits(value, value < 0 ? -1 : 0, false); if (cache2) INT_CACHE[value] = obj; return obj; } } Long3.fromInt = fromInt; function fromNumber(value, unsigned) { if (isNaN(value)) return unsigned ? UZERO : ZERO4; if (unsigned) { if (value < 0) return UZERO; if (value >= TWO_PWR_64_DBL) return MAX_UNSIGNED_VALUE; } else { if (value <= -TWO_PWR_63_DBL) return MIN_VALUE; if (value + 1 >= TWO_PWR_63_DBL) return MAX_VALUE; } if (value < 0) return fromNumber(-value, unsigned).neg(); return fromBits(value % TWO_PWR_32_DBL | 0, value / TWO_PWR_32_DBL | 0, unsigned); } Long3.fromNumber = fromNumber; function fromBits(lowBits, highBits, unsigned) { return new Long3(lowBits, highBits, unsigned); } Long3.fromBits = fromBits; var pow_dbl = Math.pow; function fromString(str3, unsigned, radix) { if (str3.length === 0) throw Error("empty string"); if (typeof unsigned === "number") { radix = unsigned; unsigned = false; } else { unsigned = !!unsigned; } if (str3 === "NaN" || str3 === "Infinity" || str3 === "+Infinity" || str3 === "-Infinity") return unsigned ? UZERO : ZERO4; radix = radix || 10; if (radix < 2 || 36 < radix) throw RangeError("radix"); var p2; if ((p2 = str3.indexOf("-")) > 0) throw Error("interior hyphen"); else if (p2 === 0) { return fromString(str3.substring(1), unsigned, radix).neg(); } var radixToPower = fromNumber(pow_dbl(radix, 8)); var result = ZERO4; for (var i3 = 0; i3 < str3.length; i3 += 8) { var size = Math.min(8, str3.length - i3), value = parseInt(str3.substring(i3, i3 + size), radix); if (size < 8) { var power = fromNumber(pow_dbl(radix, size)); result = result.mul(power).add(fromNumber(value)); } else { result = result.mul(radixToPower); result = result.add(fromNumber(value)); } } result.unsigned = unsigned; return result; } Long3.fromString = fromString; function fromValue(val2, unsigned) { if (typeof val2 === "number") return fromNumber(val2, unsigned); if (typeof val2 === "string") return fromString(val2, unsigned); return fromBits(val2.low, val2.high, typeof unsigned === "boolean" ? unsigned : val2.unsigned); } Long3.fromValue = fromValue; var TWO_PWR_16_DBL = 1 << 16; var TWO_PWR_24_DBL = 1 << 24; var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL); var ZERO4 = fromInt(0); Long3.ZERO = ZERO4; var UZERO = fromInt(0, true); Long3.UZERO = UZERO; var ONE = fromInt(1); Long3.ONE = ONE; var UONE = fromInt(1, true); Long3.UONE = UONE; var NEG_ONE = fromInt(-1); Long3.NEG_ONE = NEG_ONE; var MAX_VALUE = fromBits(4294967295 | 0, 2147483647 | 0, false); Long3.MAX_VALUE = MAX_VALUE; var MAX_UNSIGNED_VALUE = fromBits(4294967295 | 0, 4294967295 | 0, true); Long3.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE; var MIN_VALUE = fromBits(0, 2147483648 | 0, false); Long3.MIN_VALUE = MIN_VALUE; var LongPrototype = Long3.prototype; LongPrototype.toInt = function toInt() { return this.unsigned ? this.low >>> 0 : this.low; }; LongPrototype.toNumber = function toNumber() { if (this.unsigned) return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); return this.high * TWO_PWR_32_DBL + (this.low >>> 0); }; LongPrototype.toString = function toString(radix) { radix = radix || 10; if (radix < 2 || 36 < radix) throw RangeError("radix"); if (this.isZero()) return "0"; if (this.isNegative()) { if (this.eq(MIN_VALUE)) { var radixLong = fromNumber(radix), div2 = this.div(radixLong), rem1 = div2.mul(radixLong).sub(this); return div2.toString(radix) + rem1.toInt().toString(radix); } else return "-" + this.neg().toString(radix); } var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned), rem = this; var result = ""; while (true) { var remDiv = rem.div(radixToPower), intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0, digits = intval.toString(radix); rem = remDiv; if (rem.isZero()) return digits + result; else { while (digits.length < 6) digits = "0" + digits; result = "" + digits + result; } } }; LongPrototype.getHighBits = function getHighBits() { return this.high; }; LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() { return this.high >>> 0; }; LongPrototype.getLowBits = function getLowBits() { return this.low; }; LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() { return this.low >>> 0; }; LongPrototype.getNumBitsAbs = function getNumBitsAbs() { if (this.isNegative()) return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); var val2 = this.high != 0 ? this.high : this.low; for (var bit = 31; bit > 0; bit--) if ((val2 & 1 << bit) != 0) break; return this.high != 0 ? bit + 33 : bit + 1; }; LongPrototype.isZero = function isZero() { return this.high === 0 && this.low === 0; }; LongPrototype.eqz = LongPrototype.isZero; LongPrototype.isNegative = function isNegative() { return !this.unsigned && this.high < 0; }; LongPrototype.isPositive = function isPositive() { return this.unsigned || this.high >= 0; }; LongPrototype.isOdd = function isOdd() { return (this.low & 1) === 1; }; LongPrototype.isEven = function isEven() { return (this.low & 1) === 0; }; LongPrototype.equals = function equals4(other) { if (!isLong(other)) other = fromValue(other); if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1) return false; return this.high === other.high && this.low === other.low; }; LongPrototype.eq = LongPrototype.equals; LongPrototype.notEquals = function notEquals(other) { return !this.eq(other); }; LongPrototype.neq = LongPrototype.notEquals; LongPrototype.ne = LongPrototype.notEquals; LongPrototype.lessThan = function lessThan(other) { return this.comp(other) < 0; }; LongPrototype.lt = LongPrototype.lessThan; LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) { return this.comp(other) <= 0; }; LongPrototype.lte = LongPrototype.lessThanOrEqual; LongPrototype.le = LongPrototype.lessThanOrEqual; LongPrototype.greaterThan = function greaterThan(other) { return this.comp(other) > 0; }; LongPrototype.gt = LongPrototype.greaterThan; LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) { return this.comp(other) >= 0; }; LongPrototype.gte = LongPrototype.greaterThanOrEqual; LongPrototype.ge = LongPrototype.greaterThanOrEqual; LongPrototype.compare = function compare(other) { if (!isLong(other)) other = fromValue(other); if (this.eq(other)) return 0; var thisNeg = this.isNegative(), otherNeg = other.isNegative(); if (thisNeg && !otherNeg) return -1; if (!thisNeg && otherNeg) return 1; if (!this.unsigned) return this.sub(other).isNegative() ? -1 : 1; return other.high >>> 0 > this.high >>> 0 || other.high === this.high && other.low >>> 0 > this.low >>> 0 ? -1 : 1; }; LongPrototype.comp = LongPrototype.compare; LongPrototype.negate = function negate2() { if (!this.unsigned && this.eq(MIN_VALUE)) return MIN_VALUE; return this.not().add(ONE); }; LongPrototype.neg = LongPrototype.negate; LongPrototype.add = function add5(addend) { if (!isLong(addend)) addend = fromValue(addend); var a48 = this.high >>> 16; var a32 = this.high & 65535; var a16 = this.low >>> 16; var a00 = this.low & 65535; var b48 = addend.high >>> 16; var b32 = addend.high & 65535; var b16 = addend.low >>> 16; var b00 = addend.low & 65535; var c48 = 0, c32 = 0, c16 = 0, c00 = 0; c00 += a00 + b00; c16 += c00 >>> 16; c00 &= 65535; c16 += a16 + b16; c32 += c16 >>> 16; c16 &= 65535; c32 += a32 + b32; c48 += c32 >>> 16; c32 &= 65535; c48 += a48 + b48; c48 &= 65535; return fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned); }; LongPrototype.subtract = function subtract3(subtrahend) { if (!isLong(subtrahend)) subtrahend = fromValue(subtrahend); return this.add(subtrahend.neg()); }; LongPrototype.sub = LongPrototype.subtract; LongPrototype.multiply = function multiply5(multiplier) { if (this.isZero()) return this; if (!isLong(multiplier)) multiplier = fromValue(multiplier); if (wasm) { var low = wasm["mul"]( this.low, this.high, multiplier.low, multiplier.high ); return fromBits(low, wasm["get_high"](), this.unsigned); } if (multiplier.isZero()) return this.unsigned ? UZERO : ZERO4; if (this.eq(MIN_VALUE)) return multiplier.isOdd() ? MIN_VALUE : ZERO4; if (multiplier.eq(MIN_VALUE)) return this.isOdd() ? MIN_VALUE : ZERO4; if (this.isNegative()) { if (multiplier.isNegative()) return this.neg().mul(multiplier.neg()); else return this.neg().mul(multiplier).neg(); } else if (multiplier.isNegative()) return this.mul(multiplier.neg()).neg(); if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24)) return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); var a48 = this.high >>> 16; var a32 = this.high & 65535; var a16 = this.low >>> 16; var a00 = this.low & 65535; var b48 = multiplier.high >>> 16; var b32 = multiplier.high & 65535; var b16 = multiplier.low >>> 16; var b00 = multiplier.low & 65535; var c48 = 0, c32 = 0, c16 = 0, c00 = 0; c00 += a00 * b00; c16 += c00 >>> 16; c00 &= 65535; c16 += a16 * b00; c32 += c16 >>> 16; c16 &= 65535; c16 += a00 * b16; c32 += c16 >>> 16; c16 &= 65535; c32 += a32 * b00; c48 += c32 >>> 16; c32 &= 65535; c32 += a16 * b16; c48 += c32 >>> 16; c32 &= 65535; c32 += a00 * b32; c48 += c32 >>> 16; c32 &= 65535; c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; c48 &= 65535; return fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned); }; LongPrototype.mul = LongPrototype.multiply; LongPrototype.divide = function divide2(divisor) { if (!isLong(divisor)) divisor = fromValue(divisor); if (divisor.isZero()) throw Error("division by zero"); if (wasm) { if (!this.unsigned && this.high === -2147483648 && divisor.low === -1 && divisor.high === -1) { return this; } var low = (this.unsigned ? wasm["div_u"] : wasm["div_s"])( this.low, this.high, divisor.low, divisor.high ); return fromBits(low, wasm["get_high"](), this.unsigned); } if (this.isZero()) return this.unsigned ? UZERO : ZERO4; var approx, rem, res; if (!this.unsigned) { if (this.eq(MIN_VALUE)) { if (divisor.eq(ONE) || divisor.eq(NEG_ONE)) return MIN_VALUE; else if (divisor.eq(MIN_VALUE)) return ONE; else { var halfThis = this.shr(1); approx = halfThis.div(divisor).shl(1); if (approx.eq(ZERO4)) { return divisor.isNegative() ? ONE : NEG_ONE; } else { rem = this.sub(divisor.mul(approx)); res = approx.add(rem.div(divisor)); return res; } } } else if (divisor.eq(MIN_VALUE)) return this.unsigned ? UZERO : ZERO4; if (this.isNegative()) { if (divisor.isNegative()) return this.neg().div(divisor.neg()); return this.neg().div(divisor).neg(); } else if (divisor.isNegative()) return this.div(divisor.neg()).neg(); res = ZERO4; } else { if (!divisor.unsigned) divisor = divisor.toUnsigned(); if (divisor.gt(this)) return UZERO; if (divisor.gt(this.shru(1))) return UONE; res = UZERO; } rem = this; while (rem.gte(divisor)) { approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); var log22 = Math.ceil(Math.log(approx) / Math.LN2), delta = log22 <= 48 ? 1 : pow_dbl(2, log22 - 48), approxRes = fromNumber(approx), approxRem = approxRes.mul(divisor); while (approxRem.isNegative() || approxRem.gt(rem)) { approx -= delta; approxRes = fromNumber(approx, this.unsigned); approxRem = approxRes.mul(divisor); } if (approxRes.isZero()) approxRes = ONE; res = res.add(approxRes); rem = rem.sub(approxRem); } return res; }; LongPrototype.div = LongPrototype.divide; LongPrototype.modulo = function modulo(divisor) { if (!isLong(divisor)) divisor = fromValue(divisor); if (wasm) { var low = (this.unsigned ? wasm["rem_u"] : wasm["rem_s"])( this.low, this.high, divisor.low, divisor.high ); return fromBits(low, wasm["get_high"](), this.unsigned); } return this.sub(this.div(divisor).mul(divisor)); }; LongPrototype.mod = LongPrototype.modulo; LongPrototype.rem = LongPrototype.modulo; LongPrototype.not = function not() { return fromBits(~this.low, ~this.high, this.unsigned); }; LongPrototype.countLeadingZeros = function countLeadingZeros() { return this.high ? Math.clz32(this.high) : Math.clz32(this.low) + 32; }; LongPrototype.clz = LongPrototype.countLeadingZeros; LongPrototype.countTrailingZeros = function countTrailingZeros() { return this.low ? ctz32(this.low) : ctz32(this.high) + 32; }; LongPrototype.ctz = LongPrototype.countTrailingZeros; LongPrototype.and = function and(other) { if (!isLong(other)) other = fromValue(other); return fromBits(this.low & other.low, this.high & other.high, this.unsigned); }; LongPrototype.or = function or(other) { if (!isLong(other)) other = fromValue(other); return fromBits(this.low | other.low, this.high | other.high, this.unsigned); }; LongPrototype.xor = function xor(other) { if (!isLong(other)) other = fromValue(other); return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); }; LongPrototype.shiftLeft = function shiftLeft(numBits) { if (isLong(numBits)) numBits = numBits.toInt(); if ((numBits &= 63) === 0) return this; else if (numBits < 32) return fromBits(this.low << numBits, this.high << numBits | this.low >>> 32 - numBits, this.unsigned); else return fromBits(0, this.low << numBits - 32, this.unsigned); }; LongPrototype.shl = LongPrototype.shiftLeft; LongPrototype.shiftRight = function shiftRight(numBits) { if (isLong(numBits)) numBits = numBits.toInt(); if ((numBits &= 63) === 0) return this; else if (numBits < 32) return fromBits(this.low >>> numBits | this.high << 32 - numBits, this.high >> numBits, this.unsigned); else return fromBits(this.high >> numBits - 32, this.high >= 0 ? 0 : -1, this.unsigned); }; LongPrototype.shr = LongPrototype.shiftRight; LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) { if (isLong(numBits)) numBits = numBits.toInt(); if ((numBits &= 63) === 0) return this; if (numBits < 32) return fromBits(this.low >>> numBits | this.high << 32 - numBits, this.high >>> numBits, this.unsigned); if (numBits === 32) return fromBits(this.high, 0, this.unsigned); return fromBits(this.high >>> numBits - 32, 0, this.unsigned); }; LongPrototype.shru = LongPrototype.shiftRightUnsigned; LongPrototype.shr_u = LongPrototype.shiftRightUnsigned; LongPrototype.rotateLeft = function rotateLeft(numBits) { var b; if (isLong(numBits)) numBits = numBits.toInt(); if ((numBits &= 63) === 0) return this; if (numBits === 32) return fromBits(this.high, this.low, this.unsigned); if (numBits < 32) { b = 32 - numBits; return fromBits(this.low << numBits | this.high >>> b, this.high << numBits | this.low >>> b, this.unsigned); } numBits -= 32; b = 32 - numBits; return fromBits(this.high << numBits | this.low >>> b, this.low << numBits | this.high >>> b, this.unsigned); }; LongPrototype.rotl = LongPrototype.rotateLeft; LongPrototype.rotateRight = function rotateRight(numBits) { var b; if (isLong(numBits)) numBits = numBits.toInt(); if ((numBits &= 63) === 0) return this; if (numBits === 32) return fromBits(this.high, this.low, this.unsigned); if (numBits < 32) { b = 32 - numBits; return fromBits(this.high << b | this.low >>> numBits, this.low << b | this.high >>> numBits, this.unsigned); } numBits -= 32; b = 32 - numBits; return fromBits(this.low << b | this.high >>> numBits, this.high << b | this.low >>> numBits, this.unsigned); }; LongPrototype.rotr = LongPrototype.rotateRight; LongPrototype.toSigned = function toSigned() { if (!this.unsigned) return this; return fromBits(this.low, this.high, false); }; LongPrototype.toUnsigned = function toUnsigned() { if (this.unsigned) return this; return fromBits(this.low, this.high, true); }; LongPrototype.toBytes = function toBytes(le) { return le ? this.toBytesLE() : this.toBytesBE(); }; LongPrototype.toBytesLE = function toBytesLE() { var hi = this.high, lo = this.low; return [ lo & 255, lo >>> 8 & 255, lo >>> 16 & 255, lo >>> 24, hi & 255, hi >>> 8 & 255, hi >>> 16 & 255, hi >>> 24 ]; }; LongPrototype.toBytesBE = function toBytesBE() { var hi = this.high, lo = this.low; return [ hi >>> 24, hi >>> 16 & 255, hi >>> 8 & 255, hi & 255, lo >>> 24, lo >>> 16 & 255, lo >>> 8 & 255, lo & 255 ]; }; Long3.fromBytes = function fromBytes(bytes, unsigned, le) { return le ? Long3.fromBytesLE(bytes, unsigned) : Long3.fromBytesBE(bytes, unsigned); }; Long3.fromBytesLE = function fromBytesLE(bytes, unsigned) { return new Long3( bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24, bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24, unsigned ); }; Long3.fromBytesBE = function fromBytesBE(bytes, unsigned) { return new Long3( bytes[4] << 24 | bytes[5] << 16 | bytes[6] << 8 | bytes[7], bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], unsigned ); }; var long_default = Long3; // ../../node_modules/@loaders.gl/3d-tiles/dist/lib/utils/s2/s2-token-functions.js var MAXIMUM_TOKEN_LENGTH = 16; function getS2CellIdFromToken(token) { if (token === "X") { token = ""; } const paddedToken = token.padEnd(MAXIMUM_TOKEN_LENGTH, "0"); return long_default.fromString(paddedToken, true, 16); } function getS2TokenFromCellId(cellId) { if (cellId.isZero()) { return "X"; } let numZeroDigits = cellId.countTrailingZeros(); const remainder = numZeroDigits % 4; numZeroDigits = (numZeroDigits - remainder) / 4; const trailingZeroHexChars = numZeroDigits; numZeroDigits *= 4; const x2 = cellId.shiftRightUnsigned(numZeroDigits); const hexString = x2.toString(16).replace(/0+$/, ""); const zeroString = Array(17 - trailingZeroHexChars - hexString.length).join("0"); return zeroString + hexString; } function getS2ChildCellId(cellId, index) { const newLsb = lsb(cellId).shiftRightUnsigned(2); const childCellId = cellId.add(long_default.fromNumber(2 * index + 1 - 4).multiply(newLsb)); return childCellId; } function lsb(cellId) { return cellId.and(cellId.not().add(1)); } // ../../node_modules/@loaders.gl/3d-tiles/dist/lib/utils/s2/s2geometry/s2-geometry.js var FACE_BITS2 = 3; var MAX_LEVEL2 = 30; var POS_BITS2 = 2 * MAX_LEVEL2 + 1; var RADIAN_TO_DEGREE2 = 180 / Math.PI; function getS2CellFromQuadKey(hilbertQuadkey) { if (hilbertQuadkey.length === 0) { throw new Error(`Invalid Hilbert quad key ${hilbertQuadkey}`); } const parts = hilbertQuadkey.split("/"); const face = parseInt(parts[0], 10); const position = parts[1]; const maxLevel = position.length; let level = 0; const point = [0, 0]; for (let i3 = maxLevel - 1; i3 >= 0; i3--) { level = maxLevel - i3; const bit = position[i3]; let rx = 0; let ry = 0; if (bit === "1") { ry = 1; } else if (bit === "2") { rx = 1; ry = 1; } else if (bit === "3") { rx = 1; } const val2 = Math.pow(2, level - 1); rotateAndFlipQuadrant2(val2, point, rx, ry); point[0] += val2 * rx; point[1] += val2 * ry; } if (face % 2 === 1) { const t2 = point[0]; point[0] = point[1]; point[1] = t2; } return { face, ij: point, level }; } function getS2QuadkeyFromCellId(cellId) { if (cellId.isZero()) { return ""; } let bin = cellId.toString(2); while (bin.length < FACE_BITS2 + POS_BITS2) { bin = "0" + bin; } const lsbIndex = bin.lastIndexOf("1"); const faceB = bin.substring(0, 3); const posB = bin.substring(3, lsbIndex); const levelN = posB.length / 2; const faceS = long_default.fromString(faceB, true, 2).toString(10); let posS = ""; if (levelN !== 0) { posS = long_default.fromString(posB, true, 2).toString(4); while (posS.length < levelN) { posS = "0" + posS; } } return `${faceS}/${posS}`; } function IJToST2(ij, level, offsets) { const maxSize = 1 << level; return [(ij[0] + offsets[0]) / maxSize, (ij[1] + offsets[1]) / maxSize]; } function singleSTtoUV2(st) { if (st >= 0.5) { return 1 / 3 * (4 * st * st - 1); } return 1 / 3 * (1 - 4 * (1 - st) * (1 - st)); } function STToUV2(st) { return [singleSTtoUV2(st[0]), singleSTtoUV2(st[1])]; } function FaceUVToXYZ2(face, [u, v]) { switch (face) { case 0: return [1, u, v]; case 1: return [-u, 1, v]; case 2: return [-u, -v, 1]; case 3: return [-1, -v, -u]; case 4: return [v, -1, -u]; case 5: return [v, u, -1]; default: throw new Error("Invalid face"); } } function XYZToLngLat2([x2, y2, z]) { const lat = Math.atan2(z, Math.sqrt(x2 * x2 + y2 * y2)); const lng = Math.atan2(y2, x2); return [lng * RADIAN_TO_DEGREE2, lat * RADIAN_TO_DEGREE2]; } function rotateAndFlipQuadrant2(n2, point, rx, ry) { if (ry === 0) { if (rx === 1) { point[0] = n2 - 1 - point[0]; point[1] = n2 - 1 - point[1]; } const x2 = point[0]; point[0] = point[1]; point[1] = x2; } } function getS2LngLatFromS2Cell(s2Cell) { const st = IJToST2(s2Cell.ij, s2Cell.level, [0.5, 0.5]); const uv = STToUV2(st); const xyz = FaceUVToXYZ2(s2Cell.face, uv); return XYZToLngLat2(xyz); } // ../../node_modules/@loaders.gl/3d-tiles/dist/lib/utils/s2/converters/s2-to-boundary.js var MAX_RESOLUTION2 = 100; function getS2BoundaryFlatFromS2Cell(s2cell) { const { face, ij, level } = s2cell; const offsets = [ [0, 0], [0, 1], [1, 1], [1, 0], [0, 0] ]; const resolution = Math.max(1, Math.ceil(MAX_RESOLUTION2 * Math.pow(2, -level))); const result = new Float64Array(4 * resolution * 2 + 2); let ptIndex = 0; let prevLng = 0; for (let i3 = 0; i3 < 4; i3++) { const offset = offsets[i3].slice(0); const nextOffset = offsets[i3 + 1]; const stepI = (nextOffset[0] - offset[0]) / resolution; const stepJ = (nextOffset[1] - offset[1]) / resolution; for (let j = 0; j < resolution; j++) { offset[0] += stepI; offset[1] += stepJ; const st = IJToST2(ij, level, offset); const uv = STToUV2(st); const xyz = FaceUVToXYZ2(face, uv); const lngLat = XYZToLngLat2(xyz); if (Math.abs(lngLat[1]) > 89.999) { lngLat[0] = prevLng; } const deltaLng = lngLat[0] - prevLng; lngLat[0] += deltaLng > 180 ? -360 : deltaLng < -180 ? 360 : 0; result[ptIndex++] = lngLat[0]; result[ptIndex++] = lngLat[1]; prevLng = lngLat[0]; } } result[ptIndex++] = result[0]; result[ptIndex++] = result[1]; return result; } // ../../node_modules/@loaders.gl/3d-tiles/dist/lib/utils/s2/s2geometry/s2-cell-utils.js function getS2Cell(tokenOrKey) { const key = getS2QuadKey2(tokenOrKey); const s2cell = getS2CellFromQuadKey(key); return s2cell; } function getS2QuadKey2(tokenOrKey) { if (tokenOrKey.indexOf("/") > 0) { return tokenOrKey; } const id = getS2CellIdFromToken(tokenOrKey); return getS2QuadkeyFromCellId(id); } // ../../node_modules/@loaders.gl/3d-tiles/dist/lib/utils/s2/s2-geometry-functions.js function getS2LngLat(s2Token) { const s2cell = getS2Cell(s2Token); return getS2LngLatFromS2Cell(s2cell); } // ../../node_modules/@loaders.gl/3d-tiles/dist/lib/utils/s2/converters/s2-to-region.js function getS2Region(s2cell) { let region; if (s2cell.face === 2 || s2cell.face === 5) { let corners = null; let len2 = 0; for (let i3 = 0; i3 < 4; i3++) { const key = `${s2cell.face}/${i3}`; const cell = getS2Cell(key); const corns = getS2BoundaryFlatFromS2Cell(cell); if (typeof corners === "undefined" || corners === null) corners = new Float64Array(4 * corns.length); corners.set(corns, len2); len2 += corns.length; } region = get2DRegionFromS2Corners(corners); } else { const corners = getS2BoundaryFlatFromS2Cell(s2cell); region = get2DRegionFromS2Corners(corners); } return region; } function get2DRegionFromS2Corners(corners) { if (corners.length % 2 !== 0) { throw new Error("Invalid corners"); } const longitudes = []; const latitudes = []; for (let i3 = 0; i3 < corners.length; i3 += 2) { longitudes.push(corners[i3]); latitudes.push(corners[i3 + 1]); } longitudes.sort((a2, b) => a2 - b); latitudes.sort((a2, b) => a2 - b); return { west: longitudes[0], east: longitudes[longitudes.length - 1], north: latitudes[latitudes.length - 1], south: latitudes[0] }; } // ../../node_modules/@loaders.gl/3d-tiles/dist/lib/utils/s2/converters/s2-to-obb-points.js function getS2OrientedBoundingBoxCornerPoints(tokenOrKey, heightInfo) { const min2 = heightInfo?.minimumHeight || 0; const max2 = heightInfo?.maximumHeight || 0; const s2cell = getS2Cell(tokenOrKey); const region = getS2Region(s2cell); const W = region.west; const S = region.south; const E = region.east; const N = region.north; const points = []; points.push(new Vector3(W, N, min2)); points.push(new Vector3(E, N, min2)); points.push(new Vector3(E, S, min2)); points.push(new Vector3(W, S, min2)); points.push(new Vector3(W, N, max2)); points.push(new Vector3(E, N, max2)); points.push(new Vector3(E, S, max2)); points.push(new Vector3(W, S, max2)); return points; } // ../../node_modules/@loaders.gl/3d-tiles/dist/lib/utils/obb/s2-corners-to-obb.js function convertS2BoundingVolumetoOBB(s2VolumeInfo) { const token = s2VolumeInfo.token; const heightInfo = { minimumHeight: s2VolumeInfo.minimumHeight, maximumHeight: s2VolumeInfo.maximumHeight }; const corners = getS2OrientedBoundingBoxCornerPoints(token, heightInfo); const center = getS2LngLat(token); const centerLng = center[0]; const centerLat = center[1]; const point = Ellipsoid.WGS84.cartographicToCartesian([ centerLng, centerLat, heightInfo.maximumHeight ]); const centerPointAdditional = new Vector3(point[0], point[1], point[2]); corners.push(centerPointAdditional); const obb = makeOrientedBoundingBoxFromPoints(corners); const box = [...obb.center, ...obb.halfAxes]; return box; } // ../../node_modules/@loaders.gl/3d-tiles/dist/lib/parsers/helpers/parse-3d-implicit-tiles.js var QUADTREE_DIVISION_COUNT = 4; var OCTREE_DIVISION_COUNT = 8; var SUBDIVISION_COUNT_MAP = { QUADTREE: QUADTREE_DIVISION_COUNT, OCTREE: OCTREE_DIVISION_COUNT }; function getChildS2VolumeBox(s2VolumeBox, index, subdivisionScheme) { if (s2VolumeBox?.box) { const cellId = getS2CellIdFromToken(s2VolumeBox.s2VolumeInfo.token); const childCellId = getS2ChildCellId(cellId, index); const childToken = getS2TokenFromCellId(childCellId); const s2ChildVolumeInfo = { ...s2VolumeBox.s2VolumeInfo }; s2ChildVolumeInfo.token = childToken; switch (subdivisionScheme) { case "OCTREE": const s2VolumeInfo = s2VolumeBox.s2VolumeInfo; const delta = s2VolumeInfo.maximumHeight - s2VolumeInfo.minimumHeight; const sizeZ = delta / 2; const midZ = s2VolumeInfo.minimumHeight + delta / 2; s2VolumeInfo.minimumHeight = midZ - sizeZ; s2VolumeInfo.maximumHeight = midZ + sizeZ; break; default: break; } const box = convertS2BoundingVolumetoOBB(s2ChildVolumeInfo); const childS2VolumeBox = { box, s2VolumeInfo: s2ChildVolumeInfo }; return childS2VolumeBox; } return void 0; } async function parseImplicitTiles(params) { const { implicitOptions, parentData = { mortonIndex: 0, x: 0, y: 0, z: 0 }, childIndex = 0, s2VolumeBox, loaderOptions } = params; let { subtree, level = 0, globalData = { level: 0, mortonIndex: 0, x: 0, y: 0, z: 0 } } = params; const { subdivisionScheme, subtreeLevels, maximumLevel, contentUrlTemplate, subtreesUriTemplate, basePath } = implicitOptions; const tile = { children: [], lodMetricValue: 0, contentUrl: "" }; if (!maximumLevel) { dist_default.once(`Missing 'maximumLevel' or 'availableLevels' property. The subtree ${contentUrlTemplate} won't be loaded...`); return tile; } const lev = level + globalData.level; if (lev > maximumLevel) { return tile; } const childrenPerTile = SUBDIVISION_COUNT_MAP[subdivisionScheme]; const bitsPerTile = Math.log2(childrenPerTile); const childX = childIndex & 1; const childY = childIndex >> 1 & 1; const childZ = childIndex >> 2 & 1; const levelOffset = (childrenPerTile ** level - 1) / (childrenPerTile - 1); let childTileMortonIndex = concatBits(parentData.mortonIndex, childIndex, bitsPerTile); let tileAvailabilityIndex = levelOffset + childTileMortonIndex; let childTileX = concatBits(parentData.x, childX, 1); let childTileY = concatBits(parentData.y, childY, 1); let childTileZ = concatBits(parentData.z, childZ, 1); let isChildSubtreeAvailable = false; if (level >= subtreeLevels) { isChildSubtreeAvailable = getAvailabilityResult(subtree.childSubtreeAvailability, childTileMortonIndex); } const x2 = concatBits(globalData.x, childTileX, level); const y2 = concatBits(globalData.y, childTileY, level); const z = concatBits(globalData.z, childTileZ, level); if (isChildSubtreeAvailable) { const subtreePath = `${basePath}/${subtreesUriTemplate}`; const childSubtreeUrl = replaceContentUrlTemplate(subtreePath, lev, x2, y2, z); const childSubtree = await (0, import_core41.load)(childSubtreeUrl, Tile3DSubtreeLoader, loaderOptions); subtree = childSubtree; globalData = { mortonIndex: childTileMortonIndex, x: childTileX, y: childTileY, z: childTileZ, level }; childTileMortonIndex = 0; tileAvailabilityIndex = 0; childTileX = 0; childTileY = 0; childTileZ = 0; level = 0; } const isTileAvailable = getAvailabilityResult(subtree.tileAvailability, tileAvailabilityIndex); if (!isTileAvailable) { return tile; } const isContentAvailable = getAvailabilityResult(subtree.contentAvailability, tileAvailabilityIndex); if (isContentAvailable) { tile.contentUrl = replaceContentUrlTemplate(contentUrlTemplate, lev, x2, y2, z); } const childTileLevel = level + 1; const pData = { mortonIndex: childTileMortonIndex, x: childTileX, y: childTileY, z: childTileZ }; for (let index = 0; index < childrenPerTile; index++) { const childS2VolumeBox = getChildS2VolumeBox(s2VolumeBox, index, subdivisionScheme); const childTileParsed = await parseImplicitTiles({ subtree, implicitOptions, loaderOptions, parentData: pData, childIndex: index, level: childTileLevel, globalData: { ...globalData }, s2VolumeBox: childS2VolumeBox }); if (childTileParsed.contentUrl || childTileParsed.children.length) { const globalLevel = lev + 1; const childCoordinates = { childTileX, childTileY, childTileZ }; const formattedTile = formatTileData(childTileParsed, globalLevel, childCoordinates, implicitOptions, s2VolumeBox); tile.children.push(formattedTile); } } return tile; } function getAvailabilityResult(availabilityData, index) { let availabilityObject; if (Array.isArray(availabilityData)) { availabilityObject = availabilityData[0]; if (availabilityData.length > 1) { dist_default.once('Not supported extension "3DTILES_multiple_contents" has been detected'); } } else { availabilityObject = availabilityData; } if ("constant" in availabilityObject) { return Boolean(availabilityObject.constant); } if (availabilityObject.explicitBitstream) { return getBooleanValueFromBitstream(index, availabilityObject.explicitBitstream); } return false; } function formatTileData(tile, level, childCoordinates, options, s2VolumeBox) { const { basePath, refine, getRefine: getRefine2, lodMetricType, getTileType: getTileType2, rootLodMetricValue, rootBoundingVolume } = options; const uri = tile.contentUrl && tile.contentUrl.replace(`${basePath}/`, ""); const lodMetricValue = rootLodMetricValue / 2 ** level; const boundingVolume = s2VolumeBox?.box ? { box: s2VolumeBox.box } : rootBoundingVolume; const boundingVolumeForChildTile = calculateBoundingVolumeForChildTile(level, boundingVolume, childCoordinates); return { children: tile.children, contentUrl: tile.contentUrl, content: { uri }, id: tile.contentUrl, refine: getRefine2(refine), type: getTileType2(tile), lodMetricType, lodMetricValue, geometricError: lodMetricValue, transform: tile.transform, boundingVolume: boundingVolumeForChildTile }; } function calculateBoundingVolumeForChildTile(level, rootBoundingVolume, childCoordinates) { if (rootBoundingVolume.region) { const { childTileX, childTileY, childTileZ } = childCoordinates; const [west, south, east, north, minimumHeight, maximumHeight] = rootBoundingVolume.region; const boundingVolumesCount = 2 ** level; const sizeX = (east - west) / boundingVolumesCount; const sizeY = (north - south) / boundingVolumesCount; const sizeZ = (maximumHeight - minimumHeight) / boundingVolumesCount; const [childWest, childEast] = [west + sizeX * childTileX, west + sizeX * (childTileX + 1)]; const [childSouth, childNorth] = [south + sizeY * childTileY, south + sizeY * (childTileY + 1)]; const [childMinimumHeight, childMaximumHeight] = [ minimumHeight + sizeZ * childTileZ, minimumHeight + sizeZ * (childTileZ + 1) ]; return { region: [childWest, childSouth, childEast, childNorth, childMinimumHeight, childMaximumHeight] }; } if (rootBoundingVolume.box) { return rootBoundingVolume; } throw new Error(`Unsupported bounding volume type ${JSON.stringify(rootBoundingVolume)}`); } function concatBits(higher, lower, shift) { return (higher << shift) + lower; } function replaceContentUrlTemplate(templateUrl, level, x2, y2, z) { const mapUrl = generateMapUrl({ level, x: x2, y: y2, z }); return templateUrl.replace(/{level}|{x}|{y}|{z}/gi, (matched) => mapUrl[matched]); } function generateMapUrl(items) { const mapUrl = {}; for (const key in items) { mapUrl[`{${key}}`] = items[key]; } return mapUrl; } function getBooleanValueFromBitstream(availabilityIndex, availabilityBuffer) { const byteIndex = Math.floor(availabilityIndex / 8); const bitIndex = availabilityIndex % 8; const bitValue = availabilityBuffer[byteIndex] >> bitIndex & 1; return bitValue === 1; } // ../../node_modules/@loaders.gl/3d-tiles/dist/lib/parsers/parse-3d-tile-header.js function getTileType(tile, tileContentUrl = "") { if (!tileContentUrl) { return TILE_TYPE.EMPTY; } const contentUrl = tileContentUrl.split("?")[0]; const fileExtension = contentUrl.split(".").pop(); switch (fileExtension) { case "pnts": return TILE_TYPE.POINTCLOUD; case "i3dm": case "b3dm": case "glb": case "gltf": return TILE_TYPE.SCENEGRAPH; default: return fileExtension || TILE_TYPE.EMPTY; } } function getRefine(refine) { switch (refine) { case "REPLACE": case "replace": return TILE_REFINEMENT.REPLACE; case "ADD": case "add": return TILE_REFINEMENT.ADD; default: return refine; } } function resolveUri(uri, basePath) { const urlSchemeRegex = /^[a-z][0-9a-z+.-]*:/i; if (urlSchemeRegex.test(basePath)) { const url = new URL(uri, `${basePath}/`); return decodeURI(url.toString()); } else if (uri.startsWith("/")) { return uri; } return path_exports.resolve(basePath, uri); } function normalizeTileData(tile, basePath) { if (!tile) { return null; } let tileContentUrl; if (tile.content) { const contentUri = tile.content.uri || tile.content?.url; if (typeof contentUri !== "undefined") { tileContentUrl = resolveUri(contentUri, basePath); } } const tilePostprocessed = { ...tile, id: tileContentUrl, contentUrl: tileContentUrl, lodMetricType: LOD_METRIC_TYPE.GEOMETRIC_ERROR, lodMetricValue: tile.geometricError, transformMatrix: tile.transform, type: getTileType(tile, tileContentUrl), refine: getRefine(tile.refine) }; return tilePostprocessed; } async function normalizeTileHeaders(tileset, basePath, options) { let root = null; const rootImplicitTilingExtension = getImplicitTilingExtensionData(tileset.root); if (rootImplicitTilingExtension && tileset.root) { root = await normalizeImplicitTileHeaders(tileset.root, tileset, basePath, rootImplicitTilingExtension, options); } else { root = normalizeTileData(tileset.root, basePath); } const stack2 = []; stack2.push(root); while (stack2.length > 0) { const tile = stack2.pop() || {}; const children = tile.children || []; const childrenPostprocessed = []; for (const childHeader of children) { const childImplicitTilingExtension = getImplicitTilingExtensionData(childHeader); let childHeaderPostprocessed; if (childImplicitTilingExtension) { childHeaderPostprocessed = await normalizeImplicitTileHeaders(childHeader, tileset, basePath, childImplicitTilingExtension, options); } else { childHeaderPostprocessed = normalizeTileData(childHeader, basePath); } if (childHeaderPostprocessed) { childrenPostprocessed.push(childHeaderPostprocessed); stack2.push(childHeaderPostprocessed); } } tile.children = childrenPostprocessed; } return root; } async function normalizeImplicitTileHeaders(tile, tileset, basePath, implicitTilingExtension, options) { const { subdivisionScheme, maximumLevel, availableLevels, subtreeLevels, subtrees: { uri: subtreesUriTemplate } } = implicitTilingExtension; const replacedUrlTemplate = replaceContentUrlTemplate(subtreesUriTemplate, 0, 0, 0, 0); const subtreeUrl = resolveUri(replacedUrlTemplate, basePath); const subtree = await (0, import_core42.load)(subtreeUrl, Tile3DSubtreeLoader, options); const tileContentUri = tile.content?.uri; const contentUrlTemplate = tileContentUri ? resolveUri(tileContentUri, basePath) : ""; const refine = tileset?.root?.refine; const rootLodMetricValue = tile.geometricError; const s2VolumeInfo = tile.boundingVolume.extensions?.["3DTILES_bounding_volume_S2"]; if (s2VolumeInfo) { const box = convertS2BoundingVolumetoOBB(s2VolumeInfo); const s2VolumeBox = { box, s2VolumeInfo }; tile.boundingVolume = s2VolumeBox; } const rootBoundingVolume = tile.boundingVolume; const implicitOptions = { contentUrlTemplate, subtreesUriTemplate, subdivisionScheme, subtreeLevels, maximumLevel: Number.isFinite(availableLevels) ? availableLevels - 1 : maximumLevel, refine, basePath, lodMetricType: LOD_METRIC_TYPE.GEOMETRIC_ERROR, rootLodMetricValue, rootBoundingVolume, getTileType, getRefine }; return await normalizeImplicitTileData(tile, basePath, subtree, implicitOptions, options); } async function normalizeImplicitTileData(tile, basePath, rootSubtree, implicitOptions, loaderOptions) { if (!tile) { return null; } const { children, contentUrl } = await parseImplicitTiles({ subtree: rootSubtree, implicitOptions, loaderOptions }); let tileContentUrl; let tileContent = null; if (contentUrl) { tileContentUrl = contentUrl; tileContent = { uri: contentUrl.replace(`${basePath}/`, "") }; } const tilePostprocessed = { ...tile, id: tileContentUrl, contentUrl: tileContentUrl, lodMetricType: LOD_METRIC_TYPE.GEOMETRIC_ERROR, lodMetricValue: tile.geometricError, transformMatrix: tile.transform, type: getTileType(tile, tileContentUrl), refine: getRefine(tile.refine), content: tileContent || tile.content, children }; return tilePostprocessed; } function getImplicitTilingExtensionData(tile) { return tile?.extensions?.["3DTILES_implicit_tiling"] || tile?.implicitTiling; } // ../../node_modules/@loaders.gl/3d-tiles/dist/tiles-3d-loader.js var Tiles3DLoader = { dataType: null, batchType: null, id: "3d-tiles", name: "3D Tiles", module: "3d-tiles", version: VERSION8, extensions: ["cmpt", "pnts", "b3dm", "i3dm"], mimeTypes: ["application/octet-stream"], tests: ["cmpt", "pnts", "b3dm", "i3dm"], parse: parse3, options: { "3d-tiles": { loadGLTF: true, decodeQuantizedPositions: false, isTileset: "auto", assetGltfUpAxis: null } } }; async function parse3(data, options = {}, context) { const loaderOptions = options["3d-tiles"] || {}; let isTileset; if (loaderOptions.isTileset === "auto") { isTileset = context?.url && context.url.indexOf(".json") !== -1; } else { isTileset = loaderOptions.isTileset; } return isTileset ? parseTileset(data, options, context) : parseTile(data, options, context); } async function parseTileset(data, options, context) { const tilesetJson = JSON.parse(new TextDecoder().decode(data)); const tilesetUrl = context?.url || ""; const basePath = getBaseUri(tilesetUrl); const normalizedRoot = await normalizeTileHeaders(tilesetJson, basePath, options || {}); const tilesetJsonPostprocessed = { ...tilesetJson, shape: "tileset3d", loader: Tiles3DLoader, url: tilesetUrl, queryString: context?.queryString || "", basePath, root: normalizedRoot || tilesetJson.root, type: TILESET_TYPE.TILES3D, lodMetricType: LOD_METRIC_TYPE.GEOMETRIC_ERROR, lodMetricValue: tilesetJson.root?.geometricError || 0 }; return tilesetJsonPostprocessed; } async function parseTile(arrayBuffer, options, context) { const tile = { content: { shape: "tile3d", featureIds: null } }; const byteOffset = 0; await parse3DTile(arrayBuffer, byteOffset, options, context, tile.content); return tile.content; } function getBaseUri(tilesetUrl) { return path_exports.dirname(tilesetUrl); } // src/tile-3d-layer/tile-3d-layer.ts var SINGLE_DATA = [0]; var defaultProps11 = { getPointColor: { type: "accessor", value: [0, 0, 0, 255] }, pointSize: 1, data: "", loader: Tiles3DLoader, onTilesetLoad: { type: "function", value: (tileset3d) => { } }, onTileLoad: { type: "function", value: (tileHeader) => { } }, onTileUnload: { type: "function", value: (tileHeader) => { } }, onTileError: { type: "function", value: (tile, message, url) => { } }, _getMeshColor: { type: "function", value: (tileHeader) => [255, 255, 255] } }; var Tile3DLayer = class extends import_core43.CompositeLayer { initializeState() { if ("onTileLoadFail" in this.props) { import_core43.log.removed("onTileLoadFail", "onTileError")(); } this.state = { layerMap: {}, tileset3d: null, activeViewports: {}, lastUpdatedViewports: null }; } get isLoaded() { return Boolean(this.state?.tileset3d?.isLoaded() && super.isLoaded); } shouldUpdateState({ changeFlags }) { return changeFlags.somethingChanged; } updateState({ props, oldProps, changeFlags }) { if (props.data && props.data !== oldProps.data) { this._loadTileset(props.data); } if (changeFlags.viewportChanged) { const { activeViewports } = this.state; const viewportsNumber = Object.keys(activeViewports).length; if (viewportsNumber) { this._updateTileset(activeViewports); this.state.lastUpdatedViewports = activeViewports; this.state.activeViewports = {}; } } if (changeFlags.propsChanged) { const { layerMap } = this.state; for (const key in layerMap) { layerMap[key].needsUpdate = true; } } } activateViewport(viewport) { const { activeViewports, lastUpdatedViewports } = this.state; this.internalState.viewport = viewport; activeViewports[viewport.id] = viewport; const lastViewport = lastUpdatedViewports?.[viewport.id]; if (!lastViewport || !viewport.equals(lastViewport)) { this.setChangeFlags({ viewportChanged: true }); this.setNeedsUpdate(); } } getPickingInfo({ info, sourceLayer }) { const sourceTile = sourceLayer && sourceLayer.props.tile; if (info.picked) { info.object = sourceTile; } info.sourceTile = sourceTile; return info; } filterSubLayer({ layer, viewport }) { const { tile } = layer.props; const { id: viewportId } = viewport; return tile.selected && tile.viewportIds.includes(viewportId); } _updateAutoHighlight(info) { const sourceTile = info.sourceTile; const layerCache = this.state.layerMap[sourceTile?.id]; if (layerCache && layerCache.layer) { layerCache.layer.updateAutoHighlight(info); } } async _loadTileset(tilesetUrl) { const { loadOptions = {} } = this.props; const loaders = this.props.loader || this.props.loaders; const loader = Array.isArray(loaders) ? loaders[0] : loaders; const options = { loadOptions: { ...loadOptions } }; let actualTilesetUrl = tilesetUrl; if (loader.preload) { const preloadOptions = await loader.preload(tilesetUrl, loadOptions); if (preloadOptions.url) { actualTilesetUrl = preloadOptions.url; } if (preloadOptions.headers) { options.loadOptions.fetch = { ...options.loadOptions.fetch, headers: preloadOptions.headers }; } Object.assign(options, preloadOptions); } const tilesetJson = await (0, import_core44.load)(actualTilesetUrl, loader, options.loadOptions); const tileset3d = new Tileset3D(tilesetJson, { onTileLoad: this._onTileLoad.bind(this), onTileUnload: this._onTileUnload.bind(this), onTileError: this.props.onTileError, ...options }); this.setState({ tileset3d, layerMap: {} }); this._updateTileset(this.state.activeViewports); this.props.onTilesetLoad(tileset3d); } _onTileLoad(tileHeader) { const { lastUpdatedViewports } = this.state; this.props.onTileLoad(tileHeader); this._updateTileset(lastUpdatedViewports); this.setNeedsUpdate(); } _onTileUnload(tileHeader) { delete this.state.layerMap[tileHeader.id]; this.props.onTileUnload(tileHeader); } _updateTileset(viewports) { if (!viewports) { return; } const { tileset3d } = this.state; const { timeline } = this.context; const viewportsNumber = Object.keys(viewports).length; if (!timeline || !viewportsNumber || !tileset3d) { return; } tileset3d.selectTiles(Object.values(viewports)).then((frameNumber) => { const tilesetChanged = this.state.frameNumber !== frameNumber; if (tilesetChanged) { this.setState({ frameNumber }); } }); } _getSubLayer(tileHeader, oldLayer) { if (!tileHeader.content) { return null; } switch (tileHeader.type) { case TILE_TYPE.POINTCLOUD: return this._makePointCloudLayer(tileHeader, oldLayer); case TILE_TYPE.SCENEGRAPH: return this._make3DModelLayer(tileHeader); case TILE_TYPE.MESH: return this._makeSimpleMeshLayer(tileHeader, oldLayer); default: throw new Error(`Tile3DLayer: Failed to render layer of type ${tileHeader.content.type}`); } } _makePointCloudLayer(tileHeader, oldLayer) { const { attributes, pointCount, constantRGBA, cartographicOrigin, modelMatrix } = tileHeader.content; const { positions, normals, colors } = attributes; if (!positions) { return null; } const data = oldLayer && oldLayer.props.data || { header: { vertexCount: pointCount }, attributes: { POSITION: positions, NORMAL: normals, COLOR_0: colors } }; const { pointSize, getPointColor } = this.props; const SubLayerClass = this.getSubLayerClass("pointcloud", import_layers8.PointCloudLayer); return new SubLayerClass( { pointSize }, this.getSubLayerProps({ id: "pointcloud" }), { id: `${this.id}-pointcloud-${tileHeader.id}`, tile: tileHeader, data, coordinateSystem: import_core43.COORDINATE_SYSTEM.METER_OFFSETS, coordinateOrigin: cartographicOrigin, modelMatrix, getColor: constantRGBA || getPointColor, _offset: 0 } ); } _make3DModelLayer(tileHeader) { const { gltf, instances, cartographicOrigin, modelMatrix } = tileHeader.content; const SubLayerClass = this.getSubLayerClass("scenegraph", import_mesh_layers2.ScenegraphLayer); return new SubLayerClass( { _lighting: "pbr" }, this.getSubLayerProps({ id: "scenegraph" }), { id: `${this.id}-scenegraph-${tileHeader.id}`, tile: tileHeader, data: instances || SINGLE_DATA, scenegraph: gltf, coordinateSystem: import_core43.COORDINATE_SYSTEM.METER_OFFSETS, coordinateOrigin: cartographicOrigin, modelMatrix, getTransformMatrix: (instance) => instance.modelMatrix, getPosition: [0, 0, 0], _offset: 0 } ); } _makeSimpleMeshLayer(tileHeader, oldLayer) { const content = tileHeader.content; const { attributes, indices, modelMatrix, cartographicOrigin, coordinateSystem = import_core43.COORDINATE_SYSTEM.METER_OFFSETS, material, featureIds } = content; const { _getMeshColor } = this.props; const geometry = oldLayer && oldLayer.props.mesh || new import_engine2.Geometry({ topology: "triangle-list", attributes: getMeshGeometry(attributes), indices }); const SubLayerClass = this.getSubLayerClass("mesh", MeshLayer); return new SubLayerClass( this.getSubLayerProps({ id: "mesh" }), { id: `${this.id}-mesh-${tileHeader.id}`, tile: tileHeader, mesh: geometry, data: SINGLE_DATA, getColor: _getMeshColor(tileHeader), pbrMaterial: material, modelMatrix, coordinateOrigin: cartographicOrigin, coordinateSystem, featureIds, _offset: 0 } ); } renderLayers() { const { tileset3d, layerMap } = this.state; if (!tileset3d) { return null; } return tileset3d.tiles.map((tile) => { const layerCache = layerMap[tile.id] = layerMap[tile.id] || { tile }; let { layer } = layerCache; if (tile.selected) { if (!layer) { layer = this._getSubLayer(tile); } else if (layerCache.needsUpdate) { layer = this._getSubLayer(tile, layer); layerCache.needsUpdate = false; } } layerCache.layer = layer; return layer; }).filter(Boolean); } }; Tile3DLayer.defaultProps = defaultProps11; Tile3DLayer.layerName = "Tile3DLayer"; function getMeshGeometry(contentAttributes) { const attributes = {}; attributes.positions = { ...contentAttributes.positions, value: new Float32Array(contentAttributes.positions.value) }; if (contentAttributes.normals) { attributes.normals = contentAttributes.normals; } if (contentAttributes.texCoords) { attributes.texCoords = contentAttributes.texCoords; } if (contentAttributes.colors) { attributes.colors = contentAttributes.colors; } if (contentAttributes.uvRegions) { attributes.uvRegions = contentAttributes.uvRegions; } return attributes; } // src/terrain-layer/terrain-layer.ts var import_core45 = __toESM(require_core(), 1); var import_mesh_layers3 = __toESM(require_mesh_layers(), 1); var import_core46 = __toESM(require_core(), 1); // ../../node_modules/@loaders.gl/terrain/dist/lib/decode-quantized-mesh.js var QUANTIZED_MESH_HEADER = /* @__PURE__ */ new Map([ ["centerX", Float64Array.BYTES_PER_ELEMENT], ["centerY", Float64Array.BYTES_PER_ELEMENT], ["centerZ", Float64Array.BYTES_PER_ELEMENT], ["minHeight", Float32Array.BYTES_PER_ELEMENT], ["maxHeight", Float32Array.BYTES_PER_ELEMENT], ["boundingSphereCenterX", Float64Array.BYTES_PER_ELEMENT], ["boundingSphereCenterY", Float64Array.BYTES_PER_ELEMENT], ["boundingSphereCenterZ", Float64Array.BYTES_PER_ELEMENT], ["boundingSphereRadius", Float64Array.BYTES_PER_ELEMENT], ["horizonOcclusionPointX", Float64Array.BYTES_PER_ELEMENT], ["horizonOcclusionPointY", Float64Array.BYTES_PER_ELEMENT], ["horizonOcclusionPointZ", Float64Array.BYTES_PER_ELEMENT] ]); function decodeZigZag(value) { return value >> 1 ^ -(value & 1); } function decodeHeader(dataView) { let position = 0; const header = {}; for (const [key, bytesCount] of QUANTIZED_MESH_HEADER) { const getter = bytesCount === 8 ? dataView.getFloat64 : dataView.getFloat32; header[key] = getter.call(dataView, position, true); position += bytesCount; } return { header, headerEndPosition: position }; } function decodeVertexData(dataView, headerEndPosition) { let position = headerEndPosition; const elementsPerVertex = 3; const vertexCount = dataView.getUint32(position, true); const vertexData = new Uint16Array(vertexCount * elementsPerVertex); position += Uint32Array.BYTES_PER_ELEMENT; const bytesPerArrayElement = Uint16Array.BYTES_PER_ELEMENT; const elementArrayLength = vertexCount * bytesPerArrayElement; const uArrayStartPosition = position; const vArrayStartPosition = uArrayStartPosition + elementArrayLength; const heightArrayStartPosition = vArrayStartPosition + elementArrayLength; let u = 0; let v = 0; let height = 0; for (let i3 = 0; i3 < vertexCount; i3++) { u += decodeZigZag(dataView.getUint16(uArrayStartPosition + bytesPerArrayElement * i3, true)); v += decodeZigZag(dataView.getUint16(vArrayStartPosition + bytesPerArrayElement * i3, true)); height += decodeZigZag(dataView.getUint16(heightArrayStartPosition + bytesPerArrayElement * i3, true)); vertexData[i3] = u; vertexData[i3 + vertexCount] = v; vertexData[i3 + vertexCount * 2] = height; } position += elementArrayLength * 3; return { vertexData, vertexDataEndPosition: position }; } function decodeIndex(buffer, position, indicesCount, bytesPerIndex, encoded = true) { let indices; if (bytesPerIndex === 2) { indices = new Uint16Array(buffer, position, indicesCount); } else { indices = new Uint32Array(buffer, position, indicesCount); } if (!encoded) { return indices; } let highest = 0; for (let i3 = 0; i3 < indices.length; ++i3) { const code = indices[i3]; indices[i3] = highest - code; if (code === 0) { ++highest; } } return indices; } function decodeTriangleIndices(dataView, vertexData, vertexDataEndPosition) { let position = vertexDataEndPosition; const elementsPerVertex = 3; const vertexCount = vertexData.length / elementsPerVertex; const bytesPerIndex = vertexCount > 65536 ? Uint32Array.BYTES_PER_ELEMENT : Uint16Array.BYTES_PER_ELEMENT; if (position % bytesPerIndex !== 0) { position += bytesPerIndex - position % bytesPerIndex; } const triangleCount = dataView.getUint32(position, true); position += Uint32Array.BYTES_PER_ELEMENT; const triangleIndicesCount = triangleCount * 3; const triangleIndices = decodeIndex(dataView.buffer, position, triangleIndicesCount, bytesPerIndex); position += triangleIndicesCount * bytesPerIndex; return { triangleIndicesEndPosition: position, triangleIndices }; } function decodeEdgeIndices(dataView, vertexData, triangleIndicesEndPosition) { let position = triangleIndicesEndPosition; const elementsPerVertex = 3; const vertexCount = vertexData.length / elementsPerVertex; const bytesPerIndex = vertexCount > 65536 ? Uint32Array.BYTES_PER_ELEMENT : Uint16Array.BYTES_PER_ELEMENT; const westVertexCount = dataView.getUint32(position, true); position += Uint32Array.BYTES_PER_ELEMENT; const westIndices = decodeIndex(dataView.buffer, position, westVertexCount, bytesPerIndex, false); position += westVertexCount * bytesPerIndex; const southVertexCount = dataView.getUint32(position, true); position += Uint32Array.BYTES_PER_ELEMENT; const southIndices = decodeIndex(dataView.buffer, position, southVertexCount, bytesPerIndex, false); position += southVertexCount * bytesPerIndex; const eastVertexCount = dataView.getUint32(position, true); position += Uint32Array.BYTES_PER_ELEMENT; const eastIndices = decodeIndex(dataView.buffer, position, eastVertexCount, bytesPerIndex, false); position += eastVertexCount * bytesPerIndex; const northVertexCount = dataView.getUint32(position, true); position += Uint32Array.BYTES_PER_ELEMENT; const northIndices = decodeIndex(dataView.buffer, position, northVertexCount, bytesPerIndex, false); position += northVertexCount * bytesPerIndex; return { edgeIndicesEndPosition: position, westIndices, southIndices, eastIndices, northIndices }; } function decodeVertexNormalsExtension(extensionDataView) { return new Uint8Array(extensionDataView.buffer, extensionDataView.byteOffset, extensionDataView.byteLength); } function decodeWaterMaskExtension(extensionDataView) { return extensionDataView.buffer.slice(extensionDataView.byteOffset, extensionDataView.byteOffset + extensionDataView.byteLength); } function decodeExtensions2(dataView, indicesEndPosition) { const extensions = {}; if (dataView.byteLength <= indicesEndPosition) { return { extensions, extensionsEndPosition: indicesEndPosition }; } let position = indicesEndPosition; while (position < dataView.byteLength) { const extensionId = dataView.getUint8(position, true); position += Uint8Array.BYTES_PER_ELEMENT; const extensionLength = dataView.getUint32(position, true); position += Uint32Array.BYTES_PER_ELEMENT; const extensionView = new DataView(dataView.buffer, position, extensionLength); switch (extensionId) { case 1: { extensions.vertexNormals = decodeVertexNormalsExtension(extensionView); break; } case 2: { extensions.waterMask = decodeWaterMaskExtension(extensionView); break; } default: { } } position += extensionLength; } return { extensions, extensionsEndPosition: position }; } var DECODING_STEPS = { header: 0, vertices: 1, triangleIndices: 2, edgeIndices: 3, extensions: 4 }; var DEFAULT_OPTIONS = { maxDecodingStep: DECODING_STEPS.extensions }; function decode11(data, userOptions) { const options = Object.assign({}, DEFAULT_OPTIONS, userOptions); const view = new DataView(data); const { header, headerEndPosition } = decodeHeader(view); if (options.maxDecodingStep < DECODING_STEPS.vertices) { return { header }; } const { vertexData, vertexDataEndPosition } = decodeVertexData(view, headerEndPosition); if (options.maxDecodingStep < DECODING_STEPS.triangleIndices) { return { header, vertexData }; } const { triangleIndices, triangleIndicesEndPosition } = decodeTriangleIndices(view, vertexData, vertexDataEndPosition); if (options.maxDecodingStep < DECODING_STEPS.edgeIndices) { return { header, vertexData, triangleIndices }; } const { westIndices, southIndices, eastIndices, northIndices, edgeIndicesEndPosition } = decodeEdgeIndices(view, vertexData, triangleIndicesEndPosition); if (options.maxDecodingStep < DECODING_STEPS.extensions) { return { header, vertexData, triangleIndices, westIndices, northIndices, eastIndices, southIndices }; } const { extensions } = decodeExtensions2(view, edgeIndicesEndPosition); return { header, vertexData, triangleIndices, westIndices, northIndices, eastIndices, southIndices, extensions }; } // ../../node_modules/@loaders.gl/terrain/dist/lib/helpers/skirt.js function addSkirt(attributes, triangles, skirtHeight, outsideIndices) { const outsideEdges = outsideIndices ? getOutsideEdgesFromIndices(outsideIndices, attributes.POSITION.value) : getOutsideEdgesFromTriangles(triangles); const newPosition = new attributes.POSITION.value.constructor(outsideEdges.length * 6); const newTexcoord0 = new attributes.TEXCOORD_0.value.constructor(outsideEdges.length * 4); const newTriangles = new triangles.constructor(outsideEdges.length * 6); for (let i3 = 0; i3 < outsideEdges.length; i3++) { const edge = outsideEdges[i3]; updateAttributesForNewEdge({ edge, edgeIndex: i3, attributes, skirtHeight, newPosition, newTexcoord0, newTriangles }); } attributes.POSITION.value = concatenateTypedArrays(attributes.POSITION.value, newPosition); attributes.TEXCOORD_0.value = concatenateTypedArrays(attributes.TEXCOORD_0.value, newTexcoord0); const resultTriangles = triangles instanceof Array ? triangles.concat(newTriangles) : concatenateTypedArrays(triangles, newTriangles); return { attributes, triangles: resultTriangles }; } function getOutsideEdgesFromTriangles(triangles) { const edges = []; for (let i3 = 0; i3 < triangles.length; i3 += 3) { edges.push([triangles[i3], triangles[i3 + 1]]); edges.push([triangles[i3 + 1], triangles[i3 + 2]]); edges.push([triangles[i3 + 2], triangles[i3]]); } edges.sort((a2, b) => Math.min(...a2) - Math.min(...b) || Math.max(...a2) - Math.max(...b)); const outsideEdges = []; let index = 0; while (index < edges.length) { if (edges[index][0] === edges[index + 1]?.[1] && edges[index][1] === edges[index + 1]?.[0]) { index += 2; } else { outsideEdges.push(edges[index]); index++; } } return outsideEdges; } function getOutsideEdgesFromIndices(indices, position) { indices.westIndices.sort((a2, b) => position[3 * a2 + 1] - position[3 * b + 1]); indices.eastIndices.sort((a2, b) => position[3 * b + 1] - position[3 * a2 + 1]); indices.southIndices.sort((a2, b) => position[3 * b] - position[3 * a2]); indices.northIndices.sort((a2, b) => position[3 * a2] - position[3 * b]); const edges = []; for (const index in indices) { const indexGroup = indices[index]; for (let i3 = 0; i3 < indexGroup.length - 1; i3++) { edges.push([indexGroup[i3], indexGroup[i3 + 1]]); } } return edges; } function updateAttributesForNewEdge({ edge, edgeIndex, attributes, skirtHeight, newPosition, newTexcoord0, newTriangles }) { const positionsLength = attributes.POSITION.value.length; const vertex1Offset = edgeIndex * 2; const vertex2Offset = edgeIndex * 2 + 1; newPosition.set(attributes.POSITION.value.subarray(edge[0] * 3, edge[0] * 3 + 3), vertex1Offset * 3); newPosition[vertex1Offset * 3 + 2] = newPosition[vertex1Offset * 3 + 2] - skirtHeight; newPosition.set(attributes.POSITION.value.subarray(edge[1] * 3, edge[1] * 3 + 3), vertex2Offset * 3); newPosition[vertex2Offset * 3 + 2] = newPosition[vertex2Offset * 3 + 2] - skirtHeight; newTexcoord0.set(attributes.TEXCOORD_0.value.subarray(edge[0] * 2, edge[0] * 2 + 2), vertex1Offset * 2); newTexcoord0.set(attributes.TEXCOORD_0.value.subarray(edge[1] * 2, edge[1] * 2 + 2), vertex2Offset * 2); const triangle1Offset = edgeIndex * 2 * 3; newTriangles[triangle1Offset] = edge[0]; newTriangles[triangle1Offset + 1] = positionsLength / 3 + vertex2Offset; newTriangles[triangle1Offset + 2] = edge[1]; newTriangles[triangle1Offset + 3] = positionsLength / 3 + vertex2Offset; newTriangles[triangle1Offset + 4] = edge[0]; newTriangles[triangle1Offset + 5] = positionsLength / 3 + vertex1Offset; } // ../../node_modules/@loaders.gl/terrain/dist/lib/parse-quantized-mesh.js function parseQuantizedMesh(arrayBuffer, options = {}) { const { bounds } = options; const { header, vertexData, triangleIndices: originalTriangleIndices, westIndices, northIndices, eastIndices, southIndices } = decode11(arrayBuffer, DECODING_STEPS.triangleIndices); let triangleIndices = originalTriangleIndices; let attributes = getMeshAttributes(vertexData, header, bounds); const boundingBox = getMeshBoundingBox(attributes); if (options?.skirtHeight) { const { attributes: newAttributes, triangles: newTriangles } = addSkirt(attributes, triangleIndices, options.skirtHeight, { westIndices, northIndices, eastIndices, southIndices }); attributes = newAttributes; triangleIndices = newTriangles; } return { loaderData: { header: {} }, header: { vertexCount: triangleIndices.length, boundingBox }, schema: void 0, topology: "triangle-list", mode: 4, indices: { value: triangleIndices, size: 1 }, attributes }; } function getMeshAttributes(vertexData, header, bounds) { const { minHeight, maxHeight } = header; const [minX, minY, maxX, maxY] = bounds || [0, 0, 1, 1]; const xScale = maxX - minX; const yScale = maxY - minY; const zScale = maxHeight - minHeight; const nCoords = vertexData.length / 3; const positions = new Float32Array(nCoords * 3); const texCoords = new Float32Array(nCoords * 2); for (let i3 = 0; i3 < nCoords; i3++) { const x2 = vertexData[i3] / 32767; const y2 = vertexData[i3 + nCoords] / 32767; const z = vertexData[i3 + nCoords * 2] / 32767; positions[3 * i3 + 0] = x2 * xScale + minX; positions[3 * i3 + 1] = y2 * yScale + minY; positions[3 * i3 + 2] = z * zScale + minHeight; texCoords[2 * i3 + 0] = x2; texCoords[2 * i3 + 1] = y2; } return { POSITION: { value: positions, size: 3 }, TEXCOORD_0: { value: texCoords, size: 2 } }; } // ../../node_modules/@mapbox/martini/index.js var Martini = class { constructor(gridSize = 257) { this.gridSize = gridSize; const tileSize = gridSize - 1; if (tileSize & tileSize - 1) throw new Error( `Expected grid size to be 2^n+1, got ${gridSize}.` ); this.numTriangles = tileSize * tileSize * 2 - 2; this.numParentTriangles = this.numTriangles - tileSize * tileSize; this.indices = new Uint32Array(this.gridSize * this.gridSize); this.coords = new Uint16Array(this.numTriangles * 4); for (let i3 = 0; i3 < this.numTriangles; i3++) { let id = i3 + 2; let ax = 0, ay = 0, bx = 0, by = 0, cx = 0, cy = 0; if (id & 1) { bx = by = cx = tileSize; } else { ax = ay = cy = tileSize; } while ((id >>= 1) > 1) { const mx = ax + bx >> 1; const my = ay + by >> 1; if (id & 1) { bx = ax; by = ay; ax = cx; ay = cy; } else { ax = bx; ay = by; bx = cx; by = cy; } cx = mx; cy = my; } const k = i3 * 4; this.coords[k + 0] = ax; this.coords[k + 1] = ay; this.coords[k + 2] = bx; this.coords[k + 3] = by; } } createTile(terrain) { return new Tile(terrain, this); } }; var Tile = class { constructor(terrain, martini) { const size = martini.gridSize; if (terrain.length !== size * size) throw new Error( `Expected terrain data of length ${size * size} (${size} x ${size}), got ${terrain.length}.` ); this.terrain = terrain; this.martini = martini; this.errors = new Float32Array(terrain.length); this.update(); } update() { const { numTriangles, numParentTriangles, coords, gridSize: size } = this.martini; const { terrain, errors } = this; for (let i3 = numTriangles - 1; i3 >= 0; i3--) { const k = i3 * 4; const ax = coords[k + 0]; const ay = coords[k + 1]; const bx = coords[k + 2]; const by = coords[k + 3]; const mx = ax + bx >> 1; const my = ay + by >> 1; const cx = mx + my - ay; const cy = my + ax - mx; const interpolatedHeight = (terrain[ay * size + ax] + terrain[by * size + bx]) / 2; const middleIndex = my * size + mx; const middleError = Math.abs(interpolatedHeight - terrain[middleIndex]); errors[middleIndex] = Math.max(errors[middleIndex], middleError); if (i3 < numParentTriangles) { const leftChildIndex = (ay + cy >> 1) * size + (ax + cx >> 1); const rightChildIndex = (by + cy >> 1) * size + (bx + cx >> 1); errors[middleIndex] = Math.max(errors[middleIndex], errors[leftChildIndex], errors[rightChildIndex]); } } } getMesh(maxError = 0) { const { gridSize: size, indices } = this.martini; const { errors } = this; let numVertices = 0; let numTriangles = 0; const max2 = size - 1; indices.fill(0); function countElements(ax, ay, bx, by, cx, cy) { const mx = ax + bx >> 1; const my = ay + by >> 1; if (Math.abs(ax - cx) + Math.abs(ay - cy) > 1 && errors[my * size + mx] > maxError) { countElements(cx, cy, ax, ay, mx, my); countElements(bx, by, cx, cy, mx, my); } else { indices[ay * size + ax] = indices[ay * size + ax] || ++numVertices; indices[by * size + bx] = indices[by * size + bx] || ++numVertices; indices[cy * size + cx] = indices[cy * size + cx] || ++numVertices; numTriangles++; } } countElements(0, 0, max2, max2, max2, 0); countElements(max2, max2, 0, 0, 0, max2); const vertices = new Uint16Array(numVertices * 2); const triangles = new Uint32Array(numTriangles * 3); let triIndex = 0; function processTriangle(ax, ay, bx, by, cx, cy) { const mx = ax + bx >> 1; const my = ay + by >> 1; if (Math.abs(ax - cx) + Math.abs(ay - cy) > 1 && errors[my * size + mx] > maxError) { processTriangle(cx, cy, ax, ay, mx, my); processTriangle(bx, by, cx, cy, mx, my); } else { const a2 = indices[ay * size + ax] - 1; const b = indices[by * size + bx] - 1; const c = indices[cy * size + cx] - 1; vertices[2 * a2] = ax; vertices[2 * a2 + 1] = ay; vertices[2 * b] = bx; vertices[2 * b + 1] = by; vertices[2 * c] = cx; vertices[2 * c + 1] = cy; triangles[triIndex++] = a2; triangles[triIndex++] = b; triangles[triIndex++] = c; } } processTriangle(0, 0, max2, max2, max2, 0); processTriangle(max2, max2, 0, 0, 0, max2); return { vertices, triangles }; } }; // ../../node_modules/@loaders.gl/terrain/dist/lib/delatin/index.js var Delatin = class { constructor(data, width, height = width) { this.data = data; this.width = width; this.height = height; this.coords = []; this.triangles = []; this._halfedges = []; this._candidates = []; this._queueIndices = []; this._queue = []; this._errors = []; this._rms = []; this._pending = []; this._pendingLen = 0; this._rmsSum = 0; const x1 = width - 1; const y1 = height - 1; const p0 = this._addPoint(0, 0); const p1 = this._addPoint(x1, 0); const p2 = this._addPoint(0, y1); const p3 = this._addPoint(x1, y1); const t0 = this._addTriangle(p3, p0, p2, -1, -1, -1); this._addTriangle(p0, p3, p1, t0, -1, -1); this._flush(); } run(maxError = 1) { while (this.getMaxError() > maxError) { this.refine(); } } refine() { this._step(); this._flush(); } getMaxError() { return this._errors[0]; } getRMSD() { return this._rmsSum > 0 ? Math.sqrt(this._rmsSum / (this.width * this.height)) : 0; } heightAt(x2, y2) { return this.data[this.width * y2 + x2]; } _flush() { const coords = this.coords; for (let i3 = 0; i3 < this._pendingLen; i3++) { const t2 = this._pending[i3]; const a2 = 2 * this.triangles[t2 * 3 + 0]; const b = 2 * this.triangles[t2 * 3 + 1]; const c = 2 * this.triangles[t2 * 3 + 2]; this._findCandidate(coords[a2], coords[a2 + 1], coords[b], coords[b + 1], coords[c], coords[c + 1], t2); } this._pendingLen = 0; } _findCandidate(p0x, p0y, p1x, p1y, p2x, p2y, t2) { const minX = Math.min(p0x, p1x, p2x); const minY = Math.min(p0y, p1y, p2y); const maxX = Math.max(p0x, p1x, p2x); const maxY = Math.max(p0y, p1y, p2y); let w00 = orient(p1x, p1y, p2x, p2y, minX, minY); let w01 = orient(p2x, p2y, p0x, p0y, minX, minY); let w02 = orient(p0x, p0y, p1x, p1y, minX, minY); const a01 = p1y - p0y; const b01 = p0x - p1x; const a12 = p2y - p1y; const b12 = p1x - p2x; const a20 = p0y - p2y; const b20 = p2x - p0x; const a2 = orient(p0x, p0y, p1x, p1y, p2x, p2y); const z0 = this.heightAt(p0x, p0y) / a2; const z1 = this.heightAt(p1x, p1y) / a2; const z2 = this.heightAt(p2x, p2y) / a2; let maxError = 0; let mx = 0; let my = 0; let rms = 0; for (let y2 = minY; y2 <= maxY; y2++) { let dx = 0; if (w00 < 0 && a12 !== 0) { dx = Math.max(dx, Math.floor(-w00 / a12)); } if (w01 < 0 && a20 !== 0) { dx = Math.max(dx, Math.floor(-w01 / a20)); } if (w02 < 0 && a01 !== 0) { dx = Math.max(dx, Math.floor(-w02 / a01)); } let w0 = w00 + a12 * dx; let w1 = w01 + a20 * dx; let w2 = w02 + a01 * dx; let wasInside = false; for (let x2 = minX + dx; x2 <= maxX; x2++) { if (w0 >= 0 && w1 >= 0 && w2 >= 0) { wasInside = true; const z = z0 * w0 + z1 * w1 + z2 * w2; const dz = Math.abs(z - this.heightAt(x2, y2)); rms += dz * dz; if (dz > maxError) { maxError = dz; mx = x2; my = y2; } } else if (wasInside) { break; } w0 += a12; w1 += a20; w2 += a01; } w00 += b12; w01 += b20; w02 += b01; } if (mx === p0x && my === p0y || mx === p1x && my === p1y || mx === p2x && my === p2y) { maxError = 0; } this._candidates[2 * t2] = mx; this._candidates[2 * t2 + 1] = my; this._rms[t2] = rms; this._queuePush(t2, maxError, rms); } _step() { const t2 = this._queuePop(); const e0 = t2 * 3 + 0; const e1 = t2 * 3 + 1; const e2 = t2 * 3 + 2; const p0 = this.triangles[e0]; const p1 = this.triangles[e1]; const p2 = this.triangles[e2]; const ax = this.coords[2 * p0]; const ay = this.coords[2 * p0 + 1]; const bx = this.coords[2 * p1]; const by = this.coords[2 * p1 + 1]; const cx = this.coords[2 * p2]; const cy = this.coords[2 * p2 + 1]; const px = this._candidates[2 * t2]; const py = this._candidates[2 * t2 + 1]; const pn = this._addPoint(px, py); if (orient(ax, ay, bx, by, px, py) === 0) { this._handleCollinear(pn, e0); } else if (orient(bx, by, cx, cy, px, py) === 0) { this._handleCollinear(pn, e1); } else if (orient(cx, cy, ax, ay, px, py) === 0) { this._handleCollinear(pn, e2); } else { const h0 = this._halfedges[e0]; const h1 = this._halfedges[e1]; const h2 = this._halfedges[e2]; const t0 = this._addTriangle(p0, p1, pn, h0, -1, -1, e0); const t1 = this._addTriangle(p1, p2, pn, h1, -1, t0 + 1); const t22 = this._addTriangle(p2, p0, pn, h2, t0 + 2, t1 + 1); this._legalize(t0); this._legalize(t1); this._legalize(t22); } } _addPoint(x2, y2) { const i3 = this.coords.length >> 1; this.coords.push(x2, y2); return i3; } _addTriangle(a2, b, c, ab, bc, ca, e = this.triangles.length) { const t2 = e / 3; this.triangles[e + 0] = a2; this.triangles[e + 1] = b; this.triangles[e + 2] = c; this._halfedges[e + 0] = ab; this._halfedges[e + 1] = bc; this._halfedges[e + 2] = ca; if (ab >= 0) { this._halfedges[ab] = e + 0; } if (bc >= 0) { this._halfedges[bc] = e + 1; } if (ca >= 0) { this._halfedges[ca] = e + 2; } this._candidates[2 * t2 + 0] = 0; this._candidates[2 * t2 + 1] = 0; this._queueIndices[t2] = -1; this._rms[t2] = 0; this._pending[this._pendingLen++] = t2; return e; } _legalize(a2) { const b = this._halfedges[a2]; if (b < 0) { return; } const a0 = a2 - a2 % 3; const b0 = b - b % 3; const al = a0 + (a2 + 1) % 3; const ar = a0 + (a2 + 2) % 3; const bl = b0 + (b + 2) % 3; const br = b0 + (b + 1) % 3; const p0 = this.triangles[ar]; const pr = this.triangles[a2]; const pl = this.triangles[al]; const p1 = this.triangles[bl]; const coords = this.coords; if (!inCircle(coords[2 * p0], coords[2 * p0 + 1], coords[2 * pr], coords[2 * pr + 1], coords[2 * pl], coords[2 * pl + 1], coords[2 * p1], coords[2 * p1 + 1])) { return; } const hal = this._halfedges[al]; const har = this._halfedges[ar]; const hbl = this._halfedges[bl]; const hbr = this._halfedges[br]; this._queueRemove(a0 / 3); this._queueRemove(b0 / 3); const t0 = this._addTriangle(p0, p1, pl, -1, hbl, hal, a0); const t1 = this._addTriangle(p1, p0, pr, t0, har, hbr, b0); this._legalize(t0 + 1); this._legalize(t1 + 2); } _handleCollinear(pn, a2) { const a0 = a2 - a2 % 3; const al = a0 + (a2 + 1) % 3; const ar = a0 + (a2 + 2) % 3; const p0 = this.triangles[ar]; const pr = this.triangles[a2]; const pl = this.triangles[al]; const hal = this._halfedges[al]; const har = this._halfedges[ar]; const b = this._halfedges[a2]; if (b < 0) { const t02 = this._addTriangle(pn, p0, pr, -1, har, -1, a0); const t12 = this._addTriangle(p0, pn, pl, t02, -1, hal); this._legalize(t02 + 1); this._legalize(t12 + 2); return; } const b0 = b - b % 3; const bl = b0 + (b + 2) % 3; const br = b0 + (b + 1) % 3; const p1 = this.triangles[bl]; const hbl = this._halfedges[bl]; const hbr = this._halfedges[br]; this._queueRemove(b0 / 3); const t0 = this._addTriangle(p0, pr, pn, har, -1, -1, a0); const t1 = this._addTriangle(pr, p1, pn, hbr, -1, t0 + 1, b0); const t2 = this._addTriangle(p1, pl, pn, hbl, -1, t1 + 1); const t3 = this._addTriangle(pl, p0, pn, hal, t0 + 2, t2 + 1); this._legalize(t0); this._legalize(t1); this._legalize(t2); this._legalize(t3); } _queuePush(t2, error, rms) { const i3 = this._queue.length; this._queueIndices[t2] = i3; this._queue.push(t2); this._errors.push(error); this._rmsSum += rms; this._queueUp(i3); } _queuePop() { const n2 = this._queue.length - 1; this._queueSwap(0, n2); this._queueDown(0, n2); return this._queuePopBack(); } _queuePopBack() { const t2 = this._queue.pop(); this._errors.pop(); this._rmsSum -= this._rms[t2]; this._queueIndices[t2] = -1; return t2; } _queueRemove(t2) { const i3 = this._queueIndices[t2]; if (i3 < 0) { const it = this._pending.indexOf(t2); if (it !== -1) { this._pending[it] = this._pending[--this._pendingLen]; } else { throw new Error("Broken triangulation (something went wrong)."); } return; } const n2 = this._queue.length - 1; if (n2 !== i3) { this._queueSwap(i3, n2); if (!this._queueDown(i3, n2)) { this._queueUp(i3); } } this._queuePopBack(); } _queueLess(i3, j) { return this._errors[i3] > this._errors[j]; } _queueSwap(i3, j) { const pi = this._queue[i3]; const pj = this._queue[j]; this._queue[i3] = pj; this._queue[j] = pi; this._queueIndices[pi] = j; this._queueIndices[pj] = i3; const e = this._errors[i3]; this._errors[i3] = this._errors[j]; this._errors[j] = e; } _queueUp(j0) { let j = j0; while (true) { const i3 = j - 1 >> 1; if (i3 === j || !this._queueLess(j, i3)) { break; } this._queueSwap(i3, j); j = i3; } } _queueDown(i0, n2) { let i3 = i0; while (true) { const j1 = 2 * i3 + 1; if (j1 >= n2 || j1 < 0) { break; } const j2 = j1 + 1; let j = j1; if (j2 < n2 && this._queueLess(j2, j1)) { j = j2; } if (!this._queueLess(j, i3)) { break; } this._queueSwap(i3, j); i3 = j; } return i3 > i0; } }; function orient(ax, ay, bx, by, cx, cy) { return (bx - cx) * (ay - cy) - (by - cy) * (ax - cx); } function inCircle(ax, ay, bx, by, cx, cy, px, py) { const dx = ax - px; const dy = ay - py; const ex = bx - px; const ey = by - py; const fx = cx - px; const fy = cy - py; const ap = dx * dx + dy * dy; const bp = ex * ex + ey * ey; const cp = fx * fx + fy * fy; return dx * (ey * cp - bp * fy) - dy * (ex * cp - bp * fx) + ap * (ex * fy - ey * fx) < 0; } // ../../node_modules/@loaders.gl/terrain/dist/lib/parse-terrain.js function makeTerrainMeshFromImage(terrainImage, terrainOptions) { const { meshMaxError, bounds, elevationDecoder } = terrainOptions; const { data, width, height } = terrainImage; let terrain; let mesh; switch (terrainOptions.tesselator) { case "martini": terrain = getTerrain(data, width, height, elevationDecoder, terrainOptions.tesselator); mesh = getMartiniTileMesh(meshMaxError, width, terrain); break; case "delatin": terrain = getTerrain(data, width, height, elevationDecoder, terrainOptions.tesselator); mesh = getDelatinTileMesh(meshMaxError, width, height, terrain); break; default: if (width === height && !(height & width - 1)) { terrain = getTerrain(data, width, height, elevationDecoder, "martini"); mesh = getMartiniTileMesh(meshMaxError, width, terrain); } else { terrain = getTerrain(data, width, height, elevationDecoder, "delatin"); mesh = getDelatinTileMesh(meshMaxError, width, height, terrain); } break; } const { vertices } = mesh; let { triangles } = mesh; let attributes = getMeshAttributes2(vertices, terrain, width, height, bounds); const boundingBox = getMeshBoundingBox(attributes); if (terrainOptions.skirtHeight) { const { attributes: newAttributes, triangles: newTriangles } = addSkirt(attributes, triangles, terrainOptions.skirtHeight); attributes = newAttributes; triangles = newTriangles; } return { loaderData: { header: {} }, header: { vertexCount: triangles.length, boundingBox }, mode: 4, indices: { value: Uint32Array.from(triangles), size: 1 }, attributes }; } function getMartiniTileMesh(meshMaxError, width, terrain) { const gridSize = width + 1; const martini = new Martini(gridSize); const tile = martini.createTile(terrain); const { vertices, triangles } = tile.getMesh(meshMaxError); return { vertices, triangles }; } function getDelatinTileMesh(meshMaxError, width, height, terrain) { const tin = new Delatin(terrain, width + 1, height + 1); tin.run(meshMaxError); const { coords, triangles } = tin; const vertices = coords; return { vertices, triangles }; } function getTerrain(imageData, width, height, elevationDecoder, tesselator) { const { rScaler, bScaler, gScaler, offset } = elevationDecoder; const terrain = new Float32Array((width + 1) * (height + 1)); for (let i3 = 0, y2 = 0; y2 < height; y2++) { for (let x2 = 0; x2 < width; x2++, i3++) { const k = i3 * 4; const r2 = imageData[k + 0]; const g = imageData[k + 1]; const b = imageData[k + 2]; terrain[i3 + y2] = r2 * rScaler + g * gScaler + b * bScaler + offset; } } if (tesselator === "martini") { for (let i3 = (width + 1) * width, x2 = 0; x2 < width; x2++, i3++) { terrain[i3] = terrain[i3 - width - 1]; } for (let i3 = height, y2 = 0; y2 < height + 1; y2++, i3 += height + 1) { terrain[i3] = terrain[i3 - 1]; } } return terrain; } function getMeshAttributes2(vertices, terrain, width, height, bounds) { const gridSize = width + 1; const numOfVerticies = vertices.length / 2; const positions = new Float32Array(numOfVerticies * 3); const texCoords = new Float32Array(numOfVerticies * 2); const [minX, minY, maxX, maxY] = bounds || [0, 0, width, height]; const xScale = (maxX - minX) / width; const yScale = (maxY - minY) / height; for (let i3 = 0; i3 < numOfVerticies; i3++) { const x2 = vertices[i3 * 2]; const y2 = vertices[i3 * 2 + 1]; const pixelIdx = y2 * gridSize + x2; positions[3 * i3 + 0] = x2 * xScale + minX; positions[3 * i3 + 1] = -y2 * yScale + maxY; positions[3 * i3 + 2] = terrain[pixelIdx]; texCoords[2 * i3 + 0] = x2 / width; texCoords[2 * i3 + 1] = y2 / height; } return { POSITION: { value: positions, size: 3 }, TEXCOORD_0: { value: texCoords, size: 2 } }; } // ../../node_modules/@loaders.gl/terrain/dist/lib/utils/version.js var VERSION11 = true ? "4.2.0-beta.2" : "latest"; // ../../node_modules/@loaders.gl/terrain/dist/terrain-loader.js var TerrainLoader = { dataType: null, batchType: null, name: "Terrain", id: "terrain", module: "terrain", version: VERSION11, worker: true, extensions: ["png", "pngraw", "jpg", "jpeg", "gif", "webp", "bmp"], mimeTypes: ["image/png", "image/jpeg", "image/gif", "image/webp", "image/bmp"], options: { terrain: { tesselator: "auto", bounds: void 0, meshMaxError: 10, elevationDecoder: { rScaler: 1, gScaler: 0, bScaler: 0, offset: 0 }, skirtHeight: void 0 } } }; // ../../node_modules/@loaders.gl/terrain/dist/quantized-mesh-loader.js var QuantizedMeshLoader = { dataType: null, batchType: null, name: "Quantized Mesh", id: "quantized-mesh", module: "terrain", version: VERSION11, worker: true, extensions: ["terrain"], mimeTypes: ["application/vnd.quantized-mesh"], options: { "quantized-mesh": { bounds: [0, 0, 1, 1], skirtHeight: null } } }; // ../../node_modules/@loaders.gl/terrain/dist/index.js var TerrainLoader2 = { ...TerrainLoader, parse: parseTerrain }; async function parseTerrain(arrayBuffer, options, context) { const loadImageOptions = { ...options, mimeType: "application/x.image", image: { ...options?.image, type: "data" } }; const image = await parseFromContext(arrayBuffer, [], loadImageOptions, context); const terrainOptions = { ...TerrainLoader2.options.terrain, ...options?.terrain }; return makeTerrainMeshFromImage(image, terrainOptions); } var QuantizedMeshLoader2 = { ...QuantizedMeshLoader, parseSync: (arrayBuffer, options) => parseQuantizedMesh(arrayBuffer, options?.["quantized-mesh"]), parse: async (arrayBuffer, options) => parseQuantizedMesh(arrayBuffer, options?.["quantized-mesh"]) }; // src/terrain-layer/terrain-layer.ts var DUMMY_DATA = [1]; var defaultProps12 = { ...TileLayer.defaultProps, elevationData: urlType, texture: { ...urlType, optional: true }, meshMaxError: { type: "number", value: 4 }, bounds: { type: "array", value: null, optional: true, compare: true }, color: { type: "color", value: [255, 255, 255] }, elevationDecoder: { type: "object", value: { rScaler: 1, gScaler: 0, bScaler: 0, offset: 0 } }, workerUrl: "", wireframe: false, material: true, loaders: [TerrainLoader] }; function urlTemplateToUpdateTrigger(template) { if (Array.isArray(template)) { return template.join(";"); } return template || ""; } var TerrainLayer = class extends import_core45.CompositeLayer { updateState({ props, oldProps }) { const elevationDataChanged = props.elevationData !== oldProps.elevationData; if (elevationDataChanged) { const { elevationData } = props; const isTiled = elevationData && (Array.isArray(elevationData) || elevationData.includes("{x}") && elevationData.includes("{y}")); this.setState({ isTiled }); } const shouldReload = elevationDataChanged || props.meshMaxError !== oldProps.meshMaxError || props.elevationDecoder !== oldProps.elevationDecoder || props.bounds !== oldProps.bounds; if (!this.state.isTiled && shouldReload) { const terrain = this.loadTerrain(props); this.setState({ terrain }); } if (props.workerUrl) { import_core45.log.removed("workerUrl", "loadOptions.terrain.workerUrl")(); } } loadTerrain({ elevationData, bounds, elevationDecoder, meshMaxError, signal }) { if (!elevationData) { return null; } let loadOptions = this.getLoadOptions(); loadOptions = { ...loadOptions, terrain: { skirtHeight: this.state.isTiled ? meshMaxError * 2 : 0, ...loadOptions?.terrain, bounds, meshMaxError, elevationDecoder } }; const { fetch: fetch2 } = this.props; return fetch2(elevationData, { propName: "elevationData", layer: this, loadOptions, signal }); } getTiledTerrainData(tile) { const { elevationData, fetch: fetch2, texture, elevationDecoder, meshMaxError } = this.props; const { viewport } = this.context; const dataUrl = getURLFromTemplate(elevationData, tile); const textureUrl = texture && getURLFromTemplate(texture, tile); const { signal } = tile; let bottomLeft = [0, 0]; let topRight = [0, 0]; if (viewport.isGeospatial) { const bbox = tile.bbox; bottomLeft = viewport.projectFlat([bbox.west, bbox.south]); topRight = viewport.projectFlat([bbox.east, bbox.north]); } else { const bbox = tile.bbox; bottomLeft = [bbox.left, bbox.bottom]; topRight = [bbox.right, bbox.top]; } const bounds = [bottomLeft[0], bottomLeft[1], topRight[0], topRight[1]]; const terrain = this.loadTerrain({ elevationData: dataUrl, bounds, elevationDecoder, meshMaxError, signal }); const surface = textureUrl ? fetch2(textureUrl, { propName: "texture", layer: this, loaders: [], signal }).catch((_) => null) : Promise.resolve(null); return Promise.all([terrain, surface]); } renderSubLayers(props) { const SubLayerClass = this.getSubLayerClass("mesh", import_mesh_layers3.SimpleMeshLayer); const { color, wireframe, material } = this.props; const { data } = props; if (!data) { return null; } const [mesh, texture] = data; return new SubLayerClass(props, { data: DUMMY_DATA, mesh, texture, _instanced: false, coordinateSystem: import_core46.COORDINATE_SYSTEM.CARTESIAN, getPosition: (d) => [0, 0, 0], getColor: color, wireframe, material }); } onViewportLoad(tiles) { if (!tiles) { return; } const { zRange } = this.state; const ranges = tiles.map((tile) => tile.content).filter(Boolean).map((arr) => { const bounds = arr[0].header.boundingBox; return bounds.map((bound) => bound[2]); }); if (ranges.length === 0) { return; } const minZ = Math.min(...ranges.map((x2) => x2[0])); const maxZ = Math.max(...ranges.map((x2) => x2[1])); if (!zRange || minZ < zRange[0] || maxZ > zRange[1]) { this.setState({ zRange: [minZ, maxZ] }); } } renderLayers() { const { color, material, elevationData, texture, wireframe, meshMaxError, elevationDecoder, tileSize, maxZoom, minZoom, extent, maxRequests, onTileLoad, onTileUnload, onTileError, maxCacheSize, maxCacheByteSize, refinementStrategy } = this.props; if (this.state.isTiled) { return new TileLayer( this.getSubLayerProps({ id: "tiles" }), { getTileData: this.getTiledTerrainData.bind(this), renderSubLayers: this.renderSubLayers.bind(this), updateTriggers: { getTileData: { elevationData: urlTemplateToUpdateTrigger(elevationData), texture: urlTemplateToUpdateTrigger(texture), meshMaxError, elevationDecoder } }, onViewportLoad: this.onViewportLoad.bind(this), zRange: this.state.zRange || null, tileSize, maxZoom, minZoom, extent, maxRequests, onTileLoad, onTileUnload, onTileError, maxCacheSize, maxCacheByteSize, refinementStrategy } ); } if (!elevationData) { return null; } const SubLayerClass = this.getSubLayerClass("mesh", import_mesh_layers3.SimpleMeshLayer); return new SubLayerClass( this.getSubLayerProps({ id: "mesh" }), { data: DUMMY_DATA, mesh: this.state.terrain, texture, _instanced: false, getPosition: (d) => [0, 0, 0], getColor: color, material, wireframe } ); } }; TerrainLayer.defaultProps = defaultProps12; TerrainLayer.layerName = "TerrainLayer"; // src/mvt-layer/mvt-layer.ts var import_core48 = __toESM(require_core(), 1); var import_layers9 = __toESM(require_layers(), 1); var import_extensions = __toESM(require_extensions(), 1); // ../../node_modules/@math.gl/polygon/dist/polygon-utils.js var DimIndex = { x: 0, y: 1, z: 2 }; function getPolygonSignedArea(points, options = {}) { const { start = 0, end = points.length, plane = "xy" } = options; const dim = options.size || 2; let area2 = 0; const i0 = DimIndex[plane[0]]; const i1 = DimIndex[plane[1]]; for (let i3 = start, j = end - dim; i3 < end; i3 += dim) { area2 += (points[i3 + i0] - points[j + i0]) * (points[i3 + i1] + points[j + i1]); j = i3; } return area2 / 2; } // ../../node_modules/@math.gl/polygon/dist/earcut.js function earcut(positions, holeIndices, dim = 2, areas, plane = "xy") { const hasHoles = holeIndices && holeIndices.length; const outerLen = hasHoles ? holeIndices[0] * dim : positions.length; let outerNode = linkedList(positions, 0, outerLen, dim, true, areas && areas[0], plane); const triangles = []; if (!outerNode || outerNode.next === outerNode.prev) return triangles; let invSize; let maxX; let maxY; let minX; let minY; let x2; let y2; if (hasHoles) outerNode = eliminateHoles(positions, holeIndices, outerNode, dim, areas, plane); if (positions.length > 80 * dim) { minX = maxX = positions[0]; minY = maxY = positions[1]; for (let i3 = dim; i3 < outerLen; i3 += dim) { x2 = positions[i3]; y2 = positions[i3 + 1]; if (x2 < minX) minX = x2; if (y2 < minY) minY = y2; if (x2 > maxX) maxX = x2; if (y2 > maxY) maxY = y2; } invSize = Math.max(maxX - minX, maxY - minY); invSize = invSize !== 0 ? 32767 / invSize : 0; } earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0); return triangles; } function linkedList(data, start, end, dim, clockwise, area2, plane) { let i3; let last; if (area2 === void 0) { area2 = getPolygonSignedArea(data, { start, end, size: dim, plane }); } let i0 = DimIndex[plane[0]]; let i1 = DimIndex[plane[1]]; if (clockwise === area2 < 0) { for (i3 = start; i3 < end; i3 += dim) last = insertNode(i3, data[i3 + i0], data[i3 + i1], last); } else { for (i3 = end - dim; i3 >= start; i3 -= dim) last = insertNode(i3, data[i3 + i0], data[i3 + i1], last); } if (last && equals5(last, last.next)) { removeNode(last); last = last.next; } return last; } function filterPoints(start, end) { if (!start) return start; if (!end) end = start; let p2 = start; let again; do { again = false; if (!p2.steiner && (equals5(p2, p2.next) || area(p2.prev, p2, p2.next) === 0)) { removeNode(p2); p2 = end = p2.prev; if (p2 === p2.next) break; again = true; } else { p2 = p2.next; } } while (again || p2 !== end); return end; } function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) { if (!ear) return; if (!pass && invSize) indexCurve(ear, minX, minY, invSize); let stop = ear; let prev; let next; while (ear.prev !== ear.next) { prev = ear.prev; next = ear.next; if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) { triangles.push(prev.i / dim | 0); triangles.push(ear.i / dim | 0); triangles.push(next.i / dim | 0); removeNode(ear); ear = next.next; stop = next.next; continue; } ear = next; if (ear === stop) { if (!pass) { earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); } else if (pass === 1) { ear = cureLocalIntersections(filterPoints(ear), triangles, dim); earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); } else if (pass === 2) { splitEarcut(ear, triangles, dim, minX, minY, invSize); } break; } } } function isEar(ear) { const a2 = ear.prev; const b = ear; const c = ear.next; if (area(a2, b, c) >= 0) return false; const ax = a2.x; const bx = b.x; const cx = c.x; const ay = a2.y; const by = b.y; const cy = c.y; const x0 = ax < bx ? ax < cx ? ax : cx : bx < cx ? bx : cx; const y0 = ay < by ? ay < cy ? ay : cy : by < cy ? by : cy; const x1 = ax > bx ? ax > cx ? ax : cx : bx > cx ? bx : cx; const y1 = ay > by ? ay > cy ? ay : cy : by > cy ? by : cy; let p2 = c.next; while (p2 !== a2) { if (p2.x >= x0 && p2.x <= x1 && p2.y >= y0 && p2.y <= y1 && pointInTriangle(ax, ay, bx, by, cx, cy, p2.x, p2.y) && area(p2.prev, p2, p2.next) >= 0) return false; p2 = p2.next; } return true; } function isEarHashed(ear, minX, minY, invSize) { const a2 = ear.prev; const b = ear; const c = ear.next; if (area(a2, b, c) >= 0) return false; const ax = a2.x; const bx = b.x; const cx = c.x; const ay = a2.y; const by = b.y; const cy = c.y; const x0 = ax < bx ? ax < cx ? ax : cx : bx < cx ? bx : cx; const y0 = ay < by ? ay < cy ? ay : cy : by < cy ? by : cy; const x1 = ax > bx ? ax > cx ? ax : cx : bx > cx ? bx : cx; const y1 = ay > by ? ay > cy ? ay : cy : by > cy ? by : cy; const minZ = zOrder(x0, y0, minX, minY, invSize); const maxZ = zOrder(x1, y1, minX, minY, invSize); let p2 = ear.prevZ; let n2 = ear.nextZ; while (p2 && p2.z >= minZ && n2 && n2.z <= maxZ) { if (p2.x >= x0 && p2.x <= x1 && p2.y >= y0 && p2.y <= y1 && p2 !== a2 && p2 !== c && pointInTriangle(ax, ay, bx, by, cx, cy, p2.x, p2.y) && area(p2.prev, p2, p2.next) >= 0) return false; p2 = p2.prevZ; if (n2.x >= x0 && n2.x <= x1 && n2.y >= y0 && n2.y <= y1 && n2 !== a2 && n2 !== c && pointInTriangle(ax, ay, bx, by, cx, cy, n2.x, n2.y) && area(n2.prev, n2, n2.next) >= 0) return false; n2 = n2.nextZ; } while (p2 && p2.z >= minZ) { if (p2.x >= x0 && p2.x <= x1 && p2.y >= y0 && p2.y <= y1 && p2 !== a2 && p2 !== c && pointInTriangle(ax, ay, bx, by, cx, cy, p2.x, p2.y) && area(p2.prev, p2, p2.next) >= 0) return false; p2 = p2.prevZ; } while (n2 && n2.z <= maxZ) { if (n2.x >= x0 && n2.x <= x1 && n2.y >= y0 && n2.y <= y1 && n2 !== a2 && n2 !== c && pointInTriangle(ax, ay, bx, by, cx, cy, n2.x, n2.y) && area(n2.prev, n2, n2.next) >= 0) return false; n2 = n2.nextZ; } return true; } function cureLocalIntersections(start, triangles, dim) { let p2 = start; do { const a2 = p2.prev; const b = p2.next.next; if (!equals5(a2, b) && intersects(a2, p2, p2.next, b) && locallyInside(a2, b) && locallyInside(b, a2)) { triangles.push(a2.i / dim | 0); triangles.push(p2.i / dim | 0); triangles.push(b.i / dim | 0); removeNode(p2); removeNode(p2.next); p2 = start = b; } p2 = p2.next; } while (p2 !== start); return filterPoints(p2); } function splitEarcut(start, triangles, dim, minX, minY, invSize) { let a2 = start; do { let b = a2.next.next; while (b !== a2.prev) { if (a2.i !== b.i && isValidDiagonal(a2, b)) { let c = splitPolygon(a2, b); a2 = filterPoints(a2, a2.next); c = filterPoints(c, c.next); earcutLinked(a2, triangles, dim, minX, minY, invSize, 0); earcutLinked(c, triangles, dim, minX, minY, invSize, 0); return; } b = b.next; } a2 = a2.next; } while (a2 !== start); } function eliminateHoles(data, holeIndices, outerNode, dim, areas, plane) { const queue = []; let i3; let len2; let start; let end; let list; for (i3 = 0, len2 = holeIndices.length; i3 < len2; i3++) { start = holeIndices[i3] * dim; end = i3 < len2 - 1 ? holeIndices[i3 + 1] * dim : data.length; list = linkedList(data, start, end, dim, false, areas && areas[i3 + 1], plane); if (list === list.next) list.steiner = true; queue.push(getLeftmost(list)); } queue.sort(compareX); for (i3 = 0; i3 < queue.length; i3++) { outerNode = eliminateHole(queue[i3], outerNode); } return outerNode; } function compareX(a2, b) { return a2.x - b.x; } function eliminateHole(hole, outerNode) { const bridge = findHoleBridge(hole, outerNode); if (!bridge) { return outerNode; } const bridgeReverse = splitPolygon(bridge, hole); filterPoints(bridgeReverse, bridgeReverse.next); return filterPoints(bridge, bridge.next); } function findHoleBridge(hole, outerNode) { let p2 = outerNode; const hx = hole.x; const hy = hole.y; let qx = -Infinity; let m; do { if (hy <= p2.y && hy >= p2.next.y && p2.next.y !== p2.y) { const x2 = p2.x + (hy - p2.y) * (p2.next.x - p2.x) / (p2.next.y - p2.y); if (x2 <= hx && x2 > qx) { qx = x2; m = p2.x < p2.next.x ? p2 : p2.next; if (x2 === hx) return m; } } p2 = p2.next; } while (p2 !== outerNode); if (!m) return null; const stop = m; const mx = m.x; const my = m.y; let tanMin = Infinity; let tan2; p2 = m; do { if (hx >= p2.x && p2.x >= mx && hx !== p2.x && pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p2.x, p2.y)) { tan2 = Math.abs(hy - p2.y) / (hx - p2.x); if (locallyInside(p2, hole) && (tan2 < tanMin || tan2 === tanMin && (p2.x > m.x || p2.x === m.x && sectorContainsSector(m, p2)))) { m = p2; tanMin = tan2; } } p2 = p2.next; } while (p2 !== stop); return m; } function sectorContainsSector(m, p2) { return area(m.prev, m, p2.prev) < 0 && area(p2.next, m, m.next) < 0; } function indexCurve(start, minX, minY, invSize) { let p2 = start; do { if (p2.z === 0) p2.z = zOrder(p2.x, p2.y, minX, minY, invSize); p2.prevZ = p2.prev; p2.nextZ = p2.next; p2 = p2.next; } while (p2 !== start); p2.prevZ.nextZ = null; p2.prevZ = null; sortLinked(p2); } function sortLinked(list) { let e; let i3; let inSize = 1; let numMerges; let p2; let pSize; let q; let qSize; let tail; do { p2 = list; list = null; tail = null; numMerges = 0; while (p2) { numMerges++; q = p2; pSize = 0; for (i3 = 0; i3 < inSize; i3++) { pSize++; q = q.nextZ; if (!q) break; } qSize = inSize; while (pSize > 0 || qSize > 0 && q) { if (pSize !== 0 && (qSize === 0 || !q || p2.z <= q.z)) { e = p2; p2 = p2.nextZ; pSize--; } else { e = q; q = q.nextZ; qSize--; } if (tail) tail.nextZ = e; else list = e; e.prevZ = tail; tail = e; } p2 = q; } tail.nextZ = null; inSize *= 2; } while (numMerges > 1); return list; } function zOrder(x2, y2, minX, minY, invSize) { x2 = (x2 - minX) * invSize | 0; y2 = (y2 - minY) * invSize | 0; x2 = (x2 | x2 << 8) & 16711935; x2 = (x2 | x2 << 4) & 252645135; x2 = (x2 | x2 << 2) & 858993459; x2 = (x2 | x2 << 1) & 1431655765; y2 = (y2 | y2 << 8) & 16711935; y2 = (y2 | y2 << 4) & 252645135; y2 = (y2 | y2 << 2) & 858993459; y2 = (y2 | y2 << 1) & 1431655765; return x2 | y2 << 1; } function getLeftmost(start) { let p2 = start; let leftmost = start; do { if (p2.x < leftmost.x || p2.x === leftmost.x && p2.y < leftmost.y) leftmost = p2; p2 = p2.next; } while (p2 !== start); return leftmost; } 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); } function isValidDiagonal(a2, b) { return a2.next.i !== b.i && a2.prev.i !== b.i && !intersectsPolygon(a2, b) && (locallyInside(a2, b) && locallyInside(b, a2) && middleInside(a2, b) && (area(a2.prev, a2, b.prev) || area(a2, b.prev, b)) || equals5(a2, b) && area(a2.prev, a2, a2.next) > 0 && area(b.prev, b, b.next) > 0); } function area(p2, q, r2) { return (q.y - p2.y) * (r2.x - q.x) - (q.x - p2.x) * (r2.y - q.y); } function equals5(p1, p2) { return p1.x === p2.x && p1.y === p2.y; } 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; if (o1 === 0 && onSegment(p1, p2, q1)) return true; if (o2 === 0 && onSegment(p1, q2, q1)) return true; if (o3 === 0 && onSegment(p2, p1, q2)) return true; if (o4 === 0 && onSegment(p2, q1, q2)) return true; return false; } function onSegment(p2, q, r2) { return q.x <= Math.max(p2.x, r2.x) && q.x >= Math.min(p2.x, r2.x) && q.y <= Math.max(p2.y, r2.y) && q.y >= Math.min(p2.y, r2.y); } function sign(num) { return num > 0 ? 1 : num < 0 ? -1 : 0; } function intersectsPolygon(a2, b) { let p2 = a2; do { if (p2.i !== a2.i && p2.next.i !== a2.i && p2.i !== b.i && p2.next.i !== b.i && intersects(p2, p2.next, a2, b)) return true; p2 = p2.next; } while (p2 !== a2); return false; } function locallyInside(a2, b) { return area(a2.prev, a2, a2.next) < 0 ? area(a2, b, a2.next) >= 0 && area(a2, a2.prev, b) >= 0 : area(a2, b, a2.prev) < 0 || area(a2, a2.next, b) < 0; } function middleInside(a2, b) { let p2 = a2; let inside = false; const px = (a2.x + b.x) / 2; const py = (a2.y + b.y) / 2; do { if (p2.y > py !== p2.next.y > py && p2.next.y !== p2.y && px < (p2.next.x - p2.x) * (py - p2.y) / (p2.next.y - p2.y) + p2.x) inside = !inside; p2 = p2.next; } while (p2 !== a2); return inside; } function splitPolygon(a2, b) { const a22 = new Vertex(a2.i, a2.x, a2.y); const b2 = new Vertex(b.i, b.x, b.y); const an = a2.next; const bp = b.prev; a2.next = b; b.prev = a2; a22.next = an; an.prev = a22; b2.next = a22; a22.prev = b2; bp.next = b2; b2.prev = bp; return b2; } function insertNode(i3, x2, y2, last) { const p2 = new Vertex(i3, x2, y2); if (!last) { p2.prev = p2; p2.next = p2; } else { p2.next = last.next; p2.prev = last; last.next.prev = p2; last.next = p2; } return p2; } function removeNode(p2) { p2.next.prev = p2.prev; p2.prev.next = p2.next; if (p2.prevZ) p2.prevZ.nextZ = p2.nextZ; if (p2.nextZ) p2.nextZ.prevZ = p2.prevZ; } var Vertex = class { constructor(i3, x2, y2) { this.prev = null; this.next = null; this.z = 0; this.prevZ = null; this.nextZ = null; this.steiner = false; this.i = i3; this.x = x2; this.y = y2; } }; // ../../node_modules/@loaders.gl/gis/dist/lib/binary-features/flat-geojson-to-binary.js function flatGeojsonToBinary(features, geometryInfo, options) { const propArrayTypes = extractNumericPropTypes(features); const numericPropKeys = Object.keys(propArrayTypes).filter((k) => propArrayTypes[k] !== Array); return fillArrays(features, { propArrayTypes, ...geometryInfo }, { numericPropKeys: options && options.numericPropKeys || numericPropKeys, PositionDataType: options ? options.PositionDataType : Float32Array, triangulate: options ? options.triangulate : true }); } function extractNumericPropTypes(features) { const propArrayTypes = {}; for (const feature of features) { if (feature.properties) { for (const key in feature.properties) { const val2 = feature.properties[key]; propArrayTypes[key] = deduceArrayType(val2, propArrayTypes[key]); } } } return propArrayTypes; } function fillArrays(features, geometryInfo, options) { const { pointPositionsCount, pointFeaturesCount, linePositionsCount, linePathsCount, lineFeaturesCount, polygonPositionsCount, polygonObjectsCount, polygonRingsCount, polygonFeaturesCount, propArrayTypes, coordLength } = geometryInfo; const { numericPropKeys = [], PositionDataType = Float32Array, triangulate = true } = options; const hasGlobalId = features[0] && "id" in features[0]; const GlobalFeatureIdsDataType = features.length > 65535 ? Uint32Array : Uint16Array; const points = { type: "Point", positions: new PositionDataType(pointPositionsCount * coordLength), globalFeatureIds: new GlobalFeatureIdsDataType(pointPositionsCount), featureIds: pointFeaturesCount > 65535 ? new Uint32Array(pointPositionsCount) : new Uint16Array(pointPositionsCount), numericProps: {}, properties: [], fields: [] }; const lines = { type: "LineString", pathIndices: linePositionsCount > 65535 ? new Uint32Array(linePathsCount + 1) : new Uint16Array(linePathsCount + 1), positions: new PositionDataType(linePositionsCount * coordLength), globalFeatureIds: new GlobalFeatureIdsDataType(linePositionsCount), featureIds: lineFeaturesCount > 65535 ? new Uint32Array(linePositionsCount) : new Uint16Array(linePositionsCount), numericProps: {}, properties: [], fields: [] }; const polygons = { type: "Polygon", polygonIndices: polygonPositionsCount > 65535 ? new Uint32Array(polygonObjectsCount + 1) : new Uint16Array(polygonObjectsCount + 1), primitivePolygonIndices: polygonPositionsCount > 65535 ? new Uint32Array(polygonRingsCount + 1) : new Uint16Array(polygonRingsCount + 1), positions: new PositionDataType(polygonPositionsCount * coordLength), globalFeatureIds: new GlobalFeatureIdsDataType(polygonPositionsCount), featureIds: polygonFeaturesCount > 65535 ? new Uint32Array(polygonPositionsCount) : new Uint16Array(polygonPositionsCount), numericProps: {}, properties: [], fields: [] }; if (triangulate) { polygons.triangles = []; } for (const object of [points, lines, polygons]) { for (const propName of numericPropKeys) { const T = propArrayTypes[propName]; object.numericProps[propName] = new T(object.positions.length / coordLength); } } lines.pathIndices[linePathsCount] = linePositionsCount; polygons.polygonIndices[polygonObjectsCount] = polygonPositionsCount; polygons.primitivePolygonIndices[polygonRingsCount] = polygonPositionsCount; const indexMap = { pointPosition: 0, pointFeature: 0, linePosition: 0, linePath: 0, lineFeature: 0, polygonPosition: 0, polygonObject: 0, polygonRing: 0, polygonFeature: 0, feature: 0 }; for (const feature of features) { const geometry = feature.geometry; const properties = feature.properties || {}; switch (geometry.type) { case "Point": handlePoint(geometry, points, indexMap, coordLength, properties); points.properties.push(keepStringProperties(properties, numericPropKeys)); if (hasGlobalId) { points.fields.push({ id: feature.id }); } indexMap.pointFeature++; break; case "LineString": handleLineString(geometry, lines, indexMap, coordLength, properties); lines.properties.push(keepStringProperties(properties, numericPropKeys)); if (hasGlobalId) { lines.fields.push({ id: feature.id }); } indexMap.lineFeature++; break; case "Polygon": handlePolygon(geometry, polygons, indexMap, coordLength, properties); polygons.properties.push(keepStringProperties(properties, numericPropKeys)); if (hasGlobalId) { polygons.fields.push({ id: feature.id }); } indexMap.polygonFeature++; break; default: throw new Error("Invalid geometry type"); } indexMap.feature++; } return makeAccessorObjects(points, lines, polygons, coordLength); } function handlePoint(geometry, points, indexMap, coordLength, properties) { points.positions.set(geometry.data, indexMap.pointPosition * coordLength); const nPositions = geometry.data.length / coordLength; fillNumericProperties(points, properties, indexMap.pointPosition, nPositions); points.globalFeatureIds.fill(indexMap.feature, indexMap.pointPosition, indexMap.pointPosition + nPositions); points.featureIds.fill(indexMap.pointFeature, indexMap.pointPosition, indexMap.pointPosition + nPositions); indexMap.pointPosition += nPositions; } function handleLineString(geometry, lines, indexMap, coordLength, properties) { lines.positions.set(geometry.data, indexMap.linePosition * coordLength); const nPositions = geometry.data.length / coordLength; fillNumericProperties(lines, properties, indexMap.linePosition, nPositions); lines.globalFeatureIds.fill(indexMap.feature, indexMap.linePosition, indexMap.linePosition + nPositions); lines.featureIds.fill(indexMap.lineFeature, indexMap.linePosition, indexMap.linePosition + nPositions); for (let i3 = 0, il = geometry.indices.length; i3 < il; ++i3) { const start = geometry.indices[i3]; const end = i3 === il - 1 ? geometry.data.length : geometry.indices[i3 + 1]; lines.pathIndices[indexMap.linePath++] = indexMap.linePosition; indexMap.linePosition += (end - start) / coordLength; } } function handlePolygon(geometry, polygons, indexMap, coordLength, properties) { polygons.positions.set(geometry.data, indexMap.polygonPosition * coordLength); const nPositions = geometry.data.length / coordLength; fillNumericProperties(polygons, properties, indexMap.polygonPosition, nPositions); polygons.globalFeatureIds.fill(indexMap.feature, indexMap.polygonPosition, indexMap.polygonPosition + nPositions); polygons.featureIds.fill(indexMap.polygonFeature, indexMap.polygonPosition, indexMap.polygonPosition + nPositions); for (let l2 = 0, ll = geometry.indices.length; l2 < ll; ++l2) { const startPosition = indexMap.polygonPosition; polygons.polygonIndices[indexMap.polygonObject++] = startPosition; const areas = geometry.areas[l2]; const indices = geometry.indices[l2]; const nextIndices = geometry.indices[l2 + 1]; for (let i3 = 0, il = indices.length; i3 < il; ++i3) { const start = indices[i3]; const end = i3 === il - 1 ? nextIndices === void 0 ? geometry.data.length : nextIndices[0] : indices[i3 + 1]; polygons.primitivePolygonIndices[indexMap.polygonRing++] = indexMap.polygonPosition; indexMap.polygonPosition += (end - start) / coordLength; } const endPosition = indexMap.polygonPosition; triangulatePolygon(polygons, areas, indices, { startPosition, endPosition, coordLength }); } } function triangulatePolygon(polygons, areas, indices, { startPosition, endPosition, coordLength }) { if (!polygons.triangles) { return; } const start = startPosition * coordLength; const end = endPosition * coordLength; const polygonPositions = polygons.positions.subarray(start, end); const offset = indices[0]; const holes = indices.slice(1).map((n2) => (n2 - offset) / coordLength); const triangles = earcut(polygonPositions, holes, coordLength, areas); for (let t2 = 0, tl = triangles.length; t2 < tl; ++t2) { polygons.triangles.push(startPosition + triangles[t2]); } } function wrapProps(obj, size) { const returnObj = {}; for (const key in obj) { returnObj[key] = { value: obj[key], size }; } return returnObj; } function makeAccessorObjects(points, lines, polygons, coordLength) { const binaryFeatures = { shape: "binary-feature-collection", points: { ...points, positions: { value: points.positions, size: coordLength }, globalFeatureIds: { value: points.globalFeatureIds, size: 1 }, featureIds: { value: points.featureIds, size: 1 }, numericProps: wrapProps(points.numericProps, 1) }, lines: { ...lines, positions: { value: lines.positions, size: coordLength }, pathIndices: { value: lines.pathIndices, size: 1 }, globalFeatureIds: { value: lines.globalFeatureIds, size: 1 }, featureIds: { value: lines.featureIds, size: 1 }, numericProps: wrapProps(lines.numericProps, 1) }, polygons: { ...polygons, positions: { value: polygons.positions, size: coordLength }, polygonIndices: { value: polygons.polygonIndices, size: 1 }, primitivePolygonIndices: { value: polygons.primitivePolygonIndices, size: 1 }, globalFeatureIds: { value: polygons.globalFeatureIds, size: 1 }, featureIds: { value: polygons.featureIds, size: 1 }, numericProps: wrapProps(polygons.numericProps, 1) } }; if (binaryFeatures.polygons && polygons.triangles) { binaryFeatures.polygons.triangles = { value: new Uint32Array(polygons.triangles), size: 1 }; } return binaryFeatures; } function fillNumericProperties(object, properties, index, length5) { for (const numericPropName in object.numericProps) { if (numericPropName in properties) { const value = properties[numericPropName]; object.numericProps[numericPropName].fill(value, index, index + length5); } } } function keepStringProperties(properties, numericKeys) { const props = {}; for (const key in properties) { if (!numericKeys.includes(key)) { props[key] = properties[key]; } } return props; } function deduceArrayType(x2, constructor) { if (constructor === Array || !Number.isFinite(x2)) { return Array; } return constructor === Float64Array || Math.fround(x2) !== x2 ? Float64Array : Float32Array; } // ../../node_modules/@loaders.gl/gis/dist/lib/binary-features/binary-to-geojson.js function binaryToGeojson(data, options) { const globalFeatureId = options?.globalFeatureId; if (globalFeatureId !== void 0) { return getSingleFeature(data, globalFeatureId); } return parseFeatures(data, options?.type); } function getSingleFeature(data, globalFeatureId) { const dataArray = normalizeInput(data); for (const data2 of dataArray) { let lastIndex = 0; let lastValue = data2.featureIds.value[0]; for (let i3 = 0; i3 < data2.featureIds.value.length; i3++) { const currValue = data2.featureIds.value[i3]; if (currValue === lastValue) { continue; } if (globalFeatureId === data2.globalFeatureIds.value[lastIndex]) { return parseFeature(data2, lastIndex, i3); } lastIndex = i3; lastValue = currValue; } if (globalFeatureId === data2.globalFeatureIds.value[lastIndex]) { return parseFeature(data2, lastIndex, data2.featureIds.value.length); } } throw new Error(`featureId:${globalFeatureId} not found`); } function parseFeatures(data, type) { const dataArray = normalizeInput(data, type); return parseFeatureCollection(dataArray); } function binaryToGeometry(data, startIndex, endIndex) { switch (data.type) { case "Point": return pointToGeoJson(data, startIndex, endIndex); case "LineString": return lineStringToGeoJson(data, startIndex, endIndex); case "Polygon": return polygonToGeoJson(data, startIndex, endIndex); default: const unexpectedInput = data; throw new Error(`Unsupported geometry type: ${unexpectedInput?.type}`); } } function normalizeInput(data, type) { const features = []; if (data.points) { data.points.type = "Point"; features.push(data.points); } if (data.lines) { data.lines.type = "LineString"; features.push(data.lines); } if (data.polygons) { data.polygons.type = "Polygon"; features.push(data.polygons); } return features; } function parseFeatureCollection(dataArray) { const features = []; for (const data of dataArray) { if (data.featureIds.value.length === 0) { continue; } let lastIndex = 0; let lastValue = data.featureIds.value[0]; for (let i3 = 0; i3 < data.featureIds.value.length; i3++) { const currValue = data.featureIds.value[i3]; if (currValue === lastValue) { continue; } features.push(parseFeature(data, lastIndex, i3)); lastIndex = i3; lastValue = currValue; } features.push(parseFeature(data, lastIndex, data.featureIds.value.length)); } return features; } function parseFeature(data, startIndex, endIndex) { const geometry = binaryToGeometry(data, startIndex, endIndex); const properties = parseProperties(data, startIndex, endIndex); const fields = parseFields(data, startIndex, endIndex); return { type: "Feature", geometry, properties, ...fields }; } function parseFields(data, startIndex = 0, endIndex) { return data.fields && data.fields[data.featureIds.value[startIndex]]; } function parseProperties(data, startIndex = 0, endIndex) { const properties = Object.assign({}, data.properties[data.featureIds.value[startIndex]]); for (const key in data.numericProps) { properties[key] = data.numericProps[key].value[startIndex]; } return properties; } function polygonToGeoJson(data, startIndex = -Infinity, endIndex = Infinity) { const { positions } = data; const polygonIndices = data.polygonIndices.value.filter((x2) => x2 >= startIndex && x2 <= endIndex); const primitivePolygonIndices = data.primitivePolygonIndices.value.filter((x2) => x2 >= startIndex && x2 <= endIndex); const multi = polygonIndices.length > 2; if (!multi) { const coordinates2 = []; for (let i3 = 0; i3 < primitivePolygonIndices.length - 1; i3++) { const startRingIndex = primitivePolygonIndices[i3]; const endRingIndex = primitivePolygonIndices[i3 + 1]; const ringCoordinates = ringToGeoJson(positions, startRingIndex, endRingIndex); coordinates2.push(ringCoordinates); } return { type: "Polygon", coordinates: coordinates2 }; } const coordinates = []; for (let i3 = 0; i3 < polygonIndices.length - 1; i3++) { const startPolygonIndex = polygonIndices[i3]; const endPolygonIndex = polygonIndices[i3 + 1]; const polygonCoordinates = polygonToGeoJson(data, startPolygonIndex, endPolygonIndex).coordinates; coordinates.push(polygonCoordinates); } return { type: "MultiPolygon", coordinates }; } function lineStringToGeoJson(data, startIndex = -Infinity, endIndex = Infinity) { const { positions } = data; const pathIndices = data.pathIndices.value.filter((x2) => x2 >= startIndex && x2 <= endIndex); const multi = pathIndices.length > 2; if (!multi) { const coordinates2 = ringToGeoJson(positions, pathIndices[0], pathIndices[1]); return { type: "LineString", coordinates: coordinates2 }; } const coordinates = []; for (let i3 = 0; i3 < pathIndices.length - 1; i3++) { const ringCoordinates = ringToGeoJson(positions, pathIndices[i3], pathIndices[i3 + 1]); coordinates.push(ringCoordinates); } return { type: "MultiLineString", coordinates }; } function pointToGeoJson(data, startIndex, endIndex) { const { positions } = data; const coordinates = ringToGeoJson(positions, startIndex, endIndex); const multi = coordinates.length > 1; if (multi) { return { type: "MultiPoint", coordinates }; } return { type: "Point", coordinates: coordinates[0] }; } function ringToGeoJson(positions, startIndex, endIndex) { startIndex = startIndex || 0; endIndex = endIndex || positions.value.length / positions.size; const ringCoordinates = []; for (let j = startIndex; j < endIndex; j++) { const coord = Array(); for (let k = j * positions.size; k < (j + 1) * positions.size; k++) { coord.push(Number(positions.value[k])); } ringCoordinates.push(coord); } return ringCoordinates; } // ../../node_modules/@loaders.gl/mvt/dist/lib/parse-mvt.js var import_pbf = __toESM(require_pbf(), 1); // ../../node_modules/@loaders.gl/mvt/dist/helpers/mapbox-util-functions.js function classifyRings(rings) { const len2 = rings.length; if (len2 <= 1) return [rings]; const polygons = []; let polygon; let ccw; for (let i3 = 0; i3 < len2; i3++) { const area2 = signedArea(rings[i3]); if (area2 === 0) continue; if (ccw === void 0) ccw = area2 < 0; if (ccw === area2 < 0) { if (polygon) polygons.push(polygon); polygon = [rings[i3]]; } else if (polygon) polygon.push(rings[i3]); } if (polygon) polygons.push(polygon); return polygons; } function signedArea(ring) { let sum = 0; for (let i3 = 0, j = ring.length - 1, p1, p2; i3 < ring.length; j = i3++) { p1 = ring[i3]; p2 = ring[j]; sum += (p2[0] - p1[0]) * (p1[1] + p2[1]); } return sum; } function readFeature(tag, feature, pbf) { if (feature && pbf) { if (tag === 1) feature.id = pbf.readVarint(); else if (tag === 2) readTag(pbf, feature); else if (tag === 3) feature.type = pbf.readVarint(); else if (tag === 4) feature._geometry = pbf.pos; } } function readTag(pbf, feature) { const end = pbf.readVarint() + pbf.pos; while (pbf.pos < end) { const key = feature._keys[pbf.readVarint()]; const value = feature._values[pbf.readVarint()]; feature.properties[key] = value; } } // ../../node_modules/@loaders.gl/mvt/dist/lib/mapbox-vector-tile/vector-tile-feature.js var VectorTileFeature = class { properties; extent; type; id; _pbf; _geometry; _keys; _values; static get types() { return ["Unknown", "Point", "LineString", "Polygon"]; } constructor(pbf, end, extent, keys, values) { this.properties = {}; this.extent = extent; this.type = 0; this.id = null; this._pbf = pbf; this._geometry = -1; this._keys = keys; this._values = values; pbf.readFields(readFeature, this, end); } loadGeometry() { const pbf = this._pbf; pbf.pos = this._geometry; const end = pbf.readVarint() + pbf.pos; let cmd2 = 1; let length5 = 0; let x2 = 0; let y2 = 0; const lines = []; let line; while (pbf.pos < end) { if (length5 <= 0) { const cmdLen2 = pbf.readVarint(); cmd2 = cmdLen2 & 7; length5 = cmdLen2 >> 3; } length5--; if (cmd2 === 1 || cmd2 === 2) { x2 += pbf.readSVarint(); y2 += pbf.readSVarint(); if (cmd2 === 1) { if (line) lines.push(line); line = []; } if (line) line.push([x2, y2]); } else if (cmd2 === 7) { if (line) { line.push(line[0].slice()); } } else { throw new Error(`unknown command ${cmd2}`); } } if (line) lines.push(line); return lines; } bbox() { const pbf = this._pbf; pbf.pos = this._geometry; const end = pbf.readVarint() + pbf.pos; let cmd2 = 1; let length5 = 0; let x2 = 0; let y2 = 0; let x1 = Infinity; let x22 = -Infinity; let y1 = Infinity; let y22 = -Infinity; while (pbf.pos < end) { if (length5 <= 0) { const cmdLen2 = pbf.readVarint(); cmd2 = cmdLen2 & 7; length5 = cmdLen2 >> 3; } length5--; if (cmd2 === 1 || cmd2 === 2) { x2 += pbf.readSVarint(); y2 += pbf.readSVarint(); if (x2 < x1) x1 = x2; if (x2 > x22) x22 = x2; if (y2 < y1) y1 = y2; if (y2 > y22) y22 = y2; } else if (cmd2 !== 7) { throw new Error(`unknown command ${cmd2}`); } } return [x1, y1, x22, y22]; } _toGeoJSON(transform2) { let coords = this.loadGeometry(); let type = VectorTileFeature.types[this.type]; let i3; let j; switch (this.type) { case 1: const points = []; for (i3 = 0; i3 < coords.length; i3++) { points[i3] = coords[i3][0]; } coords = points; transform2(coords, this); break; case 2: for (i3 = 0; i3 < coords.length; i3++) { transform2(coords[i3], this); } break; case 3: coords = classifyRings(coords); for (i3 = 0; i3 < coords.length; i3++) { for (j = 0; j < coords[i3].length; j++) { transform2(coords[i3][j], this); } } break; } if (coords.length === 1) { coords = coords[0]; } else { type = `Multi${type}`; } const result = { type: "Feature", geometry: { type, coordinates: coords }, properties: this.properties }; if (this.id !== null) { result.id = this.id; } return result; } toGeoJSON(options) { if (typeof options === "function") { return this._toGeoJSON(options); } const { x: x2, y: y2, z } = options; const size = this.extent * Math.pow(2, z); const x0 = this.extent * x2; const y0 = this.extent * y2; function project2(line) { for (let j = 0; j < line.length; j++) { const p2 = line[j]; p2[0] = (p2[0] + x0) * 360 / size - 180; const y22 = 180 - (p2[1] + y0) * 360 / size; p2[1] = 360 / Math.PI * Math.atan(Math.exp(y22 * Math.PI / 180)) - 90; } } return this._toGeoJSON(project2); } }; // ../../node_modules/@loaders.gl/mvt/dist/lib/mapbox-vector-tile/vector-tile-layer.js var VectorTileLayer = class { version; name; extent; length; _pbf; _keys; _values; _features; constructor(pbf, end) { this.version = 1; this.name = ""; this.extent = 4096; this.length = 0; this._pbf = pbf; this._keys = []; this._values = []; this._features = []; pbf.readFields(readLayer, this, end); this.length = this._features.length; } feature(i3) { if (i3 < 0 || i3 >= this._features.length) { throw new Error("feature index out of bounds"); } this._pbf.pos = this._features[i3]; const end = this._pbf.readVarint() + this._pbf.pos; return new VectorTileFeature(this._pbf, end, this.extent, this._keys, this._values); } }; function readLayer(tag, layer, pbf) { if (layer && pbf) { if (tag === 15) layer.version = pbf.readVarint(); else if (tag === 1) layer.name = pbf.readString(); else if (tag === 5) layer.extent = pbf.readVarint(); else if (tag === 2) layer._features.push(pbf.pos); else if (tag === 3) layer._keys.push(pbf.readString()); else if (tag === 4) layer._values.push(readValueMessage(pbf)); } } function readValueMessage(pbf) { 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; } return value; } // ../../node_modules/@loaders.gl/mvt/dist/lib/mapbox-vector-tile/vector-tile.js var VectorTile = class { layers; constructor(pbf, end) { this.layers = pbf.readFields(readTile, {}, end); } }; function readTile(tag, layers, pbf) { if (tag === 3) { if (pbf) { const layer = new VectorTileLayer(pbf, pbf.readVarint() + pbf.pos); if (layer.length && layers) { layers[layer.name] = layer; } } } } // ../../node_modules/@loaders.gl/mvt/dist/helpers/binary-util-functions.js function classifyRings2(geom) { const len2 = geom.indices.length; const type = "Polygon"; if (len2 <= 1) { return { type, data: geom.data, areas: [[getPolygonSignedArea(geom.data)]], indices: [geom.indices] }; } const areas = []; const polygons = []; let ringAreas = []; let polygon = []; let ccw; let offset = 0; for (let endIndex, i3 = 0, startIndex; i3 < len2; i3++) { startIndex = geom.indices[i3] - offset; endIndex = geom.indices[i3 + 1] - offset || geom.data.length; const shape = geom.data.slice(startIndex, endIndex); const area2 = getPolygonSignedArea(shape); if (area2 === 0) { const before = geom.data.slice(0, startIndex); const after = geom.data.slice(endIndex); geom.data = before.concat(after); offset += endIndex - startIndex; continue; } if (ccw === void 0) ccw = area2 < 0; if (ccw === area2 < 0) { if (polygon.length) { areas.push(ringAreas); polygons.push(polygon); } polygon = [startIndex]; ringAreas = [area2]; } else { ringAreas.push(area2); polygon.push(startIndex); } } if (ringAreas) areas.push(ringAreas); if (polygon.length) polygons.push(polygon); return { type, areas, indices: polygons, data: geom.data }; } function project(data, x0, y0, size) { for (let j = 0, jl = data.length; j < jl; j += 2) { data[j] = (data[j] + x0) * 360 / size - 180; const y2 = 180 - (data[j + 1] + y0) * 360 / size; data[j + 1] = 360 / Math.PI * Math.atan(Math.exp(y2 * Math.PI / 180)) - 90; } } function readFeature2(tag, feature, pbf) { if (feature && pbf) { if (tag === 1) feature.id = pbf.readVarint(); else if (tag === 2) readTag2(pbf, feature); else if (tag === 3) feature.type = pbf.readVarint(); else if (tag === 4) feature._geometry = pbf.pos; } } function readTag2(pbf, feature) { const end = pbf.readVarint() + pbf.pos; while (pbf.pos < end) { const key = feature._keys[pbf.readVarint()]; const value = feature._values[pbf.readVarint()]; feature.properties[key] = value; } } // ../../node_modules/@loaders.gl/mvt/dist/lib/binary-vector-tile/vector-tile-feature.js var endPos; var cmd; var cmdLen; var length4; var x; var y; var i2; var BinaryVectorTileFeature = class { properties; extent; type; id; _pbf; _geometry; _keys; _values; _geometryInfo; constructor(pbf, end, extent, keys, values, geometryInfo) { this.properties = {}; this.extent = extent; this.type = 0; this.id = null; this._pbf = pbf; this._geometry = -1; this._keys = keys; this._values = values; this._geometryInfo = geometryInfo; pbf.readFields(readFeature2, this, end); } loadGeometry() { const pbf = this._pbf; pbf.pos = this._geometry; endPos = pbf.readVarint() + pbf.pos; cmd = 1; length4 = 0; x = 0; y = 0; i2 = 0; const indices = []; const data = []; while (pbf.pos < endPos) { if (length4 <= 0) { cmdLen = pbf.readVarint(); cmd = cmdLen & 7; length4 = cmdLen >> 3; } length4--; if (cmd === 1 || cmd === 2) { x += pbf.readSVarint(); y += pbf.readSVarint(); if (cmd === 1) { indices.push(i2); } data.push(x, y); i2 += 2; } else if (cmd === 7) { if (i2 > 0) { const start = indices[indices.length - 1]; data.push(data[start], data[start + 1]); i2 += 2; } } else { throw new Error(`unknown command ${cmd}`); } } return { data, indices }; } _toBinaryCoordinates(transform2) { const geom = this.loadGeometry(); let geometry; transform2(geom.data, this); const coordLength = 2; switch (this.type) { case 1: this._geometryInfo.pointFeaturesCount++; this._geometryInfo.pointPositionsCount += geom.indices.length; geometry = { type: "Point", ...geom }; break; case 2: this._geometryInfo.lineFeaturesCount++; this._geometryInfo.linePathsCount += geom.indices.length; this._geometryInfo.linePositionsCount += geom.data.length / coordLength; geometry = { type: "LineString", ...geom }; break; case 3: geometry = classifyRings2(geom); this._geometryInfo.polygonFeaturesCount++; this._geometryInfo.polygonObjectsCount += geometry.indices.length; for (const indices of geometry.indices) { this._geometryInfo.polygonRingsCount += indices.length; } this._geometryInfo.polygonPositionsCount += geometry.data.length / coordLength; break; default: throw new Error(`Invalid geometry type: ${this.type}`); } const result = { type: "Feature", geometry, properties: this.properties }; if (this.id !== null) { result.id = this.id; } return result; } toBinaryCoordinates(options) { if (typeof options === "function") { return this._toBinaryCoordinates(options); } const { x: x2, y: y2, z } = options; const size = this.extent * Math.pow(2, z); const x0 = this.extent * x2; const y0 = this.extent * y2; return this._toBinaryCoordinates((data) => project(data, x0, y0, size)); } }; // ../../node_modules/@loaders.gl/mvt/dist/lib/binary-vector-tile/vector-tile-layer.js var BinaryVectorTileLayer = class { version; name; extent; length; _pbf; _keys; _values; _features; constructor(pbf, end) { this.version = 1; this.name = ""; this.extent = 4096; this.length = 0; this._pbf = pbf; this._keys = []; this._values = []; this._features = []; pbf.readFields(readLayer2, this, end); this.length = this._features.length; } feature(i3, geometryInfo) { if (i3 < 0 || i3 >= this._features.length) { throw new Error("feature index out of bounds"); } this._pbf.pos = this._features[i3]; const end = this._pbf.readVarint() + this._pbf.pos; return new BinaryVectorTileFeature(this._pbf, end, this.extent, this._keys, this._values, geometryInfo); } }; function readLayer2(tag, layer, pbf) { if (layer && pbf) { if (tag === 15) layer.version = pbf.readVarint(); else if (tag === 1) layer.name = pbf.readString(); else if (tag === 5) layer.extent = pbf.readVarint(); else if (tag === 2) layer._features.push(pbf.pos); else if (tag === 3) layer._keys.push(pbf.readString()); else if (tag === 4) layer._values.push(readValueMessage2(pbf)); } } function readValueMessage2(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; } return value; } // ../../node_modules/@loaders.gl/mvt/dist/lib/binary-vector-tile/vector-tile.js var BinaryVectorTile = class { layers; constructor(pbf, end) { this.layers = pbf.readFields(readTile2, {}, end); } }; function readTile2(tag, layers, pbf) { if (tag === 3) { if (pbf) { const layer = new BinaryVectorTileLayer(pbf, pbf.readVarint() + pbf.pos); if (layer.length && layers) { layers[layer.name] = layer; } } } } // ../../node_modules/@loaders.gl/mvt/dist/lib/parse-mvt.js function parseMVT(arrayBuffer, options) { const mvtOptions = normalizeOptions(options); const shape = options?.gis?.format || options?.mvt?.shape || options?.shape; switch (shape) { case "columnar-table": return { shape: "columnar-table", data: parseToBinary(arrayBuffer, mvtOptions) }; case "geojson-table": { const table = { shape: "geojson-table", type: "FeatureCollection", features: parseToGeojsonFeatures(arrayBuffer, mvtOptions) }; return table; } case "geojson": return parseToGeojsonFeatures(arrayBuffer, mvtOptions); case "binary-geometry": return parseToBinary(arrayBuffer, mvtOptions); case "binary": return parseToBinary(arrayBuffer, mvtOptions); default: throw new Error(shape || "undefined shape"); } } function parseToBinary(arrayBuffer, options) { const [flatGeoJsonFeatures, geometryInfo] = parseToFlatGeoJson(arrayBuffer, options); const binaryData = flatGeojsonToBinary(flatGeoJsonFeatures, geometryInfo); binaryData.byteLength = arrayBuffer.byteLength; return binaryData; } function parseToFlatGeoJson(arrayBuffer, options) { const features = []; const geometryInfo = { coordLength: 2, pointPositionsCount: 0, pointFeaturesCount: 0, linePositionsCount: 0, linePathsCount: 0, lineFeaturesCount: 0, polygonPositionsCount: 0, polygonObjectsCount: 0, polygonRingsCount: 0, polygonFeaturesCount: 0 }; if (arrayBuffer.byteLength <= 0) { return [features, geometryInfo]; } const tile = new BinaryVectorTile(new import_pbf.default(arrayBuffer)); const selectedLayers = options && Array.isArray(options.layers) ? options.layers : Object.keys(tile.layers); selectedLayers.forEach((layerName) => { const vectorTileLayer = tile.layers[layerName]; if (!vectorTileLayer) { return; } for (let i3 = 0; i3 < vectorTileLayer.length; i3++) { const vectorTileFeature = vectorTileLayer.feature(i3, geometryInfo); const decodedFeature = getDecodedFeatureBinary(vectorTileFeature, options, layerName); features.push(decodedFeature); } }); return [features, geometryInfo]; } function parseToGeojsonFeatures(arrayBuffer, options) { if (arrayBuffer.byteLength <= 0) { return []; } const features = []; const tile = new VectorTile(new import_pbf.default(arrayBuffer)); const selectedLayers = Array.isArray(options.layers) ? options.layers : Object.keys(tile.layers); selectedLayers.forEach((layerName) => { const vectorTileLayer = tile.layers[layerName]; if (!vectorTileLayer) { return; } for (let i3 = 0; i3 < vectorTileLayer.length; i3++) { const vectorTileFeature = vectorTileLayer.feature(i3); const decodedFeature = getDecodedFeature(vectorTileFeature, options, layerName); features.push(decodedFeature); } }); return features; } function normalizeOptions(options) { if (!options?.mvt) { throw new Error("mvt options required"); } const wgs84Coordinates = options.mvt?.coordinates === "wgs84"; const { tileIndex } = options.mvt; const hasTileIndex = tileIndex && Number.isFinite(tileIndex.x) && Number.isFinite(tileIndex.y) && Number.isFinite(tileIndex.z); if (wgs84Coordinates && !hasTileIndex) { throw new Error("MVT Loader: WGS84 coordinates need tileIndex property"); } return options.mvt; } function getDecodedFeature(feature, options, layerName) { const decodedFeature = feature.toGeoJSON( options.coordinates === "wgs84" ? options.tileIndex : transformToLocalCoordinates ); if (options.layerProperty) { decodedFeature.properties[options.layerProperty] = layerName; } return decodedFeature; } function getDecodedFeatureBinary(feature, options, layerName) { const decodedFeature = feature.toBinaryCoordinates( options.coordinates === "wgs84" ? options.tileIndex : transformToLocalCoordinatesBinary ); if (options.layerProperty && decodedFeature.properties) { decodedFeature.properties[options.layerProperty] = layerName; } return decodedFeature; } function transformToLocalCoordinates(line, feature) { const { extent } = feature; for (let i3 = 0; i3 < line.length; i3++) { const p2 = line[i3]; p2[0] /= extent; p2[1] /= extent; } } function transformToLocalCoordinatesBinary(data, feature) { const { extent } = feature; for (let i3 = 0, il = data.length; i3 < il; ++i3) { data[i3] /= extent; } } // ../../node_modules/@loaders.gl/mvt/dist/mvt-loader.js var VERSION12 = true ? "4.2.0-beta.2" : "latest"; var MVTWorkerLoader = { dataType: null, batchType: null, name: "Mapbox Vector Tile", id: "mvt", module: "mvt", version: VERSION12, extensions: ["mvt", "pbf"], mimeTypes: [ "application/vnd.mapbox-vector-tile", "application/x-protobuf" ], worker: true, category: "geometry", options: { mvt: { shape: "geojson", coordinates: "local", layerProperty: "layerName", layers: void 0, tileIndex: null } } }; var MVTLoader = { ...MVTWorkerLoader, parse: async (arrayBuffer, options) => parseMVT(arrayBuffer, options), parseSync: parseMVT, binary: true }; // src/mvt-layer/coordinate-transform.ts var availableTransformations = { Point, MultiPoint, LineString, MultiLineString, Polygon: Polygon2, MultiPolygon }; function Point([pointX, pointY], [nw, se], viewport) { const x2 = lerp(nw[0], se[0], pointX); const y2 = lerp(nw[1], se[1], pointY); return viewport.unprojectFlat([x2, y2]); } function getPoints(geometry, bbox, viewport) { return geometry.map((g) => Point(g, bbox, viewport)); } function MultiPoint(multiPoint, bbox, viewport) { return getPoints(multiPoint, bbox, viewport); } function LineString(line, bbox, viewport) { return getPoints(line, bbox, viewport); } function MultiLineString(multiLineString, bbox, viewport) { return multiLineString.map((lineString) => LineString(lineString, bbox, viewport)); } function Polygon2(polygon, bbox, viewport) { return polygon.map((polygonRing) => getPoints(polygonRing, bbox, viewport)); } function MultiPolygon(multiPolygon, bbox, viewport) { return multiPolygon.map((polygon) => Polygon2(polygon, bbox, viewport)); } function transform(geometry, bbox, viewport) { const nw = viewport.projectFlat([bbox.west, bbox.north]); const se = viewport.projectFlat([bbox.east, bbox.south]); const projectedBbox = [nw, se]; return { ...geometry, coordinates: availableTransformations[geometry.type]( geometry.coordinates, projectedBbox, viewport ) }; } // src/mvt-layer/find-index-binary.ts var GEOM_TYPES = ["points", "lines", "polygons"]; function findIndexBinary(data, uniqueIdProperty, featureId, layerName) { for (const gt of GEOM_TYPES) { const index = data[gt] && findIndexByType(data[gt], uniqueIdProperty, featureId, layerName); if (index >= 0) { return index; } } return -1; } function findIndexByType(geomData, uniqueIdProperty, featureId, layerName) { const featureIds = geomData.featureIds.value; if (!featureIds.length) { return -1; } let startFeatureIndex = 0; let endFeatureIndex = featureIds[featureIds.length - 1] + 1; if (layerName) { const layerRange = getLayerRange(geomData, layerName); if (layerRange) { startFeatureIndex = layerRange[0]; endFeatureIndex = layerRange[1] + 1; } else { return -1; } } let featureIndex = -1; if (uniqueIdProperty in geomData.numericProps) { const vertexIndex = geomData.numericProps[uniqueIdProperty].value.findIndex( (x2, i3) => x2 === featureId && featureIds[i3] >= startFeatureIndex && featureIds[i3] < endFeatureIndex ); return vertexIndex >= 0 ? geomData.globalFeatureIds.value[vertexIndex] : -1; } else if (uniqueIdProperty) { featureIndex = findIndex( geomData.properties, (elem) => elem[uniqueIdProperty] === featureId, startFeatureIndex, endFeatureIndex ); } else if (geomData.fields) { featureIndex = findIndex( geomData.fields, (elem) => elem.id === featureId, startFeatureIndex, endFeatureIndex ); } return featureIndex >= 0 ? getGlobalFeatureId(geomData, featureIndex) : -1; } function getLayerRange(geomData, layerName) { if (!geomData.__layers) { const layerNames = {}; const { properties } = geomData; for (let i3 = 0; i3 < properties.length; i3++) { const { layerName: key } = properties[i3]; if (!key) { } else if (layerNames[key]) { layerNames[key][1] = i3; } else { layerNames[key] = [i3, i3]; } } geomData.__layers = layerNames; } return geomData.__layers[layerName]; } function getGlobalFeatureId(geomData, featureIndex) { if (!geomData.__ids) { const result = []; const featureIds = geomData.featureIds.value; const globalFeatureIds = geomData.globalFeatureIds.value; for (let i3 = 0; i3 < featureIds.length; i3++) { result[featureIds[i3]] = globalFeatureIds[i3]; } geomData.__ids = result; } return geomData.__ids[featureIndex]; } function findIndex(array, predicate, startIndex, endIndex) { for (let i3 = startIndex; i3 < endIndex; i3++) { if (predicate(array[i3], i3)) { return i3; } } return -1; } // src/mvt-layer/mvt-layer.ts var WORLD_SIZE = 512; var defaultProps13 = { ...import_layers9.GeoJsonLayer.defaultProps, data: urlType, onDataLoad: { type: "function", value: null, optional: true, compare: false }, uniqueIdProperty: "", highlightedFeatureId: null, loaders: [MVTWorkerLoader], binary: true }; var MVTLayer = class extends TileLayer { initializeState() { super.initializeState(); const binary = this.context.viewport.resolution !== void 0 ? false : this.props.binary; this.setState({ binary, data: null, tileJSON: null, hoveredFeatureId: null, hoveredFeatureLayerName: null }); } get isLoaded() { return Boolean(this.state?.data && super.isLoaded); } updateState({ props, oldProps, context, changeFlags }) { if (changeFlags.dataChanged) { this._updateTileData(); } if (this.state?.data) { super.updateState({ props, oldProps, context, changeFlags }); this._setWGS84PropertyForTiles(); } const { highlightColor } = props; if (highlightColor !== oldProps.highlightColor && Array.isArray(highlightColor)) { this.setState({ highlightColor }); } } async _updateTileData() { let data = this.props.data; let tileJSON = null; if (typeof data === "string" && !isURLTemplate(data)) { const { onDataLoad, fetch: fetch2 } = this.props; this.setState({ data: null, tileJSON: null }); try { tileJSON = await fetch2(data, { propName: "data", layer: this, loaders: [] }); } catch (error) { this.raiseError(error, "loading TileJSON"); data = null; } if (onDataLoad) { onDataLoad(tileJSON, { propName: "data", layer: this }); } } else if (data && typeof data === "object" && "tilejson" in data) { tileJSON = data; } if (tileJSON) { data = tileJSON.tiles; } this.setState({ data, tileJSON }); } _getTilesetOptions() { const opts = super._getTilesetOptions(); const tileJSON = this.state.tileJSON; const { minZoom, maxZoom } = this.props; if (tileJSON) { if (Number.isFinite(tileJSON.minzoom) && tileJSON.minzoom > minZoom) { opts.minZoom = tileJSON.minzoom; } if (Number.isFinite(tileJSON.maxzoom) && (!Number.isFinite(maxZoom) || tileJSON.maxzoom < maxZoom)) { opts.maxZoom = tileJSON.maxzoom; } } return opts; } renderLayers() { if (!this.state?.data) return null; return super.renderLayers(); } getTileData(loadProps) { const { data, binary } = this.state; const { index, signal } = loadProps; const url = getURLFromTemplate(data, loadProps); if (!url) { return Promise.reject("Invalid URL"); } let loadOptions = this.getLoadOptions(); const { fetch: fetch2 } = this.props; loadOptions = { ...loadOptions, mimeType: "application/x-protobuf", mvt: { ...loadOptions?.mvt, coordinates: this.context.viewport.resolution ? "wgs84" : "local", tileIndex: index }, gis: binary ? { format: "binary" } : {} }; return fetch2(url, { propName: "data", layer: this, loadOptions, signal }); } renderSubLayers(props) { const { x: x2, y: y2, z } = props.tile.index; const worldScale = Math.pow(2, z); const xScale = WORLD_SIZE / worldScale; const yScale = -xScale; const xOffset = WORLD_SIZE * x2 / worldScale; const yOffset = WORLD_SIZE * (1 - y2 / worldScale); const modelMatrix = new Matrix4().scale([xScale, yScale, 1]); props.autoHighlight = false; if (!this.context.viewport.resolution) { props.modelMatrix = modelMatrix; props.coordinateOrigin = [xOffset, yOffset, 0]; props.coordinateSystem = import_core48.COORDINATE_SYSTEM.CARTESIAN; props.extensions = [...props.extensions || [], new import_extensions.ClipExtension()]; } const subLayers = super.renderSubLayers(props); if (this.state.binary && !(subLayers instanceof import_layers9.GeoJsonLayer)) { import_core48.log.warn("renderSubLayers() must return GeoJsonLayer when using binary:true")(); } return subLayers; } _updateAutoHighlight(info) { const { uniqueIdProperty } = this.props; const { hoveredFeatureId, hoveredFeatureLayerName } = this.state; const hoveredFeature = info.object; let newHoveredFeatureId = null; let newHoveredFeatureLayerName = null; if (hoveredFeature) { newHoveredFeatureId = getFeatureUniqueId(hoveredFeature, uniqueIdProperty); newHoveredFeatureLayerName = getFeatureLayerName(hoveredFeature); } let { highlightColor } = this.props; if (typeof highlightColor === "function") { highlightColor = highlightColor(info); } if (hoveredFeatureId !== newHoveredFeatureId || hoveredFeatureLayerName !== newHoveredFeatureLayerName) { this.setState({ highlightColor, hoveredFeatureId: newHoveredFeatureId, hoveredFeatureLayerName: newHoveredFeatureLayerName }); } } _isWGS84() { return Boolean(this.context.viewport.resolution); } getPickingInfo(params) { const info = super.getPickingInfo(params); if (this.state.binary && info.index !== -1) { const { data } = params.sourceLayer.props; info.object = binaryToGeojson(data, { globalFeatureId: info.index }); } if (info.object && !this._isWGS84()) { info.object = transformTileCoordsToWGS84( info.object, info.tile.bbox, this.context.viewport ); } return info; } getSubLayerPropsByTile(tile) { return { highlightedObjectIndex: this.getHighlightedObjectIndex(tile), highlightColor: this.state.highlightColor }; } getHighlightedObjectIndex(tile) { const { hoveredFeatureId, hoveredFeatureLayerName, binary } = this.state; const { uniqueIdProperty, highlightedFeatureId } = this.props; const data = tile.content; const isHighlighted = isFeatureIdDefined(highlightedFeatureId); const isFeatureIdPresent = isFeatureIdDefined(hoveredFeatureId) || isHighlighted; if (!isFeatureIdPresent) { return -1; } const featureIdToHighlight = isHighlighted ? highlightedFeatureId : hoveredFeatureId; if (Array.isArray(data)) { return data.findIndex((feature) => { const isMatchingId = getFeatureUniqueId(feature, uniqueIdProperty) === featureIdToHighlight; const isMatchingLayer = isHighlighted || getFeatureLayerName(feature) === hoveredFeatureLayerName; return isMatchingId && isMatchingLayer; }); } else if (data && binary) { return findIndexBinary( data, uniqueIdProperty, featureIdToHighlight, isHighlighted ? "" : hoveredFeatureLayerName ); } return -1; } _pickObjects(maxObjects) { const { deck, viewport } = this.context; const width = viewport.width; const height = viewport.height; const x2 = viewport.x; const y2 = viewport.y; const layerIds = [this.id]; return deck.pickObjects({ x: x2, y: y2, width, height, layerIds, maxObjects }); } getRenderedFeatures(maxFeatures = null) { const features = this._pickObjects(maxFeatures); const featureCache = /* @__PURE__ */ new Set(); const renderedFeatures = []; for (const f2 of features) { const featureId = getFeatureUniqueId(f2.object, this.props.uniqueIdProperty); if (featureId === void 0) { renderedFeatures.push(f2.object); } else if (!featureCache.has(featureId)) { featureCache.add(featureId); renderedFeatures.push(f2.object); } } return renderedFeatures; } _setWGS84PropertyForTiles() { const propName = "dataInWGS84"; const tileset = this.state.tileset; tileset.selectedTiles.forEach((tile) => { if (!tile.hasOwnProperty(propName)) { Object.defineProperty(tile, propName, { get: () => { if (!tile.content) { return null; } if (this.state.binary && Array.isArray(tile.content) && !tile.content.length) { return []; } const { bbox } = tile; if (tile._contentWGS84 === void 0 && isGeoBoundingBox(bbox)) { const content = this.state.binary ? binaryToGeojson(tile.content) : tile.content; tile._contentWGS84 = content.map( (feature) => transformTileCoordsToWGS84(feature, bbox, this.context.viewport) ); } return tile._contentWGS84; } }); } }); } }; MVTLayer.layerName = "MVTLayer"; MVTLayer.defaultProps = defaultProps13; function getFeatureUniqueId(feature, uniqueIdProperty) { if (feature.properties && uniqueIdProperty) { return feature.properties[uniqueIdProperty]; } if ("id" in feature) { return feature.id; } return void 0; } function getFeatureLayerName(feature) { return feature.properties?.layerName || null; } function isFeatureIdDefined(value) { return value !== void 0 && value !== null && value !== ""; } function transformTileCoordsToWGS84(object, bbox, viewport) { const feature = { ...object, geometry: { type: object.geometry.type } }; Object.defineProperty(feature.geometry, "coordinates", { get: () => { const wgs84Geom = transform(object.geometry, bbox, viewport); return wgs84Geom.coordinates; } }); return feature; } // src/geohash-layer/geohash-utils.ts var BASE32_CODES = "0123456789bcdefghjkmnpqrstuvwxyz"; var BASE32_CODES_DICT = {}; for (let i3 = 0; i3 < BASE32_CODES.length; i3++) { BASE32_CODES_DICT[BASE32_CODES.charAt(i3)] = i3; } var MIN_LAT = -90; var MAX_LAT = 90; var MIN_LON = -180; var MAX_LON = 180; function getGeohashBounds(geohash) { let isLon = true; let maxLat = MAX_LAT; let minLat = MIN_LAT; let maxLon = MAX_LON; let minLon = MIN_LON; let mid; let hashValue = 0; for (let i3 = 0, l2 = geohash.length; i3 < l2; i3++) { const code = geohash[i3].toLowerCase(); hashValue = BASE32_CODES_DICT[code]; for (let bits = 4; bits >= 0; bits--) { const bit = hashValue >> bits & 1; if (isLon) { mid = (maxLon + minLon) / 2; if (bit === 1) { minLon = mid; } else { maxLon = mid; } } else { mid = (maxLat + minLat) / 2; if (bit === 1) { minLat = mid; } else { maxLat = mid; } } isLon = !isLon; } } return [minLat, minLon, maxLat, maxLon]; } function getGeohashPolygon(geohash) { const [s2, w, n2, e] = getGeohashBounds(geohash); return [e, n2, e, s2, w, s2, w, n2, e, n2]; } // src/geohash-layer/geohash-layer.ts var defaultProps14 = { getGeohash: { type: "accessor", value: (d) => d.geohash } }; var GeohashLayer = class extends GeoCellLayer { indexToBounds() { const { data, getGeohash } = this.props; return { data, _normalize: false, positionFormat: "XY", getPolygon: (x2, objectInfo) => getGeohashPolygon(getGeohash(x2, objectInfo)) }; } }; GeohashLayer.layerName = "GeohashLayer"; GeohashLayer.defaultProps = defaultProps14; return __toCommonJS(bundle_exports); })(); return __exports__; });