@thatopen/components 3.4.7 → 3.4.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1 @@
1
- var t=Object.defineProperty,e=(e,i,n)=>(((e,i,n)=>{i in e?t(e,i,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[i]=n})(e,"symbol"!=typeof i?i+"":i,n),n);import*as i from"@thatopen/fragments";import{DataMap as n,FragmentsModels as s,DataSet as r}from"@thatopen/fragments";import*as o from"three";import{Box3 as a,Matrix4 as l,BufferAttribute as c,Vector3 as h,Line3 as u,Plane as d,Vector2 as p,Triangle as f,BackSide as m,DoubleSide as g,REVISION as w,Ray as y,FrontSide as _,Mesh as b,LineSegments as v,LineLoop as x,Line as C,Points as S,Sphere as A,BatchedMesh as P,OrthographicCamera as T,WebGLRenderTarget as E,Scene as M,Color as I,ShaderMaterial as z,Vector4 as D,NoBlending as k,GLSL3 as B,MathUtils as O,BufferGeometry as N}from"three";import*as V from"three/webgpu";import{instancedArray as L,Fn as F,instanceIndex as R,mat4 as U,Loop as j,int as $,vec3 as W,vec4 as G,float as H,cross as Z,If as q,Continue as Y,max as X,min as K,normalize as Q,select as J,abs as tt,mix as et,uint as it,atomicAdd as nt}from"three/tsl";import*as st from"web-ifc";import rt from"camera-controls";import{TransformControls as ot}from"three/examples/jsm/controls/TransformControls.js";class at{constructor(){e(this,"enabled",!0),e(this,"trigger",t=>{if(!this.enabled)return;const e=this.handlers.slice(0);for(const i of e)i(t)}),e(this,"handlers",[])}add(t){this.handlers.push(t)}remove(t){this.handlers=this.handlers.filter(e=>e!==t)}reset(){this.handlers.length=0}}class lt{constructor(){e(this,"enabled",!0),e(this,"trigger",async t=>{if(!this.enabled)return;const e=this.handlers.slice(0);for(const i of e)await i(t)}),e(this,"handlers",[])}add(t){this.handlers.push(t)}remove(t){this.handlers=this.handlers.filter(e=>e!==t)}reset(){this.handlers.length=0}}class ct{constructor(t){e(this,"isDisposeable",()=>"dispose"in this&&"onDisposed"in this),e(this,"isResizeable",()=>"resize"in this&&"getSize"in this),e(this,"isUpdateable",()=>"onAfterUpdate"in this&&"onBeforeUpdate"in this&&"update"in this),e(this,"isHideable",()=>"visible"in this),e(this,"isConfigurable",()=>"setup"in this&&"config"in this&&"onSetup"in this),e(this,"isSerializable",()=>"import"in this&&"export"in this),this.components=t}}class ht extends ct{}class ut extends ct{constructor(t){super(t),e(this,"worlds",new n),e(this,"onWorldChanged",new at),e(this,"_currentWorld",null),this.onWorldChanged.add(({world:t,action:e})=>{"removed"===e&&this.worlds.delete(t.uuid)})}set currentWorld(t){this._currentWorld=t}get currentWorld(){return this._currentWorld}}class dt extends ut{constructor(){super(...arguments),e(this,"hasCameraControls",()=>"controls"in this)}}class pt extends ut{constructor(){super(...arguments),e(this,"onAfterUpdate",new at),e(this,"onBeforeUpdate",new at),e(this,"onDisposed",new at),e(this,"onResize",new at),e(this,"onClippingPlanesUpdated",new at),e(this,"clippingPlanes",[]),e(this,"localClippingPlanes",!1)}updateClippingPlanes(){this.onClippingPlanesUpdated.trigger()}setPlane(t,e,i=this.localClippingPlanes){e.isLocal=i;const n=this.clippingPlanes.indexOf(e);t&&-1===n?this.clippingPlanes.push(e):!t&&n>-1&&this.clippingPlanes.splice(n,1),this.three.clippingPlanes=this.clippingPlanes.filter(t=>!t.isLocal),this.updateClippingPlanes()}}const ft=class t extends ht{constructor(i){super(i),e(this,"_disposedComponents",new Set),e(this,"enabled",!0),i.add(t.uuid,this)}get(){return this._disposedComponents}destroy(t,e=!0,i=!0){t.removeFromParent();const n=t;n.dispose&&n.dispose(),this.disposeGeometryAndMaterials(t,e),i&&n.children&&n.children.length&&this.disposeChildren(n),t.children.length=0}disposeGeometry(t){t.boundsTree&&t.disposeBoundsTree&&t.disposeBoundsTree(),t.dispose()}disposeGeometryAndMaterials(e,i){const n=e;n.geometry&&this.disposeGeometry(n.geometry),i&&n.material&&t.disposeMaterial(n),n.material=[],n.geometry=null}disposeChildren(t){for(const e of t.children)this.destroy(e)}static disposeMaterial(t){if(t.material)if(Array.isArray(t.material))for(const e of t.material)e.dispose();else t.material.dispose()}};e(ft,"uuid","76e9cd8e-ad8f-4753-9ef6-cbc60f7247fe");let mt=ft;class gt extends ut{constructor(t){super(t),e(this,"onDisposed",new at),e(this,"directionalLights",new Map),e(this,"ambientLights",new Map)}dispose(){const t=this.components.get(mt);for(const e of this.three.children){const i=e;i.geometry&&t.destroy(i)}this.deleteAllLights(),this.three.children=[],this.onDisposed.trigger(),this.onDisposed.reset()}deleteAllLights(){for(const[,t]of this.directionalLights)t.removeFromParent(),t.target.removeFromParent(),t.dispose();this.directionalLights.clear();for(const[,t]of this.ambientLights)t.removeFromParent(),t.dispose();this.ambientLights.clear()}}class wt extends Set{constructor(t){super(t),e(this,"onItemAdded",new at),e(this,"onItemDeleted",new at),e(this,"onCleared",new at),e(this,"guard",()=>!0)}clear(){super.clear(),this.onCleared.trigger()}add(...t){for(const e of t){if(this.has(e))continue;this.guard(e)&&(super.add(e),this.onItemAdded||(this.onItemAdded=new at),this.onItemAdded.trigger(e))}return this}delete(t){const e=super.delete(t);return e&&this.onItemDeleted.trigger(),e}dispose(){this.clear(),this.onItemAdded.reset(),this.onItemDeleted.reset(),this.onCleared.reset()}}const yt=class t{static create(){const e=4294967295*Math.random()|0,i=4294967295*Math.random()|0,n=4294967295*Math.random()|0,s=4294967295*Math.random()|0;return`${t._lut[255&e]+t._lut[e>>8&255]+t._lut[e>>16&255]+t._lut[e>>24&255]}-${t._lut[255&i]}${t._lut[i>>8&255]}-${t._lut[i>>16&15|64]}${t._lut[i>>24&255]}-${t._lut[63&n|128]}${t._lut[n>>8&255]}-${t._lut[n>>16&255]}${t._lut[n>>24&255]}${t._lut[255&s]}${t._lut[s>>8&255]}${t._lut[s>>16&255]}${t._lut[s>>24&255]}`.toLowerCase()}static validate(e){if(!t._pattern.test(e))throw new Error(`${e} is not a valid UUID v4.\n\n- If you're the tool creator, you can take one from https://www.uuidgenerator.net/.\n\n- If you're using a platform tool, verify the uuid isn't misspelled or contact the tool creator.`)}};e(yt,"_pattern",/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/),e(yt,"_lut",["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"]);let _t=yt;const bt=":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",vt=new RegExp("^"+("["+bt+"]["+(bt+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040")+"]*")+"$");function xt(t,e){const i=[];let n=e.exec(t);for(;n;){const s=[];s.startIndex=e.lastIndex-n[0].length;const r=n.length;for(let t=0;t<r;t++)s.push(n[t]);i.push(s),n=e.exec(t)}return i}const Ct=function(t){const e=vt.exec(t);return!(null==e)};const St=["hasOwnProperty","toString","valueOf","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"],At=["__proto__","constructor","prototype"],Pt={allowBooleanAttributes:!1,unpairedTags:[]};function Tt(t){return" "===t||"\t"===t||"\n"===t||"\r"===t}function Et(t,e){const i=e;for(;e<t.length;e++)if("?"==t[e]||" "==t[e]){const n=t.substr(i,e-i);if(e>5&&"xml"===n)return Nt("InvalidXml","XML declaration allowed only at the start of the document.",Ft(t,e));if("?"==t[e]&&">"==t[e+1]){e++;break}continue}return e}function Mt(t,e){if(t.length>e+5&&"-"===t[e+1]&&"-"===t[e+2]){for(e+=3;e<t.length;e++)if("-"===t[e]&&"-"===t[e+1]&&">"===t[e+2]){e+=2;break}}else if(t.length>e+8&&"D"===t[e+1]&&"O"===t[e+2]&&"C"===t[e+3]&&"T"===t[e+4]&&"Y"===t[e+5]&&"P"===t[e+6]&&"E"===t[e+7]){let i=1;for(e+=8;e<t.length;e++)if("<"===t[e])i++;else if(">"===t[e]&&(i--,0===i))break}else if(t.length>e+9&&"["===t[e+1]&&"C"===t[e+2]&&"D"===t[e+3]&&"A"===t[e+4]&&"T"===t[e+5]&&"A"===t[e+6]&&"["===t[e+7])for(e+=8;e<t.length;e++)if("]"===t[e]&&"]"===t[e+1]&&">"===t[e+2]){e+=2;break}return e}const It='"',zt="'";function Dt(t,e){let i="",n="",s=!1;for(;e<t.length;e++){if(t[e]===It||t[e]===zt)""===n?n=t[e]:n!==t[e]||(n="");else if(">"===t[e]&&""===n){s=!0;break}i+=t[e]}return""===n&&{value:i,index:e,tagClosed:s}}const kt=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function Bt(t,e){const i=xt(t,kt),n={};for(let t=0;t<i.length;t++){if(0===i[t][1].length)return Nt("InvalidAttr","Attribute '"+i[t][2]+"' has no space in starting.",Rt(i[t]));if(void 0!==i[t][3]&&void 0===i[t][4])return Nt("InvalidAttr","Attribute '"+i[t][2]+"' is without value.",Rt(i[t]));if(void 0===i[t][3]&&!e.allowBooleanAttributes)return Nt("InvalidAttr","boolean attribute '"+i[t][2]+"' is not allowed.",Rt(i[t]));const s=i[t][2];if(!Vt(s))return Nt("InvalidAttr","Attribute '"+s+"' is an invalid name.",Rt(i[t]));if(Object.prototype.hasOwnProperty.call(n,s))return Nt("InvalidAttr","Attribute '"+s+"' is repeated.",Rt(i[t]));n[s]=1}return!0}function Ot(t,e){if(";"===t[++e])return-1;if("#"===t[e])return function(t,e){let i=/\d/;for("x"===t[e]&&(e++,i=/[\da-fA-F]/);e<t.length;e++){if(";"===t[e])return e;if(!t[e].match(i))break}return-1}(t,++e);let i=0;for(;e<t.length;e++,i++)if(!(t[e].match(/\w/)&&i<20)){if(";"===t[e])break;return-1}return e}function Nt(t,e,i){return{err:{code:t,msg:e,line:i.line||i,col:i.col}}}function Vt(t){return Ct(t)}function Lt(t){return Ct(t)}function Ft(t,e){const i=t.substring(0,e).split(/\r?\n/);return{line:i.length,col:i[i.length-1].length+1}}function Rt(t){return t.startIndex+t[1].length}const Ut={cent:"¢",pound:"£",curren:"¤",yen:"¥",euro:"€",dollar:"$",euro:"€",fnof:"ƒ",inr:"₹",af:"؋",birr:"ብር",peso:"₱",rub:"₽",won:"₩",yuan:"¥",cedil:"¸"},jt={amp:"&",apos:"'",gt:">",lt:"<",quot:'"'},$t={nbsp:" ",copy:"©",reg:"®",trade:"™",mdash:"—",ndash:"–",hellip:"…",laquo:"«",raquo:"»",lsquo:"‘",rsquo:"’",ldquo:"“",rdquo:"”",bull:"•",para:"¶",sect:"§",deg:"°",frac12:"½",frac14:"¼",frac34:"¾"},Wt=new Set("!?\\\\/[]$%{}^&*()<>|+");function Gt(t){if("#"===t[0])throw new Error(`[EntityReplacer] Invalid character '#' in entity name: "${t}"`);for(const e of t)if(Wt.has(e))throw new Error(`[EntityReplacer] Invalid character '${e}' in entity name: "${t}"`);return t}function Ht(...t){const e=Object.create(null);for(const i of t)if(i)for(const t of Object.keys(i)){const n=i[t];if("string"==typeof n)e[t]=n;else if(n&&"object"==typeof n&&void 0!==n.val){const i=n.val;"string"==typeof i&&(e[t]=i)}}return e}const Zt="external",qt="base",Yt="all";const Xt=Object.freeze({allow:0,leave:1,remove:2,throw:3}),Kt=new Set([9,10,13]);class Qt{constructor(t={}){var e;this._limit=t.limit||{},this._maxTotalExpansions=this._limit.maxTotalExpansions||0,this._maxExpandedLength=this._limit.maxExpandedLength||0,this._postCheck="function"==typeof t.postCheck?t.postCheck:t=>t,this._limitTiers=(e=this._limit.applyLimitsTo??Zt)&&e!==Zt?e===Yt?new Set([Yt]):e===qt?new Set([qt]):Array.isArray(e)?new Set(e):new Set([Zt]):new Set([Zt]),this._numericAllowed=t.numericAllowed??!0,this._baseMap=Ht(jt,t.namedEntities||null),this._externalMap=Object.create(null),this._inputMap=Object.create(null),this._totalExpansions=0,this._expandedLength=0,this._removeSet=new Set(t.remove&&Array.isArray(t.remove)?t.remove:[]),this._leaveSet=new Set(t.leave&&Array.isArray(t.leave)?t.leave:[]);const i=function(t){if(!t)return{xmlVersion:1,onLevel:Xt.allow,nullLevel:Xt.remove};const e=1.1===t.xmlVersion?1.1:1,i=Xt[t.onNCR]??Xt.allow,n=Xt[t.nullNCR]??Xt.remove;return{xmlVersion:e,onLevel:i,nullLevel:Math.max(n,Xt.remove)}}(t.ncr);this._ncrXmlVersion=i.xmlVersion,this._ncrOnLevel=i.onLevel,this._ncrNullLevel=i.nullLevel}setExternalEntities(t){if(t)for(const e of Object.keys(t))Gt(e);this._externalMap=Ht(t)}addExternalEntity(t,e){Gt(t),"string"==typeof e&&-1===e.indexOf("&")&&(this._externalMap[t]=e)}addInputEntities(t){this._totalExpansions=0,this._expandedLength=0,this._inputMap=Ht(t)}reset(){return this._inputMap=Object.create(null),this._totalExpansions=0,this._expandedLength=0,this}setXmlVersion(t){this._ncrXmlVersion=1.1===t?1.1:1}decode(t){if("string"!=typeof t||0===t.length)return t;const e=t,i=[],n=t.length;let s=0,r=0;const o=this._maxTotalExpansions>0,a=this._maxExpandedLength>0,l=o||a;for(;r<n;){if(38!==t.charCodeAt(r)){r++;continue}let e=r+1;for(;e<n&&59!==t.charCodeAt(e)&&e-r<=32;)e++;if(e>=n||59!==t.charCodeAt(e)){r++;continue}const c=t.slice(r+1,e);if(0===c.length){r++;continue}let h,u;if(this._removeSet.has(c))h="",void 0===u&&(u=Zt);else{if(this._leaveSet.has(c)){r++;continue}if(35===c.charCodeAt(0)){const t=this._resolveNCR(c);if(void 0===t){r++;continue}h=t,u=qt}else{const t=this._resolveName(c);h=null==t?void 0:t.value,u=null==t?void 0:t.tier}}if(void 0!==h){if(r>s&&i.push(t.slice(s,r)),i.push(h),s=e+1,r=s,l&&this._tierCounts(u)){if(o&&(this._totalExpansions++,this._totalExpansions>this._maxTotalExpansions))throw new Error(`[EntityReplacer] Entity expansion count limit exceeded: ${this._totalExpansions} > ${this._maxTotalExpansions}`);if(a){const t=h.length-(c.length+2);if(t>0&&(this._expandedLength+=t,this._expandedLength>this._maxExpandedLength))throw new Error(`[EntityReplacer] Expanded content length limit exceeded: ${this._expandedLength} > ${this._maxExpandedLength}`)}}}else r++}s<n&&i.push(t.slice(s));const c=0===i.length?t:i.join("");return this._postCheck(c,e)}_tierCounts(t){return!!this._limitTiers.has(Yt)||this._limitTiers.has(t)}_resolveName(t){return t in this._inputMap?{value:this._inputMap[t],tier:Zt}:t in this._externalMap?{value:this._externalMap[t],tier:Zt}:t in this._baseMap?{value:this._baseMap[t],tier:qt}:void 0}_classifyNCR(t){return 0===t?this._ncrNullLevel:t>=55296&&t<=57343||1===this._ncrXmlVersion&&t>=1&&t<=31&&!Kt.has(t)?Xt.remove:-1}_applyNCRAction(t,e,i){switch(t){case Xt.allow:return String.fromCodePoint(i);case Xt.remove:return"";case Xt.leave:return;case Xt.throw:throw new Error(`[EntityDecoder] Prohibited numeric character reference &${e}; (U+${i.toString(16).toUpperCase().padStart(4,"0")})`);default:return String.fromCodePoint(i)}}_resolveNCR(t){const e=t.charCodeAt(1);let i;if(i=120===e||88===e?parseInt(t.slice(2),16):parseInt(t.slice(1),10),Number.isNaN(i)||i<0||i>1114111)return;const n=this._classifyNCR(i);if(!this._numericAllowed&&n<Xt.remove)return;const s=-1===n?this._ncrOnLevel:Math.max(this._ncrOnLevel,n);return this._applyNCRAction(s,t,i)}}const Jt=t=>St.includes(t)?"__"+t:t,te={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(t,e){return e},attributeValueProcessor:function(t,e){return e},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,entityDecoder:null,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(t,e,i){return t},captureMetaData:!1,maxNestedTags:100,strictReservedNames:!0,jPath:!0,onDangerousProperty:Jt};function ee(t,e){if("string"!=typeof t)return;const i=t.toLowerCase();if(St.some(t=>i===t.toLowerCase()))throw new Error(`[SECURITY] Invalid ${e}: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`);if(At.some(t=>i===t.toLowerCase()))throw new Error(`[SECURITY] Invalid ${e}: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`)}function ie(t,e){return"boolean"==typeof t?{enabled:t,maxEntitySize:1e4,maxExpansionDepth:1e4,maxTotalExpansions:1/0,maxExpandedLength:1e5,maxEntityCount:1e3,allowedTags:null,tagFilter:null,appliesTo:"all"}:"object"==typeof t&&null!==t?{enabled:!1!==t.enabled,maxEntitySize:Math.max(1,t.maxEntitySize??1e4),maxExpansionDepth:Math.max(1,t.maxExpansionDepth??1e4),maxTotalExpansions:Math.max(1,t.maxTotalExpansions??1/0),maxExpandedLength:Math.max(1,t.maxExpandedLength??1e5),maxEntityCount:Math.max(1,t.maxEntityCount??1e3),allowedTags:t.allowedTags??null,tagFilter:t.tagFilter??null,appliesTo:t.appliesTo??"all"}:ie(!0)}const ne=function(t){const e=Object.assign({},te,t),i=[{value:e.attributeNamePrefix,name:"attributeNamePrefix"},{value:e.attributesGroupName,name:"attributesGroupName"},{value:e.textNodeName,name:"textNodeName"},{value:e.cdataPropName,name:"cdataPropName"},{value:e.commentPropName,name:"commentPropName"}];for(const{value:t,name:e}of i)t&&ee(t,e);return null===e.onDangerousProperty&&(e.onDangerousProperty=Jt),e.processEntities=ie(e.processEntities,e.htmlEntities),e.unpairedTagsSet=new Set(e.unpairedTags),e.stopNodes&&Array.isArray(e.stopNodes)&&(e.stopNodes=e.stopNodes.map(t=>"string"==typeof t&&t.startsWith("*.")?".."+t.substring(2):t)),e};let se;se="function"!=typeof Symbol?"@@xmlMetadata":Symbol("XML Node Metadata");class re{constructor(t){this.tagname=t,this.child=[],this[":@"]=Object.create(null)}add(t,e){"__proto__"===t&&(t="#__proto__"),this.child.push({[t]:e})}addChild(t,e){"__proto__"===t.tagname&&(t.tagname="#__proto__"),t[":@"]&&Object.keys(t[":@"]).length>0?this.child.push({[t.tagname]:t.child,":@":t[":@"]}):this.child.push({[t.tagname]:t.child}),void 0!==e&&(this.child[this.child.length-1][se]={startIndex:e})}static getMetaDataSymbol(){return se}}class oe{constructor(t){this.suppressValidationErr=!t,this.options=t}readDocType(t,e){const i=Object.create(null);let n=0;if("O"!==t[e+3]||"C"!==t[e+4]||"T"!==t[e+5]||"Y"!==t[e+6]||"P"!==t[e+7]||"E"!==t[e+8])throw new Error("Invalid Tag instead of DOCTYPE");{e+=9;let s=1,r=!1,o=!1,a="";for(;e<t.length;e++)if("<"!==t[e]||o)if(">"===t[e]){if(o?"-"===t[e-1]&&"-"===t[e-2]&&(o=!1,s--):s--,0===s)break}else"["===t[e]?r=!0:a+=t[e];else{if(r&&le(t,"!ENTITY",e)){let s,r;if(e+=7,[s,r,e]=this.readEntityExp(t,e+1,this.suppressValidationErr),-1===r.indexOf("&")){if(!1!==this.options.enabled&&null!=this.options.maxEntityCount&&n>=this.options.maxEntityCount)throw new Error(`Entity count (${n+1}) exceeds maximum allowed (${this.options.maxEntityCount})`);i[s]=r,n++}}else if(r&&le(t,"!ELEMENT",e)){e+=8;const{index:i}=this.readElementExp(t,e+1);e=i}else if(r&&le(t,"!ATTLIST",e))e+=8;else if(r&&le(t,"!NOTATION",e)){e+=9;const{index:i}=this.readNotationExp(t,e+1,this.suppressValidationErr);e=i}else{if(!le(t,"!--",e))throw new Error("Invalid DOCTYPE");o=!0}s++,a=""}if(0!==s)throw new Error("Unclosed DOCTYPE")}return{entities:i,i:e}}readEntityExp(t,e){const i=e=ae(t,e);for(;e<t.length&&!/\s/.test(t[e])&&'"'!==t[e]&&"'"!==t[e];)e++;let n=t.substring(i,e);if(ce(n),e=ae(t,e),!this.suppressValidationErr){if("SYSTEM"===t.substring(e,e+6).toUpperCase())throw new Error("External entities are not supported");if("%"===t[e])throw new Error("Parameter entities are not supported")}let s="";if([e,s]=this.readIdentifierVal(t,e,"entity"),!1!==this.options.enabled&&null!=this.options.maxEntitySize&&s.length>this.options.maxEntitySize)throw new Error(`Entity "${n}" size (${s.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`);return[n,s,--e]}readNotationExp(t,e){const i=e=ae(t,e);for(;e<t.length&&!/\s/.test(t[e]);)e++;let n=t.substring(i,e);!this.suppressValidationErr&&ce(n),e=ae(t,e);const s=t.substring(e,e+6).toUpperCase();if(!this.suppressValidationErr&&"SYSTEM"!==s&&"PUBLIC"!==s)throw new Error(`Expected SYSTEM or PUBLIC, found "${s}"`);e+=s.length,e=ae(t,e);let r=null,o=null;if("PUBLIC"===s)[e,r]=this.readIdentifierVal(t,e,"publicIdentifier"),'"'!==t[e=ae(t,e)]&&"'"!==t[e]||([e,o]=this.readIdentifierVal(t,e,"systemIdentifier"));else if("SYSTEM"===s&&([e,o]=this.readIdentifierVal(t,e,"systemIdentifier"),!this.suppressValidationErr&&!o))throw new Error("Missing mandatory system identifier for SYSTEM notation");return{notationName:n,publicIdentifier:r,systemIdentifier:o,index:--e}}readIdentifierVal(t,e,i){let n="";const s=t[e];if('"'!==s&&"'"!==s)throw new Error(`Expected quoted string, found "${s}"`);const r=++e;for(;e<t.length&&t[e]!==s;)e++;if(n=t.substring(r,e),t[e]!==s)throw new Error(`Unterminated ${i} value`);return[++e,n]}readElementExp(t,e){const i=e=ae(t,e);for(;e<t.length&&!/\s/.test(t[e]);)e++;let n=t.substring(i,e);if(!this.suppressValidationErr&&!Ct(n))throw new Error(`Invalid element name: "${n}"`);let s="";if("E"===t[e=ae(t,e)]&&le(t,"MPTY",e))e+=4;else if("A"===t[e]&&le(t,"NY",e))e+=2;else if("("===t[e]){const i=++e;for(;e<t.length&&")"!==t[e];)e++;if(s=t.substring(i,e),")"!==t[e])throw new Error("Unterminated content model")}else if(!this.suppressValidationErr)throw new Error(`Invalid Element Expression, found "${t[e]}"`);return{elementName:n,contentModel:s.trim(),index:e}}readAttlistExp(t,e){let i=e=ae(t,e);for(;e<t.length&&!/\s/.test(t[e]);)e++;let n=t.substring(i,e);for(ce(n),i=e=ae(t,e);e<t.length&&!/\s/.test(t[e]);)e++;let s=t.substring(i,e);if(!ce(s))throw new Error(`Invalid attribute name: "${s}"`);e=ae(t,e);let r="";if("NOTATION"===t.substring(e,e+8).toUpperCase()){if(r="NOTATION","("!==t[e=ae(t,e+=8)])throw new Error(`Expected '(', found "${t[e]}"`);e++;let i=[];for(;e<t.length&&")"!==t[e];){const n=e;for(;e<t.length&&"|"!==t[e]&&")"!==t[e];)e++;let s=t.substring(n,e);if(s=s.trim(),!ce(s))throw new Error(`Invalid notation name: "${s}"`);i.push(s),"|"===t[e]&&(e++,e=ae(t,e))}if(")"!==t[e])throw new Error("Unterminated list of notations");e++,r+=" ("+i.join("|")+")"}else{const i=e;for(;e<t.length&&!/\s/.test(t[e]);)e++;r+=t.substring(i,e);const n=["CDATA","ID","IDREF","IDREFS","ENTITY","ENTITIES","NMTOKEN","NMTOKENS"];if(!this.suppressValidationErr&&!n.includes(r.toUpperCase()))throw new Error(`Invalid attribute type: "${r}"`)}e=ae(t,e);let o="";return"#REQUIRED"===t.substring(e,e+8).toUpperCase()?(o="#REQUIRED",e+=8):"#IMPLIED"===t.substring(e,e+7).toUpperCase()?(o="#IMPLIED",e+=7):[e,o]=this.readIdentifierVal(t,e,"ATTLIST"),{elementName:n,attributeName:s,attributeType:r,defaultValue:o,index:e}}}const ae=(t,e)=>{for(;e<t.length&&/\s/.test(t[e]);)e++;return e};function le(t,e,i){for(let n=0;n<e.length;n++)if(e[n]!==t[i+n+1])return!1;return!0}function ce(t){if(Ct(t))return t;throw new Error(`Invalid entity name ${t}`)}const he=/^[-+]?0x[a-fA-F0-9]+$/,ue=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,de={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0,infinity:"original"};function pe(t,e={}){if(e=Object.assign({},de,e),!t||"string"!=typeof t)return t;let i=t.trim();if(0===i.length)return t;if(void 0!==e.skipLike&&e.skipLike.test(i))return t;if("0"===i)return 0;if(e.hex&&he.test(i))return function(t,e){if(parseInt)return parseInt(t,e);if(Number.parseInt)return Number.parseInt(t,e);if(window&&window.parseInt)return window.parseInt(t,e);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}(i,16);if(isFinite(i)){if(i.includes("e")||i.includes("E"))return function(t,e,i){if(!i.eNotation)return t;const n=e.match(fe);if(n){let s=n[1]||"";const r=-1===n[3].indexOf("e")?"E":"e",o=n[2],a=s?t[o.length+1]===r:t[o.length]===r;return o.length>1&&a?t:(1!==o.length||!n[3].startsWith(`.${r}`)&&n[3][0]!==r)&&o.length>0?i.leadingZeros&&!a?(e=(n[1]||"")+n[3],Number(e)):t:Number(e)}return t}(t,i,e);{const n=ue.exec(i);if(n){const s=n[1]||"",r=n[2];let o=function(t){if(t&&-1!==t.indexOf("."))return"."===(t=t.replace(/0+$/,""))?t="0":"."===t[0]?t="0"+t:"."===t[t.length-1]&&(t=t.substring(0,t.length-1)),t;return t}(n[3]);const a=s?"."===t[r.length+1]:"."===t[r.length];if(!e.leadingZeros&&(r.length>1||1===r.length&&!a))return t;{const n=Number(i),a=String(n);if(0===n)return n;if(-1!==a.search(/[eE]/))return e.eNotation?n:t;if(-1!==i.indexOf("."))return"0"===a||a===o||a===`${s}${o}`?n:t;let l=r?o:i;return r?l===a||s+l===a?n:t:l===a||l===s+a?n:t}}return t}}return function(t,e,i){const n=e===1/0;switch(i.infinity.toLowerCase()){case"null":return null;case"infinity":return e;case"string":return n?"Infinity":"-Infinity";default:return t}}(t,Number(i),e)}const fe=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;class me{constructor(t,e={},i){this.pattern=t,this.separator=e.separator||".",this.segments=this._parse(t),this.data=i,this._hasDeepWildcard=this.segments.some(t=>"deep-wildcard"===t.type),this._hasAttributeCondition=this.segments.some(t=>void 0!==t.attrName),this._hasPositionSelector=this.segments.some(t=>void 0!==t.position)}_parse(t){const e=[];let i=0,n="";for(;i<t.length;)t[i]===this.separator?i+1<t.length&&t[i+1]===this.separator?(n.trim()&&(e.push(this._parseSegment(n.trim())),n=""),e.push({type:"deep-wildcard"}),i+=2):(n.trim()&&e.push(this._parseSegment(n.trim())),n="",i++):(n+=t[i],i++);return n.trim()&&e.push(this._parseSegment(n.trim())),e}_parseSegment(t){const e={type:"tag"};let i=null,n=t;const s=t.match(/^([^\[]+)(\[[^\]]*\])(.*)$/);if(s&&(n=s[1]+s[3],s[2])){const t=s[2].slice(1,-1);t&&(i=t)}let r,o,a=n;if(n.includes("::")){const e=n.indexOf("::");if(r=n.substring(0,e).trim(),a=n.substring(e+2).trim(),!r)throw new Error(`Invalid namespace in pattern: ${t}`)}let l=null;if(a.includes(":")){const t=a.lastIndexOf(":"),e=a.substring(0,t).trim(),i=a.substring(t+1).trim();["first","last","odd","even"].includes(i)||/^nth\(\d+\)$/.test(i)?(o=e,l=i):o=a}else o=a;if(!o)throw new Error(`Invalid segment pattern: ${t}`);if(e.tag=o,r&&(e.namespace=r),i)if(i.includes("=")){const t=i.indexOf("=");e.attrName=i.substring(0,t).trim(),e.attrValue=i.substring(t+1).trim()}else e.attrName=i.trim();if(l){const t=l.match(/^nth\((\d+)\)$/);t?(e.position="nth",e.positionValue=parseInt(t[1],10)):e.position=l}return e}get length(){return this.segments.length}hasDeepWildcard(){return this._hasDeepWildcard}hasAttributeCondition(){return this._hasAttributeCondition}hasPositionSelector(){return this._hasPositionSelector}toString(){return this.pattern}}class ge{constructor(){this._byDepthAndTag=new Map,this._wildcardByDepth=new Map,this._deepWildcards=[],this._patterns=new Set,this._sealed=!1}add(t){if(this._sealed)throw new TypeError("ExpressionSet is sealed. Create a new ExpressionSet to add more expressions.");if(this._patterns.has(t.pattern))return this;if(this._patterns.add(t.pattern),t.hasDeepWildcard())return this._deepWildcards.push(t),this;const e=t.length,i=t.segments[t.segments.length-1],n=null==i?void 0:i.tag;if(n&&"*"!==n){const i=`${e}:${n}`;this._byDepthAndTag.has(i)||this._byDepthAndTag.set(i,[]),this._byDepthAndTag.get(i).push(t)}else this._wildcardByDepth.has(e)||this._wildcardByDepth.set(e,[]),this._wildcardByDepth.get(e).push(t);return this}addAll(t){for(const e of t)this.add(e);return this}has(t){return this._patterns.has(t.pattern)}get size(){return this._patterns.size}seal(){return this._sealed=!0,this}get isSealed(){return this._sealed}matchesAny(t){return null!==this.findMatch(t)}findMatch(t){const e=t.getDepth(),i=`${e}:${t.getCurrentTag()}`,n=this._byDepthAndTag.get(i);if(n)for(let e=0;e<n.length;e++)if(t.matches(n[e]))return n[e];const s=this._wildcardByDepth.get(e);if(s)for(let e=0;e<s.length;e++)if(t.matches(s[e]))return s[e];for(let e=0;e<this._deepWildcards.length;e++)if(t.matches(this._deepWildcards[e]))return this._deepWildcards[e];return null}}class we{constructor(t){this._matcher=t}get separator(){return this._matcher.separator}getCurrentTag(){const t=this._matcher.path;return t.length>0?t[t.length-1].tag:void 0}getCurrentNamespace(){const t=this._matcher.path;return t.length>0?t[t.length-1].namespace:void 0}getAttrValue(t){var e;const i=this._matcher.path;if(0!==i.length)return null==(e=i[i.length-1].values)?void 0:e[t]}hasAttr(t){const e=this._matcher.path;if(0===e.length)return!1;const i=e[e.length-1];return void 0!==i.values&&t in i.values}getPosition(){const t=this._matcher.path;return 0===t.length?-1:t[t.length-1].position??0}getCounter(){const t=this._matcher.path;return 0===t.length?-1:t[t.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this._matcher.path.length}toString(t,e=!0){return this._matcher.toString(t,e)}toArray(){return this._matcher.path.map(t=>t.tag)}matches(t){return this._matcher.matches(t)}matchesAny(t){return t.matchesAny(this._matcher)}}class ye{constructor(t={}){this.separator=t.separator||".",this.path=[],this.siblingStacks=[],this._pathStringCache=null,this._view=new we(this)}push(t,e=null,i=null){this._pathStringCache=null,this.path.length>0&&(this.path[this.path.length-1].values=void 0);const n=this.path.length;this.siblingStacks[n]||(this.siblingStacks[n]=new Map);const s=this.siblingStacks[n],r=i?`${i}:${t}`:t,o=s.get(r)||0;let a=0;for(const t of s.values())a+=t;s.set(r,o+1);const l={tag:t,position:a,counter:o};null!=i&&(l.namespace=i),null!=e&&(l.values=e),this.path.push(l)}pop(){if(0===this.path.length)return;this._pathStringCache=null;const t=this.path.pop();return this.siblingStacks.length>this.path.length+1&&(this.siblingStacks.length=this.path.length+1),t}updateCurrent(t){if(this.path.length>0){const e=this.path[this.path.length-1];null!=t&&(e.values=t)}}getCurrentTag(){return this.path.length>0?this.path[this.path.length-1].tag:void 0}getCurrentNamespace(){return this.path.length>0?this.path[this.path.length-1].namespace:void 0}getAttrValue(t){var e;if(0!==this.path.length)return null==(e=this.path[this.path.length-1].values)?void 0:e[t]}hasAttr(t){if(0===this.path.length)return!1;const e=this.path[this.path.length-1];return void 0!==e.values&&t in e.values}getPosition(){return 0===this.path.length?-1:this.path[this.path.length-1].position??0}getCounter(){return 0===this.path.length?-1:this.path[this.path.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this.path.length}toString(t,e=!0){const i=t||this.separator;if(i===this.separator&&!0===e){if(null!==this._pathStringCache)return this._pathStringCache;const t=this.path.map(t=>t.namespace?`${t.namespace}:${t.tag}`:t.tag).join(i);return this._pathStringCache=t,t}return this.path.map(t=>e&&t.namespace?`${t.namespace}:${t.tag}`:t.tag).join(i)}toArray(){return this.path.map(t=>t.tag)}reset(){this._pathStringCache=null,this.path=[],this.siblingStacks=[]}matches(t){const e=t.segments;return 0!==e.length&&(t.hasDeepWildcard()?this._matchWithDeepWildcard(e):this._matchSimple(e))}_matchSimple(t){if(this.path.length!==t.length)return!1;for(let e=0;e<t.length;e++)if(!this._matchSegment(t[e],this.path[e],e===this.path.length-1))return!1;return!0}_matchWithDeepWildcard(t){let e=this.path.length-1,i=t.length-1;for(;i>=0&&e>=0;){const n=t[i];if("deep-wildcard"===n.type){if(i--,i<0)return!0;const n=t[i];let s=!1;for(let t=e;t>=0;t--)if(this._matchSegment(n,this.path[t],t===this.path.length-1)){e=t-1,i--,s=!0;break}if(!s)return!1}else{if(!this._matchSegment(n,this.path[e],e===this.path.length-1))return!1;e--,i--}}return i<0}_matchSegment(t,e,i){if("*"!==t.tag&&t.tag!==e.tag)return!1;if(void 0!==t.namespace&&"*"!==t.namespace&&t.namespace!==e.namespace)return!1;if(void 0!==t.attrName){if(!i)return!1;if(!e.values||!(t.attrName in e.values))return!1;if(void 0!==t.attrValue&&String(e.values[t.attrName])!==String(t.attrValue))return!1}if(void 0!==t.position){if(!i)return!1;const n=e.counter??0;if("first"===t.position&&0!==n)return!1;if("odd"===t.position&&n%2!=1)return!1;if("even"===t.position&&n%2!=0)return!1;if("nth"===t.position&&n!==t.positionValue)return!1}return!0}matchesAny(t){return t.matchesAny(this)}snapshot(){return{path:this.path.map(t=>({...t})),siblingStacks:this.siblingStacks.map(t=>new Map(t))}}restore(t){this._pathStringCache=null,this.path=t.path.map(t=>({...t})),this.siblingStacks=t.siblingStacks.map(t=>new Map(t))}readOnly(){return this._view}}function _e(t,e){if(!t)return{};const i=e.attributesGroupName?t[e.attributesGroupName]:t;if(!i)return{};const n={};for(const t in i)if(t.startsWith(e.attributeNamePrefix)){n[t.substring(e.attributeNamePrefix.length)]=i[t]}else n[t]=i[t];return n}function be(t){if(!t||"string"!=typeof t)return;const e=t.indexOf(":");if(-1!==e&&e>0){const i=t.substring(0,e);if("xmlns"!==i)return i}}class ve{constructor(t,e){var i;this.options=t,this.currentNode=null,this.tagsNodeStack=[],this.parseXml=Pe,this.parseTextData=xe,this.resolveNameSpace=Ce,this.buildAttributesMap=Ae,this.isItStopNode=Ie,this.replaceEntitiesValue=Ee,this.readStopNodeData=Be,this.saveTextToParentTag=Me,this.addChild=Te,this.ignoreAttributesFn="function"==typeof(i=this.options.ignoreAttributes)?i:Array.isArray(i)?t=>{for(const e of i){if("string"==typeof e&&t===e)return!0;if(e instanceof RegExp&&e.test(t))return!0}}:()=>!1,this.entityExpansionCount=0,this.currentExpandedLength=0;let n={...jt};this.options.entityDecoder?this.entityDecoder=this.options.entityDecoder:("object"==typeof this.options.htmlEntities?n=this.options.htmlEntities:!0===this.options.htmlEntities&&(n={...$t,...Ut}),this.entityDecoder=new Qt({namedEntities:{...n,...e},numericAllowed:this.options.htmlEntities,limit:{maxTotalExpansions:this.options.processEntities.maxTotalExpansions,maxExpandedLength:this.options.processEntities.maxExpandedLength,applyLimitsTo:this.options.processEntities.appliesTo}})),this.matcher=new ye,this.readonlyMatcher=this.matcher.readOnly(),this.isCurrentNodeStopNode=!1,this.stopNodeExpressionsSet=new ge;const s=this.options.stopNodes;if(s&&s.length>0){for(let t=0;t<s.length;t++){const e=s[t];"string"==typeof e?this.stopNodeExpressionsSet.add(new me(e)):e instanceof me&&this.stopNodeExpressionsSet.add(e)}this.stopNodeExpressionsSet.seal()}}}function xe(t,e,i,n,s,r,o){const a=this.options;if(void 0!==t&&(a.trimValues&&!n&&(t=t.trim()),t.length>0)){o||(t=this.replaceEntitiesValue(t,e,i));const n=a.jPath?i.toString():i,l=a.tagValueProcessor(e,t,n,s,r);if(null==l)return t;if(typeof l!=typeof t||l!==t)return l;if(a.trimValues)return Oe(t,a.parseTagValue,a.numberParseOptions);return t.trim()===t?Oe(t,a.parseTagValue,a.numberParseOptions):t}}function Ce(t){if(this.options.removeNSPrefix){const e=t.split(":"),i="/"===t.charAt(0)?"/":"";if("xmlns"===e[0])return"";2===e.length&&(t=i+e[1])}return t}const Se=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function Ae(t,e,i,n=!1){const s=this.options;if(!0===n||!0!==s.ignoreAttributes&&"string"==typeof t){const n=xt(t,Se),r=n.length,o={},a=new Array(r);let l=!1;const c={};for(let t=0;t<r;t++){const e=this.resolveNameSpace(n[t][1]),r=n[t][4];if(e.length&&void 0!==r){let n=r;s.trimValues&&(n=n.trim()),n=this.replaceEntitiesValue(n,i,this.readonlyMatcher),a[t]=n,c[e]=n,l=!0}}l&&"object"==typeof e&&e.updateCurrent&&e.updateCurrent(c);const h=s.jPath?e.toString():this.readonlyMatcher;let u=!1;for(let t=0;t<r;t++){const e=this.resolveNameSpace(n[t][1]);if(this.ignoreAttributesFn(e,h))continue;let i=s.attributeNamePrefix+e;if(e.length)if(s.transformAttributeName&&(i=s.transformAttributeName(i)),i=Ve(i,s),void 0!==n[t][4]){const n=a[t],r=s.attributeValueProcessor(e,n,h);o[i]=null==r?n:typeof r!=typeof n||r!==n?r:Oe(n,s.parseAttributeValue,s.numberParseOptions),u=!0}else s.allowBooleanAttributes&&(o[i]=!0,u=!0)}if(!u)return;if(s.attributesGroupName&&!s.preserveOrder){const t={};return t[s.attributesGroupName]=o,t}return o}}const Pe=function(t){t=t.replace(/\r\n?/g,"\n");const e=new re("!xml");let i=e,n="";this.matcher.reset(),this.entityDecoder.reset(),this.entityExpansionCount=0,this.currentExpandedLength=0;const s=this.options,r=new oe(s.processEntities),o=t.length;for(let a=0;a<o;a++){if("<"===t[a]){const l=t.charCodeAt(a+1);if(47===l){const e=ze(t,">",a,"Closing Tag is not closed.");let r=t.substring(a+2,e).trim();if(s.removeNSPrefix){const t=r.indexOf(":");-1!==t&&(r=r.substr(t+1))}r=Ne(s.transformTagName,r,"",s).tagName,i&&(n=this.saveTextToParentTag(n,i,this.readonlyMatcher));const o=this.matcher.getCurrentTag();if(r&&s.unpairedTagsSet.has(r))throw new Error(`Unpaired tag can not be used as closing tag: </${r}>`);o&&s.unpairedTagsSet.has(o)&&(this.matcher.pop(),this.tagsNodeStack.pop()),this.matcher.pop(),this.isCurrentNodeStopNode=!1,i=this.tagsNodeStack.pop(),n="",a=e}else if(63===l){let e=ke(t,a,!1,"?>");if(!e)throw new Error("Pi Tag is not closed.");n=this.saveTextToParentTag(n,i,this.readonlyMatcher);const r=this.buildAttributesMap(e.tagExp,this.matcher,e.tagName,!0);if(r){const t=r[this.options.attributeNamePrefix+"version"];this.entityDecoder.setXmlVersion(Number(t)||1)}if(s.ignoreDeclaration&&"?xml"===e.tagName||s.ignorePiTags);else{const t=new re(e.tagName);t.add(s.textNodeName,""),e.tagName!==e.tagExp&&e.attrExpPresent&&!0!==s.ignoreAttributes&&(t[":@"]=r),this.addChild(i,t,this.readonlyMatcher,a)}a=e.closeIndex+1}else if(33===l&&45===t.charCodeAt(a+2)&&45===t.charCodeAt(a+3)){const e=ze(t,"--\x3e",a+4,"Comment is not closed.");if(s.commentPropName){const r=t.substring(a+4,e-2);n=this.saveTextToParentTag(n,i,this.readonlyMatcher),i.add(s.commentPropName,[{[s.textNodeName]:r}])}a=e}else if(33===l&&68===t.charCodeAt(a+2)){const e=r.readDocType(t,a);this.entityDecoder.addInputEntities(e.entities),a=e.i}else if(33===l&&91===t.charCodeAt(a+2)){const e=ze(t,"]]>",a,"CDATA is not closed.")-2,r=t.substring(a+9,e);n=this.saveTextToParentTag(n,i,this.readonlyMatcher);let o=this.parseTextData(r,i.tagname,this.readonlyMatcher,!0,!1,!0,!0);null==o&&(o=""),s.cdataPropName?i.add(s.cdataPropName,[{[s.textNodeName]:r}]):i.add(s.textNodeName,o),a=e+2}else{let r=ke(t,a,s.removeNSPrefix);if(!r){const e=t.substring(Math.max(0,a-50),Math.min(o,a+50));throw new Error(`readTagExp returned undefined at position ${a}. Context: "${e}"`)}let l=r.tagName;const c=r.rawTagName;let h=r.tagExp,u=r.attrExpPresent,d=r.closeIndex;if(({tagName:l,tagExp:h}=Ne(s.transformTagName,l,h,s)),s.strictReservedNames&&(l===s.commentPropName||l===s.cdataPropName||l===s.textNodeName||l===s.attributesGroupName))throw new Error(`Invalid tag name: ${l}`);i&&n&&"!xml"!==i.tagname&&(n=this.saveTextToParentTag(n,i,this.readonlyMatcher,!1));const p=i;p&&s.unpairedTagsSet.has(p.tagname)&&(i=this.tagsNodeStack.pop(),this.matcher.pop());let f=!1;h.length>0&&h.lastIndexOf("/")===h.length-1&&(f=!0,"/"===l[l.length-1]?(l=l.substr(0,l.length-1),h=l):h=h.substr(0,h.length-1),u=l!==h);let m,g=null;m=be(c),l!==e.tagname&&this.matcher.push(l,{},m),l!==h&&u&&(g=this.buildAttributesMap(h,this.matcher,l),g&&_e(g,s)),l!==e.tagname&&(this.isCurrentNodeStopNode=this.isItStopNode());const w=a;if(this.isCurrentNodeStopNode){let e="";if(f)a=r.closeIndex;else if(s.unpairedTagsSet.has(l))a=r.closeIndex;else{const i=this.readStopNodeData(t,c,d+1);if(!i)throw new Error(`Unexpected end of ${c}`);a=i.i,e=i.tagContent}const n=new re(l);g&&(n[":@"]=g),n.add(s.textNodeName,e),this.matcher.pop(),this.isCurrentNodeStopNode=!1,this.addChild(i,n,this.readonlyMatcher,w)}else{if(f){({tagName:l,tagExp:h}=Ne(s.transformTagName,l,h,s));const t=new re(l);g&&(t[":@"]=g),this.addChild(i,t,this.readonlyMatcher,w),this.matcher.pop(),this.isCurrentNodeStopNode=!1}else{if(s.unpairedTagsSet.has(l)){const t=new re(l);g&&(t[":@"]=g),this.addChild(i,t,this.readonlyMatcher,w),this.matcher.pop(),this.isCurrentNodeStopNode=!1,a=r.closeIndex;continue}{const t=new re(l);if(this.tagsNodeStack.length>s.maxNestedTags)throw new Error("Maximum nested tags exceeded");this.tagsNodeStack.push(i),g&&(t[":@"]=g),this.addChild(i,t,this.readonlyMatcher,w),i=t}}n="",a=d}}}else n+=t[a]}return e.child};function Te(t,e,i,n){this.options.captureMetaData||(n=void 0);const s=this.options.jPath?i.toString():i,r=this.options.updateTag(e.tagname,s,e[":@"]);!1===r||("string"==typeof r?(e.tagname=r,t.addChild(e,n)):t.addChild(e,n))}function Ee(t,e,i){const n=this.options.processEntities;if(!n||!n.enabled)return t;if(n.allowedTags){const s=this.options.jPath?i.toString():i;if(!(Array.isArray(n.allowedTags)?n.allowedTags.includes(e):n.allowedTags(e,s)))return t}if(n.tagFilter){const s=this.options.jPath?i.toString():i;if(!n.tagFilter(e,s))return t}return this.entityDecoder.decode(t)}function Me(t,e,i,n){return t&&(void 0===n&&(n=0===e.child.length),void 0!==(t=this.parseTextData(t,e.tagname,i,!1,!!e[":@"]&&0!==Object.keys(e[":@"]).length,n))&&""!==t&&e.add(this.options.textNodeName,t),t=""),t}function Ie(){return 0!==this.stopNodeExpressionsSet.size&&this.matcher.matchesAny(this.stopNodeExpressionsSet)}function ze(t,e,i,n){const s=t.indexOf(e,i);if(-1===s)throw new Error(n);return s+e.length-1}function De(t,e,i,n){const s=t.indexOf(e,i);if(-1===s)throw new Error(n);return s}function ke(t,e,i,n=">"){const s=function(t,e,i=">"){let n=0;const s=t.length,r=i.charCodeAt(0),o=i.length>1?i.charCodeAt(1):-1;let a="",l=e;for(let i=e;i<s;i++){const e=t.charCodeAt(i);if(n)e===n&&(n=0);else if(34===e||39===e)n=e;else if(e===r){if(-1===o)return a+=t.substring(l,i),{data:a,index:i};if(t.charCodeAt(i+1)===o)return a+=t.substring(l,i),{data:a,index:i}}else 9!==e||n||(a+=t.substring(l,i)+" ",l=i+1)}}(t,e+1,n);if(!s)return;let r=s.data;const o=s.index,a=r.search(/\s/);let l=r,c=!0;-1!==a&&(l=r.substring(0,a),r=r.substring(a+1).trimStart());const h=l;if(i){const t=l.indexOf(":");-1!==t&&(l=l.substr(t+1),c=l!==s.data.substr(t+1))}return{tagName:l,tagExp:r,closeIndex:o,attrExpPresent:c,rawTagName:h}}function Be(t,e,i){const n=i;let s=1;const r=t.length;for(;i<r;i++)if("<"===t[i]){const r=t.charCodeAt(i+1);if(47===r){const r=De(t,">",i,`${e} is not closed`);if(t.substring(i+2,r).trim()===e&&(s--,0===s))return{tagContent:t.substring(n,i),i:r};i=r}else if(63===r){i=ze(t,"?>",i+1,"StopNode is not closed.")}else if(33===r&&45===t.charCodeAt(i+2)&&45===t.charCodeAt(i+3)){i=ze(t,"--\x3e",i+3,"StopNode is not closed.")}else if(33===r&&91===t.charCodeAt(i+2)){i=ze(t,"]]>",i,"StopNode is not closed.")-2}else{const n=ke(t,i,">");if(n){(n&&n.tagName)===e&&"/"!==n.tagExp[n.tagExp.length-1]&&s++,i=n.closeIndex}}}}function Oe(t,e,i){if(e&&"string"==typeof t){const e=t.trim();return"true"===e||"false"!==e&&pe(t,i)}return void 0!==t?t:""}function Ne(t,e,i,n){if(t){const n=t(e);i===e&&(i=n),e=n}return{tagName:e=Ve(e,n),tagExp:i}}function Ve(t,e){if(At.includes(t))throw new Error(`[SECURITY] Invalid name: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`);return St.includes(t)?e.onDangerousProperty(t):t}const Le=re.getMetaDataSymbol();function Fe(t,e){if(!t||"object"!=typeof t)return{};if(!e)return t;const i={};for(const n in t)if(n.startsWith(e)){i[n.substring(e.length)]=t[n]}else i[n]=t[n];return i}function Re(t,e,i,n){return Ue(t,e,i,n)}function Ue(t,e,i,n){let s;const r={};for(let o=0;o<t.length;o++){const a=t[o],l=je(a);if(void 0!==l&&l!==e.textNodeName){const t=Fe(a[":@"]||{},e.attributeNamePrefix);i.push(l,t)}if(l===e.textNodeName)void 0===s?s=a[l]:s+=""+a[l];else{if(void 0===l)continue;if(a[l]){let t=Ue(a[l],e,i,n);const s=We(t,e);if(a[":@"]?$e(t,a[":@"],n,e):1!==Object.keys(t).length||void 0===t[e.textNodeName]||e.alwaysCreateTextNode?0===Object.keys(t).length&&(e.alwaysCreateTextNode?t[e.textNodeName]="":t=""):t=t[e.textNodeName],void 0!==a[Le]&&"object"==typeof t&&null!==t&&(t[Le]=a[Le]),void 0!==r[l]&&Object.prototype.hasOwnProperty.call(r,l))Array.isArray(r[l])||(r[l]=[r[l]]),r[l].push(t);else{const i=e.jPath?n.toString():n;e.isArray(l,i,s)?r[l]=[t]:r[l]=t}void 0!==l&&l!==e.textNodeName&&i.pop()}}}return"string"==typeof s?s.length>0&&(r[e.textNodeName]=s):void 0!==s&&(r[e.textNodeName]=s),r}function je(t){const e=Object.keys(t);for(let t=0;t<e.length;t++){const i=e[t];if(":@"!==i)return i}}function $e(t,e,i,n){if(e){const s=Object.keys(e),r=s.length;for(let o=0;o<r;o++){const r=s[o],a=r.startsWith(n.attributeNamePrefix)?r.substring(n.attributeNamePrefix.length):r,l=n.jPath?i.toString()+"."+a:i;n.isArray(r,l,!0,!0)?t[r]=[e[r]]:t[r]=e[r]}}}function We(t,e){const{textNodeName:i}=e,n=Object.keys(t).length;return 0===n||!(1!==n||!t[i]&&"boolean"!=typeof t[i]&&0!==t[i])}class Ge{constructor(t){this.externalEntities={},this.options=ne(t)}parse(t,e){if("string"!=typeof t&&t.toString)t=t.toString();else if("string"!=typeof t)throw new Error("XML data is accepted in String or Bytes[] form.");if(e){!0===e&&(e={});const i=function(t,e){e=Object.assign({},Pt,e);const i=[];let n=!1,s=!1;"\ufeff"===t[0]&&(t=t.substr(1));for(let r=0;r<t.length;r++)if("<"===t[r]&&"?"===t[r+1]){if(r+=2,r=Et(t,r),r.err)return r}else{if("<"!==t[r]){if(Tt(t[r]))continue;return Nt("InvalidChar","char '"+t[r]+"' is not expected.",Ft(t,r))}{let o=r;if(r++,"!"===t[r]){r=Mt(t,r);continue}{let a=!1;"/"===t[r]&&(a=!0,r++);let l="";for(;r<t.length&&">"!==t[r]&&" "!==t[r]&&"\t"!==t[r]&&"\n"!==t[r]&&"\r"!==t[r];r++)l+=t[r];if(l=l.trim(),"/"===l[l.length-1]&&(l=l.substring(0,l.length-1),r--),!Lt(l)){let e;return e=0===l.trim().length?"Invalid space after '<'.":"Tag '"+l+"' is an invalid name.",Nt("InvalidTag",e,Ft(t,r))}const c=Dt(t,r);if(!1===c)return Nt("InvalidAttr","Attributes for '"+l+"' have open quote.",Ft(t,r));let h=c.value;if(r=c.index,"/"===h[h.length-1]){const i=r-h.length;h=h.substring(0,h.length-1);const s=Bt(h,e);if(!0!==s)return Nt(s.err.code,s.err.msg,Ft(t,i+s.err.line));n=!0}else if(a){if(!c.tagClosed)return Nt("InvalidTag","Closing tag '"+l+"' doesn't have proper closing.",Ft(t,r));if(h.trim().length>0)return Nt("InvalidTag","Closing tag '"+l+"' can't have attributes or invalid starting.",Ft(t,o));if(0===i.length)return Nt("InvalidTag","Closing tag '"+l+"' has not been opened.",Ft(t,o));{const e=i.pop();if(l!==e.tagName){let i=Ft(t,e.tagStartPos);return Nt("InvalidTag","Expected closing tag '"+e.tagName+"' (opened in line "+i.line+", col "+i.col+") instead of closing tag '"+l+"'.",Ft(t,o))}0==i.length&&(s=!0)}}else{const a=Bt(h,e);if(!0!==a)return Nt(a.err.code,a.err.msg,Ft(t,r-h.length+a.err.line));if(!0===s)return Nt("InvalidXml","Multiple possible root nodes found.",Ft(t,r));-1!==e.unpairedTags.indexOf(l)||i.push({tagName:l,tagStartPos:o}),n=!0}for(r++;r<t.length;r++)if("<"===t[r]){if("!"===t[r+1]){r++,r=Mt(t,r);continue}if("?"!==t[r+1])break;if(r=Et(t,++r),r.err)return r}else if("&"===t[r]){const e=Ot(t,r);if(-1==e)return Nt("InvalidChar","char '&' is not expected.",Ft(t,r));r=e}else if(!0===s&&!Tt(t[r]))return Nt("InvalidXml","Extra text at the end",Ft(t,r));"<"===t[r]&&r--}}}return n?1==i.length?Nt("InvalidTag","Unclosed tag '"+i[0].tagName+"'.",Ft(t,i[0].tagStartPos)):!(i.length>0)||Nt("InvalidXml","Invalid '"+JSON.stringify(i.map(t=>t.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):Nt("InvalidXml","Start tag expected.",1)}(t,e);if(!0!==i)throw Error(`${i.err.msg}:${i.err.line}:${i.err.col}`)}const i=new ve(this.options,this.externalEntities),n=i.parseXml(t);return this.options.preserveOrder||void 0===n?n:Re(n,this.options,i.matcher,i.readonlyMatcher)}addEntity(t,e){if(-1!==e.indexOf("&"))throw new Error("Entity value can't have '&'");if(-1!==t.indexOf("&")||-1!==t.indexOf(";"))throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if("&"===e)throw new Error("An entity with value '&' is not permitted");this.externalEntities[t]=e}static getMetaDataSymbol(){return re.getMetaDataSymbol()}}function He(t,e){let i="";e.format&&e.indentBy.length>0&&(i="\n");const n=[];if(e.stopNodes&&Array.isArray(e.stopNodes))for(let t=0;t<e.stopNodes.length;t++){const i=e.stopNodes[t];"string"==typeof i?n.push(new me(i)):i instanceof me&&n.push(i)}return Ze(t,e,i,new ye,n)}function Ze(t,e,i,n,s){let r="",o=!1;if(e.maxNestedTags&&n.getDepth()>e.maxNestedTags)throw new Error("Maximum nested tags exceeded");if(!Array.isArray(t)){if(null!=t){let i=t.toString();return i=ti(i,e),i}return""}for(let a=0;a<t.length;a++){const l=t[a],c=Ke(l);if(void 0===c)continue;const h=qe(l[":@"],e);n.push(c,h);const u=Je(n,s);if(c===e.textNodeName){let t=l[c];u||(t=e.tagValueProcessor(c,t),t=ti(t,e)),o&&(r+=i),r+=t,o=!1,n.pop();continue}if(c===e.cdataPropName){o&&(r+=i);const t=l[c][0][e.textNodeName];r+=`<![CDATA[${String(t).replace(/\]\]>/g,"]]]]><![CDATA[>")}]]>`,o=!1,n.pop();continue}if(c===e.commentPropName){const t=l[c][0][e.textNodeName];r+=i+`\x3c!--${String(t).replace(/--/g,"- -").replace(/-$/,"- ")}--\x3e`,o=!0,n.pop();continue}if("?"===c[0]){const t=Qe(l[":@"],e,u),s="?xml"===c?"":i;let a=l[c][0][e.textNodeName];a=0!==a.length?" "+a:"",r+=s+`<${c}${a}${t}?>`,o=!0,n.pop();continue}let d=i;""!==d&&(d+=e.indentBy);const p=i+`<${c}${Qe(l[":@"],e,u)}`;let f;f=u?Ye(l[c],e):Ze(l[c],e,d,n,s),-1!==e.unpairedTags.indexOf(c)?e.suppressUnpairedNode?r+=p+">":r+=p+"/>":f&&0!==f.length||!e.suppressEmptyNode?f&&f.endsWith(">")?r+=p+`>${f}${i}</${c}>`:(r+=p+">",f&&""!==i&&(f.includes("/>")||f.includes("</"))?r+=i+e.indentBy+f+i:r+=f,r+=`</${c}>`):r+=p+"/>",o=!0,n.pop()}return r}function qe(t,e){if(!t||e.ignoreAttributes)return null;const i={};let n=!1;for(let s in t){if(!Object.prototype.hasOwnProperty.call(t,s))continue;i[s.startsWith(e.attributeNamePrefix)?s.substr(e.attributeNamePrefix.length):s]=t[s],n=!0}return n?i:null}function Ye(t,e){if(!Array.isArray(t))return null!=t?t.toString():"";let i="";for(let n=0;n<t.length;n++){const s=t[n],r=Ke(s);if(r===e.textNodeName)i+=s[r];else if(r===e.cdataPropName)i+=s[r][0][e.textNodeName];else if(r===e.commentPropName)i+=s[r][0][e.textNodeName];else{if(r&&"?"===r[0])continue;if(r){const t=Xe(s[":@"],e),n=Ye(s[r],e);n&&0!==n.length?i+=`<${r}${t}>${n}</${r}>`:i+=`<${r}${t}/>`}}}return i}function Xe(t,e){let i="";if(t&&!e.ignoreAttributes)for(let n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let s=t[n];!0===s&&e.suppressBooleanAttributes?i+=` ${n.substr(e.attributeNamePrefix.length)}`:i+=` ${n.substr(e.attributeNamePrefix.length)}="${s}"`}return i}function Ke(t){const e=Object.keys(t);for(let i=0;i<e.length;i++){const n=e[i];if(Object.prototype.hasOwnProperty.call(t,n)&&":@"!==n)return n}}function Qe(t,e,i){let n="";if(t&&!e.ignoreAttributes)for(let s in t){if(!Object.prototype.hasOwnProperty.call(t,s))continue;let r;i?r=t[s]:(r=e.attributeValueProcessor(s,t[s]),r=ti(r,e)),!0===r&&e.suppressBooleanAttributes?n+=` ${s.substr(e.attributeNamePrefix.length)}`:n+=` ${s.substr(e.attributeNamePrefix.length)}="${r}"`}return n}function Je(t,e){if(!e||0===e.length)return!1;for(let i=0;i<e.length;i++)if(t.matches(e[i]))return!0;return!1}function ti(t,e){if(t&&t.length>0&&e.processEntities)for(let i=0;i<e.entities.length;i++){const n=e.entities[i];t=t.replace(n.regex,n.val)}return t}const ei={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(t,e){return e},attributeValueProcessor:function(t,e){return e},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&amp;"},{regex:new RegExp(">","g"),val:"&gt;"},{regex:new RegExp("<","g"),val:"&lt;"},{regex:new RegExp("'","g"),val:"&apos;"},{regex:new RegExp('"',"g"),val:"&quot;"}],processEntities:!0,stopNodes:[],oneListGroup:!1,maxNestedTags:100,jPath:!0};function ii(t){if(this.options=Object.assign({},ei,t),this.options.stopNodes&&Array.isArray(this.options.stopNodes)&&(this.options.stopNodes=this.options.stopNodes.map(t=>"string"==typeof t&&t.startsWith("*.")?".."+t.substring(2):t)),this.stopNodeExpressions=[],this.options.stopNodes&&Array.isArray(this.options.stopNodes))for(let t=0;t<this.options.stopNodes.length;t++){const e=this.options.stopNodes[t];"string"==typeof e?this.stopNodeExpressions.push(new me(e)):e instanceof me&&this.stopNodeExpressions.push(e)}var e;!0===this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn="function"==typeof(e=this.options.ignoreAttributes)?e:Array.isArray(e)?t=>{for(const i of e){if("string"==typeof i&&t===i)return!0;if(i instanceof RegExp&&i.test(t))return!0}}:()=>!1,this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=ri),this.processTextOrObjNode=ni,this.options.format?(this.indentate=si,this.tagEndChar=">\n",this.newLine="\n"):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}function ni(t,e,i,n){const s=this.extractAttributes(t);n.push(e,s);if(this.checkStopNode(n)){const s=this.buildRawContent(t),r=this.buildAttributesForStopNode(t);return n.pop(),this.buildObjectNode(s,e,r,i)}const r=this.j2x(t,i+1,n);return n.pop(),void 0!==t[this.options.textNodeName]&&1===Object.keys(t).length?this.buildTextValNode(t[this.options.textNodeName],e,r.attrStr,i,n):this.buildObjectNode(r.val,e,r.attrStr,i)}function si(t){return this.options.indentBy.repeat(t)}function ri(t){return!(!t.startsWith(this.options.attributeNamePrefix)||t===this.options.textNodeName)&&t.substr(this.attrPrefixLen)}ii.prototype.build=function(t){if(this.options.preserveOrder)return He(t,this.options);{Array.isArray(t)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(t={[this.options.arrayNodeName]:t});const e=new ye;return this.j2x(t,0,e).val}},ii.prototype.j2x=function(t,e,i){let n="",s="";if(this.options.maxNestedTags&&i.getDepth()>=this.options.maxNestedTags)throw new Error("Maximum nested tags exceeded");const r=this.options.jPath?i.toString():i,o=this.checkStopNode(i);for(let a in t)if(Object.prototype.hasOwnProperty.call(t,a))if(void 0===t[a])this.isAttribute(a)&&(s+="");else if(null===t[a])this.isAttribute(a)||a===this.options.cdataPropName?s+="":"?"===a[0]?s+=this.indentate(e)+"<"+a+"?"+this.tagEndChar:s+=this.indentate(e)+"<"+a+"/"+this.tagEndChar;else if(t[a]instanceof Date)s+=this.buildTextValNode(t[a],a,"",e,i);else if("object"!=typeof t[a]){const l=this.isAttribute(a);if(l&&!this.ignoreAttributesFn(l,r))n+=this.buildAttrPairStr(l,""+t[a],o);else if(!l)if(a===this.options.textNodeName){let e=this.options.tagValueProcessor(a,""+t[a]);s+=this.replaceEntitiesValue(e)}else{i.push(a);const n=this.checkStopNode(i);if(i.pop(),n){const i=""+t[a];s+=""===i?this.indentate(e)+"<"+a+this.closeTag(a)+this.tagEndChar:this.indentate(e)+"<"+a+">"+i+"</"+a+this.tagEndChar}else s+=this.buildTextValNode(t[a],a,"",e,i)}}else if(Array.isArray(t[a])){const n=t[a].length;let r="",o="";for(let l=0;l<n;l++){const n=t[a][l];if(void 0===n);else if(null===n)"?"===a[0]?s+=this.indentate(e)+"<"+a+"?"+this.tagEndChar:s+=this.indentate(e)+"<"+a+"/"+this.tagEndChar;else if("object"==typeof n)if(this.options.oneListGroup){i.push(a);const t=this.j2x(n,e+1,i);i.pop(),r+=t.val,this.options.attributesGroupName&&n.hasOwnProperty(this.options.attributesGroupName)&&(o+=t.attrStr)}else r+=this.processTextOrObjNode(n,a,e,i);else if(this.options.oneListGroup){let t=this.options.tagValueProcessor(a,n);t=this.replaceEntitiesValue(t),r+=t}else{i.push(a);const t=this.checkStopNode(i);if(i.pop(),t){const t=""+n;r+=""===t?this.indentate(e)+"<"+a+this.closeTag(a)+this.tagEndChar:this.indentate(e)+"<"+a+">"+t+"</"+a+this.tagEndChar}else r+=this.buildTextValNode(n,a,"",e,i)}}this.options.oneListGroup&&(r=this.buildObjectNode(r,a,o,e)),s+=r}else if(this.options.attributesGroupName&&a===this.options.attributesGroupName){const e=Object.keys(t[a]),i=e.length;for(let s=0;s<i;s++)n+=this.buildAttrPairStr(e[s],""+t[a][e[s]],o)}else s+=this.processTextOrObjNode(t[a],a,e,i);return{attrStr:n,val:s}},ii.prototype.buildAttrPairStr=function(t,e,i){return i||(e=this.options.attributeValueProcessor(t,""+e),e=this.replaceEntitiesValue(e)),this.options.suppressBooleanAttributes&&"true"===e?" "+t:" "+t+'="'+e+'"'},ii.prototype.extractAttributes=function(t){if(!t||"object"!=typeof t)return null;const e={};let i=!1;if(this.options.attributesGroupName&&t[this.options.attributesGroupName]){const n=t[this.options.attributesGroupName];for(let t in n){if(!Object.prototype.hasOwnProperty.call(n,t))continue;e[t.startsWith(this.options.attributeNamePrefix)?t.substring(this.options.attributeNamePrefix.length):t]=n[t],i=!0}}else for(let n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;const s=this.isAttribute(n);s&&(e[s]=t[n],i=!0)}return i?e:null},ii.prototype.buildRawContent=function(t){if("string"==typeof t)return t;if("object"!=typeof t||null===t)return String(t);if(void 0!==t[this.options.textNodeName])return t[this.options.textNodeName];let e="";for(let i in t){if(!Object.prototype.hasOwnProperty.call(t,i))continue;if(this.isAttribute(i))continue;if(this.options.attributesGroupName&&i===this.options.attributesGroupName)continue;const n=t[i];if(i===this.options.textNodeName)e+=n;else if(Array.isArray(n)){for(let t of n)if("string"==typeof t||"number"==typeof t)e+=`<${i}>${t}</${i}>`;else if("object"==typeof t&&null!==t){const n=this.buildRawContent(t),s=this.buildAttributesForStopNode(t);e+=""===n?`<${i}${s}/>`:`<${i}${s}>${n}</${i}>`}}else if("object"==typeof n&&null!==n){const t=this.buildRawContent(n),s=this.buildAttributesForStopNode(n);e+=""===t?`<${i}${s}/>`:`<${i}${s}>${t}</${i}>`}else e+=`<${i}>${n}</${i}>`}return e},ii.prototype.buildAttributesForStopNode=function(t){if(!t||"object"!=typeof t)return"";let e="";if(this.options.attributesGroupName&&t[this.options.attributesGroupName]){const i=t[this.options.attributesGroupName];for(let t in i){if(!Object.prototype.hasOwnProperty.call(i,t))continue;const n=t.startsWith(this.options.attributeNamePrefix)?t.substring(this.options.attributeNamePrefix.length):t,s=i[t];!0===s&&this.options.suppressBooleanAttributes?e+=" "+n:e+=" "+n+'="'+s+'"'}}else for(let i in t){if(!Object.prototype.hasOwnProperty.call(t,i))continue;const n=this.isAttribute(i);if(n){const s=t[i];!0===s&&this.options.suppressBooleanAttributes?e+=" "+n:e+=" "+n+'="'+s+'"'}}return e},ii.prototype.buildObjectNode=function(t,e,i,n){if(""===t)return"?"===e[0]?this.indentate(n)+"<"+e+i+"?"+this.tagEndChar:this.indentate(n)+"<"+e+i+this.closeTag(e)+this.tagEndChar;{let s="</"+e+this.tagEndChar,r="";return"?"===e[0]&&(r="?",s=""),!i&&""!==i||-1!==t.indexOf("<")?!1!==this.options.commentPropName&&e===this.options.commentPropName&&0===r.length?this.indentate(n)+`\x3c!--${t}--\x3e`+this.newLine:this.indentate(n)+"<"+e+i+r+this.tagEndChar+t+this.indentate(n)+s:this.indentate(n)+"<"+e+i+r+">"+t+s}},ii.prototype.closeTag=function(t){let e="";return-1!==this.options.unpairedTags.indexOf(t)?this.options.suppressUnpairedNode||(e="/"):e=this.options.suppressEmptyNode?"/":`></${t}`,e},ii.prototype.checkStopNode=function(t){if(!this.stopNodeExpressions||0===this.stopNodeExpressions.length)return!1;for(let e=0;e<this.stopNodeExpressions.length;e++)if(t.matches(this.stopNodeExpressions[e]))return!0;return!1},ii.prototype.buildTextValNode=function(t,e,i,n,s){if(!1!==this.options.cdataPropName&&e===this.options.cdataPropName){const e=String(t).replace(/\]\]>/g,"]]]]><![CDATA[>");return this.indentate(n)+`<![CDATA[${e}]]>`+this.newLine}if(!1!==this.options.commentPropName&&e===this.options.commentPropName){const e=String(t).replace(/--/g,"- -").replace(/-$/,"- ");return this.indentate(n)+`\x3c!--${e}--\x3e`+this.newLine}if("?"===e[0])return this.indentate(n)+"<"+e+i+"?"+this.tagEndChar;{let s=this.options.tagValueProcessor(e,t);return s=this.replaceEntitiesValue(s),""===s?this.indentate(n)+"<"+e+i+this.closeTag(e)+this.tagEndChar:this.indentate(n)+"<"+e+i+">"+s+"</"+e+this.tagEndChar}},ii.prototype.replaceEntitiesValue=function(t){if(t&&t.length>0&&this.options.processEntities)for(let e=0;e<this.options.entities.length;e++){const i=this.options.entities[e];t=t.replace(i.regex,i.val)}return t};class oi{}e(oi,"parser",new Ge({allowBooleanAttributes:!0,attributeNamePrefix:"",ignoreAttributes:!1,ignoreDeclaration:!0,ignorePiTags:!0,numberParseOptions:{leadingZeros:!0,hex:!0},parseAttributeValue:!0,preserveOrder:!1,processEntities:!1,removeNSPrefix:!0,trimValues:!0})),e(oi,"builder",new ii({attributeNamePrefix:"$",ignoreAttributes:!1,suppressBooleanAttributes:!1}));class ai extends ht{constructor(t,i){super(t),e(this,"onDisposed",new at),e(this,"onVertexFound",new at),e(this,"onVertexLost",new at),e(this,"onEnabled",new at),e(this,"components"),e(this,"workingPlane",null),e(this,"_pickedPoint",null),e(this,"_config"),e(this,"_enabled",!1),this.components=t,this.config={snapDistance:.25,showOnlyVertex:!1,...i},this.enabled=!1}set enabled(t){this._enabled=t,t||(this._pickedPoint=null),this.onEnabled.trigger(t)}get enabled(){return this._enabled}set config(t){this._config={...this._config,...t}}get config(){return this._config}dispose(){this.onVertexFound.reset(),this.onVertexLost.reset(),this.components=null,this.onDisposed.trigger(),this.onDisposed.reset()}async get(t){if(!this.enabled)return this._pickedPoint;const e=this.components.get(ma).get(t),i=await e.castRay();if(!i)return null!==this._pickedPoint&&(this.onVertexLost.trigger(),this._pickedPoint=null),this._pickedPoint;const n=i.point;return null!==this._pickedPoint&&this._pickedPoint.equals(n)||(this._pickedPoint=n.clone(),this.onVertexFound.trigger(this._pickedPoint)),this._pickedPoint}}class li{static join(t){const e={};for(const i of t)for(const t in i)if(e[t])for(const n of i[t])e[t].add(n);else e[t]=new Set(i[t]);return e}static intersect(t){if(0===t.length)return{};let e=li.clone(t[0]);for(let i=1;i<t.length;i++){const n=t[i],s={};for(const t in e)if(n[t]){const i=new Set;for(const s of e[t])n[t].has(s)&&i.add(s);i.size>0&&(s[t]=i)}e=s}return e}static clone(t){const e={};for(const i in t)e[i]=new Set(t[i]);return e}static remove(t,e,i=!1){i&&(t=li.clone(t));for(const i in e)if(t[i]){for(const n of e[i])t[i].delete(n);0===t[i].size&&delete t[i]}}static add(t,e,i=!1){i&&(t=li.clone(t));for(const i in e)if(t[i])for(const n of e[i])t[i].add(n);else t[i]=new Set(e[i])}static append(t,e,...i){let n=t[e];n||(n=new Set,t[e]=n);for(const t of i)n.add(t)}static isEqual(t,e){const i=Object.keys(t),n=Object.keys(e);if(i.length!==n.length)return!1;for(const n of i){if(!e[n])return!1;if(t[n].size!==e[n].size)return!1;for(const i of t[n])if(!e[n].has(i))return!1}return!0}static isEmpty(t){return 0===Object.values(t).reduce((t,e)=>t+e.size,0)}static toRaw(t){const e={};for(const i in t)e[i]=Array.from(t[i]);return e}static fromRaw(t){const e={};for(const i in t)e[i]=new Set(t[i]);return e}}class ci extends Map{constructor(t){super(t),e(this,"onItemSet",new at),e(this,"onItemUpdated",new at),e(this,"onItemDeleted",new at),e(this,"onCleared",new at),e(this,"guard",()=>!0)}clear(){super.clear(),this.onCleared.trigger()}set(t,e){const i=this.has(t);if(!(this.guard??(()=>!0))(t,e))return this;const n=super.set(t,e);return i?(this.onItemUpdated||(this.onItemUpdated=new at),this.onItemUpdated.trigger({key:t,value:e})):(this.onItemSet||(this.onItemSet=new at),this.onItemSet.trigger({key:t,value:e})),n}add(t){const e=_t.create();return this.set(e,t),e}delete(t){const e=super.delete(t);return e&&this.onItemDeleted.trigger(t),e}dispose(){this.clear(),this.onItemSet.reset(),this.onItemDeleted.reset(),this.onCleared.reset()}}class hi{static isEntry(t){return new Set(["Boolean","Color","Text","Number","Select","Vector3","TextSet","None"]).has(t.type)}static copySchema(t,e={}){for(const i in t){const n=t[i];this.isEntry(n)?e[i]=this.copyEntry(n):(e[i]={},this.copySchema(n,e[i]))}return e}static copyEntry(t){if("Boolean"===t.type){const e=t;return{type:e.type,value:e.value}}if("Color"===t.type){const e=t;return{type:e.type,value:e.value.clone()}}if("Text"===t.type){const e=t;return{type:e.type,value:e.value}}if("Number"===t.type){const e=t;return{type:e.type,value:e.value,min:e.min,max:e.max,interpolable:e.interpolable}}if("Select"===t.type){const e=t;return{type:e.type,value:e.value,multiple:e.multiple,options:new Set(e.options)}}if("Vector3"===t.type){const e=t;return{type:e.type,value:e.value.clone()}}if("TextSet"===t.type){const e=t;return{type:e.type,value:new Set(e.value)}}if("None"===t.type){const e=t;return{type:e.type,value:e.value}}throw new Error("Invalid entry!")}}class ui{constructor(){e(this,"list",new Set)}add(t){for(const e of t)this.list.add(e)}remove(t){for(const e of t)this.list.delete(e)}set(t){for(const e of this.list)e.enabled=t}reset(){for(const t of this.list)t.reset()}}class di{constructor(t,i,n,s){e(this,"_component"),e(this,"name"),e(this,"uuid"),this._component=t,this.name=n,this.uuid=s??_t.create();i.get(fi).list.set(this.uuid,this)}get controls(){return hi.copySchema(this._config)}set(t){for(const e in t)if(e in this){this[e]=t[e].value}}export(t=this._config,e={}){for(const i in t){const n=t[i];if(hi.isEntry(n))if("Color"===n.type){const{r:t,g:s,b:r}=n.value;e[i]={...n,value:{r:t,g:s,b:r}}}else if("Vector3"===n.type){const{x:t,y:s,z:r}=n.value;e[i]={...n,value:{x:t,y:s,z:r}}}else if("TextSet"===n.type){const t=Array.from(n.value);e[i]={...n,value:t}}else if("Select"===n.type){const t=Array.from(n.options);e[i]={...n,options:t}}else e[i]={...n};else e[i]={},this.export(n,e[i])}return e}import(t,e={},i=!0){for(const i in t){const n=t[i];if(hi.isEntry(n))if("Color"===n.type){const{r:t,g:s,b:r}=n.value;e[i]={...n,value:new o.Color(t,s,r)}}else if("Vector3"===n.type){const{x:t,y:s,z:r}=n.value;e[i]={...n,value:new o.Vector3(t,s,r)}}else"TextSet"===n.type?e[i]={...n,value:new Set(n.value)}:"Select"===n.type?e[i]={...n,options:new Set(n.options)}:e[i]={...n};else e[i]={},this.import(n,e[i],!1)}i&&this.set(e)}}const pi=class t extends ht{constructor(i){super(i),e(this,"list",new n),e(this,"enabled",!0),i.add(t.uuid,this)}};e(pi,"uuid","b8c764e0-6b24-4e77-9a32-35fa728ee5b4");let fi=pi;class mi{constructor(t){e(this,"_event"),e(this,"_position",new o.Vector2),e(this,"onDisposed",new at),e(this,"updateMouseInfo",t=>{this._event=t}),this.dom=t,this.setupEvents(!0)}get position(){return this.updatePosition(!1),this._position.clone()}get rawPosition(){return this.updatePosition(!0),this._position.clone()}dispose(){this.setupEvents(!1),this.onDisposed.trigger(),this.onDisposed.reset()}updatePosition(t){if(this._event){const e=this.dom.getBoundingClientRect();this._position.x=this.getPositionX(e,this._event,t),this._position.y=this.getPositionY(e,this._event,t)}}getPositionY(t,e,i){const n=this.getDataObject(e);return i?n.clientY:-(n.clientY-t.top)/(t.bottom-t.top)*2+1}getPositionX(t,e,i){const n=this.getDataObject(e);return i?n.clientX:(n.clientX-t.left)/(t.right-t.left)*2-1}getDataObject(t){return t instanceof MouseEvent?t:t.touches[0]}setupEvents(t){t?(this.dom.addEventListener("pointermove",this.updateMouseInfo),this.dom.addEventListener("touchstart",this.updateMouseInfo)):(this.dom.removeEventListener("pointermove",this.updateMouseInfo),this.dom.removeEventListener("touchstart",this.updateMouseInfo))}}const gi=1.25,wi=32,yi=Math.pow(2,-24),_i=Symbol("SKIP_GENERATION"),bi={strategy:0,maxDepth:40,maxLeafSize:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null,[_i]:!1};function vi(t,e,i){return i.min.x=e[t],i.min.y=e[t+1],i.min.z=e[t+2],i.max.x=e[t+3],i.max.y=e[t+4],i.max.z=e[t+5],i}function xi(t){let e=-1,i=-1/0;for(let n=0;n<3;n++){const s=t[n+3]-t[n];s>i&&(i=s,e=n)}return e}function Ci(t,e){e.set(t)}function Si(t,e,i){let n,s;for(let r=0;r<3;r++){const o=r+3;n=t[r],s=e[r],i[r]=n<s?n:s,n=t[o],s=e[o],i[o]=n>s?n:s}}function Ai(t,e,i){for(let n=0;n<3;n++){const s=e[t+2*n],r=e[t+2*n+1],o=s-r,a=s+r;o<i[n]&&(i[n]=o),a>i[n+3]&&(i[n+3]=a)}}function Pi(t){const e=t[3]-t[0],i=t[4]-t[1],n=t[5]-t[2];return 2*(e*i+i*n+n*e)}function Ti(t,e){return 65535===e[t+15]}function Ei(t,e){return e[t+6]}function Mi(t,e){return e[t+14]}function Ii(t){return t+8}function zi(t,e){return t+8*e[t+6]}function Di(t,e){return e[t+7]}function ki(t){return t}function Bi(t,e,i,n,s){let r=1/0,o=1/0,a=1/0,l=-1/0,c=-1/0,h=-1/0,u=1/0,d=1/0,p=1/0,f=-1/0,m=-1/0,g=-1/0;const w=t.offset||0;for(let n=6*(e-w),s=6*(e+i-w);n<s;n+=6){const e=t[n+0],i=t[n+1],s=e-i,w=e+i;s<r&&(r=s),w>l&&(l=w),e<u&&(u=e),e>f&&(f=e);const y=t[n+2],_=t[n+3],b=y-_,v=y+_;b<o&&(o=b),v>c&&(c=v),y<d&&(d=y),y>m&&(m=y);const x=t[n+4],C=t[n+5],S=x-C,A=x+C;S<a&&(a=S),A>h&&(h=A),x<p&&(p=x),x>g&&(g=x)}n[0]=r,n[1]=o,n[2]=a,n[3]=l,n[4]=c,n[5]=h,s[0]=u,s[1]=d,s[2]=p,s[3]=f,s[4]=m,s[5]=g}const Oi=32,Ni=(t,e)=>t.candidate-e.candidate,Vi=new Array(Oi).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),Li=new Float32Array(6);class Fi{constructor(){this.boundingData=new Float32Array(6)}}let Ri,Ui,ji,$i;const Wi=Math.pow(2,32);function Gi(t){return"count"in t?1:1+Gi(t.left)+Gi(t.right)}function Hi(t,e,i){return Ri=new Float32Array(i),Ui=new Uint32Array(i),ji=new Uint16Array(i),$i=new Uint8Array(i),Zi(t,e)}function Zi(t,e){const i=t/4,n=t/2,s="count"in e,r=e.boundingData;for(let t=0;t<6;t++)Ri[i+t]=r[t];if(s)return e.buffer?($i.set(new Uint8Array(e.buffer),t),t+e.buffer.byteLength):(Ui[i+6]=e.offset,ji[n+14]=e.count,ji[n+15]=65535,t+wi);{const{left:n,right:s,splitAxis:r}=e;let o=Zi(t+wi,n);const a=o/wi-t/wi;if(a>Wi)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return Ui[i+6]=a,Ui[i+7]=r,Zi(o,s)}}function qi(t,e,i,n,s,r){const{maxDepth:o,verbose:a,maxLeafSize:l,strategy:c,onProgress:h}=s,u=t.primitiveBuffer,d=t.primitiveBufferStride,p=new Float32Array(6);let f=!1;const m=new Fi;return Bi(e,i,n,m.boundingData,p),function t(i,n,s,r=null,h=0){!f&&h>=o&&(f=!0,a&&console.warn(`BVH: Max depth of ${o} reached when generating BVH. Consider increasing maxDepth.`));if(s<=l||h>=o)return g(n+s),i.offset=n,i.count=s,i;const m=function(t,e,i,n,s,r){let o=-1,a=0;if(0===r)o=xi(e),-1!==o&&(a=(e[o]+e[o+3])/2);else if(1===r)o=xi(t),-1!==o&&(a=function(t,e,i,n){let s=0;const r=t.offset;for(let o=e,a=e+i;o<a;o++)s+=t[6*(o-r)+2*n];return s/i}(i,n,s,o));else if(2===r){const r=Pi(t);let l=gi*s;const c=i.offset||0,h=6*(n-c),u=6*(n+s-c);for(let t=0;t<3;t++){const n=e[t],c=(e[t+3]-n)/Oi;if(s<8){const e=[...Vi];e.length=s;let n=0;for(let s=h;s<u;s+=6,n++){const r=e[n];r.candidate=i[s+2*t],r.count=0;const{bounds:o,leftCacheBounds:a,rightCacheBounds:l}=r;for(let t=0;t<3;t++)l[t]=1/0,l[t+3]=-1/0,a[t]=1/0,a[t+3]=-1/0,o[t]=1/0,o[t+3]=-1/0;Ai(s,i,o)}e.sort(Ni);let c=s;for(let t=0;t<c;t++){const i=e[t];for(;t+1<c&&e[t+1].candidate===i.candidate;)e.splice(t+1,1),c--}for(let n=h;n<u;n+=6){const s=i[n+2*t];for(let t=0;t<c;t++){const r=e[t];s>=r.candidate?Ai(n,i,r.rightCacheBounds):(Ai(n,i,r.leftCacheBounds),r.count++)}}for(let i=0;i<c;i++){const n=e[i],c=n.count,h=s-n.count,u=n.leftCacheBounds,d=n.rightCacheBounds;let p=0;0!==c&&(p=Pi(u)/r);let f=0;0!==h&&(f=Pi(d)/r);const m=1+gi*(p*c+f*h);m<l&&(o=t,l=m,a=n.candidate)}}else{for(let t=0;t<Oi;t++){const e=Vi[t];e.count=0,e.candidate=n+c+t*c;const i=e.bounds;for(let t=0;t<3;t++)i[t]=1/0,i[t+3]=-1/0}for(let e=h;e<u;e+=6){let s=~~((i[e+2*t]-n)/c);s>=Oi&&(s=31);const r=Vi[s];r.count++,Ai(e,i,r.bounds)}const e=Vi[31];Ci(e.bounds,e.rightCacheBounds);for(let t=30;t>=0;t--){const e=Vi[t],i=Vi[t+1];Si(e.bounds,i.rightCacheBounds,e.rightCacheBounds)}let d=0;for(let e=0;e<31;e++){const i=Vi[e],n=i.count,c=i.bounds,h=Vi[e+1].rightCacheBounds;0!==n&&(0===d?Ci(c,Li):Si(c,Li,Li)),d+=n;let u=0,p=0;0!==d&&(u=Pi(Li)/r);const f=s-d;0!==f&&(p=Pi(h)/r);const m=1+gi*(u*d+p*f);m<l&&(o=t,l=m,a=i.candidate)}}}}else console.warn(`BVH: Invalid build strategy value ${r} used.`);return{axis:o,pos:a}}(i.boundingData,r,e,n,s,c);if(-1===m.axis)return g(n+s),i.offset=n,i.count=s,i;const w=function(t,e,i,n,s,r){let o=n,a=n+s-1;const l=r.pos,c=2*r.axis,h=i.offset||0;for(;;){for(;o<=a&&i[6*(o-h)+c]<l;)o++;for(;o<=a&&i[6*(a-h)+c]>=l;)a--;if(!(o<a))return o;for(let i=0;i<e;i++){let n=t[o*e+i];t[o*e+i]=t[a*e+i],t[a*e+i]=n}for(let t=0;t<6;t++){const e=o-h,n=a-h,s=i[6*e+t];i[6*e+t]=i[6*n+t],i[6*n+t]=s}o++,a--}}(u,d,e,n,s,m);if(w===n||w===n+s)g(n+s),i.offset=n,i.count=s;else{i.splitAxis=m.axis;const r=new Fi,o=n,a=w-n;i.left=r,Bi(e,o,a,r.boundingData,p),t(r,o,a,p,h+1);const l=new Fi,c=w,u=s-a;i.right=l,Bi(e,c,u,l.boundingData,p),t(l,c,u,p,h+1)}return i}(m,i,n,p),m;function g(t){h&&h((t-r.offset)/r.count)}}function Yi(t,e){const i=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,n=t.getRootRanges(e.range),s=n[0],r=n[n.length-1],o={offset:s.offset,count:r.offset+r.count-s.offset},a=new Float32Array(6*o.count);a.offset=o.offset,t.computePrimitiveBounds(o.offset,o.count,a),t._roots=n.map(n=>{const s=qi(t,a,n.offset,n.count,e,o),r=Gi(s),l=new i(wi*r);return Hi(0,s,l),l})}class Xi{constructor(t){this._getNewPrimitive=t,this._primitives=[]}getPrimitive(){const t=this._primitives;return 0===t.length?this._getNewPrimitive():t.pop()}releasePrimitive(t){this._primitives.push(t)}}class Ki{constructor(){this.float32Array=null,this.uint16Array=null,this.uint32Array=null;const t=[];let e=null;this.setBuffer=i=>{e&&t.push(e),e=i,this.float32Array=new Float32Array(i),this.uint16Array=new Uint16Array(i),this.uint32Array=new Uint32Array(i)},this.clearBuffer=()=>{e=null,this.float32Array=null,this.uint16Array=null,this.uint32Array=null,0!==t.length&&this.setBuffer(t.pop())}}}const Qi=new Ki;let Ji,tn;const en=[],nn=new Xi(()=>new a);function sn(t,e,i,n,s,r){Ji=nn.getPrimitive(),tn=nn.getPrimitive(),en.push(Ji,tn),Qi.setBuffer(t._roots[e]);const o=rn(0,t.geometry,i,n,s,r);Qi.clearBuffer(),nn.releasePrimitive(Ji),nn.releasePrimitive(tn),en.pop(),en.pop();const a=en.length;return a>0&&(tn=en[a-1],Ji=en[a-2]),o}function rn(t,e,i,n,s=null,r=0,o=0){const{float32Array:a,uint16Array:l,uint32Array:c}=Qi;let h=2*t;if(Ti(h,l)){const e=Ei(t,c),i=Mi(h,l);return vi(t,a,Ji),n(e,i,!1,o,r+t/8,Ji)}{let h=function(t){const{uint16Array:e,uint32Array:i}=Qi;let n=2*t;for(;!Ti(n,e);)n=2*(t=Ii(t));return Ei(t,i)},u=function(t){const{uint16Array:e,uint32Array:i}=Qi;let n=2*t;for(;!Ti(n,e);)n=2*(t=zi(t,i));return Ei(t,i)+Mi(n,e)};const d=Ii(t),p=zi(t,c);let f,m,g,w,y=d,_=p;if(s&&(g=Ji,w=tn,vi(y,a,g),vi(_,a,w),f=s(g),m=s(w),m<f)){y=p,_=d;const t=f;f=m,m=t,g=w}g||(g=Ji,vi(y,a,g));const b=i(g,Ti(2*y,l),f,o+1,r+y/8);let v;if(2===b){const t=h(y);v=n(t,u(y)-t,!0,o+1,r+y/8,g)}else v=b&&rn(y,e,i,n,s,r,o+1);if(v)return!0;w=tn,vi(_,a,w);const x=i(w,Ti(2*_,l),m,o+1,r+_/8);let C;if(2===x){const t=h(_);C=n(t,u(_)-t,!0,o+1,r+_/8,w)}else C=x&&rn(_,e,i,n,s,r,o+1);return!!C}}const on=new Qi.constructor,an=new Qi.constructor,ln=new Xi(()=>new a),cn=new a,hn=new a,un=new a,dn=new a;let pn=!1;function fn(t,e,i,n,s,r=0,o=0,a=0,l=0,c=null,h=!1){let u,d;h?(u=an,d=on):(u=on,d=an);const p=u.float32Array,f=u.uint32Array,m=u.uint16Array,g=d.float32Array,w=d.uint32Array,y=d.uint16Array,_=2*e,b=Ti(2*t,m),v=Ti(_,y);let x=!1;if(v&&b)x=h?s(Ei(e,w),Mi(2*e,y),Ei(t,f),Mi(2*t,m),l,o+e/8,a,r+t/8):s(Ei(t,f),Mi(2*t,m),Ei(e,w),Mi(2*e,y),a,r+t/8,l,o+e/8);else if(v){const c=ln.getPrimitive();vi(e,g,c),c.applyMatrix4(i);const u=Ii(t),d=zi(t,f);vi(u,p,cn),vi(d,p,hn);const m=c.intersectsBox(cn),w=c.intersectsBox(hn);x=m&&fn(e,u,n,i,s,o,r,l,a+1,c,!h)||w&&fn(e,d,n,i,s,o,r,l,a+1,c,!h),ln.releasePrimitive(c)}else{const u=Ii(e),d=zi(e,w);vi(u,g,un),vi(d,g,dn);const m=c.intersectsBox(un),y=c.intersectsBox(dn);if(m&&y)x=fn(t,u,i,n,s,r,o,a,l+1,c,h)||fn(t,d,i,n,s,r,o,a,l+1,c,h);else if(m)if(b)x=fn(t,u,i,n,s,r,o,a,l+1,c,h);else{const e=ln.getPrimitive();e.copy(un).applyMatrix4(i);const c=Ii(t),d=zi(t,f);vi(c,p,cn),vi(d,p,hn);const m=e.intersectsBox(cn),g=e.intersectsBox(hn);x=m&&fn(u,c,n,i,s,o,r,l,a+1,e,!h)||g&&fn(u,d,n,i,s,o,r,l,a+1,e,!h),ln.releasePrimitive(e)}else if(y)if(b)x=fn(t,d,i,n,s,r,o,a,l+1,c,h);else{const e=ln.getPrimitive();e.copy(dn).applyMatrix4(i);const c=Ii(t),u=zi(t,f);vi(c,p,cn),vi(u,p,hn);const m=e.intersectsBox(cn),g=e.intersectsBox(hn);x=m&&fn(d,c,n,i,s,o,r,l,a+1,e,!h)||g&&fn(d,u,n,i,s,o,r,l,a+1,e,!h),ln.releasePrimitive(e)}}return x}const mn=new a,gn=new Float32Array(6);class wn{constructor(){this._roots=null,this.primitiveBuffer=null,this.primitiveBufferStride=null}init(t){Yi(this,t={...bi,...t})}getRootRanges(){throw new Error("BVH: getRootRanges() not implemented")}writePrimitiveBounds(){throw new Error("BVH: writePrimitiveBounds() not implemented")}writePrimitiveRangeBounds(t,e,i,n){let s=1/0,r=1/0,o=1/0,a=-1/0,l=-1/0,c=-1/0;for(let i=t,n=t+e;i<n;i++){this.writePrimitiveBounds(i,gn,0);const[t,e,n,h,u,d]=gn;t<s&&(s=t),h>a&&(a=h),e<r&&(r=e),u>l&&(l=u),n<o&&(o=n),d>c&&(c=d)}return i[n+0]=s,i[n+1]=r,i[n+2]=o,i[n+3]=a,i[n+4]=l,i[n+5]=c,i}computePrimitiveBounds(t,e,i){const n=i.offset||0;for(let s=t,r=t+e;s<r;s++){this.writePrimitiveBounds(s,gn,0);const[t,e,r,o,a,l]=gn,c=(t+o)/2,h=(e+a)/2,u=(r+l)/2,d=(o-t)/2,p=(a-e)/2,f=(l-r)/2,m=6*(s-n);i[m+0]=c,i[m+1]=d+(Math.abs(c)+d)*yi,i[m+2]=h,i[m+3]=p+(Math.abs(h)+p)*yi,i[m+4]=u,i[m+5]=f+(Math.abs(u)+f)*yi}return i}shiftPrimitiveOffsets(t){const e=this._indirectBuffer;if(e)for(let i=0,n=e.length;i<n;i++)e[i]+=t;else{const e=this._roots;for(let i=0;i<e.length;i++){const n=e[i],s=new Uint32Array(n),r=new Uint16Array(n),o=n.byteLength/wi;for(let e=0;e<o;e++){const i=8*e;Ti(2*i,r)&&(s[i+6]+=t)}}}}traverse(t,e=0){const i=this._roots[e],n=new Uint32Array(i),s=new Uint16Array(i);!function e(r,o=0){const a=2*r,l=Ti(a,s);if(l){const e=n[r+6],c=s[a+14];t(o,l,new Float32Array(i,4*r,6),e,c)}else{const s=Ii(r),a=zi(r,n),c=Di(r,n);t(o,l,new Float32Array(i,4*r,6),c)||(e(s,o+1),e(a,o+1))}}(0)}refit(){const t=this._roots;for(let e=0,i=t.length;e<i;e++){const i=t[e],n=new Uint32Array(i),s=new Uint16Array(i),r=new Float32Array(i);for(let t=i.byteLength/wi-1;t>=0;t--){const e=8*t,i=2*e;if(Ti(i,s)){const t=Ei(e,n),o=Mi(i,s);this.writePrimitiveRangeBounds(t,o,gn,0),r.set(gn,e)}else{const t=Ii(e),i=zi(e,n);for(let n=0;n<3;n++){const s=r[t+n],o=r[t+n+3],a=r[i+n],l=r[i+n+3];r[e+n]=s<a?s:a,r[e+n+3]=o>l?o:l}}}}}getBoundingBox(t){t.makeEmpty();return this._roots.forEach(e=>{vi(0,new Float32Array(e),mn),t.union(mn)}),t}shapecast(t){let{boundsTraverseOrder:e,intersectsBounds:i,intersectsRange:n,intersectsPrimitive:s,scratchPrimitive:r,iterate:o}=t;if(n&&s){const t=n;n=(e,i,n,a,l)=>!!t(e,i,n,a,l)||o(e,i,this,s,n,a,r)}else n||(n=s?(t,e,i,n)=>o(t,e,this,s,i,n,r):(t,e,i)=>i);let a=!1,l=0;const c=this._roots;for(let t=0,s=c.length;t<s;t++){const s=c[t];if(a=sn(this,t,i,n,e,l),a)break;l+=s.byteLength/wi}return a}bvhcast(t,e,i){let{intersectsRanges:n}=i;return function(t,e,i,n){if(pn)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");pn=!0;const s=t._roots,r=e._roots;let o,a=0,c=0;const h=(new l).copy(i).invert();for(let t=0,e=s.length;t<e;t++){on.setBuffer(s[t]),c=0;const e=ln.getPrimitive();vi(ki(0),on.float32Array,e),e.applyMatrix4(h);for(let t=0,s=r.length;t<s&&(an.setBuffer(r[t]),o=fn(0,0,i,h,n,a,c,0,0,e),an.clearBuffer(),c+=r[t].byteLength/wi,!o);t++);if(ln.releasePrimitive(e),on.clearBuffer(),a+=s[t].byteLength/wi,o)break}return pn=!1,o}(this,t,e,n)}}function yn(t){return t.index?t.index.count:t.attributes.position.count}function _n(t){return yn(t)/3}function bn(t,e){if(!t.index){const i=t.attributes.position.count,n=function(t,e=ArrayBuffer){return t>65535?new Uint32Array(new e(4*t)):new Uint16Array(new e(2*t))}(i,e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer);t.setIndex(new c(n,1));for(let t=0;t<i;t++)n[t]=t}}function vn(t,e,i){const n=function(t,e,i){const n=yn(t)/i,s=e||t.drawRange,r=s.start/i,o=(s.start+s.count)/i,a=Math.max(0,r),l=Math.min(n,o)-a;return{offset:Math.floor(a),count:Math.floor(l)}}(t,e,i),s=function(t,e){return t.groups.map(t=>({offset:t.start/e,count:t.count/e}))}(t,i);if(!s.length)return[n];const r=[],o=n.offset,a=n.offset+n.count,l=yn(t)/i,c=[];for(const t of s){const{offset:e,count:i}=t,n=e,s=e+(isFinite(i)?i:l-e);n<a&&s>o&&(c.push({pos:Math.max(o,n),isStart:!0}),c.push({pos:Math.min(a,s),isStart:!1}))}c.sort((t,e)=>t.pos!==e.pos?t.pos-e.pos:"end"===t.type?-1:1);let h=0,u=null;for(const t of c){const e=t.pos;0!==h&&e!==u&&r.push({offset:u,count:e-u}),h+=t.isStart?1:-1,u=e}return r}class xn extends wn{get indirect(){return!!this._indirectBuffer}get primitiveStride(){return null}get primitiveBufferStride(){return this.indirect?1:this.primitiveStride}set primitiveBufferStride(t){}get primitiveBuffer(){return this.indirect?this._indirectBuffer:this.geometry.index.array}set primitiveBuffer(t){}constructor(t,e={}){if(!t.isBufferGeometry)throw new Error("BVH: Only BufferGeometries are supported.");if(t.index&&t.index.isInterleavedBufferAttribute)throw new Error("BVH: InterleavedBufferAttribute is not supported for the index attribute.");if(e.useSharedArrayBuffer&&"undefined"==typeof SharedArrayBuffer)throw new Error("BVH: SharedArrayBuffer is not available.");super(),this.geometry=t,this.resolvePrimitiveIndex=e.indirect?t=>this._indirectBuffer[t]:t=>t,this.primitiveBuffer=null,this.primitiveBufferStride=null,this._indirectBuffer=null,(e={...bi,...e})[_i]||this.init(e)}init(t){const{geometry:e,primitiveStride:i}=this;if(t.indirect){const n=function(t,e){const i=t[t.length-1],n=i.offset+i.count>65536,s=t.reduce((t,e)=>t+e.count,0),r=n?4:2,o=e?new SharedArrayBuffer(s*r):new ArrayBuffer(s*r),a=n?new Uint32Array(o):new Uint16Array(o);let l=0;for(let e=0;e<t.length;e++){const{offset:i,count:n}=t[e];for(let t=0;t<n;t++)a[l+t]=i+t;l+=n}return a}(vn(e,t.range,i),t.useSharedArrayBuffer);this._indirectBuffer=n}else bn(e,t);super.init(t),!e.boundingBox&&t.setBoundingBox&&(e.boundingBox=this.getBoundingBox(new a))}getRootRanges(t){return this.indirect?[{offset:0,count:this._indirectBuffer.length}]:vn(this.geometry,t,this.primitiveStride)}raycastObject3D(){throw new Error("BVH: raycastObject3D() not implemented")}}class Cn{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(t,e){let i=1/0,n=-1/0;for(let s=0,r=t.length;s<r;s++){const r=t[s][e];i=r<i?r:i,n=r>n?r:n}this.min=i,this.max=n}setFromPoints(t,e){let i=1/0,n=-1/0;for(let s=0,r=e.length;s<r;s++){const r=e[s],o=t.dot(r);i=o<i?o:i,n=o>n?o:n}this.min=i,this.max=n}isSeparated(t){return this.min>t.max||t.min>this.max}}Cn.prototype.setFromBox=function(){const t=new h;return function(e,i){const n=i.min,s=i.max;let r=1/0,o=-1/0;for(let i=0;i<=1;i++)for(let a=0;a<=1;a++)for(let l=0;l<=1;l++){t.x=n.x*i+s.x*(1-i),t.y=n.y*a+s.y*(1-a),t.z=n.z*l+s.z*(1-l);const c=e.dot(t);r=Math.min(c,r),o=Math.max(c,o)}this.min=r,this.max=o}}();const Sn=function(){const t=new h,e=new h,i=new h;return function(n,s,r){const o=n.start,a=t,l=s.start,c=e;i.subVectors(o,l),t.subVectors(n.end,n.start),e.subVectors(s.end,s.start);const h=i.dot(c),u=c.dot(a),d=c.dot(c),p=i.dot(a),f=a.dot(a)*d-u*u;let m,g;m=0!==f?(h*u-p*d)/f:0,g=(h+m*u)/d,r.x=m,r.y=g}}(),An=function(){const t=new p,e=new h,i=new h;return function(n,s,r,o){Sn(n,s,t);let a=t.x,l=t.y;if(a>=0&&a<=1&&l>=0&&l<=1)return n.at(a,r),void s.at(l,o);if(a>=0&&a<=1)return l<0?s.at(0,o):s.at(1,o),void n.closestPointToPoint(o,!0,r);if(l>=0&&l<=1)return a<0?n.at(0,r):n.at(1,r),void s.closestPointToPoint(r,!0,o);{let t,c;t=a<0?n.start:n.end,c=l<0?s.start:s.end;const h=e,u=i;return n.closestPointToPoint(c,!0,e),s.closestPointToPoint(t,!0,i),h.distanceToSquared(c)<=u.distanceToSquared(t)?(r.copy(h),void o.copy(c)):(r.copy(t),void o.copy(u))}}}(),Pn=function(){const t=new h,e=new h,i=new d,n=new u;return function(s,r){const{radius:o,center:a}=s,{a:l,b:c,c:h}=r;n.start=l,n.end=c;if(n.closestPointToPoint(a,!0,t).distanceTo(a)<=o)return!0;n.start=l,n.end=h;if(n.closestPointToPoint(a,!0,t).distanceTo(a)<=o)return!0;n.start=c,n.end=h;if(n.closestPointToPoint(a,!0,t).distanceTo(a)<=o)return!0;const u=r.getPlane(i);if(Math.abs(u.distanceToPoint(a))<=o){const t=u.projectPoint(a,e);if(r.containsPoint(t))return!0}return!1}}(),Tn=["x","y","z"],En=1e-15;function Mn(t){return Math.abs(t)<En}class In extends f{constructor(...t){super(...t),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new h),this.satBounds=new Array(4).fill().map(()=>new Cn),this.points=[this.a,this.b,this.c],this.plane=new d,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new u,this.needsUpdate=!0}intersectsSphere(t){return Pn(t,this)}update(){const t=this.a,e=this.b,i=this.c,n=this.points,s=this.satAxes,r=this.satBounds,o=s[0],a=r[0];this.getNormal(o),a.setFromPoints(o,n);const l=s[1],c=r[1];l.subVectors(t,e),c.setFromPoints(l,n);const h=s[2],u=r[2];h.subVectors(e,i),u.setFromPoints(h,n);const d=s[3],p=r[3];d.subVectors(i,t),p.setFromPoints(d,n);const f=l.length(),m=h.length(),g=d.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,f<En?m<En||g<En?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(i)):m<En?g<En?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(t)):g<En&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(i),this.degenerateSegment.end.copy(e)),this.plane.setFromNormalAndCoplanarPoint(o,t),this.needsUpdate=!1}}In.prototype.closestPointToSegment=function(){const t=new h,e=new h,i=new u;return function(n,s=null,r=null){const{start:o,end:a}=n,l=this.points;let c,h=1/0;for(let o=0;o<3;o++){const a=(o+1)%3;i.start.copy(l[o]),i.end.copy(l[a]),An(i,n,t,e),c=t.distanceToSquared(e),c<h&&(h=c,s&&s.copy(t),r&&r.copy(e))}return this.closestPointToPoint(o,t),c=o.distanceToSquared(t),c<h&&(h=c,s&&s.copy(t),r&&r.copy(o)),this.closestPointToPoint(a,t),c=a.distanceToSquared(t),c<h&&(h=c,s&&s.copy(t),r&&r.copy(a)),Math.sqrt(h)}}(),In.prototype.intersectsTriangle=function(){const t=new In,e=new Cn,i=new Cn,n=new h,s=new h,r=new h,o=new h,a=new u,l=new u,c=new h,d=new p,f=new p;function m(t,s,r,a){const l=n;t.isDegenerateIntoPoint||t.isDegenerateIntoSegment?l.copy(s.plane.normal):l.copy(t.plane.normal);const c=t.satBounds,h=t.satAxes;for(let n=1;n<4;n++){const r=c[n],a=h[n];if(e.setFromPoints(a,s.points),r.isSeparated(e))return!1;if(o.copy(l).cross(a),e.setFromPoints(o,t.points),i.setFromPoints(o,s.points),e.isSeparated(i))return!1}const u=s.satBounds,d=s.satAxes;for(let n=1;n<4;n++){const r=u[n],a=d[n];if(e.setFromPoints(a,t.points),r.isSeparated(e))return!1;if(o.crossVectors(l,a),e.setFromPoints(o,t.points),i.setFromPoints(o,s.points),e.isSeparated(i))return!1}return r&&(a||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),r.start.set(0,0,0),r.end.set(0,0,0)),!0}function g(t,e,i,n,s,r,o,a,l,c,h){let u=o/(o-a);c.x=n+(s-n)*u,h.start.subVectors(e,t).multiplyScalar(u).add(t),u=o/(o-l),c.y=n+(r-n)*u,h.end.subVectors(i,t).multiplyScalar(u).add(t)}function w(t,e,i,n,s,r,o,a,l,c,h){if(s>0)g(t.c,t.a,t.b,n,e,i,l,o,a,c,h);else if(r>0)g(t.b,t.a,t.c,i,e,n,a,o,l,c,h);else if(a*l>0||0!=o)g(t.a,t.b,t.c,e,i,n,o,a,l,c,h);else if(0!=a)g(t.b,t.a,t.c,i,e,n,a,o,l,c,h);else{if(0==l)return!0;g(t.c,t.a,t.b,n,e,i,l,o,a,c,h)}return!1}function y(t,e,i,s){const r=e.degenerateSegment,o=t.plane.distanceToPoint(r.start),a=t.plane.distanceToPoint(r.end);return Mn(o)?Mn(a)?m(t,e,i,s):(i&&(i.start.copy(r.start),i.end.copy(r.start)),t.containsPoint(r.start)):Mn(a)?(i&&(i.start.copy(r.end),i.end.copy(r.end)),t.containsPoint(r.end)):null!=t.plane.intersectLine(r,n)&&(i&&(i.start.copy(n),i.end.copy(n)),t.containsPoint(n))}function _(t,e,i){const n=e.a;return!(!Mn(t.plane.distanceToPoint(n))||!t.containsPoint(n))&&(i&&(i.start.copy(n),i.end.copy(n)),!0)}function b(t,e,i){const s=t.degenerateSegment,r=e.a;return s.closestPointToPoint(r,!0,n),r.distanceToSquared(n)<1e-30&&(i&&(i.start.copy(r),i.end.copy(r)),!0)}return function(e,i=null,o=!1){this.needsUpdate&&this.update(),e.isExtendedTriangle?e.needsUpdate&&e.update():(t.copy(e),t.update(),e=t);const h=function(t,e,i,o){if(t.isDegenerateIntoSegment){if(e.isDegenerateIntoSegment){const o=t.degenerateSegment,a=e.degenerateSegment,l=s,c=r;o.delta(l),a.delta(c);const h=n.subVectors(a.start,o.start),u=l.x*c.y-l.y*c.x;if(Mn(u))return!1;const d=(h.x*c.y-h.y*c.x)/u,p=-(l.x*h.y-l.y*h.x)/u;return!(d<0||d>1||p<0||p>1)&&(!!Mn(o.start.z+l.z*d-(a.start.z+c.z*p))&&(i&&(i.start.copy(o.start).addScaledVector(l,d),i.end.copy(o.start).addScaledVector(l,d)),!0))}return e.isDegenerateIntoPoint?b(t,e,i):y(e,t,i,o)}return t.isDegenerateIntoPoint?e.isDegenerateIntoPoint?e.a.distanceToSquared(t.a)<1e-30&&(i&&(i.start.copy(t.a),i.end.copy(t.a)),!0):e.isDegenerateIntoSegment?b(e,t,i):_(e,t,i):e.isDegenerateIntoPoint?_(t,e,i):e.isDegenerateIntoSegment?y(t,e,i,o):void 0}(this,e,i,o);if(void 0!==h)return h;const u=this.plane,p=e.plane;let g=p.distanceToPoint(this.a),v=p.distanceToPoint(this.b),x=p.distanceToPoint(this.c);Mn(g)&&(g=0),Mn(v)&&(v=0),Mn(x)&&(x=0);const C=g*v,S=g*x;if(C>0&&S>0)return!1;let A=u.distanceToPoint(e.a),P=u.distanceToPoint(e.b),T=u.distanceToPoint(e.c);Mn(A)&&(A=0),Mn(P)&&(P=0),Mn(T)&&(T=0);const E=A*P,M=A*T;if(E>0&&M>0)return!1;s.copy(u.normal),r.copy(p.normal);const I=s.cross(r);let z=0,D=Math.abs(I.x);const k=Math.abs(I.y);k>D&&(D=k,z=1);Math.abs(I.z)>D&&(z=2);const B=Tn[z],O=this.a[B],N=this.b[B],V=this.c[B],L=e.a[B],F=e.b[B],R=e.c[B];if(w(this,O,N,V,C,S,g,v,x,d,a))return m(this,e,i,o);if(w(e,L,F,R,E,M,A,P,T,f,l))return m(this,e,i,o);if(d.y<d.x){const t=d.y;d.y=d.x,d.x=t,c.copy(a.start),a.start.copy(a.end),a.end.copy(c)}if(f.y<f.x){const t=f.y;f.y=f.x,f.x=t,c.copy(l.start),l.start.copy(l.end),l.end.copy(c)}return!(d.y<f.x||f.y<d.x)&&(i&&(f.x>d.x?i.start.copy(l.start):i.start.copy(a.start),f.y<d.y?i.end.copy(l.end):i.end.copy(a.end)),!0)}}(),In.prototype.distanceToPoint=function(){const t=new h;return function(e){return this.closestPointToPoint(e,t),e.distanceTo(t)}}(),In.prototype.distanceToTriangle=function(){const t=new h,e=new h,i=["a","b","c"],n=new u,s=new u;return function(r,o=null,a=null){const l=o||a?n:null;if(this.intersectsTriangle(r,l))return(o||a)&&(o&&l.getCenter(o),a&&l.getCenter(a)),0;let c=1/0;for(let e=0;e<3;e++){let n;const s=i[e],l=r[s];this.closestPointToPoint(l,t),n=l.distanceToSquared(t),n<c&&(c=n,o&&o.copy(t),a&&a.copy(l));const h=this[s];r.closestPointToPoint(h,t),n=h.distanceToSquared(t),n<c&&(c=n,o&&o.copy(h),a&&a.copy(t))}for(let l=0;l<3;l++){const h=i[l],u=i[(l+1)%3];n.set(this[h],this[u]);for(let l=0;l<3;l++){const h=i[l],u=i[(l+1)%3];s.set(r[h],r[u]),An(n,s,t,e);const d=t.distanceToSquared(e);d<c&&(c=d,o&&o.copy(t),a&&a.copy(e))}}return Math.sqrt(c)}}();class zn{constructor(t,e,i){this.isOrientedBox=!0,this.min=new h,this.max=new h,this.matrix=new l,this.invMatrix=new l,this.points=new Array(8).fill().map(()=>new h),this.satAxes=new Array(3).fill().map(()=>new h),this.satBounds=new Array(3).fill().map(()=>new Cn),this.alignedSatBounds=new Array(3).fill().map(()=>new Cn),this.needsUpdate=!1,t&&this.min.copy(t),e&&this.max.copy(e),i&&this.matrix.copy(i)}set(t,e,i){this.min.copy(t),this.max.copy(e),this.matrix.copy(i),this.needsUpdate=!0}copy(t){this.min.copy(t.min),this.max.copy(t.max),this.matrix.copy(t.matrix),this.needsUpdate=!0}}zn.prototype.update=function(){return function(){const t=this.matrix,e=this.min,i=this.max,n=this.points;for(let s=0;s<=1;s++)for(let r=0;r<=1;r++)for(let o=0;o<=1;o++){const a=n[1*s|2*r|4*o];a.x=s?i.x:e.x,a.y=r?i.y:e.y,a.z=o?i.z:e.z,a.applyMatrix4(t)}const s=this.satBounds,r=this.satAxes,o=n[0];for(let t=0;t<3;t++){const e=r[t],i=s[t],a=n[1<<t];e.subVectors(o,a),i.setFromPoints(e,n)}const a=this.alignedSatBounds;a[0].setFromPointsField(n,"x"),a[1].setFromPointsField(n,"y"),a[2].setFromPointsField(n,"z"),this.invMatrix.copy(this.matrix).invert(),this.needsUpdate=!1}}(),zn.prototype.intersectsBox=function(){const t=new Cn;return function(e){this.needsUpdate&&this.update();const i=e.min,n=e.max,s=this.satBounds,r=this.satAxes,o=this.alignedSatBounds;if(t.min=i.x,t.max=n.x,o[0].isSeparated(t))return!1;if(t.min=i.y,t.max=n.y,o[1].isSeparated(t))return!1;if(t.min=i.z,t.max=n.z,o[2].isSeparated(t))return!1;for(let i=0;i<3;i++){const n=r[i],o=s[i];if(t.setFromBox(n,e),o.isSeparated(t))return!1}return!0}}(),zn.prototype.intersectsTriangle=function(){const t=new In,e=new Array(3),i=new Cn,n=new Cn,s=new h;return function(r){this.needsUpdate&&this.update(),r.isExtendedTriangle?r.needsUpdate&&r.update():(t.copy(r),t.update(),r=t);const o=this.satBounds,a=this.satAxes;e[0]=r.a,e[1]=r.b,e[2]=r.c;for(let t=0;t<3;t++){const n=o[t],s=a[t];if(i.setFromPoints(s,e),n.isSeparated(i))return!1}const l=r.satBounds,c=r.satAxes,h=this.points;for(let t=0;t<3;t++){const e=l[t],n=c[t];if(i.setFromPoints(n,h),e.isSeparated(i))return!1}for(let t=0;t<3;t++){const r=a[t];for(let t=0;t<4;t++){const o=c[t];if(s.crossVectors(r,o),i.setFromPoints(s,e),n.setFromPoints(s,h),i.isSeparated(n))return!1}}return!0}}(),zn.prototype.closestPointToPoint=function(){return function(t,e){return this.needsUpdate&&this.update(),e.copy(t).applyMatrix4(this.invMatrix).clamp(this.min,this.max).applyMatrix4(this.matrix),e}}(),zn.prototype.distanceToPoint=function(){const t=new h;return function(e){return this.closestPointToPoint(e,t),e.distanceTo(t)}}(),zn.prototype.distanceToBox=function(){const t=["x","y","z"],e=new Array(12).fill().map(()=>new u),i=new Array(12).fill().map(()=>new u),n=new h,s=new h;return function(r,o=0,a=null,l=null){if(this.needsUpdate&&this.update(),this.intersectsBox(r))return(a||l)&&(r.getCenter(s),this.closestPointToPoint(s,n),r.closestPointToPoint(n,s),a&&a.copy(n),l&&l.copy(s)),0;const c=o*o,h=r.min,u=r.max,d=this.points;let p=1/0;for(let t=0;t<8;t++){const e=d[t];s.copy(e).clamp(h,u);const i=e.distanceToSquared(s);if(i<p&&(p=i,a&&a.copy(e),l&&l.copy(s),i<c))return Math.sqrt(i)}let f=0;for(let n=0;n<3;n++)for(let s=0;s<=1;s++)for(let r=0;r<=1;r++){const o=(n+1)%3,a=(n+2)%3,l=1<<n|s<<o|r<<a,c=d[s<<o|r<<a],p=d[l];e[f].set(c,p);const m=t[n],g=t[o],w=t[a],y=i[f],_=y.start,b=y.end;_[m]=h[m],_[g]=s?h[g]:u[g],_[w]=r?h[w]:u[g],b[m]=u[m],b[g]=s?h[g]:u[g],b[w]=r?h[w]:u[g],f++}for(let t=0;t<=1;t++)for(let e=0;e<=1;e++)for(let i=0;i<=1;i++){s.x=t?u.x:h.x,s.y=e?u.y:h.y,s.z=i?u.z:h.z,this.closestPointToPoint(s,n);const r=s.distanceToSquared(n);if(r<p&&(p=r,a&&a.copy(n),l&&l.copy(s),r<c))return Math.sqrt(r)}for(let t=0;t<12;t++){const r=e[t];for(let t=0;t<12;t++){const e=i[t];An(r,e,n,s);const o=n.distanceToSquared(s);if(o<p&&(p=o,a&&a.copy(n),l&&l.copy(s),o<c))return Math.sqrt(o)}}return Math.sqrt(p)}}();class Dn extends Xi{constructor(){super(()=>new In)}}const kn=new Dn,Bn=new h,On=new h;const Nn=parseInt(w)>=169,Vn=parseInt(w)<=161,Ln=new h,Fn=new h,Rn=new h,Un=new p,jn=new p,$n=new p,Wn=new h,Gn=new h,Hn=new h,Zn=new h;function qn(t,e,i,n,s,r,o,a,l,c,u){Ln.fromBufferAttribute(e,r),Fn.fromBufferAttribute(e,o),Rn.fromBufferAttribute(e,a);const d=function(t,e,i,n,s,r,o,a){let l;if(l=r===m?t.intersectTriangle(n,i,e,!0,s):t.intersectTriangle(e,i,n,r!==g,s),null===l)return null;const c=t.origin.distanceTo(s);return c<o||c>a?null:{distance:c,point:s.clone()}}(t,Ln,Fn,Rn,Zn,l,c,u);if(d){if(n){Un.fromBufferAttribute(n,r),jn.fromBufferAttribute(n,o),$n.fromBufferAttribute(n,a),d.uv=new p;const t=f.getInterpolation(Zn,Ln,Fn,Rn,Un,jn,$n,d.uv);Nn||(d.uv=t)}if(s){Un.fromBufferAttribute(s,r),jn.fromBufferAttribute(s,o),$n.fromBufferAttribute(s,a),d.uv1=new p;const t=f.getInterpolation(Zn,Ln,Fn,Rn,Un,jn,$n,d.uv1);Nn||(d.uv1=t),Vn&&(d.uv2=d.uv1)}if(i){Wn.fromBufferAttribute(i,r),Gn.fromBufferAttribute(i,o),Hn.fromBufferAttribute(i,a),d.normal=new h;const e=f.getInterpolation(Zn,Ln,Fn,Rn,Wn,Gn,Hn,d.normal);d.normal.dot(t.direction)>0&&d.normal.multiplyScalar(-1),Nn||(d.normal=e)}const e={a:r,b:o,c:a,normal:new h,materialIndex:0};if(f.getNormal(Ln,Fn,Rn,e.normal),d.face=e,d.faceIndex=r,Nn){const t=new h;f.getBarycoord(Zn,Ln,Fn,Rn,t),d.barycoord=t}}return d}function Yn(t){return t&&t.isMaterial?t.side:t}function Xn(t,e,i,n,s,r,o){const a=3*n;let l=a+0,c=a+1,h=a+2;const{index:u,groups:d}=t;t.index&&(l=u.getX(l),c=u.getX(c),h=u.getX(h));const{position:p,normal:f,uv:m,uv1:g}=t.attributes;if(Array.isArray(e)){const t=3*n;for(let a=0,u=d.length;a<u;a++){const{start:u,count:w,materialIndex:y}=d[a];if(t>=u&&t<u+w){const t=qn(i,p,f,m,g,l,c,h,Yn(e[y]),r,o);if(t){if(t.faceIndex=n,t.face.materialIndex=y,!s)return t;s.push(t)}}}}else{const t=qn(i,p,f,m,g,l,c,h,Yn(e),r,o);if(t){if(t.faceIndex=n,t.face.materialIndex=0,!s)return t;s.push(t)}}return null}function Kn(t,e,i,n){const s=t.a,r=t.b,o=t.c;let a=e,l=e+1,c=e+2;i&&(a=i.getX(a),l=i.getX(l),c=i.getX(c)),s.x=n.getX(a),s.y=n.getY(a),s.z=n.getZ(a),r.x=n.getX(l),r.y=n.getY(l),r.z=n.getZ(l),o.x=n.getX(c),o.y=n.getY(c),o.z=n.getZ(c)}function Qn(t,e,i,n,s,r,o){const{geometry:a}=i,{index:l}=a,c=a.attributes.position;for(let i=t,a=e+t;i<a;i++){let t;if(t=i,Kn(o,3*t,l,c),o.needsUpdate=!0,n(o,t,s,r))return!0}return!1}function Jn(t,e=null){e&&Array.isArray(e)&&(e=new Set(e));const i=t.geometry,n=i.index?i.index.array:null,s=i.attributes.position;let r,o,a,l,c=0;const h=t._roots;for(let t=0,e=h.length;t<e;t++)r=h[t],o=new Uint32Array(r),a=new Uint16Array(r),l=new Float32Array(r),u(0,c),c+=r.byteLength;function u(t,i,r=!1){const c=2*t;if(Ti(c,a)){const e=Ei(t,o);let i=1/0,r=1/0,h=1/0,u=-1/0,d=-1/0,p=-1/0;for(let t=3*e,o=3*(e+Mi(c,a));t<o;t++){let e=n[t];const o=s.getX(e),a=s.getY(e),l=s.getZ(e);o<i&&(i=o),o>u&&(u=o),a<r&&(r=a),a>d&&(d=a),l<h&&(h=l),l>p&&(p=l)}return(l[t+0]!==i||l[t+1]!==r||l[t+2]!==h||l[t+3]!==u||l[t+4]!==d||l[t+5]!==p)&&(l[t+0]=i,l[t+1]=r,l[t+2]=h,l[t+3]=u,l[t+4]=d,l[t+5]=p,!0)}{const n=Ii(t),s=zi(t,o);let a=r,c=!1,h=!1;if(e){if(!a){const t=n/8+i/wi,r=s/8+i/wi;c=e.has(t),h=e.has(r),a=!c&&!h}}else c=!0,h=!0;const d=a||h;let p=!1;(a||c)&&(p=u(n,i,a));let f=!1;d&&(f=u(s,i,a));const m=p||f;if(m)for(let e=0;e<3;e++){const i=n+e,r=s+e,o=l[i],a=l[i+3],c=l[r],h=l[r+3];l[t+e]=o<c?o:c,l[t+e+3]=a>h?a:h}return m}}}function ts(t,e,i,n,s){let r,o,a,l,c,h;const u=1/i.direction.x,d=1/i.direction.y,p=1/i.direction.z,f=i.origin.x,m=i.origin.y,g=i.origin.z;let w=e[t],y=e[t+3],_=e[t+1],b=e[t+3+1],v=e[t+2],x=e[t+3+2];return u>=0?(r=(w-f)*u,o=(y-f)*u):(r=(y-f)*u,o=(w-f)*u),d>=0?(a=(_-m)*d,l=(b-m)*d):(a=(b-m)*d,l=(_-m)*d),!(r>l||a>o)&&((a>r||isNaN(r))&&(r=a),(l<o||isNaN(o))&&(o=l),p>=0?(c=(v-g)*p,h=(x-g)*p):(c=(x-g)*p,h=(v-g)*p),!(r>h||c>o)&&((c>r||r!=r)&&(r=c),(h<o||o!=o)&&(o=h),r<=s&&o>=n))}function es(t,e,i,n,s,r,o){const{geometry:a}=i,{index:l}=a,c=a.attributes.position;for(let a=t,h=e+t;a<h;a++){let t;if(t=i.resolveTriangleIndex(a),Kn(o,3*t,l,c),o.needsUpdate=!0,n(o,t,s,r))return!0}return!1}function is(t,e,i,n,s,r,o){Qi.setBuffer(t._roots[e]),ns(0,t,i,n,s,r,o),Qi.clearBuffer()}function ns(t,e,i,n,s,r,o){const{float32Array:a,uint16Array:l,uint32Array:c}=Qi,h=2*t;if(Ti(h,l)){!function(t,e,i,n,s,r,o,a){const{geometry:l,_indirectBuffer:c}=t;for(let t=n,c=n+s;t<c;t++)Xn(l,e,i,t,r,o,a)}(e,i,n,Ei(t,c),Mi(h,l),s,r,o)}else{const l=Ii(t);ts(l,a,n,r,o)&&ns(l,e,i,n,s,r,o);const h=zi(t,c);ts(h,a,n,r,o)&&ns(h,e,i,n,s,r,o)}}const ss=["x","y","z"];function rs(t,e,i,n,s,r){Qi.setBuffer(t._roots[e]);const o=os(0,t,i,n,s,r);return Qi.clearBuffer(),o}function os(t,e,i,n,s,r){const{float32Array:o,uint16Array:a,uint32Array:l}=Qi;let c=2*t;if(Ti(c,a)){return function(t,e,i,n,s,r,o){const{geometry:a,_indirectBuffer:l}=t;let c=1/0,h=null;for(let t=n,l=n+s;t<l;t++){let n;n=Xn(a,e,i,t,null,r,o),n&&n.distance<c&&(h=n,c=n.distance)}return h}(e,i,n,Ei(t,l),Mi(c,a),s,r)}{const a=Di(t,l),c=ss[a],h=n.direction[c]>=0;let u,d;h?(u=Ii(t),d=zi(t,l)):(u=zi(t,l),d=Ii(t));const p=ts(u,o,n,s,r)?os(u,e,i,n,s,r):null;if(p){const t=p.point[c];if(h?t<=o[d+a]:t>=o[d+a+3])return p}const f=ts(d,o,n,s,r)?os(d,e,i,n,s,r):null;return p&&f?p.distance<=f.distance?p:f:p||f||null}}const as=new a,ls=new In,cs=new In,hs=new l,us=new zn,ds=new zn;function ps(t,e,i,n){Qi.setBuffer(t._roots[e]);const s=fs(0,t,i,n);return Qi.clearBuffer(),s}function fs(t,e,i,n,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=Qi;let l=2*t;null===s&&(i.boundingBox||i.computeBoundingBox(),us.set(i.boundingBox.min,i.boundingBox.max,n),s=us);if(!Ti(l,o)){const o=Ii(t),l=zi(t,a);vi(o,r,as);if(s.intersectsBox(as)&&fs(o,e,i,n,s))return!0;vi(l,r,as);return!!(s.intersectsBox(as)&&fs(l,e,i,n,s))}{const s=e.geometry,c=s.index,h=s.attributes.position,u=i.index,d=i.attributes.position,p=Ei(t,a),f=Mi(l,o);if(hs.copy(n).invert(),i.boundsTree){vi(t,r,ds),ds.matrix.copy(hs),ds.needsUpdate=!0;return i.boundsTree.shapecast({intersectsBounds:t=>ds.intersectsBox(t),intersectsTriangle:t=>{t.a.applyMatrix4(n),t.b.applyMatrix4(n),t.c.applyMatrix4(n),t.needsUpdate=!0;for(let e=3*p,i=3*(f+p);e<i;e+=3)if(Kn(cs,e,c,h),cs.needsUpdate=!0,t.intersectsTriangle(cs))return!0;return!1}})}{const t=_n(i);for(let e=3*p,i=3*(f+p);e<i;e+=3){Kn(ls,e,c,h),ls.a.applyMatrix4(hs),ls.b.applyMatrix4(hs),ls.c.applyMatrix4(hs),ls.needsUpdate=!0;for(let e=0,i=3*t;e<i;e+=3)if(Kn(cs,e,u,d),cs.needsUpdate=!0,ls.intersectsTriangle(cs))return!0}}}}const ms=new l,gs=new zn,ws=new zn,ys=new h,_s=new h,bs=new h,vs=new h;function xs(t,e,i,n={},s={},r=0,o=1/0){e.boundingBox||e.computeBoundingBox(),gs.set(e.boundingBox.min,e.boundingBox.max,i),gs.needsUpdate=!0;const a=t.geometry,l=a.attributes.position,c=a.index,h=e.attributes.position,u=e.index,d=kn.getPrimitive(),p=kn.getPrimitive();let f=ys,m=_s,g=null,w=null;s&&(g=bs,w=vs);let y=1/0,_=null,b=null;return ms.copy(i).invert(),ws.matrix.copy(ms),t.shapecast({boundsTraverseOrder:t=>gs.distanceToBox(t),intersectsBounds:(t,e,i)=>i<y&&i<o&&(e&&(ws.min.copy(t.min),ws.max.copy(t.max),ws.needsUpdate=!0),!0),intersectsRange:(t,n)=>{if(e.boundsTree){return e.boundsTree.shapecast({boundsTraverseOrder:t=>ws.distanceToBox(t),intersectsBounds:(t,e,i)=>i<y&&i<o,intersectsRange:(e,s)=>{for(let o=e,a=e+s;o<a;o++){Kn(p,3*o,u,h),p.a.applyMatrix4(i),p.b.applyMatrix4(i),p.c.applyMatrix4(i),p.needsUpdate=!0;for(let e=t,i=t+n;e<i;e++){Kn(d,3*e,c,l),d.needsUpdate=!0;const t=d.distanceToTriangle(p,f,g);if(t<y&&(m.copy(f),w&&w.copy(g),y=t,_=e,b=o),t<r)return!0}}}})}for(let s=0,o=_n(e);s<o;s++){Kn(p,3*s,u,h),p.a.applyMatrix4(i),p.b.applyMatrix4(i),p.c.applyMatrix4(i),p.needsUpdate=!0;for(let e=t,i=t+n;e<i;e++){Kn(d,3*e,c,l),d.needsUpdate=!0;const t=d.distanceToTriangle(p,f,g);if(t<y&&(m.copy(f),w&&w.copy(g),y=t,_=e,b=s),t<r)return!0}}}}),kn.releasePrimitive(d),kn.releasePrimitive(p),y===1/0?null:(n.point?n.point.copy(m):n.point=m.clone(),n.distance=y,n.faceIndex=_,s&&(s.point?s.point.copy(w):s.point=w.clone(),s.point.applyMatrix4(ms),m.applyMatrix4(ms),s.distance=m.sub(s.point).length(),s.faceIndex=b),n)}function Cs(t,e=null){e&&Array.isArray(e)&&(e=new Set(e));const i=t.geometry,n=i.index?i.index.array:null,s=i.attributes.position;let r,o,a,l,c=0;const h=t._roots;for(let t=0,e=h.length;t<e;t++)r=h[t],o=new Uint32Array(r),a=new Uint16Array(r),l=new Float32Array(r),u(0,c),c+=r.byteLength;function u(i,r,c=!1){const h=2*i;if(Ti(h,a)){const e=Ei(i,o);let r=1/0,c=1/0,u=1/0,d=-1/0,p=-1/0,f=-1/0;for(let i=e,o=e+Mi(h,a);i<o;i++){const e=3*t.resolveTriangleIndex(i);for(let t=0;t<3;t++){let i=e+t;i=n?n[i]:i;const o=s.getX(i),a=s.getY(i),l=s.getZ(i);o<r&&(r=o),o>d&&(d=o),a<c&&(c=a),a>p&&(p=a),l<u&&(u=l),l>f&&(f=l)}}return(l[i+0]!==r||l[i+1]!==c||l[i+2]!==u||l[i+3]!==d||l[i+4]!==p||l[i+5]!==f)&&(l[i+0]=r,l[i+1]=c,l[i+2]=u,l[i+3]=d,l[i+4]=p,l[i+5]=f,!0)}{const t=Ii(i),n=zi(i,o);let s=c,a=!1,h=!1;if(e){if(!s){const i=t/8+r/wi,o=n/8+r/wi;a=e.has(i),h=e.has(o),s=!a&&!h}}else a=!0,h=!0;const d=s||h;let p=!1;(s||a)&&(p=u(t,r,s));let f=!1;d&&(f=u(n,r,s));const m=p||f;if(m)for(let e=0;e<3;e++){const s=t+e,r=n+e,o=l[s],a=l[s+3],c=l[r],h=l[r+3];l[i+e]=o<c?o:c,l[i+e+3]=a>h?a:h}return m}}}function Ss(t,e,i,n,s,r,o){Qi.setBuffer(t._roots[e]),As(0,t,i,n,s,r,o),Qi.clearBuffer()}function As(t,e,i,n,s,r,o){const{float32Array:a,uint16Array:l,uint32Array:c}=Qi,h=2*t;if(Ti(h,l)){!function(t,e,i,n,s,r,o,a){const{geometry:l,_indirectBuffer:c}=t;for(let t=n,h=n+s;t<h;t++)Xn(l,e,i,c?c[t]:t,r,o,a)}(e,i,n,Ei(t,c),Mi(h,l),s,r,o)}else{const l=Ii(t);ts(l,a,n,r,o)&&As(l,e,i,n,s,r,o);const h=zi(t,c);ts(h,a,n,r,o)&&As(h,e,i,n,s,r,o)}}const Ps=["x","y","z"];function Ts(t,e,i,n,s,r){Qi.setBuffer(t._roots[e]);const o=Es(0,t,i,n,s,r);return Qi.clearBuffer(),o}function Es(t,e,i,n,s,r){const{float32Array:o,uint16Array:a,uint32Array:l}=Qi;let c=2*t;if(Ti(c,a)){return function(t,e,i,n,s,r,o){const{geometry:a,_indirectBuffer:l}=t;let c=1/0,h=null;for(let t=n,u=n+s;t<u;t++){let n;n=Xn(a,e,i,l?l[t]:t,null,r,o),n&&n.distance<c&&(h=n,c=n.distance)}return h}(e,i,n,Ei(t,l),Mi(c,a),s,r)}{const a=Di(t,l),c=Ps[a],h=n.direction[c]>=0;let u,d;h?(u=Ii(t),d=zi(t,l)):(u=zi(t,l),d=Ii(t));const p=ts(u,o,n,s,r)?Es(u,e,i,n,s,r):null;if(p){const t=p.point[c];if(h?t<=o[d+a]:t>=o[d+a+3])return p}const f=ts(d,o,n,s,r)?Es(d,e,i,n,s,r):null;return p&&f?p.distance<=f.distance?p:f:p||f||null}}const Ms=new a,Is=new In,zs=new In,Ds=new l,ks=new zn,Bs=new zn;function Os(t,e,i,n){Qi.setBuffer(t._roots[e]);const s=Ns(0,t,i,n);return Qi.clearBuffer(),s}function Ns(t,e,i,n,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=Qi;let l=2*t;null===s&&(i.boundingBox||i.computeBoundingBox(),ks.set(i.boundingBox.min,i.boundingBox.max,n),s=ks);if(!Ti(l,o)){const o=Ii(t),l=zi(t,a);vi(o,r,Ms);if(s.intersectsBox(Ms)&&Ns(o,e,i,n,s))return!0;vi(l,r,Ms);return!!(s.intersectsBox(Ms)&&Ns(l,e,i,n,s))}{const s=e.geometry,c=s.index,h=s.attributes.position,u=i.index,d=i.attributes.position,p=Ei(t,a),f=Mi(l,o);if(Ds.copy(n).invert(),i.boundsTree){vi(t,r,Bs),Bs.matrix.copy(Ds),Bs.needsUpdate=!0;return i.boundsTree.shapecast({intersectsBounds:t=>Bs.intersectsBox(t),intersectsTriangle:t=>{t.a.applyMatrix4(n),t.b.applyMatrix4(n),t.c.applyMatrix4(n),t.needsUpdate=!0;for(let i=p,n=f+p;i<n;i++)if(Kn(zs,3*e.resolveTriangleIndex(i),c,h),zs.needsUpdate=!0,t.intersectsTriangle(zs))return!0;return!1}})}{const t=_n(i);for(let i=p,n=f+p;i<n;i++){const n=e.resolveTriangleIndex(i);Kn(Is,3*n,c,h),Is.a.applyMatrix4(Ds),Is.b.applyMatrix4(Ds),Is.c.applyMatrix4(Ds),Is.needsUpdate=!0;for(let e=0,i=3*t;e<i;e+=3)if(Kn(zs,e,u,d),zs.needsUpdate=!0,Is.intersectsTriangle(zs))return!0}}}}const Vs=new l,Ls=new zn,Fs=new zn,Rs=new h,Us=new h,js=new h,$s=new h;function Ws(t,e,i,n={},s={},r=0,o=1/0){e.boundingBox||e.computeBoundingBox(),Ls.set(e.boundingBox.min,e.boundingBox.max,i),Ls.needsUpdate=!0;const a=t.geometry,l=a.attributes.position,c=a.index,h=e.attributes.position,u=e.index,d=kn.getPrimitive(),p=kn.getPrimitive();let f=Rs,m=Us,g=null,w=null;s&&(g=js,w=$s);let y=1/0,_=null,b=null;return Vs.copy(i).invert(),Fs.matrix.copy(Vs),t.shapecast({boundsTraverseOrder:t=>Ls.distanceToBox(t),intersectsBounds:(t,e,i)=>i<y&&i<o&&(e&&(Fs.min.copy(t.min),Fs.max.copy(t.max),Fs.needsUpdate=!0),!0),intersectsRange:(n,s)=>{if(e.boundsTree){const a=e.boundsTree;return a.shapecast({boundsTraverseOrder:t=>Fs.distanceToBox(t),intersectsBounds:(t,e,i)=>i<y&&i<o,intersectsRange:(e,o)=>{for(let v=e,x=e+o;v<x;v++){const e=a.resolveTriangleIndex(v);Kn(p,3*e,u,h),p.a.applyMatrix4(i),p.b.applyMatrix4(i),p.c.applyMatrix4(i),p.needsUpdate=!0;for(let e=n,i=n+s;e<i;e++){const i=t.resolveTriangleIndex(e);Kn(d,3*i,c,l),d.needsUpdate=!0;const n=d.distanceToTriangle(p,f,g);if(n<y&&(m.copy(f),w&&w.copy(g),y=n,_=e,b=v),n<r)return!0}}}})}for(let o=0,a=_n(e);o<a;o++){Kn(p,3*o,u,h),p.a.applyMatrix4(i),p.b.applyMatrix4(i),p.c.applyMatrix4(i),p.needsUpdate=!0;for(let e=n,i=n+s;e<i;e++){const i=t.resolveTriangleIndex(e);Kn(d,3*i,c,l),d.needsUpdate=!0;const n=d.distanceToTriangle(p,f,g);if(n<y&&(m.copy(f),w&&w.copy(g),y=n,_=e,b=o),n<r)return!0}}}}),kn.releasePrimitive(d),kn.releasePrimitive(p),y===1/0?null:(n.point?n.point.copy(m):n.point=m.clone(),n.distance=y,n.faceIndex=_,s&&(s.point?s.point.copy(w):s.point=w.clone(),s.point.applyMatrix4(Vs),m.applyMatrix4(Vs),s.distance=m.sub(s.point).length(),s.faceIndex=b),n)}function Gs(t,e,i){return null===t?null:(t.point.applyMatrix4(e.matrixWorld),t.distance=t.point.distanceTo(i.ray.origin),t.object=e,t)}const Hs=new zn,Zs=new y,qs=new h,Ys=new l,Xs=new h,Ks=["getX","getY","getZ"];class Qs extends xn{static serialize(t,e={}){e={cloneBuffers:!0,...e};const i=t.geometry,n=t._roots,s=t._indirectBuffer,r=i.getIndex(),o={version:1,roots:null,index:null,indirectBuffer:null};return e.cloneBuffers?(o.roots=n.map(t=>t.slice()),o.index=r?r.array.slice():null,o.indirectBuffer=s?s.slice():null):(o.roots=n,o.index=r?r.array:null,o.indirectBuffer=s),o}static deserialize(t,e,i={}){i={setIndex:!0,indirect:Boolean(t.indirectBuffer),...i};const{index:n,roots:s,indirectBuffer:r}=t;t.version||(console.warn("MeshBVH.deserialize: Serialization format has been changed and will be fixed up. It is recommended to regenerate any stored serialized data."),function(t){for(let e=0;e<t.length;e++){const i=t[e],n=new Uint32Array(i),s=new Uint16Array(i);for(let t=0,e=i.byteLength/wi;t<e;t++){const e=8*t;Ti(2*e,s)||(n[e+6]=n[e+6]/8-t)}}}(s));const o=new Qs(e,{...i,[_i]:!0});if(o._roots=s,o._indirectBuffer=r||null,i.setIndex){const i=e.getIndex();if(null===i){const i=new c(t.index,1,!1);e.setIndex(i)}else i.array!==n&&(i.array.set(n),i.needsUpdate=!0)}return o}get primitiveStride(){return 3}get resolveTriangleIndex(){return this.resolvePrimitiveIndex}constructor(t,e={}){e.maxLeafTris&&(console.warn('MeshBVH: "maxLeafTris" option has been deprecated. Use maxLeafSize, instead.'),e={...e,maxLeafSize:e.maxLeafTris}),super(t,e)}shiftTriangleOffsets(t){return super.shiftPrimitiveOffsets(t)}writePrimitiveBounds(t,e,i){const n=this.geometry,s=this._indirectBuffer,r=n.attributes.position,o=n.index?n.index.array:null,a=3*(s?s[t]:t);let l=a+0,c=a+1,h=a+2;o&&(l=o[l],c=o[c],h=o[h]);for(let t=0;t<3;t++){const n=r[Ks[t]](l),s=r[Ks[t]](c),o=r[Ks[t]](h);let a=n;s<a&&(a=s),o<a&&(a=o);let u=n;s>u&&(u=s),o>u&&(u=o),e[i+t]=a,e[i+t+3]=u}return e}computePrimitiveBounds(t,e,i){const n=this.geometry,s=this._indirectBuffer,r=n.attributes.position,o=n.index?n.index.array:null,a=r.normalized;if(t<0||e+t-i.offset>i.length/6)throw new Error("MeshBVH: compute triangle bounds range is invalid.");const l=r.array,c=r.offset||0;let h=3;r.isInterleavedBufferAttribute&&(h=r.data.stride);const u=["getX","getY","getZ"],d=i.offset;for(let n=t,p=t+e;n<p;n++){const t=3*(s?s[n]:n),e=6*(n-d);let p=t+0,f=t+1,m=t+2;o&&(p=o[p],f=o[f],m=o[m]),a||(p=p*h+c,f=f*h+c,m=m*h+c);for(let t=0;t<3;t++){let n,s,o;a?(n=r[u[t]](p),s=r[u[t]](f),o=r[u[t]](m)):(n=l[p+t],s=l[f+t],o=l[m+t]);let c=n;s<c&&(c=s),o<c&&(c=o);let h=n;s>h&&(h=s),o>h&&(h=o);const d=(h-c)/2,g=2*t;i[e+g+0]=c+d,i[e+g+1]=d+(Math.abs(c)+d)*yi}}return i}raycastObject3D(t,e,i=[]){const{material:n}=t;if(void 0===n)return;Ys.copy(t.matrixWorld).invert(),Zs.copy(e.ray).applyMatrix4(Ys),Xs.setFromMatrixScale(t.matrixWorld),qs.copy(Zs.direction).multiply(Xs);const s=qs.length(),r=e.near/s,o=e.far/s;if(!0===e.firstHitOnly){let s=this.raycastFirst(Zs,n,r,o);s=Gs(s,t,e),s&&i.push(s)}else{const s=this.raycast(Zs,n,r,o);for(let n=0,r=s.length;n<r;n++){const r=Gs(s[n],t,e);r&&i.push(r)}}return i}refit(t=null){return(this.indirect?Cs:Jn)(this,t)}raycast(t,e=_,i=0,n=1/0){const s=this._roots,r=[],o=this.indirect?Ss:is;for(let a=0,l=s.length;a<l;a++)o(this,a,e,t,r,i,n);return r}raycastFirst(t,e=_,i=0,n=1/0){const s=this._roots;let r=null;const o=this.indirect?Ts:rs;for(let a=0,l=s.length;a<l;a++){const s=o(this,a,e,t,i,n);null!=s&&(null==r||s.distance<r.distance)&&(r=s)}return r}intersectsGeometry(t,e){let i=!1;const n=this._roots,s=this.indirect?Os:ps;for(let r=0,o=n.length;r<o&&(i=s(this,r,t,e),!i);r++);return i}shapecast(t){const e=kn.getPrimitive(),i=super.shapecast({...t,intersectsPrimitive:t.intersectsTriangle,scratchPrimitive:e,iterate:this.indirect?es:Qn});return kn.releasePrimitive(e),i}bvhcast(t,e,i){let{intersectsRanges:n,intersectsTriangles:s}=i;const r=kn.getPrimitive(),o=this.geometry.index,a=this.geometry.attributes.position,l=this.indirect?t=>{const e=this.resolveTriangleIndex(t);Kn(r,3*e,o,a)}:t=>{Kn(r,3*t,o,a)},c=kn.getPrimitive(),h=t.geometry.index,u=t.geometry.attributes.position,d=t.indirect?e=>{const i=t.resolveTriangleIndex(e);Kn(c,3*i,h,u)}:t=>{Kn(c,3*t,h,u)};if(s){if(!(t instanceof Qs))throw new Error('MeshBVH: "intersectsTriangles" callback can only be used with another MeshBVH.');const i=(t,i,n,o,a,h,u,p)=>{for(let f=n,m=n+o;f<m;f++){d(f),c.a.applyMatrix4(e),c.b.applyMatrix4(e),c.c.applyMatrix4(e),c.needsUpdate=!0;for(let e=t,n=t+i;e<n;e++)if(l(e),r.needsUpdate=!0,s(r,c,e,f,a,h,u,p))return!0}return!1};if(n){const t=n;n=function(e,n,s,r,o,a,l,c){return!!t(e,n,s,r,o,a,l,c)||i(e,n,s,r,o,a,l,c)}}else n=i}return super.bvhcast(t,e,{intersectsRanges:n})}intersectsBox(t,e){return Hs.set(t.min,t.max,e),Hs.needsUpdate=!0,this.shapecast({intersectsBounds:t=>Hs.intersectsBox(t),intersectsTriangle:t=>Hs.intersectsTriangle(t)})}intersectsSphere(t){return this.shapecast({intersectsBounds:e=>t.intersectsBox(e),intersectsTriangle:e=>e.intersectsSphere(t)})}closestPointToGeometry(t,e,i={},n={},s=0,r=1/0){return(this.indirect?Ws:xs)(this,t,e,i,n,s,r)}closestPointToPoint(t,e={},i=0,n=1/0){return function(t,e,i={},n=0,s=1/0){const r=n*n,o=s*s;let a=1/0,l=null;if(t.shapecast({boundsTraverseOrder:t=>(Bn.copy(e).clamp(t.min,t.max),Bn.distanceToSquared(e)),intersectsBounds:(t,e,i)=>i<a&&i<o,intersectsTriangle:(t,i)=>{t.closestPointToPoint(e,Bn);const n=e.distanceToSquared(Bn);return n<a&&(On.copy(Bn),a=n,l=i),n<r}}),a===1/0)return null;const c=Math.sqrt(a);return i.point?i.point.copy(On):i.point=On.clone(),i.distance=c,i.faceIndex=l,i}(this,t,e,i,n)}}const Js=new l,tr=new y,er=new Xi(()=>new u),ir=new h,nr=new h,sr=new a,rr=["getX","getY","getZ"];class or extends xn{get primitiveStride(){return 2}writePrimitiveBounds(t,e,i){const n=this._indirectBuffer,{geometry:s,primitiveStride:r}=this,o=s.attributes.position,a=s.index,l=a?a.count:o.count;let c=(n?n[t]:t)*r,h=(c+1)%l;a&&(c=a.getX(c),h=a.getX(h));for(let t=0;t<3;t++){const n=o[rr[t]](c),s=o[rr[t]](h),r=n<s?n:s,a=n>s?n:s;e[i+t]=r,e[i+t+3]=a}return e}shapecast(t){const e=er.getPrimitive(),i=super.shapecast({...t,intersectsPrimitive:t.intersectsLine,scratchPrimitive:e,iterate:ar});return er.releasePrimitive(e),i}raycastObject3D(t,e,i=[]){const{matrixWorld:n}=t,{firstHitOnly:s}=e;Js.copy(n).invert(),tr.copy(e.ray).applyMatrix4(Js);const r=e.params.Line.threshold/((t.scale.x+t.scale.y+t.scale.z)/3),o=r*r;let a=null,l=1/0;return this.shapecast({boundsTraverseOrder:t=>t.distanceToPoint(tr.origin),intersectsBounds:t=>(sr.copy(t).expandByScalar(Math.abs(r)),tr.intersectsBox(sr)?1:0),intersectsLine:(r,c)=>{if(tr.distanceSqToSegment(r.start,r.end,ir,nr)>o)return;ir.applyMatrix4(t.matrixWorld);const h=e.ray.origin.distanceTo(ir);h<e.near||h>e.far||s&&h>=l||(l=h,c=this.resolvePrimitiveIndex(c),a={distance:h,point:nr.clone().applyMatrix4(n),index:c*this.primitiveStride,face:null,faceIndex:null,barycoord:null,object:t},s||i.push(a))}}),s&&a&&i.push(a),i}}function ar(t,e,i,n,s,r,o){const{geometry:a,primitiveStride:l}=i,{index:c}=a,h=a.attributes.position,u=c?c.count:h.count;for(let a=t,d=e+t;a<d;a++){let t=i.resolvePrimitiveIndex(a)*l,e=(t+1)%u;if(c&&(t=c.getX(t),e=c.getX(e)),o.start.fromBufferAttribute(h,t),o.end.fromBufferAttribute(h,e),n(o,a,s,r))return!0}return!1}const lr={Mesh:b.prototype.raycast,Line:C.prototype.raycast,LineSegments:v.prototype.raycast,LineLoop:x.prototype.raycast,Points:S.prototype.raycast,BatchedMesh:P.prototype.raycast},cr=new b,hr=[];function ur(t,e){if(this.isBatchedMesh)dr.call(this,t,e);else{const{geometry:i}=this;if(i.boundsTree)i.boundsTree.raycastObject3D(this,t,e);else{let i;if(this instanceof b)i=lr.Mesh;else if(this instanceof v)i=lr.LineSegments;else if(this instanceof x)i=lr.LineLoop;else if(this instanceof C)i=lr.Line;else{if(!(this instanceof S))throw new Error("BVH: Fallback raycast function not found.");i=lr.Points}i.call(this,t,e)}}}function dr(t,e){if(this.boundsTrees){const i=this.boundsTrees,n=this._drawInfo||this._instanceInfo,s=this._drawRanges||this._geometryInfo,r=this.matrixWorld;cr.material=this.material,cr.geometry=this.geometry;const o=cr.geometry.boundsTree,a=cr.geometry.drawRange;null===cr.geometry.boundingSphere&&(cr.geometry.boundingSphere=new A);for(let o=0,a=n.length;o<a;o++){if(!this.getVisibleAt(o))continue;const a=n[o].geometryIndex;if(cr.geometry.boundsTree=i[a],this.getMatrixAt(o,cr.matrixWorld).premultiply(r),!cr.geometry.boundsTree){this.getBoundingBoxAt(a,cr.geometry.boundingBox),this.getBoundingSphereAt(a,cr.geometry.boundingSphere);const t=s[a];cr.geometry.setDrawRange(t.start,t.count)}cr.raycast(t,hr);for(let t=0,i=hr.length;t<i;t++){const i=hr[t];i.object=this,i.batchId=o,e.push(i)}hr.length=0}cr.geometry.boundsTree=o,cr.geometry.drawRange=a,cr.material=null,cr.geometry=null}else lr.BatchedMesh.call(this,t,e)}function pr(t={}){const{type:e=Qs}=t;return this.boundsTree=new e(this,t),this.boundsTree}function fr(){this.boundsTree=null}const mr=class t extends ht{constructor(i){super(i),e(this,"onDisposed",new at),e(this,"onBeforeDispose",new at),e(this,"onFragmentsLoaded",new at),e(this,"baseCoordinationModel",""),e(this,"baseCoordinationMatrix",new o.Matrix4),e(this,"enabled",!0),e(this,"_core"),this.components.add(t.uuid,this)}static getWorker(){return s.getWorker()}get initialized(){return!!this._core}get list(){return this.core.models.list}get core(){if(!this._core)throw new Error("FragmentsManager not initialized. Call init() first.");return this._core}get _hasCoordinationModel(){return""!==this.baseCoordinationModel}dispose(){this.onBeforeDispose.trigger(),this._core&&(this.core.dispose(),this._core=void 0),this.baseCoordinationModel="",this.onFragmentsLoaded.reset(),this.onDisposed.trigger(),this.onDisposed.reset()}init(t,e){this._core=new s(t,e),this.core.onModelLoaded.add(async()=>{if(this._hasCoordinationModel)return;const t=[...this.list.values()][0];t&&(this.baseCoordinationModel=t.modelId,this.baseCoordinationMatrix=await t.getCoordinationMatrix())}),this.list.onItemDeleted.add(()=>{this.list.size>0||(this.baseCoordinationModel="",this.baseCoordinationMatrix=new o.Matrix4)})}async raycast(t){const e=[];for(const i of this.core.models.list.values())if(t.snappingClasses&&t.snappingClasses.length>0){const n=await i.raycastWithSnapping(t);if(n&&n.length>0)e.push(n[0]);else{const n=await i.raycast(t);n&&e.push(n)}}else{const n=await i.raycast(t);n&&e.push(n)}if(await Promise.all(e),0===e.length)return;let i=e[0],n=i.distance;for(let t=1;t<e.length;t++)e[t].distance<n&&(n=e[t].distance,i=e[t]);return i}async getPositions(t){const e=[],i=async(t,i)=>{const n=await t.getPositions(i);for(const t of n)e.push(t)},n=[];for(const e in t){const s=this.core.models.list.get(e);s&&n.push(i(s,Array.from(t[e])))}return await Promise.all(n),e}async getBBoxes(t){const e=[],i=async(t,i)=>{const n=await t.getBoxes(i);if(n)for(const t of n)e.push(t)},n=[];for(const e in t){const s=this.core.models.list.get(e);s&&n.push(i(s,Array.from(t[e])))}return await Promise.all(n),e}async highlight(t,e){await this.forEachModel(e,"highlight",t)}async getData(t,e){const i={};for(const[n,s]of Object.entries(t)){const t=this.list.get(n);if(!t)continue;if(0===s.size){i[n]=[];continue}const r=await t.getItemsData([...s],e);i[n]=r}return i}async resetHighlight(t){await this.forEachModel(t,"resetHighlight")}async forEachModel(t,e,...i){const n={};if(t)for(const e in t){const i=t[e];n[e]=Array.from(i)}else for(const t of this.core.models.list.keys())n[t]=void 0;const s=[];for(const t in n){const r=this.core.models.list.get(t);if(r){const o=n[t],a=r[e](o,...i);s.push(a)}}await Promise.all(s)}async guidsToModelIdMap(t){const e={};for(const[i,n]of this.list){const s=(await n.getLocalIdsByGuids([...t])).filter(t=>null!==t);e[i]=new Set(s)}return e}async modelIdMapToGuids(t){const e=[];for(const[i,n]of Object.entries(t)){const t=this.list.get(i);if(!t)continue;const s=(await t.getGuidsByLocalIds([...n])).filter(t=>null!==t);e.push(...s)}return e}applyBaseCoordinateSystem(t,e){const i=new o.Matrix4;return e&&i.copy(e.clone()).invert(),i.multiply(this.baseCoordinationMatrix),t.applyMatrix4(i),i}};e(mr,"uuid","fef46874-46a3-461b-8c44-2922ab77c806");let gr=mr;function wr(t,e){return t[e]|t[e+1]<<8|t[e+2]<<16}class yr{constructor(t,e={}){const{pixelsPerMeter:i=.1}=e;this.pixelsPerMeter=i,this.renderer=t}async cull(t){t=function(t){const e=new Set;return t.traverse(t=>{t.isMesh&&e.add(t)}),Array.from(e)}(t);const{renderer:e,pixelsPerMeter:i}=this,n=new h,s=new T,r=new a,o=new E(1,1);r.makeEmpty(),t.forEach(t=>{r.expandByObject(t)}),r.getSize(n);const l=Math.min(e.capabilities.maxTextureSize,8192),c=Math.ceil(n.x/i),u=Math.ceil(n.z/i),d=Math.ceil(c/l),p=Math.ceil(u/l);o.setSize(Math.ceil(c/d),Math.ceil(u/p));const f=.01*Math.max(n.y,1);s.rotation.x=-Math.PI/2,s.near=0,s.far=n.y+2*f,s.position.y=r.max.y+f;const m=new M,g=new Map,w=new Map,y=[];for(let e=0;e<t.length;e++){const i=t[e];g.set(i,i.material),w.set(i,i.parent);const n=new _r;n.objectId=e,y.push(n),i.material=n,m.add(i)}const _=e.getClearColor(new I),b=e.getClearAlpha(),v=e.getRenderTarget(),x=e.autoClear;e.autoClear=!0,e.setClearColor(0,0),e.setRenderTarget(o);const C=new Uint8Array(o.width*o.height*4),S=new Set,A=n.x/d,P=n.z/p;for(let i=0;i<d;i++)for(let n=0;n<p;n++){const a=r.min.x+A*i,l=a+A,c=r.min.z+P*n,h=(a+l)/2,u=(c+(c+P))/2;s.position.set(h,r.max.y+f,u);const d=A/2,p=P/2;s.left=-d,s.right=d,s.top=p,s.bottom=-p,s.updateProjectionMatrix(),e.render(m,s);const g=await e.readRenderTargetPixelsAsync(o,0,0,o.width,o.height,C);for(let e=0,i=g.length;e<i;e+=4){if(0===g[e+3])continue;const i=wr(g,e);S.add(t[i])}}for(const e of t){e.material=g.get(e);const t=w.get(e);t?t.add(e):m.remove(e)}e.setClearColor(_,b),e.setRenderTarget(v),e.autoClear=x;for(const t of y)t.dispose();return o.dispose(),Array.from(S)}}class _r extends z{get objectId(){return this._objectId}set objectId(t){var e,i;this._objectId=t,e=t,(i=this.uniforms.objectId.value).x=(255&e)/255,i.y=(e>>8&255)/255,i.z=(e>>16&255)/255,i.w=1}constructor(t){super({glslVersion:B,blending:k,side:g,uniforms:{objectId:{value:new D}},vertexShader:"\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\t\t\t\tlayout(location = 0) out vec4 out_id;\n\t\t\t\tuniform vec4 objectId;\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tout_id = objectId;\n\n\t\t\t\t}\n\t\t\t"}),this._objectId=0,this.setValues(t)}}const br=1e-16,vr=new h(0,1,0),xr=new h;function Cr(t){return t.delta(xr).normalize(),Math.abs(xr.dot(vr))>=1-br}function Sr(t,e){const{start:i,end:n}=e,s=t.points;let r=!1,o=!1;for(let t=0;t<3;t++){const e=s[t];if(!r&&i.distanceToSquared(e)<=br&&(r=!0),!o&&n.distanceToSquared(e)<=br&&(o=!0),r&&o)return!0}return r&&o}const Ar=new u;function Pr(t,e,i=!1,n=[]){let s=[[0,1]];for(let t=0,i=e.length;t<i;t++){const i=s[t],n=e[t];i[1]=n[0],s.push([n[1],1])}i&&([e,s]=[s,e]);for(let e=0,i=s.length;e<i;e++){const{start:i,end:r}=t;Ar.start.lerpVectors(i,r,s[e][0]),Ar.end.lerpVectors(i,r,s[e][1]),n.push(new Float32Array([Ar.start.x,Ar.start.y,Ar.start.z,Ar.end.x,Ar.end.y,Ar.end.z]))}return n}const Tr=new h(0,1,0),Er=new h,Mr=new h,Ir=new h,zr=new f;function*Dr(t,e=[],i={}){const{projectionDirection:n=Tr,thresholdAngle:s=1,iterationTime:r=30}=i,o=Math.pow(10,4),a=Math.cos(O.DEG2RAD*s),l=t.getIndex(),c=t.getAttribute("position"),h=l?l.count:c.count,d=[0,0,0],p=["a","b","c"],f=new Array(3),m={};let g=performance.now();for(let t=0;t<h;t+=3){performance.now()-g>r&&(yield,g=performance.now()),l?(d[0]=l.getX(t),d[1]=l.getX(t+1),d[2]=l.getX(t+2)):(d[0]=t,d[1]=t+1,d[2]=t+2);const{a:i,b:s,c:h}=zr;if(i.fromBufferAttribute(c,d[0]),s.fromBufferAttribute(c,d[1]),h.fromBufferAttribute(c,d[2]),zr.getNormal(Ir),f[0]=`${Math.round(i.x*o)},${Math.round(i.y*o)},${Math.round(i.z*o)}`,f[1]=`${Math.round(s.x*o)},${Math.round(s.y*o)},${Math.round(s.z*o)}`,f[2]=`${Math.round(h.x*o)},${Math.round(h.y*o)},${Math.round(h.z*o)}`,f[0]!==f[1]&&f[1]!==f[2]&&f[2]!==f[0])for(let t=0;t<3;t++){const i=(t+1)%3,s=f[t],r=f[i],o=zr[p[t]],l=zr[p[i]],c=`${s}_${r}`,h=`${r}_${s}`;if(h in m&&m[h]){const t=m[h].normal,i=Ir.dot(t)<=a;let s=!1;if(null!==n){let e=n.dot(Ir);e=Math.abs(e)<1e-10?0:e;let i=n.dot(t);i=Math.abs(i)<1e-10?0:i,s=Math.sign(e)!==Math.sign(i)}if(i||s){const t=new u;t.start.copy(o),t.end.copy(l),e.push(t)}m[h]=null}else c in m||(m[c]={index0:d[t],index1:d[i],normal:Ir.clone()})}}for(const t in m)if(m[t]){const{index0:i,index1:n}=m[t];Er.fromBufferAttribute(c,i),Mr.fromBufferAttribute(c,n);const s=new u;s.start.copy(Er),s.end.copy(Mr),e.push(s)}return e}const kr=new u;function Br(t,e,i,n=[]){return t.bvhcast(e,i,{intersectsTriangles:(t,e)=>!function(t,e){const i=["a","b","c"];let n=0;for(let s=0;s<3;s++)for(let r=0;r<3;r++){Or(t[i[s]],e[i[r]])&&n++}return n>=2}(t,e)&&(t.needsUpdate&&t.update(),e.needsUpdate&&e.update(),!(Math.abs(t.plane.normal.dot(e.plane.normal))>.999999)&&void(!t.intersectsTriangle(e,kr,!0)||Sr(t,kr)||Sr(e,kr)||n.push(kr.clone())))}),n}function Or(t,e){return t.distanceTo(e)<1e-10}function Nr(t){Vr(t);let e=[];return t.traverse(t=>{t.geometry&&t.visible&&e.push(t)}),e}const Vr=t=>{if(void 0===t)return;const e=[...t.children];for(const i of e)void 0===i?t.children.splice(t.children.indexOf(i),1):Vr(i)},Lr=new l,Fr=new l;class Rr{constructor(){this.projectionDirection=new h(0,1,0),this.thresholdAngle=50,this.iterationTime=30}getEdges(...t){const e=this.iterationTime;this.iterationTime=1/0;const i=this.getEdgesGenerator(...t).next().value;return this.iterationTime=e,i}*getEdgesGenerator(t,e=[],i=null){const{projectionDirection:n,thresholdAngle:s,iterationTime:r}=this;if(t.isObject3D){const o=Nr(t);let a=null;n&&(a=new h);let l=performance.now();for(let t=0;t<o.length;t++){l-performance.now()>r&&(yield);const c=o[t];a&&(Fr.copy(c.matrixWorld).invert(),a.copy(n).transformDirection(Fr).normalize());const h=yield*Dr(c.geometry,[],{projectionDirection:a,thresholdAngle:s,iterationTime:r});Ur(h,c.matrixWorld);for(let t=0;t<h.length;t++)e.push(h[t]);if(null!==i)for(let t=0;t<h.length;t++)i.push(c)}return e}return yield*Dr(t,e,{projectionDirection:n,thresholdAngle:s,iterationTime:r})}getIntersectionEdges(...t){const e=this.iterationTime;this.iterationTime=1/0;const i=this.getIntersectionEdgesGenerator(...t).next().value;return this.iterationTime=e,i}*getIntersectionEdgesGenerator(t,e=[],i=null){const{iterationTime:n}=this;if(t.isObject3D){const s=Nr(t),r=new Map;let o=performance.now();for(let t=0;t<s.length;t++){performance.now()-o>n&&(yield,o=performance.now());const e=s[t].geometry;if(!r.has(e)){const t=e.boundsTree||new Qs(e,{maxLeafSize:1});r.set(e,t)}}o=performance.now();for(let t=0;t<s.length;t++)for(let a=t;a<s.length;a++){performance.now()-o>n&&(yield,o=performance.now());const l=s[t],c=s[a],h=r.get(l.geometry),u=r.get(c.geometry);Lr.copy(l.matrixWorld).invert().multiply(c.matrixWorld);const d=Br(h,u,Lr,[]);Ur(d,l.matrixWorld);for(let t=0;t<d.length;t++)e.push(d[t]);if(null!==i)for(let t=0;t<d.length;t++)i.push(l)}return e}{let i;return t.isBufferGeometry?i=t.boundsTree||new Qs(t,{maxLeafSize:1}):(i=t,t=i.geometry),Lr.identity(),Br(i,i,Lr,e)}}}function Ur(t,e,i=1e-6){for(let n=0;n<t.length;n++){const s=t[n];s.applyMatrix4(e),s.start.y+=i,s.end.y+=i}}class jr extends wn{get lines(){return this.primitiveBuffer}constructor(t,e){super(e),this.primitiveBuffer=t,this.primitiveBufferStride=1,this.heightOffset=e.heightOffset??1e3,this.init(e)}writePrimitiveBounds(t,e,i){const{primitiveBuffer:n,heightOffset:s}=this,{start:r,end:o}=n[t];e[i+0]=Math.min(r.x,o.x),e[i+1]=Math.min(r.y,o.y),e[i+2]=Math.min(r.z,o.z),e[i+3]=Math.max(r.x,o.x),e[i+4]=Math.max(r.y,o.y)+s,e[i+5]=Math.max(r.z,o.z)}getRootRanges(){return[{offset:0,count:this.primitiveBuffer.length}]}}const $r=new h(0,1,0),Wr=new d,Gr=new h,Hr=new h;function Zr(t,e,i){t.needsUpdate&&t.update(),Wr.copy(t.plane),Wr.normal.dot($r)<0&&(Wr.normal.multiplyScalar(-1),Wr.constant*=-1);const n=Wr.distanceToPoint(e.start),s=Wr.distanceToPoint(e.end),r=Math.abs(n)<1e-16,o=n<0,a=s<0;if(e.delta(Hr).normalize(),Math.abs(Wr.normal.dot(Hr))<1e-16)return!(r||!o)&&(i.copy(e),!0);if(o&&a)return i.copy(e),!0;if(!o&&!a)return!1;{const t=O.mapLinear(0,n,s,0,1);if(e.at(t,Gr),o)return i.start.copy(e.start),i.end.copy(Gr),!0;if(a)return i.end.copy(e.end),i.start.copy(Gr),!0}return!1}const qr=new d,Yr=new h,Xr=new h,Kr=new In,Qr=new u,Jr=new u,to=new h,eo=new h,io=new h;function no(t,e,i=new u){if(Kr.copy(e),Kr.a.y=0,Kr.b.y=0,Kr.c.y=0,Kr.update(),Qr.copy(t),Qr.start.y=0,Qr.end.y=0,Kr.getArea()<=1e-16)return null;const n=Qr.distance();Qr.delta(to).divideScalar(n),eo.copy(to).cross(Kr.plane.normal).normalize(),qr.setFromNormalAndCoplanarPoint(eo,Qr.start);let s=0;const{points:r}=Kr;for(let t=0;t<3;t++){const e=r[t],i=r[(t+1)%3],n=qr.distanceToPoint(e),o=qr.distanceToPoint(i),a=Math.abs(n)<1e-16,l=Math.abs(o)<1e-16;let c=!1;if(!a&&!l&&n*o<0){const t=n/(n-o);Yr.lerpVectors(e,i,t),c=!0}if((c&&!l||a)&&(a&&!c&&Yr.copy(e),0===s?Jr.start.copy(Yr):Jr.end.copy(Yr),s++,2===s))break}if(2===s){if(Jr.delta(io).normalize(),to.dot(io)<0){const t=Jr.start;Jr.start=Jr.end,Jr.end=t}const e=0,s=Xr.subVectors(Qr.end,Qr.start).dot(to),r=Xr.subVectors(Jr.start,Qr.start).dot(to),o=Xr.subVectors(Jr.end,Qr.start).dot(to);return s<=r||o<=e?null:(t.at(Math.max(e,r)/n,i.start),t.at(Math.min(s,o)/n,i.end),i)}return null}const so=new h,ro=new h,oo=new h;function ao(t,e,i){const n=function(t,e){t.delta(so),ro.subVectors(e.start,t.start),oo.subVectors(e.end,t.start);const i=so.length();let n=ro.length()/i,s=oo.length()/i;if(n=Math.min(Math.max(n,0),1),s=Math.min(Math.max(s,0),1),Math.abs(n-s)<=1e-16)return null;return[n,s]}(t,e);return!!n&&(lo(n,i),!0)}function lo(t,e){let[i,n]=t,s=0,r=e.length;for(;s<r;){const t=s+r>>>1;e[t][0]<=i?s=t+1:r=t}let o=Math.max(0,s-1),a=0;for(let t=o,s=e.length;t<s;t++){const[s,r]=e[t];if(i<=r&&n>=s)i=Math.min(s,i),n=Math.max(r,n),a++;else{if(!(i>=s))break;o=t+1}}e.splice(o,a,[i,n])}const co=new h(0,1,0),ho=new u,uo=new u,po=new In;function fo(t,e,i,n,s=null){const{geometry:r,matrixWorld:o,material:a}=i,l=a.side,c=o.determinant()<0,h=t.lines;t.bvhcast(e,o,{intersectsRanges:(t,e,i,a)=>{s&&(s.candidates+=e*a);for(let u=i,d=a+i;u<d;u++){let i=3*u+0,a=3*u+1,d=3*u+2;r.index&&(i=r.index.getX(i),a=r.index.getX(a),d=r.index.getX(d));const{a:p,b:f,c:w}=po;if(p.fromBufferAttribute(r.attributes.position,i).applyMatrix4(o),f.fromBufferAttribute(r.attributes.position,a).applyMatrix4(o),w.fromBufferAttribute(r.attributes.position,d).applyMatrix4(o),po.needsUpdate=!0,po.update(),l!==g){if(po.plane.normal.dot(co)!==c===(l===m)){s&&(s.backFaceCulled+=e);continue}}const y=Math.max(p.y,f.y,w.y),_=Math.min(p.y,f.y,w.y),b=po.plane.normal;let v=b.x,x=b.y,C=b.z,S=po.plane.constant;x<0&&(v=-v,x=-x,C=-C,S=-S);for(let i=t,r=e+t;i<r;i++){const t=h[i],e=Math.min(t.start.y,t.end.y),r=Math.max(t.start.y,t.end.y);if(y<=e){s&&s.yBoundsCulled++;continue}const o=t.end.x-t.start.x,a=t.end.z-t.start.z,l=o*o+a*a;if(l>1e-20){const e=1/Math.sqrt(l),i=o*e,n=a*e,r=-n,c=i,h=p.x-t.start.x,u=p.z-t.start.z,d=f.x-t.start.x,m=f.z-t.start.z,g=w.x-t.start.x,y=w.z-t.start.z,_=h*i+u*n,b=d*i+m*n,v=g*i+y*n,x=1/e,C=Math.min(_,b,v);if(Math.max(_,b,v)<0||C>x){s&&s.xzBoundsCulled++;continue}const S=h*r+u*c,A=d*r+m*c,P=g*r+y*c,T=Math.min(S,A,P),E=Math.max(S,A,P);if(T>0||E<0){s&&s.xzBoundsCulled++;continue}}const c=v*t.start.x+x*t.start.y+C*t.start.z+S,u=v*t.end.x+x*t.end.y+C*t.end.z+S;if(c>=0&&u>=0)s&&s.planeTrimCulled++;else if(Sr(po,t))s&&s.triangleEdgeCulled++;else{if(r<_)ho.copy(t);else if(!Zr(po,t,ho)){s&&s.planeTrimCulled++;continue}ho.distance()<1e-10?s&&s.distThresholdCulled++:no(ho,po,uo)?(s&&s.used++,ao(t,uo,n[i])):s&&s.noOverlapCulled++}}}}})}po.update=()=>{po.plane.setFromCoplanarPoints(...po.points)};let mo=!1;const go={},wo={};let yo=null,_o=0,bo=0;const vo={get enabled(){return mo},set enabled(t){mo=t},reset(){for(const t in go)delete go[t];for(const t in wo)delete wo[t];yo=null,_o=0,bo=0},setStat(t,e){wo[t]=e},startTotal(){mo&&(bo=performance.now())},startStep(t){mo&&(null!==yo&&this.endStep(),yo=t,_o=performance.now())},endStep(){if(!mo||null===yo)return;const t=performance.now()-_o;go[yo]=t,yo=null},printSummary(){if(!mo)return;null!==yo&&this.endStep();const t=performance.now()-bo;console.log("\n=== Projection Summary ==="),console.log(`Total time: ${t.toFixed(1)}ms\n`);for(const[e,i]of Object.entries(go)){const n=(i/t*100).toFixed(1);console.log(` ${e}: ${i.toFixed(1)}ms (${n}%)`)}if(Object.keys(wo).length>0){console.log("\n--- Stats ---");for(const[t,e]of Object.entries(wo))console.log(` ${t}: ${e}`)}console.log("")}},xo=1e-5,Co=1e-16,So=1e-16;function Ao(t,e,i,n,s){t.bvhcast(e,i.matrixWorld,{intersectsRanges:(t,e,i,r)=>{n._edgeOffsets.push(t),n._edgeCounts.push(e),n._meshOffsets.push(i),n._meshCounts.push(r),n._meshIndex.push(s),n.groupCount++}})}let Po=null;async function To(t,e,i,n,s=null){const r=await async function(){return null===Po&&(Po=new V.WebGPURenderer,await Po.init()),Po}();t._edgeOffsets&&(t.edgeOffsets=new Uint32Array(t._edgeOffsets),t.edgeCounts=new Uint32Array(t._edgeCounts),t.meshOffsets=new Uint32Array(t._meshOffsets),t.meshCounts=new Uint32Array(t._meshCounts),t.meshIndex=new Uint32Array(t._meshIndex),t._edgeOffsets=null,t._edgeCounts=null,t._meshOffsets=null,t._meshCounts=null,t._meshIndex=null);const o=L(function(t){const e=new Float32Array(6*t.length);for(let i=0;i<t.length;i++){const n=t[i];e[6*i+0]=n.start.x,e[6*i+1]=n.start.y,e[6*i+2]=n.start.z,e[6*i+3]=n.end.x,e[6*i+4]=n.end.y,e[6*i+5]=n.end.z}return e}(i.lines),"float");vo.enabled&&console.log("Number of meshes:",e.length),vo.enabled&&console.log("Group count:",t.groupCount);const a=[];{let t=0;for(;t<e.length;){let i=t,n=0;for(;i<e.length;){const s=e[i].geometry,r=s.index?s.index.count/3:s.attributes.position.count/3;if(i>t&&(i-t>=1e3||n+r>1e5))break;n+=r,i++}a.push({start:t,end:i}),t=i}}vo.enabled&&console.log(`Split ${e.length} meshes into ${a.length} batches`);let l=0,c=0,h=0,u=0,d=0;for(let i=0;i<a.length;i++){const{start:p,end:f}=a[i],m=f-p;vo.enabled&&console.log(`Processing batch ${i+1}/${a.length} (meshes ${p}-${f-1})`);let g=0,w=0;const y=[];for(let t=p;t<f;t++){const i=e[t].geometry;y.push(w/3),g+=i.attributes.position.array.length,w+=i.index.array.length}const _=new Float32Array(g),b=new Uint32Array(w);let v=0,x=0,C=0;for(let t=p;t<f;t++){const i=e[t].geometry,n=i.attributes.position.array,s=i.index.array;_.set(n,v),v+=n.length;for(let t=0;t<s.length;t++)b[x+t]=s[t]+C;x+=s.length,C+=i.attributes.position.count}const S=new Float32Array(16*m);for(let t=p;t<f;t++){const i=t-p;S.set(e[t].matrixWorld.elements,16*i)}const A=[];for(let e=0;e<t.groupCount;e++){const i=t.meshIndex[e];if(i>=p&&i<f){const n=i-p,s=y[n]+t.meshOffsets[e];A.push({edgeOffset:t.edgeOffsets[e],edgeCount:t.edgeCounts[e],triOffset:s,triCount:t.meshCounts[e],meshIdx:n})}}if(0===A.length){vo.enabled&&console.log(` Batch ${i+1}: no groups, skipping`);continue}const P=new Uint32Array(5*A.length);for(let t=0;t<A.length;t++){const e=A[t],i=5*t;P[i+0]=e.edgeOffset,P[i+1]=e.edgeCount,P[i+2]=e.triOffset,P[i+3]=e.triCount,P[i+4]=e.meshIdx}let T=0;for(let t=0;t<A.length;t++)T+=A[t].edgeCount*A[t].triCount;s&&(s.candidates+=T);let E=Math.min(Math.ceil(.1*T),2e6),M=Math.max(E,1e4);vo.enabled&&console.log(` Batch ${i+1}: ${A.length} groups, ${g/3} vertices, ${w/3} triangles, ${T} pairs, buffer for ${M} overlaps`);const I=performance.now(),z=L(_,"float"),D=L(b,"uint"),k=L(S,"float"),B=L(P,"uint");let O=L(new Uint32Array([0]),"uint").toAtomic(),N=L(new Float32Array(3*M),"float");u+=performance.now()-I;const V=performance.now(),st=F(()=>{const t=R.mul(5),e=B.element(t),i=B.element(t.add(1)),n=B.element(t.add(2)),s=B.element(t.add(3)),r=B.element(t.add(4)).mul(16),a=U(k.element(r),k.element(r.add(1)),k.element(r.add(2)),k.element(r.add(3)),k.element(r.add(4)),k.element(r.add(5)),k.element(r.add(6)),k.element(r.add(7)),k.element(r.add(8)),k.element(r.add(9)),k.element(r.add(10)),k.element(r.add(11)),k.element(r.add(12)),k.element(r.add(13)),k.element(r.add(14)),k.element(r.add(15)));j({start:$(0),end:s.toInt(),type:"int",condition:"<",name:"triIdx"},({triIdx:t})=>{const s=n.add(t.toUint()).mul(3),r=D.element(s),l=D.element(s.add(1)),c=D.element(s.add(2)),h=W(z.element(r.mul(3)),z.element(r.mul(3).add(1)),z.element(r.mul(3).add(2))),u=W(z.element(l.mul(3)),z.element(l.mul(3).add(1)),z.element(l.mul(3).add(2))),d=W(z.element(c.mul(3)),z.element(c.mul(3).add(1)),z.element(c.mul(3).add(2))),p=a.mul(G(h,H(1))).xyz,f=a.mul(G(u,H(1))).xyz,m=a.mul(G(d,H(1))).xyz,g=f.sub(p),w=m.sub(p),y=Z(g,w),_=y.dot(y);q(_.lessThan(H(4e-16*Co)),()=>{Y()}),q(y.y.lessThan(0),()=>{Y()});const b=X(p.y,X(f.y,m.y));j({start:$(0),end:i.toInt(),type:"int",condition:"<",name:"edgeIdx"},({edgeIdx:t})=>{const i=e.add(t.toUint()),n=i.mul(6),s=W(o.element(n),o.element(n.add(1)),o.element(n.add(2))),r=W(o.element(n.add(3)),o.element(n.add(4)),o.element(n.add(5))),a=K(s.y,r.y);q(b.lessThanEqual(a),()=>{Y()});const l=Q(y),c=l.dot(p).negate(),h=l.y.lessThan(0),u=J(h,l.negate(),l),d=J(h,c.negate(),c),g=u.dot(s).add(d),w=u.dot(r).add(d),_=g.lessThan(0),v=w.lessThan(0),x=tt(g).lessThan(H(xo)),C=_.not().and(v.not()),S=w.sub(g),A=tt(S).lessThan(H(xo)),P=A.and(x.or(_.not()));q(P,()=>{Y()}),q(C.and(A.not()),()=>{Y()});const T=g.negate().div(S),E=et(s,r,T),I=W(J(A.or(_),s.x,E.x),J(A.or(_),s.y,E.y),J(A.or(_),s.z,E.z)),z=W(J(A.or(v),r.x,E.x),J(A.or(v),r.y,E.y),J(A.or(v),r.z,E.z)),D=z.sub(I),k=D.dot(D);q(k.lessThan(H(xo)),()=>{Y()});const B=s.sub(p),V=s.sub(f),L=s.sub(m),F=r.sub(p),R=r.sub(f),U=r.sub(m),j=B.dot(B).lessThanEqual(H(xo)),$=V.dot(V).lessThanEqual(H(xo)),G=L.dot(L).lessThanEqual(H(xo)),st=F.dot(F).lessThanEqual(H(xo)),rt=R.dot(R).lessThanEqual(H(xo)),ot=U.dot(U).lessThanEqual(H(xo)),at=j.or($).or(G),lt=st.or(rt).or(ot),ct=at.and(lt);q(ct,()=>{Y()});const ht=W(p.x,H(0),p.z),ut=W(f.x,H(0),f.z),dt=W(m.x,H(0),m.z),pt=W(I.x,H(0),I.z),ft=W(z.x,H(0),z.z),mt=W(s.x,H(0),s.z),gt=W(r.x,H(0),r.z).sub(mt),wt=gt.dot(gt);q(wt.lessThan(H(xo)),()=>{Y()});const yt=wt.sqrt(),_t=ut.sub(ht),bt=dt.sub(ht),vt=Z(_t,bt),xt=vt.dot(vt);q(xt.lessThanEqual(H(4e-16*Co)),()=>{Y()});const Ct=ft.sub(pt),St=Ct.dot(Ct);q(St.lessThan(H(xo)),()=>{Y()});const At=St.sqrt(),Pt=Ct.div(At),Tt=gt.div(yt),Et=Q(vt),Mt=Z(Pt,Et),It=H(0).toVar(),zt=H(0).toVar(),Dt=H(0).toVar(),kt=H(0).toVar(),Bt=it(0).toVar(),Ot=Mt.dot(ht.sub(pt)),Nt=Mt.dot(ut.sub(pt)),Vt=tt(Ot).lessThan(H(So)),Lt=tt(Nt).lessThan(H(So)),Ft=Vt.not().and(Lt.not()).and(Ot.mul(Nt).lessThan(0));q(Ft,()=>{const t=Ot.div(Ot.sub(Nt)),e=et(ht.x,ut.x,t),i=et(ht.z,ut.z,t);q(Bt.equal(0),()=>{It.assign(e),zt.assign(i)}).Else(()=>{Dt.assign(e),kt.assign(i)}),Bt.addAssign(1)}).ElseIf(Vt,()=>{q(Bt.equal(0),()=>{It.assign(ht.x),zt.assign(ht.z)}).Else(()=>{Dt.assign(ht.x),kt.assign(ht.z)}),Bt.addAssign(1)});const Rt=Nt,Ut=Mt.dot(dt.sub(pt)),jt=Lt,$t=tt(Ut).lessThan(H(So)),Wt=jt.not().and($t.not()).and(Rt.mul(Ut).lessThan(0));q(Bt.lessThan(2),()=>{q(Wt,()=>{const t=Rt.div(Rt.sub(Ut)),e=et(ut.x,dt.x,t),i=et(ut.z,dt.z,t);q(Bt.equal(0),()=>{It.assign(e),zt.assign(i)}).Else(()=>{Dt.assign(e),kt.assign(i)}),Bt.addAssign(1)}).ElseIf(jt.and(Ft.not()).and(Vt.not()),()=>{q(Bt.equal(0),()=>{It.assign(ut.x),zt.assign(ut.z)}).Else(()=>{Dt.assign(ut.x),kt.assign(ut.z)}),Bt.addAssign(1)})});const Gt=Ut,Ht=Ot,Zt=$t,qt=Vt,Yt=Zt.not().and(qt.not()).and(Gt.mul(Ht).lessThan(0));q(Bt.lessThan(2),()=>{q(Yt,()=>{const t=Gt.div(Gt.sub(Ht)),e=et(dt.x,ht.x,t),i=et(dt.z,ht.z,t);q(Bt.equal(0),()=>{It.assign(e),zt.assign(i)}).Else(()=>{Dt.assign(e),kt.assign(i)}),Bt.addAssign(1)}).ElseIf(Zt.and(Wt.not()).and(jt.not()),()=>{q(Bt.equal(0),()=>{It.assign(dt.x),zt.assign(dt.z)}).Else(()=>{Dt.assign(dt.x),kt.assign(dt.z)}),Bt.addAssign(1)})}),q(Bt.notEqual(2),()=>{Y()});const Xt=W(It,H(0),zt),Kt=W(Dt,H(0),kt).sub(Xt).dot(Pt),Qt=W(It,H(0),zt).toVar(),Jt=W(Dt,H(0),kt).toVar();q(Kt.lessThan(0),()=>{const t=It,e=zt;Qt.x.assign(Dt),Qt.z.assign(kt),Jt.x.assign(t),Jt.z.assign(e)});const te=H(0),ee=At,ie=Qt.sub(pt).dot(Pt),ne=Jt.sub(pt).dot(Pt),se=ee.lessThanEqual(ie).or(ne.lessThanEqual(te));q(se,()=>{Y()});const re=X(te,ie),oe=K(ee,ne),ae=pt.add(Pt.mul(re)),le=pt.add(Pt.mul(oe)),ce=ae.sub(mt).dot(Tt).div(yt),he=le.sub(mt).dot(Tt).div(yt),ue=X(H(0),K(H(1),ce)),de=X(H(0),K(H(1),he)),pe=tt(de.sub(ue));q(pe.lessThanEqual(H(So)),()=>{Y()});const fe=nt(O.element(0),1);q(fe.lessThan(it(M)),()=>{const t=fe.mul(3);N.element(t).assign(i.toFloat()),N.element(t.add(1)).assign(ue),N.element(t.add(2)).assign(de)})})})})().compute(A.length);d+=performance.now()-V;const rt=performance.now();await r.computeAsync(st),l+=performance.now()-rt;const ot=performance.now(),at=await r.getArrayBufferAsync(O.value),lt=new Uint32Array(at)[0];if(s&&(s.used+=Math.min(lt,M)),vo.enabled&&console.log(` Batch ${i+1}: ${lt} overlaps found (capacity: ${M})`),lt>M&&vo.enabled&&console.warn(` WARNING: Overlap buffer overflow! ${lt} > ${M}. Some occlusion data lost.`),lt>0){const t=await r.getArrayBufferAsync(N.value),e=new Float32Array(t);c+=performance.now()-ot;const i=performance.now(),s=Math.min(lt,M);for(let t=0;t<s;t++){const i=3*t,s=Math.round(e[i]);lo([e[i+1],e[i+2]],n[s])}h+=performance.now()-i,vo.enabled&&console.log(` Processed ${s} overlaps into hiddenOverlapMap`)}else c+=performance.now()-ot}r.dispose(),Po=null;const p=u+d+l+c+h;vo.enabled&&(console.log(`WebGPU timing breakdown (total: ${p.toFixed(1)}ms):`),console.log(` Buffer creation: ${u.toFixed(1)}ms`),console.log(` Shader build: ${d.toFixed(1)}ms`),console.log(` GPU compute: ${l.toFixed(1)}ms`),console.log(` Readback: ${c.toFixed(1)}ms`),console.log(` CPU merge: ${h.toFixed(1)}ms`))}const Eo=new h(0,1,0);function Mo(t,e=null){const i=new Float32Array(6*t.length);let n=0;for(let e=0,s=t.length;e<s;e++){const s=t[e];i[n++]=s[0],i[n++]=0,i[n++]=s[2],i[n++]=s[3],i[n++]=0,i[n++]=s[5]}const s=new N,r=new c(i,3,!0);if(s.setAttribute("position",r),e){const i=new Float32Array(2*t.length);for(let t=0,n=e.length;t<n;t++)i[2*t]=e[t],i[2*t+1]=e[t];s.setAttribute("group",new c(i,1))}return s}class Io{constructor(t,e=!0){this.meshes=Nr(t),this.bvhs=new Map,this.visibleEdges=[],this.hiddenEdges=[],this.visibleGroupIndices=[],this.hiddenGroupIndices=[],this.groupKeyToIndex=null,this.hasGroups=!1,this.iterationTime=30,this.useWebGPU=e}reset(){this.visibleEdges.length=0,this.hiddenEdges.length=0,this.visibleGroupIndices.length=0,this.hiddenGroupIndices.length=0,this.groupKeyToIndex=null,this.hasGroups=!1}getVisibleLineGeometry(){return Mo(this.visibleEdges,this.groupKeyToIndex?this.visibleGroupIndices:null)}getHiddenLineGeometry(){return Mo(this.hiddenEdges,this.groupKeyToIndex?this.hiddenGroupIndices:null)}getGroupKeys(){return this.groupKeyToIndex?Object.fromEntries(this.groupKeyToIndex):{}}addEdges(...t){const e=this.iterationTime;this.iterationTime=1/0;const i=this.addEdgesGenerator(...t).next().value;return this.iterationTime=e,i}*addEdgesGenerator(t,e={}){const{meshes:i,bvhs:n,visibleEdges:s,hiddenEdges:r,iterationTime:o}=this;let a=performance.now();vo.startStep("Building mesh BVH");for(let t=0;t<i.length;t++){performance.now()-a>o&&(yield,a=performance.now());const e=i[t].geometry;if(!n.has(e)){const t=e.boundsTree||new Qs(e);n.set(e,t)}}let l=0;for(let t=0;t<i.length;t++){const e=i[t].geometry;l+=e.index?e.index.count/3:e.attributes.position.count/3}const c={};for(let e=0;e<t.length;e++)c[e]=[];vo.startStep("Building line BVH");const h=new jr(t,{maxLeafSize:2,strategy:2});vo.startStep("BVHcast overlaps"),a=performance.now();const u={candidates:0,backFaceCulled:0,yBoundsCulled:0,xzBoundsCulled:0,triangleEdgeCulled:0,planeTrimCulled:0,distThresholdCulled:0,noOverlapCulled:0,used:0,totalEdges:t.length,totalTriangles:l},d=this.useWebGPU,p={};d&&(p._edgeOffsets=[],p._edgeCounts=[],p._meshOffsets=[],p._meshCounts=[],p._meshIndex=[],p.groupCount=0);for(let t=0;t<i.length;t++){performance.now()-a>o&&(e.onProgress&&e.onProgress(t,i.length),yield,a=performance.now());const s=i[t];d?Ao(h,n.get(s.geometry),s,p,t):fo(h,n.get(s.geometry),s,c,u)}if(d){let t=!1;for(To(p,i,h,c,u).then(()=>{t=!0});!t;)yield}const f=u.totalEdges*u.totalTriangles;if(vo.setStat("Total edges",u.totalEdges.toLocaleString()),vo.setStat("Total triangles",u.totalTriangles.toLocaleString()),vo.setStat("Brute-force pairs (edges × triangles)",f.toLocaleString()),vo.setStat("BVH candidate pairs",u.candidates.toLocaleString()),f>0&&vo.setStat("BVH reduction",(u.candidates/f*100).toFixed(3)+"% of brute-force"),u.candidates>0){const t=u.candidates,e=e=>(e/t*100).toFixed(2)+"%";d||(vo.setStat("Rejected: back-face culling",u.backFaceCulled.toLocaleString()+" ("+e(u.backFaceCulled)+")"),vo.setStat("Rejected: Y-bounds (tri below edge)",u.yBoundsCulled.toLocaleString()+" ("+e(u.yBoundsCulled)+")"),vo.setStat("Rejected: XZ-bounds (no 2D overlap)",u.xzBoundsCulled.toLocaleString()+" ("+e(u.xzBoundsCulled)+")"),vo.setStat("Rejected: edge lies on triangle",u.triangleEdgeCulled.toLocaleString()+" ("+e(u.triangleEdgeCulled)+")"),vo.setStat("Rejected: line above tri plane",u.planeTrimCulled.toLocaleString()+" ("+e(u.planeTrimCulled)+")"),vo.setStat("Rejected: trimmed edge too small",u.distThresholdCulled.toLocaleString()+" ("+e(u.distThresholdCulled)+")"),vo.setStat("Rejected: no projected overlap",u.noOverlapCulled.toLocaleString()+" ("+e(u.noOverlapCulled)+")")),vo.setStat("Producing overlaps",u.used.toLocaleString()+" ("+e(u.used)+")")}vo.startStep("Converting overlaps to lines");const m=this.hasGroups;for(let e=0;e<t.length;e++){performance.now()-a>o&&(yield,a=performance.now());const i=t[e],n=c[e],l=s.length,h=r.length;if(Pr(i,n,!1,s),Pr(i,n,!0,r),m){const t=i.groupIndex;for(let e=l;e<s.length;e++)this.visibleGroupIndices.push(t);for(let e=h;e<r.length;e++)this.hiddenGroupIndices.push(t)}}}}class zo{constructor(){this.iterationTime=30,this.angleThreshold=50,this.includeIntersectionEdges=!0,this.useWebGPU=!0}generateAsync(t,e={}){return new Promise((i,n)=>{const{signal:s}=e,r=this.generate(t,e);!function t(){if(s&&s.aborted)return void n(new Error("ProjectionGenerator: Process aborted via AbortSignal."));const e=r.next();e.done?i(e.value):requestAnimationFrame(t)}()})}*generate(t,e){const{iterationTime:i,angleThreshold:n,includeIntersectionEdges:s}=this,{onProgress:r=()=>{},visibilityCuller:o=null,groupFn:a=null}=e;if(vo.reset(),vo.startTotal(),t.isBufferGeometry&&(t=new b(t)),o){vo.startStep("Visibility culling");let e=!1;for(o.cull(t).then(i=>{(t=new M).children=i,e=!0});!e;)yield}const l=new Rr;l.iterationTime=i,l.thresholdAngle=n,l.projectionDirection.copy(Eo),vo.startStep("Generating candidate edges"),r("Generating candidate edges");let c=[],h=a?[]:null;if(yield*l.getEdgesGenerator(t,c,h),s&&(vo.startStep("Generating intersection edges"),r("Generating intersection edges"),yield*l.getIntersectionEdgesGenerator(t,c,h)),vo.startStep("Pre-filtering edges"),r("Pre-filtering edges"),h){const t=[],e=[];for(let i=0;i<c.length;i++)Cr(c[i])||(t.push(c[i]),e.push(h[i]));c=t,h=e}else c=c.filter(t=>!Cr(t));yield;const u=new Io(t,this.useWebGPU);if(u.iterationTime=i,a&&h){const t=new Map;for(let e=0;e<c.length;e++){const i=a(h[e]);t.has(i)||t.set(i,t.size),c[e].groupIndex=t.get(i)}u.groupKeyToIndex=t,u.hasGroups=!0}return r("Building BVH & computing overlaps"),yield*u.addEdgesGenerator(c,{onProgress:r?(t,e)=>{r("Building BVH & computing overlaps",t/e,u)}:null}),vo.printSummary(),u}}new u,new u,new h;const Do=class t extends ht{constructor(i){super(i),e(this,"enabled",!0),e(this,"onDisposed",new at),e(this,"generator",new zo),e(this,"cullerPixelsPerMeter",.05),e(this,"projectionDirection",new o.Vector3(0,-1,0)),e(this,"nearPlane",-1/0),e(this,"farPlane",1/0),this.components.add(t.uuid,this),this.generator.includeIntersectionEdges=!1}async get(t,e,i){const n=this.components.get(gr),s=new o.Group,r=new Map;for(const[e,i]of Object.entries(t)){const t=n.list.get(e);if(!t)continue;const a=(await t.getItemsIdsWithGeometry()).filter(t=>i.has(t));if(0===a.length)continue;const l=await t.getItemsGeometry(a);for(const i in l){const n=l[i];for(const i of n){if(!(i.positions&&i.indices&&i.transform&&i.representationId))continue;const n=i.representationId;if(!r.has(n)){const t=new o.BufferGeometry;t.setAttribute("position",new o.Float32BufferAttribute(i.positions,3)),i.normals&&t.setAttribute("normal",new o.Float32BufferAttribute(i.normals,3)),t.setIndex(Array.from(i.indices)),r.set(n,t)}const a=r.get(n),l=new o.Mesh(a);l.applyMatrix4(i.transform),l.applyMatrix4(t.object.matrixWorld),l.updateWorldMatrix(!0,!0),l.userData._edgeProjectorModelId=e,l.userData._edgeProjectorLocalId=i.localId,s.add(l)}}}const a=this.projectionDirection.clone().normalize(),l=new o.Vector3(0,-1,0),c=(new o.Quaternion).setFromUnitVectors(a,l),h=(new o.Matrix4).makeRotationFromQuaternion(c),u=h.clone().invert();for(const t of s.children)t.applyMatrix4(h),t.updateWorldMatrix(!1,!1);if(s.traverse(t=>{const e=t;if(e.geometry&&!e.geometry.boundsTree){const t=e.geometry.index?e.geometry.index.count:e.geometry.attributes.position.count;e.geometry.groups.forEach(e=>{e.count===1/0&&(e.count=t-e.start)}),e.geometry.boundsTree=new Qs(e.geometry,{maxLeafSize:1,strategy:2})}}),this.nearPlane!==-1/0||this.farPlane!==1/0){const t=new o.Box3,e=[];for(const i of s.children){const n=i;n.geometry&&(t.setFromObject(n),(t.max.y<this.nearPlane||t.min.y>this.farPlane)&&e.push(n))}for(const t of e)s.remove(t)}const d=e.renderer.three,p=new yr(d,{pixelsPerMeter:this.cullerPixelsPerMeter}),f=await this.generator.generateAsync(s,{visibilityCuller:p,groupFn:t=>`${t.userData._edgeProjectorModelId??"unknown"}:${t.userData._edgeProjectorLocalId??0}`,onProgress:null==i?void 0:i.onProgress}),m=f.getVisibleLineGeometry(),g=f.getHiddenLineGeometry();m.applyMatrix4(u),g.applyMatrix4(u);const w=f.getGroupKeys(),y={};for(const[t,e]of Object.entries(w)){const i=t.lastIndexOf(":"),n=t.substring(0,i),s=Number(t.substring(i+1));y[e]={modelId:n,localId:s}}for(const t of r.values())t.dispose();return{visible:m,hidden:g,groups:y}}dispose(){this.onDisposed.trigger(t.uuid),this.onDisposed.reset()}};e(Do,"uuid","f2e76c3a-8b1d-4d5e-9a3f-7c6b2d4e8f1a");let ko=Do;class Bo{constructor(){e(this,"wasm",{path:"",absolute:!1,logLevel:st.LogLevel.LOG_LEVEL_OFF}),e(this,"webIfc",{COORDINATE_TO_ORIGIN:!0}),e(this,"autoSetWasm",!0),e(this,"customLocateFileHandler",null)}}const Oo=class t extends ht{constructor(i){super(i),e(this,"onDisposed",new at),e(this,"onIfcStartedLoading",new at),e(this,"onIfcImporterInitialized",new at),e(this,"onSetup",new at),e(this,"settings",new Bo),e(this,"webIfc",new st.IfcAPI),e(this,"enabled",!0),this.components.add(t.uuid,this)}dispose(){this.webIfc=null,this.onDisposed.trigger(t.uuid),this.onDisposed.reset()}async setup(t){this.settings={...this.settings,...t},this.settings.autoSetWasm&&await this.autoSetWasm(),this.onSetup.trigger()}async load(t,e,n,s){const r=this.components.get(gr);if(!r.initialized)throw new Error("You need to initialize fragments first.");this.settings.autoSetWasm&&await this.autoSetWasm(),r.core.settings.autoCoordinate=e;const o=new i.IfcImporter;o.wasm.path=this.settings.wasm.path,o.wasm.absolute=this.settings.wasm.absolute,o.webIfcSettings=this.settings.webIfc,this.onIfcImporterInitialized.trigger(o),(null==s?void 0:s.instanceCallback)&&s.instanceCallback(o);const a=await o.process({...null==s?void 0:s.processData,bytes:t});return await r.core.load(a,{modelId:n,userData:null==s?void 0:s.userData})}async readIfcFile(t){const{path:e,absolute:i,logLevel:n}=this.settings.wasm;return this.webIfc.SetWasmPath(e,i),await this.webIfc.Init(this.settings.customLocateFileHandler||void 0),n&&this.webIfc.SetLogLevel(n),this.webIfc.OpenModel(t,this.settings.webIfc)}cleanUp(){try{this.webIfc.Dispose()}catch(t){console.log("Web-ifc wasn't disposed.")}this.webIfc=null,this.webIfc=new st.IfcAPI}async autoSetWasm(){const t=await fetch(`https://unpkg.com/@thatopen/components@${Da.release}/package.json`);if(!t.ok)return void console.warn("Couldn't get openbim-components package.json. Set wasm settings manually.");const e=await t.json();if("web-ifc"in e.peerDependencies){const t=e.peerDependencies["web-ifc"];this.settings.wasm.path=`https://unpkg.com/web-ifc@${t}/`,this.settings.wasm.absolute=!0}else console.warn("Couldn't get web-ifc from peer dependencies in openbim-components. Set wasm settings manually.")}};e(Oo,"uuid","a659add7-1418-4771-a0d6-7d4d438e4624");let No=Oo;const Vo=class t extends ht{constructor(i){super(i),e(this,"enabled",!0),this.components.add(t.uuid,this)}async set(t,e){const i=this.components.get(gr),n=[];if(e)for(const[s,r]of Object.entries(e)){const e=i.list.get(s);e&&n.push(e.setVisible([...r],t))}else for(const e of i.list.values())n.push(e.setVisible(void 0,t));await Promise.all(n),await i.core.update(!0)}async isolate(t){await Promise.all([this.set(!1),this.set(!0,t)])}async toggle(t){const e=[],i=this.components.get(gr);for(const[n,s]of Object.entries(t)){const t=i.list.get(n);t&&e.push(t.toggleVisible([...s]))}await Promise.all(e),await i.core.update(!0)}async getVisibilityMap(t,e){const i=[],n=[],s=this.components.get(gr);if(e)for(const r of e){const e=s.list.get(r);e&&(i.push(e.modelId),n.push(e.getItemsByVisibility(t)))}else for(const e of s.list.values())i.push(e.modelId),n.push(e.getItemsByVisibility(t));const r=await Promise.all(n),o={};for(const[t,e]of i.entries())o[e]=r[t];return o}};e(Vo,"uuid","dd9ccf2d-8a21-4821-b7f6-2949add16a29");let Lo=Vo;const Fo=class t extends ht{constructor(n){super(n),e(this,"enabled",!0),e(this,"onDisposed",new at),e(this,"list",new i.DataSet),this.components.add(t.uuid,this)}dispose(e=!0){this.list.clear(),this.onDisposed.trigger(t.uuid),e&&(this.onDisposed.reset(),this.list.eventsEnabled=!1,this.list.dispose())}get(){const t=new o.Box3;for(const e of this.list)t.union(e);return t}async addFromModelIdMap(t){const e=this.components.get(gr),i=new o.Box3;for(const[n,s]of Object.entries(t)){const t=e.list.get(n);if(!t)continue;const r=await t.getMergedBox([...s]);i.union(r)}this.list.add(i)}addFromModels(t){const e=this.components.get(gr);for(const[i,n]of e.list)t&&!t.some(t=>t.test(i))||this.list.add(n.box)}async getCenter(t){this.list.clear(),await this.addFromModelIdMap(t);const e=this.get();this.list.clear();const i=new o.Vector3;return e.getCenter(i),i}async getCameraOrientation(t,e=1){const i=this.components.get(gr);this.list.clear();for(const[t,e]of i.list)this.list.add(e.box);const n=this.get();this.list.clear();const s=new o.Vector3;n.getCenter(s);const r=new o.Vector3;n.getSize(r);const a=Math.max(r.x,r.y,r.z)*e,l=new o.Vector3;switch(t){case"front":default:l.set(s.x,s.y,s.z+a);break;case"back":l.set(s.x,s.y,s.z-a);break;case"left":l.set(s.x-a,s.y,s.z);break;case"right":l.set(s.x+a,s.y,s.z);break;case"top":l.set(s.x,s.y+a,s.z);break;case"bottom":l.set(s.x,s.y-a,s.z)}return{position:l,target:s}}};e(Fo,"uuid","d1444724-dba6-4cdd-a0c7-68ee1450d166");let Ro=Fo;class Uo{constructor(t,i){e(this,"name","Query"),e(this,"customData",{}),e(this,"_components"),e(this,"_queries",[]),e(this,"_aggregation","exclusive"),e(this,"result",null),e(this,"cache",!0),e(this,"serializeQueryParameters",t=>{var e;return{categories:null==(e=t.categories)?void 0:e.map(t=>t.source),attributes:t.attributes?{aggregation:t.attributes.aggregation,queries:t.attributes.queries.map(this.serializeAttributeQuery)}:void 0,relation:t.relation?{name:t.relation.name,query:t.relation.query?this.serializeQueryParameters(t.relation.query):void 0}:void 0}}),e(this,"deserializeQueryParameters",t=>{var e;return{categories:null==(e=t.categories)?void 0:e.map(t=>new RegExp(t)),attributes:t.attributes?{aggregation:t.attributes.aggregation,queries:t.attributes.queries.map(this.deserializeAttributeQuery)}:void 0,relation:t.relation?{name:t.relation.name,query:t.relation.query?this.deserializeQueryParameters(t.relation.query):void 0}:void 0}}),this._components=t,this.queries=i}set queries(t){this._queries=t,this.clearCache()}get queries(){return this._queries}set aggregation(t){t!==this._aggregation&&this.clearCache(),this._aggregation=t}get aggregation(){return this._aggregation}async test(t){const{modelIds:e,force:i}={force:!1,...t};if(this.result&&!i)return this.result;const n=this._components.get($o),s=await n.getItems(this.queries,{modelIds:e,aggregation:this.aggregation});return this.cache&&(this.result=s),s}clearCache(){this.result=null}serializeAttributeQuery(t){let e;e=Array.isArray(t.value)?t.value.map(t=>t.source):t.value instanceof RegExp?t.value.source:t.value;return{name:t.name.source,value:e,type:t.type instanceof RegExp?t.type.source:t.type,negate:t.negate,itemIds:t.itemIds}}toJSON(){return{guid:this._components.get($o).list.getKey(this)??_t.create(),name:this.name,customData:this.customData,queries:this.queries.map(this.serializeQueryParameters),aggregation:this.aggregation,cache:this.cache}}deserializeAttributeQuery(t){let e;e=Array.isArray(t.value)?t.value.map(t=>new RegExp(t)):"string"==typeof t.value?new RegExp(t.value):t.value;return{name:new RegExp(t.name),value:e,type:t.type?new RegExp(t.type):void 0,negate:t.negate,itemIds:t.itemIds}}fromJSON(t){return this.name=t.name,this.customData=t.customData,this.aggregation=t.aggregation,this.cache=t.cache,this.queries=t.queries.map(this.deserializeQueryParameters),this}}const jo=class t extends ht{constructor(n){super(n),e(this,"enabled",!0),e(this,"list",new i.DataMap),n.add(t.uuid,this)}async getItems(t,e){let i;if(e){const{modelIds:t,items:n}=e;if(n){const t=Object.keys(n);t.length>0&&(i=t.map(t=>new RegExp(`^${t}$`)))}else t&&(i=t)}const n=(null==e?void 0:e.aggregation)??"exclusive",s=this.components.get(gr),r=await Promise.all(t.map(async t=>{const n={};return await Promise.all(Array.from(s.list).map(async([s,r])=>{var o;if(i&&!i.some(t=>t.test(s)))return;const a=null==(o=null==e?void 0:e.items)?void 0:o[s],l=await r.getItemsByQuery(t,{localIds:a?[...a]:void 0});n[s]=new Set(l)})),n}));return"inclusive"===n?li.join(r):li.intersect(r)}create(t,e){const i=new Uo(this.components,e);return this.list.set(t,i),i}async addFromCategories(t){const e=new Set,i=this.components.get(gr);for(const[n,s]of i.list){if(t&&!t.some(t=>t.test(n)))continue;const i=(await s.getItemsWithGeometryCategories()).filter(t=>null!==t),r=new Set(i);for(const t of r)this.list.has(t)||(this.create(t,[{categories:[new RegExp(`^${t}$`)]}]),e.add(t))}return[...e]}import(t){const{data:e}=t,i=[];if(!e)return i;for(const t of e){const e=this.create(t.guid,[]);e.fromJSON(t),i.push(e)}return i}export(){const t=[];for(const[e,i]of this.list.entries()){const n={...i.toJSON(),name:e};t.push(n)}return{data:t}}};e(jo,"uuid","0da7ad77-f734-42ca-942f-a074adfd1e3a");let $o=jo;const Wo=class t extends ht{constructor(n){super(n),e(this,"enabled",!0),e(this,"onDisposed",new at),e(this,"list",new i.DataMap),e(this,"defaultSaveFunction",t=>"value"in t.Name?t.Name.value:null),e(this,"onBeforeFragmentsDispose",async t=>{const{key:e,value:i}=t,n=await i.getLocalIds(),s={[e]:new Set(n)};this.removeItems(s)}),n.add(t.uuid,this),this.setupEvents();n.get(gr).list.onBeforeDelete.add(this.onBeforeFragmentsDispose)}setupEvents(){this.list.onBeforeDelete.add(({value:t})=>t.dispose())}getClassificationGroups(t){let e=this.list.get(t);return e||(e=new i.DataMap,this.list.set(t,e)),e}getModelItems(t,e,i){const{map:n}=this.getGroupData(t,e);let s=n[i];return s||(s=new Set,n[i]=s),s}getGroupData(t,e){const i=this.components.get($o),n=this.getClassificationGroups(t);let s=n.get(e);return s||(s={map:{},get:()=>new Promise(t=>{if(s)if(s.query){const{name:e,config:n}=s.query,r=i.list.get(e);if(!r)throw new Error("Classifier: the query name associated with the group doesn't exist in the ItemsFinder component");r.test(n).then(e=>{if(!s)return void t({});const i=li.join([e,s.map]);t(i)})}else t(s.map);else t({})})},n.set(e,s)),s}async aggregateItems(t,e,i){const n=(null==i?void 0:i.data)??void 0,s=(null==i?void 0:i.aggregationCallback)??this.defaultSaveFunction,r=this.components.get(gr),o=this.components.get($o),a=await o.getItems([e],{modelIds:null==i?void 0:i.modelIds});for(const[e,i]of Object.entries(a)){const o=r.list.get(e);if(!o)continue;const a=(i,...n)=>{const s=this.getModelItems(t,i,e);for(const t of n)s.add(t)},l=await o.getItemsData([...i],n);for(const t of l)s(t,a)}}addGroupItems(t,e,i){const{map:n}=this.getGroupData(t,e);li.add(n,i)}setGroupQuery(t,e,i){this.getGroupData(t,e).query=i}async find(t){const e=[];for(const[i,n]of Object.entries(t)){const t=[],s=this.list.get(i);if(!s)continue;for(const e of n){const i=s.get(e);if(!i)continue;const n=await i.get();t.push(n)}const r=li.join(t);e.push(r)}return li.intersect(e)}async aggregateItemRelations(t,e,i,n){const s=(null==n?void 0:n.attribute)??"Name",r={relations:{[i]:{attributes:!0,relations:!1}}};await this.aggregateItems(t,e,{modelIds:null==n?void 0:n.modelIds,data:r,aggregationCallback:(t,e)=>{if(!(null==t?void 0:t[s]))return;const n=t[s];if(!("value"in n))return;const r=t[i];if(Array.isArray(r))for(const t of r)"value"in t._localId&&e(n.value,t._localId.value)}})}async byIfcBuildingStorey(t){await this.aggregateItemRelations((null==t?void 0:t.classificationName)??"Storeys",{categories:[/BUILDINGSTOREY/]},"ContainsElements",{modelIds:null==t?void 0:t.modelIds})}async byCategory(t){const e=this.components.get($o),i=await e.addFromCategories(null==t?void 0:t.modelIds);for(const e of i)this.setGroupQuery((null==t?void 0:t.classificationName)??"Categories",e,{name:e})}dispose(){this.list.clear();this.components.get(gr).list.onBeforeDelete.remove(this.onBeforeFragmentsDispose),this.onDisposed.trigger()}removeItems(t,e){if(e&&e.classificationName){const i=this.list.get(e.classificationName);if(!i)return;if(e.groupName){if(!i.get(e.groupName))return}for(const[,e]of i)li.remove(e.map,t);return}for(const[,e]of this.list.entries())for(const[,i]of e)li.remove(i.map,t)}async byModel(t){const e=this.components.get(gr),i=(null==t?void 0:t.classificationName)??"Models";for(const[n,s]of e.list){if(t&&t.modelIds&&!t.modelIds.some(t=>t.test(n)))continue;const e=await s.getItemsIdsWithGeometry(),r={[n]:new Set(e)};this.getGroupData(i,n),this.addGroupItems(i,n,r)}}};e(Wo,"uuid","e25a7f3c-46c4-4a14-9d3d-5115f24ebeb7");let Go=Wo;const Ho=class t{constructor(t,i){if(e(this,"enabled",!0),e(this,"components"),e(this,"onDisposed",new at),e(this,"mouse"),e(this,"world"),e(this,"debugMode",!1),e(this,"_renderTarget"),e(this,"_renderTargetSize",new o.Vector2),e(this,"_debugCanvas"),e(this,"_debugContainer"),e(this,"_idMaterial"),e(this,"_depthMaterial"),e(this,"_normalMaterial"),e(this,"_originalMaterials",new Map),e(this,"_hiddenLods",[]),e(this,"_ownMeshes",new Map),!i.renderer)throw new Error("A renderer is needed for the FastModelPicker to work!");this.world=i,this.mouse=new mi(i.renderer.three.domElement),this.components=t,this._idMaterial=this.buildIdMaterial(),this._depthMaterial=this.buildDepthMaterial(),this._normalMaterial=this.buildNormalMaterial(),this.setupRenderTarget()}async getModelAt(t){const e=await this.runIdPass(t);return e?e.modelId:null}async getItemAt(t){const e=await this.runIdPass(t);if(!e)return null;const i=this.components.get(gr).list.get(e.modelId);if(!i)return null;const n=await i.getLocalIdsFromItemIds([e.itemId]),s=null==n?void 0:n[0];return null==s?null:{modelId:e.modelId,localId:s,itemId:e.itemId}}async getPointAt(t){if(!this.enabled)return null;if(!this._renderTarget||!this.world.renderer)return null;const e=this.components.get(gr);if(!e.initialized||0===e.list.size)return null;this.renderDepthPass();const i=t??this.mouse.position,n=this.readPixelAt(i);if(!n)return null;if(0===n[0]&&0===n[1]&&0===n[2]&&0===n[3])return null;const s=function(t){const e=t[0]/255,i=t[1]/255,n=t[2]/255,s=t[3]/255;return 255/256*(e/16777216+i/65536+n/256+s)}(n);return s>=.999999?null:function(t,e,i){const n=new o.Vector3(t.x,t.y,2*e-1);return n.unproject(i),n}(i,s,this.world.camera.three)}async getNormalAt(t){if(!this.enabled)return null;if(!this._renderTarget||!this.world.renderer)return null;const e=this.components.get(gr);if(!e.initialized||0===e.list.size)return null;this.renderNormalPass();const i=t??this.mouse.position,n=this.readPixelAt(i);if(!n)return null;if(0===n[3])return null;const s=n[0]/255*2-1,r=n[1]/255*2-1,a=n[2]/255*2-1,l=new o.Vector3(s,r,a);return l.lengthSq()<1e-8?null:l.normalize()}async getFullPick(t){const e=await this.getItemAt(t);if(!e)return null;const i=await this.getPointAt(t);if(!i)return null;const n=await this.getNormalAt(t),s=i.distanceTo(this.world.camera.three.position);return{...e,point:i,normal:n,distance:s}}setDebugMode(t){this.debugMode=t,t?this.setupDebugCanvas():this.removeDebugCanvas()}dispose(){this.mouse.dispose(),this.removeDebugCanvas(),this._idMaterial.dispose(),this._depthMaterial.dispose(),this._normalMaterial.dispose(),this._renderTarget&&this._renderTarget.dispose(),this._renderTarget=void 0,this._originalMaterials.clear(),this._hiddenLods.length=0,this.onDisposed.trigger(),this.onDisposed.reset()}async runIdPass(t){if(!this.enabled)return null;if(!this._renderTarget)return null;if(!this.world.renderer)return null;const e=this.components.get(gr);if(!e.initialized||0===e.list.size)return null;const i=this.applyIdMaterial();if(0===i.size)return this.restoreOriginalMaterials(),null;const n=t??this.mouse.position;this.renderIdPass(i,n),this.restoreOriginalMaterials(),this.debugMode&&this._debugCanvas&&this.updateDebugCanvas();const s=this.readPixelAt(this._renderTarget,n);if(!s)return null;const r=s[0];if(0===r)return null;const o=i.get(r);if(!o)return null;const a=s[1]<<16|s[2]<<8|s[3];if(0===a)return null;return{modelId:o,itemId:a-1}}applyIdMaterial(){const e=this.components.get(gr),i=new Map,n=this.getModelRoots();this._ownMeshes.clear();let s=1;for(const[r,a]of e.list){if(s>t.MAX_MODELS)break;const e=[];this.traverseOwn(a.object,n,t=>{if(!(t instanceof o.Mesh))return;const i=t.geometry;if(!i)return;if(!i.attributes||!i.attributes.id)return void(t.visible&&(this._hiddenLods.push(t),t.visible=!1));this._originalMaterials.set(t,t.material);const n=t.material,s=Array.isArray(n)?n.length:1;t.material=new Array(s).fill(this._idMaterial),e.push(t)}),e.length&&(this._ownMeshes.set(r,e),i.set(s,r),s+=1)}return i}getModelRoots(){const t=this.components.get(gr),e=new Set;for(const[,i]of t.list)e.add(i.object);return e}traverseOwn(t,e,i){const n=[t];for(;n.length;){const s=n.pop();if(s===t||!e.has(s)){i(s);for(const t of s.children)n.push(t)}}}renderIdPass(t,e){this.renderPickPass(t,this._renderTarget,this._idMaterial,e)}renderPickPass(t,e,i,n){const s=this.world.renderer.three,r=this.world.scene.three,a=this.world.camera.three,l=this.components.get(gr),c=s.clippingPlanes??[];i.clippingPlanes=c,i.clipping=c.length>0;const h=s.getRenderTarget(),u=s.autoClear,d=s.getClearColor(new o.Color),p=s.getClearAlpha(),f=s.getScissorTest(),m=s.getScissor(new o.Vector4);s.setRenderTarget(e),s.setClearColor(0,0),s.autoClear=!1,s.setScissorTest(!1),s.clear(!0,!0,!1);const g=e.width,w=e.height,y=Math.floor(.5*(n.x+1)*g),_=Math.floor(.5*(n.y+1)*(w-1)),b=Math.max(0,Math.min(g-4,y-2)),v=Math.max(0,Math.min(w-4,_-2)),x=s.getPixelRatio();s.setScissor(b/x,v/x,4/x,4/x),s.setScissorTest(!0);const C=new Map;for(const[t,e]of l.list)C.set(t,e.object);const S=new Set(C.values()),A=new Map;r.traverse(t=>{t!==r&&t.isMesh&&((t=>{let e=t;for(;e;){if(S.has(e))return!0;e=e.parent}return!1})(t)||(A.set(t,t.visible),t.visible=!1))});const P=new Map;for(const[t,e]of C){let i=!0,n=e;for(;n;){if(!n.visible){i=!1;break}n=n.parent}P.set(t,i)}const T=new Map;for(const t of C.values())T.set(t,t.visible),t.visible=!0;const E=new Map;for(const t of this._ownMeshes.values())for(const e of t)E.set(e,e.visible),e.visible=!1;for(const[e,n]of t){if(!P.get(n))continue;const t=this._ownMeshes.get(n);if(t){for(const e of t)e.visible=E.get(e);i.uniforms.modelByte.value=e,s.render(r,a);for(const e of t)e.visible=!1}}for(const[t,e]of E)t.visible=e;for(const[t,e]of T)t.visible=e;for(const[t,e]of A)t.visible=e;s.setScissorTest(f),s.setScissor(m),s.setRenderTarget(h),s.autoClear=u,s.setClearColor(d,p)}renderWithTileMaterial(t){const e=this.world.renderer.three,i=this.world.scene.three,n=this.world.camera.three,s=this.components.get(gr),r=e.clippingPlanes??[];t.clippingPlanes=r,t.clipping=r.length>0;const a=e.getRenderTarget(),l=e.autoClear,c=e.getClearColor(new o.Color),h=e.getClearAlpha(),u=new Map,d=[],p=this.getModelRoots();for(const[,e]of s.list)this.traverseOwn(e.object,p,e=>{if(!(e instanceof o.Mesh))return;const i=e.geometry;if(!i)return;if(!i.attributes||!i.attributes.id)return void(e.visible&&(d.push(e),e.visible=!1));if(!e.visible)return;u.set(e,e.material);const n=e.material,s=Array.isArray(n)?n.length:1;e.material=new Array(s).fill(t)});const f=new Set;for(const[,t]of s.list)f.add(t.object);const m=new Map;i.traverse(t=>{t!==i&&t.isMesh&&((t=>{let e=t;for(;e;){if(f.has(e))return!0;e=e.parent}return!1})(t)||(m.set(t,t.visible),t.visible=!1))}),e.setRenderTarget(this._renderTarget),e.setClearColor(0,0),e.autoClear=!1,e.clear(!0,!0,!1),e.render(i,n);for(const[t,e]of u)t.material=e;for(const t of d)t.visible=!0;for(const[t,e]of m)t.visible=e;e.setRenderTarget(a),e.autoClear=l,e.setClearColor(c,h)}renderDepthPass(){this.renderWithTileMaterial(this._depthMaterial)}renderNormalPass(){this.renderWithTileMaterial(this._normalMaterial)}restoreOriginalMaterials(){for(const[t,e]of this._originalMaterials)t.material=e;this._originalMaterials.clear(),this._ownMeshes.clear();for(const t of this._hiddenLods)t.visible=!0;this._hiddenLods.length=0}readPixelAt(t,e){let i,n;t instanceof o.WebGLRenderTarget?(i=t,n=e):(i=this._renderTarget,n=t);const s=this.world.renderer.three,r=this._renderTargetSize,a=Math.floor(.5*(n.x+1)*r.x),l=Math.floor(.5*(n.y+1)*(r.y-1)),c=Math.max(0,Math.min(r.x-1,a)),h=Math.max(0,Math.min(r.y-1,l)),u=new Uint8Array(4);return s.readRenderTargetPixels(i,c,h,1,1,u),u}buildIdMaterial(){return new o.ShaderMaterial({uniforms:{modelByte:{value:1}},vertexShader:"\n attribute vec4 id;\n varying vec4 vId;\n #if NUM_CLIPPING_PLANES > 0\n varying vec3 vClipPosition;\n #endif\n void main() {\n vId = id;\n vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);\n #if NUM_CLIPPING_PLANES > 0\n vClipPosition = -mvPosition.xyz;\n #endif\n gl_Position = projectionMatrix * mvPosition;\n }\n ",fragmentShader:"\n precision highp float;\n uniform float modelByte;\n varying vec4 vId;\n #if NUM_CLIPPING_PLANES > 0\n varying vec3 vClipPosition;\n uniform vec4 clippingPlanes[NUM_CLIPPING_PLANES];\n #endif\n void main() {\n #if NUM_CLIPPING_PLANES > 0\n for (int i = 0; i < NUM_CLIPPING_PLANES; i++) {\n vec4 plane = clippingPlanes[i];\n if (dot(vClipPosition, plane.xyz) > plane.w) discard;\n }\n #endif\n gl_FragColor = vec4(modelByte / 255.0, vId.y / 255.0, vId.z / 255.0, vId.w / 255.0);\n }\n ",side:o.DoubleSide})}buildDepthMaterial(){return new o.ShaderMaterial({uniforms:{},vertexShader:"\n #if NUM_CLIPPING_PLANES > 0\n varying vec3 vClipPosition;\n #endif\n void main() {\n vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);\n #if NUM_CLIPPING_PLANES > 0\n vClipPosition = -mvPosition.xyz;\n #endif\n gl_Position = projectionMatrix * mvPosition;\n }\n ",fragmentShader:"\n #if NUM_CLIPPING_PLANES > 0\n varying vec3 vClipPosition;\n uniform vec4 clippingPlanes[NUM_CLIPPING_PLANES];\n #endif\n void main() {\n #if NUM_CLIPPING_PLANES > 0\n for (int i = 0; i < NUM_CLIPPING_PLANES; i++) {\n vec4 plane = clippingPlanes[i];\n if (dot(vClipPosition, plane.xyz) > plane.w) discard;\n }\n #endif\n float v = gl_FragCoord.z;\n vec4 r = vec4(\n fract(v * 16777216.0),\n fract(v * 65536.0),\n fract(v * 256.0),\n v\n );\n r.yzw -= r.xyz * (1.0 / 256.0);\n gl_FragColor = r * (256.0 / 255.0);\n }\n ",side:o.DoubleSide})}buildNormalMaterial(){return new o.ShaderMaterial({uniforms:{},vertexShader:"\n varying vec3 vWorldNormal;\n #if NUM_CLIPPING_PLANES > 0\n varying vec3 vClipPosition;\n #endif\n void main() {\n vWorldNormal = normalize(\n (modelMatrix * vec4(normal, 0.0)).xyz\n );\n vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);\n #if NUM_CLIPPING_PLANES > 0\n vClipPosition = -mvPosition.xyz;\n #endif\n gl_Position = projectionMatrix * mvPosition;\n }\n ",fragmentShader:"\n varying vec3 vWorldNormal;\n #if NUM_CLIPPING_PLANES > 0\n varying vec3 vClipPosition;\n uniform vec4 clippingPlanes[NUM_CLIPPING_PLANES];\n #endif\n void main() {\n #if NUM_CLIPPING_PLANES > 0\n for (int i = 0; i < NUM_CLIPPING_PLANES; i++) {\n vec4 plane = clippingPlanes[i];\n if (dot(vClipPosition, plane.xyz) > plane.w) discard;\n }\n #endif\n vec3 n = normalize(vWorldNormal);\n if (!gl_FrontFacing) n = -n;\n gl_FragColor = vec4(n * 0.5 + 0.5, 1.0);\n }\n ",side:o.DoubleSide})}setupRenderTarget(){const t=this.world.renderer.three.getSize(new o.Vector2);this._renderTargetSize.copy(t);const e={format:o.RGBAFormat,type:o.UnsignedByteType,minFilter:o.NearestFilter,magFilter:o.NearestFilter,depthBuffer:!0};this._renderTarget=new o.WebGLRenderTarget(t.x,t.y,e),this.debugMode&&this.setupDebugCanvas(),this.world.renderer.onResize.add(t=>{this._renderTargetSize.copy(t),this._renderTarget.setSize(t.x,t.y),this._debugCanvas&&(this._debugCanvas.width=t.x,this._debugCanvas.height=t.y)})}setupDebugCanvas(){if(this._debugCanvas)return;const t=this.world.renderer.three.getSize(new o.Vector2);this._debugContainer=document.createElement("div"),this._debugContainer.style.position="fixed",this._debugContainer.style.top="10px",this._debugContainer.style.right="10px",this._debugContainer.style.width="300px",this._debugContainer.style.height="300px",this._debugContainer.style.border="2px solid #fff",this._debugContainer.style.backgroundColor="#000",this._debugContainer.style.zIndex="10000",this._debugContainer.style.pointerEvents="none",this._debugCanvas=document.createElement("canvas"),this._debugCanvas.width=t.x,this._debugCanvas.height=t.y,this._debugCanvas.style.width="100%",this._debugCanvas.style.height="100%",this._debugCanvas.style.imageRendering="pixelated",this._debugContainer.appendChild(this._debugCanvas),document.body.appendChild(this._debugContainer)}removeDebugCanvas(){this._debugContainer&&(this._debugContainer.remove(),this._debugContainer=void 0,this._debugCanvas=void 0)}updateDebugCanvas(){if(!this._debugCanvas||!this._renderTarget||!this.world.renderer)return;const t=this.world.renderer.three,e=this._renderTargetSize,i=new Uint8Array(e.x*e.y*4);t.readRenderTargetPixels(this._renderTarget,0,0,e.x,e.y,i);const n=this._debugCanvas.getContext("2d");if(!n)return;const s=n.createImageData(e.x,e.y),r=4*e.x;for(let t=0;t<e.y;t++){const n=t*r,o=(e.y-1-t)*r;s.data.set(i.subarray(n,n+r),o)}n.putImageData(s,0,0)}};e(Ho,"MAX_MODELS",254);let Zo=Ho;const qo=class t extends ht{constructor(i){super(i),e(this,"enabled",!0),e(this,"list",new Map),e(this,"onDisposed",new at),i.add(t.uuid,this)}get(t){if(this.list.has(t.uuid))return this.list.get(t.uuid);const e=new Zo(this.components,t);return this.list.set(t.uuid,e),t.onDisposed.add(()=>{this.delete(t)}),e}delete(t){const e=this.list.get(t.uuid);e&&e.dispose(),this.list.delete(t.uuid)}dispose(){for(const[t,e]of this.list)e.dispose();this.list.clear(),this.onDisposed.trigger()}};e(qo,"uuid","4a82430c-7ff2-49ea-9401-60807502dad6");let Yo=qo;var Xo=(t=>(t[t.POINT=0]="POINT",t[t.LINE=1]="LINE",t[t.FACE=2]="FACE",t))(Xo||{});const Ko=1e3;class Qo{constructor(t){e(this,"onDisposed",new at),e(this,"maxDistance",1),e(this,"maxCacheSize",1e3),e(this,"components"),e(this,"_precision","half"),e(this,"cache",new Map),this.components=t}get precision(){return this._precision}set precision(t){t!==this._precision&&(this._precision=t,this.clear())}dispose(){this.cache.clear(),this.onDisposed.trigger(),this.onDisposed.reset()}async resolve(t,e,i,n){const s=Qo.keyOf(e,i);let r=this.cache.get(s);if(r)this.cache.delete(s),this.cache.set(s,r);else{if(r=await this.fetchItemSnapData(e,i),!r)return null;this.storeWithLRU(s,r)}const o=this.snap(t,r,2),a=new Set(n),l=[0,1,2];let c=null;for(const e of l){if(!a.has(e))continue;const i=this.snap(t,r,e);if(i){c=i.result;break}}if(!c)return o?o.result:null;if(o&&2!==c.snappingClass){const t=o.result;!c.normal&&t.normal&&(c.normal=t.normal),!c.facePoints&&t.facePoints&&(c.facePoints=t.facePoints),!c.faceIndices&&t.faceIndices&&(c.faceIndices=t.faceIndices)}return c}async prefetch(t,e){const i=Qo.keyOf(t,e);if(this.cache.has(i))return;const n=await this.fetchItemSnapData(t,e);n&&this.storeWithLRU(i,n)}invalidate(t,e){const i=Qo.keyOf(t,e);this.cache.delete(i)}clear(){this.cache.clear()}static keyOf(t,e){return`${t}:${e}`}storeWithLRU(t,e){for(this.cache.set(t,e);this.cache.size>this.maxCacheSize;){const t=this.cache.keys().next().value;if(void 0===t)break;this.cache.delete(t)}}async fetchItemSnapData(t,e){const i=this.components.get(gr).list.get(t);if(!i)return null;const n=await i._getItemSnapData(e);if(!n)return null;const s=i.object.matrixWorld,r=[];for(const t of Object.keys(n.samples??{})){const e=n.samples[Number(t)],i=n.representations[e.representation];if(!i||1!==i.representationClass)continue;const o=i.geometry;if(!o)continue;const a=n.localTransforms[e.localTransform],l=oa(s,n.globalTransforms[e.item],a);this.collectPolygonsFromShell(o,l,r)}if(0===r.length)return null;return{faces:r,edges:function(t,e){const i=new Set,n=[];for(const e of t){const t=e.points,s=t.length/3;for(let e=0;e<s;e++){const r=(e+1)%s,o=t[3*e],a=t[3*e+1],l=t[3*e+2],c=t[3*r],h=t[3*r+1],u=t[3*r+2],d=ca(o,a,l,c,h,u);i.has(d)||(i.add(d),n.push(o,a,l,c,h,u))}}return new("full"===e?Float64Array:Float32Array)(n)}(r,this._precision),vertices:function(t,e){const i=new Set,n=[];for(const e of t){const t=e.points,s=t.length/3;for(let e=0;e<s;e++){const s=t[3*e],r=t[3*e+1],o=t[3*e+2],a=la(s,r,o);i.has(a)||(i.add(a),n.push(s,r,o))}}return new("full"===e?Float64Array:Float32Array)(n)}(r,this._precision)}}collectPolygonsFromShell(t,e,i){const n=t.points,s=t.profiles??new Map,r=t.bigProfiles??new Map,a=new o.Vector3,l=t=>{if(t.length<3)return;const s=new("full"===this._precision?Float64Array:Float32Array)(3*t.length);for(let i=0;i<t.length;i++){const r=n[t[i]];a.set(r[0],r[1],r[2]).applyMatrix4(e),s[3*i]=a.x,s[3*i+1]=a.y,s[3*i+2]=a.z}const r=function(t){const e=new o.Vector3,i=t.length/3;for(let n=0;n<i;n++){const s=(n+1)%i,r=t[3*n],o=t[3*n+1],a=t[3*n+2],l=t[3*s],c=t[3*s+1],h=t[3*s+2];e.x+=(o-c)*(a+h),e.y+=(a-h)*(r+l),e.z+=(r-l)*(o+c)}const n=e.length();return n<1e-10?null:e.divideScalar(n)}(s);if(!r)return;const l=r.x*s[0]+r.y*s[1]+r.z*s[2];i.push({points:s,normal:r,d:l})};for(const t of s.values())l(t);for(const t of r.values())l(t)}snap(t,e,i){return 0===i?this.snapToPoint(t,e):1===i?this.snapToLine(t,e):2===i?this.snapToFace(t,e):null}snapToPoint(t,e){const i=e.vertices;if(0===i.length)return null;const n=this.maxDistance*this.maxDistance;let s=-1,r=1/0;for(let e=0;e<i.length;e+=3){const o=i[e]-t.x,a=i[e+1]-t.y,l=i[e+2]-t.z,c=o*o+a*a+l*l;c<=n&&c<r&&(r=c,s=e)}return s<0?null:{result:{point:new o.Vector3(i[s],i[s+1],i[s+2]),snappingClass:0}}}snapToLine(t,e){const i=e.edges;if(0===i.length)return null;const n=this.maxDistance*this.maxDistance,s=new o.Vector3,r=new o.Vector3;let a=1/0,l=-1;for(let e=0;e<i.length;e+=6){const o=ha(t,i[e],i[e+1],i[e+2],i[e+3],i[e+4],i[e+5],r);o<=n&&o<a&&(a=o,l=e,s.copy(r))}return l<0?null:{result:{point:s.clone(),snappingClass:1,snappedEdgeP1:new o.Vector3(i[l],i[l+1],i[l+2]),snappedEdgeP2:new o.Vector3(i[l+3],i[l+4],i[l+5])}}}snapToFace(t,e){const i=e.faces;if(0===i.length)return null;let n=null,s=1/0,r=!1;for(const e of i){const i=this.signedDistance(e,t),o=Math.abs(i);if(o>this.maxDistance)continue;const a=this.containsPoint(e,this.projectOntoPlane(t,e,i));r&&!a||(!a||r?o<s&&(s=o,n=e):(r=!0,s=o,n=e))}if(!n)return null;return{result:{point:this.projectOntoPlane(t,n,this.signedDistance(n,t)),normal:n.normal.clone(),snappingClass:2,facePoints:n.points,faceIndices:aa(n.points.length/3)}}}signedDistance(t,e){return t.normal.x*e.x+t.normal.y*e.y+t.normal.z*e.z-t.d}projectOntoPlane(t,e,i){return t.clone().sub(e.normal.clone().multiplyScalar(i))}containsPoint(t,e){const{points:i,normal:n}=t,s=i.length/3;if(s<3)return!1;const r=Math.abs(n.x),o=Math.abs(n.y),a=Math.abs(n.z);let l=0,c=1;r>=o&&r>=a?(l=1,c=2):o>=a&&(l=0,c=2);const h=e.getComponent(l),u=e.getComponent(c);let d=!1;for(let t=0,e=s-1;t<s;e=t,t+=1){const n=i[3*t+l],s=i[3*t+c],r=i[3*e+l],o=i[3*e+c];if(!(s>u!=o>u))continue;h<(r-n)*(u-s)/(o-s)+n&&(d=!d)}return d}}const Jo=new o.Matrix4,ta=new o.Vector3,ea=new o.Vector3,ia=new o.Vector3;function na(t,e){if(!t)return e.identity();const i=t.position[0],n=t.position[1],s=t.position[2];return ta.set(t.xDirection[0],t.xDirection[1],t.xDirection[2]),ea.set(t.yDirection[0],t.yDirection[1],t.yDirection[2]),ia.crossVectors(ta,ea),e.set(ta.x,ea.x,ia.x,i,ta.y,ea.y,ia.y,n,ta.z,ea.z,ia.z,s,0,0,0,1),e}const sa=new o.Matrix4,ra=new o.Matrix4;function oa(t,e,i){return na(e,sa),na(i,ra),Jo.copy(t).multiply(sa).multiply(ra).clone()}function aa(t){if(t<3)return new Uint32Array(0);const e=t-2,i=new Uint32Array(3*e);for(let t=0;t<e;t++)i[3*t]=0,i[3*t+1]=t+1,i[3*t+2]=t+2;return i}function la(t,e,i){return`${Math.round(t*Ko)},${Math.round(e*Ko)},${Math.round(i*Ko)}`}function ca(t,e,i,n,s,r){const o=la(t,e,i),a=la(n,s,r);return o<a?`${o}|${a}`:`${a}|${o}`}function ha(t,e,i,n,s,r,o,a){const l=s-e,c=r-i,h=o-n,u=l*l+c*c+h*h;let d=0;u>0&&(d=((t.x-e)*l+(t.y-i)*c+(t.z-n)*h)/u,d<0?d=0:d>1&&(d=1));const p=e+d*l,f=i+d*c,m=n+d*h;a.set(p,f,m);const g=t.x-p,w=t.y-f,y=t.z-m;return g*g+w*w+y*y}const ua=class t extends ht{constructor(i){super(i),e(this,"enabled",!0),e(this,"onDisposed",new at),e(this,"_resolver"),i.add(t.uuid,this),this._resolver=new Qo(i)}get(){return this._resolver}dispose(){this._resolver.dispose(),this.onDisposed.trigger()}};e(ua,"uuid","be9b8e6c-7f5b-4a36-8e7e-3a1f5e2a6c9d");let da=ua;class pa{constructor(t,i){e(this,"enabled",!0),e(this,"components"),e(this,"onDisposed",new at),e(this,"mouse"),e(this,"three",new o.Raycaster),e(this,"world");const n=i.renderer;if(!n)throw new Error("A renderer is needed for the raycaster to work!");this.world=i,this.mouse=new mi(n.three.domElement),this.components=t}dispose(){this.mouse.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}castRayToObjects(t=Array.from(this.world.meshes),e=this.mouse.position){if(!this.world)throw new Error("A world is needed to cast rays!");const i=this.world.camera.three;return this.three.setFromCamera(e,i),this.intersect(t)}async castRay(t){const e=null==t?void 0:t.snappingClasses,i=(null==t?void 0:t.items)??Array.from(this.world.meshes),n=(null==t?void 0:t.position)??this.mouse.position;if(!this.world)throw new Error("A world is needed to cast rays!");const s=this.world.camera.three,r=this.components.get(gr);let o=null;if(r.initialized){const t=this.components.get(Yo).get(this.world),a=await t.getFullPick(n);if(a){const t=r.list.get(a.modelId);if(o={localId:a.localId,point:a.point,normal:a.normal,distance:a.distance,fragments:t,object:null==t?void 0:t.object,ray:void 0,frustum:void 0},e&&e.length>0){const t=await this.components.get(da).get().resolve(a.point,a.modelId,a.itemId,e);t&&(o.point=t.point,t.normal&&(o.normal=t.normal),o.snappingClass=t.snappingClass,t.facePoints&&(o.facePoints=t.facePoints),t.faceIndices&&(o.faceIndices=t.faceIndices),t.snappedEdgeP1&&(o.snappedEdgeP1=t.snappedEdgeP1),t.snappedEdgeP2&&(o.snappedEdgeP2=t.snappedEdgeP2),o.distance=t.point.distanceTo(s.position))}}if(0===i.length)return o}this.three.setFromCamera(n,s);const a=this.intersect(i);return o?a&&a.distance<o.distance?a:o:a}castRayFromVector(t,e,i=Array.from(this.world.meshes)){return this.three.set(t,e),this.intersect(i)}intersect(t=Array.from(this.world.meshes)){const e=this.three.intersectObjects(t),i=this.filterClippingPlanes(e);return i.length>0?i[0]:null}filterClippingPlanes(t){if(!this.world.renderer)throw new Error("Renderer not found!");const e=this.world.renderer.three;if(!e.clippingPlanes)return t;const i=e.clippingPlanes;return t.length<=0||!i||(null==i?void 0:i.length)<=0?t:t.filter(t=>i.every(e=>e.distanceToPoint(t.point)>0))}}const fa=class t extends ht{constructor(i){super(i),e(this,"enabled",!0),e(this,"list",new Map),e(this,"onDisposed",new at),i.add(t.uuid,this)}get(t){if(this.list.has(t.uuid))return this.list.get(t.uuid);const e=new pa(this.components,t);return this.list.set(t.uuid,e),t.onDisposed.add(()=>{this.delete(t)}),e}delete(t){const e=this.list.get(t.uuid);e&&e.dispose(),this.list.delete(t.uuid)}dispose(){for(const[t,e]of this.list)e.dispose();this.list.clear(),this.onDisposed.trigger()}};e(fa,"uuid","d5d8bdf0-db25-4952-b951-b643af207ace");let ma=fa;class ga extends ct{constructor(){super(...arguments),e(this,"onCameraChanged",new at),e(this,"meshes",new Set),e(this,"onAfterUpdate",new at),e(this,"onBeforeUpdate",new at),e(this,"onDisposed",new at),e(this,"isDisposing",!1),e(this,"enabled",!0),e(this,"_dynamicAnchor",!1),e(this,"_anchorRequestId",0),e(this,"uuid",_t.create()),e(this,"name"),e(this,"_scene"),e(this,"_camera"),e(this,"_renderer",null),e(this,"onPointerDown",t=>{if(!this.camera.hasCameraControls())throw new Error("World: can't set dynamic anchor if the camera doesn't have controls.");if(0!==t.button)return;const e=this.getPointerPosition(t);if(!e)return;const i=this.components.get(ma).get(this),n=this.getPlaneAnchor(i,e);n&&this.camera.controls.setOrbitPoint(n.x,n.y,n.z);const s=++this._anchorRequestId;i.castRay({position:e}).then(t=>{if(s!==this._anchorRequestId||this.isDisposing||!this._dynamicAnchor)return;if(!(null==t?void 0:t.point)||!this.camera.hasCameraControls())return;const{x:e,y:i,z:n}=t.point;this.camera.controls.setOrbitPoint(e,i,n)})}),e(this,"_defaultCamera")}set dynamicAnchor(t){var e;const i=null==(e=this.renderer)?void 0:e.three.domElement.parentElement;if(!i)throw new Error("World: the renderer must have a parentElement to set dynamic anchoring.");t?(this.camera.controls&&(this.camera.controls.minDistance=.01),i.addEventListener("pointerdown",this.onPointerDown)):i.removeEventListener("pointerdown",this.onPointerDown),this._dynamicAnchor=t}get dynamicAnchor(){return this._dynamicAnchor}getPointerPosition(t){var e;const i=null==(e=this.renderer)?void 0:e.three.domElement;if(!i)return null;const n=i.getBoundingClientRect();return new o.Vector2((t.clientX-n.left)/(n.right-n.left)*2-1,-(t.clientY-n.top)/(n.bottom-n.top)*2+1)}getPlaneAnchor(t,e){if(!this.camera.hasCameraControls())return null;const i=this.camera.three;t.three.setFromCamera(e,i);const n=this.camera.controls.getTarget(new o.Vector3),s=i.getWorldDirection(new o.Vector3),r=(new o.Plane).setFromNormalAndCoplanarPoint(s,n);return t.three.ray.intersectPlane(r,new o.Vector3)}get defaultCamera(){if(!this._defaultCamera)throw new Error("World: there is no default camera defined.");return this._defaultCamera}set defaultCamera(t){this._defaultCamera=t}get scene(){if(!this._scene)throw new Error("No scene initialized!");return this._scene}set scene(t){this._scene=t,t.worlds.set(this.uuid,this),t.currentWorld=this,t.onWorldChanged.trigger({world:this,action:"added"})}get camera(){if(!this._camera)throw new Error("No camera initialized!");return this._camera}set camera(t){this._camera||(this.defaultCamera=t),this._camera=t,t.currentWorld=this,this.onCameraChanged.trigger(t)}get renderer(){return this._renderer}set renderer(t){this._renderer=t,t&&(t.worlds.set(this.uuid,this),t.currentWorld=this,t.onWorldChanged.trigger({world:this,action:"added"}))}useDefaultCamera(){this.camera=this.defaultCamera}update(t){this.enabled&&this._scene&&this._camera&&(this.scene.currentWorld=this,this.camera.currentWorld=this,this.renderer&&(this.renderer.currentWorld=this),this.onBeforeUpdate.trigger(),this.scene.isUpdateable()&&this.scene.update(t),this.camera.isUpdateable()&&this.camera.update(t),this.renderer&&this.renderer.update(t),this.onAfterUpdate.trigger())}dispose(t=!0){var e;if(this.isDisposing)return;this.enabled=!1,this.isDisposing=!0;const i=null==(e=this.renderer)?void 0:e.three.domElement.parentElement;if(i&&i.removeEventListener("pointerdown",this.onPointerDown),this._dynamicAnchor=!1,this.scene.onWorldChanged.trigger({world:this,action:"removed"}),this.camera.onWorldChanged.trigger({world:this,action:"removed"}),this.renderer&&this.renderer.onWorldChanged.trigger({world:this,action:"removed"}),t){const t=this.components.get(mt);this.scene.dispose(),this.camera.isDisposeable()&&this.camera.dispose(),this.renderer&&this.renderer.dispose();for(const e of this.meshes)t.destroy(e);this.meshes.clear()}this._scene=null,this._camera=null,this._renderer=null;this.components.get(Pa).list.delete(this.uuid),this.onDisposed.trigger(),this.onDisposed.reset()}}class wa{constructor(t,i){e(this,"_list"),e(this,"_scene"),this._list=t,this._scene=i}get color(){return this._list.directionalLight.color.value}set color(t){this._list.directionalLight.color.value=t;for(const[,e]of this._scene.directionalLights)e.color.copy(t)}get intensity(){return this._list.directionalLight.intensity.value}set intensity(t){this._list.directionalLight.intensity.value=t;for(const[,e]of this._scene.directionalLights)e.intensity=t}get position(){return this._list.directionalLight.position.value.clone()}set position(t){this._list.directionalLight.position.value=t;for(const[,e]of this._scene.directionalLights)e.position.copy(t)}}class ya{constructor(t,i){e(this,"_list"),e(this,"_scene"),this._list=t,this._scene=i}get color(){return this._list.ambientLight.color.value}set color(t){this._list.ambientLight.color.value=t;for(const[,e]of this._scene.ambientLights)e.color.copy(t)}get intensity(){return this._list.ambientLight.intensity.value}set intensity(t){this._list.ambientLight.intensity.value=t;for(const[,e]of this._scene.ambientLights)e.intensity=t}}class _a extends di{constructor(){super(...arguments),e(this,"_config",{backgroundColor:{value:new o.Color,type:"Color"},ambientLight:{color:{type:"Color",value:new o.Color},intensity:{type:"Number",interpolable:!0,min:0,max:10,value:2}},directionalLight:{color:{type:"Color",value:new o.Color},intensity:{type:"Number",interpolable:!0,min:0,max:10,value:2},position:{type:"Vector3",value:new o.Vector3}}}),e(this,"ambientLight",new ya(this._config,this._component)),e(this,"directionalLight",new wa(this._config,this._component))}get backgroundColor(){return this._config.backgroundColor.value}set backgroundColor(t){this._config.backgroundColor.value=t,this._component.three.background=t}}class ba extends gt{constructor(t){super(t),e(this,"onSetup",new at),e(this,"isSetup",!1),e(this,"three"),e(this,"config",new _a(this,this.components,"Scene")),e(this,"_defaultConfig",{backgroundColor:new o.Color(2107698),directionalLight:{color:new o.Color("white"),intensity:1.5,position:new o.Vector3(5,10,3)},ambientLight:{color:new o.Color("white"),intensity:1}}),this.three=new o.Scene,this.three.background=new o.Color(2107698)}setup(t){const e={...this._defaultConfig,...t};this.config.backgroundColor=e.backgroundColor;const i=e.ambientLight;this.config.ambientLight.color=i.color,this.config.ambientLight.intensity=i.intensity;const n=e.directionalLight;this.config.directionalLight.color=n.color,this.config.directionalLight.intensity=n.intensity,this.config.directionalLight.position=n.position,this.deleteAllLights();const{color:s,intensity:r}=this.config.directionalLight,a=new o.DirectionalLight(s,r);a.position.copy(n.position);const{color:l,intensity:c}=this.config.directionalLight,h=new o.AmbientLight(l,c);this.three.add(a,h),this.directionalLights.set(a.uuid,a),this.ambientLights.set(h.uuid,h),this.isSetup=!0,this.onSetup.trigger()}dispose(){super.dispose();this.components.get(fi).list.delete(this.config.uuid)}}const va='\n<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 120 40" fill="none" aria-label="That Open Company">\n<path d="M42.2856 19.6517V8.4048H38.8676V7.14978H46.998V8.40976H43.6131V19.6566L42.2856 19.6517Z" fill="#BCF124"/>\n<path d="M48.459 19.6516V7.14978H49.7032V12.404L49.4204 12.3371C49.6285 11.7727 50.0095 11.2904 50.5078 10.9607C51.0285 10.6201 51.638 10.4449 52.2578 10.4577C52.853 10.4483 53.44 10.5988 53.9589 10.8938C54.456 11.1789 54.8687 11.5934 55.1541 12.0943C55.449 12.6164 55.6 13.2089 55.5913 13.8102V19.6516H54.3495V14.2958C54.3637 13.8139 54.2611 13.3359 54.0507 12.9033C53.8646 12.537 53.5797 12.2315 53.229 12.0224C52.8685 11.8121 52.4584 11.7046 52.0423 11.7115C51.624 11.7054 51.2117 11.8128 50.8483 12.0224C50.4912 12.2324 50.2006 12.541 50.0106 12.912C49.7956 13.3401 49.6899 13.8158 49.7032 14.2958V19.6516H48.459Z" fill="#BCF124"/>\n<path d="M60.5388 19.8524C60.0174 19.8619 59.5007 19.75 59.0289 19.5253C58.6071 19.3259 58.2459 19.0157 57.983 18.6271C57.7263 18.2403 57.593 17.7833 57.6009 17.3175C57.5959 16.8715 57.6984 16.4309 57.8997 16.034C58.1173 15.6285 58.4383 15.2892 58.8292 15.0516C59.3232 14.7561 59.8701 14.5624 60.4384 14.4817L63.9188 13.8932V15.0355L60.7348 15.5744C60.0931 15.6867 59.6314 15.8932 59.3497 16.1938C59.0735 16.4811 58.9212 16.8673 58.926 17.268C58.9244 17.4635 58.9661 17.657 59.0481 17.8341C59.1301 18.0112 59.2503 18.1674 59.3999 18.2913C59.7416 18.5818 60.1787 18.7318 60.6246 18.7113C61.1803 18.7244 61.7296 18.5884 62.2166 18.3173C62.6597 18.066 63.0268 17.6972 63.2784 17.2506C63.535 16.7959 63.6669 16.2801 63.6604 15.7565V13.4744C63.6679 13.2259 63.6196 12.979 63.519 12.7521C63.4185 12.5253 63.2684 12.3245 63.08 12.1649C62.693 11.8287 62.1897 11.6607 61.57 11.6607C61.0801 11.6502 60.5978 11.7845 60.1822 12.047C59.7665 12.3095 59.4355 12.6888 59.2297 13.1387L58.1018 12.5192C58.2839 12.117 58.553 11.7614 58.8892 11.4785C59.2572 11.162 59.6754 10.9107 60.1261 10.7352C60.5858 10.5517 61.0758 10.4579 61.57 10.4589C62.1703 10.4448 62.7654 10.5748 63.3065 10.838C63.7888 11.077 64.1965 11.4462 64.4846 11.9047C64.7683 12.3771 64.912 12.9219 64.8986 13.4744V19.6517H63.658V17.8552L63.8405 18.0398C63.6702 18.3954 63.4238 18.7081 63.1191 18.9554C62.7772 19.238 62.3899 19.4593 61.9741 19.6095C61.5136 19.7756 61.0277 19.8578 60.5388 19.8524Z" fill="#BCF124"/>\n<path d="M70.6935 19.752C69.8975 19.752 69.2852 19.517 68.8566 19.0471C68.428 18.5771 68.2108 17.9056 68.2051 17.0326V11.9122H66.5616V10.6534H66.9804C67.1477 10.662 67.3148 10.6332 67.4697 10.5689C67.6247 10.5047 67.7637 10.4066 67.8769 10.2818C68.1017 10.0195 68.2202 9.68094 68.2088 9.33398V8.57825H69.453V10.6596H71.4124V11.9184H69.453V17.0388C69.4478 17.3107 69.4926 17.5813 69.5853 17.8366C69.6729 18.065 69.8337 18.2569 70.042 18.3818C70.3083 18.5292 70.6096 18.5991 70.9128 18.5837C71.0009 18.5837 71.1063 18.5775 71.2287 18.5664C71.3512 18.5552 71.4553 18.5441 71.5434 18.5329V19.6578C71.396 19.6937 71.2462 19.7189 71.0952 19.7334C70.9262 19.7433 70.7927 19.752 70.6935 19.752Z" fill="#BCF124"/>\n<path d="M82.2003 19.8523C81.3145 19.8603 80.4355 19.6954 79.6114 19.3666C78.4307 18.8928 77.4197 18.068 76.7118 17.001C76.0038 15.9341 75.6323 14.6751 75.646 13.3901C75.6376 12.5147 75.8043 11.6466 76.1359 10.838C76.453 10.0681 76.9213 9.37141 77.5123 8.79004C78.1118 8.20273 78.819 7.73977 79.5942 7.42723C81.2715 6.778 83.1266 6.778 84.8039 7.42723C85.5794 7.73911 86.2867 8.20215 86.8857 8.79004C87.4768 9.3717 87.9454 10.0683 88.2635 10.838C88.5945 11.6468 88.7611 12.5148 88.7533 13.3901C88.7674 14.6752 88.396 15.9343 87.688 17.0013C86.98 18.0683 85.9688 18.8931 84.7879 19.3666C83.9642 19.6952 83.0857 19.8601 82.2003 19.8523ZM82.2003 17.4984C82.7378 17.5032 83.2709 17.4005 83.769 17.1961C84.2425 16.9994 84.6735 16.7111 85.0378 16.3474C85.4069 15.9786 85.6952 15.5354 85.884 15.0465C86.0882 14.5173 86.1896 13.9532 86.1828 13.3852C86.1898 12.8203 86.0883 12.2594 85.884 11.7337C85.6922 11.2464 85.4043 10.8038 85.0378 10.4328C84.6764 10.0659 84.2446 9.77748 83.769 9.58542C82.7594 9.19396 81.6424 9.19396 80.6327 9.58542C80.1568 9.77745 79.7246 10.0658 79.3628 10.4328C78.9967 10.8041 78.7088 11.2467 78.5166 11.7337C78.3119 12.2602 78.2104 12.8219 78.2177 13.3876C78.2109 13.9557 78.3123 14.5198 78.5166 15.049C78.7058 15.5377 78.994 15.9808 79.3628 16.3499C79.7275 16.7136 80.1589 17.0019 80.6327 17.1985C81.1302 17.4038 81.663 17.5074 82.2003 17.5033V17.4984Z" fill="#BCF124"/>\n<path d="M90.398 23.2209V10.4861H92.7248V12.2293L92.5081 11.7251C92.8117 11.2627 93.2354 10.8941 93.7327 10.6596C94.2857 10.3994 94.8901 10.2702 95.4999 10.2817C96.3233 10.271 97.1335 10.4919 97.8401 10.9198C98.5312 11.3384 99.1029 11.9314 99.4995 12.6406C99.9126 13.38 100.124 14.2172 100.112 15.0664C100.122 15.9116 99.913 16.7448 99.5069 17.4835C99.1168 18.1988 98.5469 18.7971 97.8548 19.218C97.1376 19.6483 96.3164 19.8688 95.4827 19.8548C94.894 19.8605 94.3104 19.7437 93.7682 19.5116C93.2614 19.2967 92.8226 18.9454 92.4995 18.4957L92.8975 17.9754V23.2234L90.398 23.2209ZM95.1741 17.5863C95.6033 17.5949 96.0268 17.4848 96.3987 17.268C96.7521 17.0559 97.0394 16.7477 97.2278 16.3784C97.4328 15.9736 97.5355 15.5237 97.5266 15.0689C97.5364 14.6168 97.4337 14.1694 97.2278 13.768C97.0366 13.4007 96.7499 13.0932 96.3987 12.8785C96.0288 12.6556 95.6046 12.5419 95.1741 12.5502C94.7569 12.5434 94.3461 12.6541 93.9874 12.8698C93.6387 13.0826 93.3568 13.391 93.1743 13.7593C92.9832 14.1688 92.8841 14.6161 92.8841 15.0689C92.8841 15.5217 92.9832 15.9689 93.1743 16.3784C93.3571 16.7465 93.639 17.0548 93.9874 17.268C94.3469 17.4837 94.7586 17.594 95.1766 17.5863H95.1741Z" fill="#BCF124"/>\n<path d="M105.924 19.8524C104.961 19.8524 104.126 19.6372 103.418 19.2069C102.724 18.7915 102.156 18.1916 101.776 17.4724C101.384 16.7291 101.184 15.8977 101.194 15.0553C101.179 14.1986 101.388 13.3532 101.801 12.6047C102.189 11.9046 102.753 11.3198 103.434 10.9087C104.139 10.4899 104.944 10.2756 105.761 10.2892C106.414 10.277 107.062 10.394 107.67 10.6336C108.202 10.8483 108.68 11.1777 109.073 11.5987C109.454 12.0141 109.75 12.5023 109.943 13.0346C110.147 13.6019 110.248 14.2016 110.242 14.805C110.242 14.9847 110.234 15.1606 110.218 15.334C110.205 15.4855 110.174 15.6349 110.126 15.7788H103.34V13.9266H108.716L107.538 14.8001C107.65 14.3786 107.645 13.9339 107.522 13.5153C107.411 13.1561 107.186 12.8437 106.883 12.6258C106.553 12.4 106.161 12.2855 105.762 12.2987C105.368 12.2877 104.981 12.3993 104.652 12.6184C104.327 12.8492 104.083 13.1779 103.955 13.5574C103.79 14.0428 103.728 14.5577 103.772 15.0689C103.719 15.5315 103.782 16.0001 103.955 16.4317C104.108 16.81 104.375 17.1302 104.718 17.3473C105.08 17.5514 105.486 17.6634 105.901 17.6736C106.316 17.6837 106.727 17.5917 107.098 17.4055C107.407 17.2317 107.661 16.9743 107.833 16.6622L109.824 17.6186C109.643 18.0737 109.355 18.4776 108.986 18.7956C108.59 19.1398 108.132 19.4046 107.638 19.5761C107.087 19.766 106.507 19.8594 105.924 19.8524Z" fill="#BCF124"/>\n<path d="M111.703 19.6516V10.4837H114.03V12.2962L113.898 11.8935C114.081 11.3764 114.443 10.944 114.918 10.6769C115.425 10.404 115.994 10.2679 116.569 10.2817C117.196 10.2676 117.816 10.4179 118.369 10.7178C118.875 11.0011 119.293 11.4232 119.573 11.9357C119.87 12.4948 120.018 13.1223 120.004 13.7569V19.6491H117.515V14.2958C117.524 13.9753 117.452 13.6579 117.307 13.3728C117.173 13.1206 116.972 12.9112 116.727 12.7682C116.459 12.625 116.162 12.5502 115.859 12.5502C115.557 12.5502 115.26 12.625 114.992 12.7682C114.743 12.9091 114.539 13.1188 114.403 13.3728C114.259 13.658 114.188 13.9754 114.196 14.2958V19.6516H111.703Z" fill="#BCF124"/>\n<path d="M45.7329 35.9372C44.8875 35.9451 44.0493 35.7794 43.269 35.4503C42.525 35.134 41.851 34.6707 41.2863 34.0875C40.7178 33.4992 40.2696 32.8033 39.9673 32.0396C39.6453 31.2229 39.4843 30.3504 39.4934 29.4713C39.4848 28.5902 39.6427 27.7155 39.9588 26.8943C40.2511 26.1324 40.6939 25.4388 41.2601 24.8558C41.8262 24.2727 42.504 23.8126 43.2518 23.5034C44.039 23.178 44.8826 23.015 45.7329 23.024C46.5598 23.0107 47.3809 23.1649 48.1479 23.4774C48.8259 23.756 49.443 24.1669 49.9641 24.6866C50.4412 25.1559 50.8045 25.7304 51.0258 26.3653L48.7529 27.4729C48.5362 26.8433 48.1263 26.3001 47.5831 25.9226C47.0399 25.5451 46.3917 25.3529 45.7329 25.3742C45.0556 25.3604 44.3882 25.5408 43.8078 25.8945C43.2553 26.2426 42.8099 26.74 42.5219 27.3304C42.2056 27.9978 42.0495 28.7313 42.0664 29.4713C42.0503 30.2135 42.2063 30.9493 42.5219 31.6196C42.8077 32.2136 43.2534 32.7139 43.8078 33.0629C44.3879 33.4172 45.0555 33.5976 45.7329 33.5832C46.3917 33.6045 47.0399 33.4124 47.5831 33.0348C48.1263 32.6573 48.5362 32.1142 48.7529 31.4845L51.0258 32.5933C50.8056 33.2316 50.4422 33.8096 49.9641 34.282C49.4426 34.8009 48.8256 35.2113 48.1479 35.4899C47.3805 35.8004 46.5594 35.9524 45.7329 35.9372Z" fill="#BCF124"/>\n<path d="M56.8159 35.9372C55.9603 35.9485 55.1164 35.735 54.3667 35.3177C53.6426 34.9153 53.0357 34.3274 52.6069 33.613C52.1777 32.8648 51.9517 32.0151 51.9517 31.15C51.9517 30.285 52.1777 29.4353 52.6069 28.6871C53.0376 27.9762 53.6442 27.3911 54.3667 26.9898C55.118 26.5823 55.9573 26.3691 56.8098 26.3691C57.6623 26.3691 58.5016 26.5823 59.253 26.9898C59.9716 27.3928 60.5749 27.9771 61.0042 28.6858C61.4334 29.4341 61.6594 30.2837 61.6594 31.1488C61.6594 32.0139 61.4334 32.8635 61.0042 33.6118C60.577 34.3244 59.9733 34.912 59.253 35.3165C58.5078 35.7343 57.6678 35.9482 56.8159 35.9372ZM56.8159 33.6712C57.2335 33.681 57.6451 33.5701 58.0026 33.3516C58.3443 33.1354 58.6199 32.8274 58.7986 32.462C58.9985 32.0556 59.0985 31.6064 59.0901 31.1525C59.099 30.7014 58.9989 30.2548 58.7986 29.8517C58.6161 29.4889 58.3414 29.1818 58.0026 28.9621C57.6468 28.739 57.2345 28.6254 56.8159 28.635C56.3952 28.6261 55.9807 28.7396 55.6219 28.9621C55.2792 29.18 55.0008 29.4873 54.8161 29.8517C54.6162 30.2549 54.5166 30.7015 54.5259 31.1525C54.517 31.6063 54.6166 32.0555 54.8161 32.462C54.997 32.8291 55.2762 33.1373 55.6219 33.3516C55.9824 33.5695 56.3962 33.6803 56.8159 33.6712Z" fill="#BCF124"/>\n<path d="M63.1228 35.7364V26.5685H65.4496V28.7985L65.2047 28.4269C65.337 27.7223 65.6574 27.202 66.1661 26.8658C66.7124 26.5198 67.3477 26.3448 67.992 26.3628C68.6955 26.3487 69.3867 26.5504 69.9747 26.9414C70.2455 27.1163 70.4794 27.3435 70.6631 27.6102C70.8468 27.8768 70.9766 28.1775 71.045 28.495L70.3311 28.5619C70.6299 27.8128 71.056 27.2586 71.6096 26.8993C72.1912 26.5332 72.8658 26.3468 73.5506 26.3628C74.1566 26.3506 74.755 26.5011 75.2847 26.7989C75.7839 27.0856 76.1947 27.5068 76.4714 28.0155C76.7686 28.5772 76.9163 29.2073 76.9 29.8442V35.7364H74.4067V30.3806C74.4151 30.0621 74.3496 29.746 74.2156 29.4576C74.0956 29.2086 73.9084 28.999 73.6756 28.853C73.4175 28.71 73.1279 28.635 72.8336 28.635C72.5393 28.635 72.2498 28.71 71.9917 28.853C71.7556 28.9972 71.5655 29.2071 71.4443 29.4576C71.3103 29.746 71.2448 30.0621 71.2532 30.3806V35.7364H68.7648V30.3806C68.7731 30.0621 68.7077 29.746 68.5737 29.4576C68.4538 29.2089 68.267 28.9994 68.0349 28.853C67.7765 28.71 67.4868 28.635 67.1923 28.635C66.8978 28.635 66.6081 28.71 66.3498 28.853C66.1137 28.9972 65.9236 29.2071 65.8023 29.4576C65.6683 29.746 65.6029 30.0621 65.6113 30.3806V35.7364H63.1228Z" fill="#BCF124"/>\n<path d="M78.5374 39.3107V26.5697H80.8642V28.3166L80.6486 27.8123C80.9522 27.35 81.376 26.9813 81.8733 26.7469C82.4266 26.4883 83.0311 26.3611 83.6404 26.3752C84.464 26.3639 85.2743 26.5848 85.9807 27.0132C86.6715 27.4323 87.2431 28.0251 87.6401 28.7341C88.0532 29.473 88.2645 30.3098 88.2524 31.1586C88.2623 32.0044 88.0533 32.8381 87.6462 33.577C87.2571 34.2926 86.6875 34.8911 85.9954 35.3115C85.2785 35.7427 84.4572 35.9636 83.6233 35.9495C83.0345 35.9548 82.4509 35.8376 81.9088 35.6051C81.4019 35.391 80.963 35.04 80.6401 34.5904L81.0381 34.0701V39.3231L78.5374 39.3107ZM83.3134 33.6712C83.7428 33.6796 84.1663 33.5691 84.5381 33.3515C84.892 33.1399 85.1798 32.8316 85.3684 32.462C85.573 32.057 85.6757 31.6072 85.6672 31.1524C85.6761 30.7004 85.5734 30.2533 85.3684 29.8516C85.176 29.4847 84.8891 29.1774 84.5381 28.962C84.1679 28.7398 83.7438 28.6266 83.3134 28.635C82.8964 28.6281 82.4856 28.7383 82.1268 28.9534C81.778 29.1666 81.496 29.4755 81.3136 29.8442C81.1225 30.2534 81.0233 30.7004 81.0233 31.1531C81.0233 31.6057 81.1225 32.0527 81.3136 32.462C81.4954 32.8308 81.7775 33.1394 82.1268 33.3515C82.4863 33.5682 82.8986 33.679 83.3171 33.6712H83.3134Z" fill="#BCF124"/>\n<path d="M92.5093 35.9371C91.9294 35.9511 91.353 35.8427 90.8168 35.6187C90.3699 35.4306 89.9887 35.1118 89.722 34.7032C89.4607 34.2804 89.3278 33.7893 89.3399 33.2908C89.3319 32.8129 89.4525 32.3418 89.689 31.928C89.9498 31.5033 90.3197 31.1581 90.7593 30.9295C91.3217 30.6339 91.931 30.4406 92.5595 30.3583L95.3296 29.9049V31.7521L93.0028 32.1708C92.7069 32.2127 92.4268 32.3314 92.1897 32.5153C92.0938 32.6024 92.0186 32.7102 91.9696 32.8307C91.9207 32.9513 91.8992 33.0814 91.9068 33.2115C91.9015 33.3387 91.9277 33.4652 91.9828 33.5796C92.038 33.6941 92.1204 33.7928 92.2227 33.8669C92.4503 34.0296 92.7243 34.1123 93.0028 34.1023C93.3792 34.1101 93.7509 34.0174 94.0805 33.8335C94.3832 33.6617 94.6332 33.4087 94.803 33.1025C94.9751 32.7929 95.0638 32.443 95.0602 32.0878V29.698C95.062 29.5308 95.0264 29.3654 94.956 29.2141C94.8855 29.0628 94.7822 28.9296 94.6536 28.8245C94.3818 28.5891 94.0144 28.4714 93.5515 28.4714C93.1318 28.4645 92.7212 28.5949 92.3807 28.8431C92.0467 29.0873 91.7912 29.4256 91.6459 29.8157L89.6547 28.8592C89.826 28.354 90.1169 27.8989 90.5021 27.5336C90.9038 27.1547 91.3782 26.8634 91.8958 26.6775C92.4648 26.471 93.0657 26.3686 93.6702 26.3752C94.3679 26.3612 95.0599 26.5046 95.6958 26.7952C96.2502 27.0473 96.724 27.4511 97.0637 27.961C97.3951 28.4765 97.5658 29.0807 97.5536 29.6955V35.7389H95.2268V34.2584L95.7913 34.1581C95.5497 34.5339 95.2533 34.8706 94.912 35.1566C94.5921 35.4193 94.2261 35.6185 93.8331 35.7439C93.4044 35.877 92.9578 35.9422 92.5093 35.9371Z" fill="#BCF124"/>\n<path d="M99.3795 35.7365V26.5685H101.706V28.3823L101.573 27.9796C101.757 27.4626 102.119 27.0301 102.593 26.7618C103.101 26.4898 103.67 26.3542 104.245 26.3678C104.872 26.3532 105.493 26.5034 106.045 26.8039C106.551 27.0867 106.968 27.5085 107.248 28.0205C107.545 28.5801 107.693 29.208 107.679 29.8429V35.7352H105.189V30.3806C105.197 30.0603 105.126 29.743 104.982 29.4576C104.848 29.2051 104.646 28.9957 104.401 28.8531C104.135 28.7035 103.834 28.6282 103.53 28.635C103.23 28.6314 102.935 28.7065 102.673 28.8531C102.423 28.9936 102.219 29.2034 102.084 29.4576C101.939 29.7428 101.868 30.0603 101.877 30.3806V35.7365H99.3795Z" fill="#BCF124"/>\n<path d="M110.563 39.4631C110.304 39.4633 110.046 39.4405 109.791 39.3949C109.563 39.3571 109.342 39.2835 109.136 39.1769V37.1128C109.316 37.1628 109.499 37.2017 109.684 37.2293C109.875 37.2621 110.07 37.2791 110.264 37.2801C110.754 37.2801 111.099 37.1562 111.31 36.9282C111.522 36.6884 111.696 36.4162 111.824 36.1217L112.437 34.6945L112.404 36.7932L108.421 26.5697H111.093L113.731 33.8384H112.735L115.373 26.5697H118.048L114.165 36.5925C113.955 37.1702 113.652 37.7089 113.269 38.187C112.942 38.5905 112.531 38.9169 112.066 39.1434C111.594 39.3617 111.081 39.4709 110.563 39.4631Z" fill="#BCF124"/>\n<path d="M7.00861 16.1097H0C0.00583172 11.8399 1.68502 7.74676 4.66939 4.7276C7.65377 1.70844 11.6998 0.00968387 15.9203 0.00378418V7.09408C13.558 7.09801 11.2935 8.04913 9.62308 9.73902C7.95266 11.4289 7.0125 13.7198 7.00861 16.1097Z" fill="#BCF124"/>\n<path d="M15.9243 39.3094C11.7037 39.3035 7.65771 37.6047 4.67333 34.5856C1.68896 31.5664 0.00976849 27.4732 0.00393677 23.2035H7.01255C7.01255 24.9874 7.53543 26.7311 8.51506 28.2144C9.4947 29.6976 10.8871 30.8536 12.5162 31.5362C14.1452 32.2189 15.9378 32.3975 17.6672 32.0495C19.3966 31.7015 20.9852 30.8425 22.2321 29.5811C23.4789 28.3197 24.328 26.7127 24.672 24.9631C25.016 23.2135 24.8394 21.4 24.1647 19.752C23.4899 18.1039 22.3472 16.6953 20.881 15.7042C19.4149 14.7132 17.6912 14.1842 15.9279 14.1842V7.09021C20.1512 7.09021 24.2016 8.78747 27.1879 11.8086C30.1742 14.8297 31.8519 18.9273 31.8519 23.1998C31.8519 27.4723 30.1742 31.5699 27.1879 34.591C24.2016 37.6121 20.1512 39.3094 15.9279 39.3094H15.9243Z" fill="#BCF124"/>\n</svg>\n'.trim();var xa=(t=>(t[t.MANUAL=0]="MANUAL",t[t.AUTO=1]="AUTO",t))(xa||{});class Ca extends pt{constructor(t,i,n){super(t),e(this,"enabled",!0),e(this,"container"),e(this,"three"),e(this,"mode",1),e(this,"needsUpdate",!1),e(this,"_canvas"),e(this,"_parameters"),e(this,"_resizeObserver",null),e(this,"onContainerUpdated",new at),e(this,"_resizing",!1),e(this,"_logo",null),e(this,"_showLogo",!0),e(this,"resize",t=>{if(this._resizing)return;this._resizing=!0,this.onContainerUpdated.trigger();const e=t?t.x:this.container.clientWidth,i=t?t.y:this.container.clientHeight;this.three.setSize(e,i),this.onResize.trigger(new o.Vector2(e,i)),this._resizing=!1}),e(this,"resizeEvent",()=>{this.resize()}),e(this,"onContextLost",t=>{t.preventDefault(),this.enabled=!1}),e(this,"onContextBack",()=>{this.three.setRenderTarget(null),this.three.dispose(),this.three=new o.WebGLRenderer({canvas:this._canvas,antialias:!0,alpha:!0,...this._parameters}),this.enabled=!0}),this.container=i,this._parameters=n,this.three=new o.WebGLRenderer({antialias:!0,alpha:!0,...n}),this.three.setPixelRatio(Math.min(window.devicePixelRatio,2)),this.setupRenderer(),this.setupEvents(!0),this.resize(),this._canvas=this.three.domElement;const s=this.three.getContext(),{canvas:r}=s;r.addEventListener("webglcontextlost",this.onContextLost,!1),r.addEventListener("webglcontextrestored",this.onContextBack,!1)}get showLogo(){return this._showLogo}set showLogo(t){this._showLogo=t,this._logo&&(this._logo.style.display=t?"":"none")}get logo(){return this._logo}update(){if(!this.enabled||!this.currentWorld)return;if(0===this.mode&&!this.needsUpdate)return;this.needsUpdate=!1,this.onBeforeUpdate.trigger(this);const t=this.currentWorld.scene.three,e=this.currentWorld.camera.three;this.three.render(t,e),this.onAfterUpdate.trigger(this)}dispose(){this.enabled=!1,this.setupEvents(!1),this.three.domElement.remove(),this._logo&&(this._logo.remove(),this._logo=null),this.three.forceContextLoss(),this.three.dispose(),this.onResize.reset(),this.onAfterUpdate.reset(),this.onBeforeUpdate.reset(),this.onDisposed.trigger(),this.onDisposed.reset()}getSize(){return new o.Vector2(this.three.domElement.clientWidth,this.three.domElement.clientHeight)}setupEvents(t){const e=this.three.domElement.parentElement;if(!e)throw new Error("This renderer needs to have an HTML container!");this._resizeObserver&&(this._resizeObserver.disconnect(),this._resizeObserver=null),window.removeEventListener("resize",this.resizeEvent),t&&(this._resizeObserver=new ResizeObserver(this.resizeEvent),this._resizeObserver.observe(e),window.addEventListener("resize",this.resizeEvent))}setupRenderer(){this.three.localClippingEnabled=!0,this.container&&(this.container.appendChild(this.three.domElement),this.setupLogo()),this.onContainerUpdated.trigger()}setupLogo(){if(this._logo||!this.container)return;"static"===window.getComputedStyle(this.container).position&&(this.container.style.position="relative"),this._logo=function(){const t=document.createElement("div");t.setAttribute("data-thatopen-logo",""),t.innerHTML=va,t.style.cssText=["position: absolute","left: 0.75rem","bottom: 0.75rem","width: 6rem","height: auto","pointer-events: none","user-select: none","opacity: 0.85","z-index: 1"].join("; ");const e=t.firstElementChild;return e&&(e.setAttribute("width","100%"),e.setAttribute("height","100%")),t}(),this._logo.style.display=this._showLogo?"":"none",this.container.appendChild(this._logo)}}class Sa extends dt{constructor(t){super(t),e(this,"onBeforeUpdate",new at),e(this,"onAfterUpdate",new at),e(this,"onAspectUpdated",new at),e(this,"onDisposed",new at),e(this,"three"),e(this,"_resizeObserver",null),e(this,"_allControls",new Map),e(this,"updateAspect",()=>{var t;if(this.currentWorld&&this.currentWorld.renderer)if(this.three instanceof o.OrthographicCamera)this.onAspectUpdated.trigger();else if(null==(t=this.currentWorld.renderer)?void 0:t.isResizeable()){const t=this.currentWorld.renderer.getSize();this.three.aspect=t.width/t.height,this.three.updateProjectionMatrix(),this.onAspectUpdated.trigger()}}),this.three=this.setupCamera(),this.worlds.onItemSet.add(({value:t})=>{const e=this.newCameraControls();this.setupEvents(!0),this._allControls.set(t.uuid,e)}),this.worlds.onBeforeDelete.add(({value:t})=>{var e;const i=this._allControls.get(t.uuid);i&&(i.dispose(),this._allControls.delete(t.uuid)),null==(e=this._resizeObserver)||e.disconnect()})}get controls(){if(!this.currentWorld)throw new Error("This camera needs a world to work!");const t=this._allControls.get(this.currentWorld.uuid);if(!t)throw new Error("Controls not found!");return t}get enabled(){return null!==this.currentWorld&&this.controls.enabled}set enabled(t){null!==this.currentWorld&&(this.controls.enabled=t)}set currentWorld(t){if(super.currentWorld=t,!t)return;this.worlds.get(t.uuid)||this.worlds.set(t.uuid,t)}get currentWorld(){return this._currentWorld}dispose(){this.setupEvents(!1),this.onAspectUpdated.reset(),this.onBeforeUpdate.reset(),this.onAfterUpdate.reset(),this.three.removeFromParent(),this.onDisposed.trigger(),this.onDisposed.reset();for(const[t,e]of this._allControls)e.dispose();this.worlds.clear()}async fitToItems(t){const e=await this.getItemsBounding(t);await this.controls.fitToSphere(e,!0)}async setOrbitToItems(t){const e=await this.getItemsBounding(t);this.controls.setOrbitPoint(e.center.x,e.center.y,e.center.z)}update(t){this.enabled&&(this.onBeforeUpdate.trigger(this),this.controls.update(t),this.onAfterUpdate.trigger(this))}async getItemsBounding(t){const e=this.components.get(gr),i=this.components.get(Ro);i.list.clear();const n=new o.Sphere;if(t)await i.addFromModelIdMap(t);else for(const[,t]of e.list)i.list.add(t.box);return i.get().getBoundingSphere(n),i.list.clear(),n}setupCamera(){const t=window.innerWidth/window.innerHeight,e=new o.PerspectiveCamera(60,t,1,1e3);return e.position.set(50,50,50),e.lookAt(new o.Vector3(0,0,0)),e}newCameraControls(){if(!this.currentWorld)throw new Error("This camera needs a world to work!");if(!this.currentWorld.renderer)throw new Error("This camera needs a renderer to work!");rt.install({THREE:Sa.getSubsetOfThree()});const{domElement:t}=this.currentWorld.renderer.three,e=new rt(this.three,t);return e.smoothTime=.2,e.dollyToCursor=!0,e.infinityDolly=!0,e.minDistance=6,e}setupEvents(t){if(this._resizeObserver&&(this._resizeObserver.disconnect(),this._resizeObserver=null),t){if(!this.currentWorld)throw new Error("This camera needs a world to work!");if(!this.currentWorld.renderer)throw new Error("This camera needs a renderer to work!");const{domElement:t}=this.currentWorld.renderer.three;this._resizeObserver=new ResizeObserver(this.updateAspect),this._resizeObserver.observe(t)}}static getSubsetOfThree(){return{MOUSE:o.MOUSE,Vector2:o.Vector2,Vector3:o.Vector3,Vector4:o.Vector4,Quaternion:o.Quaternion,Matrix4:o.Matrix4,Spherical:o.Spherical,Box3:o.Box3,Sphere:o.Sphere,Raycaster:o.Raycaster,MathUtils:o.MathUtils}}}const Aa=class t extends ht{constructor(i){super(i),e(this,"onAfterUpdate",new at),e(this,"onBeforeUpdate",new at),e(this,"onDisposed",new at),e(this,"list",new n),e(this,"enabled",!0),i.add(t.uuid,this)}create(){const t=new ga(this.components),e=t.uuid;if(this.list.has(e))throw new Error("There is already a world with this name!");return this.list.set(e,t),t}delete(t){if(!this.list.has(t.uuid))throw new Error("The provided world is not found in the list!");this.list.delete(t.uuid),t.dispose()}dispose(){this.enabled=!1;for(const[t,e]of this.list)e.dispose();this.list.clear(),this.onDisposed.trigger()}update(t){if(this.enabled)for(const[e,i]of this.list)i.update(t)}};e(Aa,"uuid","fdb61dc4-2ec1-4966-b83d-54ea795fad4a");let Pa=Aa;class Ta extends di{constructor(){super(...arguments),e(this,"_config",{visible:{value:!0,type:"Boolean"},color:{value:new o.Color,type:"Color"},primarySize:{type:"Number",interpolable:!0,value:1,min:0,max:1e3},secondarySize:{type:"Number",interpolable:!0,value:10,min:0,max:1e3},distance:{type:"Number",interpolable:!0,value:500,min:0,max:500}})}get visible(){return this._config.visible.value}set visible(t){this._config.visible.value=t,this._component.visible=t}get color(){return this._config.color.value}set color(t){this._config.color.value=t,this._component.material.uniforms.uColor.value=t,this._component.material.uniformsNeedUpdate=!0}get primarySize(){return this._config.primarySize.value}set primarySize(t){this._config.primarySize.value=t,this._component.material.uniforms.uSize1.value=t,this._component.material.uniformsNeedUpdate=!0}get secondarySize(){return this._config.secondarySize.value}set secondarySize(t){this._config.secondarySize.value=t,this._component.material.uniforms.uSize2.value=t,this._component.material.uniformsNeedUpdate=!0}get distance(){return this._config.distance.value}set distance(t){this._config.distance.value=t,this._component.material.uniforms.uDistance.value=t,this._component.material.uniformsNeedUpdate=!0}}class Ea{constructor(t,i){e(this,"onDisposed",new at),e(this,"onSetup",new at),e(this,"isSetup",!1),e(this,"world"),e(this,"components"),e(this,"config"),e(this,"_defaultConfig",{visible:!0,color:new o.Color(12303291),primarySize:1,secondarySize:10,distance:500}),e(this,"three"),e(this,"_fade",3),e(this,"updateZoom",()=>{this.world.camera instanceof Sa&&(this.material.uniforms.uZoom.value=this.world.camera.three.zoom)}),this.world=i;const{color:n,primarySize:s,secondarySize:r,distance:a}=this._defaultConfig;this.components=t,this.config=new Ta(this,this.components,"Grid");const l=new o.PlaneGeometry(2,2,1,1),c=new o.ShaderMaterial({side:o.DoubleSide,uniforms:{uSize1:{value:s},uSize2:{value:r},uColor:{value:n},uDistance:{value:a},uFade:{value:this._fade},uZoom:{value:1}},transparent:!0,vertexShader:"\n \n varying vec3 worldPosition;\n \n uniform float uDistance;\n \n void main() {\n \n vec3 pos = position.xzy * uDistance;\n pos.xz += cameraPosition.xz;\n \n worldPosition = pos;\n \n gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);\n \n }\n ",fragmentShader:"\n \n varying vec3 worldPosition;\n \n uniform float uZoom;\n uniform float uFade;\n uniform float uSize1;\n uniform float uSize2;\n uniform vec3 uColor;\n uniform float uDistance;\n \n \n \n float getGrid(float size) {\n \n vec2 r = worldPosition.xz / size;\n \n \n vec2 grid = abs(fract(r - 0.5) - 0.5) / fwidth(r);\n float line = min(grid.x, grid.y);\n \n \n return 1.0 - min(line, 1.0);\n }\n \n void main() {\n \n \n float d = 1.0 - min(distance(cameraPosition.xz, worldPosition.xz) / uDistance, 1.0);\n \n float g1 = getGrid(uSize1);\n float g2 = getGrid(uSize2);\n \n // Ortho camera fades the grid away when zooming out\n float minZoom = step(0.2, uZoom);\n float zoomFactor = pow(min(uZoom, 1.), 2.) * minZoom;\n \n gl_FragColor = vec4(uColor.rgb, mix(g2, g1, g1) * pow(d, uFade));\n gl_FragColor.a = mix(0.5 * gl_FragColor.a, gl_FragColor.a, g2) * zoomFactor;\n \n if ( gl_FragColor.a <= 0.0 ) discard;\n \n \n }\n \n ",extensions:{derivatives:!0}});this.three=new o.Mesh(l,c),this.three.frustumCulled=!1,i.scene.three.add(this.three),this.setupEvents(!0)}get visible(){return this.three.visible}set visible(t){if(this.three.visible=t,t){this.world.scene.three.add(this.three)}else this.three.removeFromParent()}get material(){return this.three.material}get fade(){return 3===this._fade}set fade(t){this._fade=t?3:0,this.material.uniforms.uFade.value=this._fade}setup(t){const e={...this._defaultConfig,...t};this.config.visible=!0,this.config.color=e.color,this.config.primarySize=e.primarySize,this.config.secondarySize=e.secondarySize,this.config.distance=e.distance,this.isSetup=!0,this.onSetup.trigger()}dispose(){this.setupEvents(!1);this.components.get(fi).list.delete(this.config.uuid);this.components.get(mt).destroy(this.three),this.onDisposed.trigger(),this.onDisposed.reset(),this.world=null,this.components=null}setupEvents(t){if(this.world.isDisposing)return;if(!(this.world.camera instanceof Sa))return;const e=this.world.camera.controls;t?e.addEventListener("update",this.updateZoom):e.removeEventListener("update",this.updateZoom)}}const Ma=class t extends ht{constructor(i){super(i),e(this,"list",new Map),e(this,"onDisposed",new at),e(this,"enabled",!0),i.add(t.uuid,this)}create(t){if(this.list.has(t.uuid))throw new Error("This world already has a grid!");const e=new Ea(this.components,t);return this.list.set(t.uuid,e),t.onDisposed.add(()=>{this.delete(t)}),e}delete(t){const e=this.list.get(t.uuid);e&&e.dispose(),this.list.delete(t.uuid)}dispose(){for(const[t,e]of this.list)e.dispose();this.list.clear(),this.onDisposed.trigger(),this.onDisposed.reset()}};e(Ma,"uuid","d1e814d5-b81c-4452-87a2-f039375e0489");let Ia=Ma;const za=class t{constructor(){e(this,"onDisposed",new at),e(this,"list",new n),e(this,"enabled",!1),e(this,"_timer"),e(this,"onInit",new at),e(this,"update",()=>{if(!this.enabled)return;this._timer.update();const t=this._timer.getDelta();for(const[e,i]of this.list)i.enabled&&i.isUpdateable()&&i.update(t);requestAnimationFrame(this.update)}),this._timer=new o.Timer,t.setupBVH()}add(t,e){if(this.list.has(t))throw new Error("You're trying to add a component that already exists in the components instance. Use Components.get() instead.");_t.validate(t),this.list.set(t,e)}get(t){var e;const i=t.uuid;if(!this.list.has(i)){const n=new t(this);return(null==(e=n.isDisposeable)?void 0:e.call(n))&&n.onDisposed.add(()=>this.list.delete(i)),this.list.has(i)||this.add(i,n),n}return this.list.get(i)}init(){this.enabled=!0;for(const[t,e]of this.list.entries())e.enabled=!0;this._timer.reset(),this.update(),this.onInit.trigger()}dispose(){let t,e;this.enabled=!1;for(const[i,n]of this.list)n.enabled=!1,i!==gr.uuid?i!==Pa.uuid?n.isDisposeable()&&n.dispose():e=n:t=n;(null==e?void 0:e.isDisposeable())&&e.dispose(),null==t||t.dispose(),this._timer.dispose(),this.onDisposed.trigger()}static setupBVH(){o.BufferGeometry.prototype.computeBoundsTree=pr,o.BufferGeometry.prototype.disposeBoundsTree=fr,o.Mesh.prototype.raycast=ur,o.LineSegments.prototype.raycast=ur}};e(za,"release","2.4.3");let Da=za;class ka{constructor(t){e(this,"enabled",!1),e(this,"id","FirstPerson"),this.camera=t}set(t){if(this.enabled=t,t){if("Perspective"!==this.camera.projection.current)return void this.camera.set("Orbit");this.setupFirstPersonCamera()}}setupFirstPersonCamera(){const t=this.camera.controls,e=new o.Vector3;t.distance--,t.getPosition(e),t.minDistance=1,t.maxDistance=1,t.distance=1,t.moveTo(e.x,e.y,e.z),t.truckSpeed=50,t.mouseButtons.wheel=rt.ACTION.DOLLY,t.touches.two=rt.ACTION.TOUCH_ZOOM_TRUCK}}class Ba{constructor(t){e(this,"enabled",!0),e(this,"id","Orbit"),this.camera=t,this.activateOrbitControls()}set(t){this.enabled=t,t&&this.activateOrbitControls()}activateOrbitControls(){const t=this.camera.controls;t.minDistance=1,t.maxDistance=300;const e=new o.Vector3;t.getPosition(e);const i=e.length();t.distance=i,t.truckSpeed=2;const{rotation:n}=this.camera.three,s=new o.Vector3(0,0,-1).applyEuler(n),r=e.addScaledVector(s,i);t.moveTo(r.x,r.y,r.z)}}class Oa{constructor(t){e(this,"enabled",!1),e(this,"id","Plan"),e(this,"mouseAction1"),e(this,"mouseAction2"),e(this,"mouseInitialized",!1),e(this,"defaultAzimuthSpeed"),e(this,"defaultPolarSpeed"),this.camera=t,this.defaultAzimuthSpeed=t.controls.azimuthRotateSpeed,this.defaultPolarSpeed=t.controls.polarRotateSpeed}set(t){this.enabled=t;const e=this.camera.controls;e.azimuthRotateSpeed=t?0:this.defaultAzimuthSpeed,e.polarRotateSpeed=t?0:this.defaultPolarSpeed,this.mouseInitialized||(this.mouseAction1=e.touches.one,this.mouseAction2=e.touches.two,this.mouseInitialized=!0),t?(e.mouseButtons.left=rt.ACTION.TRUCK,e.touches.one=rt.ACTION.TOUCH_TRUCK,e.touches.two=rt.ACTION.TOUCH_ZOOM):(e.mouseButtons.left=rt.ACTION.ROTATE,e.touches.one=this.mouseAction1,e.touches.two=this.mouseAction2)}}class Na{constructor(t){e(this,"onChanged",new at),e(this,"current","Perspective"),e(this,"camera"),e(this,"matchOrthoDistanceEnabled",!1),e(this,"_component"),e(this,"_previousDistance",-1),this._component=t,this.camera=t.three}async set(t){this.current!==t&&("Orthographic"===t?this.setOrthoCamera():await this.setPerspectiveCamera(),this.onChanged.trigger(this.camera))}async toggle(){const t="Perspective"===this.current?"Orthographic":"Perspective";await this.set(t)}setOrthoCamera(){if(null===this._component.mode)return;if("FirstPerson"===this._component.mode.id)return;this._previousDistance=this._component.controls.distance,this._component.controls.distance=200;const t=this.getPerspectiveDims();if(!t)return;const{width:e,height:i}=t;this.setupOrthoCamera(i,e),this.camera=this._component.threeOrtho,this.current="Orthographic"}getPerspectiveDims(){const t=this._component.currentWorld;if(!t||!t.renderer)return null;const e=new o.Vector3;this._component.threePersp.getWorldDirection(e);const i=new o.Vector3;this._component.controls.getTarget(i);const n=i.clone().sub(this._component.threePersp.position).dot(e),s=t.renderer.getSize(),r=s.x/s.y,a=this._component.threePersp,l=2*n*Math.atan(a.fov*(Math.PI/180)/2);return{width:l*r,height:l}}setupOrthoCamera(t,e){this._component.controls.mouseButtons.wheel=rt.ACTION.ZOOM,this._component.controls.mouseButtons.middle=rt.ACTION.ZOOM;const i=this._component.threePersp,n=this._component.threeOrtho;n.zoom=1,n.left=e/-2,n.right=e/2,n.top=t/2,n.bottom=t/-2,n.updateProjectionMatrix(),n.position.copy(i.position),n.quaternion.copy(i.quaternion),this._component.controls.camera=n}getDistance(){const t=this._component.threePersp,e=this._component.threeOrtho;return(e.top-e.bottom)/e.zoom/(2*Math.atan(t.fov*(Math.PI/180)/2))}async setPerspectiveCamera(){this._component.controls.mouseButtons.wheel=rt.ACTION.DOLLY,this._component.controls.mouseButtons.middle=rt.ACTION.DOLLY;const t=this._component.threePersp,e=this._component.threeOrtho;t.position.copy(e.position),t.quaternion.copy(e.quaternion),this._component.controls.mouseButtons.wheel=rt.ACTION.DOLLY,this.matchOrthoDistanceEnabled?this._component.controls.distance=this.getDistance():this._component.controls.distance=this._previousDistance,await this._component.controls.zoomTo(1),t.updateProjectionMatrix(),this._component.controls.camera=t,this.camera=t,this.current="Perspective"}}class Va extends Sa{constructor(t){super(t),e(this,"projection"),e(this,"threeOrtho"),e(this,"threePersp"),e(this,"_userInputButtons",{}),e(this,"_frustumSize",50),e(this,"_navigationModes",new Map),e(this,"_mode",null),e(this,"previousSize",null),this.threePersp=this.three,this.threeOrtho=this.newOrthoCamera(),this.projection=new Na(this),this.onAspectUpdated.add(()=>{this.setOrthoPerspCameraAspect()}),this.projection.onChanged.add(t=>{this.three=t,this.updateAspect()}),this.worlds.onItemSet.add(()=>{this._navigationModes.clear(),this._navigationModes.set("Orbit",new Ba(this)),this._navigationModes.set("FirstPerson",new ka(this)),this._navigationModes.set("Plan",new Oa(this)),this._mode=this._navigationModes.get("Orbit"),this.mode.set(!0,{preventTargetAdjustment:!0}),this.currentWorld&&this.currentWorld.renderer&&(this.previousSize=this.currentWorld.renderer.getSize().clone())}),this.worlds.onItemDeleted.add(()=>{this._navigationModes.clear()})}get mode(){if(!this._mode)throw new Error("Mode not found, camera not initialized");return this._mode}dispose(){super.dispose(),this.threeOrtho.removeFromParent()}set(t){if(null!==this.mode&&this.mode.id!==t){if(this.mode.set(!1),!this._navigationModes.has(t))throw new Error("The specified mode does not exist!");this._mode=this._navigationModes.get(t),this.mode.set(!0)}}async fit(t,e=1.5){if(!this.enabled)return;const i=Number.MAX_VALUE,n=Number.MIN_VALUE,s=new o.Vector3(i,i,i),r=new o.Vector3(n,n,n);for(const e of t){const t=(new o.Box3).setFromObject(e);t.min.x<s.x&&(s.x=t.min.x),t.min.y<s.y&&(s.y=t.min.y),t.min.z<s.z&&(s.z=t.min.z),t.max.x>r.x&&(r.x=t.max.x),t.max.y>r.y&&(r.y=t.max.y),t.max.z>r.z&&(r.z=t.max.z)}const a=new o.Box3(s,r),l=this.components.get(gr);if(l.initialized)for(const[,t]of l.list){const e=t.box;e.min.x<s.x&&(s.x=e.min.x),e.min.y<s.y&&(s.y=e.min.y),e.min.z<s.z&&(s.z=e.min.z),e.max.x>r.x&&(r.x=e.max.x),e.max.y>r.y&&(r.y=e.max.y),e.max.z>r.z&&(r.z=e.max.z)}const c=new o.Vector3;a.getSize(c);const h=new o.Vector3;a.getCenter(h);const u=Math.max(c.x,c.y,c.z)*e,d=new o.Sphere(h,u);await this.controls.fitToSphere(d,!0)}setUserInput(t){t?this.enableUserInput():this.disableUserInput()}addCustomNavigationMode(t){this._navigationModes.set(t.id,t)}disableUserInput(){this._userInputButtons.left=this.controls.mouseButtons.left,this._userInputButtons.right=this.controls.mouseButtons.right,this._userInputButtons.middle=this.controls.mouseButtons.middle,this._userInputButtons.wheel=this.controls.mouseButtons.wheel,this.controls.mouseButtons.left=0,this.controls.mouseButtons.right=0,this.controls.mouseButtons.middle=0,this.controls.mouseButtons.wheel=0}enableUserInput(){0!==Object.keys(this._userInputButtons).length&&(this.controls.mouseButtons.left=this._userInputButtons.left,this.controls.mouseButtons.right=this._userInputButtons.right,this.controls.mouseButtons.middle=this._userInputButtons.middle,this.controls.mouseButtons.wheel=this._userInputButtons.wheel)}newOrthoCamera(){const t=window.innerWidth/window.innerHeight;return new o.OrthographicCamera(this._frustumSize*t/-2,this._frustumSize*t/2,this._frustumSize/2,this._frustumSize/-2,.1,1e3)}setOrthoPerspCameraAspect(){if(!this.currentWorld||!this.currentWorld.renderer)return;if(!this.previousSize)return;const t=this.currentWorld.renderer.getSize(),e=this.threeOrtho.top,i=this.threeOrtho.right,n=e*(t.y/this.previousSize.y),s=i*(t.x/this.previousSize.x);this.threeOrtho.left=-s,this.threeOrtho.right=s,this.threeOrtho.top=n,this.threeOrtho.bottom=-n,this.threeOrtho.updateProjectionMatrix(),this.previousSize.copy(t)}}var La="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Fa(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function Ra(t){throw new Error('Could not dynamically require "'+t+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Ua={exports:{}};
2
- /*!
3
-
4
- JSZip v3.10.1 - A JavaScript class for generating and reading zip files
5
- <http://stuartk.com/jszip>
6
-
7
- (c) 2009-2016 Stuart Knightley <stuart [at] stuartk.com>
8
- Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown.
9
-
10
- JSZip uses the library pako released under the MIT license :
11
- https://github.com/nodeca/pako/blob/main/LICENSE
12
- */const ja=Fa(Ua.exports=function t(e,i,n){function s(o,a){if(!i[o]){if(!e[o]){if(!a&&Ra)return Ra(o);if(r)return r(o,!0);var l=new Error("Cannot find module '"+o+"'");throw l.code="MODULE_NOT_FOUND",l}var c=i[o]={exports:{}};e[o][0].call(c.exports,function(t){return s(e[o][1][t]||t)},c,c.exports,t,e,i,n)}return i[o].exports}for(var r=Ra,o=0;o<n.length;o++)s(n[o]);return s}({1:[function(t,e,i){var n=t("./utils"),s=t("./support"),r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";i.encode=function(t){for(var e,i,s,o,a,l,c,h=[],u=0,d=t.length,p=d,f="string"!==n.getTypeOf(t);u<t.length;)p=d-u,s=f?(e=t[u++],i=u<d?t[u++]:0,u<d?t[u++]:0):(e=t.charCodeAt(u++),i=u<d?t.charCodeAt(u++):0,u<d?t.charCodeAt(u++):0),o=e>>2,a=(3&e)<<4|i>>4,l=1<p?(15&i)<<2|s>>6:64,c=2<p?63&s:64,h.push(r.charAt(o)+r.charAt(a)+r.charAt(l)+r.charAt(c));return h.join("")},i.decode=function(t){var e,i,n,o,a,l,c=0,h=0,u="data:";if(t.substr(0,u.length)===u)throw new Error("Invalid base64 input, it looks like a data url.");var d,p=3*(t=t.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(t.charAt(t.length-1)===r.charAt(64)&&p--,t.charAt(t.length-2)===r.charAt(64)&&p--,p%1!=0)throw new Error("Invalid base64 input, bad content length.");for(d=s.uint8array?new Uint8Array(0|p):new Array(0|p);c<t.length;)e=r.indexOf(t.charAt(c++))<<2|(o=r.indexOf(t.charAt(c++)))>>4,i=(15&o)<<4|(a=r.indexOf(t.charAt(c++)))>>2,n=(3&a)<<6|(l=r.indexOf(t.charAt(c++))),d[h++]=e,64!==a&&(d[h++]=i),64!==l&&(d[h++]=n);return d}},{"./support":30,"./utils":32}],2:[function(t,e,i){var n=t("./external"),s=t("./stream/DataWorker"),r=t("./stream/Crc32Probe"),o=t("./stream/DataLengthProbe");function a(t,e,i,n,s){this.compressedSize=t,this.uncompressedSize=e,this.crc32=i,this.compression=n,this.compressedContent=s}a.prototype={getContentWorker:function(){var t=new s(n.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new o("data_length")),e=this;return t.on("end",function(){if(this.streamInfo.data_length!==e.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),t},getCompressedWorker:function(){return new s(n.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},a.createWorkerFrom=function(t,e,i){return t.pipe(new r).pipe(new o("uncompressedSize")).pipe(e.compressWorker(i)).pipe(new o("compressedSize")).withStreamInfo("compression",e)},e.exports=a},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(t,e,i){var n=t("./stream/GenericWorker");i.STORE={magic:"\0\0",compressWorker:function(){return new n("STORE compression")},uncompressWorker:function(){return new n("STORE decompression")}},i.DEFLATE=t("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(t,e,i){var n=t("./utils"),s=function(){for(var t,e=[],i=0;i<256;i++){t=i;for(var n=0;n<8;n++)t=1&t?3988292384^t>>>1:t>>>1;e[i]=t}return e}();e.exports=function(t,e){return void 0!==t&&t.length?"string"!==n.getTypeOf(t)?function(t,e,i,n){var r=s,o=n+i;t^=-1;for(var a=n;a<o;a++)t=t>>>8^r[255&(t^e[a])];return-1^t}(0|e,t,t.length,0):function(t,e,i,n){var r=s,o=n+i;t^=-1;for(var a=n;a<o;a++)t=t>>>8^r[255&(t^e.charCodeAt(a))];return-1^t}(0|e,t,t.length,0):0}},{"./utils":32}],5:[function(t,e,i){i.base64=!1,i.binary=!1,i.dir=!1,i.createFolders=!0,i.date=null,i.compression=null,i.compressionOptions=null,i.comment=null,i.unixPermissions=null,i.dosPermissions=null},{}],6:[function(t,e,i){var n=null;n="undefined"!=typeof Promise?Promise:t("lie"),e.exports={Promise:n}},{lie:37}],7:[function(t,e,i){var n="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Uint32Array,s=t("pako"),r=t("./utils"),o=t("./stream/GenericWorker"),a=n?"uint8array":"array";function l(t,e){o.call(this,"FlateWorker/"+t),this._pako=null,this._pakoAction=t,this._pakoOptions=e,this.meta={}}i.magic="\b\0",r.inherits(l,o),l.prototype.processChunk=function(t){this.meta=t.meta,null===this._pako&&this._createPako(),this._pako.push(r.transformTo(a,t.data),!1)},l.prototype.flush=function(){o.prototype.flush.call(this),null===this._pako&&this._createPako(),this._pako.push([],!0)},l.prototype.cleanUp=function(){o.prototype.cleanUp.call(this),this._pako=null},l.prototype._createPako=function(){this._pako=new s[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var t=this;this._pako.onData=function(e){t.push({data:e,meta:t.meta})}},i.compressWorker=function(t){return new l("Deflate",t)},i.uncompressWorker=function(){return new l("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(t,e,i){function n(t,e){var i,n="";for(i=0;i<e;i++)n+=String.fromCharCode(255&t),t>>>=8;return n}function s(t,e,i,s,o,h){var u,d,p=t.file,f=t.compression,m=h!==a.utf8encode,g=r.transformTo("string",h(p.name)),w=r.transformTo("string",a.utf8encode(p.name)),y=p.comment,_=r.transformTo("string",h(y)),b=r.transformTo("string",a.utf8encode(y)),v=w.length!==p.name.length,x=b.length!==y.length,C="",S="",A="",P=p.dir,T=p.date,E={crc32:0,compressedSize:0,uncompressedSize:0};e&&!i||(E.crc32=t.crc32,E.compressedSize=t.compressedSize,E.uncompressedSize=t.uncompressedSize);var M=0;e&&(M|=8),m||!v&&!x||(M|=2048);var I,z,D,k=0,B=0;P&&(k|=16),"UNIX"===o?(B=798,k|=(I=p.unixPermissions,z=P,D=I,I||(D=z?16893:33204),(65535&D)<<16)):(B=20,k|=function(t){return 63&(t||0)}(p.dosPermissions)),u=T.getUTCHours(),u<<=6,u|=T.getUTCMinutes(),u<<=5,u|=T.getUTCSeconds()/2,d=T.getUTCFullYear()-1980,d<<=4,d|=T.getUTCMonth()+1,d<<=5,d|=T.getUTCDate(),v&&(S=n(1,1)+n(l(g),4)+w,C+="up"+n(S.length,2)+S),x&&(A=n(1,1)+n(l(_),4)+b,C+="uc"+n(A.length,2)+A);var O="";return O+="\n\0",O+=n(M,2),O+=f.magic,O+=n(u,2),O+=n(d,2),O+=n(E.crc32,4),O+=n(E.compressedSize,4),O+=n(E.uncompressedSize,4),O+=n(g.length,2),O+=n(C.length,2),{fileRecord:c.LOCAL_FILE_HEADER+O+g+C,dirRecord:c.CENTRAL_FILE_HEADER+n(B,2)+O+n(_.length,2)+"\0\0\0\0"+n(k,4)+n(s,4)+g+C+_}}var r=t("../utils"),o=t("../stream/GenericWorker"),a=t("../utf8"),l=t("../crc32"),c=t("../signature");function h(t,e,i,n){o.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=e,this.zipPlatform=i,this.encodeFileName=n,this.streamFiles=t,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}r.inherits(h,o),h.prototype.push=function(t){var e=t.meta.percent||0,i=this.entriesCount,n=this._sources.length;this.accumulate?this.contentBuffer.push(t):(this.bytesWritten+=t.data.length,o.prototype.push.call(this,{data:t.data,meta:{currentFile:this.currentFile,percent:i?(e+100*(i-n-1))/i:100}}))},h.prototype.openedSource=function(t){this.currentSourceOffset=this.bytesWritten,this.currentFile=t.file.name;var e=this.streamFiles&&!t.file.dir;if(e){var i=s(t,e,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:i.fileRecord,meta:{percent:0}})}else this.accumulate=!0},h.prototype.closedSource=function(t){this.accumulate=!1;var e,i=this.streamFiles&&!t.file.dir,r=s(t,i,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(r.dirRecord),i)this.push({data:(e=t,c.DATA_DESCRIPTOR+n(e.crc32,4)+n(e.compressedSize,4)+n(e.uncompressedSize,4)),meta:{percent:100}});else for(this.push({data:r.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},h.prototype.flush=function(){for(var t=this.bytesWritten,e=0;e<this.dirRecords.length;e++)this.push({data:this.dirRecords[e],meta:{percent:100}});var i,s,o,a,l,h,u=this.bytesWritten-t,d=(i=this.dirRecords.length,s=u,o=t,a=this.zipComment,l=this.encodeFileName,h=r.transformTo("string",l(a)),c.CENTRAL_DIRECTORY_END+"\0\0\0\0"+n(i,2)+n(i,2)+n(s,4)+n(o,4)+n(h.length,2)+h);this.push({data:d,meta:{percent:100}})},h.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},h.prototype.registerPrevious=function(t){this._sources.push(t);var e=this;return t.on("data",function(t){e.processChunk(t)}),t.on("end",function(){e.closedSource(e.previous.streamInfo),e._sources.length?e.prepareNextSource():e.end()}),t.on("error",function(t){e.error(t)}),this},h.prototype.resume=function(){return!!o.prototype.resume.call(this)&&(!this.previous&&this._sources.length?(this.prepareNextSource(),!0):this.previous||this._sources.length||this.generatedError?void 0:(this.end(),!0))},h.prototype.error=function(t){var e=this._sources;if(!o.prototype.error.call(this,t))return!1;for(var i=0;i<e.length;i++)try{e[i].error(t)}catch(t){}return!0},h.prototype.lock=function(){o.prototype.lock.call(this);for(var t=this._sources,e=0;e<t.length;e++)t[e].lock()},e.exports=h},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(t,e,i){var n=t("../compressions"),s=t("./ZipFileWorker");i.generateWorker=function(t,e,i){var r=new s(e.streamFiles,i,e.platform,e.encodeFileName),o=0;try{t.forEach(function(t,i){o++;var s=function(t,e){var i=t||e,s=n[i];if(!s)throw new Error(i+" is not a valid compression method !");return s}(i.options.compression,e.compression),a=i.options.compressionOptions||e.compressionOptions||{},l=i.dir,c=i.date;i._compressWorker(s,a).withStreamInfo("file",{name:t,dir:l,date:c,comment:i.comment||"",unixPermissions:i.unixPermissions,dosPermissions:i.dosPermissions}).pipe(r)}),r.entriesCount=o}catch(t){r.error(t)}return r}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(t,e,i){function n(){if(!(this instanceof n))return new n;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");this.files=Object.create(null),this.comment=null,this.root="",this.clone=function(){var t=new n;for(var e in this)"function"!=typeof this[e]&&(t[e]=this[e]);return t}}(n.prototype=t("./object")).loadAsync=t("./load"),n.support=t("./support"),n.defaults=t("./defaults"),n.version="3.10.1",n.loadAsync=function(t,e){return(new n).loadAsync(t,e)},n.external=t("./external"),e.exports=n},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(t,e,i){var n=t("./utils"),s=t("./external"),r=t("./utf8"),o=t("./zipEntries"),a=t("./stream/Crc32Probe"),l=t("./nodejsUtils");function c(t){return new s.Promise(function(e,i){var n=t.decompressed.getContentWorker().pipe(new a);n.on("error",function(t){i(t)}).on("end",function(){n.streamInfo.crc32!==t.decompressed.crc32?i(new Error("Corrupted zip : CRC32 mismatch")):e()}).resume()})}e.exports=function(t,e){var i=this;return e=n.extend(e||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:r.utf8decode}),l.isNode&&l.isStream(t)?s.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):n.prepareContent("the loaded zip file",t,!0,e.optimizedBinaryString,e.base64).then(function(t){var i=new o(e);return i.load(t),i}).then(function(t){var i=[s.Promise.resolve(t)],n=t.files;if(e.checkCRC32)for(var r=0;r<n.length;r++)i.push(c(n[r]));return s.Promise.all(i)}).then(function(t){for(var s=t.shift(),r=s.files,o=0;o<r.length;o++){var a=r[o],l=a.fileNameStr,c=n.resolve(a.fileNameStr);i.file(c,a.decompressed,{binary:!0,optimizedBinaryString:!0,date:a.date,dir:a.dir,comment:a.fileCommentStr.length?a.fileCommentStr:null,unixPermissions:a.unixPermissions,dosPermissions:a.dosPermissions,createFolders:e.createFolders}),a.dir||(i.file(c).unsafeOriginalName=l)}return s.zipComment.length&&(i.comment=s.zipComment),i})}},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(t,e,i){var n=t("../utils"),s=t("../stream/GenericWorker");function r(t,e){s.call(this,"Nodejs stream input adapter for "+t),this._upstreamEnded=!1,this._bindStream(e)}n.inherits(r,s),r.prototype._bindStream=function(t){var e=this;(this._stream=t).pause(),t.on("data",function(t){e.push({data:t,meta:{percent:0}})}).on("error",function(t){e.isPaused?this.generatedError=t:e.error(t)}).on("end",function(){e.isPaused?e._upstreamEnded=!0:e.end()})},r.prototype.pause=function(){return!!s.prototype.pause.call(this)&&(this._stream.pause(),!0)},r.prototype.resume=function(){return!!s.prototype.resume.call(this)&&(this._upstreamEnded?this.end():this._stream.resume(),!0)},e.exports=r},{"../stream/GenericWorker":28,"../utils":32}],13:[function(t,e,i){var n=t("readable-stream").Readable;function s(t,e,i){n.call(this,e),this._helper=t;var s=this;t.on("data",function(t,e){s.push(t)||s._helper.pause(),i&&i(e)}).on("error",function(t){s.emit("error",t)}).on("end",function(){s.push(null)})}t("../utils").inherits(s,n),s.prototype._read=function(){this._helper.resume()},e.exports=s},{"../utils":32,"readable-stream":16}],14:[function(t,e,i){e.exports={isNode:"undefined"!=typeof Buffer,newBufferFrom:function(t,e){if(Buffer.from&&Buffer.from!==Uint8Array.from)return Buffer.from(t,e);if("number"==typeof t)throw new Error('The "data" argument must not be a number');return new Buffer(t,e)},allocBuffer:function(t){if(Buffer.alloc)return Buffer.alloc(t);var e=new Buffer(t);return e.fill(0),e},isBuffer:function(t){return Buffer.isBuffer(t)},isStream:function(t){return t&&"function"==typeof t.on&&"function"==typeof t.pause&&"function"==typeof t.resume}}},{}],15:[function(t,e,i){function n(t,e,i){var n,s=r.getTypeOf(e),a=r.extend(i||{},l);a.date=a.date||new Date,null!==a.compression&&(a.compression=a.compression.toUpperCase()),"string"==typeof a.unixPermissions&&(a.unixPermissions=parseInt(a.unixPermissions,8)),a.unixPermissions&&16384&a.unixPermissions&&(a.dir=!0),a.dosPermissions&&16&a.dosPermissions&&(a.dir=!0),a.dir&&(t=m(t)),a.createFolders&&(n=f(t))&&g.call(this,n,!0);var u="string"===s&&!1===a.binary&&!1===a.base64;i&&void 0!==i.binary||(a.binary=!u),(e instanceof c&&0===e.uncompressedSize||a.dir||!e||0===e.length)&&(a.base64=!1,a.binary=!0,e="",a.compression="STORE",s="string");var w=null;w=e instanceof c||e instanceof o?e:d.isNode&&d.isStream(e)?new p(t,e):r.prepareContent(t,e,a.binary,a.optimizedBinaryString,a.base64);var y=new h(t,w,a);this.files[t]=y}var s=t("./utf8"),r=t("./utils"),o=t("./stream/GenericWorker"),a=t("./stream/StreamHelper"),l=t("./defaults"),c=t("./compressedObject"),h=t("./zipObject"),u=t("./generate"),d=t("./nodejsUtils"),p=t("./nodejs/NodejsStreamInputAdapter"),f=function(t){"/"===t.slice(-1)&&(t=t.substring(0,t.length-1));var e=t.lastIndexOf("/");return 0<e?t.substring(0,e):""},m=function(t){return"/"!==t.slice(-1)&&(t+="/"),t},g=function(t,e){return e=void 0!==e?e:l.createFolders,t=m(t),this.files[t]||n.call(this,t,null,{dir:!0,createFolders:e}),this.files[t]};function w(t){return"[object RegExp]"===Object.prototype.toString.call(t)}var y={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(t){var e,i,n;for(e in this.files)n=this.files[e],(i=e.slice(this.root.length,e.length))&&e.slice(0,this.root.length)===this.root&&t(i,n)},filter:function(t){var e=[];return this.forEach(function(i,n){t(i,n)&&e.push(n)}),e},file:function(t,e,i){if(1!==arguments.length)return t=this.root+t,n.call(this,t,e,i),this;if(w(t)){var s=t;return this.filter(function(t,e){return!e.dir&&s.test(t)})}var r=this.files[this.root+t];return r&&!r.dir?r:null},folder:function(t){if(!t)return this;if(w(t))return this.filter(function(e,i){return i.dir&&t.test(e)});var e=this.root+t,i=g.call(this,e),n=this.clone();return n.root=i.name,n},remove:function(t){t=this.root+t;var e=this.files[t];if(e||("/"!==t.slice(-1)&&(t+="/"),e=this.files[t]),e&&!e.dir)delete this.files[t];else for(var i=this.filter(function(e,i){return i.name.slice(0,t.length)===t}),n=0;n<i.length;n++)delete this.files[i[n].name];return this},generate:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(t){var e,i={};try{if((i=r.extend(t||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:s.utf8encode})).type=i.type.toLowerCase(),i.compression=i.compression.toUpperCase(),"binarystring"===i.type&&(i.type="string"),!i.type)throw new Error("No output type specified.");r.checkSupport(i.type),"darwin"!==i.platform&&"freebsd"!==i.platform&&"linux"!==i.platform&&"sunos"!==i.platform||(i.platform="UNIX"),"win32"===i.platform&&(i.platform="DOS");var n=i.comment||this.comment||"";e=u.generateWorker(this,i,n)}catch(t){(e=new o("error")).error(t)}return new a(e,i.type||"string",i.mimeType)},generateAsync:function(t,e){return this.generateInternalStream(t).accumulate(e)},generateNodeStream:function(t,e){return(t=t||{}).type||(t.type="nodebuffer"),this.generateInternalStream(t).toNodejsStream(e)}};e.exports=y},{"./compressedObject":2,"./defaults":5,"./generate":9,"./nodejs/NodejsStreamInputAdapter":12,"./nodejsUtils":14,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31,"./utils":32,"./zipObject":35}],16:[function(t,e,i){e.exports=t("stream")},{stream:void 0}],17:[function(t,e,i){var n=t("./DataReader");function s(t){n.call(this,t);for(var e=0;e<this.data.length;e++)t[e]=255&t[e]}t("../utils").inherits(s,n),s.prototype.byteAt=function(t){return this.data[this.zero+t]},s.prototype.lastIndexOfSignature=function(t){for(var e=t.charCodeAt(0),i=t.charCodeAt(1),n=t.charCodeAt(2),s=t.charCodeAt(3),r=this.length-4;0<=r;--r)if(this.data[r]===e&&this.data[r+1]===i&&this.data[r+2]===n&&this.data[r+3]===s)return r-this.zero;return-1},s.prototype.readAndCheckSignature=function(t){var e=t.charCodeAt(0),i=t.charCodeAt(1),n=t.charCodeAt(2),s=t.charCodeAt(3),r=this.readData(4);return e===r[0]&&i===r[1]&&n===r[2]&&s===r[3]},s.prototype.readData=function(t){if(this.checkOffset(t),0===t)return[];var e=this.data.slice(this.zero+this.index,this.zero+this.index+t);return this.index+=t,e},e.exports=s},{"../utils":32,"./DataReader":18}],18:[function(t,e,i){var n=t("../utils");function s(t){this.data=t,this.length=t.length,this.index=0,this.zero=0}s.prototype={checkOffset:function(t){this.checkIndex(this.index+t)},checkIndex:function(t){if(this.length<this.zero+t||t<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+t+"). Corrupted zip ?")},setIndex:function(t){this.checkIndex(t),this.index=t},skip:function(t){this.setIndex(this.index+t)},byteAt:function(){},readInt:function(t){var e,i=0;for(this.checkOffset(t),e=this.index+t-1;e>=this.index;e--)i=(i<<8)+this.byteAt(e);return this.index+=t,i},readString:function(t){return n.transformTo("string",this.readData(t))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var t=this.readInt(4);return new Date(Date.UTC(1980+(t>>25&127),(t>>21&15)-1,t>>16&31,t>>11&31,t>>5&63,(31&t)<<1))}},e.exports=s},{"../utils":32}],19:[function(t,e,i){var n=t("./Uint8ArrayReader");function s(t){n.call(this,t)}t("../utils").inherits(s,n),s.prototype.readData=function(t){this.checkOffset(t);var e=this.data.slice(this.zero+this.index,this.zero+this.index+t);return this.index+=t,e},e.exports=s},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(t,e,i){var n=t("./DataReader");function s(t){n.call(this,t)}t("../utils").inherits(s,n),s.prototype.byteAt=function(t){return this.data.charCodeAt(this.zero+t)},s.prototype.lastIndexOfSignature=function(t){return this.data.lastIndexOf(t)-this.zero},s.prototype.readAndCheckSignature=function(t){return t===this.readData(4)},s.prototype.readData=function(t){this.checkOffset(t);var e=this.data.slice(this.zero+this.index,this.zero+this.index+t);return this.index+=t,e},e.exports=s},{"../utils":32,"./DataReader":18}],21:[function(t,e,i){var n=t("./ArrayReader");function s(t){n.call(this,t)}t("../utils").inherits(s,n),s.prototype.readData=function(t){if(this.checkOffset(t),0===t)return new Uint8Array(0);var e=this.data.subarray(this.zero+this.index,this.zero+this.index+t);return this.index+=t,e},e.exports=s},{"../utils":32,"./ArrayReader":17}],22:[function(t,e,i){var n=t("../utils"),s=t("../support"),r=t("./ArrayReader"),o=t("./StringReader"),a=t("./NodeBufferReader"),l=t("./Uint8ArrayReader");e.exports=function(t){var e=n.getTypeOf(t);return n.checkSupport(e),"string"!==e||s.uint8array?"nodebuffer"===e?new a(t):s.uint8array?new l(n.transformTo("uint8array",t)):new r(n.transformTo("array",t)):new o(t)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(t,e,i){i.LOCAL_FILE_HEADER="PK",i.CENTRAL_FILE_HEADER="PK",i.CENTRAL_DIRECTORY_END="PK",i.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK",i.ZIP64_CENTRAL_DIRECTORY_END="PK",i.DATA_DESCRIPTOR="PK\b"},{}],24:[function(t,e,i){var n=t("./GenericWorker"),s=t("../utils");function r(t){n.call(this,"ConvertWorker to "+t),this.destType=t}s.inherits(r,n),r.prototype.processChunk=function(t){this.push({data:s.transformTo(this.destType,t.data),meta:t.meta})},e.exports=r},{"../utils":32,"./GenericWorker":28}],25:[function(t,e,i){var n=t("./GenericWorker"),s=t("../crc32");function r(){n.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}t("../utils").inherits(r,n),r.prototype.processChunk=function(t){this.streamInfo.crc32=s(t.data,this.streamInfo.crc32||0),this.push(t)},e.exports=r},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(t,e,i){var n=t("../utils"),s=t("./GenericWorker");function r(t){s.call(this,"DataLengthProbe for "+t),this.propName=t,this.withStreamInfo(t,0)}n.inherits(r,s),r.prototype.processChunk=function(t){if(t){var e=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=e+t.data.length}s.prototype.processChunk.call(this,t)},e.exports=r},{"../utils":32,"./GenericWorker":28}],27:[function(t,e,i){var n=t("../utils"),s=t("./GenericWorker");function r(t){s.call(this,"DataWorker");var e=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,t.then(function(t){e.dataIsReady=!0,e.data=t,e.max=t&&t.length||0,e.type=n.getTypeOf(t),e.isPaused||e._tickAndRepeat()},function(t){e.error(t)})}n.inherits(r,s),r.prototype.cleanUp=function(){s.prototype.cleanUp.call(this),this.data=null},r.prototype.resume=function(){return!!s.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,n.delay(this._tickAndRepeat,[],this)),!0)},r.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(n.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},r.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var t=null,e=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":t=this.data.substring(this.index,e);break;case"uint8array":t=this.data.subarray(this.index,e);break;case"array":case"nodebuffer":t=this.data.slice(this.index,e)}return this.index=e,this.push({data:t,meta:{percent:this.max?this.index/this.max*100:0}})},e.exports=r},{"../utils":32,"./GenericWorker":28}],28:[function(t,e,i){function n(t){this.name=t||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}n.prototype={push:function(t){this.emit("data",t)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(t){this.emit("error",t)}return!0},error:function(t){return!this.isFinished&&(this.isPaused?this.generatedError=t:(this.isFinished=!0,this.emit("error",t),this.previous&&this.previous.error(t),this.cleanUp()),!0)},on:function(t,e){return this._listeners[t].push(e),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(t,e){if(this._listeners[t])for(var i=0;i<this._listeners[t].length;i++)this._listeners[t][i].call(this,e)},pipe:function(t){return t.registerPrevious(this)},registerPrevious:function(t){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=t.streamInfo,this.mergeStreamInfo(),this.previous=t;var e=this;return t.on("data",function(t){e.processChunk(t)}),t.on("end",function(){e.end()}),t.on("error",function(t){e.error(t)}),this},pause:function(){return!this.isPaused&&!this.isFinished&&(this.isPaused=!0,this.previous&&this.previous.pause(),!0)},resume:function(){if(!this.isPaused||this.isFinished)return!1;var t=this.isPaused=!1;return this.generatedError&&(this.error(this.generatedError),t=!0),this.previous&&this.previous.resume(),!t},flush:function(){},processChunk:function(t){this.push(t)},withStreamInfo:function(t,e){return this.extraStreamInfo[t]=e,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var t in this.extraStreamInfo)Object.prototype.hasOwnProperty.call(this.extraStreamInfo,t)&&(this.streamInfo[t]=this.extraStreamInfo[t])},lock:function(){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.isLocked=!0,this.previous&&this.previous.lock()},toString:function(){var t="Worker "+this.name;return this.previous?this.previous+" -> "+t:t}},e.exports=n},{}],29:[function(t,e,i){var n=t("../utils"),s=t("./ConvertWorker"),r=t("./GenericWorker"),o=t("../base64"),a=t("../support"),l=t("../external"),c=null;if(a.nodestream)try{c=t("../nodejs/NodejsStreamOutputAdapter")}catch(t){}function h(t,e){return new l.Promise(function(i,s){var r=[],a=t._internalType,l=t._outputType,c=t._mimeType;t.on("data",function(t,i){r.push(t),e&&e(i)}).on("error",function(t){r=[],s(t)}).on("end",function(){try{var t=function(t,e,i){switch(t){case"blob":return n.newBlob(n.transformTo("arraybuffer",e),i);case"base64":return o.encode(e);default:return n.transformTo(t,e)}}(l,function(t,e){var i,n=0,s=null,r=0;for(i=0;i<e.length;i++)r+=e[i].length;switch(t){case"string":return e.join("");case"array":return Array.prototype.concat.apply([],e);case"uint8array":for(s=new Uint8Array(r),i=0;i<e.length;i++)s.set(e[i],n),n+=e[i].length;return s;case"nodebuffer":return Buffer.concat(e);default:throw new Error("concat : unsupported type '"+t+"'")}}(a,r),c);i(t)}catch(t){s(t)}r=[]}).resume()})}function u(t,e,i){var o=e;switch(e){case"blob":case"arraybuffer":o="uint8array";break;case"base64":o="string"}try{this._internalType=o,this._outputType=e,this._mimeType=i,n.checkSupport(o),this._worker=t.pipe(new s(o)),t.lock()}catch(t){this._worker=new r("error"),this._worker.error(t)}}u.prototype={accumulate:function(t){return h(this,t)},on:function(t,e){var i=this;return"data"===t?this._worker.on(t,function(t){e.call(i,t.data,t.meta)}):this._worker.on(t,function(){n.delay(e,arguments,i)}),this},resume:function(){return n.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(t){if(n.checkSupport("nodestream"),"nodebuffer"!==this._outputType)throw new Error(this._outputType+" is not supported by this method");return new c(this,{objectMode:"nodebuffer"!==this._outputType},t)}},e.exports=u},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(t,e,i){if(i.base64=!0,i.array=!0,i.string=!0,i.arraybuffer="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array,i.nodebuffer="undefined"!=typeof Buffer,i.uint8array="undefined"!=typeof Uint8Array,"undefined"==typeof ArrayBuffer)i.blob=!1;else{var n=new ArrayBuffer(0);try{i.blob=0===new Blob([n],{type:"application/zip"}).size}catch(t){try{var s=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);s.append(n),i.blob=0===s.getBlob("application/zip").size}catch(t){i.blob=!1}}}try{i.nodestream=!!t("readable-stream").Readable}catch(t){i.nodestream=!1}},{"readable-stream":16}],31:[function(t,e,i){for(var n=t("./utils"),s=t("./support"),r=t("./nodejsUtils"),o=t("./stream/GenericWorker"),a=new Array(256),l=0;l<256;l++)a[l]=252<=l?6:248<=l?5:240<=l?4:224<=l?3:192<=l?2:1;function c(){o.call(this,"utf-8 decode"),this.leftOver=null}function h(){o.call(this,"utf-8 encode")}a[254]=a[254]=1,i.utf8encode=function(t){return s.nodebuffer?r.newBufferFrom(t,"utf-8"):function(t){var e,i,n,r,o,a=t.length,l=0;for(r=0;r<a;r++)55296==(64512&(i=t.charCodeAt(r)))&&r+1<a&&56320==(64512&(n=t.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(n-56320),r++),l+=i<128?1:i<2048?2:i<65536?3:4;for(e=s.uint8array?new Uint8Array(l):new Array(l),r=o=0;o<l;r++)55296==(64512&(i=t.charCodeAt(r)))&&r+1<a&&56320==(64512&(n=t.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(n-56320),r++),i<128?e[o++]=i:(i<2048?e[o++]=192|i>>>6:(i<65536?e[o++]=224|i>>>12:(e[o++]=240|i>>>18,e[o++]=128|i>>>12&63),e[o++]=128|i>>>6&63),e[o++]=128|63&i);return e}(t)},i.utf8decode=function(t){return s.nodebuffer?n.transformTo("nodebuffer",t).toString("utf-8"):function(t){var e,i,s,r,o=t.length,l=new Array(2*o);for(e=i=0;e<o;)if((s=t[e++])<128)l[i++]=s;else if(4<(r=a[s]))l[i++]=65533,e+=r-1;else{for(s&=2===r?31:3===r?15:7;1<r&&e<o;)s=s<<6|63&t[e++],r--;1<r?l[i++]=65533:s<65536?l[i++]=s:(s-=65536,l[i++]=55296|s>>10&1023,l[i++]=56320|1023&s)}return l.length!==i&&(l.subarray?l=l.subarray(0,i):l.length=i),n.applyFromCharCode(l)}(t=n.transformTo(s.uint8array?"uint8array":"array",t))},n.inherits(c,o),c.prototype.processChunk=function(t){var e=n.transformTo(s.uint8array?"uint8array":"array",t.data);if(this.leftOver&&this.leftOver.length){if(s.uint8array){var r=e;(e=new Uint8Array(r.length+this.leftOver.length)).set(this.leftOver,0),e.set(r,this.leftOver.length)}else e=this.leftOver.concat(e);this.leftOver=null}var o=function(t,e){var i;for((e=e||t.length)>t.length&&(e=t.length),i=e-1;0<=i&&128==(192&t[i]);)i--;return i<0||0===i?e:i+a[t[i]]>e?i:e}(e),l=e;o!==e.length&&(s.uint8array?(l=e.subarray(0,o),this.leftOver=e.subarray(o,e.length)):(l=e.slice(0,o),this.leftOver=e.slice(o,e.length))),this.push({data:i.utf8decode(l),meta:t.meta})},c.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:i.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},i.Utf8DecodeWorker=c,n.inherits(h,o),h.prototype.processChunk=function(t){this.push({data:i.utf8encode(t.data),meta:t.meta})},i.Utf8EncodeWorker=h},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(t,e,i){var n=t("./support"),s=t("./base64"),r=t("./nodejsUtils"),o=t("./external");function a(t){return t}function l(t,e){for(var i=0;i<t.length;++i)e[i]=255&t.charCodeAt(i);return e}t("setimmediate"),i.newBlob=function(t,e){i.checkSupport("blob");try{return new Blob([t],{type:e})}catch(i){try{var n=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return n.append(t),n.getBlob(e)}catch(t){throw new Error("Bug : can't construct the Blob.")}}};var c={stringifyByChunk:function(t,e,i){var n=[],s=0,r=t.length;if(r<=i)return String.fromCharCode.apply(null,t);for(;s<r;)"array"===e||"nodebuffer"===e?n.push(String.fromCharCode.apply(null,t.slice(s,Math.min(s+i,r)))):n.push(String.fromCharCode.apply(null,t.subarray(s,Math.min(s+i,r)))),s+=i;return n.join("")},stringifyByChar:function(t){for(var e="",i=0;i<t.length;i++)e+=String.fromCharCode(t[i]);return e},applyCanBeUsed:{uint8array:function(){try{return n.uint8array&&1===String.fromCharCode.apply(null,new Uint8Array(1)).length}catch(t){return!1}}(),nodebuffer:function(){try{return n.nodebuffer&&1===String.fromCharCode.apply(null,r.allocBuffer(1)).length}catch(t){return!1}}()}};function h(t){var e=65536,n=i.getTypeOf(t),s=!0;if("uint8array"===n?s=c.applyCanBeUsed.uint8array:"nodebuffer"===n&&(s=c.applyCanBeUsed.nodebuffer),s)for(;1<e;)try{return c.stringifyByChunk(t,n,e)}catch(t){e=Math.floor(e/2)}return c.stringifyByChar(t)}function u(t,e){for(var i=0;i<t.length;i++)e[i]=t[i];return e}i.applyFromCharCode=h;var d={};d.string={string:a,array:function(t){return l(t,new Array(t.length))},arraybuffer:function(t){return d.string.uint8array(t).buffer},uint8array:function(t){return l(t,new Uint8Array(t.length))},nodebuffer:function(t){return l(t,r.allocBuffer(t.length))}},d.array={string:h,array:a,arraybuffer:function(t){return new Uint8Array(t).buffer},uint8array:function(t){return new Uint8Array(t)},nodebuffer:function(t){return r.newBufferFrom(t)}},d.arraybuffer={string:function(t){return h(new Uint8Array(t))},array:function(t){return u(new Uint8Array(t),new Array(t.byteLength))},arraybuffer:a,uint8array:function(t){return new Uint8Array(t)},nodebuffer:function(t){return r.newBufferFrom(new Uint8Array(t))}},d.uint8array={string:h,array:function(t){return u(t,new Array(t.length))},arraybuffer:function(t){return t.buffer},uint8array:a,nodebuffer:function(t){return r.newBufferFrom(t)}},d.nodebuffer={string:h,array:function(t){return u(t,new Array(t.length))},arraybuffer:function(t){return d.nodebuffer.uint8array(t).buffer},uint8array:function(t){return u(t,new Uint8Array(t.length))},nodebuffer:a},i.transformTo=function(t,e){if(e=e||"",!t)return e;i.checkSupport(t);var n=i.getTypeOf(e);return d[n][t](e)},i.resolve=function(t){for(var e=t.split("/"),i=[],n=0;n<e.length;n++){var s=e[n];"."===s||""===s&&0!==n&&n!==e.length-1||(".."===s?i.pop():i.push(s))}return i.join("/")},i.getTypeOf=function(t){return"string"==typeof t?"string":"[object Array]"===Object.prototype.toString.call(t)?"array":n.nodebuffer&&r.isBuffer(t)?"nodebuffer":n.uint8array&&t instanceof Uint8Array?"uint8array":n.arraybuffer&&t instanceof ArrayBuffer?"arraybuffer":void 0},i.checkSupport=function(t){if(!n[t.toLowerCase()])throw new Error(t+" is not supported by this platform")},i.MAX_VALUE_16BITS=65535,i.MAX_VALUE_32BITS=-1,i.pretty=function(t){var e,i,n="";for(i=0;i<(t||"").length;i++)n+="\\x"+((e=t.charCodeAt(i))<16?"0":"")+e.toString(16).toUpperCase();return n},i.delay=function(t,e,i){setImmediate(function(){t.apply(i||null,e||[])})},i.inherits=function(t,e){function i(){}i.prototype=e.prototype,t.prototype=new i},i.extend=function(){var t,e,i={};for(t=0;t<arguments.length;t++)for(e in arguments[t])Object.prototype.hasOwnProperty.call(arguments[t],e)&&void 0===i[e]&&(i[e]=arguments[t][e]);return i},i.prepareContent=function(t,e,r,a,c){return o.Promise.resolve(e).then(function(t){return n.blob&&(t instanceof Blob||-1!==["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(t)))&&"undefined"!=typeof FileReader?new o.Promise(function(e,i){var n=new FileReader;n.onload=function(t){e(t.target.result)},n.onerror=function(t){i(t.target.error)},n.readAsArrayBuffer(t)}):t}).then(function(e){var h,u=i.getTypeOf(e);return u?("arraybuffer"===u?e=i.transformTo("uint8array",e):"string"===u&&(c?e=s.decode(e):r&&!0!==a&&(e=l(h=e,n.uint8array?new Uint8Array(h.length):new Array(h.length)))),e):o.Promise.reject(new Error("Can't read the data of '"+t+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))})}},{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,setimmediate:54}],33:[function(t,e,i){var n=t("./reader/readerFor"),s=t("./utils"),r=t("./signature"),o=t("./zipEntry"),a=t("./support");function l(t){this.files=[],this.loadOptions=t}l.prototype={checkSignature:function(t){if(!this.reader.readAndCheckSignature(t)){this.reader.index-=4;var e=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+s.pretty(e)+", expected "+s.pretty(t)+")")}},isSignature:function(t,e){var i=this.reader.index;this.reader.setIndex(t);var n=this.reader.readString(4)===e;return this.reader.setIndex(i),n},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2);var t=this.reader.readData(this.zipCommentLength),e=a.uint8array?"uint8array":"array",i=s.transformTo(e,t);this.zipComment=this.loadOptions.decodeFileName(i)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.reader.skip(4),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var t,e,i,n=this.zip64EndOfCentralSize-44;0<n;)t=this.reader.readInt(2),e=this.reader.readInt(4),i=this.reader.readData(e),this.zip64ExtensibleData[t]={id:t,length:e,value:i}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),1<this.disksCount)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var t,e;for(t=0;t<this.files.length;t++)e=this.files[t],this.reader.setIndex(e.localHeaderOffset),this.checkSignature(r.LOCAL_FILE_HEADER),e.readLocalPart(this.reader),e.handleUTF8(),e.processAttributes()},readCentralDir:function(){var t;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(r.CENTRAL_FILE_HEADER);)(t=new o({zip64:this.zip64},this.loadOptions)).readCentralPart(this.reader),this.files.push(t);if(this.centralDirRecords!==this.files.length&&0!==this.centralDirRecords&&0===this.files.length)throw new Error("Corrupted zip or bug: expected "+this.centralDirRecords+" records in central dir, got "+this.files.length)},readEndOfCentral:function(){var t=this.reader.lastIndexOfSignature(r.CENTRAL_DIRECTORY_END);if(t<0)throw this.isSignature(0,r.LOCAL_FILE_HEADER)?new Error("Corrupted zip: can't find end of central directory"):new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html");this.reader.setIndex(t);var e=t;if(this.checkSignature(r.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===s.MAX_VALUE_16BITS||this.diskWithCentralDirStart===s.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===s.MAX_VALUE_16BITS||this.centralDirRecords===s.MAX_VALUE_16BITS||this.centralDirSize===s.MAX_VALUE_32BITS||this.centralDirOffset===s.MAX_VALUE_32BITS){if(this.zip64=!0,(t=this.reader.lastIndexOfSignature(r.ZIP64_CENTRAL_DIRECTORY_LOCATOR))<0)throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");if(this.reader.setIndex(t),this.checkSignature(r.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),!this.isSignature(this.relativeOffsetEndOfZip64CentralDir,r.ZIP64_CENTRAL_DIRECTORY_END)&&(this.relativeOffsetEndOfZip64CentralDir=this.reader.lastIndexOfSignature(r.ZIP64_CENTRAL_DIRECTORY_END),this.relativeOffsetEndOfZip64CentralDir<0))throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir),this.checkSignature(r.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral()}var i=this.centralDirOffset+this.centralDirSize;this.zip64&&(i+=20,i+=12+this.zip64EndOfCentralSize);var n=e-i;if(0<n)this.isSignature(e,r.CENTRAL_FILE_HEADER)||(this.reader.zero=n);else if(n<0)throw new Error("Corrupted zip: missing "+Math.abs(n)+" bytes.")},prepareReader:function(t){this.reader=n(t)},load:function(t){this.prepareReader(t),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}},e.exports=l},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(t,e,i){var n=t("./reader/readerFor"),s=t("./utils"),r=t("./compressedObject"),o=t("./crc32"),a=t("./utf8"),l=t("./compressions"),c=t("./support");function h(t,e){this.options=t,this.loadOptions=e}h.prototype={isEncrypted:function(){return!(1&~this.bitFlag)},useUTF8:function(){return!(2048&~this.bitFlag)},readLocalPart:function(t){var e,i;if(t.skip(22),this.fileNameLength=t.readInt(2),i=t.readInt(2),this.fileName=t.readData(this.fileNameLength),t.skip(i),-1===this.compressedSize||-1===this.uncompressedSize)throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");if(null===(e=function(t){for(var e in l)if(Object.prototype.hasOwnProperty.call(l,e)&&l[e].magic===t)return l[e];return null}(this.compressionMethod)))throw new Error("Corrupted zip : compression "+s.pretty(this.compressionMethod)+" unknown (inner file : "+s.transformTo("string",this.fileName)+")");this.decompressed=new r(this.compressedSize,this.uncompressedSize,this.crc32,e,t.readData(this.compressedSize))},readCentralPart:function(t){this.versionMadeBy=t.readInt(2),t.skip(2),this.bitFlag=t.readInt(2),this.compressionMethod=t.readString(2),this.date=t.readDate(),this.crc32=t.readInt(4),this.compressedSize=t.readInt(4),this.uncompressedSize=t.readInt(4);var e=t.readInt(2);if(this.extraFieldsLength=t.readInt(2),this.fileCommentLength=t.readInt(2),this.diskNumberStart=t.readInt(2),this.internalFileAttributes=t.readInt(2),this.externalFileAttributes=t.readInt(4),this.localHeaderOffset=t.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");t.skip(e),this.readExtraFields(t),this.parseZIP64ExtraField(t),this.fileComment=t.readData(this.fileCommentLength)},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var t=this.versionMadeBy>>8;this.dir=!!(16&this.externalFileAttributes),0==t&&(this.dosPermissions=63&this.externalFileAttributes),3==t&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||"/"!==this.fileNameStr.slice(-1)||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var t=n(this.extraFields[1].value);this.uncompressedSize===s.MAX_VALUE_32BITS&&(this.uncompressedSize=t.readInt(8)),this.compressedSize===s.MAX_VALUE_32BITS&&(this.compressedSize=t.readInt(8)),this.localHeaderOffset===s.MAX_VALUE_32BITS&&(this.localHeaderOffset=t.readInt(8)),this.diskNumberStart===s.MAX_VALUE_32BITS&&(this.diskNumberStart=t.readInt(4))}},readExtraFields:function(t){var e,i,n,s=t.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});t.index+4<s;)e=t.readInt(2),i=t.readInt(2),n=t.readData(i),this.extraFields[e]={id:e,length:i,value:n};t.setIndex(s)},handleUTF8:function(){var t=c.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=a.utf8decode(this.fileName),this.fileCommentStr=a.utf8decode(this.fileComment);else{var e=this.findExtraFieldUnicodePath();if(null!==e)this.fileNameStr=e;else{var i=s.transformTo(t,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(i)}var n=this.findExtraFieldUnicodeComment();if(null!==n)this.fileCommentStr=n;else{var r=s.transformTo(t,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(r)}}},findExtraFieldUnicodePath:function(){var t=this.extraFields[28789];if(t){var e=n(t.value);return 1!==e.readInt(1)||o(this.fileName)!==e.readInt(4)?null:a.utf8decode(e.readData(t.length-5))}return null},findExtraFieldUnicodeComment:function(){var t=this.extraFields[25461];if(t){var e=n(t.value);return 1!==e.readInt(1)||o(this.fileComment)!==e.readInt(4)?null:a.utf8decode(e.readData(t.length-5))}return null}},e.exports=h},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(t,e,i){function n(t,e,i){this.name=t,this.dir=i.dir,this.date=i.date,this.comment=i.comment,this.unixPermissions=i.unixPermissions,this.dosPermissions=i.dosPermissions,this._data=e,this._dataBinary=i.binary,this.options={compression:i.compression,compressionOptions:i.compressionOptions}}var s=t("./stream/StreamHelper"),r=t("./stream/DataWorker"),o=t("./utf8"),a=t("./compressedObject"),l=t("./stream/GenericWorker");n.prototype={internalStream:function(t){var e=null,i="string";try{if(!t)throw new Error("No output type specified.");var n="string"===(i=t.toLowerCase())||"text"===i;"binarystring"!==i&&"text"!==i||(i="string"),e=this._decompressWorker();var r=!this._dataBinary;r&&!n&&(e=e.pipe(new o.Utf8EncodeWorker)),!r&&n&&(e=e.pipe(new o.Utf8DecodeWorker))}catch(t){(e=new l("error")).error(t)}return new s(e,i,"")},async:function(t,e){return this.internalStream(t).accumulate(e)},nodeStream:function(t,e){return this.internalStream(t||"nodebuffer").toNodejsStream(e)},_compressWorker:function(t,e){if(this._data instanceof a&&this._data.compression.magic===t.magic)return this._data.getCompressedWorker();var i=this._decompressWorker();return this._dataBinary||(i=i.pipe(new o.Utf8EncodeWorker)),a.createWorkerFrom(i,t,e)},_decompressWorker:function(){return this._data instanceof a?this._data.getContentWorker():this._data instanceof l?this._data:new r(this._data)}};for(var c=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],h=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},u=0;u<c.length;u++)n.prototype[c[u]]=h;e.exports=n},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(t,e,i){(function(t){var i,n,s=t.MutationObserver||t.WebKitMutationObserver;if(s){var r=0,o=new s(h),a=t.document.createTextNode("");o.observe(a,{characterData:!0}),i=function(){a.data=r=++r%2}}else if(t.setImmediate||void 0===t.MessageChannel)i="document"in t&&"onreadystatechange"in t.document.createElement("script")?function(){var e=t.document.createElement("script");e.onreadystatechange=function(){h(),e.onreadystatechange=null,e.parentNode.removeChild(e),e=null},t.document.documentElement.appendChild(e)}:function(){setTimeout(h,0)};else{var l=new t.MessageChannel;l.port1.onmessage=h,i=function(){l.port2.postMessage(0)}}var c=[];function h(){var t,e;n=!0;for(var i=c.length;i;){for(e=c,c=[],t=-1;++t<i;)e[t]();i=c.length}n=!1}e.exports=function(t){1!==c.push(t)||n||i()}}).call(this,void 0!==La?La:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],37:[function(t,e,i){var n=t("immediate");function s(){}var r={},o=["REJECTED"],a=["FULFILLED"],l=["PENDING"];function c(t){if("function"!=typeof t)throw new TypeError("resolver must be a function");this.state=l,this.queue=[],this.outcome=void 0,t!==s&&p(this,t)}function h(t,e,i){this.promise=t,"function"==typeof e&&(this.onFulfilled=e,this.callFulfilled=this.otherCallFulfilled),"function"==typeof i&&(this.onRejected=i,this.callRejected=this.otherCallRejected)}function u(t,e,i){n(function(){var n;try{n=e(i)}catch(e){return r.reject(t,e)}n===t?r.reject(t,new TypeError("Cannot resolve promise with itself")):r.resolve(t,n)})}function d(t){var e=t&&t.then;if(t&&("object"==typeof t||"function"==typeof t)&&"function"==typeof e)return function(){e.apply(t,arguments)}}function p(t,e){var i=!1;function n(e){i||(i=!0,r.reject(t,e))}function s(e){i||(i=!0,r.resolve(t,e))}var o=f(function(){e(s,n)});"error"===o.status&&n(o.value)}function f(t,e){var i={};try{i.value=t(e),i.status="success"}catch(t){i.status="error",i.value=t}return i}(e.exports=c).prototype.finally=function(t){if("function"!=typeof t)return this;var e=this.constructor;return this.then(function(i){return e.resolve(t()).then(function(){return i})},function(i){return e.resolve(t()).then(function(){throw i})})},c.prototype.catch=function(t){return this.then(null,t)},c.prototype.then=function(t,e){if("function"!=typeof t&&this.state===a||"function"!=typeof e&&this.state===o)return this;var i=new this.constructor(s);return this.state!==l?u(i,this.state===a?t:e,this.outcome):this.queue.push(new h(i,t,e)),i},h.prototype.callFulfilled=function(t){r.resolve(this.promise,t)},h.prototype.otherCallFulfilled=function(t){u(this.promise,this.onFulfilled,t)},h.prototype.callRejected=function(t){r.reject(this.promise,t)},h.prototype.otherCallRejected=function(t){u(this.promise,this.onRejected,t)},r.resolve=function(t,e){var i=f(d,e);if("error"===i.status)return r.reject(t,i.value);var n=i.value;if(n)p(t,n);else{t.state=a,t.outcome=e;for(var s=-1,o=t.queue.length;++s<o;)t.queue[s].callFulfilled(e)}return t},r.reject=function(t,e){t.state=o,t.outcome=e;for(var i=-1,n=t.queue.length;++i<n;)t.queue[i].callRejected(e);return t},c.resolve=function(t){return t instanceof this?t:r.resolve(new this(s),t)},c.reject=function(t){var e=new this(s);return r.reject(e,t)},c.all=function(t){var e=this;if("[object Array]"!==Object.prototype.toString.call(t))return this.reject(new TypeError("must be an array"));var i=t.length,n=!1;if(!i)return this.resolve([]);for(var o=new Array(i),a=0,l=-1,c=new this(s);++l<i;)h(t[l],l);return c;function h(t,s){e.resolve(t).then(function(t){o[s]=t,++a!==i||n||(n=!0,r.resolve(c,o))},function(t){n||(n=!0,r.reject(c,t))})}},c.race=function(t){var e=this;if("[object Array]"!==Object.prototype.toString.call(t))return this.reject(new TypeError("must be an array"));var i=t.length,n=!1;if(!i)return this.resolve([]);for(var o,a=-1,l=new this(s);++a<i;)o=t[a],e.resolve(o).then(function(t){n||(n=!0,r.resolve(l,t))},function(t){n||(n=!0,r.reject(l,t))});return l}},{immediate:36}],38:[function(t,e,i){var n={};(0,t("./lib/utils/common").assign)(n,t("./lib/deflate"),t("./lib/inflate"),t("./lib/zlib/constants")),e.exports=n},{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(t,e,i){var n=t("./zlib/deflate"),s=t("./utils/common"),r=t("./utils/strings"),o=t("./zlib/messages"),a=t("./zlib/zstream"),l=Object.prototype.toString,c=0,h=-1,u=0,d=8;function p(t){if(!(this instanceof p))return new p(t);this.options=s.assign({level:h,method:d,chunkSize:16384,windowBits:15,memLevel:8,strategy:u,to:""},t||{});var e=this.options;e.raw&&0<e.windowBits?e.windowBits=-e.windowBits:e.gzip&&0<e.windowBits&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new a,this.strm.avail_out=0;var i=n.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(i!==c)throw new Error(o[i]);if(e.header&&n.deflateSetHeader(this.strm,e.header),e.dictionary){var f;if(f="string"==typeof e.dictionary?r.string2buf(e.dictionary):"[object ArrayBuffer]"===l.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,(i=n.deflateSetDictionary(this.strm,f))!==c)throw new Error(o[i]);this._dict_set=!0}}function f(t,e){var i=new p(e);if(i.push(t,!0),i.err)throw i.msg||o[i.err];return i.result}p.prototype.push=function(t,e){var i,o,a=this.strm,h=this.options.chunkSize;if(this.ended)return!1;o=e===~~e?e:!0===e?4:0,"string"==typeof t?a.input=r.string2buf(t):"[object ArrayBuffer]"===l.call(t)?a.input=new Uint8Array(t):a.input=t,a.next_in=0,a.avail_in=a.input.length;do{if(0===a.avail_out&&(a.output=new s.Buf8(h),a.next_out=0,a.avail_out=h),1!==(i=n.deflate(a,o))&&i!==c)return this.onEnd(i),!(this.ended=!0);0!==a.avail_out&&(0!==a.avail_in||4!==o&&2!==o)||("string"===this.options.to?this.onData(r.buf2binstring(s.shrinkBuf(a.output,a.next_out))):this.onData(s.shrinkBuf(a.output,a.next_out)))}while((0<a.avail_in||0===a.avail_out)&&1!==i);return 4===o?(i=n.deflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===c):2!==o||(this.onEnd(c),!(a.avail_out=0))},p.prototype.onData=function(t){this.chunks.push(t)},p.prototype.onEnd=function(t){t===c&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=s.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg},i.Deflate=p,i.deflate=f,i.deflateRaw=function(t,e){return(e=e||{}).raw=!0,f(t,e)},i.gzip=function(t,e){return(e=e||{}).gzip=!0,f(t,e)}},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(t,e,i){var n=t("./zlib/inflate"),s=t("./utils/common"),r=t("./utils/strings"),o=t("./zlib/constants"),a=t("./zlib/messages"),l=t("./zlib/zstream"),c=t("./zlib/gzheader"),h=Object.prototype.toString;function u(t){if(!(this instanceof u))return new u(t);this.options=s.assign({chunkSize:16384,windowBits:0,to:""},t||{});var e=this.options;e.raw&&0<=e.windowBits&&e.windowBits<16&&(e.windowBits=-e.windowBits,0===e.windowBits&&(e.windowBits=-15)),!(0<=e.windowBits&&e.windowBits<16)||t&&t.windowBits||(e.windowBits+=32),15<e.windowBits&&e.windowBits<48&&!(15&e.windowBits)&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var i=n.inflateInit2(this.strm,e.windowBits);if(i!==o.Z_OK)throw new Error(a[i]);this.header=new c,n.inflateGetHeader(this.strm,this.header)}function d(t,e){var i=new u(e);if(i.push(t,!0),i.err)throw i.msg||a[i.err];return i.result}u.prototype.push=function(t,e){var i,a,l,c,u,d,p=this.strm,f=this.options.chunkSize,m=this.options.dictionary,g=!1;if(this.ended)return!1;a=e===~~e?e:!0===e?o.Z_FINISH:o.Z_NO_FLUSH,"string"==typeof t?p.input=r.binstring2buf(t):"[object ArrayBuffer]"===h.call(t)?p.input=new Uint8Array(t):p.input=t,p.next_in=0,p.avail_in=p.input.length;do{if(0===p.avail_out&&(p.output=new s.Buf8(f),p.next_out=0,p.avail_out=f),(i=n.inflate(p,o.Z_NO_FLUSH))===o.Z_NEED_DICT&&m&&(d="string"==typeof m?r.string2buf(m):"[object ArrayBuffer]"===h.call(m)?new Uint8Array(m):m,i=n.inflateSetDictionary(this.strm,d)),i===o.Z_BUF_ERROR&&!0===g&&(i=o.Z_OK,g=!1),i!==o.Z_STREAM_END&&i!==o.Z_OK)return this.onEnd(i),!(this.ended=!0);p.next_out&&(0!==p.avail_out&&i!==o.Z_STREAM_END&&(0!==p.avail_in||a!==o.Z_FINISH&&a!==o.Z_SYNC_FLUSH)||("string"===this.options.to?(l=r.utf8border(p.output,p.next_out),c=p.next_out-l,u=r.buf2string(p.output,l),p.next_out=c,p.avail_out=f-c,c&&s.arraySet(p.output,p.output,l,c,0),this.onData(u)):this.onData(s.shrinkBuf(p.output,p.next_out)))),0===p.avail_in&&0===p.avail_out&&(g=!0)}while((0<p.avail_in||0===p.avail_out)&&i!==o.Z_STREAM_END);return i===o.Z_STREAM_END&&(a=o.Z_FINISH),a===o.Z_FINISH?(i=n.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===o.Z_OK):a!==o.Z_SYNC_FLUSH||(this.onEnd(o.Z_OK),!(p.avail_out=0))},u.prototype.onData=function(t){this.chunks.push(t)},u.prototype.onEnd=function(t){t===o.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=s.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg},i.Inflate=u,i.inflate=d,i.inflateRaw=function(t,e){return(e=e||{}).raw=!0,d(t,e)},i.ungzip=d},{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(t,e,i){var n="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;i.assign=function(t){for(var e=Array.prototype.slice.call(arguments,1);e.length;){var i=e.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(var n in i)i.hasOwnProperty(n)&&(t[n]=i[n])}}return t},i.shrinkBuf=function(t,e){return t.length===e?t:t.subarray?t.subarray(0,e):(t.length=e,t)};var s={arraySet:function(t,e,i,n,s){if(e.subarray&&t.subarray)t.set(e.subarray(i,i+n),s);else for(var r=0;r<n;r++)t[s+r]=e[i+r]},flattenChunks:function(t){var e,i,n,s,r,o;for(e=n=0,i=t.length;e<i;e++)n+=t[e].length;for(o=new Uint8Array(n),e=s=0,i=t.length;e<i;e++)r=t[e],o.set(r,s),s+=r.length;return o}},r={arraySet:function(t,e,i,n,s){for(var r=0;r<n;r++)t[s+r]=e[i+r]},flattenChunks:function(t){return[].concat.apply([],t)}};i.setTyped=function(t){t?(i.Buf8=Uint8Array,i.Buf16=Uint16Array,i.Buf32=Int32Array,i.assign(i,s)):(i.Buf8=Array,i.Buf16=Array,i.Buf32=Array,i.assign(i,r))},i.setTyped(n)},{}],42:[function(t,e,i){var n=t("./common"),s=!0,r=!0;try{String.fromCharCode.apply(null,[0])}catch(t){s=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){r=!1}for(var o=new n.Buf8(256),a=0;a<256;a++)o[a]=252<=a?6:248<=a?5:240<=a?4:224<=a?3:192<=a?2:1;function l(t,e){if(e<65537&&(t.subarray&&r||!t.subarray&&s))return String.fromCharCode.apply(null,n.shrinkBuf(t,e));for(var i="",o=0;o<e;o++)i+=String.fromCharCode(t[o]);return i}o[254]=o[254]=1,i.string2buf=function(t){var e,i,s,r,o,a=t.length,l=0;for(r=0;r<a;r++)55296==(64512&(i=t.charCodeAt(r)))&&r+1<a&&56320==(64512&(s=t.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(s-56320),r++),l+=i<128?1:i<2048?2:i<65536?3:4;for(e=new n.Buf8(l),r=o=0;o<l;r++)55296==(64512&(i=t.charCodeAt(r)))&&r+1<a&&56320==(64512&(s=t.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(s-56320),r++),i<128?e[o++]=i:(i<2048?e[o++]=192|i>>>6:(i<65536?e[o++]=224|i>>>12:(e[o++]=240|i>>>18,e[o++]=128|i>>>12&63),e[o++]=128|i>>>6&63),e[o++]=128|63&i);return e},i.buf2binstring=function(t){return l(t,t.length)},i.binstring2buf=function(t){for(var e=new n.Buf8(t.length),i=0,s=e.length;i<s;i++)e[i]=t.charCodeAt(i);return e},i.buf2string=function(t,e){var i,n,s,r,a=e||t.length,c=new Array(2*a);for(i=n=0;i<a;)if((s=t[i++])<128)c[n++]=s;else if(4<(r=o[s]))c[n++]=65533,i+=r-1;else{for(s&=2===r?31:3===r?15:7;1<r&&i<a;)s=s<<6|63&t[i++],r--;1<r?c[n++]=65533:s<65536?c[n++]=s:(s-=65536,c[n++]=55296|s>>10&1023,c[n++]=56320|1023&s)}return l(c,n)},i.utf8border=function(t,e){var i;for((e=e||t.length)>t.length&&(e=t.length),i=e-1;0<=i&&128==(192&t[i]);)i--;return i<0||0===i?e:i+o[t[i]]>e?i:e}},{"./common":41}],43:[function(t,e,i){e.exports=function(t,e,i,n){for(var s=65535&t,r=t>>>16&65535,o=0;0!==i;){for(i-=o=2e3<i?2e3:i;r=r+(s=s+e[n++]|0)|0,--o;);s%=65521,r%=65521}return s|r<<16}},{}],44:[function(t,e,i){e.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],45:[function(t,e,i){var n=function(){for(var t,e=[],i=0;i<256;i++){t=i;for(var n=0;n<8;n++)t=1&t?3988292384^t>>>1:t>>>1;e[i]=t}return e}();e.exports=function(t,e,i,s){var r=n,o=s+i;t^=-1;for(var a=s;a<o;a++)t=t>>>8^r[255&(t^e[a])];return-1^t}},{}],46:[function(t,e,i){var n,s=t("../utils/common"),r=t("./trees"),o=t("./adler32"),a=t("./crc32"),l=t("./messages"),c=0,h=4,u=0,d=-2,p=-1,f=4,m=2,g=8,w=9,y=286,_=30,b=19,v=2*y+1,x=15,C=3,S=258,A=S+C+1,P=42,T=113,E=1,M=2,I=3,z=4;function D(t,e){return t.msg=l[e],e}function k(t){return(t<<1)-(4<t?9:0)}function B(t){for(var e=t.length;0<=--e;)t[e]=0}function O(t){var e=t.state,i=e.pending;i>t.avail_out&&(i=t.avail_out),0!==i&&(s.arraySet(t.output,e.pending_buf,e.pending_out,i,t.next_out),t.next_out+=i,e.pending_out+=i,t.total_out+=i,t.avail_out-=i,e.pending-=i,0===e.pending&&(e.pending_out=0))}function N(t,e){r._tr_flush_block(t,0<=t.block_start?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,O(t.strm)}function V(t,e){t.pending_buf[t.pending++]=e}function L(t,e){t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e}function F(t,e){var i,n,s=t.max_chain_length,r=t.strstart,o=t.prev_length,a=t.nice_match,l=t.strstart>t.w_size-A?t.strstart-(t.w_size-A):0,c=t.window,h=t.w_mask,u=t.prev,d=t.strstart+S,p=c[r+o-1],f=c[r+o];t.prev_length>=t.good_match&&(s>>=2),a>t.lookahead&&(a=t.lookahead);do{if(c[(i=e)+o]===f&&c[i+o-1]===p&&c[i]===c[r]&&c[++i]===c[r+1]){r+=2,i++;do{}while(c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&r<d);if(n=S-(d-r),r=d-S,o<n){if(t.match_start=e,a<=(o=n))break;p=c[r+o-1],f=c[r+o]}}}while((e=u[e&h])>l&&0!=--s);return o<=t.lookahead?o:t.lookahead}function R(t){var e,i,n,r,l,c,h,u,d,p,f=t.w_size;do{if(r=t.window_size-t.lookahead-t.strstart,t.strstart>=f+(f-A)){for(s.arraySet(t.window,t.window,f,f,0),t.match_start-=f,t.strstart-=f,t.block_start-=f,e=i=t.hash_size;n=t.head[--e],t.head[e]=f<=n?n-f:0,--i;);for(e=i=f;n=t.prev[--e],t.prev[e]=f<=n?n-f:0,--i;);r+=f}if(0===t.strm.avail_in)break;if(c=t.strm,h=t.window,u=t.strstart+t.lookahead,p=void 0,(d=r)<(p=c.avail_in)&&(p=d),i=0===p?0:(c.avail_in-=p,s.arraySet(h,c.input,c.next_in,p,u),1===c.state.wrap?c.adler=o(c.adler,h,p,u):2===c.state.wrap&&(c.adler=a(c.adler,h,p,u)),c.next_in+=p,c.total_in+=p,p),t.lookahead+=i,t.lookahead+t.insert>=C)for(l=t.strstart-t.insert,t.ins_h=t.window[l],t.ins_h=(t.ins_h<<t.hash_shift^t.window[l+1])&t.hash_mask;t.insert&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[l+C-1])&t.hash_mask,t.prev[l&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=l,l++,t.insert--,!(t.lookahead+t.insert<C)););}while(t.lookahead<A&&0!==t.strm.avail_in)}function U(t,e){for(var i,n;;){if(t.lookahead<A){if(R(t),t.lookahead<A&&e===c)return E;if(0===t.lookahead)break}if(i=0,t.lookahead>=C&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+C-1])&t.hash_mask,i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==i&&t.strstart-i<=t.w_size-A&&(t.match_length=F(t,i)),t.match_length>=C)if(n=r._tr_tally(t,t.strstart-t.match_start,t.match_length-C),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=C){for(t.match_length--;t.strstart++,t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+C-1])&t.hash_mask,i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart,0!=--t.match_length;);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+1])&t.hash_mask;else n=r._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(n&&(N(t,!1),0===t.strm.avail_out))return E}return t.insert=t.strstart<C-1?t.strstart:C-1,e===h?(N(t,!0),0===t.strm.avail_out?I:z):t.last_lit&&(N(t,!1),0===t.strm.avail_out)?E:M}function j(t,e){for(var i,n,s;;){if(t.lookahead<A){if(R(t),t.lookahead<A&&e===c)return E;if(0===t.lookahead)break}if(i=0,t.lookahead>=C&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+C-1])&t.hash_mask,i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=C-1,0!==i&&t.prev_length<t.max_lazy_match&&t.strstart-i<=t.w_size-A&&(t.match_length=F(t,i),t.match_length<=5&&(1===t.strategy||t.match_length===C&&4096<t.strstart-t.match_start)&&(t.match_length=C-1)),t.prev_length>=C&&t.match_length<=t.prev_length){for(s=t.strstart+t.lookahead-C,n=r._tr_tally(t,t.strstart-1-t.prev_match,t.prev_length-C),t.lookahead-=t.prev_length-1,t.prev_length-=2;++t.strstart<=s&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+C-1])&t.hash_mask,i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!=--t.prev_length;);if(t.match_available=0,t.match_length=C-1,t.strstart++,n&&(N(t,!1),0===t.strm.avail_out))return E}else if(t.match_available){if((n=r._tr_tally(t,0,t.window[t.strstart-1]))&&N(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return E}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(n=r._tr_tally(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<C-1?t.strstart:C-1,e===h?(N(t,!0),0===t.strm.avail_out?I:z):t.last_lit&&(N(t,!1),0===t.strm.avail_out)?E:M}function $(t,e,i,n,s){this.good_length=t,this.max_lazy=e,this.nice_length=i,this.max_chain=n,this.func=s}function W(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=g,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new s.Buf16(2*v),this.dyn_dtree=new s.Buf16(2*(2*_+1)),this.bl_tree=new s.Buf16(2*(2*b+1)),B(this.dyn_ltree),B(this.dyn_dtree),B(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new s.Buf16(x+1),this.heap=new s.Buf16(2*y+1),B(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new s.Buf16(2*y+1),B(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function G(t){var e;return t&&t.state?(t.total_in=t.total_out=0,t.data_type=m,(e=t.state).pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=e.wrap?P:T,t.adler=2===e.wrap?0:1,e.last_flush=c,r._tr_init(e),u):D(t,d)}function H(t){var e,i=G(t);return i===u&&((e=t.state).window_size=2*e.w_size,B(e.head),e.max_lazy_match=n[e.level].max_lazy,e.good_match=n[e.level].good_length,e.nice_match=n[e.level].nice_length,e.max_chain_length=n[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=C-1,e.match_available=0,e.ins_h=0),i}function Z(t,e,i,n,r,o){if(!t)return d;var a=1;if(e===p&&(e=6),n<0?(a=0,n=-n):15<n&&(a=2,n-=16),r<1||w<r||i!==g||n<8||15<n||e<0||9<e||o<0||f<o)return D(t,d);8===n&&(n=9);var l=new W;return(t.state=l).strm=t,l.wrap=a,l.gzhead=null,l.w_bits=n,l.w_size=1<<l.w_bits,l.w_mask=l.w_size-1,l.hash_bits=r+7,l.hash_size=1<<l.hash_bits,l.hash_mask=l.hash_size-1,l.hash_shift=~~((l.hash_bits+C-1)/C),l.window=new s.Buf8(2*l.w_size),l.head=new s.Buf16(l.hash_size),l.prev=new s.Buf16(l.w_size),l.lit_bufsize=1<<r+6,l.pending_buf_size=4*l.lit_bufsize,l.pending_buf=new s.Buf8(l.pending_buf_size),l.d_buf=1*l.lit_bufsize,l.l_buf=3*l.lit_bufsize,l.level=e,l.strategy=o,l.method=i,H(t)}n=[new $(0,0,0,0,function(t,e){var i=65535;for(i>t.pending_buf_size-5&&(i=t.pending_buf_size-5);;){if(t.lookahead<=1){if(R(t),0===t.lookahead&&e===c)return E;if(0===t.lookahead)break}t.strstart+=t.lookahead,t.lookahead=0;var n=t.block_start+i;if((0===t.strstart||t.strstart>=n)&&(t.lookahead=t.strstart-n,t.strstart=n,N(t,!1),0===t.strm.avail_out))return E;if(t.strstart-t.block_start>=t.w_size-A&&(N(t,!1),0===t.strm.avail_out))return E}return t.insert=0,e===h?(N(t,!0),0===t.strm.avail_out?I:z):(t.strstart>t.block_start&&(N(t,!1),t.strm.avail_out),E)}),new $(4,4,8,4,U),new $(4,5,16,8,U),new $(4,6,32,32,U),new $(4,4,16,16,j),new $(8,16,32,32,j),new $(8,16,128,128,j),new $(8,32,128,256,j),new $(32,128,258,1024,j),new $(32,258,258,4096,j)],i.deflateInit=function(t,e){return Z(t,e,g,15,8,0)},i.deflateInit2=Z,i.deflateReset=H,i.deflateResetKeep=G,i.deflateSetHeader=function(t,e){return t&&t.state?2!==t.state.wrap?d:(t.state.gzhead=e,u):d},i.deflate=function(t,e){var i,s,o,l;if(!t||!t.state||5<e||e<0)return t?D(t,d):d;if(s=t.state,!t.output||!t.input&&0!==t.avail_in||666===s.status&&e!==h)return D(t,0===t.avail_out?-5:d);if(s.strm=t,i=s.last_flush,s.last_flush=e,s.status===P)if(2===s.wrap)t.adler=0,V(s,31),V(s,139),V(s,8),s.gzhead?(V(s,(s.gzhead.text?1:0)+(s.gzhead.hcrc?2:0)+(s.gzhead.extra?4:0)+(s.gzhead.name?8:0)+(s.gzhead.comment?16:0)),V(s,255&s.gzhead.time),V(s,s.gzhead.time>>8&255),V(s,s.gzhead.time>>16&255),V(s,s.gzhead.time>>24&255),V(s,9===s.level?2:2<=s.strategy||s.level<2?4:0),V(s,255&s.gzhead.os),s.gzhead.extra&&s.gzhead.extra.length&&(V(s,255&s.gzhead.extra.length),V(s,s.gzhead.extra.length>>8&255)),s.gzhead.hcrc&&(t.adler=a(t.adler,s.pending_buf,s.pending,0)),s.gzindex=0,s.status=69):(V(s,0),V(s,0),V(s,0),V(s,0),V(s,0),V(s,9===s.level?2:2<=s.strategy||s.level<2?4:0),V(s,3),s.status=T);else{var p=g+(s.w_bits-8<<4)<<8;p|=(2<=s.strategy||s.level<2?0:s.level<6?1:6===s.level?2:3)<<6,0!==s.strstart&&(p|=32),p+=31-p%31,s.status=T,L(s,p),0!==s.strstart&&(L(s,t.adler>>>16),L(s,65535&t.adler)),t.adler=1}if(69===s.status)if(s.gzhead.extra){for(o=s.pending;s.gzindex<(65535&s.gzhead.extra.length)&&(s.pending!==s.pending_buf_size||(s.gzhead.hcrc&&s.pending>o&&(t.adler=a(t.adler,s.pending_buf,s.pending-o,o)),O(t),o=s.pending,s.pending!==s.pending_buf_size));)V(s,255&s.gzhead.extra[s.gzindex]),s.gzindex++;s.gzhead.hcrc&&s.pending>o&&(t.adler=a(t.adler,s.pending_buf,s.pending-o,o)),s.gzindex===s.gzhead.extra.length&&(s.gzindex=0,s.status=73)}else s.status=73;if(73===s.status)if(s.gzhead.name){o=s.pending;do{if(s.pending===s.pending_buf_size&&(s.gzhead.hcrc&&s.pending>o&&(t.adler=a(t.adler,s.pending_buf,s.pending-o,o)),O(t),o=s.pending,s.pending===s.pending_buf_size)){l=1;break}l=s.gzindex<s.gzhead.name.length?255&s.gzhead.name.charCodeAt(s.gzindex++):0,V(s,l)}while(0!==l);s.gzhead.hcrc&&s.pending>o&&(t.adler=a(t.adler,s.pending_buf,s.pending-o,o)),0===l&&(s.gzindex=0,s.status=91)}else s.status=91;if(91===s.status)if(s.gzhead.comment){o=s.pending;do{if(s.pending===s.pending_buf_size&&(s.gzhead.hcrc&&s.pending>o&&(t.adler=a(t.adler,s.pending_buf,s.pending-o,o)),O(t),o=s.pending,s.pending===s.pending_buf_size)){l=1;break}l=s.gzindex<s.gzhead.comment.length?255&s.gzhead.comment.charCodeAt(s.gzindex++):0,V(s,l)}while(0!==l);s.gzhead.hcrc&&s.pending>o&&(t.adler=a(t.adler,s.pending_buf,s.pending-o,o)),0===l&&(s.status=103)}else s.status=103;if(103===s.status&&(s.gzhead.hcrc?(s.pending+2>s.pending_buf_size&&O(t),s.pending+2<=s.pending_buf_size&&(V(s,255&t.adler),V(s,t.adler>>8&255),t.adler=0,s.status=T)):s.status=T),0!==s.pending){if(O(t),0===t.avail_out)return s.last_flush=-1,u}else if(0===t.avail_in&&k(e)<=k(i)&&e!==h)return D(t,-5);if(666===s.status&&0!==t.avail_in)return D(t,-5);if(0!==t.avail_in||0!==s.lookahead||e!==c&&666!==s.status){var f=2===s.strategy?function(t,e){for(var i;;){if(0===t.lookahead&&(R(t),0===t.lookahead)){if(e===c)return E;break}if(t.match_length=0,i=r._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,i&&(N(t,!1),0===t.strm.avail_out))return E}return t.insert=0,e===h?(N(t,!0),0===t.strm.avail_out?I:z):t.last_lit&&(N(t,!1),0===t.strm.avail_out)?E:M}(s,e):3===s.strategy?function(t,e){for(var i,n,s,o,a=t.window;;){if(t.lookahead<=S){if(R(t),t.lookahead<=S&&e===c)return E;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=C&&0<t.strstart&&(n=a[s=t.strstart-1])===a[++s]&&n===a[++s]&&n===a[++s]){o=t.strstart+S;do{}while(n===a[++s]&&n===a[++s]&&n===a[++s]&&n===a[++s]&&n===a[++s]&&n===a[++s]&&n===a[++s]&&n===a[++s]&&s<o);t.match_length=S-(o-s),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=C?(i=r._tr_tally(t,1,t.match_length-C),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(i=r._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),i&&(N(t,!1),0===t.strm.avail_out))return E}return t.insert=0,e===h?(N(t,!0),0===t.strm.avail_out?I:z):t.last_lit&&(N(t,!1),0===t.strm.avail_out)?E:M}(s,e):n[s.level].func(s,e);if(f!==I&&f!==z||(s.status=666),f===E||f===I)return 0===t.avail_out&&(s.last_flush=-1),u;if(f===M&&(1===e?r._tr_align(s):5!==e&&(r._tr_stored_block(s,0,0,!1),3===e&&(B(s.head),0===s.lookahead&&(s.strstart=0,s.block_start=0,s.insert=0))),O(t),0===t.avail_out))return s.last_flush=-1,u}return e!==h?u:s.wrap<=0?1:(2===s.wrap?(V(s,255&t.adler),V(s,t.adler>>8&255),V(s,t.adler>>16&255),V(s,t.adler>>24&255),V(s,255&t.total_in),V(s,t.total_in>>8&255),V(s,t.total_in>>16&255),V(s,t.total_in>>24&255)):(L(s,t.adler>>>16),L(s,65535&t.adler)),O(t),0<s.wrap&&(s.wrap=-s.wrap),0!==s.pending?u:1)},i.deflateEnd=function(t){var e;return t&&t.state?(e=t.state.status)!==P&&69!==e&&73!==e&&91!==e&&103!==e&&e!==T&&666!==e?D(t,d):(t.state=null,e===T?D(t,-3):u):d},i.deflateSetDictionary=function(t,e){var i,n,r,a,l,c,h,p,f=e.length;if(!t||!t.state)return d;if(2===(a=(i=t.state).wrap)||1===a&&i.status!==P||i.lookahead)return d;for(1===a&&(t.adler=o(t.adler,e,f,0)),i.wrap=0,f>=i.w_size&&(0===a&&(B(i.head),i.strstart=0,i.block_start=0,i.insert=0),p=new s.Buf8(i.w_size),s.arraySet(p,e,f-i.w_size,i.w_size,0),e=p,f=i.w_size),l=t.avail_in,c=t.next_in,h=t.input,t.avail_in=f,t.next_in=0,t.input=e,R(i);i.lookahead>=C;){for(n=i.strstart,r=i.lookahead-(C-1);i.ins_h=(i.ins_h<<i.hash_shift^i.window[n+C-1])&i.hash_mask,i.prev[n&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=n,n++,--r;);i.strstart=n,i.lookahead=C-1,R(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=C-1,i.match_available=0,t.next_in=c,t.input=h,t.avail_in=l,i.wrap=a,u},i.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(t,e,i){e.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],48:[function(t,e,i){e.exports=function(t,e){var i,n,s,r,o,a,l,c,h,u,d,p,f,m,g,w,y,_,b,v,x,C,S,A,P;i=t.state,n=t.next_in,A=t.input,s=n+(t.avail_in-5),r=t.next_out,P=t.output,o=r-(e-t.avail_out),a=r+(t.avail_out-257),l=i.dmax,c=i.wsize,h=i.whave,u=i.wnext,d=i.window,p=i.hold,f=i.bits,m=i.lencode,g=i.distcode,w=(1<<i.lenbits)-1,y=(1<<i.distbits)-1;t:do{f<15&&(p+=A[n++]<<f,f+=8,p+=A[n++]<<f,f+=8),_=m[p&w];e:for(;;){if(p>>>=b=_>>>24,f-=b,0==(b=_>>>16&255))P[r++]=65535&_;else{if(!(16&b)){if(!(64&b)){_=m[(65535&_)+(p&(1<<b)-1)];continue e}if(32&b){i.mode=12;break t}t.msg="invalid literal/length code",i.mode=30;break t}v=65535&_,(b&=15)&&(f<b&&(p+=A[n++]<<f,f+=8),v+=p&(1<<b)-1,p>>>=b,f-=b),f<15&&(p+=A[n++]<<f,f+=8,p+=A[n++]<<f,f+=8),_=g[p&y];i:for(;;){if(p>>>=b=_>>>24,f-=b,!(16&(b=_>>>16&255))){if(!(64&b)){_=g[(65535&_)+(p&(1<<b)-1)];continue i}t.msg="invalid distance code",i.mode=30;break t}if(x=65535&_,f<(b&=15)&&(p+=A[n++]<<f,(f+=8)<b&&(p+=A[n++]<<f,f+=8)),l<(x+=p&(1<<b)-1)){t.msg="invalid distance too far back",i.mode=30;break t}if(p>>>=b,f-=b,(b=r-o)<x){if(h<(b=x-b)&&i.sane){t.msg="invalid distance too far back",i.mode=30;break t}if(S=d,(C=0)===u){if(C+=c-b,b<v){for(v-=b;P[r++]=d[C++],--b;);C=r-x,S=P}}else if(u<b){if(C+=c+u-b,(b-=u)<v){for(v-=b;P[r++]=d[C++],--b;);if(C=0,u<v){for(v-=b=u;P[r++]=d[C++],--b;);C=r-x,S=P}}}else if(C+=u-b,b<v){for(v-=b;P[r++]=d[C++],--b;);C=r-x,S=P}for(;2<v;)P[r++]=S[C++],P[r++]=S[C++],P[r++]=S[C++],v-=3;v&&(P[r++]=S[C++],1<v&&(P[r++]=S[C++]))}else{for(C=r-x;P[r++]=P[C++],P[r++]=P[C++],P[r++]=P[C++],2<(v-=3););v&&(P[r++]=P[C++],1<v&&(P[r++]=P[C++]))}break}}break}}while(n<s&&r<a);n-=v=f>>3,p&=(1<<(f-=v<<3))-1,t.next_in=n,t.next_out=r,t.avail_in=n<s?s-n+5:5-(n-s),t.avail_out=r<a?a-r+257:257-(r-a),i.hold=p,i.bits=f}},{}],49:[function(t,e,i){var n=t("../utils/common"),s=t("./adler32"),r=t("./crc32"),o=t("./inffast"),a=t("./inftrees"),l=1,c=2,h=0,u=-2,d=1,p=852,f=592;function m(t){return(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24)}function g(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new n.Buf16(320),this.work=new n.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function w(t){var e;return t&&t.state?(e=t.state,t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=d,e.last=0,e.havedict=0,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new n.Buf32(p),e.distcode=e.distdyn=new n.Buf32(f),e.sane=1,e.back=-1,h):u}function y(t){var e;return t&&t.state?((e=t.state).wsize=0,e.whave=0,e.wnext=0,w(t)):u}function _(t,e){var i,n;return t&&t.state?(n=t.state,e<0?(i=0,e=-e):(i=1+(e>>4),e<48&&(e&=15)),e&&(e<8||15<e)?u:(null!==n.window&&n.wbits!==e&&(n.window=null),n.wrap=i,n.wbits=e,y(t))):u}function b(t,e){var i,n;return t?(n=new g,(t.state=n).window=null,(i=_(t,e))!==h&&(t.state=null),i):u}var v,x,C=!0;function S(t){if(C){var e;for(v=new n.Buf32(512),x=new n.Buf32(32),e=0;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(a(l,t.lens,0,288,v,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;a(c,t.lens,0,32,x,0,t.work,{bits:5}),C=!1}t.lencode=v,t.lenbits=9,t.distcode=x,t.distbits=5}function A(t,e,i,s){var r,o=t.state;return null===o.window&&(o.wsize=1<<o.wbits,o.wnext=0,o.whave=0,o.window=new n.Buf8(o.wsize)),s>=o.wsize?(n.arraySet(o.window,e,i-o.wsize,o.wsize,0),o.wnext=0,o.whave=o.wsize):(s<(r=o.wsize-o.wnext)&&(r=s),n.arraySet(o.window,e,i-s,r,o.wnext),(s-=r)?(n.arraySet(o.window,e,i-s,s,0),o.wnext=s,o.whave=o.wsize):(o.wnext+=r,o.wnext===o.wsize&&(o.wnext=0),o.whave<o.wsize&&(o.whave+=r))),0}i.inflateReset=y,i.inflateReset2=_,i.inflateResetKeep=w,i.inflateInit=function(t){return b(t,15)},i.inflateInit2=b,i.inflate=function(t,e){var i,p,f,g,w,y,_,b,v,x,C,P,T,E,M,I,z,D,k,B,O,N,V,L,F=0,R=new n.Buf8(4),U=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!t||!t.state||!t.output||!t.input&&0!==t.avail_in)return u;12===(i=t.state).mode&&(i.mode=13),w=t.next_out,f=t.output,_=t.avail_out,g=t.next_in,p=t.input,y=t.avail_in,b=i.hold,v=i.bits,x=y,C=_,N=h;t:for(;;)switch(i.mode){case d:if(0===i.wrap){i.mode=13;break}for(;v<16;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}if(2&i.wrap&&35615===b){R[i.check=0]=255&b,R[1]=b>>>8&255,i.check=r(i.check,R,2,0),v=b=0,i.mode=2;break}if(i.flags=0,i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&b)<<8)+(b>>8))%31){t.msg="incorrect header check",i.mode=30;break}if(8!=(15&b)){t.msg="unknown compression method",i.mode=30;break}if(v-=4,O=8+(15&(b>>>=4)),0===i.wbits)i.wbits=O;else if(O>i.wbits){t.msg="invalid window size",i.mode=30;break}i.dmax=1<<O,t.adler=i.check=1,i.mode=512&b?10:12,v=b=0;break;case 2:for(;v<16;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}if(i.flags=b,8!=(255&i.flags)){t.msg="unknown compression method",i.mode=30;break}if(57344&i.flags){t.msg="unknown header flags set",i.mode=30;break}i.head&&(i.head.text=b>>8&1),512&i.flags&&(R[0]=255&b,R[1]=b>>>8&255,i.check=r(i.check,R,2,0)),v=b=0,i.mode=3;case 3:for(;v<32;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}i.head&&(i.head.time=b),512&i.flags&&(R[0]=255&b,R[1]=b>>>8&255,R[2]=b>>>16&255,R[3]=b>>>24&255,i.check=r(i.check,R,4,0)),v=b=0,i.mode=4;case 4:for(;v<16;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}i.head&&(i.head.xflags=255&b,i.head.os=b>>8),512&i.flags&&(R[0]=255&b,R[1]=b>>>8&255,i.check=r(i.check,R,2,0)),v=b=0,i.mode=5;case 5:if(1024&i.flags){for(;v<16;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}i.length=b,i.head&&(i.head.extra_len=b),512&i.flags&&(R[0]=255&b,R[1]=b>>>8&255,i.check=r(i.check,R,2,0)),v=b=0}else i.head&&(i.head.extra=null);i.mode=6;case 6:if(1024&i.flags&&(y<(P=i.length)&&(P=y),P&&(i.head&&(O=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Array(i.head.extra_len)),n.arraySet(i.head.extra,p,g,P,O)),512&i.flags&&(i.check=r(i.check,p,P,g)),y-=P,g+=P,i.length-=P),i.length))break t;i.length=0,i.mode=7;case 7:if(2048&i.flags){if(0===y)break t;for(P=0;O=p[g+P++],i.head&&O&&i.length<65536&&(i.head.name+=String.fromCharCode(O)),O&&P<y;);if(512&i.flags&&(i.check=r(i.check,p,P,g)),y-=P,g+=P,O)break t}else i.head&&(i.head.name=null);i.length=0,i.mode=8;case 8:if(4096&i.flags){if(0===y)break t;for(P=0;O=p[g+P++],i.head&&O&&i.length<65536&&(i.head.comment+=String.fromCharCode(O)),O&&P<y;);if(512&i.flags&&(i.check=r(i.check,p,P,g)),y-=P,g+=P,O)break t}else i.head&&(i.head.comment=null);i.mode=9;case 9:if(512&i.flags){for(;v<16;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}if(b!==(65535&i.check)){t.msg="header crc mismatch",i.mode=30;break}v=b=0}i.head&&(i.head.hcrc=i.flags>>9&1,i.head.done=!0),t.adler=i.check=0,i.mode=12;break;case 10:for(;v<32;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}t.adler=i.check=m(b),v=b=0,i.mode=11;case 11:if(0===i.havedict)return t.next_out=w,t.avail_out=_,t.next_in=g,t.avail_in=y,i.hold=b,i.bits=v,2;t.adler=i.check=1,i.mode=12;case 12:if(5===e||6===e)break t;case 13:if(i.last){b>>>=7&v,v-=7&v,i.mode=27;break}for(;v<3;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}switch(i.last=1&b,v-=1,3&(b>>>=1)){case 0:i.mode=14;break;case 1:if(S(i),i.mode=20,6!==e)break;b>>>=2,v-=2;break t;case 2:i.mode=17;break;case 3:t.msg="invalid block type",i.mode=30}b>>>=2,v-=2;break;case 14:for(b>>>=7&v,v-=7&v;v<32;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}if((65535&b)!=(b>>>16^65535)){t.msg="invalid stored block lengths",i.mode=30;break}if(i.length=65535&b,v=b=0,i.mode=15,6===e)break t;case 15:i.mode=16;case 16:if(P=i.length){if(y<P&&(P=y),_<P&&(P=_),0===P)break t;n.arraySet(f,p,g,P,w),y-=P,g+=P,_-=P,w+=P,i.length-=P;break}i.mode=12;break;case 17:for(;v<14;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}if(i.nlen=257+(31&b),b>>>=5,v-=5,i.ndist=1+(31&b),b>>>=5,v-=5,i.ncode=4+(15&b),b>>>=4,v-=4,286<i.nlen||30<i.ndist){t.msg="too many length or distance symbols",i.mode=30;break}i.have=0,i.mode=18;case 18:for(;i.have<i.ncode;){for(;v<3;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}i.lens[U[i.have++]]=7&b,b>>>=3,v-=3}for(;i.have<19;)i.lens[U[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,V={bits:i.lenbits},N=a(0,i.lens,0,19,i.lencode,0,i.work,V),i.lenbits=V.bits,N){t.msg="invalid code lengths set",i.mode=30;break}i.have=0,i.mode=19;case 19:for(;i.have<i.nlen+i.ndist;){for(;I=(F=i.lencode[b&(1<<i.lenbits)-1])>>>16&255,z=65535&F,!((M=F>>>24)<=v);){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}if(z<16)b>>>=M,v-=M,i.lens[i.have++]=z;else{if(16===z){for(L=M+2;v<L;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}if(b>>>=M,v-=M,0===i.have){t.msg="invalid bit length repeat",i.mode=30;break}O=i.lens[i.have-1],P=3+(3&b),b>>>=2,v-=2}else if(17===z){for(L=M+3;v<L;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}v-=M,O=0,P=3+(7&(b>>>=M)),b>>>=3,v-=3}else{for(L=M+7;v<L;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}v-=M,O=0,P=11+(127&(b>>>=M)),b>>>=7,v-=7}if(i.have+P>i.nlen+i.ndist){t.msg="invalid bit length repeat",i.mode=30;break}for(;P--;)i.lens[i.have++]=O}}if(30===i.mode)break;if(0===i.lens[256]){t.msg="invalid code -- missing end-of-block",i.mode=30;break}if(i.lenbits=9,V={bits:i.lenbits},N=a(l,i.lens,0,i.nlen,i.lencode,0,i.work,V),i.lenbits=V.bits,N){t.msg="invalid literal/lengths set",i.mode=30;break}if(i.distbits=6,i.distcode=i.distdyn,V={bits:i.distbits},N=a(c,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,V),i.distbits=V.bits,N){t.msg="invalid distances set",i.mode=30;break}if(i.mode=20,6===e)break t;case 20:i.mode=21;case 21:if(6<=y&&258<=_){t.next_out=w,t.avail_out=_,t.next_in=g,t.avail_in=y,i.hold=b,i.bits=v,o(t,C),w=t.next_out,f=t.output,_=t.avail_out,g=t.next_in,p=t.input,y=t.avail_in,b=i.hold,v=i.bits,12===i.mode&&(i.back=-1);break}for(i.back=0;I=(F=i.lencode[b&(1<<i.lenbits)-1])>>>16&255,z=65535&F,!((M=F>>>24)<=v);){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}if(I&&!(240&I)){for(D=M,k=I,B=z;I=(F=i.lencode[B+((b&(1<<D+k)-1)>>D)])>>>16&255,z=65535&F,!(D+(M=F>>>24)<=v);){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}b>>>=D,v-=D,i.back+=D}if(b>>>=M,v-=M,i.back+=M,i.length=z,0===I){i.mode=26;break}if(32&I){i.back=-1,i.mode=12;break}if(64&I){t.msg="invalid literal/length code",i.mode=30;break}i.extra=15&I,i.mode=22;case 22:if(i.extra){for(L=i.extra;v<L;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}i.length+=b&(1<<i.extra)-1,b>>>=i.extra,v-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=23;case 23:for(;I=(F=i.distcode[b&(1<<i.distbits)-1])>>>16&255,z=65535&F,!((M=F>>>24)<=v);){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}if(!(240&I)){for(D=M,k=I,B=z;I=(F=i.distcode[B+((b&(1<<D+k)-1)>>D)])>>>16&255,z=65535&F,!(D+(M=F>>>24)<=v);){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}b>>>=D,v-=D,i.back+=D}if(b>>>=M,v-=M,i.back+=M,64&I){t.msg="invalid distance code",i.mode=30;break}i.offset=z,i.extra=15&I,i.mode=24;case 24:if(i.extra){for(L=i.extra;v<L;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}i.offset+=b&(1<<i.extra)-1,b>>>=i.extra,v-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){t.msg="invalid distance too far back",i.mode=30;break}i.mode=25;case 25:if(0===_)break t;if(P=C-_,i.offset>P){if((P=i.offset-P)>i.whave&&i.sane){t.msg="invalid distance too far back",i.mode=30;break}T=P>i.wnext?(P-=i.wnext,i.wsize-P):i.wnext-P,P>i.length&&(P=i.length),E=i.window}else E=f,T=w-i.offset,P=i.length;for(_<P&&(P=_),_-=P,i.length-=P;f[w++]=E[T++],--P;);0===i.length&&(i.mode=21);break;case 26:if(0===_)break t;f[w++]=i.length,_--,i.mode=21;break;case 27:if(i.wrap){for(;v<32;){if(0===y)break t;y--,b|=p[g++]<<v,v+=8}if(C-=_,t.total_out+=C,i.total+=C,C&&(t.adler=i.check=i.flags?r(i.check,f,C,w-C):s(i.check,f,C,w-C)),C=_,(i.flags?b:m(b))!==i.check){t.msg="incorrect data check",i.mode=30;break}v=b=0}i.mode=28;case 28:if(i.wrap&&i.flags){for(;v<32;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}if(b!==(4294967295&i.total)){t.msg="incorrect length check",i.mode=30;break}v=b=0}i.mode=29;case 29:N=1;break t;case 30:N=-3;break t;case 31:return-4;default:return u}return t.next_out=w,t.avail_out=_,t.next_in=g,t.avail_in=y,i.hold=b,i.bits=v,(i.wsize||C!==t.avail_out&&i.mode<30&&(i.mode<27||4!==e))&&A(t,t.output,t.next_out,C-t.avail_out)?(i.mode=31,-4):(x-=t.avail_in,C-=t.avail_out,t.total_in+=x,t.total_out+=C,i.total+=C,i.wrap&&C&&(t.adler=i.check=i.flags?r(i.check,f,C,t.next_out-C):s(i.check,f,C,t.next_out-C)),t.data_type=i.bits+(i.last?64:0)+(12===i.mode?128:0)+(20===i.mode||15===i.mode?256:0),(0==x&&0===C||4===e)&&N===h&&(N=-5),N)},i.inflateEnd=function(t){if(!t||!t.state)return u;var e=t.state;return e.window&&(e.window=null),t.state=null,h},i.inflateGetHeader=function(t,e){var i;return t&&t.state&&2&(i=t.state).wrap?((i.head=e).done=!1,h):u},i.inflateSetDictionary=function(t,e){var i,n=e.length;return t&&t.state?0!==(i=t.state).wrap&&11!==i.mode?u:11===i.mode&&s(1,e,n,0)!==i.check?-3:A(t,e,n,n)?(i.mode=31,-4):(i.havedict=1,h):u},i.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(t,e,i){var n=t("../utils/common"),s=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],r=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],o=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],a=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];e.exports=function(t,e,i,l,c,h,u,d){var p,f,m,g,w,y,_,b,v,x=d.bits,C=0,S=0,A=0,P=0,T=0,E=0,M=0,I=0,z=0,D=0,k=null,B=0,O=new n.Buf16(16),N=new n.Buf16(16),V=null,L=0;for(C=0;C<=15;C++)O[C]=0;for(S=0;S<l;S++)O[e[i+S]]++;for(T=x,P=15;1<=P&&0===O[P];P--);if(P<T&&(T=P),0===P)return c[h++]=20971520,c[h++]=20971520,d.bits=1,0;for(A=1;A<P&&0===O[A];A++);for(T<A&&(T=A),C=I=1;C<=15;C++)if(I<<=1,(I-=O[C])<0)return-1;if(0<I&&(0===t||1!==P))return-1;for(N[1]=0,C=1;C<15;C++)N[C+1]=N[C]+O[C];for(S=0;S<l;S++)0!==e[i+S]&&(u[N[e[i+S]]++]=S);if(y=0===t?(k=V=u,19):1===t?(k=s,B-=257,V=r,L-=257,256):(k=o,V=a,-1),C=A,w=h,M=S=D=0,m=-1,g=(z=1<<(E=T))-1,1===t&&852<z||2===t&&592<z)return 1;for(;;){for(_=C-M,v=u[S]<y?(b=0,u[S]):u[S]>y?(b=V[L+u[S]],k[B+u[S]]):(b=96,0),p=1<<C-M,A=f=1<<E;c[w+(D>>M)+(f-=p)]=_<<24|b<<16|v,0!==f;);for(p=1<<C-1;D&p;)p>>=1;if(0!==p?(D&=p-1,D+=p):D=0,S++,0==--O[C]){if(C===P)break;C=e[i+u[S]]}if(T<C&&(D&g)!==m){for(0===M&&(M=T),w+=A,I=1<<(E=C-M);E+M<P&&!((I-=O[E+M])<=0);)E++,I<<=1;if(z+=1<<E,1===t&&852<z||2===t&&592<z)return 1;c[m=D&g]=T<<24|E<<16|w-h}}return 0!==D&&(c[w+D]=C-M<<24|64<<16),d.bits=T,0}},{"../utils/common":41}],51:[function(t,e,i){e.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],52:[function(t,e,i){var n=t("../utils/common"),s=0,r=1;function o(t){for(var e=t.length;0<=--e;)t[e]=0}var a=0,l=29,c=256,h=c+1+l,u=30,d=19,p=2*h+1,f=15,m=16,g=7,w=256,y=16,_=17,b=18,v=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],x=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],C=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],S=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],A=new Array(2*(h+2));o(A);var P=new Array(2*u);o(P);var T=new Array(512);o(T);var E=new Array(256);o(E);var M=new Array(l);o(M);var I,z,D,k=new Array(u);function B(t,e,i,n,s){this.static_tree=t,this.extra_bits=e,this.extra_base=i,this.elems=n,this.max_length=s,this.has_stree=t&&t.length}function O(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}function N(t){return t<256?T[t]:T[256+(t>>>7)]}function V(t,e){t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255}function L(t,e,i){t.bi_valid>m-i?(t.bi_buf|=e<<t.bi_valid&65535,V(t,t.bi_buf),t.bi_buf=e>>m-t.bi_valid,t.bi_valid+=i-m):(t.bi_buf|=e<<t.bi_valid&65535,t.bi_valid+=i)}function F(t,e,i){L(t,i[2*e],i[2*e+1])}function R(t,e){for(var i=0;i|=1&t,t>>>=1,i<<=1,0<--e;);return i>>>1}function U(t,e,i){var n,s,r=new Array(f+1),o=0;for(n=1;n<=f;n++)r[n]=o=o+i[n-1]<<1;for(s=0;s<=e;s++){var a=t[2*s+1];0!==a&&(t[2*s]=R(r[a]++,a))}}function j(t){var e;for(e=0;e<h;e++)t.dyn_ltree[2*e]=0;for(e=0;e<u;e++)t.dyn_dtree[2*e]=0;for(e=0;e<d;e++)t.bl_tree[2*e]=0;t.dyn_ltree[2*w]=1,t.opt_len=t.static_len=0,t.last_lit=t.matches=0}function $(t){8<t.bi_valid?V(t,t.bi_buf):0<t.bi_valid&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0}function W(t,e,i,n){var s=2*e,r=2*i;return t[s]<t[r]||t[s]===t[r]&&n[e]<=n[i]}function G(t,e,i){for(var n=t.heap[i],s=i<<1;s<=t.heap_len&&(s<t.heap_len&&W(e,t.heap[s+1],t.heap[s],t.depth)&&s++,!W(e,n,t.heap[s],t.depth));)t.heap[i]=t.heap[s],i=s,s<<=1;t.heap[i]=n}function H(t,e,i){var n,s,r,o,a=0;if(0!==t.last_lit)for(;n=t.pending_buf[t.d_buf+2*a]<<8|t.pending_buf[t.d_buf+2*a+1],s=t.pending_buf[t.l_buf+a],a++,0===n?F(t,s,e):(F(t,(r=E[s])+c+1,e),0!==(o=v[r])&&L(t,s-=M[r],o),F(t,r=N(--n),i),0!==(o=x[r])&&L(t,n-=k[r],o)),a<t.last_lit;);F(t,w,e)}function Z(t,e){var i,n,s,r=e.dyn_tree,o=e.stat_desc.static_tree,a=e.stat_desc.has_stree,l=e.stat_desc.elems,c=-1;for(t.heap_len=0,t.heap_max=p,i=0;i<l;i++)0!==r[2*i]?(t.heap[++t.heap_len]=c=i,t.depth[i]=0):r[2*i+1]=0;for(;t.heap_len<2;)r[2*(s=t.heap[++t.heap_len]=c<2?++c:0)]=1,t.depth[s]=0,t.opt_len--,a&&(t.static_len-=o[2*s+1]);for(e.max_code=c,i=t.heap_len>>1;1<=i;i--)G(t,r,i);for(s=l;i=t.heap[1],t.heap[1]=t.heap[t.heap_len--],G(t,r,1),n=t.heap[1],t.heap[--t.heap_max]=i,t.heap[--t.heap_max]=n,r[2*s]=r[2*i]+r[2*n],t.depth[s]=(t.depth[i]>=t.depth[n]?t.depth[i]:t.depth[n])+1,r[2*i+1]=r[2*n+1]=s,t.heap[1]=s++,G(t,r,1),2<=t.heap_len;);t.heap[--t.heap_max]=t.heap[1],function(t,e){var i,n,s,r,o,a,l=e.dyn_tree,c=e.max_code,h=e.stat_desc.static_tree,u=e.stat_desc.has_stree,d=e.stat_desc.extra_bits,m=e.stat_desc.extra_base,g=e.stat_desc.max_length,w=0;for(r=0;r<=f;r++)t.bl_count[r]=0;for(l[2*t.heap[t.heap_max]+1]=0,i=t.heap_max+1;i<p;i++)g<(r=l[2*l[2*(n=t.heap[i])+1]+1]+1)&&(r=g,w++),l[2*n+1]=r,c<n||(t.bl_count[r]++,o=0,m<=n&&(o=d[n-m]),a=l[2*n],t.opt_len+=a*(r+o),u&&(t.static_len+=a*(h[2*n+1]+o)));if(0!==w){do{for(r=g-1;0===t.bl_count[r];)r--;t.bl_count[r]--,t.bl_count[r+1]+=2,t.bl_count[g]--,w-=2}while(0<w);for(r=g;0!==r;r--)for(n=t.bl_count[r];0!==n;)c<(s=t.heap[--i])||(l[2*s+1]!==r&&(t.opt_len+=(r-l[2*s+1])*l[2*s],l[2*s+1]=r),n--)}}(t,e),U(r,c,t.bl_count)}function q(t,e,i){var n,s,r=-1,o=e[1],a=0,l=7,c=4;for(0===o&&(l=138,c=3),e[2*(i+1)+1]=65535,n=0;n<=i;n++)s=o,o=e[2*(n+1)+1],++a<l&&s===o||(a<c?t.bl_tree[2*s]+=a:0!==s?(s!==r&&t.bl_tree[2*s]++,t.bl_tree[2*y]++):a<=10?t.bl_tree[2*_]++:t.bl_tree[2*b]++,r=s,c=(a=0)===o?(l=138,3):s===o?(l=6,3):(l=7,4))}function Y(t,e,i){var n,s,r=-1,o=e[1],a=0,l=7,c=4;for(0===o&&(l=138,c=3),n=0;n<=i;n++)if(s=o,o=e[2*(n+1)+1],!(++a<l&&s===o)){if(a<c)for(;F(t,s,t.bl_tree),0!=--a;);else 0!==s?(s!==r&&(F(t,s,t.bl_tree),a--),F(t,y,t.bl_tree),L(t,a-3,2)):a<=10?(F(t,_,t.bl_tree),L(t,a-3,3)):(F(t,b,t.bl_tree),L(t,a-11,7));r=s,c=(a=0)===o?(l=138,3):s===o?(l=6,3):(l=7,4)}}o(k);var X=!1;function K(t,e,i,s){var r,o,l;L(t,(a<<1)+(s?1:0),3),o=e,l=i,$(r=t),V(r,l),V(r,~l),n.arraySet(r.pending_buf,r.window,o,l,r.pending),r.pending+=l}i._tr_init=function(t){X||(function(){var t,e,i,n,s,r=new Array(f+1);for(n=i=0;n<l-1;n++)for(M[n]=i,t=0;t<1<<v[n];t++)E[i++]=n;for(E[i-1]=n,n=s=0;n<16;n++)for(k[n]=s,t=0;t<1<<x[n];t++)T[s++]=n;for(s>>=7;n<u;n++)for(k[n]=s<<7,t=0;t<1<<x[n]-7;t++)T[256+s++]=n;for(e=0;e<=f;e++)r[e]=0;for(t=0;t<=143;)A[2*t+1]=8,t++,r[8]++;for(;t<=255;)A[2*t+1]=9,t++,r[9]++;for(;t<=279;)A[2*t+1]=7,t++,r[7]++;for(;t<=287;)A[2*t+1]=8,t++,r[8]++;for(U(A,h+1,r),t=0;t<u;t++)P[2*t+1]=5,P[2*t]=R(t,5);I=new B(A,v,c+1,h,f),z=new B(P,x,0,u,f),D=new B(new Array(0),C,0,d,g)}(),X=!0),t.l_desc=new O(t.dyn_ltree,I),t.d_desc=new O(t.dyn_dtree,z),t.bl_desc=new O(t.bl_tree,D),t.bi_buf=0,t.bi_valid=0,j(t)},i._tr_stored_block=K,i._tr_flush_block=function(t,e,i,n){var o,a,l=0;0<t.level?(2===t.strm.data_type&&(t.strm.data_type=function(t){var e,i=4093624447;for(e=0;e<=31;e++,i>>>=1)if(1&i&&0!==t.dyn_ltree[2*e])return s;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return r;for(e=32;e<c;e++)if(0!==t.dyn_ltree[2*e])return r;return s}(t)),Z(t,t.l_desc),Z(t,t.d_desc),l=function(t){var e;for(q(t,t.dyn_ltree,t.l_desc.max_code),q(t,t.dyn_dtree,t.d_desc.max_code),Z(t,t.bl_desc),e=d-1;3<=e&&0===t.bl_tree[2*S[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e}(t),o=t.opt_len+3+7>>>3,(a=t.static_len+3+7>>>3)<=o&&(o=a)):o=a=i+5,i+4<=o&&-1!==e?K(t,e,i,n):4===t.strategy||a===o?(L(t,2+(n?1:0),3),H(t,A,P)):(L(t,4+(n?1:0),3),function(t,e,i,n){var s;for(L(t,e-257,5),L(t,i-1,5),L(t,n-4,4),s=0;s<n;s++)L(t,t.bl_tree[2*S[s]+1],3);Y(t,t.dyn_ltree,e-1),Y(t,t.dyn_dtree,i-1)}(t,t.l_desc.max_code+1,t.d_desc.max_code+1,l+1),H(t,t.dyn_ltree,t.dyn_dtree)),j(t),n&&$(t)},i._tr_tally=function(t,e,i){return t.pending_buf[t.d_buf+2*t.last_lit]=e>>>8&255,t.pending_buf[t.d_buf+2*t.last_lit+1]=255&e,t.pending_buf[t.l_buf+t.last_lit]=255&i,t.last_lit++,0===e?t.dyn_ltree[2*i]++:(t.matches++,e--,t.dyn_ltree[2*(E[i]+c+1)]++,t.dyn_dtree[2*N(e)]++),t.last_lit===t.lit_bufsize-1},i._tr_align=function(t){var e;L(t,2,3),F(t,w,A),16===(e=t).bi_valid?(V(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):8<=e.bi_valid&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}},{"../utils/common":41}],53:[function(t,e,i){e.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(t,e,i){(function(t){!function(t,e){if(!t.setImmediate){var i,n,s,r,o=1,a={},l=!1,c=t.document,h=Object.getPrototypeOf&&Object.getPrototypeOf(t);h=h&&h.setTimeout?h:t,i="[object process]"==={}.toString.call(t.process)?function(t){process.nextTick(function(){d(t)})}:function(){if(t.postMessage&&!t.importScripts){var e=!0,i=t.onmessage;return t.onmessage=function(){e=!1},t.postMessage("","*"),t.onmessage=i,e}}()?(r="setImmediate$"+Math.random()+"$",t.addEventListener?t.addEventListener("message",p,!1):t.attachEvent("onmessage",p),function(e){t.postMessage(r+e,"*")}):t.MessageChannel?((s=new MessageChannel).port1.onmessage=function(t){d(t.data)},function(t){s.port2.postMessage(t)}):c&&"onreadystatechange"in c.createElement("script")?(n=c.documentElement,function(t){var e=c.createElement("script");e.onreadystatechange=function(){d(t),e.onreadystatechange=null,n.removeChild(e),e=null},n.appendChild(e)}):function(t){setTimeout(d,0,t)},h.setImmediate=function(t){"function"!=typeof t&&(t=new Function(""+t));for(var e=new Array(arguments.length-1),n=0;n<e.length;n++)e[n]=arguments[n+1];var s={callback:t,args:e};return a[o]=s,i(o),o++},h.clearImmediate=u}function u(t){delete a[t]}function d(t){if(l)setTimeout(d,0,t);else{var i=a[t];if(i){l=!0;try{!function(t){var i=t.callback,n=t.args;switch(n.length){case 0:i();break;case 1:i(n[0]);break;case 2:i(n[0],n[1]);break;case 3:i(n[0],n[1],n[2]);break;default:i.apply(e,n)}}(i)}finally{u(t),l=!1}}}}function p(e){e.source===t&&"string"==typeof e.data&&0===e.data.indexOf(r)&&d(+e.data.slice(r.length))}}("undefined"==typeof self?void 0===t?this:t:self)}).call(this,void 0!==La?La:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}]},{},[10])(10));class $a{constructor(t,i){e(this,"date",new Date),e(this,"author"),e(this,"guid",_t.create()),e(this,"viewpoint"),e(this,"modifiedAuthor"),e(this,"modifiedDate"),e(this,"topic"),e(this,"_components"),e(this,"_comment",""),this._components=t,this._comment=i;const n=this._components.get(Ya);this.author=n.config.author}set comment(t){var e;const i=this._components.get(Ya);this._comment=t,this.modifiedDate=new Date,this.modifiedAuthor=i.config.author,null==(e=this.topic)||e.comments.set(this.guid,this)}get comment(){return this._comment}toJSON(){var t,e;const i={guid:this.guid,date:this.date.toISOString(),author:this.author,comment:this.comment,topic_guid:null==(t=this.topic)?void 0:t.guid,viewpoint_guid:this.viewpoint,modified_date:null==(e=this.modifiedDate)?void 0:e.toISOString(),modified_author:this.modifiedAuthor};for(const[t,e]of Object.entries(i))void 0===e&&delete i[t];return i}}const Wa=class t{constructor(i){e(this,"guid",_t.create()),e(this,"title",t.default.title),e(this,"creationDate",new Date),e(this,"creationAuthor",""),e(this,"viewpoints",new r),e(this,"relatedTopics",new r),e(this,"comments",new n),e(this,"documentReferences",new r),e(this,"customData",{}),e(this,"description"),e(this,"serverAssignedId"),e(this,"dueDate"),e(this,"modifiedAuthor"),e(this,"modifiedDate"),e(this,"index"),e(this,"_type",t.default.type),e(this,"_status",t.default.status),e(this,"_priority",t.default.priority),e(this,"_stage",t.default.stage),e(this,"_assignedTo",t.default.assignedTo),e(this,"_labels",t.default.labels??new Set),e(this,"_components"),this._components=i;const s=i.get(Ya);this.creationAuthor=s.config.author,this.relatedTopics.guard=t=>t!==this.guid}set type(t){const e=this._components.get(Ya),{strict:i,types:n}=e.config;(!i||n.has(t))&&(this._type=t)}get type(){return this._type}set status(t){const e=this._components.get(Ya),{strict:i,statuses:n}=e.config;(!i||n.has(t))&&(this._status=t)}get status(){return this._status}set priority(t){const e=this._components.get(Ya);if(t){const{strict:i,priorities:n}=e.config;if(!(!i||n.has(t)))return;this._priority=t}else this._priority=t}get priority(){return this._priority}set stage(t){const e=this._components.get(Ya);if(t){const{strict:i,stages:n}=e.config;if(!(!i||n.has(t)))return;this._stage=t}else this._stage=t}get stage(){return this._stage}set assignedTo(t){const e=this._components.get(Ya);if(t){const{strict:i,users:n}=e.config;if(!(!i||n.has(t)))return;this._assignedTo=t}else this._assignedTo=t}get assignedTo(){return this._assignedTo}set labels(t){const e=this._components.get(Ya),{strict:i,labels:n}=e.config;if(i){const e=new Set;for(const s of t){(!i||n.has(s))&&e.add(s)}this._labels=e}else this._labels=t}get labels(){return this._labels}get _managerVersion(){return this._components.get(Ya).config.version}set(t){const e=t,i=this;for(const n in t){if("guid"===n)continue;const t=e[n];n in this&&(i[n]=t)}return this._components.get(Ya).list.set(this.guid,this),this}createComment(t,e){const i=new $a(this._components,t);return i.viewpoint=e,i.topic=this,this.comments.set(i.guid,i),i}createLabelTags(){const t=[...this.labels];if(this._components.get(Ya).config.exportCustomDataAsLabels)for(const e in this.customData){const i=this.customData[e];"string"==typeof i&&t.push(i)}return t}createCommentTags(){return[...this.comments.values()].map(t=>{var e;return{$Guid:t.guid,Date:t.date.toISOString(),Author:t.author,Comment:t.comment,ModifiedAuthor:t.modifiedAuthor,ModifiedDate:null==(e=t.modifiedDate)?void 0:e.toISOString(),Viewpoint:t.viewpoint?{$Guid:t.viewpoint}:void 0}})}createViewpointTags(){const t=this._components.get(nl);return[...this.viewpoints].map(e=>t.list.get(e)).filter(t=>t).map(e=>{const i={$Guid:e.guid,Viewpoint:`${e.title??e.guid}.bcfv`};if(t.snapshots.get(e.snapshot)){const n=t.getSnapshotExtension(e.snapshot);i.Snapshot=`${e.snapshot}.${n}`}return i})}createRelatedTopicTags(){return[...this.relatedTopics].map(t=>({$Guid:t}))}createDocumentReferencesTag(t=this._managerVersion){const e=[];if("3"!==t&&"2.1"!==t)return e;const i=this._components.get(Ya);for(const n of this.documentReferences){const s=i.documents.get(n);if(!s)continue;let r={$Guid:_t.create(),Description:s.description};"2.1"===t&&(r={...r,$isExternal:"external"===s.type||void 0,ReferencedDocument:"external"===s.type?s.url:`../${s.fileName}`}),"3"===t&&(r={...r,DocumentGuid:"internal"===s.type?n:void 0,Url:"external"===s.type?s.url:void 0}),Object.keys(r).length>0&&e.push(r)}return e}toJSON(){var t,e;const i={guid:this.guid,server_assigned_id:this.serverAssignedId,topic_type:this.type,topic_status:this.status,title:this.title,priority:this.priority,index:this.index,labels:[...this.labels],creation_date:this.creationDate.toISOString(),creation_author:this.creationAuthor,modified_date:null==(t=this.modifiedDate)?void 0:t.toISOString(),modified_author:this.modifiedAuthor,assigned_to:this.assignedTo,stage:this.stage,description:this.description,due_date:null==(e=this.dueDate)?void 0:e.toISOString(),comments:[...this.comments].map(([t,e])=>e.toJSON()),relatedTopics:[...this.relatedTopics].map(t=>({related_topic_guid:t}))},n=this._components.get(nl);for(const t of this.viewpoints){const e=n.list.get(t);e&&(i.viewpoints||(i.viewpoints=[]),i.viewpoints.push(e.toJSON()))}const s=this._components.get(Ya);for(const t of this.documentReferences){const e=s.documents.get(t);e&&(i.document_references||(i.document_references=[]),"external"===e.type?i.document_references.push({guid:_t.create(),description:e.description,url:e.url}):i.document_references.push({guid:_t.create(),description:e.description,document_guid:t}))}for(const[t,e]of Object.entries(i))(void 0===e||Array.isArray(e)&&0===e.length)&&delete i[t];return i}serialize(){var t,e;const i=this._managerVersion,n="3"===i,s={Markup:{Topic:{$Guid:this.guid,$TopicType:this.type,$TopicStatus:this.status,$ServerAssignedId:this.serverAssignedId,Title:this.title,Priority:this.priority,Index:"2.1"===i?this.index:void 0,Labels:n?{Label:this.createLabelTags()}:this.createLabelTags(),CreationDate:this.creationDate.toISOString(),CreationAuthor:this.creationAuthor,ModifiedDate:null==(t=this.modifiedDate)?void 0:t.toISOString(),ModifiedAuthor:this.modifiedAuthor,DueDate:null==(e=this.dueDate)?void 0:e.toISOString(),AssignedTo:this.assignedTo,Stage:this.stage,Description:this.description,DocumentReferences:n?{DocumentReference:this.createDocumentReferencesTag(i)}:void 0,DocumentReference:n?void 0:this.createDocumentReferencesTag(i),RelatedTopics:n?{RelatedTopic:this.createRelatedTopicTags()}:void 0,RelatedTopic:n?void 0:this.createRelatedTopicTags(),Comments:n?{Comment:this.createCommentTags()}:void 0,Viewpoints:n?{ViewPoint:this.createViewpointTags()}:void 0}}};return"2.1"===i&&(s.Markup.Viewpoints=this.createViewpointTags(),s.Markup.Comment=this.createCommentTags()),`<?xml version="1.0" encoding="UTF-8"?>\n ${oi.builder.build(s)}`}};e(Wa,"default",{title:"BCF Topic",type:"Issue",status:"Active"});let Ga=Wa;const Ha=(t,e)=>{if(""===e.trim())return;const i=Ya.xmlParser.parse(e).Extensions;if(!i)return;const{Priorities:n,TopicStatuses:s,TopicTypes:r,Users:o}=i;if(n&&n.Priority){const e=Array.isArray(n.Priority)?n.Priority:[n.Priority];for(const i of e)t.config.priorities.add(i)}if(s&&s.TopicStatus){const e=Array.isArray(s.TopicStatus)?s.TopicStatus:[s.TopicStatus];for(const i of e)t.config.statuses.add(i)}if(r&&r.TopicType){const e=Array.isArray(r.TopicType)?r.TopicType:[r.TopicType];for(const i of e)t.config.types.add(i)}if(o&&o.User){const e=Array.isArray(o.User)?o.User:[o.User];for(const i of e)t.config.users.add(i)}};class Za extends di{constructor(){super(...arguments),e(this,"_config",{version:{type:"Select",options:new Set(["2.1","3"]),multiple:!1,value:""},author:{type:"Text",value:""},types:{type:"TextSet",value:new Set},statuses:{type:"TextSet",value:new Set},priorities:{type:"TextSet",value:new Set},labels:{type:"TextSet",value:new Set},stages:{type:"TextSet",value:new Set},users:{type:"TextSet",value:new Set},includeSelectionTag:{type:"Boolean",value:!1},updateExtensionsOnImport:{type:"Boolean",value:!1},strict:{type:"Boolean",value:!1},includeAllExtensionsOnExport:{type:"Boolean",value:!1},fallbackVersionOnImport:{type:"Select",multiple:!1,options:new Set(["2.1","3"]),value:""},ignoreIncompleteTopicsOnImport:{type:"Boolean",value:!1},exportCustomDataAsLabels:{type:"Boolean",value:!1}})}get version(){return this._config.version.value}set version(t){this._config.version.value=t}get author(){return this._config.author.value}set author(t){this._config.author.value=t}get types(){return this._config.types.value}set types(t){this._config.types.value=t}get statuses(){return this._config.statuses.value}set statuses(t){this._config.statuses.value=t}get priorities(){return this._config.priorities.value}set priorities(t){this._config.priorities.value=t}get labels(){return this._config.labels.value}set labels(t){this._config.labels.value=t}get stages(){return this._config.stages.value}set stages(t){this._config.stages.value=t}get users(){return this._config.users.value}set users(t){this._config.users.value=t}get includeSelectionTag(){return this._config.includeSelectionTag.value}set includeSelectionTag(t){this._config.includeSelectionTag.value=t}get updateExtensionsOnImport(){return this._config.updateExtensionsOnImport.value}set updateExtensionsOnImport(t){this._config.updateExtensionsOnImport.value=t}get strict(){return this._config.strict.value}set strict(t){this._config.strict.value=t}get includeAllExtensionsOnExport(){return this._config.includeAllExtensionsOnExport.value}set includeAllExtensionsOnExport(t){this._config.includeAllExtensionsOnExport.value=t}get fallbackVersionOnImport(){return this._config.fallbackVersionOnImport.value}set fallbackVersionOnImport(t){this._config.fallbackVersionOnImport.value=t}get ignoreIncompleteTopicsOnImport(){return this._config.ignoreIncompleteTopicsOnImport.value}set ignoreIncompleteTopicsOnImport(t){this._config.ignoreIncompleteTopicsOnImport.value=t}get exportCustomDataAsLabels(){return this._config.exportCustomDataAsLabels.value}set exportCustomDataAsLabels(t){this._config.exportCustomDataAsLabels.value=t}}const qa=class t extends ht{constructor(){super(...arguments),e(this,"enabled",!1),e(this,"_defaultConfig",{author:"jhon.doe@example.com",version:"2.1",types:new Set(["Clash","Failure","Fault","Inquiry","Issue","Remark","Request"]),statuses:new Set(["Active","In Progress","Done","In Review","Closed"]),priorities:new Set(["On hold","Minor","Normal","Major","Critical"]),labels:new Set,stages:new Set,users:new Set,includeSelectionTag:!1,updateExtensionsOnImport:!0,strict:!1,includeAllExtensionsOnExport:!0,fallbackVersionOnImport:"2.1",ignoreIncompleteTopicsOnImport:!1,exportCustomDataAsLabels:!1}),e(this,"config",new Za(this,this.components,"BCF Topics",t.uuid)),e(this,"list",new n),e(this,"documents",new n),e(this,"onSetup",new at),e(this,"isSetup",!1),e(this,"onBCFImported",new at),e(this,"onDisposed",new at)}setup(t){if(this.isSetup)return;const e={...this._defaultConfig,...t};this.config.version=e.version,this.config.author=e.author,this.config.types=e.types,this.config.statuses=e.statuses,this.config.priorities=e.priorities,this.config.labels=e.labels,this.config.stages=e.stages,this.config.users=e.users,this.config.includeSelectionTag=e.includeSelectionTag,this.config.updateExtensionsOnImport=e.updateExtensionsOnImport,this.config.strict=e.strict,this.config.includeAllExtensionsOnExport=e.includeAllExtensionsOnExport,this.config.fallbackVersionOnImport=e.fallbackVersionOnImport||"",this.config.ignoreIncompleteTopicsOnImport=e.ignoreIncompleteTopicsOnImport,this.isSetup=!0,this.enabled=!0,this.onSetup.trigger()}create(t){const e=new Ga(this.components);return t?(e.guid=t.guid??e.guid,e.set(t)):this.list.set(e.guid,e),e}dispose(){this.list.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}get usedTypes(){const t=[...this.list].map(([t,e])=>e.type);return new Set(t)}get usedStatuses(){const t=[...this.list].map(([t,e])=>e.status);return new Set(t)}get usedPriorities(){const t=[...this.list].map(([t,e])=>e.priority).filter(t=>t);return new Set(t)}get usedStages(){const t=[...this.list].map(([t,e])=>e.stage).filter(t=>t);return new Set(t)}get usedUsers(){const t=[];for(const[e,i]of this.list){t.push(i.creationAuthor),i.assignedTo&&t.push(i.assignedTo),i.modifiedAuthor&&t.push(i.modifiedAuthor);for(const[e,n]of i.comments)t.push(n.author),n.modifiedAuthor&&t.push(n.modifiedAuthor)}return new Set(t)}get usedLabels(){const t=[];for(const[e,i]of this.list)t.push(...i.labels);return new Set(t)}updateExtensions(){for(const[t,e]of this.list){for(const t of e.labels)this.config.labels.add(t);this.config.types.add(e.type),e.priority&&this.config.priorities.add(e.priority),e.stage&&this.config.stages.add(e.stage),this.config.statuses.add(e.status),this.config.users.add(e.creationAuthor),e.assignedTo&&this.config.users.add(e.assignedTo),e.modifiedAuthor&&this.config.users.add(e.modifiedAuthor);for(const[t,i]of e.comments)this.config.users.add(i.author),i.modifiedAuthor&&this.config.users.add(i.modifiedAuthor)}}updateViewpointReferences(){const t=this.components.get(nl);for(const[e,i]of this.list)for(const e of i.viewpoints){t.list.has(e)||i.viewpoints.delete(e)}}async export(t=this.list.values()){const e=new ja,i="3"===this.config.version,n=i?"3.0":this.config.version,s=i?"release_3_0":"release_2_1";e.file("bcf.version",`<?xml version="1.0" encoding="UTF-8"?>\n <Version VersionId="${n}" xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/buildingSMART/BCF-XML/${s}/Schemas/version.xsd"\n xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\n </Version>`);for(const[t,i]of this.documents.entries())"external"!==i.type&&e.file("2.1"===this.config.version?i.fileName:`documents/${t}`,i.data);if("3"===this.config.version){const t=[];for(const[e,i]of this.documents.entries()){const{type:n,description:s}=i;"external"!==n&&t.push(`<Document Guid="${e}">\n <Filename>${i.fileName}</Filename>\n ${s?`<Description>${s}</Description>`:""}\n </Document>`)}t.length>0&&e.file("documents.xml",`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n <DocumentInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="documents.xsd">\n <Documents>\n ${t.join("\n")}\n </Documents>\n </DocumentInfo>`)}e.file("extensions.xml",this.serializeExtensions());const r=this.components.get(nl);for(const i of t){const t=e.folder(i.guid);t.file("markup.bcf",i.serialize());for(const e of i.viewpoints){const i=r.list.get(e);if(!i)continue;const n=i.title??i.guid;t.file(`${n}.bcfv`,await i.serialize());const s=r.snapshots.get(i.snapshot);if(!s)continue;const o=s?i.snapshot:i.guid,a=r.getSnapshotExtension(i.snapshot);t.file(`${o}.${a}`,s,{binary:!0})}}return await e.generateAsync({type:"blob"})}serializeExtensions(){const t=[...this.config.types].map(t=>`<TopicType>${t}</TopicType>`).join("\n"),e=[...this.config.statuses].map(t=>`<TopicStatus>${t}</TopicStatus>`).join("\n"),i=[...this.config.priorities].map(t=>`<Priority>${t}</Priority>`).join("\n"),n=[...this.config.labels].map(t=>`<TopicLabel>${t}</TopicLabel>`).join("\n"),s=[...this.config.stages].map(t=>`<Stage>${t}</Stage>`).join("\n"),r=[...this.config.users].map(t=>`<User>${t}</User>`).join("\n");return`\n <?xml version="1.0" encoding="UTF-8"?>\n <Extensions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="your-schema-location.xsd">\n ${0!==t.length?`<TopicTypes>\n${t}\n</TopicTypes>`:""}\n ${0!==e.length?`<TopicStatuses>\n${e}\n</TopicStatuses>`:""}\n ${0!==i.length?`<Priorities>\n${i}\n</Priorities>`:""}\n ${0!==n.length?`<TopicLabels>\n${n}\n</TopicLabels>`:""}\n ${0!==s.length?`<Stages>\n${s}\n</Stages>`:""}\n ${0!==r.length?`<Users>\n${r}\n</Users>`:""}\n </Extensions>\n `}processMarkupComment(t){const{Guid:e,Date:i,Author:n,Comment:s,Viewpoint:r}=t;if(!(e&&i&&n&&($a||r)))return null;const o=new $a(this.components,s??"");return o.guid=e,o.date=new Date(i),o.author=n,o.viewpoint=null==r?void 0:r.Guid,o.modifiedAuthor=t.ModifiedAuthor,o.modifiedDate=t.ModifiedDate?new Date(t.ModifiedDate):void 0,o}getMarkupComments(t,e){var i;let n;if("2.1"===e&&(n=t.Comment),"3"===e&&(n=null==(i=t.Topic.Comments)?void 0:i.Comment),!n)return[];n=Array.isArray(n)?n:[n];const s=n.map(t=>this.processMarkupComment(t)).filter(t=>t);return Array.isArray(s)?s:[s]}getMarkupLabels(t,e){var i;let n;if("2.1"===e&&(n=t.Topic.Labels),"3"===e&&(n=null==(i=t.Topic.Labels)?void 0:i.Label),!n)return[];return Array.isArray(n)?n:[n]}getMarkupViewpoints(t,e){var i;let n;return"2.1"===e&&(n=t.Viewpoints),"3"===e&&(n=null==(i=t.Topic.Viewpoints)?void 0:i.ViewPoint),n?(n=Array.isArray(n)?n:[n],n):[]}getMarkupRelatedTopics(t,e){var i;let n;if("2.1"===e&&(n=t.Topic.RelatedTopic),"3"===e&&(n=null==(i=t.Topic.RelatedTopics)?void 0:i.RelatedTopic),!n)return[];return(Array.isArray(n)?n:[n]).map(t=>t.Guid)}getMarkupDocumentReferences(t,e){var i;let n;if("2.1"===e&&(n=t.Topic.DocumentReference),"3"===e&&(n=null==(i=t.Topic.DocumentReferences)?void 0:i.DocumentReference),!n)return[];return Array.isArray(n)?n:[n]}async load(e){var i,n,s;const{fallbackVersionOnImport:r,ignoreIncompleteTopicsOnImport:a,updateExtensionsOnImport:l}=this.config,c=new ja;await c.loadAsync(e);const h=Object.values(c.files);let u=r;const d=h.find(t=>t.name.endsWith(".version"));if(d){const e=await d.async("string"),i=String(t.xmlParser.parse(e).Version.VersionId);u="3.0"===i?"3":i}if(!u||"2.1"!==u&&"3"!==u)throw new Error(`BCFTopics: ${u} is not supported.`);const p=h.find(t=>t.name.endsWith("extensions.xml")||t.name.endsWith(".extensions"));if(l&&p){const t=await p.async("string");Ha(this,t)}const f=[],m=this.components.get(nl),g=h.filter(t=>t.name.endsWith(".bcfv"));for(const e of g){const n=await e.async("string"),s=t.xmlParser.parse(n).VisualizationInfo;if(!s){console.warn("Missing VisualizationInfo in Viewpoint");continue}const r={},{Guid:a,ClippingPlanes:l,Components:c,OrthogonalCamera:h,PerspectiveCamera:d}=s;if(a&&(r.guid=a),c){const t={selection:[],coloring:[],visibility:{default_visibility:!1,exceptions:[],view_setup_hints:{spaces_visible:!1,space_boundaries_visible:!1,openings_visible:!1}}};r.components=t;const{Selection:e,Visibility:n}=c;if(e&&e.Component){const i=Array.isArray(e.Component)?e.Component:[e.Component];t.selection=i.map(t=>t.IfcGuid?{ifc_guid:t.IfcGuid}:null).filter(t=>null!==t)}if(n&&"DefaultVisibility"in n&&(t.visibility.default_visibility=n.DefaultVisibility),n&&n.Exceptions&&"Component"in n.Exceptions){const{Component:e}=n.Exceptions,i=Array.isArray(e)?e:[e];t.visibility.exceptions=i.map(t=>t.IfcGuid?{ifc_guid:t.IfcGuid}:null).filter(t=>null!==t)}let s;"2.1"===u&&(s=c.ViewSetupHints),"3"===u&&(s=null==(i=c.Visibility)?void 0:i.ViewSetupHints),s&&("OpeningsVisible"in s&&(t.visibility.view_setup_hints.openings_visible=s.OpeningsVisible),"SpacesVisible"in s&&(t.visibility.view_setup_hints.spaces_visible=s.SpacesVisible),"SpaceBoundariesVisible"in s&&(t.visibility.view_setup_hints.space_boundaries_visible=s.SpaceBoundariesVisible));const{Coloring:o}=c;if(o&&o.Color){const e=Array.isArray(o.Color)?o.Color:[o.Color];for(const i of e){const{Color:e,Component:n}=i;if(6!==e.length&&8!==e.length)continue;const s=6===e.length?e:e.slice(2),r=(Array.isArray(n)?n:[n]).map(t=>t.IfcGuid?{ifc_guid:t.IfcGuid}:null).filter(t=>null!==t);t.coloring.push({color:s,components:r})}}}if(h||d){const t=s.PerspectiveCamera??s.OrthogonalCamera,{CameraViewPoint:e,CameraDirection:i}=t,n=new o.Vector3(Number(e.X),Number(e.Z),Number(-e.Y)),a=new o.Vector3(Number(i.X),Number(i.Z),Number(-i.Y)),l={camera_view_point:{x:n.x,y:n.y,z:n.z},camera_direction:{x:a.x,y:a.y,z:a.z},aspect_ratio:"AspectRatio"in t?t.AspectRatio:1,camera_up_vector:{x:0,y:0,z:0}};"ViewToWorldScale"in t&&(r.orthogonal_camera={...l,view_to_world_scale:t.ViewToWorldScale}),"FieldOfView"in t&&(r.perspective_camera={...l,field_of_view:t.FieldOfView})}if(l){const t=(Array.isArray(l.ClippingPlane)?l.ClippingPlane:[l.ClippingPlane]).map(({Location:t,Direction:e})=>({location:{x:t.x,y:t.y,z:t.z},direction:{x:e.x,y:e.y,z:e.z}}));r.clipping_planes=t}const p=new tl(this.components,r);f.push(p)}const w={},y=[],_=h.filter(t=>t.name.endsWith(".bcf"));for(const e of _){const i=await e.async("string"),r=t.xmlParser.parse(i).Markup,o=r.Topic,{Guid:l,TopicType:c,TopicStatus:d,Title:p,CreationDate:f,CreationAuthor:g}=o;if(a&&!(l&&c&&d&&p&&f&&g))continue;const _=new Ga(this.components);_.guid=l??_.guid;const b=this.getMarkupRelatedTopics(r,u);w[_.guid]=new Set(b),_.type=c??_.type,_.status=d??_.status,_.title=p??_.title,_.creationDate=f?new Date(f):_.creationDate,_.creationAuthor=g??_.creationAuthor,_.serverAssignedId=o.ServerAssignedId,_.priority=o.Priority,_.index=o.Index,_.modifiedDate=o.ModifiedDate?new Date(o.ModifiedDate):void 0,_.modifiedAuthor=o.ModifiedAuthor,_.dueDate=o.DueDate?new Date(o.DueDate):void 0,_.assignedTo=o.AssignedTo,_.description=o.Description,_.stage=o.Stage;const v=this.getMarkupLabels(r,u);for(const t of v)_.labels.add(t);const x=this.getMarkupComments(r,u);for(const t of x)_.comments.set(t.guid,t);const C=this.getMarkupViewpoints(r,u);for(const t of C){if(!t||!t.Guid)continue;const e=m.list.get(t.Guid);if(!e)continue;_.viewpoints.add(e.guid);const i=`${_.guid}/${t.Snapshot}`,n=h.find(({name:t})=>t===i);if(n){const t=await n.async("arraybuffer"),i=new Uint8Array(t);m.snapshots.set(e.guid,i),e.snapshot=e.guid??null}}const S=this.getMarkupDocumentReferences(r,u),A=h.find(t=>"documents.xml"===t.name);let P=[];const T=await(null==A?void 0:A.async("string"));if(T){const t=null==(s=null==(n=oi.parser.parse(T).DocumentInfo)?void 0:n.Documents)?void 0:s.Document;P=Array.isArray(t)?t:[t]}for(const t of S){const{Description:e,DocumentGuid:i,Url:n,isExternal:s,ReferencedDocument:r}=t;if(i&&P.length>0){const t=P.find(({Guid:t})=>t===i),e=h.find(t=>t.name.endsWith(i)),n=await(null==e?void 0:e.async("uint8array"));if(!t||!n)continue;const{Description:s,Filename:r}=t;this.documents.set(i,{type:"internal",fileName:r,description:s,data:n}),_.documentReferences.add(i)}if(n){const t=this.documents.add({type:"external",url:n,description:e});_.documentReferences.add(t)}if(r){let t=null;if(s)t=this.documents.add({type:"external",url:r,description:e});else{const i=r.split("/"),n=i[i.length-1],s=h.find(t=>t.name.endsWith(n)),o=await(null==s?void 0:s.async("uint8array"));if(!o)continue;t=this.documents.add({type:"internal",fileName:n,data:o,description:e})}_.documentReferences.add(t)}}this.list.set(_.guid,_),y.push(_)}for(const t in w){const e=this.list.get(t);if(!e)continue;const i=w[t];for(const t of i)e.relatedTopics.add(t)}return this.onBCFImported.trigger(y),{viewpoints:f,topics:y}}};e(qa,"uuid","de977976-e4f6-4e4f-a01a-204727839802"),e(qa,"xmlParser",new Ge({allowBooleanAttributes:!0,attributeNamePrefix:"",ignoreAttributes:!1,ignoreDeclaration:!0,ignorePiTags:!0,numberParseOptions:{leadingZeros:!0,hex:!0},parseAttributeValue:!0,preserveOrder:!1,processEntities:!1,removeNSPrefix:!0,trimValues:!0}));let Ya=qa;class Xa{constructor(t,i,n,s,r,a=5,l=!0){var c;if(e(this,"onDraggingStarted",new at),e(this,"onDraggingEnded",new at),e(this,"onDisposed",new at),e(this,"normal"),e(this,"origin"),e(this,"three",new o.Plane),e(this,"components"),e(this,"world"),e(this,"type","default"),e(this,"_title","Clipping Plane"),e(this,"_helper"),e(this,"_visible",!0),e(this,"_enabled",!0),e(this,"_controlsActive",!1),e(this,"_arrowBoundBox",new o.Mesh),e(this,"_planeMesh"),e(this,"_controls"),e(this,"_hiddenMaterial",new o.MeshBasicMaterial({visible:!1})),e(this,"_sizeMultiplier",5),e(this,"_autoScale",!0),e(this,"_visibilityBeforeDisabled",!0),e(this,"notifyManager",()=>{const t=this.components.get(Ja),e=t.list.getKey(this);e&&t.list.set(e,this)}),e(this,"update",()=>{this._enabled&&(this.three.setFromNormalAndCoplanarPoint(this.normal,this._helper.position),this.updateScale())}),e(this,"updateScale",()=>{var t;if(!this.autoScale)return;const e=null==(t=this.world.camera)?void 0:t.three;if(!e)return;if(!(e instanceof o.PerspectiveCamera))return;const i=new o.Vector3;e.getWorldPosition(i);const n=i.distanceTo(this._helper.position)/7*this._sizeMultiplier;this._planeMesh.scale.set(n,n,n)}),e(this,"changeDrag",t=>{this._visible=!t.value,this.preventCameraMovement(),this.notifyDraggingChanged(t)}),this.components=t,this.world=i,!i.renderer)throw new Error("The given world must have a renderer!");this.normal=s,this.origin=n,this._sizeMultiplier=a;const h=t.get(Ja);i.renderer.setPlane(!0,this.three,h.localClippingPlanes),this._planeMesh=Xa.newPlaneMesh(a,r),this._helper=this.newHelper(),this._controls=this.newTransformControls(),this.three.setFromNormalAndCoplanarPoint(s,n),l&&this.toggleControls(!0),this.updateScale(),(null==(c=i.camera)?void 0:c.controls)&&i.camera.controls.addEventListener("update",this.updateScale)}set title(t){this._title=t,this.notifyManager()}get title(){return this._title}get autoScale(){return this._autoScale}set autoScale(t){this._autoScale=t,t&&this.updateScale()}get enabled(){return this._enabled}set enabled(t){if(this.world.isDisposing)return;if(!this.world.renderer)throw new Error("No renderer found for clipping plane!");this._enabled=t,t?this.visible=this._visibilityBeforeDisabled:(this._visibilityBeforeDisabled=this.visible,this.visible=!1);const e=this.components.get(Ja);this.world.renderer.setPlane(t,this.three,e.localClippingPlanes),this.notifyManager()}get visible(){return this._visible}set visible(t){this._visible=t,this._controls.getHelper().visible=t,this._helper.visible=t,this.toggleControls(t),this.notifyManager()}get meshes(){return[this._planeMesh,this._arrowBoundBox]}get planeMaterial(){return this._planeMesh.material}set planeMaterial(t){this._planeMesh.material=t}get size(){return this._sizeMultiplier}set size(t){this._sizeMultiplier=t,this.autoScale?this.updateScale():this._planeMesh.scale.set(t,t,t)}get helper(){return this._helper}get controls(){return this._controls}setFromNormalAndCoplanarPoint(t,e){this.reset(),this.normal.equals(t)||(this.normal.copy(t),this._helper.lookAt(t)),this.origin.copy(e),this._helper.position.copy(e),this._helper.updateMatrix(),this.update()}dispose(){var t;this._enabled=!1,!this.world.isDisposing&&(null==(t=this.world.camera)?void 0:t.controls)&&this.world.camera.controls.removeEventListener("update",this.updateScale),this.onDraggingStarted.reset(),this.onDraggingEnded.reset(),this._helper.removeFromParent(),this.world.renderer&&this.world.renderer.setPlane(!1,this.three),this._arrowBoundBox.removeFromParent(),this._arrowBoundBox.geometry.dispose(),this._planeMesh.geometry.dispose(),this._controls.getHelper().removeFromParent(),this._controls.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}reset(){const t=new o.Vector3(1,0,0),e=new o.Vector3;this.normal.equals(t)||(this.normal.copy(t),this._helper.lookAt(t)),this.origin.copy(e),this._helper.position.copy(e),this._helper.updateMatrix()}toggleControls(t){if(t){if(this._controlsActive)return;this._controls.addEventListener("change",this.update),this._controls.addEventListener("dragging-changed",this.changeDrag)}else this._controls.removeEventListener("change",this.update),this._controls.removeEventListener("dragging-changed",this.changeDrag);this._controlsActive=t}newTransformControls(){if(!this.world.renderer)throw new Error("No renderer found for clipping plane!");const t=this.world.camera.three,e=this.world.renderer.three.domElement,i=new ot(t,e);return this.initializeControls(i),this.world.scene.three.add(i.getHelper()),i}initializeControls(t){t.attach(this._helper),t.showX=!1,t.showY=!1,t.setSpace("local"),this.createArrowBoundingBox(),t.getHelper().children[0].children[0].add(this._arrowBoundBox)}createArrowBoundingBox(){this._arrowBoundBox.geometry=new o.CylinderGeometry(.18,.18,1.2),this._arrowBoundBox.material=this._hiddenMaterial,this._arrowBoundBox.rotateX(Math.PI/2),this._arrowBoundBox.updateMatrix(),this._arrowBoundBox.geometry.applyMatrix4(this._arrowBoundBox.matrix)}notifyDraggingChanged(t){t.value?this.onDraggingStarted.trigger():this.onDraggingEnded.trigger()}preventCameraMovement(){this.world.camera.enabled=this._visible}newHelper(){const t=new o.Object3D;return t.lookAt(this.normal),t.position.copy(this.origin),this._planeMesh.position.z+=.01,t.add(this._planeMesh),this.world.scene.three.add(t),t}static newPlaneMesh(t,e){const i=new o.PlaneGeometry(1),n=new o.Mesh(i,e);return n.scale.set(t,t,t),n}}class Ka extends di{constructor(){super(...arguments),e(this,"_config",{enabled:{value:!0,type:"Boolean"},visible:{value:!0,type:"Boolean"},color:{value:new o.Color,type:"Color"},opacity:{type:"Number",interpolable:!0,value:1,min:0,max:1},size:{type:"Number",interpolable:!0,value:2,min:0,max:100}})}get enabled(){return this._config.enabled.value}set enabled(t){this._config.enabled.value=t,this._component.enabled=t}get visible(){return this._config.visible.value}set visible(t){this._config.visible.value=t,this._component.visible=t}get color(){return this._config.color.value}set color(t){this._config.color.value=t,this._component.material.color.copy(t)}get opacity(){return this._config.opacity.value}set opacity(t){this._config.opacity.value=t,this._component.material.opacity=t}get size(){return this._config.size.value}set size(t){this._config.size.value=t,this._component.size=t}}const Qa=class t extends ht{constructor(n){super(n),e(this,"onSetup",new at),e(this,"onBeforeDrag",new at),e(this,"onAfterDrag",new at),e(this,"onBeforeCreate",new at),e(this,"onBeforeCancel",new at),e(this,"onAfterCancel",new at),e(this,"onBeforeDelete",new at),e(this,"onAfterCreate",new at),e(this,"onAfterDelete",new at),e(this,"onDisposed",new at),e(this,"isSetup",!1),e(this,"orthogonalY",!1),e(this,"toleranceOrthogonalY",.7),e(this,"autoScalePlanes",!0),e(this,"_localClippingPlanes",!1),e(this,"Type",Xa),e(this,"list",new i.DataMap),e(this,"config",new Ka(this,this.components,"Clipper",t.uuid)),e(this,"_defaultConfig",{color:new o.Color(12255487),opacity:.2,size:2}),e(this,"_material",new o.MeshBasicMaterial({color:12255487,side:o.DoubleSide,transparent:!0,opacity:.2})),e(this,"_size",5),e(this,"_enabled",!1),e(this,"_visible",!0),e(this,"onStateChanged",new at),this.components.add(t.uuid,this),this.setEvents()}get localClippingPlanes(){return this._localClippingPlanes}set localClippingPlanes(t){this._localClippingPlanes=t;const e=this.components.get(Pa);for(const[,i]of e.list)i.renderer&&(i.renderer.localClippingPlanes=t)}get enabled(){return this._enabled}set enabled(t){this._enabled=t,this.onStateChanged.trigger(["enabled"])}get visible(){return this._visible}set visible(t){this._visible=t;for(const[e,i]of this.list)i.visible=t;this.onStateChanged.trigger(["visibility"])}get material(){return this._material}set material(t){this._material=t;for(const[e,i]of this.list)i.planeMaterial=t;this.onStateChanged.trigger(["material"])}get size(){return this._size}set size(t){this._size=t;for(const[e,i]of this.list)i.size=t;this.onStateChanged.trigger(["size"])}setEvents(){this.list.onBeforeDelete.add(({value:t})=>{if(!t.world.renderer)throw new Error("Renderer not found for this plane's world!");t.world.renderer.setPlane(!1,t.three),t.dispose(),this.updateMaterialsAndPlanes(),this.onAfterDelete.trigger(t)});const t=this.components.get(gr);if(t.initialized)this.subscribeToFragmentMaterials();else{const e=()=>{t.onFragmentsLoaded.remove(e),this.subscribeToFragmentMaterials()};t.onFragmentsLoaded.add(e)}}subscribeToFragmentMaterials(){const t=this.components.get(gr);for(const[,e]of t.core.models.materials.list)this.applyClippingToFragmentMaterial(e);t.core.models.materials.list.onItemSet.add(({value:t})=>{this.applyClippingToFragmentMaterial(t)})}applyClippingToFragmentMaterial(t){if(!this.localClippingPlanes)return;const e=this.components.get(Pa);for(const[,i]of e.list)if(i.renderer)return void(t.clippingPlanes=i.renderer.clippingPlanes)}dispose(){this._enabled=!1;this.components.get(fi).list.delete(this.config.uuid),this.list.clear(),this._material.dispose(),this.onBeforeCreate.reset(),this.onBeforeCancel.reset(),this.onBeforeDelete.reset(),this.onBeforeDrag.reset(),this.onAfterCreate.reset(),this.onAfterCancel.reset(),this.onAfterDelete.reset(),this.onAfterDrag.reset(),this.onDisposed.trigger(t.uuid),this.onDisposed.reset()}async create(t){const e=this.components.get(ma).get(t),i=await e.castRay();return i?this.createPlaneFromIntersection(t,i):null}createFromNormalAndCoplanarPoint(t,e,i){const n=this.newPlane(t,i,e);return this.updateMaterialsAndPlanes(),n}async delete(t,e){if(!e){const i=await this.pickPlane(t);if(!i)return;e=this.list.getKey(i)}e&&this.list.delete(e)}deleteAll(t){for(const[e,i]of this.list)t&&!t.has(i.type)||this.list.delete(e)}setup(t){const e={...this._defaultConfig,...t};this.config.color=e.color,this.config.opacity=e.opacity,this.config.size=e.size,this.isSetup=!0,this.onSetup.trigger()}pickPlane(t){const e=this.components.get(ma).get(t),i=this.getAllPlaneMeshes(),n=e.castRayToObjects(i);if(n){const t=n.object;return[...this.list.values()].find(e=>e.meshes.includes(t))}}getAllPlaneMeshes(){const t=[];for(const[e,i]of this.list)t.push(...i.meshes);return t}createPlaneFromIntersection(t,e){var i;if(!t.renderer)throw new Error("The given world must have a renderer!");const n=e.point.distanceTo(new o.Vector3(0,0,0)),s=e.normal||(null==(i=e.face)?void 0:i.normal);if(!n||!s)return null;const r=this.getWorldNormal(e,s),a=this.newPlane(t,e.point,r.negate()),l=this.list.get(a);return l.visible=this._visible,l.size=this._size,t.renderer.setPlane(!0,l.three,this.localClippingPlanes),this.updateMaterialsAndPlanes(),l}getWorldNormal(t,e){const i=t.object;let n=t.object.matrixWorld.clone();if(i instanceof o.InstancedMesh&&void 0!==t.instanceId){const e=new o.Matrix4;i.getMatrixAt(t.instanceId,e),n=e.multiply(n)}const s=(new o.Matrix3).getNormalMatrix(n),r=e.clone().applyMatrix3(s).normalize();return this.normalizePlaneDirectionY(r),r}normalizePlaneDirectionY(t){this.orthogonalY&&(t.y>this.toleranceOrthogonalY&&(t.x=0,t.y=1,t.z=0),t.y<-this.toleranceOrthogonalY&&(t.x=0,t.y=-1,t.z=0))}newPlane(t,e,i){const n=new this.Type(this.components,t,e,i,this._material);n.autoScale=this.autoScalePlanes,n.onDraggingStarted.add(()=>this.onBeforeDrag.trigger(n)),n.onDraggingEnded.add(()=>this.onAfterDrag.trigger(n));const s=_t.create();return this.list.set(s,n),this.onAfterCreate.trigger(n),s}updateMaterialsAndPlanes(){const t=this.components.get(Pa);for(const[e,i]of t.list){if(!i.renderer)continue;i.renderer.updateClippingPlanes();const{clippingPlanes:t}=i.renderer;for(const e of i.meshes)if(e.material)if(Array.isArray(e.material))for(const i of e.material)i.clippingPlanes=t;else e.material.clippingPlanes=t}}};e(Qa,"uuid","66290bc5-18c4-4cd1-9379-2e17a0617611");let Ja=Qa;class tl{constructor(t,n){e(this,"title"),e(this,"guid",_t.create()),e(this,"clippingPlanes",new i.DataSet),e(this,"camera",{aspect_ratio:1,field_of_view:60,camera_direction:{x:0,y:0,z:0},camera_view_point:{x:0,y:0,z:0},camera_up_vector:{x:0,y:1,z:0}}),e(this,"customData",{}),e(this,"exceptionComponents",new i.DataSet),e(this,"selectionComponents",new i.DataSet),e(this,"componentColors",new i.DataMap),e(this,"spacesVisible",!1),e(this,"spaceBoundariesVisible",!1),e(this,"openingsVisible",!1),e(this,"defaultVisibility",!0),e(this,"snapshot",this.guid),e(this,"_components"),e(this,"_world",null),e(this,"notifyUpdate",()=>{this._components.get(nl).list.set(this.guid,this)}),this._components=t,n&&(this.guid=n.guid??this.guid,this.set(n)),this.setEvents()}async getSelectionMap(){const t=this._components.get(gr);return await t.guidsToModelIdMap([...this.selectionComponents])}async getExceptionMap(){const t=this._components.get(gr);return await t.guidsToModelIdMap([...this.exceptionComponents])}get projection(){return"field_of_view"in this.camera?"Perspective":"Orthographic"}get position(){const t=this._components.get(gr),{camera_view_point:e}=this.camera,{x:i,y:n,z:s}=e,r=new o.Vector3(i,n,s);return t.applyBaseCoordinateSystem(r,new o.Matrix4),r}set position(t){const e=t.clone(),i=this._components.get(gr);t.clone().applyMatrix4(i.baseCoordinationMatrix.clone().invert()),this.camera.camera_view_point={x:e.x,y:e.y,z:e.z}}get direction(){const{camera_direction:t}=this.camera,{x:e,y:i,z:n}=t;return new o.Vector3(e,i,n)}set world(t){this._world=t}get world(){return this._world}get _managerVersion(){return this._components.get(Ya).config.version}get topics(){return[...this._components.get(Ya).list.values()].filter(t=>t.viewpoints.has(this.guid))}setEvents(){this.selectionComponents.onUpdated.add(this.notifyUpdate),this.exceptionComponents.onUpdated.add(this.notifyUpdate),this.clippingPlanes.onUpdated.add(this.notifyUpdate),this.componentColors.onItemSet.add(this.notifyUpdate),this.componentColors.onItemDeleted.add(this.notifyUpdate),this.componentColors.onItemUpdated.add(this.notifyUpdate),this.componentColors.onCleared.add(this.notifyUpdate)}set(t){this.title=t.title;const{components:e,perspective_camera:i,orthogonal_camera:n,clipping_planes:s}=t;if(e){const{selection:t,visibility:i,coloring:n}=e;if(t){this.selectionComponents.clear();for(const{ifc_guid:e}of t)e&&this.selectionComponents.add(e)}if(i){const{default_visibility:t,exceptions:e,view_setup_hints:n}=i;if(void 0!==t&&(this.defaultVisibility=t),e){this.exceptionComponents.clear();for(const{ifc_guid:t}of e)t&&this.exceptionComponents.add(t)}if(n){const{spaces_visible:t,space_boundaries_visible:e,openings_visible:i}=n;void 0!==t&&(this.spacesVisible=t),void 0!==e&&(this.spaceBoundariesVisible=e),void 0!==i&&(this.openingsVisible=i)}}if(n){this.componentColors.clear();for(const t of n){const{color:e,components:i}=t,n=i.map(t=>t.ifc_guid).filter(t=>null!==t);this.componentColors.set(e,n)}}}if((i||n)&&(this.camera=i??n),s&&this.world){const t=this._components.get(Ja);for(const e of s){const{location:i,direction:n}=e,s=new o.Vector3(i.x,i.z,-i.y),r=new o.Vector3(n.x,n.z,-n.y),a=t.createFromNormalAndCoplanarPoint(this.world,r,s);this.clippingPlanes.add(a),t.list.get(a).enabled=!1,t.list.get(a).visible=!1}}this.notifyUpdate()}async go(t){if(!this.world)return;const{camera:e}=this.world;if(!(e instanceof Va))throw new Error("Viewpoint: the world's camera component must be of type OrthoPerspectiveCamera to switch between perspective and orthographic projections.");const{transition:i,applyClippings:n,applyVisibility:s,clippingsVisibility:r}={transition:!0,applyClippings:!0,applyVisibility:!0,clippingsVisibility:!0,...t};e.projection.set(this.projection);const a=new o.Vector3(this.camera.camera_view_point.x,this.camera.camera_view_point.y,this.camera.camera_view_point.z),l=new o.Vector3(this.camera.camera_direction.x,this.camera.camera_direction.y,this.camera.camera_direction.z);if(a.equals(new o.Vector3)&&l.equals(new o.Vector3))return;const c=this.position,h=this.direction,u={x:c.x+80*h.x,y:c.y+80*h.y,z:c.z+80*h.z},d=[];n&&this.setClippingState(!0),s&&d.push(this.applyVisibility()),this.setClippingVisibility(r),d.push(e.controls.setLookAt(c.x,c.y,c.z,u.x,u.y,u.z,i)),await Promise.all(d)}async updateCamera(t=!0){return new Promise(e=>{if(!this.world)return void e(!1);const{camera:i,renderer:n}=this.world;if(!n)throw new Error("Viewpoint: the world needs to have a renderer!");if(!i.hasCameraControls())throw new Error("Viewpoint: world's camera need camera controls!");const s=i.three,r=s.getWorldPosition(new o.Vector3),a=s.getWorldDirection(new o.Vector3),{width:l,height:c}=n.getSize();let h=l/c;Number.isNaN(h)&&(h=1);const u=this._components.get(gr);r.applyMatrix4(u.baseCoordinationMatrix.clone().invert());const d={aspect_ratio:h,camera_view_point:{x:r.x,y:r.y,z:r.z},camera_direction:{x:a.x,y:a.y,z:a.z},camera_up_vector:{x:0,y:1,z:0}};if(s instanceof o.PerspectiveCamera?this.camera={...d,field_of_view:s.fov}:s instanceof o.OrthographicCamera&&(this.camera={...d,view_to_world_scale:s.top-s.bottom}),t){const t=this._components.get(nl),s=n.three.domElement;n.three.render(this.world.scene.three,i.three),s.toBlob(async i=>{if(i){const e=await i.arrayBuffer(),n=new Uint8Array(e);t.snapshots.set(this.guid,n)}this.notifyUpdate(),e(!0)})}else this.notifyUpdate(),e(!0)})}takeSnapshot(){return new Promise(t=>{if(!this.world)return void t(!1);const{camera:e,renderer:i}=this.world;if(!i)throw new Error("Viewpoint: the world needs to have a renderer!");const n=this._components.get(nl),s=i.three.domElement;i.three.render(this.world.scene.three,e.three),s.toBlob(async e=>{if(e){const t=await e.arrayBuffer(),i=new Uint8Array(t);n.snapshots.set(this.guid,i)}this.notifyUpdate(),t(!0)})})}updateClippingPlanes(){this.clippingPlanes.clear();const t=this._components.get(Ja);for(const[e,i]of t.list)i.enabled&&this.clippingPlanes.add(e)}async applyVisibility(){const t=this._components.get(Lo);t.set(this.defaultVisibility);const e=await this.getExceptionMap();t.set(!this.defaultVisibility,e);const i=await this.getSelectionMap();t.set(!0,i)}async setColorizationState(t){const e=this._components.get(gr),n=[];if(t)for(const[t,s]of this.componentColors){const r=`#${t}`,a=await e.guidsToModelIdMap(s);for(const[t,s]of Object.entries(a)){const a=e.list.get(t);a&&n.push(a.highlight([...s],{customId:r,color:new o.Color(r),renderedFaces:i.RenderedFaces.ONE,opacity:1,transparent:!1}))}}else for(const[t,i]of this.componentColors){const t=await e.guidsToModelIdMap(i);for(const[i,s]of Object.entries(t)){const t=e.list.get(i);t&&n.push(t.resetHighlight([...s]))}}n.push(e.core.update(!0)),await Promise.all(n)}setClippingState(t){const e=this._components.get(Ja);for(const[i,n]of e.list)n.enabled=t&&this.clippingPlanes.has(i)}setClippingVisibility(t){const e=this._components.get(Ja);for(const i of this.clippingPlanes){const n=e.list.get(i);n&&(n.visible=t)}}async createComponentTags(t){var e;const i=this._components.get(gr);let n="";if(this._components.get(Ya).config.includeSelectionTag){const s="selection"===t?await this.getSelectionMap():await this.getExceptionMap();for(const t in s){const r=i.list.get(t);if(!r)continue;const o=s[t];for(const t of o){const i=r.getItem(t),s=await i.getGuid();if(!s)continue;const o=null==(e=await i.getAttributes())?void 0:e.getValue("Tag");let a=null;o&&(a=`AuthoringToolId="${o}"`),n+=`\n<Component IfcGuid="${s}" ${a??""} />`}}}else n=[...this.selectionComponents].map(t=>`<Component IfcGuid="${t}" />`).join("\n");return n}createColorTags(){let t="";for(const[e,i]of this.componentColors.entries()){t+=`<Color Color="${e}">\n${i.map(t=>`\n<Component IfcGuid="${t}" />`).join("\n")}\n</Color>`}return 0!==t.length?`<Coloring>\n${t}\n</Coloring>`:"<Coloring />"}toJSON(){const t=this._components.get(Ja),e={guid:this.guid,components:{selection:[...this.selectionComponents].map(t=>({ifc_guid:t,authoring_tool_id:null})),coloring:[...this.componentColors].map(([t,e])=>({color:t,components:e.map(t=>({ifc_guid:t,authoring_tool_id:null}))})),visibility:{default_visibility:this.defaultVisibility,exceptions:[...this.exceptionComponents].map(t=>({ifc_guid:t,authoring_tool_id:null})),view_setup_hints:{spaces_visible:this.spacesVisible,space_boundaries_visible:this.spaceBoundariesVisible,openings_visible:this.openingsVisible}}},clipping_planes:[...this.clippingPlanes].map(e=>{const i=t.list.get(e);if(!i)return null;const n=i._controls.worldPosition??i.origin,{normal:s}=i;return{location:{x:n.x,y:-n.z,z:n.y},direction:{x:s.x,y:-s.z,z:s.y}}}).filter(t=>null!==t)};"field_of_view"in this.camera?e.perspective_camera=this.camera:e.orthogonal_camera=this.camera;const i=this._components.get(nl),n=i.snapshots.get(this.snapshot);if(n){const t=n.toString(),s=btoa(t),r=i.getSnapshotExtension(this.snapshot);e.snapshot={snapshot_type:r,snapshot_data:s}}return e}async serialize(t=this._managerVersion){const e=this._components.get(gr),i=this.position;i.applyMatrix4(e.baseCoordinationMatrix.clone().invert());const n=this.direction;n.normalize();const s=(new o.Matrix4).makeRotationX(Math.PI/2),r=n.clone().applyMatrix4(s);r.normalize();const a=`<CameraViewPoint>\n <X>${i.x}</X>\n <Y>${-i.z}</Y>\n <Z>${i.y}</Z>\n </CameraViewPoint>`,l=`<CameraDirection>\n <X>${n.x}</X>\n <Y>${-n.z}</Y>\n <Z>${n.y}</Z>\n </CameraDirection>`,c=`<CameraUpVector>\n <X>${r.x}</X>\n <Y>${-r.z}</Y>\n <Z>${r.y}</Z>\n </CameraUpVector>`,h=`<AspectRatio>${this.camera.aspect_ratio}</AspectRatio>`;let u="";"view_to_world_scale"in this.camera?u=`<OrthogonalCamera>\n ${a}\n ${l}\n ${c}\n ${h}\n <ViewToWorldScale>${this.camera.view_to_world_scale}</ViewToWorldScale>\n </OrthogonalCamera>`:"field_of_view"in this.camera&&(u=`<PerspectiveCamera>\n ${a}\n ${l}\n ${c}\n ${h}\n <FieldOfView>${this.camera.field_of_view}</FieldOfView>\n </PerspectiveCamera>`);const d=`<ViewSetupHints SpacesVisible="${this.spacesVisible??!1}" SpaceBoundariesVisible="${this.spaceBoundariesVisible??!1}" OpeningsVisible="${this.openingsVisible??!1}" />`,p=(await this.createComponentTags("selection")).trim(),f=(await this.createComponentTags("exception")).trim(),m=this.createColorTags();return`<?xml version="1.0" encoding="UTF-8"?>\n <VisualizationInfo Guid="${this.guid}">\n <Components>\n ${"2.1"===t?d:""}\n ${0!==p.length?`<Selection>${p}</Selection>`:""}\n <Visibility DefaultVisibility="${this.defaultVisibility}">\n ${"3"===t?d:""}\n ${0!==f.length?`<Exceptions>${f}</Exceptions>`:""}\n </Visibility>\n ${m}\n </Components>\n ${u}\n </VisualizationInfo>`}}class el extends di{constructor(){super(...arguments),e(this,"_config",{overwriteColors:{value:!1,type:"Boolean"}})}get overwriteColors(){return this._config.overwriteColors.value}set overwriteColors(t){this._config.overwriteColors.value=t}}const il=class t extends ht{constructor(i){super(i),e(this,"enabled",!0),e(this,"world",null),e(this,"list",new n),e(this,"snapshots",new n),e(this,"isSetup",!1),e(this,"onSetup",new at),e(this,"config",new el(this,this.components,"Viewpoints",t.uuid)),e(this,"onDisposed",new at),i.add(t.uuid,this)}create(t){const e=new tl(this.components,t);return e.world=this.world,t||this.list.set(e.guid,e),e}getSnapshotExtension(t){let e="jpeg";const i=this.snapshots.get(t);if(!i)return e;const n=i.subarray(0,4);let s="";for(let t=0;t<n.length;t++)s+=n[t].toString(16);return s.startsWith("89504e47")&&(e="png"),s.startsWith("ffd8ffe")&&(e="jpeg"),e}setup(){}dispose(){this.list.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}};e(il,"uuid","ee867824-a796-408d-8aa0-4e5962a83c66");let nl=il;class sl{constructor(t,i){e(this,"_components"),e(this,"_cameraOffset",10),e(this,"_planeHelper"),e(this,"_farPlaneHelper"),e(this,"_cameraHelper"),e(this,"onStateChanged",new at),e(this,"onUpdated",new at),e(this,"onDisposed",new at),e(this,"camera"),e(this,"plane",new o.Plane),e(this,"farPlane",new o.Plane),e(this,"id",_t.create()),e(this,"_open",!1),e(this,"_range",ol.defaultRange),e(this,"_world",null),e(this,"_helpersVisible",!1),e(this,"_planesEnabled",!1),this._components=t,this.camera=new Va(this._components);const{threeOrtho:n}=this.camera;if((null==i?void 0:i.id)&&(this.id=i.id),(null==i?void 0:i.normal)&&(null==i?void 0:i.point)){const{normal:t,point:e}=i;this.plane.setFromNormalAndCoplanarPoint(t,e)}this._cameraHelper=new o.CameraHelper(n),this._planeHelper=new o.PlaneHelper(this.plane,50),this._farPlaneHelper=new o.PlaneHelper(this.farPlane,50),this.farPlaneHelperColor=new o.Color("blue"),this.update()}get _planeNormalOpposite(){return this.plane.normal.clone().negate()}get _planePosition(){return this.plane.normal.clone().multiplyScalar(-this.plane.constant)}get _cameraPosition(){return this._planePosition.addScaledVector(this._planeNormalOpposite,this._cameraOffset)}set open(t){this._open=t,this.onStateChanged.trigger(["open"])}get open(){return this._open}set planeHelperColor(t){!Array.isArray(this._planeHelper.material)&&"color"in this._planeHelper.material&&this._planeHelper.material.color instanceof o.Color&&(this._planeHelper.material.color=t)}set farPlaneHelperColor(t){!Array.isArray(this._farPlaneHelper.material)&&"color"in this._farPlaneHelper.material&&this._farPlaneHelper.material.color instanceof o.Color&&(this._farPlaneHelper.material.color=t)}set range(t){this._range=t,this.update()}get range(){return this._range}set distance(t){this.plane.constant=t,this.update()}get distance(){return this.plane.constant}set world(t){this._world=t,this.camera.currentWorld=t,t&&(this.camera.projection.set("Orthographic"),this.camera.set("Plan"),this.camera.controls.dollySpeed=6,this.camera.controls.restThreshold=.005,this.update())}get world(){return this._world}set helpersVisible(t){if(!t)return this._helpersVisible=t,this._planeHelper.removeFromParent(),this._farPlaneHelper.removeFromParent(),void this._cameraHelper.removeFromParent();this.world&&(this._helpersVisible=t,this.world.scene.three.add(this._planeHelper,this._farPlaneHelper))}get helpersVisible(){return this._helpersVisible}set planesEnabled(t){const{world:e}=this;if(!e)return;const{renderer:i}=e;i&&(i.setPlane(t,this.plane),i.setPlane(t,this.farPlane),this._planesEnabled=t)}get planesEnabled(){return this._planesEnabled}dispose(){this.helpersVisible=!1;const t=this._components.get(mt);t.destroy(this._planeHelper),t.destroy(this._farPlaneHelper),t.destroy(this._cameraHelper),this.camera.dispose(),this.onDisposed.trigger()}update(){if(this.world){const t=this._cameraPosition,e=this._planePosition;this.camera.controls.setLookAt(t.x,t.y,t.z,e.x,e.y,e.z,!1)}this.farPlane.normal.copy(this._planeNormalOpposite),this.farPlane.constant=this.range-this.plane.constant,this.onUpdated.trigger()}flip(){this.plane.normal.negate(),this.update()}}const rl=class t extends ht{constructor(i){super(i),e(this,"list",new n),e(this,"enabled",!0),e(this,"world",null),e(this,"_fragmentsUpdateEvent",()=>{this.components.get(gr).core.update(!0)}),e(this,"restoreCameraOnClose",!0),e(this,"_restoreState",null),i.add(t.uuid,this),this.setupEvents()}get hasOpenViews(){return[...this.list.values()].some(t=>t.open)}setupEvents(){this.list.onBeforeDelete.add(({key:t,value:e})=>{e.open&&this.close(t),e.dispose()})}create(t,e,i){const n=new sl(this.components,{id:null==i?void 0:i.id,normal:t,point:e});return n.world=(null==i?void 0:i.world)??this.world,this.list.set(n.id,n),n}createFromPlane(t,e){const i=new sl(this.components,{id:null==e?void 0:e.id});return i.plane.copy(t),i.update(),i.world=(null==e?void 0:e.world)??this.world,this.list.set(i.id,i),i}async createFromIfcStoreys(t){const e=[],i=this.components.get(gr),n=void 0===(null==t?void 0:t.offset)?.25:t.offset;for(const[s,r]of i.list){if(t&&t.modelIds&&!t.modelIds.some(t=>t.test(s)))continue;const i=Object.values(await r.getItemsOfCategories([/BUILDINGSTOREY/])).flat();if(0===i.length)continue;const a=await r.getItemsData(i),[,l]=await r.getCoordinates(),c=new o.Vector3(0,-1,0);for(const i of a){if(!("value"in i.Name)||!("value"in i.Elevation))continue;const{value:s}=i.Name;if((null==t?void 0:t.storeyNames)&&!t.storeyNames.some(t=>t.test(s)))continue;const r=i.Elevation.value+l+n,a=new o.Plane(c,r),h=this.createFromPlane(a,{id:s,world:null==t?void 0:t.world});e.push(h)}}return e}createElevations(t){const e=[],i=this.components.get(gr),n=void 0!==(null==t?void 0:t.combine)&&t.combine,s=(null==t?void 0:t.namingCallback)??(t=>({front:""+(n?"Front":`${t}: Front`),back:""+(n?"Back":`${t}: Back`),left:""+(n?"Left":`${t}: Left`),right:""+(n?"Right":`${t}: Right`)}));let r=[];for(const[e,n]of i.list)t&&t.modelIds&&!t.modelIds.some(t=>t.test(e))||r.push({id:e,box:n.box});if(0===r.length)return e;if(n){const t=this.components.get(Ro);t.list.clear(),t.list.add(...r.map(t=>t.box));r=[{id:"combined",box:t.get()}]}for(const{id:i,box:n}of r){const{min:r,max:a}=n,l=Math.abs(a.x-r.x),c=Math.abs(a.z-r.z),h=new o.Vector3;n.getCenter(h);const u=new o.Plane(new o.Vector3(0,0,-1),a.z),d=new o.Plane(new o.Vector3(0,0,1),-r.z),p=new o.Plane(new o.Vector3(-1,0,0),a.x),f=new o.Plane(new o.Vector3(1,0,0),-r.x),{front:m,back:g,left:w,right:y}=s(i),_=this.createFromPlane(u,{id:m,world:null==t?void 0:t.world});_.range=c;const b=this.createFromPlane(d,{id:g,world:null==t?void 0:t.world});b.range=c;const v=this.createFromPlane(p,{id:w,world:null==t?void 0:t.world});v.range=l;const x=this.createFromPlane(f,{id:y,world:null==t?void 0:t.world});x.range=l,e.push(_,b,v,x)}return e}open(t){const e=this.list.get(t);if(!e)throw new Error(`Views: the view with id ${t} doesn't exist.`);if(e.open)return;const{world:i}=e;if(!i)throw new Error(`Views: no world found for view with id ${t}.`);const{renderer:n}=i;if(!n)throw new Error(`Views: no renderer found for world with id ${i.uuid}.`);for(const[,t]of this.list)t.world===i&&this.close(t.id);this.restoreCameraOnClose&&i.camera!==e.camera&&!this._restoreState&&i.camera.controls&&(this._restoreState={camera:i.camera,json:i.camera.controls.toJSON()}),n.setPlane(!0,e.plane),n.setPlane(!0,e.farPlane),this.setOnlyEnabledControls(i,e),e.camera.controls.addEventListener("rest",this._fragmentsUpdateEvent),i.camera=e.camera,e.open=!0}close(t){let e;if(e=t?this.list.get(t):[...this.list.values()].find(t=>t.open),t&&!e)throw new Error(`Views: the view with id ${t} doesn't exist.`);if(!e)return;if(!e.open)return;const{world:i}=e;if(!i)throw new Error(`Views: no world found for view with id ${t}.`);const{renderer:n}=i;if(!n)throw new Error(`Views: no renderer found for world with id ${i.uuid}.`);if(n.setPlane(!1,e.plane),n.setPlane(!1,e.farPlane),e.camera.controls.removeEventListener("rest",this._fragmentsUpdateEvent),i.useDefaultCamera(),e.open=!1,this.setOnlyEnabledControls(i,null),this.restoreCameraOnClose&&this._restoreState){const{camera:t,json:e}=this._restoreState;t===i.camera&&t.controls&&t.controls.fromJSON(e,!1),this._restoreState=null}}setOnlyEnabledControls(t,e){const i=e?e.camera:t.defaultCamera,n=(t,e)=>{t.controls&&(t.controls.enabled=e)};n(i,!0),i!==t.defaultCamera&&n(t.defaultCamera,!1);for(const[,e]of this.list)e.world===t&&e.camera!==i&&n(e.camera,!1)}};e(rl,"uuid","fb22f1f5-6598-4664-a11d-de8963ae420f"),e(rl,"defaultRange",15);let ol=rl;async function al(t,e,i,n,s,r,o){const a=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);t.flush(),await function(t,e,i,n){return new Promise((s,r)=>{!function o(){const a=t.clientWaitSync(e,i,0);a!==t.WAIT_FAILED?a!==t.TIMEOUT_EXPIRED?s():setTimeout(o,n):r()}()})}(t,a,0,10),t.deleteSync(a),t.bindBuffer(e,i),t.getBufferSubData(e,n,s,r,o),t.bindBuffer(e,null)}class ll{constructor(t,i){if(e(this,"onDisposed",new at),e(this,"onDistanceComputed",new at),e(this,"excludedObjects",new Set),e(this,"enabled",!0),e(this,"renderDebugFrame",!1),e(this,"components"),e(this,"scene",new o.Scene),e(this,"camera",new o.OrthographicCamera(-1,1,1,-1,0,1)),e(this,"depthMaterial"),e(this,"world"),e(this,"worker"),e(this,"_width",512),e(this,"_height",512),e(this,"_postQuad"),e(this,"tempRT"),e(this,"resultRT"),e(this,"bufferSize"),e(this,"_buffer"),e(this,"_isWorkerBusy",!1),e(this,"compute",async()=>{if(!this.enabled||this.world.isDisposing)return;if(this._isWorkerBusy)return;this._isWorkerBusy=!0,this.world.camera.three.updateMatrix();const t=this.world.renderer.three;t.setRenderTarget(this.tempRT);const e="visibilityBeforeDistanceCheck";for(const t of this.excludedObjects)t.userData[e]=t.visible,t.visible=!1;t.render(this.world.scene.three,this.world.camera.three);for(const t of this.excludedObjects)void 0!==t.userData[e]&&(t.visible=t.userData[e]);this.depthMaterial.uniforms.tDiffuse.value=this.tempRT.texture,this.depthMaterial.uniforms.tDepth.value=this.tempRT.depthTexture,t.setRenderTarget(this.resultRT),t.render(this.scene,this.camera);const i=t.getContext();try{await async function(t,e,i,n,s,r,o,a){const l=t.createBuffer();return t.bindBuffer(t.PIXEL_PACK_BUFFER,l),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(e,i,n,s,r,o,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),await al(t,t.PIXEL_PACK_BUFFER,l,0,a),t.deleteBuffer(l),a}(i,0,0,this._width,this._height,i.RGBA,i.UNSIGNED_BYTE,this._buffer)}catch(e){return t.setRenderTarget(null),void(this._isWorkerBusy=!1)}t.setRenderTarget(null),this.renderDebugFrame&&t.render(this.scene,this.camera),this.worker.postMessage({buffer:this._buffer})}),e(this,"handleWorkerMessage",t=>{if(!this.enabled||this.world.isDisposing)return;const e=t.data.colors;let i=Number.MAX_VALUE;for(const t of e)0!==t&&t<i&&(i=t);const n=this.world.camera.three||o.OrthographicCamera,s=-1*(i/255-1)*(n.far-n.near),r=Math.min(s,n.far);this.onDistanceComputed.trigger(r),this._isWorkerBusy=!1}),!i.renderer)throw new Error("The given world must have a renderer!");this.components=t,this.world=i;const n=i.camera.three;this.tempRT=new o.WebGLRenderTarget(this._width,this._height),this.bufferSize=this._width*this._height*4,this._buffer=new Uint8Array(this.bufferSize),this.tempRT.texture.minFilter=o.NearestFilter,this.tempRT.texture.magFilter=o.NearestFilter,this.tempRT.stencilBuffer=!1,this.tempRT.samples=0,this.tempRT.depthTexture=new o.DepthTexture(this._width,this._height),this.tempRT.depthTexture.format=o.DepthFormat,this.tempRT.depthTexture.type=o.UnsignedShortType,this.resultRT=new o.WebGLRenderTarget(this._width,this._height),this.depthMaterial=new o.ShaderMaterial({vertexShader:"\nvarying vec2 vUv;\n\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n ",fragmentShader:"\n#include <packing>\n\nvarying vec2 vUv;\nuniform sampler2D tDiffuse;\nuniform sampler2D tDepth;\nuniform float cameraNear;\nuniform float cameraFar;\n\n\nfloat readDepth( sampler2D depthSampler, vec2 coord ) {\n float fragCoordZ = texture2D( depthSampler, coord ).x;\n float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar );\n return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );\n}\n\nvoid main() {\n //vec3 diffuse = texture2D( tDiffuse, vUv ).rgb;\n float depth = readDepth( tDepth, vUv );\n\n gl_FragColor.rgb = 1.0 - vec3( depth );\n gl_FragColor.a = 1.0;\n}\n ",uniforms:{cameraNear:{value:n.near},cameraFar:{value:n.far},tDiffuse:{value:null},tDepth:{value:null}}});const s=new o.PlaneGeometry(2,2);this._postQuad=new o.Mesh(s,this.depthMaterial),this.scene.add(this._postQuad);const r=new Blob(['\n addEventListener("message", (event) => {\n const { buffer } = event.data;\n const colors = new Set();\n for (let i = 0; i < buffer.length; i += 4) {\n const r = buffer[i];\n colors.add(r);\n }\n postMessage({ colors });\n });\n '],{type:"application/javascript"});this.worker=new Worker(URL.createObjectURL(r)),this.worker.addEventListener("message",this.handleWorkerMessage)}dispose(){this.enabled=!1,this.onDistanceComputed.reset(),this.worker.terminate(),this.tempRT.dispose(),this.resultRT.dispose();const t=[...this.scene.children];this.excludedObjects.clear();for(const e of t)e.removeFromParent();this._postQuad.geometry.dispose(),this._postQuad.removeFromParent(),this._buffer=null,this.onDisposed.reset()}}class cl extends ba{constructor(){super(...arguments),e(this,"_distanceRenderer"),e(this,"autoBias",!0),e(this,"_defaultShadowConfig",{cascade:1,resolution:512}),e(this,"_lightsWithShadow",new Map),e(this,"_isComputingShadows",!1),e(this,"_shadowsEnabled",!0),e(this,"_bias",0),e(this,"recomputeShadows",t=>{if(!this._shadowsEnabled)return;this.autoBias&&(this.bias=-.005);if(t*=1.5,!this.currentWorld)throw new Error("A world needs to be assigned to the scene before computing shadows!");if(!this._lightsWithShadow.size)throw new Error("No shadows found!");const e=this.currentWorld.camera.three;if(!(e instanceof o.PerspectiveCamera||e instanceof o.OrthographicCamera))throw new Error("Invalid camera type!");const i=new o.Vector3;e.getWorldDirection(i);let n=t;const s=new o.Vector3;s.copy(this.config.directionalLight.position),s.normalize();for(const[t,r]of this._lightsWithShadow){const a=this.directionalLights.get(r);if(!a)throw new Error("Light not found.");const l=new o.Vector3;l.copy(i);const c=t===this._lightsWithShadow.size-1,h=c?n/2:2*n/3;l.multiplyScalar(h),l.add(e.position);const u=n-h,d=new o.Vector3;d.copy(s),d.multiplyScalar(u),a.target.position.copy(l),a.position.copy(l),a.position.add(d),a.shadow.camera.right=u,a.shadow.camera.left=-u,a.shadow.camera.top=u,a.shadow.camera.bottom=-u,a.shadow.camera.far=2*u,a.shadow.camera.updateProjectionMatrix(),a.shadow.camera.updateMatrix(),c||(n/=3)}this._isComputingShadows=!1})}get bias(){return this._bias}set bias(t){this._bias=t;for(const[,e]of this._lightsWithShadow){const i=this.directionalLights.get(e);i&&(i.shadow.bias=t)}}get shadowsEnabled(){return this._shadowsEnabled}set shadowsEnabled(t){this._shadowsEnabled=t;for(const[,e]of this.directionalLights)e.castShadow=t}get distanceRenderer(){if(!this._distanceRenderer)throw new Error("You must set up this component before accessing the distance renderer!");return this._distanceRenderer}setup(t){super.setup(t);const e={...this._defaultConfig,...this._defaultShadowConfig,...t};if(e.cascade<=0)throw new Error("Config.shadows.cascade must be a natural number greater than 0!");if(e.cascade>1)throw new Error("Multiple shadows not supported yet!");if(!this.currentWorld)throw new Error("A world needs to be assigned to the scene before setting it up!");for(const[,t]of this.directionalLights)t.target.removeFromParent(),t.removeFromParent(),t.dispose();this.directionalLights.clear(),this._distanceRenderer||(this._distanceRenderer=new ll(this.components,this.currentWorld),this._distanceRenderer.onDistanceComputed.add(this.recomputeShadows)),this._lightsWithShadow.clear();for(let t=0;t<e.cascade;t++){const i=new o.DirectionalLight;i.intensity=this.config.directionalLight.intensity,i.color=this.config.directionalLight.color,i.position.copy(this.config.directionalLight.position),i.shadow.mapSize.width=e.resolution,i.shadow.mapSize.height=e.resolution,this.three.add(i,i.target),this.directionalLights.set(i.uuid,i),this._lightsWithShadow.set(t,i.uuid),i.castShadow=!0,i.shadow.bias=this._bias}}dispose(){super.dispose(),this._distanceRenderer&&this._distanceRenderer.dispose(),this._lightsWithShadow.clear()}async updateShadows(){!this._isComputingShadows&&this._shadowsEnabled&&(this._isComputingShadows=!0,await this.distanceRenderer.compute())}}class hl{constructor(t){e(this,"cardinality","required"),e(this,"instructions"),e(this,"evalRequirement",(t,e,i,n)=>{const s={parameter:i,currentValue:t,requiredValue:e,pass:!1};n&&this.addCheckResult(s,n);let r=!1;if("simple"===e.type&&(r=t===e.parameter),"enumeration"===e.type&&(r=e.parameter.includes(t)),"pattern"===e.type){r=new RegExp(e.parameter).test(String(t))}if("length"===e.type){const{min:i,length:n,max:s}=e.parameter;void 0!==n&&(r=String(t).length===n),void 0!==i&&(r=String(t).length>=i),void 0!==s&&(r=String(t).length<=s)}if("bounds"===e.type&&"number"==typeof t){const{min:i,minInclusive:n,max:s,maxInclusive:o}=e.parameter;let a=!0,l=!0;void 0!==i&&(a=n?t>=i:t>i),void 0!==s&&(l=o?t<=s:t<s),r=a&&l}return"prohibited"===this.cardinality&&(r=!r),"optional"===this.cardinality&&(r=!0),s.pass=r,s.pass}),this._components=t}addCheckResult(t,e){const i=e.findIndex(({parameter:e})=>e===t.parameter);-1!==i?e[i]=t:e.push(t)}getItemChecks(t,e,n,s){if(!("value"in n._localId)||"number"!=typeof n._localId.value)return null;let r=t.get(e);r||(r=new i.DataMap,t.set(e,r));let o=r.get(n._localId.value);if(o&&s&&!o.pass)return null;if(!o){const t=[];o={guid:Array.isArray(n._guid)?void 0:n._guid.value,pass:!1,checks:t},Object.defineProperty(o,"pass",{get:()=>t.every(({pass:t})=>t)}),r.set(n._localId.value,o)}const a=[],l={facetType:this.facetType,cardinality:this.cardinality,checks:a,pass:!1};return Object.defineProperty(l,"pass",{get:()=>a.every(({pass:t})=>t)}),o.checks.push(l),l.checks}}const ul=(t,e)=>{let i="";if(!e)return i;if("simple"===e.type&&(i=`<simpleValue>${e.parameter}</simpleValue>`),"enumeration"===e.type){i=`<xs:restriction base="xs:string">\n ${e.parameter.map(t=>`<xs:enumeration value="${t}" />`).join("\n")}\n </xs:restriction>`}if("pattern"===e.type){i=`<xs:restriction base="xs:string">\n <xs:pattern value="${e.parameter}" />\n </xs:restriction>`}if("bounds"===e.type){const{min:t,minInclusive:n,max:s,maxInclusive:r}=e.parameter;let o="";void 0!==t&&(o=`<xs:min${n?"Inclusive":"Exclusive"} value="${t}">`);let a="";void 0!==s&&(a=`<xs:max${r?"Inclusive":"Exclusive"} value="${s}">`),i=`<xs:restriction base="xs:double">\n ${o}\n ${a}\n </xs:restriction>`}if("length"===e.type){const{length:t,min:n,max:s}=e.parameter;let r="";void 0!==t&&void 0===n&&void 0===s&&(r=`<xs:length value="${t}" />`);let o="";void 0!==n&&void 0===t&&(o=`<xs:minLength value="${n}" />`);let a="";void 0!==s&&void 0===t&&(a=`<xs:maxLength value="${s}" />`),i=`<xs:restriction base="xs:string">\n ${r}\n ${o}\n ${a}\n </xs:restriction>`}return`<${t[0].toLowerCase()+t.slice(1)}>\n ${i}\n </${t[0].toLowerCase()+t.slice(1)}>`};class dl extends hl{constructor(t,i){super(t),e(this,"facetType","Attribute"),e(this,"name"),e(this,"value"),this.name=i}serialize(t){const e=ul("Name",this.name),i=ul("Value",this.value);let n="";return"requirement"===t&&(n+=`cardinality="${this.cardinality}"`,n+=this.instructions?`instructions="${this.instructions}"`:""),`<attribute ${n}>\n ${e}\n ${i}\n</attribute>`}async getEntities(){}async test(t,e,i={skipIfFails:!0}){const n=this._components.get(gr);for(const[s,r]of Object.entries(t)){const t=n.list.get(s);if(!t)continue;const o=await t.getItemsData([...r]);for(const t of o){const n=this.getItemChecks(e,s,t,i.skipIfFails);if(!n)continue;const r=Object.keys(t).filter(e=>{const i=this.evalRequirement(e,this.name,"Name");if(!i)return!1;const n=t[e];return!!Array.isArray(n)||(null===n||null===n.value?"optional"===this.cardinality||"prohibited"===this.cardinality:(!Array.isArray(n.value)||0!==n.value.length)&&(("string"!=typeof n.value||""!==n.value.trim())&&i))}),o=r.length>0;if(n.push({parameter:"Name",currentValue:o?r[0]:null,requiredValue:this.name,pass:"prohibited"===this.cardinality?!o:o}),this.value)if(r[0]){const e=t[r[0]];if(Array.isArray(e))n.push({parameter:"Value",currentValue:null,requiredValue:this.value,pass:"prohibited"===this.cardinality});else{Array.isArray(e.value)?n.push({parameter:"Value",currentValue:null,requiredValue:this.value,pass:"prohibited"===this.cardinality}):this.evalRequirement(e.value,this.value,"Value",n)}}else n.push({parameter:"Value",currentValue:null,requiredValue:this.value,pass:"prohibited"===this.cardinality})}}}}class pl extends hl{constructor(t,i){super(t),e(this,"facetType","Classification"),e(this,"system"),e(this,"value"),e(this,"uri"),this.system=i}serialize(t){const e=ul("System",this.system),i=ul("Value",this.value);let n="";return"requirement"===t&&(n+=`cardinality="${this.cardinality}"`,n+=this.uri?`uri=${this.uri}`:"",n+=this.instructions?`instructions="${this.instructions}"`:""),`<classification ${n}>\n ${e}\n ${i}\n</classification>`}async getEntities(t,e){}async test(t,e){}}class fl extends hl{constructor(t,i){super(t),e(this,"facetType","Entity"),e(this,"name"),e(this,"predefinedType"),this.name=i}serialize(t){const e=ul("Name",this.name),i=ul("Name",this.predefinedType);let n="";return"requirement"===t&&(n+=`cardinality="${this.cardinality}"`,n+=this.instructions?`instructions="${this.instructions}"`:""),`<entity ${n}>\n ${e}\n ${i}\n</entity>`}async getEntities(t,e){const i=this._components.get(gr),n=new Map;for(const[e,s]of i.list){if(!t.find(t=>t.test(e)))continue;const i=await s.getCategories();for(const t of i){if(!await this.evalName(t))continue;let i=n.get(e);i||(i=[],n.set(e,i)),i.push(t)}}const s={};if(await Promise.all(Array.from(n.entries()).map(async([t,e])=>{const n=i.list.get(t);if(!n)return;const r=e.map(t=>new RegExp(`^${t}$`)),o=await n.getItemsOfCategories(r),a=Object.values(o).flat();s[t]=new Set(a)})),this.predefinedType)for(const[t,n]of Object.entries(s)){const s=i.list.get(t);if(!s)continue;const r=await s.getItemsData([...n]);for(const i of r){if(!("value"in i._localId))continue;await this.evalPredefinedType(t,i)&&li.append(e,t,i._localId.value)}}else li.add(e,s)}async test(t,e,i){const n=this._components.get(gr);for(const[s,r]of Object.entries(t)){const t=n.list.get(s);if(!t)continue;const o=await t.getItemsData([...r]);for(const t of o){if(!("value"in t._category))continue;const n=this.getItemChecks(e,s,t,i.skipIfFails);n&&(await this.evalName(t._category.value,n),await this.evalPredefinedType(s,t,n))}}}async evalName(t,e){return this.evalRequirement(t,this.name,"Name",e)}async evalPredefinedType(t,e,i){if(!this.predefinedType)return null;if(!("value"in e.PredefinedType))return null;const n="string"==typeof this.predefinedType.parameter&&"USERDEFINED"===this.predefinedType.parameter;let s=e.PredefinedType.value;if("USERDEFINED"===s&&!n){const t=Object.keys(e).find(t=>/^((?!Predefined).)*Type$/.test(t));if(t){const i=e[t];"value"in i&&(s=i.value)}else s="USERDEFINED"}if(!s){const i=this._components.get(gr).list.get(t);if(i&&"value"in e._localId){const[t]=await i.getItemsData([e._localId.value],{relations:{IsTypedBy:{attributes:!0,relations:!1}}});if(Array.isArray(t.IsTypedBy)){const e=t.IsTypedBy[0];if(e&&"value"in e.PredefinedType&&(s=e.PredefinedType.value,"USERDEFINED"===s&&!n)){const t=Object.keys(e).find(t=>/^((?!Predefined).)*Type$/.test(t));if(t){const i=e[t];"value"in i&&(s=i.value)}else s="USERDEFINED"}}}}return this.evalRequirement(s,this.predefinedType,"PredefinedType",i)}}class ml extends hl{constructor(t,i,n){super(t),e(this,"facetType","Property"),e(this,"propertySet"),e(this,"baseName"),e(this,"value"),e(this,"dataType"),e(this,"uri"),e(this,"_unsupportedTypes",["IFCCOMPLEXPROPERTY","IFCPHYSICALCOMPLEXQUANTITY"]),this.propertySet=i,this.baseName=n}serialize(t){const e=ul("PropertySet",this.propertySet),i=ul("BaseName",this.baseName),n=ul("Value",this.value),s=this.dataType?`dataType=${this.dataType}`:"";let r="";return"requirement"===t&&(r+=`cardinality="${this.cardinality}"`,r+=this.uri?`uri=${this.uri}`:"",r+=this.instructions?`instructions="${this.instructions}"`:""),`<property ${s} ${r}>\n ${e}\n ${i}\n ${n}\n</property>`}async getEntities(t,e){const i=this._components.get(gr);for(const[n,s]of i.list){if(!t.find(t=>t.test(n)))continue;const i=await s.getItemsOfCategories([/PROPERTYSET/,/ELEMENTQUANTITY/]),r=Object.values(i).flat();if(0===r.length)continue;const o=await s.getItemsData(r,{relations:{HasProperties:{attributes:!0,relations:!1},DefinesOcurrence:{attributes:!0,relations:!1}}});for(const t of o){if(!("value"in t._localId&&"value"in t._category&&"value"in t.Name&&Array.isArray(t.DefinesOcurrence)))continue;if(!this.evalRequirement(t.Name.value,this.propertySet,"PropertySet"))continue;let i;if("IFCPROPERTYSET"===t._category.value&&(i="HasProperties"),"IFCELEMENTQUANTITY"===t._category.value&&(i="Quantities"),!i)continue;const s=t[i];if(Array.isArray(s))for(const i of s){const s=Object.keys(i),r=s.find(t=>/Name/.test(t));if(!r||!("value"in i[r]))continue;const o=i[r];if(!("value"in o))continue;if(!this.evalRequirement(o.value,this.baseName,"BaseName"))continue;if(this.value){const t=s.find(t=>/Value/.test(t));if(!t)continue;const e=i[t];if(!("value"in e))continue;if(!this.evalRequirement(e.value,this.value,"Value"))continue}const a=t.DefinesOcurrence.map(t=>"value"in t._localId&&"number"==typeof t._localId.value?t._localId.value:null).filter(t=>null!==t);li.append(e,n,...a)}}}}async test(t,e,i={skipIfFails:!0}){const n=this._components.get(gr);for(const[s,r]of Object.entries(t)){const t=n.list.get(s);if(!t)continue;const o=await t.getItemsData([...r],{relations:{IsDefinedBy:{attributes:!0,relations:!0},IsTypedBy:{attributes:!0,relations:!1},HasPropertySets:{attributes:!0,relations:!0},DefinesOcurrence:{attributes:!1,relations:!1}}});for(const t of o){const n=this.getItemChecks(e,s,t,i.skipIfFails);if(!n)continue;const r=(await this.getPsets(t)).filter(t=>{if(!("value"in t.Name))return!1;return!!this.evalRequirement(t.Name.value,this.propertySet,"PropertySet")&&(n.push({currentValue:t.Name.value,parameter:"PropertySet",pass:!0,requiredValue:this.propertySet}),!0)});if(0!==r.length)for(const t of r){const e=this.getPropertyListName(t);if(!e)continue;const i=t[e];if(!Array.isArray(i)){n.push({currentValue:null,parameter:"BaseName",pass:!1,requiredValue:this.baseName});continue}const s=i.filter(t=>{if(!("value"in t._category)||!("value"in t.Name))return!1;if(this._unsupportedTypes.includes(t._category.value))return!1;return!!this.evalRequirement(t.Name.value,this.baseName,"BaseName")&&(n.push({currentValue:t.Name.value,parameter:"BaseName",pass:!0,requiredValue:this.baseName}),!0)});if(0!==s.length)for(const t of s)this.evalValue(t,n),this.evalDataType(t,n),this.evalURI();else n.push({currentValue:null,parameter:"BaseName",pass:!1,requiredValue:this.baseName})}else n.push({currentValue:null,parameter:"PropertySet",pass:!1,requiredValue:this.propertySet})}}}getPropertyListName(t){let e;return"value"in t._category?("IFCPROPERTYSET"===t._category.value&&(e="HasProperties"),"IFCELEMENTQUANTITY"===t._category.value&&(e="Quantities"),e):e}getValueKey(t){return Object.keys(t).find(t=>/Value/.test(t)||/Values/.test(t))}getTypePsets(t){const e=[...Array.isArray(t.IsTypedBy)?t.IsTypedBy:[],...Array.isArray(t.IsDefinedBy)?t.IsDefinedBy:[]],i=[];for(const t of e)Array.isArray(null==t?void 0:t.HasPropertySets)&&i.push(...t.HasPropertySets);return i}async getPsets(t){const e=this.getTypePsets(t);if(!Array.isArray(t.IsDefinedBy))return e;const i=[],n=new Set;for(const s of t.IsDefinedBy){if(!("value"in s.Name))continue;const t=s.Name.value,r=this.getPropertyListName(s);if(!t||!r)continue;const o=e.find(e=>"value"in e.Name&&e.Name.value===t);if(o&&(n.add(o),Array.isArray(o.HasProperties)&&Array.isArray(s.HasProperties)))for(const t of o.HasProperties){if(!("value"in t.Name))continue;const e=t.Name.value;s.HasProperties.find(t=>"value"in t.Name&&t.Name.value===e)||s.HasProperties.push(t)}i.push(s)}for(const t of e)n.has(t)||i.push(t);return i}evalValue(t,e){const i=this.getValueKey(t),n=t[i];if(!("value"in n))return!1;if(this.value){if(!i)return null==e||e.push({parameter:"Value",currentValue:null,pass:!1,requiredValue:this.value}),!1;const t=structuredClone(this.value);"string"==typeof n.value&&"simple"===t.type&&(t.parameter=String(t.parameter));return this.evalRequirement(n.value,t,"Value",e)}return!i||("string"!=typeof n.value||""!==n.value.trim()||(null==e||e.push({parameter:"Value",currentValue:"",pass:!1,requiredValue:this.value}),!1))}evalDataType(t,e){if(!this.dataType)return!0;const i=this.getValueKey(t);if(!i||!("value"in t[i]))return null==e||e.push({parameter:"DataType",currentValue:null,pass:!1,requiredValue:this.dataType}),!1;const n=t[i];return this.evalRequirement(n.type??null,{type:"simple",parameter:this.dataType},"DataType",e)}evalURI(){return!0}}class gl extends hl{constructor(){super(...arguments),e(this,"_ifcMaterialEntities",[/^IFCMATERIALLAYERSETUSAGE$/,/^IFCMATERIALLAYERSET$/,/^IFCMATERIALPROFILESETUSAGE$/,/^IFCMATERIALPROFILESET$/,/^IFCMATERIALCONSTITUENTSET$/,/^IFCMATERIAL$/,/^IFCMATERIALLIST$/]),e(this,"_materialParentAttributes",["ForLayerSet","MaterialLayers","ForProfileSet","MaterialProfiles","Material","MaterialConstituents","Materials"]),e(this,"_materialRelations",{MaterialConstituents:{attributes:!0,relations:!0},ForLayerSet:{attributes:!0,relations:!0},MaterialLayers:{attributes:!0,relations:!0},ForProfileSet:{attributes:!0,relations:!0},MaterialProfiles:{attributes:!0,relations:!0},Materials:{attributes:!0,relations:!1}}),e(this,"facetType","Material"),e(this,"value"),e(this,"uri")}serialize(t){if(!this.value||!this.uri)return"<material />";const e=ul("Value",this.value);let i="";return"requirement"===t&&(i+=`cardinality="${this.cardinality}"`,i+=this.uri?`uri=${this.uri}`:"",i+=this.instructions?`instructions="${this.instructions}"`:""),`<material ${i}>\n ${e}\n</material>`}async getEntities(t,e){const i=this._components.get(gr);for(const[n,s]of i.list){if(!t.find(t=>t.test(n)))continue;const i=await s.getItemsOfCategories(this._ifcMaterialEntities),r=Object.values(i).flat();if(0===r.length)continue;const o=await s.getItemsData(r,{relations:{AssociatedTo:{attributes:!0,relations:!1},...this._materialRelations}});for(const t of o){if(!("value"in t._localId&&"value"in t._category&&Array.isArray(t.AssociatedTo)))continue;if(!this.hasValidMaterial(t))continue;const i=t.AssociatedTo.map(t=>"value"in t._localId&&t._localId.value?t._localId.value:null).filter(t=>null!==t);li.append(e,n,...i)}}}async test(t,e,i={skipIfFails:!0}){const n=this._components.get(gr);for(const[s,r]of Object.entries(t)){const t=n.list.get(s);if(!t)continue;const o=await t.getItemsData([[...r][0]],{relations:{AssociatedTo:{attributes:!1,relations:!1},HasAssociations:{attributes:!0,relations:!0},...this._materialRelations}});for(const t of o){const n=this.getItemChecks(e,s,t,i.skipIfFails);if(n)if(Array.isArray(t.HasAssociations))for(const e of t.HasAssociations){if(!this._ifcMaterialEntities.some(t=>"value"in e._category&&t.test(e._category.value)))continue;if(this.hasValidMaterial(e,n))break}else n.push({parameter:null,currentValue:null,requiredValue:this.value,pass:!1})}}}hasValidMaterial(t,e){let i=!1;if("value"in t._category&&"IFCMATERIAL"===t._category.value){this.evalValue(t,e)&&(i=!0)}else for(const[n,s]of Object.entries(t))if(this._materialParentAttributes.includes(n)&&Array.isArray(s))for(const t of s){if("value"in t._category&&"IFCMATERIAL"===t._category.value){if(this.evalValue(t,e)){i=!0;break}}else{if(this.hasValidMaterial(t)){i=!0;break}}}return i}evalValue(t,e){if(!this.value)return null==e||e.push({parameter:null,currentValue:t.Name&&"value"in t.Name?t.Name.value:null,pass:!0}),!0;if(!("value"in t._category)||"IFCMATERIAL"!==t._category.value)return null;let i=!1;return t.Name&&"value"in t.Name&&(i=this.evalRequirement(t.Name.value,this.value,"Value",e)),i||(t.Category&&"value"in t.Category&&(i=this.evalRequirement(t.Category.value,this.value,"Value",e)),i)}}class wl extends hl{constructor(t,i){super(t),e(this,"facetType","PartOf"),e(this,"_entityFacet"),e(this,"_entity"),e(this,"relation"),e(this,"cardinality","required"),this._entity=i,this._entityFacet=new fl(t,i.name),this._entityFacet.predefinedType=i.predefinedType}set entity(t){this._entity=t;const{name:e,predefinedType:i}=t;this._entityFacet=new fl(this._components,e),this._entityFacet.predefinedType=i}get entity(){return this._entity}serialize(){return""}async getEntities(t,e){}async test(t){}}class yl{constructor(t,n,s){e(this,"name"),e(this,"ifcVersion",new Set),e(this,"identifier",_t.create()),e(this,"description"),e(this,"instructions"),e(this,"requirementsDescription"),e(this,"applicability",new i.DataSet),e(this,"requirements",new i.DataSet),e(this,"components"),this.components=t,this.name=n;for(const t of s)this.ifcVersion.add(t)}set(t){const e=t,i=this;for(const n in t){if("identifier"===n)continue;const t=e[n];n in this&&(i[n]=t)}return this.components.get(Tl).list.set(this.identifier,this),this}async test(t,e={skipIfFails:!0}){const n=new i.DataMap;if(0===this.requirements.size)return n;const s={},r=[];for(const e of this.applicability)r.push(e.getEntities(t,s));await Promise.all(r);const o=[];for(const t of this.requirements)o.push(t.test(s,n,e));return await Promise.all(o),n}serialize(){const t=`name="${this.name}"`,e=this.identifier?`identifier="${this.identifier}"`:"",i=this.description?`description="${this.description}"`:"",n=this.instructions?`instructions="${this.instructions}"`:"";return`<specification ifcVersion="${[...this.ifcVersion].join(" ")}" ${t} ${e} ${i} ${n}>\n <applicability minOccurs="1" maxOccurs="unbounded">\n ${[...this.applicability].map(t=>t.serialize("applicability")).join("\n")}\n </applicability>\n <requirements>\n ${[...this.requirements].map(t=>t.serialize("requirement")).join("\n")}\n </requirements>\n </specification>`}}const _l=t=>{if(!t)return;const e={};if("simpleValue"in t&&(e.type="simple",e.parameter=t.simpleValue),"restriction"in t){const i=t.restriction,n=Object.keys(i);if("pattern"in i&&(e.type="pattern",e.parameter=i.pattern.value),"enumeration"in i){e.type="enumeration";const t=i.enumeration.map(({value:t})=>i.base.includes("string")?String(t):i.base.includes("integer")||i.base.includes("double")?Number(t):t);e.parameter=t}if(n.some(t=>["minInclusive","minExclusive","maxInclusive","maxExclusive"].includes(t))){e.type="bounds";const t={},s=n.find(t=>t.includes("min")),r=n.find(t=>t.includes("max"));s&&(t.minInclusive="minInclusive"===s,t.min=i[s].value),r&&(t.maxInclusive="maxInclusive"===r,t.max=i[r].value),e.parameter=t}if(n.some(t=>["minLength","length","maxLength"].includes(t))){e.type="length";const t={};void 0!==i.length&&(t.length=i.length.value),void 0!==i.minLength&&(t.min=i.minLength.value),void 0!==i.maxLength&&(t.max=i.maxLength.value),e.parameter=t}}return void 0!==e.parameter?e:void 0},bl=(t,e)=>{const i=[];for(const n of e){const e=n.name,s=_l(e);if(!s)continue;const r=new fl(t,s);n.cardinality&&(r.cardinality=n.cardinality),r.predefinedType=_l(n.predefinedType),r.instructions=n.instructions,i.push(r)}return i},vl=(t,e)=>{const i=[];for(const n of e){const e=n.name,s=_l(e);if(!s)continue;const r=new dl(t,s);n.cardinality&&(r.cardinality=n.cardinality),r.value=_l(n.value),r.instructions=n.instructions,i.push(r)}return i},xl=(t,e)=>{const i=[];for(const n of e){const e=new gl(t);n.cardinality&&(e.cardinality=n.cardinality);const s=_l(n.value);"enumeration"===(null==s?void 0:s.type)&&Array.isArray(s.parameter)&&(s.parameter=s.parameter.map(String)),e.value=s,e.uri=n.uri,e.instructions=n.instructions,i.push(e)}return i},Cl=(t,e)=>{const i=[];for(const n of e){const e=n.propertySet,s=n.baseName,r=_l(e),o=_l(s);if(!o||!r)continue;const a=new ml(t,r,o);n.cardinality&&(a.cardinality=n.cardinality);const l=_l(n.value);a.value=l,a.dataType=n.dataType,a.uri=n.uri,a.instructions=n.instructions,i.push(a)}return i},Sl=(t,e)=>{const i=[];for(const n of e){const e=n.system,s=_l(e);if(!s)continue;const r=new pl(t,s);n.cardinality&&(r.cardinality=n.cardinality);const o=_l(n.value);"simple"===(null==o?void 0:o.type)&&(o.parameter=String(o.parameter)),"enumeration"===(null==o?void 0:o.type)&&Array.isArray(o.parameter)&&(o.parameter=o.parameter.map(String)),r.value=o,r.uri=n.uri,r.instructions=n.instructions,i.push(r)}return i},Al=(t,e)=>{const i=[];for(const n of e){const e=_l(n.entity.name);if(!e)continue;const s=_l(n.entity.predefinedType),r=new wl(t,{name:e,predefinedType:s});r.relation=n.relation,n.cardinality&&(r.cardinality=n.cardinality),r.instructions=n.instructions,i.push(r)}return i},Pl=class t extends ht{constructor(i){super(i),e(this,"enabled",!0),e(this,"IDSInfo"),e(this,"list",new n),i.add(t.uuid,this)}getModelIdMap(t){const e={},i={};for(const[n,s]of t){const t=[...s].filter(([,t])=>t.pass).map(([t])=>t);li.append(e,n,...t);const r=[...s].filter(([,t])=>!t.pass).map(([t])=>t);li.append(i,n,...r)}return{pass:e,fail:i}}create(t,e,i){const n=new yl(this.components,t,e);return i&&(n.identifier=i),this.list.set(n.identifier,n),n}load(e){const i=[],n=t.xmlParser.parse(e).ids,{specifications:s,info:r}=n;if(this.IDSInfo={...r},s&&s.specification){const t=Array.isArray(s.specification)?s.specification:[s.specification];for(const e of t){const{name:t,ifcVersion:n,description:s,instructions:r,identifier:o}=e;if(!t||!n)continue;const a=[],l=[],{applicability:c,requirements:h}=e;if(c){const{maxOccurs:t,...e}=c,i=Array.isArray(e)?e:[e];for(const t of i)for(const e in t){const i=Array.isArray(t[e])?t[e]:[t[e]];if("entity"===e){const t=bl(this.components,i);a.push(...t)}if("attribute"===e){const t=vl(this.components,i);a.push(...t)}if("material"===e){const t=xl(this.components,i);a.push(...t)}if("classification"===e){const t=Sl(this.components,i);a.push(...t)}if("property"===e){const t=Cl(this.components,i);a.push(...t)}if("partOf"===e){const t=Al(this.components,i);a.push(...t)}}}let u;if(h){const{maxOccurs:t,...e}=h;u=h.description;const i=Array.isArray(e)?e:[e];for(const t of i)for(const e in t){const i=Array.isArray(t[e])?t[e]:[t[e]];if("entity"===e){const t=bl(this.components,i);l.push(...t)}if("attribute"===e){const t=vl(this.components,i);l.push(...t)}if("material"===e){const t=xl(this.components,i);l.push(...t)}if("classification"===e){const t=Sl(this.components,i);l.push(...t)}if("property"===e){const t=Cl(this.components,i);l.push(...t)}if("partOf"===e){const t=Al(this.components,i);l.push(...t)}}}const d=this.create(t,n.split(/\s+/),o);d.description=s,d.instructions=r,d.requirementsDescription=u,d.applicability.add(...a),d.requirements.add(...l),i.push(d)}}return i}export(t,e=this.list.values()){const i=e??this.list;return`<ids xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://standards.buildingsmart.org/IDS http://standards.buildingsmart.org/IDS/1.0/ids.xsd" xmlns:ids="http://standards.buildingsmart.org/IDS">\n \x3c!-- Made with That Open Engine ${Da.release} (https://github.com/thatopen/engine_components) --\x3e\n <info>\n <title>${t.title}</title>\n ${t.copyright?`<copyright>${t.copyright}</copyright>`:""}\n ${t.version?`<version>${t.version}</version>`:""}\n ${t.description?`<description>${t.description}</description>`:""}\n ${t.author?`<author>${t.author}</author>`:""}\n ${t.date?`<date>${t.date.toISOString().split("T")[0]}</date>`:""}\n ${t.purpose?`<purpose>${t.purpose}</purpose>`:""}\n ${t.milestone?`<milestone>${t.milestone}</milestone>`:""}\n </info>\n <specifications>\n ${[...i].map(t=>t.serialize()).join("\n")}\n </specifications>\n</ids>`}};e(Pl,"uuid","9f0b9f78-9b2e-481a-b766-2fbfd01f342c"),e(Pl,"xmlParser",new Ge({allowBooleanAttributes:!0,attributeNamePrefix:"",ignoreAttributes:!1,ignoreDeclaration:!0,ignorePiTags:!0,numberParseOptions:{leadingZeros:!0,hex:!0},parseAttributeValue:!0,preserveOrder:!1,processEntities:!1,removeNSPrefix:!0,trimValues:!0}));let Tl=Pl;const El=class t extends ht{constructor(i){super(i),e(this,"enabled",!0),i.add(t.uuid,this)}static distanceFromPointToLine(t,e,i,n=!1){const s=new o.Line3,r=new o.Vector3;return s.set(e,i),s.closestPointToPoint(t,n,r),r.distanceTo(t)}round(t){const e=1e3;t.x=Math.trunc(t.x*e)/e,t.y=Math.trunc(t.y*e)/e,t.z=Math.trunc(t.z*e)/e}async getVolumeFromFragments(t){return console.warn("getVolumeFromFragments is deprecated. Use getItemsVolume instead."),this.getItemsVolume(t)}async getItemsVolume(t){let e=0;const i=this.components.get(gr);for(const[n,s]of Object.entries(t)){const t=i.list.get(n);t&&(e+=await t.getItemsVolume([...s]))}return e}static convertUnits(t,e,i,n=2){const s={m:1,cm:.01,mm:.001,km:1e3,m2:1,cm2:1e-4,mm2:1e-6,km2:1e6,m3:1,cm3:1e-6,mm3:1e-9,km3:1e9};if(!s[e]||!s[i])throw new Error("Invalid units provided for conversion.");if(!Number.isInteger(n)||n<0||n>5)throw new Error("Precision must be an integer between 0 and 5.");const r=t*(s[e]/s[i]),o=10**n;return Math.round(r*o)/o}};e(El,"uuid","267ca032-672f-4cb0-afa9-d24e904f39d6");let Ml=El;const Il=(t,e,i)=>{const n=new o.Vector3(-e.z,0,e.x),s=new o.Vector3(e.x+n.x,0,e.z+n.z).normalize().multiplyScalar(i/2);return[t.x+s.x,t.y,t.z+s.z,t.x-s.x,t.y,t.z-s.z]},zl=(t,e,i)=>{const n=new o.Vector3(-e.z,0,e.x),s=t.x-e.x*i+n.x*i*.4,r=t.z-e.z*i+n.z*i*.4,a=t.x-e.x*i-n.x*i*.4,l=t.z-e.z*i-n.z*i*.4;return[t.x,t.y,t.z,s,t.y,r,t.x,t.y,t.z,a,t.y,l,s,t.y,r,a,t.y,l]},Dl=(t,e,i)=>{const n=new o.Vector3(-e.z,0,e.x),s=t.x-e.x*i+n.x*i*.4,r=t.z-e.z*i+n.z*i*.4,a=t.x-e.x*i-n.x*i*.4,l=t.z-e.z*i-n.z*i*.4;return[t.x,t.y,t.z,s,t.y,r,t.x,t.y,t.z,a,t.y,l]},kl=()=>[],Bl=(t,e,i)=>{const n=.4*i,s=[];for(let e=0;e<12;e++){const i=e/12*Math.PI*2,r=(e+1)/12*Math.PI*2;s.push(t.x+Math.cos(i)*n,t.y,t.z+Math.sin(i)*n,t.x+Math.cos(r)*n,t.y,t.z+Math.sin(r)*n)}return s},Ol=(t,e,i)=>{const n=.4*i,s=[];for(let e=0;e<16;e++){const i=e/16*Math.PI*2,r=(e+1)/16*Math.PI*2;s.push(t.x,t.y,t.z,t.x+Math.cos(i)*n,t.y,t.z+Math.sin(i)*n,t.x+Math.cos(r)*n,t.y,t.z+Math.sin(r)*n)}return s},Nl=(t,e,i)=>{const n=new o.Vector3(-e.z,0,e.x),s=.4*i,r=t.clone().addScaledVector(e,s).addScaledVector(n,s),a=t.clone().addScaledVector(e,s).addScaledVector(n,-s),l=t.clone().addScaledVector(e,-s).addScaledVector(n,-s),c=t.clone().addScaledVector(e,-s).addScaledVector(n,s);return[r.x,r.y,r.z,a.x,a.y,a.z,l.x,l.y,l.z,r.x,r.y,r.z,l.x,l.y,l.z,c.x,c.y,c.z]},Vl=(t,e,i)=>{const n=new o.Vector3(-e.z,0,e.x),s=t.clone().addScaledVector(e,-i),r=s.clone().addScaledVector(n,.4*i),a=s.clone().addScaledVector(n,.4*-i);return[t.x,t.y,t.z,r.x,r.y,r.z,a.x,a.y,a.z]};class Ll extends i.DataMap{constructor(){super()}getBySystem(t){const e=new Map;for(const[i,n]of this)n.system===t&&e.set(i,n.data);return e}}class Fl extends i.DataMap{constructor(t){super(),e(this,"_container"),this._container=t,this.deleteGuard=t=>"0"!==t,this.set("0",{name:"0",visible:!0,material:new o.LineBasicMaterial({color:0})})}create(t,e){if(!this.has(t)){const i={name:t,visible:(null==e?void 0:e.visible)??!0,material:(null==e?void 0:e.material)??new o.LineBasicMaterial({color:0})};this.set(t,i)}return this.get(t)}setColor(t,e){const i=this.get(t);i&&(i.material.color.setHex(e),this.set(t,i))}setMaterial(t,e){const i=this.get(t);if(!i)return;const n=i.material;i.material=e,this._container.traverse(i=>{i.userData.layer===t&&(i.userData.isDimension||i.isLineSegments&&(i.material=e))}),n.dispose(),this.set(t,i)}setVisibility(t,e){const i=this.get(t);i&&(i.visible=e,this._container.traverse(i=>{i.userData.layer===t&&(i.visible=e)}),this.set(t,i))}assign(t,e){const i=this.get(e);i&&(t.userData.layer=e,i.visible||(t.visible=!1),t.isLineSegments&&(t.material=i.material))}resolveColor(t){const e=this.get(t);if(e)return e.material.color.getHex()}}const Rl=class t extends o.Group{constructor(i){super(),e(this,"_viewport"),e(this,"_border"),e(this,"_handles",[]),e(this,"_raycaster",new o.Raycaster),e(this,"_resizable",!1),e(this,"_movable",!1),e(this,"_dragHandle",null),e(this,"_dragConstraints",[]),e(this,"_hoveredHandle",null),e(this,"_moveDrag",null),e(this,"_hoveringBorder",!1),e(this,"_normalMat"),e(this,"_hoverMat"),e(this,"_borderMat"),this._viewport=i,this._borderMat=new o.LineBasicMaterial({color:t._BORDER_COLOR,depthTest:!1});const n=new o.BufferGeometry;n.setAttribute("position",new o.BufferAttribute(new Float32Array(24),3)),this._border=new o.LineSegments(n,this._borderMat),this._border.renderOrder=999,this._border.frustumCulled=!1,this._border.userData.isDimension=!0,this.add(this._border),this._normalMat=new o.MeshBasicMaterial({color:t._BORDER_COLOR}),this._hoverMat=new o.MeshBasicMaterial({color:t._BORDER_HOVER_COLOR});const s=new o.SphereGeometry(.05,8,6);for(const e of t._HANDLE_DEFS){const t=new o.Mesh(s,this._normalMat);t.renderOrder=1e3,t.visible=!1,t.userData.constraints=e.constraints,t.userData.isDimension=!0,this.add(t),this._handles.push(t)}this.update()}get resizable(){return this._resizable}set resizable(t){this._resizable=t;for(const e of this._handles)e.visible=t;t||(this._hoveredHandle&&(this._hoveredHandle.material=this._normalMat,this._hoveredHandle=null),this._dragHandle=null,this._dragConstraints=[])}get movable(){return this._movable}set movable(t){this._movable=t,t||(this._moveDrag=null,this._setBorderHover(!1))}get isDragging(){return null!==this._dragHandle||null!==this._moveDrag}update(){const t=this._viewport,e=t.left,i=t.right,n=-t.top,s=-t.bottom,r=.005,o=this._border.geometry.attributes.position;o.setXYZ(0,e,r,n),o.setXYZ(1,i,r,n),o.setXYZ(2,i,r,n),o.setXYZ(3,i,r,s),o.setXYZ(4,i,r,s),o.setXYZ(5,e,r,s),o.setXYZ(6,e,r,s),o.setXYZ(7,e,r,n),o.needsUpdate=!0,this._border.geometry.computeBoundingSphere();const a=(e+i)/2,l=(n+s)/2,c=.01,h=[[e,c,n],[i,c,n],[i,c,s],[e,c,s],[a,c,n],[i,c,l],[a,c,s],[e,c,l]];for(let t=0;t<this._handles.length;t++)this._handles[t].position.set(...h[t])}onPointerMove(e){if(this._dragHandle){const t=this._projectToLocal(e);if(!t)return;for(const e of this._dragConstraints)switch(e){case"left":this._viewport.left=t.x;break;case"right":this._viewport.right=t.x;break;case"top":this._viewport.top=-t.z;break;case"bottom":this._viewport.bottom=-t.z}return this._viewport.right<this._viewport.left&&([this._viewport.left,this._viewport.right]=[this._viewport.right,this._viewport.left],this._dragConstraints=this._dragConstraints.map(t=>"right"===t?"left":"left"===t?"right":t)),this._viewport.top<this._viewport.bottom&&([this._viewport.top,this._viewport.bottom]=[this._viewport.bottom,this._viewport.top],this._dragConstraints=this._dragConstraints.map(t=>"top"===t?"bottom":"bottom"===t?"top":t)),void this.update()}if(this._moveDrag){const t=this._projectToLocal(e);if(!t)return;const i=t.x-this._moveDrag.origin.x,n=t.z-this._moveDrag.origin.z;return this._viewport.left=this._moveDrag.left0+i,this._viewport.right=this._moveDrag.right0+i,this._viewport.top=this._moveDrag.top0-n,this._viewport.bottom=this._moveDrag.bottom0-n,void this.update()}if(!this._resizable&&!this._movable)return;this._raycaster.set(e.origin,e.direction);let i=null;if(this._resizable){const t=this._handles.filter(t=>t.visible),e=this._raycaster.intersectObjects(t,!1);i=e.length>0?e[0].object:null}if(i!==this._hoveredHandle&&(this._hoveredHandle&&(this._hoveredHandle.material=this._normalMat),i&&(i.material=this._hoverMat),this._hoveredHandle=i),this._movable&&!this._hoveredHandle){this._raycaster.params.Line={threshold:t._LINE_THRESHOLD};const e=this._raycaster.intersectObject(this._border,!1).length>0;this._setBorderHover(e)}else this._setBorderHover(!1)}onPointerDown(e){if(this._resizable||this._movable){if(this._raycaster.set(e.origin,e.direction),this._resizable){const t=this._handles.filter(t=>t.visible),e=this._raycaster.intersectObjects(t,!1);if(e.length>0)return this._dragHandle=e[0].object,void(this._dragConstraints=[...this._dragHandle.userData.constraints])}if(this._movable){this._raycaster.params.Line={threshold:t._LINE_THRESHOLD};if(this._raycaster.intersectObject(this._border,!1).length>0){const t=this._projectToLocal(e);if(!t)return;this._moveDrag={origin:t,left0:this._viewport.left,right0:this._viewport.right,top0:this._viewport.top,bottom0:this._viewport.bottom}}}}}onPointerUp(){this._dragHandle=null,this._dragConstraints=[],this._moveDrag=null}dispose(){this._border.geometry.dispose(),this._borderMat.dispose(),this._normalMat.dispose(),this._hoverMat.dispose(),this._handles.length>0&&this._handles[0].geometry.dispose(),this.removeFromParent()}_projectToLocal(t){this.updateWorldMatrix(!0,!1);const e=new o.Vector3(0,1,0).transformDirection(this.matrixWorld),i=(new o.Vector3).setFromMatrixPosition(this.matrixWorld),n=(new o.Plane).setFromNormalAndCoplanarPoint(e,i),s=new o.Vector3;return t.intersectPlane(n,s)?this.worldToLocal(s):null}_setBorderHover(e){e!==this._hoveringBorder&&(this._hoveringBorder=e,this._borderMat.color.setHex(e?t._BORDER_HOVER_COLOR:t._BORDER_COLOR))}};e(Rl,"_BORDER_COLOR",22015),e(Rl,"_BORDER_HOVER_COLOR",16746496),e(Rl,"_LINE_THRESHOLD",.06),e(Rl,"_HANDLE_DEFS",[{constraints:["left","top"]},{constraints:["right","top"]},{constraints:["right","bottom"]},{constraints:["left","bottom"]},{constraints:["top"]},{constraints:["right"]},{constraints:["bottom"]},{constraints:["left"]}]);let Ul=Rl;class jl{constructor(t){e(this,"uuid",o.MathUtils.generateUUID()),e(this,"name"),e(this,"camera"),e(this,"onDisposed",new at),e(this,"_left"),e(this,"_right"),e(this,"_top"),e(this,"_bottom"),e(this,"_drawingScale"),e(this,"_container",null),e(this,"_helper",null),e(this,"_helperVisible",!1),this._left=t.left,this._right=t.right,this._top=t.top,this._bottom=t.bottom,this._drawingScale=t.scale??100,this.name=t.name??"Drawing Viewport",this.camera=new o.OrthographicCamera(this._left,this._right,this._top,this._bottom,.1,30),this.camera.up.set(0,0,-1),this.camera.position.set(0,10,0),this.camera.lookAt(0,0,0),this.camera.layers.set(1)}get left(){return this._left}set left(t){var e;this._left=t,this.camera.left=t,this.camera.updateProjectionMatrix(),null==(e=this._helper)||e.update()}get right(){return this._right}set right(t){var e;this._right=t,this.camera.right=t,this.camera.updateProjectionMatrix(),null==(e=this._helper)||e.update()}get top(){return this._top}set top(t){var e;this._top=t,this.camera.top=t,this.camera.updateProjectionMatrix(),null==(e=this._helper)||e.update()}get bottom(){return this._bottom}set bottom(t){var e;this._bottom=t,this.camera.bottom=t,this.camera.updateProjectionMatrix(),null==(e=this._helper)||e.update()}get drawingScale(){return this._drawingScale}set drawingScale(t){this._drawingScale=t}get helper(){return this._helper||(this._helper=new Ul(this)),this._helper}get helperVisible(){return this._helperVisible}set helperVisible(t){var e,i;this._helperVisible=t,t?null==(e=this._container)||e.add(this.helper):null==(i=this._helper)||i.removeFromParent()}get bbox(){const t=new o.Vector3(this._left,0,-this._top),e=new o.Vector3(this._right,0,-this._bottom);return new o.Box3(t,e)}get size(){const t=new o.Vector3;return this.bbox.getSize(t),new o.Vector2(1e3*t.x,1e3*t.z)}get localXAxis(){return new o.Vector3(1,0,0)}get localYAxis(){return new o.Vector3(0,0,-1)}get normal(){return new o.Vector3(0,1,0)}setContainer(t){this._container=t,this._helperVisible&&this._helper&&t.add(this._helper)}clipLine(t){const e=this.bbox,{start:i,end:n}=t,s=e.containsPoint(i),r=e.containsPoint(n);if(s&&r)return t;if(!s&&!r){const e=this.getPlaneIntersections(t);return e.length<2?null:new o.Line3(e[0],e[1])}const a=this.getPlaneIntersections(t);return 0===a.length?null:s?new o.Line3(i,a[0]):new o.Line3(a[0],n)}dispose(){var t;null==(t=this._helper)||t.dispose(),this._helper=null,this.onDisposed.trigger(),this.onDisposed.reset()}get bboxPlanes(){const t=this.bbox;return[new o.Plane(new o.Vector3(1,0,0),-t.min.x),new o.Plane(new o.Vector3(-1,0,0),t.max.x),new o.Plane(new o.Vector3(0,0,1),-t.min.z),new o.Plane(new o.Vector3(0,0,-1),t.max.z)]}getPlaneIntersections(t){const e=[];for(const i of this.bboxPlanes){const n=new o.Vector3;i.intersectLine(t,n)&&this.bbox.containsPoint(n)&&e.push(n)}return e}}class $l extends i.DataMap{constructor(t){super(),e(this,"_container"),this._container=t,this.onBeforeDelete.add(({value:t})=>{this._container.remove(t.camera),t.dispose()})}create(t){const e=new jl(t);return this._container.add(e.camera),e.setContainer(this._container),this.set(e.uuid,e),e}}const Wl=class t extends o.Group{constructor(i){super(),e(this,"_drawing"),e(this,"_topFrame"),e(this,"_pillars"),e(this,"_bottomFrame"),e(this,"_topPlane"),e(this,"_bottomPlane"),e(this,"_frameMat"),e(this,"_depthMat"),e(this,"_planeMat"),e(this,"width",10),e(this,"height",10),e(this,"farHandle",new o.Object3D),e(this,"widthHandle",new o.Object3D),e(this,"heightHandle",new o.Object3D),this._drawing=i,this._frameMat=new o.LineBasicMaterial({color:t._FRAME_COLOR,depthTest:!1}),this._depthMat=new o.LineBasicMaterial({color:t._DEPTH_COLOR,depthTest:!1,transparent:!0,opacity:.4}),this._planeMat=new o.MeshBasicMaterial({color:t._FRAME_COLOR,transparent:!0,opacity:.07,side:o.DoubleSide,depthTest:!1});const n=()=>{const t=new o.BufferGeometry;return t.setAttribute("position",new o.BufferAttribute(new Float32Array(12),3)),t.setIndex([0,1,2,0,2,3]),t};this._topPlane=new o.Mesh(n(),this._planeMat),this._topPlane.renderOrder=998,this._topPlane.frustumCulled=!1,this._topPlane.userData.isDimension=!0,this._bottomPlane=new o.Mesh(n(),this._planeMat),this._bottomPlane.renderOrder=998,this._bottomPlane.frustumCulled=!1,this._bottomPlane.userData.isDimension=!0;const s=new o.BufferGeometry;s.setAttribute("position",new o.BufferAttribute(new Float32Array(24),3)),this._topFrame=new o.LineSegments(s,this._frameMat),this._topFrame.renderOrder=999,this._topFrame.frustumCulled=!1,this._topFrame.userData.isDimension=!0;const r=new o.BufferGeometry;r.setAttribute("position",new o.BufferAttribute(new Float32Array(24),3)),this._pillars=new o.LineSegments(r,this._depthMat),this._pillars.renderOrder=999,this._pillars.frustumCulled=!1,this._pillars.userData.isDimension=!0;const a=new o.BufferGeometry;a.setAttribute("position",new o.BufferAttribute(new Float32Array(24),3)),this._bottomFrame=new o.LineSegments(a,this._depthMat),this._bottomFrame.renderOrder=999,this._bottomFrame.frustumCulled=!1,this._bottomFrame.userData.isDimension=!0,this.add(this._topPlane,this._bottomPlane),this.add(this._topFrame,this._pillars,this._bottomFrame),this.add(this.farHandle,this.widthHandle,this.heightHandle),this.farHandle.rotation.x=Math.PI,this.update()}update(){const t=this.width/2,e=this.height/2,i=-this._drawing.far,n=.005,s=-t,r=t,o=-e,a=e,l=this._topFrame.geometry.attributes.position;l.setXYZ(0,s,n,o),l.setXYZ(1,r,n,o),l.setXYZ(2,r,n,o),l.setXYZ(3,r,n,a),l.setXYZ(4,r,n,a),l.setXYZ(5,s,n,a),l.setXYZ(6,s,n,a),l.setXYZ(7,s,n,o),l.needsUpdate=!0,this._topFrame.geometry.computeBoundingSphere();const c=this._pillars.geometry.attributes.position;c.setXYZ(0,s,n,o),c.setXYZ(1,s,i,o),c.setXYZ(2,r,n,o),c.setXYZ(3,r,i,o),c.setXYZ(4,r,n,a),c.setXYZ(5,r,i,a),c.setXYZ(6,s,n,a),c.setXYZ(7,s,i,a),c.needsUpdate=!0,this._pillars.geometry.computeBoundingSphere();const h=this._bottomFrame.geometry.attributes.position;h.setXYZ(0,s,i,o),h.setXYZ(1,r,i,o),h.setXYZ(2,r,i,o),h.setXYZ(3,r,i,a),h.setXYZ(4,r,i,a),h.setXYZ(5,s,i,a),h.setXYZ(6,s,i,a),h.setXYZ(7,s,i,o),h.needsUpdate=!0,this._bottomFrame.geometry.computeBoundingSphere();const u=(t,e)=>{const i=t.geometry.attributes.position;i.setXYZ(0,s,e,o),i.setXYZ(1,r,e,o),i.setXYZ(2,r,e,a),i.setXYZ(3,s,e,a),i.needsUpdate=!0,t.geometry.computeBoundingSphere()};u(this._topPlane,n),u(this._bottomPlane,i),this.farHandle.position.set(0,i,0),this.widthHandle.position.set(r,n,0),this.heightHandle.position.set(0,n,a)}attachFarGizmo(t){t.attach(this.farHandle),t.setSpace("local"),t.showX=!1,t.showZ=!1,t.addEventListener("objectChange",()=>{this.farHandle.position.x=0,this.farHandle.position.z=0;const t=Math.max(.1,-this.farHandle.position.y);this._drawing.far=t,this.farHandle.position.y=-t,this.update()})}attachWidthGizmo(t){t.attach(this.widthHandle),t.setSpace("local"),t.showY=!1,t.showZ=!1,t.addEventListener("objectChange",()=>{this.widthHandle.position.y=.005,this.widthHandle.position.z=0,this.width=Math.max(.1,2*this.widthHandle.position.x),this.widthHandle.position.x=this.width/2,this.update()})}attachHeightGizmo(t){t.attach(this.heightHandle),t.setSpace("local"),t.showX=!1,t.showY=!1,t.addEventListener("objectChange",()=>{this.heightHandle.position.x=0,this.heightHandle.position.y=.005,this.height=Math.max(.1,2*this.heightHandle.position.z),this.heightHandle.position.z=this.height/2,this.update()})}dispose(){this._topPlane.geometry.dispose(),this._bottomPlane.geometry.dispose(),this._topFrame.geometry.dispose(),this._pillars.geometry.dispose(),this._bottomFrame.geometry.dispose(),this._planeMat.dispose(),this._frameMat.dispose(),this._depthMat.dispose(),this.removeFromParent()}};e(Wl,"_FRAME_COLOR",22015),e(Wl,"_DEPTH_COLOR",22015);let Gl=Wl;function Hl(t,e){if(3!==t.length||3!==e.length)throw new Error("computeAlignmentMatrix requires exactly 3 point pairs.");const i=(t,e)=>{const i=(new o.Vector3).subVectors(t[1],t[0]),n=(new o.Vector3).subVectors(t[2],t[0]);if((new o.Vector3).crossVectors(i,n).length()<1e-6)throw new Error(`${e} points are collinear — three non-collinear points are required to define a plane.`)};i(t,"Drawing"),i(e,"World");const n=(t,e,i)=>{const n=(new o.Vector3).subVectors(e,t),s=(new o.Vector3).subVectors(i,t),r=n.clone().normalize(),a=(new o.Vector3).crossVectors(n,s).normalize(),l=(new o.Vector3).crossVectors(r,a).normalize();return(new o.Matrix4).makeBasis(r,a,l)},s=n(t[0],t[1],t[2]),r=n(e[0],e[1],e[2]).clone().multiply(s.clone().invert()),a=t[0].distanceTo(t[1]);if(a<1e-10)throw new Error("The first two drawing points are coincident — cannot compute scale.");const l=e[0].distanceTo(e[1])/a,c=t[0].clone().multiplyScalar(l).applyMatrix4(r),h=(new o.Vector3).subVectors(e[0],c),u=(new o.Quaternion).setFromRotationMatrix(r),d=new o.Matrix4;return d.compose(h,u,new o.Vector3(l,l,l)),d}class Zl{constructor(t){e(this,"uuid",o.MathUtils.generateUUID()),e(this,"_raycaster",new o.Raycaster),e(this,"_components"),e(this,"world",null),e(this,"three",new o.Group),e(this,"annotations",new Ll),e(this,"layers",new Fl(this.three)),e(this,"activeLayer","0"),e(this,"far",10),e(this,"viewports",new $l(this.three)),e(this,"onDisposed",new at),this._components=t}raycast(t,e=null){this._raycaster.set(t.origin,t.direction),this._raycaster.layers.set(1),this._raycaster.params.Line&&(this._raycaster.params.Line.threshold=.1);const i=[];this.three.traverse(t=>{t instanceof o.LineSegments&&!t.userData.isDimension&&i.push(t)});const n=this._raycaster.intersectObjects(i,!1);if(0===n.length)return null;const s=n[0],r=this.three.worldToLocal(s.point.clone());let a=null;if(s.object instanceof o.LineSegments&&void 0!==s.index){const t=s.object.geometry.attributes.position,e=s.index,i=new o.Vector3(t.getX(e),t.getY(e),t.getZ(e)),n=new o.Vector3(t.getX(e+1),t.getY(e+1),t.getZ(e+1));i.applyMatrix4(s.object.matrixWorld),this.three.worldToLocal(i),n.applyMatrix4(s.object.matrixWorld),this.three.worldToLocal(n),a=new o.Line3(i,n)}return{point:r,object:s.object,viewport:e,line:a}}alignTo(t,e){Hl(t,e).decompose(this.three.position,this.three.quaternion,this.three.scale)}static toDrawingSpace(t,e){t.updateWorldMatrix(!0,!1),e.three.updateWorldMatrix(!0,!1);const i=(new o.Matrix4).copy(e.three.matrixWorld).invert().multiply(t.matrixWorld),n=t.geometry.attributes.position,s=n.count,r=new Float32Array(3*s),a=new o.Vector3;for(let t=0;t<s;t++)a.fromBufferAttribute(n,t).applyMatrix4(i),r[3*t]=a.x,r[3*t+1]=0,r[3*t+2]=a.z;const l=new o.BufferGeometry;return l.setAttribute("position",new o.BufferAttribute(r,3)),new o.LineSegments(l)}addProjectionLines(t,e="0"){return this.layers.has(e)||(console.warn(`[TechnicalDrawing] Layer "${e}" does not exist. Falling back to "0".`),e="0"),this.layers.assign(t,e),t.layers.set(1),t.material instanceof o.LineDashedMaterial&&t.computeLineDistances(),t.geometry.computeBoundsTree({strategy:0,indirect:!0,type:or}),this.three.add(t),t}async addProjectionFromItems(t,e){if(!this.world)return void console.warn("[TechnicalDrawing] addProjectionFromItems: drawing has no world assigned.");for(const t of[e.layers.visible,e.layers.hidden])if(!this.layers.has(t))return void console.warn(`[TechnicalDrawing] Layer "${t}" does not exist — create it before calling addProjectionFromItems.`);const i=this._components.get(ko),n=i.projectionDirection.clone(),s=i.nearPlane,r=i.farPlane;try{this.three.updateWorldMatrix(!0,!1);const n=new o.Vector3(0,-1,0).transformDirection(this.three.matrixWorld).normalize();i.projectionDirection.copy(n);const s=(new o.Matrix4).makeRotationFromQuaternion((new o.Quaternion).setFromUnitVectors(n,new o.Vector3(0,-1,0))),r=(new o.Vector3).setFromMatrixPosition(this.three.matrixWorld).applyMatrix4(s).y;i.farPlane=r,i.nearPlane=r-this.far;const a=await i.get(t,this.world,{onProgress:e.onProgress}),l=t=>Zl.toDrawingSpace(new o.LineSegments(t),this);this.addProjectionLines(l(a.visible),e.layers.visible),this.addProjectionLines(l(a.hidden),e.layers.hidden)}finally{i.projectionDirection.copy(n),i.nearPlane=s,i.farPlane=r}}orientTo(t){const e=t.clone().normalize(),i=Math.SQRT1_2;e.x>.999?this.three.quaternion.set(.5,-.5,.5,.5):e.x<-.999?this.three.quaternion.set(.5,.5,-.5,.5):e.y>.999?this.three.quaternion.set(0,0,1,0):e.y<-.999?this.three.quaternion.set(0,0,0,1):e.z>.999?this.three.quaternion.set(0,i,-i,0):e.z<-.999?this.three.quaternion.set(i,0,0,i):console.warn("[TechnicalDrawing] orientTo: direction does not match any of the 6 standard axes.")}dispose(){this.viewports.clear(),this.layers.clear(),this.annotations.clear();this._components.get(mt).destroy(this.three),this.onDisposed.trigger(),this.onDisposed.reset()}}const ql={m:{factor:1,suffix:"m"},cm:{factor:100,suffix:"cm"},mm:{factor:1e3,suffix:"mm"},ft:{factor:3.28084,suffix:"ft"},in:{factor:39.3701,suffix:"in"}};class Yl{constructor(t){e(this,"styles",new i.DataMap),e(this,"activeStyle","default"),e(this,"onCommit",new at),e(this,"onUpdate",new at),e(this,"onDelete",new at),e(this,"onDisposed",new at),e(this,"_knownDrawings",new Set),e(this,"_previewMaterial",new o.LineBasicMaterial({color:16737894,depthTest:!1})),e(this,"_previewObject",null),e(this,"_previewDrawing",null),e(this,"_materialCache",new i.DataMap),e(this,"_meshMaterialCache",new i.DataMap),e(this,"_ownsChildGeometry",!0),this._components=t,this.styles.onItemUpdated.add(({key:t})=>{const e=this._materialCache.get(t);e&&e.color.setHex(this._resolveStyle(t).color);const i=this._meshMaterialCache.get(t);i&&i.color.setHex(this._resolveStyle(t).color);const n=this._components.get(Bc),s=n?[...n.list.values()]:[...this._knownDrawings];for(const e of s){const i=[...e.annotations.getBySystem(this)].filter(([,e])=>e.style===t).map(([t])=>t);i.length>0&&this.update(e,i,{})}})}_onAfterPersist(t,e){}_onDispose(){}_updatePreview(){}get(t){const e=new i.DataMap;for(const i of t)for(const[t,n]of i.annotations.getBySystem(this))e.set(t,{drawingUuid:i.uuid,item:n});return e}add(t,e){const i={uuid:o.MathUtils.generateUUID(),style:this.activeStyle,...e},n=this._persist(t,i);return this.onCommit.trigger([n]),i}update(t,e,i){for(const n of e){const e=t.annotations.get(n);if(!e||e.system!==this)continue;const s=e.data;Object.assign(s,i),this._redraw(s,e.three),this.onUpdate.trigger({item:s,group:e.three})}}pick(t,e=.05){const i=new o.Raycaster;i.ray.copy(t),i.params.Line={threshold:e},i.params.LineSegments={threshold:e};const n=o.Line.prototype.raycast;let s=null,r=1/0;for(const t of this._knownDrawings)for(const[e,a]of t.annotations){if(a.system!==this)continue;const t=a.three;t.updateWorldMatrix(!0,!0),t.traverse(a=>{if(a===t)return;const l=[];if(a instanceof o.LineSegments&&a.userData.isDimension)n.call(a,i,l),l.length>0&&l[0].distance<r&&(r=l[0].distance,s=e);else if(a instanceof o.Mesh){const t=(new o.Box3).setFromObject(a),n=new o.Vector3;if(i.ray.intersectBox(t,n)){const t=i.ray.origin.distanceTo(n);t<r&&(r=t,s=e)}}})}return s}delete(t,e){const i=[];for(const n of e){const e=t.annotations.get(n);e&&e.system===this&&(this._disposeGroup(e.three),t.annotations.delete(n),i.push(n))}i.length&&this.onDelete.trigger(i)}clear(t){const e=t??[...this._knownDrawings];for(const t of e){const e=[];for(const[i,n]of t.annotations)n.system===this&&e.push(i);for(const i of e){const e=t.annotations.get(i);this._disposeGroup(e.three),t.annotations.delete(i)}}}dispose(){this._clearPreview(),this._onDispose(),this.clear();for(const t of this._materialCache.values())t.dispose();this._materialCache.clear();for(const t of this._meshMaterialCache.values())t.dispose();this._meshMaterialCache.clear(),this._previewMaterial.dispose(),this.onCommit.reset(),this.onUpdate.reset(),this.onDelete.reset(),this.onDisposed.trigger(),this.onDisposed.reset()}_trackDrawing(t){this._knownDrawings.has(t)||(this._knownDrawings.add(t),t.onDisposed.add(()=>this._knownDrawings.delete(t)))}_resolveStyle(t){return this.styles.get(t)??this.styles.get("default")}_getMaterial(t){const e=this._materialCache.get(t);if(e)return e;const i=new o.LineBasicMaterial({color:this._resolveStyle(t).color});return this._materialCache.set(t,i),i}_getMeshMaterial(t){const e=this._meshMaterialCache.get(t);if(e)return e;const i=new o.MeshBasicMaterial({color:this._resolveStyle(t).color,side:o.DoubleSide});return this._meshMaterialCache.set(t,i),i}_disposeGroup(t){if(t.removeFromParent(),this._ownsChildGeometry)t.traverse(t=>{t.geometry instanceof o.BufferGeometry&&t.geometry.dispose()});else for(;t.children.length>0;)t.remove(t.children[0])}_clearPreview(){this._previewObject&&(this._previewObject.removeFromParent(),this._previewObject.geometry.dispose(),this._previewObject=null)}_persist(t,e){this._trackDrawing(t);const i=this._resolveStyle(e.style),n=this._buildGroup(e,i);return n.userData.isDimension=!0,n.userData.annotationUuid=e.uuid,n.userData.layer=t.activeLayer,t.three.add(n),t.annotations.set(e.uuid,{system:this,data:e,three:n}),this._onAfterPersist(e,n),{drawing:t,item:e,group:n}}_redraw(t,e){for(;e.children.length>0;){const t=e.children[0];this._ownsChildGeometry&&t.geometry instanceof o.BufferGeometry&&t.geometry.dispose(),e.remove(t)}const i=this._resolveStyle(t.style),n=this._buildGroup(t,i);for(;n.children.length>0;)e.add(n.children[0]);this._onAfterPersist(t,e)}}function Xl(t,e){const i=t[0],n=t[t.length-1],s=(new o.Vector3).subVectors(n,i);if(s.lengthSq()<1e-10)return 0;s.normalize();const r=new o.Vector3(-s.z,0,s.x);return e.clone().sub(i).dot(r)}function Kl(t,e){const i=[];for(let n=0;n<t.length-1;n++)i.push({uuid:o.MathUtils.generateUUID(),pointA:t[n].clone(),pointB:t[n+1].clone(),offset:e,style:""});return i}function Ql(t,e){switch(t.kind){case"awaitingFirstPoint":if("CLICK"===e.type){if(!e.line)return t;const i=(new o.Vector3).subVectors(e.line.end,e.line.start).normalize();return{kind:"placingPoints",points:[e.point.clone()],cursor:null,lineDir:i,firstLine:e.line.clone()}}return"SELECT_LINE"===e.type?{kind:"positioningOffset",points:[e.line.start.clone(),e.line.end.clone()],cursor:null}:t;case"placingPoints":if("MOUSE_MOVE"===e.type){const i=new o.Vector3(-t.lineDir.z,0,t.lineDir.x),n=t.points[t.points.length-1],s=e.point.clone().sub(n).dot(i),r=n.clone().addScaledVector(i,s);return{...t,cursor:r}}if("CLICK"===e.type){if(!e.line)return t;if(function(t,e){const i=1e-6;return t.start.distanceTo(e.start)<i&&t.end.distanceTo(e.end)<i||t.start.distanceTo(e.end)<i&&t.end.distanceTo(e.start)<i}(e.line,t.firstLine))return t;const s=(new o.Vector3).subVectors(e.line.end,e.line.start).normalize();if(i=s,n=t.lineDir,!(Math.abs(i.dot(n))>.999))return t;const r=function(t,e,i){const n=t.clone().sub(e.start).dot(i);return e.start.clone().addScaledVector(i,n)}(t.points[0],e.line,t.lineDir),a=[...t.points,r];return{...t,points:a,cursor:t.cursor}}return"CONFIRM"===e.type&&t.points.length>=2?{kind:"positioningOffset",points:t.points,cursor:null}:"ESCAPE"===e.type?{kind:"awaitingFirstPoint"}:t;case"positioningOffset":if("MOUSE_MOVE"===e.type)return{...t,cursor:e.point.clone()};if("CLICK"===e.type){const i=Xl(t.points,e.point);return{kind:"committed",dimensions:Kl(t.points,i)}}return"ESCAPE"===e.type?{kind:"awaitingFirstPoint"}:t;case"committed":return"ESCAPE"===e.type?{kind:"awaitingFirstPoint"}:t}var i,n}function Jl(t){const{pointA:e,pointB:i,offset:n}=t,s=(new o.Vector3).subVectors(i,e),r=new o.Vector3(-s.z,0,s.x).normalize(),a=e.clone().addScaledVector(r,n),l=i.clone().addScaledVector(r,n),c=(new o.Vector3).subVectors(l,a).normalize();return[{tip:a,dir:c},{tip:l,dir:c.clone().negate()}]}function tc(t,e){const{pointA:i,pointB:n,offset:s}=t,r=(new o.Vector3).subVectors(n,i),a=new o.Vector3(-r.z,0,r.x).normalize(),l=s>=0?1:-1,c=Math.abs(s),h=i.clone().addScaledVector(a,e.extensionGap*l),u=i.clone().addScaledVector(a,(c+e.extensionOvershoot)*l),d=n.clone().addScaledVector(a,e.extensionGap*l),p=n.clone().addScaledVector(a,(c+e.extensionOvershoot)*l),f=i.clone().addScaledVector(a,s),m=n.clone().addScaledVector(a,s),g=(new o.Vector3).subVectors(m,f).normalize(),w=e.lineTick(f,g,e.tickSize),y=e.lineTick(m,g.clone().negate(),e.tickSize);return[h.x,h.y,h.z,u.x,u.y,u.z,d.x,d.y,d.z,p.x,p.y,p.z,f.x,f.y,f.z,m.x,m.y,m.z,...w,...y]}function ec(t,e,i,n){if("placingPoints"===t){const t=[];for(let i=0;i<e.length-1;i++){const n=e[i],s=e[i+1];t.push(n.x,n.y,n.z,s.x,s.y,s.z)}if(i){const n=e[e.length-1];t.push(n.x,n.y,n.z,i.x,i.y,i.z)}return t}if(!i||e.length<2)return[];const s=Xl(e,i),r=[];for(let t=0;t<e.length-1;t++)r.push(...tc({pointA:e[t],pointB:e[t+1],offset:s},n));return r}class ic extends Yl{constructor(t){super(t),e(this,"enabled",!0),e(this,"machineState",{kind:"awaitingFirstPoint"}),e(this,"onMachineStateChanged",new at),this.styles.set("default",{lineTick:Il,tickSize:.4,extensionGap:.05,extensionOvershoot:.2,color:0,textOffset:.4,fontSize:.45})}pickHandle(t,e,i=.1){const n=(new o.Matrix4).copy(t.three.matrixWorld).invert(),s=e.origin.clone().applyMatrix4(n),r=e.direction.clone().transformDirection(n).normalize(),a=new o.Ray(s,r),l=new o.Plane(new o.Vector3(0,1,0),0),c=a.intersectPlane(l,new o.Vector3);if(!c)return null;let h=null,u=i;for(const[e,i]of t.annotations.getBySystem(this)){const t=(new o.Vector3).subVectors(i.pointB,i.pointA),n=new o.Vector3(-t.z,0,t.x).normalize(),s=(new o.Vector3).addVectors(i.pointA,i.pointB).multiplyScalar(.5).addScaledVector(n,i.offset);for(const[t,n]of[["pointA",i.pointA],["pointB",i.pointB],["offset",s]]){const i=Math.hypot(c.x-n.x,c.z-n.z);i<u&&(u=i,h={uuid:e,handle:t})}}return h}sendMachineEvent(t){const e=t.drawing??null;e&&(this._previewDrawing=e);const i=Ql(this.machineState,t);if(i!==this.machineState){if(this.machineState=i,this._updatePreview(),"committed"===i.kind){if(!this._previewDrawing)return console.warn("LinearAnnotations: no drawing context — send a CLICK or SELECT_LINE with `drawing` first. Skipping."),void this._resetMachine();for(const t of i.dimensions)t.style=this.activeStyle;const t=i.dimensions.map(t=>this._persist(this._previewDrawing,t));this.onCommit.trigger(t)}this.onMachineStateChanged.trigger(this.machineState),"committed"===i.kind&&this._resetMachine()}}_buildGroup(t,e){const i=new o.Group,n=tc(t,e),s=new o.BufferGeometry;s.setAttribute("position",new o.BufferAttribute(new Float32Array(n),3));const r=new o.LineSegments(s,this._getMaterial(t.style));if(r.layers.set(1),r.userData.isDimension=!0,i.add(r),e.meshTick)for(const{tip:n,dir:s}of Jl(t)){const r=e.meshTick(n,s,e.tickSize),a=new o.BufferGeometry;a.setAttribute("position",new o.BufferAttribute(new Float32Array(r),3));const l=new o.Mesh(a,this._getMeshMaterial(t.style));l.layers.set(1),l.userData.isMeshTick=!0,i.add(l)}return i}_updatePreview(){const t=this.machineState;if("placingPoints"!==t.kind&&"positioningOffset"!==t.kind)return void this._clearPreview();if(!this._previewDrawing)return void this._clearPreview();const e=this._resolveStyle(this.activeStyle);this._previewMaterial.color.setHex(e.color);const i=ec(t.kind,t.points,t.cursor,e);if(0===i.length)return void this._clearPreview();const n=i.length/3;if(!this._previewObject||this._previewObject.geometry.attributes.position.count!==n){this._clearPreview();const t=new o.BufferGeometry;t.setAttribute("position",new o.BufferAttribute(new Float32Array(i),3)),this._previewObject=new o.LineSegments(t,this._previewMaterial),this._previewObject.layers.set(1),this._previewObject.renderOrder=1,this._previewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._previewObject)}else{const t=this._previewObject.geometry.attributes.position;t.set(i),t.needsUpdate=!0}}_resetMachine(){this.machineState={kind:"awaitingFirstPoint"},this._previewDrawing=null,this._updatePreview(),this.onMachineStateChanged.trigger(this.machineState)}}const nc=Math.PI/180;function sc(t,e,i,n){const s=function(t,e,i){const n=(new o.Vector3).subVectors(t,e).normalize(),s=(new o.Vector3).subVectors(i,e).normalize();return(new o.Vector3).addVectors(n,s).normalize()}(t,e,i);return(new o.Vector3).subVectors(n,e).setY(0).dot(s)}function rc(t,e,i,n){return sc(t,e,i,n)<0}function oc(t,e){switch(t.kind){case"awaitingFirstLine":return"CLICK"===e.type&&e.line?{kind:"awaitingSecondLine",line1:e.line.clone(),pointA:e.point.clone()}:t;case"awaitingSecondLine":if("CLICK"===e.type&&e.line){const i=(new o.Vector3).subVectors(t.line1.end,t.line1.start).normalize(),n=(new o.Vector3).subVectors(e.line.end,e.line.start).normalize();if(Math.abs(i.dot(n))>Math.cos(nc))return t;const s=function(t,e,i,n){const s=e.x*n.z-e.z*n.x;if(Math.abs(s)<1e-10)return null;const r=(new o.Vector3).subVectors(i,t),a=(r.x*n.z-r.z*n.x)/s;return new o.Vector3(t.x+e.x*a,0,t.z+e.z*a)}(t.line1.start,i,e.line.start,n);return s?{kind:"positioningArc",pointA:t.pointA.clone(),vertex:s,pointB:e.point.clone(),cursor:null,flipped:!1}:t}return"ESCAPE"===e.type?{kind:"awaitingFirstLine"}:t;case"positioningArc":if("MOUSE_MOVE"===e.type){const i=rc(t.pointA,t.vertex,t.pointB,e.point);return{...t,cursor:e.point.clone(),flipped:i}}if("CLICK"===e.type){const i=rc(t.pointA,t.vertex,t.pointB,e.point),n=Math.max(.05,Math.abs(sc(t.pointA,t.vertex,t.pointB,e.point)));return{kind:"committed",dimension:{uuid:o.MathUtils.generateUUID(),pointA:t.pointA.clone(),vertex:t.vertex.clone(),pointB:t.pointB.clone(),arcRadius:n,flipped:i,style:""}}}return"ESCAPE"===e.type?{kind:"awaitingFirstLine"}:t;case"committed":return"ESCAPE"===e.type?{kind:"awaitingFirstLine"}:t}}function ac(t){const e=(new o.Vector3).subVectors(t.pointA,t.vertex).normalize(),i=(new o.Vector3).subVectors(t.pointB,t.vertex).normalize(),n=Math.atan2(e.z,e.x);let s=Math.atan2(i.z,i.x)-n;for(;s>Math.PI;)s-=2*Math.PI;for(;s<-Math.PI;)s+=2*Math.PI;t.flipped&&(s-=2*Math.sign(s)*Math.PI);const r=new o.Vector3(t.vertex.x+Math.cos(n)*t.arcRadius,0,t.vertex.z+Math.sin(n)*t.arcRadius),a=n+s,l=new o.Vector3(t.vertex.x+Math.cos(a)*t.arcRadius,0,t.vertex.z+Math.sin(a)*t.arcRadius),c=Math.sign(s);return[{tip:r,dir:new o.Vector3(-Math.sin(n)*c,0,Math.cos(n)*c)},{tip:l,dir:new o.Vector3(Math.sin(a)*c,0,-Math.cos(a)*c)}]}function lc(t){const e=(new o.Vector3).subVectors(t.pointA,t.vertex).normalize(),i=(new o.Vector3).subVectors(t.pointB,t.vertex).normalize(),n=Math.acos(o.MathUtils.clamp(e.dot(i),-1,1));return t.flipped?2*Math.PI-n:n}function cc(t){const e=(new o.Vector3).subVectors(t.pointA,t.vertex).normalize(),i=(new o.Vector3).subVectors(t.pointB,t.vertex).normalize(),n=Math.atan2(e.z,e.x);let s=Math.atan2(i.z,i.x)-n;for(;s>Math.PI;)s-=2*Math.PI;for(;s<-Math.PI;)s+=2*Math.PI;const r=n+s/2;return t.flipped?r+Math.PI:r}function hc(t,e,i,n,s,r=!1){const a=Math.atan2(e.z,e.x);let l=Math.atan2(i.z,i.x)-a;for(;l>Math.PI;)l-=2*Math.PI;for(;l<-Math.PI;)l+=2*Math.PI;r&&(l-=2*Math.sign(l)*Math.PI);const c=[];for(let e=0;e<8;e++){const i=a+l*(e/8),s=a+l*((e+1)/8);c.push(t.x+Math.cos(i)*n,0,t.z+Math.sin(i)*n,t.x+Math.cos(s)*n,0,t.z+Math.sin(s)*n)}const h=new o.Vector3(t.x+Math.cos(a)*n,0,t.z+Math.sin(a)*n),u=new o.Vector3(t.x+Math.cos(a+l)*n,0,t.z+Math.sin(a+l)*n),d=t.clone().addScaledVector(e,s.extensionGap),p=t.clone().addScaledVector(i,s.extensionGap);c.push(d.x,d.y,d.z,h.x,h.y,h.z,p.x,p.y,p.z,u.x,u.y,u.z);const f=Math.sign(l),m=new o.Vector3(-Math.sin(a)*f,0,Math.cos(a)*f),g=a+l,w=new o.Vector3(Math.sin(g)*f,0,-Math.cos(g)*f);return c.push(...s.lineTick(h,m,s.tickSize),...s.lineTick(u,w,s.tickSize)),c}function uc(t,e){const i=(new o.Vector3).subVectors(t.pointA,t.vertex).normalize(),n=(new o.Vector3).subVectors(t.pointB,t.vertex).normalize();return hc(t.vertex,i,n,t.arcRadius,e,t.flipped??!1)}function dc(t,e,i,n,s,r=!1){if(!n)return[];const a=Math.max(.05,(new o.Vector3).subVectors(n,e).setY(0).length());return hc(e,(new o.Vector3).subVectors(t,e).normalize(),(new o.Vector3).subVectors(i,e).normalize(),a,s,r)}class pc extends Yl{constructor(t){super(t),e(this,"enabled",!0),e(this,"machineState",{kind:"awaitingFirstLine"}),e(this,"onMachineStateChanged",new at),e(this,"_secondLinePreviewObject",null),this.styles.set("default",{lineTick:Il,tickSize:.4,extensionGap:.05,color:0,textOffset:.25,fontSize:.45})}pickHandle(t,e,i){return null}sendMachineEvent(t){const e=t.drawing??null;if("awaitingSecondLine"===this.machineState.kind&&"MOUSE_MOVE"===t.type)return e&&(this._previewDrawing=e),void this._updateSecondLinePreview(t.point,t.line??null);const i=oc(this.machineState,t);if(i!==this.machineState){if("awaitingSecondLine"===this.machineState.kind&&this._clearSecondLinePreview(),this.machineState=i,e&&(this._previewDrawing=e),this._updatePreview(),"committed"===i.kind){if(!this._previewDrawing)return console.warn("AngleAnnotations: CLICK that commits must include `drawing`. Skipping."),void this._resetMachine();i.dimension.style=this.activeStyle;const t=this._persist(this._previewDrawing,i.dimension);this.onCommit.trigger([t])}this.onMachineStateChanged.trigger(this.machineState),"committed"===i.kind&&this._resetMachine()}}_buildGroup(t,e){const i=new o.Group,n=uc(t,e),s=new o.BufferGeometry;s.setAttribute("position",new o.BufferAttribute(new Float32Array(n),3));const r=new o.LineSegments(s,this._getMaterial(t.style));if(r.layers.set(1),r.userData.isDimension=!0,i.add(r),e.meshTick)for(const{tip:n,dir:s}of ac(t)){const r=e.meshTick(n,s,e.tickSize),a=new o.BufferGeometry;a.setAttribute("position",new o.BufferAttribute(new Float32Array(r),3));const l=new o.Mesh(a,this._getMeshMaterial(t.style));l.layers.set(1),l.userData.isMeshTick=!0,i.add(l)}return i}_updatePreview(){const t=this.machineState;if("positioningArc"!==t.kind)return void this._clearPreview();if(!this._previewDrawing)return void this._clearPreview();const e=this._resolveStyle(this.activeStyle),i=dc(t.pointA,t.vertex,t.pointB,t.cursor,e,t.flipped);if(0===i.length)return void this._clearPreview();const n=i.length/3;if(!this._previewObject||this._previewObject.geometry.attributes.position.count!==n){this._clearPreview();const t=new o.BufferGeometry;t.setAttribute("position",new o.BufferAttribute(new Float32Array(i),3)),this._previewObject=new o.LineSegments(t,this._previewMaterial),this._previewObject.layers.set(1),this._previewObject.renderOrder=1,this._previewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._previewObject)}else{const t=this._previewObject.geometry.attributes.position;t.set(i),t.needsUpdate=!0}}_onDispose(){this._clearSecondLinePreview()}_resetMachine(){this.machineState={kind:"awaitingFirstLine"},this._previewDrawing=null,this._updatePreview(),this.onMachineStateChanged.trigger(this.machineState)}_clearSecondLinePreview(){this._secondLinePreviewObject&&(this._secondLinePreviewObject.removeFromParent(),this._secondLinePreviewObject.geometry.dispose(),this._secondLinePreviewObject=null)}_updateSecondLinePreview(t,e){if("awaitingSecondLine"!==this.machineState.kind)return void this._clearSecondLinePreview();if(!this._previewDrawing)return void this._clearSecondLinePreview();const i=this.machineState,n=(new o.Vector3).subVectors(i.line1.end,i.line1.start).normalize();if(!e)return void this._clearSecondLinePreview();const s=(new o.Vector3).subVectors(e.end,e.start).normalize(),r=function(t,e,i,n){const s=e.x*n.z-e.z*n.x;if(Math.abs(s)<1e-6)return null;const r=i.x-t.x,a=i.z-t.z,l=(r*n.z-a*n.x)/s;return new o.Vector3(t.x+l*e.x,0,t.z+l*e.z)}(i.line1.start,n,e.start,s);if(!r)return void this._clearSecondLinePreview();const a=t.clone(),l=(new o.Vector3).subVectors(a,r).setY(0);if(l.length()<.01)return void this._clearSecondLinePreview();const c=(new o.Vector3).subVectors(i.pointA,r).normalize(),h=l.normalize(),u=Math.atan2(c.z,c.x);let d=Math.atan2(h.z,h.x)-u;for(;d>Math.PI;)d-=2*Math.PI;for(;d<-Math.PI;)d+=2*Math.PI;const p=u+d/2,f=Math.max(.1,.4*Math.min(i.pointA.distanceTo(r),a.distanceTo(r))),m=new o.Vector3(r.x+Math.cos(p)*f,0,r.z+Math.sin(p)*f),g=this._resolveStyle(this.activeStyle),w=dc(i.pointA,r,a,m,g);if(0===w.length)return void this._clearSecondLinePreview();const y=w.length/3;if(!this._secondLinePreviewObject||this._secondLinePreviewObject.geometry.attributes.position.count!==y){this._clearSecondLinePreview();const t=new o.BufferGeometry;t.setAttribute("position",new o.BufferAttribute(new Float32Array(w),3)),this._secondLinePreviewObject=new o.LineSegments(t,this._previewMaterial),this._secondLinePreviewObject.layers.set(1),this._secondLinePreviewObject.renderOrder=1,this._secondLinePreviewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._secondLinePreviewObject)}else{const t=this._secondLinePreviewObject.geometry.attributes.position;t.set(w),t.needsUpdate=!0}}}function fc(t,e){const i=e.x-t.x,n=e.z-t.z,s=Math.sqrt(i*i+n*n);if(0===s)return t.clone();const r=Math.atan2(n,i),a=Math.round(r/(Math.PI/4))*(Math.PI/4);return new o.Vector3(t.x+Math.cos(a)*s,0,t.z+Math.sin(a)*s)}function mc(t,e){switch(t.kind){case"awaitingArrowTip":return"CLICK"===e.type?{kind:"placingElbow",arrowTip:e.point.clone(),cursor:null}:t;case"placingElbow":return"MOUSE_MOVE"===e.type?{...t,cursor:e.point.clone()}:"CLICK"===e.type?{kind:"placingExtension",arrowTip:t.arrowTip,elbow:e.point.clone(),cursor:null}:"ESCAPE"===e.type?{kind:"awaitingArrowTip"}:t;case"placingExtension":return"MOUSE_MOVE"===e.type?{...t,cursor:fc(t.elbow,e.point)}:"CLICK"===e.type?{kind:"enteringText",arrowTip:t.arrowTip,elbow:t.elbow,extensionEnd:fc(t.elbow,e.point)}:"ESCAPE"===e.type?{kind:"awaitingArrowTip"}:t;case"enteringText":if("SUBMIT_TEXT"===e.type&&e.text.trim().length>0){return{kind:"committed",annotation:{uuid:o.MathUtils.generateUUID(),arrowTip:t.arrowTip.clone(),elbow:t.elbow.clone(),extensionEnd:t.extensionEnd.clone(),text:e.text.trim(),style:""}}}return"ESCAPE"===e.type?{kind:"awaitingArrowTip"}:t;case"committed":return"ESCAPE"===e.type?{kind:"awaitingArrowTip"}:t}}function gc(t,e,i,n){return"curved"===n.leaderShape?function(t,e,i,n){const s=new o.QuadraticBezierCurve3(t,e,i).getPoints(24),r=[];for(let t=0;t<s.length-1;t++){const e=s[t],i=s[t+1];r.push(e.x,e.y,e.z,i.x,i.y,i.z)}if(n.lineTick){const i=(new o.Vector3).subVectors(t,e);i.lengthSq()>1e-10&&r.push(...n.lineTick(t,i.normalize(),n.tickSize))}return r}(t,e,i,n):function(t,e,i,n){const s=[t.x,t.y,t.z,e.x,e.y,e.z,e.x,e.y,e.z,i.x,i.y,i.z];if(n.lineTick){const i=(new o.Vector3).subVectors(t,e);i.lengthSq()>1e-10&&s.push(...n.lineTick(t,i.normalize(),n.tickSize))}return s}(t,e,i,n)}function wc(t,e){return gc(t.arrowTip,t.elbow,t.extensionEnd,e)}function yc(t,e,i,n,s){return n?gc(e,"placingElbow"===t?n:i,n,s):[]}class _c extends Yl{constructor(t){super(t),e(this,"enabled",!0),e(this,"machineState",{kind:"awaitingArrowTip"}),e(this,"onMachineStateChanged",new at),e(this,"_previewMeshMaterial",new o.MeshBasicMaterial({color:16737894,side:o.DoubleSide,depthTest:!1})),e(this,"_previewMeshObject",null),this.styles.set("default",{tickSize:.4,color:0,textOffset:.1,fontSize:.45,lineTick:Dl})}pickHandle(t,e,i=.1){const n=(new o.Matrix4).copy(t.three.matrixWorld).invert(),s=e.origin.clone().applyMatrix4(n),r=e.direction.clone().transformDirection(n).normalize(),a=new o.Ray(s,r),l=new o.Plane(new o.Vector3(0,1,0),0),c=a.intersectPlane(l,new o.Vector3);if(!c)return null;let h=null,u=i;for(const[e,i]of t.annotations.getBySystem(this))for(const[t,n]of[["elbow",i.elbow],["extensionEnd",i.extensionEnd]]){const i=Math.hypot(c.x-n.x,c.z-n.z);i<u&&(u=i,h={uuid:e,handle:t})}return h}sendMachineEvent(t){const e=t.drawing??null;e&&(this._previewDrawing=e);const i=mc(this.machineState,t);if(i!==this.machineState){if(this.machineState=i,this._updatePreview(),"committed"===i.kind){if(!this._previewDrawing)return console.warn("LeaderAnnotations: commit requires a drawing. Skipping."),void this._resetMachine();i.annotation.style=this.activeStyle;const t=this._persist(this._previewDrawing,i.annotation);this.onCommit.trigger([t])}this.onMachineStateChanged.trigger(this.machineState),"committed"===i.kind&&this._resetMachine()}}_buildGroup(t,e){const i=new o.Group,n=wc(t,e),s=new o.BufferGeometry;s.setAttribute("position",new o.BufferAttribute(new Float32Array(n),3));const r=new o.LineSegments(s,this._getMaterial(t.style));if(r.layers.set(1),r.userData.isDimension=!0,i.add(r),e.meshTick){const n=(new o.Vector3).subVectors(t.arrowTip,t.elbow);if(n.lengthSq()>1e-10){n.normalize();const s=e.meshTick(t.arrowTip,n,e.tickSize),r=new o.BufferGeometry;r.setAttribute("position",new o.BufferAttribute(new Float32Array(s),3));const a=new o.Mesh(r,this._getMeshMaterial(t.style));a.layers.set(1),a.userData.isMeshArrow=!0,i.add(a)}}return i}_updatePreview(){const t=this.machineState;if("placingElbow"!==t.kind&&"placingExtension"!==t.kind)return void this._clearPreview();if(!this._previewDrawing)return void this._clearPreview();const e=this._resolveStyle(this.activeStyle),i="placingElbow"===t.kind?yc("placingElbow",t.arrowTip,null,t.cursor,e):yc("placingExtension",t.arrowTip,t.elbow,t.cursor,e);if(0===i.length)return void this._clearPreview();const n=i.length/3;if(!this._previewObject||this._previewObject.geometry.attributes.position.count!==n){this._clearPreview();const t=new o.BufferGeometry;t.setAttribute("position",new o.BufferAttribute(new Float32Array(i),3)),this._previewObject=new o.LineSegments(t,this._previewMaterial),this._previewObject.layers.set(1),this._previewObject.renderOrder=1,this._previewObject.frustumCulled=!1,this._previewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._previewObject)}else{const t=this._previewObject.geometry.attributes.position;t.set(i),t.needsUpdate=!0}if(e.meshTick){const i="placingElbow"===t.kind?t.cursor:t.elbow,n=i?(new o.Vector3).subVectors(t.arrowTip,i):null;if(n&&n.lengthSq()>1e-10){n.normalize();const i=e.meshTick(t.arrowTip,n,e.tickSize);if(this._previewMeshObject){const t=this._previewMeshObject.geometry.attributes.position;t.set(i),t.needsUpdate=!0}else{const t=new o.BufferGeometry;t.setAttribute("position",new o.BufferAttribute(new Float32Array(i),3)),this._previewMeshObject=new o.Mesh(t,this._previewMeshMaterial),this._previewMeshObject.layers.set(1),this._previewMeshObject.renderOrder=1,this._previewMeshObject.frustumCulled=!1,this._previewDrawing.three.add(this._previewMeshObject)}}else this._clearPreviewMesh()}else this._clearPreviewMesh()}_clearPreview(){super._clearPreview(),this._clearPreviewMesh()}_onDispose(){this._clearPreviewMesh(),this._previewMeshMaterial.dispose()}_resetMachine(){this.machineState={kind:"awaitingArrowTip"},this._previewDrawing=null,this._updatePreview(),this.onMachineStateChanged.trigger(this.machineState)}_clearPreviewMesh(){this._previewMeshObject&&(this._previewMeshObject.removeFromParent(),this._previewMeshObject.geometry.dispose(),this._previewMeshObject=null)}}class bc extends Yl{constructor(t){super(t),e(this,"enabled",!0),e(this,"_ownsChildGeometry",!1),e(this,"definitions",new i.DataMap),this.styles.set("default",{color:0,textOffset:0,fontSize:0})}pickHandle(t,e,i){return null}pick(t,e=.05){const i=new o.Raycaster;i.ray.copy(t),i.params.Line={threshold:e},i.params.LineSegments={threshold:e};let n=null,s=1/0;for(const t of this._knownDrawings)for(const[e,r]of t.annotations){if(r.system!==this)continue;const t=r.three;t.updateWorldMatrix(!0,!0),t.traverse(r=>{if(r===t)return;if(!(r instanceof o.LineSegments))return;const a=[];r.raycast(i,a),a.length>0&&a[0].distance<s&&(s=a[0].distance,n=e)})}return n}define(t,e){this.definitions.set(t,e)}_buildGroup(t,e){const i=this.definitions.get(t.blockName);if(!i)throw new Error(`BlockAnnotations: block "${t.blockName}" is not defined.`);const n=new o.Group;if(i.lines){const e=new o.LineSegments(i.lines,this._getMaterial(t.style));e.layers.set(1),e.userData.isDimension=!0,n.add(e)}if(i.mesh){const e=new o.Mesh(i.mesh,this._getMeshMaterial(t.style));e.layers.set(1),e.userData.isBlockMesh=!0,n.add(e)}return n}_onAfterPersist(t,e){e.position.set(t.position.x,0,t.position.z),e.rotation.set(0,t.rotation,0),e.scale.setScalar(t.scale)}_onDispose(){var t,e;for(const i of this.definitions.values())null==(t=i.lines)||t.dispose(),null==(e=i.mesh)||e.dispose();this.definitions.clear()}}function vc(t,e){const{position:i,direction:n}=t,{length:s}=e,r=new o.Vector3(i.x+n.x*s,0,i.z+n.z*s),a=new o.Vector3(n.x,0,n.z),l=e.lineTick(r,a,e.tickSize),c=[i.x,0,i.z,r.x,0,r.z];return new Float32Array([...c,...l])}function xc(t,e){return new o.Vector3(t.position.x+t.direction.x*e,0,t.position.z+t.direction.z*e)}function Cc(t,e){switch(e){case"percentage":return`${(100*t).toFixed(2)} %`;case"ratio":return 0===t?"1:∞":`1:${(1/t).toFixed(2)}`;case"degrees":return`${(180*Math.atan(t)/Math.PI).toFixed(2)}°`}}class Sc extends Yl{constructor(t){super(t),e(this,"enabled",!0),this.styles.set("default",{lineTick:kl,meshTick:Vl,tickSize:.4,length:3,color:0,textOffset:.1,fontSize:.45,format:"percentage"})}pickHandle(t,e,i){return null}_buildGroup(t,e){const i=new o.Group,n=vc(t,e),s=new o.BufferGeometry;s.setAttribute("position",new o.BufferAttribute(n,3));const r=new o.LineSegments(s,this._getMaterial(t.style));if(r.layers.set(1),r.userData.isDimension=!0,i.add(r),e.meshTick){const n=xc(t,e.length),s=e.meshTick(n,t.direction,e.tickSize),r=new o.BufferGeometry;r.setAttribute("position",new o.BufferAttribute(new Float32Array(s),3));const a=new o.Mesh(r,this._getMeshMaterial(t.style));a.layers.set(1),a.userData.isDimension=!0,i.add(a)}return i}}function Ac(t,e){const i=e.x-t.x,n=e.z-t.z,s=Math.sqrt(i*i+n*n);if(0===s)return t.clone();const r=Math.atan2(n,i),a=Math.round(r/(Math.PI/4))*(Math.PI/4);return new o.Vector3(t.x+Math.cos(a)*s,0,t.z+Math.sin(a)*s)}function Pc(t,e){switch(t.kind){case"awaitingCenter":return"CLICK"===e.type?{kind:"awaitingRadius",center:e.point.clone(),cursor:null}:t;case"awaitingRadius":if("MOUSE_MOVE"===e.type)return{...t,cursor:e.point.clone()};if("CLICK"===e.type){const i=Math.max(.1,Math.abs(e.point.x-t.center.x)),n=Math.max(.1,Math.abs(e.point.z-t.center.z));return{kind:"awaitingElbow",center:t.center,halfW:i,halfH:n,cursor:null}}return"ESCAPE"===e.type?{kind:"awaitingCenter"}:t;case"awaitingElbow":return"MOUSE_MOVE"===e.type?{...t,cursor:e.point.clone()}:"CLICK"===e.type?{kind:"awaitingExtension",center:t.center,halfW:t.halfW,halfH:t.halfH,elbow:e.point.clone(),cursor:null}:"ESCAPE"===e.type?{kind:"awaitingCenter"}:t;case"awaitingExtension":return"MOUSE_MOVE"===e.type?{...t,cursor:Ac(t.elbow,e.point)}:"CLICK"===e.type?{kind:"enteringText",center:t.center,halfW:t.halfW,halfH:t.halfH,elbow:t.elbow,extensionEnd:Ac(t.elbow,e.point)}:"ESCAPE"===e.type?{kind:"awaitingCenter"}:t;case"enteringText":if("SUBMIT_TEXT"===e.type&&e.text.trim().length>0){return{kind:"committed",annotation:{uuid:o.MathUtils.generateUUID(),center:t.center.clone(),halfW:t.halfW,halfH:t.halfH,elbow:t.elbow.clone(),extensionEnd:t.extensionEnd.clone(),text:e.text.trim(),style:""}}}return"ESCAPE"===e.type?{kind:"awaitingCenter"}:t;case"committed":return"ESCAPE"===e.type?{kind:"awaitingCenter"}:t}}function Tc(t,e){const i=[];i.push(...e.enclosure.buildGeometry(t.center,t.halfW,t.halfH));const n=(new o.Vector3).subVectors(t.elbow,t.center),s=n.lengthSq()>1e-10?n.clone().normalize():new o.Vector3(1,0,0),r=e.enclosure.getAttachmentPoint(t.center,t.halfW,t.halfH,s);if(i.push(r.x,r.y,r.z,t.elbow.x,t.elbow.y,t.elbow.z,t.elbow.x,t.elbow.y,t.elbow.z,t.extensionEnd.x,t.extensionEnd.y,t.extensionEnd.z),e.lineTick){const n=(new o.Vector3).subVectors(t.extensionEnd,t.elbow);n.lengthSq()>1e-10&&i.push(...e.lineTick(t.extensionEnd,n.normalize(),e.tickSize))}return i}function Ec(t,e,i,n,s,r,a){const l="awaitingRadius"===t?r?Math.max(.05,Math.abs(r.x-e.x)):0:i,c="awaitingRadius"===t?r?Math.max(.05,Math.abs(r.z-e.z)):0:n;if(l<1e-10||c<1e-10)return[];const h=[];if(h.push(...a.enclosure.buildGeometry(e,l,c)),"awaitingRadius"===t)return h;const u="awaitingElbow"===t?r:s;if(!u)return h;const d=(new o.Vector3).subVectors(u,e),p=d.lengthSq()>1e-10?d.clone().normalize():new o.Vector3(1,0,0),f=a.enclosure.getAttachmentPoint(e,l,c,p);return"awaitingElbow"===t?(h.push(f.x,0,f.z,u.x,0,u.z),h):r?(h.push(f.x,0,f.z,s.x,0,s.z,s.x,0,s.z,r.x,0,r.z),h):h}const Mc={buildGeometry(t,e,i){const n=.25*Math.min(e,i),s=new o.Vector3(t.x-e,0,t.z-i),r=new o.Vector3(t.x+e,0,t.z-i),a=new o.Vector3(t.x+e,0,t.z+i),l=new o.Vector3(t.x-e,0,t.z+i),c=[[s,r,new o.Vector3(0,0,-1)],[r,a,new o.Vector3(1,0,0)],[a,l,new o.Vector3(0,0,1)],[l,s,new o.Vector3(-1,0,0)]],h=[];for(const[t,e,i]of c){const s=t.distanceTo(e),r=Math.max(1,Math.round(s/(2*n))),a=s/r,l=a/2,c=(new o.Vector3).subVectors(e,t).normalize();for(let e=0;e<r;e++){const n=t.clone().addScaledVector(c,(e+.5)*a),s=t.clone().addScaledVector(c,e*a),r=(new o.Vector3).subVectors(s,n);let u=s.clone();for(let t=1;t<=8;t++){const e=t/8*Math.PI,s=n.x+r.x*Math.cos(e)+i.x*l*Math.sin(e),a=n.z+r.z*Math.cos(e)+i.z*l*Math.sin(e),c=new o.Vector3(s,0,a);h.push(u.x,0,u.z,c.x,0,c.z),u=c}}}return h},getAttachmentPoint(t,e,i,n){const s=Math.abs(n.x)>1e-10?e/Math.abs(n.x):1/0,r=Math.abs(n.z)>1e-10?i/Math.abs(n.z):1/0,a=Math.min(s,r);return new o.Vector3(t.x+n.x*a,0,t.z+n.z*a)}},Ic={buildGeometry(t,e,i){const n=new o.Vector3(t.x-e,0,t.z-i),s=new o.Vector3(t.x+e,0,t.z-i),r=new o.Vector3(t.x+e,0,t.z+i),a=new o.Vector3(t.x-e,0,t.z+i);return[n.x,0,n.z,s.x,0,s.z,s.x,0,s.z,r.x,0,r.z,r.x,0,r.z,a.x,0,a.z,a.x,0,a.z,n.x,0,n.z]},getAttachmentPoint(t,e,i,n){const s=Math.abs(n.x)>1e-10?e/Math.abs(n.x):1/0,r=Math.abs(n.z)>1e-10?i/Math.abs(n.z):1/0,a=Math.min(s,r);return new o.Vector3(t.x+n.x*a,0,t.z+n.z*a)}},zc={buildGeometry(t,e,i){const n=[];for(let s=0;s<32;s++){const r=s/32*Math.PI*2,o=(s+1)/32*Math.PI*2;n.push(t.x+Math.cos(r)*e,0,t.z+Math.sin(r)*i,t.x+Math.cos(o)*e,0,t.z+Math.sin(o)*i)}return n},getAttachmentPoint(t,e,i,n){const s=n.x/e,r=n.z/i,a=Math.sqrt(s*s+r*r),l=a>1e-10?1/a:e;return new o.Vector3(t.x+n.x*l,0,t.z+n.z*l)}};class Dc extends Yl{constructor(t){super(t),e(this,"enabled",!0),e(this,"machineState",{kind:"awaitingCenter"}),e(this,"onMachineStateChanged",new at),this.styles.set("default",{enclosure:Mc,lineTick:Dl,tickSize:.4,color:22015,textOffset:.1,fontSize:.45})}pickHandle(t,e,i){return null}sendMachineEvent(t){const e=t.drawing??null;e&&(this._previewDrawing=e);const i=Pc(this.machineState,t);if(i!==this.machineState){if(this.machineState=i,this._updatePreview(),"committed"===i.kind){if(!this._previewDrawing)return console.warn("CalloutAnnotations: commit requires a drawing. Pass `drawing` on the first CLICK."),void this._resetMachine();i.annotation.style=this.activeStyle;const t=this._persist(this._previewDrawing,i.annotation);this.onCommit.trigger([t])}this.onMachineStateChanged.trigger(this.machineState),"committed"===i.kind&&this._resetMachine()}}_buildGroup(t,e){const i=new o.Group,n=Tc(t,e),s=new o.BufferGeometry;s.setAttribute("position",new o.BufferAttribute(new Float32Array(n),3));const r=new o.LineSegments(s,this._getMaterial(t.style));if(r.layers.set(1),r.userData.isDimension=!0,i.add(r),e.meshTick){const n=(new o.Vector3).subVectors(t.extensionEnd,t.elbow);if(n.lengthSq()>1e-10){n.normalize();const s=e.meshTick(t.extensionEnd,n,e.tickSize),r=new o.BufferGeometry;r.setAttribute("position",new o.BufferAttribute(new Float32Array(s),3));const a=new o.Mesh(r,this._getMeshMaterial(t.style));a.layers.set(1),a.userData.isMeshArrow=!0,i.add(a)}}return i}_updatePreview(){const t=this.machineState;if("awaitingRadius"!==t.kind&&"awaitingElbow"!==t.kind&&"awaitingExtension"!==t.kind)return void this._clearPreview();if(!this._previewDrawing)return;const e=this._resolveStyle(this.activeStyle),i=(()=>{switch(t.kind){case"awaitingRadius":return Ec("awaitingRadius",t.center,0,0,null,t.cursor,e);case"awaitingElbow":return Ec("awaitingElbow",t.center,t.halfW,t.halfH,null,t.cursor,e);case"awaitingExtension":return Ec("awaitingExtension",t.center,t.halfW,t.halfH,t.elbow,t.cursor,e)}})();if(0===i.length)return void this._clearPreview();const n=i.length/3;if(!this._previewObject||this._previewObject.geometry.attributes.position.count!==n){this._clearPreview();const t=new o.BufferGeometry;t.setAttribute("position",new o.BufferAttribute(new Float32Array(i),3)),this._previewObject=new o.LineSegments(t,this._previewMaterial),this._previewObject.layers.set(1),this._previewObject.renderOrder=1,this._previewObject.frustumCulled=!1,this._previewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._previewObject)}else{const t=this._previewObject.geometry.attributes.position;t.set(i),t.needsUpdate=!0}}_resetMachine(){this.machineState={kind:"awaitingCenter"},this._clearPreview(),this._previewDrawing=null,this.onMachineStateChanged.trigger(this.machineState)}}const kc=class t extends ht{constructor(n){super(n),e(this,"enabled",!0),e(this,"list",new i.DataMap),e(this,"systems",new i.DataMap),e(this,"onDisposed",new at),n.add(t.uuid,this),this.list.onBeforeDelete.add(({value:t})=>t.dispose()),this.systems.onBeforeDelete.add(({value:t})=>t.dispose())}use(t){if(this.systems.has(t))return this.systems.get(t);const e=new t(this.components);return this.systems.set(t,e),e}create(t){const e=new Zl(this.components);e.world=t,t.scene.three.add(e.three),t.onDisposed.add(()=>this.list.delete(e.uuid));const i=t.camera;return i.three.layers.enable(1),i instanceof Va&&(i.threePersp.layers.enable(1),i.threeOrtho.layers.enable(1)),this.list.set(e.uuid,e),e}dispose(){this.list.clear(),this.systems.clear(),this.onDisposed.trigger(),this.onDisposed.reset()}};e(kc,"uuid","5c7d3b9a-4e8f-4a2b-9c1d-0e3f2a5b7c8d");let Bc=kc;const Oc=[[16711680,1],[16776960,2],[65280,3],[65535,4],[255,5],[16711935,6],[16777215,7],[0,7]];function Nc(t){const e=t>>16&255,i=t>>8&255,n=255&t;let s=7,r=1/0;for(const[t,o]of Oc){const a=(e-(t>>16&255))**2+(i-(t>>8&255))**2+(n-(255&t))**2;a<r&&(r=a,s=o)}return s}const Vc="\0HANDSEED\0";class Lc{constructor(){e(this,"_lines",[]),e(this,"_handleCounter",1)}p(t,e){return this._lines.push(String(t),String(e)),this}n(t,e,i=6){return this._lines.push(String(t),e.toFixed(i)),this}handle(){return(this._handleCounter++).toString(16).toUpperCase()}entityHeader(t,e,i){return this._lines.push("0",t,"5",this.handle(),"100","AcDbEntity","8",e,"62",String(i)),this}symbolTable(t,e){return this._lines.push("0","TABLE","2",t,"5",this.handle(),"100","AcDbSymbolTable","70",String(e)),this}symbolRecord(t,e){return this._lines.push("0",t,"5",this.handle(),"100","AcDbSymbolTableRecord","100",e),this}writeHandSeed(){return this._lines.push("9","$HANDSEED","5",Vc),this}build(){return(this._lines.join("\n")+"\n").replace(Vc,this._handleCounter.toString(16).toUpperCase())}}class Fc{constructor(t){e(this,"precision",2),e(this,"config",{trueColor:!1}),e(this,"_viewport",null),e(this,"_paperSlot",null),e(this,"_annotationLayers",new Map),e(this,"_systemExporters",new Map),this._components=t}registerSystemExporter(t,e){this._systemExporters.set(t,e)}export(t,e){const i=!!e,n=new Lc,s=new Map;for(const e of t)for(const t of e.drawing.layers.values())s.has(t.name)||s.set(t.name,t);const r=[...s.values()],o=this._components.get(Bc).systems.get(bc),a=o?[...o.definitions.keys()]:[];this._writeHeader(n,i),this._writeTables(n,r,a),this._writeBlocks(n,o??null),n.p(0,"SECTION").p(2,"ENTITIES"),i&&e&&this._writePaperBorders(n,e);for(const s of t){s.drawing.three.traverse(t=>{t.userData.isDimension&&t.userData.annotationUuid&&this._annotationLayers.set(t.userData.annotationUuid,t.userData.layer??"0")});for(const t of s.viewports){if(this._viewport=t.viewport??null,i&&t.viewport){const i=t.viewport,n=e.heightMm-2*e.margin;this._paperSlot={x:t.x??0,y:n-(t.y??0),mmPerUnit:1e3/i.drawingScale,vpLeft:i.left,vpTop:i.top}}else this._paperSlot=null;this._writeViewportBorder(n),this._writeRawLines(n,s.drawing),this._writeLinearAnnotations(n,s.drawing),this._writeAngleAnnotations(n,s.drawing),this._writeLeaderAnnotations(n,s.drawing),this._writeSlopeAnnotations(n,s.drawing),this._writeCalloutAnnotations(n,s.drawing),this._writeBlockInsertions(n,s.drawing),this._writeCustomSystems(n,s.drawing)}this._annotationLayers.clear()}return n.p(0,"ENDSEC"),this._writeObjects(n),n.p(0,"EOF"),this._viewport=null,this._paperSlot=null,n.build()}_writeHeader(t,e){t.p(0,"SECTION").p(2,"HEADER"),t.p(9,"$ACADVER").p(1,this.config.trueColor?"AC1018":"AC1015"),t.p(9,"$DWGCODEPAGE").p(3,"ANSI_1252"),t.p(9,"$INSUNITS").p(70,e?4:6),t.writeHandSeed(),t.p(0,"ENDSEC")}_writeTables(t,e,i){t.p(0,"SECTION").p(2,"TABLES"),t.symbolTable("VPORT",0).p(0,"ENDTAB"),t.symbolTable("LTYPE",1),t.symbolRecord("LTYPE","AcDbLinetypeTableRecord").p(2,"CONTINUOUS").p(70,0).p(3,"Solid line").p(72,65).p(73,0).n(40,0),t.p(0,"ENDTAB"),t.symbolTable("LAYER",e.length);for(const i of e){const e=Nc(i.material.color.getHex());t.symbolRecord("LAYER","AcDbLayerTableRecord").p(2,i.name).p(70,0).p(62,e).p(6,"CONTINUOUS")}t.p(0,"ENDTAB"),t.symbolTable("STYLE",1),t.symbolRecord("STYLE","AcDbTextStyleTableRecord").p(2,"STANDARD").p(70,0).n(40,0).n(41,1).n(50,0).p(71,0).n(42,.2).p(3,"txt").p(4,""),t.p(0,"ENDTAB"),t.symbolTable("VIEW",0).p(0,"ENDTAB"),t.symbolTable("UCS",0).p(0,"ENDTAB"),t.symbolTable("APPID",1),t.symbolRecord("APPID","AcDbRegAppTableRecord").p(2,"ACAD").p(70,0),t.p(0,"ENDTAB"),t.symbolTable("DIMSTYLE",0).p(0,"ENDTAB");const n=["*Model_Space","*Paper_Space",...i];t.symbolTable("BLOCK_RECORD",n.length);for(const e of n)t.symbolRecord("BLOCK_RECORD","AcDbBlockTableRecord").p(2,e);t.p(0,"ENDTAB"),t.p(0,"ENDSEC")}_writeBlocks(t,e){if(t.p(0,"SECTION").p(2,"BLOCKS"),this._writeBlock(t,"*Model_Space",null),this._writeBlock(t,"*Paper_Space",null),e)for(const[i,n]of e.definitions)this._writeBlock(t,i,n.lines??null);t.p(0,"ENDSEC")}_writeBlock(t,e,i){if(t.p(0,"BLOCK").p(5,t.handle()).p(100,"AcDbEntity").p(8,"0").p(100,"AcDbBlockBegin").p(2,e).p(70,0).n(10,0).n(20,0).n(30,0).p(3,e).p(1,""),i){const e=this._viewport,n=this._paperSlot;this._viewport=null,this._paperSlot=null,this._writeGeoAsLines(t,i,"0"),this._viewport=e,this._paperSlot=n}t.p(0,"ENDBLK").p(5,t.handle()).p(100,"AcDbEntity").p(8,"0").p(100,"AcDbBlockEnd")}_writeViewportBorder(t){if(!this._viewport)return;const e=this._viewport,i=this._tx(e.left),n=this._tx(e.right),s=this._ty(-e.bottom),r=this._ty(-e.top);this._writeRawLine(t,i,s,n,s,"0",7),this._writeRawLine(t,n,s,n,r,"0",7),this._writeRawLine(t,n,r,i,r,"0",7),this._writeRawLine(t,i,r,i,s,"0",7)}_writePaperBorders(t,e){const{margin:i,widthMm:n,heightMm:s}=e,r=n-2*i,o=s-2*i;this._writeRawLine(t,0,0,r,0,"0",7),this._writeRawLine(t,r,0,r,o,"0",7),this._writeRawLine(t,r,o,0,o,"0",7),this._writeRawLine(t,0,o,0,0,"0",7),this._writeRawLine(t,-i,-i,r+i,-i,"0",7),this._writeRawLine(t,r+i,-i,r+i,o+i,"0",7),this._writeRawLine(t,r+i,o+i,-i,o+i,"0",7),this._writeRawLine(t,-i,o+i,-i,-i,"0",7)}_writeObjects(t){t.p(0,"SECTION").p(2,"OBJECTS"),t.p(0,"DICTIONARY").p(5,t.handle()).p(330,0).p(100,"AcDbDictionary").p(281,1),t.p(0,"ENDSEC")}_writeRawLines(t,e){e.three.traverse(e=>{var i;if(!(e instanceof o.LineSegments))return;if(e.userData.isDimension)return;if(null==(i=e.parent)?void 0:i.userData.blockUuid)return;if(!e.visible)return;const n=e.userData.layer??"0",s=e.material.color.getHex();this._writeGeoAsLines(t,e.geometry,n,Nc(s),s)})}_writeLinearAnnotations(t,e){var i;const n=this._components.get(Bc).systems.get(ic);if(n)for(const[,s]of e.annotations.getBySystem(n)){const r=n.styles.get(s.style)??n.styles.get("default"),a=Nc(r.color),l=this._annotationLayers.get(s.uuid)??"0";if(!1===(null==(i=e.layers.get(l))?void 0:i.visible))continue;const c=tc(s,r);if(!this._fullyInViewport(this._bboxFromPositions(c)))continue;if(this._writePairsAsLines(t,c,l,a,r.color),r.meshTick)for(const{tip:e,dir:i}of Jl(s))this._writeMeshTriangles(t,r.meshTick(e,i,r.tickSize),l,a,r.color);const h=(new o.Vector3).subVectors(s.pointB,s.pointA),u=new o.Vector3(-h.z,0,h.x).normalize(),d=s.offset>=0?1:-1,p=s.pointA.clone().addScaledVector(u,s.offset),f=s.pointB.clone().addScaledVector(u,s.offset),m=p.clone().add(f).multiplyScalar(.5).addScaledVector(u,(r.textOffset+.5*r.fontSize)*d),g=r.unit??{factor:1,suffix:"m"},w=`${(s.pointA.distanceTo(s.pointB)*g.factor).toFixed(this.precision)} ${g.suffix}`;this._writeText(t,w,m.x,m.z,r.fontSize,l,a,this._textAngle(h.x,h.z),1,2,r.color)}}_writeAngleAnnotations(t,e){var i;const n=this._components.get(Bc).systems.get(pc);if(n)for(const[,s]of e.annotations.getBySystem(n)){const r=n.styles.get(s.style)??n.styles.get("default"),a=Nc(r.color),l=this._annotationLayers.get(s.uuid)??"0";if(!1===(null==(i=e.layers.get(l))?void 0:i.visible))continue;const c=uc(s,r);if(!this._fullyInViewport(this._bboxFromPositions(c)))continue;if(this._writePairsAsLines(t,c,l,a,r.color),r.meshTick)for(const{tip:e,dir:i}of ac(s))this._writeMeshTriangles(t,r.meshTick(e,i,r.tickSize),l,a,r.color);const h=cc(s),u=s.arcRadius+r.textOffset,d=s.vertex.x+Math.cos(h)*u,p=s.vertex.z+Math.sin(h)*u,f=o.MathUtils.radToDeg(lc(s));this._writeText(t,`${f.toFixed(this.precision)}°`,d,p,r.fontSize,l,a,0,1,0,r.color)}}_writeLeaderAnnotations(t,e){var i;const n=this._components.get(Bc).systems.get(_c);if(n)for(const[,s]of e.annotations.getBySystem(n)){const r=n.styles.get(s.style)??n.styles.get("default"),a=Nc(r.color),l=this._annotationLayers.get(s.uuid)??"0";if(!1===(null==(i=e.layers.get(l))?void 0:i.visible))continue;const c=wc(s,r);if(!this._fullyInViewport(this._bboxFromPositions(c)))continue;if(this._writePairsAsLines(t,c,l,a,r.color),r.meshTick){const e=(new o.Vector3).subVectors(s.arrowTip,s.elbow);e.lengthSq()>1e-10&&this._writeMeshTriangles(t,r.meshTick(s.arrowTip,e.normalize(),r.tickSize),l,a,r.color)}const h=(new o.Vector3).subVectors(s.extensionEnd,s.elbow).setY(0).normalize(),u=h.x<-.1?2:h.x>.1?0:1,d=1===u?.5*r.fontSize:0,p=s.extensionEnd.clone().addScaledVector(h,r.textOffset+d);this._writeText(t,s.text,p.x,p.z,r.fontSize,l,a,0,u,2,r.color)}}_writeSlopeAnnotations(t,e){var i;const n=this._components.get(Bc).systems.get(Sc);if(n)for(const[,s]of e.annotations.getBySystem(n)){const r=n.styles.get(s.style)??n.styles.get("default"),a=Nc(r.color),l=this._annotationLayers.get(s.uuid)??"0";if(!1===(null==(i=e.layers.get(l))?void 0:i.visible))continue;const c=vc(s,r);if(!this._fullyInViewport(this._bboxFromPositions(c)))continue;if(this._writePairsAsLines(t,c,l,a,r.color),r.meshTick){const e=xc(s,r.length);this._writeMeshTriangles(t,r.meshTick(e,s.direction,r.tickSize),l,a,r.color)}const h=new o.Vector3(s.position.x+s.direction.x*r.length,0,s.position.z+s.direction.z*r.length),u=s.position.clone().add(h).multiplyScalar(.5).addScaledVector(new o.Vector3(-s.direction.z,0,s.direction.x),r.textOffset+r.fontSize);this._writeText(t,Cc(s.slope,r.format),u.x,u.z,r.fontSize,l,a,this._textAngle(s.direction.x,s.direction.z),1,0,r.color)}}_writeCalloutAnnotations(t,e){var i;const n=this._components.get(Bc).systems.get(Dc);if(n)for(const[,s]of e.annotations.getBySystem(n)){const r=n.styles.get(s.style)??n.styles.get("default"),a=Nc(r.color),l=this._annotationLayers.get(s.uuid)??"0";if(!1===(null==(i=e.layers.get(l))?void 0:i.visible))continue;const c=Tc(s,r);if(!this._fullyInViewport(this._bboxFromPositions(c)))continue;if(this._writePairsAsLines(t,c,l,a,r.color),r.meshTick){const e=(new o.Vector3).subVectors(s.extensionEnd,s.elbow);e.lengthSq()>1e-10&&this._writeMeshTriangles(t,r.meshTick(s.extensionEnd,e.normalize(),r.tickSize),l,a,r.color)}const h=(new o.Vector3).subVectors(s.extensionEnd,s.elbow).setY(0).normalize(),u=h.x<-.1?2:h.x>.1?0:1,d=1===u?.5*r.fontSize:0,p=s.extensionEnd.clone().addScaledVector(h,r.textOffset+d);this._writeText(t,s.text,p.x,p.z,r.fontSize,l,a,0,u,2,r.color)}}_writeBlockInsertions(t,e){const i=this._components.get(Bc).systems.get(bc);if(i)for(const[,n]of e.annotations.getBySystem(i)){if(!this._inViewport(n.position.x,n.position.z))continue;const e=i.styles.get(n.style)??i.styles.get("default"),s=Nc(e.color),r=-o.MathUtils.radToDeg(n.rotation),a=n.scale*this._scale();t.entityHeader("INSERT","0",s),this._emitTrueColor(t,e.color),t.p(100,"AcDbBlockReference").p(2,n.blockName).n(10,this._tx(n.position.x)).n(20,this._ty(n.position.z)).n(30,0).n(41,a).n(42,a).n(43,a).n(50,r)}}_writeGeoAsLines(t,e,i,n=7,s){const r=e.attributes.position;if(r)for(let e=0;e+1<r.count;e+=2){const a=this._clipSegment(new o.Vector3(r.getX(e),0,r.getZ(e)),new o.Vector3(r.getX(e+1),0,r.getZ(e+1)));a&&this._writeLine(t,a.start.x,a.start.z,a.end.x,a.end.z,i,n,s)}}_writePairsAsLines(t,e,i,n=7,s){for(let r=0;r+5<e.length;r+=6){const a=this._clipSegment(new o.Vector3(e[r],0,e[r+2]),new o.Vector3(e[r+3],0,e[r+5]));a&&this._writeLine(t,a.start.x,a.start.z,a.end.x,a.end.z,i,n,s)}}_emitTrueColor(t,e){this.config.trueColor&&void 0!==e&&t.p(420,e)}_writeLine(t,e,i,n,s,r,o,a){t.entityHeader("LINE",r,o),this._emitTrueColor(t,a),t.p(100,"AcDbLine").n(10,this._tx(e)).n(20,this._ty(i)).n(30,0).n(11,this._tx(n)).n(21,this._ty(s)).n(31,0)}_writeRawLine(t,e,i,n,s,r,o){t.entityHeader("LINE",r,o).p(100,"AcDbLine").n(10,e).n(20,i).n(30,0).n(11,n).n(21,s).n(31,0)}_writeSolid(t,e,i,n,s,r,o,a,l,c){t.entityHeader("SOLID",a,l),this._emitTrueColor(t,c),t.p(100,"AcDbTrace").n(10,this._tx(e)).n(20,this._ty(i)).n(30,0).n(11,this._tx(n)).n(21,this._ty(s)).n(31,0).n(12,this._tx(r)).n(22,this._ty(o)).n(32,0).n(13,this._tx(r)).n(23,this._ty(o)).n(33,0)}_writeMeshTriangles(t,e,i,n,s){for(let r=0;r+8<e.length;r+=9)this._writeSolid(t,e[r],e[r+2],e[r+3],e[r+5],e[r+6],e[r+8],i,n,s)}_writeText(t,e,i,n,s,r,o,a=0,l=0,c=0,h){const u=this._tx(i),d=this._ty(n);t.entityHeader("TEXT",r,o),this._emitTrueColor(t,h),t.p(100,"AcDbText").n(10,u).n(20,d).n(30,0).n(40,s*this._scale()).n(50,a).p(1,e),0===l&&0===c||(0!==l&&t.p(72,l),0!==c&&t.p(73,c),t.n(11,u).n(21,d).n(31,0))}_tx(t){return this._paperSlot?this._paperSlot.x+(t-this._paperSlot.vpLeft)*this._paperSlot.mmPerUnit:this._viewport?t-this._viewport.left:t}_ty(t){return this._paperSlot?this._paperSlot.y-(t+this._paperSlot.vpTop)*this._paperSlot.mmPerUnit:this._viewport?-t-this._viewport.bottom:-t}_scale(){return this._paperSlot?this._paperSlot.mmPerUnit:1}_clipSegment(t,e){return this._viewport?this._viewport.clipLine(new o.Line3(t,e)):new o.Line3(t,e)}_inViewport(t,e){return!this._viewport||this._viewport.bbox.containsPoint(new o.Vector3(t,0,e))}_bboxFromPositions(t){const e=new o.Box3;for(let i=0;i+2<t.length;i+=3)e.expandByPoint(new o.Vector3(t[i],0,t[i+2]));return e}_fullyInViewport(t){return!this._viewport||this._viewport.bbox.containsBox(t)}_textAngle(t,e){let i=Math.atan2(-e,t);return(i>Math.PI/2||i<=-Math.PI/2)&&(i+=Math.PI),o.MathUtils.radToDeg(i)}_writeCustomSystems(t,e){if(0===this._systemExporters.size)return;const i=this._makeContext(t);for(const[t,e]of this._systemExporters){const n=this._components.get(Bc).systems.get(t);n&&e(n,i)}}_makeContext(t){return{writeLine:(e,i,n,s,r="0",o=7)=>{this._writeLine(t,e,i,n,s,r,o)},writePairs:(e,i="0",n=7)=>{this._writePairsAsLines(t,e,i,n)},writeMeshTriangles:(e,i="0",n=7)=>{this._writeMeshTriangles(t,e,i,n)},writeText:(e,i,n,s,r={})=>{this._writeText(t,e,i,n,s,r.layer??"0",r.aciColor??7,r.rotDeg??0,r.hAlign??0)},hexToAci:Nc,textAngle:(t,e)=>this._textAngle(t,e)}}}const Rc=class t extends ht{constructor(i){super(i),e(this,"enabled",!0),e(this,"exporter",new Fc(this.components)),i.add(t.uuid,this)}};e(Rc,"uuid","e9a2c3d4-5f67-4b89-a012-1c3d5e7f9b2a");let Uc=Rc;export{pc as AngleAnnotations,Yl as AnnotationSystem,zl as ArrowTick,lt as AsyncEvent,Ya as BCFTopics,Za as BCFTopicsConfigManager,ct as Base,dt as BaseCamera,pt as BaseRenderer,gt as BaseScene,ut as BaseWorldItem,bc as BlockAnnotations,Ro as BoundingBoxer,Dc as CalloutAnnotations,zc as CircleEnclosure,Go as Classifier,Ja as Clipper,Mc as CloudEnclosure,$a as Comment,ht as Component,Da as Components,fi as ConfigManager,di as Configurator,hi as ControlsUtils,ci as DataMap,wt as DataSet,Il as DiagonalTick,mt as Disposer,Bl as DotTick,Ll as DrawingAnnotations,Fl as DrawingLayers,Yl as DrawingSystem,jl as DrawingViewport,Ul as DrawingViewportHelper,$l as DrawingViewports,Fc as DxfExporter,Uc as DxfManager,ko as EdgeProjector,at as Event,ui as EventManager,Zo as FastModelPicker,Yo as FastModelPickers,Vl as FilledArrowTick,Ol as FilledCircleTick,Nl as FilledSquareTick,Uo as FinderQuery,ka as FirstPersonMode,gr as FragmentsManager,Ia as Grids,Lo as Hider,dl as IDSAttribute,pl as IDSClassification,fl as IDSEntity,hl as IDSFacet,gl as IDSMaterial,wl as IDSPartOf,ml as IDSProperty,yl as IDSSpecification,Tl as IDSSpecifications,Bo as IfcFragmentSettings,No as IfcLoader,$o as ItemsFinder,_c as LeaderAnnotations,ic as LinearAnnotations,Ml as MeasurementUtils,li as ModelIdMapUtils,mi as Mouse,kl as NoTick,Dl as OpenArrowTick,Ba as OrbitMode,Va as OrthoPerspectiveCamera,Oa as PlanMode,Na as ProjectionManager,ma as Raycasters,Ic as RectEnclosure,xa as RendererMode,cl as ShadowedScene,Sa as SimpleCamera,Ea as SimpleGrid,Ta as SimpleGridConfigManager,Xa as SimplePlane,pa as SimpleRaycaster,Ca as SimpleRenderer,ba as SimpleScene,_a as SimpleSceneConfigManager,ga as SimpleWorld,Sc as SlopeAnnotations,Xo as SnapClass,Qo as SnapResolver,da as SnapResolvers,Zl as TechnicalDrawing,Gl as TechnicalDrawingHelper,Bc as TechnicalDrawings,Ga as Topic,_t as UUID,ql as Units,ai as VertexPicker,sl as View,tl as Viewpoint,nl as Viewpoints,ol as Views,Pa as Worlds,oi as XML,oc as angleDimensionMachine,uc as buildAnglePositions,dc as buildAnglePreviewPositions,Tc as buildCalloutPositions,Ec as buildCalloutPreviewPositions,tc as buildDimensionPositions,Kl as buildDimensions,wc as buildLeaderPositions,yc as buildLeaderPreviewPositions,ec as buildPreviewPositions,vc as buildSlopePositions,Pc as calloutAnnotationMachine,Hl as computeAlignmentMatrix,lc as computeAngle,cc as computeBisectorAngle,Xl as computeOffset,Ha as extensionsImporter,Cc as formatSlope,ac as getAngleTickEndpoints,Jl as getDimensionTickEndpoints,xc as getSlopeTip,mc as leaderAnnotationMachine,Ql as linearDimensionMachine};
1
+ import*as e from"@thatopen/fragments";import{DataMap as t,FragmentsModels as i,DataSet as n}from"@thatopen/fragments";import*as s from"three";import{Box3 as r,Matrix4 as o,BufferAttribute as a,Vector3 as l,Line3 as c,Plane as h,Vector2 as u,Triangle as d,BackSide as p,DoubleSide as f,REVISION as m,Ray as g,FrontSide as w,Mesh as y,LineSegments as _,LineLoop as b,Line as v,Points as x,Sphere as C,BatchedMesh as S,OrthographicCamera as A,WebGLRenderTarget as T,Scene as P,Color as E,ShaderMaterial as M,Vector4 as I,NoBlending as z,GLSL3 as D,MathUtils as k,BufferGeometry as B}from"three";import*as O from"three/webgpu";import{instancedArray as V,Fn as N,instanceIndex as L,mat4 as F,Loop as R,int as U,vec3 as j,vec4 as $,float as W,cross as H,If as G,Continue as Z,max as q,min as Y,normalize as X,select as K,abs as Q,mix as J,uint as ee,atomicAdd as te}from"three/tsl";import*as ie from"web-ifc";import ne from"camera-controls";import{TransformControls as se}from"three/examples/jsm/controls/TransformControls.js";class re{enabled=!0;add(e){this.handlers.push(e)}remove(e){this.handlers=this.handlers.filter(t=>t!==e)}trigger=e=>{if(!this.enabled)return;const t=this.handlers.slice(0);for(const i of t)i(e)};reset(){this.handlers.length=0}handlers=[]}class oe{enabled=!0;add(e){this.handlers.push(e)}remove(e){this.handlers=this.handlers.filter(t=>t!==e)}trigger=async e=>{if(!this.enabled)return;const t=this.handlers.slice(0);for(const i of t)await i(e)};reset(){this.handlers.length=0}handlers=[]}class ae{constructor(e){this.components=e}components;isDisposeable=()=>"dispose"in this&&"onDisposed"in this;isResizeable=()=>"resize"in this&&"getSize"in this;isUpdateable=()=>"onAfterUpdate"in this&&"onBeforeUpdate"in this&&"update"in this;isHideable=()=>"visible"in this;isConfigurable=()=>"setup"in this&&"config"in this&&"onSetup"in this;isSerializable=()=>"import"in this&&"export"in this}class le extends ae{}class ce extends ae{worlds=new t;onWorldChanged=new re;_currentWorld=null;set currentWorld(e){this._currentWorld=e}get currentWorld(){return this._currentWorld}constructor(e){super(e),this.onWorldChanged.add(({world:e,action:t})=>{"removed"===t&&this.worlds.delete(e.uuid)})}}class he extends ce{hasCameraControls=()=>"controls"in this}class ue extends ce{onAfterUpdate=new re;onBeforeUpdate=new re;onDisposed=new re;onResize=new re;onClippingPlanesUpdated=new re;clippingPlanes=[];localClippingPlanes=!1;updateClippingPlanes(){this.onClippingPlanesUpdated.trigger()}setPlane(e,t,i=this.localClippingPlanes){t.isLocal=i;const n=this.clippingPlanes.indexOf(t);e&&-1===n?this.clippingPlanes.push(t):!e&&n>-1&&this.clippingPlanes.splice(n,1),this.three.clippingPlanes=this.clippingPlanes.filter(e=>!e.isLocal),this.updateClippingPlanes()}}class de extends le{_disposedComponents=new Set;enabled=!0;static uuid="76e9cd8e-ad8f-4753-9ef6-cbc60f7247fe";constructor(e){super(e),e.add(de.uuid,this)}get(){return this._disposedComponents}destroy(e,t=!0,i=!0){e.removeFromParent();const n=e;n.dispose&&n.dispose(),this.disposeGeometryAndMaterials(e,t),i&&n.children&&n.children.length&&this.disposeChildren(n),e.children.length=0}disposeGeometry(e){e.boundsTree&&e.disposeBoundsTree&&e.disposeBoundsTree(),e.dispose()}disposeGeometryAndMaterials(e,t){const i=e;i.geometry&&this.disposeGeometry(i.geometry),t&&i.material&&de.disposeMaterial(i),i.material=[],i.geometry=null}disposeChildren(e){for(const t of[...e.children])this.destroy(t)}static disposeMaterial(e){if(e.material)if(Array.isArray(e.material))for(const t of e.material)t.dispose();else e.material.dispose()}}class pe extends ce{onDisposed=new re;directionalLights=new Map;ambientLights=new Map;constructor(e){super(e)}dispose(){const e=this.components.get(de);for(const t of this.three.children){const i=t;i.geometry&&e.destroy(i)}this.deleteAllLights(),this.three.children=[],this.onDisposed.trigger(),this.onDisposed.reset()}deleteAllLights(){for(const[,e]of this.directionalLights)e.removeFromParent(),e.target.removeFromParent(),e.dispose();this.directionalLights.clear();for(const[,e]of this.ambientLights)e.removeFromParent(),e.dispose();this.ambientLights.clear()}}class fe extends Set{onItemAdded=new re;onItemDeleted=new re;onCleared=new re;constructor(e){super(e)}clear(){super.clear(),this.onCleared.trigger()}add(...e){for(const t of e){if(this.has(t))continue;this.guard(t)&&(super.add(t),this.onItemAdded||(this.onItemAdded=new re),this.onItemAdded.trigger(t))}return this}guard=()=>!0;delete(e){const t=super.delete(e);return t&&this.onItemDeleted.trigger(),t}dispose(){this.clear(),this.onItemAdded.reset(),this.onItemDeleted.reset(),this.onCleared.reset()}}class me{static _pattern=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/;static _lut=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];static create(){const e=4294967295*Math.random()|0,t=4294967295*Math.random()|0,i=4294967295*Math.random()|0,n=4294967295*Math.random()|0;return`${me._lut[255&e]+me._lut[e>>8&255]+me._lut[e>>16&255]+me._lut[e>>24&255]}-${me._lut[255&t]}${me._lut[t>>8&255]}-${me._lut[t>>16&15|64]}${me._lut[t>>24&255]}-${me._lut[63&i|128]}${me._lut[i>>8&255]}-${me._lut[i>>16&255]}${me._lut[i>>24&255]}${me._lut[255&n]}${me._lut[n>>8&255]}${me._lut[n>>16&255]}${me._lut[n>>24&255]}`.toLowerCase()}static validate(e){if(!me._pattern.test(e))throw new Error(`${e} is not a valid UUID v4.\n\n- If you're the tool creator, you can take one from https://www.uuidgenerator.net/.\n\n- If you're using a platform tool, verify the uuid isn't misspelled or contact the tool creator.`)}}const ge=":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",we=new RegExp("^"+("["+ge+"]["+(ge+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040")+"]*")+"$");function ye(e,t){const i=[];let n=t.exec(e);for(;n;){const s=[];s.startIndex=t.lastIndex-n[0].length;const r=n.length;for(let e=0;e<r;e++)s.push(n[e]);i.push(s),n=t.exec(e)}return i}const _e=function(e){const t=we.exec(e);return!(null==t)};const be=["hasOwnProperty","toString","valueOf","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"],ve=["__proto__","constructor","prototype"],xe={allowBooleanAttributes:!1,unpairedTags:[]};function Ce(e){return" "===e||"\t"===e||"\n"===e||"\r"===e}function Se(e,t){const i=t;for(;t<e.length;t++)if("?"==e[t]||" "==e[t]){const n=e.substr(i,t-i);if(t>5&&"xml"===n)return De("InvalidXml","XML declaration allowed only at the start of the document.",Oe(e,t));if("?"==e[t]&&">"==e[t+1]){t++;break}continue}return t}function Ae(e,t){if(e.length>t+5&&"-"===e[t+1]&&"-"===e[t+2]){for(t+=3;t<e.length;t++)if("-"===e[t]&&"-"===e[t+1]&&">"===e[t+2]){t+=2;break}}else if(e.length>t+8&&"D"===e[t+1]&&"O"===e[t+2]&&"C"===e[t+3]&&"T"===e[t+4]&&"Y"===e[t+5]&&"P"===e[t+6]&&"E"===e[t+7]){let i=1;for(t+=8;t<e.length;t++)if("<"===e[t])i++;else if(">"===e[t]&&(i--,0===i))break}else if(e.length>t+9&&"["===e[t+1]&&"C"===e[t+2]&&"D"===e[t+3]&&"A"===e[t+4]&&"T"===e[t+5]&&"A"===e[t+6]&&"["===e[t+7])for(t+=8;t<e.length;t++)if("]"===e[t]&&"]"===e[t+1]&&">"===e[t+2]){t+=2;break}return t}const Te='"',Pe="'";function Ee(e,t){let i="",n="",s=!1;for(;t<e.length;t++){if(e[t]===Te||e[t]===Pe)""===n?n=e[t]:n!==e[t]||(n="");else if(">"===e[t]&&""===n){s=!0;break}i+=e[t]}return""===n&&{value:i,index:t,tagClosed:s}}const Me=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function Ie(e,t){const i=ye(e,Me),n={};for(let e=0;e<i.length;e++){if(0===i[e][1].length)return De("InvalidAttr","Attribute '"+i[e][2]+"' has no space in starting.",Ve(i[e]));if(void 0!==i[e][3]&&void 0===i[e][4])return De("InvalidAttr","Attribute '"+i[e][2]+"' is without value.",Ve(i[e]));if(void 0===i[e][3]&&!t.allowBooleanAttributes)return De("InvalidAttr","boolean attribute '"+i[e][2]+"' is not allowed.",Ve(i[e]));const s=i[e][2];if(!ke(s))return De("InvalidAttr","Attribute '"+s+"' is an invalid name.",Ve(i[e]));if(Object.prototype.hasOwnProperty.call(n,s))return De("InvalidAttr","Attribute '"+s+"' is repeated.",Ve(i[e]));n[s]=1}return!0}function ze(e,t){if(";"===e[++t])return-1;if("#"===e[t])return function(e,t){let i=/\d/;for("x"===e[t]&&(t++,i=/[\da-fA-F]/);t<e.length;t++){if(";"===e[t])return t;if(!e[t].match(i))break}return-1}(e,++t);let i=0;for(;t<e.length;t++,i++)if(!(e[t].match(/\w/)&&i<20)){if(";"===e[t])break;return-1}return t}function De(e,t,i){return{err:{code:e,msg:t,line:i.line||i,col:i.col}}}function ke(e){return _e(e)}function Be(e){return _e(e)}function Oe(e,t){const i=e.substring(0,t).split(/\r?\n/);return{line:i.length,col:i[i.length-1].length+1}}function Ve(e){return e.startIndex+e[1].length}const Ne={cent:"¢",pound:"£",curren:"¤",yen:"¥",euro:"€",dollar:"$",euro:"€",fnof:"ƒ",inr:"₹",af:"؋",birr:"ብር",peso:"₱",rub:"₽",won:"₩",yuan:"¥",cedil:"¸"},Le={amp:"&",apos:"'",gt:">",lt:"<",quot:'"'},Fe={nbsp:" ",copy:"©",reg:"®",trade:"™",mdash:"—",ndash:"–",hellip:"…",laquo:"«",raquo:"»",lsquo:"‘",rsquo:"’",ldquo:"“",rdquo:"”",bull:"•",para:"¶",sect:"§",deg:"°",frac12:"½",frac14:"¼",frac34:"¾"},Re=new Set("!?\\\\/[]$%{}^&*()<>|+");function Ue(e){if("#"===e[0])throw new Error(`[EntityReplacer] Invalid character '#' in entity name: "${e}"`);for(const t of e)if(Re.has(t))throw new Error(`[EntityReplacer] Invalid character '${t}' in entity name: "${e}"`);return e}function je(...e){const t=Object.create(null);for(const i of e)if(i)for(const e of Object.keys(i)){const n=i[e];if("string"==typeof n)t[e]=n;else if(n&&"object"==typeof n&&void 0!==n.val){const i=n.val;"string"==typeof i&&(t[e]=i)}}return t}const $e="external",We="base",He="all";const Ge=Object.freeze({allow:0,leave:1,remove:2,throw:3}),Ze=new Set([9,10,13]);class qe{constructor(e={}){var t;this._limit=e.limit||{},this._maxTotalExpansions=this._limit.maxTotalExpansions||0,this._maxExpandedLength=this._limit.maxExpandedLength||0,this._postCheck="function"==typeof e.postCheck?e.postCheck:e=>e,this._limitTiers=(t=this._limit.applyLimitsTo??$e)&&t!==$e?t===He?new Set([He]):t===We?new Set([We]):Array.isArray(t)?new Set(t):new Set([$e]):new Set([$e]),this._numericAllowed=e.numericAllowed??!0,this._baseMap=je(Le,e.namedEntities||null),this._externalMap=Object.create(null),this._inputMap=Object.create(null),this._totalExpansions=0,this._expandedLength=0,this._removeSet=new Set(e.remove&&Array.isArray(e.remove)?e.remove:[]),this._leaveSet=new Set(e.leave&&Array.isArray(e.leave)?e.leave:[]);const i=function(e){if(!e)return{xmlVersion:1,onLevel:Ge.allow,nullLevel:Ge.remove};const t=1.1===e.xmlVersion?1.1:1,i=Ge[e.onNCR]??Ge.allow,n=Ge[e.nullNCR]??Ge.remove;return{xmlVersion:t,onLevel:i,nullLevel:Math.max(n,Ge.remove)}}(e.ncr);this._ncrXmlVersion=i.xmlVersion,this._ncrOnLevel=i.onLevel,this._ncrNullLevel=i.nullLevel}setExternalEntities(e){if(e)for(const t of Object.keys(e))Ue(t);this._externalMap=je(e)}addExternalEntity(e,t){Ue(e),"string"==typeof t&&-1===t.indexOf("&")&&(this._externalMap[e]=t)}addInputEntities(e){this._totalExpansions=0,this._expandedLength=0,this._inputMap=je(e)}reset(){return this._inputMap=Object.create(null),this._totalExpansions=0,this._expandedLength=0,this}setXmlVersion(e){this._ncrXmlVersion=1.1===e?1.1:1}decode(e){if("string"!=typeof e||0===e.length)return e;const t=e,i=[],n=e.length;let s=0,r=0;const o=this._maxTotalExpansions>0,a=this._maxExpandedLength>0,l=o||a;for(;r<n;){if(38!==e.charCodeAt(r)){r++;continue}let t=r+1;for(;t<n&&59!==e.charCodeAt(t)&&t-r<=32;)t++;if(t>=n||59!==e.charCodeAt(t)){r++;continue}const c=e.slice(r+1,t);if(0===c.length){r++;continue}let h,u;if(this._removeSet.has(c))h="",void 0===u&&(u=$e);else{if(this._leaveSet.has(c)){r++;continue}if(35===c.charCodeAt(0)){const e=this._resolveNCR(c);if(void 0===e){r++;continue}h=e,u=We}else{const e=this._resolveName(c);h=e?.value,u=e?.tier}}if(void 0!==h){if(r>s&&i.push(e.slice(s,r)),i.push(h),s=t+1,r=s,l&&this._tierCounts(u)){if(o&&(this._totalExpansions++,this._totalExpansions>this._maxTotalExpansions))throw new Error(`[EntityReplacer] Entity expansion count limit exceeded: ${this._totalExpansions} > ${this._maxTotalExpansions}`);if(a){const e=h.length-(c.length+2);if(e>0&&(this._expandedLength+=e,this._expandedLength>this._maxExpandedLength))throw new Error(`[EntityReplacer] Expanded content length limit exceeded: ${this._expandedLength} > ${this._maxExpandedLength}`)}}}else r++}s<n&&i.push(e.slice(s));const c=0===i.length?e:i.join("");return this._postCheck(c,t)}_tierCounts(e){return!!this._limitTiers.has(He)||this._limitTiers.has(e)}_resolveName(e){return e in this._inputMap?{value:this._inputMap[e],tier:$e}:e in this._externalMap?{value:this._externalMap[e],tier:$e}:e in this._baseMap?{value:this._baseMap[e],tier:We}:void 0}_classifyNCR(e){return 0===e?this._ncrNullLevel:e>=55296&&e<=57343||1===this._ncrXmlVersion&&e>=1&&e<=31&&!Ze.has(e)?Ge.remove:-1}_applyNCRAction(e,t,i){switch(e){case Ge.allow:return String.fromCodePoint(i);case Ge.remove:return"";case Ge.leave:return;case Ge.throw:throw new Error(`[EntityDecoder] Prohibited numeric character reference &${t}; (U+${i.toString(16).toUpperCase().padStart(4,"0")})`);default:return String.fromCodePoint(i)}}_resolveNCR(e){const t=e.charCodeAt(1);let i;if(i=120===t||88===t?parseInt(e.slice(2),16):parseInt(e.slice(1),10),Number.isNaN(i)||i<0||i>1114111)return;const n=this._classifyNCR(i);if(!this._numericAllowed&&n<Ge.remove)return;const s=-1===n?this._ncrOnLevel:Math.max(this._ncrOnLevel,n);return this._applyNCRAction(s,e,i)}}const Ye=e=>be.includes(e)?"__"+e:e,Xe={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(e,t){return t},attributeValueProcessor:function(e,t){return t},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,entityDecoder:null,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(e,t,i){return e},captureMetaData:!1,maxNestedTags:100,strictReservedNames:!0,jPath:!0,onDangerousProperty:Ye};function Ke(e,t){if("string"!=typeof e)return;const i=e.toLowerCase();if(be.some(e=>i===e.toLowerCase()))throw new Error(`[SECURITY] Invalid ${t}: "${e}" is a reserved JavaScript keyword that could cause prototype pollution`);if(ve.some(e=>i===e.toLowerCase()))throw new Error(`[SECURITY] Invalid ${t}: "${e}" is a reserved JavaScript keyword that could cause prototype pollution`)}function Qe(e,t){return"boolean"==typeof e?{enabled:e,maxEntitySize:1e4,maxExpansionDepth:1e4,maxTotalExpansions:1/0,maxExpandedLength:1e5,maxEntityCount:1e3,allowedTags:null,tagFilter:null,appliesTo:"all"}:"object"==typeof e&&null!==e?{enabled:!1!==e.enabled,maxEntitySize:Math.max(1,e.maxEntitySize??1e4),maxExpansionDepth:Math.max(1,e.maxExpansionDepth??1e4),maxTotalExpansions:Math.max(1,e.maxTotalExpansions??1/0),maxExpandedLength:Math.max(1,e.maxExpandedLength??1e5),maxEntityCount:Math.max(1,e.maxEntityCount??1e3),allowedTags:e.allowedTags??null,tagFilter:e.tagFilter??null,appliesTo:e.appliesTo??"all"}:Qe(!0)}const Je=function(e){const t=Object.assign({},Xe,e),i=[{value:t.attributeNamePrefix,name:"attributeNamePrefix"},{value:t.attributesGroupName,name:"attributesGroupName"},{value:t.textNodeName,name:"textNodeName"},{value:t.cdataPropName,name:"cdataPropName"},{value:t.commentPropName,name:"commentPropName"}];for(const{value:e,name:t}of i)e&&Ke(e,t);return null===t.onDangerousProperty&&(t.onDangerousProperty=Ye),t.processEntities=Qe(t.processEntities,t.htmlEntities),t.unpairedTagsSet=new Set(t.unpairedTags),t.stopNodes&&Array.isArray(t.stopNodes)&&(t.stopNodes=t.stopNodes.map(e=>"string"==typeof e&&e.startsWith("*.")?".."+e.substring(2):e)),t};let et;et="function"!=typeof Symbol?"@@xmlMetadata":Symbol("XML Node Metadata");class tt{constructor(e){this.tagname=e,this.child=[],this[":@"]=Object.create(null)}add(e,t){"__proto__"===e&&(e="#__proto__"),this.child.push({[e]:t})}addChild(e,t){"__proto__"===e.tagname&&(e.tagname="#__proto__"),e[":@"]&&Object.keys(e[":@"]).length>0?this.child.push({[e.tagname]:e.child,":@":e[":@"]}):this.child.push({[e.tagname]:e.child}),void 0!==t&&(this.child[this.child.length-1][et]={startIndex:t})}static getMetaDataSymbol(){return et}}class it{constructor(e){this.suppressValidationErr=!e,this.options=e}readDocType(e,t){const i=Object.create(null);let n=0;if("O"!==e[t+3]||"C"!==e[t+4]||"T"!==e[t+5]||"Y"!==e[t+6]||"P"!==e[t+7]||"E"!==e[t+8])throw new Error("Invalid Tag instead of DOCTYPE");{t+=9;let s=1,r=!1,o=!1,a="";for(;t<e.length;t++)if("<"!==e[t]||o)if(">"===e[t]){if(o?"-"===e[t-1]&&"-"===e[t-2]&&(o=!1,s--):s--,0===s)break}else"["===e[t]?r=!0:a+=e[t];else{if(r&&st(e,"!ENTITY",t)){let s,r;if(t+=7,[s,r,t]=this.readEntityExp(e,t+1,this.suppressValidationErr),-1===r.indexOf("&")){if(!1!==this.options.enabled&&null!=this.options.maxEntityCount&&n>=this.options.maxEntityCount)throw new Error(`Entity count (${n+1}) exceeds maximum allowed (${this.options.maxEntityCount})`);i[s]=r,n++}}else if(r&&st(e,"!ELEMENT",t)){t+=8;const{index:i}=this.readElementExp(e,t+1);t=i}else if(r&&st(e,"!ATTLIST",t))t+=8;else if(r&&st(e,"!NOTATION",t)){t+=9;const{index:i}=this.readNotationExp(e,t+1,this.suppressValidationErr);t=i}else{if(!st(e,"!--",t))throw new Error("Invalid DOCTYPE");o=!0}s++,a=""}if(0!==s)throw new Error("Unclosed DOCTYPE")}return{entities:i,i:t}}readEntityExp(e,t){const i=t=nt(e,t);for(;t<e.length&&!/\s/.test(e[t])&&'"'!==e[t]&&"'"!==e[t];)t++;let n=e.substring(i,t);if(rt(n),t=nt(e,t),!this.suppressValidationErr){if("SYSTEM"===e.substring(t,t+6).toUpperCase())throw new Error("External entities are not supported");if("%"===e[t])throw new Error("Parameter entities are not supported")}let s="";if([t,s]=this.readIdentifierVal(e,t,"entity"),!1!==this.options.enabled&&null!=this.options.maxEntitySize&&s.length>this.options.maxEntitySize)throw new Error(`Entity "${n}" size (${s.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`);return[n,s,--t]}readNotationExp(e,t){const i=t=nt(e,t);for(;t<e.length&&!/\s/.test(e[t]);)t++;let n=e.substring(i,t);!this.suppressValidationErr&&rt(n),t=nt(e,t);const s=e.substring(t,t+6).toUpperCase();if(!this.suppressValidationErr&&"SYSTEM"!==s&&"PUBLIC"!==s)throw new Error(`Expected SYSTEM or PUBLIC, found "${s}"`);t+=s.length,t=nt(e,t);let r=null,o=null;if("PUBLIC"===s)[t,r]=this.readIdentifierVal(e,t,"publicIdentifier"),'"'!==e[t=nt(e,t)]&&"'"!==e[t]||([t,o]=this.readIdentifierVal(e,t,"systemIdentifier"));else if("SYSTEM"===s&&([t,o]=this.readIdentifierVal(e,t,"systemIdentifier"),!this.suppressValidationErr&&!o))throw new Error("Missing mandatory system identifier for SYSTEM notation");return{notationName:n,publicIdentifier:r,systemIdentifier:o,index:--t}}readIdentifierVal(e,t,i){let n="";const s=e[t];if('"'!==s&&"'"!==s)throw new Error(`Expected quoted string, found "${s}"`);const r=++t;for(;t<e.length&&e[t]!==s;)t++;if(n=e.substring(r,t),e[t]!==s)throw new Error(`Unterminated ${i} value`);return[++t,n]}readElementExp(e,t){const i=t=nt(e,t);for(;t<e.length&&!/\s/.test(e[t]);)t++;let n=e.substring(i,t);if(!this.suppressValidationErr&&!_e(n))throw new Error(`Invalid element name: "${n}"`);let s="";if("E"===e[t=nt(e,t)]&&st(e,"MPTY",t))t+=4;else if("A"===e[t]&&st(e,"NY",t))t+=2;else if("("===e[t]){const i=++t;for(;t<e.length&&")"!==e[t];)t++;if(s=e.substring(i,t),")"!==e[t])throw new Error("Unterminated content model")}else if(!this.suppressValidationErr)throw new Error(`Invalid Element Expression, found "${e[t]}"`);return{elementName:n,contentModel:s.trim(),index:t}}readAttlistExp(e,t){let i=t=nt(e,t);for(;t<e.length&&!/\s/.test(e[t]);)t++;let n=e.substring(i,t);for(rt(n),i=t=nt(e,t);t<e.length&&!/\s/.test(e[t]);)t++;let s=e.substring(i,t);if(!rt(s))throw new Error(`Invalid attribute name: "${s}"`);t=nt(e,t);let r="";if("NOTATION"===e.substring(t,t+8).toUpperCase()){if(r="NOTATION","("!==e[t=nt(e,t+=8)])throw new Error(`Expected '(', found "${e[t]}"`);t++;let i=[];for(;t<e.length&&")"!==e[t];){const n=t;for(;t<e.length&&"|"!==e[t]&&")"!==e[t];)t++;let s=e.substring(n,t);if(s=s.trim(),!rt(s))throw new Error(`Invalid notation name: "${s}"`);i.push(s),"|"===e[t]&&(t++,t=nt(e,t))}if(")"!==e[t])throw new Error("Unterminated list of notations");t++,r+=" ("+i.join("|")+")"}else{const i=t;for(;t<e.length&&!/\s/.test(e[t]);)t++;r+=e.substring(i,t);const n=["CDATA","ID","IDREF","IDREFS","ENTITY","ENTITIES","NMTOKEN","NMTOKENS"];if(!this.suppressValidationErr&&!n.includes(r.toUpperCase()))throw new Error(`Invalid attribute type: "${r}"`)}t=nt(e,t);let o="";return"#REQUIRED"===e.substring(t,t+8).toUpperCase()?(o="#REQUIRED",t+=8):"#IMPLIED"===e.substring(t,t+7).toUpperCase()?(o="#IMPLIED",t+=7):[t,o]=this.readIdentifierVal(e,t,"ATTLIST"),{elementName:n,attributeName:s,attributeType:r,defaultValue:o,index:t}}}const nt=(e,t)=>{for(;t<e.length&&/\s/.test(e[t]);)t++;return t};function st(e,t,i){for(let n=0;n<t.length;n++)if(t[n]!==e[i+n+1])return!1;return!0}function rt(e){if(_e(e))return e;throw new Error(`Invalid entity name ${e}`)}const ot=/^[-+]?0x[a-fA-F0-9]+$/,at=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,lt={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0,infinity:"original"};function ct(e,t={}){if(t=Object.assign({},lt,t),!e||"string"!=typeof e)return e;let i=e.trim();if(0===i.length)return e;if(void 0!==t.skipLike&&t.skipLike.test(i))return e;if("0"===i)return 0;if(t.hex&&ot.test(i))return function(e,t){if(parseInt)return parseInt(e,t);if(Number.parseInt)return Number.parseInt(e,t);if(window&&window.parseInt)return window.parseInt(e,t);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}(i,16);if(isFinite(i)){if(i.includes("e")||i.includes("E"))return function(e,t,i){if(!i.eNotation)return e;const n=t.match(ht);if(n){let s=n[1]||"";const r=-1===n[3].indexOf("e")?"E":"e",o=n[2],a=s?e[o.length+1]===r:e[o.length]===r;return o.length>1&&a?e:(1!==o.length||!n[3].startsWith(`.${r}`)&&n[3][0]!==r)&&o.length>0?i.leadingZeros&&!a?(t=(n[1]||"")+n[3],Number(t)):e:Number(t)}return e}(e,i,t);{const n=at.exec(i);if(n){const s=n[1]||"",r=n[2];let o=function(e){if(e&&-1!==e.indexOf("."))return"."===(e=e.replace(/0+$/,""))?e="0":"."===e[0]?e="0"+e:"."===e[e.length-1]&&(e=e.substring(0,e.length-1)),e;return e}(n[3]);const a=s?"."===e[r.length+1]:"."===e[r.length];if(!t.leadingZeros&&(r.length>1||1===r.length&&!a))return e;{const n=Number(i),a=String(n);if(0===n)return n;if(-1!==a.search(/[eE]/))return t.eNotation?n:e;if(-1!==i.indexOf("."))return"0"===a||a===o||a===`${s}${o}`?n:e;let l=r?o:i;return r?l===a||s+l===a?n:e:l===a||l===s+a?n:e}}return e}}return function(e,t,i){const n=t===1/0;switch(i.infinity.toLowerCase()){case"null":return null;case"infinity":return t;case"string":return n?"Infinity":"-Infinity";default:return e}}(e,Number(i),t)}const ht=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;class ut{constructor(e,t={},i){this.pattern=e,this.separator=t.separator||".",this.segments=this._parse(e),this.data=i,this._hasDeepWildcard=this.segments.some(e=>"deep-wildcard"===e.type),this._hasAttributeCondition=this.segments.some(e=>void 0!==e.attrName),this._hasPositionSelector=this.segments.some(e=>void 0!==e.position)}_parse(e){const t=[];let i=0,n="";for(;i<e.length;)e[i]===this.separator?i+1<e.length&&e[i+1]===this.separator?(n.trim()&&(t.push(this._parseSegment(n.trim())),n=""),t.push({type:"deep-wildcard"}),i+=2):(n.trim()&&t.push(this._parseSegment(n.trim())),n="",i++):(n+=e[i],i++);return n.trim()&&t.push(this._parseSegment(n.trim())),t}_parseSegment(e){const t={type:"tag"};let i=null,n=e;const s=e.match(/^([^\[]+)(\[[^\]]*\])(.*)$/);if(s&&(n=s[1]+s[3],s[2])){const e=s[2].slice(1,-1);e&&(i=e)}let r,o,a=n;if(n.includes("::")){const t=n.indexOf("::");if(r=n.substring(0,t).trim(),a=n.substring(t+2).trim(),!r)throw new Error(`Invalid namespace in pattern: ${e}`)}let l=null;if(a.includes(":")){const e=a.lastIndexOf(":"),t=a.substring(0,e).trim(),i=a.substring(e+1).trim();["first","last","odd","even"].includes(i)||/^nth\(\d+\)$/.test(i)?(o=t,l=i):o=a}else o=a;if(!o)throw new Error(`Invalid segment pattern: ${e}`);if(t.tag=o,r&&(t.namespace=r),i)if(i.includes("=")){const e=i.indexOf("=");t.attrName=i.substring(0,e).trim(),t.attrValue=i.substring(e+1).trim()}else t.attrName=i.trim();if(l){const e=l.match(/^nth\((\d+)\)$/);e?(t.position="nth",t.positionValue=parseInt(e[1],10)):t.position=l}return t}get length(){return this.segments.length}hasDeepWildcard(){return this._hasDeepWildcard}hasAttributeCondition(){return this._hasAttributeCondition}hasPositionSelector(){return this._hasPositionSelector}toString(){return this.pattern}}class dt{constructor(){this._byDepthAndTag=new Map,this._wildcardByDepth=new Map,this._deepWildcards=[],this._patterns=new Set,this._sealed=!1}add(e){if(this._sealed)throw new TypeError("ExpressionSet is sealed. Create a new ExpressionSet to add more expressions.");if(this._patterns.has(e.pattern))return this;if(this._patterns.add(e.pattern),e.hasDeepWildcard())return this._deepWildcards.push(e),this;const t=e.length,i=e.segments[e.segments.length-1],n=i?.tag;if(n&&"*"!==n){const i=`${t}:${n}`;this._byDepthAndTag.has(i)||this._byDepthAndTag.set(i,[]),this._byDepthAndTag.get(i).push(e)}else this._wildcardByDepth.has(t)||this._wildcardByDepth.set(t,[]),this._wildcardByDepth.get(t).push(e);return this}addAll(e){for(const t of e)this.add(t);return this}has(e){return this._patterns.has(e.pattern)}get size(){return this._patterns.size}seal(){return this._sealed=!0,this}get isSealed(){return this._sealed}matchesAny(e){return null!==this.findMatch(e)}findMatch(e){const t=e.getDepth(),i=`${t}:${e.getCurrentTag()}`,n=this._byDepthAndTag.get(i);if(n)for(let t=0;t<n.length;t++)if(e.matches(n[t]))return n[t];const s=this._wildcardByDepth.get(t);if(s)for(let t=0;t<s.length;t++)if(e.matches(s[t]))return s[t];for(let t=0;t<this._deepWildcards.length;t++)if(e.matches(this._deepWildcards[t]))return this._deepWildcards[t];return null}}class pt{constructor(e){this._matcher=e}get separator(){return this._matcher.separator}getCurrentTag(){const e=this._matcher.path;return e.length>0?e[e.length-1].tag:void 0}getCurrentNamespace(){const e=this._matcher.path;return e.length>0?e[e.length-1].namespace:void 0}getAttrValue(e){const t=this._matcher.path;if(0!==t.length)return t[t.length-1].values?.[e]}hasAttr(e){const t=this._matcher.path;if(0===t.length)return!1;const i=t[t.length-1];return void 0!==i.values&&e in i.values}getPosition(){const e=this._matcher.path;return 0===e.length?-1:e[e.length-1].position??0}getCounter(){const e=this._matcher.path;return 0===e.length?-1:e[e.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this._matcher.path.length}toString(e,t=!0){return this._matcher.toString(e,t)}toArray(){return this._matcher.path.map(e=>e.tag)}matches(e){return this._matcher.matches(e)}matchesAny(e){return e.matchesAny(this._matcher)}}class ft{constructor(e={}){this.separator=e.separator||".",this.path=[],this.siblingStacks=[],this._pathStringCache=null,this._view=new pt(this)}push(e,t=null,i=null){this._pathStringCache=null,this.path.length>0&&(this.path[this.path.length-1].values=void 0);const n=this.path.length;this.siblingStacks[n]||(this.siblingStacks[n]=new Map);const s=this.siblingStacks[n],r=i?`${i}:${e}`:e,o=s.get(r)||0;let a=0;for(const e of s.values())a+=e;s.set(r,o+1);const l={tag:e,position:a,counter:o};null!=i&&(l.namespace=i),null!=t&&(l.values=t),this.path.push(l)}pop(){if(0===this.path.length)return;this._pathStringCache=null;const e=this.path.pop();return this.siblingStacks.length>this.path.length+1&&(this.siblingStacks.length=this.path.length+1),e}updateCurrent(e){if(this.path.length>0){const t=this.path[this.path.length-1];null!=e&&(t.values=e)}}getCurrentTag(){return this.path.length>0?this.path[this.path.length-1].tag:void 0}getCurrentNamespace(){return this.path.length>0?this.path[this.path.length-1].namespace:void 0}getAttrValue(e){if(0!==this.path.length)return this.path[this.path.length-1].values?.[e]}hasAttr(e){if(0===this.path.length)return!1;const t=this.path[this.path.length-1];return void 0!==t.values&&e in t.values}getPosition(){return 0===this.path.length?-1:this.path[this.path.length-1].position??0}getCounter(){return 0===this.path.length?-1:this.path[this.path.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this.path.length}toString(e,t=!0){const i=e||this.separator;if(i===this.separator&&!0===t){if(null!==this._pathStringCache)return this._pathStringCache;const e=this.path.map(e=>e.namespace?`${e.namespace}:${e.tag}`:e.tag).join(i);return this._pathStringCache=e,e}return this.path.map(e=>t&&e.namespace?`${e.namespace}:${e.tag}`:e.tag).join(i)}toArray(){return this.path.map(e=>e.tag)}reset(){this._pathStringCache=null,this.path=[],this.siblingStacks=[]}matches(e){const t=e.segments;return 0!==t.length&&(e.hasDeepWildcard()?this._matchWithDeepWildcard(t):this._matchSimple(t))}_matchSimple(e){if(this.path.length!==e.length)return!1;for(let t=0;t<e.length;t++)if(!this._matchSegment(e[t],this.path[t],t===this.path.length-1))return!1;return!0}_matchWithDeepWildcard(e){let t=this.path.length-1,i=e.length-1;for(;i>=0&&t>=0;){const n=e[i];if("deep-wildcard"===n.type){if(i--,i<0)return!0;const n=e[i];let s=!1;for(let e=t;e>=0;e--)if(this._matchSegment(n,this.path[e],e===this.path.length-1)){t=e-1,i--,s=!0;break}if(!s)return!1}else{if(!this._matchSegment(n,this.path[t],t===this.path.length-1))return!1;t--,i--}}return i<0}_matchSegment(e,t,i){if("*"!==e.tag&&e.tag!==t.tag)return!1;if(void 0!==e.namespace&&"*"!==e.namespace&&e.namespace!==t.namespace)return!1;if(void 0!==e.attrName){if(!i)return!1;if(!t.values||!(e.attrName in t.values))return!1;if(void 0!==e.attrValue&&String(t.values[e.attrName])!==String(e.attrValue))return!1}if(void 0!==e.position){if(!i)return!1;const n=t.counter??0;if("first"===e.position&&0!==n)return!1;if("odd"===e.position&&n%2!=1)return!1;if("even"===e.position&&n%2!=0)return!1;if("nth"===e.position&&n!==e.positionValue)return!1}return!0}matchesAny(e){return e.matchesAny(this)}snapshot(){return{path:this.path.map(e=>({...e})),siblingStacks:this.siblingStacks.map(e=>new Map(e))}}restore(e){this._pathStringCache=null,this.path=e.path.map(e=>({...e})),this.siblingStacks=e.siblingStacks.map(e=>new Map(e))}readOnly(){return this._view}}function mt(e,t){if(!e)return{};const i=t.attributesGroupName?e[t.attributesGroupName]:e;if(!i)return{};const n={};for(const e in i)if(e.startsWith(t.attributeNamePrefix)){n[e.substring(t.attributeNamePrefix.length)]=i[e]}else n[e]=i[e];return n}function gt(e){if(!e||"string"!=typeof e)return;const t=e.indexOf(":");if(-1!==t&&t>0){const i=e.substring(0,t);if("xmlns"!==i)return i}}class wt{constructor(e,t){var i;this.options=e,this.currentNode=null,this.tagsNodeStack=[],this.parseXml=xt,this.parseTextData=yt,this.resolveNameSpace=_t,this.buildAttributesMap=vt,this.isItStopNode=Tt,this.replaceEntitiesValue=St,this.readStopNodeData=It,this.saveTextToParentTag=At,this.addChild=Ct,this.ignoreAttributesFn="function"==typeof(i=this.options.ignoreAttributes)?i:Array.isArray(i)?e=>{for(const t of i){if("string"==typeof t&&e===t)return!0;if(t instanceof RegExp&&t.test(e))return!0}}:()=>!1,this.entityExpansionCount=0,this.currentExpandedLength=0;let n={...Le};this.options.entityDecoder?this.entityDecoder=this.options.entityDecoder:("object"==typeof this.options.htmlEntities?n=this.options.htmlEntities:!0===this.options.htmlEntities&&(n={...Fe,...Ne}),this.entityDecoder=new qe({namedEntities:{...n,...t},numericAllowed:this.options.htmlEntities,limit:{maxTotalExpansions:this.options.processEntities.maxTotalExpansions,maxExpandedLength:this.options.processEntities.maxExpandedLength,applyLimitsTo:this.options.processEntities.appliesTo}})),this.matcher=new ft,this.readonlyMatcher=this.matcher.readOnly(),this.isCurrentNodeStopNode=!1,this.stopNodeExpressionsSet=new dt;const s=this.options.stopNodes;if(s&&s.length>0){for(let e=0;e<s.length;e++){const t=s[e];"string"==typeof t?this.stopNodeExpressionsSet.add(new ut(t)):t instanceof ut&&this.stopNodeExpressionsSet.add(t)}this.stopNodeExpressionsSet.seal()}}}function yt(e,t,i,n,s,r,o){const a=this.options;if(void 0!==e&&(a.trimValues&&!n&&(e=e.trim()),e.length>0)){o||(e=this.replaceEntitiesValue(e,t,i));const n=a.jPath?i.toString():i,l=a.tagValueProcessor(t,e,n,s,r);if(null==l)return e;if(typeof l!=typeof e||l!==e)return l;if(a.trimValues)return zt(e,a.parseTagValue,a.numberParseOptions);return e.trim()===e?zt(e,a.parseTagValue,a.numberParseOptions):e}}function _t(e){if(this.options.removeNSPrefix){const t=e.split(":"),i="/"===e.charAt(0)?"/":"";if("xmlns"===t[0])return"";2===t.length&&(e=i+t[1])}return e}const bt=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function vt(e,t,i,n=!1){const s=this.options;if(!0===n||!0!==s.ignoreAttributes&&"string"==typeof e){const n=ye(e,bt),r=n.length,o={},a=new Array(r);let l=!1;const c={};for(let e=0;e<r;e++){const t=this.resolveNameSpace(n[e][1]),r=n[e][4];if(t.length&&void 0!==r){let n=r;s.trimValues&&(n=n.trim()),n=this.replaceEntitiesValue(n,i,this.readonlyMatcher),a[e]=n,c[t]=n,l=!0}}l&&"object"==typeof t&&t.updateCurrent&&t.updateCurrent(c);const h=s.jPath?t.toString():this.readonlyMatcher;let u=!1;for(let e=0;e<r;e++){const t=this.resolveNameSpace(n[e][1]);if(this.ignoreAttributesFn(t,h))continue;let i=s.attributeNamePrefix+t;if(t.length)if(s.transformAttributeName&&(i=s.transformAttributeName(i)),i=kt(i,s),void 0!==n[e][4]){const n=a[e],r=s.attributeValueProcessor(t,n,h);o[i]=null==r?n:typeof r!=typeof n||r!==n?r:zt(n,s.parseAttributeValue,s.numberParseOptions),u=!0}else s.allowBooleanAttributes&&(o[i]=!0,u=!0)}if(!u)return;if(s.attributesGroupName&&!s.preserveOrder){const e={};return e[s.attributesGroupName]=o,e}return o}}const xt=function(e){e=e.replace(/\r\n?/g,"\n");const t=new tt("!xml");let i=t,n="";this.matcher.reset(),this.entityDecoder.reset(),this.entityExpansionCount=0,this.currentExpandedLength=0;const s=this.options,r=new it(s.processEntities),o=e.length;for(let a=0;a<o;a++){if("<"===e[a]){const l=e.charCodeAt(a+1);if(47===l){const t=Pt(e,">",a,"Closing Tag is not closed.");let r=e.substring(a+2,t).trim();if(s.removeNSPrefix){const e=r.indexOf(":");-1!==e&&(r=r.substr(e+1))}r=Dt(s.transformTagName,r,"",s).tagName,i&&(n=this.saveTextToParentTag(n,i,this.readonlyMatcher));const o=this.matcher.getCurrentTag();if(r&&s.unpairedTagsSet.has(r))throw new Error(`Unpaired tag can not be used as closing tag: </${r}>`);o&&s.unpairedTagsSet.has(o)&&(this.matcher.pop(),this.tagsNodeStack.pop()),this.matcher.pop(),this.isCurrentNodeStopNode=!1,i=this.tagsNodeStack.pop(),n="",a=t}else if(63===l){let t=Mt(e,a,!1,"?>");if(!t)throw new Error("Pi Tag is not closed.");n=this.saveTextToParentTag(n,i,this.readonlyMatcher);const r=this.buildAttributesMap(t.tagExp,this.matcher,t.tagName,!0);if(r){const e=r[this.options.attributeNamePrefix+"version"];this.entityDecoder.setXmlVersion(Number(e)||1)}if(s.ignoreDeclaration&&"?xml"===t.tagName||s.ignorePiTags);else{const e=new tt(t.tagName);e.add(s.textNodeName,""),t.tagName!==t.tagExp&&t.attrExpPresent&&!0!==s.ignoreAttributes&&(e[":@"]=r),this.addChild(i,e,this.readonlyMatcher,a)}a=t.closeIndex+1}else if(33===l&&45===e.charCodeAt(a+2)&&45===e.charCodeAt(a+3)){const t=Pt(e,"--\x3e",a+4,"Comment is not closed.");if(s.commentPropName){const r=e.substring(a+4,t-2);n=this.saveTextToParentTag(n,i,this.readonlyMatcher),i.add(s.commentPropName,[{[s.textNodeName]:r}])}a=t}else if(33===l&&68===e.charCodeAt(a+2)){const t=r.readDocType(e,a);this.entityDecoder.addInputEntities(t.entities),a=t.i}else if(33===l&&91===e.charCodeAt(a+2)){const t=Pt(e,"]]>",a,"CDATA is not closed.")-2,r=e.substring(a+9,t);n=this.saveTextToParentTag(n,i,this.readonlyMatcher);let o=this.parseTextData(r,i.tagname,this.readonlyMatcher,!0,!1,!0,!0);null==o&&(o=""),s.cdataPropName?i.add(s.cdataPropName,[{[s.textNodeName]:r}]):i.add(s.textNodeName,o),a=t+2}else{let r=Mt(e,a,s.removeNSPrefix);if(!r){const t=e.substring(Math.max(0,a-50),Math.min(o,a+50));throw new Error(`readTagExp returned undefined at position ${a}. Context: "${t}"`)}let l=r.tagName;const c=r.rawTagName;let h=r.tagExp,u=r.attrExpPresent,d=r.closeIndex;if(({tagName:l,tagExp:h}=Dt(s.transformTagName,l,h,s)),s.strictReservedNames&&(l===s.commentPropName||l===s.cdataPropName||l===s.textNodeName||l===s.attributesGroupName))throw new Error(`Invalid tag name: ${l}`);i&&n&&"!xml"!==i.tagname&&(n=this.saveTextToParentTag(n,i,this.readonlyMatcher,!1));const p=i;p&&s.unpairedTagsSet.has(p.tagname)&&(i=this.tagsNodeStack.pop(),this.matcher.pop());let f=!1;h.length>0&&h.lastIndexOf("/")===h.length-1&&(f=!0,"/"===l[l.length-1]?(l=l.substr(0,l.length-1),h=l):h=h.substr(0,h.length-1),u=l!==h);let m,g=null;m=gt(c),l!==t.tagname&&this.matcher.push(l,{},m),l!==h&&u&&(g=this.buildAttributesMap(h,this.matcher,l),g&&mt(g,s)),l!==t.tagname&&(this.isCurrentNodeStopNode=this.isItStopNode());const w=a;if(this.isCurrentNodeStopNode){let t="";if(f)a=r.closeIndex;else if(s.unpairedTagsSet.has(l))a=r.closeIndex;else{const i=this.readStopNodeData(e,c,d+1);if(!i)throw new Error(`Unexpected end of ${c}`);a=i.i,t=i.tagContent}const n=new tt(l);g&&(n[":@"]=g),n.add(s.textNodeName,t),this.matcher.pop(),this.isCurrentNodeStopNode=!1,this.addChild(i,n,this.readonlyMatcher,w)}else{if(f){({tagName:l,tagExp:h}=Dt(s.transformTagName,l,h,s));const e=new tt(l);g&&(e[":@"]=g),this.addChild(i,e,this.readonlyMatcher,w),this.matcher.pop(),this.isCurrentNodeStopNode=!1}else{if(s.unpairedTagsSet.has(l)){const e=new tt(l);g&&(e[":@"]=g),this.addChild(i,e,this.readonlyMatcher,w),this.matcher.pop(),this.isCurrentNodeStopNode=!1,a=r.closeIndex;continue}{const e=new tt(l);if(this.tagsNodeStack.length>s.maxNestedTags)throw new Error("Maximum nested tags exceeded");this.tagsNodeStack.push(i),g&&(e[":@"]=g),this.addChild(i,e,this.readonlyMatcher,w),i=e}}n="",a=d}}}else n+=e[a]}return t.child};function Ct(e,t,i,n){this.options.captureMetaData||(n=void 0);const s=this.options.jPath?i.toString():i,r=this.options.updateTag(t.tagname,s,t[":@"]);!1===r||("string"==typeof r?(t.tagname=r,e.addChild(t,n)):e.addChild(t,n))}function St(e,t,i){const n=this.options.processEntities;if(!n||!n.enabled)return e;if(n.allowedTags){const s=this.options.jPath?i.toString():i;if(!(Array.isArray(n.allowedTags)?n.allowedTags.includes(t):n.allowedTags(t,s)))return e}if(n.tagFilter){const s=this.options.jPath?i.toString():i;if(!n.tagFilter(t,s))return e}return this.entityDecoder.decode(e)}function At(e,t,i,n){return e&&(void 0===n&&(n=0===t.child.length),void 0!==(e=this.parseTextData(e,t.tagname,i,!1,!!t[":@"]&&0!==Object.keys(t[":@"]).length,n))&&""!==e&&t.add(this.options.textNodeName,e),e=""),e}function Tt(){return 0!==this.stopNodeExpressionsSet.size&&this.matcher.matchesAny(this.stopNodeExpressionsSet)}function Pt(e,t,i,n){const s=e.indexOf(t,i);if(-1===s)throw new Error(n);return s+t.length-1}function Et(e,t,i,n){const s=e.indexOf(t,i);if(-1===s)throw new Error(n);return s}function Mt(e,t,i,n=">"){const s=function(e,t,i=">"){let n=0;const s=e.length,r=i.charCodeAt(0),o=i.length>1?i.charCodeAt(1):-1;let a="",l=t;for(let i=t;i<s;i++){const t=e.charCodeAt(i);if(n)t===n&&(n=0);else if(34===t||39===t)n=t;else if(t===r){if(-1===o)return a+=e.substring(l,i),{data:a,index:i};if(e.charCodeAt(i+1)===o)return a+=e.substring(l,i),{data:a,index:i}}else 9!==t||n||(a+=e.substring(l,i)+" ",l=i+1)}}(e,t+1,n);if(!s)return;let r=s.data;const o=s.index,a=r.search(/\s/);let l=r,c=!0;-1!==a&&(l=r.substring(0,a),r=r.substring(a+1).trimStart());const h=l;if(i){const e=l.indexOf(":");-1!==e&&(l=l.substr(e+1),c=l!==s.data.substr(e+1))}return{tagName:l,tagExp:r,closeIndex:o,attrExpPresent:c,rawTagName:h}}function It(e,t,i){const n=i;let s=1;const r=e.length;for(;i<r;i++)if("<"===e[i]){const r=e.charCodeAt(i+1);if(47===r){const r=Et(e,">",i,`${t} is not closed`);if(e.substring(i+2,r).trim()===t&&(s--,0===s))return{tagContent:e.substring(n,i),i:r};i=r}else if(63===r){i=Pt(e,"?>",i+1,"StopNode is not closed.")}else if(33===r&&45===e.charCodeAt(i+2)&&45===e.charCodeAt(i+3)){i=Pt(e,"--\x3e",i+3,"StopNode is not closed.")}else if(33===r&&91===e.charCodeAt(i+2)){i=Pt(e,"]]>",i,"StopNode is not closed.")-2}else{const n=Mt(e,i,">");if(n){(n&&n.tagName)===t&&"/"!==n.tagExp[n.tagExp.length-1]&&s++,i=n.closeIndex}}}}function zt(e,t,i){if(t&&"string"==typeof e){const t=e.trim();return"true"===t||"false"!==t&&ct(e,i)}return void 0!==e?e:""}function Dt(e,t,i,n){if(e){const n=e(t);i===t&&(i=n),t=n}return{tagName:t=kt(t,n),tagExp:i}}function kt(e,t){if(ve.includes(e))throw new Error(`[SECURITY] Invalid name: "${e}" is a reserved JavaScript keyword that could cause prototype pollution`);return be.includes(e)?t.onDangerousProperty(e):e}const Bt=tt.getMetaDataSymbol();function Ot(e,t){if(!e||"object"!=typeof e)return{};if(!t)return e;const i={};for(const n in e)if(n.startsWith(t)){i[n.substring(t.length)]=e[n]}else i[n]=e[n];return i}function Vt(e,t,i,n){return Nt(e,t,i,n)}function Nt(e,t,i,n){let s;const r={};for(let o=0;o<e.length;o++){const a=e[o],l=Lt(a);if(void 0!==l&&l!==t.textNodeName){const e=Ot(a[":@"]||{},t.attributeNamePrefix);i.push(l,e)}if(l===t.textNodeName)void 0===s?s=a[l]:s+=""+a[l];else{if(void 0===l)continue;if(a[l]){let e=Nt(a[l],t,i,n);const s=Rt(e,t);if(a[":@"]?Ft(e,a[":@"],n,t):1!==Object.keys(e).length||void 0===e[t.textNodeName]||t.alwaysCreateTextNode?0===Object.keys(e).length&&(t.alwaysCreateTextNode?e[t.textNodeName]="":e=""):e=e[t.textNodeName],void 0!==a[Bt]&&"object"==typeof e&&null!==e&&(e[Bt]=a[Bt]),void 0!==r[l]&&Object.prototype.hasOwnProperty.call(r,l))Array.isArray(r[l])||(r[l]=[r[l]]),r[l].push(e);else{const i=t.jPath?n.toString():n;t.isArray(l,i,s)?r[l]=[e]:r[l]=e}void 0!==l&&l!==t.textNodeName&&i.pop()}}}return"string"==typeof s?s.length>0&&(r[t.textNodeName]=s):void 0!==s&&(r[t.textNodeName]=s),r}function Lt(e){const t=Object.keys(e);for(let e=0;e<t.length;e++){const i=t[e];if(":@"!==i)return i}}function Ft(e,t,i,n){if(t){const s=Object.keys(t),r=s.length;for(let o=0;o<r;o++){const r=s[o],a=r.startsWith(n.attributeNamePrefix)?r.substring(n.attributeNamePrefix.length):r,l=n.jPath?i.toString()+"."+a:i;n.isArray(r,l,!0,!0)?e[r]=[t[r]]:e[r]=t[r]}}}function Rt(e,t){const{textNodeName:i}=t,n=Object.keys(e).length;return 0===n||!(1!==n||!e[i]&&"boolean"!=typeof e[i]&&0!==e[i])}class Ut{constructor(e){this.externalEntities={},this.options=Je(e)}parse(e,t){if("string"!=typeof e&&e.toString)e=e.toString();else if("string"!=typeof e)throw new Error("XML data is accepted in String or Bytes[] form.");if(t){!0===t&&(t={});const i=function(e,t){t=Object.assign({},xe,t);const i=[];let n=!1,s=!1;"\ufeff"===e[0]&&(e=e.substr(1));for(let r=0;r<e.length;r++)if("<"===e[r]&&"?"===e[r+1]){if(r+=2,r=Se(e,r),r.err)return r}else{if("<"!==e[r]){if(Ce(e[r]))continue;return De("InvalidChar","char '"+e[r]+"' is not expected.",Oe(e,r))}{let o=r;if(r++,"!"===e[r]){r=Ae(e,r);continue}{let a=!1;"/"===e[r]&&(a=!0,r++);let l="";for(;r<e.length&&">"!==e[r]&&" "!==e[r]&&"\t"!==e[r]&&"\n"!==e[r]&&"\r"!==e[r];r++)l+=e[r];if(l=l.trim(),"/"===l[l.length-1]&&(l=l.substring(0,l.length-1),r--),!Be(l)){let t;return t=0===l.trim().length?"Invalid space after '<'.":"Tag '"+l+"' is an invalid name.",De("InvalidTag",t,Oe(e,r))}const c=Ee(e,r);if(!1===c)return De("InvalidAttr","Attributes for '"+l+"' have open quote.",Oe(e,r));let h=c.value;if(r=c.index,"/"===h[h.length-1]){const i=r-h.length;h=h.substring(0,h.length-1);const s=Ie(h,t);if(!0!==s)return De(s.err.code,s.err.msg,Oe(e,i+s.err.line));n=!0}else if(a){if(!c.tagClosed)return De("InvalidTag","Closing tag '"+l+"' doesn't have proper closing.",Oe(e,r));if(h.trim().length>0)return De("InvalidTag","Closing tag '"+l+"' can't have attributes or invalid starting.",Oe(e,o));if(0===i.length)return De("InvalidTag","Closing tag '"+l+"' has not been opened.",Oe(e,o));{const t=i.pop();if(l!==t.tagName){let i=Oe(e,t.tagStartPos);return De("InvalidTag","Expected closing tag '"+t.tagName+"' (opened in line "+i.line+", col "+i.col+") instead of closing tag '"+l+"'.",Oe(e,o))}0==i.length&&(s=!0)}}else{const a=Ie(h,t);if(!0!==a)return De(a.err.code,a.err.msg,Oe(e,r-h.length+a.err.line));if(!0===s)return De("InvalidXml","Multiple possible root nodes found.",Oe(e,r));-1!==t.unpairedTags.indexOf(l)||i.push({tagName:l,tagStartPos:o}),n=!0}for(r++;r<e.length;r++)if("<"===e[r]){if("!"===e[r+1]){r++,r=Ae(e,r);continue}if("?"!==e[r+1])break;if(r=Se(e,++r),r.err)return r}else if("&"===e[r]){const t=ze(e,r);if(-1==t)return De("InvalidChar","char '&' is not expected.",Oe(e,r));r=t}else if(!0===s&&!Ce(e[r]))return De("InvalidXml","Extra text at the end",Oe(e,r));"<"===e[r]&&r--}}}return n?1==i.length?De("InvalidTag","Unclosed tag '"+i[0].tagName+"'.",Oe(e,i[0].tagStartPos)):!(i.length>0)||De("InvalidXml","Invalid '"+JSON.stringify(i.map(e=>e.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):De("InvalidXml","Start tag expected.",1)}(e,t);if(!0!==i)throw Error(`${i.err.msg}:${i.err.line}:${i.err.col}`)}const i=new wt(this.options,this.externalEntities),n=i.parseXml(e);return this.options.preserveOrder||void 0===n?n:Vt(n,this.options,i.matcher,i.readonlyMatcher)}addEntity(e,t){if(-1!==t.indexOf("&"))throw new Error("Entity value can't have '&'");if(-1!==e.indexOf("&")||-1!==e.indexOf(";"))throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if("&"===t)throw new Error("An entity with value '&' is not permitted");this.externalEntities[e]=t}static getMetaDataSymbol(){return tt.getMetaDataSymbol()}}function jt(e,t){let i="";t.format&&t.indentBy.length>0&&(i="\n");const n=[];if(t.stopNodes&&Array.isArray(t.stopNodes))for(let e=0;e<t.stopNodes.length;e++){const i=t.stopNodes[e];"string"==typeof i?n.push(new ut(i)):i instanceof ut&&n.push(i)}return $t(e,t,i,new ft,n)}function $t(e,t,i,n,s){let r="",o=!1;if(t.maxNestedTags&&n.getDepth()>t.maxNestedTags)throw new Error("Maximum nested tags exceeded");if(!Array.isArray(e)){if(null!=e){let i=e.toString();return i=Xt(i,t),i}return""}for(let a=0;a<e.length;a++){const l=e[a],c=Zt(l);if(void 0===c)continue;const h=Wt(l[":@"],t);n.push(c,h);const u=Yt(n,s);if(c===t.textNodeName){let e=l[c];u||(e=t.tagValueProcessor(c,e),e=Xt(e,t)),o&&(r+=i),r+=e,o=!1,n.pop();continue}if(c===t.cdataPropName){o&&(r+=i);const e=l[c][0][t.textNodeName];r+=`<![CDATA[${String(e).replace(/\]\]>/g,"]]]]><![CDATA[>")}]]>`,o=!1,n.pop();continue}if(c===t.commentPropName){const e=l[c][0][t.textNodeName];r+=i+`\x3c!--${String(e).replace(/--/g,"- -").replace(/-$/,"- ")}--\x3e`,o=!0,n.pop();continue}if("?"===c[0]){const e=qt(l[":@"],t,u),s="?xml"===c?"":i;let a=l[c][0][t.textNodeName];a=0!==a.length?" "+a:"",r+=s+`<${c}${a}${e}?>`,o=!0,n.pop();continue}let d=i;""!==d&&(d+=t.indentBy);const p=i+`<${c}${qt(l[":@"],t,u)}`;let f;f=u?Ht(l[c],t):$t(l[c],t,d,n,s),-1!==t.unpairedTags.indexOf(c)?t.suppressUnpairedNode?r+=p+">":r+=p+"/>":f&&0!==f.length||!t.suppressEmptyNode?f&&f.endsWith(">")?r+=p+`>${f}${i}</${c}>`:(r+=p+">",f&&""!==i&&(f.includes("/>")||f.includes("</"))?r+=i+t.indentBy+f+i:r+=f,r+=`</${c}>`):r+=p+"/>",o=!0,n.pop()}return r}function Wt(e,t){if(!e||t.ignoreAttributes)return null;const i={};let n=!1;for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;i[s.startsWith(t.attributeNamePrefix)?s.substr(t.attributeNamePrefix.length):s]=e[s],n=!0}return n?i:null}function Ht(e,t){if(!Array.isArray(e))return null!=e?e.toString():"";let i="";for(let n=0;n<e.length;n++){const s=e[n],r=Zt(s);if(r===t.textNodeName)i+=s[r];else if(r===t.cdataPropName)i+=s[r][0][t.textNodeName];else if(r===t.commentPropName)i+=s[r][0][t.textNodeName];else{if(r&&"?"===r[0])continue;if(r){const e=Gt(s[":@"],t),n=Ht(s[r],t);n&&0!==n.length?i+=`<${r}${e}>${n}</${r}>`:i+=`<${r}${e}/>`}}}return i}function Gt(e,t){let i="";if(e&&!t.ignoreAttributes)for(let n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;let s=e[n];!0===s&&t.suppressBooleanAttributes?i+=` ${n.substr(t.attributeNamePrefix.length)}`:i+=` ${n.substr(t.attributeNamePrefix.length)}="${s}"`}return i}function Zt(e){const t=Object.keys(e);for(let i=0;i<t.length;i++){const n=t[i];if(Object.prototype.hasOwnProperty.call(e,n)&&":@"!==n)return n}}function qt(e,t,i){let n="";if(e&&!t.ignoreAttributes)for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let r;i?r=e[s]:(r=t.attributeValueProcessor(s,e[s]),r=Xt(r,t)),!0===r&&t.suppressBooleanAttributes?n+=` ${s.substr(t.attributeNamePrefix.length)}`:n+=` ${s.substr(t.attributeNamePrefix.length)}="${r}"`}return n}function Yt(e,t){if(!t||0===t.length)return!1;for(let i=0;i<t.length;i++)if(e.matches(t[i]))return!0;return!1}function Xt(e,t){if(e&&e.length>0&&t.processEntities)for(let i=0;i<t.entities.length;i++){const n=t.entities[i];e=e.replace(n.regex,n.val)}return e}const Kt={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(e,t){return t},attributeValueProcessor:function(e,t){return t},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&amp;"},{regex:new RegExp(">","g"),val:"&gt;"},{regex:new RegExp("<","g"),val:"&lt;"},{regex:new RegExp("'","g"),val:"&apos;"},{regex:new RegExp('"',"g"),val:"&quot;"}],processEntities:!0,stopNodes:[],oneListGroup:!1,maxNestedTags:100,jPath:!0};function Qt(e){if(this.options=Object.assign({},Kt,e),this.options.stopNodes&&Array.isArray(this.options.stopNodes)&&(this.options.stopNodes=this.options.stopNodes.map(e=>"string"==typeof e&&e.startsWith("*.")?".."+e.substring(2):e)),this.stopNodeExpressions=[],this.options.stopNodes&&Array.isArray(this.options.stopNodes))for(let e=0;e<this.options.stopNodes.length;e++){const t=this.options.stopNodes[e];"string"==typeof t?this.stopNodeExpressions.push(new ut(t)):t instanceof ut&&this.stopNodeExpressions.push(t)}var t;!0===this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn="function"==typeof(t=this.options.ignoreAttributes)?t:Array.isArray(t)?e=>{for(const i of t){if("string"==typeof i&&e===i)return!0;if(i instanceof RegExp&&i.test(e))return!0}}:()=>!1,this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=ti),this.processTextOrObjNode=Jt,this.options.format?(this.indentate=ei,this.tagEndChar=">\n",this.newLine="\n"):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}function Jt(e,t,i,n){const s=this.extractAttributes(e);n.push(t,s);if(this.checkStopNode(n)){const s=this.buildRawContent(e),r=this.buildAttributesForStopNode(e);return n.pop(),this.buildObjectNode(s,t,r,i)}const r=this.j2x(e,i+1,n);return n.pop(),void 0!==e[this.options.textNodeName]&&1===Object.keys(e).length?this.buildTextValNode(e[this.options.textNodeName],t,r.attrStr,i,n):this.buildObjectNode(r.val,t,r.attrStr,i)}function ei(e){return this.options.indentBy.repeat(e)}function ti(e){return!(!e.startsWith(this.options.attributeNamePrefix)||e===this.options.textNodeName)&&e.substr(this.attrPrefixLen)}Qt.prototype.build=function(e){if(this.options.preserveOrder)return jt(e,this.options);{Array.isArray(e)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(e={[this.options.arrayNodeName]:e});const t=new ft;return this.j2x(e,0,t).val}},Qt.prototype.j2x=function(e,t,i){let n="",s="";if(this.options.maxNestedTags&&i.getDepth()>=this.options.maxNestedTags)throw new Error("Maximum nested tags exceeded");const r=this.options.jPath?i.toString():i,o=this.checkStopNode(i);for(let a in e)if(Object.prototype.hasOwnProperty.call(e,a))if(void 0===e[a])this.isAttribute(a)&&(s+="");else if(null===e[a])this.isAttribute(a)||a===this.options.cdataPropName?s+="":"?"===a[0]?s+=this.indentate(t)+"<"+a+"?"+this.tagEndChar:s+=this.indentate(t)+"<"+a+"/"+this.tagEndChar;else if(e[a]instanceof Date)s+=this.buildTextValNode(e[a],a,"",t,i);else if("object"!=typeof e[a]){const l=this.isAttribute(a);if(l&&!this.ignoreAttributesFn(l,r))n+=this.buildAttrPairStr(l,""+e[a],o);else if(!l)if(a===this.options.textNodeName){let t=this.options.tagValueProcessor(a,""+e[a]);s+=this.replaceEntitiesValue(t)}else{i.push(a);const n=this.checkStopNode(i);if(i.pop(),n){const i=""+e[a];s+=""===i?this.indentate(t)+"<"+a+this.closeTag(a)+this.tagEndChar:this.indentate(t)+"<"+a+">"+i+"</"+a+this.tagEndChar}else s+=this.buildTextValNode(e[a],a,"",t,i)}}else if(Array.isArray(e[a])){const n=e[a].length;let r="",o="";for(let l=0;l<n;l++){const n=e[a][l];if(void 0===n);else if(null===n)"?"===a[0]?s+=this.indentate(t)+"<"+a+"?"+this.tagEndChar:s+=this.indentate(t)+"<"+a+"/"+this.tagEndChar;else if("object"==typeof n)if(this.options.oneListGroup){i.push(a);const e=this.j2x(n,t+1,i);i.pop(),r+=e.val,this.options.attributesGroupName&&n.hasOwnProperty(this.options.attributesGroupName)&&(o+=e.attrStr)}else r+=this.processTextOrObjNode(n,a,t,i);else if(this.options.oneListGroup){let e=this.options.tagValueProcessor(a,n);e=this.replaceEntitiesValue(e),r+=e}else{i.push(a);const e=this.checkStopNode(i);if(i.pop(),e){const e=""+n;r+=""===e?this.indentate(t)+"<"+a+this.closeTag(a)+this.tagEndChar:this.indentate(t)+"<"+a+">"+e+"</"+a+this.tagEndChar}else r+=this.buildTextValNode(n,a,"",t,i)}}this.options.oneListGroup&&(r=this.buildObjectNode(r,a,o,t)),s+=r}else if(this.options.attributesGroupName&&a===this.options.attributesGroupName){const t=Object.keys(e[a]),i=t.length;for(let s=0;s<i;s++)n+=this.buildAttrPairStr(t[s],""+e[a][t[s]],o)}else s+=this.processTextOrObjNode(e[a],a,t,i);return{attrStr:n,val:s}},Qt.prototype.buildAttrPairStr=function(e,t,i){return i||(t=this.options.attributeValueProcessor(e,""+t),t=this.replaceEntitiesValue(t)),this.options.suppressBooleanAttributes&&"true"===t?" "+e:" "+e+'="'+t+'"'},Qt.prototype.extractAttributes=function(e){if(!e||"object"!=typeof e)return null;const t={};let i=!1;if(this.options.attributesGroupName&&e[this.options.attributesGroupName]){const n=e[this.options.attributesGroupName];for(let e in n){if(!Object.prototype.hasOwnProperty.call(n,e))continue;t[e.startsWith(this.options.attributeNamePrefix)?e.substring(this.options.attributeNamePrefix.length):e]=n[e],i=!0}}else for(let n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;const s=this.isAttribute(n);s&&(t[s]=e[n],i=!0)}return i?t:null},Qt.prototype.buildRawContent=function(e){if("string"==typeof e)return e;if("object"!=typeof e||null===e)return String(e);if(void 0!==e[this.options.textNodeName])return e[this.options.textNodeName];let t="";for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;if(this.isAttribute(i))continue;if(this.options.attributesGroupName&&i===this.options.attributesGroupName)continue;const n=e[i];if(i===this.options.textNodeName)t+=n;else if(Array.isArray(n)){for(let e of n)if("string"==typeof e||"number"==typeof e)t+=`<${i}>${e}</${i}>`;else if("object"==typeof e&&null!==e){const n=this.buildRawContent(e),s=this.buildAttributesForStopNode(e);t+=""===n?`<${i}${s}/>`:`<${i}${s}>${n}</${i}>`}}else if("object"==typeof n&&null!==n){const e=this.buildRawContent(n),s=this.buildAttributesForStopNode(n);t+=""===e?`<${i}${s}/>`:`<${i}${s}>${e}</${i}>`}else t+=`<${i}>${n}</${i}>`}return t},Qt.prototype.buildAttributesForStopNode=function(e){if(!e||"object"!=typeof e)return"";let t="";if(this.options.attributesGroupName&&e[this.options.attributesGroupName]){const i=e[this.options.attributesGroupName];for(let e in i){if(!Object.prototype.hasOwnProperty.call(i,e))continue;const n=e.startsWith(this.options.attributeNamePrefix)?e.substring(this.options.attributeNamePrefix.length):e,s=i[e];!0===s&&this.options.suppressBooleanAttributes?t+=" "+n:t+=" "+n+'="'+s+'"'}}else for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;const n=this.isAttribute(i);if(n){const s=e[i];!0===s&&this.options.suppressBooleanAttributes?t+=" "+n:t+=" "+n+'="'+s+'"'}}return t},Qt.prototype.buildObjectNode=function(e,t,i,n){if(""===e)return"?"===t[0]?this.indentate(n)+"<"+t+i+"?"+this.tagEndChar:this.indentate(n)+"<"+t+i+this.closeTag(t)+this.tagEndChar;{let s="</"+t+this.tagEndChar,r="";return"?"===t[0]&&(r="?",s=""),!i&&""!==i||-1!==e.indexOf("<")?!1!==this.options.commentPropName&&t===this.options.commentPropName&&0===r.length?this.indentate(n)+`\x3c!--${e}--\x3e`+this.newLine:this.indentate(n)+"<"+t+i+r+this.tagEndChar+e+this.indentate(n)+s:this.indentate(n)+"<"+t+i+r+">"+e+s}},Qt.prototype.closeTag=function(e){let t="";return-1!==this.options.unpairedTags.indexOf(e)?this.options.suppressUnpairedNode||(t="/"):t=this.options.suppressEmptyNode?"/":`></${e}`,t},Qt.prototype.checkStopNode=function(e){if(!this.stopNodeExpressions||0===this.stopNodeExpressions.length)return!1;for(let t=0;t<this.stopNodeExpressions.length;t++)if(e.matches(this.stopNodeExpressions[t]))return!0;return!1},Qt.prototype.buildTextValNode=function(e,t,i,n,s){if(!1!==this.options.cdataPropName&&t===this.options.cdataPropName){const t=String(e).replace(/\]\]>/g,"]]]]><![CDATA[>");return this.indentate(n)+`<![CDATA[${t}]]>`+this.newLine}if(!1!==this.options.commentPropName&&t===this.options.commentPropName){const t=String(e).replace(/--/g,"- -").replace(/-$/,"- ");return this.indentate(n)+`\x3c!--${t}--\x3e`+this.newLine}if("?"===t[0])return this.indentate(n)+"<"+t+i+"?"+this.tagEndChar;{let s=this.options.tagValueProcessor(t,e);return s=this.replaceEntitiesValue(s),""===s?this.indentate(n)+"<"+t+i+this.closeTag(t)+this.tagEndChar:this.indentate(n)+"<"+t+i+">"+s+"</"+t+this.tagEndChar}},Qt.prototype.replaceEntitiesValue=function(e){if(e&&e.length>0&&this.options.processEntities)for(let t=0;t<this.options.entities.length;t++){const i=this.options.entities[t];e=e.replace(i.regex,i.val)}return e};class ii{static parser=new Ut({allowBooleanAttributes:!0,attributeNamePrefix:"",ignoreAttributes:!1,ignoreDeclaration:!0,ignorePiTags:!0,numberParseOptions:{leadingZeros:!0,hex:!0},parseAttributeValue:!0,preserveOrder:!1,processEntities:!1,removeNSPrefix:!0,trimValues:!0});static builder=new Qt({attributeNamePrefix:"$",ignoreAttributes:!1,suppressBooleanAttributes:!1})}class ni extends le{onDisposed=new re;onVertexFound=new re;onVertexLost=new re;onEnabled=new re;components;workingPlane=null;_pickedPoint=null;_config;_enabled=!1;set enabled(e){this._enabled=e,e||(this._pickedPoint=null),this.onEnabled.trigger(e)}get enabled(){return this._enabled}set config(e){this._config={...this._config,...e}}get config(){return this._config}constructor(e,t){super(e),this.components=e,this.config={snapDistance:.25,showOnlyVertex:!1,...t},this.enabled=!1}dispose(){this.onVertexFound.reset(),this.onVertexLost.reset(),this.components=null,this.onDisposed.trigger(),this.onDisposed.reset()}async get(e){if(!this.enabled)return this._pickedPoint;const t=this.components.get(fa).get(e),i=await t.castRay();if(!i)return null!==this._pickedPoint&&(this.onVertexLost.trigger(),this._pickedPoint=null),this._pickedPoint;const n=i.point;return null!==this._pickedPoint&&this._pickedPoint.equals(n)||(this._pickedPoint=n.clone(),this.onVertexFound.trigger(this._pickedPoint)),this._pickedPoint}}class si{static join(e){const t={};for(const i of e)for(const e in i)if(t[e])for(const n of i[e])t[e].add(n);else t[e]=new Set(i[e]);return t}static intersect(e){if(0===e.length)return{};let t=si.clone(e[0]);for(let i=1;i<e.length;i++){const n=e[i],s={};for(const e in t)if(n[e]){const i=new Set;for(const s of t[e])n[e].has(s)&&i.add(s);i.size>0&&(s[e]=i)}t=s}return t}static clone(e){const t={};for(const i in e)t[i]=new Set(e[i]);return t}static remove(e,t,i=!1){i&&(e=si.clone(e));for(const i in t)if(e[i]){for(const n of t[i])e[i].delete(n);0===e[i].size&&delete e[i]}}static add(e,t,i=!1){i&&(e=si.clone(e));for(const i in t)if(e[i])for(const n of t[i])e[i].add(n);else e[i]=new Set(t[i])}static append(e,t,...i){let n=e[t];n||(n=new Set,e[t]=n);for(const e of i)n.add(e)}static isEqual(e,t){const i=Object.keys(e),n=Object.keys(t);if(i.length!==n.length)return!1;for(const n of i){if(!t[n])return!1;if(e[n].size!==t[n].size)return!1;for(const i of e[n])if(!t[n].has(i))return!1}return!0}static isEmpty(e){return 0===Object.values(e).reduce((e,t)=>e+t.size,0)}static toRaw(e){const t={};for(const i in e)t[i]=Array.from(e[i]);return t}static fromRaw(e){const t={};for(const i in e)t[i]=new Set(e[i]);return t}}class ri extends Map{onItemSet=new re;onItemUpdated=new re;onItemDeleted=new re;onCleared=new re;constructor(e){super(e)}clear(){super.clear(),this.onCleared.trigger()}set(e,t){const i=this.has(e);if(!(this.guard??(()=>!0))(e,t))return this;const n=super.set(e,t);return i?(this.onItemUpdated||(this.onItemUpdated=new re),this.onItemUpdated.trigger({key:e,value:t})):(this.onItemSet||(this.onItemSet=new re),this.onItemSet.trigger({key:e,value:t})),n}add(e){const t=me.create();return this.set(t,e),t}guard=()=>!0;delete(e){const t=super.delete(e);return t&&this.onItemDeleted.trigger(e),t}dispose(){this.clear(),this.onItemSet.reset(),this.onItemDeleted.reset(),this.onCleared.reset()}}class oi{static isEntry(e){return new Set(["Boolean","Color","Text","Number","Select","Vector3","TextSet","None"]).has(e.type)}static copySchema(e,t={}){for(const i in e){const n=e[i];this.isEntry(n)?t[i]=this.copyEntry(n):(t[i]={},this.copySchema(n,t[i]))}return t}static copyEntry(e){if("Boolean"===e.type){const t=e;return{type:t.type,value:t.value}}if("Color"===e.type){const t=e;return{type:t.type,value:t.value.clone()}}if("Text"===e.type){const t=e;return{type:t.type,value:t.value}}if("Number"===e.type){const t=e;return{type:t.type,value:t.value,min:t.min,max:t.max,interpolable:t.interpolable}}if("Select"===e.type){const t=e;return{type:t.type,value:t.value,multiple:t.multiple,options:new Set(t.options)}}if("Vector3"===e.type){const t=e;return{type:t.type,value:t.value.clone()}}if("TextSet"===e.type){const t=e;return{type:t.type,value:new Set(t.value)}}if("None"===e.type){const t=e;return{type:t.type,value:t.value}}throw new Error("Invalid entry!")}}class ai{list=new Set;add(e){for(const t of e)this.list.add(t)}remove(e){for(const t of e)this.list.delete(t)}set(e){for(const t of this.list)t.enabled=e}reset(){for(const e of this.list)e.reset()}}class li{_component;name;uuid;get controls(){return oi.copySchema(this._config)}constructor(e,t,i,n){this._component=e,this.name=i,this.uuid=n??me.create();t.get(ci).list.set(this.uuid,this)}set(e){for(const t in e)if(t in this){this[t]=e[t].value}}export(e=this._config,t={}){for(const i in e){const n=e[i];if(oi.isEntry(n))if("Color"===n.type){const{r:e,g:s,b:r}=n.value;t[i]={...n,value:{r:e,g:s,b:r}}}else if("Vector3"===n.type){const{x:e,y:s,z:r}=n.value;t[i]={...n,value:{x:e,y:s,z:r}}}else if("TextSet"===n.type){const e=Array.from(n.value);t[i]={...n,value:e}}else if("Select"===n.type){const e=Array.from(n.options);t[i]={...n,options:e}}else t[i]={...n};else t[i]={},this.export(n,t[i])}return t}import(e,t={},i=!0){for(const i in e){const n=e[i];if(oi.isEntry(n))if("Color"===n.type){const{r:e,g:r,b:o}=n.value;t[i]={...n,value:new s.Color(e,r,o)}}else if("Vector3"===n.type){const{x:e,y:r,z:o}=n.value;t[i]={...n,value:new s.Vector3(e,r,o)}}else"TextSet"===n.type?t[i]={...n,value:new Set(n.value)}:"Select"===n.type?t[i]={...n,options:new Set(n.options)}:t[i]={...n};else t[i]={},this.import(n,t[i],!1)}i&&this.set(t)}}class ci extends le{list=new t;enabled=!0;static uuid="b8c764e0-6b24-4e77-9a32-35fa728ee5b4";constructor(e){super(e),e.add(ci.uuid,this)}}class hi{constructor(e){this.dom=e,this.setupEvents(!0)}dom;_event;_position=new s.Vector2;onDisposed=new re;get position(){return this.updatePosition(!1),this._position.clone()}get rawPosition(){return this.updatePosition(!0),this._position.clone()}dispose(){this.setupEvents(!1),this.onDisposed.trigger(),this.onDisposed.reset()}updatePosition(e){if(this._event){const t=this.dom.getBoundingClientRect();this._position.x=this.getPositionX(t,this._event,e),this._position.y=this.getPositionY(t,this._event,e)}}getPositionY(e,t,i){const n=this.getDataObject(t);return i?n.clientY:-(n.clientY-e.top)/(e.bottom-e.top)*2+1}getPositionX(e,t,i){const n=this.getDataObject(t);return i?n.clientX:(n.clientX-e.left)/(e.right-e.left)*2-1}updateMouseInfo=e=>{this._event=e};getDataObject(e){return e instanceof MouseEvent?e:e.touches[0]}setupEvents(e){e?(this.dom.addEventListener("pointermove",this.updateMouseInfo),this.dom.addEventListener("touchstart",this.updateMouseInfo)):(this.dom.removeEventListener("pointermove",this.updateMouseInfo),this.dom.removeEventListener("touchstart",this.updateMouseInfo))}}const ui=1.25,di=32,pi=Math.pow(2,-24),fi=Symbol("SKIP_GENERATION"),mi={strategy:0,maxDepth:40,maxLeafSize:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null,[fi]:!1};function gi(e,t,i){return i.min.x=t[e],i.min.y=t[e+1],i.min.z=t[e+2],i.max.x=t[e+3],i.max.y=t[e+4],i.max.z=t[e+5],i}function wi(e){let t=-1,i=-1/0;for(let n=0;n<3;n++){const s=e[n+3]-e[n];s>i&&(i=s,t=n)}return t}function yi(e,t){t.set(e)}function _i(e,t,i){let n,s;for(let r=0;r<3;r++){const o=r+3;n=e[r],s=t[r],i[r]=n<s?n:s,n=e[o],s=t[o],i[o]=n>s?n:s}}function bi(e,t,i){for(let n=0;n<3;n++){const s=t[e+2*n],r=t[e+2*n+1],o=s-r,a=s+r;o<i[n]&&(i[n]=o),a>i[n+3]&&(i[n+3]=a)}}function vi(e){const t=e[3]-e[0],i=e[4]-e[1],n=e[5]-e[2];return 2*(t*i+i*n+n*t)}function xi(e,t){return 65535===t[e+15]}function Ci(e,t){return t[e+6]}function Si(e,t){return t[e+14]}function Ai(e){return e+8}function Ti(e,t){return e+8*t[e+6]}function Pi(e,t){return t[e+7]}function Ei(e){return e}function Mi(e,t,i,n,s){let r=1/0,o=1/0,a=1/0,l=-1/0,c=-1/0,h=-1/0,u=1/0,d=1/0,p=1/0,f=-1/0,m=-1/0,g=-1/0;const w=e.offset||0;for(let n=6*(t-w),s=6*(t+i-w);n<s;n+=6){const t=e[n+0],i=e[n+1],s=t-i,w=t+i;s<r&&(r=s),w>l&&(l=w),t<u&&(u=t),t>f&&(f=t);const y=e[n+2],_=e[n+3],b=y-_,v=y+_;b<o&&(o=b),v>c&&(c=v),y<d&&(d=y),y>m&&(m=y);const x=e[n+4],C=e[n+5],S=x-C,A=x+C;S<a&&(a=S),A>h&&(h=A),x<p&&(p=x),x>g&&(g=x)}n[0]=r,n[1]=o,n[2]=a,n[3]=l,n[4]=c,n[5]=h,s[0]=u,s[1]=d,s[2]=p,s[3]=f,s[4]=m,s[5]=g}const Ii=32,zi=(e,t)=>e.candidate-t.candidate,Di=new Array(Ii).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),ki=new Float32Array(6);class Bi{constructor(){this.boundingData=new Float32Array(6)}}let Oi,Vi,Ni,Li;const Fi=Math.pow(2,32);function Ri(e){return"count"in e?1:1+Ri(e.left)+Ri(e.right)}function Ui(e,t,i){return Oi=new Float32Array(i),Vi=new Uint32Array(i),Ni=new Uint16Array(i),Li=new Uint8Array(i),ji(e,t)}function ji(e,t){const i=e/4,n=e/2,s="count"in t,r=t.boundingData;for(let e=0;e<6;e++)Oi[i+e]=r[e];if(s)return t.buffer?(Li.set(new Uint8Array(t.buffer),e),e+t.buffer.byteLength):(Vi[i+6]=t.offset,Ni[n+14]=t.count,Ni[n+15]=65535,e+di);{const{left:n,right:s,splitAxis:r}=t;let o=ji(e+di,n);const a=o/di-e/di;if(a>Fi)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return Vi[i+6]=a,Vi[i+7]=r,ji(o,s)}}function $i(e,t,i,n,s,r){const{maxDepth:o,verbose:a,maxLeafSize:l,strategy:c,onProgress:h}=s,u=e.primitiveBuffer,d=e.primitiveBufferStride,p=new Float32Array(6);let f=!1;const m=new Bi;return Mi(t,i,n,m.boundingData,p),function e(i,n,s,r=null,h=0){!f&&h>=o&&(f=!0,a&&console.warn(`BVH: Max depth of ${o} reached when generating BVH. Consider increasing maxDepth.`));if(s<=l||h>=o)return g(n+s),i.offset=n,i.count=s,i;const m=function(e,t,i,n,s,r){let o=-1,a=0;if(0===r)o=wi(t),-1!==o&&(a=(t[o]+t[o+3])/2);else if(1===r)o=wi(e),-1!==o&&(a=function(e,t,i,n){let s=0;const r=e.offset;for(let o=t,a=t+i;o<a;o++)s+=e[6*(o-r)+2*n];return s/i}(i,n,s,o));else if(2===r){const r=vi(e);let l=ui*s;const c=i.offset||0,h=6*(n-c),u=6*(n+s-c);for(let e=0;e<3;e++){const n=t[e],c=(t[e+3]-n)/Ii;if(s<8){const t=[...Di];t.length=s;let n=0;for(let s=h;s<u;s+=6,n++){const r=t[n];r.candidate=i[s+2*e],r.count=0;const{bounds:o,leftCacheBounds:a,rightCacheBounds:l}=r;for(let e=0;e<3;e++)l[e]=1/0,l[e+3]=-1/0,a[e]=1/0,a[e+3]=-1/0,o[e]=1/0,o[e+3]=-1/0;bi(s,i,o)}t.sort(zi);let c=s;for(let e=0;e<c;e++){const i=t[e];for(;e+1<c&&t[e+1].candidate===i.candidate;)t.splice(e+1,1),c--}for(let n=h;n<u;n+=6){const s=i[n+2*e];for(let e=0;e<c;e++){const r=t[e];s>=r.candidate?bi(n,i,r.rightCacheBounds):(bi(n,i,r.leftCacheBounds),r.count++)}}for(let i=0;i<c;i++){const n=t[i],c=n.count,h=s-n.count,u=n.leftCacheBounds,d=n.rightCacheBounds;let p=0;0!==c&&(p=vi(u)/r);let f=0;0!==h&&(f=vi(d)/r);const m=1+ui*(p*c+f*h);m<l&&(o=e,l=m,a=n.candidate)}}else{for(let e=0;e<Ii;e++){const t=Di[e];t.count=0,t.candidate=n+c+e*c;const i=t.bounds;for(let e=0;e<3;e++)i[e]=1/0,i[e+3]=-1/0}for(let t=h;t<u;t+=6){let s=~~((i[t+2*e]-n)/c);s>=Ii&&(s=31);const r=Di[s];r.count++,bi(t,i,r.bounds)}const t=Di[31];yi(t.bounds,t.rightCacheBounds);for(let e=30;e>=0;e--){const t=Di[e],i=Di[e+1];_i(t.bounds,i.rightCacheBounds,t.rightCacheBounds)}let d=0;for(let t=0;t<31;t++){const i=Di[t],n=i.count,c=i.bounds,h=Di[t+1].rightCacheBounds;0!==n&&(0===d?yi(c,ki):_i(c,ki,ki)),d+=n;let u=0,p=0;0!==d&&(u=vi(ki)/r);const f=s-d;0!==f&&(p=vi(h)/r);const m=1+ui*(u*d+p*f);m<l&&(o=e,l=m,a=i.candidate)}}}}else console.warn(`BVH: Invalid build strategy value ${r} used.`);return{axis:o,pos:a}}(i.boundingData,r,t,n,s,c);if(-1===m.axis)return g(n+s),i.offset=n,i.count=s,i;const w=function(e,t,i,n,s,r){let o=n,a=n+s-1;const l=r.pos,c=2*r.axis,h=i.offset||0;for(;;){for(;o<=a&&i[6*(o-h)+c]<l;)o++;for(;o<=a&&i[6*(a-h)+c]>=l;)a--;if(!(o<a))return o;for(let i=0;i<t;i++){let n=e[o*t+i];e[o*t+i]=e[a*t+i],e[a*t+i]=n}for(let e=0;e<6;e++){const t=o-h,n=a-h,s=i[6*t+e];i[6*t+e]=i[6*n+e],i[6*n+e]=s}o++,a--}}(u,d,t,n,s,m);if(w===n||w===n+s)g(n+s),i.offset=n,i.count=s;else{i.splitAxis=m.axis;const r=new Bi,o=n,a=w-n;i.left=r,Mi(t,o,a,r.boundingData,p),e(r,o,a,p,h+1);const l=new Bi,c=w,u=s-a;i.right=l,Mi(t,c,u,l.boundingData,p),e(l,c,u,p,h+1)}return i}(m,i,n,p),m;function g(e){h&&h((e-r.offset)/r.count)}}function Wi(e,t){const i=t.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,n=e.getRootRanges(t.range),s=n[0],r=n[n.length-1],o={offset:s.offset,count:r.offset+r.count-s.offset},a=new Float32Array(6*o.count);a.offset=o.offset,e.computePrimitiveBounds(o.offset,o.count,a),e._roots=n.map(n=>{const s=$i(e,a,n.offset,n.count,t,o),r=Ri(s),l=new i(di*r);return Ui(0,s,l),l})}class Hi{constructor(e){this._getNewPrimitive=e,this._primitives=[]}getPrimitive(){const e=this._primitives;return 0===e.length?this._getNewPrimitive():e.pop()}releasePrimitive(e){this._primitives.push(e)}}class Gi{constructor(){this.float32Array=null,this.uint16Array=null,this.uint32Array=null;const e=[];let t=null;this.setBuffer=i=>{t&&e.push(t),t=i,this.float32Array=new Float32Array(i),this.uint16Array=new Uint16Array(i),this.uint32Array=new Uint32Array(i)},this.clearBuffer=()=>{t=null,this.float32Array=null,this.uint16Array=null,this.uint32Array=null,0!==e.length&&this.setBuffer(e.pop())}}}const Zi=new Gi;let qi,Yi;const Xi=[],Ki=new Hi(()=>new r);function Qi(e,t,i,n,s,r){qi=Ki.getPrimitive(),Yi=Ki.getPrimitive(),Xi.push(qi,Yi),Zi.setBuffer(e._roots[t]);const o=Ji(0,e.geometry,i,n,s,r);Zi.clearBuffer(),Ki.releasePrimitive(qi),Ki.releasePrimitive(Yi),Xi.pop(),Xi.pop();const a=Xi.length;return a>0&&(Yi=Xi[a-1],qi=Xi[a-2]),o}function Ji(e,t,i,n,s=null,r=0,o=0){const{float32Array:a,uint16Array:l,uint32Array:c}=Zi;let h=2*e;if(xi(h,l)){const t=Ci(e,c),i=Si(h,l);return gi(e,a,qi),n(t,i,!1,o,r+e/8,qi)}{let h=function(e){const{uint16Array:t,uint32Array:i}=Zi;let n=2*e;for(;!xi(n,t);)n=2*(e=Ai(e));return Ci(e,i)},u=function(e){const{uint16Array:t,uint32Array:i}=Zi;let n=2*e;for(;!xi(n,t);)n=2*(e=Ti(e,i));return Ci(e,i)+Si(n,t)};const d=Ai(e),p=Ti(e,c);let f,m,g,w,y=d,_=p;if(s&&(g=qi,w=Yi,gi(y,a,g),gi(_,a,w),f=s(g),m=s(w),m<f)){y=p,_=d;const e=f;f=m,m=e,g=w}g||(g=qi,gi(y,a,g));const b=i(g,xi(2*y,l),f,o+1,r+y/8);let v;if(2===b){const e=h(y);v=n(e,u(y)-e,!0,o+1,r+y/8,g)}else v=b&&Ji(y,t,i,n,s,r,o+1);if(v)return!0;w=Yi,gi(_,a,w);const x=i(w,xi(2*_,l),m,o+1,r+_/8);let C;if(2===x){const e=h(_);C=n(e,u(_)-e,!0,o+1,r+_/8,w)}else C=x&&Ji(_,t,i,n,s,r,o+1);return!!C}}const en=new Zi.constructor,tn=new Zi.constructor,nn=new Hi(()=>new r),sn=new r,rn=new r,on=new r,an=new r;let ln=!1;function cn(e,t,i,n,s,r=0,o=0,a=0,l=0,c=null,h=!1){let u,d;h?(u=tn,d=en):(u=en,d=tn);const p=u.float32Array,f=u.uint32Array,m=u.uint16Array,g=d.float32Array,w=d.uint32Array,y=d.uint16Array,_=2*t,b=xi(2*e,m),v=xi(_,y);let x=!1;if(v&&b)x=h?s(Ci(t,w),Si(2*t,y),Ci(e,f),Si(2*e,m),l,o+t/8,a,r+e/8):s(Ci(e,f),Si(2*e,m),Ci(t,w),Si(2*t,y),a,r+e/8,l,o+t/8);else if(v){const c=nn.getPrimitive();gi(t,g,c),c.applyMatrix4(i);const u=Ai(e),d=Ti(e,f);gi(u,p,sn),gi(d,p,rn);const m=c.intersectsBox(sn),w=c.intersectsBox(rn);x=m&&cn(t,u,n,i,s,o,r,l,a+1,c,!h)||w&&cn(t,d,n,i,s,o,r,l,a+1,c,!h),nn.releasePrimitive(c)}else{const u=Ai(t),d=Ti(t,w);gi(u,g,on),gi(d,g,an);const m=c.intersectsBox(on),y=c.intersectsBox(an);if(m&&y)x=cn(e,u,i,n,s,r,o,a,l+1,c,h)||cn(e,d,i,n,s,r,o,a,l+1,c,h);else if(m)if(b)x=cn(e,u,i,n,s,r,o,a,l+1,c,h);else{const t=nn.getPrimitive();t.copy(on).applyMatrix4(i);const c=Ai(e),d=Ti(e,f);gi(c,p,sn),gi(d,p,rn);const m=t.intersectsBox(sn),g=t.intersectsBox(rn);x=m&&cn(u,c,n,i,s,o,r,l,a+1,t,!h)||g&&cn(u,d,n,i,s,o,r,l,a+1,t,!h),nn.releasePrimitive(t)}else if(y)if(b)x=cn(e,d,i,n,s,r,o,a,l+1,c,h);else{const t=nn.getPrimitive();t.copy(an).applyMatrix4(i);const c=Ai(e),u=Ti(e,f);gi(c,p,sn),gi(u,p,rn);const m=t.intersectsBox(sn),g=t.intersectsBox(rn);x=m&&cn(d,c,n,i,s,o,r,l,a+1,t,!h)||g&&cn(d,u,n,i,s,o,r,l,a+1,t,!h),nn.releasePrimitive(t)}}return x}const hn=new r,un=new Float32Array(6);class dn{constructor(){this._roots=null,this.primitiveBuffer=null,this.primitiveBufferStride=null}init(e){Wi(this,e={...mi,...e})}getRootRanges(){throw new Error("BVH: getRootRanges() not implemented")}writePrimitiveBounds(){throw new Error("BVH: writePrimitiveBounds() not implemented")}writePrimitiveRangeBounds(e,t,i,n){let s=1/0,r=1/0,o=1/0,a=-1/0,l=-1/0,c=-1/0;for(let i=e,n=e+t;i<n;i++){this.writePrimitiveBounds(i,un,0);const[e,t,n,h,u,d]=un;e<s&&(s=e),h>a&&(a=h),t<r&&(r=t),u>l&&(l=u),n<o&&(o=n),d>c&&(c=d)}return i[n+0]=s,i[n+1]=r,i[n+2]=o,i[n+3]=a,i[n+4]=l,i[n+5]=c,i}computePrimitiveBounds(e,t,i){const n=i.offset||0;for(let s=e,r=e+t;s<r;s++){this.writePrimitiveBounds(s,un,0);const[e,t,r,o,a,l]=un,c=(e+o)/2,h=(t+a)/2,u=(r+l)/2,d=(o-e)/2,p=(a-t)/2,f=(l-r)/2,m=6*(s-n);i[m+0]=c,i[m+1]=d+(Math.abs(c)+d)*pi,i[m+2]=h,i[m+3]=p+(Math.abs(h)+p)*pi,i[m+4]=u,i[m+5]=f+(Math.abs(u)+f)*pi}return i}shiftPrimitiveOffsets(e){const t=this._indirectBuffer;if(t)for(let i=0,n=t.length;i<n;i++)t[i]+=e;else{const t=this._roots;for(let i=0;i<t.length;i++){const n=t[i],s=new Uint32Array(n),r=new Uint16Array(n),o=n.byteLength/di;for(let t=0;t<o;t++){const i=8*t;xi(2*i,r)&&(s[i+6]+=e)}}}}traverse(e,t=0){const i=this._roots[t],n=new Uint32Array(i),s=new Uint16Array(i);!function t(r,o=0){const a=2*r,l=xi(a,s);if(l){const t=n[r+6],c=s[a+14];e(o,l,new Float32Array(i,4*r,6),t,c)}else{const s=Ai(r),a=Ti(r,n),c=Pi(r,n);e(o,l,new Float32Array(i,4*r,6),c)||(t(s,o+1),t(a,o+1))}}(0)}refit(){const e=this._roots;for(let t=0,i=e.length;t<i;t++){const i=e[t],n=new Uint32Array(i),s=new Uint16Array(i),r=new Float32Array(i);for(let e=i.byteLength/di-1;e>=0;e--){const t=8*e,i=2*t;if(xi(i,s)){const e=Ci(t,n),o=Si(i,s);this.writePrimitiveRangeBounds(e,o,un,0),r.set(un,t)}else{const e=Ai(t),i=Ti(t,n);for(let n=0;n<3;n++){const s=r[e+n],o=r[e+n+3],a=r[i+n],l=r[i+n+3];r[t+n]=s<a?s:a,r[t+n+3]=o>l?o:l}}}}}getBoundingBox(e){e.makeEmpty();return this._roots.forEach(t=>{gi(0,new Float32Array(t),hn),e.union(hn)}),e}shapecast(e){let{boundsTraverseOrder:t,intersectsBounds:i,intersectsRange:n,intersectsPrimitive:s,scratchPrimitive:r,iterate:o}=e;if(n&&s){const e=n;n=(t,i,n,a,l)=>!!e(t,i,n,a,l)||o(t,i,this,s,n,a,r)}else n||(n=s?(e,t,i,n)=>o(e,t,this,s,i,n,r):(e,t,i)=>i);let a=!1,l=0;const c=this._roots;for(let e=0,s=c.length;e<s;e++){const s=c[e];if(a=Qi(this,e,i,n,t,l),a)break;l+=s.byteLength/di}return a}bvhcast(e,t,i){let{intersectsRanges:n}=i;return function(e,t,i,n){if(ln)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");ln=!0;const s=e._roots,r=t._roots;let a,l=0,c=0;const h=(new o).copy(i).invert();for(let e=0,t=s.length;e<t;e++){en.setBuffer(s[e]),c=0;const t=nn.getPrimitive();gi(Ei(0),en.float32Array,t),t.applyMatrix4(h);for(let e=0,s=r.length;e<s&&(tn.setBuffer(r[e]),a=cn(0,0,i,h,n,l,c,0,0,t),tn.clearBuffer(),c+=r[e].byteLength/di,!a);e++);if(nn.releasePrimitive(t),en.clearBuffer(),l+=s[e].byteLength/di,a)break}return ln=!1,a}(this,e,t,n)}}function pn(e){return e.index?e.index.count:e.attributes.position.count}function fn(e){return pn(e)/3}function mn(e,t){if(!e.index){const i=e.attributes.position.count,n=function(e,t=ArrayBuffer){return e>65535?new Uint32Array(new t(4*e)):new Uint16Array(new t(2*e))}(i,t.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer);e.setIndex(new a(n,1));for(let e=0;e<i;e++)n[e]=e}}function gn(e,t,i){const n=function(e,t,i){const n=pn(e)/i,s=t||e.drawRange,r=s.start/i,o=(s.start+s.count)/i,a=Math.max(0,r),l=Math.min(n,o)-a;return{offset:Math.floor(a),count:Math.floor(l)}}(e,t,i),s=function(e,t){return e.groups.map(e=>({offset:e.start/t,count:e.count/t}))}(e,i);if(!s.length)return[n];const r=[],o=n.offset,a=n.offset+n.count,l=pn(e)/i,c=[];for(const e of s){const{offset:t,count:i}=e,n=t,s=t+(isFinite(i)?i:l-t);n<a&&s>o&&(c.push({pos:Math.max(o,n),isStart:!0}),c.push({pos:Math.min(a,s),isStart:!1}))}c.sort((e,t)=>e.pos!==t.pos?e.pos-t.pos:"end"===e.type?-1:1);let h=0,u=null;for(const e of c){const t=e.pos;0!==h&&t!==u&&r.push({offset:u,count:t-u}),h+=e.isStart?1:-1,u=t}return r}class wn extends dn{get indirect(){return!!this._indirectBuffer}get primitiveStride(){return null}get primitiveBufferStride(){return this.indirect?1:this.primitiveStride}set primitiveBufferStride(e){}get primitiveBuffer(){return this.indirect?this._indirectBuffer:this.geometry.index.array}set primitiveBuffer(e){}constructor(e,t={}){if(!e.isBufferGeometry)throw new Error("BVH: Only BufferGeometries are supported.");if(e.index&&e.index.isInterleavedBufferAttribute)throw new Error("BVH: InterleavedBufferAttribute is not supported for the index attribute.");if(t.useSharedArrayBuffer&&"undefined"==typeof SharedArrayBuffer)throw new Error("BVH: SharedArrayBuffer is not available.");super(),this.geometry=e,this.resolvePrimitiveIndex=t.indirect?e=>this._indirectBuffer[e]:e=>e,this.primitiveBuffer=null,this.primitiveBufferStride=null,this._indirectBuffer=null,(t={...mi,...t})[fi]||this.init(t)}init(e){const{geometry:t,primitiveStride:i}=this;if(e.indirect){const n=function(e,t){const i=e[e.length-1],n=i.offset+i.count>65536,s=e.reduce((e,t)=>e+t.count,0),r=n?4:2,o=t?new SharedArrayBuffer(s*r):new ArrayBuffer(s*r),a=n?new Uint32Array(o):new Uint16Array(o);let l=0;for(let t=0;t<e.length;t++){const{offset:i,count:n}=e[t];for(let e=0;e<n;e++)a[l+e]=i+e;l+=n}return a}(gn(t,e.range,i),e.useSharedArrayBuffer);this._indirectBuffer=n}else mn(t,e);super.init(e),!t.boundingBox&&e.setBoundingBox&&(t.boundingBox=this.getBoundingBox(new r))}getRootRanges(e){return this.indirect?[{offset:0,count:this._indirectBuffer.length}]:gn(this.geometry,e,this.primitiveStride)}raycastObject3D(){throw new Error("BVH: raycastObject3D() not implemented")}}class yn{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(e,t){let i=1/0,n=-1/0;for(let s=0,r=e.length;s<r;s++){const r=e[s][t];i=r<i?r:i,n=r>n?r:n}this.min=i,this.max=n}setFromPoints(e,t){let i=1/0,n=-1/0;for(let s=0,r=t.length;s<r;s++){const r=t[s],o=e.dot(r);i=o<i?o:i,n=o>n?o:n}this.min=i,this.max=n}isSeparated(e){return this.min>e.max||e.min>this.max}}yn.prototype.setFromBox=function(){const e=new l;return function(t,i){const n=i.min,s=i.max;let r=1/0,o=-1/0;for(let i=0;i<=1;i++)for(let a=0;a<=1;a++)for(let l=0;l<=1;l++){e.x=n.x*i+s.x*(1-i),e.y=n.y*a+s.y*(1-a),e.z=n.z*l+s.z*(1-l);const c=t.dot(e);r=Math.min(c,r),o=Math.max(c,o)}this.min=r,this.max=o}}();const _n=function(){const e=new l,t=new l,i=new l;return function(n,s,r){const o=n.start,a=e,l=s.start,c=t;i.subVectors(o,l),e.subVectors(n.end,n.start),t.subVectors(s.end,s.start);const h=i.dot(c),u=c.dot(a),d=c.dot(c),p=i.dot(a),f=a.dot(a)*d-u*u;let m,g;m=0!==f?(h*u-p*d)/f:0,g=(h+m*u)/d,r.x=m,r.y=g}}(),bn=function(){const e=new u,t=new l,i=new l;return function(n,s,r,o){_n(n,s,e);let a=e.x,l=e.y;if(a>=0&&a<=1&&l>=0&&l<=1)return n.at(a,r),void s.at(l,o);if(a>=0&&a<=1)return l<0?s.at(0,o):s.at(1,o),void n.closestPointToPoint(o,!0,r);if(l>=0&&l<=1)return a<0?n.at(0,r):n.at(1,r),void s.closestPointToPoint(r,!0,o);{let e,c;e=a<0?n.start:n.end,c=l<0?s.start:s.end;const h=t,u=i;return n.closestPointToPoint(c,!0,t),s.closestPointToPoint(e,!0,i),h.distanceToSquared(c)<=u.distanceToSquared(e)?(r.copy(h),void o.copy(c)):(r.copy(e),void o.copy(u))}}}(),vn=function(){const e=new l,t=new l,i=new h,n=new c;return function(s,r){const{radius:o,center:a}=s,{a:l,b:c,c:h}=r;n.start=l,n.end=c;if(n.closestPointToPoint(a,!0,e).distanceTo(a)<=o)return!0;n.start=l,n.end=h;if(n.closestPointToPoint(a,!0,e).distanceTo(a)<=o)return!0;n.start=c,n.end=h;if(n.closestPointToPoint(a,!0,e).distanceTo(a)<=o)return!0;const u=r.getPlane(i);if(Math.abs(u.distanceToPoint(a))<=o){const e=u.projectPoint(a,t);if(r.containsPoint(e))return!0}return!1}}(),xn=["x","y","z"],Cn=1e-15;function Sn(e){return Math.abs(e)<Cn}class An extends d{constructor(...e){super(...e),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new l),this.satBounds=new Array(4).fill().map(()=>new yn),this.points=[this.a,this.b,this.c],this.plane=new h,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new c,this.needsUpdate=!0}intersectsSphere(e){return vn(e,this)}update(){const e=this.a,t=this.b,i=this.c,n=this.points,s=this.satAxes,r=this.satBounds,o=s[0],a=r[0];this.getNormal(o),a.setFromPoints(o,n);const l=s[1],c=r[1];l.subVectors(e,t),c.setFromPoints(l,n);const h=s[2],u=r[2];h.subVectors(t,i),u.setFromPoints(h,n);const d=s[3],p=r[3];d.subVectors(i,e),p.setFromPoints(d,n);const f=l.length(),m=h.length(),g=d.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,f<Cn?m<Cn||g<Cn?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(i)):m<Cn?g<Cn?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(e)):g<Cn&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(i),this.degenerateSegment.end.copy(t)),this.plane.setFromNormalAndCoplanarPoint(o,e),this.needsUpdate=!1}}An.prototype.closestPointToSegment=function(){const e=new l,t=new l,i=new c;return function(n,s=null,r=null){const{start:o,end:a}=n,l=this.points;let c,h=1/0;for(let o=0;o<3;o++){const a=(o+1)%3;i.start.copy(l[o]),i.end.copy(l[a]),bn(i,n,e,t),c=e.distanceToSquared(t),c<h&&(h=c,s&&s.copy(e),r&&r.copy(t))}return this.closestPointToPoint(o,e),c=o.distanceToSquared(e),c<h&&(h=c,s&&s.copy(e),r&&r.copy(o)),this.closestPointToPoint(a,e),c=a.distanceToSquared(e),c<h&&(h=c,s&&s.copy(e),r&&r.copy(a)),Math.sqrt(h)}}(),An.prototype.intersectsTriangle=function(){const e=new An,t=new yn,i=new yn,n=new l,s=new l,r=new l,o=new l,a=new c,h=new c,d=new l,p=new u,f=new u;function m(e,s,r,a){const l=n;e.isDegenerateIntoPoint||e.isDegenerateIntoSegment?l.copy(s.plane.normal):l.copy(e.plane.normal);const c=e.satBounds,h=e.satAxes;for(let n=1;n<4;n++){const r=c[n],a=h[n];if(t.setFromPoints(a,s.points),r.isSeparated(t))return!1;if(o.copy(l).cross(a),t.setFromPoints(o,e.points),i.setFromPoints(o,s.points),t.isSeparated(i))return!1}const u=s.satBounds,d=s.satAxes;for(let n=1;n<4;n++){const r=u[n],a=d[n];if(t.setFromPoints(a,e.points),r.isSeparated(t))return!1;if(o.crossVectors(l,a),t.setFromPoints(o,e.points),i.setFromPoints(o,s.points),t.isSeparated(i))return!1}return r&&(a||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),r.start.set(0,0,0),r.end.set(0,0,0)),!0}function g(e,t,i,n,s,r,o,a,l,c,h){let u=o/(o-a);c.x=n+(s-n)*u,h.start.subVectors(t,e).multiplyScalar(u).add(e),u=o/(o-l),c.y=n+(r-n)*u,h.end.subVectors(i,e).multiplyScalar(u).add(e)}function w(e,t,i,n,s,r,o,a,l,c,h){if(s>0)g(e.c,e.a,e.b,n,t,i,l,o,a,c,h);else if(r>0)g(e.b,e.a,e.c,i,t,n,a,o,l,c,h);else if(a*l>0||0!=o)g(e.a,e.b,e.c,t,i,n,o,a,l,c,h);else if(0!=a)g(e.b,e.a,e.c,i,t,n,a,o,l,c,h);else{if(0==l)return!0;g(e.c,e.a,e.b,n,t,i,l,o,a,c,h)}return!1}function y(e,t,i,s){const r=t.degenerateSegment,o=e.plane.distanceToPoint(r.start),a=e.plane.distanceToPoint(r.end);return Sn(o)?Sn(a)?m(e,t,i,s):(i&&(i.start.copy(r.start),i.end.copy(r.start)),e.containsPoint(r.start)):Sn(a)?(i&&(i.start.copy(r.end),i.end.copy(r.end)),e.containsPoint(r.end)):null!=e.plane.intersectLine(r,n)&&(i&&(i.start.copy(n),i.end.copy(n)),e.containsPoint(n))}function _(e,t,i){const n=t.a;return!(!Sn(e.plane.distanceToPoint(n))||!e.containsPoint(n))&&(i&&(i.start.copy(n),i.end.copy(n)),!0)}function b(e,t,i){const s=e.degenerateSegment,r=t.a;return s.closestPointToPoint(r,!0,n),r.distanceToSquared(n)<1e-30&&(i&&(i.start.copy(r),i.end.copy(r)),!0)}return function(t,i=null,o=!1){this.needsUpdate&&this.update(),t.isExtendedTriangle?t.needsUpdate&&t.update():(e.copy(t),e.update(),t=e);const l=function(e,t,i,o){if(e.isDegenerateIntoSegment){if(t.isDegenerateIntoSegment){const o=e.degenerateSegment,a=t.degenerateSegment,l=s,c=r;o.delta(l),a.delta(c);const h=n.subVectors(a.start,o.start),u=l.x*c.y-l.y*c.x;if(Sn(u))return!1;const d=(h.x*c.y-h.y*c.x)/u,p=-(l.x*h.y-l.y*h.x)/u;return!(d<0||d>1||p<0||p>1)&&(!!Sn(o.start.z+l.z*d-(a.start.z+c.z*p))&&(i&&(i.start.copy(o.start).addScaledVector(l,d),i.end.copy(o.start).addScaledVector(l,d)),!0))}return t.isDegenerateIntoPoint?b(e,t,i):y(t,e,i,o)}return e.isDegenerateIntoPoint?t.isDegenerateIntoPoint?t.a.distanceToSquared(e.a)<1e-30&&(i&&(i.start.copy(e.a),i.end.copy(e.a)),!0):t.isDegenerateIntoSegment?b(t,e,i):_(t,e,i):t.isDegenerateIntoPoint?_(e,t,i):t.isDegenerateIntoSegment?y(e,t,i,o):void 0}(this,t,i,o);if(void 0!==l)return l;const c=this.plane,u=t.plane;let g=u.distanceToPoint(this.a),v=u.distanceToPoint(this.b),x=u.distanceToPoint(this.c);Sn(g)&&(g=0),Sn(v)&&(v=0),Sn(x)&&(x=0);const C=g*v,S=g*x;if(C>0&&S>0)return!1;let A=c.distanceToPoint(t.a),T=c.distanceToPoint(t.b),P=c.distanceToPoint(t.c);Sn(A)&&(A=0),Sn(T)&&(T=0),Sn(P)&&(P=0);const E=A*T,M=A*P;if(E>0&&M>0)return!1;s.copy(c.normal),r.copy(u.normal);const I=s.cross(r);let z=0,D=Math.abs(I.x);const k=Math.abs(I.y);k>D&&(D=k,z=1);Math.abs(I.z)>D&&(z=2);const B=xn[z],O=this.a[B],V=this.b[B],N=this.c[B],L=t.a[B],F=t.b[B],R=t.c[B];if(w(this,O,V,N,C,S,g,v,x,p,a))return m(this,t,i,o);if(w(t,L,F,R,E,M,A,T,P,f,h))return m(this,t,i,o);if(p.y<p.x){const e=p.y;p.y=p.x,p.x=e,d.copy(a.start),a.start.copy(a.end),a.end.copy(d)}if(f.y<f.x){const e=f.y;f.y=f.x,f.x=e,d.copy(h.start),h.start.copy(h.end),h.end.copy(d)}return!(p.y<f.x||f.y<p.x)&&(i&&(f.x>p.x?i.start.copy(h.start):i.start.copy(a.start),f.y<p.y?i.end.copy(h.end):i.end.copy(a.end)),!0)}}(),An.prototype.distanceToPoint=function(){const e=new l;return function(t){return this.closestPointToPoint(t,e),t.distanceTo(e)}}(),An.prototype.distanceToTriangle=function(){const e=new l,t=new l,i=["a","b","c"],n=new c,s=new c;return function(r,o=null,a=null){const l=o||a?n:null;if(this.intersectsTriangle(r,l))return(o||a)&&(o&&l.getCenter(o),a&&l.getCenter(a)),0;let c=1/0;for(let t=0;t<3;t++){let n;const s=i[t],l=r[s];this.closestPointToPoint(l,e),n=l.distanceToSquared(e),n<c&&(c=n,o&&o.copy(e),a&&a.copy(l));const h=this[s];r.closestPointToPoint(h,e),n=h.distanceToSquared(e),n<c&&(c=n,o&&o.copy(h),a&&a.copy(e))}for(let l=0;l<3;l++){const h=i[l],u=i[(l+1)%3];n.set(this[h],this[u]);for(let l=0;l<3;l++){const h=i[l],u=i[(l+1)%3];s.set(r[h],r[u]),bn(n,s,e,t);const d=e.distanceToSquared(t);d<c&&(c=d,o&&o.copy(e),a&&a.copy(t))}}return Math.sqrt(c)}}();class Tn{constructor(e,t,i){this.isOrientedBox=!0,this.min=new l,this.max=new l,this.matrix=new o,this.invMatrix=new o,this.points=new Array(8).fill().map(()=>new l),this.satAxes=new Array(3).fill().map(()=>new l),this.satBounds=new Array(3).fill().map(()=>new yn),this.alignedSatBounds=new Array(3).fill().map(()=>new yn),this.needsUpdate=!1,e&&this.min.copy(e),t&&this.max.copy(t),i&&this.matrix.copy(i)}set(e,t,i){this.min.copy(e),this.max.copy(t),this.matrix.copy(i),this.needsUpdate=!0}copy(e){this.min.copy(e.min),this.max.copy(e.max),this.matrix.copy(e.matrix),this.needsUpdate=!0}}Tn.prototype.update=function(){return function(){const e=this.matrix,t=this.min,i=this.max,n=this.points;for(let s=0;s<=1;s++)for(let r=0;r<=1;r++)for(let o=0;o<=1;o++){const a=n[1*s|2*r|4*o];a.x=s?i.x:t.x,a.y=r?i.y:t.y,a.z=o?i.z:t.z,a.applyMatrix4(e)}const s=this.satBounds,r=this.satAxes,o=n[0];for(let e=0;e<3;e++){const t=r[e],i=s[e],a=n[1<<e];t.subVectors(o,a),i.setFromPoints(t,n)}const a=this.alignedSatBounds;a[0].setFromPointsField(n,"x"),a[1].setFromPointsField(n,"y"),a[2].setFromPointsField(n,"z"),this.invMatrix.copy(this.matrix).invert(),this.needsUpdate=!1}}(),Tn.prototype.intersectsBox=function(){const e=new yn;return function(t){this.needsUpdate&&this.update();const i=t.min,n=t.max,s=this.satBounds,r=this.satAxes,o=this.alignedSatBounds;if(e.min=i.x,e.max=n.x,o[0].isSeparated(e))return!1;if(e.min=i.y,e.max=n.y,o[1].isSeparated(e))return!1;if(e.min=i.z,e.max=n.z,o[2].isSeparated(e))return!1;for(let i=0;i<3;i++){const n=r[i],o=s[i];if(e.setFromBox(n,t),o.isSeparated(e))return!1}return!0}}(),Tn.prototype.intersectsTriangle=function(){const e=new An,t=new Array(3),i=new yn,n=new yn,s=new l;return function(r){this.needsUpdate&&this.update(),r.isExtendedTriangle?r.needsUpdate&&r.update():(e.copy(r),e.update(),r=e);const o=this.satBounds,a=this.satAxes;t[0]=r.a,t[1]=r.b,t[2]=r.c;for(let e=0;e<3;e++){const n=o[e],s=a[e];if(i.setFromPoints(s,t),n.isSeparated(i))return!1}const l=r.satBounds,c=r.satAxes,h=this.points;for(let e=0;e<3;e++){const t=l[e],n=c[e];if(i.setFromPoints(n,h),t.isSeparated(i))return!1}for(let e=0;e<3;e++){const r=a[e];for(let e=0;e<4;e++){const o=c[e];if(s.crossVectors(r,o),i.setFromPoints(s,t),n.setFromPoints(s,h),i.isSeparated(n))return!1}}return!0}}(),Tn.prototype.closestPointToPoint=function(){return function(e,t){return this.needsUpdate&&this.update(),t.copy(e).applyMatrix4(this.invMatrix).clamp(this.min,this.max).applyMatrix4(this.matrix),t}}(),Tn.prototype.distanceToPoint=function(){const e=new l;return function(t){return this.closestPointToPoint(t,e),t.distanceTo(e)}}(),Tn.prototype.distanceToBox=function(){const e=["x","y","z"],t=new Array(12).fill().map(()=>new c),i=new Array(12).fill().map(()=>new c),n=new l,s=new l;return function(r,o=0,a=null,l=null){if(this.needsUpdate&&this.update(),this.intersectsBox(r))return(a||l)&&(r.getCenter(s),this.closestPointToPoint(s,n),r.closestPointToPoint(n,s),a&&a.copy(n),l&&l.copy(s)),0;const c=o*o,h=r.min,u=r.max,d=this.points;let p=1/0;for(let e=0;e<8;e++){const t=d[e];s.copy(t).clamp(h,u);const i=t.distanceToSquared(s);if(i<p&&(p=i,a&&a.copy(t),l&&l.copy(s),i<c))return Math.sqrt(i)}let f=0;for(let n=0;n<3;n++)for(let s=0;s<=1;s++)for(let r=0;r<=1;r++){const o=(n+1)%3,a=(n+2)%3,l=1<<n|s<<o|r<<a,c=d[s<<o|r<<a],p=d[l];t[f].set(c,p);const m=e[n],g=e[o],w=e[a],y=i[f],_=y.start,b=y.end;_[m]=h[m],_[g]=s?h[g]:u[g],_[w]=r?h[w]:u[g],b[m]=u[m],b[g]=s?h[g]:u[g],b[w]=r?h[w]:u[g],f++}for(let e=0;e<=1;e++)for(let t=0;t<=1;t++)for(let i=0;i<=1;i++){s.x=e?u.x:h.x,s.y=t?u.y:h.y,s.z=i?u.z:h.z,this.closestPointToPoint(s,n);const r=s.distanceToSquared(n);if(r<p&&(p=r,a&&a.copy(n),l&&l.copy(s),r<c))return Math.sqrt(r)}for(let e=0;e<12;e++){const r=t[e];for(let e=0;e<12;e++){const t=i[e];bn(r,t,n,s);const o=n.distanceToSquared(s);if(o<p&&(p=o,a&&a.copy(n),l&&l.copy(s),o<c))return Math.sqrt(o)}}return Math.sqrt(p)}}();class Pn extends Hi{constructor(){super(()=>new An)}}const En=new Pn,Mn=new l,In=new l;const zn=parseInt(m)>=169,Dn=parseInt(m)<=161,kn=new l,Bn=new l,On=new l,Vn=new u,Nn=new u,Ln=new u,Fn=new l,Rn=new l,Un=new l,jn=new l;function $n(e,t,i,n,s,r,o,a,c,h,m){kn.fromBufferAttribute(t,r),Bn.fromBufferAttribute(t,o),On.fromBufferAttribute(t,a);const g=function(e,t,i,n,s,r,o,a){let l;if(l=r===p?e.intersectTriangle(n,i,t,!0,s):e.intersectTriangle(t,i,n,r!==f,s),null===l)return null;const c=e.origin.distanceTo(s);return c<o||c>a?null:{distance:c,point:s.clone()}}(e,kn,Bn,On,jn,c,h,m);if(g){if(n){Vn.fromBufferAttribute(n,r),Nn.fromBufferAttribute(n,o),Ln.fromBufferAttribute(n,a),g.uv=new u;const e=d.getInterpolation(jn,kn,Bn,On,Vn,Nn,Ln,g.uv);zn||(g.uv=e)}if(s){Vn.fromBufferAttribute(s,r),Nn.fromBufferAttribute(s,o),Ln.fromBufferAttribute(s,a),g.uv1=new u;const e=d.getInterpolation(jn,kn,Bn,On,Vn,Nn,Ln,g.uv1);zn||(g.uv1=e),Dn&&(g.uv2=g.uv1)}if(i){Fn.fromBufferAttribute(i,r),Rn.fromBufferAttribute(i,o),Un.fromBufferAttribute(i,a),g.normal=new l;const t=d.getInterpolation(jn,kn,Bn,On,Fn,Rn,Un,g.normal);g.normal.dot(e.direction)>0&&g.normal.multiplyScalar(-1),zn||(g.normal=t)}const t={a:r,b:o,c:a,normal:new l,materialIndex:0};if(d.getNormal(kn,Bn,On,t.normal),g.face=t,g.faceIndex=r,zn){const e=new l;d.getBarycoord(jn,kn,Bn,On,e),g.barycoord=e}}return g}function Wn(e){return e&&e.isMaterial?e.side:e}function Hn(e,t,i,n,s,r,o){const a=3*n;let l=a+0,c=a+1,h=a+2;const{index:u,groups:d}=e;e.index&&(l=u.getX(l),c=u.getX(c),h=u.getX(h));const{position:p,normal:f,uv:m,uv1:g}=e.attributes;if(Array.isArray(t)){const e=3*n;for(let a=0,u=d.length;a<u;a++){const{start:u,count:w,materialIndex:y}=d[a];if(e>=u&&e<u+w){const e=$n(i,p,f,m,g,l,c,h,Wn(t[y]),r,o);if(e){if(e.faceIndex=n,e.face.materialIndex=y,!s)return e;s.push(e)}}}}else{const e=$n(i,p,f,m,g,l,c,h,Wn(t),r,o);if(e){if(e.faceIndex=n,e.face.materialIndex=0,!s)return e;s.push(e)}}return null}function Gn(e,t,i,n){const s=e.a,r=e.b,o=e.c;let a=t,l=t+1,c=t+2;i&&(a=i.getX(a),l=i.getX(l),c=i.getX(c)),s.x=n.getX(a),s.y=n.getY(a),s.z=n.getZ(a),r.x=n.getX(l),r.y=n.getY(l),r.z=n.getZ(l),o.x=n.getX(c),o.y=n.getY(c),o.z=n.getZ(c)}function Zn(e,t,i,n,s,r,o){const{geometry:a}=i,{index:l}=a,c=a.attributes.position;for(let i=e,a=t+e;i<a;i++){let e;if(e=i,Gn(o,3*e,l,c),o.needsUpdate=!0,n(o,e,s,r))return!0}return!1}function qn(e,t=null){t&&Array.isArray(t)&&(t=new Set(t));const i=e.geometry,n=i.index?i.index.array:null,s=i.attributes.position;let r,o,a,l,c=0;const h=e._roots;for(let e=0,t=h.length;e<t;e++)r=h[e],o=new Uint32Array(r),a=new Uint16Array(r),l=new Float32Array(r),u(0,c),c+=r.byteLength;function u(e,i,r=!1){const c=2*e;if(xi(c,a)){const t=Ci(e,o);let i=1/0,r=1/0,h=1/0,u=-1/0,d=-1/0,p=-1/0;for(let e=3*t,o=3*(t+Si(c,a));e<o;e++){let t=n[e];const o=s.getX(t),a=s.getY(t),l=s.getZ(t);o<i&&(i=o),o>u&&(u=o),a<r&&(r=a),a>d&&(d=a),l<h&&(h=l),l>p&&(p=l)}return(l[e+0]!==i||l[e+1]!==r||l[e+2]!==h||l[e+3]!==u||l[e+4]!==d||l[e+5]!==p)&&(l[e+0]=i,l[e+1]=r,l[e+2]=h,l[e+3]=u,l[e+4]=d,l[e+5]=p,!0)}{const n=Ai(e),s=Ti(e,o);let a=r,c=!1,h=!1;if(t){if(!a){const e=n/8+i/di,r=s/8+i/di;c=t.has(e),h=t.has(r),a=!c&&!h}}else c=!0,h=!0;const d=a||h;let p=!1;(a||c)&&(p=u(n,i,a));let f=!1;d&&(f=u(s,i,a));const m=p||f;if(m)for(let t=0;t<3;t++){const i=n+t,r=s+t,o=l[i],a=l[i+3],c=l[r],h=l[r+3];l[e+t]=o<c?o:c,l[e+t+3]=a>h?a:h}return m}}}function Yn(e,t,i,n,s){let r,o,a,l,c,h;const u=1/i.direction.x,d=1/i.direction.y,p=1/i.direction.z,f=i.origin.x,m=i.origin.y,g=i.origin.z;let w=t[e],y=t[e+3],_=t[e+1],b=t[e+3+1],v=t[e+2],x=t[e+3+2];return u>=0?(r=(w-f)*u,o=(y-f)*u):(r=(y-f)*u,o=(w-f)*u),d>=0?(a=(_-m)*d,l=(b-m)*d):(a=(b-m)*d,l=(_-m)*d),!(r>l||a>o)&&((a>r||isNaN(r))&&(r=a),(l<o||isNaN(o))&&(o=l),p>=0?(c=(v-g)*p,h=(x-g)*p):(c=(x-g)*p,h=(v-g)*p),!(r>h||c>o)&&((c>r||r!=r)&&(r=c),(h<o||o!=o)&&(o=h),r<=s&&o>=n))}function Xn(e,t,i,n,s,r,o){const{geometry:a}=i,{index:l}=a,c=a.attributes.position;for(let a=e,h=t+e;a<h;a++){let e;if(e=i.resolveTriangleIndex(a),Gn(o,3*e,l,c),o.needsUpdate=!0,n(o,e,s,r))return!0}return!1}function Kn(e,t,i,n,s,r,o){Zi.setBuffer(e._roots[t]),Qn(0,e,i,n,s,r,o),Zi.clearBuffer()}function Qn(e,t,i,n,s,r,o){const{float32Array:a,uint16Array:l,uint32Array:c}=Zi,h=2*e;if(xi(h,l)){!function(e,t,i,n,s,r,o,a){const{geometry:l,_indirectBuffer:c}=e;for(let e=n,c=n+s;e<c;e++)Hn(l,t,i,e,r,o,a)}(t,i,n,Ci(e,c),Si(h,l),s,r,o)}else{const l=Ai(e);Yn(l,a,n,r,o)&&Qn(l,t,i,n,s,r,o);const h=Ti(e,c);Yn(h,a,n,r,o)&&Qn(h,t,i,n,s,r,o)}}const Jn=["x","y","z"];function es(e,t,i,n,s,r){Zi.setBuffer(e._roots[t]);const o=ts(0,e,i,n,s,r);return Zi.clearBuffer(),o}function ts(e,t,i,n,s,r){const{float32Array:o,uint16Array:a,uint32Array:l}=Zi;let c=2*e;if(xi(c,a)){return function(e,t,i,n,s,r,o){const{geometry:a,_indirectBuffer:l}=e;let c=1/0,h=null;for(let e=n,l=n+s;e<l;e++){let n;n=Hn(a,t,i,e,null,r,o),n&&n.distance<c&&(h=n,c=n.distance)}return h}(t,i,n,Ci(e,l),Si(c,a),s,r)}{const a=Pi(e,l),c=Jn[a],h=n.direction[c]>=0;let u,d;h?(u=Ai(e),d=Ti(e,l)):(u=Ti(e,l),d=Ai(e));const p=Yn(u,o,n,s,r)?ts(u,t,i,n,s,r):null;if(p){const e=p.point[c];if(h?e<=o[d+a]:e>=o[d+a+3])return p}const f=Yn(d,o,n,s,r)?ts(d,t,i,n,s,r):null;return p&&f?p.distance<=f.distance?p:f:p||f||null}}const is=new r,ns=new An,ss=new An,rs=new o,os=new Tn,as=new Tn;function ls(e,t,i,n){Zi.setBuffer(e._roots[t]);const s=cs(0,e,i,n);return Zi.clearBuffer(),s}function cs(e,t,i,n,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=Zi;let l=2*e;null===s&&(i.boundingBox||i.computeBoundingBox(),os.set(i.boundingBox.min,i.boundingBox.max,n),s=os);if(!xi(l,o)){const o=Ai(e),l=Ti(e,a);gi(o,r,is);if(s.intersectsBox(is)&&cs(o,t,i,n,s))return!0;gi(l,r,is);return!!(s.intersectsBox(is)&&cs(l,t,i,n,s))}{const s=t.geometry,c=s.index,h=s.attributes.position,u=i.index,d=i.attributes.position,p=Ci(e,a),f=Si(l,o);if(rs.copy(n).invert(),i.boundsTree){gi(e,r,as),as.matrix.copy(rs),as.needsUpdate=!0;return i.boundsTree.shapecast({intersectsBounds:e=>as.intersectsBox(e),intersectsTriangle:e=>{e.a.applyMatrix4(n),e.b.applyMatrix4(n),e.c.applyMatrix4(n),e.needsUpdate=!0;for(let t=3*p,i=3*(f+p);t<i;t+=3)if(Gn(ss,t,c,h),ss.needsUpdate=!0,e.intersectsTriangle(ss))return!0;return!1}})}{const e=fn(i);for(let t=3*p,i=3*(f+p);t<i;t+=3){Gn(ns,t,c,h),ns.a.applyMatrix4(rs),ns.b.applyMatrix4(rs),ns.c.applyMatrix4(rs),ns.needsUpdate=!0;for(let t=0,i=3*e;t<i;t+=3)if(Gn(ss,t,u,d),ss.needsUpdate=!0,ns.intersectsTriangle(ss))return!0}}}}const hs=new o,us=new Tn,ds=new Tn,ps=new l,fs=new l,ms=new l,gs=new l;function ws(e,t,i,n={},s={},r=0,o=1/0){t.boundingBox||t.computeBoundingBox(),us.set(t.boundingBox.min,t.boundingBox.max,i),us.needsUpdate=!0;const a=e.geometry,l=a.attributes.position,c=a.index,h=t.attributes.position,u=t.index,d=En.getPrimitive(),p=En.getPrimitive();let f=ps,m=fs,g=null,w=null;s&&(g=ms,w=gs);let y=1/0,_=null,b=null;return hs.copy(i).invert(),ds.matrix.copy(hs),e.shapecast({boundsTraverseOrder:e=>us.distanceToBox(e),intersectsBounds:(e,t,i)=>i<y&&i<o&&(t&&(ds.min.copy(e.min),ds.max.copy(e.max),ds.needsUpdate=!0),!0),intersectsRange:(e,n)=>{if(t.boundsTree){return t.boundsTree.shapecast({boundsTraverseOrder:e=>ds.distanceToBox(e),intersectsBounds:(e,t,i)=>i<y&&i<o,intersectsRange:(t,s)=>{for(let o=t,a=t+s;o<a;o++){Gn(p,3*o,u,h),p.a.applyMatrix4(i),p.b.applyMatrix4(i),p.c.applyMatrix4(i),p.needsUpdate=!0;for(let t=e,i=e+n;t<i;t++){Gn(d,3*t,c,l),d.needsUpdate=!0;const e=d.distanceToTriangle(p,f,g);if(e<y&&(m.copy(f),w&&w.copy(g),y=e,_=t,b=o),e<r)return!0}}}})}for(let s=0,o=fn(t);s<o;s++){Gn(p,3*s,u,h),p.a.applyMatrix4(i),p.b.applyMatrix4(i),p.c.applyMatrix4(i),p.needsUpdate=!0;for(let t=e,i=e+n;t<i;t++){Gn(d,3*t,c,l),d.needsUpdate=!0;const e=d.distanceToTriangle(p,f,g);if(e<y&&(m.copy(f),w&&w.copy(g),y=e,_=t,b=s),e<r)return!0}}}}),En.releasePrimitive(d),En.releasePrimitive(p),y===1/0?null:(n.point?n.point.copy(m):n.point=m.clone(),n.distance=y,n.faceIndex=_,s&&(s.point?s.point.copy(w):s.point=w.clone(),s.point.applyMatrix4(hs),m.applyMatrix4(hs),s.distance=m.sub(s.point).length(),s.faceIndex=b),n)}function ys(e,t=null){t&&Array.isArray(t)&&(t=new Set(t));const i=e.geometry,n=i.index?i.index.array:null,s=i.attributes.position;let r,o,a,l,c=0;const h=e._roots;for(let e=0,t=h.length;e<t;e++)r=h[e],o=new Uint32Array(r),a=new Uint16Array(r),l=new Float32Array(r),u(0,c),c+=r.byteLength;function u(i,r,c=!1){const h=2*i;if(xi(h,a)){const t=Ci(i,o);let r=1/0,c=1/0,u=1/0,d=-1/0,p=-1/0,f=-1/0;for(let i=t,o=t+Si(h,a);i<o;i++){const t=3*e.resolveTriangleIndex(i);for(let e=0;e<3;e++){let i=t+e;i=n?n[i]:i;const o=s.getX(i),a=s.getY(i),l=s.getZ(i);o<r&&(r=o),o>d&&(d=o),a<c&&(c=a),a>p&&(p=a),l<u&&(u=l),l>f&&(f=l)}}return(l[i+0]!==r||l[i+1]!==c||l[i+2]!==u||l[i+3]!==d||l[i+4]!==p||l[i+5]!==f)&&(l[i+0]=r,l[i+1]=c,l[i+2]=u,l[i+3]=d,l[i+4]=p,l[i+5]=f,!0)}{const e=Ai(i),n=Ti(i,o);let s=c,a=!1,h=!1;if(t){if(!s){const i=e/8+r/di,o=n/8+r/di;a=t.has(i),h=t.has(o),s=!a&&!h}}else a=!0,h=!0;const d=s||h;let p=!1;(s||a)&&(p=u(e,r,s));let f=!1;d&&(f=u(n,r,s));const m=p||f;if(m)for(let t=0;t<3;t++){const s=e+t,r=n+t,o=l[s],a=l[s+3],c=l[r],h=l[r+3];l[i+t]=o<c?o:c,l[i+t+3]=a>h?a:h}return m}}}function _s(e,t,i,n,s,r,o){Zi.setBuffer(e._roots[t]),bs(0,e,i,n,s,r,o),Zi.clearBuffer()}function bs(e,t,i,n,s,r,o){const{float32Array:a,uint16Array:l,uint32Array:c}=Zi,h=2*e;if(xi(h,l)){!function(e,t,i,n,s,r,o,a){const{geometry:l,_indirectBuffer:c}=e;for(let e=n,h=n+s;e<h;e++)Hn(l,t,i,c?c[e]:e,r,o,a)}(t,i,n,Ci(e,c),Si(h,l),s,r,o)}else{const l=Ai(e);Yn(l,a,n,r,o)&&bs(l,t,i,n,s,r,o);const h=Ti(e,c);Yn(h,a,n,r,o)&&bs(h,t,i,n,s,r,o)}}const vs=["x","y","z"];function xs(e,t,i,n,s,r){Zi.setBuffer(e._roots[t]);const o=Cs(0,e,i,n,s,r);return Zi.clearBuffer(),o}function Cs(e,t,i,n,s,r){const{float32Array:o,uint16Array:a,uint32Array:l}=Zi;let c=2*e;if(xi(c,a)){return function(e,t,i,n,s,r,o){const{geometry:a,_indirectBuffer:l}=e;let c=1/0,h=null;for(let e=n,u=n+s;e<u;e++){let n;n=Hn(a,t,i,l?l[e]:e,null,r,o),n&&n.distance<c&&(h=n,c=n.distance)}return h}(t,i,n,Ci(e,l),Si(c,a),s,r)}{const a=Pi(e,l),c=vs[a],h=n.direction[c]>=0;let u,d;h?(u=Ai(e),d=Ti(e,l)):(u=Ti(e,l),d=Ai(e));const p=Yn(u,o,n,s,r)?Cs(u,t,i,n,s,r):null;if(p){const e=p.point[c];if(h?e<=o[d+a]:e>=o[d+a+3])return p}const f=Yn(d,o,n,s,r)?Cs(d,t,i,n,s,r):null;return p&&f?p.distance<=f.distance?p:f:p||f||null}}const Ss=new r,As=new An,Ts=new An,Ps=new o,Es=new Tn,Ms=new Tn;function Is(e,t,i,n){Zi.setBuffer(e._roots[t]);const s=zs(0,e,i,n);return Zi.clearBuffer(),s}function zs(e,t,i,n,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=Zi;let l=2*e;null===s&&(i.boundingBox||i.computeBoundingBox(),Es.set(i.boundingBox.min,i.boundingBox.max,n),s=Es);if(!xi(l,o)){const o=Ai(e),l=Ti(e,a);gi(o,r,Ss);if(s.intersectsBox(Ss)&&zs(o,t,i,n,s))return!0;gi(l,r,Ss);return!!(s.intersectsBox(Ss)&&zs(l,t,i,n,s))}{const s=t.geometry,c=s.index,h=s.attributes.position,u=i.index,d=i.attributes.position,p=Ci(e,a),f=Si(l,o);if(Ps.copy(n).invert(),i.boundsTree){gi(e,r,Ms),Ms.matrix.copy(Ps),Ms.needsUpdate=!0;return i.boundsTree.shapecast({intersectsBounds:e=>Ms.intersectsBox(e),intersectsTriangle:e=>{e.a.applyMatrix4(n),e.b.applyMatrix4(n),e.c.applyMatrix4(n),e.needsUpdate=!0;for(let i=p,n=f+p;i<n;i++)if(Gn(Ts,3*t.resolveTriangleIndex(i),c,h),Ts.needsUpdate=!0,e.intersectsTriangle(Ts))return!0;return!1}})}{const e=fn(i);for(let i=p,n=f+p;i<n;i++){const n=t.resolveTriangleIndex(i);Gn(As,3*n,c,h),As.a.applyMatrix4(Ps),As.b.applyMatrix4(Ps),As.c.applyMatrix4(Ps),As.needsUpdate=!0;for(let t=0,i=3*e;t<i;t+=3)if(Gn(Ts,t,u,d),Ts.needsUpdate=!0,As.intersectsTriangle(Ts))return!0}}}}const Ds=new o,ks=new Tn,Bs=new Tn,Os=new l,Vs=new l,Ns=new l,Ls=new l;function Fs(e,t,i,n={},s={},r=0,o=1/0){t.boundingBox||t.computeBoundingBox(),ks.set(t.boundingBox.min,t.boundingBox.max,i),ks.needsUpdate=!0;const a=e.geometry,l=a.attributes.position,c=a.index,h=t.attributes.position,u=t.index,d=En.getPrimitive(),p=En.getPrimitive();let f=Os,m=Vs,g=null,w=null;s&&(g=Ns,w=Ls);let y=1/0,_=null,b=null;return Ds.copy(i).invert(),Bs.matrix.copy(Ds),e.shapecast({boundsTraverseOrder:e=>ks.distanceToBox(e),intersectsBounds:(e,t,i)=>i<y&&i<o&&(t&&(Bs.min.copy(e.min),Bs.max.copy(e.max),Bs.needsUpdate=!0),!0),intersectsRange:(n,s)=>{if(t.boundsTree){const a=t.boundsTree;return a.shapecast({boundsTraverseOrder:e=>Bs.distanceToBox(e),intersectsBounds:(e,t,i)=>i<y&&i<o,intersectsRange:(t,o)=>{for(let v=t,x=t+o;v<x;v++){const t=a.resolveTriangleIndex(v);Gn(p,3*t,u,h),p.a.applyMatrix4(i),p.b.applyMatrix4(i),p.c.applyMatrix4(i),p.needsUpdate=!0;for(let t=n,i=n+s;t<i;t++){const i=e.resolveTriangleIndex(t);Gn(d,3*i,c,l),d.needsUpdate=!0;const n=d.distanceToTriangle(p,f,g);if(n<y&&(m.copy(f),w&&w.copy(g),y=n,_=t,b=v),n<r)return!0}}}})}for(let o=0,a=fn(t);o<a;o++){Gn(p,3*o,u,h),p.a.applyMatrix4(i),p.b.applyMatrix4(i),p.c.applyMatrix4(i),p.needsUpdate=!0;for(let t=n,i=n+s;t<i;t++){const i=e.resolveTriangleIndex(t);Gn(d,3*i,c,l),d.needsUpdate=!0;const n=d.distanceToTriangle(p,f,g);if(n<y&&(m.copy(f),w&&w.copy(g),y=n,_=t,b=o),n<r)return!0}}}}),En.releasePrimitive(d),En.releasePrimitive(p),y===1/0?null:(n.point?n.point.copy(m):n.point=m.clone(),n.distance=y,n.faceIndex=_,s&&(s.point?s.point.copy(w):s.point=w.clone(),s.point.applyMatrix4(Ds),m.applyMatrix4(Ds),s.distance=m.sub(s.point).length(),s.faceIndex=b),n)}function Rs(e,t,i){return null===e?null:(e.point.applyMatrix4(t.matrixWorld),e.distance=e.point.distanceTo(i.ray.origin),e.object=t,e)}const Us=new Tn,js=new g,$s=new l,Ws=new o,Hs=new l,Gs=["getX","getY","getZ"];class Zs extends wn{static serialize(e,t={}){t={cloneBuffers:!0,...t};const i=e.geometry,n=e._roots,s=e._indirectBuffer,r=i.getIndex(),o={version:1,roots:null,index:null,indirectBuffer:null};return t.cloneBuffers?(o.roots=n.map(e=>e.slice()),o.index=r?r.array.slice():null,o.indirectBuffer=s?s.slice():null):(o.roots=n,o.index=r?r.array:null,o.indirectBuffer=s),o}static deserialize(e,t,i={}){i={setIndex:!0,indirect:Boolean(e.indirectBuffer),...i};const{index:n,roots:s,indirectBuffer:r}=e;e.version||(console.warn("MeshBVH.deserialize: Serialization format has been changed and will be fixed up. It is recommended to regenerate any stored serialized data."),function(e){for(let t=0;t<e.length;t++){const i=e[t],n=new Uint32Array(i),s=new Uint16Array(i);for(let e=0,t=i.byteLength/di;e<t;e++){const t=8*e;xi(2*t,s)||(n[t+6]=n[t+6]/8-e)}}}(s));const o=new Zs(t,{...i,[fi]:!0});if(o._roots=s,o._indirectBuffer=r||null,i.setIndex){const i=t.getIndex();if(null===i){const i=new a(e.index,1,!1);t.setIndex(i)}else i.array!==n&&(i.array.set(n),i.needsUpdate=!0)}return o}get primitiveStride(){return 3}get resolveTriangleIndex(){return this.resolvePrimitiveIndex}constructor(e,t={}){t.maxLeafTris&&(console.warn('MeshBVH: "maxLeafTris" option has been deprecated. Use maxLeafSize, instead.'),t={...t,maxLeafSize:t.maxLeafTris}),super(e,t)}shiftTriangleOffsets(e){return super.shiftPrimitiveOffsets(e)}writePrimitiveBounds(e,t,i){const n=this.geometry,s=this._indirectBuffer,r=n.attributes.position,o=n.index?n.index.array:null,a=3*(s?s[e]:e);let l=a+0,c=a+1,h=a+2;o&&(l=o[l],c=o[c],h=o[h]);for(let e=0;e<3;e++){const n=r[Gs[e]](l),s=r[Gs[e]](c),o=r[Gs[e]](h);let a=n;s<a&&(a=s),o<a&&(a=o);let u=n;s>u&&(u=s),o>u&&(u=o),t[i+e]=a,t[i+e+3]=u}return t}computePrimitiveBounds(e,t,i){const n=this.geometry,s=this._indirectBuffer,r=n.attributes.position,o=n.index?n.index.array:null,a=r.normalized;if(e<0||t+e-i.offset>i.length/6)throw new Error("MeshBVH: compute triangle bounds range is invalid.");const l=r.array,c=r.offset||0;let h=3;r.isInterleavedBufferAttribute&&(h=r.data.stride);const u=["getX","getY","getZ"],d=i.offset;for(let n=e,p=e+t;n<p;n++){const e=3*(s?s[n]:n),t=6*(n-d);let p=e+0,f=e+1,m=e+2;o&&(p=o[p],f=o[f],m=o[m]),a||(p=p*h+c,f=f*h+c,m=m*h+c);for(let e=0;e<3;e++){let n,s,o;a?(n=r[u[e]](p),s=r[u[e]](f),o=r[u[e]](m)):(n=l[p+e],s=l[f+e],o=l[m+e]);let c=n;s<c&&(c=s),o<c&&(c=o);let h=n;s>h&&(h=s),o>h&&(h=o);const d=(h-c)/2,g=2*e;i[t+g+0]=c+d,i[t+g+1]=d+(Math.abs(c)+d)*pi}}return i}raycastObject3D(e,t,i=[]){const{material:n}=e;if(void 0===n)return;Ws.copy(e.matrixWorld).invert(),js.copy(t.ray).applyMatrix4(Ws),Hs.setFromMatrixScale(e.matrixWorld),$s.copy(js.direction).multiply(Hs);const s=$s.length(),r=t.near/s,o=t.far/s;if(!0===t.firstHitOnly){let s=this.raycastFirst(js,n,r,o);s=Rs(s,e,t),s&&i.push(s)}else{const s=this.raycast(js,n,r,o);for(let n=0,r=s.length;n<r;n++){const r=Rs(s[n],e,t);r&&i.push(r)}}return i}refit(e=null){return(this.indirect?ys:qn)(this,e)}raycast(e,t=w,i=0,n=1/0){const s=this._roots,r=[],o=this.indirect?_s:Kn;for(let a=0,l=s.length;a<l;a++)o(this,a,t,e,r,i,n);return r}raycastFirst(e,t=w,i=0,n=1/0){const s=this._roots;let r=null;const o=this.indirect?xs:es;for(let a=0,l=s.length;a<l;a++){const s=o(this,a,t,e,i,n);null!=s&&(null==r||s.distance<r.distance)&&(r=s)}return r}intersectsGeometry(e,t){let i=!1;const n=this._roots,s=this.indirect?Is:ls;for(let r=0,o=n.length;r<o&&(i=s(this,r,e,t),!i);r++);return i}shapecast(e){const t=En.getPrimitive(),i=super.shapecast({...e,intersectsPrimitive:e.intersectsTriangle,scratchPrimitive:t,iterate:this.indirect?Xn:Zn});return En.releasePrimitive(t),i}bvhcast(e,t,i){let{intersectsRanges:n,intersectsTriangles:s}=i;const r=En.getPrimitive(),o=this.geometry.index,a=this.geometry.attributes.position,l=this.indirect?e=>{const t=this.resolveTriangleIndex(e);Gn(r,3*t,o,a)}:e=>{Gn(r,3*e,o,a)},c=En.getPrimitive(),h=e.geometry.index,u=e.geometry.attributes.position,d=e.indirect?t=>{const i=e.resolveTriangleIndex(t);Gn(c,3*i,h,u)}:e=>{Gn(c,3*e,h,u)};if(s){if(!(e instanceof Zs))throw new Error('MeshBVH: "intersectsTriangles" callback can only be used with another MeshBVH.');const i=(e,i,n,o,a,h,u,p)=>{for(let f=n,m=n+o;f<m;f++){d(f),c.a.applyMatrix4(t),c.b.applyMatrix4(t),c.c.applyMatrix4(t),c.needsUpdate=!0;for(let t=e,n=e+i;t<n;t++)if(l(t),r.needsUpdate=!0,s(r,c,t,f,a,h,u,p))return!0}return!1};if(n){const e=n;n=function(t,n,s,r,o,a,l,c){return!!e(t,n,s,r,o,a,l,c)||i(t,n,s,r,o,a,l,c)}}else n=i}return super.bvhcast(e,t,{intersectsRanges:n})}intersectsBox(e,t){return Us.set(e.min,e.max,t),Us.needsUpdate=!0,this.shapecast({intersectsBounds:e=>Us.intersectsBox(e),intersectsTriangle:e=>Us.intersectsTriangle(e)})}intersectsSphere(e){return this.shapecast({intersectsBounds:t=>e.intersectsBox(t),intersectsTriangle:t=>t.intersectsSphere(e)})}closestPointToGeometry(e,t,i={},n={},s=0,r=1/0){return(this.indirect?Fs:ws)(this,e,t,i,n,s,r)}closestPointToPoint(e,t={},i=0,n=1/0){return function(e,t,i={},n=0,s=1/0){const r=n*n,o=s*s;let a=1/0,l=null;if(e.shapecast({boundsTraverseOrder:e=>(Mn.copy(t).clamp(e.min,e.max),Mn.distanceToSquared(t)),intersectsBounds:(e,t,i)=>i<a&&i<o,intersectsTriangle:(e,i)=>{e.closestPointToPoint(t,Mn);const n=t.distanceToSquared(Mn);return n<a&&(In.copy(Mn),a=n,l=i),n<r}}),a===1/0)return null;const c=Math.sqrt(a);return i.point?i.point.copy(In):i.point=In.clone(),i.distance=c,i.faceIndex=l,i}(this,e,t,i,n)}}const qs=new o,Ys=new g,Xs=new Hi(()=>new c),Ks=new l,Qs=new l,Js=new r,er=["getX","getY","getZ"];class tr extends wn{get primitiveStride(){return 2}writePrimitiveBounds(e,t,i){const n=this._indirectBuffer,{geometry:s,primitiveStride:r}=this,o=s.attributes.position,a=s.index,l=a?a.count:o.count;let c=(n?n[e]:e)*r,h=(c+1)%l;a&&(c=a.getX(c),h=a.getX(h));for(let e=0;e<3;e++){const n=o[er[e]](c),s=o[er[e]](h),r=n<s?n:s,a=n>s?n:s;t[i+e]=r,t[i+e+3]=a}return t}shapecast(e){const t=Xs.getPrimitive(),i=super.shapecast({...e,intersectsPrimitive:e.intersectsLine,scratchPrimitive:t,iterate:ir});return Xs.releasePrimitive(t),i}raycastObject3D(e,t,i=[]){const{matrixWorld:n}=e,{firstHitOnly:s}=t;qs.copy(n).invert(),Ys.copy(t.ray).applyMatrix4(qs);const r=t.params.Line.threshold/((e.scale.x+e.scale.y+e.scale.z)/3),o=r*r;let a=null,l=1/0;return this.shapecast({boundsTraverseOrder:e=>e.distanceToPoint(Ys.origin),intersectsBounds:e=>(Js.copy(e).expandByScalar(Math.abs(r)),Ys.intersectsBox(Js)?1:0),intersectsLine:(r,c)=>{if(Ys.distanceSqToSegment(r.start,r.end,Ks,Qs)>o)return;Ks.applyMatrix4(e.matrixWorld);const h=t.ray.origin.distanceTo(Ks);h<t.near||h>t.far||s&&h>=l||(l=h,c=this.resolvePrimitiveIndex(c),a={distance:h,point:Qs.clone().applyMatrix4(n),index:c*this.primitiveStride,face:null,faceIndex:null,barycoord:null,object:e},s||i.push(a))}}),s&&a&&i.push(a),i}}function ir(e,t,i,n,s,r,o){const{geometry:a,primitiveStride:l}=i,{index:c}=a,h=a.attributes.position,u=c?c.count:h.count;for(let a=e,d=t+e;a<d;a++){let e=i.resolvePrimitiveIndex(a)*l,t=(e+1)%u;if(c&&(e=c.getX(e),t=c.getX(t)),o.start.fromBufferAttribute(h,e),o.end.fromBufferAttribute(h,t),n(o,a,s,r))return!0}return!1}const nr={Mesh:y.prototype.raycast,Line:v.prototype.raycast,LineSegments:_.prototype.raycast,LineLoop:b.prototype.raycast,Points:x.prototype.raycast,BatchedMesh:S.prototype.raycast},sr=new y,rr=[];function or(e,t){if(this.isBatchedMesh)ar.call(this,e,t);else{const{geometry:i}=this;if(i.boundsTree)i.boundsTree.raycastObject3D(this,e,t);else{let i;if(this instanceof y)i=nr.Mesh;else if(this instanceof _)i=nr.LineSegments;else if(this instanceof b)i=nr.LineLoop;else if(this instanceof v)i=nr.Line;else{if(!(this instanceof x))throw new Error("BVH: Fallback raycast function not found.");i=nr.Points}i.call(this,e,t)}}}function ar(e,t){if(this.boundsTrees){const i=this.boundsTrees,n=this._drawInfo||this._instanceInfo,s=this._drawRanges||this._geometryInfo,r=this.matrixWorld;sr.material=this.material,sr.geometry=this.geometry;const o=sr.geometry.boundsTree,a=sr.geometry.drawRange;null===sr.geometry.boundingSphere&&(sr.geometry.boundingSphere=new C);for(let o=0,a=n.length;o<a;o++){if(!this.getVisibleAt(o))continue;const a=n[o].geometryIndex;if(sr.geometry.boundsTree=i[a],this.getMatrixAt(o,sr.matrixWorld).premultiply(r),!sr.geometry.boundsTree){this.getBoundingBoxAt(a,sr.geometry.boundingBox),this.getBoundingSphereAt(a,sr.geometry.boundingSphere);const e=s[a];sr.geometry.setDrawRange(e.start,e.count)}sr.raycast(e,rr);for(let e=0,i=rr.length;e<i;e++){const i=rr[e];i.object=this,i.batchId=o,t.push(i)}rr.length=0}sr.geometry.boundsTree=o,sr.geometry.drawRange=a,sr.material=null,sr.geometry=null}else nr.BatchedMesh.call(this,e,t)}function lr(e={}){const{type:t=Zs}=e;return this.boundsTree=new t(this,e),this.boundsTree}function cr(){this.boundsTree=null}class hr extends le{static getWorker(){return i.getWorker()}static uuid="fef46874-46a3-461b-8c44-2922ab77c806";onDisposed=new re;onBeforeDispose=new re;onFragmentsLoaded=new re;baseCoordinationModel="";baseCoordinationMatrix=new s.Matrix4;enabled=!0;get initialized(){return!!this._core}_core;get list(){return this.core.models.list}get core(){if(!this._core)throw new Error("FragmentsManager not initialized. Call init() first.");return this._core}get _hasCoordinationModel(){return""!==this.baseCoordinationModel}constructor(e){super(e),this.components.add(hr.uuid,this)}dispose(){this.onBeforeDispose.trigger(),this._core&&(this.core.dispose(),this._core=void 0),this.baseCoordinationModel="",this.onFragmentsLoaded.reset(),this.onDisposed.trigger(),this.onDisposed.reset()}init(e,t){this._core=new i(e,t),this.core.onModelLoaded.add(async()=>{if(this._hasCoordinationModel)return;const e=[...this.list.values()][0];e&&(this.baseCoordinationModel=e.modelId,this.baseCoordinationMatrix=await e.getCoordinationMatrix())}),this.list.onItemDeleted.add(()=>{this.list.size>0||(this.baseCoordinationModel="",this.baseCoordinationMatrix=new s.Matrix4)})}async raycast(e){const t=[];for(const i of this.core.models.list.values())if(e.snappingClasses&&e.snappingClasses.length>0){const n=await i.raycastWithSnapping(e);if(n&&n.length>0)t.push(n[0]);else{const n=await i.raycast(e);n&&t.push(n)}}else{const n=await i.raycast(e);n&&t.push(n)}if(await Promise.all(t),0===t.length)return;let i=t[0],n=i.distance;for(let e=1;e<t.length;e++)t[e].distance<n&&(n=t[e].distance,i=t[e]);return i}async getPositions(e){const t=[],i=async(e,i)=>{const n=await e.getPositions(i);for(const e of n)t.push(e)},n=[];for(const t in e){const s=this.core.models.list.get(t);s&&n.push(i(s,Array.from(e[t])))}return await Promise.all(n),t}async getBBoxes(e){const t=[],i=async(e,i)=>{const n=await e.getBoxes(i);if(n)for(const e of n)t.push(e)},n=[];for(const t in e){const s=this.core.models.list.get(t);s&&n.push(i(s,Array.from(e[t])))}return await Promise.all(n),t}async highlight(e,t){await this.forEachModel(t,"highlight",e)}async getData(e,t){const i={};for(const[n,s]of Object.entries(e)){const e=this.list.get(n);if(!e)continue;if(0===s.size){i[n]=[];continue}const r=await e.getItemsData([...s],t);i[n]=r}return i}async resetHighlight(e){await this.forEachModel(e,"resetHighlight")}async forEachModel(e,t,...i){const n={};if(e)for(const t in e){const i=e[t];n[t]=Array.from(i)}else for(const e of this.core.models.list.keys())n[e]=void 0;const s=[];for(const e in n){const r=this.core.models.list.get(e);if(r){const o=n[e],a=r[t](o,...i);s.push(a)}}await Promise.all(s)}async guidsToModelIdMap(e){const t={};for(const[i,n]of this.list){const s=(await n.getLocalIdsByGuids([...e])).filter(e=>null!==e);t[i]=new Set(s)}return t}async modelIdMapToGuids(e){const t=[];for(const[i,n]of Object.entries(e)){const e=this.list.get(i);if(!e)continue;const s=(await e.getGuidsByLocalIds([...n])).filter(e=>null!==e);t.push(...s)}return t}applyBaseCoordinateSystem(e,t){const i=new s.Matrix4;return t&&i.copy(t.clone()).invert(),i.multiply(this.baseCoordinationMatrix),e.applyMatrix4(i),i}}function ur(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16}function dr(e){if(e&&e.aborted)throw new Error("VisibilityCuller: Process aborted via AbortSignal.")}class pr{constructor(e,t={}){const{pixelsPerMeter:i=.1}=t;this.pixelsPerMeter=i,this.renderer=e}async cull(e,t={}){const{signal:i=null}=t;dr(i),e=function(e){const t=new Set;return e.traverse(e=>{e.isMesh&&t.add(e)}),Array.from(t)}(e);const{renderer:n,pixelsPerMeter:s}=this,o=new l,a=new A,c=new r,h=new T(1,1);c.makeEmpty(),e.forEach(e=>{c.expandByObject(e)}),c.getSize(o);const u=Math.min(n.capabilities.maxTextureSize,8192),d=Math.ceil(o.x/s),p=Math.ceil(o.z/s),f=Math.ceil(d/u),m=Math.ceil(p/u);h.setSize(Math.ceil(d/f),Math.ceil(p/m));const g=.01*Math.max(o.y,1);a.rotation.x=-Math.PI/2,a.near=0,a.far=o.y+2*g,a.position.y=c.max.y+g;const w=new P,y=new Map,_=new Map,b=[];for(let t=0;t<e.length;t++){const i=e[t];y.set(i,i.material),_.set(i,i.parent);const n=new fr;n.objectId=t,b.push(n),i.material=n,w.add(i)}const v=n.getClearColor(new E),x=n.getClearAlpha(),C=n.getRenderTarget(),S=n.autoClear,M=new Uint8Array(h.width*h.height*4),I=new Set,z=o.x/f,D=o.z/m;let k=!1;const B=()=>{if(!k){k=!0,i&&i.removeEventListener("abort",B);for(const t of e){t.material=y.get(t);const e=_.get(t);e?e.add(t):w.remove(t)}n.setClearColor(v,x),n.setRenderTarget(C),n.autoClear=S;for(const e of b)e.dispose();h.dispose()}};i&&i.addEventListener("abort",B);try{n.autoClear=!0,n.setClearColor(0,0),n.setRenderTarget(h);for(let t=0;t<f;t++)for(let s=0;s<m;s++){const r=c.min.x+z*t,o=r+z,l=c.min.z+D*s,u=(r+o)/2,d=(l+(l+D))/2;a.position.set(u,c.max.y+g,d);const p=z/2,f=D/2;a.left=-p,a.right=p,a.top=f,a.bottom=-f,a.updateProjectionMatrix(),dr(i),n.render(w,a);const m=await n.readRenderTargetPixelsAsync(h,0,0,h.width,h.height,M);dr(i);for(let t=0,i=m.length;t<i;t+=4){if(0===m[t+3])continue;const i=ur(m,t);I.add(e[i])}}}finally{B()}return Array.from(I)}}class fr extends M{get objectId(){return this._objectId}set objectId(e){var t,i;this._objectId=e,t=e,(i=this.uniforms.objectId.value).x=(255&t)/255,i.y=(t>>8&255)/255,i.z=(t>>16&255)/255,i.w=1}constructor(e){super({glslVersion:D,blending:z,side:f,uniforms:{objectId:{value:new I}},vertexShader:"\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\t\t\t\tlayout(location = 0) out vec4 out_id;\n\t\t\t\tuniform vec4 objectId;\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tout_id = objectId;\n\n\t\t\t\t}\n\t\t\t"}),this._objectId=0,this.setValues(e)}}const mr=1e-16,gr=new l(0,1,0),wr=new l;function yr(e){return e.delta(wr).normalize(),Math.abs(wr.dot(gr))>=1-mr}function _r(e,t){const{start:i,end:n}=t,s=e.points;let r=!1,o=!1;for(let e=0;e<3;e++){const t=s[e];if(!r&&i.distanceToSquared(t)<=mr&&(r=!0),!o&&n.distanceToSquared(t)<=mr&&(o=!0),r&&o)return!0}return r&&o}const br=new c;function vr(e,t,i=!1,n=[]){let s=[[0,1]];for(let e=0,i=t.length;e<i;e++){const i=s[e],n=t[e];i[1]=n[0],s.push([n[1],1])}i&&([t,s]=[s,t]);for(let t=0,i=s.length;t<i;t++){const{start:i,end:r}=e;br.start.lerpVectors(i,r,s[t][0]),br.end.lerpVectors(i,r,s[t][1]),n.push(new Float32Array([br.start.x,br.start.y,br.start.z,br.end.x,br.end.y,br.end.z]))}return n}const xr=new l(0,1,0),Cr=new l,Sr=new l,Ar=new l,Tr=new d;function*Pr(e,t=[],i={}){const{projectionDirection:n=xr,thresholdAngle:s=1,iterationTime:r=30}=i,o=Math.pow(10,4),a=Math.cos(k.DEG2RAD*s),l=e.getIndex(),h=e.getAttribute("position"),u=l?l.count:h.count,d=[0,0,0],p=["a","b","c"],f=new Array(3),m={};let g=performance.now();for(let e=0;e<u;e+=3){performance.now()-g>r&&(yield,g=performance.now()),l?(d[0]=l.getX(e),d[1]=l.getX(e+1),d[2]=l.getX(e+2)):(d[0]=e,d[1]=e+1,d[2]=e+2);const{a:i,b:s,c:u}=Tr;if(i.fromBufferAttribute(h,d[0]),s.fromBufferAttribute(h,d[1]),u.fromBufferAttribute(h,d[2]),Tr.getNormal(Ar),f[0]=`${Math.round(i.x*o)},${Math.round(i.y*o)},${Math.round(i.z*o)}`,f[1]=`${Math.round(s.x*o)},${Math.round(s.y*o)},${Math.round(s.z*o)}`,f[2]=`${Math.round(u.x*o)},${Math.round(u.y*o)},${Math.round(u.z*o)}`,f[0]!==f[1]&&f[1]!==f[2]&&f[2]!==f[0])for(let e=0;e<3;e++){const i=(e+1)%3,s=f[e],r=f[i],o=Tr[p[e]],l=Tr[p[i]],h=`${s}_${r}`,u=`${r}_${s}`;if(u in m&&m[u]){const e=m[u].normal,i=Ar.dot(e)<=a;let s=!1;if(null!==n){let t=n.dot(Ar);t=Math.abs(t)<1e-10?0:t;let i=n.dot(e);i=Math.abs(i)<1e-10?0:i,s=Math.sign(t)!==Math.sign(i)}if(i||s){const e=new c;e.start.copy(o),e.end.copy(l),t.push(e)}m[u]=null}else h in m||(m[h]={index0:d[e],index1:d[i],normal:Ar.clone()})}}for(const e in m)if(m[e]){const{index0:i,index1:n}=m[e];Cr.fromBufferAttribute(h,i),Sr.fromBufferAttribute(h,n);const s=new c;s.start.copy(Cr),s.end.copy(Sr),t.push(s)}return t}const Er=new c;function Mr(e,t,i,n=[]){return e.bvhcast(t,i,{intersectsTriangles:(e,t)=>!function(e,t){const i=["a","b","c"];let n=0;for(let s=0;s<3;s++)for(let r=0;r<3;r++){Ir(e[i[s]],t[i[r]])&&n++}return n>=2}(e,t)&&(e.needsUpdate&&e.update(),t.needsUpdate&&t.update(),!(Math.abs(e.plane.normal.dot(t.plane.normal))>.999999)&&void(!e.intersectsTriangle(t,Er,!0)||_r(e,Er)||_r(t,Er)||n.push(Er.clone())))}),n}function Ir(e,t){return e.distanceTo(t)<1e-10}function zr(e){Dr(e);let t=[];return e.traverse(e=>{e.geometry&&e.visible&&t.push(e)}),t}const Dr=e=>{if(void 0===e)return;const t=[...e.children];for(const i of t)void 0===i?e.children.splice(e.children.indexOf(i),1):Dr(i)},kr=new o,Br=new o;class Or{constructor(){this.projectionDirection=new l(0,1,0),this.thresholdAngle=50,this.iterationTime=30}getEdges(...e){const t=this.iterationTime;this.iterationTime=1/0;const i=this.getEdgesGenerator(...e).next().value;return this.iterationTime=t,i}*getEdgesGenerator(e,t=[],i=null){const{projectionDirection:n,thresholdAngle:s,iterationTime:r}=this;if(e.isObject3D){const o=zr(e);let a=null;n&&(a=new l);let c=performance.now();for(let e=0;e<o.length;e++){performance.now()-c>r&&(yield,c=performance.now());const l=o[e];a&&(Br.copy(l.matrixWorld).invert(),a.copy(n).transformDirection(Br).normalize());const h=yield*Pr(l.geometry,[],{projectionDirection:a,thresholdAngle:s,iterationTime:r});Vr(h,l.matrixWorld);for(let e=0;e<h.length;e++)t.push(h[e]);if(null!==i)for(let e=0;e<h.length;e++)i.push(l)}return t}return yield*Pr(e,t,{projectionDirection:n,thresholdAngle:s,iterationTime:r})}getIntersectionEdges(...e){const t=this.iterationTime;this.iterationTime=1/0;const i=this.getIntersectionEdgesGenerator(...e).next().value;return this.iterationTime=t,i}*getIntersectionEdgesGenerator(e,t=[],i=null){const{iterationTime:n}=this;if(e.isObject3D){const s=zr(e),r=new Map;let o=performance.now();for(let e=0;e<s.length;e++){performance.now()-o>n&&(yield,o=performance.now());const t=s[e].geometry;if(!r.has(t)){const e=t.boundsTree||new Zs(t,{maxLeafSize:1});r.set(t,e)}}o=performance.now();for(let e=0;e<s.length;e++)for(let a=e;a<s.length;a++){performance.now()-o>n&&(yield,o=performance.now());const l=s[e],c=s[a],h=r.get(l.geometry),u=r.get(c.geometry);kr.copy(l.matrixWorld).invert().multiply(c.matrixWorld);const d=Mr(h,u,kr,[]);Vr(d,l.matrixWorld);for(let e=0;e<d.length;e++)t.push(d[e]);if(null!==i)for(let e=0;e<d.length;e++)i.push(l)}return t}{let i;return e.isBufferGeometry?i=e.boundsTree||new Zs(e,{maxLeafSize:1}):(i=e,e=i.geometry),kr.identity(),Mr(i,i,kr,t)}}}function Vr(e,t,i=1e-6){for(let n=0;n<e.length;n++){const s=e[n];s.applyMatrix4(t),s.start.y+=i,s.end.y+=i}}class Nr extends dn{get lines(){return this.primitiveBuffer}constructor(e,t){super(t),this.primitiveBuffer=e,this.primitiveBufferStride=1,this.heightOffset=t.heightOffset??1e3,this.init(t)}writePrimitiveBounds(e,t,i){const{primitiveBuffer:n,heightOffset:s}=this,{start:r,end:o}=n[e];t[i+0]=Math.min(r.x,o.x),t[i+1]=Math.min(r.y,o.y),t[i+2]=Math.min(r.z,o.z),t[i+3]=Math.max(r.x,o.x),t[i+4]=Math.max(r.y,o.y)+s,t[i+5]=Math.max(r.z,o.z)}getRootRanges(){return[{offset:0,count:this.primitiveBuffer.length}]}}const Lr=new l(0,1,0),Fr=new h,Rr=new l,Ur=new l;function jr(e,t,i){e.needsUpdate&&e.update(),Fr.copy(e.plane),Fr.normal.dot(Lr)<0&&(Fr.normal.multiplyScalar(-1),Fr.constant*=-1);const n=Fr.distanceToPoint(t.start),s=Fr.distanceToPoint(t.end),r=Math.abs(n)<1e-16,o=n<0,a=s<0;if(t.delta(Ur).normalize(),Math.abs(Fr.normal.dot(Ur))<1e-16)return!(r||!o)&&(i.copy(t),!0);if(o&&a)return i.copy(t),!0;if(!o&&!a)return!1;{const e=k.mapLinear(0,n,s,0,1);if(t.at(e,Rr),o)return i.start.copy(t.start),i.end.copy(Rr),!0;if(a)return i.end.copy(t.end),i.start.copy(Rr),!0}return!1}const $r=new h,Wr=new l,Hr=new l,Gr=new An,Zr=new c,qr=new c,Yr=new l,Xr=new l,Kr=new l;function Qr(e,t,i=new c){if(Gr.copy(t),Gr.a.y=0,Gr.b.y=0,Gr.c.y=0,Gr.update(),Zr.copy(e),Zr.start.y=0,Zr.end.y=0,Gr.getArea()<=1e-16)return null;const n=Zr.distance();Zr.delta(Yr).divideScalar(n),Xr.copy(Yr).cross(Gr.plane.normal).normalize(),$r.setFromNormalAndCoplanarPoint(Xr,Zr.start);let s=0;const{points:r}=Gr;for(let e=0;e<3;e++){const t=r[e],i=r[(e+1)%3],n=$r.distanceToPoint(t),o=$r.distanceToPoint(i),a=Math.abs(n)<1e-16,l=Math.abs(o)<1e-16;let c=!1;if(!a&&!l&&n*o<0){const e=n/(n-o);Wr.lerpVectors(t,i,e),c=!0}if((c&&!l||a)&&(a&&!c&&Wr.copy(t),0===s?qr.start.copy(Wr):qr.end.copy(Wr),s++,2===s))break}if(2===s){if(qr.delta(Kr).normalize(),Yr.dot(Kr)<0){const e=qr.start;qr.start=qr.end,qr.end=e}const t=0,s=Hr.subVectors(Zr.end,Zr.start).dot(Yr),r=Hr.subVectors(qr.start,Zr.start).dot(Yr),o=Hr.subVectors(qr.end,Zr.start).dot(Yr);return s<=r||o<=t?null:(e.at(Math.max(t,r)/n,i.start),e.at(Math.min(s,o)/n,i.end),i)}return null}const Jr=new l,eo=new l,to=new l;function io(e,t,i){const n=function(e,t){e.delta(Jr),eo.subVectors(t.start,e.start),to.subVectors(t.end,e.start);const i=Jr.length();let n=eo.length()/i,s=to.length()/i;if(n=Math.min(Math.max(n,0),1),s=Math.min(Math.max(s,0),1),Math.abs(n-s)<=1e-16)return null;return[n,s]}(e,t);return!!n&&(no(n,i),!0)}function no(e,t){let[i,n]=e,s=0,r=t.length;for(;s<r;){const e=s+r>>>1;t[e][0]<=i?s=e+1:r=e}let o=Math.max(0,s-1),a=0;for(let e=o,s=t.length;e<s;e++){const[s,r]=t[e];if(i<=r&&n>=s)i=Math.min(s,i),n=Math.max(r,n),a++;else{if(!(i>=s))break;o=e+1}}t.splice(o,a,[i,n])}const so=new l(0,1,0),ro=new c,oo=new c,ao=new An;function lo(e,t,i,n,s=null){const{geometry:r,matrixWorld:o,material:a}=i,l=a.side,c=o.determinant()<0,h=e.lines;e.bvhcast(t,o,{intersectsRanges:(e,t,i,a)=>{s&&(s.candidates+=t*a);for(let u=i,d=a+i;u<d;u++){let i=3*u+0,a=3*u+1,d=3*u+2;r.index&&(i=r.index.getX(i),a=r.index.getX(a),d=r.index.getX(d));const{a:m,b:g,c:w}=ao;if(m.fromBufferAttribute(r.attributes.position,i).applyMatrix4(o),g.fromBufferAttribute(r.attributes.position,a).applyMatrix4(o),w.fromBufferAttribute(r.attributes.position,d).applyMatrix4(o),ao.needsUpdate=!0,ao.update(),l!==f){if(ao.plane.normal.dot(so)!==c===(l===p)){s&&(s.backFaceCulled+=t);continue}}const y=Math.max(m.y,g.y,w.y),_=Math.min(m.y,g.y,w.y),b=ao.plane.normal;let v=b.x,x=b.y,C=b.z,S=ao.plane.constant;x<0&&(v=-v,x=-x,C=-C,S=-S);for(let i=e,r=t+e;i<r;i++){const e=h[i],t=Math.min(e.start.y,e.end.y),r=Math.max(e.start.y,e.end.y);if(y<=t){s&&s.yBoundsCulled++;continue}const o=e.end.x-e.start.x,a=e.end.z-e.start.z,l=o*o+a*a;if(l>1e-20){const t=1/Math.sqrt(l),i=o*t,n=a*t,r=-n,c=i,h=m.x-e.start.x,u=m.z-e.start.z,d=g.x-e.start.x,p=g.z-e.start.z,f=w.x-e.start.x,y=w.z-e.start.z,_=h*i+u*n,b=d*i+p*n,v=f*i+y*n,x=1/t,C=Math.min(_,b,v);if(Math.max(_,b,v)<0||C>x){s&&s.xzBoundsCulled++;continue}const S=h*r+u*c,A=d*r+p*c,T=f*r+y*c,P=Math.min(S,A,T),E=Math.max(S,A,T);if(P>0||E<0){s&&s.xzBoundsCulled++;continue}}const c=v*e.start.x+x*e.start.y+C*e.start.z+S,u=v*e.end.x+x*e.end.y+C*e.end.z+S;if(c>=0&&u>=0)s&&s.planeTrimCulled++;else if(_r(ao,e))s&&s.triangleEdgeCulled++;else{if(r<_)ro.copy(e);else if(!jr(ao,e,ro)){s&&s.planeTrimCulled++;continue}ro.distance()<1e-10?s&&s.distThresholdCulled++:Qr(ro,ao,oo)?(s&&s.used++,io(e,oo,n[i])):s&&s.noOverlapCulled++}}}}})}ao.update=()=>{ao.plane.setFromCoplanarPoints(...ao.points)};let co=!1;const ho={},uo={};let po=null,fo=0,mo=0;const go={get enabled(){return co},set enabled(e){co=e},reset(){for(const e in ho)delete ho[e];for(const e in uo)delete uo[e];po=null,fo=0,mo=0},setStat(e,t){uo[e]=t},startTotal(){co&&(mo=performance.now())},startStep(e){co&&(null!==po&&this.endStep(),po=e,fo=performance.now())},endStep(){if(!co||null===po)return;const e=performance.now()-fo;ho[po]=e,po=null},printSummary(){if(!co)return;null!==po&&this.endStep();const e=performance.now()-mo;console.log("\n=== Projection Summary ==="),console.log(`Total time: ${e.toFixed(1)}ms\n`);for(const[t,i]of Object.entries(ho)){const n=(i/e*100).toFixed(1);console.log(` ${t}: ${i.toFixed(1)}ms (${n}%)`)}if(Object.keys(uo).length>0){console.log("\n--- Stats ---");for(const[e,t]of Object.entries(uo))console.log(` ${e}: ${t}`)}console.log("")}},wo=1e-5,yo=1e-16,_o=1e-16;function bo(e,t,i,n,s){e.bvhcast(t,i.matrixWorld,{intersectsRanges:(e,t,i,r)=>{n._edgeOffsets.push(e),n._edgeCounts.push(t),n._meshOffsets.push(i),n._meshCounts.push(r),n._meshIndex.push(s),n.groupCount++}})}let vo=null;async function xo(e,t,i,n,s=null){const r=await async function(){return null===vo&&(vo=new O.WebGPURenderer,await vo.init()),vo}();e._edgeOffsets&&(e.edgeOffsets=new Uint32Array(e._edgeOffsets),e.edgeCounts=new Uint32Array(e._edgeCounts),e.meshOffsets=new Uint32Array(e._meshOffsets),e.meshCounts=new Uint32Array(e._meshCounts),e.meshIndex=new Uint32Array(e._meshIndex),e._edgeOffsets=null,e._edgeCounts=null,e._meshOffsets=null,e._meshCounts=null,e._meshIndex=null);const o=V(function(e){const t=new Float32Array(6*e.length);for(let i=0;i<e.length;i++){const n=e[i];t[6*i+0]=n.start.x,t[6*i+1]=n.start.y,t[6*i+2]=n.start.z,t[6*i+3]=n.end.x,t[6*i+4]=n.end.y,t[6*i+5]=n.end.z}return t}(i.lines),"float");go.enabled&&console.log("Number of meshes:",t.length),go.enabled&&console.log("Group count:",e.groupCount);const a=[];{let e=0;for(;e<t.length;){let i=e,n=0;for(;i<t.length;){const s=t[i].geometry,r=s.index?s.index.count/3:s.attributes.position.count/3;if(i>e&&(i-e>=1e3||n+r>1e5))break;n+=r,i++}a.push({start:e,end:i}),e=i}}go.enabled&&console.log(`Split ${t.length} meshes into ${a.length} batches`);let l=0,c=0,h=0,u=0,d=0;for(let i=0;i<a.length;i++){const{start:p,end:f}=a[i],m=f-p;go.enabled&&console.log(`Processing batch ${i+1}/${a.length} (meshes ${p}-${f-1})`);let g=0,w=0;const y=[];for(let e=p;e<f;e++){const i=t[e].geometry;y.push(w/3),g+=i.attributes.position.array.length,w+=i.index.array.length}const _=new Float32Array(g),b=new Uint32Array(w);let v=0,x=0,C=0;for(let e=p;e<f;e++){const i=t[e].geometry,n=i.attributes.position.array,s=i.index.array;_.set(n,v),v+=n.length;for(let e=0;e<s.length;e++)b[x+e]=s[e]+C;x+=s.length,C+=i.attributes.position.count}const S=new Float32Array(16*m);for(let e=p;e<f;e++){const i=e-p;S.set(t[e].matrixWorld.elements,16*i)}const A=[];for(let t=0;t<e.groupCount;t++){const i=e.meshIndex[t];if(i>=p&&i<f){const n=i-p,s=y[n]+e.meshOffsets[t];A.push({edgeOffset:e.edgeOffsets[t],edgeCount:e.edgeCounts[t],triOffset:s,triCount:e.meshCounts[t],meshIdx:n})}}if(0===A.length){go.enabled&&console.log(` Batch ${i+1}: no groups, skipping`);continue}const T=new Uint32Array(5*A.length);for(let e=0;e<A.length;e++){const t=A[e],i=5*e;T[i+0]=t.edgeOffset,T[i+1]=t.edgeCount,T[i+2]=t.triOffset,T[i+3]=t.triCount,T[i+4]=t.meshIdx}let P=0;for(let e=0;e<A.length;e++)P+=A[e].edgeCount*A[e].triCount;s&&(s.candidates+=P);let E=Math.min(Math.ceil(.1*P),2e6),M=Math.max(E,1e4);go.enabled&&console.log(` Batch ${i+1}: ${A.length} groups, ${g/3} vertices, ${w/3} triangles, ${P} pairs, buffer for ${M} overlaps`);const I=performance.now(),z=V(_,"float"),D=V(b,"uint"),k=V(S,"float"),B=V(T,"uint");let O=V(new Uint32Array([0]),"uint").toAtomic(),ie=V(new Float32Array(3*M),"float");u+=performance.now()-I;const ne=performance.now(),se=N(()=>{const e=L.mul(5),t=B.element(e),i=B.element(e.add(1)),n=B.element(e.add(2)),s=B.element(e.add(3)),r=B.element(e.add(4)).mul(16),a=F(k.element(r),k.element(r.add(1)),k.element(r.add(2)),k.element(r.add(3)),k.element(r.add(4)),k.element(r.add(5)),k.element(r.add(6)),k.element(r.add(7)),k.element(r.add(8)),k.element(r.add(9)),k.element(r.add(10)),k.element(r.add(11)),k.element(r.add(12)),k.element(r.add(13)),k.element(r.add(14)),k.element(r.add(15)));R({start:U(0),end:s.toInt(),type:"int",condition:"<",name:"triIdx"},({triIdx:e})=>{const s=n.add(e.toUint()).mul(3),r=D.element(s),l=D.element(s.add(1)),c=D.element(s.add(2)),h=j(z.element(r.mul(3)),z.element(r.mul(3).add(1)),z.element(r.mul(3).add(2))),u=j(z.element(l.mul(3)),z.element(l.mul(3).add(1)),z.element(l.mul(3).add(2))),d=j(z.element(c.mul(3)),z.element(c.mul(3).add(1)),z.element(c.mul(3).add(2))),p=a.mul($(h,W(1))).xyz,f=a.mul($(u,W(1))).xyz,m=a.mul($(d,W(1))).xyz,g=f.sub(p),w=m.sub(p),y=H(g,w),_=y.dot(y);G(_.lessThan(W(4e-16*yo)),()=>{Z()}),G(y.y.lessThan(0),()=>{Z()});const b=q(p.y,q(f.y,m.y));R({start:U(0),end:i.toInt(),type:"int",condition:"<",name:"edgeIdx"},({edgeIdx:e})=>{const i=t.add(e.toUint()),n=i.mul(6),s=j(o.element(n),o.element(n.add(1)),o.element(n.add(2))),r=j(o.element(n.add(3)),o.element(n.add(4)),o.element(n.add(5))),a=Y(s.y,r.y);G(b.lessThanEqual(a),()=>{Z()});const l=X(y),c=l.dot(p).negate(),h=l.y.lessThan(0),u=K(h,l.negate(),l),d=K(h,c.negate(),c),g=u.dot(s).add(d),w=u.dot(r).add(d),_=g.lessThan(0),v=w.lessThan(0),x=Q(g).lessThan(W(wo)),C=_.not().and(v.not()),S=w.sub(g),A=Q(S).lessThan(W(wo)),T=A.and(x.or(_.not()));G(T,()=>{Z()}),G(C.and(A.not()),()=>{Z()});const P=g.negate().div(S),E=J(s,r,P),I=j(K(A.or(_),s.x,E.x),K(A.or(_),s.y,E.y),K(A.or(_),s.z,E.z)),z=j(K(A.or(v),r.x,E.x),K(A.or(v),r.y,E.y),K(A.or(v),r.z,E.z)),D=z.sub(I),k=D.dot(D);G(k.lessThan(W(wo)),()=>{Z()});const B=s.sub(p),V=s.sub(f),N=s.sub(m),L=r.sub(p),F=r.sub(f),R=r.sub(m),U=B.dot(B).lessThanEqual(W(wo)),$=V.dot(V).lessThanEqual(W(wo)),ne=N.dot(N).lessThanEqual(W(wo)),se=L.dot(L).lessThanEqual(W(wo)),re=F.dot(F).lessThanEqual(W(wo)),oe=R.dot(R).lessThanEqual(W(wo)),ae=U.or($).or(ne),le=se.or(re).or(oe),ce=ae.and(le);G(ce,()=>{Z()});const he=j(p.x,W(0),p.z),ue=j(f.x,W(0),f.z),de=j(m.x,W(0),m.z),pe=j(I.x,W(0),I.z),fe=j(z.x,W(0),z.z),me=j(s.x,W(0),s.z),ge=j(r.x,W(0),r.z).sub(me),we=ge.dot(ge);G(we.lessThan(W(wo)),()=>{Z()});const ye=we.sqrt(),_e=ue.sub(he),be=de.sub(he),ve=H(_e,be),xe=ve.dot(ve);G(xe.lessThanEqual(W(4e-16*yo)),()=>{Z()});const Ce=fe.sub(pe),Se=Ce.dot(Ce);G(Se.lessThan(W(wo)),()=>{Z()});const Ae=Se.sqrt(),Te=Ce.div(Ae),Pe=ge.div(ye),Ee=X(ve),Me=H(Te,Ee),Ie=W(0).toVar(),ze=W(0).toVar(),De=W(0).toVar(),ke=W(0).toVar(),Be=ee(0).toVar(),Oe=Me.dot(he.sub(pe)),Ve=Me.dot(ue.sub(pe)),Ne=Q(Oe).lessThan(W(_o)),Le=Q(Ve).lessThan(W(_o)),Fe=Ne.not().and(Le.not()).and(Oe.mul(Ve).lessThan(0));G(Fe,()=>{const e=Oe.div(Oe.sub(Ve)),t=J(he.x,ue.x,e),i=J(he.z,ue.z,e);G(Be.equal(0),()=>{Ie.assign(t),ze.assign(i)}).Else(()=>{De.assign(t),ke.assign(i)}),Be.addAssign(1)}).ElseIf(Ne,()=>{G(Be.equal(0),()=>{Ie.assign(he.x),ze.assign(he.z)}).Else(()=>{De.assign(he.x),ke.assign(he.z)}),Be.addAssign(1)});const Re=Ve,Ue=Me.dot(de.sub(pe)),je=Le,$e=Q(Ue).lessThan(W(_o)),We=je.not().and($e.not()).and(Re.mul(Ue).lessThan(0));G(Be.lessThan(2),()=>{G(We,()=>{const e=Re.div(Re.sub(Ue)),t=J(ue.x,de.x,e),i=J(ue.z,de.z,e);G(Be.equal(0),()=>{Ie.assign(t),ze.assign(i)}).Else(()=>{De.assign(t),ke.assign(i)}),Be.addAssign(1)}).ElseIf(je.and(Fe.not()).and(Ne.not()),()=>{G(Be.equal(0),()=>{Ie.assign(ue.x),ze.assign(ue.z)}).Else(()=>{De.assign(ue.x),ke.assign(ue.z)}),Be.addAssign(1)})});const He=Ue,Ge=Oe,Ze=$e,qe=Ne,Ye=Ze.not().and(qe.not()).and(He.mul(Ge).lessThan(0));G(Be.lessThan(2),()=>{G(Ye,()=>{const e=He.div(He.sub(Ge)),t=J(de.x,he.x,e),i=J(de.z,he.z,e);G(Be.equal(0),()=>{Ie.assign(t),ze.assign(i)}).Else(()=>{De.assign(t),ke.assign(i)}),Be.addAssign(1)}).ElseIf(Ze.and(We.not()).and(je.not()),()=>{G(Be.equal(0),()=>{Ie.assign(de.x),ze.assign(de.z)}).Else(()=>{De.assign(de.x),ke.assign(de.z)}),Be.addAssign(1)})}),G(Be.notEqual(2),()=>{Z()});const Xe=j(Ie,W(0),ze),Ke=j(De,W(0),ke).sub(Xe).dot(Te),Qe=j(Ie,W(0),ze).toVar(),Je=j(De,W(0),ke).toVar();G(Ke.lessThan(0),()=>{const e=Ie,t=ze;Qe.x.assign(De),Qe.z.assign(ke),Je.x.assign(e),Je.z.assign(t)});const et=W(0),tt=Ae,it=Qe.sub(pe).dot(Te),nt=Je.sub(pe).dot(Te),st=tt.lessThanEqual(it).or(nt.lessThanEqual(et));G(st,()=>{Z()});const rt=q(et,it),ot=Y(tt,nt),at=pe.add(Te.mul(rt)),lt=pe.add(Te.mul(ot)),ct=at.sub(me).dot(Pe).div(ye),ht=lt.sub(me).dot(Pe).div(ye),ut=q(W(0),Y(W(1),ct)),dt=q(W(0),Y(W(1),ht)),pt=Q(dt.sub(ut));G(pt.lessThanEqual(W(_o)),()=>{Z()});const ft=te(O.element(0),1);G(ft.lessThan(ee(M)),()=>{const e=ft.mul(3);ie.element(e).assign(i.toFloat()),ie.element(e.add(1)).assign(ut),ie.element(e.add(2)).assign(dt)})})})})().compute(A.length);d+=performance.now()-ne;const re=performance.now();await r.computeAsync(se),l+=performance.now()-re;const oe=performance.now(),ae=await r.getArrayBufferAsync(O.value),le=new Uint32Array(ae)[0];if(s&&(s.used+=Math.min(le,M)),go.enabled&&console.log(` Batch ${i+1}: ${le} overlaps found (capacity: ${M})`),le>M&&go.enabled&&console.warn(` WARNING: Overlap buffer overflow! ${le} > ${M}. Some occlusion data lost.`),le>0){const e=await r.getArrayBufferAsync(ie.value),t=new Float32Array(e);c+=performance.now()-oe;const i=performance.now(),s=Math.min(le,M);for(let e=0;e<s;e++){const i=3*e,s=Math.round(t[i]);no([t[i+1],t[i+2]],n[s])}h+=performance.now()-i,go.enabled&&console.log(` Processed ${s} overlaps into hiddenOverlapMap`)}else c+=performance.now()-oe}r.dispose(),vo=null;const p=u+d+l+c+h;go.enabled&&(console.log(`WebGPU timing breakdown (total: ${p.toFixed(1)}ms):`),console.log(` Buffer creation: ${u.toFixed(1)}ms`),console.log(` Shader build: ${d.toFixed(1)}ms`),console.log(` GPU compute: ${l.toFixed(1)}ms`),console.log(` Readback: ${c.toFixed(1)}ms`),console.log(` CPU merge: ${h.toFixed(1)}ms`))}const Co=new l(0,1,0);function So(e,t=null){const i=new Float32Array(6*e.length);let n=0;for(let t=0,s=e.length;t<s;t++){const s=e[t];i[n++]=s[0],i[n++]=0,i[n++]=s[2],i[n++]=s[3],i[n++]=0,i[n++]=s[5]}const s=new B,r=new a(i,3,!0);if(s.setAttribute("position",r),t){const i=new Float32Array(2*e.length);for(let e=0,n=t.length;e<n;e++)i[2*e]=t[e],i[2*e+1]=t[e];s.setAttribute("group",new a(i,1))}return s}class Ao{constructor(e,t=!0){this.meshes=zr(e),this.bvhs=new Map,this.visibleEdges=[],this.hiddenEdges=[],this.visibleGroupIndices=[],this.hiddenGroupIndices=[],this.groupKeyToIndex=null,this.hasGroups=!1,this.iterationTime=30,this.useWebGPU=t}reset(){this.visibleEdges.length=0,this.hiddenEdges.length=0,this.visibleGroupIndices.length=0,this.hiddenGroupIndices.length=0,this.groupKeyToIndex=null,this.hasGroups=!1}getVisibleLineGeometry(){return So(this.visibleEdges,this.groupKeyToIndex?this.visibleGroupIndices:null)}getHiddenLineGeometry(){return So(this.hiddenEdges,this.groupKeyToIndex?this.hiddenGroupIndices:null)}getGroupKeys(){return this.groupKeyToIndex?Object.fromEntries(this.groupKeyToIndex):{}}addEdges(...e){const t=this.iterationTime;this.iterationTime=1/0;const i=this.addEdgesGenerator(...e).next().value;return this.iterationTime=t,i}*addEdgesGenerator(e,t={}){const{meshes:i,bvhs:n,visibleEdges:s,hiddenEdges:r,iterationTime:o}=this;let a=performance.now();go.startStep("Building mesh BVH");for(let e=0;e<i.length;e++){performance.now()-a>o&&(yield,a=performance.now());const t=i[e].geometry;if(!n.has(t)){const e=t.boundsTree||new Zs(t);n.set(t,e)}}let l=0;for(let e=0;e<i.length;e++){const t=i[e].geometry;l+=t.index?t.index.count/3:t.attributes.position.count/3}const c={};for(let t=0;t<e.length;t++)c[t]=[];go.startStep("Building line BVH");const h=new Nr(e,{maxLeafSize:2,strategy:2});go.startStep("BVHcast overlaps"),a=performance.now();const u={candidates:0,backFaceCulled:0,yBoundsCulled:0,xzBoundsCulled:0,triangleEdgeCulled:0,planeTrimCulled:0,distThresholdCulled:0,noOverlapCulled:0,used:0,totalEdges:e.length,totalTriangles:l},d=this.useWebGPU,p={};d&&(p._edgeOffsets=[],p._edgeCounts=[],p._meshOffsets=[],p._meshCounts=[],p._meshIndex=[],p.groupCount=0);for(let e=0;e<i.length;e++){performance.now()-a>o&&(t.onProgress&&t.onProgress(e,i.length),yield,a=performance.now());const s=i[e];d?bo(h,n.get(s.geometry),s,p,e):lo(h,n.get(s.geometry),s,c,u)}if(d){let e=!1,t=null;for(xo(p,i,h,c,u).then(()=>{e=!0},i=>{t=i,e=!0});!e;)yield;if(t)throw t}const f=u.totalEdges*u.totalTriangles;if(go.setStat("Total edges",u.totalEdges.toLocaleString()),go.setStat("Total triangles",u.totalTriangles.toLocaleString()),go.setStat("Brute-force pairs (edges × triangles)",f.toLocaleString()),go.setStat("BVH candidate pairs",u.candidates.toLocaleString()),f>0&&go.setStat("BVH reduction",(u.candidates/f*100).toFixed(3)+"% of brute-force"),u.candidates>0){const e=u.candidates,t=t=>(t/e*100).toFixed(2)+"%";d||(go.setStat("Rejected: back-face culling",u.backFaceCulled.toLocaleString()+" ("+t(u.backFaceCulled)+")"),go.setStat("Rejected: Y-bounds (tri below edge)",u.yBoundsCulled.toLocaleString()+" ("+t(u.yBoundsCulled)+")"),go.setStat("Rejected: XZ-bounds (no 2D overlap)",u.xzBoundsCulled.toLocaleString()+" ("+t(u.xzBoundsCulled)+")"),go.setStat("Rejected: edge lies on triangle",u.triangleEdgeCulled.toLocaleString()+" ("+t(u.triangleEdgeCulled)+")"),go.setStat("Rejected: line above tri plane",u.planeTrimCulled.toLocaleString()+" ("+t(u.planeTrimCulled)+")"),go.setStat("Rejected: trimmed edge too small",u.distThresholdCulled.toLocaleString()+" ("+t(u.distThresholdCulled)+")"),go.setStat("Rejected: no projected overlap",u.noOverlapCulled.toLocaleString()+" ("+t(u.noOverlapCulled)+")")),go.setStat("Producing overlaps",u.used.toLocaleString()+" ("+t(u.used)+")")}go.startStep("Converting overlaps to lines");const m=this.hasGroups;for(let t=0;t<e.length;t++){performance.now()-a>o&&(yield,a=performance.now());const i=e[t],n=c[t],l=s.length,h=r.length;if(vr(i,n,!1,s),vr(i,n,!0,r),m){const e=i.groupIndex;for(let t=l;t<s.length;t++)this.visibleGroupIndices.push(e);for(let t=h;t<r.length;t++)this.hiddenGroupIndices.push(e)}}}}class To{constructor(){this.iterationTime=30,this.angleThreshold=50,this.includeIntersectionEdges=!0,this.useWebGPU=!0}generateAsync(e,t={}){return new Promise((i,n)=>{const{signal:s}=t,r=this.generate(e,t);!function e(){if(s&&s.aborted)return void n(new Error("ProjectionGenerator: Process aborted via AbortSignal."));let t;try{t=r.next()}catch(e){return void n(e)}t.done?i(t.value):requestAnimationFrame(e)}()})}*generate(e,t){const{iterationTime:i,angleThreshold:n,includeIntersectionEdges:s}=this,{onProgress:r=()=>{},visibilityCuller:o=null,groupFn:a=null}=t;if(go.reset(),go.startTotal(),e.isBufferGeometry&&(e=new y(e)),o){go.startStep("Visibility culling");let i=!1,n=null;for(o.cull(e,{signal:t.signal}).then(t=>{(e=new P).children=t,i=!0},e=>{n=e,i=!0});!i;)yield;if(n)throw n}const l=new Or;l.iterationTime=i,l.thresholdAngle=n,l.projectionDirection.copy(Co),go.startStep("Generating candidate edges"),r("Generating candidate edges");let c=[],h=a?[]:null;if(yield*l.getEdgesGenerator(e,c,h),s&&(go.startStep("Generating intersection edges"),r("Generating intersection edges"),yield*l.getIntersectionEdgesGenerator(e,c,h)),go.startStep("Pre-filtering edges"),r("Pre-filtering edges"),h){const e=[],t=[];for(let i=0;i<c.length;i++)yr(c[i])||(e.push(c[i]),t.push(h[i]));c=e,h=t}else c=c.filter(e=>!yr(e));yield;const u=new Ao(e,this.useWebGPU);if(u.iterationTime=i,a&&h){const e=new Map;for(let t=0;t<c.length;t++){const i=a(h[t]);e.has(i)||e.set(i,e.size),c[t].groupIndex=e.get(i)}u.groupKeyToIndex=e,u.hasGroups=!0}return r("Building BVH & computing overlaps"),yield*u.addEdgesGenerator(c,{onProgress:r?(e,t)=>{r("Building BVH & computing overlaps",e/t,u)}:null}),go.printSummary(),u}}new c,new c,new l;class Po extends le{static uuid="f2e76c3a-8b1d-4d5e-9a3f-7c6b2d4e8f1a";enabled=!0;onDisposed=new re;generator=new To;cullerPixelsPerMeter=.05;get cullerMetersPerPixel(){return this.cullerPixelsPerMeter}set cullerMetersPerPixel(e){this.cullerPixelsPerMeter=e}projectionDirection=new s.Vector3(0,-1,0);nearPlane=-1/0;farPlane=1/0;constructor(e){super(e),this.components.add(Po.uuid,this),this.generator.includeIntersectionEdges=!1}async get(e,t,i){const n=this.components.get(hr),r=new s.Group,o=new Map;for(const[t,i]of Object.entries(e)){const e=n.list.get(t);if(!e)continue;const a=(await e.getItemsIdsWithGeometry()).filter(e=>i.has(e));if(0===a.length)continue;const l=await e.getItemsGeometry(a);for(const i in l){const n=l[i];for(const i of n){if(!(i.positions&&i.indices&&i.transform&&i.representationId))continue;const n=i.representationId;if(!o.has(n)){const e=new s.BufferGeometry;e.setAttribute("position",new s.Float32BufferAttribute(i.positions,3)),i.normals&&e.setAttribute("normal",new s.Float32BufferAttribute(i.normals,3)),e.setIndex(Array.from(i.indices)),o.set(n,e)}const a=o.get(n),l=new s.Mesh(a);l.applyMatrix4(i.transform),l.applyMatrix4(e.object.matrixWorld),l.updateWorldMatrix(!0,!0),l.userData._edgeProjectorModelId=t,l.userData._edgeProjectorLocalId=i.localId,r.add(l)}}}const a=this.projectionDirection.clone().normalize(),l=new s.Vector3(0,-1,0),c=(new s.Quaternion).setFromUnitVectors(a,l),h=(new s.Matrix4).makeRotationFromQuaternion(c),u=h.clone().invert();for(const e of r.children)e.applyMatrix4(h),e.updateWorldMatrix(!1,!1);if(r.traverse(e=>{const t=e;if(t.geometry&&!t.geometry.boundsTree){const e=t.geometry.index?t.geometry.index.count:t.geometry.attributes.position.count;t.geometry.groups.forEach(t=>{t.count===1/0&&(t.count=e-t.start)}),t.geometry.boundsTree=new Zs(t.geometry,{maxLeafSize:1,strategy:2})}}),this.nearPlane!==-1/0||this.farPlane!==1/0){const e=new s.Box3,t=[];for(const i of r.children){const n=i;n.geometry&&(e.setFromObject(n),(e.max.y<this.nearPlane||e.min.y>this.farPlane)&&t.push(n))}for(const e of t)r.remove(e)}const d=t.renderer.three,p=new pr(d,{pixelsPerMeter:this.cullerPixelsPerMeter});let f;try{f=await this.generator.generateAsync(r,{visibilityCuller:p,groupFn:e=>`${e.userData._edgeProjectorModelId??"unknown"}:${e.userData._edgeProjectorLocalId??0}`,onProgress:i?.onProgress,signal:i?.signal})}catch(e){for(const e of o.values())e.dispose();throw e}const m=f.getVisibleLineGeometry(),g=f.getHiddenLineGeometry();m.applyMatrix4(u),g.applyMatrix4(u);const w=f.getGroupKeys(),y={};for(const[e,t]of Object.entries(w)){const i=e.lastIndexOf(":"),n=e.substring(0,i),s=Number(e.substring(i+1));y[t]={modelId:n,localId:s}}for(const e of o.values())e.dispose();return{visible:m,hidden:g,groups:y}}dispose(){this.onDisposed.trigger(Po.uuid),this.onDisposed.reset()}}class Eo{wasm={path:"",absolute:!1,logLevel:ie.LogLevel.LOG_LEVEL_OFF};webIfc={COORDINATE_TO_ORIGIN:!0};autoSetWasm=!0;customLocateFileHandler=null}class Mo extends le{static uuid="a659add7-1418-4771-a0d6-7d4d438e4624";onDisposed=new re;onIfcStartedLoading=new re;onIfcImporterInitialized=new re;onSetup=new re;settings=new Eo;webIfc=new ie.IfcAPI;enabled=!0;constructor(e){super(e),this.components.add(Mo.uuid,this)}dispose(){this.webIfc=null,this.onDisposed.trigger(Mo.uuid),this.onDisposed.reset()}async setup(e){this.settings={...this.settings,...e},this.settings.autoSetWasm&&await this.autoSetWasm(),this.onSetup.trigger()}async load(t,i,n,s){const r=this.components.get(hr);if(!r.initialized)throw new Error("You need to initialize fragments first.");this.settings.autoSetWasm&&await this.autoSetWasm(),r.core.settings.autoCoordinate=i;const o=new e.IfcImporter;o.wasm.path=this.settings.wasm.path,o.wasm.absolute=this.settings.wasm.absolute,o.webIfcSettings=this.settings.webIfc,this.onIfcImporterInitialized.trigger(o),s?.instanceCallback&&s.instanceCallback(o);const a=await o.process({...s?.processData,bytes:t});return await r.core.load(a,{modelId:n,userData:s?.userData})}async readIfcFile(e){const{path:t,absolute:i,logLevel:n}=this.settings.wasm;return this.webIfc.SetWasmPath(t,i),await this.webIfc.Init(this.settings.customLocateFileHandler||void 0),n&&this.webIfc.SetLogLevel(n),this.webIfc.OpenModel(e,this.settings.webIfc)}cleanUp(){try{this.webIfc.Dispose()}catch(e){console.log("Web-ifc wasn't disposed.")}this.webIfc=null,this.webIfc=new ie.IfcAPI}async autoSetWasm(){const e=await fetch(`https://unpkg.com/@thatopen/components@${Ma.release}/package.json`);if(!e.ok)return void console.warn("Couldn't get openbim-components package.json. Set wasm settings manually.");const t=await e.json();if("web-ifc"in t.peerDependencies){const e=t.peerDependencies["web-ifc"];this.settings.wasm.path=`https://unpkg.com/web-ifc@${e}/`,this.settings.wasm.absolute=!0}else console.warn("Couldn't get web-ifc from peer dependencies in openbim-components. Set wasm settings manually.")}}class Io extends le{static uuid="dd9ccf2d-8a21-4821-b7f6-2949add16a29";enabled=!0;constructor(e){super(e),this.components.add(Io.uuid,this)}async set(e,t){const i=this.components.get(hr),n=[];if(t)for(const[s,r]of Object.entries(t)){const t=i.list.get(s);t&&n.push(t.setVisible([...r],e))}else for(const t of i.list.values())n.push(t.setVisible(void 0,e));await Promise.all(n),await i.core.update(!0)}async isolate(e){await Promise.all([this.set(!1),this.set(!0,e)])}async toggle(e){const t=[],i=this.components.get(hr);for(const[n,s]of Object.entries(e)){const e=i.list.get(n);e&&t.push(e.toggleVisible([...s]))}await Promise.all(t),await i.core.update(!0)}async getVisibilityMap(e,t){const i=[],n=[],s=this.components.get(hr);if(t)for(const r of t){const t=s.list.get(r);t&&(i.push(t.modelId),n.push(t.getItemsByVisibility(e)))}else for(const t of s.list.values())i.push(t.modelId),n.push(t.getItemsByVisibility(e));const r=await Promise.all(n),o={};for(const[e,t]of i.entries())o[t]=r[e];return o}}class zo extends le{static uuid="d1444724-dba6-4cdd-a0c7-68ee1450d166";enabled=!0;onDisposed=new re;list=new e.DataSet;constructor(e){super(e),this.components.add(zo.uuid,this)}dispose(e=!0){this.list.clear(),this.onDisposed.trigger(zo.uuid),e&&(this.onDisposed.reset(),this.list.eventsEnabled=!1,this.list.dispose())}get(){const e=new s.Box3;for(const t of this.list)e.union(t);return e}async addFromModelIdMap(e){const t=this.components.get(hr),i=new s.Box3;for(const[n,s]of Object.entries(e)){const e=t.list.get(n);if(!e)continue;const r=await e.getMergedBox([...s]);i.union(r)}this.list.add(i)}addFromModels(e){const t=this.components.get(hr);for(const[i,n]of t.list)e&&!e.some(e=>e.test(i))||this.list.add(n.box)}async getCenter(e){this.list.clear(),await this.addFromModelIdMap(e);const t=this.get();this.list.clear();const i=new s.Vector3;return t.getCenter(i),i}async getCameraOrientation(e,t=1){const i=this.components.get(hr);this.list.clear();for(const[e,t]of i.list)this.list.add(t.box);const n=this.get();this.list.clear();const r=new s.Vector3;n.getCenter(r);const o=new s.Vector3;n.getSize(o);const a=Math.max(o.x,o.y,o.z)*t,l=new s.Vector3;switch(e){case"front":default:l.set(r.x,r.y,r.z+a);break;case"back":l.set(r.x,r.y,r.z-a);break;case"left":l.set(r.x-a,r.y,r.z);break;case"right":l.set(r.x+a,r.y,r.z);break;case"top":l.set(r.x,r.y+a,r.z);break;case"bottom":l.set(r.x,r.y-a,r.z)}return{position:l,target:r}}}class Do{name="Query";customData={};_components;_queries=[];set queries(e){this._queries=e,this.clearCache()}get queries(){return this._queries}_aggregation="exclusive";set aggregation(e){e!==this._aggregation&&this.clearCache(),this._aggregation=e}get aggregation(){return this._aggregation}result=null;cache=!0;constructor(e,t){this._components=e,this.queries=t}async test(e){const{modelIds:t,force:i}={force:!1,...e};if(this.result&&!i)return this.result;const n=this._components.get(ko),s=await n.getItems(this.queries,{modelIds:t,aggregation:this.aggregation});return this.cache&&(this.result=s),s}clearCache(){this.result=null}serializeAttributeQuery(e){let t;t=Array.isArray(e.value)?e.value.map(e=>e.source):e.value instanceof RegExp?e.value.source:e.value;return{name:e.name.source,value:t,type:e.type instanceof RegExp?e.type.source:e.type,negate:e.negate,itemIds:e.itemIds}}serializeQueryParameters=e=>({categories:e.categories?.map(e=>e.source),attributes:e.attributes?{aggregation:e.attributes.aggregation,queries:e.attributes.queries.map(this.serializeAttributeQuery)}:void 0,relation:e.relation?{name:e.relation.name,query:e.relation.query?this.serializeQueryParameters(e.relation.query):void 0}:void 0});toJSON(){return{guid:this._components.get(ko).list.getKey(this)??me.create(),name:this.name,customData:this.customData,queries:this.queries.map(this.serializeQueryParameters),aggregation:this.aggregation,cache:this.cache}}deserializeAttributeQuery(e){let t;t=Array.isArray(e.value)?e.value.map(e=>new RegExp(e)):"string"==typeof e.value?new RegExp(e.value):e.value;return{name:new RegExp(e.name),value:t,type:e.type?new RegExp(e.type):void 0,negate:e.negate,itemIds:e.itemIds}}deserializeQueryParameters=e=>({categories:e.categories?.map(e=>new RegExp(e)),attributes:e.attributes?{aggregation:e.attributes.aggregation,queries:e.attributes.queries.map(this.deserializeAttributeQuery)}:void 0,relation:e.relation?{name:e.relation.name,query:e.relation.query?this.deserializeQueryParameters(e.relation.query):void 0}:void 0});fromJSON(e){return this.name=e.name,this.customData=e.customData,this.aggregation=e.aggregation,this.cache=e.cache,this.queries=e.queries.map(this.deserializeQueryParameters),this}}class ko extends le{static uuid="0da7ad77-f734-42ca-942f-a074adfd1e3a";enabled=!0;list=new e.DataMap;constructor(e){super(e),e.add(ko.uuid,this)}async getItems(e,t){let i;if(t){const{modelIds:e,items:n}=t;if(n){const e=Object.keys(n);e.length>0&&(i=e.map(e=>new RegExp(`^${e}$`)))}else e&&(i=e)}const n=t?.aggregation??"exclusive",s=this.components.get(hr),r=await Promise.all(e.map(async e=>{const n={};return await Promise.all(Array.from(s.list).map(async([s,r])=>{if(i&&!i.some(e=>e.test(s)))return;const o=t?.items?.[s],a=await r.getItemsByQuery(e,{localIds:o?[...o]:void 0});n[s]=new Set(a)})),n}));return"inclusive"===n?si.join(r):si.intersect(r)}create(e,t){const i=new Do(this.components,t);return this.list.set(e,i),i}async addFromCategories(e){const t=new Set,i=this.components.get(hr);for(const[n,s]of i.list){if(e&&!e.some(e=>e.test(n)))continue;const i=(await s.getItemsWithGeometryCategories()).filter(e=>null!==e),r=new Set(i);for(const e of r)this.list.has(e)||(this.create(e,[{categories:[new RegExp(`^${e}$`)]}]),t.add(e))}return[...t]}import(e){const{data:t}=e,i=[];if(!t)return i;for(const e of t){const t=this.create(e.guid,[]);t.fromJSON(e),i.push(t)}return i}export(){const e=[];for(const[t,i]of this.list.entries()){const n={...i.toJSON(),name:t};e.push(n)}return{data:e}}}class Bo extends le{static uuid="e25a7f3c-46c4-4a14-9d3d-5115f24ebeb7";enabled=!0;onDisposed=new re;list=new e.DataMap;constructor(e){super(e),e.add(Bo.uuid,this),this.setupEvents();e.get(hr).list.onBeforeDelete.add(this.onBeforeFragmentsDispose)}setupEvents(){this.list.onBeforeDelete.add(({value:e})=>e.dispose())}getClassificationGroups(t){let i=this.list.get(t);return i||(i=new e.DataMap,this.list.set(t,i)),i}getModelItems(e,t,i){const{map:n}=this.getGroupData(e,t);let s=n[i];return s||(s=new Set,n[i]=s),s}getGroupData(e,t){const i=this.components.get(ko),n=this.getClassificationGroups(e);let s=n.get(t);return s||(s={map:{},get:()=>new Promise(e=>{if(s)if(s.query){const{name:t,config:n}=s.query,r=i.list.get(t);if(!r)throw new Error("Classifier: the query name associated with the group doesn't exist in the ItemsFinder component");r.test(n).then(t=>{if(!s)return void e({});const i=si.join([t,s.map]);e(i)})}else e(s.map);else e({})})},n.set(t,s)),s}defaultSaveFunction=e=>"value"in e.Name?e.Name.value:null;async aggregateItems(e,t,i){const n=i?.data??void 0,s=i?.aggregationCallback??this.defaultSaveFunction,r=this.components.get(hr),o=this.components.get(ko),a=await o.getItems([t],{modelIds:i?.modelIds});for(const[t,i]of Object.entries(a)){const o=r.list.get(t);if(!o)continue;const a=(i,...n)=>{const s=this.getModelItems(e,i,t);for(const e of n)s.add(e)},l=await o.getItemsData([...i],n);for(const e of l)s(e,a)}}addGroupItems(e,t,i){const{map:n}=this.getGroupData(e,t);si.add(n,i)}setGroupQuery(e,t,i){this.getGroupData(e,t).query=i}async find(e){const t=[];for(const[i,n]of Object.entries(e)){const e=[],s=this.list.get(i);if(!s)continue;for(const t of n){const i=s.get(t);if(!i)continue;const n=await i.get();e.push(n)}const r=si.join(e);t.push(r)}return si.intersect(t)}async aggregateItemRelations(e,t,i,n){const s=n?.attribute??"Name",r={relations:{[i]:{attributes:!0,relations:!1}}};await this.aggregateItems(e,t,{modelIds:n?.modelIds,data:r,aggregationCallback:(e,t)=>{if(!e?.[s])return;const n=e[s];if(!("value"in n))return;const r=e[i];if(Array.isArray(r))for(const e of r)"value"in e._localId&&t(n.value,e._localId.value)}})}async byIfcBuildingStorey(e){await this.aggregateItemRelations(e?.classificationName??"Storeys",{categories:[/BUILDINGSTOREY/]},"ContainsElements",{modelIds:e?.modelIds})}async byCategory(e){const t=this.components.get(ko),i=await t.addFromCategories(e?.modelIds);for(const t of i)this.setGroupQuery(e?.classificationName??"Categories",t,{name:t})}onBeforeFragmentsDispose=async e=>{const{key:t,value:i}=e,n=await i.getLocalIds(),s={[t]:new Set(n)};this.removeItems(s)};dispose(){this.list.clear();this.components.get(hr).list.onBeforeDelete.remove(this.onBeforeFragmentsDispose),this.onDisposed.trigger()}removeItems(e,t){if(t&&t.classificationName){const i=this.list.get(t.classificationName);if(!i)return;if(t.groupName){if(!i.get(t.groupName))return}for(const[,t]of i)si.remove(t.map,e);return}for(const[,t]of this.list.entries())for(const[,i]of t)si.remove(i.map,e)}async byModel(e){const t=this.components.get(hr),i=e?.classificationName??"Models";for(const[n,s]of t.list){if(e&&e.modelIds&&!e.modelIds.some(e=>e.test(n)))continue;const t=await s.getItemsIdsWithGeometry(),r={[n]:new Set(t)};this.getGroupData(i,n),this.addGroupItems(i,n,r)}}}const Oo={id:0,depth:1,normal:2},Vo=Object.keys(Oo),No={id:!0},Lo={depth:!0},Fo={normal:!0},Ro={id:!0,depth:!0,normal:!0},Uo={},jo=new s.Vector2;class $o extends s.Camera{updateProjectionMatrix(){}}function Wo(e,t){return new s.WebGLRenderTarget(e,t,{count:Vo.length,format:s.RGBAFormat,type:s.UnsignedByteType,minFilter:s.NearestFilter,magFilter:s.NearestFilter,depthBuffer:!0})}function Ho(e){const t=e;return Boolean(t.isMesh||t.isLine||t.isPoints||t.isSprite)}function Go(e,t){const i=t.get(e[0]);if(!i)return null;const n=e[1]<<16|e[2]<<8|e[3];return 0===n?null:{modelId:i,itemId:n-1}}function Zo(e,t){if(0===e[0]&&0===e[1]&&0===e[2]&&0===e[3])return null;const i=255/256*((n=e)[0]/255/16777216+n[1]/255/65536+n[2]/255/256+n[3]/255);var n;const{reversedDepth:r}=t;return(r?i<=1e-6:i>=.999999)?null:function(e,t,i,n){const r=n?t:2*t-1,o=new s.Vector3(e.x,e.y,r);return o.unproject(i),o}(t.ndc,i,t.camera,r)}async function qo(e,t,i){const n=e.list.get(t);if(!n)return null;const s=await n.getLocalIdsFromItemIds([i]),r=s?.[0];return r??null}class Yo{enabled=!0;components;onDisposed=new re;mouse;world;debugMode=!1;static MAX_MODELS=254;_pickTarget=Wo(1,1);_debugTarget;_pickBuffers={id:new Uint8Array(4),depth:new Uint8Array(4),normal:new Uint8Array(4)};_debugCanvas;_debugContainer;_pickMaterial;_pickCamera=new $o;_pickMatrix=new s.Matrix4;_pickNdc=new s.Vector2;_viewportSize=new s.Vector2;_clearColor=new s.Color;_cameraPosition=new s.Vector3;_meshBytes=new Map;_byteToModel=new Map;_modelBytes=new Map;_modelRoots=new Map;_hidden=[];_forcedOverrides=[];_walkNodes=[];_walkOwners=[];_localPlanes=[];constructor(e,t){if(!t.renderer)throw new Error("A renderer is needed for the FastModelPicker to work!");this.world=t,this.mouse=new hi(t.renderer.three.domElement),this.components=e,this._pickMaterial=this.buildPickMaterial(),this._pickCamera.matrixAutoUpdate=!1,this._pickCamera.matrixWorldAutoUpdate=!1}async getModelAt(e){return this.pick(e,No)?.item?.modelId??null}async getItemAt(e){const t=this.pick(e,No)?.item;if(!t)return null;const i=this.components.get(hr),n=await qo(i,t.modelId,t.itemId);return null==n?null:{modelId:t.modelId,localId:n,itemId:t.itemId}}async getPointAt(e){return this.pick(e,Lo)?.surface?.point??null}async getNormalAt(e){return this.pick(e,Fo)?.normal??null}async getFullPick(e){const t=this.pick(e,Ro);if(!t?.item||!t.surface)return null;const i=this.components.get(hr),{modelId:n,itemId:s}=t.item,r=await qo(i,n,s);return null==r?null:{modelId:n,itemId:s,localId:r,point:t.surface.point,normal:t.normal,distance:t.surface.distance}}setDebugMode(e){this.debugMode=e,e?this.setupDebugCanvas():this.removeDebugCanvas()}dispose(){this.mouse.dispose(),this.removeDebugCanvas(),this._pickMaterial.dispose(),this._pickTarget?.dispose(),this._pickTarget=void 0,this._debugTarget?.dispose(),this._debugTarget=void 0,this.onDisposed.trigger(),this.onDisposed.reset()}pick(e,t){if(!this._pickTarget)return null;this.debugMode&&this.updateDebugCanvas();const i=e??this.mouse.position,n=this._pickBuffers,r=this.renderPick(i,t,this._pickTarget,n);if(!r)return null;const o=t.depth?Zo(n.depth,r):null;return{item:t.id?Go(n.id,r.byteToModel):null,surface:o?{point:o,distance:o.distanceTo(this._cameraPosition.setFromMatrixPosition(r.camera.matrixWorld))}:null,normal:t.normal?(a=n.normal,0===a[3]?null:new s.Vector3(a[0]/255*2-1,a[1]/255*2-1,a[2]/255*2-1).normalize()):null};var a}renderPick(e,t,i,n){if(!this.enabled||!this.world.renderer)return null;const s=this.world.scene.three;if(!s.isScene)return null;const r=this.components.get(hr);if(!r.initialized||0===r.list.size)return null;const o=this.world.renderer.three,a=o.getSize(this._viewportSize);if(0===a.x||0===a.y)return null;const l=this.snapshotCamera(e,a,i),c=this._pickMaterial;c.clippingPlanes=this.collectLocalPlanes(this.world.renderer);const h=o.getRenderTarget(),u=o.autoClear,d=o.getClearColor(this._clearColor),p=o.getClearAlpha(),f=s.background,m=s.overrideMaterial,{shadowMap:g}=o,w=g.autoUpdate,y=g.needsUpdate;try{if(this.collectPickables(s,r),0===this._byteToModel.size)return null;s.background=null,s.overrideMaterial=c,g.autoUpdate=!1,g.needsUpdate=!1,o.setRenderTarget(i),o.setClearColor(0,0),o.autoClear=!1,o.clear(!0,!0,!1),o.render(s,l)}finally{this.restorePickables(),g.autoUpdate=w,g.needsUpdate=y,s.overrideMaterial=m,s.background=f,o.setRenderTarget(h),o.autoClear=u,o.setClearColor(d,p)}const _=Math.floor(i.width/2),b=Math.floor(i.height/2);for(const e of Vo){if(!t[e])continue;const s=n[e];s.fill(0);const r=Oo[e];o.readRenderTargetPixels(i,_,b,1,1,s,void 0,r)}this._pickNdc.set((_+.5)/i.width*2-1,(b+.5)/i.height*2-1);const v=o.capabilities;return{byteToModel:this._byteToModel,camera:l,ndc:this._pickNdc,reversedDepth:!0===v?.reversedDepthBuffer}}snapshotCamera(e,t,i){const n=this.world.camera.three;n.updateWorldMatrix(!0,!1);const s=this._pickCamera;s.matrixWorld.copy(n.matrixWorld),s.matrixWorldInverse.copy(n.matrixWorldInverse),s.layers.mask=n.layers.mask;const r=t.x/i.width,o=t.y/i.height;return this._pickMatrix.set(r,0,0,-e.x*r,0,o,0,-e.y*o,0,0,1,0,0,0,0,1),s.projectionMatrix.multiplyMatrices(this._pickMatrix,n.projectionMatrix),s.projectionMatrixInverse.copy(s.projectionMatrix).invert(),s}collectLocalPlanes(e){const t=this._localPlanes;t.length=0;for(const i of e.clippingPlanes)i.isLocal&&t.push(i);return t}collectPickables(e,t){this._byteToModel.clear(),this._modelBytes.clear();for(const[e,i]of t.list)this._modelRoots.set(i.object,e);const i=this._walkNodes,n=this._walkOwners;for(i.push(e),n.push(null);i.length;){const e=i.pop(),t=n.pop();if(!e.visible)continue;const s=this._modelRoots.get(e)??t;if(Ho(e)){const t=null===s?0:this.pickableByte(e,s);if(!t){e.visible=!1,this._hidden.push(e);continue}this._meshBytes.set(e,t)}for(const t of e.children)i.push(t),n.push(s)}}pickableByte(e,t){const i=e;if(!i.isMesh||!i.geometry?.attributes?.id)return 0;let n=this._modelBytes.get(t);if(void 0===n){if(n=this._byteToModel.size+1,n>Yo.MAX_MODELS)return 0;this._modelBytes.set(t,n),this._byteToModel.set(n,t)}return this.allowOverride(i.material),n}allowOverride(e){if(Array.isArray(e))for(const t of e)this.allowOverride(t);else e&&!1===e.allowOverride&&(e.allowOverride=!0,this._forcedOverrides.push(e))}restorePickables(){for(const e of this._hidden)e.visible=!0;for(const e of this._forcedOverrides)e.allowOverride=!1;this._hidden.length=0,this._forcedOverrides.length=0,this._walkNodes.length=0,this._walkOwners.length=0,this._meshBytes.clear(),this._modelRoots.clear()}buildPickMaterial(){const e=new s.ShaderMaterial({glslVersion:s.GLSL3,uniforms:{modelByte:{value:0}},vertexShader:"\n attribute vec4 id;\n varying vec4 vId;\n varying vec3 vWorldNormal;\n #if NUM_CLIPPING_PLANES > 0\n varying vec3 vClipPosition;\n #endif\n void main() {\n vId = id;\n vWorldNormal = normalize((modelMatrix * vec4(normal, 0.0)).xyz);\n vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);\n #if NUM_CLIPPING_PLANES > 0\n vClipPosition = -mvPosition.xyz;\n #endif\n gl_Position = projectionMatrix * mvPosition;\n }\n ",fragmentShader:`\n precision highp float;\n uniform float modelByte;\n varying vec4 vId;\n varying vec3 vWorldNormal;\n #if NUM_CLIPPING_PLANES > 0\n varying vec3 vClipPosition;\n uniform vec4 clippingPlanes[NUM_CLIPPING_PLANES];\n #endif\n layout(location = ${Oo.id}) out highp vec4 outId;\n layout(location = ${Oo.depth}) out highp vec4 outDepth;\n layout(location = ${Oo.normal}) out highp vec4 outNormal;\n void main() {\n #if NUM_CLIPPING_PLANES > 0\n for (int i = 0; i < NUM_CLIPPING_PLANES; i++) {\n vec4 plane = clippingPlanes[i];\n if (dot(vClipPosition, plane.xyz) > plane.w) discard;\n }\n #endif\n outId = vec4(modelByte / 255.0, vId.y / 255.0, vId.z / 255.0, vId.w / 255.0);\n\n float v = gl_FragCoord.z;\n vec4 r = vec4(\n fract(v * 16777216.0),\n fract(v * 65536.0),\n fract(v * 256.0),\n v\n );\n r.yzw -= r.xyz * (1.0 / 256.0);\n outDepth = r * (256.0 / 255.0);\n\n vec3 n = normalize(vWorldNormal);\n if (!gl_FrontFacing) n = -n;\n outNormal = vec4(n * 0.5 + 0.5, 1.0);\n }\n `,side:s.DoubleSide,clipping:!0});return e.onBeforeRender=(t,i,n,s,r)=>{e.uniforms.modelByte.value=this._meshBytes.get(r)??0,e.uniformsNeedUpdate=!0},e}setupDebugCanvas(){if(this._debugCanvas)return;const e=this.world.renderer.three.getSize(new s.Vector2);this._debugContainer=document.createElement("div"),this._debugContainer.style.position="fixed",this._debugContainer.style.top="10px",this._debugContainer.style.right="10px",this._debugContainer.style.width="300px",this._debugContainer.style.height="300px",this._debugContainer.style.border="2px solid #fff",this._debugContainer.style.backgroundColor="#000",this._debugContainer.style.zIndex="10000",this._debugContainer.style.pointerEvents="none",this._debugCanvas=document.createElement("canvas"),this._debugCanvas.width=e.x,this._debugCanvas.height=e.y,this._debugCanvas.style.width="100%",this._debugCanvas.style.height="100%",this._debugCanvas.style.imageRendering="pixelated",this._debugContainer.appendChild(this._debugCanvas),document.body.appendChild(this._debugContainer)}removeDebugCanvas(){this._debugContainer&&(this._debugContainer.remove(),this._debugContainer=void 0,this._debugCanvas=void 0)}updateDebugCanvas(){if(!this._debugCanvas||!this.world.renderer)return;const e=this.world.renderer.three,t=e.getSize(new s.Vector2),i=Math.floor(t.x),n=Math.floor(t.y);if(0===i||0===n)return;this._debugTarget??=Wo(i,n);const r=this._debugTarget;if(r.setSize(i,n),!this.renderPick(jo,Uo,r,this._pickBuffers))return;const o=new Uint8Array(i*n*4);e.readRenderTargetPixels(r,0,0,i,n,o,void 0,Oo.id);const a=this._debugCanvas;a.width=i,a.height=n;const l=a.getContext("2d");if(!l)return;const c=l.createImageData(i,n),h=4*i;for(let e=0;e<n;e++){const t=e*h,i=(n-1-e)*h;c.data.set(o.subarray(t,t+h),i)}l.putImageData(c,0,0)}}class Xo extends le{static uuid="4a82430c-7ff2-49ea-9401-60807502dad6";enabled=!0;list=new Map;onDisposed=new re;constructor(e){super(e),e.add(Xo.uuid,this)}get(e){if(this.list.has(e.uuid))return this.list.get(e.uuid);const t=new Yo(this.components,e);return this.list.set(e.uuid,t),e.onDisposed.add(()=>{this.delete(e)}),t}delete(e){const t=this.list.get(e.uuid);t&&t.dispose(),this.list.delete(e.uuid)}dispose(){for(const[e,t]of this.list)t.dispose();this.list.clear(),this.onDisposed.trigger()}}var Ko=(e=>(e[e.POINT=0]="POINT",e[e.LINE=1]="LINE",e[e.FACE=2]="FACE",e))(Ko||{});const Qo=1e3;class Jo{onDisposed=new re;maxDistance=1;maxCacheSize=1e3;get precision(){return this._precision}set precision(e){e!==this._precision&&(this._precision=e,this.clear())}components;_precision="half";cache=new Map;constructor(e){this.components=e}dispose(){this.cache.clear(),this.onDisposed.trigger(),this.onDisposed.reset()}async resolve(e,t,i,n){const s=Jo.keyOf(t,i);let r=this.cache.get(s);if(r)this.cache.delete(s),this.cache.set(s,r);else{if(r=await this.fetchItemSnapData(t,i),!r)return null;this.storeWithLRU(s,r)}const o=this.snap(e,r,2),a=new Set(n),l=[0,1,2];let c=null;for(const t of l){if(!a.has(t))continue;const i=this.snap(e,r,t);if(i){c=i.result;break}}if(!c)return o?o.result:null;if(o&&2!==c.snappingClass){const e=o.result;!c.normal&&e.normal&&(c.normal=e.normal),!c.facePoints&&e.facePoints&&(c.facePoints=e.facePoints),!c.faceIndices&&e.faceIndices&&(c.faceIndices=e.faceIndices)}return c}async prefetch(e,t){const i=Jo.keyOf(e,t);if(this.cache.has(i))return;const n=await this.fetchItemSnapData(e,t);n&&this.storeWithLRU(i,n)}invalidate(e,t){const i=Jo.keyOf(e,t);this.cache.delete(i)}clear(){this.cache.clear()}static keyOf(e,t){return`${e}:${t}`}storeWithLRU(e,t){for(this.cache.set(e,t);this.cache.size>this.maxCacheSize;){const e=this.cache.keys().next().value;if(void 0===e)break;this.cache.delete(e)}}async fetchItemSnapData(e,t){const i=this.components.get(hr).list.get(e);if(!i)return null;const n=await i._getItemSnapData(t);if(!n)return null;const s=i.object.matrixWorld,r=[];for(const e of Object.keys(n.samples??{})){const t=n.samples[Number(e)],i=n.representations[t.representation];if(!i||1!==i.representationClass)continue;const o=i.geometry;if(!o)continue;const a=n.localTransforms[t.localTransform],l=aa(s,n.globalTransforms[t.item],a);this.collectPolygonsFromShell(o,l,r)}if(0===r.length)return null;return{faces:r,edges:function(e,t){const i=new Set,n=[];for(const t of e){const e=t.points,s=e.length/3;for(let t=0;t<s;t++){const r=(t+1)%s,o=e[3*t],a=e[3*t+1],l=e[3*t+2],c=e[3*r],h=e[3*r+1],u=e[3*r+2],d=ha(o,a,l,c,h,u);i.has(d)||(i.add(d),n.push(o,a,l,c,h,u))}}return new("full"===t?Float64Array:Float32Array)(n)}(r,this._precision),vertices:function(e,t){const i=new Set,n=[];for(const t of e){const e=t.points,s=e.length/3;for(let t=0;t<s;t++){const s=e[3*t],r=e[3*t+1],o=e[3*t+2],a=ca(s,r,o);i.has(a)||(i.add(a),n.push(s,r,o))}}return new("full"===t?Float64Array:Float32Array)(n)}(r,this._precision)}}collectPolygonsFromShell(e,t,i){const n=e.points,r=e.profiles??new Map,o=e.bigProfiles??new Map,a=new s.Vector3,l=e=>{if(e.length<3)return;const r=new("full"===this._precision?Float64Array:Float32Array)(3*e.length);for(let i=0;i<e.length;i++){const s=n[e[i]];a.set(s[0],s[1],s[2]).applyMatrix4(t),r[3*i]=a.x,r[3*i+1]=a.y,r[3*i+2]=a.z}const o=function(e){const t=new s.Vector3,i=e.length/3;for(let n=0;n<i;n++){const s=(n+1)%i,r=e[3*n],o=e[3*n+1],a=e[3*n+2],l=e[3*s],c=e[3*s+1],h=e[3*s+2];t.x+=(o-c)*(a+h),t.y+=(a-h)*(r+l),t.z+=(r-l)*(o+c)}const n=t.length();return n<1e-10?null:t.divideScalar(n)}(r);if(!o)return;const l=o.x*r[0]+o.y*r[1]+o.z*r[2];i.push({points:r,normal:o,d:l})};for(const e of r.values())l(e);for(const e of o.values())l(e)}snap(e,t,i){return 0===i?this.snapToPoint(e,t):1===i?this.snapToLine(e,t):2===i?this.snapToFace(e,t):null}snapToPoint(e,t){const i=t.vertices;if(0===i.length)return null;const n=this.maxDistance*this.maxDistance;let r=-1,o=1/0;for(let t=0;t<i.length;t+=3){const s=i[t]-e.x,a=i[t+1]-e.y,l=i[t+2]-e.z,c=s*s+a*a+l*l;c<=n&&c<o&&(o=c,r=t)}return r<0?null:{result:{point:new s.Vector3(i[r],i[r+1],i[r+2]),snappingClass:0}}}snapToLine(e,t){const i=t.edges;if(0===i.length)return null;const n=this.maxDistance*this.maxDistance,r=new s.Vector3,o=new s.Vector3;let a=1/0,l=-1;for(let t=0;t<i.length;t+=6){const s=ua(e,i[t],i[t+1],i[t+2],i[t+3],i[t+4],i[t+5],o);s<=n&&s<a&&(a=s,l=t,r.copy(o))}return l<0?null:{result:{point:r.clone(),snappingClass:1,snappedEdgeP1:new s.Vector3(i[l],i[l+1],i[l+2]),snappedEdgeP2:new s.Vector3(i[l+3],i[l+4],i[l+5])}}}snapToFace(e,t){const i=t.faces;if(0===i.length)return null;let n=null,s=1/0,r=!1;for(const t of i){const i=this.signedDistance(t,e),o=Math.abs(i);if(o>this.maxDistance)continue;const a=this.containsPoint(t,this.projectOntoPlane(e,t,i));r&&!a||(!a||r?o<s&&(s=o,n=t):(r=!0,s=o,n=t))}if(!n)return null;return{result:{point:this.projectOntoPlane(e,n,this.signedDistance(n,e)),normal:n.normal.clone(),snappingClass:2,facePoints:n.points,faceIndices:la(n.points.length/3)}}}signedDistance(e,t){return e.normal.x*t.x+e.normal.y*t.y+e.normal.z*t.z-e.d}projectOntoPlane(e,t,i){return e.clone().sub(t.normal.clone().multiplyScalar(i))}containsPoint(e,t){const{points:i,normal:n}=e,s=i.length/3;if(s<3)return!1;const r=Math.abs(n.x),o=Math.abs(n.y),a=Math.abs(n.z);let l=0,c=1;r>=o&&r>=a?(l=1,c=2):o>=a&&(l=0,c=2);const h=t.getComponent(l),u=t.getComponent(c);let d=!1;for(let e=0,t=s-1;e<s;t=e,e+=1){const n=i[3*e+l],s=i[3*e+c],r=i[3*t+l],o=i[3*t+c];if(!(s>u!=o>u))continue;h<(r-n)*(u-s)/(o-s)+n&&(d=!d)}return d}}const ea=new s.Matrix4,ta=new s.Vector3,ia=new s.Vector3,na=new s.Vector3;function sa(e,t){if(!e)return t.identity();const i=e.position[0],n=e.position[1],s=e.position[2];return ta.set(e.xDirection[0],e.xDirection[1],e.xDirection[2]),ia.set(e.yDirection[0],e.yDirection[1],e.yDirection[2]),na.crossVectors(ta,ia),t.set(ta.x,ia.x,na.x,i,ta.y,ia.y,na.y,n,ta.z,ia.z,na.z,s,0,0,0,1),t}const ra=new s.Matrix4,oa=new s.Matrix4;function aa(e,t,i){return sa(t,ra),sa(i,oa),ea.copy(e).multiply(ra).multiply(oa).clone()}function la(e){if(e<3)return new Uint32Array(0);const t=e-2,i=new Uint32Array(3*t);for(let e=0;e<t;e++)i[3*e]=0,i[3*e+1]=e+1,i[3*e+2]=e+2;return i}function ca(e,t,i){return`${Math.round(e*Qo)},${Math.round(t*Qo)},${Math.round(i*Qo)}`}function ha(e,t,i,n,s,r){const o=ca(e,t,i),a=ca(n,s,r);return o<a?`${o}|${a}`:`${a}|${o}`}function ua(e,t,i,n,s,r,o,a){const l=s-t,c=r-i,h=o-n,u=l*l+c*c+h*h;let d=0;u>0&&(d=((e.x-t)*l+(e.y-i)*c+(e.z-n)*h)/u,d<0?d=0:d>1&&(d=1));const p=t+d*l,f=i+d*c,m=n+d*h;a.set(p,f,m);const g=e.x-p,w=e.y-f,y=e.z-m;return g*g+w*w+y*y}class da extends le{static uuid="be9b8e6c-7f5b-4a36-8e7e-3a1f5e2a6c9d";enabled=!0;onDisposed=new re;_resolver;constructor(e){super(e),e.add(da.uuid,this),this._resolver=new Jo(e)}get(){return this._resolver}dispose(){this._resolver.dispose(),this.onDisposed.trigger()}}class pa{enabled=!0;components;onDisposed=new re;mouse;three=new s.Raycaster;world;constructor(e,t){const i=t.renderer;if(!i)throw new Error("A renderer is needed for the raycaster to work!");this.world=t,this.mouse=new hi(i.three.domElement),this.components=e}dispose(){this.mouse.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}castRayToObjects(e=Array.from(this.world.meshes),t=this.mouse.position){if(!this.world)throw new Error("A world is needed to cast rays!");const i=this.world.camera.three;return this.three.setFromCamera(t,i),this.intersect(e)}async castRay(e){const t=e?.snappingClasses,i=e?.items??Array.from(this.world.meshes),n=e?.position??this.mouse.position;if(!this.world)throw new Error("A world is needed to cast rays!");const s=this.world.camera.three,r=this.components.get(hr);let o=null;if(r.initialized){const e=this.components.get(Xo).get(this.world),a=await e.getFullPick(n);if(a){const e=r.list.get(a.modelId);if(o={localId:a.localId,point:a.point,normal:a.normal,distance:a.distance,fragments:e,object:e?.object,ray:void 0,frustum:void 0},t&&t.length>0){const e=await this.components.get(da).get().resolve(a.point,a.modelId,a.itemId,t);e&&(o.point=e.point,e.normal&&(o.normal=e.normal),o.snappingClass=e.snappingClass,e.facePoints&&(o.facePoints=e.facePoints),e.faceIndices&&(o.faceIndices=e.faceIndices),e.snappedEdgeP1&&(o.snappedEdgeP1=e.snappedEdgeP1),e.snappedEdgeP2&&(o.snappedEdgeP2=e.snappedEdgeP2),o.distance=e.point.distanceTo(s.position))}}if(0===i.length)return o}this.three.setFromCamera(n,s);const a=this.intersect(i);return o?a&&a.distance<o.distance?a:o:a}castRayFromVector(e,t,i=Array.from(this.world.meshes)){return this.three.set(e,t),this.intersect(i)}intersect(e=Array.from(this.world.meshes)){const t=this.three.intersectObjects(e),i=this.filterClippingPlanes(t);return i.length>0?i[0]:null}filterClippingPlanes(e){if(!this.world.renderer)throw new Error("Renderer not found!");const t=this.world.renderer.three;if(!t.clippingPlanes)return e;const i=t.clippingPlanes;return e.length<=0||!i||i?.length<=0?e:e.filter(e=>i.every(t=>t.distanceToPoint(e.point)>0))}}class fa extends le{static uuid="d5d8bdf0-db25-4952-b951-b643af207ace";enabled=!0;list=new Map;onDisposed=new re;constructor(e){super(e),e.add(fa.uuid,this)}get(e){if(this.list.has(e.uuid))return this.list.get(e.uuid);const t=new pa(this.components,e);return this.list.set(e.uuid,t),e.onDisposed.add(()=>{this.delete(e)}),t}delete(e){const t=this.list.get(e.uuid);t&&t.dispose(),this.list.delete(e.uuid)}dispose(){for(const[e,t]of this.list)t.dispose();this.list.clear(),this.onDisposed.trigger()}}class ma extends ae{onCameraChanged=new re;meshes=new Set;onAfterUpdate=new re;onBeforeUpdate=new re;onDisposed=new re;isDisposing=!1;enabled=!0;_dynamicAnchor=!1;_anchorRequestId=0;set dynamicAnchor(e){const t=this.renderer?.three.domElement.parentElement;if(!t)throw new Error("World: the renderer must have a parentElement to set dynamic anchoring.");e?t.addEventListener("pointerdown",this.onPointerDown):t.removeEventListener("pointerdown",this.onPointerDown),this._dynamicAnchor=e}get dynamicAnchor(){return this._dynamicAnchor}uuid=me.create();name;_scene;_camera;_renderer=null;onPointerDown=e=>{if(!this.camera.hasCameraControls())throw new Error("World: can't set dynamic anchor if the camera doesn't have controls.");if(0!==e.button)return;const t=this.getPointerPosition(e);if(!t)return;const i=this.components.get(fa).get(this),n=this.getPlaneAnchor(i,t);n&&Ca(this.camera.controls,n);const s=++this._anchorRequestId;i.castRay({position:t}).then(e=>{s!==this._anchorRequestId||this.isDisposing||!this._dynamicAnchor||e?.point&&this.camera.hasCameraControls()&&Ca(this.camera.controls,e.point)})};getPointerPosition(e){const t=this.renderer?.three.domElement;if(!t)return null;const i=t.getBoundingClientRect();return new s.Vector2((e.clientX-i.left)/(i.right-i.left)*2-1,-(e.clientY-i.top)/(i.bottom-i.top)*2+1)}getPlaneAnchor(e,t){if(!this.camera.hasCameraControls())return null;const i=this.camera.three;e.three.setFromCamera(t,i);const n=this.camera.controls.getTarget(new s.Vector3),r=i.getWorldDirection(new s.Vector3),o=(new s.Plane).setFromNormalAndCoplanarPoint(r,n);return e.three.ray.intersectPlane(o,new s.Vector3)}_defaultCamera;get defaultCamera(){if(!this._defaultCamera)throw new Error("World: there is no default camera defined.");return this._defaultCamera}set defaultCamera(e){this._defaultCamera=e}get scene(){if(!this._scene)throw new Error("No scene initialized!");return this._scene}set scene(e){this._scene=e,e.worlds.set(this.uuid,this),e.currentWorld=this,e.onWorldChanged.trigger({world:this,action:"added"})}get camera(){if(!this._camera)throw new Error("No camera initialized!");return this._camera}set camera(e){this._camera||(this.defaultCamera=e),this._camera=e,e.currentWorld=this,this.onCameraChanged.trigger(e)}get renderer(){return this._renderer}set renderer(e){this._renderer=e,e&&(e.worlds.set(this.uuid,this),e.currentWorld=this,e.onWorldChanged.trigger({world:this,action:"added"}))}useDefaultCamera(){this.camera=this.defaultCamera}update(e){this.enabled&&this._scene&&this._camera&&(this.scene.currentWorld=this,this.camera.currentWorld=this,this.renderer&&(this.renderer.currentWorld=this),this.onBeforeUpdate.trigger(),this.scene.isUpdateable()&&this.scene.update(e),this.camera.isUpdateable()&&this.camera.update(e),this.renderer&&this.renderer.update(e),this.onAfterUpdate.trigger())}dispose(e=!0){if(this.isDisposing)return;this.enabled=!1,this.isDisposing=!0;const t=this.renderer?.three.domElement.parentElement;if(t&&t.removeEventListener("pointerdown",this.onPointerDown),this._dynamicAnchor=!1,this.scene.onWorldChanged.trigger({world:this,action:"removed"}),this.camera.onWorldChanged.trigger({world:this,action:"removed"}),this.renderer&&this.renderer.onWorldChanged.trigger({world:this,action:"removed"}),e){const e=this.components.get(de);this.scene.dispose(),this.camera.isDisposeable()&&this.camera.dispose(),this.renderer&&this.renderer.dispose();for(const t of this.meshes)e.destroy(t);this.meshes.clear()}this._scene=null,this._camera=null,this._renderer=null;this.components.get(Aa).list.delete(this.uuid),this.onDisposed.trigger(),this.onDisposed.reset()}}class ga{_list;_scene;constructor(e,t){this._list=e,this._scene=t}get color(){return this._list.directionalLight.color.value}set color(e){this._list.directionalLight.color.value=e;for(const[,t]of this._scene.directionalLights)t.color.copy(e)}get intensity(){return this._list.directionalLight.intensity.value}set intensity(e){this._list.directionalLight.intensity.value=e;for(const[,t]of this._scene.directionalLights)t.intensity=e}get position(){return this._list.directionalLight.position.value.clone()}set position(e){this._list.directionalLight.position.value=e;for(const[,t]of this._scene.directionalLights)t.position.copy(e)}}class wa{_list;_scene;constructor(e,t){this._list=e,this._scene=t}get color(){return this._list.ambientLight.color.value}set color(e){this._list.ambientLight.color.value=e;for(const[,t]of this._scene.ambientLights)t.color.copy(e)}get intensity(){return this._list.ambientLight.intensity.value}set intensity(e){this._list.ambientLight.intensity.value=e;for(const[,t]of this._scene.ambientLights)t.intensity=e}}class ya extends li{_config={backgroundColor:{value:new s.Color,type:"Color"},ambientLight:{color:{type:"Color",value:new s.Color},intensity:{type:"Number",interpolable:!0,min:0,max:10,value:2}},directionalLight:{color:{type:"Color",value:new s.Color},intensity:{type:"Number",interpolable:!0,min:0,max:10,value:2},position:{type:"Vector3",value:new s.Vector3}}};ambientLight=new wa(this._config,this._component);directionalLight=new ga(this._config,this._component);get backgroundColor(){return this._config.backgroundColor.value}set backgroundColor(e){this._config.backgroundColor.value=e,this._component.three.background=e}}class _a extends pe{onSetup=new re;isSetup=!1;three;config=new ya(this,this.components,"Scene");_defaultConfig={backgroundColor:new s.Color(2107698),directionalLight:{color:new s.Color("white"),intensity:1.5,position:new s.Vector3(5,10,3)},ambientLight:{color:new s.Color("white"),intensity:1}};constructor(e){super(e),this.three=new s.Scene,this.three.background=new s.Color(2107698)}setup(e){const t={...this._defaultConfig,...e};this.config.backgroundColor=t.backgroundColor;const i=t.ambientLight;this.config.ambientLight.color=i.color,this.config.ambientLight.intensity=i.intensity;const n=t.directionalLight;this.config.directionalLight.color=n.color,this.config.directionalLight.intensity=n.intensity,this.config.directionalLight.position=n.position,this.deleteAllLights();const{color:r,intensity:o}=this.config.directionalLight,a=new s.DirectionalLight(r,o);a.position.copy(n.position);const{color:l,intensity:c}=this.config.directionalLight,h=new s.AmbientLight(l,c);this.three.add(a,h),this.directionalLights.set(a.uuid,a),this.ambientLights.set(h.uuid,h),this.isSetup=!0,this.onSetup.trigger()}dispose(){super.dispose();this.components.get(ci).list.delete(this.config.uuid)}}const ba='\n<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 120 40" fill="none" aria-label="That Open Company">\n<path d="M42.2856 19.6517V8.4048H38.8676V7.14978H46.998V8.40976H43.6131V19.6566L42.2856 19.6517Z" fill="#BCF124"/>\n<path d="M48.459 19.6516V7.14978H49.7032V12.404L49.4204 12.3371C49.6285 11.7727 50.0095 11.2904 50.5078 10.9607C51.0285 10.6201 51.638 10.4449 52.2578 10.4577C52.853 10.4483 53.44 10.5988 53.9589 10.8938C54.456 11.1789 54.8687 11.5934 55.1541 12.0943C55.449 12.6164 55.6 13.2089 55.5913 13.8102V19.6516H54.3495V14.2958C54.3637 13.8139 54.2611 13.3359 54.0507 12.9033C53.8646 12.537 53.5797 12.2315 53.229 12.0224C52.8685 11.8121 52.4584 11.7046 52.0423 11.7115C51.624 11.7054 51.2117 11.8128 50.8483 12.0224C50.4912 12.2324 50.2006 12.541 50.0106 12.912C49.7956 13.3401 49.6899 13.8158 49.7032 14.2958V19.6516H48.459Z" fill="#BCF124"/>\n<path d="M60.5388 19.8524C60.0174 19.8619 59.5007 19.75 59.0289 19.5253C58.6071 19.3259 58.2459 19.0157 57.983 18.6271C57.7263 18.2403 57.593 17.7833 57.6009 17.3175C57.5959 16.8715 57.6984 16.4309 57.8997 16.034C58.1173 15.6285 58.4383 15.2892 58.8292 15.0516C59.3232 14.7561 59.8701 14.5624 60.4384 14.4817L63.9188 13.8932V15.0355L60.7348 15.5744C60.0931 15.6867 59.6314 15.8932 59.3497 16.1938C59.0735 16.4811 58.9212 16.8673 58.926 17.268C58.9244 17.4635 58.9661 17.657 59.0481 17.8341C59.1301 18.0112 59.2503 18.1674 59.3999 18.2913C59.7416 18.5818 60.1787 18.7318 60.6246 18.7113C61.1803 18.7244 61.7296 18.5884 62.2166 18.3173C62.6597 18.066 63.0268 17.6972 63.2784 17.2506C63.535 16.7959 63.6669 16.2801 63.6604 15.7565V13.4744C63.6679 13.2259 63.6196 12.979 63.519 12.7521C63.4185 12.5253 63.2684 12.3245 63.08 12.1649C62.693 11.8287 62.1897 11.6607 61.57 11.6607C61.0801 11.6502 60.5978 11.7845 60.1822 12.047C59.7665 12.3095 59.4355 12.6888 59.2297 13.1387L58.1018 12.5192C58.2839 12.117 58.553 11.7614 58.8892 11.4785C59.2572 11.162 59.6754 10.9107 60.1261 10.7352C60.5858 10.5517 61.0758 10.4579 61.57 10.4589C62.1703 10.4448 62.7654 10.5748 63.3065 10.838C63.7888 11.077 64.1965 11.4462 64.4846 11.9047C64.7683 12.3771 64.912 12.9219 64.8986 13.4744V19.6517H63.658V17.8552L63.8405 18.0398C63.6702 18.3954 63.4238 18.7081 63.1191 18.9554C62.7772 19.238 62.3899 19.4593 61.9741 19.6095C61.5136 19.7756 61.0277 19.8578 60.5388 19.8524Z" fill="#BCF124"/>\n<path d="M70.6935 19.752C69.8975 19.752 69.2852 19.517 68.8566 19.0471C68.428 18.5771 68.2108 17.9056 68.2051 17.0326V11.9122H66.5616V10.6534H66.9804C67.1477 10.662 67.3148 10.6332 67.4697 10.5689C67.6247 10.5047 67.7637 10.4066 67.8769 10.2818C68.1017 10.0195 68.2202 9.68094 68.2088 9.33398V8.57825H69.453V10.6596H71.4124V11.9184H69.453V17.0388C69.4478 17.3107 69.4926 17.5813 69.5853 17.8366C69.6729 18.065 69.8337 18.2569 70.042 18.3818C70.3083 18.5292 70.6096 18.5991 70.9128 18.5837C71.0009 18.5837 71.1063 18.5775 71.2287 18.5664C71.3512 18.5552 71.4553 18.5441 71.5434 18.5329V19.6578C71.396 19.6937 71.2462 19.7189 71.0952 19.7334C70.9262 19.7433 70.7927 19.752 70.6935 19.752Z" fill="#BCF124"/>\n<path d="M82.2003 19.8523C81.3145 19.8603 80.4355 19.6954 79.6114 19.3666C78.4307 18.8928 77.4197 18.068 76.7118 17.001C76.0038 15.9341 75.6323 14.6751 75.646 13.3901C75.6376 12.5147 75.8043 11.6466 76.1359 10.838C76.453 10.0681 76.9213 9.37141 77.5123 8.79004C78.1118 8.20273 78.819 7.73977 79.5942 7.42723C81.2715 6.778 83.1266 6.778 84.8039 7.42723C85.5794 7.73911 86.2867 8.20215 86.8857 8.79004C87.4768 9.3717 87.9454 10.0683 88.2635 10.838C88.5945 11.6468 88.7611 12.5148 88.7533 13.3901C88.7674 14.6752 88.396 15.9343 87.688 17.0013C86.98 18.0683 85.9688 18.8931 84.7879 19.3666C83.9642 19.6952 83.0857 19.8601 82.2003 19.8523ZM82.2003 17.4984C82.7378 17.5032 83.2709 17.4005 83.769 17.1961C84.2425 16.9994 84.6735 16.7111 85.0378 16.3474C85.4069 15.9786 85.6952 15.5354 85.884 15.0465C86.0882 14.5173 86.1896 13.9532 86.1828 13.3852C86.1898 12.8203 86.0883 12.2594 85.884 11.7337C85.6922 11.2464 85.4043 10.8038 85.0378 10.4328C84.6764 10.0659 84.2446 9.77748 83.769 9.58542C82.7594 9.19396 81.6424 9.19396 80.6327 9.58542C80.1568 9.77745 79.7246 10.0658 79.3628 10.4328C78.9967 10.8041 78.7088 11.2467 78.5166 11.7337C78.3119 12.2602 78.2104 12.8219 78.2177 13.3876C78.2109 13.9557 78.3123 14.5198 78.5166 15.049C78.7058 15.5377 78.994 15.9808 79.3628 16.3499C79.7275 16.7136 80.1589 17.0019 80.6327 17.1985C81.1302 17.4038 81.663 17.5074 82.2003 17.5033V17.4984Z" fill="#BCF124"/>\n<path d="M90.398 23.2209V10.4861H92.7248V12.2293L92.5081 11.7251C92.8117 11.2627 93.2354 10.8941 93.7327 10.6596C94.2857 10.3994 94.8901 10.2702 95.4999 10.2817C96.3233 10.271 97.1335 10.4919 97.8401 10.9198C98.5312 11.3384 99.1029 11.9314 99.4995 12.6406C99.9126 13.38 100.124 14.2172 100.112 15.0664C100.122 15.9116 99.913 16.7448 99.5069 17.4835C99.1168 18.1988 98.5469 18.7971 97.8548 19.218C97.1376 19.6483 96.3164 19.8688 95.4827 19.8548C94.894 19.8605 94.3104 19.7437 93.7682 19.5116C93.2614 19.2967 92.8226 18.9454 92.4995 18.4957L92.8975 17.9754V23.2234L90.398 23.2209ZM95.1741 17.5863C95.6033 17.5949 96.0268 17.4848 96.3987 17.268C96.7521 17.0559 97.0394 16.7477 97.2278 16.3784C97.4328 15.9736 97.5355 15.5237 97.5266 15.0689C97.5364 14.6168 97.4337 14.1694 97.2278 13.768C97.0366 13.4007 96.7499 13.0932 96.3987 12.8785C96.0288 12.6556 95.6046 12.5419 95.1741 12.5502C94.7569 12.5434 94.3461 12.6541 93.9874 12.8698C93.6387 13.0826 93.3568 13.391 93.1743 13.7593C92.9832 14.1688 92.8841 14.6161 92.8841 15.0689C92.8841 15.5217 92.9832 15.9689 93.1743 16.3784C93.3571 16.7465 93.639 17.0548 93.9874 17.268C94.3469 17.4837 94.7586 17.594 95.1766 17.5863H95.1741Z" fill="#BCF124"/>\n<path d="M105.924 19.8524C104.961 19.8524 104.126 19.6372 103.418 19.2069C102.724 18.7915 102.156 18.1916 101.776 17.4724C101.384 16.7291 101.184 15.8977 101.194 15.0553C101.179 14.1986 101.388 13.3532 101.801 12.6047C102.189 11.9046 102.753 11.3198 103.434 10.9087C104.139 10.4899 104.944 10.2756 105.761 10.2892C106.414 10.277 107.062 10.394 107.67 10.6336C108.202 10.8483 108.68 11.1777 109.073 11.5987C109.454 12.0141 109.75 12.5023 109.943 13.0346C110.147 13.6019 110.248 14.2016 110.242 14.805C110.242 14.9847 110.234 15.1606 110.218 15.334C110.205 15.4855 110.174 15.6349 110.126 15.7788H103.34V13.9266H108.716L107.538 14.8001C107.65 14.3786 107.645 13.9339 107.522 13.5153C107.411 13.1561 107.186 12.8437 106.883 12.6258C106.553 12.4 106.161 12.2855 105.762 12.2987C105.368 12.2877 104.981 12.3993 104.652 12.6184C104.327 12.8492 104.083 13.1779 103.955 13.5574C103.79 14.0428 103.728 14.5577 103.772 15.0689C103.719 15.5315 103.782 16.0001 103.955 16.4317C104.108 16.81 104.375 17.1302 104.718 17.3473C105.08 17.5514 105.486 17.6634 105.901 17.6736C106.316 17.6837 106.727 17.5917 107.098 17.4055C107.407 17.2317 107.661 16.9743 107.833 16.6622L109.824 17.6186C109.643 18.0737 109.355 18.4776 108.986 18.7956C108.59 19.1398 108.132 19.4046 107.638 19.5761C107.087 19.766 106.507 19.8594 105.924 19.8524Z" fill="#BCF124"/>\n<path d="M111.703 19.6516V10.4837H114.03V12.2962L113.898 11.8935C114.081 11.3764 114.443 10.944 114.918 10.6769C115.425 10.404 115.994 10.2679 116.569 10.2817C117.196 10.2676 117.816 10.4179 118.369 10.7178C118.875 11.0011 119.293 11.4232 119.573 11.9357C119.87 12.4948 120.018 13.1223 120.004 13.7569V19.6491H117.515V14.2958C117.524 13.9753 117.452 13.6579 117.307 13.3728C117.173 13.1206 116.972 12.9112 116.727 12.7682C116.459 12.625 116.162 12.5502 115.859 12.5502C115.557 12.5502 115.26 12.625 114.992 12.7682C114.743 12.9091 114.539 13.1188 114.403 13.3728C114.259 13.658 114.188 13.9754 114.196 14.2958V19.6516H111.703Z" fill="#BCF124"/>\n<path d="M45.7329 35.9372C44.8875 35.9451 44.0493 35.7794 43.269 35.4503C42.525 35.134 41.851 34.6707 41.2863 34.0875C40.7178 33.4992 40.2696 32.8033 39.9673 32.0396C39.6453 31.2229 39.4843 30.3504 39.4934 29.4713C39.4848 28.5902 39.6427 27.7155 39.9588 26.8943C40.2511 26.1324 40.6939 25.4388 41.2601 24.8558C41.8262 24.2727 42.504 23.8126 43.2518 23.5034C44.039 23.178 44.8826 23.015 45.7329 23.024C46.5598 23.0107 47.3809 23.1649 48.1479 23.4774C48.8259 23.756 49.443 24.1669 49.9641 24.6866C50.4412 25.1559 50.8045 25.7304 51.0258 26.3653L48.7529 27.4729C48.5362 26.8433 48.1263 26.3001 47.5831 25.9226C47.0399 25.5451 46.3917 25.3529 45.7329 25.3742C45.0556 25.3604 44.3882 25.5408 43.8078 25.8945C43.2553 26.2426 42.8099 26.74 42.5219 27.3304C42.2056 27.9978 42.0495 28.7313 42.0664 29.4713C42.0503 30.2135 42.2063 30.9493 42.5219 31.6196C42.8077 32.2136 43.2534 32.7139 43.8078 33.0629C44.3879 33.4172 45.0555 33.5976 45.7329 33.5832C46.3917 33.6045 47.0399 33.4124 47.5831 33.0348C48.1263 32.6573 48.5362 32.1142 48.7529 31.4845L51.0258 32.5933C50.8056 33.2316 50.4422 33.8096 49.9641 34.282C49.4426 34.8009 48.8256 35.2113 48.1479 35.4899C47.3805 35.8004 46.5594 35.9524 45.7329 35.9372Z" fill="#BCF124"/>\n<path d="M56.8159 35.9372C55.9603 35.9485 55.1164 35.735 54.3667 35.3177C53.6426 34.9153 53.0357 34.3274 52.6069 33.613C52.1777 32.8648 51.9517 32.0151 51.9517 31.15C51.9517 30.285 52.1777 29.4353 52.6069 28.6871C53.0376 27.9762 53.6442 27.3911 54.3667 26.9898C55.118 26.5823 55.9573 26.3691 56.8098 26.3691C57.6623 26.3691 58.5016 26.5823 59.253 26.9898C59.9716 27.3928 60.5749 27.9771 61.0042 28.6858C61.4334 29.4341 61.6594 30.2837 61.6594 31.1488C61.6594 32.0139 61.4334 32.8635 61.0042 33.6118C60.577 34.3244 59.9733 34.912 59.253 35.3165C58.5078 35.7343 57.6678 35.9482 56.8159 35.9372ZM56.8159 33.6712C57.2335 33.681 57.6451 33.5701 58.0026 33.3516C58.3443 33.1354 58.6199 32.8274 58.7986 32.462C58.9985 32.0556 59.0985 31.6064 59.0901 31.1525C59.099 30.7014 58.9989 30.2548 58.7986 29.8517C58.6161 29.4889 58.3414 29.1818 58.0026 28.9621C57.6468 28.739 57.2345 28.6254 56.8159 28.635C56.3952 28.6261 55.9807 28.7396 55.6219 28.9621C55.2792 29.18 55.0008 29.4873 54.8161 29.8517C54.6162 30.2549 54.5166 30.7015 54.5259 31.1525C54.517 31.6063 54.6166 32.0555 54.8161 32.462C54.997 32.8291 55.2762 33.1373 55.6219 33.3516C55.9824 33.5695 56.3962 33.6803 56.8159 33.6712Z" fill="#BCF124"/>\n<path d="M63.1228 35.7364V26.5685H65.4496V28.7985L65.2047 28.4269C65.337 27.7223 65.6574 27.202 66.1661 26.8658C66.7124 26.5198 67.3477 26.3448 67.992 26.3628C68.6955 26.3487 69.3867 26.5504 69.9747 26.9414C70.2455 27.1163 70.4794 27.3435 70.6631 27.6102C70.8468 27.8768 70.9766 28.1775 71.045 28.495L70.3311 28.5619C70.6299 27.8128 71.056 27.2586 71.6096 26.8993C72.1912 26.5332 72.8658 26.3468 73.5506 26.3628C74.1566 26.3506 74.755 26.5011 75.2847 26.7989C75.7839 27.0856 76.1947 27.5068 76.4714 28.0155C76.7686 28.5772 76.9163 29.2073 76.9 29.8442V35.7364H74.4067V30.3806C74.4151 30.0621 74.3496 29.746 74.2156 29.4576C74.0956 29.2086 73.9084 28.999 73.6756 28.853C73.4175 28.71 73.1279 28.635 72.8336 28.635C72.5393 28.635 72.2498 28.71 71.9917 28.853C71.7556 28.9972 71.5655 29.2071 71.4443 29.4576C71.3103 29.746 71.2448 30.0621 71.2532 30.3806V35.7364H68.7648V30.3806C68.7731 30.0621 68.7077 29.746 68.5737 29.4576C68.4538 29.2089 68.267 28.9994 68.0349 28.853C67.7765 28.71 67.4868 28.635 67.1923 28.635C66.8978 28.635 66.6081 28.71 66.3498 28.853C66.1137 28.9972 65.9236 29.2071 65.8023 29.4576C65.6683 29.746 65.6029 30.0621 65.6113 30.3806V35.7364H63.1228Z" fill="#BCF124"/>\n<path d="M78.5374 39.3107V26.5697H80.8642V28.3166L80.6486 27.8123C80.9522 27.35 81.376 26.9813 81.8733 26.7469C82.4266 26.4883 83.0311 26.3611 83.6404 26.3752C84.464 26.3639 85.2743 26.5848 85.9807 27.0132C86.6715 27.4323 87.2431 28.0251 87.6401 28.7341C88.0532 29.473 88.2645 30.3098 88.2524 31.1586C88.2623 32.0044 88.0533 32.8381 87.6462 33.577C87.2571 34.2926 86.6875 34.8911 85.9954 35.3115C85.2785 35.7427 84.4572 35.9636 83.6233 35.9495C83.0345 35.9548 82.4509 35.8376 81.9088 35.6051C81.4019 35.391 80.963 35.04 80.6401 34.5904L81.0381 34.0701V39.3231L78.5374 39.3107ZM83.3134 33.6712C83.7428 33.6796 84.1663 33.5691 84.5381 33.3515C84.892 33.1399 85.1798 32.8316 85.3684 32.462C85.573 32.057 85.6757 31.6072 85.6672 31.1524C85.6761 30.7004 85.5734 30.2533 85.3684 29.8516C85.176 29.4847 84.8891 29.1774 84.5381 28.962C84.1679 28.7398 83.7438 28.6266 83.3134 28.635C82.8964 28.6281 82.4856 28.7383 82.1268 28.9534C81.778 29.1666 81.496 29.4755 81.3136 29.8442C81.1225 30.2534 81.0233 30.7004 81.0233 31.1531C81.0233 31.6057 81.1225 32.0527 81.3136 32.462C81.4954 32.8308 81.7775 33.1394 82.1268 33.3515C82.4863 33.5682 82.8986 33.679 83.3171 33.6712H83.3134Z" fill="#BCF124"/>\n<path d="M92.5093 35.9371C91.9294 35.9511 91.353 35.8427 90.8168 35.6187C90.3699 35.4306 89.9887 35.1118 89.722 34.7032C89.4607 34.2804 89.3278 33.7893 89.3399 33.2908C89.3319 32.8129 89.4525 32.3418 89.689 31.928C89.9498 31.5033 90.3197 31.1581 90.7593 30.9295C91.3217 30.6339 91.931 30.4406 92.5595 30.3583L95.3296 29.9049V31.7521L93.0028 32.1708C92.7069 32.2127 92.4268 32.3314 92.1897 32.5153C92.0938 32.6024 92.0186 32.7102 91.9696 32.8307C91.9207 32.9513 91.8992 33.0814 91.9068 33.2115C91.9015 33.3387 91.9277 33.4652 91.9828 33.5796C92.038 33.6941 92.1204 33.7928 92.2227 33.8669C92.4503 34.0296 92.7243 34.1123 93.0028 34.1023C93.3792 34.1101 93.7509 34.0174 94.0805 33.8335C94.3832 33.6617 94.6332 33.4087 94.803 33.1025C94.9751 32.7929 95.0638 32.443 95.0602 32.0878V29.698C95.062 29.5308 95.0264 29.3654 94.956 29.2141C94.8855 29.0628 94.7822 28.9296 94.6536 28.8245C94.3818 28.5891 94.0144 28.4714 93.5515 28.4714C93.1318 28.4645 92.7212 28.5949 92.3807 28.8431C92.0467 29.0873 91.7912 29.4256 91.6459 29.8157L89.6547 28.8592C89.826 28.354 90.1169 27.8989 90.5021 27.5336C90.9038 27.1547 91.3782 26.8634 91.8958 26.6775C92.4648 26.471 93.0657 26.3686 93.6702 26.3752C94.3679 26.3612 95.0599 26.5046 95.6958 26.7952C96.2502 27.0473 96.724 27.4511 97.0637 27.961C97.3951 28.4765 97.5658 29.0807 97.5536 29.6955V35.7389H95.2268V34.2584L95.7913 34.1581C95.5497 34.5339 95.2533 34.8706 94.912 35.1566C94.5921 35.4193 94.2261 35.6185 93.8331 35.7439C93.4044 35.877 92.9578 35.9422 92.5093 35.9371Z" fill="#BCF124"/>\n<path d="M99.3795 35.7365V26.5685H101.706V28.3823L101.573 27.9796C101.757 27.4626 102.119 27.0301 102.593 26.7618C103.101 26.4898 103.67 26.3542 104.245 26.3678C104.872 26.3532 105.493 26.5034 106.045 26.8039C106.551 27.0867 106.968 27.5085 107.248 28.0205C107.545 28.5801 107.693 29.208 107.679 29.8429V35.7352H105.189V30.3806C105.197 30.0603 105.126 29.743 104.982 29.4576C104.848 29.2051 104.646 28.9957 104.401 28.8531C104.135 28.7035 103.834 28.6282 103.53 28.635C103.23 28.6314 102.935 28.7065 102.673 28.8531C102.423 28.9936 102.219 29.2034 102.084 29.4576C101.939 29.7428 101.868 30.0603 101.877 30.3806V35.7365H99.3795Z" fill="#BCF124"/>\n<path d="M110.563 39.4631C110.304 39.4633 110.046 39.4405 109.791 39.3949C109.563 39.3571 109.342 39.2835 109.136 39.1769V37.1128C109.316 37.1628 109.499 37.2017 109.684 37.2293C109.875 37.2621 110.07 37.2791 110.264 37.2801C110.754 37.2801 111.099 37.1562 111.31 36.9282C111.522 36.6884 111.696 36.4162 111.824 36.1217L112.437 34.6945L112.404 36.7932L108.421 26.5697H111.093L113.731 33.8384H112.735L115.373 26.5697H118.048L114.165 36.5925C113.955 37.1702 113.652 37.7089 113.269 38.187C112.942 38.5905 112.531 38.9169 112.066 39.1434C111.594 39.3617 111.081 39.4709 110.563 39.4631Z" fill="#BCF124"/>\n<path d="M7.00861 16.1097H0C0.00583172 11.8399 1.68502 7.74676 4.66939 4.7276C7.65377 1.70844 11.6998 0.00968387 15.9203 0.00378418V7.09408C13.558 7.09801 11.2935 8.04913 9.62308 9.73902C7.95266 11.4289 7.0125 13.7198 7.00861 16.1097Z" fill="#BCF124"/>\n<path d="M15.9243 39.3094C11.7037 39.3035 7.65771 37.6047 4.67333 34.5856C1.68896 31.5664 0.00976849 27.4732 0.00393677 23.2035H7.01255C7.01255 24.9874 7.53543 26.7311 8.51506 28.2144C9.4947 29.6976 10.8871 30.8536 12.5162 31.5362C14.1452 32.2189 15.9378 32.3975 17.6672 32.0495C19.3966 31.7015 20.9852 30.8425 22.2321 29.5811C23.4789 28.3197 24.328 26.7127 24.672 24.9631C25.016 23.2135 24.8394 21.4 24.1647 19.752C23.4899 18.1039 22.3472 16.6953 20.881 15.7042C19.4149 14.7132 17.6912 14.1842 15.9279 14.1842V7.09021C20.1512 7.09021 24.2016 8.78747 27.1879 11.8086C30.1742 14.8297 31.8519 18.9273 31.8519 23.1998C31.8519 27.4723 30.1742 31.5699 27.1879 34.591C24.2016 37.6121 20.1512 39.3094 15.9279 39.3094H15.9243Z" fill="#BCF124"/>\n</svg>\n'.trim();var va=(e=>(e[e.MANUAL=0]="MANUAL",e[e.AUTO=1]="AUTO",e))(va||{});class xa extends ue{enabled=!0;container;three;mode=1;needsUpdate=!1;_canvas;_parameters;_resizeObserver=null;onContainerUpdated=new re;_resizing=!1;_logo=null;_showLogo=!0;get showLogo(){return this._showLogo}set showLogo(e){this._showLogo=e,this._logo&&(this._logo.style.display=e?"":"none")}get logo(){return this._logo}constructor(e,t,i){super(e),this.container=t,this._parameters=i,this.three=new s.WebGLRenderer({antialias:!0,alpha:!0,...i}),this.three.setPixelRatio(Math.min(window.devicePixelRatio,2)),this.setupRenderer(),this.setupEvents(!0),this.resize(),this._canvas=this.three.domElement;const n=this.three.getContext(),{canvas:r}=n;r.addEventListener("webglcontextlost",this.onContextLost,!1),r.addEventListener("webglcontextrestored",this.onContextBack,!1)}update(){if(!this.enabled||!this.currentWorld)return;if(0===this.mode&&!this.needsUpdate)return;this.needsUpdate=!1,this.onBeforeUpdate.trigger(this);const e=this.currentWorld.scene.three,t=this.currentWorld.camera.three;this.three.render(e,t),this.onAfterUpdate.trigger(this)}dispose(){this.enabled=!1,this.setupEvents(!1),this.three.domElement.remove(),this._logo&&(this._logo.remove(),this._logo=null),this.three.forceContextLoss(),this.three.dispose(),this.onResize.reset(),this.onAfterUpdate.reset(),this.onBeforeUpdate.reset(),this.onDisposed.trigger(),this.onDisposed.reset()}getSize(){return new s.Vector2(this.three.domElement.clientWidth,this.three.domElement.clientHeight)}resize=e=>{if(this._resizing)return;this._resizing=!0,this.onContainerUpdated.trigger();const t=e?e.x:this.container.clientWidth,i=e?e.y:this.container.clientHeight;this.three.setSize(t,i),this.onResize.trigger(new s.Vector2(t,i)),this._resizing=!1};setupEvents(e){const t=this.three.domElement.parentElement;if(!t)throw new Error("This renderer needs to have an HTML container!");this._resizeObserver&&(this._resizeObserver.disconnect(),this._resizeObserver=null),window.removeEventListener("resize",this.resizeEvent),e&&(this._resizeObserver=new ResizeObserver(this.resizeEvent),this._resizeObserver.observe(t),window.addEventListener("resize",this.resizeEvent))}resizeEvent=()=>{this.resize()};setupRenderer(){this.three.localClippingEnabled=!0,this.container&&(this.container.appendChild(this.three.domElement),this.setupLogo()),this.onContainerUpdated.trigger()}setupLogo(){if(this._logo||!this.container)return;"static"===window.getComputedStyle(this.container).position&&(this.container.style.position="relative"),this._logo=function(){const e=document.createElement("div");e.setAttribute("data-thatopen-logo",""),e.innerHTML=ba,e.style.cssText=["position: absolute","left: 0.75rem","bottom: 0.75rem","width: 6rem","height: auto","pointer-events: none","user-select: none","opacity: 0.85","z-index: 1"].join("; ");const t=e.firstElementChild;return t&&(t.setAttribute("width","100%"),t.setAttribute("height","100%")),e}(),this._logo.style.display=this._showLogo?"":"none",this.container.appendChild(this._logo)}onContextLost=e=>{e.preventDefault(),this.enabled=!1};onContextBack=()=>{this.three.setRenderTarget(null),this.three.dispose(),this.three=new s.WebGLRenderer({canvas:this._canvas,antialias:!0,alpha:!0,...this._parameters}),this.enabled=!0}}function Ca(e,t){const{minDistance:i}=e;e.minDistance=.01,e.setOrbitPoint(t.x,t.y,t.z),e.minDistance=i}class Sa extends he{onBeforeUpdate=new re;onAfterUpdate=new re;onAspectUpdated=new re;onDisposed=new re;three;_resizeObserver=null;_allControls=new Map;get controls(){if(!this.currentWorld)throw new Error("This camera needs a world to work!");const e=this._allControls.get(this.currentWorld.uuid);if(!e)throw new Error("Controls not found!");return e}get enabled(){return null!==this.currentWorld&&this.controls.enabled}set enabled(e){null!==this.currentWorld&&(this.controls.enabled=e)}set currentWorld(e){if(super.currentWorld=e,!e)return;this.worlds.get(e.uuid)||this.worlds.set(e.uuid,e)}get currentWorld(){return this._currentWorld}constructor(e){super(e),this.three=this.setupCamera(),this.worlds.onItemSet.add(({value:e})=>{const t=this.newCameraControls();this.setupEvents(!0),this._allControls.set(e.uuid,t)}),this.worlds.onBeforeDelete.add(({value:e})=>{const t=this._allControls.get(e.uuid);t&&(t.dispose(),this._allControls.delete(e.uuid)),this._resizeObserver?.disconnect()})}dispose(){this.setupEvents(!1),this.onAspectUpdated.reset(),this.onBeforeUpdate.reset(),this.onAfterUpdate.reset(),this.three.removeFromParent(),this.onDisposed.trigger(),this.onDisposed.reset();for(const[e,t]of this._allControls)t.dispose();this.worlds.clear()}async fitToItems(e){const t=await this.getItemsBounding(e);await this.controls.fitToSphere(t,!0)}async setOrbitToItems(e){const t=await this.getItemsBounding(e);Ca(this.controls,t.center)}update(e){this.enabled&&(this.onBeforeUpdate.trigger(this),this.controls.update(e),this.onAfterUpdate.trigger(this))}updateAspect=()=>{if(this.currentWorld&&this.currentWorld.renderer){if(this.currentWorld.renderer?.isResizeable()){const e=this.currentWorld.renderer.getSize();if(0===e.width||0===e.height)return}if(this.three instanceof s.OrthographicCamera)this.onAspectUpdated.trigger();else if(this.currentWorld.renderer?.isResizeable()){const e=this.currentWorld.renderer.getSize();this.three.aspect=e.width/e.height,this.three.updateProjectionMatrix(),this.onAspectUpdated.trigger()}}};async getItemsBounding(e){const t=this.components.get(hr),i=this.components.get(zo);i.list.clear();const n=new s.Sphere;if(e)await i.addFromModelIdMap(e);else for(const[,e]of t.list)i.list.add(e.box);return i.get().getBoundingSphere(n),i.list.clear(),n}setupCamera(){const e=window.innerWidth/window.innerHeight,t=new s.PerspectiveCamera(60,e,1,1e3);return t.position.set(50,50,50),t.lookAt(new s.Vector3(0,0,0)),t}newCameraControls(){if(!this.currentWorld)throw new Error("This camera needs a world to work!");if(!this.currentWorld.renderer)throw new Error("This camera needs a renderer to work!");ne.install({THREE:Sa.getSubsetOfThree()});const{domElement:e}=this.currentWorld.renderer.three,t=new ne(this.three,e);return t.smoothTime=.2,t.dollyToCursor=!0,t.infinityDolly=!0,t.minDistance=6,t}setupEvents(e){if(this._resizeObserver&&(this._resizeObserver.disconnect(),this._resizeObserver=null),e){if(!this.currentWorld)throw new Error("This camera needs a world to work!");if(!this.currentWorld.renderer)throw new Error("This camera needs a renderer to work!");const{domElement:e}=this.currentWorld.renderer.three;this._resizeObserver=new ResizeObserver(this.updateAspect),this._resizeObserver.observe(e)}}static getSubsetOfThree(){return{MOUSE:s.MOUSE,Vector2:s.Vector2,Vector3:s.Vector3,Vector4:s.Vector4,Quaternion:s.Quaternion,Matrix4:s.Matrix4,Spherical:s.Spherical,Box3:s.Box3,Sphere:s.Sphere,Raycaster:s.Raycaster,MathUtils:s.MathUtils}}}class Aa extends le{static uuid="fdb61dc4-2ec1-4966-b83d-54ea795fad4a";onAfterUpdate=new re;onBeforeUpdate=new re;onDisposed=new re;list=new t;enabled=!0;constructor(e){super(e),e.add(Aa.uuid,this)}create(){const e=new ma(this.components),t=e.uuid;if(this.list.has(t))throw new Error("There is already a world with this name!");return this.list.set(t,e),e}delete(e){if(!this.list.has(e.uuid))throw new Error("The provided world is not found in the list!");this.list.delete(e.uuid),e.dispose()}dispose(){this.enabled=!1;for(const[e,t]of this.list)t.dispose();this.list.clear(),this.onDisposed.trigger()}update(e){if(this.enabled)for(const[t,i]of this.list)i.update(e)}}class Ta extends li{_config={visible:{value:!0,type:"Boolean"},color:{value:new s.Color,type:"Color"},primarySize:{type:"Number",interpolable:!0,value:1,min:0,max:1e3},secondarySize:{type:"Number",interpolable:!0,value:10,min:0,max:1e3},distance:{type:"Number",interpolable:!0,value:500,min:0,max:500}};get visible(){return this._config.visible.value}set visible(e){this._config.visible.value=e,this._component.visible=e}get color(){return this._config.color.value}set color(e){this._config.color.value=e,this._component.material.uniforms.uColor.value=e,this._component.material.uniformsNeedUpdate=!0}get primarySize(){return this._config.primarySize.value}set primarySize(e){this._config.primarySize.value=e,this._component.material.uniforms.uSize1.value=e,this._component.material.uniformsNeedUpdate=!0}get secondarySize(){return this._config.secondarySize.value}set secondarySize(e){this._config.secondarySize.value=e,this._component.material.uniforms.uSize2.value=e,this._component.material.uniformsNeedUpdate=!0}get distance(){return this._config.distance.value}set distance(e){this._config.distance.value=e,this._component.material.uniforms.uDistance.value=e,this._component.material.uniformsNeedUpdate=!0}}class Pa{onDisposed=new re;onSetup=new re;isSetup=!1;world;components;config;_defaultConfig={visible:!0,color:new s.Color(12303291),primarySize:1,secondarySize:10,distance:500};get visible(){return this.three.visible}set visible(e){if(this.three.visible=e,e){this.world.scene.three.add(this.three)}else this.three.removeFromParent()}get material(){return this.three.material}get fade(){return 3===this._fade}set fade(e){this._fade=e?3:0,this.material.uniforms.uFade.value=this._fade}three;_fade=3;constructor(e,t){this.world=t;const{color:i,primarySize:n,secondarySize:r,distance:o}=this._defaultConfig;this.components=e,this.config=new Ta(this,this.components,"Grid");const a=new s.PlaneGeometry(2,2,1,1),l=new s.ShaderMaterial({side:s.DoubleSide,uniforms:{uSize1:{value:n},uSize2:{value:r},uColor:{value:i},uDistance:{value:o},uFade:{value:this._fade},uZoom:{value:1}},transparent:!0,vertexShader:"\n \n varying vec3 worldPosition;\n \n uniform float uDistance;\n \n void main() {\n \n vec3 pos = position.xzy * uDistance;\n pos.xz += cameraPosition.xz;\n \n worldPosition = pos;\n \n gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);\n \n }\n ",fragmentShader:"\n \n varying vec3 worldPosition;\n \n uniform float uZoom;\n uniform float uFade;\n uniform float uSize1;\n uniform float uSize2;\n uniform vec3 uColor;\n uniform float uDistance;\n \n \n \n float getGrid(float size) {\n \n vec2 r = worldPosition.xz / size;\n \n \n vec2 grid = abs(fract(r - 0.5) - 0.5) / fwidth(r);\n float line = min(grid.x, grid.y);\n \n \n return 1.0 - min(line, 1.0);\n }\n \n void main() {\n \n \n float d = 1.0 - min(distance(cameraPosition.xz, worldPosition.xz) / uDistance, 1.0);\n \n float g1 = getGrid(uSize1);\n float g2 = getGrid(uSize2);\n \n // Ortho camera fades the grid away when zooming out\n float minZoom = step(0.2, uZoom);\n float zoomFactor = pow(min(uZoom, 1.), 2.) * minZoom;\n \n gl_FragColor = vec4(uColor.rgb, mix(g2, g1, g1) * pow(d, uFade));\n gl_FragColor.a = mix(0.5 * gl_FragColor.a, gl_FragColor.a, g2) * zoomFactor;\n \n if ( gl_FragColor.a <= 0.0 ) discard;\n \n \n }\n \n ",extensions:{derivatives:!0}});this.three=new s.Mesh(a,l),this.three.frustumCulled=!1,t.scene.three.add(this.three),this.setupEvents(!0)}setup(e){const t={...this._defaultConfig,...e};this.config.visible=!0,this.config.color=t.color,this.config.primarySize=t.primarySize,this.config.secondarySize=t.secondarySize,this.config.distance=t.distance,this.isSetup=!0,this.onSetup.trigger()}dispose(){this.setupEvents(!1);this.components.get(ci).list.delete(this.config.uuid);this.components.get(de).destroy(this.three),this.onDisposed.trigger(),this.onDisposed.reset(),this.world=null,this.components=null}setupEvents(e){if(this.world.isDisposing)return;if(!(this.world.camera instanceof Sa))return;const t=this.world.camera.controls;e?t.addEventListener("update",this.updateZoom):t.removeEventListener("update",this.updateZoom)}updateZoom=()=>{this.world.camera instanceof Sa&&(this.material.uniforms.uZoom.value=this.world.camera.three.zoom)}}class Ea extends le{static uuid="d1e814d5-b81c-4452-87a2-f039375e0489";list=new Map;onDisposed=new re;enabled=!0;constructor(e){super(e),e.add(Ea.uuid,this)}create(e){if(this.list.has(e.uuid))throw new Error("This world already has a grid!");const t=new Pa(this.components,e);return this.list.set(e.uuid,t),e.onDisposed.add(()=>{this.delete(e)}),t}delete(e){const t=this.list.get(e.uuid);t&&t.dispose(),this.list.delete(e.uuid)}dispose(){for(const[e,t]of this.list)t.dispose();this.list.clear(),this.onDisposed.trigger(),this.onDisposed.reset()}}class Ma{static release="2.4.3";onDisposed=new re;list=new t;enabled=!1;_timer;onInit=new re;add(e,t){if(this.list.has(e))throw new Error("You're trying to add a component that already exists in the components instance. Use Components.get() instead.");me.validate(e),this.list.set(e,t)}get(e){const t=e.uuid;if(!this.list.has(t)){const i=new e(this);return i.isDisposeable?.()&&i.onDisposed.add(()=>this.list.delete(t)),this.list.has(t)||this.add(t,i),i}return this.list.get(t)}constructor(){this._timer=new s.Timer,Ma.setupBVH()}init(){this.enabled=!0;for(const[e,t]of this.list.entries())t.enabled=!0;this._timer.reset(),this.update(),this.onInit.trigger()}dispose(){let e,t;this.enabled=!1;for(const[i,n]of this.list)n.enabled=!1,i!==hr.uuid?i!==Aa.uuid?n.isDisposeable()&&n.dispose():t=n:e=n;t?.isDisposeable()&&t.dispose(),e?.dispose(),this._timer.dispose(),this.onDisposed.trigger()}update=()=>{if(!this.enabled)return;this._timer.update();const e=this._timer.getDelta();for(const[t,i]of this.list)i.enabled&&i.isUpdateable()&&i.update(e);requestAnimationFrame(this.update)};static setupBVH(){s.BufferGeometry.prototype.computeBoundsTree=lr,s.BufferGeometry.prototype.disposeBoundsTree=cr,s.Mesh.prototype.raycast=or,s.LineSegments.prototype.raycast=or}}class Ia{constructor(e){this.camera=e}camera;enabled=!1;id="FirstPerson";set(e,t){if(this.enabled=e,e){if("Perspective"!==this.camera.projection.current)return void this.camera.set("Orbit");this.setupFirstPersonCamera(t)}}setupFirstPersonCamera(e){const t=this.camera.controls;if(e?.preventTargetAdjustment)t.minDistance=1,t.maxDistance=1,t.distance=1;else{const e=new s.Vector3;t.distance--,t.getPosition(e),t.minDistance=1,t.maxDistance=1,t.distance=1,t.moveTo(e.x,e.y,e.z)}t.truckSpeed=50,t.mouseButtons.wheel=ne.ACTION.DOLLY,t.touches.two=ne.ACTION.TOUCH_ZOOM_TRUCK}}class za{constructor(e){this.camera=e,this.activateOrbitControls()}camera;enabled=!0;id="Orbit";set(e,t){this.enabled=e,e&&this.activateOrbitControls(t)}activateOrbitControls(e){const t=this.camera.controls;t.minDistance=1,t.maxDistance=300;const i=new s.Vector3;t.getPosition(i);const n=i.length();if(t.distance=n,t.truckSpeed=2,e?.preventTargetAdjustment)return;const{rotation:r}=this.camera.three,o=new s.Vector3(0,0,-1).applyEuler(r),a=i.addScaledVector(o,n);t.moveTo(a.x,a.y,a.z)}}class Da{constructor(e){this.camera=e,this.defaultAzimuthSpeed=e.controls.azimuthRotateSpeed,this.defaultPolarSpeed=e.controls.polarRotateSpeed}camera;enabled=!1;id="Plan";mouseAction1;mouseAction2;mouseInitialized=!1;defaultAzimuthSpeed;defaultPolarSpeed;set(e,t){this.enabled=e;const i=this.camera.controls;i.azimuthRotateSpeed=e?0:this.defaultAzimuthSpeed,i.polarRotateSpeed=e?0:this.defaultPolarSpeed,this.mouseInitialized||(this.mouseAction1=i.touches.one,this.mouseAction2=i.touches.two,this.mouseInitialized=!0),e?(i.mouseButtons.left=ne.ACTION.TRUCK,i.touches.one=ne.ACTION.TOUCH_TRUCK,i.touches.two=ne.ACTION.TOUCH_ZOOM):(i.mouseButtons.left=ne.ACTION.ROTATE,i.touches.one=this.mouseAction1,i.touches.two=this.mouseAction2)}}class ka{onChanged=new re;current="Perspective";camera;matchOrthoDistanceEnabled=!1;_component;_previousDistance=-1;constructor(e){this._component=e,this.camera=e.three}async set(e){if(this.current===e)return;let t;"Orthographic"===e?t=this.setOrthoCamera():(await this.setPerspectiveCamera(),t=!0),t&&this.onChanged.trigger(this.camera)}async toggle(){const e="Perspective"===this.current?"Orthographic":"Perspective";await this.set(e)}setOrthoCamera(){if(!this._component.hasMode)return!1;if("FirstPerson"===this._component.mode.id)return!1;const e=this._component.currentWorld;if(!e||!e.renderer)return!1;this._previousDistance=this._component.controls.distance,this._component.controls.distance=200;const t=this.getPerspectiveDims();if(!t)return this._component.controls.distance=this._previousDistance,!1;const{width:i,height:n}=t;return this.setupOrthoCamera(n,i),this.camera=this._component.threeOrtho,this.current="Orthographic",!0}getPerspectiveDims(){const e=this._component.currentWorld;if(!e||!e.renderer)return null;const t=new s.Vector3;this._component.threePersp.getWorldDirection(t);const i=new s.Vector3;this._component.controls.getTarget(i);const n=i.clone().sub(this._component.threePersp.position).dot(t),r=e.renderer.getSize(),o=r.x/r.y,a=this._component.threePersp,l=2*n*Math.tan(a.fov*(Math.PI/180)/2);return{width:l*o,height:l}}setupOrthoCamera(e,t){this._component.controls.mouseButtons.wheel=ne.ACTION.ZOOM,this._component.controls.mouseButtons.middle=ne.ACTION.ZOOM;const i=this._component.threePersp,n=this._component.threeOrtho;n.zoom=1,n.left=t/-2,n.right=t/2,n.top=e/2,n.bottom=e/-2,n.updateProjectionMatrix(),n.position.copy(i.position),n.quaternion.copy(i.quaternion),this._component.controls.camera=n}getDistance(){const e=this._component.threePersp,t=this._component.threeOrtho;return(t.top-t.bottom)/t.zoom/(2*Math.tan(e.fov*(Math.PI/180)/2))}async setPerspectiveCamera(){this._component.controls.mouseButtons.wheel=ne.ACTION.DOLLY,this._component.controls.mouseButtons.middle=ne.ACTION.DOLLY;const e=this._component.threePersp,t=this._component.threeOrtho;e.position.copy(t.position),e.quaternion.copy(t.quaternion),this._component.controls.mouseButtons.wheel=ne.ACTION.DOLLY,this.matchOrthoDistanceEnabled?this._component.controls.distance=this.getDistance():this._component.controls.distance=this._previousDistance,await this._component.controls.zoomTo(1),e.updateProjectionMatrix(),this._component.controls.camera=e,this.camera=e,this.current="Perspective"}}class Ba extends Sa{projection;threeOrtho;threePersp;_userInputButtons={};_frustumSize=50;_navigationModes=new Map;_mode=null;previousSize=null;get mode(){if(!this._mode)throw new Error("Mode not found, camera not initialized");return this._mode}get hasMode(){return null!==this._mode}constructor(e){super(e),this.threePersp=this.three,this.threeOrtho=this.newOrthoCamera(),this.projection=new ka(this),this.onAspectUpdated.add(()=>{this.setOrthoPerspCameraAspect()}),this.projection.onChanged.add(e=>{this.three=e,this.updateAspect()}),this.worlds.onItemSet.add(()=>{this._navigationModes.clear(),this._navigationModes.set("Orbit",new za(this)),this._navigationModes.set("FirstPerson",new Ia(this)),this._navigationModes.set("Plan",new Da(this)),this._mode=this._navigationModes.get("Orbit"),this.mode.set(!0,{preventTargetAdjustment:!0}),this.currentWorld&&this.currentWorld.renderer&&(this.previousSize=this.currentWorld.renderer.getSize().clone())}),this.worlds.onItemDeleted.add(()=>{this._navigationModes.clear()})}dispose(){super.dispose(),this.threeOrtho.removeFromParent()}set(e){if(this.hasMode&&this.mode.id!==e){if(this.mode.set(!1),!this._navigationModes.has(e))throw new Error("The specified mode does not exist!");this._mode=this._navigationModes.get(e),this.mode.set(!0)}}async fit(e,t=1.5){if(!this.enabled)return;const i=Number.MAX_VALUE,n=Number.MIN_VALUE,r=new s.Vector3(i,i,i),o=new s.Vector3(n,n,n);for(const t of e){const e=(new s.Box3).setFromObject(t);e.min.x<r.x&&(r.x=e.min.x),e.min.y<r.y&&(r.y=e.min.y),e.min.z<r.z&&(r.z=e.min.z),e.max.x>o.x&&(o.x=e.max.x),e.max.y>o.y&&(o.y=e.max.y),e.max.z>o.z&&(o.z=e.max.z)}const a=new s.Box3(r,o),l=this.components.get(hr);if(l.initialized)for(const[,e]of l.list){const t=e.box;t.min.x<r.x&&(r.x=t.min.x),t.min.y<r.y&&(r.y=t.min.y),t.min.z<r.z&&(r.z=t.min.z),t.max.x>o.x&&(o.x=t.max.x),t.max.y>o.y&&(o.y=t.max.y),t.max.z>o.z&&(o.z=t.max.z)}const c=new s.Vector3;a.getSize(c);const h=new s.Vector3;a.getCenter(h);const u=Math.max(c.x,c.y,c.z)*t,d=new s.Sphere(h,u);await this.controls.fitToSphere(d,!0)}setUserInput(e){e?this.enableUserInput():this.disableUserInput()}addCustomNavigationMode(e){this._navigationModes.set(e.id,e)}disableUserInput(){this._userInputButtons.left=this.controls.mouseButtons.left,this._userInputButtons.right=this.controls.mouseButtons.right,this._userInputButtons.middle=this.controls.mouseButtons.middle,this._userInputButtons.wheel=this.controls.mouseButtons.wheel,this.controls.mouseButtons.left=0,this.controls.mouseButtons.right=0,this.controls.mouseButtons.middle=0,this.controls.mouseButtons.wheel=0}enableUserInput(){0!==Object.keys(this._userInputButtons).length&&(this.controls.mouseButtons.left=this._userInputButtons.left,this.controls.mouseButtons.right=this._userInputButtons.right,this.controls.mouseButtons.middle=this._userInputButtons.middle,this.controls.mouseButtons.wheel=this._userInputButtons.wheel)}newOrthoCamera(){const e=window.innerWidth/window.innerHeight;return new s.OrthographicCamera(this._frustumSize*e/-2,this._frustumSize*e/2,this._frustumSize/2,this._frustumSize/-2,.1,1e3)}setOrthoPerspCameraAspect(){if(!this.currentWorld||!this.currentWorld.renderer)return;if(!this.previousSize)return;const e=this.currentWorld.renderer.getSize();if(0===this.previousSize.x||0===this.previousSize.y)return void this.previousSize.copy(e);const t=this.threeOrtho.top,i=this.threeOrtho.right,n=t*(e.y/this.previousSize.y),s=i*(e.x/this.previousSize.x);this.threeOrtho.left=-s,this.threeOrtho.right=s,this.threeOrtho.top=n,this.threeOrtho.bottom=-n,this.threeOrtho.updateProjectionMatrix(),this.previousSize.copy(e)}}var Oa="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Va(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Na(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var La,Fa={exports:{}};const Ra=Va((La||(La=1,Fa.exports=function e(t,i,n){function s(o,a){if(!i[o]){if(!t[o]){if(!a&&Na)return Na(o);if(r)return r(o,!0);var l=new Error("Cannot find module '"+o+"'");throw l.code="MODULE_NOT_FOUND",l}var c=i[o]={exports:{}};t[o][0].call(c.exports,function(e){return s(t[o][1][e]||e)},c,c.exports,e,t,i,n)}return i[o].exports}for(var r=Na,o=0;o<n.length;o++)s(n[o]);return s}({1:[function(e,t,i){var n=e("./utils"),s=e("./support"),r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";i.encode=function(e){for(var t,i,s,o,a,l,c,h=[],u=0,d=e.length,p=d,f="string"!==n.getTypeOf(e);u<e.length;)p=d-u,s=f?(t=e[u++],i=u<d?e[u++]:0,u<d?e[u++]:0):(t=e.charCodeAt(u++),i=u<d?e.charCodeAt(u++):0,u<d?e.charCodeAt(u++):0),o=t>>2,a=(3&t)<<4|i>>4,l=1<p?(15&i)<<2|s>>6:64,c=2<p?63&s:64,h.push(r.charAt(o)+r.charAt(a)+r.charAt(l)+r.charAt(c));return h.join("")},i.decode=function(e){var t,i,n,o,a,l,c=0,h=0,u="data:";if(e.substr(0,u.length)===u)throw new Error("Invalid base64 input, it looks like a data url.");var d,p=3*(e=e.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(e.charAt(e.length-1)===r.charAt(64)&&p--,e.charAt(e.length-2)===r.charAt(64)&&p--,p%1!=0)throw new Error("Invalid base64 input, bad content length.");for(d=s.uint8array?new Uint8Array(0|p):new Array(0|p);c<e.length;)t=r.indexOf(e.charAt(c++))<<2|(o=r.indexOf(e.charAt(c++)))>>4,i=(15&o)<<4|(a=r.indexOf(e.charAt(c++)))>>2,n=(3&a)<<6|(l=r.indexOf(e.charAt(c++))),d[h++]=t,64!==a&&(d[h++]=i),64!==l&&(d[h++]=n);return d}},{"./support":30,"./utils":32}],2:[function(e,t,i){var n=e("./external"),s=e("./stream/DataWorker"),r=e("./stream/Crc32Probe"),o=e("./stream/DataLengthProbe");function a(e,t,i,n,s){this.compressedSize=e,this.uncompressedSize=t,this.crc32=i,this.compression=n,this.compressedContent=s}a.prototype={getContentWorker:function(){var e=new s(n.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new o("data_length")),t=this;return e.on("end",function(){if(this.streamInfo.data_length!==t.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),e},getCompressedWorker:function(){return new s(n.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},a.createWorkerFrom=function(e,t,i){return e.pipe(new r).pipe(new o("uncompressedSize")).pipe(t.compressWorker(i)).pipe(new o("compressedSize")).withStreamInfo("compression",t)},t.exports=a},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(e,t,i){var n=e("./stream/GenericWorker");i.STORE={magic:"\0\0",compressWorker:function(){return new n("STORE compression")},uncompressWorker:function(){return new n("STORE decompression")}},i.DEFLATE=e("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(e,t,i){var n=e("./utils"),s=function(){for(var e,t=[],i=0;i<256;i++){e=i;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t}();t.exports=function(e,t){return void 0!==e&&e.length?"string"!==n.getTypeOf(e)?function(e,t,i,n){var r=s,o=n+i;e^=-1;for(var a=n;a<o;a++)e=e>>>8^r[255&(e^t[a])];return-1^e}(0|t,e,e.length,0):function(e,t,i,n){var r=s,o=n+i;e^=-1;for(var a=n;a<o;a++)e=e>>>8^r[255&(e^t.charCodeAt(a))];return-1^e}(0|t,e,e.length,0):0}},{"./utils":32}],5:[function(e,t,i){i.base64=!1,i.binary=!1,i.dir=!1,i.createFolders=!0,i.date=null,i.compression=null,i.compressionOptions=null,i.comment=null,i.unixPermissions=null,i.dosPermissions=null},{}],6:[function(e,t,i){var n=null;n="undefined"!=typeof Promise?Promise:e("lie"),t.exports={Promise:n}},{lie:37}],7:[function(e,t,i){var n="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Uint32Array,s=e("pako"),r=e("./utils"),o=e("./stream/GenericWorker"),a=n?"uint8array":"array";function l(e,t){o.call(this,"FlateWorker/"+e),this._pako=null,this._pakoAction=e,this._pakoOptions=t,this.meta={}}i.magic="\b\0",r.inherits(l,o),l.prototype.processChunk=function(e){this.meta=e.meta,null===this._pako&&this._createPako(),this._pako.push(r.transformTo(a,e.data),!1)},l.prototype.flush=function(){o.prototype.flush.call(this),null===this._pako&&this._createPako(),this._pako.push([],!0)},l.prototype.cleanUp=function(){o.prototype.cleanUp.call(this),this._pako=null},l.prototype._createPako=function(){this._pako=new s[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var e=this;this._pako.onData=function(t){e.push({data:t,meta:e.meta})}},i.compressWorker=function(e){return new l("Deflate",e)},i.uncompressWorker=function(){return new l("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(e,t,i){function n(e,t){var i,n="";for(i=0;i<t;i++)n+=String.fromCharCode(255&e),e>>>=8;return n}function s(e,t,i,s,o,h){var u,d,p=e.file,f=e.compression,m=h!==a.utf8encode,g=r.transformTo("string",h(p.name)),w=r.transformTo("string",a.utf8encode(p.name)),y=p.comment,_=r.transformTo("string",h(y)),b=r.transformTo("string",a.utf8encode(y)),v=w.length!==p.name.length,x=b.length!==y.length,C="",S="",A="",T=p.dir,P=p.date,E={crc32:0,compressedSize:0,uncompressedSize:0};t&&!i||(E.crc32=e.crc32,E.compressedSize=e.compressedSize,E.uncompressedSize=e.uncompressedSize);var M=0;t&&(M|=8),m||!v&&!x||(M|=2048);var I,z,D,k=0,B=0;T&&(k|=16),"UNIX"===o?(B=798,k|=(I=p.unixPermissions,z=T,D=I,I||(D=z?16893:33204),(65535&D)<<16)):(B=20,k|=function(e){return 63&(e||0)}(p.dosPermissions)),u=P.getUTCHours(),u<<=6,u|=P.getUTCMinutes(),u<<=5,u|=P.getUTCSeconds()/2,d=P.getUTCFullYear()-1980,d<<=4,d|=P.getUTCMonth()+1,d<<=5,d|=P.getUTCDate(),v&&(S=n(1,1)+n(l(g),4)+w,C+="up"+n(S.length,2)+S),x&&(A=n(1,1)+n(l(_),4)+b,C+="uc"+n(A.length,2)+A);var O="";return O+="\n\0",O+=n(M,2),O+=f.magic,O+=n(u,2),O+=n(d,2),O+=n(E.crc32,4),O+=n(E.compressedSize,4),O+=n(E.uncompressedSize,4),O+=n(g.length,2),O+=n(C.length,2),{fileRecord:c.LOCAL_FILE_HEADER+O+g+C,dirRecord:c.CENTRAL_FILE_HEADER+n(B,2)+O+n(_.length,2)+"\0\0\0\0"+n(k,4)+n(s,4)+g+C+_}}var r=e("../utils"),o=e("../stream/GenericWorker"),a=e("../utf8"),l=e("../crc32"),c=e("../signature");function h(e,t,i,n){o.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=t,this.zipPlatform=i,this.encodeFileName=n,this.streamFiles=e,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}r.inherits(h,o),h.prototype.push=function(e){var t=e.meta.percent||0,i=this.entriesCount,n=this._sources.length;this.accumulate?this.contentBuffer.push(e):(this.bytesWritten+=e.data.length,o.prototype.push.call(this,{data:e.data,meta:{currentFile:this.currentFile,percent:i?(t+100*(i-n-1))/i:100}}))},h.prototype.openedSource=function(e){this.currentSourceOffset=this.bytesWritten,this.currentFile=e.file.name;var t=this.streamFiles&&!e.file.dir;if(t){var i=s(e,t,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:i.fileRecord,meta:{percent:0}})}else this.accumulate=!0},h.prototype.closedSource=function(e){this.accumulate=!1;var t,i=this.streamFiles&&!e.file.dir,r=s(e,i,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(r.dirRecord),i)this.push({data:(t=e,c.DATA_DESCRIPTOR+n(t.crc32,4)+n(t.compressedSize,4)+n(t.uncompressedSize,4)),meta:{percent:100}});else for(this.push({data:r.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},h.prototype.flush=function(){for(var e=this.bytesWritten,t=0;t<this.dirRecords.length;t++)this.push({data:this.dirRecords[t],meta:{percent:100}});var i,s,o,a,l,h,u=this.bytesWritten-e,d=(i=this.dirRecords.length,s=u,o=e,a=this.zipComment,l=this.encodeFileName,h=r.transformTo("string",l(a)),c.CENTRAL_DIRECTORY_END+"\0\0\0\0"+n(i,2)+n(i,2)+n(s,4)+n(o,4)+n(h.length,2)+h);this.push({data:d,meta:{percent:100}})},h.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},h.prototype.registerPrevious=function(e){this._sources.push(e);var t=this;return e.on("data",function(e){t.processChunk(e)}),e.on("end",function(){t.closedSource(t.previous.streamInfo),t._sources.length?t.prepareNextSource():t.end()}),e.on("error",function(e){t.error(e)}),this},h.prototype.resume=function(){return!!o.prototype.resume.call(this)&&(!this.previous&&this._sources.length?(this.prepareNextSource(),!0):this.previous||this._sources.length||this.generatedError?void 0:(this.end(),!0))},h.prototype.error=function(e){var t=this._sources;if(!o.prototype.error.call(this,e))return!1;for(var i=0;i<t.length;i++)try{t[i].error(e)}catch(e){}return!0},h.prototype.lock=function(){o.prototype.lock.call(this);for(var e=this._sources,t=0;t<e.length;t++)e[t].lock()},t.exports=h},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(e,t,i){var n=e("../compressions"),s=e("./ZipFileWorker");i.generateWorker=function(e,t,i){var r=new s(t.streamFiles,i,t.platform,t.encodeFileName),o=0;try{e.forEach(function(e,i){o++;var s=function(e,t){var i=e||t,s=n[i];if(!s)throw new Error(i+" is not a valid compression method !");return s}(i.options.compression,t.compression),a=i.options.compressionOptions||t.compressionOptions||{},l=i.dir,c=i.date;i._compressWorker(s,a).withStreamInfo("file",{name:e,dir:l,date:c,comment:i.comment||"",unixPermissions:i.unixPermissions,dosPermissions:i.dosPermissions}).pipe(r)}),r.entriesCount=o}catch(e){r.error(e)}return r}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(e,t,i){function n(){if(!(this instanceof n))return new n;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");this.files=Object.create(null),this.comment=null,this.root="",this.clone=function(){var e=new n;for(var t in this)"function"!=typeof this[t]&&(e[t]=this[t]);return e}}(n.prototype=e("./object")).loadAsync=e("./load"),n.support=e("./support"),n.defaults=e("./defaults"),n.version="3.10.1",n.loadAsync=function(e,t){return(new n).loadAsync(e,t)},n.external=e("./external"),t.exports=n},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(e,t,i){var n=e("./utils"),s=e("./external"),r=e("./utf8"),o=e("./zipEntries"),a=e("./stream/Crc32Probe"),l=e("./nodejsUtils");function c(e){return new s.Promise(function(t,i){var n=e.decompressed.getContentWorker().pipe(new a);n.on("error",function(e){i(e)}).on("end",function(){n.streamInfo.crc32!==e.decompressed.crc32?i(new Error("Corrupted zip : CRC32 mismatch")):t()}).resume()})}t.exports=function(e,t){var i=this;return t=n.extend(t||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:r.utf8decode}),l.isNode&&l.isStream(e)?s.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):n.prepareContent("the loaded zip file",e,!0,t.optimizedBinaryString,t.base64).then(function(e){var i=new o(t);return i.load(e),i}).then(function(e){var i=[s.Promise.resolve(e)],n=e.files;if(t.checkCRC32)for(var r=0;r<n.length;r++)i.push(c(n[r]));return s.Promise.all(i)}).then(function(e){for(var s=e.shift(),r=s.files,o=0;o<r.length;o++){var a=r[o],l=a.fileNameStr,c=n.resolve(a.fileNameStr);i.file(c,a.decompressed,{binary:!0,optimizedBinaryString:!0,date:a.date,dir:a.dir,comment:a.fileCommentStr.length?a.fileCommentStr:null,unixPermissions:a.unixPermissions,dosPermissions:a.dosPermissions,createFolders:t.createFolders}),a.dir||(i.file(c).unsafeOriginalName=l)}return s.zipComment.length&&(i.comment=s.zipComment),i})}},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(e,t,i){var n=e("../utils"),s=e("../stream/GenericWorker");function r(e,t){s.call(this,"Nodejs stream input adapter for "+e),this._upstreamEnded=!1,this._bindStream(t)}n.inherits(r,s),r.prototype._bindStream=function(e){var t=this;(this._stream=e).pause(),e.on("data",function(e){t.push({data:e,meta:{percent:0}})}).on("error",function(e){t.isPaused?this.generatedError=e:t.error(e)}).on("end",function(){t.isPaused?t._upstreamEnded=!0:t.end()})},r.prototype.pause=function(){return!!s.prototype.pause.call(this)&&(this._stream.pause(),!0)},r.prototype.resume=function(){return!!s.prototype.resume.call(this)&&(this._upstreamEnded?this.end():this._stream.resume(),!0)},t.exports=r},{"../stream/GenericWorker":28,"../utils":32}],13:[function(e,t,i){var n=e("readable-stream").Readable;function s(e,t,i){n.call(this,t),this._helper=e;var s=this;e.on("data",function(e,t){s.push(e)||s._helper.pause(),i&&i(t)}).on("error",function(e){s.emit("error",e)}).on("end",function(){s.push(null)})}e("../utils").inherits(s,n),s.prototype._read=function(){this._helper.resume()},t.exports=s},{"../utils":32,"readable-stream":16}],14:[function(e,t,i){t.exports={isNode:"undefined"!=typeof Buffer,newBufferFrom:function(e,t){if(Buffer.from&&Buffer.from!==Uint8Array.from)return Buffer.from(e,t);if("number"==typeof e)throw new Error('The "data" argument must not be a number');return new Buffer(e,t)},allocBuffer:function(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);return t.fill(0),t},isBuffer:function(e){return Buffer.isBuffer(e)},isStream:function(e){return e&&"function"==typeof e.on&&"function"==typeof e.pause&&"function"==typeof e.resume}}},{}],15:[function(e,t,i){function n(e,t,i){var n,s=r.getTypeOf(t),a=r.extend(i||{},l);a.date=a.date||new Date,null!==a.compression&&(a.compression=a.compression.toUpperCase()),"string"==typeof a.unixPermissions&&(a.unixPermissions=parseInt(a.unixPermissions,8)),a.unixPermissions&&16384&a.unixPermissions&&(a.dir=!0),a.dosPermissions&&16&a.dosPermissions&&(a.dir=!0),a.dir&&(e=m(e)),a.createFolders&&(n=f(e))&&g.call(this,n,!0);var u="string"===s&&!1===a.binary&&!1===a.base64;i&&void 0!==i.binary||(a.binary=!u),(t instanceof c&&0===t.uncompressedSize||a.dir||!t||0===t.length)&&(a.base64=!1,a.binary=!0,t="",a.compression="STORE",s="string");var w=null;w=t instanceof c||t instanceof o?t:d.isNode&&d.isStream(t)?new p(e,t):r.prepareContent(e,t,a.binary,a.optimizedBinaryString,a.base64);var y=new h(e,w,a);this.files[e]=y}var s=e("./utf8"),r=e("./utils"),o=e("./stream/GenericWorker"),a=e("./stream/StreamHelper"),l=e("./defaults"),c=e("./compressedObject"),h=e("./zipObject"),u=e("./generate"),d=e("./nodejsUtils"),p=e("./nodejs/NodejsStreamInputAdapter"),f=function(e){"/"===e.slice(-1)&&(e=e.substring(0,e.length-1));var t=e.lastIndexOf("/");return 0<t?e.substring(0,t):""},m=function(e){return"/"!==e.slice(-1)&&(e+="/"),e},g=function(e,t){return t=void 0!==t?t:l.createFolders,e=m(e),this.files[e]||n.call(this,e,null,{dir:!0,createFolders:t}),this.files[e]};function w(e){return"[object RegExp]"===Object.prototype.toString.call(e)}var y={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(e){var t,i,n;for(t in this.files)n=this.files[t],(i=t.slice(this.root.length,t.length))&&t.slice(0,this.root.length)===this.root&&e(i,n)},filter:function(e){var t=[];return this.forEach(function(i,n){e(i,n)&&t.push(n)}),t},file:function(e,t,i){if(1!==arguments.length)return e=this.root+e,n.call(this,e,t,i),this;if(w(e)){var s=e;return this.filter(function(e,t){return!t.dir&&s.test(e)})}var r=this.files[this.root+e];return r&&!r.dir?r:null},folder:function(e){if(!e)return this;if(w(e))return this.filter(function(t,i){return i.dir&&e.test(t)});var t=this.root+e,i=g.call(this,t),n=this.clone();return n.root=i.name,n},remove:function(e){e=this.root+e;var t=this.files[e];if(t||("/"!==e.slice(-1)&&(e+="/"),t=this.files[e]),t&&!t.dir)delete this.files[e];else for(var i=this.filter(function(t,i){return i.name.slice(0,e.length)===e}),n=0;n<i.length;n++)delete this.files[i[n].name];return this},generate:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(e){var t,i={};try{if((i=r.extend(e||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:s.utf8encode})).type=i.type.toLowerCase(),i.compression=i.compression.toUpperCase(),"binarystring"===i.type&&(i.type="string"),!i.type)throw new Error("No output type specified.");r.checkSupport(i.type),"darwin"!==i.platform&&"freebsd"!==i.platform&&"linux"!==i.platform&&"sunos"!==i.platform||(i.platform="UNIX"),"win32"===i.platform&&(i.platform="DOS");var n=i.comment||this.comment||"";t=u.generateWorker(this,i,n)}catch(e){(t=new o("error")).error(e)}return new a(t,i.type||"string",i.mimeType)},generateAsync:function(e,t){return this.generateInternalStream(e).accumulate(t)},generateNodeStream:function(e,t){return(e=e||{}).type||(e.type="nodebuffer"),this.generateInternalStream(e).toNodejsStream(t)}};t.exports=y},{"./compressedObject":2,"./defaults":5,"./generate":9,"./nodejs/NodejsStreamInputAdapter":12,"./nodejsUtils":14,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31,"./utils":32,"./zipObject":35}],16:[function(e,t,i){t.exports=e("stream")},{stream:void 0}],17:[function(e,t,i){var n=e("./DataReader");function s(e){n.call(this,e);for(var t=0;t<this.data.length;t++)e[t]=255&e[t]}e("../utils").inherits(s,n),s.prototype.byteAt=function(e){return this.data[this.zero+e]},s.prototype.lastIndexOfSignature=function(e){for(var t=e.charCodeAt(0),i=e.charCodeAt(1),n=e.charCodeAt(2),s=e.charCodeAt(3),r=this.length-4;0<=r;--r)if(this.data[r]===t&&this.data[r+1]===i&&this.data[r+2]===n&&this.data[r+3]===s)return r-this.zero;return-1},s.prototype.readAndCheckSignature=function(e){var t=e.charCodeAt(0),i=e.charCodeAt(1),n=e.charCodeAt(2),s=e.charCodeAt(3),r=this.readData(4);return t===r[0]&&i===r[1]&&n===r[2]&&s===r[3]},s.prototype.readData=function(e){if(this.checkOffset(e),0===e)return[];var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=s},{"../utils":32,"./DataReader":18}],18:[function(e,t,i){var n=e("../utils");function s(e){this.data=e,this.length=e.length,this.index=0,this.zero=0}s.prototype={checkOffset:function(e){this.checkIndex(this.index+e)},checkIndex:function(e){if(this.length<this.zero+e||e<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+e+"). Corrupted zip ?")},setIndex:function(e){this.checkIndex(e),this.index=e},skip:function(e){this.setIndex(this.index+e)},byteAt:function(){},readInt:function(e){var t,i=0;for(this.checkOffset(e),t=this.index+e-1;t>=this.index;t--)i=(i<<8)+this.byteAt(t);return this.index+=e,i},readString:function(e){return n.transformTo("string",this.readData(e))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var e=this.readInt(4);return new Date(Date.UTC(1980+(e>>25&127),(e>>21&15)-1,e>>16&31,e>>11&31,e>>5&63,(31&e)<<1))}},t.exports=s},{"../utils":32}],19:[function(e,t,i){var n=e("./Uint8ArrayReader");function s(e){n.call(this,e)}e("../utils").inherits(s,n),s.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=s},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(e,t,i){var n=e("./DataReader");function s(e){n.call(this,e)}e("../utils").inherits(s,n),s.prototype.byteAt=function(e){return this.data.charCodeAt(this.zero+e)},s.prototype.lastIndexOfSignature=function(e){return this.data.lastIndexOf(e)-this.zero},s.prototype.readAndCheckSignature=function(e){return e===this.readData(4)},s.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=s},{"../utils":32,"./DataReader":18}],21:[function(e,t,i){var n=e("./ArrayReader");function s(e){n.call(this,e)}e("../utils").inherits(s,n),s.prototype.readData=function(e){if(this.checkOffset(e),0===e)return new Uint8Array(0);var t=this.data.subarray(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=s},{"../utils":32,"./ArrayReader":17}],22:[function(e,t,i){var n=e("../utils"),s=e("../support"),r=e("./ArrayReader"),o=e("./StringReader"),a=e("./NodeBufferReader"),l=e("./Uint8ArrayReader");t.exports=function(e){var t=n.getTypeOf(e);return n.checkSupport(t),"string"!==t||s.uint8array?"nodebuffer"===t?new a(e):s.uint8array?new l(n.transformTo("uint8array",e)):new r(n.transformTo("array",e)):new o(e)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(e,t,i){i.LOCAL_FILE_HEADER="PK",i.CENTRAL_FILE_HEADER="PK",i.CENTRAL_DIRECTORY_END="PK",i.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK",i.ZIP64_CENTRAL_DIRECTORY_END="PK",i.DATA_DESCRIPTOR="PK\b"},{}],24:[function(e,t,i){var n=e("./GenericWorker"),s=e("../utils");function r(e){n.call(this,"ConvertWorker to "+e),this.destType=e}s.inherits(r,n),r.prototype.processChunk=function(e){this.push({data:s.transformTo(this.destType,e.data),meta:e.meta})},t.exports=r},{"../utils":32,"./GenericWorker":28}],25:[function(e,t,i){var n=e("./GenericWorker"),s=e("../crc32");function r(){n.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}e("../utils").inherits(r,n),r.prototype.processChunk=function(e){this.streamInfo.crc32=s(e.data,this.streamInfo.crc32||0),this.push(e)},t.exports=r},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(e,t,i){var n=e("../utils"),s=e("./GenericWorker");function r(e){s.call(this,"DataLengthProbe for "+e),this.propName=e,this.withStreamInfo(e,0)}n.inherits(r,s),r.prototype.processChunk=function(e){if(e){var t=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=t+e.data.length}s.prototype.processChunk.call(this,e)},t.exports=r},{"../utils":32,"./GenericWorker":28}],27:[function(e,t,i){var n=e("../utils"),s=e("./GenericWorker");function r(e){s.call(this,"DataWorker");var t=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,e.then(function(e){t.dataIsReady=!0,t.data=e,t.max=e&&e.length||0,t.type=n.getTypeOf(e),t.isPaused||t._tickAndRepeat()},function(e){t.error(e)})}n.inherits(r,s),r.prototype.cleanUp=function(){s.prototype.cleanUp.call(this),this.data=null},r.prototype.resume=function(){return!!s.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,n.delay(this._tickAndRepeat,[],this)),!0)},r.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(n.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},r.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var e=null,t=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":e=this.data.substring(this.index,t);break;case"uint8array":e=this.data.subarray(this.index,t);break;case"array":case"nodebuffer":e=this.data.slice(this.index,t)}return this.index=t,this.push({data:e,meta:{percent:this.max?this.index/this.max*100:0}})},t.exports=r},{"../utils":32,"./GenericWorker":28}],28:[function(e,t,i){function n(e){this.name=e||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}n.prototype={push:function(e){this.emit("data",e)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(e){this.emit("error",e)}return!0},error:function(e){return!this.isFinished&&(this.isPaused?this.generatedError=e:(this.isFinished=!0,this.emit("error",e),this.previous&&this.previous.error(e),this.cleanUp()),!0)},on:function(e,t){return this._listeners[e].push(t),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(e,t){if(this._listeners[e])for(var i=0;i<this._listeners[e].length;i++)this._listeners[e][i].call(this,t)},pipe:function(e){return e.registerPrevious(this)},registerPrevious:function(e){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=e.streamInfo,this.mergeStreamInfo(),this.previous=e;var t=this;return e.on("data",function(e){t.processChunk(e)}),e.on("end",function(){t.end()}),e.on("error",function(e){t.error(e)}),this},pause:function(){return!this.isPaused&&!this.isFinished&&(this.isPaused=!0,this.previous&&this.previous.pause(),!0)},resume:function(){if(!this.isPaused||this.isFinished)return!1;var e=this.isPaused=!1;return this.generatedError&&(this.error(this.generatedError),e=!0),this.previous&&this.previous.resume(),!e},flush:function(){},processChunk:function(e){this.push(e)},withStreamInfo:function(e,t){return this.extraStreamInfo[e]=t,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var e in this.extraStreamInfo)Object.prototype.hasOwnProperty.call(this.extraStreamInfo,e)&&(this.streamInfo[e]=this.extraStreamInfo[e])},lock:function(){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.isLocked=!0,this.previous&&this.previous.lock()},toString:function(){var e="Worker "+this.name;return this.previous?this.previous+" -> "+e:e}},t.exports=n},{}],29:[function(e,t,i){var n=e("../utils"),s=e("./ConvertWorker"),r=e("./GenericWorker"),o=e("../base64"),a=e("../support"),l=e("../external"),c=null;if(a.nodestream)try{c=e("../nodejs/NodejsStreamOutputAdapter")}catch(e){}function h(e,t){return new l.Promise(function(i,s){var r=[],a=e._internalType,l=e._outputType,c=e._mimeType;e.on("data",function(e,i){r.push(e),t&&t(i)}).on("error",function(e){r=[],s(e)}).on("end",function(){try{var e=function(e,t,i){switch(e){case"blob":return n.newBlob(n.transformTo("arraybuffer",t),i);case"base64":return o.encode(t);default:return n.transformTo(e,t)}}(l,function(e,t){var i,n=0,s=null,r=0;for(i=0;i<t.length;i++)r+=t[i].length;switch(e){case"string":return t.join("");case"array":return Array.prototype.concat.apply([],t);case"uint8array":for(s=new Uint8Array(r),i=0;i<t.length;i++)s.set(t[i],n),n+=t[i].length;return s;case"nodebuffer":return Buffer.concat(t);default:throw new Error("concat : unsupported type '"+e+"'")}}(a,r),c);i(e)}catch(e){s(e)}r=[]}).resume()})}function u(e,t,i){var o=t;switch(t){case"blob":case"arraybuffer":o="uint8array";break;case"base64":o="string"}try{this._internalType=o,this._outputType=t,this._mimeType=i,n.checkSupport(o),this._worker=e.pipe(new s(o)),e.lock()}catch(e){this._worker=new r("error"),this._worker.error(e)}}u.prototype={accumulate:function(e){return h(this,e)},on:function(e,t){var i=this;return"data"===e?this._worker.on(e,function(e){t.call(i,e.data,e.meta)}):this._worker.on(e,function(){n.delay(t,arguments,i)}),this},resume:function(){return n.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(e){if(n.checkSupport("nodestream"),"nodebuffer"!==this._outputType)throw new Error(this._outputType+" is not supported by this method");return new c(this,{objectMode:"nodebuffer"!==this._outputType},e)}},t.exports=u},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(e,t,i){if(i.base64=!0,i.array=!0,i.string=!0,i.arraybuffer="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array,i.nodebuffer="undefined"!=typeof Buffer,i.uint8array="undefined"!=typeof Uint8Array,"undefined"==typeof ArrayBuffer)i.blob=!1;else{var n=new ArrayBuffer(0);try{i.blob=0===new Blob([n],{type:"application/zip"}).size}catch(e){try{var s=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);s.append(n),i.blob=0===s.getBlob("application/zip").size}catch(e){i.blob=!1}}}try{i.nodestream=!!e("readable-stream").Readable}catch(e){i.nodestream=!1}},{"readable-stream":16}],31:[function(e,t,i){for(var n=e("./utils"),s=e("./support"),r=e("./nodejsUtils"),o=e("./stream/GenericWorker"),a=new Array(256),l=0;l<256;l++)a[l]=252<=l?6:248<=l?5:240<=l?4:224<=l?3:192<=l?2:1;function c(){o.call(this,"utf-8 decode"),this.leftOver=null}function h(){o.call(this,"utf-8 encode")}a[254]=a[254]=1,i.utf8encode=function(e){return s.nodebuffer?r.newBufferFrom(e,"utf-8"):function(e){var t,i,n,r,o,a=e.length,l=0;for(r=0;r<a;r++)55296==(64512&(i=e.charCodeAt(r)))&&r+1<a&&56320==(64512&(n=e.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(n-56320),r++),l+=i<128?1:i<2048?2:i<65536?3:4;for(t=s.uint8array?new Uint8Array(l):new Array(l),r=o=0;o<l;r++)55296==(64512&(i=e.charCodeAt(r)))&&r+1<a&&56320==(64512&(n=e.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(n-56320),r++),i<128?t[o++]=i:(i<2048?t[o++]=192|i>>>6:(i<65536?t[o++]=224|i>>>12:(t[o++]=240|i>>>18,t[o++]=128|i>>>12&63),t[o++]=128|i>>>6&63),t[o++]=128|63&i);return t}(e)},i.utf8decode=function(e){return s.nodebuffer?n.transformTo("nodebuffer",e).toString("utf-8"):function(e){var t,i,s,r,o=e.length,l=new Array(2*o);for(t=i=0;t<o;)if((s=e[t++])<128)l[i++]=s;else if(4<(r=a[s]))l[i++]=65533,t+=r-1;else{for(s&=2===r?31:3===r?15:7;1<r&&t<o;)s=s<<6|63&e[t++],r--;1<r?l[i++]=65533:s<65536?l[i++]=s:(s-=65536,l[i++]=55296|s>>10&1023,l[i++]=56320|1023&s)}return l.length!==i&&(l.subarray?l=l.subarray(0,i):l.length=i),n.applyFromCharCode(l)}(e=n.transformTo(s.uint8array?"uint8array":"array",e))},n.inherits(c,o),c.prototype.processChunk=function(e){var t=n.transformTo(s.uint8array?"uint8array":"array",e.data);if(this.leftOver&&this.leftOver.length){if(s.uint8array){var r=t;(t=new Uint8Array(r.length+this.leftOver.length)).set(this.leftOver,0),t.set(r,this.leftOver.length)}else t=this.leftOver.concat(t);this.leftOver=null}var o=function(e,t){var i;for((t=t||e.length)>e.length&&(t=e.length),i=t-1;0<=i&&128==(192&e[i]);)i--;return i<0||0===i?t:i+a[e[i]]>t?i:t}(t),l=t;o!==t.length&&(s.uint8array?(l=t.subarray(0,o),this.leftOver=t.subarray(o,t.length)):(l=t.slice(0,o),this.leftOver=t.slice(o,t.length))),this.push({data:i.utf8decode(l),meta:e.meta})},c.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:i.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},i.Utf8DecodeWorker=c,n.inherits(h,o),h.prototype.processChunk=function(e){this.push({data:i.utf8encode(e.data),meta:e.meta})},i.Utf8EncodeWorker=h},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(e,t,i){var n=e("./support"),s=e("./base64"),r=e("./nodejsUtils"),o=e("./external");function a(e){return e}function l(e,t){for(var i=0;i<e.length;++i)t[i]=255&e.charCodeAt(i);return t}e("setimmediate"),i.newBlob=function(e,t){i.checkSupport("blob");try{return new Blob([e],{type:t})}catch(i){try{var n=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return n.append(e),n.getBlob(t)}catch(e){throw new Error("Bug : can't construct the Blob.")}}};var c={stringifyByChunk:function(e,t,i){var n=[],s=0,r=e.length;if(r<=i)return String.fromCharCode.apply(null,e);for(;s<r;)"array"===t||"nodebuffer"===t?n.push(String.fromCharCode.apply(null,e.slice(s,Math.min(s+i,r)))):n.push(String.fromCharCode.apply(null,e.subarray(s,Math.min(s+i,r)))),s+=i;return n.join("")},stringifyByChar:function(e){for(var t="",i=0;i<e.length;i++)t+=String.fromCharCode(e[i]);return t},applyCanBeUsed:{uint8array:function(){try{return n.uint8array&&1===String.fromCharCode.apply(null,new Uint8Array(1)).length}catch(e){return!1}}(),nodebuffer:function(){try{return n.nodebuffer&&1===String.fromCharCode.apply(null,r.allocBuffer(1)).length}catch(e){return!1}}()}};function h(e){var t=65536,n=i.getTypeOf(e),s=!0;if("uint8array"===n?s=c.applyCanBeUsed.uint8array:"nodebuffer"===n&&(s=c.applyCanBeUsed.nodebuffer),s)for(;1<t;)try{return c.stringifyByChunk(e,n,t)}catch(e){t=Math.floor(t/2)}return c.stringifyByChar(e)}function u(e,t){for(var i=0;i<e.length;i++)t[i]=e[i];return t}i.applyFromCharCode=h;var d={};d.string={string:a,array:function(e){return l(e,new Array(e.length))},arraybuffer:function(e){return d.string.uint8array(e).buffer},uint8array:function(e){return l(e,new Uint8Array(e.length))},nodebuffer:function(e){return l(e,r.allocBuffer(e.length))}},d.array={string:h,array:a,arraybuffer:function(e){return new Uint8Array(e).buffer},uint8array:function(e){return new Uint8Array(e)},nodebuffer:function(e){return r.newBufferFrom(e)}},d.arraybuffer={string:function(e){return h(new Uint8Array(e))},array:function(e){return u(new Uint8Array(e),new Array(e.byteLength))},arraybuffer:a,uint8array:function(e){return new Uint8Array(e)},nodebuffer:function(e){return r.newBufferFrom(new Uint8Array(e))}},d.uint8array={string:h,array:function(e){return u(e,new Array(e.length))},arraybuffer:function(e){return e.buffer},uint8array:a,nodebuffer:function(e){return r.newBufferFrom(e)}},d.nodebuffer={string:h,array:function(e){return u(e,new Array(e.length))},arraybuffer:function(e){return d.nodebuffer.uint8array(e).buffer},uint8array:function(e){return u(e,new Uint8Array(e.length))},nodebuffer:a},i.transformTo=function(e,t){if(t=t||"",!e)return t;i.checkSupport(e);var n=i.getTypeOf(t);return d[n][e](t)},i.resolve=function(e){for(var t=e.split("/"),i=[],n=0;n<t.length;n++){var s=t[n];"."===s||""===s&&0!==n&&n!==t.length-1||(".."===s?i.pop():i.push(s))}return i.join("/")},i.getTypeOf=function(e){return"string"==typeof e?"string":"[object Array]"===Object.prototype.toString.call(e)?"array":n.nodebuffer&&r.isBuffer(e)?"nodebuffer":n.uint8array&&e instanceof Uint8Array?"uint8array":n.arraybuffer&&e instanceof ArrayBuffer?"arraybuffer":void 0},i.checkSupport=function(e){if(!n[e.toLowerCase()])throw new Error(e+" is not supported by this platform")},i.MAX_VALUE_16BITS=65535,i.MAX_VALUE_32BITS=-1,i.pretty=function(e){var t,i,n="";for(i=0;i<(e||"").length;i++)n+="\\x"+((t=e.charCodeAt(i))<16?"0":"")+t.toString(16).toUpperCase();return n},i.delay=function(e,t,i){setImmediate(function(){e.apply(i||null,t||[])})},i.inherits=function(e,t){function i(){}i.prototype=t.prototype,e.prototype=new i},i.extend=function(){var e,t,i={};for(e=0;e<arguments.length;e++)for(t in arguments[e])Object.prototype.hasOwnProperty.call(arguments[e],t)&&void 0===i[t]&&(i[t]=arguments[e][t]);return i},i.prepareContent=function(e,t,r,a,c){return o.Promise.resolve(t).then(function(e){return n.blob&&(e instanceof Blob||-1!==["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(e)))&&"undefined"!=typeof FileReader?new o.Promise(function(t,i){var n=new FileReader;n.onload=function(e){t(e.target.result)},n.onerror=function(e){i(e.target.error)},n.readAsArrayBuffer(e)}):e}).then(function(t){var h,u=i.getTypeOf(t);return u?("arraybuffer"===u?t=i.transformTo("uint8array",t):"string"===u&&(c?t=s.decode(t):r&&!0!==a&&(t=l(h=t,n.uint8array?new Uint8Array(h.length):new Array(h.length)))),t):o.Promise.reject(new Error("Can't read the data of '"+e+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))})}},{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,setimmediate:54}],33:[function(e,t,i){var n=e("./reader/readerFor"),s=e("./utils"),r=e("./signature"),o=e("./zipEntry"),a=e("./support");function l(e){this.files=[],this.loadOptions=e}l.prototype={checkSignature:function(e){if(!this.reader.readAndCheckSignature(e)){this.reader.index-=4;var t=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+s.pretty(t)+", expected "+s.pretty(e)+")")}},isSignature:function(e,t){var i=this.reader.index;this.reader.setIndex(e);var n=this.reader.readString(4)===t;return this.reader.setIndex(i),n},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2);var e=this.reader.readData(this.zipCommentLength),t=a.uint8array?"uint8array":"array",i=s.transformTo(t,e);this.zipComment=this.loadOptions.decodeFileName(i)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.reader.skip(4),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var e,t,i,n=this.zip64EndOfCentralSize-44;0<n;)e=this.reader.readInt(2),t=this.reader.readInt(4),i=this.reader.readData(t),this.zip64ExtensibleData[e]={id:e,length:t,value:i}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),1<this.disksCount)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var e,t;for(e=0;e<this.files.length;e++)t=this.files[e],this.reader.setIndex(t.localHeaderOffset),this.checkSignature(r.LOCAL_FILE_HEADER),t.readLocalPart(this.reader),t.handleUTF8(),t.processAttributes()},readCentralDir:function(){var e;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(r.CENTRAL_FILE_HEADER);)(e=new o({zip64:this.zip64},this.loadOptions)).readCentralPart(this.reader),this.files.push(e);if(this.centralDirRecords!==this.files.length&&0!==this.centralDirRecords&&0===this.files.length)throw new Error("Corrupted zip or bug: expected "+this.centralDirRecords+" records in central dir, got "+this.files.length)},readEndOfCentral:function(){var e=this.reader.lastIndexOfSignature(r.CENTRAL_DIRECTORY_END);if(e<0)throw this.isSignature(0,r.LOCAL_FILE_HEADER)?new Error("Corrupted zip: can't find end of central directory"):new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html");this.reader.setIndex(e);var t=e;if(this.checkSignature(r.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===s.MAX_VALUE_16BITS||this.diskWithCentralDirStart===s.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===s.MAX_VALUE_16BITS||this.centralDirRecords===s.MAX_VALUE_16BITS||this.centralDirSize===s.MAX_VALUE_32BITS||this.centralDirOffset===s.MAX_VALUE_32BITS){if(this.zip64=!0,(e=this.reader.lastIndexOfSignature(r.ZIP64_CENTRAL_DIRECTORY_LOCATOR))<0)throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");if(this.reader.setIndex(e),this.checkSignature(r.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),!this.isSignature(this.relativeOffsetEndOfZip64CentralDir,r.ZIP64_CENTRAL_DIRECTORY_END)&&(this.relativeOffsetEndOfZip64CentralDir=this.reader.lastIndexOfSignature(r.ZIP64_CENTRAL_DIRECTORY_END),this.relativeOffsetEndOfZip64CentralDir<0))throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir),this.checkSignature(r.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral()}var i=this.centralDirOffset+this.centralDirSize;this.zip64&&(i+=20,i+=12+this.zip64EndOfCentralSize);var n=t-i;if(0<n)this.isSignature(t,r.CENTRAL_FILE_HEADER)||(this.reader.zero=n);else if(n<0)throw new Error("Corrupted zip: missing "+Math.abs(n)+" bytes.")},prepareReader:function(e){this.reader=n(e)},load:function(e){this.prepareReader(e),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}},t.exports=l},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(e,t,i){var n=e("./reader/readerFor"),s=e("./utils"),r=e("./compressedObject"),o=e("./crc32"),a=e("./utf8"),l=e("./compressions"),c=e("./support");function h(e,t){this.options=e,this.loadOptions=t}h.prototype={isEncrypted:function(){return!(1&~this.bitFlag)},useUTF8:function(){return!(2048&~this.bitFlag)},readLocalPart:function(e){var t,i;if(e.skip(22),this.fileNameLength=e.readInt(2),i=e.readInt(2),this.fileName=e.readData(this.fileNameLength),e.skip(i),-1===this.compressedSize||-1===this.uncompressedSize)throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");if(null===(t=function(e){for(var t in l)if(Object.prototype.hasOwnProperty.call(l,t)&&l[t].magic===e)return l[t];return null}(this.compressionMethod)))throw new Error("Corrupted zip : compression "+s.pretty(this.compressionMethod)+" unknown (inner file : "+s.transformTo("string",this.fileName)+")");this.decompressed=new r(this.compressedSize,this.uncompressedSize,this.crc32,t,e.readData(this.compressedSize))},readCentralPart:function(e){this.versionMadeBy=e.readInt(2),e.skip(2),this.bitFlag=e.readInt(2),this.compressionMethod=e.readString(2),this.date=e.readDate(),this.crc32=e.readInt(4),this.compressedSize=e.readInt(4),this.uncompressedSize=e.readInt(4);var t=e.readInt(2);if(this.extraFieldsLength=e.readInt(2),this.fileCommentLength=e.readInt(2),this.diskNumberStart=e.readInt(2),this.internalFileAttributes=e.readInt(2),this.externalFileAttributes=e.readInt(4),this.localHeaderOffset=e.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");e.skip(t),this.readExtraFields(e),this.parseZIP64ExtraField(e),this.fileComment=e.readData(this.fileCommentLength)},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var e=this.versionMadeBy>>8;this.dir=!!(16&this.externalFileAttributes),0==e&&(this.dosPermissions=63&this.externalFileAttributes),3==e&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||"/"!==this.fileNameStr.slice(-1)||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var e=n(this.extraFields[1].value);this.uncompressedSize===s.MAX_VALUE_32BITS&&(this.uncompressedSize=e.readInt(8)),this.compressedSize===s.MAX_VALUE_32BITS&&(this.compressedSize=e.readInt(8)),this.localHeaderOffset===s.MAX_VALUE_32BITS&&(this.localHeaderOffset=e.readInt(8)),this.diskNumberStart===s.MAX_VALUE_32BITS&&(this.diskNumberStart=e.readInt(4))}},readExtraFields:function(e){var t,i,n,s=e.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});e.index+4<s;)t=e.readInt(2),i=e.readInt(2),n=e.readData(i),this.extraFields[t]={id:t,length:i,value:n};e.setIndex(s)},handleUTF8:function(){var e=c.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=a.utf8decode(this.fileName),this.fileCommentStr=a.utf8decode(this.fileComment);else{var t=this.findExtraFieldUnicodePath();if(null!==t)this.fileNameStr=t;else{var i=s.transformTo(e,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(i)}var n=this.findExtraFieldUnicodeComment();if(null!==n)this.fileCommentStr=n;else{var r=s.transformTo(e,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(r)}}},findExtraFieldUnicodePath:function(){var e=this.extraFields[28789];if(e){var t=n(e.value);return 1!==t.readInt(1)||o(this.fileName)!==t.readInt(4)?null:a.utf8decode(t.readData(e.length-5))}return null},findExtraFieldUnicodeComment:function(){var e=this.extraFields[25461];if(e){var t=n(e.value);return 1!==t.readInt(1)||o(this.fileComment)!==t.readInt(4)?null:a.utf8decode(t.readData(e.length-5))}return null}},t.exports=h},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(e,t,i){function n(e,t,i){this.name=e,this.dir=i.dir,this.date=i.date,this.comment=i.comment,this.unixPermissions=i.unixPermissions,this.dosPermissions=i.dosPermissions,this._data=t,this._dataBinary=i.binary,this.options={compression:i.compression,compressionOptions:i.compressionOptions}}var s=e("./stream/StreamHelper"),r=e("./stream/DataWorker"),o=e("./utf8"),a=e("./compressedObject"),l=e("./stream/GenericWorker");n.prototype={internalStream:function(e){var t=null,i="string";try{if(!e)throw new Error("No output type specified.");var n="string"===(i=e.toLowerCase())||"text"===i;"binarystring"!==i&&"text"!==i||(i="string"),t=this._decompressWorker();var r=!this._dataBinary;r&&!n&&(t=t.pipe(new o.Utf8EncodeWorker)),!r&&n&&(t=t.pipe(new o.Utf8DecodeWorker))}catch(e){(t=new l("error")).error(e)}return new s(t,i,"")},async:function(e,t){return this.internalStream(e).accumulate(t)},nodeStream:function(e,t){return this.internalStream(e||"nodebuffer").toNodejsStream(t)},_compressWorker:function(e,t){if(this._data instanceof a&&this._data.compression.magic===e.magic)return this._data.getCompressedWorker();var i=this._decompressWorker();return this._dataBinary||(i=i.pipe(new o.Utf8EncodeWorker)),a.createWorkerFrom(i,e,t)},_decompressWorker:function(){return this._data instanceof a?this._data.getContentWorker():this._data instanceof l?this._data:new r(this._data)}};for(var c=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],h=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},u=0;u<c.length;u++)n.prototype[c[u]]=h;t.exports=n},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(e,t,i){(function(e){var i,n,s=e.MutationObserver||e.WebKitMutationObserver;if(s){var r=0,o=new s(h),a=e.document.createTextNode("");o.observe(a,{characterData:!0}),i=function(){a.data=r=++r%2}}else if(e.setImmediate||void 0===e.MessageChannel)i="document"in e&&"onreadystatechange"in e.document.createElement("script")?function(){var t=e.document.createElement("script");t.onreadystatechange=function(){h(),t.onreadystatechange=null,t.parentNode.removeChild(t),t=null},e.document.documentElement.appendChild(t)}:function(){setTimeout(h,0)};else{var l=new e.MessageChannel;l.port1.onmessage=h,i=function(){l.port2.postMessage(0)}}var c=[];function h(){var e,t;n=!0;for(var i=c.length;i;){for(t=c,c=[],e=-1;++e<i;)t[e]();i=c.length}n=!1}t.exports=function(e){1!==c.push(e)||n||i()}}).call(this,void 0!==Oa?Oa:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],37:[function(e,t,i){var n=e("immediate");function s(){}var r={},o=["REJECTED"],a=["FULFILLED"],l=["PENDING"];function c(e){if("function"!=typeof e)throw new TypeError("resolver must be a function");this.state=l,this.queue=[],this.outcome=void 0,e!==s&&p(this,e)}function h(e,t,i){this.promise=e,"function"==typeof t&&(this.onFulfilled=t,this.callFulfilled=this.otherCallFulfilled),"function"==typeof i&&(this.onRejected=i,this.callRejected=this.otherCallRejected)}function u(e,t,i){n(function(){var n;try{n=t(i)}catch(t){return r.reject(e,t)}n===e?r.reject(e,new TypeError("Cannot resolve promise with itself")):r.resolve(e,n)})}function d(e){var t=e&&e.then;if(e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof t)return function(){t.apply(e,arguments)}}function p(e,t){var i=!1;function n(t){i||(i=!0,r.reject(e,t))}function s(t){i||(i=!0,r.resolve(e,t))}var o=f(function(){t(s,n)});"error"===o.status&&n(o.value)}function f(e,t){var i={};try{i.value=e(t),i.status="success"}catch(e){i.status="error",i.value=e}return i}(t.exports=c).prototype.finally=function(e){if("function"!=typeof e)return this;var t=this.constructor;return this.then(function(i){return t.resolve(e()).then(function(){return i})},function(i){return t.resolve(e()).then(function(){throw i})})},c.prototype.catch=function(e){return this.then(null,e)},c.prototype.then=function(e,t){if("function"!=typeof e&&this.state===a||"function"!=typeof t&&this.state===o)return this;var i=new this.constructor(s);return this.state!==l?u(i,this.state===a?e:t,this.outcome):this.queue.push(new h(i,e,t)),i},h.prototype.callFulfilled=function(e){r.resolve(this.promise,e)},h.prototype.otherCallFulfilled=function(e){u(this.promise,this.onFulfilled,e)},h.prototype.callRejected=function(e){r.reject(this.promise,e)},h.prototype.otherCallRejected=function(e){u(this.promise,this.onRejected,e)},r.resolve=function(e,t){var i=f(d,t);if("error"===i.status)return r.reject(e,i.value);var n=i.value;if(n)p(e,n);else{e.state=a,e.outcome=t;for(var s=-1,o=e.queue.length;++s<o;)e.queue[s].callFulfilled(t)}return e},r.reject=function(e,t){e.state=o,e.outcome=t;for(var i=-1,n=e.queue.length;++i<n;)e.queue[i].callRejected(t);return e},c.resolve=function(e){return e instanceof this?e:r.resolve(new this(s),e)},c.reject=function(e){var t=new this(s);return r.reject(t,e)},c.all=function(e){var t=this;if("[object Array]"!==Object.prototype.toString.call(e))return this.reject(new TypeError("must be an array"));var i=e.length,n=!1;if(!i)return this.resolve([]);for(var o=new Array(i),a=0,l=-1,c=new this(s);++l<i;)h(e[l],l);return c;function h(e,s){t.resolve(e).then(function(e){o[s]=e,++a!==i||n||(n=!0,r.resolve(c,o))},function(e){n||(n=!0,r.reject(c,e))})}},c.race=function(e){var t=this;if("[object Array]"!==Object.prototype.toString.call(e))return this.reject(new TypeError("must be an array"));var i=e.length,n=!1;if(!i)return this.resolve([]);for(var o,a=-1,l=new this(s);++a<i;)o=e[a],t.resolve(o).then(function(e){n||(n=!0,r.resolve(l,e))},function(e){n||(n=!0,r.reject(l,e))});return l}},{immediate:36}],38:[function(e,t,i){var n={};(0,e("./lib/utils/common").assign)(n,e("./lib/deflate"),e("./lib/inflate"),e("./lib/zlib/constants")),t.exports=n},{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(e,t,i){var n=e("./zlib/deflate"),s=e("./utils/common"),r=e("./utils/strings"),o=e("./zlib/messages"),a=e("./zlib/zstream"),l=Object.prototype.toString,c=0,h=-1,u=0,d=8;function p(e){if(!(this instanceof p))return new p(e);this.options=s.assign({level:h,method:d,chunkSize:16384,windowBits:15,memLevel:8,strategy:u,to:""},e||{});var t=this.options;t.raw&&0<t.windowBits?t.windowBits=-t.windowBits:t.gzip&&0<t.windowBits&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new a,this.strm.avail_out=0;var i=n.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(i!==c)throw new Error(o[i]);if(t.header&&n.deflateSetHeader(this.strm,t.header),t.dictionary){var f;if(f="string"==typeof t.dictionary?r.string2buf(t.dictionary):"[object ArrayBuffer]"===l.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,(i=n.deflateSetDictionary(this.strm,f))!==c)throw new Error(o[i]);this._dict_set=!0}}function f(e,t){var i=new p(t);if(i.push(e,!0),i.err)throw i.msg||o[i.err];return i.result}p.prototype.push=function(e,t){var i,o,a=this.strm,h=this.options.chunkSize;if(this.ended)return!1;o=t===~~t?t:!0===t?4:0,"string"==typeof e?a.input=r.string2buf(e):"[object ArrayBuffer]"===l.call(e)?a.input=new Uint8Array(e):a.input=e,a.next_in=0,a.avail_in=a.input.length;do{if(0===a.avail_out&&(a.output=new s.Buf8(h),a.next_out=0,a.avail_out=h),1!==(i=n.deflate(a,o))&&i!==c)return this.onEnd(i),!(this.ended=!0);0!==a.avail_out&&(0!==a.avail_in||4!==o&&2!==o)||("string"===this.options.to?this.onData(r.buf2binstring(s.shrinkBuf(a.output,a.next_out))):this.onData(s.shrinkBuf(a.output,a.next_out)))}while((0<a.avail_in||0===a.avail_out)&&1!==i);return 4===o?(i=n.deflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===c):2!==o||(this.onEnd(c),!(a.avail_out=0))},p.prototype.onData=function(e){this.chunks.push(e)},p.prototype.onEnd=function(e){e===c&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=s.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},i.Deflate=p,i.deflate=f,i.deflateRaw=function(e,t){return(t=t||{}).raw=!0,f(e,t)},i.gzip=function(e,t){return(t=t||{}).gzip=!0,f(e,t)}},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(e,t,i){var n=e("./zlib/inflate"),s=e("./utils/common"),r=e("./utils/strings"),o=e("./zlib/constants"),a=e("./zlib/messages"),l=e("./zlib/zstream"),c=e("./zlib/gzheader"),h=Object.prototype.toString;function u(e){if(!(this instanceof u))return new u(e);this.options=s.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&0<=t.windowBits&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(0<=t.windowBits&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),15<t.windowBits&&t.windowBits<48&&!(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var i=n.inflateInit2(this.strm,t.windowBits);if(i!==o.Z_OK)throw new Error(a[i]);this.header=new c,n.inflateGetHeader(this.strm,this.header)}function d(e,t){var i=new u(t);if(i.push(e,!0),i.err)throw i.msg||a[i.err];return i.result}u.prototype.push=function(e,t){var i,a,l,c,u,d,p=this.strm,f=this.options.chunkSize,m=this.options.dictionary,g=!1;if(this.ended)return!1;a=t===~~t?t:!0===t?o.Z_FINISH:o.Z_NO_FLUSH,"string"==typeof e?p.input=r.binstring2buf(e):"[object ArrayBuffer]"===h.call(e)?p.input=new Uint8Array(e):p.input=e,p.next_in=0,p.avail_in=p.input.length;do{if(0===p.avail_out&&(p.output=new s.Buf8(f),p.next_out=0,p.avail_out=f),(i=n.inflate(p,o.Z_NO_FLUSH))===o.Z_NEED_DICT&&m&&(d="string"==typeof m?r.string2buf(m):"[object ArrayBuffer]"===h.call(m)?new Uint8Array(m):m,i=n.inflateSetDictionary(this.strm,d)),i===o.Z_BUF_ERROR&&!0===g&&(i=o.Z_OK,g=!1),i!==o.Z_STREAM_END&&i!==o.Z_OK)return this.onEnd(i),!(this.ended=!0);p.next_out&&(0!==p.avail_out&&i!==o.Z_STREAM_END&&(0!==p.avail_in||a!==o.Z_FINISH&&a!==o.Z_SYNC_FLUSH)||("string"===this.options.to?(l=r.utf8border(p.output,p.next_out),c=p.next_out-l,u=r.buf2string(p.output,l),p.next_out=c,p.avail_out=f-c,c&&s.arraySet(p.output,p.output,l,c,0),this.onData(u)):this.onData(s.shrinkBuf(p.output,p.next_out)))),0===p.avail_in&&0===p.avail_out&&(g=!0)}while((0<p.avail_in||0===p.avail_out)&&i!==o.Z_STREAM_END);return i===o.Z_STREAM_END&&(a=o.Z_FINISH),a===o.Z_FINISH?(i=n.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===o.Z_OK):a!==o.Z_SYNC_FLUSH||(this.onEnd(o.Z_OK),!(p.avail_out=0))},u.prototype.onData=function(e){this.chunks.push(e)},u.prototype.onEnd=function(e){e===o.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=s.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},i.Inflate=u,i.inflate=d,i.inflateRaw=function(e,t){return(t=t||{}).raw=!0,d(e,t)},i.ungzip=d},{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(e,t,i){var n="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;i.assign=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var i=t.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(var n in i)i.hasOwnProperty(n)&&(e[n]=i[n])}}return e},i.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var s={arraySet:function(e,t,i,n,s){if(t.subarray&&e.subarray)e.set(t.subarray(i,i+n),s);else for(var r=0;r<n;r++)e[s+r]=t[i+r]},flattenChunks:function(e){var t,i,n,s,r,o;for(t=n=0,i=e.length;t<i;t++)n+=e[t].length;for(o=new Uint8Array(n),t=s=0,i=e.length;t<i;t++)r=e[t],o.set(r,s),s+=r.length;return o}},r={arraySet:function(e,t,i,n,s){for(var r=0;r<n;r++)e[s+r]=t[i+r]},flattenChunks:function(e){return[].concat.apply([],e)}};i.setTyped=function(e){e?(i.Buf8=Uint8Array,i.Buf16=Uint16Array,i.Buf32=Int32Array,i.assign(i,s)):(i.Buf8=Array,i.Buf16=Array,i.Buf32=Array,i.assign(i,r))},i.setTyped(n)},{}],42:[function(e,t,i){var n=e("./common"),s=!0,r=!0;try{String.fromCharCode.apply(null,[0])}catch(e){s=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){r=!1}for(var o=new n.Buf8(256),a=0;a<256;a++)o[a]=252<=a?6:248<=a?5:240<=a?4:224<=a?3:192<=a?2:1;function l(e,t){if(t<65537&&(e.subarray&&r||!e.subarray&&s))return String.fromCharCode.apply(null,n.shrinkBuf(e,t));for(var i="",o=0;o<t;o++)i+=String.fromCharCode(e[o]);return i}o[254]=o[254]=1,i.string2buf=function(e){var t,i,s,r,o,a=e.length,l=0;for(r=0;r<a;r++)55296==(64512&(i=e.charCodeAt(r)))&&r+1<a&&56320==(64512&(s=e.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(s-56320),r++),l+=i<128?1:i<2048?2:i<65536?3:4;for(t=new n.Buf8(l),r=o=0;o<l;r++)55296==(64512&(i=e.charCodeAt(r)))&&r+1<a&&56320==(64512&(s=e.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(s-56320),r++),i<128?t[o++]=i:(i<2048?t[o++]=192|i>>>6:(i<65536?t[o++]=224|i>>>12:(t[o++]=240|i>>>18,t[o++]=128|i>>>12&63),t[o++]=128|i>>>6&63),t[o++]=128|63&i);return t},i.buf2binstring=function(e){return l(e,e.length)},i.binstring2buf=function(e){for(var t=new n.Buf8(e.length),i=0,s=t.length;i<s;i++)t[i]=e.charCodeAt(i);return t},i.buf2string=function(e,t){var i,n,s,r,a=t||e.length,c=new Array(2*a);for(i=n=0;i<a;)if((s=e[i++])<128)c[n++]=s;else if(4<(r=o[s]))c[n++]=65533,i+=r-1;else{for(s&=2===r?31:3===r?15:7;1<r&&i<a;)s=s<<6|63&e[i++],r--;1<r?c[n++]=65533:s<65536?c[n++]=s:(s-=65536,c[n++]=55296|s>>10&1023,c[n++]=56320|1023&s)}return l(c,n)},i.utf8border=function(e,t){var i;for((t=t||e.length)>e.length&&(t=e.length),i=t-1;0<=i&&128==(192&e[i]);)i--;return i<0||0===i?t:i+o[e[i]]>t?i:t}},{"./common":41}],43:[function(e,t,i){t.exports=function(e,t,i,n){for(var s=65535&e,r=e>>>16&65535,o=0;0!==i;){for(i-=o=2e3<i?2e3:i;r=r+(s=s+t[n++]|0)|0,--o;);s%=65521,r%=65521}return s|r<<16}},{}],44:[function(e,t,i){t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],45:[function(e,t,i){var n=function(){for(var e,t=[],i=0;i<256;i++){e=i;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t}();t.exports=function(e,t,i,s){var r=n,o=s+i;e^=-1;for(var a=s;a<o;a++)e=e>>>8^r[255&(e^t[a])];return-1^e}},{}],46:[function(e,t,i){var n,s=e("../utils/common"),r=e("./trees"),o=e("./adler32"),a=e("./crc32"),l=e("./messages"),c=0,h=4,u=0,d=-2,p=-1,f=4,m=2,g=8,w=9,y=286,_=30,b=19,v=2*y+1,x=15,C=3,S=258,A=S+C+1,T=42,P=113,E=1,M=2,I=3,z=4;function D(e,t){return e.msg=l[t],t}function k(e){return(e<<1)-(4<e?9:0)}function B(e){for(var t=e.length;0<=--t;)e[t]=0}function O(e){var t=e.state,i=t.pending;i>e.avail_out&&(i=e.avail_out),0!==i&&(s.arraySet(e.output,t.pending_buf,t.pending_out,i,e.next_out),e.next_out+=i,t.pending_out+=i,e.total_out+=i,e.avail_out-=i,t.pending-=i,0===t.pending&&(t.pending_out=0))}function V(e,t){r._tr_flush_block(e,0<=e.block_start?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,O(e.strm)}function N(e,t){e.pending_buf[e.pending++]=t}function L(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t}function F(e,t){var i,n,s=e.max_chain_length,r=e.strstart,o=e.prev_length,a=e.nice_match,l=e.strstart>e.w_size-A?e.strstart-(e.w_size-A):0,c=e.window,h=e.w_mask,u=e.prev,d=e.strstart+S,p=c[r+o-1],f=c[r+o];e.prev_length>=e.good_match&&(s>>=2),a>e.lookahead&&(a=e.lookahead);do{if(c[(i=t)+o]===f&&c[i+o-1]===p&&c[i]===c[r]&&c[++i]===c[r+1]){r+=2,i++;do{}while(c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&r<d);if(n=S-(d-r),r=d-S,o<n){if(e.match_start=t,a<=(o=n))break;p=c[r+o-1],f=c[r+o]}}}while((t=u[t&h])>l&&0!=--s);return o<=e.lookahead?o:e.lookahead}function R(e){var t,i,n,r,l,c,h,u,d,p,f=e.w_size;do{if(r=e.window_size-e.lookahead-e.strstart,e.strstart>=f+(f-A)){for(s.arraySet(e.window,e.window,f,f,0),e.match_start-=f,e.strstart-=f,e.block_start-=f,t=i=e.hash_size;n=e.head[--t],e.head[t]=f<=n?n-f:0,--i;);for(t=i=f;n=e.prev[--t],e.prev[t]=f<=n?n-f:0,--i;);r+=f}if(0===e.strm.avail_in)break;if(c=e.strm,h=e.window,u=e.strstart+e.lookahead,p=void 0,(d=r)<(p=c.avail_in)&&(p=d),i=0===p?0:(c.avail_in-=p,s.arraySet(h,c.input,c.next_in,p,u),1===c.state.wrap?c.adler=o(c.adler,h,p,u):2===c.state.wrap&&(c.adler=a(c.adler,h,p,u)),c.next_in+=p,c.total_in+=p,p),e.lookahead+=i,e.lookahead+e.insert>=C)for(l=e.strstart-e.insert,e.ins_h=e.window[l],e.ins_h=(e.ins_h<<e.hash_shift^e.window[l+1])&e.hash_mask;e.insert&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[l+C-1])&e.hash_mask,e.prev[l&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=l,l++,e.insert--,!(e.lookahead+e.insert<C)););}while(e.lookahead<A&&0!==e.strm.avail_in)}function U(e,t){for(var i,n;;){if(e.lookahead<A){if(R(e),e.lookahead<A&&t===c)return E;if(0===e.lookahead)break}if(i=0,e.lookahead>=C&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+C-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==i&&e.strstart-i<=e.w_size-A&&(e.match_length=F(e,i)),e.match_length>=C)if(n=r._tr_tally(e,e.strstart-e.match_start,e.match_length-C),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=C){for(e.match_length--;e.strstart++,e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+C-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart,0!=--e.match_length;);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+1])&e.hash_mask;else n=r._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(n&&(V(e,!1),0===e.strm.avail_out))return E}return e.insert=e.strstart<C-1?e.strstart:C-1,t===h?(V(e,!0),0===e.strm.avail_out?I:z):e.last_lit&&(V(e,!1),0===e.strm.avail_out)?E:M}function j(e,t){for(var i,n,s;;){if(e.lookahead<A){if(R(e),e.lookahead<A&&t===c)return E;if(0===e.lookahead)break}if(i=0,e.lookahead>=C&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+C-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=C-1,0!==i&&e.prev_length<e.max_lazy_match&&e.strstart-i<=e.w_size-A&&(e.match_length=F(e,i),e.match_length<=5&&(1===e.strategy||e.match_length===C&&4096<e.strstart-e.match_start)&&(e.match_length=C-1)),e.prev_length>=C&&e.match_length<=e.prev_length){for(s=e.strstart+e.lookahead-C,n=r._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-C),e.lookahead-=e.prev_length-1,e.prev_length-=2;++e.strstart<=s&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+C-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!=--e.prev_length;);if(e.match_available=0,e.match_length=C-1,e.strstart++,n&&(V(e,!1),0===e.strm.avail_out))return E}else if(e.match_available){if((n=r._tr_tally(e,0,e.window[e.strstart-1]))&&V(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return E}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(n=r._tr_tally(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<C-1?e.strstart:C-1,t===h?(V(e,!0),0===e.strm.avail_out?I:z):e.last_lit&&(V(e,!1),0===e.strm.avail_out)?E:M}function $(e,t,i,n,s){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=n,this.func=s}function W(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=g,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new s.Buf16(2*v),this.dyn_dtree=new s.Buf16(2*(2*_+1)),this.bl_tree=new s.Buf16(2*(2*b+1)),B(this.dyn_ltree),B(this.dyn_dtree),B(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new s.Buf16(x+1),this.heap=new s.Buf16(2*y+1),B(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new s.Buf16(2*y+1),B(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function H(e){var t;return e&&e.state?(e.total_in=e.total_out=0,e.data_type=m,(t=e.state).pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?T:P,e.adler=2===t.wrap?0:1,t.last_flush=c,r._tr_init(t),u):D(e,d)}function G(e){var t,i=H(e);return i===u&&((t=e.state).window_size=2*t.w_size,B(t.head),t.max_lazy_match=n[t.level].max_lazy,t.good_match=n[t.level].good_length,t.nice_match=n[t.level].nice_length,t.max_chain_length=n[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=C-1,t.match_available=0,t.ins_h=0),i}function Z(e,t,i,n,r,o){if(!e)return d;var a=1;if(t===p&&(t=6),n<0?(a=0,n=-n):15<n&&(a=2,n-=16),r<1||w<r||i!==g||n<8||15<n||t<0||9<t||o<0||f<o)return D(e,d);8===n&&(n=9);var l=new W;return(e.state=l).strm=e,l.wrap=a,l.gzhead=null,l.w_bits=n,l.w_size=1<<l.w_bits,l.w_mask=l.w_size-1,l.hash_bits=r+7,l.hash_size=1<<l.hash_bits,l.hash_mask=l.hash_size-1,l.hash_shift=~~((l.hash_bits+C-1)/C),l.window=new s.Buf8(2*l.w_size),l.head=new s.Buf16(l.hash_size),l.prev=new s.Buf16(l.w_size),l.lit_bufsize=1<<r+6,l.pending_buf_size=4*l.lit_bufsize,l.pending_buf=new s.Buf8(l.pending_buf_size),l.d_buf=1*l.lit_bufsize,l.l_buf=3*l.lit_bufsize,l.level=t,l.strategy=o,l.method=i,G(e)}n=[new $(0,0,0,0,function(e,t){var i=65535;for(i>e.pending_buf_size-5&&(i=e.pending_buf_size-5);;){if(e.lookahead<=1){if(R(e),0===e.lookahead&&t===c)return E;if(0===e.lookahead)break}e.strstart+=e.lookahead,e.lookahead=0;var n=e.block_start+i;if((0===e.strstart||e.strstart>=n)&&(e.lookahead=e.strstart-n,e.strstart=n,V(e,!1),0===e.strm.avail_out))return E;if(e.strstart-e.block_start>=e.w_size-A&&(V(e,!1),0===e.strm.avail_out))return E}return e.insert=0,t===h?(V(e,!0),0===e.strm.avail_out?I:z):(e.strstart>e.block_start&&(V(e,!1),e.strm.avail_out),E)}),new $(4,4,8,4,U),new $(4,5,16,8,U),new $(4,6,32,32,U),new $(4,4,16,16,j),new $(8,16,32,32,j),new $(8,16,128,128,j),new $(8,32,128,256,j),new $(32,128,258,1024,j),new $(32,258,258,4096,j)],i.deflateInit=function(e,t){return Z(e,t,g,15,8,0)},i.deflateInit2=Z,i.deflateReset=G,i.deflateResetKeep=H,i.deflateSetHeader=function(e,t){return e&&e.state?2!==e.state.wrap?d:(e.state.gzhead=t,u):d},i.deflate=function(e,t){var i,s,o,l;if(!e||!e.state||5<t||t<0)return e?D(e,d):d;if(s=e.state,!e.output||!e.input&&0!==e.avail_in||666===s.status&&t!==h)return D(e,0===e.avail_out?-5:d);if(s.strm=e,i=s.last_flush,s.last_flush=t,s.status===T)if(2===s.wrap)e.adler=0,N(s,31),N(s,139),N(s,8),s.gzhead?(N(s,(s.gzhead.text?1:0)+(s.gzhead.hcrc?2:0)+(s.gzhead.extra?4:0)+(s.gzhead.name?8:0)+(s.gzhead.comment?16:0)),N(s,255&s.gzhead.time),N(s,s.gzhead.time>>8&255),N(s,s.gzhead.time>>16&255),N(s,s.gzhead.time>>24&255),N(s,9===s.level?2:2<=s.strategy||s.level<2?4:0),N(s,255&s.gzhead.os),s.gzhead.extra&&s.gzhead.extra.length&&(N(s,255&s.gzhead.extra.length),N(s,s.gzhead.extra.length>>8&255)),s.gzhead.hcrc&&(e.adler=a(e.adler,s.pending_buf,s.pending,0)),s.gzindex=0,s.status=69):(N(s,0),N(s,0),N(s,0),N(s,0),N(s,0),N(s,9===s.level?2:2<=s.strategy||s.level<2?4:0),N(s,3),s.status=P);else{var p=g+(s.w_bits-8<<4)<<8;p|=(2<=s.strategy||s.level<2?0:s.level<6?1:6===s.level?2:3)<<6,0!==s.strstart&&(p|=32),p+=31-p%31,s.status=P,L(s,p),0!==s.strstart&&(L(s,e.adler>>>16),L(s,65535&e.adler)),e.adler=1}if(69===s.status)if(s.gzhead.extra){for(o=s.pending;s.gzindex<(65535&s.gzhead.extra.length)&&(s.pending!==s.pending_buf_size||(s.gzhead.hcrc&&s.pending>o&&(e.adler=a(e.adler,s.pending_buf,s.pending-o,o)),O(e),o=s.pending,s.pending!==s.pending_buf_size));)N(s,255&s.gzhead.extra[s.gzindex]),s.gzindex++;s.gzhead.hcrc&&s.pending>o&&(e.adler=a(e.adler,s.pending_buf,s.pending-o,o)),s.gzindex===s.gzhead.extra.length&&(s.gzindex=0,s.status=73)}else s.status=73;if(73===s.status)if(s.gzhead.name){o=s.pending;do{if(s.pending===s.pending_buf_size&&(s.gzhead.hcrc&&s.pending>o&&(e.adler=a(e.adler,s.pending_buf,s.pending-o,o)),O(e),o=s.pending,s.pending===s.pending_buf_size)){l=1;break}l=s.gzindex<s.gzhead.name.length?255&s.gzhead.name.charCodeAt(s.gzindex++):0,N(s,l)}while(0!==l);s.gzhead.hcrc&&s.pending>o&&(e.adler=a(e.adler,s.pending_buf,s.pending-o,o)),0===l&&(s.gzindex=0,s.status=91)}else s.status=91;if(91===s.status)if(s.gzhead.comment){o=s.pending;do{if(s.pending===s.pending_buf_size&&(s.gzhead.hcrc&&s.pending>o&&(e.adler=a(e.adler,s.pending_buf,s.pending-o,o)),O(e),o=s.pending,s.pending===s.pending_buf_size)){l=1;break}l=s.gzindex<s.gzhead.comment.length?255&s.gzhead.comment.charCodeAt(s.gzindex++):0,N(s,l)}while(0!==l);s.gzhead.hcrc&&s.pending>o&&(e.adler=a(e.adler,s.pending_buf,s.pending-o,o)),0===l&&(s.status=103)}else s.status=103;if(103===s.status&&(s.gzhead.hcrc?(s.pending+2>s.pending_buf_size&&O(e),s.pending+2<=s.pending_buf_size&&(N(s,255&e.adler),N(s,e.adler>>8&255),e.adler=0,s.status=P)):s.status=P),0!==s.pending){if(O(e),0===e.avail_out)return s.last_flush=-1,u}else if(0===e.avail_in&&k(t)<=k(i)&&t!==h)return D(e,-5);if(666===s.status&&0!==e.avail_in)return D(e,-5);if(0!==e.avail_in||0!==s.lookahead||t!==c&&666!==s.status){var f=2===s.strategy?function(e,t){for(var i;;){if(0===e.lookahead&&(R(e),0===e.lookahead)){if(t===c)return E;break}if(e.match_length=0,i=r._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(V(e,!1),0===e.strm.avail_out))return E}return e.insert=0,t===h?(V(e,!0),0===e.strm.avail_out?I:z):e.last_lit&&(V(e,!1),0===e.strm.avail_out)?E:M}(s,t):3===s.strategy?function(e,t){for(var i,n,s,o,a=e.window;;){if(e.lookahead<=S){if(R(e),e.lookahead<=S&&t===c)return E;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=C&&0<e.strstart&&(n=a[s=e.strstart-1])===a[++s]&&n===a[++s]&&n===a[++s]){o=e.strstart+S;do{}while(n===a[++s]&&n===a[++s]&&n===a[++s]&&n===a[++s]&&n===a[++s]&&n===a[++s]&&n===a[++s]&&n===a[++s]&&s<o);e.match_length=S-(o-s),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=C?(i=r._tr_tally(e,1,e.match_length-C),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=r._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(V(e,!1),0===e.strm.avail_out))return E}return e.insert=0,t===h?(V(e,!0),0===e.strm.avail_out?I:z):e.last_lit&&(V(e,!1),0===e.strm.avail_out)?E:M}(s,t):n[s.level].func(s,t);if(f!==I&&f!==z||(s.status=666),f===E||f===I)return 0===e.avail_out&&(s.last_flush=-1),u;if(f===M&&(1===t?r._tr_align(s):5!==t&&(r._tr_stored_block(s,0,0,!1),3===t&&(B(s.head),0===s.lookahead&&(s.strstart=0,s.block_start=0,s.insert=0))),O(e),0===e.avail_out))return s.last_flush=-1,u}return t!==h?u:s.wrap<=0?1:(2===s.wrap?(N(s,255&e.adler),N(s,e.adler>>8&255),N(s,e.adler>>16&255),N(s,e.adler>>24&255),N(s,255&e.total_in),N(s,e.total_in>>8&255),N(s,e.total_in>>16&255),N(s,e.total_in>>24&255)):(L(s,e.adler>>>16),L(s,65535&e.adler)),O(e),0<s.wrap&&(s.wrap=-s.wrap),0!==s.pending?u:1)},i.deflateEnd=function(e){var t;return e&&e.state?(t=e.state.status)!==T&&69!==t&&73!==t&&91!==t&&103!==t&&t!==P&&666!==t?D(e,d):(e.state=null,t===P?D(e,-3):u):d},i.deflateSetDictionary=function(e,t){var i,n,r,a,l,c,h,p,f=t.length;if(!e||!e.state)return d;if(2===(a=(i=e.state).wrap)||1===a&&i.status!==T||i.lookahead)return d;for(1===a&&(e.adler=o(e.adler,t,f,0)),i.wrap=0,f>=i.w_size&&(0===a&&(B(i.head),i.strstart=0,i.block_start=0,i.insert=0),p=new s.Buf8(i.w_size),s.arraySet(p,t,f-i.w_size,i.w_size,0),t=p,f=i.w_size),l=e.avail_in,c=e.next_in,h=e.input,e.avail_in=f,e.next_in=0,e.input=t,R(i);i.lookahead>=C;){for(n=i.strstart,r=i.lookahead-(C-1);i.ins_h=(i.ins_h<<i.hash_shift^i.window[n+C-1])&i.hash_mask,i.prev[n&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=n,n++,--r;);i.strstart=n,i.lookahead=C-1,R(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=C-1,i.match_available=0,e.next_in=c,e.input=h,e.avail_in=l,i.wrap=a,u},i.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(e,t,i){t.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],48:[function(e,t,i){t.exports=function(e,t){var i,n,s,r,o,a,l,c,h,u,d,p,f,m,g,w,y,_,b,v,x,C,S,A,T;i=e.state,n=e.next_in,A=e.input,s=n+(e.avail_in-5),r=e.next_out,T=e.output,o=r-(t-e.avail_out),a=r+(e.avail_out-257),l=i.dmax,c=i.wsize,h=i.whave,u=i.wnext,d=i.window,p=i.hold,f=i.bits,m=i.lencode,g=i.distcode,w=(1<<i.lenbits)-1,y=(1<<i.distbits)-1;e:do{f<15&&(p+=A[n++]<<f,f+=8,p+=A[n++]<<f,f+=8),_=m[p&w];t:for(;;){if(p>>>=b=_>>>24,f-=b,0==(b=_>>>16&255))T[r++]=65535&_;else{if(!(16&b)){if(!(64&b)){_=m[(65535&_)+(p&(1<<b)-1)];continue t}if(32&b){i.mode=12;break e}e.msg="invalid literal/length code",i.mode=30;break e}v=65535&_,(b&=15)&&(f<b&&(p+=A[n++]<<f,f+=8),v+=p&(1<<b)-1,p>>>=b,f-=b),f<15&&(p+=A[n++]<<f,f+=8,p+=A[n++]<<f,f+=8),_=g[p&y];i:for(;;){if(p>>>=b=_>>>24,f-=b,!(16&(b=_>>>16&255))){if(!(64&b)){_=g[(65535&_)+(p&(1<<b)-1)];continue i}e.msg="invalid distance code",i.mode=30;break e}if(x=65535&_,f<(b&=15)&&(p+=A[n++]<<f,(f+=8)<b&&(p+=A[n++]<<f,f+=8)),l<(x+=p&(1<<b)-1)){e.msg="invalid distance too far back",i.mode=30;break e}if(p>>>=b,f-=b,(b=r-o)<x){if(h<(b=x-b)&&i.sane){e.msg="invalid distance too far back",i.mode=30;break e}if(S=d,(C=0)===u){if(C+=c-b,b<v){for(v-=b;T[r++]=d[C++],--b;);C=r-x,S=T}}else if(u<b){if(C+=c+u-b,(b-=u)<v){for(v-=b;T[r++]=d[C++],--b;);if(C=0,u<v){for(v-=b=u;T[r++]=d[C++],--b;);C=r-x,S=T}}}else if(C+=u-b,b<v){for(v-=b;T[r++]=d[C++],--b;);C=r-x,S=T}for(;2<v;)T[r++]=S[C++],T[r++]=S[C++],T[r++]=S[C++],v-=3;v&&(T[r++]=S[C++],1<v&&(T[r++]=S[C++]))}else{for(C=r-x;T[r++]=T[C++],T[r++]=T[C++],T[r++]=T[C++],2<(v-=3););v&&(T[r++]=T[C++],1<v&&(T[r++]=T[C++]))}break}}break}}while(n<s&&r<a);n-=v=f>>3,p&=(1<<(f-=v<<3))-1,e.next_in=n,e.next_out=r,e.avail_in=n<s?s-n+5:5-(n-s),e.avail_out=r<a?a-r+257:257-(r-a),i.hold=p,i.bits=f}},{}],49:[function(e,t,i){var n=e("../utils/common"),s=e("./adler32"),r=e("./crc32"),o=e("./inffast"),a=e("./inftrees"),l=1,c=2,h=0,u=-2,d=1,p=852,f=592;function m(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function g(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new n.Buf16(320),this.work=new n.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function w(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=d,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new n.Buf32(p),t.distcode=t.distdyn=new n.Buf32(f),t.sane=1,t.back=-1,h):u}function y(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,w(e)):u}function _(e,t){var i,n;return e&&e.state?(n=e.state,t<0?(i=0,t=-t):(i=1+(t>>4),t<48&&(t&=15)),t&&(t<8||15<t)?u:(null!==n.window&&n.wbits!==t&&(n.window=null),n.wrap=i,n.wbits=t,y(e))):u}function b(e,t){var i,n;return e?(n=new g,(e.state=n).window=null,(i=_(e,t))!==h&&(e.state=null),i):u}var v,x,C=!0;function S(e){if(C){var t;for(v=new n.Buf32(512),x=new n.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(a(l,e.lens,0,288,v,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;a(c,e.lens,0,32,x,0,e.work,{bits:5}),C=!1}e.lencode=v,e.lenbits=9,e.distcode=x,e.distbits=5}function A(e,t,i,s){var r,o=e.state;return null===o.window&&(o.wsize=1<<o.wbits,o.wnext=0,o.whave=0,o.window=new n.Buf8(o.wsize)),s>=o.wsize?(n.arraySet(o.window,t,i-o.wsize,o.wsize,0),o.wnext=0,o.whave=o.wsize):(s<(r=o.wsize-o.wnext)&&(r=s),n.arraySet(o.window,t,i-s,r,o.wnext),(s-=r)?(n.arraySet(o.window,t,i-s,s,0),o.wnext=s,o.whave=o.wsize):(o.wnext+=r,o.wnext===o.wsize&&(o.wnext=0),o.whave<o.wsize&&(o.whave+=r))),0}i.inflateReset=y,i.inflateReset2=_,i.inflateResetKeep=w,i.inflateInit=function(e){return b(e,15)},i.inflateInit2=b,i.inflate=function(e,t){var i,p,f,g,w,y,_,b,v,x,C,T,P,E,M,I,z,D,k,B,O,V,N,L,F=0,R=new n.Buf8(4),U=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&0!==e.avail_in)return u;12===(i=e.state).mode&&(i.mode=13),w=e.next_out,f=e.output,_=e.avail_out,g=e.next_in,p=e.input,y=e.avail_in,b=i.hold,v=i.bits,x=y,C=_,V=h;e:for(;;)switch(i.mode){case d:if(0===i.wrap){i.mode=13;break}for(;v<16;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}if(2&i.wrap&&35615===b){R[i.check=0]=255&b,R[1]=b>>>8&255,i.check=r(i.check,R,2,0),v=b=0,i.mode=2;break}if(i.flags=0,i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&b)<<8)+(b>>8))%31){e.msg="incorrect header check",i.mode=30;break}if(8!=(15&b)){e.msg="unknown compression method",i.mode=30;break}if(v-=4,O=8+(15&(b>>>=4)),0===i.wbits)i.wbits=O;else if(O>i.wbits){e.msg="invalid window size",i.mode=30;break}i.dmax=1<<O,e.adler=i.check=1,i.mode=512&b?10:12,v=b=0;break;case 2:for(;v<16;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}if(i.flags=b,8!=(255&i.flags)){e.msg="unknown compression method",i.mode=30;break}if(57344&i.flags){e.msg="unknown header flags set",i.mode=30;break}i.head&&(i.head.text=b>>8&1),512&i.flags&&(R[0]=255&b,R[1]=b>>>8&255,i.check=r(i.check,R,2,0)),v=b=0,i.mode=3;case 3:for(;v<32;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}i.head&&(i.head.time=b),512&i.flags&&(R[0]=255&b,R[1]=b>>>8&255,R[2]=b>>>16&255,R[3]=b>>>24&255,i.check=r(i.check,R,4,0)),v=b=0,i.mode=4;case 4:for(;v<16;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}i.head&&(i.head.xflags=255&b,i.head.os=b>>8),512&i.flags&&(R[0]=255&b,R[1]=b>>>8&255,i.check=r(i.check,R,2,0)),v=b=0,i.mode=5;case 5:if(1024&i.flags){for(;v<16;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}i.length=b,i.head&&(i.head.extra_len=b),512&i.flags&&(R[0]=255&b,R[1]=b>>>8&255,i.check=r(i.check,R,2,0)),v=b=0}else i.head&&(i.head.extra=null);i.mode=6;case 6:if(1024&i.flags&&(y<(T=i.length)&&(T=y),T&&(i.head&&(O=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Array(i.head.extra_len)),n.arraySet(i.head.extra,p,g,T,O)),512&i.flags&&(i.check=r(i.check,p,T,g)),y-=T,g+=T,i.length-=T),i.length))break e;i.length=0,i.mode=7;case 7:if(2048&i.flags){if(0===y)break e;for(T=0;O=p[g+T++],i.head&&O&&i.length<65536&&(i.head.name+=String.fromCharCode(O)),O&&T<y;);if(512&i.flags&&(i.check=r(i.check,p,T,g)),y-=T,g+=T,O)break e}else i.head&&(i.head.name=null);i.length=0,i.mode=8;case 8:if(4096&i.flags){if(0===y)break e;for(T=0;O=p[g+T++],i.head&&O&&i.length<65536&&(i.head.comment+=String.fromCharCode(O)),O&&T<y;);if(512&i.flags&&(i.check=r(i.check,p,T,g)),y-=T,g+=T,O)break e}else i.head&&(i.head.comment=null);i.mode=9;case 9:if(512&i.flags){for(;v<16;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}if(b!==(65535&i.check)){e.msg="header crc mismatch",i.mode=30;break}v=b=0}i.head&&(i.head.hcrc=i.flags>>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=12;break;case 10:for(;v<32;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}e.adler=i.check=m(b),v=b=0,i.mode=11;case 11:if(0===i.havedict)return e.next_out=w,e.avail_out=_,e.next_in=g,e.avail_in=y,i.hold=b,i.bits=v,2;e.adler=i.check=1,i.mode=12;case 12:if(5===t||6===t)break e;case 13:if(i.last){b>>>=7&v,v-=7&v,i.mode=27;break}for(;v<3;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}switch(i.last=1&b,v-=1,3&(b>>>=1)){case 0:i.mode=14;break;case 1:if(S(i),i.mode=20,6!==t)break;b>>>=2,v-=2;break e;case 2:i.mode=17;break;case 3:e.msg="invalid block type",i.mode=30}b>>>=2,v-=2;break;case 14:for(b>>>=7&v,v-=7&v;v<32;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}if((65535&b)!=(b>>>16^65535)){e.msg="invalid stored block lengths",i.mode=30;break}if(i.length=65535&b,v=b=0,i.mode=15,6===t)break e;case 15:i.mode=16;case 16:if(T=i.length){if(y<T&&(T=y),_<T&&(T=_),0===T)break e;n.arraySet(f,p,g,T,w),y-=T,g+=T,_-=T,w+=T,i.length-=T;break}i.mode=12;break;case 17:for(;v<14;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}if(i.nlen=257+(31&b),b>>>=5,v-=5,i.ndist=1+(31&b),b>>>=5,v-=5,i.ncode=4+(15&b),b>>>=4,v-=4,286<i.nlen||30<i.ndist){e.msg="too many length or distance symbols",i.mode=30;break}i.have=0,i.mode=18;case 18:for(;i.have<i.ncode;){for(;v<3;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}i.lens[U[i.have++]]=7&b,b>>>=3,v-=3}for(;i.have<19;)i.lens[U[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,N={bits:i.lenbits},V=a(0,i.lens,0,19,i.lencode,0,i.work,N),i.lenbits=N.bits,V){e.msg="invalid code lengths set",i.mode=30;break}i.have=0,i.mode=19;case 19:for(;i.have<i.nlen+i.ndist;){for(;I=(F=i.lencode[b&(1<<i.lenbits)-1])>>>16&255,z=65535&F,!((M=F>>>24)<=v);){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}if(z<16)b>>>=M,v-=M,i.lens[i.have++]=z;else{if(16===z){for(L=M+2;v<L;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}if(b>>>=M,v-=M,0===i.have){e.msg="invalid bit length repeat",i.mode=30;break}O=i.lens[i.have-1],T=3+(3&b),b>>>=2,v-=2}else if(17===z){for(L=M+3;v<L;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}v-=M,O=0,T=3+(7&(b>>>=M)),b>>>=3,v-=3}else{for(L=M+7;v<L;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}v-=M,O=0,T=11+(127&(b>>>=M)),b>>>=7,v-=7}if(i.have+T>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=30;break}for(;T--;)i.lens[i.have++]=O}}if(30===i.mode)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=30;break}if(i.lenbits=9,N={bits:i.lenbits},V=a(l,i.lens,0,i.nlen,i.lencode,0,i.work,N),i.lenbits=N.bits,V){e.msg="invalid literal/lengths set",i.mode=30;break}if(i.distbits=6,i.distcode=i.distdyn,N={bits:i.distbits},V=a(c,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,N),i.distbits=N.bits,V){e.msg="invalid distances set",i.mode=30;break}if(i.mode=20,6===t)break e;case 20:i.mode=21;case 21:if(6<=y&&258<=_){e.next_out=w,e.avail_out=_,e.next_in=g,e.avail_in=y,i.hold=b,i.bits=v,o(e,C),w=e.next_out,f=e.output,_=e.avail_out,g=e.next_in,p=e.input,y=e.avail_in,b=i.hold,v=i.bits,12===i.mode&&(i.back=-1);break}for(i.back=0;I=(F=i.lencode[b&(1<<i.lenbits)-1])>>>16&255,z=65535&F,!((M=F>>>24)<=v);){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}if(I&&!(240&I)){for(D=M,k=I,B=z;I=(F=i.lencode[B+((b&(1<<D+k)-1)>>D)])>>>16&255,z=65535&F,!(D+(M=F>>>24)<=v);){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}b>>>=D,v-=D,i.back+=D}if(b>>>=M,v-=M,i.back+=M,i.length=z,0===I){i.mode=26;break}if(32&I){i.back=-1,i.mode=12;break}if(64&I){e.msg="invalid literal/length code",i.mode=30;break}i.extra=15&I,i.mode=22;case 22:if(i.extra){for(L=i.extra;v<L;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}i.length+=b&(1<<i.extra)-1,b>>>=i.extra,v-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=23;case 23:for(;I=(F=i.distcode[b&(1<<i.distbits)-1])>>>16&255,z=65535&F,!((M=F>>>24)<=v);){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}if(!(240&I)){for(D=M,k=I,B=z;I=(F=i.distcode[B+((b&(1<<D+k)-1)>>D)])>>>16&255,z=65535&F,!(D+(M=F>>>24)<=v);){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}b>>>=D,v-=D,i.back+=D}if(b>>>=M,v-=M,i.back+=M,64&I){e.msg="invalid distance code",i.mode=30;break}i.offset=z,i.extra=15&I,i.mode=24;case 24:if(i.extra){for(L=i.extra;v<L;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}i.offset+=b&(1<<i.extra)-1,b>>>=i.extra,v-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=30;break}i.mode=25;case 25:if(0===_)break e;if(T=C-_,i.offset>T){if((T=i.offset-T)>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=30;break}P=T>i.wnext?(T-=i.wnext,i.wsize-T):i.wnext-T,T>i.length&&(T=i.length),E=i.window}else E=f,P=w-i.offset,T=i.length;for(_<T&&(T=_),_-=T,i.length-=T;f[w++]=E[P++],--T;);0===i.length&&(i.mode=21);break;case 26:if(0===_)break e;f[w++]=i.length,_--,i.mode=21;break;case 27:if(i.wrap){for(;v<32;){if(0===y)break e;y--,b|=p[g++]<<v,v+=8}if(C-=_,e.total_out+=C,i.total+=C,C&&(e.adler=i.check=i.flags?r(i.check,f,C,w-C):s(i.check,f,C,w-C)),C=_,(i.flags?b:m(b))!==i.check){e.msg="incorrect data check",i.mode=30;break}v=b=0}i.mode=28;case 28:if(i.wrap&&i.flags){for(;v<32;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}if(b!==(4294967295&i.total)){e.msg="incorrect length check",i.mode=30;break}v=b=0}i.mode=29;case 29:V=1;break e;case 30:V=-3;break e;case 31:return-4;default:return u}return e.next_out=w,e.avail_out=_,e.next_in=g,e.avail_in=y,i.hold=b,i.bits=v,(i.wsize||C!==e.avail_out&&i.mode<30&&(i.mode<27||4!==t))&&A(e,e.output,e.next_out,C-e.avail_out)?(i.mode=31,-4):(x-=e.avail_in,C-=e.avail_out,e.total_in+=x,e.total_out+=C,i.total+=C,i.wrap&&C&&(e.adler=i.check=i.flags?r(i.check,f,C,e.next_out-C):s(i.check,f,C,e.next_out-C)),e.data_type=i.bits+(i.last?64:0)+(12===i.mode?128:0)+(20===i.mode||15===i.mode?256:0),(0==x&&0===C||4===t)&&V===h&&(V=-5),V)},i.inflateEnd=function(e){if(!e||!e.state)return u;var t=e.state;return t.window&&(t.window=null),e.state=null,h},i.inflateGetHeader=function(e,t){var i;return e&&e.state&&2&(i=e.state).wrap?((i.head=t).done=!1,h):u},i.inflateSetDictionary=function(e,t){var i,n=t.length;return e&&e.state?0!==(i=e.state).wrap&&11!==i.mode?u:11===i.mode&&s(1,t,n,0)!==i.check?-3:A(e,t,n,n)?(i.mode=31,-4):(i.havedict=1,h):u},i.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(e,t,i){var n=e("../utils/common"),s=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],r=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],o=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],a=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];t.exports=function(e,t,i,l,c,h,u,d){var p,f,m,g,w,y,_,b,v,x=d.bits,C=0,S=0,A=0,T=0,P=0,E=0,M=0,I=0,z=0,D=0,k=null,B=0,O=new n.Buf16(16),V=new n.Buf16(16),N=null,L=0;for(C=0;C<=15;C++)O[C]=0;for(S=0;S<l;S++)O[t[i+S]]++;for(P=x,T=15;1<=T&&0===O[T];T--);if(T<P&&(P=T),0===T)return c[h++]=20971520,c[h++]=20971520,d.bits=1,0;for(A=1;A<T&&0===O[A];A++);for(P<A&&(P=A),C=I=1;C<=15;C++)if(I<<=1,(I-=O[C])<0)return-1;if(0<I&&(0===e||1!==T))return-1;for(V[1]=0,C=1;C<15;C++)V[C+1]=V[C]+O[C];for(S=0;S<l;S++)0!==t[i+S]&&(u[V[t[i+S]]++]=S);if(y=0===e?(k=N=u,19):1===e?(k=s,B-=257,N=r,L-=257,256):(k=o,N=a,-1),C=A,w=h,M=S=D=0,m=-1,g=(z=1<<(E=P))-1,1===e&&852<z||2===e&&592<z)return 1;for(;;){for(_=C-M,v=u[S]<y?(b=0,u[S]):u[S]>y?(b=N[L+u[S]],k[B+u[S]]):(b=96,0),p=1<<C-M,A=f=1<<E;c[w+(D>>M)+(f-=p)]=_<<24|b<<16|v,0!==f;);for(p=1<<C-1;D&p;)p>>=1;if(0!==p?(D&=p-1,D+=p):D=0,S++,0==--O[C]){if(C===T)break;C=t[i+u[S]]}if(P<C&&(D&g)!==m){for(0===M&&(M=P),w+=A,I=1<<(E=C-M);E+M<T&&!((I-=O[E+M])<=0);)E++,I<<=1;if(z+=1<<E,1===e&&852<z||2===e&&592<z)return 1;c[m=D&g]=P<<24|E<<16|w-h}}return 0!==D&&(c[w+D]=C-M<<24|64<<16),d.bits=P,0}},{"../utils/common":41}],51:[function(e,t,i){t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],52:[function(e,t,i){var n=e("../utils/common"),s=0,r=1;function o(e){for(var t=e.length;0<=--t;)e[t]=0}var a=0,l=29,c=256,h=c+1+l,u=30,d=19,p=2*h+1,f=15,m=16,g=7,w=256,y=16,_=17,b=18,v=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],x=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],C=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],S=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],A=new Array(2*(h+2));o(A);var T=new Array(2*u);o(T);var P=new Array(512);o(P);var E=new Array(256);o(E);var M=new Array(l);o(M);var I,z,D,k=new Array(u);function B(e,t,i,n,s){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=n,this.max_length=s,this.has_stree=e&&e.length}function O(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function V(e){return e<256?P[e]:P[256+(e>>>7)]}function N(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255}function L(e,t,i){e.bi_valid>m-i?(e.bi_buf|=t<<e.bi_valid&65535,N(e,e.bi_buf),e.bi_buf=t>>m-e.bi_valid,e.bi_valid+=i-m):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=i)}function F(e,t,i){L(e,i[2*t],i[2*t+1])}function R(e,t){for(var i=0;i|=1&e,e>>>=1,i<<=1,0<--t;);return i>>>1}function U(e,t,i){var n,s,r=new Array(f+1),o=0;for(n=1;n<=f;n++)r[n]=o=o+i[n-1]<<1;for(s=0;s<=t;s++){var a=e[2*s+1];0!==a&&(e[2*s]=R(r[a]++,a))}}function j(e){var t;for(t=0;t<h;t++)e.dyn_ltree[2*t]=0;for(t=0;t<u;t++)e.dyn_dtree[2*t]=0;for(t=0;t<d;t++)e.bl_tree[2*t]=0;e.dyn_ltree[2*w]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0}function $(e){8<e.bi_valid?N(e,e.bi_buf):0<e.bi_valid&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function W(e,t,i,n){var s=2*t,r=2*i;return e[s]<e[r]||e[s]===e[r]&&n[t]<=n[i]}function H(e,t,i){for(var n=e.heap[i],s=i<<1;s<=e.heap_len&&(s<e.heap_len&&W(t,e.heap[s+1],e.heap[s],e.depth)&&s++,!W(t,n,e.heap[s],e.depth));)e.heap[i]=e.heap[s],i=s,s<<=1;e.heap[i]=n}function G(e,t,i){var n,s,r,o,a=0;if(0!==e.last_lit)for(;n=e.pending_buf[e.d_buf+2*a]<<8|e.pending_buf[e.d_buf+2*a+1],s=e.pending_buf[e.l_buf+a],a++,0===n?F(e,s,t):(F(e,(r=E[s])+c+1,t),0!==(o=v[r])&&L(e,s-=M[r],o),F(e,r=V(--n),i),0!==(o=x[r])&&L(e,n-=k[r],o)),a<e.last_lit;);F(e,w,t)}function Z(e,t){var i,n,s,r=t.dyn_tree,o=t.stat_desc.static_tree,a=t.stat_desc.has_stree,l=t.stat_desc.elems,c=-1;for(e.heap_len=0,e.heap_max=p,i=0;i<l;i++)0!==r[2*i]?(e.heap[++e.heap_len]=c=i,e.depth[i]=0):r[2*i+1]=0;for(;e.heap_len<2;)r[2*(s=e.heap[++e.heap_len]=c<2?++c:0)]=1,e.depth[s]=0,e.opt_len--,a&&(e.static_len-=o[2*s+1]);for(t.max_code=c,i=e.heap_len>>1;1<=i;i--)H(e,r,i);for(s=l;i=e.heap[1],e.heap[1]=e.heap[e.heap_len--],H(e,r,1),n=e.heap[1],e.heap[--e.heap_max]=i,e.heap[--e.heap_max]=n,r[2*s]=r[2*i]+r[2*n],e.depth[s]=(e.depth[i]>=e.depth[n]?e.depth[i]:e.depth[n])+1,r[2*i+1]=r[2*n+1]=s,e.heap[1]=s++,H(e,r,1),2<=e.heap_len;);e.heap[--e.heap_max]=e.heap[1],function(e,t){var i,n,s,r,o,a,l=t.dyn_tree,c=t.max_code,h=t.stat_desc.static_tree,u=t.stat_desc.has_stree,d=t.stat_desc.extra_bits,m=t.stat_desc.extra_base,g=t.stat_desc.max_length,w=0;for(r=0;r<=f;r++)e.bl_count[r]=0;for(l[2*e.heap[e.heap_max]+1]=0,i=e.heap_max+1;i<p;i++)g<(r=l[2*l[2*(n=e.heap[i])+1]+1]+1)&&(r=g,w++),l[2*n+1]=r,c<n||(e.bl_count[r]++,o=0,m<=n&&(o=d[n-m]),a=l[2*n],e.opt_len+=a*(r+o),u&&(e.static_len+=a*(h[2*n+1]+o)));if(0!==w){do{for(r=g-1;0===e.bl_count[r];)r--;e.bl_count[r]--,e.bl_count[r+1]+=2,e.bl_count[g]--,w-=2}while(0<w);for(r=g;0!==r;r--)for(n=e.bl_count[r];0!==n;)c<(s=e.heap[--i])||(l[2*s+1]!==r&&(e.opt_len+=(r-l[2*s+1])*l[2*s],l[2*s+1]=r),n--)}}(e,t),U(r,c,e.bl_count)}function q(e,t,i){var n,s,r=-1,o=t[1],a=0,l=7,c=4;for(0===o&&(l=138,c=3),t[2*(i+1)+1]=65535,n=0;n<=i;n++)s=o,o=t[2*(n+1)+1],++a<l&&s===o||(a<c?e.bl_tree[2*s]+=a:0!==s?(s!==r&&e.bl_tree[2*s]++,e.bl_tree[2*y]++):a<=10?e.bl_tree[2*_]++:e.bl_tree[2*b]++,r=s,c=(a=0)===o?(l=138,3):s===o?(l=6,3):(l=7,4))}function Y(e,t,i){var n,s,r=-1,o=t[1],a=0,l=7,c=4;for(0===o&&(l=138,c=3),n=0;n<=i;n++)if(s=o,o=t[2*(n+1)+1],!(++a<l&&s===o)){if(a<c)for(;F(e,s,e.bl_tree),0!=--a;);else 0!==s?(s!==r&&(F(e,s,e.bl_tree),a--),F(e,y,e.bl_tree),L(e,a-3,2)):a<=10?(F(e,_,e.bl_tree),L(e,a-3,3)):(F(e,b,e.bl_tree),L(e,a-11,7));r=s,c=(a=0)===o?(l=138,3):s===o?(l=6,3):(l=7,4)}}o(k);var X=!1;function K(e,t,i,s){var r,o,l;L(e,(a<<1)+(s?1:0),3),o=t,l=i,$(r=e),N(r,l),N(r,~l),n.arraySet(r.pending_buf,r.window,o,l,r.pending),r.pending+=l}i._tr_init=function(e){X||(function(){var e,t,i,n,s,r=new Array(f+1);for(n=i=0;n<l-1;n++)for(M[n]=i,e=0;e<1<<v[n];e++)E[i++]=n;for(E[i-1]=n,n=s=0;n<16;n++)for(k[n]=s,e=0;e<1<<x[n];e++)P[s++]=n;for(s>>=7;n<u;n++)for(k[n]=s<<7,e=0;e<1<<x[n]-7;e++)P[256+s++]=n;for(t=0;t<=f;t++)r[t]=0;for(e=0;e<=143;)A[2*e+1]=8,e++,r[8]++;for(;e<=255;)A[2*e+1]=9,e++,r[9]++;for(;e<=279;)A[2*e+1]=7,e++,r[7]++;for(;e<=287;)A[2*e+1]=8,e++,r[8]++;for(U(A,h+1,r),e=0;e<u;e++)T[2*e+1]=5,T[2*e]=R(e,5);I=new B(A,v,c+1,h,f),z=new B(T,x,0,u,f),D=new B(new Array(0),C,0,d,g)}(),X=!0),e.l_desc=new O(e.dyn_ltree,I),e.d_desc=new O(e.dyn_dtree,z),e.bl_desc=new O(e.bl_tree,D),e.bi_buf=0,e.bi_valid=0,j(e)},i._tr_stored_block=K,i._tr_flush_block=function(e,t,i,n){var o,a,l=0;0<e.level?(2===e.strm.data_type&&(e.strm.data_type=function(e){var t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return s;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return r;for(t=32;t<c;t++)if(0!==e.dyn_ltree[2*t])return r;return s}(e)),Z(e,e.l_desc),Z(e,e.d_desc),l=function(e){var t;for(q(e,e.dyn_ltree,e.l_desc.max_code),q(e,e.dyn_dtree,e.d_desc.max_code),Z(e,e.bl_desc),t=d-1;3<=t&&0===e.bl_tree[2*S[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}(e),o=e.opt_len+3+7>>>3,(a=e.static_len+3+7>>>3)<=o&&(o=a)):o=a=i+5,i+4<=o&&-1!==t?K(e,t,i,n):4===e.strategy||a===o?(L(e,2+(n?1:0),3),G(e,A,T)):(L(e,4+(n?1:0),3),function(e,t,i,n){var s;for(L(e,t-257,5),L(e,i-1,5),L(e,n-4,4),s=0;s<n;s++)L(e,e.bl_tree[2*S[s]+1],3);Y(e,e.dyn_ltree,t-1),Y(e,e.dyn_dtree,i-1)}(e,e.l_desc.max_code+1,e.d_desc.max_code+1,l+1),G(e,e.dyn_ltree,e.dyn_dtree)),j(e),n&&$(e)},i._tr_tally=function(e,t,i){return e.pending_buf[e.d_buf+2*e.last_lit]=t>>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&i,e.last_lit++,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(E[i]+c+1)]++,e.dyn_dtree[2*V(t)]++),e.last_lit===e.lit_bufsize-1},i._tr_align=function(e){var t;L(e,2,3),F(e,w,A),16===(t=e).bi_valid?(N(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):8<=t.bi_valid&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)}},{"../utils/common":41}],53:[function(e,t,i){t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(e,t,i){(function(e){!function(e,t){if(!e.setImmediate){var i,n,s,r,o=1,a={},l=!1,c=e.document,h=Object.getPrototypeOf&&Object.getPrototypeOf(e);h=h&&h.setTimeout?h:e,i="[object process]"==={}.toString.call(e.process)?function(e){process.nextTick(function(){d(e)})}:function(){if(e.postMessage&&!e.importScripts){var t=!0,i=e.onmessage;return e.onmessage=function(){t=!1},e.postMessage("","*"),e.onmessage=i,t}}()?(r="setImmediate$"+Math.random()+"$",e.addEventListener?e.addEventListener("message",p,!1):e.attachEvent("onmessage",p),function(t){e.postMessage(r+t,"*")}):e.MessageChannel?((s=new MessageChannel).port1.onmessage=function(e){d(e.data)},function(e){s.port2.postMessage(e)}):c&&"onreadystatechange"in c.createElement("script")?(n=c.documentElement,function(e){var t=c.createElement("script");t.onreadystatechange=function(){d(e),t.onreadystatechange=null,n.removeChild(t),t=null},n.appendChild(t)}):function(e){setTimeout(d,0,e)},h.setImmediate=function(e){"function"!=typeof e&&(e=new Function(""+e));for(var t=new Array(arguments.length-1),n=0;n<t.length;n++)t[n]=arguments[n+1];var s={callback:e,args:t};return a[o]=s,i(o),o++},h.clearImmediate=u}function u(e){delete a[e]}function d(e){if(l)setTimeout(d,0,e);else{var i=a[e];if(i){l=!0;try{!function(e){var i=e.callback,n=e.args;switch(n.length){case 0:i();break;case 1:i(n[0]);break;case 2:i(n[0],n[1]);break;case 3:i(n[0],n[1],n[2]);break;default:i.apply(t,n)}}(i)}finally{u(e),l=!1}}}}function p(t){t.source===e&&"string"==typeof t.data&&0===t.data.indexOf(r)&&d(+t.data.slice(r.length))}}("undefined"==typeof self?void 0===e?this:e:self)}).call(this,void 0!==Oa?Oa:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}]},{},[10])(10)),Fa.exports));class Ua{date=new Date;author;guid=me.create();viewpoint;modifiedAuthor;modifiedDate;topic;_components;_comment="";set comment(e){const t=this._components.get(Ha);this._comment=e,this.modifiedDate=new Date,this.modifiedAuthor=t.config.author,this.topic?.comments.set(this.guid,this)}get comment(){return this._comment}constructor(e,t){this._components=e,this._comment=t;const i=this._components.get(Ha);this.author=i.config.author}toJSON(){const e={guid:this.guid,date:this.date.toISOString(),author:this.author,comment:this.comment,topic_guid:this.topic?.guid,viewpoint_guid:this.viewpoint,modified_date:this.modifiedDate?.toISOString(),modified_author:this.modifiedAuthor};for(const[t,i]of Object.entries(e))void 0===i&&delete e[t];return e}}class ja{static default={title:"BCF Topic",type:"Issue",status:"Active"};guid=me.create();title=ja.default.title;creationDate=new Date;creationAuthor="";viewpoints=new n;relatedTopics=new n;comments=new t;documentReferences=new n;customData={};description;serverAssignedId;dueDate;modifiedAuthor;modifiedDate;index;_type=ja.default.type;set type(e){const t=this._components.get(Ha),{strict:i,types:n}=t.config;(!i||n.has(e))&&(this._type=e)}get type(){return this._type}_status=ja.default.status;set status(e){const t=this._components.get(Ha),{strict:i,statuses:n}=t.config;(!i||n.has(e))&&(this._status=e)}get status(){return this._status}_priority=ja.default.priority;set priority(e){const t=this._components.get(Ha);if(e){const{strict:i,priorities:n}=t.config;if(!(!i||n.has(e)))return;this._priority=e}else this._priority=e}get priority(){return this._priority}_stage=ja.default.stage;set stage(e){const t=this._components.get(Ha);if(e){const{strict:i,stages:n}=t.config;if(!(!i||n.has(e)))return;this._stage=e}else this._stage=e}get stage(){return this._stage}_assignedTo=ja.default.assignedTo;set assignedTo(e){const t=this._components.get(Ha);if(e){const{strict:i,users:n}=t.config;if(!(!i||n.has(e)))return;this._assignedTo=e}else this._assignedTo=e}get assignedTo(){return this._assignedTo}_labels=ja.default.labels??new Set;set labels(e){const t=this._components.get(Ha),{strict:i,labels:n}=t.config;if(i){const t=new Set;for(const s of e){(!i||n.has(s))&&t.add(s)}this._labels=t}else this._labels=e}get labels(){return this._labels}_components;get _managerVersion(){return this._components.get(Ha).config.version}constructor(e){this._components=e;const t=e.get(Ha);this.creationAuthor=t.config.author,this.relatedTopics.guard=e=>e!==this.guid}set(e){const t=e,i=this;for(const n in e){if("guid"===n)continue;const e=t[n];n in this&&(i[n]=e)}return this._components.get(Ha).list.set(this.guid,this),this}createComment(e,t){const i=new Ua(this._components,e);return i.viewpoint=t,i.topic=this,this.comments.set(i.guid,i),i}createLabelTags(){const e=[...this.labels];if(this._components.get(Ha).config.exportCustomDataAsLabels)for(const t in this.customData){const i=this.customData[t];"string"==typeof i&&e.push(i)}return e}createCommentTags(){return[...this.comments.values()].map(e=>({$Guid:e.guid,Date:e.date.toISOString(),Author:e.author,Comment:e.comment,ModifiedAuthor:e.modifiedAuthor,ModifiedDate:e.modifiedDate?.toISOString(),Viewpoint:e.viewpoint?{$Guid:e.viewpoint}:void 0}))}createViewpointTags(){const e=this._components.get(Ka);return[...this.viewpoints].map(t=>e.list.get(t)).filter(e=>e).map(t=>{const i={$Guid:t.guid,Viewpoint:`${t.title??t.guid}.bcfv`};if(e.snapshots.get(t.snapshot)){const n=e.getSnapshotExtension(t.snapshot);i.Snapshot=`${t.snapshot}.${n}`}return i})}createRelatedTopicTags(){return[...this.relatedTopics].map(e=>({$Guid:e}))}createDocumentReferencesTag(e=this._managerVersion){const t=[];if("3"!==e&&"2.1"!==e)return t;const i=this._components.get(Ha);for(const n of this.documentReferences){const s=i.documents.get(n);if(!s)continue;let r={$Guid:me.create(),Description:s.description};"2.1"===e&&(r={...r,$isExternal:"external"===s.type||void 0,ReferencedDocument:"external"===s.type?s.url:`../${s.fileName}`}),"3"===e&&(r={...r,DocumentGuid:"internal"===s.type?n:void 0,Url:"external"===s.type?s.url:void 0}),Object.keys(r).length>0&&t.push(r)}return t}toJSON(){const e={guid:this.guid,server_assigned_id:this.serverAssignedId,topic_type:this.type,topic_status:this.status,title:this.title,priority:this.priority,index:this.index,labels:[...this.labels],creation_date:this.creationDate.toISOString(),creation_author:this.creationAuthor,modified_date:this.modifiedDate?.toISOString(),modified_author:this.modifiedAuthor,assigned_to:this.assignedTo,stage:this.stage,description:this.description,due_date:this.dueDate?.toISOString(),comments:[...this.comments].map(([e,t])=>t.toJSON()),relatedTopics:[...this.relatedTopics].map(e=>({related_topic_guid:e}))},t=this._components.get(Ka);for(const i of this.viewpoints){const n=t.list.get(i);n&&(e.viewpoints||(e.viewpoints=[]),e.viewpoints.push(n.toJSON()))}const i=this._components.get(Ha);for(const t of this.documentReferences){const n=i.documents.get(t);n&&(e.document_references||(e.document_references=[]),"external"===n.type?e.document_references.push({guid:me.create(),description:n.description,url:n.url}):e.document_references.push({guid:me.create(),description:n.description,document_guid:t}))}for(const[t,i]of Object.entries(e))(void 0===i||Array.isArray(i)&&0===i.length)&&delete e[t];return e}serialize(){const e=this._managerVersion,t="3"===e,i={Markup:{Topic:{$Guid:this.guid,$TopicType:this.type,$TopicStatus:this.status,$ServerAssignedId:this.serverAssignedId,Title:this.title,Priority:this.priority,Index:"2.1"===e?this.index:void 0,Labels:t?{Label:this.createLabelTags()}:this.createLabelTags(),CreationDate:this.creationDate.toISOString(),CreationAuthor:this.creationAuthor,ModifiedDate:this.modifiedDate?.toISOString(),ModifiedAuthor:this.modifiedAuthor,DueDate:this.dueDate?.toISOString(),AssignedTo:this.assignedTo,Stage:this.stage,Description:this.description,DocumentReferences:t?{DocumentReference:this.createDocumentReferencesTag(e)}:void 0,DocumentReference:t?void 0:this.createDocumentReferencesTag(e),RelatedTopics:t?{RelatedTopic:this.createRelatedTopicTags()}:void 0,RelatedTopic:t?void 0:this.createRelatedTopicTags(),Comments:t?{Comment:this.createCommentTags()}:void 0,Viewpoints:t?{ViewPoint:this.createViewpointTags()}:void 0}}};return"2.1"===e&&(i.Markup.Viewpoints=this.createViewpointTags(),i.Markup.Comment=this.createCommentTags()),`<?xml version="1.0" encoding="UTF-8"?>\n ${ii.builder.build(i)}`}}const $a=(e,t)=>{if(""===t.trim())return;const i=Ha.xmlParser.parse(t).Extensions;if(!i)return;const{Priorities:n,TopicStatuses:s,TopicTypes:r,Users:o}=i;if(n&&n.Priority){const t=Array.isArray(n.Priority)?n.Priority:[n.Priority];for(const i of t)e.config.priorities.add(i)}if(s&&s.TopicStatus){const t=Array.isArray(s.TopicStatus)?s.TopicStatus:[s.TopicStatus];for(const i of t)e.config.statuses.add(i)}if(r&&r.TopicType){const t=Array.isArray(r.TopicType)?r.TopicType:[r.TopicType];for(const i of t)e.config.types.add(i)}if(o&&o.User){const t=Array.isArray(o.User)?o.User:[o.User];for(const i of t)e.config.users.add(i)}};class Wa extends li{_config={version:{type:"Select",options:new Set(["2.1","3"]),multiple:!1,value:""},author:{type:"Text",value:""},types:{type:"TextSet",value:new Set},statuses:{type:"TextSet",value:new Set},priorities:{type:"TextSet",value:new Set},labels:{type:"TextSet",value:new Set},stages:{type:"TextSet",value:new Set},users:{type:"TextSet",value:new Set},includeSelectionTag:{type:"Boolean",value:!1},updateExtensionsOnImport:{type:"Boolean",value:!1},strict:{type:"Boolean",value:!1},includeAllExtensionsOnExport:{type:"Boolean",value:!1},fallbackVersionOnImport:{type:"Select",multiple:!1,options:new Set(["2.1","3"]),value:""},ignoreIncompleteTopicsOnImport:{type:"Boolean",value:!1},exportCustomDataAsLabels:{type:"Boolean",value:!1}};get version(){return this._config.version.value}set version(e){this._config.version.value=e}get author(){return this._config.author.value}set author(e){this._config.author.value=e}get types(){return this._config.types.value}set types(e){this._config.types.value=e}get statuses(){return this._config.statuses.value}set statuses(e){this._config.statuses.value=e}get priorities(){return this._config.priorities.value}set priorities(e){this._config.priorities.value=e}get labels(){return this._config.labels.value}set labels(e){this._config.labels.value=e}get stages(){return this._config.stages.value}set stages(e){this._config.stages.value=e}get users(){return this._config.users.value}set users(e){this._config.users.value=e}get includeSelectionTag(){return this._config.includeSelectionTag.value}set includeSelectionTag(e){this._config.includeSelectionTag.value=e}get updateExtensionsOnImport(){return this._config.updateExtensionsOnImport.value}set updateExtensionsOnImport(e){this._config.updateExtensionsOnImport.value=e}get strict(){return this._config.strict.value}set strict(e){this._config.strict.value=e}get includeAllExtensionsOnExport(){return this._config.includeAllExtensionsOnExport.value}set includeAllExtensionsOnExport(e){this._config.includeAllExtensionsOnExport.value=e}get fallbackVersionOnImport(){return this._config.fallbackVersionOnImport.value}set fallbackVersionOnImport(e){this._config.fallbackVersionOnImport.value=e}get ignoreIncompleteTopicsOnImport(){return this._config.ignoreIncompleteTopicsOnImport.value}set ignoreIncompleteTopicsOnImport(e){this._config.ignoreIncompleteTopicsOnImport.value=e}get exportCustomDataAsLabels(){return this._config.exportCustomDataAsLabels.value}set exportCustomDataAsLabels(e){this._config.exportCustomDataAsLabels.value=e}}class Ha extends le{static uuid="de977976-e4f6-4e4f-a01a-204727839802";enabled=!1;static xmlParser=new Ut({allowBooleanAttributes:!0,attributeNamePrefix:"",ignoreAttributes:!1,ignoreDeclaration:!0,ignorePiTags:!0,numberParseOptions:{leadingZeros:!0,hex:!0},parseAttributeValue:!0,preserveOrder:!1,processEntities:!1,removeNSPrefix:!0,trimValues:!0});_defaultConfig={author:"jhon.doe@example.com",version:"2.1",types:new Set(["Clash","Failure","Fault","Inquiry","Issue","Remark","Request"]),statuses:new Set(["Active","In Progress","Done","In Review","Closed"]),priorities:new Set(["On hold","Minor","Normal","Major","Critical"]),labels:new Set,stages:new Set,users:new Set,includeSelectionTag:!1,updateExtensionsOnImport:!0,strict:!1,includeAllExtensionsOnExport:!0,fallbackVersionOnImport:"2.1",ignoreIncompleteTopicsOnImport:!1,exportCustomDataAsLabels:!1};config=new Wa(this,this.components,"BCF Topics",Ha.uuid);list=new t;documents=new t;onSetup=new re;isSetup=!1;setup(e){if(this.isSetup)return;const t={...this._defaultConfig,...e};this.config.version=t.version,this.config.author=t.author,this.config.types=t.types,this.config.statuses=t.statuses,this.config.priorities=t.priorities,this.config.labels=t.labels,this.config.stages=t.stages,this.config.users=t.users,this.config.includeSelectionTag=t.includeSelectionTag,this.config.updateExtensionsOnImport=t.updateExtensionsOnImport,this.config.strict=t.strict,this.config.includeAllExtensionsOnExport=t.includeAllExtensionsOnExport,this.config.fallbackVersionOnImport=t.fallbackVersionOnImport||"",this.config.ignoreIncompleteTopicsOnImport=t.ignoreIncompleteTopicsOnImport,this.isSetup=!0,this.enabled=!0,this.onSetup.trigger()}onBCFImported=new re;create(e){const t=new ja(this.components);return e?(t.guid=e.guid??t.guid,t.set(e)):this.list.set(t.guid,t),t}onDisposed=new re;dispose(){this.list.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}get usedTypes(){const e=[...this.list].map(([e,t])=>t.type);return new Set(e)}get usedStatuses(){const e=[...this.list].map(([e,t])=>t.status);return new Set(e)}get usedPriorities(){const e=[...this.list].map(([e,t])=>t.priority).filter(e=>e);return new Set(e)}get usedStages(){const e=[...this.list].map(([e,t])=>t.stage).filter(e=>e);return new Set(e)}get usedUsers(){const e=[];for(const[t,i]of this.list){e.push(i.creationAuthor),i.assignedTo&&e.push(i.assignedTo),i.modifiedAuthor&&e.push(i.modifiedAuthor);for(const[t,n]of i.comments)e.push(n.author),n.modifiedAuthor&&e.push(n.modifiedAuthor)}return new Set(e)}get usedLabels(){const e=[];for(const[t,i]of this.list)e.push(...i.labels);return new Set(e)}updateExtensions(){for(const[e,t]of this.list){for(const e of t.labels)this.config.labels.add(e);this.config.types.add(t.type),t.priority&&this.config.priorities.add(t.priority),t.stage&&this.config.stages.add(t.stage),this.config.statuses.add(t.status),this.config.users.add(t.creationAuthor),t.assignedTo&&this.config.users.add(t.assignedTo),t.modifiedAuthor&&this.config.users.add(t.modifiedAuthor);for(const[e,i]of t.comments)this.config.users.add(i.author),i.modifiedAuthor&&this.config.users.add(i.modifiedAuthor)}}updateViewpointReferences(){const e=this.components.get(Ka);for(const[t,i]of this.list)for(const t of i.viewpoints){e.list.has(t)||i.viewpoints.delete(t)}}async export(e=this.list.values()){const t=new Ra,i="3"===this.config.version,n=i?"3.0":this.config.version,s=i?"release_3_0":"release_2_1";t.file("bcf.version",`<?xml version="1.0" encoding="UTF-8"?>\n <Version VersionId="${n}" xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/buildingSMART/BCF-XML/${s}/Schemas/version.xsd"\n xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\n </Version>`);for(const[e,i]of this.documents.entries())"external"!==i.type&&t.file("2.1"===this.config.version?i.fileName:`documents/${e}`,i.data);if("3"===this.config.version){const e=[];for(const[t,i]of this.documents.entries()){const{type:n,description:s}=i;"external"!==n&&e.push(`<Document Guid="${t}">\n <Filename>${i.fileName}</Filename>\n ${s?`<Description>${s}</Description>`:""}\n </Document>`)}e.length>0&&t.file("documents.xml",`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n <DocumentInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="documents.xsd">\n <Documents>\n ${e.join("\n")}\n </Documents>\n </DocumentInfo>`)}t.file("extensions.xml",this.serializeExtensions());const r=this.components.get(Ka);for(const i of e){const e=t.folder(i.guid);e.file("markup.bcf",i.serialize());for(const t of i.viewpoints){const i=r.list.get(t);if(!i)continue;const n=i.title??i.guid;e.file(`${n}.bcfv`,await i.serialize());const s=r.snapshots.get(i.snapshot);if(!s)continue;const o=s?i.snapshot:i.guid,a=r.getSnapshotExtension(i.snapshot);e.file(`${o}.${a}`,s,{binary:!0})}}return await t.generateAsync({type:"blob"})}serializeExtensions(){const e=[...this.config.types].map(e=>`<TopicType>${e}</TopicType>`).join("\n"),t=[...this.config.statuses].map(e=>`<TopicStatus>${e}</TopicStatus>`).join("\n"),i=[...this.config.priorities].map(e=>`<Priority>${e}</Priority>`).join("\n"),n=[...this.config.labels].map(e=>`<TopicLabel>${e}</TopicLabel>`).join("\n"),s=[...this.config.stages].map(e=>`<Stage>${e}</Stage>`).join("\n"),r=[...this.config.users].map(e=>`<User>${e}</User>`).join("\n");return`\n <?xml version="1.0" encoding="UTF-8"?>\n <Extensions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="your-schema-location.xsd">\n ${0!==e.length?`<TopicTypes>\n${e}\n</TopicTypes>`:""}\n ${0!==t.length?`<TopicStatuses>\n${t}\n</TopicStatuses>`:""}\n ${0!==i.length?`<Priorities>\n${i}\n</Priorities>`:""}\n ${0!==n.length?`<TopicLabels>\n${n}\n</TopicLabels>`:""}\n ${0!==s.length?`<Stages>\n${s}\n</Stages>`:""}\n ${0!==r.length?`<Users>\n${r}\n</Users>`:""}\n </Extensions>\n `}processMarkupComment(e){const{Guid:t,Date:i,Author:n,Comment:s,Viewpoint:r}=e;if(!(t&&i&&n&&(Ua||r)))return null;const o=new Ua(this.components,s??"");return o.guid=t,o.date=new Date(i),o.author=n,o.viewpoint=r?.Guid,o.modifiedAuthor=e.ModifiedAuthor,o.modifiedDate=e.ModifiedDate?new Date(e.ModifiedDate):void 0,o}getMarkupComments(e,t){let i;if("2.1"===t&&(i=e.Comment),"3"===t&&(i=e.Topic.Comments?.Comment),!i)return[];i=Array.isArray(i)?i:[i];const n=i.map(e=>this.processMarkupComment(e)).filter(e=>e);return Array.isArray(n)?n:[n]}getMarkupLabels(e,t){let i;if("2.1"===t&&(i=e.Topic.Labels),"3"===t&&(i=e.Topic.Labels?.Label),!i)return[];return Array.isArray(i)?i:[i]}getMarkupViewpoints(e,t){let i;return"2.1"===t&&(i=e.Viewpoints),"3"===t&&(i=e.Topic.Viewpoints?.ViewPoint),i?(i=Array.isArray(i)?i:[i],i):[]}getMarkupRelatedTopics(e,t){let i;if("2.1"===t&&(i=e.Topic.RelatedTopic),"3"===t&&(i=e.Topic.RelatedTopics?.RelatedTopic),!i)return[];return(Array.isArray(i)?i:[i]).map(e=>e.Guid)}getMarkupDocumentReferences(e,t){let i;if("2.1"===t&&(i=e.Topic.DocumentReference),"3"===t&&(i=e.Topic.DocumentReferences?.DocumentReference),!i)return[];return Array.isArray(i)?i:[i]}async load(e){const{fallbackVersionOnImport:t,ignoreIncompleteTopicsOnImport:i,updateExtensionsOnImport:n}=this.config,r=new Ra;await r.loadAsync(e);const o=Object.values(r.files);let a=t;const l=o.find(e=>e.name.endsWith(".version"));if(l){const e=await l.async("string"),t=String(Ha.xmlParser.parse(e).Version.VersionId);a="3.0"===t?"3":t}if(!a||"2.1"!==a&&"3"!==a)throw new Error(`BCFTopics: ${a} is not supported.`);const c=o.find(e=>e.name.endsWith("extensions.xml")||e.name.endsWith(".extensions"));if(n&&c){const e=await c.async("string");$a(this,e)}const h=[],u=this.components.get(Ka),d=o.filter(e=>e.name.endsWith(".bcfv"));for(const e of d){const t=await e.async("string"),i=Ha.xmlParser.parse(t).VisualizationInfo;if(!i){console.warn("Missing VisualizationInfo in Viewpoint");continue}const n={},{Guid:r,ClippingPlanes:o,Components:l,OrthogonalCamera:c,PerspectiveCamera:u}=i;if(r&&(n.guid=r),l){const e={selection:[],coloring:[],visibility:{default_visibility:!1,exceptions:[],view_setup_hints:{spaces_visible:!1,space_boundaries_visible:!1,openings_visible:!1}}};n.components=e;const{Selection:t,Visibility:i}=l;if(t&&t.Component){const i=Array.isArray(t.Component)?t.Component:[t.Component];e.selection=i.map(e=>e.IfcGuid?{ifc_guid:e.IfcGuid}:null).filter(e=>null!==e)}if(i&&"DefaultVisibility"in i&&(e.visibility.default_visibility=i.DefaultVisibility),i&&i.Exceptions&&"Component"in i.Exceptions){const{Component:t}=i.Exceptions,n=Array.isArray(t)?t:[t];e.visibility.exceptions=n.map(e=>e.IfcGuid?{ifc_guid:e.IfcGuid}:null).filter(e=>null!==e)}let s;"2.1"===a&&(s=l.ViewSetupHints),"3"===a&&(s=l.Visibility?.ViewSetupHints),s&&("OpeningsVisible"in s&&(e.visibility.view_setup_hints.openings_visible=s.OpeningsVisible),"SpacesVisible"in s&&(e.visibility.view_setup_hints.spaces_visible=s.SpacesVisible),"SpaceBoundariesVisible"in s&&(e.visibility.view_setup_hints.space_boundaries_visible=s.SpaceBoundariesVisible));const{Coloring:r}=l;if(r&&r.Color){const t=Array.isArray(r.Color)?r.Color:[r.Color];for(const i of t){const{Color:t,Component:n}=i;if(6!==t.length&&8!==t.length)continue;const s=6===t.length?t:t.slice(2),r=(Array.isArray(n)?n:[n]).map(e=>e.IfcGuid?{ifc_guid:e.IfcGuid}:null).filter(e=>null!==e);e.coloring.push({color:s,components:r})}}}if(c||u){const e=i.PerspectiveCamera??i.OrthogonalCamera,{CameraViewPoint:t,CameraDirection:r}=e,o=new s.Vector3(Number(t.X),Number(t.Z),Number(-t.Y)),a=new s.Vector3(Number(r.X),Number(r.Z),Number(-r.Y)),l={camera_view_point:{x:o.x,y:o.y,z:o.z},camera_direction:{x:a.x,y:a.y,z:a.z},aspect_ratio:"AspectRatio"in e?e.AspectRatio:1,camera_up_vector:{x:0,y:0,z:0}};"ViewToWorldScale"in e&&(n.orthogonal_camera={...l,view_to_world_scale:e.ViewToWorldScale}),"FieldOfView"in e&&(n.perspective_camera={...l,field_of_view:e.FieldOfView})}if(o){const e=(Array.isArray(o.ClippingPlane)?o.ClippingPlane:[o.ClippingPlane]).map(({Location:e,Direction:t})=>({location:{x:e.x,y:e.y,z:e.z},direction:{x:t.x,y:t.y,z:t.z}}));n.clipping_planes=e}const d=new Ya(this.components,n);h.push(d)}const p={},f=[],m=o.filter(e=>e.name.endsWith(".bcf"));for(const e of m){const t=await e.async("string"),n=Ha.xmlParser.parse(t).Markup,s=n.Topic,{Guid:r,TopicType:l,TopicStatus:c,Title:h,CreationDate:d,CreationAuthor:m}=s;if(i&&!(r&&l&&c&&h&&d&&m))continue;const g=new ja(this.components);g.guid=r??g.guid;const w=this.getMarkupRelatedTopics(n,a);p[g.guid]=new Set(w),g.type=l??g.type,g.status=c??g.status,g.title=h??g.title,g.creationDate=d?new Date(d):g.creationDate,g.creationAuthor=m??g.creationAuthor,g.serverAssignedId=s.ServerAssignedId,g.priority=s.Priority,g.index=s.Index,g.modifiedDate=s.ModifiedDate?new Date(s.ModifiedDate):void 0,g.modifiedAuthor=s.ModifiedAuthor,g.dueDate=s.DueDate?new Date(s.DueDate):void 0,g.assignedTo=s.AssignedTo,g.description=s.Description,g.stage=s.Stage;const y=this.getMarkupLabels(n,a);for(const e of y)g.labels.add(e);const _=this.getMarkupComments(n,a);for(const e of _)g.comments.set(e.guid,e);const b=this.getMarkupViewpoints(n,a);for(const e of b){if(!e||!e.Guid)continue;const t=u.list.get(e.Guid);if(!t)continue;g.viewpoints.add(t.guid);const i=`${g.guid}/${e.Snapshot}`,n=o.find(({name:e})=>e===i);if(n){const e=await n.async("arraybuffer"),i=new Uint8Array(e);u.snapshots.set(t.guid,i),t.snapshot=t.guid??null}}const v=this.getMarkupDocumentReferences(n,a),x=o.find(e=>"documents.xml"===e.name);let C=[];const S=await(x?.async("string"));if(S){const e=ii.parser.parse(S).DocumentInfo?.Documents?.Document;C=Array.isArray(e)?e:[e]}for(const e of v){const{Description:t,DocumentGuid:i,Url:n,isExternal:s,ReferencedDocument:r}=e;if(i&&C.length>0){const e=C.find(({Guid:e})=>e===i),t=o.find(e=>e.name.endsWith(i)),n=await(t?.async("uint8array"));if(!e||!n)continue;const{Description:s,Filename:r}=e;this.documents.set(i,{type:"internal",fileName:r,description:s,data:n}),g.documentReferences.add(i)}if(n){const e=this.documents.add({type:"external",url:n,description:t});g.documentReferences.add(e)}if(r){let e=null;if(s)e=this.documents.add({type:"external",url:r,description:t});else{const i=r.split("/"),n=i[i.length-1],s=o.find(e=>e.name.endsWith(n)),a=await(s?.async("uint8array"));if(!a)continue;e=this.documents.add({type:"internal",fileName:n,data:a,description:t})}g.documentReferences.add(e)}}this.list.set(g.guid,g),f.push(g)}for(const e in p){const t=this.list.get(e);if(!t)continue;const i=p[e];for(const e of i)t.relatedTopics.add(e)}return this.onBCFImported.trigger(f),{viewpoints:h,topics:f}}}class Ga{onDraggingStarted=new re;onDraggingEnded=new re;onDisposed=new re;normal;origin;three=new s.Plane;components;world;type="default";_title="Clipping Plane";set title(e){this._title=e,this.notifyManager()}get title(){return this._title}_helper;_visible=!0;_enabled=!0;_controlsActive=!1;_arrowBoundBox=new s.Mesh;_planeMesh;_controls;_hiddenMaterial=new s.MeshBasicMaterial({visible:!1});_sizeMultiplier=5;_autoScale=!0;get autoScale(){return this._autoScale}set autoScale(e){this._autoScale=e,e&&this.updateScale()}get enabled(){return this._enabled}set enabled(e){if(this.world.isDisposing)return;if(!this.world.renderer)throw new Error("No renderer found for clipping plane!");this._enabled=e,e?this.visible=this._visibilityBeforeDisabled:(this._visibilityBeforeDisabled=this.visible,this.visible=!1);const t=this.components.get(qa);this.world.renderer.setPlane(e,this.three,t.localClippingPlanes),this.notifyManager()}_visibilityBeforeDisabled=!0;get visible(){return this._visible}set visible(e){this._visible=e,this._controls.getHelper().visible=e,this._helper.visible=e,this.toggleControls(e),this.notifyManager()}get meshes(){return[this._planeMesh,this._arrowBoundBox]}get planeMaterial(){return this._planeMesh.material}set planeMaterial(e){this._planeMesh.material=e}get size(){return this._sizeMultiplier}set size(e){this._sizeMultiplier=e,this.autoScale?this.updateScale():this._planeMesh.scale.set(e,e,e)}get helper(){return this._helper}get controls(){return this._controls}constructor(e,t,i,n,s,r=5,o=!0){if(this.components=e,this.world=t,!t.renderer)throw new Error("The given world must have a renderer!");this.normal=n,this.origin=i,this._sizeMultiplier=r;const a=e.get(qa);t.renderer.setPlane(!0,this.three,a.localClippingPlanes),this._planeMesh=Ga.newPlaneMesh(r,s),this._helper=this.newHelper(),this._controls=this.newTransformControls(),this.three.setFromNormalAndCoplanarPoint(n,i),o&&this.toggleControls(!0),this.updateScale(),t.camera?.controls&&t.camera.controls.addEventListener("update",this.updateScale)}notifyManager=()=>{const e=this.components.get(qa),t=e.list.getKey(this);t&&e.list.set(t,this)};setFromNormalAndCoplanarPoint(e,t){this.reset(),this.normal.equals(e)||(this.normal.copy(e),this._helper.lookAt(e)),this.origin.copy(t),this._helper.position.copy(t),this._helper.updateMatrix(),this.update()}update=()=>{this._enabled&&(this.three.setFromNormalAndCoplanarPoint(this.normal,this._helper.position),this.updateScale())};updateScale=()=>{if(!this.autoScale)return;const e=this.world.camera?.three;if(!e)return;if(!(e instanceof s.PerspectiveCamera))return;const t=new s.Vector3;e.getWorldPosition(t);const i=t.distanceTo(this._helper.position)/7*this._sizeMultiplier;this._planeMesh.scale.set(i,i,i)};dispose(){this._enabled=!1,!this.world.isDisposing&&this.world.camera?.controls&&this.world.camera.controls.removeEventListener("update",this.updateScale),this.onDraggingStarted.reset(),this.onDraggingEnded.reset(),this._helper.removeFromParent(),this.world.renderer&&this.world.renderer.setPlane(!1,this.three),this._arrowBoundBox.removeFromParent(),this._arrowBoundBox.geometry.dispose(),this._planeMesh.geometry.dispose(),this._controls.getHelper().removeFromParent(),this._controls.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}reset(){const e=new s.Vector3(1,0,0),t=new s.Vector3;this.normal.equals(e)||(this.normal.copy(e),this._helper.lookAt(e)),this.origin.copy(t),this._helper.position.copy(t),this._helper.updateMatrix()}toggleControls(e){if(e){if(this._controlsActive)return;this._controls.addEventListener("change",this.update),this._controls.addEventListener("dragging-changed",this.changeDrag)}else this._controls.removeEventListener("change",this.update),this._controls.removeEventListener("dragging-changed",this.changeDrag);this._controlsActive=e}newTransformControls(){if(!this.world.renderer)throw new Error("No renderer found for clipping plane!");const e=this.world.camera.three,t=this.world.renderer.three.domElement,i=new se(e,t);return this.initializeControls(i),this.world.scene.three.add(i.getHelper()),i}initializeControls(e){e.attach(this._helper),e.showX=!1,e.showY=!1,e.setSpace("local"),this.createArrowBoundingBox(),e.getHelper().children[0].children[0].add(this._arrowBoundBox)}createArrowBoundingBox(){this._arrowBoundBox.geometry=new s.CylinderGeometry(.18,.18,1.2),this._arrowBoundBox.material=this._hiddenMaterial,this._arrowBoundBox.rotateX(Math.PI/2),this._arrowBoundBox.updateMatrix(),this._arrowBoundBox.geometry.applyMatrix4(this._arrowBoundBox.matrix)}changeDrag=e=>{this._visible=!e.value,this.preventCameraMovement(),this.notifyDraggingChanged(e)};notifyDraggingChanged(e){e.value?this.onDraggingStarted.trigger():this.onDraggingEnded.trigger()}preventCameraMovement(){this.world.camera.enabled=this._visible}newHelper(){const e=new s.Object3D;return e.lookAt(this.normal),e.position.copy(this.origin),this._planeMesh.position.z+=.01,e.add(this._planeMesh),this.world.scene.three.add(e),e}static newPlaneMesh(e,t){const i=new s.PlaneGeometry(1),n=new s.Mesh(i,t);return n.scale.set(e,e,e),n}}class Za extends li{_config={enabled:{value:!0,type:"Boolean"},visible:{value:!0,type:"Boolean"},color:{value:new s.Color,type:"Color"},opacity:{type:"Number",interpolable:!0,value:1,min:0,max:1},size:{type:"Number",interpolable:!0,value:2,min:0,max:100}};get enabled(){return this._config.enabled.value}set enabled(e){this._config.enabled.value=e,this._component.enabled=e}get visible(){return this._config.visible.value}set visible(e){this._config.visible.value=e,this._component.visible=e}get color(){return this._config.color.value}set color(e){this._config.color.value=e,this._component.material.color.copy(e)}get opacity(){return this._config.opacity.value}set opacity(e){this._config.opacity.value=e,this._component.material.opacity=e}get size(){return this._config.size.value}set size(e){this._config.size.value=e,this._component.size=e}}class qa extends le{static uuid="66290bc5-18c4-4cd1-9379-2e17a0617611";onSetup=new re;onBeforeDrag=new re;onAfterDrag=new re;onBeforeCreate=new re;onBeforeCancel=new re;onAfterCancel=new re;onBeforeDelete=new re;onAfterCreate=new re;onAfterDelete=new re;onDisposed=new re;isSetup=!1;orthogonalY=!1;toleranceOrthogonalY=.7;autoScalePlanes=!0;_localClippingPlanes=!1;get localClippingPlanes(){return this._localClippingPlanes}set localClippingPlanes(e){this._localClippingPlanes=e;const t=this.components.get(Aa);for(const[,i]of t.list)i.renderer&&(i.renderer.localClippingPlanes=e)}Type=Ga;list=new e.DataMap;_deleting=new Map;config=new Za(this,this.components,"Clipper",qa.uuid);_defaultConfig={color:new s.Color(12255487),opacity:.2,size:2};_material=new s.MeshBasicMaterial({color:12255487,side:s.DoubleSide,transparent:!0,opacity:.2});_size=5;_enabled=!1;_visible=!0;onStateChanged=new re;get enabled(){return this._enabled}set enabled(e){this._enabled=e,this.onStateChanged.trigger(["enabled"])}get visible(){return this._visible}set visible(e){this._visible=e;for(const[t,i]of this.list)i.visible=e;this.onStateChanged.trigger(["visibility"])}get material(){return this._material}set material(e){this._material=e;for(const[t,i]of this.list)i.planeMaterial=e;this.onStateChanged.trigger(["material"])}get size(){return this._size}set size(e){this._size=e;for(const[t,i]of this.list)i.size=e;this.onStateChanged.trigger(["size"])}constructor(e){super(e),this.components.add(qa.uuid,this),this.setEvents()}setEvents(){this.list.onBeforeDelete.add(({key:e,value:t})=>{if(this.onBeforeDelete.trigger(),!t.world.renderer)throw new Error("Renderer not found for this plane's world!");this._deleting.set(e,t),t.world.renderer.setPlane(!1,t.three),t.dispose()}),this.list.onItemDeleted.add(e=>{const t=this._deleting.get(e);this._deleting.delete(e),this.updateMaterialsAndPlanes(),t&&this.onAfterDelete.trigger(t)}),this.list.onCleared.add(()=>{const e=[...this._deleting.values()];this._deleting.clear(),this.updateMaterialsAndPlanes();for(const t of e)this.onAfterDelete.trigger(t)});const e=this.components.get(hr);if(e.initialized)this.subscribeToFragmentMaterials();else{const t=()=>{e.onFragmentsLoaded.remove(t),this.subscribeToFragmentMaterials()};e.onFragmentsLoaded.add(t)}}subscribeToFragmentMaterials(){const e=this.components.get(hr);for(const[,t]of e.core.models.materials.list)this.applyClippingToFragmentMaterial(t);e.core.models.materials.list.onItemSet.add(({value:e})=>{this.applyClippingToFragmentMaterial(e)})}applyClippingToFragmentMaterial(e){if(!this.localClippingPlanes)return;const t=this.components.get(Aa);for(const[,i]of t.list)if(i.renderer)return void(e.clippingPlanes=i.renderer.clippingPlanes)}dispose(){this._enabled=!1;this.components.get(ci).list.delete(this.config.uuid),this.list.clear(),this._material.dispose(),this.onBeforeCreate.reset(),this.onBeforeCancel.reset(),this.onBeforeDelete.reset(),this.onBeforeDrag.reset(),this.onAfterCreate.reset(),this.onAfterCancel.reset(),this.onAfterDelete.reset(),this.onAfterDrag.reset(),this.onDisposed.trigger(qa.uuid),this.onDisposed.reset()}async create(e){const t=this.components.get(fa).get(e),i=await t.castRay();return i?this.createPlaneFromIntersection(e,i):null}createFromNormalAndCoplanarPoint(e,t,i){const n=this.newPlane(e,i,t);return this.updateMaterialsAndPlanes(),n}async delete(e,t){if(!t){const i=await this.pickPlane(e);if(!i)return;t=this.list.getKey(i)}t&&this.list.delete(t)}deleteAll(e){for(const[t,i]of this.list)e&&!e.has(i.type)||this.list.delete(t)}setup(e){const t={...this._defaultConfig,...e};this.config.color=t.color,this.config.opacity=t.opacity,this.config.size=t.size,this.isSetup=!0,this.onSetup.trigger()}pickPlane(e){const t=this.components.get(fa).get(e),i=this.getAllPlaneMeshes(),n=t.castRayToObjects(i);if(n){const e=n.object;return[...this.list.values()].find(t=>t.meshes.includes(e))}}getAllPlaneMeshes(){const e=[];for(const[t,i]of this.list)e.push(...i.meshes);return e}createPlaneFromIntersection(e,t){if(!e.renderer)throw new Error("The given world must have a renderer!");const i=t.point.distanceTo(new s.Vector3(0,0,0)),n=t.normal||t.face?.normal;if(!i||!n)return null;const r=this.getWorldNormal(t,n),o=this.newPlane(e,t.point,r.negate()),a=this.list.get(o);return a.visible=this._visible,a.size=this._size,e.renderer.setPlane(!0,a.three,this.localClippingPlanes),this.updateMaterialsAndPlanes(),a}getWorldNormal(e,t){const i=e.object;let n=e.object.matrixWorld.clone();if(i instanceof s.InstancedMesh&&void 0!==e.instanceId){const t=new s.Matrix4;i.getMatrixAt(e.instanceId,t),n=t.multiply(n)}const r=(new s.Matrix3).getNormalMatrix(n),o=t.clone().applyMatrix3(r).normalize();return this.normalizePlaneDirectionY(o),o}normalizePlaneDirectionY(e){this.orthogonalY&&(e.y>this.toleranceOrthogonalY&&(e.x=0,e.y=1,e.z=0),e.y<-this.toleranceOrthogonalY&&(e.x=0,e.y=-1,e.z=0))}newPlane(e,t,i){const n=new this.Type(this.components,e,t,i,this._material);n.autoScale=this.autoScalePlanes,n.onDraggingStarted.add(()=>this.onBeforeDrag.trigger(n)),n.onDraggingEnded.add(()=>this.onAfterDrag.trigger(n));const s=me.create();return this.list.set(s,n),this.onAfterCreate.trigger(n),s}updateMaterialsAndPlanes(){const e=this.components.get(Aa);for(const[t,i]of e.list){if(!i.renderer)continue;i.renderer.updateClippingPlanes();const{clippingPlanes:e}=i.renderer;for(const t of i.meshes)if(t.material)if(Array.isArray(t.material))for(const i of t.material)i.clippingPlanes=e;else t.material.clippingPlanes=e}}}class Ya{title;guid=me.create();clippingPlanes=new e.DataSet;camera={aspect_ratio:1,field_of_view:60,camera_direction:{x:0,y:0,z:0},camera_view_point:{x:0,y:0,z:0},camera_up_vector:{x:0,y:1,z:0}};customData={};exceptionComponents=new e.DataSet;selectionComponents=new e.DataSet;componentColors=new e.DataMap;spacesVisible=!1;spaceBoundariesVisible=!1;openingsVisible=!1;defaultVisibility=!0;snapshot=this.guid;async getSelectionMap(){const e=this._components.get(hr);return await e.guidsToModelIdMap([...this.selectionComponents])}async getExceptionMap(){const e=this._components.get(hr);return await e.guidsToModelIdMap([...this.exceptionComponents])}get projection(){return"field_of_view"in this.camera?"Perspective":"Orthographic"}get position(){const e=this._components.get(hr),{camera_view_point:t}=this.camera,{x:i,y:n,z:r}=t,o=new s.Vector3(i,n,r);return e.applyBaseCoordinateSystem(o,new s.Matrix4),o}set position(e){const t=e.clone(),i=this._components.get(hr);e.clone().applyMatrix4(i.baseCoordinationMatrix.clone().invert()),this.camera.camera_view_point={x:t.x,y:t.y,z:t.z}}get direction(){const{camera_direction:e}=this.camera,{x:t,y:i,z:n}=e;return new s.Vector3(t,i,n)}_components;_world=null;set world(e){this._world=e}get world(){return this._world}get _managerVersion(){return this._components.get(Ha).config.version}get topics(){return[...this._components.get(Ha).list.values()].filter(e=>e.viewpoints.has(this.guid))}constructor(e,t){this._components=e,t&&(this.guid=t.guid??this.guid,this.set(t)),this.setEvents()}notifyUpdate=()=>{this._components.get(Ka).list.set(this.guid,this)};setEvents(){this.selectionComponents.onUpdated.add(this.notifyUpdate),this.exceptionComponents.onUpdated.add(this.notifyUpdate),this.clippingPlanes.onUpdated.add(this.notifyUpdate),this.componentColors.onItemSet.add(this.notifyUpdate),this.componentColors.onItemDeleted.add(this.notifyUpdate),this.componentColors.onItemUpdated.add(this.notifyUpdate),this.componentColors.onCleared.add(this.notifyUpdate)}set(e){this.title=e.title;const{components:t,perspective_camera:i,orthogonal_camera:n,clipping_planes:r}=e;if(t){const{selection:e,visibility:i,coloring:n}=t;if(e){this.selectionComponents.clear();for(const{ifc_guid:t}of e)t&&this.selectionComponents.add(t)}if(i){const{default_visibility:e,exceptions:t,view_setup_hints:n}=i;if(void 0!==e&&(this.defaultVisibility=e),t){this.exceptionComponents.clear();for(const{ifc_guid:e}of t)e&&this.exceptionComponents.add(e)}if(n){const{spaces_visible:e,space_boundaries_visible:t,openings_visible:i}=n;void 0!==e&&(this.spacesVisible=e),void 0!==t&&(this.spaceBoundariesVisible=t),void 0!==i&&(this.openingsVisible=i)}}if(n){this.componentColors.clear();for(const e of n){const{color:t,components:i}=e,n=i.map(e=>e.ifc_guid).filter(e=>null!==e);this.componentColors.set(t,n)}}}if((i||n)&&(this.camera=i??n),r&&this.world){const e=this._components.get(qa);for(const t of r){const{location:i,direction:n}=t,r=new s.Vector3(i.x,i.z,-i.y),o=new s.Vector3(n.x,n.z,-n.y),a=e.createFromNormalAndCoplanarPoint(this.world,o,r);this.clippingPlanes.add(a),e.list.get(a).enabled=!1,e.list.get(a).visible=!1}}this.notifyUpdate()}async go(e){if(!this.world)return;const{camera:t}=this.world;if(!(t instanceof Ba))throw new Error("Viewpoint: the world's camera component must be of type OrthoPerspectiveCamera to switch between perspective and orthographic projections.");const{transition:i,applyClippings:n,applyVisibility:r,clippingsVisibility:o}={transition:!0,applyClippings:!0,applyVisibility:!0,clippingsVisibility:!0,...e};t.projection.set(this.projection);const a=new s.Vector3(this.camera.camera_view_point.x,this.camera.camera_view_point.y,this.camera.camera_view_point.z),l=new s.Vector3(this.camera.camera_direction.x,this.camera.camera_direction.y,this.camera.camera_direction.z);if(a.equals(new s.Vector3)&&l.equals(new s.Vector3))return;const c=this.position,h=this.direction,u={x:c.x+80*h.x,y:c.y+80*h.y,z:c.z+80*h.z},d=[];n&&this.setClippingState(!0),r&&d.push(this.applyVisibility()),this.setClippingVisibility(o),d.push(t.controls.setLookAt(c.x,c.y,c.z,u.x,u.y,u.z,i)),await Promise.all(d)}async updateCamera(e=!0){return new Promise(t=>{if(!this.world)return void t(!1);const{camera:i,renderer:n}=this.world;if(!n)throw new Error("Viewpoint: the world needs to have a renderer!");if(!i.hasCameraControls())throw new Error("Viewpoint: world's camera need camera controls!");const r=i.three,o=r.getWorldPosition(new s.Vector3),a=r.getWorldDirection(new s.Vector3),{width:l,height:c}=n.getSize();let h=l/c;Number.isNaN(h)&&(h=1);const u=this._components.get(hr);o.applyMatrix4(u.baseCoordinationMatrix.clone().invert());const d={aspect_ratio:h,camera_view_point:{x:o.x,y:o.y,z:o.z},camera_direction:{x:a.x,y:a.y,z:a.z},camera_up_vector:{x:0,y:1,z:0}};if(r instanceof s.PerspectiveCamera?this.camera={...d,field_of_view:r.fov}:r instanceof s.OrthographicCamera&&(this.camera={...d,view_to_world_scale:r.top-r.bottom}),e){const e=this._components.get(Ka),s=n.three.domElement;n.three.render(this.world.scene.three,i.three),s.toBlob(async i=>{if(i){const t=await i.arrayBuffer(),n=new Uint8Array(t);e.snapshots.set(this.guid,n)}this.notifyUpdate(),t(!0)})}else this.notifyUpdate(),t(!0)})}takeSnapshot(){return new Promise(e=>{if(!this.world)return void e(!1);const{camera:t,renderer:i}=this.world;if(!i)throw new Error("Viewpoint: the world needs to have a renderer!");const n=this._components.get(Ka),s=i.three.domElement;i.three.render(this.world.scene.three,t.three),s.toBlob(async t=>{if(t){const e=await t.arrayBuffer(),i=new Uint8Array(e);n.snapshots.set(this.guid,i)}this.notifyUpdate(),e(!0)})})}updateClippingPlanes(){this.clippingPlanes.clear();const e=this._components.get(qa);for(const[t,i]of e.list)i.enabled&&this.clippingPlanes.add(t)}async applyVisibility(){const e=this._components.get(Io);e.set(this.defaultVisibility);const t=await this.getExceptionMap();e.set(!this.defaultVisibility,t);const i=await this.getSelectionMap();e.set(!0,i)}async setColorizationState(t){const i=this._components.get(hr),n=[];if(t)for(const[t,r]of this.componentColors){const o=`#${t}`,a=await i.guidsToModelIdMap(r);for(const[t,r]of Object.entries(a)){const a=i.list.get(t);a&&n.push(a.highlight([...r],{customId:o,color:new s.Color(o),renderedFaces:e.RenderedFaces.ONE,opacity:1,transparent:!1}))}}else for(const[e,t]of this.componentColors){const e=await i.guidsToModelIdMap(t);for(const[t,s]of Object.entries(e)){const e=i.list.get(t);e&&n.push(e.resetHighlight([...s]))}}n.push(i.core.update(!0)),await Promise.all(n)}setClippingState(e){const t=this._components.get(qa);for(const[i,n]of t.list)n.enabled=e&&this.clippingPlanes.has(i)}setClippingVisibility(e){const t=this._components.get(qa);for(const i of this.clippingPlanes){const n=t.list.get(i);n&&(n.visible=e)}}async createComponentTags(e){const t=this._components.get(hr);let i="";if(this._components.get(Ha).config.includeSelectionTag){const n="selection"===e?await this.getSelectionMap():await this.getExceptionMap();for(const e in n){const s=t.list.get(e);if(!s)continue;const r=n[e];for(const e of r){const t=s.getItem(e),n=await t.getGuid();if(!n)continue;const r=(await t.getAttributes())?.getValue("Tag");let o=null;r&&(o=`AuthoringToolId="${r}"`),i+=`\n<Component IfcGuid="${n}" ${o??""} />`}}}else i=[...this.selectionComponents].map(e=>`<Component IfcGuid="${e}" />`).join("\n");return i}createColorTags(){let e="";for(const[t,i]of this.componentColors.entries()){e+=`<Color Color="${t}">\n${i.map(e=>`\n<Component IfcGuid="${e}" />`).join("\n")}\n</Color>`}return 0!==e.length?`<Coloring>\n${e}\n</Coloring>`:"<Coloring />"}toJSON(){const e=this._components.get(qa),t={guid:this.guid,components:{selection:[...this.selectionComponents].map(e=>({ifc_guid:e,authoring_tool_id:null})),coloring:[...this.componentColors].map(([e,t])=>({color:e,components:t.map(e=>({ifc_guid:e,authoring_tool_id:null}))})),visibility:{default_visibility:this.defaultVisibility,exceptions:[...this.exceptionComponents].map(e=>({ifc_guid:e,authoring_tool_id:null})),view_setup_hints:{spaces_visible:this.spacesVisible,space_boundaries_visible:this.spaceBoundariesVisible,openings_visible:this.openingsVisible}}},clipping_planes:[...this.clippingPlanes].map(t=>{const i=e.list.get(t);if(!i)return null;const n=i._controls.worldPosition??i.origin,{normal:s}=i;return{location:{x:n.x,y:-n.z,z:n.y},direction:{x:s.x,y:-s.z,z:s.y}}}).filter(e=>null!==e)};"field_of_view"in this.camera?t.perspective_camera=this.camera:t.orthogonal_camera=this.camera;const i=this._components.get(Ka),n=i.snapshots.get(this.snapshot);if(n){const e=n.toString(),s=btoa(e),r=i.getSnapshotExtension(this.snapshot);t.snapshot={snapshot_type:r,snapshot_data:s}}return t}async serialize(e=this._managerVersion){const t=this._components.get(hr),i=this.position;i.applyMatrix4(t.baseCoordinationMatrix.clone().invert());const n=this.direction;n.normalize();const r=(new s.Matrix4).makeRotationX(Math.PI/2),o=n.clone().applyMatrix4(r);o.normalize();const a=`<CameraViewPoint>\n <X>${i.x}</X>\n <Y>${-i.z}</Y>\n <Z>${i.y}</Z>\n </CameraViewPoint>`,l=`<CameraDirection>\n <X>${n.x}</X>\n <Y>${-n.z}</Y>\n <Z>${n.y}</Z>\n </CameraDirection>`,c=`<CameraUpVector>\n <X>${o.x}</X>\n <Y>${-o.z}</Y>\n <Z>${o.y}</Z>\n </CameraUpVector>`,h=`<AspectRatio>${this.camera.aspect_ratio}</AspectRatio>`;let u="";"view_to_world_scale"in this.camera?u=`<OrthogonalCamera>\n ${a}\n ${l}\n ${c}\n ${h}\n <ViewToWorldScale>${this.camera.view_to_world_scale}</ViewToWorldScale>\n </OrthogonalCamera>`:"field_of_view"in this.camera&&(u=`<PerspectiveCamera>\n ${a}\n ${l}\n ${c}\n ${h}\n <FieldOfView>${this.camera.field_of_view}</FieldOfView>\n </PerspectiveCamera>`);const d=`<ViewSetupHints SpacesVisible="${this.spacesVisible??!1}" SpaceBoundariesVisible="${this.spaceBoundariesVisible??!1}" OpeningsVisible="${this.openingsVisible??!1}" />`,p=(await this.createComponentTags("selection")).trim(),f=(await this.createComponentTags("exception")).trim(),m=this.createColorTags();return`<?xml version="1.0" encoding="UTF-8"?>\n <VisualizationInfo Guid="${this.guid}">\n <Components>\n ${"2.1"===e?d:""}\n ${0!==p.length?`<Selection>${p}</Selection>`:""}\n <Visibility DefaultVisibility="${this.defaultVisibility}">\n ${"3"===e?d:""}\n ${0!==f.length?`<Exceptions>${f}</Exceptions>`:""}\n </Visibility>\n ${m}\n </Components>\n ${u}\n </VisualizationInfo>`}}class Xa extends li{_config={overwriteColors:{value:!1,type:"Boolean"}};get overwriteColors(){return this._config.overwriteColors.value}set overwriteColors(e){this._config.overwriteColors.value=e}}class Ka extends le{static uuid="ee867824-a796-408d-8aa0-4e5962a83c66";enabled=!0;world=null;list=new t;snapshots=new t;create(e){const t=new Ya(this.components,e);return t.world=this.world,e||this.list.set(t.guid,t),t}constructor(e){super(e),e.add(Ka.uuid,this)}getSnapshotExtension(e){let t="jpeg";const i=this.snapshots.get(e);if(!i)return t;const n=i.subarray(0,4);let s="";for(let e=0;e<n.length;e++)s+=n[e].toString(16);return s.startsWith("89504e47")&&(t="png"),s.startsWith("ffd8ffe")&&(t="jpeg"),t}isSetup=!1;setup(){}onSetup=new re;config=new Xa(this,this.components,"Viewpoints",Ka.uuid);onDisposed=new re;dispose(){this.list.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}}class Qa{_components;_cameraOffset=10;_planeHelper;_farPlaneHelper;_cameraHelper;get _planeNormalOpposite(){return this.plane.normal.clone().negate()}get _planePosition(){return this.plane.normal.clone().multiplyScalar(-this.plane.constant)}get _cameraPosition(){return this._planePosition.addScaledVector(this._planeNormalOpposite,this._cameraOffset)}onStateChanged=new re;onUpdated=new re;onDisposed=new re;camera;plane=new s.Plane;farPlane=new s.Plane;id=me.create();_open=!1;set open(e){this._open=e,this.onStateChanged.trigger(["open"])}get open(){return this._open}set planeHelperColor(e){!Array.isArray(this._planeHelper.material)&&"color"in this._planeHelper.material&&this._planeHelper.material.color instanceof s.Color&&(this._planeHelper.material.color=e)}set farPlaneHelperColor(e){!Array.isArray(this._farPlaneHelper.material)&&"color"in this._farPlaneHelper.material&&this._farPlaneHelper.material.color instanceof s.Color&&(this._farPlaneHelper.material.color=e)}_range=Ja.defaultRange;set range(e){this._range=e,this.update()}get range(){return this._range}set distance(e){this.plane.constant=e,this.update()}get distance(){return this.plane.constant}_world=null;set world(e){this._world=e,this.camera.currentWorld=e,e&&(this.camera.projection.set("Orthographic"),this.camera.set("Plan"),this.camera.controls.dollySpeed=6,this.camera.controls.restThreshold=.005,this.update())}get world(){return this._world}_helpersVisible=!1;set helpersVisible(e){if(!e)return this._helpersVisible=e,this._planeHelper.removeFromParent(),this._farPlaneHelper.removeFromParent(),void this._cameraHelper.removeFromParent();this.world&&(this._helpersVisible=e,this.world.scene.three.add(this._planeHelper,this._farPlaneHelper))}get helpersVisible(){return this._helpersVisible}_planesEnabled=!1;set planesEnabled(e){const{world:t}=this;if(!t)return;const{renderer:i}=t;i&&(i.setPlane(e,this.plane),i.setPlane(e,this.farPlane),this._planesEnabled=e)}get planesEnabled(){return this._planesEnabled}constructor(e,t){this._components=e,this.camera=new Ba(this._components);const{threeOrtho:i}=this.camera;if(t?.id&&(this.id=t.id),t?.normal&&t?.point){const{normal:e,point:i}=t;this.plane.setFromNormalAndCoplanarPoint(e,i)}this._cameraHelper=new s.CameraHelper(i),this._planeHelper=new s.PlaneHelper(this.plane,50),this._farPlaneHelper=new s.PlaneHelper(this.farPlane,50),this.farPlaneHelperColor=new s.Color("blue"),this.update()}dispose(){this.helpersVisible=!1;const e=this._components.get(de);e.destroy(this._planeHelper),e.destroy(this._farPlaneHelper),e.destroy(this._cameraHelper),this.camera.dispose(),this.onDisposed.trigger()}update(){if(this.world){const e=this._cameraPosition,t=this._planePosition;this.camera.controls.setLookAt(e.x,e.y,e.z,t.x,t.y,t.z,!1)}this.farPlane.normal.copy(this._planeNormalOpposite),this.farPlane.constant=this.range-this.plane.constant,this.onUpdated.trigger()}flip(){this.plane.normal.negate(),this.update()}}class Ja extends le{static uuid="fb22f1f5-6598-4664-a11d-de8963ae420f";static defaultRange=15;list=new t;enabled=!0;world=null;_fragmentsUpdateEvent=()=>{this.components.get(hr).core.update(!0)};restoreCameraOnClose=!0;_restoreState=null;get hasOpenViews(){return[...this.list.values()].some(e=>e.open)}constructor(e){super(e),e.add(Ja.uuid,this),this.setupEvents()}setupEvents(){this.list.onBeforeDelete.add(({key:e,value:t})=>{t.open&&this.close(e),t.dispose()})}create(e,t,i){const n=new Qa(this.components,{id:i?.id,normal:e,point:t});return n.world=i?.world??this.world,this.list.set(n.id,n),n}createFromPlane(e,t){const i=new Qa(this.components,{id:t?.id});return i.plane.copy(e),i.update(),i.world=t?.world??this.world,this.list.set(i.id,i),i}async createFromIfcStoreys(e){const t=[],i=this.components.get(hr),n=void 0===e?.offset?.25:e.offset;for(const[r,o]of i.list){if(e&&e.modelIds&&!e.modelIds.some(e=>e.test(r)))continue;const i=Object.values(await o.getItemsOfCategories([/BUILDINGSTOREY/])).flat();if(0===i.length)continue;const a=await o.getItemsData(i),[,l]=await o.getCoordinates(),c=new s.Vector3(0,-1,0);for(const i of a){if(!(i.Name&&"value"in i.Name&&i.Elevation&&"value"in i.Elevation)){const e=i._localId&&"value"in i._localId?i._localId.value:"unknown";console.warn(`[Views] Storey ${e} of model "${r}" has no Name or no Elevation value. Skipping it: no view will be created for it.`);continue}const{value:o}=i.Name;if(e?.storeyNames&&!e.storeyNames.some(e=>e.test(o)))continue;const a=i.Elevation.value+l+n,h=new s.Plane(c,a),u=this.createFromPlane(h,{id:o,world:e?.world});t.push(u)}}return t}createElevations(e){const t=[],i=this.components.get(hr),n=void 0!==e?.combine&&e.combine,r=e?.namingCallback??(e=>({front:""+(n?"Front":`${e}: Front`),back:""+(n?"Back":`${e}: Back`),left:""+(n?"Left":`${e}: Left`),right:""+(n?"Right":`${e}: Right`)}));let o=[];for(const[t,n]of i.list)e&&e.modelIds&&!e.modelIds.some(e=>e.test(t))||o.push({id:t,box:n.box});if(0===o.length)return t;if(n){const e=this.components.get(zo);e.list.clear(),e.list.add(...o.map(e=>e.box));o=[{id:"combined",box:e.get()}]}for(const{id:i,box:n}of o){const{min:o,max:a}=n,l=Math.abs(a.x-o.x),c=Math.abs(a.z-o.z),h=new s.Vector3;n.getCenter(h);const u=new s.Plane(new s.Vector3(0,0,-1),a.z),d=new s.Plane(new s.Vector3(0,0,1),-o.z),p=new s.Plane(new s.Vector3(-1,0,0),a.x),f=new s.Plane(new s.Vector3(1,0,0),-o.x),{front:m,back:g,left:w,right:y}=r(i),_=this.createFromPlane(u,{id:m,world:e?.world});_.range=c;const b=this.createFromPlane(d,{id:g,world:e?.world});b.range=c;const v=this.createFromPlane(p,{id:w,world:e?.world});v.range=l;const x=this.createFromPlane(f,{id:y,world:e?.world});x.range=l,t.push(_,b,v,x)}return t}open(e){const t=this.list.get(e);if(!t)throw new Error(`Views: the view with id ${e} doesn't exist.`);if(t.open)return;const{world:i}=t;if(!i)throw new Error(`Views: no world found for view with id ${e}.`);const{renderer:n}=i;if(!n)throw new Error(`Views: no renderer found for world with id ${i.uuid}.`);for(const[,e]of this.list)e.world===i&&this.close(e.id);this.restoreCameraOnClose&&i.camera!==t.camera&&!this._restoreState&&i.camera.controls&&(this._restoreState={camera:i.camera,json:i.camera.controls.toJSON()}),n.setPlane(!0,t.plane),n.setPlane(!0,t.farPlane),this.setOnlyEnabledControls(i,t),t.camera.controls.addEventListener("rest",this._fragmentsUpdateEvent),i.camera=t.camera,t.open=!0}close(e){let t;if(t=e?this.list.get(e):[...this.list.values()].find(e=>e.open),e&&!t)throw new Error(`Views: the view with id ${e} doesn't exist.`);if(!t)return;if(!t.open)return;const{world:i}=t;if(!i)throw new Error(`Views: no world found for view with id ${e}.`);const{renderer:n}=i;if(!n)throw new Error(`Views: no renderer found for world with id ${i.uuid}.`);if(n.setPlane(!1,t.plane),n.setPlane(!1,t.farPlane),t.camera.controls.removeEventListener("rest",this._fragmentsUpdateEvent),i.useDefaultCamera(),t.open=!1,this.setOnlyEnabledControls(i,null),this.restoreCameraOnClose&&this._restoreState){const{camera:e,json:t}=this._restoreState;e===i.camera&&e.controls&&e.controls.fromJSON(t,!1),this._restoreState=null}}setOnlyEnabledControls(e,t){const i=t?t.camera:e.defaultCamera,n=(e,t)=>{e.controls&&(e.controls.enabled=t)};n(i,!0),i!==e.defaultCamera&&n(e.defaultCamera,!1);for(const[,t]of this.list)t.world===e&&t.camera!==i&&n(t.camera,!1)}}async function el(e,t,i,n,s,r,o){const a=e.fenceSync(e.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),await function(e,t,i,n){return new Promise((s,r)=>{!function o(){const a=e.clientWaitSync(t,i,0);a!==e.WAIT_FAILED?a!==e.TIMEOUT_EXPIRED?s():setTimeout(o,n):r()}()})}(e,a,0,10),e.deleteSync(a),e.bindBuffer(t,i),e.getBufferSubData(t,n,s,r,o),e.bindBuffer(t,null)}class tl{onDisposed=new re;onDistanceComputed=new re;excludedObjects=new Set;enabled=!0;renderDebugFrame=!1;components;scene=new s.Scene;camera=new s.OrthographicCamera(-1,1,1,-1,0,1);depthMaterial;world;worker;_width=512;_height=512;_postQuad;tempRT;resultRT;bufferSize;_buffer;_isWorkerBusy=!1;constructor(e,t){if(!t.renderer)throw new Error("The given world must have a renderer!");this.components=e,this.world=t;const i=t.camera.three;this.tempRT=new s.WebGLRenderTarget(this._width,this._height),this.bufferSize=this._width*this._height*4,this._buffer=new Uint8Array(this.bufferSize),this.tempRT.texture.minFilter=s.NearestFilter,this.tempRT.texture.magFilter=s.NearestFilter,this.tempRT.stencilBuffer=!1,this.tempRT.samples=0,this.tempRT.depthTexture=new s.DepthTexture(this._width,this._height),this.tempRT.depthTexture.format=s.DepthFormat,this.tempRT.depthTexture.type=s.UnsignedShortType,this.resultRT=new s.WebGLRenderTarget(this._width,this._height),this.depthMaterial=new s.ShaderMaterial({vertexShader:"\nvarying vec2 vUv;\n\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n ",fragmentShader:"\n#include <packing>\n\nvarying vec2 vUv;\nuniform sampler2D tDiffuse;\nuniform sampler2D tDepth;\nuniform float cameraNear;\nuniform float cameraFar;\n\n\nfloat readDepth( sampler2D depthSampler, vec2 coord ) {\n float fragCoordZ = texture2D( depthSampler, coord ).x;\n float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar );\n return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );\n}\n\nvoid main() {\n //vec3 diffuse = texture2D( tDiffuse, vUv ).rgb;\n float depth = readDepth( tDepth, vUv );\n\n gl_FragColor.rgb = 1.0 - vec3( depth );\n gl_FragColor.a = 1.0;\n}\n ",uniforms:{cameraNear:{value:i.near},cameraFar:{value:i.far},tDiffuse:{value:null},tDepth:{value:null}}});const n=new s.PlaneGeometry(2,2);this._postQuad=new s.Mesh(n,this.depthMaterial),this.scene.add(this._postQuad);const r=new Blob(['\n addEventListener("message", (event) => {\n const { buffer } = event.data;\n const colors = new Set();\n for (let i = 0; i < buffer.length; i += 4) {\n const r = buffer[i];\n colors.add(r);\n }\n postMessage({ colors });\n });\n '],{type:"application/javascript"});this.worker=new Worker(URL.createObjectURL(r)),this.worker.addEventListener("message",this.handleWorkerMessage)}dispose(){this.enabled=!1,this.onDistanceComputed.reset(),this.worker.terminate(),this.tempRT.dispose(),this.resultRT.dispose();const e=[...this.scene.children];this.excludedObjects.clear();for(const t of e)t.removeFromParent();this._postQuad.geometry.dispose(),this._postQuad.removeFromParent(),this._buffer=null,this.onDisposed.reset()}compute=async()=>{if(!this.enabled||this.world.isDisposing)return;if(this._isWorkerBusy)return;this._isWorkerBusy=!0,this.world.camera.three.updateMatrix();const e=this.world.renderer.three;e.setRenderTarget(this.tempRT);const t="visibilityBeforeDistanceCheck";for(const e of this.excludedObjects)e.userData[t]=e.visible,e.visible=!1;e.render(this.world.scene.three,this.world.camera.three);for(const e of this.excludedObjects)void 0!==e.userData[t]&&(e.visible=e.userData[t]);this.depthMaterial.uniforms.tDiffuse.value=this.tempRT.texture,this.depthMaterial.uniforms.tDepth.value=this.tempRT.depthTexture,e.setRenderTarget(this.resultRT),e.render(this.scene,this.camera);const i=e.getContext();try{await async function(e,t,i,n,s,r,o,a){const l=e.createBuffer();return e.bindBuffer(e.PIXEL_PACK_BUFFER,l),e.bufferData(e.PIXEL_PACK_BUFFER,a.byteLength,e.STREAM_READ),e.readPixels(t,i,n,s,r,o,0),e.bindBuffer(e.PIXEL_PACK_BUFFER,null),await el(e,e.PIXEL_PACK_BUFFER,l,0,a),e.deleteBuffer(l),a}(i,0,0,this._width,this._height,i.RGBA,i.UNSIGNED_BYTE,this._buffer)}catch(t){return e.setRenderTarget(null),void(this._isWorkerBusy=!1)}e.setRenderTarget(null),this.renderDebugFrame&&e.render(this.scene,this.camera),this.worker.postMessage({buffer:this._buffer})};handleWorkerMessage=e=>{if(!this.enabled||this.world.isDisposing)return;const t=e.data.colors;let i=Number.MAX_VALUE;for(const e of t)0!==e&&e<i&&(i=e);const n=this.world.camera.three||s.OrthographicCamera,r=-1*(i/255-1)*(n.far-n.near),o=Math.min(r,n.far);this.onDistanceComputed.trigger(o),this._isWorkerBusy=!1}}class il extends _a{_distanceRenderer;autoBias=!0;_defaultShadowConfig={cascade:1,resolution:512};_lightsWithShadow=new Map;_isComputingShadows=!1;_shadowsEnabled=!0;_bias=0;get bias(){return this._bias}set bias(e){this._bias=e;for(const[,t]of this._lightsWithShadow){const i=this.directionalLights.get(t);i&&(i.shadow.bias=e)}}get shadowsEnabled(){return this._shadowsEnabled}set shadowsEnabled(e){this._shadowsEnabled=e;for(const[,t]of this.directionalLights)t.castShadow=e}get distanceRenderer(){if(!this._distanceRenderer)throw new Error("You must set up this component before accessing the distance renderer!");return this._distanceRenderer}setup(e){super.setup(e);const t={...this._defaultConfig,...this._defaultShadowConfig,...e};if(t.cascade<=0)throw new Error("Config.shadows.cascade must be a natural number greater than 0!");if(t.cascade>1)throw new Error("Multiple shadows not supported yet!");if(!this.currentWorld)throw new Error("A world needs to be assigned to the scene before setting it up!");for(const[,e]of this.directionalLights)e.target.removeFromParent(),e.removeFromParent(),e.dispose();this.directionalLights.clear(),this._distanceRenderer||(this._distanceRenderer=new tl(this.components,this.currentWorld),this._distanceRenderer.onDistanceComputed.add(this.recomputeShadows)),this._lightsWithShadow.clear();for(let e=0;e<t.cascade;e++){const i=new s.DirectionalLight;i.intensity=this.config.directionalLight.intensity,i.color=this.config.directionalLight.color,i.position.copy(this.config.directionalLight.position),i.shadow.mapSize.width=t.resolution,i.shadow.mapSize.height=t.resolution,this.three.add(i,i.target),this.directionalLights.set(i.uuid,i),this._lightsWithShadow.set(e,i.uuid),i.castShadow=!0,i.shadow.bias=this._bias}}dispose(){super.dispose(),this._distanceRenderer&&this._distanceRenderer.dispose(),this._lightsWithShadow.clear()}async updateShadows(){!this._isComputingShadows&&this._shadowsEnabled&&(this._isComputingShadows=!0,await this.distanceRenderer.compute())}recomputeShadows=e=>{if(!this._shadowsEnabled)return;this.autoBias&&(this.bias=-.005);if(e*=1.5,!this.currentWorld)throw new Error("A world needs to be assigned to the scene before computing shadows!");if(!this._lightsWithShadow.size)throw new Error("No shadows found!");const t=this.currentWorld.camera.three;if(!(t instanceof s.PerspectiveCamera||t instanceof s.OrthographicCamera))throw new Error("Invalid camera type!");const i=new s.Vector3;t.getWorldDirection(i);let n=e;const r=new s.Vector3;r.copy(this.config.directionalLight.position),r.normalize();for(const[e,o]of this._lightsWithShadow){const a=this.directionalLights.get(o);if(!a)throw new Error("Light not found.");const l=new s.Vector3;l.copy(i);const c=e===this._lightsWithShadow.size-1,h=c?n/2:2*n/3;l.multiplyScalar(h),l.add(t.position);const u=n-h,d=new s.Vector3;d.copy(r),d.multiplyScalar(u),a.target.position.copy(l),a.position.copy(l),a.position.add(d),a.shadow.camera.right=u,a.shadow.camera.left=-u,a.shadow.camera.top=u,a.shadow.camera.bottom=-u,a.shadow.camera.far=2*u,a.shadow.camera.updateProjectionMatrix(),a.shadow.camera.updateMatrix(),c||(n/=3)}this._isComputingShadows=!1}}class nl{constructor(e){this._components=e}_components;cardinality="required";instructions;addCheckResult(e,t){const i=t.findIndex(({parameter:t})=>t===e.parameter);-1!==i?t[i]=e:t.push(e)}evalRequirement=(e,t,i,n)=>{const s={parameter:i,currentValue:e,requiredValue:t,pass:!1};n&&this.addCheckResult(s,n);let r=!1;if("simple"===t.type&&(r=e===t.parameter),"enumeration"===t.type&&(r=t.parameter.includes(e)),"pattern"===t.type){r=new RegExp(t.parameter).test(String(e))}if("length"===t.type){const{min:i,length:n,max:s}=t.parameter;void 0!==n&&(r=String(e).length===n),void 0!==i&&(r=String(e).length>=i),void 0!==s&&(r=String(e).length<=s)}if("bounds"===t.type&&"number"==typeof e){const{min:i,minInclusive:n,max:s,maxInclusive:o}=t.parameter;let a=!0,l=!0;void 0!==i&&(a=n?e>=i:e>i),void 0!==s&&(l=o?e<=s:e<s),r=a&&l}return"prohibited"===this.cardinality&&(r=!r),"optional"===this.cardinality&&(r=!0),s.pass=r,s.pass};getItemChecks(t,i,n,s){if(!("value"in n._localId)||"number"!=typeof n._localId.value)return null;let r=t.get(i);r||(r=new e.DataMap,t.set(i,r));let o=r.get(n._localId.value);if(o&&s&&!o.pass)return null;if(!o){const e=[];o={guid:Array.isArray(n._guid)?void 0:n._guid.value,pass:!1,checks:e},Object.defineProperty(o,"pass",{get:()=>e.every(({pass:e})=>e)}),r.set(n._localId.value,o)}const a=[],l={facetType:this.facetType,cardinality:this.cardinality,checks:a,pass:!1};return Object.defineProperty(l,"pass",{get:()=>a.every(({pass:e})=>e)}),o.checks.push(l),l.checks}}const sl=(e,t)=>{let i="";if(!t)return i;if("simple"===t.type&&(i=`<simpleValue>${t.parameter}</simpleValue>`),"enumeration"===t.type){i=`<xs:restriction base="xs:string">\n ${t.parameter.map(e=>`<xs:enumeration value="${e}" />`).join("\n")}\n </xs:restriction>`}if("pattern"===t.type){i=`<xs:restriction base="xs:string">\n <xs:pattern value="${t.parameter}" />\n </xs:restriction>`}if("bounds"===t.type){const{min:e,minInclusive:n,max:s,maxInclusive:r}=t.parameter;let o="";void 0!==e&&(o=`<xs:min${n?"Inclusive":"Exclusive"} value="${e}">`);let a="";void 0!==s&&(a=`<xs:max${r?"Inclusive":"Exclusive"} value="${s}">`),i=`<xs:restriction base="xs:double">\n ${o}\n ${a}\n </xs:restriction>`}if("length"===t.type){const{length:e,min:n,max:s}=t.parameter;let r="";void 0!==e&&void 0===n&&void 0===s&&(r=`<xs:length value="${e}" />`);let o="";void 0!==n&&void 0===e&&(o=`<xs:minLength value="${n}" />`);let a="";void 0!==s&&void 0===e&&(a=`<xs:maxLength value="${s}" />`),i=`<xs:restriction base="xs:string">\n ${r}\n ${o}\n ${a}\n </xs:restriction>`}return`<${e[0].toLowerCase()+e.slice(1)}>\n ${i}\n </${e[0].toLowerCase()+e.slice(1)}>`};class rl extends nl{facetType="Attribute";name;value;constructor(e,t){super(e),this.name=t}serialize(e){const t=sl("Name",this.name),i=sl("Value",this.value);let n="";return"requirement"===e&&(n+=`cardinality="${this.cardinality}"`,n+=this.instructions?`instructions="${this.instructions}"`:""),`<attribute ${n}>\n ${t}\n ${i}\n</attribute>`}async getEntities(){}async test(e,t,i={skipIfFails:!0}){const n=this._components.get(hr);for(const[s,r]of Object.entries(e)){const e=n.list.get(s);if(!e)continue;const o=await e.getItemsData([...r]);for(const e of o){const n=this.getItemChecks(t,s,e,i.skipIfFails);if(!n)continue;const r=Object.keys(e).filter(t=>{const i=this.evalRequirement(t,this.name,"Name");if(!i)return!1;const n=e[t];return!!Array.isArray(n)||(null===n||null===n.value?"optional"===this.cardinality||"prohibited"===this.cardinality:(!Array.isArray(n.value)||0!==n.value.length)&&(("string"!=typeof n.value||""!==n.value.trim())&&i))}),o=r.length>0;if(n.push({parameter:"Name",currentValue:o?r[0]:null,requiredValue:this.name,pass:"prohibited"===this.cardinality?!o:o}),this.value)if(r[0]){const t=e[r[0]];if(Array.isArray(t))n.push({parameter:"Value",currentValue:null,requiredValue:this.value,pass:"prohibited"===this.cardinality});else{Array.isArray(t.value)?n.push({parameter:"Value",currentValue:null,requiredValue:this.value,pass:"prohibited"===this.cardinality}):this.evalRequirement(t.value,this.value,"Value",n)}}else n.push({parameter:"Value",currentValue:null,requiredValue:this.value,pass:"prohibited"===this.cardinality})}}}}class ol extends nl{facetType="Classification";system;value;uri;constructor(e,t){super(e),this.system=t}serialize(e){const t=sl("System",this.system),i=sl("Value",this.value);let n="";return"requirement"===e&&(n+=`cardinality="${this.cardinality}"`,n+=this.uri?`uri=${this.uri}`:"",n+=this.instructions?`instructions="${this.instructions}"`:""),`<classification ${n}>\n ${t}\n ${i}\n</classification>`}async getEntities(e,t){}async test(e,t){}}class al extends nl{facetType="Entity";name;predefinedType;constructor(e,t){super(e),this.name=t}serialize(e){const t=sl("Name",this.name),i=sl("Name",this.predefinedType);let n="";return"requirement"===e&&(n+=`cardinality="${this.cardinality}"`,n+=this.instructions?`instructions="${this.instructions}"`:""),`<entity ${n}>\n ${t}\n ${i}\n</entity>`}async getEntities(e,t){const i=this._components.get(hr),n=new Map;for(const[t,s]of i.list){if(!e.find(e=>e.test(t)))continue;const i=await s.getCategories();for(const e of i){if(!await this.evalName(e))continue;let i=n.get(t);i||(i=[],n.set(t,i)),i.push(e)}}const s={};if(await Promise.all(Array.from(n.entries()).map(async([e,t])=>{const n=i.list.get(e);if(!n)return;const r=t.map(e=>new RegExp(`^${e}$`)),o=await n.getItemsOfCategories(r),a=Object.values(o).flat();s[e]=new Set(a)})),this.predefinedType)for(const[e,n]of Object.entries(s)){const s=i.list.get(e);if(!s)continue;const r=await s.getItemsData([...n]);for(const i of r){if(!("value"in i._localId))continue;await this.evalPredefinedType(e,i)&&si.append(t,e,i._localId.value)}}else si.add(t,s)}async test(e,t,i){const n=this._components.get(hr);for(const[s,r]of Object.entries(e)){const e=n.list.get(s);if(!e)continue;const o=await e.getItemsData([...r]);for(const e of o){if(!("value"in e._category))continue;const n=this.getItemChecks(t,s,e,i.skipIfFails);n&&(await this.evalName(e._category.value,n),await this.evalPredefinedType(s,e,n))}}}async evalName(e,t){return this.evalRequirement(e,this.name,"Name",t)}async evalPredefinedType(e,t,i){if(!this.predefinedType)return null;if(!("value"in t.PredefinedType))return null;const n="string"==typeof this.predefinedType.parameter&&"USERDEFINED"===this.predefinedType.parameter;let s=t.PredefinedType.value;if("USERDEFINED"===s&&!n){const e=Object.keys(t).find(e=>/^((?!Predefined).)*Type$/.test(e));if(e){const i=t[e];"value"in i&&(s=i.value)}else s="USERDEFINED"}if(!s){const i=this._components.get(hr).list.get(e);if(i&&"value"in t._localId){const[e]=await i.getItemsData([t._localId.value],{relations:{IsTypedBy:{attributes:!0,relations:!1}}});if(Array.isArray(e.IsTypedBy)){const t=e.IsTypedBy[0];if(t&&"value"in t.PredefinedType&&(s=t.PredefinedType.value,"USERDEFINED"===s&&!n)){const e=Object.keys(t).find(e=>/^((?!Predefined).)*Type$/.test(e));if(e){const i=t[e];"value"in i&&(s=i.value)}else s="USERDEFINED"}}}}return this.evalRequirement(s,this.predefinedType,"PredefinedType",i)}}class ll extends nl{facetType="Property";propertySet;baseName;value;dataType;uri;_unsupportedTypes=["IFCCOMPLEXPROPERTY","IFCPHYSICALCOMPLEXQUANTITY"];constructor(e,t,i){super(e),this.propertySet=t,this.baseName=i}serialize(e){const t=sl("PropertySet",this.propertySet),i=sl("BaseName",this.baseName),n=sl("Value",this.value),s=this.dataType?`dataType=${this.dataType}`:"";let r="";return"requirement"===e&&(r+=`cardinality="${this.cardinality}"`,r+=this.uri?`uri=${this.uri}`:"",r+=this.instructions?`instructions="${this.instructions}"`:""),`<property ${s} ${r}>\n ${t}\n ${i}\n ${n}\n</property>`}async getEntities(e,t){const i=this._components.get(hr);for(const[n,s]of i.list){if(!e.find(e=>e.test(n)))continue;const i=await s.getItemsOfCategories([/PROPERTYSET/,/ELEMENTQUANTITY/]),r=Object.values(i).flat();if(0===r.length)continue;const o=await s.getItemsData(r,{relations:{HasProperties:{attributes:!0,relations:!1},DefinesOccurrence:{attributes:!0,relations:!1},DefinesOcurrence:{attributes:!0,relations:!1}}}),a=new Map;for(const e of o){const i=e.DefinesOccurrence??e.DefinesOcurrence;if(!("value"in e._localId&&"value"in e._category&&"value"in e.Name))continue;if(!this.evalRequirement(e.Name.value,this.propertySet,"PropertySet"))continue;let s;if("IFCPROPERTYSET"===e._category.value&&(s="HasProperties"),"IFCELEMENTQUANTITY"===e._category.value&&(s="Quantities"),!s)continue;const r=e[s];if(Array.isArray(r))for(const s of r){const r=Object.keys(s),o=r.find(e=>/Name/.test(e));if(!o||!("value"in s[o]))continue;const l=s[o];if(!("value"in l))continue;if(!this.evalRequirement(l.value,this.baseName,"BaseName"))continue;if(this.value){const e=r.find(e=>/Value/.test(e));if(!e)continue;const t=s[e];if(!("value"in t))continue;if(!this.evalRequirement(t.value,this.value,"Value"))continue}const c=e._localId.value;let h=a.get(c);if(h||(h={name:String(e.Name.value),props:new Set},a.set(c,h)),h.props.add(String(l.value)),!Array.isArray(i))continue;const u=i.map(e=>"value"in e._localId&&"number"==typeof e._localId.value?e._localId.value:null).filter(e=>null!==e);si.append(t,n,...u)}}a.size>0&&await this.appendTypeInstances(s,n,a,t)}}async appendTypeInstances(e,t,i,n){const s=Object.values(await e.getItemsOfCategories([/TYPE$/,/^IFCTYPE/,/STYLE$/])).flat();if(0===s.length)return;const r={attributes:!0,relations:!1},o=await e.getItemsData(s,{attributesDefault:!1,relations:{HasPropertySets:r,ObjectTypeOf:r,Types:r}}),a=new Map,l=n[t];for(const e of o){if(!Array.isArray(e.HasPropertySets))continue;const t=e.HasPropertySets.flatMap(e=>{const t=e._localId&&"value"in e._localId?e._localId.value:null,n=i.get(t);return n?[n]:[]});if(0===t.length)continue;const n=[...Array.isArray(e.ObjectTypeOf)?e.ObjectTypeOf:[],...Array.isArray(e.Types)?e.Types:[]];for(const e of n){if(!e._localId||!("value"in e._localId))continue;const i=e._localId.value;if("number"!=typeof i||l?.has(i))continue;let n=a.get(i);n||(n=[],a.set(i,n)),n.push(...t)}}if(0===a.size)return;const c=await e.getItemsData([...a.keys()],{relations:{IsDefinedBy:{attributes:!0,relations:!0}}}),h=[];for(const e of c){if(!("value"in e._localId))continue;const t=e._localId.value,i=Array.isArray(e.IsDefinedBy)?e.IsDefinedBy:[],n=(e,t)=>i.some(i=>{if(!i.Name||!("value"in i.Name)||i.Name.value!==e)return!1;const n=this.getPropertyListName(i),s=n?i[n]:void 0;return!!Array.isArray(s)&&s.some(e=>e.Name&&"value"in e.Name&&e.Name.value===t)});a.get(t).some(e=>[...e.props].some(t=>!n(e.name,t)))&&h.push(t)}si.append(n,t,...h)}async test(e,t,i={skipIfFails:!0}){const n=this._components.get(hr);for(const[s,r]of Object.entries(e)){const e=n.list.get(s);if(!e)continue;const o=await e.getItemsData([...r],{relations:{IsDefinedBy:{attributes:!0,relations:!0},IsTypedBy:{attributes:!0,relations:!1},HasPropertySets:{attributes:!0,relations:!0},DefinesOccurrence:{attributes:!1,relations:!1},DefinesOcurrence:{attributes:!1,relations:!1}}});for(const e of o){const n=this.getItemChecks(t,s,e,i.skipIfFails);if(!n)continue;const r=(await this.getPsets(e)).filter(e=>{if(!("value"in e.Name))return!1;return!!this.evalRequirement(e.Name.value,this.propertySet,"PropertySet")&&(n.push({currentValue:e.Name.value,parameter:"PropertySet",pass:!0,requiredValue:this.propertySet}),!0)});if(0!==r.length)for(const e of r){const t=this.getPropertyListName(e);if(!t)continue;const i=e[t];if(!Array.isArray(i)){n.push({currentValue:null,parameter:"BaseName",pass:!1,requiredValue:this.baseName});continue}const s=i.filter(e=>{if(!("value"in e._category)||!("value"in e.Name))return!1;if(this._unsupportedTypes.includes(e._category.value))return!1;return!!this.evalRequirement(e.Name.value,this.baseName,"BaseName")&&(n.push({currentValue:e.Name.value,parameter:"BaseName",pass:!0,requiredValue:this.baseName}),!0)});if(0!==s.length)for(const e of s)this.evalValue(e,n),this.evalDataType(e,n),this.evalURI();else n.push({currentValue:null,parameter:"BaseName",pass:!1,requiredValue:this.baseName})}else n.push({currentValue:null,parameter:"PropertySet",pass:!1,requiredValue:this.propertySet})}}}getPropertyListName(e){let t;return"value"in e._category?("IFCPROPERTYSET"===e._category.value&&(t="HasProperties"),"IFCELEMENTQUANTITY"===e._category.value&&(t="Quantities"),t):t}getValueKey(e){return Object.keys(e).find(e=>/Value/.test(e)||/Values/.test(e))}getTypePsets(e){const t=[...Array.isArray(e.IsTypedBy)?e.IsTypedBy:[],...Array.isArray(e.IsDefinedBy)?e.IsDefinedBy:[]],i=[];for(const e of t)Array.isArray(e?.HasPropertySets)&&i.push(...e.HasPropertySets);return i}async getPsets(e){const t=this.getTypePsets(e);if(!Array.isArray(e.IsDefinedBy))return t;const i=[],n=new Set;for(const s of e.IsDefinedBy){if(!("value"in s.Name))continue;const e=s.Name.value,r=this.getPropertyListName(s);if(!e||!r)continue;const o=t.find(t=>"value"in t.Name&&t.Name.value===e);if(o&&(n.add(o),Array.isArray(o.HasProperties)&&Array.isArray(s.HasProperties)))for(const e of o.HasProperties){if(!("value"in e.Name))continue;const t=e.Name.value;s.HasProperties.find(e=>"value"in e.Name&&e.Name.value===t)||s.HasProperties.push(e)}i.push(s)}for(const e of t)n.has(e)||i.push(e);return i}evalValue(e,t){const i=this.getValueKey(e),n=e[i];if(!("value"in n))return!1;if(this.value){if(!i)return t?.push({parameter:"Value",currentValue:null,pass:!1,requiredValue:this.value}),!1;const e=structuredClone(this.value);"string"==typeof n.value&&"simple"===e.type&&(e.parameter=String(e.parameter));return this.evalRequirement(n.value,e,"Value",t)}return!i||("string"!=typeof n.value||""!==n.value.trim()||(t?.push({parameter:"Value",currentValue:"",pass:!1,requiredValue:this.value}),!1))}evalDataType(e,t){if(!this.dataType)return!0;const i=this.getValueKey(e);if(!i||!("value"in e[i]))return t?.push({parameter:"DataType",currentValue:null,pass:!1,requiredValue:this.dataType}),!1;const n=e[i];return this.evalRequirement(n.type??null,{type:"simple",parameter:this.dataType},"DataType",t)}evalURI(){return!0}}class cl extends nl{_ifcMaterialEntities=[/^IFCMATERIALLAYERSETUSAGE$/,/^IFCMATERIALLAYERSET$/,/^IFCMATERIALPROFILESETUSAGE$/,/^IFCMATERIALPROFILESET$/,/^IFCMATERIALCONSTITUENTSET$/,/^IFCMATERIAL$/,/^IFCMATERIALLIST$/];_materialParentAttributes=["ForLayerSet","MaterialLayers","ForProfileSet","MaterialProfiles","Material","MaterialConstituents","Materials"];_materialRelations={MaterialConstituents:{attributes:!0,relations:!0},ForLayerSet:{attributes:!0,relations:!0},MaterialLayers:{attributes:!0,relations:!0},ForProfileSet:{attributes:!0,relations:!0},MaterialProfiles:{attributes:!0,relations:!0},Materials:{attributes:!0,relations:!1}};facetType="Material";value;uri;serialize(e){if(!this.value||!this.uri)return"<material />";const t=sl("Value",this.value);let i="";return"requirement"===e&&(i+=`cardinality="${this.cardinality}"`,i+=this.uri?`uri=${this.uri}`:"",i+=this.instructions?`instructions="${this.instructions}"`:""),`<material ${i}>\n ${t}\n</material>`}async getEntities(e,t){const i=this._components.get(hr);for(const[n,s]of i.list){if(!e.find(e=>e.test(n)))continue;const i=await s.getItemsOfCategories(this._ifcMaterialEntities),r=Object.values(i).flat();if(0===r.length)continue;const o=await s.getItemsData(r,{relations:{AssociatedTo:{attributes:!0,relations:!1},...this._materialRelations}});for(const e of o){if(!("value"in e._localId&&"value"in e._category&&Array.isArray(e.AssociatedTo)))continue;if(!this.hasValidMaterial(e))continue;const i=e.AssociatedTo.map(e=>"value"in e._localId&&e._localId.value?e._localId.value:null).filter(e=>null!==e);si.append(t,n,...i)}}}async test(e,t,i={skipIfFails:!0}){const n=this._components.get(hr);for(const[s,r]of Object.entries(e)){const e=n.list.get(s);if(!e)continue;const o=await e.getItemsData([[...r][0]],{relations:{AssociatedTo:{attributes:!1,relations:!1},HasAssociations:{attributes:!0,relations:!0},...this._materialRelations}});for(const e of o){const n=this.getItemChecks(t,s,e,i.skipIfFails);if(n)if(Array.isArray(e.HasAssociations))for(const t of e.HasAssociations){if(!this._ifcMaterialEntities.some(e=>"value"in t._category&&e.test(t._category.value)))continue;if(this.hasValidMaterial(t,n))break}else n.push({parameter:null,currentValue:null,requiredValue:this.value,pass:!1})}}}hasValidMaterial(e,t){let i=!1;if("value"in e._category&&"IFCMATERIAL"===e._category.value){this.evalValue(e,t)&&(i=!0)}else for(const[n,s]of Object.entries(e))if(this._materialParentAttributes.includes(n)&&Array.isArray(s))for(const e of s){if("value"in e._category&&"IFCMATERIAL"===e._category.value){if(this.evalValue(e,t)){i=!0;break}}else{if(this.hasValidMaterial(e)){i=!0;break}}}return i}evalValue(e,t){if(!this.value)return t?.push({parameter:null,currentValue:e.Name&&"value"in e.Name?e.Name.value:null,pass:!0}),!0;if(!("value"in e._category)||"IFCMATERIAL"!==e._category.value)return null;let i=!1;return e.Name&&"value"in e.Name&&(i=this.evalRequirement(e.Name.value,this.value,"Value",t)),i||(e.Category&&"value"in e.Category&&(i=this.evalRequirement(e.Category.value,this.value,"Value",t)),i)}}class hl extends nl{facetType="PartOf";_entityFacet;_entity;set entity(e){this._entity=e;const{name:t,predefinedType:i}=e;this._entityFacet=new al(this._components,t),this._entityFacet.predefinedType=i}get entity(){return this._entity}relation;cardinality="required";constructor(e,t){super(e),this._entity=t,this._entityFacet=new al(e,t.name),this._entityFacet.predefinedType=t.predefinedType}serialize(){return""}async getEntities(e,t){}async test(e){}}class ul{name;ifcVersion=new Set;identifier=me.create();description;instructions;requirementsDescription;applicability=new e.DataSet;requirements=new e.DataSet;components;constructor(e,t,i){this.components=e,this.name=t;for(const e of i)this.ifcVersion.add(e)}set(e){const t=e,i=this;for(const n in e){if("identifier"===n)continue;const e=t[n];n in this&&(i[n]=e)}return this.components.get(_l).list.set(this.identifier,this),this}async test(t,i={skipIfFails:!0}){const n=new e.DataMap;if(0===this.requirements.size)return n;const s={},r=[];for(const e of this.applicability)r.push(e.getEntities(t,s));await Promise.all(r);const o=[];for(const e of this.requirements)o.push(e.test(s,n,i));return await Promise.all(o),n}serialize(){const e=`name="${this.name}"`,t=this.identifier?`identifier="${this.identifier}"`:"",i=this.description?`description="${this.description}"`:"",n=this.instructions?`instructions="${this.instructions}"`:"";return`<specification ifcVersion="${[...this.ifcVersion].join(" ")}" ${e} ${t} ${i} ${n}>\n <applicability minOccurs="1" maxOccurs="unbounded">\n ${[...this.applicability].map(e=>e.serialize("applicability")).join("\n")}\n </applicability>\n <requirements>\n ${[...this.requirements].map(e=>e.serialize("requirement")).join("\n")}\n </requirements>\n </specification>`}}const dl=e=>{if(!e)return;const t={};if("simpleValue"in e&&(t.type="simple",t.parameter=e.simpleValue),"restriction"in e){const i=e.restriction,n=Object.keys(i);if("pattern"in i&&(t.type="pattern",t.parameter=i.pattern.value),"enumeration"in i){t.type="enumeration";const e=i.enumeration.map(({value:e})=>i.base.includes("string")?String(e):i.base.includes("integer")||i.base.includes("double")?Number(e):e);t.parameter=e}if(n.some(e=>["minInclusive","minExclusive","maxInclusive","maxExclusive"].includes(e))){t.type="bounds";const e={},s=n.find(e=>e.includes("min")),r=n.find(e=>e.includes("max"));s&&(e.minInclusive="minInclusive"===s,e.min=i[s].value),r&&(e.maxInclusive="maxInclusive"===r,e.max=i[r].value),t.parameter=e}if(n.some(e=>["minLength","length","maxLength"].includes(e))){t.type="length";const e={};void 0!==i.length&&(e.length=i.length.value),void 0!==i.minLength&&(e.min=i.minLength.value),void 0!==i.maxLength&&(e.max=i.maxLength.value),t.parameter=e}}return void 0!==t.parameter?t:void 0},pl=(e,t)=>{const i=[];for(const n of t){const t=n.name,s=dl(t);if(!s)continue;const r=new al(e,s);n.cardinality&&(r.cardinality=n.cardinality),r.predefinedType=dl(n.predefinedType),r.instructions=n.instructions,i.push(r)}return i},fl=(e,t)=>{const i=[];for(const n of t){const t=n.name,s=dl(t);if(!s)continue;const r=new rl(e,s);n.cardinality&&(r.cardinality=n.cardinality),r.value=dl(n.value),r.instructions=n.instructions,i.push(r)}return i},ml=(e,t)=>{const i=[];for(const n of t){const t=new cl(e);n.cardinality&&(t.cardinality=n.cardinality);const s=dl(n.value);"enumeration"===s?.type&&Array.isArray(s.parameter)&&(s.parameter=s.parameter.map(String)),t.value=s,t.uri=n.uri,t.instructions=n.instructions,i.push(t)}return i},gl=(e,t)=>{const i=[];for(const n of t){const t=n.propertySet,s=n.baseName,r=dl(t),o=dl(s);if(!o||!r)continue;const a=new ll(e,r,o);n.cardinality&&(a.cardinality=n.cardinality);const l=dl(n.value);a.value=l,a.dataType=n.dataType,a.uri=n.uri,a.instructions=n.instructions,i.push(a)}return i},wl=(e,t)=>{const i=[];for(const n of t){const t=n.system,s=dl(t);if(!s)continue;const r=new ol(e,s);n.cardinality&&(r.cardinality=n.cardinality);const o=dl(n.value);"simple"===o?.type&&(o.parameter=String(o.parameter)),"enumeration"===o?.type&&Array.isArray(o.parameter)&&(o.parameter=o.parameter.map(String)),r.value=o,r.uri=n.uri,r.instructions=n.instructions,i.push(r)}return i},yl=(e,t)=>{const i=[];for(const n of t){const t=dl(n.entity.name);if(!t)continue;const s=dl(n.entity.predefinedType),r=new hl(e,{name:t,predefinedType:s});r.relation=n.relation,n.cardinality&&(r.cardinality=n.cardinality),r.instructions=n.instructions,i.push(r)}return i};class _l extends le{static uuid="9f0b9f78-9b2e-481a-b766-2fbfd01f342c";enabled=!0;static xmlParser=new Ut({allowBooleanAttributes:!0,attributeNamePrefix:"",ignoreAttributes:!1,ignoreDeclaration:!0,ignorePiTags:!0,numberParseOptions:{leadingZeros:!0,hex:!0},parseAttributeValue:!0,preserveOrder:!1,processEntities:!1,removeNSPrefix:!0,trimValues:!0});IDSInfo;constructor(e){super(e),e.add(_l.uuid,this)}list=new t;getModelIdMap(e){const t={},i={};for(const[n,s]of e){const e=[...s].filter(([,e])=>e.pass).map(([e])=>e);si.append(t,n,...e);const r=[...s].filter(([,e])=>!e.pass).map(([e])=>e);si.append(i,n,...r)}return{pass:t,fail:i}}create(e,t,i){const n=new ul(this.components,e,t);return i&&(n.identifier=i),this.list.set(n.identifier,n),n}load(e){const t=[],i=_l.xmlParser.parse(e).ids,{specifications:n,info:s}=i;if(this.IDSInfo={...s},n&&n.specification){const e=Array.isArray(n.specification)?n.specification:[n.specification];for(const i of e){const{name:e,ifcVersion:n,description:s,instructions:r,identifier:o}=i;if(!e||!n)continue;const a=[],l=[],{applicability:c,requirements:h}=i;if(c){const{maxOccurs:e,...t}=c,i=Array.isArray(t)?t:[t];for(const e of i)for(const t in e){const i=Array.isArray(e[t])?e[t]:[e[t]];if("entity"===t){const e=pl(this.components,i);a.push(...e)}if("attribute"===t){const e=fl(this.components,i);a.push(...e)}if("material"===t){const e=ml(this.components,i);a.push(...e)}if("classification"===t){const e=wl(this.components,i);a.push(...e)}if("property"===t){const e=gl(this.components,i);a.push(...e)}if("partOf"===t){const e=yl(this.components,i);a.push(...e)}}}let u;if(h){const{maxOccurs:e,...t}=h;u=h.description;const i=Array.isArray(t)?t:[t];for(const e of i)for(const t in e){const i=Array.isArray(e[t])?e[t]:[e[t]];if("entity"===t){const e=pl(this.components,i);l.push(...e)}if("attribute"===t){const e=fl(this.components,i);l.push(...e)}if("material"===t){const e=ml(this.components,i);l.push(...e)}if("classification"===t){const e=wl(this.components,i);l.push(...e)}if("property"===t){const e=gl(this.components,i);l.push(...e)}if("partOf"===t){const e=yl(this.components,i);l.push(...e)}}}const d=this.create(e,n.split(/\s+/),o);d.description=s,d.instructions=r,d.requirementsDescription=u,d.applicability.add(...a),d.requirements.add(...l),t.push(d)}}return t}export(e,t=this.list.values()){const i=t??this.list;return`<ids xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://standards.buildingsmart.org/IDS http://standards.buildingsmart.org/IDS/1.0/ids.xsd" xmlns:ids="http://standards.buildingsmart.org/IDS">\n \x3c!-- Made with That Open Engine ${Ma.release} (https://github.com/thatopen/engine_components) --\x3e\n <info>\n <title>${e.title}</title>\n ${e.copyright?`<copyright>${e.copyright}</copyright>`:""}\n ${e.version?`<version>${e.version}</version>`:""}\n ${e.description?`<description>${e.description}</description>`:""}\n ${e.author?`<author>${e.author}</author>`:""}\n ${e.date?`<date>${e.date.toISOString().split("T")[0]}</date>`:""}\n ${e.purpose?`<purpose>${e.purpose}</purpose>`:""}\n ${e.milestone?`<milestone>${e.milestone}</milestone>`:""}\n </info>\n <specifications>\n ${[...i].map(e=>e.serialize()).join("\n")}\n </specifications>\n</ids>`}}class bl extends le{static uuid="267ca032-672f-4cb0-afa9-d24e904f39d6";enabled=!0;constructor(e){super(e),e.add(bl.uuid,this)}static distanceFromPointToLine(e,t,i,n=!1){const r=new s.Line3,o=new s.Vector3;return r.set(t,i),r.closestPointToPoint(e,n,o),o.distanceTo(e)}round(e){const t=1e3;e.x=Math.trunc(e.x*t)/t,e.y=Math.trunc(e.y*t)/t,e.z=Math.trunc(e.z*t)/t}async getVolumeFromFragments(e){return console.warn("getVolumeFromFragments is deprecated. Use getItemsVolume instead."),this.getItemsVolume(e)}async getItemsVolume(e){let t=0;const i=this.components.get(hr);for(const[n,s]of Object.entries(e)){const e=i.list.get(n);e&&(t+=await e.getItemsVolume([...s]))}return t}static convertUnits(e,t,i,n=2){const s={m:1,cm:.01,mm:.001,km:1e3,m2:1,cm2:1e-4,mm2:1e-6,km2:1e6,m3:1,cm3:1e-6,mm3:1e-9,km3:1e9};if(!s[t]||!s[i])throw new Error("Invalid units provided for conversion.");if(!Number.isInteger(n)||n<0||n>5)throw new Error("Precision must be an integer between 0 and 5.");const r=e*(s[t]/s[i]),o=10**n;return Math.round(r*o)/o}}const vl=(e,t,i)=>{const n=new s.Vector3(-t.z,0,t.x),r=new s.Vector3(t.x+n.x,0,t.z+n.z).normalize().multiplyScalar(i/2);return[e.x+r.x,e.y,e.z+r.z,e.x-r.x,e.y,e.z-r.z]},xl=(e,t,i)=>{const n=new s.Vector3(-t.z,0,t.x),r=e.x-t.x*i+n.x*i*.4,o=e.z-t.z*i+n.z*i*.4,a=e.x-t.x*i-n.x*i*.4,l=e.z-t.z*i-n.z*i*.4;return[e.x,e.y,e.z,r,e.y,o,e.x,e.y,e.z,a,e.y,l,r,e.y,o,a,e.y,l]},Cl=(e,t,i)=>{const n=new s.Vector3(-t.z,0,t.x),r=e.x-t.x*i+n.x*i*.4,o=e.z-t.z*i+n.z*i*.4,a=e.x-t.x*i-n.x*i*.4,l=e.z-t.z*i-n.z*i*.4;return[e.x,e.y,e.z,r,e.y,o,e.x,e.y,e.z,a,e.y,l]},Sl=()=>[],Al=(e,t,i)=>{const n=.4*i,s=[];for(let t=0;t<12;t++){const i=t/12*Math.PI*2,r=(t+1)/12*Math.PI*2;s.push(e.x+Math.cos(i)*n,e.y,e.z+Math.sin(i)*n,e.x+Math.cos(r)*n,e.y,e.z+Math.sin(r)*n)}return s},Tl=(e,t,i)=>{const n=.4*i,s=[];for(let t=0;t<16;t++){const i=t/16*Math.PI*2,r=(t+1)/16*Math.PI*2;s.push(e.x,e.y,e.z,e.x+Math.cos(i)*n,e.y,e.z+Math.sin(i)*n,e.x+Math.cos(r)*n,e.y,e.z+Math.sin(r)*n)}return s},Pl=(e,t,i)=>{const n=new s.Vector3(-t.z,0,t.x),r=.4*i,o=e.clone().addScaledVector(t,r).addScaledVector(n,r),a=e.clone().addScaledVector(t,r).addScaledVector(n,-r),l=e.clone().addScaledVector(t,-r).addScaledVector(n,-r),c=e.clone().addScaledVector(t,-r).addScaledVector(n,r);return[o.x,o.y,o.z,a.x,a.y,a.z,l.x,l.y,l.z,o.x,o.y,o.z,l.x,l.y,l.z,c.x,c.y,c.z]},El=(e,t,i)=>{const n=new s.Vector3(-t.z,0,t.x),r=e.clone().addScaledVector(t,-i),o=r.clone().addScaledVector(n,.4*i),a=r.clone().addScaledVector(n,.4*-i);return[e.x,e.y,e.z,o.x,o.y,o.z,a.x,a.y,a.z]};class Ml extends e.DataMap{constructor(){super()}getBySystem(e){const t=new Map;for(const[i,n]of this)n.system===e&&t.set(i,n.data);return t}}class Il extends e.DataMap{_container;constructor(e){super(),this._container=e,this.deleteGuard=e=>"0"!==e,this.set("0",{name:"0",visible:!0,material:new s.LineBasicMaterial({color:0})})}create(e,t){if(!this.has(e)){const i={name:e,visible:t?.visible??!0,material:t?.material??new s.LineBasicMaterial({color:0})};this.set(e,i)}return this.get(e)}setColor(e,t){const i=this.get(e);i&&(i.material.color.setHex(t),this.set(e,i))}setMaterial(e,t){const i=this.get(e);if(!i)return;const n=i.material;i.material=t,this._container.traverse(i=>{i.userData.layer===e&&(i.userData.isDimension||i.isLineSegments&&(i.material=t))}),n.dispose(),this.set(e,i)}setVisibility(e,t){const i=this.get(e);i&&(i.visible=t,this._container.traverse(i=>{i.userData.layer===e&&(i.visible=t)}),this.set(e,i))}assign(e,t){const i=this.get(t);i&&(e.userData.layer=t,i.visible||(e.visible=!1),e.isLineSegments&&(e.material=i.material))}resolveColor(e){const t=this.get(e);if(t)return t.material.color.getHex()}}class zl extends s.Group{_viewport;_border;_handles=[];_raycaster=new s.Raycaster;_resizable=!1;_movable=!1;_dragHandle=null;_dragConstraints=[];_hoveredHandle=null;_moveDrag=null;_hoveringBorder=!1;_normalMat;_hoverMat;_borderMat;static _BORDER_COLOR=22015;static _BORDER_HOVER_COLOR=16746496;static _LINE_THRESHOLD=.06;static _HANDLE_DEFS=[{constraints:["left","top"]},{constraints:["right","top"]},{constraints:["right","bottom"]},{constraints:["left","bottom"]},{constraints:["top"]},{constraints:["right"]},{constraints:["bottom"]},{constraints:["left"]}];get resizable(){return this._resizable}set resizable(e){this._resizable=e;for(const t of this._handles)t.visible=e;e||(this._hoveredHandle&&(this._hoveredHandle.material=this._normalMat,this._hoveredHandle=null),this._dragHandle=null,this._dragConstraints=[])}get movable(){return this._movable}set movable(e){this._movable=e,e||(this._moveDrag=null,this._setBorderHover(!1))}get isDragging(){return null!==this._dragHandle||null!==this._moveDrag}constructor(e){super(),this._viewport=e,this._borderMat=new s.LineBasicMaterial({color:zl._BORDER_COLOR,depthTest:!1});const t=new s.BufferGeometry;t.setAttribute("position",new s.BufferAttribute(new Float32Array(24),3)),this._border=new s.LineSegments(t,this._borderMat),this._border.renderOrder=999,this._border.frustumCulled=!1,this._border.userData.isDimension=!0,this.add(this._border),this._normalMat=new s.MeshBasicMaterial({color:zl._BORDER_COLOR}),this._hoverMat=new s.MeshBasicMaterial({color:zl._BORDER_HOVER_COLOR});const i=new s.SphereGeometry(.05,8,6);for(const e of zl._HANDLE_DEFS){const t=new s.Mesh(i,this._normalMat);t.renderOrder=1e3,t.visible=!1,t.userData.constraints=e.constraints,t.userData.isDimension=!0,this.add(t),this._handles.push(t)}this.update()}update(){const e=this._viewport,t=e.left,i=e.right,n=-e.top,s=-e.bottom,r=.005,o=this._border.geometry.attributes.position;o.setXYZ(0,t,r,n),o.setXYZ(1,i,r,n),o.setXYZ(2,i,r,n),o.setXYZ(3,i,r,s),o.setXYZ(4,i,r,s),o.setXYZ(5,t,r,s),o.setXYZ(6,t,r,s),o.setXYZ(7,t,r,n),o.needsUpdate=!0,this._border.geometry.computeBoundingSphere();const a=(t+i)/2,l=(n+s)/2,c=.01,h=[[t,c,n],[i,c,n],[i,c,s],[t,c,s],[a,c,n],[i,c,l],[a,c,s],[t,c,l]];for(let e=0;e<this._handles.length;e++)this._handles[e].position.set(...h[e])}onPointerMove(e){if(this._dragHandle){const t=this._projectToLocal(e);if(!t)return;for(const e of this._dragConstraints)switch(e){case"left":this._viewport.left=t.x;break;case"right":this._viewport.right=t.x;break;case"top":this._viewport.top=-t.z;break;case"bottom":this._viewport.bottom=-t.z}return this._viewport.right<this._viewport.left&&([this._viewport.left,this._viewport.right]=[this._viewport.right,this._viewport.left],this._dragConstraints=this._dragConstraints.map(e=>"right"===e?"left":"left"===e?"right":e)),this._viewport.top<this._viewport.bottom&&([this._viewport.top,this._viewport.bottom]=[this._viewport.bottom,this._viewport.top],this._dragConstraints=this._dragConstraints.map(e=>"top"===e?"bottom":"bottom"===e?"top":e)),void this.update()}if(this._moveDrag){const t=this._projectToLocal(e);if(!t)return;const i=t.x-this._moveDrag.origin.x,n=t.z-this._moveDrag.origin.z;return this._viewport.left=this._moveDrag.left0+i,this._viewport.right=this._moveDrag.right0+i,this._viewport.top=this._moveDrag.top0-n,this._viewport.bottom=this._moveDrag.bottom0-n,void this.update()}if(!this._resizable&&!this._movable)return;this._raycaster.set(e.origin,e.direction);let t=null;if(this._resizable){const e=this._handles.filter(e=>e.visible),i=this._raycaster.intersectObjects(e,!1);t=i.length>0?i[0].object:null}if(t!==this._hoveredHandle&&(this._hoveredHandle&&(this._hoveredHandle.material=this._normalMat),t&&(t.material=this._hoverMat),this._hoveredHandle=t),this._movable&&!this._hoveredHandle){this._raycaster.params.Line={threshold:zl._LINE_THRESHOLD};const e=this._raycaster.intersectObject(this._border,!1).length>0;this._setBorderHover(e)}else this._setBorderHover(!1)}onPointerDown(e){if(this._resizable||this._movable){if(this._raycaster.set(e.origin,e.direction),this._resizable){const e=this._handles.filter(e=>e.visible),t=this._raycaster.intersectObjects(e,!1);if(t.length>0)return this._dragHandle=t[0].object,void(this._dragConstraints=[...this._dragHandle.userData.constraints])}if(this._movable){this._raycaster.params.Line={threshold:zl._LINE_THRESHOLD};if(this._raycaster.intersectObject(this._border,!1).length>0){const t=this._projectToLocal(e);if(!t)return;this._moveDrag={origin:t,left0:this._viewport.left,right0:this._viewport.right,top0:this._viewport.top,bottom0:this._viewport.bottom}}}}}onPointerUp(){this._dragHandle=null,this._dragConstraints=[],this._moveDrag=null}dispose(){this._border.geometry.dispose(),this._borderMat.dispose(),this._normalMat.dispose(),this._hoverMat.dispose(),this._handles.length>0&&this._handles[0].geometry.dispose(),this.removeFromParent()}_projectToLocal(e){this.updateWorldMatrix(!0,!1);const t=new s.Vector3(0,1,0).transformDirection(this.matrixWorld),i=(new s.Vector3).setFromMatrixPosition(this.matrixWorld),n=(new s.Plane).setFromNormalAndCoplanarPoint(t,i),r=new s.Vector3;return e.intersectPlane(n,r)?this.worldToLocal(r):null}_setBorderHover(e){e!==this._hoveringBorder&&(this._hoveringBorder=e,this._borderMat.color.setHex(e?zl._BORDER_HOVER_COLOR:zl._BORDER_COLOR))}}class Dl{uuid=s.MathUtils.generateUUID();name;camera;onDisposed=new re;_left;_right;_top;_bottom;_drawingScale;_container=null;_helper=null;_helperVisible=!1;get left(){return this._left}set left(e){this._left=e,this.camera.left=e,this.camera.updateProjectionMatrix(),this._helper?.update()}get right(){return this._right}set right(e){this._right=e,this.camera.right=e,this.camera.updateProjectionMatrix(),this._helper?.update()}get top(){return this._top}set top(e){this._top=e,this.camera.top=e,this.camera.updateProjectionMatrix(),this._helper?.update()}get bottom(){return this._bottom}set bottom(e){this._bottom=e,this.camera.bottom=e,this.camera.updateProjectionMatrix(),this._helper?.update()}get drawingScale(){return this._drawingScale}set drawingScale(e){this._drawingScale=e}get helper(){return this._helper||(this._helper=new zl(this)),this._helper}get helperVisible(){return this._helperVisible}set helperVisible(e){this._helperVisible=e,e?this._container?.add(this.helper):this._helper?.removeFromParent()}get bbox(){const e=new s.Vector3(this._left,0,-this._top),t=new s.Vector3(this._right,0,-this._bottom);return new s.Box3(e,t)}get size(){const e=new s.Vector3;return this.bbox.getSize(e),new s.Vector2(1e3*e.x,1e3*e.z)}get localXAxis(){return new s.Vector3(1,0,0)}get localYAxis(){return new s.Vector3(0,0,-1)}get normal(){return new s.Vector3(0,1,0)}constructor(e){this._left=e.left,this._right=e.right,this._top=e.top,this._bottom=e.bottom,this._drawingScale=e.scale??100,this.name=e.name??"Drawing Viewport",this.camera=new s.OrthographicCamera(this._left,this._right,this._top,this._bottom,.1,30),this.camera.up.set(0,0,-1),this.camera.position.set(0,10,0),this.camera.lookAt(0,0,0),this.camera.layers.set(1)}setContainer(e){this._container=e,this._helperVisible&&this._helper&&e.add(this._helper)}clipLine(e){const t=this.bbox,{start:i,end:n}=e,r=t.containsPoint(i),o=t.containsPoint(n);if(r&&o)return e;if(!r&&!o){const t=this.getPlaneIntersections(e);return t.length<2?null:new s.Line3(t[0],t[1])}const a=this.getPlaneIntersections(e);return 0===a.length?null:r?new s.Line3(i,a[0]):new s.Line3(a[0],n)}dispose(){this._helper?.dispose(),this._helper=null,this.onDisposed.trigger(),this.onDisposed.reset()}get bboxPlanes(){const e=this.bbox;return[new s.Plane(new s.Vector3(1,0,0),-e.min.x),new s.Plane(new s.Vector3(-1,0,0),e.max.x),new s.Plane(new s.Vector3(0,0,1),-e.min.z),new s.Plane(new s.Vector3(0,0,-1),e.max.z)]}getPlaneIntersections(e){const t=[];for(const i of this.bboxPlanes){const n=new s.Vector3;i.intersectLine(e,n)&&this.bbox.containsPoint(n)&&t.push(n)}return t}}class kl extends e.DataMap{_container;constructor(e){super(),this._container=e,this.onBeforeDelete.add(({value:e})=>{this._container.remove(e.camera),e.dispose()})}create(e){const t=new Dl(e);return this._container.add(t.camera),t.setContainer(this._container),this.set(t.uuid,t),t}}class Bl extends s.Group{_drawing;_topFrame;_pillars;_bottomFrame;_topPlane;_bottomPlane;_frameMat;_depthMat;_planeMat;static _FRAME_COLOR=22015;static _DEPTH_COLOR=22015;width=10;height=10;farHandle=new s.Object3D;widthHandle=new s.Object3D;heightHandle=new s.Object3D;constructor(e){super(),this._drawing=e,this._frameMat=new s.LineBasicMaterial({color:Bl._FRAME_COLOR,depthTest:!1}),this._depthMat=new s.LineBasicMaterial({color:Bl._DEPTH_COLOR,depthTest:!1,transparent:!0,opacity:.4}),this._planeMat=new s.MeshBasicMaterial({color:Bl._FRAME_COLOR,transparent:!0,opacity:.07,side:s.DoubleSide,depthTest:!1});const t=()=>{const e=new s.BufferGeometry;return e.setAttribute("position",new s.BufferAttribute(new Float32Array(12),3)),e.setIndex([0,1,2,0,2,3]),e};this._topPlane=new s.Mesh(t(),this._planeMat),this._topPlane.renderOrder=998,this._topPlane.frustumCulled=!1,this._topPlane.userData.isDimension=!0,this._bottomPlane=new s.Mesh(t(),this._planeMat),this._bottomPlane.renderOrder=998,this._bottomPlane.frustumCulled=!1,this._bottomPlane.userData.isDimension=!0;const i=new s.BufferGeometry;i.setAttribute("position",new s.BufferAttribute(new Float32Array(24),3)),this._topFrame=new s.LineSegments(i,this._frameMat),this._topFrame.renderOrder=999,this._topFrame.frustumCulled=!1,this._topFrame.userData.isDimension=!0;const n=new s.BufferGeometry;n.setAttribute("position",new s.BufferAttribute(new Float32Array(24),3)),this._pillars=new s.LineSegments(n,this._depthMat),this._pillars.renderOrder=999,this._pillars.frustumCulled=!1,this._pillars.userData.isDimension=!0;const r=new s.BufferGeometry;r.setAttribute("position",new s.BufferAttribute(new Float32Array(24),3)),this._bottomFrame=new s.LineSegments(r,this._depthMat),this._bottomFrame.renderOrder=999,this._bottomFrame.frustumCulled=!1,this._bottomFrame.userData.isDimension=!0,this.add(this._topPlane,this._bottomPlane),this.add(this._topFrame,this._pillars,this._bottomFrame),this.add(this.farHandle,this.widthHandle,this.heightHandle),this.farHandle.rotation.x=Math.PI,this.update()}update(){const e=this.width/2,t=this.height/2,i=-this._drawing.far,n=.005,s=-e,r=e,o=-t,a=t,l=this._topFrame.geometry.attributes.position;l.setXYZ(0,s,n,o),l.setXYZ(1,r,n,o),l.setXYZ(2,r,n,o),l.setXYZ(3,r,n,a),l.setXYZ(4,r,n,a),l.setXYZ(5,s,n,a),l.setXYZ(6,s,n,a),l.setXYZ(7,s,n,o),l.needsUpdate=!0,this._topFrame.geometry.computeBoundingSphere();const c=this._pillars.geometry.attributes.position;c.setXYZ(0,s,n,o),c.setXYZ(1,s,i,o),c.setXYZ(2,r,n,o),c.setXYZ(3,r,i,o),c.setXYZ(4,r,n,a),c.setXYZ(5,r,i,a),c.setXYZ(6,s,n,a),c.setXYZ(7,s,i,a),c.needsUpdate=!0,this._pillars.geometry.computeBoundingSphere();const h=this._bottomFrame.geometry.attributes.position;h.setXYZ(0,s,i,o),h.setXYZ(1,r,i,o),h.setXYZ(2,r,i,o),h.setXYZ(3,r,i,a),h.setXYZ(4,r,i,a),h.setXYZ(5,s,i,a),h.setXYZ(6,s,i,a),h.setXYZ(7,s,i,o),h.needsUpdate=!0,this._bottomFrame.geometry.computeBoundingSphere();const u=(e,t)=>{const i=e.geometry.attributes.position;i.setXYZ(0,s,t,o),i.setXYZ(1,r,t,o),i.setXYZ(2,r,t,a),i.setXYZ(3,s,t,a),i.needsUpdate=!0,e.geometry.computeBoundingSphere()};u(this._topPlane,n),u(this._bottomPlane,i),this.farHandle.position.set(0,i,0),this.widthHandle.position.set(r,n,0),this.heightHandle.position.set(0,n,a)}attachFarGizmo(e){e.attach(this.farHandle),e.setSpace("local"),e.showX=!1,e.showZ=!1,e.addEventListener("objectChange",()=>{this.farHandle.position.x=0,this.farHandle.position.z=0;const e=Math.max(.1,-this.farHandle.position.y);this._drawing.far=e,this.farHandle.position.y=-e,this.update()})}attachWidthGizmo(e){e.attach(this.widthHandle),e.setSpace("local"),e.showY=!1,e.showZ=!1,e.addEventListener("objectChange",()=>{this.widthHandle.position.y=.005,this.widthHandle.position.z=0,this.width=Math.max(.1,2*this.widthHandle.position.x),this.widthHandle.position.x=this.width/2,this.update()})}attachHeightGizmo(e){e.attach(this.heightHandle),e.setSpace("local"),e.showX=!1,e.showY=!1,e.addEventListener("objectChange",()=>{this.heightHandle.position.x=0,this.heightHandle.position.y=.005,this.height=Math.max(.1,2*this.heightHandle.position.z),this.heightHandle.position.z=this.height/2,this.update()})}dispose(){this._topPlane.geometry.dispose(),this._bottomPlane.geometry.dispose(),this._topFrame.geometry.dispose(),this._pillars.geometry.dispose(),this._bottomFrame.geometry.dispose(),this._planeMat.dispose(),this._frameMat.dispose(),this._depthMat.dispose(),this.removeFromParent()}}function Ol(e,t){if(3!==e.length||3!==t.length)throw new Error("computeAlignmentMatrix requires exactly 3 point pairs.");const i=(e,t)=>{const i=(new s.Vector3).subVectors(e[1],e[0]),n=(new s.Vector3).subVectors(e[2],e[0]);if((new s.Vector3).crossVectors(i,n).length()<1e-6)throw new Error(`${t} points are collinear — three non-collinear points are required to define a plane.`)};i(e,"Drawing"),i(t,"World");const n=(e,t,i)=>{const n=(new s.Vector3).subVectors(t,e),r=(new s.Vector3).subVectors(i,e),o=n.clone().normalize(),a=(new s.Vector3).crossVectors(n,r).normalize(),l=(new s.Vector3).crossVectors(o,a).normalize();return(new s.Matrix4).makeBasis(o,a,l)},r=n(e[0],e[1],e[2]),o=n(t[0],t[1],t[2]).clone().multiply(r.clone().invert()),a=e[0].distanceTo(e[1]);if(a<1e-10)throw new Error("The first two drawing points are coincident — cannot compute scale.");const l=t[0].distanceTo(t[1])/a,c=e[0].clone().multiplyScalar(l).applyMatrix4(o),h=(new s.Vector3).subVectors(t[0],c),u=(new s.Quaternion).setFromRotationMatrix(o),d=new s.Matrix4;return d.compose(h,u,new s.Vector3(l,l,l)),d}class Vl{uuid=s.MathUtils.generateUUID();_raycaster=new s.Raycaster;_components;constructor(e){this._components=e}world=null;three=new s.Group;annotations=new Ml;layers=new Il(this.three);activeLayer="0";far=10;viewports=new kl(this.three);onDisposed=new re;raycast(e,t=null){this._raycaster.set(e.origin,e.direction),this._raycaster.layers.set(1),this._raycaster.params.Line&&(this._raycaster.params.Line.threshold=.1);const i=[];this.three.traverse(e=>{e instanceof s.LineSegments&&!e.userData.isDimension&&i.push(e)});const n=this._raycaster.intersectObjects(i,!1);if(0===n.length)return null;const r=n[0],o=this.three.worldToLocal(r.point.clone());let a=null;if(r.object instanceof s.LineSegments&&void 0!==r.index){const e=r.object.geometry.attributes.position,t=r.index,i=new s.Vector3(e.getX(t),e.getY(t),e.getZ(t)),n=new s.Vector3(e.getX(t+1),e.getY(t+1),e.getZ(t+1));i.applyMatrix4(r.object.matrixWorld),this.three.worldToLocal(i),n.applyMatrix4(r.object.matrixWorld),this.three.worldToLocal(n),a=new s.Line3(i,n)}return{point:o,object:r.object,viewport:t,line:a}}alignTo(e,t){Ol(e,t).decompose(this.three.position,this.three.quaternion,this.three.scale)}static toDrawingSpace(e,t){e.updateWorldMatrix(!0,!1),t.three.updateWorldMatrix(!0,!1);const i=(new s.Matrix4).copy(t.three.matrixWorld).invert().multiply(e.matrixWorld),n=e.geometry.attributes.position,r=n.count,o=new Float32Array(3*r),a=new s.Vector3;for(let e=0;e<r;e++)a.fromBufferAttribute(n,e).applyMatrix4(i),o[3*e]=a.x,o[3*e+1]=0,o[3*e+2]=a.z;const l=new s.BufferGeometry;return l.setAttribute("position",new s.BufferAttribute(o,3)),new s.LineSegments(l)}addProjectionLines(e,t="0"){return this.layers.has(t)||(console.warn(`[TechnicalDrawing] Layer "${t}" does not exist. Falling back to "0".`),t="0"),this.layers.assign(e,t),e.layers.set(1),e.material instanceof s.LineDashedMaterial&&e.computeLineDistances(),e.geometry.computeBoundsTree({strategy:0,indirect:!0,type:tr}),this.three.add(e),e}async addProjectionFromItems(e,t){if(!this.world)return void console.warn("[TechnicalDrawing] addProjectionFromItems: drawing has no world assigned.");for(const e of[t.layers.visible,t.layers.hidden])if(!this.layers.has(e))return void console.warn(`[TechnicalDrawing] Layer "${e}" does not exist — create it before calling addProjectionFromItems.`);const i=this._components.get(Po),n=i.projectionDirection.clone(),r=i.nearPlane,o=i.farPlane;try{this.three.updateWorldMatrix(!0,!1);const n=new s.Vector3(0,-1,0).transformDirection(this.three.matrixWorld).normalize();i.projectionDirection.copy(n);const r=(new s.Matrix4).makeRotationFromQuaternion((new s.Quaternion).setFromUnitVectors(n,new s.Vector3(0,-1,0))),o=(new s.Vector3).setFromMatrixPosition(this.three.matrixWorld).applyMatrix4(r).y;i.farPlane=o,i.nearPlane=o-this.far;const a=await i.get(e,this.world,{onProgress:t.onProgress}),l=e=>Vl.toDrawingSpace(new s.LineSegments(e),this);this.addProjectionLines(l(a.visible),t.layers.visible),this.addProjectionLines(l(a.hidden),t.layers.hidden)}finally{i.projectionDirection.copy(n),i.nearPlane=r,i.farPlane=o}}orientTo(e){const t=e.clone().normalize(),i=Math.SQRT1_2;t.x>.999?this.three.quaternion.set(.5,-.5,.5,.5):t.x<-.999?this.three.quaternion.set(.5,.5,-.5,.5):t.y>.999?this.three.quaternion.set(0,0,1,0):t.y<-.999?this.three.quaternion.set(0,0,0,1):t.z>.999?this.three.quaternion.set(0,i,-i,0):t.z<-.999?this.three.quaternion.set(i,0,0,i):console.warn("[TechnicalDrawing] orientTo: direction does not match any of the 6 standard axes.")}dispose(){this.viewports.clear(),this.layers.clear(),this.annotations.clear();this._components.get(de).destroy(this.three),this.onDisposed.trigger(),this.onDisposed.reset()}}const Nl={m:{factor:1,suffix:"m"},cm:{factor:100,suffix:"cm"},mm:{factor:1e3,suffix:"mm"},ft:{factor:3.28084,suffix:"ft"},in:{factor:39.3701,suffix:"in"}};class Ll{constructor(e){this._components=e,this.styles.onItemUpdated.add(({key:e})=>{const t=this._materialCache.get(e);t&&t.color.setHex(this._resolveStyle(e).color);const i=this._meshMaterialCache.get(e);i&&i.color.setHex(this._resolveStyle(e).color);const n=this._components.get(xc),s=n?[...n.list.values()]:[...this._knownDrawings];for(const t of s){const i=[...t.annotations.getBySystem(this)].filter(([,t])=>t.style===e).map(([e])=>e);i.length>0&&this.update(t,i,{})}})}_components;styles=new e.DataMap;activeStyle="default";onCommit=new re;onUpdate=new re;onDelete=new re;onDisposed=new re;_knownDrawings=new Set;_previewMaterial=new s.LineBasicMaterial({color:16737894,depthTest:!1});_previewObject=null;_previewDrawing=null;_materialCache=new e.DataMap;_meshMaterialCache=new e.DataMap;_ownsChildGeometry=!0;_onAfterPersist(e,t){}_onDispose(){}_updatePreview(){}get(t){const i=new e.DataMap;for(const e of t)for(const[t,n]of e.annotations.getBySystem(this))i.set(t,{drawingUuid:e.uuid,item:n});return i}add(e,t){const i={uuid:s.MathUtils.generateUUID(),style:this.activeStyle,...t},n=this._persist(e,i);return this.onCommit.trigger([n]),i}update(e,t,i){for(const n of t){const t=e.annotations.get(n);if(!t||t.system!==this)continue;const s=t.data;Object.assign(s,i),this._redraw(s,t.three),this.onUpdate.trigger({item:s,group:t.three})}}pick(e,t=.05){const i=new s.Raycaster;i.ray.copy(e),i.params.Line={threshold:t},i.params.LineSegments={threshold:t};const n=s.Line.prototype.raycast;let r=null,o=1/0;for(const e of this._knownDrawings)for(const[t,a]of e.annotations){if(a.system!==this)continue;const e=a.three;e.updateWorldMatrix(!0,!0),e.traverse(a=>{if(a===e)return;const l=[];if(a instanceof s.LineSegments&&a.userData.isDimension)n.call(a,i,l),l.length>0&&l[0].distance<o&&(o=l[0].distance,r=t);else if(a instanceof s.Mesh){const e=(new s.Box3).setFromObject(a),n=new s.Vector3;if(i.ray.intersectBox(e,n)){const e=i.ray.origin.distanceTo(n);e<o&&(o=e,r=t)}}})}return r}delete(e,t){const i=[];for(const n of t){const t=e.annotations.get(n);t&&t.system===this&&(this._disposeGroup(t.three),e.annotations.delete(n),i.push(n))}i.length&&this.onDelete.trigger(i)}clear(e){const t=e??[...this._knownDrawings];for(const e of t){const t=[];for(const[i,n]of e.annotations)n.system===this&&t.push(i);for(const i of t){const t=e.annotations.get(i);this._disposeGroup(t.three),e.annotations.delete(i)}}}dispose(){this._clearPreview(),this._onDispose(),this.clear();for(const e of this._materialCache.values())e.dispose();this._materialCache.clear();for(const e of this._meshMaterialCache.values())e.dispose();this._meshMaterialCache.clear(),this._previewMaterial.dispose(),this.onCommit.reset(),this.onUpdate.reset(),this.onDelete.reset(),this.onDisposed.trigger(),this.onDisposed.reset()}_trackDrawing(e){this._knownDrawings.has(e)||(this._knownDrawings.add(e),e.onDisposed.add(()=>this._knownDrawings.delete(e)))}_resolveStyle(e){return this.styles.get(e)??this.styles.get("default")}_getMaterial(e){const t=this._materialCache.get(e);if(t)return t;const i=new s.LineBasicMaterial({color:this._resolveStyle(e).color});return this._materialCache.set(e,i),i}_getMeshMaterial(e){const t=this._meshMaterialCache.get(e);if(t)return t;const i=new s.MeshBasicMaterial({color:this._resolveStyle(e).color,side:s.DoubleSide});return this._meshMaterialCache.set(e,i),i}_disposeGroup(e){if(e.removeFromParent(),this._ownsChildGeometry)e.traverse(e=>{e.geometry instanceof s.BufferGeometry&&e.geometry.dispose()});else for(;e.children.length>0;)e.remove(e.children[0])}_clearPreview(){this._previewObject&&(this._previewObject.removeFromParent(),this._previewObject.geometry.dispose(),this._previewObject=null)}_persist(e,t){this._trackDrawing(e);const i=this._resolveStyle(t.style),n=this._buildGroup(t,i);return n.userData.isDimension=!0,n.userData.annotationUuid=t.uuid,n.userData.layer=e.activeLayer,e.three.add(n),e.annotations.set(t.uuid,{system:this,data:t,three:n}),this._onAfterPersist(t,n),{drawing:e,item:t,group:n}}_redraw(e,t){for(;t.children.length>0;){const e=t.children[0];this._ownsChildGeometry&&e.geometry instanceof s.BufferGeometry&&e.geometry.dispose(),t.remove(e)}const i=this._resolveStyle(e.style),n=this._buildGroup(e,i);for(;n.children.length>0;)t.add(n.children[0]);this._onAfterPersist(e,t)}}function Fl(e,t){const i=e[0],n=e[e.length-1],r=(new s.Vector3).subVectors(n,i);if(r.lengthSq()<1e-10)return 0;r.normalize();const o=new s.Vector3(-r.z,0,r.x);return t.clone().sub(i).dot(o)}function Rl(e,t){const i=[];for(let n=0;n<e.length-1;n++)i.push({uuid:s.MathUtils.generateUUID(),pointA:e[n].clone(),pointB:e[n+1].clone(),offset:t,style:""});return i}function Ul(e,t){switch(e.kind){case"awaitingFirstPoint":if("CLICK"===t.type){if(!t.line)return e;const i=(new s.Vector3).subVectors(t.line.end,t.line.start).normalize();return{kind:"placingPoints",points:[t.point.clone()],cursor:null,lineDir:i,firstLine:t.line.clone()}}return"SELECT_LINE"===t.type?{kind:"positioningOffset",points:[t.line.start.clone(),t.line.end.clone()],cursor:null}:e;case"placingPoints":if("MOUSE_MOVE"===t.type){const i=new s.Vector3(-e.lineDir.z,0,e.lineDir.x),n=e.points[e.points.length-1],r=t.point.clone().sub(n).dot(i),o=n.clone().addScaledVector(i,r);return{...e,cursor:o}}if("CLICK"===t.type){if(!t.line)return e;if(function(e,t){const i=1e-6;return e.start.distanceTo(t.start)<i&&e.end.distanceTo(t.end)<i||e.start.distanceTo(t.end)<i&&e.end.distanceTo(t.start)<i}(t.line,e.firstLine))return e;const r=(new s.Vector3).subVectors(t.line.end,t.line.start).normalize();if(i=r,n=e.lineDir,!(Math.abs(i.dot(n))>.999))return e;const o=function(e,t,i){const n=e.clone().sub(t.start).dot(i);return t.start.clone().addScaledVector(i,n)}(e.points[0],t.line,e.lineDir),a=[...e.points,o];return{...e,points:a,cursor:e.cursor}}return"CONFIRM"===t.type&&e.points.length>=2?{kind:"positioningOffset",points:e.points,cursor:null}:"ESCAPE"===t.type?{kind:"awaitingFirstPoint"}:e;case"positioningOffset":if("MOUSE_MOVE"===t.type)return{...e,cursor:t.point.clone()};if("CLICK"===t.type){const i=Fl(e.points,t.point);return{kind:"committed",dimensions:Rl(e.points,i)}}return"ESCAPE"===t.type?{kind:"awaitingFirstPoint"}:e;case"committed":return"ESCAPE"===t.type?{kind:"awaitingFirstPoint"}:e}var i,n}function jl(e){const{pointA:t,pointB:i,offset:n}=e,r=(new s.Vector3).subVectors(i,t),o=new s.Vector3(-r.z,0,r.x).normalize(),a=t.clone().addScaledVector(o,n),l=i.clone().addScaledVector(o,n),c=(new s.Vector3).subVectors(l,a).normalize();return[{tip:a,dir:c},{tip:l,dir:c.clone().negate()}]}function $l(e,t){const{pointA:i,pointB:n,offset:r}=e,o=(new s.Vector3).subVectors(n,i),a=new s.Vector3(-o.z,0,o.x).normalize(),l=r>=0?1:-1,c=Math.abs(r),h=i.clone().addScaledVector(a,t.extensionGap*l),u=i.clone().addScaledVector(a,(c+t.extensionOvershoot)*l),d=n.clone().addScaledVector(a,t.extensionGap*l),p=n.clone().addScaledVector(a,(c+t.extensionOvershoot)*l),f=i.clone().addScaledVector(a,r),m=n.clone().addScaledVector(a,r),g=(new s.Vector3).subVectors(m,f).normalize(),w=t.lineTick(f,g,t.tickSize),y=t.lineTick(m,g.clone().negate(),t.tickSize);return[h.x,h.y,h.z,u.x,u.y,u.z,d.x,d.y,d.z,p.x,p.y,p.z,f.x,f.y,f.z,m.x,m.y,m.z,...w,...y]}function Wl(e,t,i,n){if("placingPoints"===e){const e=[];for(let i=0;i<t.length-1;i++){const n=t[i],s=t[i+1];e.push(n.x,n.y,n.z,s.x,s.y,s.z)}if(i){const n=t[t.length-1];e.push(n.x,n.y,n.z,i.x,i.y,i.z)}return e}if(!i||t.length<2)return[];const s=Fl(t,i),r=[];for(let e=0;e<t.length-1;e++)r.push(...$l({pointA:t[e],pointB:t[e+1],offset:s},n));return r}class Hl extends Ll{enabled=!0;machineState={kind:"awaitingFirstPoint"};onMachineStateChanged=new re;constructor(e){super(e),this.styles.set("default",{lineTick:vl,tickSize:.4,extensionGap:.05,extensionOvershoot:.2,color:0,textOffset:.4,fontSize:.45})}pickHandle(e,t,i=.1){const n=(new s.Matrix4).copy(e.three.matrixWorld).invert(),r=t.origin.clone().applyMatrix4(n),o=t.direction.clone().transformDirection(n).normalize(),a=new s.Ray(r,o),l=new s.Plane(new s.Vector3(0,1,0),0),c=a.intersectPlane(l,new s.Vector3);if(!c)return null;let h=null,u=i;for(const[t,i]of e.annotations.getBySystem(this)){const e=(new s.Vector3).subVectors(i.pointB,i.pointA),n=new s.Vector3(-e.z,0,e.x).normalize(),r=(new s.Vector3).addVectors(i.pointA,i.pointB).multiplyScalar(.5).addScaledVector(n,i.offset);for(const[e,n]of[["pointA",i.pointA],["pointB",i.pointB],["offset",r]]){const i=Math.hypot(c.x-n.x,c.z-n.z);i<u&&(u=i,h={uuid:t,handle:e})}}return h}sendMachineEvent(e){const t=e.drawing??null;t&&(this._previewDrawing=t);const i=Ul(this.machineState,e);if(i!==this.machineState){if(this.machineState=i,this._updatePreview(),"committed"===i.kind){if(!this._previewDrawing)return console.warn("LinearAnnotations: no drawing context — send a CLICK or SELECT_LINE with `drawing` first. Skipping."),void this._resetMachine();for(const e of i.dimensions)e.style=this.activeStyle;const e=i.dimensions.map(e=>this._persist(this._previewDrawing,e));this.onCommit.trigger(e)}this.onMachineStateChanged.trigger(this.machineState),"committed"===i.kind&&this._resetMachine()}}_buildGroup(e,t){const i=new s.Group,n=$l(e,t),r=new s.BufferGeometry;r.setAttribute("position",new s.BufferAttribute(new Float32Array(n),3));const o=new s.LineSegments(r,this._getMaterial(e.style));if(o.layers.set(1),o.userData.isDimension=!0,i.add(o),t.meshTick)for(const{tip:n,dir:r}of jl(e)){const o=t.meshTick(n,r,t.tickSize),a=new s.BufferGeometry;a.setAttribute("position",new s.BufferAttribute(new Float32Array(o),3));const l=new s.Mesh(a,this._getMeshMaterial(e.style));l.layers.set(1),l.userData.isMeshTick=!0,i.add(l)}return i}_updatePreview(){const e=this.machineState;if("placingPoints"!==e.kind&&"positioningOffset"!==e.kind)return void this._clearPreview();if(!this._previewDrawing)return void this._clearPreview();const t=this._resolveStyle(this.activeStyle);this._previewMaterial.color.setHex(t.color);const i=Wl(e.kind,e.points,e.cursor,t);if(0===i.length)return void this._clearPreview();const n=i.length/3;if(!this._previewObject||this._previewObject.geometry.attributes.position.count!==n){this._clearPreview();const e=new s.BufferGeometry;e.setAttribute("position",new s.BufferAttribute(new Float32Array(i),3)),this._previewObject=new s.LineSegments(e,this._previewMaterial),this._previewObject.layers.set(1),this._previewObject.renderOrder=1,this._previewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._previewObject)}else{const e=this._previewObject.geometry.attributes.position;e.set(i),e.needsUpdate=!0}}_resetMachine(){this.machineState={kind:"awaitingFirstPoint"},this._previewDrawing=null,this._updatePreview(),this.onMachineStateChanged.trigger(this.machineState)}}const Gl=Math.PI/180;function Zl(e,t,i,n){const r=function(e,t,i){const n=(new s.Vector3).subVectors(e,t).normalize(),r=(new s.Vector3).subVectors(i,t).normalize();return(new s.Vector3).addVectors(n,r).normalize()}(e,t,i);return(new s.Vector3).subVectors(n,t).setY(0).dot(r)}function ql(e,t,i,n){return Zl(e,t,i,n)<0}function Yl(e,t){switch(e.kind){case"awaitingFirstLine":return"CLICK"===t.type&&t.line?{kind:"awaitingSecondLine",line1:t.line.clone(),pointA:t.point.clone()}:e;case"awaitingSecondLine":if("CLICK"===t.type&&t.line){const i=(new s.Vector3).subVectors(e.line1.end,e.line1.start).normalize(),n=(new s.Vector3).subVectors(t.line.end,t.line.start).normalize();if(Math.abs(i.dot(n))>Math.cos(Gl))return e;const r=function(e,t,i,n){const r=t.x*n.z-t.z*n.x;if(Math.abs(r)<1e-10)return null;const o=(new s.Vector3).subVectors(i,e),a=(o.x*n.z-o.z*n.x)/r;return new s.Vector3(e.x+t.x*a,0,e.z+t.z*a)}(e.line1.start,i,t.line.start,n);return r?{kind:"positioningArc",pointA:e.pointA.clone(),vertex:r,pointB:t.point.clone(),cursor:null,flipped:!1}:e}return"ESCAPE"===t.type?{kind:"awaitingFirstLine"}:e;case"positioningArc":if("MOUSE_MOVE"===t.type){const i=ql(e.pointA,e.vertex,e.pointB,t.point);return{...e,cursor:t.point.clone(),flipped:i}}if("CLICK"===t.type){const i=ql(e.pointA,e.vertex,e.pointB,t.point),n=Math.max(.05,Math.abs(Zl(e.pointA,e.vertex,e.pointB,t.point)));return{kind:"committed",dimension:{uuid:s.MathUtils.generateUUID(),pointA:e.pointA.clone(),vertex:e.vertex.clone(),pointB:e.pointB.clone(),arcRadius:n,flipped:i,style:""}}}return"ESCAPE"===t.type?{kind:"awaitingFirstLine"}:e;case"committed":return"ESCAPE"===t.type?{kind:"awaitingFirstLine"}:e}}function Xl(e){const t=(new s.Vector3).subVectors(e.pointA,e.vertex).normalize(),i=(new s.Vector3).subVectors(e.pointB,e.vertex).normalize(),n=Math.atan2(t.z,t.x);let r=Math.atan2(i.z,i.x)-n;for(;r>Math.PI;)r-=2*Math.PI;for(;r<-Math.PI;)r+=2*Math.PI;e.flipped&&(r-=2*Math.sign(r)*Math.PI);const o=new s.Vector3(e.vertex.x+Math.cos(n)*e.arcRadius,0,e.vertex.z+Math.sin(n)*e.arcRadius),a=n+r,l=new s.Vector3(e.vertex.x+Math.cos(a)*e.arcRadius,0,e.vertex.z+Math.sin(a)*e.arcRadius),c=Math.sign(r);return[{tip:o,dir:new s.Vector3(-Math.sin(n)*c,0,Math.cos(n)*c)},{tip:l,dir:new s.Vector3(Math.sin(a)*c,0,-Math.cos(a)*c)}]}function Kl(e){const t=(new s.Vector3).subVectors(e.pointA,e.vertex).normalize(),i=(new s.Vector3).subVectors(e.pointB,e.vertex).normalize(),n=Math.acos(s.MathUtils.clamp(t.dot(i),-1,1));return e.flipped?2*Math.PI-n:n}function Ql(e){const t=(new s.Vector3).subVectors(e.pointA,e.vertex).normalize(),i=(new s.Vector3).subVectors(e.pointB,e.vertex).normalize(),n=Math.atan2(t.z,t.x);let r=Math.atan2(i.z,i.x)-n;for(;r>Math.PI;)r-=2*Math.PI;for(;r<-Math.PI;)r+=2*Math.PI;const o=n+r/2;return e.flipped?o+Math.PI:o}function Jl(e,t,i,n,r,o=!1){const a=Math.atan2(t.z,t.x);let l=Math.atan2(i.z,i.x)-a;for(;l>Math.PI;)l-=2*Math.PI;for(;l<-Math.PI;)l+=2*Math.PI;o&&(l-=2*Math.sign(l)*Math.PI);const c=[];for(let t=0;t<8;t++){const i=a+l*(t/8),s=a+l*((t+1)/8);c.push(e.x+Math.cos(i)*n,0,e.z+Math.sin(i)*n,e.x+Math.cos(s)*n,0,e.z+Math.sin(s)*n)}const h=new s.Vector3(e.x+Math.cos(a)*n,0,e.z+Math.sin(a)*n),u=new s.Vector3(e.x+Math.cos(a+l)*n,0,e.z+Math.sin(a+l)*n),d=e.clone().addScaledVector(t,r.extensionGap),p=e.clone().addScaledVector(i,r.extensionGap);c.push(d.x,d.y,d.z,h.x,h.y,h.z,p.x,p.y,p.z,u.x,u.y,u.z);const f=Math.sign(l),m=new s.Vector3(-Math.sin(a)*f,0,Math.cos(a)*f),g=a+l,w=new s.Vector3(Math.sin(g)*f,0,-Math.cos(g)*f);return c.push(...r.lineTick(h,m,r.tickSize),...r.lineTick(u,w,r.tickSize)),c}function ec(e,t){const i=(new s.Vector3).subVectors(e.pointA,e.vertex).normalize(),n=(new s.Vector3).subVectors(e.pointB,e.vertex).normalize();return Jl(e.vertex,i,n,e.arcRadius,t,e.flipped??!1)}function tc(e,t,i,n,r,o=!1){if(!n)return[];const a=Math.max(.05,(new s.Vector3).subVectors(n,t).setY(0).length());return Jl(t,(new s.Vector3).subVectors(e,t).normalize(),(new s.Vector3).subVectors(i,t).normalize(),a,r,o)}class ic extends Ll{enabled=!0;machineState={kind:"awaitingFirstLine"};onMachineStateChanged=new re;_secondLinePreviewObject=null;constructor(e){super(e),this.styles.set("default",{lineTick:vl,tickSize:.4,extensionGap:.05,color:0,textOffset:.25,fontSize:.45})}pickHandle(e,t,i){return null}sendMachineEvent(e){const t=e.drawing??null;if("awaitingSecondLine"===this.machineState.kind&&"MOUSE_MOVE"===e.type)return t&&(this._previewDrawing=t),void this._updateSecondLinePreview(e.point,e.line??null);const i=Yl(this.machineState,e);if(i!==this.machineState){if("awaitingSecondLine"===this.machineState.kind&&this._clearSecondLinePreview(),this.machineState=i,t&&(this._previewDrawing=t),this._updatePreview(),"committed"===i.kind){if(!this._previewDrawing)return console.warn("AngleAnnotations: CLICK that commits must include `drawing`. Skipping."),void this._resetMachine();i.dimension.style=this.activeStyle;const e=this._persist(this._previewDrawing,i.dimension);this.onCommit.trigger([e])}this.onMachineStateChanged.trigger(this.machineState),"committed"===i.kind&&this._resetMachine()}}_buildGroup(e,t){const i=new s.Group,n=ec(e,t),r=new s.BufferGeometry;r.setAttribute("position",new s.BufferAttribute(new Float32Array(n),3));const o=new s.LineSegments(r,this._getMaterial(e.style));if(o.layers.set(1),o.userData.isDimension=!0,i.add(o),t.meshTick)for(const{tip:n,dir:r}of Xl(e)){const o=t.meshTick(n,r,t.tickSize),a=new s.BufferGeometry;a.setAttribute("position",new s.BufferAttribute(new Float32Array(o),3));const l=new s.Mesh(a,this._getMeshMaterial(e.style));l.layers.set(1),l.userData.isMeshTick=!0,i.add(l)}return i}_updatePreview(){const e=this.machineState;if("positioningArc"!==e.kind)return void this._clearPreview();if(!this._previewDrawing)return void this._clearPreview();const t=this._resolveStyle(this.activeStyle),i=tc(e.pointA,e.vertex,e.pointB,e.cursor,t,e.flipped);if(0===i.length)return void this._clearPreview();const n=i.length/3;if(!this._previewObject||this._previewObject.geometry.attributes.position.count!==n){this._clearPreview();const e=new s.BufferGeometry;e.setAttribute("position",new s.BufferAttribute(new Float32Array(i),3)),this._previewObject=new s.LineSegments(e,this._previewMaterial),this._previewObject.layers.set(1),this._previewObject.renderOrder=1,this._previewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._previewObject)}else{const e=this._previewObject.geometry.attributes.position;e.set(i),e.needsUpdate=!0}}_onDispose(){this._clearSecondLinePreview()}_resetMachine(){this.machineState={kind:"awaitingFirstLine"},this._previewDrawing=null,this._updatePreview(),this.onMachineStateChanged.trigger(this.machineState)}_clearSecondLinePreview(){this._secondLinePreviewObject&&(this._secondLinePreviewObject.removeFromParent(),this._secondLinePreviewObject.geometry.dispose(),this._secondLinePreviewObject=null)}_updateSecondLinePreview(e,t){if("awaitingSecondLine"!==this.machineState.kind)return void this._clearSecondLinePreview();if(!this._previewDrawing)return void this._clearSecondLinePreview();const i=this.machineState,n=(new s.Vector3).subVectors(i.line1.end,i.line1.start).normalize();if(!t)return void this._clearSecondLinePreview();const r=(new s.Vector3).subVectors(t.end,t.start).normalize(),o=function(e,t,i,n){const r=t.x*n.z-t.z*n.x;if(Math.abs(r)<1e-6)return null;const o=i.x-e.x,a=i.z-e.z,l=(o*n.z-a*n.x)/r;return new s.Vector3(e.x+l*t.x,0,e.z+l*t.z)}(i.line1.start,n,t.start,r);if(!o)return void this._clearSecondLinePreview();const a=e.clone(),l=(new s.Vector3).subVectors(a,o).setY(0);if(l.length()<.01)return void this._clearSecondLinePreview();const c=(new s.Vector3).subVectors(i.pointA,o).normalize(),h=l.normalize(),u=Math.atan2(c.z,c.x);let d=Math.atan2(h.z,h.x)-u;for(;d>Math.PI;)d-=2*Math.PI;for(;d<-Math.PI;)d+=2*Math.PI;const p=u+d/2,f=Math.max(.1,.4*Math.min(i.pointA.distanceTo(o),a.distanceTo(o))),m=new s.Vector3(o.x+Math.cos(p)*f,0,o.z+Math.sin(p)*f),g=this._resolveStyle(this.activeStyle),w=tc(i.pointA,o,a,m,g);if(0===w.length)return void this._clearSecondLinePreview();const y=w.length/3;if(!this._secondLinePreviewObject||this._secondLinePreviewObject.geometry.attributes.position.count!==y){this._clearSecondLinePreview();const e=new s.BufferGeometry;e.setAttribute("position",new s.BufferAttribute(new Float32Array(w),3)),this._secondLinePreviewObject=new s.LineSegments(e,this._previewMaterial),this._secondLinePreviewObject.layers.set(1),this._secondLinePreviewObject.renderOrder=1,this._secondLinePreviewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._secondLinePreviewObject)}else{const e=this._secondLinePreviewObject.geometry.attributes.position;e.set(w),e.needsUpdate=!0}}}function nc(e,t){const i=t.x-e.x,n=t.z-e.z,r=Math.sqrt(i*i+n*n);if(0===r)return e.clone();const o=Math.atan2(n,i),a=Math.round(o/(Math.PI/4))*(Math.PI/4);return new s.Vector3(e.x+Math.cos(a)*r,0,e.z+Math.sin(a)*r)}function sc(e,t){switch(e.kind){case"awaitingArrowTip":return"CLICK"===t.type?{kind:"placingElbow",arrowTip:t.point.clone(),cursor:null}:e;case"placingElbow":return"MOUSE_MOVE"===t.type?{...e,cursor:t.point.clone()}:"CLICK"===t.type?{kind:"placingExtension",arrowTip:e.arrowTip,elbow:t.point.clone(),cursor:null}:"ESCAPE"===t.type?{kind:"awaitingArrowTip"}:e;case"placingExtension":return"MOUSE_MOVE"===t.type?{...e,cursor:nc(e.elbow,t.point)}:"CLICK"===t.type?{kind:"enteringText",arrowTip:e.arrowTip,elbow:e.elbow,extensionEnd:nc(e.elbow,t.point)}:"ESCAPE"===t.type?{kind:"awaitingArrowTip"}:e;case"enteringText":if("SUBMIT_TEXT"===t.type&&t.text.trim().length>0){return{kind:"committed",annotation:{uuid:s.MathUtils.generateUUID(),arrowTip:e.arrowTip.clone(),elbow:e.elbow.clone(),extensionEnd:e.extensionEnd.clone(),text:t.text.trim(),style:""}}}return"ESCAPE"===t.type?{kind:"awaitingArrowTip"}:e;case"committed":return"ESCAPE"===t.type?{kind:"awaitingArrowTip"}:e}}function rc(e,t,i,n){return"curved"===n.leaderShape?function(e,t,i,n){const r=new s.QuadraticBezierCurve3(e,t,i).getPoints(24),o=[];for(let e=0;e<r.length-1;e++){const t=r[e],i=r[e+1];o.push(t.x,t.y,t.z,i.x,i.y,i.z)}if(n.lineTick){const i=(new s.Vector3).subVectors(e,t);i.lengthSq()>1e-10&&o.push(...n.lineTick(e,i.normalize(),n.tickSize))}return o}(e,t,i,n):function(e,t,i,n){const r=[e.x,e.y,e.z,t.x,t.y,t.z,t.x,t.y,t.z,i.x,i.y,i.z];if(n.lineTick){const i=(new s.Vector3).subVectors(e,t);i.lengthSq()>1e-10&&r.push(...n.lineTick(e,i.normalize(),n.tickSize))}return r}(e,t,i,n)}function oc(e,t){return rc(e.arrowTip,e.elbow,e.extensionEnd,t)}function ac(e,t,i,n,s){return n?rc(t,"placingElbow"===e?n:i,n,s):[]}class lc extends Ll{enabled=!0;machineState={kind:"awaitingArrowTip"};onMachineStateChanged=new re;_previewMeshMaterial=new s.MeshBasicMaterial({color:16737894,side:s.DoubleSide,depthTest:!1});_previewMeshObject=null;constructor(e){super(e),this.styles.set("default",{tickSize:.4,color:0,textOffset:.1,fontSize:.45,lineTick:Cl})}pickHandle(e,t,i=.1){const n=(new s.Matrix4).copy(e.three.matrixWorld).invert(),r=t.origin.clone().applyMatrix4(n),o=t.direction.clone().transformDirection(n).normalize(),a=new s.Ray(r,o),l=new s.Plane(new s.Vector3(0,1,0),0),c=a.intersectPlane(l,new s.Vector3);if(!c)return null;let h=null,u=i;for(const[t,i]of e.annotations.getBySystem(this))for(const[e,n]of[["elbow",i.elbow],["extensionEnd",i.extensionEnd]]){const i=Math.hypot(c.x-n.x,c.z-n.z);i<u&&(u=i,h={uuid:t,handle:e})}return h}sendMachineEvent(e){const t=e.drawing??null;t&&(this._previewDrawing=t);const i=sc(this.machineState,e);if(i!==this.machineState){if(this.machineState=i,this._updatePreview(),"committed"===i.kind){if(!this._previewDrawing)return console.warn("LeaderAnnotations: commit requires a drawing. Skipping."),void this._resetMachine();i.annotation.style=this.activeStyle;const e=this._persist(this._previewDrawing,i.annotation);this.onCommit.trigger([e])}this.onMachineStateChanged.trigger(this.machineState),"committed"===i.kind&&this._resetMachine()}}_buildGroup(e,t){const i=new s.Group,n=oc(e,t),r=new s.BufferGeometry;r.setAttribute("position",new s.BufferAttribute(new Float32Array(n),3));const o=new s.LineSegments(r,this._getMaterial(e.style));if(o.layers.set(1),o.userData.isDimension=!0,i.add(o),t.meshTick){const n=(new s.Vector3).subVectors(e.arrowTip,e.elbow);if(n.lengthSq()>1e-10){n.normalize();const r=t.meshTick(e.arrowTip,n,t.tickSize),o=new s.BufferGeometry;o.setAttribute("position",new s.BufferAttribute(new Float32Array(r),3));const a=new s.Mesh(o,this._getMeshMaterial(e.style));a.layers.set(1),a.userData.isMeshArrow=!0,i.add(a)}}return i}_updatePreview(){const e=this.machineState;if("placingElbow"!==e.kind&&"placingExtension"!==e.kind)return void this._clearPreview();if(!this._previewDrawing)return void this._clearPreview();const t=this._resolveStyle(this.activeStyle),i="placingElbow"===e.kind?ac("placingElbow",e.arrowTip,null,e.cursor,t):ac("placingExtension",e.arrowTip,e.elbow,e.cursor,t);if(0===i.length)return void this._clearPreview();const n=i.length/3;if(!this._previewObject||this._previewObject.geometry.attributes.position.count!==n){this._clearPreview();const e=new s.BufferGeometry;e.setAttribute("position",new s.BufferAttribute(new Float32Array(i),3)),this._previewObject=new s.LineSegments(e,this._previewMaterial),this._previewObject.layers.set(1),this._previewObject.renderOrder=1,this._previewObject.frustumCulled=!1,this._previewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._previewObject)}else{const e=this._previewObject.geometry.attributes.position;e.set(i),e.needsUpdate=!0}if(t.meshTick){const i="placingElbow"===e.kind?e.cursor:e.elbow,n=i?(new s.Vector3).subVectors(e.arrowTip,i):null;if(n&&n.lengthSq()>1e-10){n.normalize();const i=t.meshTick(e.arrowTip,n,t.tickSize);if(this._previewMeshObject){const e=this._previewMeshObject.geometry.attributes.position;e.set(i),e.needsUpdate=!0}else{const e=new s.BufferGeometry;e.setAttribute("position",new s.BufferAttribute(new Float32Array(i),3)),this._previewMeshObject=new s.Mesh(e,this._previewMeshMaterial),this._previewMeshObject.layers.set(1),this._previewMeshObject.renderOrder=1,this._previewMeshObject.frustumCulled=!1,this._previewDrawing.three.add(this._previewMeshObject)}}else this._clearPreviewMesh()}else this._clearPreviewMesh()}_clearPreview(){super._clearPreview(),this._clearPreviewMesh()}_onDispose(){this._clearPreviewMesh(),this._previewMeshMaterial.dispose()}_resetMachine(){this.machineState={kind:"awaitingArrowTip"},this._previewDrawing=null,this._updatePreview(),this.onMachineStateChanged.trigger(this.machineState)}_clearPreviewMesh(){this._previewMeshObject&&(this._previewMeshObject.removeFromParent(),this._previewMeshObject.geometry.dispose(),this._previewMeshObject=null)}}class cc extends Ll{enabled=!0;_ownsChildGeometry=!1;definitions=new e.DataMap;constructor(e){super(e),this.styles.set("default",{color:0,textOffset:0,fontSize:0})}pickHandle(e,t,i){return null}pick(e,t=.05){const i=new s.Raycaster;i.ray.copy(e),i.params.Line={threshold:t},i.params.LineSegments={threshold:t};let n=null,r=1/0;for(const e of this._knownDrawings)for(const[t,o]of e.annotations){if(o.system!==this)continue;const e=o.three;e.updateWorldMatrix(!0,!0),e.traverse(o=>{if(o===e)return;if(!(o instanceof s.LineSegments))return;const a=[];o.raycast(i,a),a.length>0&&a[0].distance<r&&(r=a[0].distance,n=t)})}return n}define(e,t){this.definitions.set(e,t)}_buildGroup(e,t){const i=this.definitions.get(e.blockName);if(!i)throw new Error(`BlockAnnotations: block "${e.blockName}" is not defined.`);const n=new s.Group;if(i.lines){const t=new s.LineSegments(i.lines,this._getMaterial(e.style));t.layers.set(1),t.userData.isDimension=!0,n.add(t)}if(i.mesh){const t=new s.Mesh(i.mesh,this._getMeshMaterial(e.style));t.layers.set(1),t.userData.isBlockMesh=!0,n.add(t)}return n}_onAfterPersist(e,t){t.position.set(e.position.x,0,e.position.z),t.rotation.set(0,e.rotation,0),t.scale.setScalar(e.scale)}_onDispose(){for(const e of this.definitions.values())e.lines?.dispose(),e.mesh?.dispose();this.definitions.clear()}}function hc(e,t){const{position:i,direction:n}=e,{length:r}=t,o=new s.Vector3(i.x+n.x*r,0,i.z+n.z*r),a=new s.Vector3(n.x,0,n.z),l=t.lineTick(o,a,t.tickSize),c=[i.x,0,i.z,o.x,0,o.z];return new Float32Array([...c,...l])}function uc(e,t){return new s.Vector3(e.position.x+e.direction.x*t,0,e.position.z+e.direction.z*t)}function dc(e,t){switch(t){case"percentage":return`${(100*e).toFixed(2)} %`;case"ratio":return 0===e?"1:∞":`1:${(1/e).toFixed(2)}`;case"degrees":return`${(180*Math.atan(e)/Math.PI).toFixed(2)}°`}}class pc extends Ll{enabled=!0;constructor(e){super(e),this.styles.set("default",{lineTick:Sl,meshTick:El,tickSize:.4,length:3,color:0,textOffset:.1,fontSize:.45,format:"percentage"})}pickHandle(e,t,i){return null}_buildGroup(e,t){const i=new s.Group,n=hc(e,t),r=new s.BufferGeometry;r.setAttribute("position",new s.BufferAttribute(n,3));const o=new s.LineSegments(r,this._getMaterial(e.style));if(o.layers.set(1),o.userData.isDimension=!0,i.add(o),t.meshTick){const n=uc(e,t.length),r=t.meshTick(n,e.direction,t.tickSize),o=new s.BufferGeometry;o.setAttribute("position",new s.BufferAttribute(new Float32Array(r),3));const a=new s.Mesh(o,this._getMeshMaterial(e.style));a.layers.set(1),a.userData.isDimension=!0,i.add(a)}return i}}function fc(e,t){const i=t.x-e.x,n=t.z-e.z,r=Math.sqrt(i*i+n*n);if(0===r)return e.clone();const o=Math.atan2(n,i),a=Math.round(o/(Math.PI/4))*(Math.PI/4);return new s.Vector3(e.x+Math.cos(a)*r,0,e.z+Math.sin(a)*r)}function mc(e,t){switch(e.kind){case"awaitingCenter":return"CLICK"===t.type?{kind:"awaitingRadius",center:t.point.clone(),cursor:null}:e;case"awaitingRadius":if("MOUSE_MOVE"===t.type)return{...e,cursor:t.point.clone()};if("CLICK"===t.type){const i=Math.max(.1,Math.abs(t.point.x-e.center.x)),n=Math.max(.1,Math.abs(t.point.z-e.center.z));return{kind:"awaitingElbow",center:e.center,halfW:i,halfH:n,cursor:null}}return"ESCAPE"===t.type?{kind:"awaitingCenter"}:e;case"awaitingElbow":return"MOUSE_MOVE"===t.type?{...e,cursor:t.point.clone()}:"CLICK"===t.type?{kind:"awaitingExtension",center:e.center,halfW:e.halfW,halfH:e.halfH,elbow:t.point.clone(),cursor:null}:"ESCAPE"===t.type?{kind:"awaitingCenter"}:e;case"awaitingExtension":return"MOUSE_MOVE"===t.type?{...e,cursor:fc(e.elbow,t.point)}:"CLICK"===t.type?{kind:"enteringText",center:e.center,halfW:e.halfW,halfH:e.halfH,elbow:e.elbow,extensionEnd:fc(e.elbow,t.point)}:"ESCAPE"===t.type?{kind:"awaitingCenter"}:e;case"enteringText":if("SUBMIT_TEXT"===t.type&&t.text.trim().length>0){return{kind:"committed",annotation:{uuid:s.MathUtils.generateUUID(),center:e.center.clone(),halfW:e.halfW,halfH:e.halfH,elbow:e.elbow.clone(),extensionEnd:e.extensionEnd.clone(),text:t.text.trim(),style:""}}}return"ESCAPE"===t.type?{kind:"awaitingCenter"}:e;case"committed":return"ESCAPE"===t.type?{kind:"awaitingCenter"}:e}}function gc(e,t){const i=[];i.push(...t.enclosure.buildGeometry(e.center,e.halfW,e.halfH));const n=(new s.Vector3).subVectors(e.elbow,e.center),r=n.lengthSq()>1e-10?n.clone().normalize():new s.Vector3(1,0,0),o=t.enclosure.getAttachmentPoint(e.center,e.halfW,e.halfH,r);if(i.push(o.x,o.y,o.z,e.elbow.x,e.elbow.y,e.elbow.z,e.elbow.x,e.elbow.y,e.elbow.z,e.extensionEnd.x,e.extensionEnd.y,e.extensionEnd.z),t.lineTick){const n=(new s.Vector3).subVectors(e.extensionEnd,e.elbow);n.lengthSq()>1e-10&&i.push(...t.lineTick(e.extensionEnd,n.normalize(),t.tickSize))}return i}function wc(e,t,i,n,r,o,a){const l="awaitingRadius"===e?o?Math.max(.05,Math.abs(o.x-t.x)):0:i,c="awaitingRadius"===e?o?Math.max(.05,Math.abs(o.z-t.z)):0:n;if(l<1e-10||c<1e-10)return[];const h=[];if(h.push(...a.enclosure.buildGeometry(t,l,c)),"awaitingRadius"===e)return h;const u="awaitingElbow"===e?o:r;if(!u)return h;const d=(new s.Vector3).subVectors(u,t),p=d.lengthSq()>1e-10?d.clone().normalize():new s.Vector3(1,0,0),f=a.enclosure.getAttachmentPoint(t,l,c,p);return"awaitingElbow"===e?(h.push(f.x,0,f.z,u.x,0,u.z),h):o?(h.push(f.x,0,f.z,r.x,0,r.z,r.x,0,r.z,o.x,0,o.z),h):h}const yc={buildGeometry(e,t,i){const n=.25*Math.min(t,i),r=new s.Vector3(e.x-t,0,e.z-i),o=new s.Vector3(e.x+t,0,e.z-i),a=new s.Vector3(e.x+t,0,e.z+i),l=new s.Vector3(e.x-t,0,e.z+i),c=[[r,o,new s.Vector3(0,0,-1)],[o,a,new s.Vector3(1,0,0)],[a,l,new s.Vector3(0,0,1)],[l,r,new s.Vector3(-1,0,0)]],h=[];for(const[e,t,i]of c){const r=e.distanceTo(t),o=Math.max(1,Math.round(r/(2*n))),a=r/o,l=a/2,c=(new s.Vector3).subVectors(t,e).normalize();for(let t=0;t<o;t++){const n=e.clone().addScaledVector(c,(t+.5)*a),r=e.clone().addScaledVector(c,t*a),o=(new s.Vector3).subVectors(r,n);let u=r.clone();for(let e=1;e<=8;e++){const t=e/8*Math.PI,r=n.x+o.x*Math.cos(t)+i.x*l*Math.sin(t),a=n.z+o.z*Math.cos(t)+i.z*l*Math.sin(t),c=new s.Vector3(r,0,a);h.push(u.x,0,u.z,c.x,0,c.z),u=c}}}return h},getAttachmentPoint(e,t,i,n){const r=Math.abs(n.x)>1e-10?t/Math.abs(n.x):1/0,o=Math.abs(n.z)>1e-10?i/Math.abs(n.z):1/0,a=Math.min(r,o);return new s.Vector3(e.x+n.x*a,0,e.z+n.z*a)}},_c={buildGeometry(e,t,i){const n=new s.Vector3(e.x-t,0,e.z-i),r=new s.Vector3(e.x+t,0,e.z-i),o=new s.Vector3(e.x+t,0,e.z+i),a=new s.Vector3(e.x-t,0,e.z+i);return[n.x,0,n.z,r.x,0,r.z,r.x,0,r.z,o.x,0,o.z,o.x,0,o.z,a.x,0,a.z,a.x,0,a.z,n.x,0,n.z]},getAttachmentPoint(e,t,i,n){const r=Math.abs(n.x)>1e-10?t/Math.abs(n.x):1/0,o=Math.abs(n.z)>1e-10?i/Math.abs(n.z):1/0,a=Math.min(r,o);return new s.Vector3(e.x+n.x*a,0,e.z+n.z*a)}},bc={buildGeometry(e,t,i){const n=[];for(let s=0;s<32;s++){const r=s/32*Math.PI*2,o=(s+1)/32*Math.PI*2;n.push(e.x+Math.cos(r)*t,0,e.z+Math.sin(r)*i,e.x+Math.cos(o)*t,0,e.z+Math.sin(o)*i)}return n},getAttachmentPoint(e,t,i,n){const r=n.x/t,o=n.z/i,a=Math.sqrt(r*r+o*o),l=a>1e-10?1/a:t;return new s.Vector3(e.x+n.x*l,0,e.z+n.z*l)}};class vc extends Ll{enabled=!0;machineState={kind:"awaitingCenter"};onMachineStateChanged=new re;constructor(e){super(e),this.styles.set("default",{enclosure:yc,lineTick:Cl,tickSize:.4,color:22015,textOffset:.1,fontSize:.45})}pickHandle(e,t,i){return null}sendMachineEvent(e){const t=e.drawing??null;t&&(this._previewDrawing=t);const i=mc(this.machineState,e);if(i!==this.machineState){if(this.machineState=i,this._updatePreview(),"committed"===i.kind){if(!this._previewDrawing)return console.warn("CalloutAnnotations: commit requires a drawing. Pass `drawing` on the first CLICK."),void this._resetMachine();i.annotation.style=this.activeStyle;const e=this._persist(this._previewDrawing,i.annotation);this.onCommit.trigger([e])}this.onMachineStateChanged.trigger(this.machineState),"committed"===i.kind&&this._resetMachine()}}_buildGroup(e,t){const i=new s.Group,n=gc(e,t),r=new s.BufferGeometry;r.setAttribute("position",new s.BufferAttribute(new Float32Array(n),3));const o=new s.LineSegments(r,this._getMaterial(e.style));if(o.layers.set(1),o.userData.isDimension=!0,i.add(o),t.meshTick){const n=(new s.Vector3).subVectors(e.extensionEnd,e.elbow);if(n.lengthSq()>1e-10){n.normalize();const r=t.meshTick(e.extensionEnd,n,t.tickSize),o=new s.BufferGeometry;o.setAttribute("position",new s.BufferAttribute(new Float32Array(r),3));const a=new s.Mesh(o,this._getMeshMaterial(e.style));a.layers.set(1),a.userData.isMeshArrow=!0,i.add(a)}}return i}_updatePreview(){const e=this.machineState;if("awaitingRadius"!==e.kind&&"awaitingElbow"!==e.kind&&"awaitingExtension"!==e.kind)return void this._clearPreview();if(!this._previewDrawing)return;const t=this._resolveStyle(this.activeStyle),i=(()=>{switch(e.kind){case"awaitingRadius":return wc("awaitingRadius",e.center,0,0,null,e.cursor,t);case"awaitingElbow":return wc("awaitingElbow",e.center,e.halfW,e.halfH,null,e.cursor,t);case"awaitingExtension":return wc("awaitingExtension",e.center,e.halfW,e.halfH,e.elbow,e.cursor,t)}})();if(0===i.length)return void this._clearPreview();const n=i.length/3;if(!this._previewObject||this._previewObject.geometry.attributes.position.count!==n){this._clearPreview();const e=new s.BufferGeometry;e.setAttribute("position",new s.BufferAttribute(new Float32Array(i),3)),this._previewObject=new s.LineSegments(e,this._previewMaterial),this._previewObject.layers.set(1),this._previewObject.renderOrder=1,this._previewObject.frustumCulled=!1,this._previewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._previewObject)}else{const e=this._previewObject.geometry.attributes.position;e.set(i),e.needsUpdate=!0}}_resetMachine(){this.machineState={kind:"awaitingCenter"},this._clearPreview(),this._previewDrawing=null,this.onMachineStateChanged.trigger(this.machineState)}}class xc extends le{static uuid="5c7d3b9a-4e8f-4a2b-9c1d-0e3f2a5b7c8d";enabled=!0;list=new e.DataMap;systems=new e.DataMap;onDisposed=new re;constructor(e){super(e),e.add(xc.uuid,this),this.list.onBeforeDelete.add(({value:e})=>e.dispose()),this.systems.onBeforeDelete.add(({value:e})=>e.dispose())}use(e){if(this.systems.has(e))return this.systems.get(e);const t=new e(this.components);return this.systems.set(e,t),t}create(e){const t=new Vl(this.components);t.world=e,e.scene.three.add(t.three),e.onDisposed.add(()=>this.list.delete(t.uuid));const i=e.camera;return i.three.layers.enable(1),i instanceof Ba&&(i.threePersp.layers.enable(1),i.threeOrtho.layers.enable(1)),this.list.set(t.uuid,t),t}dispose(){this.list.clear(),this.systems.clear(),this.onDisposed.trigger(),this.onDisposed.reset()}}const Cc=[[16711680,1],[16776960,2],[65280,3],[65535,4],[255,5],[16711935,6],[16777215,7],[0,7]];function Sc(e){const t=e>>16&255,i=e>>8&255,n=255&e;let s=7,r=1/0;for(const[e,o]of Cc){const a=(t-(e>>16&255))**2+(i-(e>>8&255))**2+(n-(255&e))**2;a<r&&(r=a,s=o)}return s}const Ac="\0HANDSEED\0";class Tc{_lines=[];_handleCounter=1;p(e,t){return this._lines.push(String(e),String(t)),this}n(e,t,i=6){return this._lines.push(String(e),t.toFixed(i)),this}handle(){return(this._handleCounter++).toString(16).toUpperCase()}entityHeader(e,t,i){return this._lines.push("0",e,"5",this.handle(),"100","AcDbEntity","8",t,"62",String(i)),this}symbolTable(e,t){return this._lines.push("0","TABLE","2",e,"5",this.handle(),"100","AcDbSymbolTable","70",String(t)),this}symbolRecord(e,t){return this._lines.push("0",e,"5",this.handle(),"100","AcDbSymbolTableRecord","100",t),this}writeHandSeed(){return this._lines.push("9","$HANDSEED","5",Ac),this}build(){return(this._lines.join("\n")+"\n").replace(Ac,this._handleCounter.toString(16).toUpperCase())}}class Pc{constructor(e){this._components=e}_components;precision=2;config={trueColor:!1};_viewport=null;_paperSlot=null;_annotationLayers=new Map;_systemExporters=new Map;registerSystemExporter(e,t){this._systemExporters.set(e,t)}export(e,t){const i=!!t,n=new Tc,s=new Map;for(const t of e)for(const e of t.drawing.layers.values())s.has(e.name)||s.set(e.name,e);const r=[...s.values()],o=this._components.get(xc).systems.get(cc),a=o?[...o.definitions.keys()]:[];this._writeHeader(n,i),this._writeTables(n,r,a),this._writeBlocks(n,o??null),n.p(0,"SECTION").p(2,"ENTITIES"),i&&t&&this._writePaperBorders(n,t);for(const s of e){s.drawing.three.traverse(e=>{e.userData.isDimension&&e.userData.annotationUuid&&this._annotationLayers.set(e.userData.annotationUuid,e.userData.layer??"0")});for(const e of s.viewports){if(this._viewport=e.viewport??null,i&&e.viewport){const i=e.viewport,n=t.heightMm-2*t.margin;this._paperSlot={x:e.x??0,y:n-(e.y??0),mmPerUnit:1e3/i.drawingScale,vpLeft:i.left,vpTop:i.top}}else this._paperSlot=null;this._writeViewportBorder(n),this._writeRawLines(n,s.drawing),this._writeLinearAnnotations(n,s.drawing),this._writeAngleAnnotations(n,s.drawing),this._writeLeaderAnnotations(n,s.drawing),this._writeSlopeAnnotations(n,s.drawing),this._writeCalloutAnnotations(n,s.drawing),this._writeBlockInsertions(n,s.drawing),this._writeCustomSystems(n,s.drawing)}this._annotationLayers.clear()}return n.p(0,"ENDSEC"),this._writeObjects(n),n.p(0,"EOF"),this._viewport=null,this._paperSlot=null,n.build()}_writeHeader(e,t){e.p(0,"SECTION").p(2,"HEADER"),e.p(9,"$ACADVER").p(1,this.config.trueColor?"AC1018":"AC1015"),e.p(9,"$DWGCODEPAGE").p(3,"ANSI_1252"),e.p(9,"$INSUNITS").p(70,t?4:6),e.writeHandSeed(),e.p(0,"ENDSEC")}_writeTables(e,t,i){e.p(0,"SECTION").p(2,"TABLES"),e.symbolTable("VPORT",0).p(0,"ENDTAB"),e.symbolTable("LTYPE",1),e.symbolRecord("LTYPE","AcDbLinetypeTableRecord").p(2,"CONTINUOUS").p(70,0).p(3,"Solid line").p(72,65).p(73,0).n(40,0),e.p(0,"ENDTAB"),e.symbolTable("LAYER",t.length);for(const i of t){const t=Sc(i.material.color.getHex());e.symbolRecord("LAYER","AcDbLayerTableRecord").p(2,i.name).p(70,0).p(62,t).p(6,"CONTINUOUS")}e.p(0,"ENDTAB"),e.symbolTable("STYLE",1),e.symbolRecord("STYLE","AcDbTextStyleTableRecord").p(2,"STANDARD").p(70,0).n(40,0).n(41,1).n(50,0).p(71,0).n(42,.2).p(3,"txt").p(4,""),e.p(0,"ENDTAB"),e.symbolTable("VIEW",0).p(0,"ENDTAB"),e.symbolTable("UCS",0).p(0,"ENDTAB"),e.symbolTable("APPID",1),e.symbolRecord("APPID","AcDbRegAppTableRecord").p(2,"ACAD").p(70,0),e.p(0,"ENDTAB"),e.symbolTable("DIMSTYLE",0).p(0,"ENDTAB");const n=["*Model_Space","*Paper_Space",...i];e.symbolTable("BLOCK_RECORD",n.length);for(const t of n)e.symbolRecord("BLOCK_RECORD","AcDbBlockTableRecord").p(2,t);e.p(0,"ENDTAB"),e.p(0,"ENDSEC")}_writeBlocks(e,t){if(e.p(0,"SECTION").p(2,"BLOCKS"),this._writeBlock(e,"*Model_Space",null),this._writeBlock(e,"*Paper_Space",null),t)for(const[i,n]of t.definitions)this._writeBlock(e,i,n.lines??null);e.p(0,"ENDSEC")}_writeBlock(e,t,i){if(e.p(0,"BLOCK").p(5,e.handle()).p(100,"AcDbEntity").p(8,"0").p(100,"AcDbBlockBegin").p(2,t).p(70,0).n(10,0).n(20,0).n(30,0).p(3,t).p(1,""),i){const t=this._viewport,n=this._paperSlot;this._viewport=null,this._paperSlot=null,this._writeGeoAsLines(e,i,"0"),this._viewport=t,this._paperSlot=n}e.p(0,"ENDBLK").p(5,e.handle()).p(100,"AcDbEntity").p(8,"0").p(100,"AcDbBlockEnd")}_writeViewportBorder(e){if(!this._viewport)return;const t=this._viewport,i=this._tx(t.left),n=this._tx(t.right),s=this._ty(-t.bottom),r=this._ty(-t.top);this._writeRawLine(e,i,s,n,s,"0",7),this._writeRawLine(e,n,s,n,r,"0",7),this._writeRawLine(e,n,r,i,r,"0",7),this._writeRawLine(e,i,r,i,s,"0",7)}_writePaperBorders(e,t){const{margin:i,widthMm:n,heightMm:s}=t,r=n-2*i,o=s-2*i;this._writeRawLine(e,0,0,r,0,"0",7),this._writeRawLine(e,r,0,r,o,"0",7),this._writeRawLine(e,r,o,0,o,"0",7),this._writeRawLine(e,0,o,0,0,"0",7),this._writeRawLine(e,-i,-i,r+i,-i,"0",7),this._writeRawLine(e,r+i,-i,r+i,o+i,"0",7),this._writeRawLine(e,r+i,o+i,-i,o+i,"0",7),this._writeRawLine(e,-i,o+i,-i,-i,"0",7)}_writeObjects(e){e.p(0,"SECTION").p(2,"OBJECTS"),e.p(0,"DICTIONARY").p(5,e.handle()).p(330,0).p(100,"AcDbDictionary").p(281,1),e.p(0,"ENDSEC")}_writeRawLines(e,t){t.three.traverse(t=>{if(!(t instanceof s.LineSegments))return;if(t.userData.isDimension)return;if(t.parent?.userData.blockUuid)return;if(!t.visible)return;const i=t.userData.layer??"0",n=t.material.color.getHex();this._writeGeoAsLines(e,t.geometry,i,Sc(n),n)})}_writeLinearAnnotations(e,t){const i=this._components.get(xc).systems.get(Hl);if(i)for(const[,n]of t.annotations.getBySystem(i)){const r=i.styles.get(n.style)??i.styles.get("default"),o=Sc(r.color),a=this._annotationLayers.get(n.uuid)??"0";if(!1===t.layers.get(a)?.visible)continue;const l=$l(n,r);if(!this._fullyInViewport(this._bboxFromPositions(l)))continue;if(this._writePairsAsLines(e,l,a,o,r.color),r.meshTick)for(const{tip:t,dir:i}of jl(n))this._writeMeshTriangles(e,r.meshTick(t,i,r.tickSize),a,o,r.color);const c=(new s.Vector3).subVectors(n.pointB,n.pointA),h=new s.Vector3(-c.z,0,c.x).normalize(),u=n.offset>=0?1:-1,d=n.pointA.clone().addScaledVector(h,n.offset),p=n.pointB.clone().addScaledVector(h,n.offset),f=d.clone().add(p).multiplyScalar(.5).addScaledVector(h,(r.textOffset+.5*r.fontSize)*u),m=r.unit??{factor:1,suffix:"m"},g=`${(n.pointA.distanceTo(n.pointB)*m.factor).toFixed(this.precision)} ${m.suffix}`;this._writeText(e,g,f.x,f.z,r.fontSize,a,o,this._textAngle(c.x,c.z),1,2,r.color)}}_writeAngleAnnotations(e,t){const i=this._components.get(xc).systems.get(ic);if(i)for(const[,n]of t.annotations.getBySystem(i)){const r=i.styles.get(n.style)??i.styles.get("default"),o=Sc(r.color),a=this._annotationLayers.get(n.uuid)??"0";if(!1===t.layers.get(a)?.visible)continue;const l=ec(n,r);if(!this._fullyInViewport(this._bboxFromPositions(l)))continue;if(this._writePairsAsLines(e,l,a,o,r.color),r.meshTick)for(const{tip:t,dir:i}of Xl(n))this._writeMeshTriangles(e,r.meshTick(t,i,r.tickSize),a,o,r.color);const c=Ql(n),h=n.arcRadius+r.textOffset,u=n.vertex.x+Math.cos(c)*h,d=n.vertex.z+Math.sin(c)*h,p=s.MathUtils.radToDeg(Kl(n));this._writeText(e,`${p.toFixed(this.precision)}°`,u,d,r.fontSize,a,o,0,1,0,r.color)}}_writeLeaderAnnotations(e,t){const i=this._components.get(xc).systems.get(lc);if(i)for(const[,n]of t.annotations.getBySystem(i)){const r=i.styles.get(n.style)??i.styles.get("default"),o=Sc(r.color),a=this._annotationLayers.get(n.uuid)??"0";if(!1===t.layers.get(a)?.visible)continue;const l=oc(n,r);if(!this._fullyInViewport(this._bboxFromPositions(l)))continue;if(this._writePairsAsLines(e,l,a,o,r.color),r.meshTick){const t=(new s.Vector3).subVectors(n.arrowTip,n.elbow);t.lengthSq()>1e-10&&this._writeMeshTriangles(e,r.meshTick(n.arrowTip,t.normalize(),r.tickSize),a,o,r.color)}const c=(new s.Vector3).subVectors(n.extensionEnd,n.elbow).setY(0).normalize(),h=c.x<-.1?2:c.x>.1?0:1,u=1===h?.5*r.fontSize:0,d=n.extensionEnd.clone().addScaledVector(c,r.textOffset+u);this._writeText(e,n.text,d.x,d.z,r.fontSize,a,o,0,h,2,r.color)}}_writeSlopeAnnotations(e,t){const i=this._components.get(xc).systems.get(pc);if(i)for(const[,n]of t.annotations.getBySystem(i)){const r=i.styles.get(n.style)??i.styles.get("default"),o=Sc(r.color),a=this._annotationLayers.get(n.uuid)??"0";if(!1===t.layers.get(a)?.visible)continue;const l=hc(n,r);if(!this._fullyInViewport(this._bboxFromPositions(l)))continue;if(this._writePairsAsLines(e,l,a,o,r.color),r.meshTick){const t=uc(n,r.length);this._writeMeshTriangles(e,r.meshTick(t,n.direction,r.tickSize),a,o,r.color)}const c=new s.Vector3(n.position.x+n.direction.x*r.length,0,n.position.z+n.direction.z*r.length),h=n.position.clone().add(c).multiplyScalar(.5).addScaledVector(new s.Vector3(-n.direction.z,0,n.direction.x),r.textOffset+r.fontSize);this._writeText(e,dc(n.slope,r.format),h.x,h.z,r.fontSize,a,o,this._textAngle(n.direction.x,n.direction.z),1,0,r.color)}}_writeCalloutAnnotations(e,t){const i=this._components.get(xc).systems.get(vc);if(i)for(const[,n]of t.annotations.getBySystem(i)){const r=i.styles.get(n.style)??i.styles.get("default"),o=Sc(r.color),a=this._annotationLayers.get(n.uuid)??"0";if(!1===t.layers.get(a)?.visible)continue;const l=gc(n,r);if(!this._fullyInViewport(this._bboxFromPositions(l)))continue;if(this._writePairsAsLines(e,l,a,o,r.color),r.meshTick){const t=(new s.Vector3).subVectors(n.extensionEnd,n.elbow);t.lengthSq()>1e-10&&this._writeMeshTriangles(e,r.meshTick(n.extensionEnd,t.normalize(),r.tickSize),a,o,r.color)}const c=(new s.Vector3).subVectors(n.extensionEnd,n.elbow).setY(0).normalize(),h=c.x<-.1?2:c.x>.1?0:1,u=1===h?.5*r.fontSize:0,d=n.extensionEnd.clone().addScaledVector(c,r.textOffset+u);this._writeText(e,n.text,d.x,d.z,r.fontSize,a,o,0,h,2,r.color)}}_writeBlockInsertions(e,t){const i=this._components.get(xc).systems.get(cc);if(i)for(const[,n]of t.annotations.getBySystem(i)){if(!this._inViewport(n.position.x,n.position.z))continue;const t=i.styles.get(n.style)??i.styles.get("default"),r=Sc(t.color),o=-s.MathUtils.radToDeg(n.rotation),a=n.scale*this._scale();e.entityHeader("INSERT","0",r),this._emitTrueColor(e,t.color),e.p(100,"AcDbBlockReference").p(2,n.blockName).n(10,this._tx(n.position.x)).n(20,this._ty(n.position.z)).n(30,0).n(41,a).n(42,a).n(43,a).n(50,o)}}_writeGeoAsLines(e,t,i,n=7,r){const o=t.attributes.position;if(o)for(let t=0;t+1<o.count;t+=2){const a=this._clipSegment(new s.Vector3(o.getX(t),0,o.getZ(t)),new s.Vector3(o.getX(t+1),0,o.getZ(t+1)));a&&this._writeLine(e,a.start.x,a.start.z,a.end.x,a.end.z,i,n,r)}}_writePairsAsLines(e,t,i,n=7,r){for(let o=0;o+5<t.length;o+=6){const a=this._clipSegment(new s.Vector3(t[o],0,t[o+2]),new s.Vector3(t[o+3],0,t[o+5]));a&&this._writeLine(e,a.start.x,a.start.z,a.end.x,a.end.z,i,n,r)}}_emitTrueColor(e,t){this.config.trueColor&&void 0!==t&&e.p(420,t)}_writeLine(e,t,i,n,s,r,o,a){e.entityHeader("LINE",r,o),this._emitTrueColor(e,a),e.p(100,"AcDbLine").n(10,this._tx(t)).n(20,this._ty(i)).n(30,0).n(11,this._tx(n)).n(21,this._ty(s)).n(31,0)}_writeRawLine(e,t,i,n,s,r,o){e.entityHeader("LINE",r,o).p(100,"AcDbLine").n(10,t).n(20,i).n(30,0).n(11,n).n(21,s).n(31,0)}_writeSolid(e,t,i,n,s,r,o,a,l,c){e.entityHeader("SOLID",a,l),this._emitTrueColor(e,c),e.p(100,"AcDbTrace").n(10,this._tx(t)).n(20,this._ty(i)).n(30,0).n(11,this._tx(n)).n(21,this._ty(s)).n(31,0).n(12,this._tx(r)).n(22,this._ty(o)).n(32,0).n(13,this._tx(r)).n(23,this._ty(o)).n(33,0)}_writeMeshTriangles(e,t,i,n,s){for(let r=0;r+8<t.length;r+=9)this._writeSolid(e,t[r],t[r+2],t[r+3],t[r+5],t[r+6],t[r+8],i,n,s)}_writeText(e,t,i,n,s,r,o,a=0,l=0,c=0,h){const u=this._tx(i),d=this._ty(n);e.entityHeader("TEXT",r,o),this._emitTrueColor(e,h),e.p(100,"AcDbText").n(10,u).n(20,d).n(30,0).n(40,s*this._scale()).n(50,a).p(1,t),0===l&&0===c||(0!==l&&e.p(72,l),0!==c&&e.p(73,c),e.n(11,u).n(21,d).n(31,0))}_tx(e){return this._paperSlot?this._paperSlot.x+(e-this._paperSlot.vpLeft)*this._paperSlot.mmPerUnit:this._viewport?e-this._viewport.left:e}_ty(e){return this._paperSlot?this._paperSlot.y-(e+this._paperSlot.vpTop)*this._paperSlot.mmPerUnit:this._viewport?-e-this._viewport.bottom:-e}_scale(){return this._paperSlot?this._paperSlot.mmPerUnit:1}_clipSegment(e,t){return this._viewport?this._viewport.clipLine(new s.Line3(e,t)):new s.Line3(e,t)}_inViewport(e,t){return!this._viewport||this._viewport.bbox.containsPoint(new s.Vector3(e,0,t))}_bboxFromPositions(e){const t=new s.Box3;for(let i=0;i+2<e.length;i+=3)t.expandByPoint(new s.Vector3(e[i],0,e[i+2]));return t}_fullyInViewport(e){return!this._viewport||this._viewport.bbox.containsBox(e)}_textAngle(e,t){let i=Math.atan2(-t,e);return(i>Math.PI/2||i<=-Math.PI/2)&&(i+=Math.PI),s.MathUtils.radToDeg(i)}_writeCustomSystems(e,t){if(0===this._systemExporters.size)return;const i=this._makeContext(e);for(const[e,t]of this._systemExporters){const n=this._components.get(xc).systems.get(e);n&&t(n,i)}}_makeContext(e){return{writeLine:(t,i,n,s,r="0",o=7)=>{this._writeLine(e,t,i,n,s,r,o)},writePairs:(t,i="0",n=7)=>{this._writePairsAsLines(e,t,i,n)},writeMeshTriangles:(t,i="0",n=7)=>{this._writeMeshTriangles(e,t,i,n)},writeText:(t,i,n,s,r={})=>{this._writeText(e,t,i,n,s,r.layer??"0",r.aciColor??7,r.rotDeg??0,r.hAlign??0)},hexToAci:Sc,textAngle:(e,t)=>this._textAngle(e,t)}}}class Ec extends le{static uuid="e9a2c3d4-5f67-4b89-a012-1c3d5e7f9b2a";enabled=!0;exporter=new Pc(this.components);constructor(e){super(e),e.add(Ec.uuid,this)}}export{ic as AngleAnnotations,Ll as AnnotationSystem,xl as ArrowTick,oe as AsyncEvent,Ha as BCFTopics,Wa as BCFTopicsConfigManager,ae as Base,he as BaseCamera,ue as BaseRenderer,pe as BaseScene,ce as BaseWorldItem,cc as BlockAnnotations,zo as BoundingBoxer,vc as CalloutAnnotations,bc as CircleEnclosure,Bo as Classifier,qa as Clipper,yc as CloudEnclosure,Ua as Comment,le as Component,Ma as Components,ci as ConfigManager,li as Configurator,oi as ControlsUtils,ri as DataMap,fe as DataSet,vl as DiagonalTick,de as Disposer,Al as DotTick,Ml as DrawingAnnotations,Il as DrawingLayers,Ll as DrawingSystem,Dl as DrawingViewport,zl as DrawingViewportHelper,kl as DrawingViewports,Pc as DxfExporter,Ec as DxfManager,Po as EdgeProjector,re as Event,ai as EventManager,Yo as FastModelPicker,Xo as FastModelPickers,El as FilledArrowTick,Tl as FilledCircleTick,Pl as FilledSquareTick,Do as FinderQuery,Ia as FirstPersonMode,hr as FragmentsManager,Ea as Grids,Io as Hider,rl as IDSAttribute,ol as IDSClassification,al as IDSEntity,nl as IDSFacet,cl as IDSMaterial,hl as IDSPartOf,ll as IDSProperty,ul as IDSSpecification,_l as IDSSpecifications,Eo as IfcFragmentSettings,Mo as IfcLoader,ko as ItemsFinder,lc as LeaderAnnotations,Hl as LinearAnnotations,bl as MeasurementUtils,si as ModelIdMapUtils,hi as Mouse,Sl as NoTick,Cl as OpenArrowTick,za as OrbitMode,Ba as OrthoPerspectiveCamera,Da as PlanMode,ka as ProjectionManager,fa as Raycasters,_c as RectEnclosure,va as RendererMode,il as ShadowedScene,Sa as SimpleCamera,Pa as SimpleGrid,Ta as SimpleGridConfigManager,Ga as SimplePlane,pa as SimpleRaycaster,xa as SimpleRenderer,_a as SimpleScene,ya as SimpleSceneConfigManager,ma as SimpleWorld,pc as SlopeAnnotations,Ko as SnapClass,Jo as SnapResolver,da as SnapResolvers,Vl as TechnicalDrawing,Bl as TechnicalDrawingHelper,xc as TechnicalDrawings,ja as Topic,me as UUID,Nl as Units,ni as VertexPicker,Qa as View,Ya as Viewpoint,Ka as Viewpoints,Ja as Views,Aa as Worlds,ii as XML,Yl as angleDimensionMachine,ec as buildAnglePositions,tc as buildAnglePreviewPositions,gc as buildCalloutPositions,wc as buildCalloutPreviewPositions,$l as buildDimensionPositions,Rl as buildDimensions,oc as buildLeaderPositions,ac as buildLeaderPreviewPositions,Wl as buildPreviewPositions,hc as buildSlopePositions,mc as calloutAnnotationMachine,Ol as computeAlignmentMatrix,Kl as computeAngle,Ql as computeBisectorAngle,Fl as computeOffset,$a as extensionsImporter,dc as formatSlope,Xl as getAngleTickEndpoints,jl as getDimensionTickEndpoints,uc as getSlopeTip,sc as leaderAnnotationMachine,Ul as linearDimensionMachine,Ca as setOrbitPoint};