@thatopen/components 3.4.1 → 3.4.2
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.
- package/dist/index.cjs +21 -0
- package/dist/index.d.ts +20 -1
- package/dist/index.min.cjs +1 -1
- package/dist/index.min.mjs +1 -1
- package/dist/index.mjs +21 -0
- package/package.json +2 -2
package/dist/index.min.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
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 d,Plane as u,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 S,Points as T,Sphere as C,BatchedMesh as A,OrthographicCamera as E,WebGLRenderTarget as M,Scene as P,Color as z,ShaderMaterial as I,Vector4 as D,NoBlending as k,GLSL3 as B,MathUtils as O,BufferGeometry as V}from"three";import*as L from"three/webgpu";import{instancedArray as N,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 q,If as Z,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 dt 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 ut extends dt{constructor(){super(...arguments),e(this,"hasCameraControls",()=>"controls"in this)}}class pt extends dt{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",[])}updateClippingPlanes(){this.onClippingPlanesUpdated.trigger()}setPlane(t,e,i){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)}}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 dt{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 St=function(t){const e=vt.exec(t);return!(null==e)};const Tt={allowBooleanAttributes:!1,unpairedTags:[]};function Ct(t){return" "===t||"\t"===t||"\n"===t||"\r"===t}function At(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 Bt("InvalidXml","XML declaration allowed only at the start of the document.",Lt(t,e));if("?"==t[e]&&">"==t[e+1]){e++;break}continue}return e}function Et(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 Mt='"',Pt="'";function zt(t,e){let i="",n="",s=!1;for(;e<t.length;e++){if(t[e]===Mt||t[e]===Pt)""===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 It=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function Dt(t,e){const i=xt(t,It),n={};for(let t=0;t<i.length;t++){if(0===i[t][1].length)return Bt("InvalidAttr","Attribute '"+i[t][2]+"' has no space in starting.",Nt(i[t]));if(void 0!==i[t][3]&&void 0===i[t][4])return Bt("InvalidAttr","Attribute '"+i[t][2]+"' is without value.",Nt(i[t]));if(void 0===i[t][3]&&!e.allowBooleanAttributes)return Bt("InvalidAttr","boolean attribute '"+i[t][2]+"' is not allowed.",Nt(i[t]));const s=i[t][2];if(!Ot(s))return Bt("InvalidAttr","Attribute '"+s+"' is an invalid name.",Nt(i[t]));if(n.hasOwnProperty(s))return Bt("InvalidAttr","Attribute '"+s+"' is repeated.",Nt(i[t]));n[s]=1}return!0}function kt(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 Bt(t,e,i){return{err:{code:t,msg:e,line:i.line||i,col:i.col}}}function Ot(t){return St(t)}function Vt(t){return St(t)}function Lt(t,e){const i=t.substring(0,e).split(/\r?\n/);return{line:i.length,col:i[i.length-1].length+1}}function Nt(t){return t.startIndex+t[1].length}const Ft={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,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(t,e,i){return t},captureMetaData:!1};function Rt(t){return"boolean"==typeof t?{enabled:t,maxEntitySize:1e4,maxExpansionDepth:10,maxTotalExpansions:1e3,maxExpandedLength:1e5,allowedTags:null,tagFilter:null}:"object"==typeof t&&null!==t?{enabled:!1!==t.enabled,maxEntitySize:t.maxEntitySize??1e4,maxExpansionDepth:t.maxExpansionDepth??10,maxTotalExpansions:t.maxTotalExpansions??1e3,maxExpandedLength:t.maxExpandedLength??1e5,allowedTags:t.allowedTags??null,tagFilter:t.tagFilter??null}:Rt(!0)}const Ut=function(t){const e=Object.assign({},Ft,t);return e.processEntities=Rt(e.processEntities),e};let jt;jt="function"!=typeof Symbol?"@@xmlMetadata":Symbol("XML Node Metadata");class $t{constructor(t){this.tagname=t,this.child=[],this[":@"]={}}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][jt]={startIndex:e})}static getMetaDataSymbol(){return jt}}class Wt{constructor(t){this.suppressValidationErr=!t,this.options=t}readDocType(t,e){const i={};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 n=1,s=!1,r=!1,o="";for(;e<t.length;e++)if("<"!==t[e]||r)if(">"===t[e]){if(r?"-"===t[e-1]&&"-"===t[e-2]&&(r=!1,n--):n--,0===n)break}else"["===t[e]?s=!0:o+=t[e];else{if(s&&Ht(t,"!ENTITY",e)){let n,s;if(e+=7,[n,s,e]=this.readEntityExp(t,e+1,this.suppressValidationErr),-1===s.indexOf("&")){const t=n.replace(/[.\-+*:]/g,"\\.");i[n]={regx:RegExp(`&${t};`,"g"),val:s}}}else if(s&&Ht(t,"!ELEMENT",e)){e+=8;const{index:i}=this.readElementExp(t,e+1);e=i}else if(s&&Ht(t,"!ATTLIST",e))e+=8;else if(s&&Ht(t,"!NOTATION",e)){e+=9;const{index:i}=this.readNotationExp(t,e+1,this.suppressValidationErr);e=i}else{if(!Ht(t,"!--",e))throw new Error("Invalid DOCTYPE");r=!0}n++,o=""}if(0!==n)throw new Error("Unclosed DOCTYPE")}return{entities:i,i:e}}readEntityExp(t,e){e=Gt(t,e);let i="";for(;e<t.length&&!/\s/.test(t[e])&&'"'!==t[e]&&"'"!==t[e];)i+=t[e],e++;if(qt(i),e=Gt(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 n="";if([e,n]=this.readIdentifierVal(t,e,"entity"),!1!==this.options.enabled&&this.options.maxEntitySize&&n.length>this.options.maxEntitySize)throw new Error(`Entity "${i}" size (${n.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`);return[i,n,--e]}readNotationExp(t,e){e=Gt(t,e);let i="";for(;e<t.length&&!/\s/.test(t[e]);)i+=t[e],e++;!this.suppressValidationErr&&qt(i),e=Gt(t,e);const n=t.substring(e,e+6).toUpperCase();if(!this.suppressValidationErr&&"SYSTEM"!==n&&"PUBLIC"!==n)throw new Error(`Expected SYSTEM or PUBLIC, found "${n}"`);e+=n.length,e=Gt(t,e);let s=null,r=null;if("PUBLIC"===n)[e,s]=this.readIdentifierVal(t,e,"publicIdentifier"),'"'!==t[e=Gt(t,e)]&&"'"!==t[e]||([e,r]=this.readIdentifierVal(t,e,"systemIdentifier"));else if("SYSTEM"===n&&([e,r]=this.readIdentifierVal(t,e,"systemIdentifier"),!this.suppressValidationErr&&!r))throw new Error("Missing mandatory system identifier for SYSTEM notation");return{notationName:i,publicIdentifier:s,systemIdentifier:r,index:--e}}readIdentifierVal(t,e,i){let n="";const s=t[e];if('"'!==s&&"'"!==s)throw new Error(`Expected quoted string, found "${s}"`);for(e++;e<t.length&&t[e]!==s;)n+=t[e],e++;if(t[e]!==s)throw new Error(`Unterminated ${i} value`);return[++e,n]}readElementExp(t,e){e=Gt(t,e);let i="";for(;e<t.length&&!/\s/.test(t[e]);)i+=t[e],e++;if(!this.suppressValidationErr&&!St(i))throw new Error(`Invalid element name: "${i}"`);let n="";if("E"===t[e=Gt(t,e)]&&Ht(t,"MPTY",e))e+=4;else if("A"===t[e]&&Ht(t,"NY",e))e+=2;else if("("===t[e]){for(e++;e<t.length&&")"!==t[e];)n+=t[e],e++;if(")"!==t[e])throw new Error("Unterminated content model")}else if(!this.suppressValidationErr)throw new Error(`Invalid Element Expression, found "${t[e]}"`);return{elementName:i,contentModel:n.trim(),index:e}}readAttlistExp(t,e){e=Gt(t,e);let i="";for(;e<t.length&&!/\s/.test(t[e]);)i+=t[e],e++;qt(i),e=Gt(t,e);let n="";for(;e<t.length&&!/\s/.test(t[e]);)n+=t[e],e++;if(!qt(n))throw new Error(`Invalid attribute name: "${n}"`);e=Gt(t,e);let s="";if("NOTATION"===t.substring(e,e+8).toUpperCase()){if(s="NOTATION","("!==t[e=Gt(t,e+=8)])throw new Error(`Expected '(', found "${t[e]}"`);e++;let i=[];for(;e<t.length&&")"!==t[e];){let n="";for(;e<t.length&&"|"!==t[e]&&")"!==t[e];)n+=t[e],e++;if(n=n.trim(),!qt(n))throw new Error(`Invalid notation name: "${n}"`);i.push(n),"|"===t[e]&&(e++,e=Gt(t,e))}if(")"!==t[e])throw new Error("Unterminated list of notations");e++,s+=" ("+i.join("|")+")"}else{for(;e<t.length&&!/\s/.test(t[e]);)s+=t[e],e++;const i=["CDATA","ID","IDREF","IDREFS","ENTITY","ENTITIES","NMTOKEN","NMTOKENS"];if(!this.suppressValidationErr&&!i.includes(s.toUpperCase()))throw new Error(`Invalid attribute type: "${s}"`)}e=Gt(t,e);let r="";return"#REQUIRED"===t.substring(e,e+8).toUpperCase()?(r="#REQUIRED",e+=8):"#IMPLIED"===t.substring(e,e+7).toUpperCase()?(r="#IMPLIED",e+=7):[e,r]=this.readIdentifierVal(t,e,"ATTLIST"),{elementName:i,attributeName:n,attributeType:s,defaultValue:r,index:e}}}const Gt=(t,e)=>{for(;e<t.length&&/\s/.test(t[e]);)e++;return e};function Ht(t,e,i){for(let n=0;n<e.length;n++)if(e[n]!==t[i+n+1])return!1;return!0}function qt(t){if(St(t))return t;throw new Error(`Invalid entity name ${t}`)}const Zt=/^[-+]?0x[a-fA-F0-9]+$/,Yt=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,Xt={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function Kt(t,e={}){if(e=Object.assign({},Xt,e),!t||"string"!=typeof t)return t;let i=t.trim();if(void 0!==e.skipLike&&e.skipLike.test(i))return t;if("0"===t)return 0;if(e.hex&&Zt.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(i.includes("e")||i.includes("E"))return function(t,e,i){if(!i.eNotation)return t;const n=e.match(Qt);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?i.leadingZeros&&!a?(e=(n[1]||"")+n[3],Number(e)):t:Number(e)}return t}(t,i,e);{const n=Yt.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}}const Qt=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function Jt(t){return"function"==typeof t?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}class te{constructor(t){if(this.options=t,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"¢"},pound:{regex:/&(pound|#163);/g,val:"£"},yen:{regex:/&(yen|#165);/g,val:"¥"},euro:{regex:/&(euro|#8364);/g,val:"€"},copyright:{regex:/&(copy|#169);/g,val:"©"},reg:{regex:/&(reg|#174);/g,val:"®"},inr:{regex:/&(inr|#8377);/g,val:"₹"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(t,e)=>me(e,10,"&#")},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(t,e)=>me(e,16,"&#x")}},this.addExternalEntities=ee,this.parseXml=oe,this.parseTextData=ie,this.resolveNameSpace=ne,this.buildAttributesMap=re,this.isItStopNode=he,this.replaceEntitiesValue=le,this.readStopNodeData=pe,this.saveTextToParentTag=ce,this.addChild=ae,this.ignoreAttributesFn=Jt(this.options.ignoreAttributes),this.entityExpansionCount=0,this.currentExpandedLength=0,this.options.stopNodes&&this.options.stopNodes.length>0){this.stopNodesExact=new Set,this.stopNodesWildcard=new Set;for(let t=0;t<this.options.stopNodes.length;t++){const e=this.options.stopNodes[t];"string"==typeof e&&(e.startsWith("*.")?this.stopNodesWildcard.add(e.substring(2)):this.stopNodesExact.add(e))}}}}function ee(t){const e=Object.keys(t);for(let i=0;i<e.length;i++){const n=e[i],s=n.replace(/[.\-+*:]/g,"\\.");this.lastEntities[n]={regex:new RegExp("&"+s+";","g"),val:t[n]}}}function ie(t,e,i,n,s,r,o){if(void 0!==t&&(this.options.trimValues&&!n&&(t=t.trim()),t.length>0)){o||(t=this.replaceEntitiesValue(t,e,i));const n=this.options.tagValueProcessor(e,t,i,s,r);if(null==n)return t;if(typeof n!=typeof t||n!==t)return n;if(this.options.trimValues)return fe(t,this.options.parseTagValue,this.options.numberParseOptions);return t.trim()===t?fe(t,this.options.parseTagValue,this.options.numberParseOptions):t}}function ne(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 re(t,e,i){if(!0!==this.options.ignoreAttributes&&"string"==typeof t){const n=xt(t,se),s=n.length,r={};for(let t=0;t<s;t++){const s=this.resolveNameSpace(n[t][1]);if(this.ignoreAttributesFn(s,e))continue;let o=n[t][4],a=this.options.attributeNamePrefix+s;if(s.length)if(this.options.transformAttributeName&&(a=this.options.transformAttributeName(a)),"__proto__"===a&&(a="#__proto__"),void 0!==o){this.options.trimValues&&(o=o.trim()),o=this.replaceEntitiesValue(o,i,e);const t=this.options.attributeValueProcessor(s,o,e);r[a]=null==t?o:typeof t!=typeof o||t!==o?t:fe(o,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(r[a]=!0)}if(!Object.keys(r).length)return;if(this.options.attributesGroupName){const t={};return t[this.options.attributesGroupName]=r,t}return r}}const oe=function(t){t=t.replace(/\r\n?/g,"\n");const e=new $t("!xml");let i=e,n="",s="";this.entityExpansionCount=0,this.currentExpandedLength=0;const r=new Wt(this.options.processEntities);for(let o=0;o<t.length;o++){if("<"===t[o])if("/"===t[o+1]){const e=de(t,">",o,"Closing Tag is not closed.");let r=t.substring(o+2,e).trim();if(this.options.removeNSPrefix){const t=r.indexOf(":");-1!==t&&(r=r.substr(t+1))}this.options.transformTagName&&(r=this.options.transformTagName(r)),i&&(n=this.saveTextToParentTag(n,i,s));const a=s.substring(s.lastIndexOf(".")+1);if(r&&-1!==this.options.unpairedTags.indexOf(r))throw new Error(`Unpaired tag can not be used as closing tag: </${r}>`);let l=0;a&&-1!==this.options.unpairedTags.indexOf(a)?(l=s.lastIndexOf(".",s.lastIndexOf(".")-1),this.tagsNodeStack.pop()):l=s.lastIndexOf("."),s=s.substring(0,l),i=this.tagsNodeStack.pop(),n="",o=e}else if("?"===t[o+1]){let e=ue(t,o,!1,"?>");if(!e)throw new Error("Pi Tag is not closed.");if(n=this.saveTextToParentTag(n,i,s),this.options.ignoreDeclaration&&"?xml"===e.tagName||this.options.ignorePiTags);else{const t=new $t(e.tagName);t.add(this.options.textNodeName,""),e.tagName!==e.tagExp&&e.attrExpPresent&&(t[":@"]=this.buildAttributesMap(e.tagExp,s,e.tagName)),this.addChild(i,t,s,o)}o=e.closeIndex+1}else if("!--"===t.substr(o+1,3)){const e=de(t,"--\x3e",o+4,"Comment is not closed.");if(this.options.commentPropName){const r=t.substring(o+4,e-2);n=this.saveTextToParentTag(n,i,s),i.add(this.options.commentPropName,[{[this.options.textNodeName]:r}])}o=e}else if("!D"===t.substr(o+1,2)){const e=r.readDocType(t,o);this.docTypeEntities=e.entities,o=e.i}else if("!["===t.substr(o+1,2)){const e=de(t,"]]>",o,"CDATA is not closed.")-2,r=t.substring(o+9,e);n=this.saveTextToParentTag(n,i,s);let a=this.parseTextData(r,i.tagname,s,!0,!1,!0,!0);null==a&&(a=""),this.options.cdataPropName?i.add(this.options.cdataPropName,[{[this.options.textNodeName]:r}]):i.add(this.options.textNodeName,a),o=e+2}else{let r=ue(t,o,this.options.removeNSPrefix),a=r.tagName;const l=r.rawTagName;let c=r.tagExp,h=r.attrExpPresent,d=r.closeIndex;if(this.options.transformTagName){const t=this.options.transformTagName(a);c===a&&(c=t),a=t}i&&n&&"!xml"!==i.tagname&&(n=this.saveTextToParentTag(n,i,s,!1));const u=i;u&&-1!==this.options.unpairedTags.indexOf(u.tagname)&&(i=this.tagsNodeStack.pop(),s=s.substring(0,s.lastIndexOf("."))),a!==e.tagname&&(s+=s?"."+a:a);const p=o;if(this.isItStopNode(this.stopNodesExact,this.stopNodesWildcard,s,a)){let e="";if(c.length>0&&c.lastIndexOf("/")===c.length-1)"/"===a[a.length-1]?(a=a.substr(0,a.length-1),s=s.substr(0,s.length-1),c=a):c=c.substr(0,c.length-1),o=r.closeIndex;else if(-1!==this.options.unpairedTags.indexOf(a))o=r.closeIndex;else{const i=this.readStopNodeData(t,l,d+1);if(!i)throw new Error(`Unexpected end of ${l}`);o=i.i,e=i.tagContent}const n=new $t(a);a!==c&&h&&(n[":@"]=this.buildAttributesMap(c,s,a)),e&&(e=this.parseTextData(e,a,s,!0,h,!0,!0)),s=s.substr(0,s.lastIndexOf(".")),n.add(this.options.textNodeName,e),this.addChild(i,n,s,p)}else{if(c.length>0&&c.lastIndexOf("/")===c.length-1){if("/"===a[a.length-1]?(a=a.substr(0,a.length-1),s=s.substr(0,s.length-1),c=a):c=c.substr(0,c.length-1),this.options.transformTagName){const t=this.options.transformTagName(a);c===a&&(c=t),a=t}const t=new $t(a);a!==c&&h&&(t[":@"]=this.buildAttributesMap(c,s,a)),this.addChild(i,t,s,p),s=s.substr(0,s.lastIndexOf("."))}else{const t=new $t(a);this.tagsNodeStack.push(i),a!==c&&h&&(t[":@"]=this.buildAttributesMap(c,s,a)),this.addChild(i,t,s,p),i=t}n="",o=d}}else n+=t[o]}return e.child};function ae(t,e,i,n){this.options.captureMetaData||(n=void 0);const s=this.options.updateTag(e.tagname,i,e[":@"]);!1===s||("string"==typeof s?(e.tagname=s,t.addChild(e,n)):t.addChild(e,n))}const le=function(t,e,i){if(-1===t.indexOf("&"))return t;const n=this.options.processEntities;if(!n.enabled)return t;if(n.allowedTags&&!n.allowedTags.includes(e))return t;if(n.tagFilter&&!n.tagFilter(e,i))return t;for(let e in this.docTypeEntities){const i=this.docTypeEntities[e],s=t.match(i.regx);if(s){if(this.entityExpansionCount+=s.length,n.maxTotalExpansions&&this.entityExpansionCount>n.maxTotalExpansions)throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${n.maxTotalExpansions}`);const e=t.length;if(t=t.replace(i.regx,i.val),n.maxExpandedLength&&(this.currentExpandedLength+=t.length-e,this.currentExpandedLength>n.maxExpandedLength))throw new Error(`Total expanded content size exceeded: ${this.currentExpandedLength} > ${n.maxExpandedLength}`)}}if(-1===t.indexOf("&"))return t;for(let e in this.lastEntities){const i=this.lastEntities[e];t=t.replace(i.regex,i.val)}if(-1===t.indexOf("&"))return t;if(this.options.htmlEntities)for(let e in this.htmlEntities){const i=this.htmlEntities[e];t=t.replace(i.regex,i.val)}return t=t.replace(this.ampEntity.regex,this.ampEntity.val)};function ce(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 he(t,e,i,n){return!(!e||!e.has(n))||!(!t||!t.has(i))}function de(t,e,i,n){const s=t.indexOf(e,i);if(-1===s)throw new Error(n);return s+e.length-1}function ue(t,e,i,n=">"){const s=function(t,e,i=">"){let n,s="";for(let r=e;r<t.length;r++){let e=t[r];if(n)e===n&&(n="");else if('"'===e||"'"===e)n=e;else if(e===i[0]){if(!i[1])return{data:s,index:r};if(t[r+1]===i[1])return{data:s,index:r}}else"\t"===e&&(e=" ");s+=e}}(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 pe(t,e,i){const n=i;let s=1;for(;i<t.length;i++)if("<"===t[i])if("/"===t[i+1]){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("?"===t[i+1]){i=de(t,"?>",i+1,"StopNode is not closed.")}else if("!--"===t.substr(i+1,3)){i=de(t,"--\x3e",i+3,"StopNode is not closed.")}else if("!["===t.substr(i+1,2)){i=de(t,"]]>",i,"StopNode is not closed.")-2}else{const n=ue(t,i,">");if(n){(n&&n.tagName)===e&&"/"!==n.tagExp[n.tagExp.length-1]&&s++,i=n.closeIndex}}}function fe(t,e,i){if(e&&"string"==typeof t){const e=t.trim();return"true"===e||"false"!==e&&Kt(t,i)}return void 0!==t?t:""}function me(t,e,i){const n=Number.parseInt(t,e);return n>=0&&n<=1114111?String.fromCodePoint(n):i+t+";"}const ge=$t.getMetaDataSymbol();function we(t,e){return ye(t,e)}function ye(t,e,i){let n;const s={};for(let r=0;r<t.length;r++){const o=t[r],a=_e(o);let l="";if(l=void 0===i?a:i+"."+a,a===e.textNodeName)void 0===n?n=o[a]:n+=""+o[a];else{if(void 0===a)continue;if(o[a]){let t=ye(o[a],e,l);const i=ve(t,e);void 0!==o[ge]&&(t[ge]=o[ge]),o[":@"]?be(t,o[":@"],l,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!==s[a]&&s.hasOwnProperty(a)?(Array.isArray(s[a])||(s[a]=[s[a]]),s[a].push(t)):e.isArray(a,l,i)?s[a]=[t]:s[a]=t}}}return"string"==typeof n?n.length>0&&(s[e.textNodeName]=n):void 0!==n&&(s[e.textNodeName]=n),s}function _e(t){const e=Object.keys(t);for(let t=0;t<e.length;t++){const i=e[t];if(":@"!==i)return i}}function be(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];n.isArray(r,i+"."+r,!0,!0)?t[r]=[e[r]]:t[r]=e[r]}}}function ve(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 xe{constructor(t){this.externalEntities={},this.options=Ut(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({},Tt,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=At(t,r),r.err)return r}else{if("<"!==t[r]){if(Ct(t[r]))continue;return Bt("InvalidChar","char '"+t[r]+"' is not expected.",Lt(t,r))}{let o=r;if(r++,"!"===t[r]){r=Et(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--),!Vt(l)){let e;return e=0===l.trim().length?"Invalid space after '<'.":"Tag '"+l+"' is an invalid name.",Bt("InvalidTag",e,Lt(t,r))}const c=zt(t,r);if(!1===c)return Bt("InvalidAttr","Attributes for '"+l+"' have open quote.",Lt(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=Dt(h,e);if(!0!==s)return Bt(s.err.code,s.err.msg,Lt(t,i+s.err.line));n=!0}else if(a){if(!c.tagClosed)return Bt("InvalidTag","Closing tag '"+l+"' doesn't have proper closing.",Lt(t,r));if(h.trim().length>0)return Bt("InvalidTag","Closing tag '"+l+"' can't have attributes or invalid starting.",Lt(t,o));if(0===i.length)return Bt("InvalidTag","Closing tag '"+l+"' has not been opened.",Lt(t,o));{const e=i.pop();if(l!==e.tagName){let i=Lt(t,e.tagStartPos);return Bt("InvalidTag","Expected closing tag '"+e.tagName+"' (opened in line "+i.line+", col "+i.col+") instead of closing tag '"+l+"'.",Lt(t,o))}0==i.length&&(s=!0)}}else{const a=Dt(h,e);if(!0!==a)return Bt(a.err.code,a.err.msg,Lt(t,r-h.length+a.err.line));if(!0===s)return Bt("InvalidXml","Multiple possible root nodes found.",Lt(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=Et(t,r);continue}if("?"!==t[r+1])break;if(r=At(t,++r),r.err)return r}else if("&"===t[r]){const e=kt(t,r);if(-1==e)return Bt("InvalidChar","char '&' is not expected.",Lt(t,r));r=e}else if(!0===s&&!Ct(t[r]))return Bt("InvalidXml","Extra text at the end",Lt(t,r));"<"===t[r]&&r--}}}return n?1==i.length?Bt("InvalidTag","Unclosed tag '"+i[0].tagName+"'.",Lt(t,i[0].tagStartPos)):!(i.length>0)||Bt("InvalidXml","Invalid '"+JSON.stringify(i.map(t=>t.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):Bt("InvalidXml","Start tag expected.",1)}(t,e);if(!0!==i)throw Error(`${i.err.msg}:${i.err.line}:${i.err.col}`)}const i=new te(this.options);i.addExternalEntities(this.externalEntities);const n=i.parseXml(t);return this.options.preserveOrder||void 0===n?n:we(n,this.options)}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 '
'");if("&"===e)throw new Error("An entity with value '&' is not permitted");this.externalEntities[t]=e}static getMetaDataSymbol(){return $t.getMetaDataSymbol()}}function Se(t,e){let i="";return e.format&&e.indentBy.length>0&&(i="\n"),Te(t,e,"",i)}function Te(t,e,i,n){let s="",r=!1;for(let o=0;o<t.length;o++){const a=t[o],l=Ce(a);if(void 0===l)continue;let c="";if(c=0===i.length?l:`${i}.${l}`,l===e.textNodeName){let t=a[l];Ee(c,e)||(t=e.tagValueProcessor(l,t),t=Me(t,e)),r&&(s+=n),s+=t,r=!1;continue}if(l===e.cdataPropName){r&&(s+=n),s+=`<![CDATA[${a[l][0][e.textNodeName]}]]>`,r=!1;continue}if(l===e.commentPropName){s+=n+`\x3c!--${a[l][0][e.textNodeName]}--\x3e`,r=!0;continue}if("?"===l[0]){const t=Ae(a[":@"],e),i="?xml"===l?"":n;let o=a[l][0][e.textNodeName];o=0!==o.length?" "+o:"",s+=i+`<${l}${o}${t}?>`,r=!0;continue}let h=n;""!==h&&(h+=e.indentBy);const d=n+`<${l}${Ae(a[":@"],e)}`,u=Te(a[l],e,c,h);-1!==e.unpairedTags.indexOf(l)?e.suppressUnpairedNode?s+=d+">":s+=d+"/>":u&&0!==u.length||!e.suppressEmptyNode?u&&u.endsWith(">")?s+=d+`>${u}${n}</${l}>`:(s+=d+">",u&&""!==n&&(u.includes("/>")||u.includes("</"))?s+=n+e.indentBy+u+n:s+=u,s+=`</${l}>`):s+=d+"/>",r=!0}return s}function Ce(t){const e=Object.keys(t);for(let i=0;i<e.length;i++){const n=e[i];if(t.hasOwnProperty(n)&&":@"!==n)return n}}function Ae(t,e){let i="";if(t&&!e.ignoreAttributes)for(let n in t){if(!t.hasOwnProperty(n))continue;let s=e.attributeValueProcessor(n,t[n]);s=Me(s,e),!0===s&&e.suppressBooleanAttributes?i+=` ${n.substr(e.attributeNamePrefix.length)}`:i+=` ${n.substr(e.attributeNamePrefix.length)}="${s}"`}return i}function Ee(t,e){let i=(t=t.substr(0,t.length-e.textNodeName.length-1)).substr(t.lastIndexOf(".")+1);for(let n in e.stopNodes)if(e.stopNodes[n]===t||e.stopNodes[n]==="*."+i)return!0;return!1}function Me(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 Pe={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:"&"},{regex:new RegExp(">","g"),val:">"},{regex:new RegExp("<","g"),val:"<"},{regex:new RegExp("'","g"),val:"'"},{regex:new RegExp('"',"g"),val:"""}],processEntities:!0,stopNodes:[],oneListGroup:!1};function ze(t){this.options=Object.assign({},Pe,t),!0===this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn=Jt(this.options.ignoreAttributes),this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=ke),this.processTextOrObjNode=Ie,this.options.format?(this.indentate=De,this.tagEndChar=">\n",this.newLine="\n"):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}function Ie(t,e,i,n){const s=this.j2x(t,i+1,n.concat(e));return void 0!==t[this.options.textNodeName]&&1===Object.keys(t).length?this.buildTextValNode(t[this.options.textNodeName],e,s.attrStr,i):this.buildObjectNode(s.val,e,s.attrStr,i)}function De(t){return this.options.indentBy.repeat(t)}function ke(t){return!(!t.startsWith(this.options.attributeNamePrefix)||t===this.options.textNodeName)&&t.substr(this.attrPrefixLen)}ze.prototype.build=function(t){return this.options.preserveOrder?Se(t,this.options):(Array.isArray(t)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(t={[this.options.arrayNodeName]:t}),this.j2x(t,0,[]).val)},ze.prototype.j2x=function(t,e,i){let n="",s="";const r=i.join(".");for(let o in t)if(Object.prototype.hasOwnProperty.call(t,o))if(void 0===t[o])this.isAttribute(o)&&(s+="");else if(null===t[o])this.isAttribute(o)||o===this.options.cdataPropName?s+="":"?"===o[0]?s+=this.indentate(e)+"<"+o+"?"+this.tagEndChar:s+=this.indentate(e)+"<"+o+"/"+this.tagEndChar;else if(t[o]instanceof Date)s+=this.buildTextValNode(t[o],o,"",e);else if("object"!=typeof t[o]){const i=this.isAttribute(o);if(i&&!this.ignoreAttributesFn(i,r))n+=this.buildAttrPairStr(i,""+t[o]);else if(!i)if(o===this.options.textNodeName){let e=this.options.tagValueProcessor(o,""+t[o]);s+=this.replaceEntitiesValue(e)}else s+=this.buildTextValNode(t[o],o,"",e)}else if(Array.isArray(t[o])){const n=t[o].length;let r="",a="";for(let l=0;l<n;l++){const n=t[o][l];if(void 0===n);else if(null===n)"?"===o[0]?s+=this.indentate(e)+"<"+o+"?"+this.tagEndChar:s+=this.indentate(e)+"<"+o+"/"+this.tagEndChar;else if("object"==typeof n)if(this.options.oneListGroup){const t=this.j2x(n,e+1,i.concat(o));r+=t.val,this.options.attributesGroupName&&n.hasOwnProperty(this.options.attributesGroupName)&&(a+=t.attrStr)}else r+=this.processTextOrObjNode(n,o,e,i);else if(this.options.oneListGroup){let t=this.options.tagValueProcessor(o,n);t=this.replaceEntitiesValue(t),r+=t}else r+=this.buildTextValNode(n,o,"",e)}this.options.oneListGroup&&(r=this.buildObjectNode(r,o,a,e)),s+=r}else if(this.options.attributesGroupName&&o===this.options.attributesGroupName){const e=Object.keys(t[o]),i=e.length;for(let s=0;s<i;s++)n+=this.buildAttrPairStr(e[s],""+t[o][e[s]])}else s+=this.processTextOrObjNode(t[o],o,e,i);return{attrStr:n,val:s}},ze.prototype.buildAttrPairStr=function(t,e){return e=this.options.attributeValueProcessor(t,""+e),e=this.replaceEntitiesValue(e),this.options.suppressBooleanAttributes&&"true"===e?" "+t:" "+t+'="'+e+'"'},ze.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}},ze.prototype.closeTag=function(t){let e="";return-1!==this.options.unpairedTags.indexOf(t)?this.options.suppressUnpairedNode||(e="/"):e=this.options.suppressEmptyNode?"/":`></${t}`,e},ze.prototype.buildTextValNode=function(t,e,i,n){if(!1!==this.options.cdataPropName&&e===this.options.cdataPropName)return this.indentate(n)+`<![CDATA[${t}]]>`+this.newLine;if(!1!==this.options.commentPropName&&e===this.options.commentPropName)return this.indentate(n)+`\x3c!--${t}--\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}},ze.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 Be{}e(Be,"parser",new xe({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(Be,"builder",new ze({attributeNamePrefix:"$",ignoreAttributes:!1,suppressBooleanAttributes:!1}));class Oe 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(Co).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 Ve{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=Ve.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=Ve.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=Ve.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 Le 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 Ne{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 Fe{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 Re{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(je).list.set(this.uuid,this)}get controls(){return Ne.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(Ne.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(Ne.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 Ue=class t extends ht{constructor(i){super(i),e(this,"list",new n),e(this,"enabled",!0),i.add(t.uuid,this)}};e(Ue,"uuid","b8c764e0-6b24-4e77-9a32-35fa728ee5b4");let je=Ue;class $e{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 We=1.25,Ge=32,He=Math.pow(2,-24),qe=Symbol("SKIP_GENERATION"),Ze={strategy:0,maxDepth:40,maxLeafSize:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null,[qe]:!1};function Ye(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 Xe(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 Ke(t,e){e.set(t)}function Qe(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 Je(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 ti(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 ei(t,e){return 65535===e[t+15]}function ii(t,e){return e[t+6]}function ni(t,e){return e[t+14]}function si(t){return t+8}function ri(t,e){return t+8*e[t+6]}function oi(t,e){return e[t+7]}function ai(t){return t}function li(t,e,i,n,s){let r=1/0,o=1/0,a=1/0,l=-1/0,c=-1/0,h=-1/0,d=1/0,u=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<d&&(d=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<u&&(u=y),y>m&&(m=y);const x=t[n+4],S=t[n+5],T=x-S,C=x+S;T<a&&(a=T),C>h&&(h=C),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]=d,s[1]=u,s[2]=p,s[3]=f,s[4]=m,s[5]=g}const ci=32,hi=(t,e)=>t.candidate-e.candidate,di=new Array(ci).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),ui=new Float32Array(6);class pi{constructor(){this.boundingData=new Float32Array(6)}}let fi,mi,gi,wi;const yi=Math.pow(2,32);function _i(t){return"count"in t?1:1+_i(t.left)+_i(t.right)}function bi(t,e,i){return fi=new Float32Array(i),mi=new Uint32Array(i),gi=new Uint16Array(i),wi=new Uint8Array(i),vi(t,e)}function vi(t,e){const i=t/4,n=t/2,s="count"in e,r=e.boundingData;for(let t=0;t<6;t++)fi[i+t]=r[t];if(s)return e.buffer?(wi.set(new Uint8Array(e.buffer),t),t+e.buffer.byteLength):(mi[i+6]=e.offset,gi[n+14]=e.count,gi[n+15]=65535,t+Ge);{const{left:n,right:s,splitAxis:r}=e;let o=vi(t+Ge,n);const a=o/Ge-t/Ge;if(a>yi)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return mi[i+6]=a,mi[i+7]=r,vi(o,s)}}function xi(t,e,i,n,s,r){const{maxDepth:o,verbose:a,maxLeafSize:l,strategy:c,onProgress:h}=s,d=t.primitiveBuffer,u=t.primitiveBufferStride,p=new Float32Array(6);let f=!1;const m=new pi;return li(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=Xe(e),-1!==o&&(a=(e[o]+e[o+3])/2);else if(1===r)o=Xe(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=ti(t);let l=We*s;const c=i.offset||0,h=6*(n-c),d=6*(n+s-c);for(let t=0;t<3;t++){const n=e[t],c=(e[t+3]-n)/ci;if(s<8){const e=[...di];e.length=s;let n=0;for(let s=h;s<d;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;Je(s,i,o)}e.sort(hi);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<d;n+=6){const s=i[n+2*t];for(let t=0;t<c;t++){const r=e[t];s>=r.candidate?Je(n,i,r.rightCacheBounds):(Je(n,i,r.leftCacheBounds),r.count++)}}for(let i=0;i<c;i++){const n=e[i],c=n.count,h=s-n.count,d=n.leftCacheBounds,u=n.rightCacheBounds;let p=0;0!==c&&(p=ti(d)/r);let f=0;0!==h&&(f=ti(u)/r);const m=1+We*(p*c+f*h);m<l&&(o=t,l=m,a=n.candidate)}}else{for(let t=0;t<ci;t++){const e=di[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<d;e+=6){let s=~~((i[e+2*t]-n)/c);s>=ci&&(s=31);const r=di[s];r.count++,Je(e,i,r.bounds)}const e=di[31];Ke(e.bounds,e.rightCacheBounds);for(let t=30;t>=0;t--){const e=di[t],i=di[t+1];Qe(e.bounds,i.rightCacheBounds,e.rightCacheBounds)}let u=0;for(let e=0;e<31;e++){const i=di[e],n=i.count,c=i.bounds,h=di[e+1].rightCacheBounds;0!==n&&(0===u?Ke(c,ui):Qe(c,ui,ui)),u+=n;let d=0,p=0;0!==u&&(d=ti(ui)/r);const f=s-u;0!==f&&(p=ti(h)/r);const m=1+We*(d*u+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--}}(d,u,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 pi,o=n,a=w-n;i.left=r,li(e,o,a,r.boundingData,p),t(r,o,a,p,h+1);const l=new pi,c=w,d=s-a;i.right=l,li(e,c,d,l.boundingData,p),t(l,c,d,p,h+1)}return i}(m,i,n,p),m;function g(t){h&&h((t-r.offset)/r.count)}}function Si(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=xi(t,a,n.offset,n.count,e,o),r=_i(s),l=new i(Ge*r);return bi(0,s,l),l})}class Ti{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 Ci{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 Ai=new Ci;let Ei,Mi;const Pi=[],zi=new Ti(()=>new a);function Ii(t,e,i,n,s,r){Ei=zi.getPrimitive(),Mi=zi.getPrimitive(),Pi.push(Ei,Mi),Ai.setBuffer(t._roots[e]);const o=Di(0,t.geometry,i,n,s,r);Ai.clearBuffer(),zi.releasePrimitive(Ei),zi.releasePrimitive(Mi),Pi.pop(),Pi.pop();const a=Pi.length;return a>0&&(Mi=Pi[a-1],Ei=Pi[a-2]),o}function Di(t,e,i,n,s=null,r=0,o=0){const{float32Array:a,uint16Array:l,uint32Array:c}=Ai;let h=2*t;if(ei(h,l)){const e=ii(t,c),i=ni(h,l);return Ye(t,a,Ei),n(e,i,!1,o,r+t/8,Ei)}{let h=function(t){const{uint16Array:e,uint32Array:i}=Ai;let n=2*t;for(;!ei(n,e);)n=2*(t=si(t));return ii(t,i)},d=function(t){const{uint16Array:e,uint32Array:i}=Ai;let n=2*t;for(;!ei(n,e);)n=2*(t=ri(t,i));return ii(t,i)+ni(n,e)};const u=si(t),p=ri(t,c);let f,m,g,w,y=u,_=p;if(s&&(g=Ei,w=Mi,Ye(y,a,g),Ye(_,a,w),f=s(g),m=s(w),m<f)){y=p,_=u;const t=f;f=m,m=t,g=w}g||(g=Ei,Ye(y,a,g));const b=i(g,ei(2*y,l),f,o+1,r+y/8);let v;if(2===b){const t=h(y);v=n(t,d(y)-t,!0,o+1,r+y/8,g)}else v=b&&Di(y,e,i,n,s,r,o+1);if(v)return!0;w=Mi,Ye(_,a,w);const x=i(w,ei(2*_,l),m,o+1,r+_/8);let S;if(2===x){const t=h(_);S=n(t,d(_)-t,!0,o+1,r+_/8,w)}else S=x&&Di(_,e,i,n,s,r,o+1);return!!S}}const ki=new Ai.constructor,Bi=new Ai.constructor,Oi=new Ti(()=>new a),Vi=new a,Li=new a,Ni=new a,Fi=new a;let Ri=!1;function Ui(t,e,i,n,s,r=0,o=0,a=0,l=0,c=null,h=!1){let d,u;h?(d=Bi,u=ki):(d=ki,u=Bi);const p=d.float32Array,f=d.uint32Array,m=d.uint16Array,g=u.float32Array,w=u.uint32Array,y=u.uint16Array,_=2*e,b=ei(2*t,m),v=ei(_,y);let x=!1;if(v&&b)x=h?s(ii(e,w),ni(2*e,y),ii(t,f),ni(2*t,m),l,o+e/8,a,r+t/8):s(ii(t,f),ni(2*t,m),ii(e,w),ni(2*e,y),a,r+t/8,l,o+e/8);else if(v){const c=Oi.getPrimitive();Ye(e,g,c),c.applyMatrix4(i);const d=si(t),u=ri(t,f);Ye(d,p,Vi),Ye(u,p,Li);const m=c.intersectsBox(Vi),w=c.intersectsBox(Li);x=m&&Ui(e,d,n,i,s,o,r,l,a+1,c,!h)||w&&Ui(e,u,n,i,s,o,r,l,a+1,c,!h),Oi.releasePrimitive(c)}else{const d=si(e),u=ri(e,w);Ye(d,g,Ni),Ye(u,g,Fi);const m=c.intersectsBox(Ni),y=c.intersectsBox(Fi);if(m&&y)x=Ui(t,d,i,n,s,r,o,a,l+1,c,h)||Ui(t,u,i,n,s,r,o,a,l+1,c,h);else if(m)if(b)x=Ui(t,d,i,n,s,r,o,a,l+1,c,h);else{const e=Oi.getPrimitive();e.copy(Ni).applyMatrix4(i);const c=si(t),u=ri(t,f);Ye(c,p,Vi),Ye(u,p,Li);const m=e.intersectsBox(Vi),g=e.intersectsBox(Li);x=m&&Ui(d,c,n,i,s,o,r,l,a+1,e,!h)||g&&Ui(d,u,n,i,s,o,r,l,a+1,e,!h),Oi.releasePrimitive(e)}else if(y)if(b)x=Ui(t,u,i,n,s,r,o,a,l+1,c,h);else{const e=Oi.getPrimitive();e.copy(Fi).applyMatrix4(i);const c=si(t),d=ri(t,f);Ye(c,p,Vi),Ye(d,p,Li);const m=e.intersectsBox(Vi),g=e.intersectsBox(Li);x=m&&Ui(u,c,n,i,s,o,r,l,a+1,e,!h)||g&&Ui(u,d,n,i,s,o,r,l,a+1,e,!h),Oi.releasePrimitive(e)}}return x}const ji=new a,$i=new Float32Array(6);class Wi{constructor(){this._roots=null,this.primitiveBuffer=null,this.primitiveBufferStride=null}init(t){Si(this,t={...Ze,...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,$i,0);const[t,e,n,h,d,u]=$i;t<s&&(s=t),h>a&&(a=h),e<r&&(r=e),d>l&&(l=d),n<o&&(o=n),u>c&&(c=u)}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,$i,0);const[t,e,r,o,a,l]=$i,c=(t+o)/2,h=(e+a)/2,d=(r+l)/2,u=(o-t)/2,p=(a-e)/2,f=(l-r)/2,m=6*(s-n);i[m+0]=c,i[m+1]=u+(Math.abs(c)+u)*He,i[m+2]=h,i[m+3]=p+(Math.abs(h)+p)*He,i[m+4]=d,i[m+5]=f+(Math.abs(d)+f)*He}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/Ge;for(let e=0;e<o;e++){const i=8*e;ei(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=ei(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=si(r),a=ri(r,n),c=oi(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/Ge-1;t>=0;t--){const e=8*t,i=2*e;if(ei(i,s)){const t=ii(e,n),o=ni(i,s);this.writePrimitiveRangeBounds(t,o,$i,0),r.set($i,e)}else{const t=si(e),i=ri(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=>{Ye(0,new Float32Array(e),ji),t.union(ji)}),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=Ii(this,t,i,n,e,l),a)break;l+=s.byteLength/Ge}return a}bvhcast(t,e,i){let{intersectsRanges:n}=i;return function(t,e,i,n){if(Ri)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");Ri=!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++){ki.setBuffer(s[t]),c=0;const e=Oi.getPrimitive();Ye(ai(0),ki.float32Array,e),e.applyMatrix4(h);for(let t=0,s=r.length;t<s&&(Bi.setBuffer(r[t]),o=Ui(0,0,i,h,n,a,c,0,0,e),Bi.clearBuffer(),c+=r[t].byteLength/Ge,!o);t++);if(Oi.releasePrimitive(e),ki.clearBuffer(),a+=s[t].byteLength/Ge,o)break}return Ri=!1,o}(this,t,e,n)}}function Gi(t){return t.index?t.index.count:t.attributes.position.count}function Hi(t){return Gi(t)/3}function qi(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 Zi(t,e,i){const n=function(t,e,i){const n=Gi(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=Gi(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,d=null;for(const t of c){const e=t.pos;0!==h&&e!==d&&r.push({offset:d,count:e-d}),h+=t.isStart?1:-1,d=e}return r}class Yi extends Wi{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={...Ze,...e})[qe]||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}(Zi(e,t.range,i),t.useSharedArrayBuffer);this._indirectBuffer=n}else qi(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}]:Zi(this.geometry,t,this.primitiveStride)}raycastObject3D(){throw new Error("BVH: raycastObject3D() not implemented")}}class Xi{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}}Xi.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 Ki=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),d=c.dot(a),u=c.dot(c),p=i.dot(a),f=a.dot(a)*u-d*d;let m,g;m=0!==f?(h*d-p*u)/f:0,g=(h+m*d)/u,r.x=m,r.y=g}}(),Qi=function(){const t=new p,e=new h,i=new h;return function(n,s,r,o){Ki(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,d=i;return n.closestPointToPoint(c,!0,e),s.closestPointToPoint(t,!0,i),h.distanceToSquared(c)<=d.distanceToSquared(t)?(r.copy(h),void o.copy(c)):(r.copy(t),void o.copy(d))}}}(),Ji=function(){const t=new h,e=new h,i=new u,n=new d;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 d=r.getPlane(i);if(Math.abs(d.distanceToPoint(a))<=o){const t=d.projectPoint(a,e);if(r.containsPoint(t))return!0}return!1}}(),tn=["x","y","z"],en=1e-15;function nn(t){return Math.abs(t)<en}class sn 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 Xi),this.points=[this.a,this.b,this.c],this.plane=new u,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new d,this.needsUpdate=!0}intersectsSphere(t){return Ji(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],d=r[2];h.subVectors(e,i),d.setFromPoints(h,n);const u=s[3],p=r[3];u.subVectors(i,t),p.setFromPoints(u,n);const f=l.length(),m=h.length(),g=u.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}}sn.prototype.closestPointToSegment=function(){const t=new h,e=new h,i=new d;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]),Qi(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)}}(),sn.prototype.intersectsTriangle=function(){const t=new sn,e=new Xi,i=new Xi,n=new h,s=new h,r=new h,o=new h,a=new d,l=new d,c=new h,u=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 d=s.satBounds,u=s.satAxes;for(let n=1;n<4;n++){const r=d[n],a=u[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 d=o/(o-a);c.x=n+(s-n)*d,h.start.subVectors(e,t).multiplyScalar(d).add(t),d=o/(o-l),c.y=n+(r-n)*d,h.end.subVectors(i,t).multiplyScalar(d).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 nn(o)?nn(a)?m(t,e,i,s):(i&&(i.start.copy(r.start),i.end.copy(r.start)),t.containsPoint(r.start)):nn(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!(!nn(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),d=l.x*c.y-l.y*c.x;if(nn(d))return!1;const u=(h.x*c.y-h.y*c.x)/d,p=-(l.x*h.y-l.y*h.x)/d;return!(u<0||u>1||p<0||p>1)&&(!!nn(o.start.z+l.z*u-(a.start.z+c.z*p))&&(i&&(i.start.copy(o.start).addScaledVector(l,u),i.end.copy(o.start).addScaledVector(l,u)),!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 d=this.plane,p=e.plane;let g=p.distanceToPoint(this.a),v=p.distanceToPoint(this.b),x=p.distanceToPoint(this.c);nn(g)&&(g=0),nn(v)&&(v=0),nn(x)&&(x=0);const S=g*v,T=g*x;if(S>0&&T>0)return!1;let C=d.distanceToPoint(e.a),A=d.distanceToPoint(e.b),E=d.distanceToPoint(e.c);nn(C)&&(C=0),nn(A)&&(A=0),nn(E)&&(E=0);const M=C*A,P=C*E;if(M>0&&P>0)return!1;s.copy(d.normal),r.copy(p.normal);const z=s.cross(r);let I=0,D=Math.abs(z.x);const k=Math.abs(z.y);k>D&&(D=k,I=1);Math.abs(z.z)>D&&(I=2);const B=tn[I],O=this.a[B],V=this.b[B],L=this.c[B],N=e.a[B],F=e.b[B],R=e.c[B];if(w(this,O,V,L,S,T,g,v,x,u,a))return m(this,e,i,o);if(w(e,N,F,R,M,P,C,A,E,f,l))return m(this,e,i,o);if(u.y<u.x){const t=u.y;u.y=u.x,u.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!(u.y<f.x||f.y<u.x)&&(i&&(f.x>u.x?i.start.copy(l.start):i.start.copy(a.start),f.y<u.y?i.end.copy(l.end):i.end.copy(a.end)),!0)}}(),sn.prototype.distanceToPoint=function(){const t=new h;return function(e){return this.closestPointToPoint(e,t),e.distanceTo(t)}}(),sn.prototype.distanceToTriangle=function(){const t=new h,e=new h,i=["a","b","c"],n=new d,s=new d;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],d=i[(l+1)%3];n.set(this[h],this[d]);for(let l=0;l<3;l++){const h=i[l],d=i[(l+1)%3];s.set(r[h],r[d]),Qi(n,s,t,e);const u=t.distanceToSquared(e);u<c&&(c=u,o&&o.copy(t),a&&a.copy(e))}}return Math.sqrt(c)}}();class rn{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 Xi),this.alignedSatBounds=new Array(3).fill().map(()=>new Xi),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}}rn.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}}(),rn.prototype.intersectsBox=function(){const t=new Xi;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}}(),rn.prototype.intersectsTriangle=function(){const t=new sn,e=new Array(3),i=new Xi,n=new Xi,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}}(),rn.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}}(),rn.prototype.distanceToPoint=function(){const t=new h;return function(e){return this.closestPointToPoint(e,t),e.distanceTo(t)}}(),rn.prototype.distanceToBox=function(){const t=["x","y","z"],e=new Array(12).fill().map(()=>new d),i=new Array(12).fill().map(()=>new d),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,d=r.max,u=this.points;let p=1/0;for(let t=0;t<8;t++){const e=u[t];s.copy(e).clamp(h,d);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=u[s<<o|r<<a],p=u[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]:d[g],_[w]=r?h[w]:d[g],b[m]=d[m],b[g]=s?h[g]:d[g],b[w]=r?h[w]:d[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?d.x:h.x,s.y=e?d.y:h.y,s.z=i?d.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];Qi(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 on extends Ti{constructor(){super(()=>new sn)}}const an=new on,ln=new h,cn=new h;const hn=parseInt(w)>=169,dn=parseInt(w)<=161,un=new h,pn=new h,fn=new h,mn=new p,gn=new p,wn=new p,yn=new h,_n=new h,bn=new h,vn=new h;function xn(t,e,i,n,s,r,o,a,l,c,d){un.fromBufferAttribute(e,r),pn.fromBufferAttribute(e,o),fn.fromBufferAttribute(e,a);const u=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,un,pn,fn,vn,l,c,d);if(u){if(n){mn.fromBufferAttribute(n,r),gn.fromBufferAttribute(n,o),wn.fromBufferAttribute(n,a),u.uv=new p;const t=f.getInterpolation(vn,un,pn,fn,mn,gn,wn,u.uv);hn||(u.uv=t)}if(s){mn.fromBufferAttribute(s,r),gn.fromBufferAttribute(s,o),wn.fromBufferAttribute(s,a),u.uv1=new p;const t=f.getInterpolation(vn,un,pn,fn,mn,gn,wn,u.uv1);hn||(u.uv1=t),dn&&(u.uv2=u.uv1)}if(i){yn.fromBufferAttribute(i,r),_n.fromBufferAttribute(i,o),bn.fromBufferAttribute(i,a),u.normal=new h;const e=f.getInterpolation(vn,un,pn,fn,yn,_n,bn,u.normal);u.normal.dot(t.direction)>0&&u.normal.multiplyScalar(-1),hn||(u.normal=e)}const e={a:r,b:o,c:a,normal:new h,materialIndex:0};if(f.getNormal(un,pn,fn,e.normal),u.face=e,u.faceIndex=r,hn){const t=new h;f.getBarycoord(vn,un,pn,fn,t),u.barycoord=t}}return u}function Sn(t){return t&&t.isMaterial?t.side:t}function Tn(t,e,i,n,s,r,o){const a=3*n;let l=a+0,c=a+1,h=a+2;const{index:d,groups:u}=t;t.index&&(l=d.getX(l),c=d.getX(c),h=d.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,d=u.length;a<d;a++){const{start:d,count:w,materialIndex:y}=u[a];if(t>=d&&t<d+w){const t=xn(i,p,f,m,g,l,c,h,Sn(e[y]),r,o);if(t){if(t.faceIndex=n,t.face.materialIndex=y,!s)return t;s.push(t)}}}}else{const t=xn(i,p,f,m,g,l,c,h,Sn(e),r,o);if(t){if(t.faceIndex=n,t.face.materialIndex=0,!s)return t;s.push(t)}}return null}function Cn(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 An(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,Cn(o,3*t,l,c),o.needsUpdate=!0,n(o,t,s,r))return!0}return!1}function En(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),d(0,c),c+=r.byteLength;function d(t,i,r=!1){const c=2*t;if(ei(c,a)){const e=ii(t,o);let i=1/0,r=1/0,h=1/0,d=-1/0,u=-1/0,p=-1/0;for(let t=3*e,o=3*(e+ni(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>d&&(d=o),a<r&&(r=a),a>u&&(u=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]!==d||l[t+4]!==u||l[t+5]!==p)&&(l[t+0]=i,l[t+1]=r,l[t+2]=h,l[t+3]=d,l[t+4]=u,l[t+5]=p,!0)}{const n=si(t),s=ri(t,o);let a=r,c=!1,h=!1;if(e){if(!a){const t=n/8+i/Ge,r=s/8+i/Ge;c=e.has(t),h=e.has(r),a=!c&&!h}}else c=!0,h=!0;const u=a||h;let p=!1;(a||c)&&(p=d(n,i,a));let f=!1;u&&(f=d(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 Mn(t,e,i,n,s){let r,o,a,l,c,h;const d=1/i.direction.x,u=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 d>=0?(r=(w-f)*d,o=(y-f)*d):(r=(y-f)*d,o=(w-f)*d),u>=0?(a=(_-m)*u,l=(b-m)*u):(a=(b-m)*u,l=(_-m)*u),!(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 Pn(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),Cn(o,3*t,l,c),o.needsUpdate=!0,n(o,t,s,r))return!0}return!1}function zn(t,e,i,n,s,r,o){Ai.setBuffer(t._roots[e]),In(0,t,i,n,s,r,o),Ai.clearBuffer()}function In(t,e,i,n,s,r,o){const{float32Array:a,uint16Array:l,uint32Array:c}=Ai,h=2*t;if(ei(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++)Tn(l,e,i,t,r,o,a)}(e,i,n,ii(t,c),ni(h,l),s,r,o)}else{const l=si(t);Mn(l,a,n,r,o)&&In(l,e,i,n,s,r,o);const h=ri(t,c);Mn(h,a,n,r,o)&&In(h,e,i,n,s,r,o)}}const Dn=["x","y","z"];function kn(t,e,i,n,s,r){Ai.setBuffer(t._roots[e]);const o=Bn(0,t,i,n,s,r);return Ai.clearBuffer(),o}function Bn(t,e,i,n,s,r){const{float32Array:o,uint16Array:a,uint32Array:l}=Ai;let c=2*t;if(ei(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=Tn(a,e,i,t,null,r,o),n&&n.distance<c&&(h=n,c=n.distance)}return h}(e,i,n,ii(t,l),ni(c,a),s,r)}{const a=oi(t,l),c=Dn[a],h=n.direction[c]>=0;let d,u;h?(d=si(t),u=ri(t,l)):(d=ri(t,l),u=si(t));const p=Mn(d,o,n,s,r)?Bn(d,e,i,n,s,r):null;if(p){const t=p.point[c];if(h?t<=o[u+a]:t>=o[u+a+3])return p}const f=Mn(u,o,n,s,r)?Bn(u,e,i,n,s,r):null;return p&&f?p.distance<=f.distance?p:f:p||f||null}}const On=new a,Vn=new sn,Ln=new sn,Nn=new l,Fn=new rn,Rn=new rn;function Un(t,e,i,n){Ai.setBuffer(t._roots[e]);const s=jn(0,t,i,n);return Ai.clearBuffer(),s}function jn(t,e,i,n,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=Ai;let l=2*t;null===s&&(i.boundingBox||i.computeBoundingBox(),Fn.set(i.boundingBox.min,i.boundingBox.max,n),s=Fn);if(!ei(l,o)){const o=si(t),l=ri(t,a);Ye(o,r,On);if(s.intersectsBox(On)&&jn(o,e,i,n,s))return!0;Ye(l,r,On);return!!(s.intersectsBox(On)&&jn(l,e,i,n,s))}{const s=e.geometry,c=s.index,h=s.attributes.position,d=i.index,u=i.attributes.position,p=ii(t,a),f=ni(l,o);if(Nn.copy(n).invert(),i.boundsTree){Ye(t,r,Rn),Rn.matrix.copy(Nn),Rn.needsUpdate=!0;return i.boundsTree.shapecast({intersectsBounds:t=>Rn.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(Cn(Ln,e,c,h),Ln.needsUpdate=!0,t.intersectsTriangle(Ln))return!0;return!1}})}{const t=Hi(i);for(let e=3*p,i=3*(f+p);e<i;e+=3){Cn(Vn,e,c,h),Vn.a.applyMatrix4(Nn),Vn.b.applyMatrix4(Nn),Vn.c.applyMatrix4(Nn),Vn.needsUpdate=!0;for(let e=0,i=3*t;e<i;e+=3)if(Cn(Ln,e,d,u),Ln.needsUpdate=!0,Vn.intersectsTriangle(Ln))return!0}}}}const $n=new l,Wn=new rn,Gn=new rn,Hn=new h,qn=new h,Zn=new h,Yn=new h;function Xn(t,e,i,n={},s={},r=0,o=1/0){e.boundingBox||e.computeBoundingBox(),Wn.set(e.boundingBox.min,e.boundingBox.max,i),Wn.needsUpdate=!0;const a=t.geometry,l=a.attributes.position,c=a.index,h=e.attributes.position,d=e.index,u=an.getPrimitive(),p=an.getPrimitive();let f=Hn,m=qn,g=null,w=null;s&&(g=Zn,w=Yn);let y=1/0,_=null,b=null;return $n.copy(i).invert(),Gn.matrix.copy($n),t.shapecast({boundsTraverseOrder:t=>Wn.distanceToBox(t),intersectsBounds:(t,e,i)=>i<y&&i<o&&(e&&(Gn.min.copy(t.min),Gn.max.copy(t.max),Gn.needsUpdate=!0),!0),intersectsRange:(t,n)=>{if(e.boundsTree){return e.boundsTree.shapecast({boundsTraverseOrder:t=>Gn.distanceToBox(t),intersectsBounds:(t,e,i)=>i<y&&i<o,intersectsRange:(e,s)=>{for(let o=e,a=e+s;o<a;o++){Cn(p,3*o,d,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++){Cn(u,3*e,c,l),u.needsUpdate=!0;const t=u.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=Hi(e);s<o;s++){Cn(p,3*s,d,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++){Cn(u,3*e,c,l),u.needsUpdate=!0;const t=u.distanceToTriangle(p,f,g);if(t<y&&(m.copy(f),w&&w.copy(g),y=t,_=e,b=s),t<r)return!0}}}}),an.releasePrimitive(u),an.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($n),m.applyMatrix4($n),s.distance=m.sub(s.point).length(),s.faceIndex=b),n)}function Kn(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),d(0,c),c+=r.byteLength;function d(i,r,c=!1){const h=2*i;if(ei(h,a)){const e=ii(i,o);let r=1/0,c=1/0,d=1/0,u=-1/0,p=-1/0,f=-1/0;for(let i=e,o=e+ni(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>u&&(u=o),a<c&&(c=a),a>p&&(p=a),l<d&&(d=l),l>f&&(f=l)}}return(l[i+0]!==r||l[i+1]!==c||l[i+2]!==d||l[i+3]!==u||l[i+4]!==p||l[i+5]!==f)&&(l[i+0]=r,l[i+1]=c,l[i+2]=d,l[i+3]=u,l[i+4]=p,l[i+5]=f,!0)}{const t=si(i),n=ri(i,o);let s=c,a=!1,h=!1;if(e){if(!s){const i=t/8+r/Ge,o=n/8+r/Ge;a=e.has(i),h=e.has(o),s=!a&&!h}}else a=!0,h=!0;const u=s||h;let p=!1;(s||a)&&(p=d(t,r,s));let f=!1;u&&(f=d(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 Qn(t,e,i,n,s,r,o){Ai.setBuffer(t._roots[e]),Jn(0,t,i,n,s,r,o),Ai.clearBuffer()}function Jn(t,e,i,n,s,r,o){const{float32Array:a,uint16Array:l,uint32Array:c}=Ai,h=2*t;if(ei(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++)Tn(l,e,i,c?c[t]:t,r,o,a)}(e,i,n,ii(t,c),ni(h,l),s,r,o)}else{const l=si(t);Mn(l,a,n,r,o)&&Jn(l,e,i,n,s,r,o);const h=ri(t,c);Mn(h,a,n,r,o)&&Jn(h,e,i,n,s,r,o)}}const ts=["x","y","z"];function es(t,e,i,n,s,r){Ai.setBuffer(t._roots[e]);const o=is(0,t,i,n,s,r);return Ai.clearBuffer(),o}function is(t,e,i,n,s,r){const{float32Array:o,uint16Array:a,uint32Array:l}=Ai;let c=2*t;if(ei(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,d=n+s;t<d;t++){let n;n=Tn(a,e,i,l?l[t]:t,null,r,o),n&&n.distance<c&&(h=n,c=n.distance)}return h}(e,i,n,ii(t,l),ni(c,a),s,r)}{const a=oi(t,l),c=ts[a],h=n.direction[c]>=0;let d,u;h?(d=si(t),u=ri(t,l)):(d=ri(t,l),u=si(t));const p=Mn(d,o,n,s,r)?is(d,e,i,n,s,r):null;if(p){const t=p.point[c];if(h?t<=o[u+a]:t>=o[u+a+3])return p}const f=Mn(u,o,n,s,r)?is(u,e,i,n,s,r):null;return p&&f?p.distance<=f.distance?p:f:p||f||null}}const ns=new a,ss=new sn,rs=new sn,os=new l,as=new rn,ls=new rn;function cs(t,e,i,n){Ai.setBuffer(t._roots[e]);const s=hs(0,t,i,n);return Ai.clearBuffer(),s}function hs(t,e,i,n,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=Ai;let l=2*t;null===s&&(i.boundingBox||i.computeBoundingBox(),as.set(i.boundingBox.min,i.boundingBox.max,n),s=as);if(!ei(l,o)){const o=si(t),l=ri(t,a);Ye(o,r,ns);if(s.intersectsBox(ns)&&hs(o,e,i,n,s))return!0;Ye(l,r,ns);return!!(s.intersectsBox(ns)&&hs(l,e,i,n,s))}{const s=e.geometry,c=s.index,h=s.attributes.position,d=i.index,u=i.attributes.position,p=ii(t,a),f=ni(l,o);if(os.copy(n).invert(),i.boundsTree){Ye(t,r,ls),ls.matrix.copy(os),ls.needsUpdate=!0;return i.boundsTree.shapecast({intersectsBounds:t=>ls.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(Cn(rs,3*e.resolveTriangleIndex(i),c,h),rs.needsUpdate=!0,t.intersectsTriangle(rs))return!0;return!1}})}{const t=Hi(i);for(let i=p,n=f+p;i<n;i++){const n=e.resolveTriangleIndex(i);Cn(ss,3*n,c,h),ss.a.applyMatrix4(os),ss.b.applyMatrix4(os),ss.c.applyMatrix4(os),ss.needsUpdate=!0;for(let e=0,i=3*t;e<i;e+=3)if(Cn(rs,e,d,u),rs.needsUpdate=!0,ss.intersectsTriangle(rs))return!0}}}}const ds=new l,us=new rn,ps=new rn,fs=new h,ms=new h,gs=new h,ws=new h;function ys(t,e,i,n={},s={},r=0,o=1/0){e.boundingBox||e.computeBoundingBox(),us.set(e.boundingBox.min,e.boundingBox.max,i),us.needsUpdate=!0;const a=t.geometry,l=a.attributes.position,c=a.index,h=e.attributes.position,d=e.index,u=an.getPrimitive(),p=an.getPrimitive();let f=fs,m=ms,g=null,w=null;s&&(g=gs,w=ws);let y=1/0,_=null,b=null;return ds.copy(i).invert(),ps.matrix.copy(ds),t.shapecast({boundsTraverseOrder:t=>us.distanceToBox(t),intersectsBounds:(t,e,i)=>i<y&&i<o&&(e&&(ps.min.copy(t.min),ps.max.copy(t.max),ps.needsUpdate=!0),!0),intersectsRange:(n,s)=>{if(e.boundsTree){const a=e.boundsTree;return a.shapecast({boundsTraverseOrder:t=>ps.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);Cn(p,3*e,d,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);Cn(u,3*i,c,l),u.needsUpdate=!0;const n=u.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=Hi(e);o<a;o++){Cn(p,3*o,d,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);Cn(u,3*i,c,l),u.needsUpdate=!0;const n=u.distanceToTriangle(p,f,g);if(n<y&&(m.copy(f),w&&w.copy(g),y=n,_=e,b=o),n<r)return!0}}}}),an.releasePrimitive(u),an.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 _s(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 bs=new rn,vs=new y,xs=new h,Ss=new l,Ts=new h,Cs=["getX","getY","getZ"];class As extends Yi{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/Ge;t<e;t++){const e=8*t;ei(2*e,s)||(n[e+6]=n[e+6]/8-t)}}}(s));const o=new As(e,{...i,[qe]:!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[Cs[t]](l),s=r[Cs[t]](c),o=r[Cs[t]](h);let a=n;s<a&&(a=s),o<a&&(a=o);let d=n;s>d&&(d=s),o>d&&(d=o),e[i+t]=a,e[i+t+3]=d}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 d=["getX","getY","getZ"],u=i.offset;for(let n=t,p=t+e;n<p;n++){const t=3*(s?s[n]:n),e=6*(n-u);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[d[t]](p),s=r[d[t]](f),o=r[d[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 u=(h-c)/2,g=2*t;i[e+g+0]=c+u,i[e+g+1]=u+(Math.abs(c)+u)*He}}return i}raycastObject3D(t,e,i=[]){const{material:n}=t;if(void 0===n)return;Ss.copy(t.matrixWorld).invert(),vs.copy(e.ray).applyMatrix4(Ss),Ts.setFromMatrixScale(t.matrixWorld),xs.copy(vs.direction).multiply(Ts);const s=xs.length(),r=e.near/s,o=e.far/s;if(!0===e.firstHitOnly){let s=this.raycastFirst(vs,n,r,o);s=_s(s,t,e),s&&i.push(s)}else{const s=this.raycast(vs,n,r,o);for(let n=0,r=s.length;n<r;n++){const r=_s(s[n],t,e);r&&i.push(r)}}return i}refit(t=null){return(this.indirect?Kn:En)(this,t)}raycast(t,e=_,i=0,n=1/0){const s=this._roots,r=[],o=this.indirect?Qn:zn;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?es:kn;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?cs:Un;for(let r=0,o=n.length;r<o&&(i=s(this,r,t,e),!i);r++);return i}shapecast(t){const e=an.getPrimitive(),i=super.shapecast({...t,intersectsPrimitive:t.intersectsTriangle,scratchPrimitive:e,iterate:this.indirect?Pn:An});return an.releasePrimitive(e),i}bvhcast(t,e,i){let{intersectsRanges:n,intersectsTriangles:s}=i;const r=an.getPrimitive(),o=this.geometry.index,a=this.geometry.attributes.position,l=this.indirect?t=>{const e=this.resolveTriangleIndex(t);Cn(r,3*e,o,a)}:t=>{Cn(r,3*t,o,a)},c=an.getPrimitive(),h=t.geometry.index,d=t.geometry.attributes.position,u=t.indirect?e=>{const i=t.resolveTriangleIndex(e);Cn(c,3*i,h,d)}:t=>{Cn(c,3*t,h,d)};if(s){if(!(t instanceof As))throw new Error('MeshBVH: "intersectsTriangles" callback can only be used with another MeshBVH.');const i=(t,i,n,o,a,h,d,p)=>{for(let f=n,m=n+o;f<m;f++){u(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,d,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 bs.set(t.min,t.max,e),bs.needsUpdate=!0,this.shapecast({intersectsBounds:t=>bs.intersectsBox(t),intersectsTriangle:t=>bs.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?ys:Xn)(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=>(ln.copy(e).clamp(t.min,t.max),ln.distanceToSquared(e)),intersectsBounds:(t,e,i)=>i<a&&i<o,intersectsTriangle:(t,i)=>{t.closestPointToPoint(e,ln);const n=e.distanceToSquared(ln);return n<a&&(cn.copy(ln),a=n,l=i),n<r}}),a===1/0)return null;const c=Math.sqrt(a);return i.point?i.point.copy(cn):i.point=cn.clone(),i.distance=c,i.faceIndex=l,i}(this,t,e,i,n)}}const Es=new l,Ms=new y,Ps=new Ti(()=>new d),zs=new h,Is=new h,Ds=new a,ks=["getX","getY","getZ"];class Bs extends Yi{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[ks[t]](c),s=o[ks[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=Ps.getPrimitive(),i=super.shapecast({...t,intersectsPrimitive:t.intersectsLine,scratchPrimitive:e,iterate:Os});return Ps.releasePrimitive(e),i}raycastObject3D(t,e,i=[]){const{matrixWorld:n}=t,{firstHitOnly:s}=e;Es.copy(n).invert(),Ms.copy(e.ray).applyMatrix4(Es);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(Ms.origin),intersectsBounds:t=>(Ds.copy(t).expandByScalar(Math.abs(r)),Ms.intersectsBox(Ds)?1:0),intersectsLine:(r,c)=>{if(Ms.distanceSqToSegment(r.start,r.end,zs,Is)>o)return;zs.applyMatrix4(t.matrixWorld);const h=e.ray.origin.distanceTo(zs);h<e.near||h>e.far||s&&h>=l||(l=h,c=this.resolvePrimitiveIndex(c),a={distance:h,point:Is.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 Os(t,e,i,n,s,r,o){const{geometry:a,primitiveStride:l}=i,{index:c}=a,h=a.attributes.position,d=c?c.count:h.count;for(let a=t,u=e+t;a<u;a++){let t=i.resolvePrimitiveIndex(a)*l,e=(t+1)%d;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 Vs={Mesh:b.prototype.raycast,Line:S.prototype.raycast,LineSegments:v.prototype.raycast,LineLoop:x.prototype.raycast,Points:T.prototype.raycast,BatchedMesh:A.prototype.raycast},Ls=new b,Ns=[];function Fs(t,e){if(this.isBatchedMesh)Rs.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=Vs.Mesh;else if(this instanceof v)i=Vs.LineSegments;else if(this instanceof x)i=Vs.LineLoop;else if(this instanceof S)i=Vs.Line;else{if(!(this instanceof T))throw new Error("BVH: Fallback raycast function not found.");i=Vs.Points}i.call(this,t,e)}}}function Rs(t,e){if(this.boundsTrees){const i=this.boundsTrees,n=this._drawInfo||this._instanceInfo,s=this._drawRanges||this._geometryInfo,r=this.matrixWorld;Ls.material=this.material,Ls.geometry=this.geometry;const o=Ls.geometry.boundsTree,a=Ls.geometry.drawRange;null===Ls.geometry.boundingSphere&&(Ls.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(Ls.geometry.boundsTree=i[a],this.getMatrixAt(o,Ls.matrixWorld).premultiply(r),!Ls.geometry.boundsTree){this.getBoundingBoxAt(a,Ls.geometry.boundingBox),this.getBoundingSphereAt(a,Ls.geometry.boundingSphere);const t=s[a];Ls.geometry.setDrawRange(t.start,t.count)}Ls.raycast(t,Ns);for(let t=0,i=Ns.length;t<i;t++){const i=Ns[t];i.object=this,i.batchId=o,e.push(i)}Ns.length=0}Ls.geometry.boundsTree=o,Ls.geometry.drawRange=a,Ls.material=null,Ls.geometry=null}else Vs.BatchedMesh.call(this,t,e)}function Us(t={}){const{type:e=As}=t;return this.boundsTree=new e(this,t),this.boundsTree}function js(){this.boundsTree=null}const $s=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)}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($s,"uuid","fef46874-46a3-461b-8c44-2922ab77c806");let Ws=$s;function Gs(t,e){return t[e]|t[e+1]<<8|t[e+2]<<16}class Hs{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 E,r=new a,o=new M(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),d=Math.ceil(n.z/i),u=Math.ceil(c/l),p=Math.ceil(d/l);o.setSize(Math.ceil(c/u),Math.ceil(d/p)),s.rotation.x=-Math.PI/2,s.far=r.max.y-r.min.y+s.near,s.position.y=r.max.y+s.near;const f=new P,m=new Map,g=new Map,w=[];for(let e=0;e<t.length;e++){const i=t[e];m.set(i,i.material),g.set(i,i.parent);const n=new qs;n.objectId=e,w.push(n),i.material=n,f.add(i)}const y=e.getClearColor(new z),_=e.getClearAlpha(),b=e.getRenderTarget(),v=e.autoClear;e.autoClear=!0,e.setClearColor(0,0),e.setRenderTarget(o);const x=new Uint8Array(o.width*o.height*4),S=new Set,T=n.x/u,C=n.z/p;for(let i=0;i<u;i++)for(let n=0;n<p;n++){const a=r.min.x+T*i,l=a+T,c=r.min.z+C*n,h=(a+l)/2,d=(c+(c+C))/2;s.position.set(h,r.max.y,d);const u=T/2,p=C/2;s.left=-u,s.right=u,s.top=p,s.bottom=-p,s.updateProjectionMatrix(),e.render(f,s);const m=await e.readRenderTargetPixelsAsync(o,0,0,o.width,o.height,x);for(let e=0,i=m.length;e<i;e+=4){if(0===m[e+3])continue;const i=Gs(m,e);S.add(t[i])}}for(const e of t){e.material=m.get(e);const t=g.get(e);t?t.add(e):f.remove(e)}e.setClearColor(y,_),e.setRenderTarget(b),e.autoClear=v;for(const t of w)t.dispose();return o.dispose(),Array.from(S)}}class qs extends I{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,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 Zs=1e-16,Ys=new h(0,1,0),Xs=new h;function Ks(t){return t.delta(Xs).normalize(),Math.abs(Xs.dot(Ys))>=1-Zs}function Qs(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)<=Zs&&(r=!0),!o&&n.distanceToSquared(e)<=Zs&&(o=!0),r&&o)return!0}return r&&o}const Js=new d;function tr(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;Js.start.lerpVectors(i,r,s[e][0]),Js.end.lerpVectors(i,r,s[e][1]),n.push(new Float32Array([Js.start.x,Js.start.y,Js.start.z,Js.end.x,Js.end.y,Js.end.z]))}return n}const er=new h(0,1,0),ir=new h,nr=new h,sr=new h,rr=new f;function*or(t,e=[],i={}){const{projectionDirection:n=er,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,u=[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?(u[0]=l.getX(t),u[1]=l.getX(t+1),u[2]=l.getX(t+2)):(u[0]=t,u[1]=t+1,u[2]=t+2);const{a:i,b:s,c:h}=rr;if(i.fromBufferAttribute(c,u[0]),s.fromBufferAttribute(c,u[1]),h.fromBufferAttribute(c,u[2]),rr.getNormal(sr),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=rr[p[t]],l=rr[p[i]],c=`${s}_${r}`,h=`${r}_${s}`;if(h in m&&m[h]){const t=m[h].normal,i=sr.dot(t)<=a;let s=!1;if(null!==n){let e=n.dot(sr);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 d;t.start.copy(o),t.end.copy(l),e.push(t)}m[h]=null}else c in m||(m[c]={index0:u[t],index1:u[i],normal:sr.clone()})}}for(const t in m)if(m[t]){const{index0:i,index1:n}=m[t];ir.fromBufferAttribute(c,i),nr.fromBufferAttribute(c,n);const s=new d;s.start.copy(ir),s.end.copy(nr),e.push(s)}return e}const ar=new d;function lr(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++){cr(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,ar,!0)||Qs(t,ar)||Qs(e,ar)||n.push(ar.clone())))}),n}function cr(t,e){return t.distanceTo(e)<1e-10}function hr(t){dr(t);let e=[];return t.traverse(t=>{t.geometry&&t.visible&&e.push(t)}),e}const dr=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):dr(i)},ur=new l,pr=new l;class fr{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=hr(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&&(pr.copy(c.matrixWorld).invert(),a.copy(n).transformDirection(pr).normalize());const h=yield*or(c.geometry,[],{projectionDirection:a,thresholdAngle:s,iterationTime:r});mr(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*or(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=hr(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 As(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),d=r.get(c.geometry);ur.copy(l.matrixWorld).invert().multiply(c.matrixWorld);const u=lr(h,d,ur,[]);mr(u,l.matrixWorld);for(let t=0;t<u.length;t++)e.push(u[t]);if(null!==i)for(let t=0;t<u.length;t++)i.push(l)}return e}{let i;return t.isBufferGeometry?i=t.boundsTree||new As(t,{maxLeafSize:1}):(i=t,t=i.geometry),ur.identity(),lr(i,i,ur,e)}}}function mr(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 gr extends Wi{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 wr=new h(0,1,0),yr=new u,_r=new h,br=new h;function vr(t,e,i){t.needsUpdate&&t.update(),yr.copy(t.plane),yr.normal.dot(wr)<0&&(yr.normal.multiplyScalar(-1),yr.constant*=-1);const n=yr.distanceToPoint(e.start),s=yr.distanceToPoint(e.end),r=Math.abs(n)<1e-16,o=n<0,a=s<0;if(e.delta(br).normalize(),Math.abs(yr.normal.dot(br))<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,_r),o)return i.start.copy(e.start),i.end.copy(_r),!0;if(a)return i.end.copy(e.end),i.start.copy(_r),!0}return!1}const xr=new u,Sr=new h,Tr=new h,Cr=new sn,Ar=new d,Er=new d,Mr=new h,Pr=new h,zr=new h;function Ir(t,e,i=new d){if(Cr.copy(e),Cr.a.y=0,Cr.b.y=0,Cr.c.y=0,Cr.update(),Ar.copy(t),Ar.start.y=0,Ar.end.y=0,Cr.getArea()<=1e-16)return null;const n=Ar.distance();Ar.delta(Mr).divideScalar(n),Pr.copy(Mr).cross(Cr.plane.normal).normalize(),xr.setFromNormalAndCoplanarPoint(Pr,Ar.start);let s=0;const{points:r}=Cr;for(let t=0;t<3;t++){const e=r[t],i=r[(t+1)%3],n=xr.distanceToPoint(e),o=xr.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);Sr.lerpVectors(e,i,t),c=!0}if((c&&!l||a)&&(a&&!c&&Sr.copy(e),0===s?Er.start.copy(Sr):Er.end.copy(Sr),s++,2===s))break}if(2===s){if(Er.delta(zr).normalize(),Mr.dot(zr)<0){const t=Er.start;Er.start=Er.end,Er.end=t}const e=0,s=Tr.subVectors(Ar.end,Ar.start).dot(Mr),r=Tr.subVectors(Er.start,Ar.start).dot(Mr),o=Tr.subVectors(Er.end,Ar.start).dot(Mr);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 Dr=new h,kr=new h,Br=new h;function Or(t,e,i){const n=function(t,e){t.delta(Dr),kr.subVectors(e.start,t.start),Br.subVectors(e.end,t.start);const i=Dr.length();let n=kr.length()/i,s=Br.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&&(Vr(n,i),!0)}function Vr(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 Lr=new h(0,1,0),Nr=new d,Fr=new d,Rr=new sn;function Ur(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 d=i,u=a+i;d<u;d++){let i=3*d+0,a=3*d+1,u=3*d+2;r.index&&(i=r.index.getX(i),a=r.index.getX(a),u=r.index.getX(u));const{a:p,b:f,c:w}=Rr;if(p.fromBufferAttribute(r.attributes.position,i).applyMatrix4(o),f.fromBufferAttribute(r.attributes.position,a).applyMatrix4(o),w.fromBufferAttribute(r.attributes.position,u).applyMatrix4(o),Rr.needsUpdate=!0,Rr.update(),l!==g){if(Rr.plane.normal.dot(Lr)!==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=Rr.plane.normal;let v=b.x,x=b.y,S=b.z,T=Rr.plane.constant;x<0&&(v=-v,x=-x,S=-S,T=-T);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,d=p.z-t.start.z,u=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+d*n,b=u*i+m*n,v=g*i+y*n,x=1/e,S=Math.min(_,b,v);if(Math.max(_,b,v)<0||S>x){s&&s.xzBoundsCulled++;continue}const T=h*r+d*c,C=u*r+m*c,A=g*r+y*c,E=Math.min(T,C,A),M=Math.max(T,C,A);if(E>0||M<0){s&&s.xzBoundsCulled++;continue}}const c=v*t.start.x+x*t.start.y+S*t.start.z+T,d=v*t.end.x+x*t.end.y+S*t.end.z+T;if(c>=0&&d>=0)s&&s.planeTrimCulled++;else if(Qs(Rr,t))s&&s.triangleEdgeCulled++;else{if(r<_)Nr.copy(t);else if(!vr(Rr,t,Nr)){s&&s.planeTrimCulled++;continue}Nr.distance()<1e-10?s&&s.distThresholdCulled++:Ir(Nr,Rr,Fr)?(s&&s.used++,Or(t,Fr,n[i])):s&&s.noOverlapCulled++}}}}})}Rr.update=()=>{Rr.plane.setFromCoplanarPoints(...Rr.points)};let jr=!1;const $r={},Wr={};let Gr=null,Hr=0,qr=0;const Zr={get enabled(){return jr},set enabled(t){jr=t},reset(){for(const t in $r)delete $r[t];for(const t in Wr)delete Wr[t];Gr=null,Hr=0,qr=0},setStat(t,e){Wr[t]=e},startTotal(){jr&&(qr=performance.now())},startStep(t){jr&&(null!==Gr&&this.endStep(),Gr=t,Hr=performance.now())},endStep(){if(!jr||null===Gr)return;const t=performance.now()-Hr;$r[Gr]=t,Gr=null},printSummary(){if(!jr)return;null!==Gr&&this.endStep();const t=performance.now()-qr;console.log("\n=== Projection Summary ==="),console.log(`Total time: ${t.toFixed(1)}ms\n`);for(const[e,i]of Object.entries($r)){const n=(i/t*100).toFixed(1);console.log(` ${e}: ${i.toFixed(1)}ms (${n}%)`)}if(Object.keys(Wr).length>0){console.log("\n--- Stats ---");for(const[t,e]of Object.entries(Wr))console.log(` ${t}: ${e}`)}console.log("")}},Yr=1e-5,Xr=1e-16,Kr=1e-16;function Qr(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 Jr=null;async function to(t,e,i,n,s=null){const r=await async function(){return null===Jr&&(Jr=new L.WebGPURenderer,await Jr.init()),Jr}();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=N(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");Zr.enabled&&console.log("Number of meshes:",e.length),Zr.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}}Zr.enabled&&console.log(`Split ${e.length} meshes into ${a.length} batches`);let l=0,c=0,h=0,d=0,u=0;for(let i=0;i<a.length;i++){const{start:p,end:f}=a[i],m=f-p;Zr.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,S=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]+S;x+=s.length,S+=i.attributes.position.count}const T=new Float32Array(16*m);for(let t=p;t<f;t++){const i=t-p;T.set(e[t].matrixWorld.elements,16*i)}const C=[];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];C.push({edgeOffset:t.edgeOffsets[e],edgeCount:t.edgeCounts[e],triOffset:s,triCount:t.meshCounts[e],meshIdx:n})}}if(0===C.length){Zr.enabled&&console.log(` Batch ${i+1}: no groups, skipping`);continue}const A=new Uint32Array(5*C.length);for(let t=0;t<C.length;t++){const e=C[t],i=5*t;A[i+0]=e.edgeOffset,A[i+1]=e.edgeCount,A[i+2]=e.triOffset,A[i+3]=e.triCount,A[i+4]=e.meshIdx}let E=0;for(let t=0;t<C.length;t++)E+=C[t].edgeCount*C[t].triCount;s&&(s.candidates+=E);let M=Math.min(Math.ceil(.1*E),2e6),P=Math.max(M,1e4);Zr.enabled&&console.log(` Batch ${i+1}: ${C.length} groups, ${g/3} vertices, ${w/3} triangles, ${E} pairs, buffer for ${P} overlaps`);const z=performance.now(),I=N(_,"float"),D=N(b,"uint"),k=N(T,"float"),B=N(A,"uint");let O=N(new Uint32Array([0]),"uint").toAtomic(),V=N(new Float32Array(3*P),"float");d+=performance.now()-z;const L=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(I.element(r.mul(3)),I.element(r.mul(3).add(1)),I.element(r.mul(3).add(2))),d=W(I.element(l.mul(3)),I.element(l.mul(3).add(1)),I.element(l.mul(3).add(2))),u=W(I.element(c.mul(3)),I.element(c.mul(3).add(1)),I.element(c.mul(3).add(2))),p=a.mul(G(h,H(1))).xyz,f=a.mul(G(d,H(1))).xyz,m=a.mul(G(u,H(1))).xyz,g=f.sub(p),w=m.sub(p),y=q(g,w),_=y.dot(y);Z(_.lessThan(H(4e-16*Xr)),()=>{Y()}),Z(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);Z(b.lessThanEqual(a),()=>{Y()});const l=Q(y),c=l.dot(p).negate(),h=l.y.lessThan(0),d=J(h,l.negate(),l),u=J(h,c.negate(),c),g=d.dot(s).add(u),w=d.dot(r).add(u),_=g.lessThan(0),v=w.lessThan(0),x=tt(g).lessThan(H(Yr)),S=_.not().and(v.not()),T=w.sub(g),C=tt(T).lessThan(H(Yr)),A=C.and(x.or(_.not()));Z(A,()=>{Y()}),Z(S.and(C.not()),()=>{Y()});const E=g.negate().div(T),M=et(s,r,E),z=W(J(C.or(_),s.x,M.x),J(C.or(_),s.y,M.y),J(C.or(_),s.z,M.z)),I=W(J(C.or(v),r.x,M.x),J(C.or(v),r.y,M.y),J(C.or(v),r.z,M.z)),D=I.sub(z),k=D.dot(D);Z(k.lessThan(H(Yr)),()=>{Y()});const B=s.sub(p),L=s.sub(f),N=s.sub(m),F=r.sub(p),R=r.sub(f),U=r.sub(m),j=B.dot(B).lessThanEqual(H(Yr)),$=L.dot(L).lessThanEqual(H(Yr)),G=N.dot(N).lessThanEqual(H(Yr)),st=F.dot(F).lessThanEqual(H(Yr)),rt=R.dot(R).lessThanEqual(H(Yr)),ot=U.dot(U).lessThanEqual(H(Yr)),at=j.or($).or(G),lt=st.or(rt).or(ot),ct=at.and(lt);Z(ct,()=>{Y()});const ht=W(p.x,H(0),p.z),dt=W(f.x,H(0),f.z),ut=W(m.x,H(0),m.z),pt=W(z.x,H(0),z.z),ft=W(I.x,H(0),I.z),mt=W(s.x,H(0),s.z),gt=W(r.x,H(0),r.z).sub(mt),wt=gt.dot(gt);Z(wt.lessThan(H(Yr)),()=>{Y()});const yt=wt.sqrt(),_t=dt.sub(ht),bt=ut.sub(ht),vt=q(_t,bt),xt=vt.dot(vt);Z(xt.lessThanEqual(H(4e-16*Xr)),()=>{Y()});const St=ft.sub(pt),Tt=St.dot(St);Z(Tt.lessThan(H(Yr)),()=>{Y()});const Ct=Tt.sqrt(),At=St.div(Ct),Et=gt.div(yt),Mt=Q(vt),Pt=q(At,Mt),zt=H(0).toVar(),It=H(0).toVar(),Dt=H(0).toVar(),kt=H(0).toVar(),Bt=it(0).toVar(),Ot=Pt.dot(ht.sub(pt)),Vt=Pt.dot(dt.sub(pt)),Lt=tt(Ot).lessThan(H(Kr)),Nt=tt(Vt).lessThan(H(Kr)),Ft=Lt.not().and(Nt.not()).and(Ot.mul(Vt).lessThan(0));Z(Ft,()=>{const t=Ot.div(Ot.sub(Vt)),e=et(ht.x,dt.x,t),i=et(ht.z,dt.z,t);Z(Bt.equal(0),()=>{zt.assign(e),It.assign(i)}).Else(()=>{Dt.assign(e),kt.assign(i)}),Bt.addAssign(1)}).ElseIf(Lt,()=>{Z(Bt.equal(0),()=>{zt.assign(ht.x),It.assign(ht.z)}).Else(()=>{Dt.assign(ht.x),kt.assign(ht.z)}),Bt.addAssign(1)});const Rt=Vt,Ut=Pt.dot(ut.sub(pt)),jt=Nt,$t=tt(Ut).lessThan(H(Kr)),Wt=jt.not().and($t.not()).and(Rt.mul(Ut).lessThan(0));Z(Bt.lessThan(2),()=>{Z(Wt,()=>{const t=Rt.div(Rt.sub(Ut)),e=et(dt.x,ut.x,t),i=et(dt.z,ut.z,t);Z(Bt.equal(0),()=>{zt.assign(e),It.assign(i)}).Else(()=>{Dt.assign(e),kt.assign(i)}),Bt.addAssign(1)}).ElseIf(jt.and(Ft.not()).and(Lt.not()),()=>{Z(Bt.equal(0),()=>{zt.assign(dt.x),It.assign(dt.z)}).Else(()=>{Dt.assign(dt.x),kt.assign(dt.z)}),Bt.addAssign(1)})});const Gt=Ut,Ht=Ot,qt=$t,Zt=Lt,Yt=qt.not().and(Zt.not()).and(Gt.mul(Ht).lessThan(0));Z(Bt.lessThan(2),()=>{Z(Yt,()=>{const t=Gt.div(Gt.sub(Ht)),e=et(ut.x,ht.x,t),i=et(ut.z,ht.z,t);Z(Bt.equal(0),()=>{zt.assign(e),It.assign(i)}).Else(()=>{Dt.assign(e),kt.assign(i)}),Bt.addAssign(1)}).ElseIf(qt.and(Wt.not()).and(jt.not()),()=>{Z(Bt.equal(0),()=>{zt.assign(ut.x),It.assign(ut.z)}).Else(()=>{Dt.assign(ut.x),kt.assign(ut.z)}),Bt.addAssign(1)})}),Z(Bt.notEqual(2),()=>{Y()});const Xt=W(zt,H(0),It),Kt=W(Dt,H(0),kt).sub(Xt).dot(At),Qt=W(zt,H(0),It).toVar(),Jt=W(Dt,H(0),kt).toVar();Z(Kt.lessThan(0),()=>{const t=zt,e=It;Qt.x.assign(Dt),Qt.z.assign(kt),Jt.x.assign(t),Jt.z.assign(e)});const te=H(0),ee=Ct,ie=Qt.sub(pt).dot(At),ne=Jt.sub(pt).dot(At),se=ee.lessThanEqual(ie).or(ne.lessThanEqual(te));Z(se,()=>{Y()});const re=X(te,ie),oe=K(ee,ne),ae=pt.add(At.mul(re)),le=pt.add(At.mul(oe)),ce=ae.sub(mt).dot(Et).div(yt),he=le.sub(mt).dot(Et).div(yt),de=X(H(0),K(H(1),ce)),ue=X(H(0),K(H(1),he)),pe=tt(ue.sub(de));Z(pe.lessThanEqual(H(Kr)),()=>{Y()});const fe=nt(O.element(0),1);Z(fe.lessThan(it(P)),()=>{const t=fe.mul(3);V.element(t).assign(i.toFloat()),V.element(t.add(1)).assign(de),V.element(t.add(2)).assign(ue)})})})})().compute(C.length);u+=performance.now()-L;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,P)),Zr.enabled&&console.log(` Batch ${i+1}: ${lt} overlaps found (capacity: ${P})`),lt>P&&Zr.enabled&&console.warn(` WARNING: Overlap buffer overflow! ${lt} > ${P}. Some occlusion data lost.`),lt>0){const t=await r.getArrayBufferAsync(V.value),e=new Float32Array(t);c+=performance.now()-ot;const i=performance.now(),s=Math.min(lt,P);for(let t=0;t<s;t++){const i=3*t,s=Math.round(e[i]);Vr([e[i+1],e[i+2]],n[s])}h+=performance.now()-i,Zr.enabled&&console.log(` Processed ${s} overlaps into hiddenOverlapMap`)}else c+=performance.now()-ot}r.dispose(),Jr=null;const p=d+u+l+c+h;Zr.enabled&&(console.log(`WebGPU timing breakdown (total: ${p.toFixed(1)}ms):`),console.log(` Buffer creation: ${d.toFixed(1)}ms`),console.log(` Shader build: ${u.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 io(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 V,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 no{constructor(t,e=!0){this.meshes=hr(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 io(this.visibleEdges,this.groupKeyToIndex?this.visibleGroupIndices:null)}getHiddenLineGeometry(){return io(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();Zr.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 As(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]=[];Zr.startStep("Building line BVH");const h=new gr(t,{maxLeafSize:2,strategy:2});Zr.startStep("BVHcast overlaps"),a=performance.now();const d={candidates:0,backFaceCulled:0,yBoundsCulled:0,xzBoundsCulled:0,triangleEdgeCulled:0,planeTrimCulled:0,distThresholdCulled:0,noOverlapCulled:0,used:0,totalEdges:t.length,totalTriangles:l},u=this.useWebGPU,p={};u&&(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];u?Qr(h,n.get(s.geometry),s,p,t):Ur(h,n.get(s.geometry),s,c,d)}if(u){let t=!1;for(to(p,i,h,c,d).then(()=>{t=!0});!t;)yield}const f=d.totalEdges*d.totalTriangles;if(Zr.setStat("Total edges",d.totalEdges.toLocaleString()),Zr.setStat("Total triangles",d.totalTriangles.toLocaleString()),Zr.setStat("Brute-force pairs (edges × triangles)",f.toLocaleString()),Zr.setStat("BVH candidate pairs",d.candidates.toLocaleString()),f>0&&Zr.setStat("BVH reduction",(d.candidates/f*100).toFixed(3)+"% of brute-force"),d.candidates>0){const t=d.candidates,e=e=>(e/t*100).toFixed(2)+"%";u||(Zr.setStat("Rejected: back-face culling",d.backFaceCulled.toLocaleString()+" ("+e(d.backFaceCulled)+")"),Zr.setStat("Rejected: Y-bounds (tri below edge)",d.yBoundsCulled.toLocaleString()+" ("+e(d.yBoundsCulled)+")"),Zr.setStat("Rejected: XZ-bounds (no 2D overlap)",d.xzBoundsCulled.toLocaleString()+" ("+e(d.xzBoundsCulled)+")"),Zr.setStat("Rejected: edge lies on triangle",d.triangleEdgeCulled.toLocaleString()+" ("+e(d.triangleEdgeCulled)+")"),Zr.setStat("Rejected: line above tri plane",d.planeTrimCulled.toLocaleString()+" ("+e(d.planeTrimCulled)+")"),Zr.setStat("Rejected: trimmed edge too small",d.distThresholdCulled.toLocaleString()+" ("+e(d.distThresholdCulled)+")"),Zr.setStat("Rejected: no projected overlap",d.noOverlapCulled.toLocaleString()+" ("+e(d.noOverlapCulled)+")")),Zr.setStat("Producing overlaps",d.used.toLocaleString()+" ("+e(d.used)+")")}Zr.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(tr(i,n,!1,s),tr(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 so{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(Zr.reset(),Zr.startTotal(),t.isBufferGeometry&&(t=new b(t)),o){Zr.startStep("Visibility culling");let e=!1;for(o.cull(t).then(i=>{(t=new P).children=i,e=!0});!e;)yield}const l=new fr;l.iterationTime=i,l.thresholdAngle=n,l.projectionDirection.copy(eo),Zr.startStep("Generating candidate edges"),r("Generating candidate edges");let c=[],h=a?[]:null;if(yield*l.getEdgesGenerator(t,c,h),s&&(Zr.startStep("Generating intersection edges"),r("Generating intersection edges"),yield*l.getIntersectionEdgesGenerator(t,c,h)),Zr.startStep("Pre-filtering edges"),r("Pre-filtering edges"),h){const t=[],e=[];for(let i=0;i<c.length;i++)Ks(c[i])||(t.push(c[i]),e.push(h[i]));c=t,h=e}else c=c.filter(t=>!Ks(t));yield;const d=new no(t,this.useWebGPU);if(d.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)}d.groupKeyToIndex=t,d.hasGroups=!0}return r("Building BVH & computing overlaps"),yield*d.addEdgesGenerator(c,{onProgress:r?(t,e)=>{r("Building BVH & computing overlaps",t/e,d)}:null}),Zr.printSummary(),d}}new d,new d,new h;const ro=class t extends ht{constructor(i){super(i),e(this,"enabled",!0),e(this,"onDisposed",new at),e(this,"generator",new so),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(Ws),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),d=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 As(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 u=e.renderer.three,p=new Hs(u,{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(d),g.applyMatrix4(d);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(ro,"uuid","f2e76c3a-8b1d-4d5e-9a3f-7c6b2d4e8f1a");let oo=ro;class ao{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 lo=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 ao),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(Ws);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@${Uo.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(lo,"uuid","a659add7-1418-4771-a0d6-7d4d438e4624");let co=lo;const ho=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(Ws),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(Ws);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(Ws);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(ho,"uuid","dd9ccf2d-8a21-4821-b7f6-2949add16a29");let uo=ho;const po=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(Ws),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(Ws);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(Ws);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(po,"uuid","d1444724-dba6-4cdd-a0c7-68ee1450d166");let fo=po;class mo{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(wo),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(wo).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 go=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(Ws),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?Ve.join(r):Ve.intersect(r)}create(t,e){const i=new mo(this.components,e);return this.list.set(t,i),i}async addFromCategories(t){const e=new Set,i=this.components.get(Ws);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(go,"uuid","0da7ad77-f734-42ca-942f-a074adfd1e3a");let wo=go;const yo=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(Ws).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(wo),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=Ve.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(Ws),o=this.components.get(wo),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);Ve.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=Ve.join(t);e.push(r)}return Ve.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(wo),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(Ws).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)Ve.remove(e.map,t);return}for(const[,e]of this.list.entries())for(const[,i]of e)Ve.remove(i.map,t)}async byModel(t){const e=this.components.get(Ws),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(yo,"uuid","e25a7f3c-46c4-4a14-9d3d-5115f24ebeb7");let _o=yo;class bo{constructor(t,i){e(this,"enabled",!0),e(this,"components"),e(this,"onDisposed",new at),e(this,"mouse"),e(this,"world"),e(this,"debugMode",!1),e(this,"colorToModelId",new Map),e(this,"modelIdToColor",new Map),e(this,"renderTarget"),e(this,"renderTargetSize",new o.Vector2),e(this,"debugCanvas"),e(this,"debugContainer"),e(this,"colorMaterials",new Map),e(this,"originalMaterials",new Map),e(this,"originalLodColors",new Map),e(this,"colorsNeedUpdate",!0);const n=i.renderer;if(!n)throw new Error("A renderer is needed for the FastModelPicker to work!");this.world=i,this.mouse=new $e(n.three.domElement),this.components=t,this.setupRenderTarget(),this.setupFragmentListeners()}setupFragmentListeners(){const t=this.components.get(Ws);t.list.onItemSet.add(()=>{this.colorsNeedUpdate=!0}),t.list.onItemDeleted.add(()=>{this.colorsNeedUpdate=!0})}setupRenderTarget(){const t=this.world.renderer.three.getSize(new o.Vector2);this.renderTargetSize.copy(t),this.renderTarget=new o.WebGLRenderTarget(t.x,t.y),this.renderTarget.texture.format=o.RGBAFormat,this.renderTarget.texture.type=o.UnsignedByteType,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)}generateColorForModel(t){let e=0;for(let i=0;i<t.length;i++)e=(e<<5)-e+t.charCodeAt(i),e&=e;let i=Math.abs(e)%16777215;0===i&&(i=1);const n=i>>16&255||1,s=i>>8&255||1,r=255&i||1;return new o.Color(n/255,s/255,r/255)}colorToId(t){return Math.round(255*t.r)<<16|Math.round(255*t.g)<<8|Math.round(255*t.b)}assignColors(){const t=this.components.get(Ws);if(t.initialized){if(!this.colorsNeedUpdate){const e=new Set(t.list.keys()),i=new Set(this.modelIdToColor.keys());(e.size!==i.size||[...e].some(t=>!i.has(t)))&&(this.colorsNeedUpdate=!0)}if(this.colorsNeedUpdate){this.colorToModelId.clear(),this.modelIdToColor.clear();for(const t of this.colorMaterials.values())t.dispose();this.colorMaterials.clear();for(const[e]of t.list){const t=this.generateColorForModel(e),i=this.colorToId(t);this.colorToModelId.set(i,e),this.modelIdToColor.set(e,t);const n=new o.MeshBasicMaterial({color:t,depthTest:!0,depthWrite:!0});this.colorMaterials.set(e,n)}this.colorsNeedUpdate=!1}}}applyColorMaterials(){const t=this.components.get(Ws);if(t.initialized)for(const[e,i]of t.list){const t=this.colorMaterials.get(e);t&&i.object.traverse(e=>{if(e instanceof o.Mesh){if("isLODGeometry"in e.geometry){const i=e.material[0].uniforms.lodColor;return this.originalLodColors.has(i)||this.originalLodColors.set(i,i.value),void(i.value=t.color)}this.originalMaterials.has(e)||this.originalMaterials.set(e,e.material),e.material=t}})}}restoreOriginalMaterials(){for(const[t,e]of this.originalMaterials)t.material=e;for(const[t,e]of this.originalLodColors)t.value=e;this.originalMaterials.clear()}renderColorCoded(){if(!this.renderTarget||!this.world.renderer)throw new Error("Render target not initialized!");const t=this.world.renderer.three,e=this.world.scene.three,i=this.world.camera.three,n=t.getRenderTarget(),s=t.autoClear,r=new o.Color,a=t.getClearAlpha();t.getClearColor(r),this.applyColorMaterials(),t.setRenderTarget(this.renderTarget),t.autoClear=!0,t.setClearColor(0,1),t.clear(!0,!0,!1),t.render(e,i),t.setRenderTarget(n),t.autoClear=s,t.setClearColor(r,a),this.restoreOriginalMaterials(),this.debugMode&&this.debugCanvas&&this.updateDebugCanvas()}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)}async getModelAt(t){if(!this.renderTarget||!this.world.renderer)throw new Error("Render target not initialized!");const e=this.components.get(Ws);if(!e.initialized||0===e.list.size)return null;this.assignColors(),this.renderColorCoded();const i=t||this.mouse.position,n=this.renderTargetSize,s=Math.floor(.5*(i.x+1)*n.x),r=Math.floor(.5*(i.y+1)*(n.y-1)),o=Math.max(0,Math.min(n.x-1,s)),a=Math.max(0,Math.min(n.y-1,r)),l=this.world.renderer.three,c=new Uint8Array(4);l.readRenderTargetPixels(this.renderTarget,o,a,1,1,c);const h=c[0]<<16|c[1]<<8|c[2];return this.colorToModelId.get(h)||null}setDebugMode(t){this.debugMode=t,t?this.setupDebugCanvas():this.removeDebugCanvas()}removeDebugCanvas(){this.debugContainer&&(this.debugContainer.remove(),this.debugContainer=void 0,this.debugCanvas=void 0)}dispose(){this.mouse.dispose(),this.removeDebugCanvas();for(const t of this.colorMaterials.values())t.dispose();this.colorMaterials.clear(),this.renderTarget&&this.renderTarget.dispose(),this.colorToModelId.clear(),this.modelIdToColor.clear(),this.originalMaterials.clear(),this.originalLodColors.clear(),this.onDisposed.trigger(),this.onDisposed.reset()}}const vo=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 bo(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(vo,"uuid","4a82430c-7ff2-49ea-9401-60807502dad6");let xo=vo;class So{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"),e(this,"useFastModelPicking",!1);const n=i.renderer;if(!n)throw new Error("A renderer is needed for the raycaster to work!");this.world=i,this.mouse=new $e(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(Ws),o=this.world.renderer.three.domElement,a=this.mouse.rawPosition;let l=null;if(r.initialized){if(this.useFastModelPicking){const t=this.components.get(xo).get(this.world),i=await t.getModelAt(n);if(i){const t=r.list.get(i);if(t)if(e&&e.length>0){const i=await t.raycastWithSnapping({camera:s,dom:o,mouse:a,snappingClasses:e});l=i&&i.length>0?i[0]:await t.raycast({camera:s,dom:o,mouse:a})}else l=await t.raycast({camera:s,dom:o,mouse:a})}}else l=await r.raycast({camera:s,dom:o,mouse:a,snappingClasses:e});if(0===i.length)return l}this.three.setFromCamera(n,s);const c=this.intersect(i);return l?c&&c.distance<l.distance?c:l:c}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 To=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 So(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(To,"uuid","d5d8bdf0-db25-4952-b951-b643af207ace");let Co=To;class Ao 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,"uuid",_t.create()),e(this,"name"),e(this,"_scene"),e(this,"_camera"),e(this,"_renderer",null),e(this,"onPointerDown",async t=>{if(!this.camera.hasCameraControls())throw new Error("World: can't set dynamic anchor if the camera doesn't have controls.");const e=this.components.get(Co).get(this),i=await e.castRay();i&&i.point&&0===t.button&&this.camera.controls.setOrbitPoint(i.point.x,i.point.y,i.point.z)}),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)}get dynamicAnchor(){return this._dynamicAnchor}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){if(this.enabled=!1,this.isDisposing=!0,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(Oo).list.delete(this.uuid),this.onDisposed.trigger(),this.onDisposed.reset()}}class Eo{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 Mo{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 Po extends Re{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 Mo(this._config,this._component)),e(this,"directionalLight",new Eo(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 zo extends gt{constructor(t){super(t),e(this,"onSetup",new at),e(this,"isSetup",!1),e(this,"three"),e(this,"config",new Po(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(je).list.delete(this.config.uuid)}}var Io=(t=>(t[t.MANUAL=0]="MANUAL",t[t.AUTO=1]="AUTO",t))(Io||{});class Do 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,"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)}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.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.onContainerUpdated.trigger()}}class ko extends ut{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(Ws),i=this.components.get(fo);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:ko.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 Bo=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 Ao(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(Bo,"uuid","fdb61dc4-2ec1-4966-b83d-54ea795fad4a");let Oo=Bo;class Vo extends Re{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 Lo{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 ko&&(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 Vo(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(je).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 ko))return;const e=this.world.camera.controls;t?e.addEventListener("update",this.updateZoom):e.removeEventListener("update",this.updateZoom)}}const No=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 Lo(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(No,"uuid","d1e814d5-b81c-4452-87a2-f039375e0489");let Fo=No;const Ro=class t{constructor(){e(this,"onDisposed",new at),e(this,"list",new n),e(this,"enabled",!1),e(this,"_clock"),e(this,"onInit",new at),e(this,"update",()=>{if(!this.enabled)return;const t=this._clock.getDelta();for(const[e,i]of this.list)i.enabled&&i.isUpdateable()&&i.update(t);requestAnimationFrame(this.update)}),this._clock=new o.Clock,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._clock.start(),this.update(),this.onInit.trigger()}dispose(){let t;this.enabled=!1;for(const[e,i]of this.list)i.enabled=!1,e!==Ws.uuid?i.isDisposeable()&&i.dispose():t=i;null==t||t.dispose(),this._clock.stop(),this.onDisposed.trigger()}static setupBVH(){o.BufferGeometry.prototype.computeBoundsTree=Us,o.BufferGeometry.prototype.disposeBoundsTree=js,o.Mesh.prototype.raycast=Fs,o.LineSegments.prototype.raycast=Fs}};e(Ro,"release","2.4.3");let Uo=Ro;class jo{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 $o{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 Wo{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 Go{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 Ho extends ko{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 Go(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 $o(this)),this._navigationModes.set("FirstPerson",new jo(this)),this._navigationModes.set("Plan",new Wo(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(Ws);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 d=Math.max(c.x,c.y,c.z)*e,u=new o.Sphere(h,d);await this.controls.fitToSphere(u,!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 qo="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Zo(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function Yo(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 Xo={exports:{}};
|
|
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 d,Plane as u,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 S,Points as T,Sphere as C,BatchedMesh as A,OrthographicCamera as E,WebGLRenderTarget as M,Scene as P,Color as z,ShaderMaterial as I,Vector4 as D,NoBlending as k,GLSL3 as B,MathUtils as O,BufferGeometry as V}from"three";import*as L from"three/webgpu";import{instancedArray as N,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 q,If as Z,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 dt 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 ut extends dt{constructor(){super(...arguments),e(this,"hasCameraControls",()=>"controls"in this)}}class pt extends dt{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",[])}updateClippingPlanes(){this.onClippingPlanesUpdated.trigger()}setPlane(t,e,i){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)}}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 dt{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 St=function(t){const e=vt.exec(t);return!(null==e)};const Tt={allowBooleanAttributes:!1,unpairedTags:[]};function Ct(t){return" "===t||"\t"===t||"\n"===t||"\r"===t}function At(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 Bt("InvalidXml","XML declaration allowed only at the start of the document.",Lt(t,e));if("?"==t[e]&&">"==t[e+1]){e++;break}continue}return e}function Et(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 Mt='"',Pt="'";function zt(t,e){let i="",n="",s=!1;for(;e<t.length;e++){if(t[e]===Mt||t[e]===Pt)""===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 It=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function Dt(t,e){const i=xt(t,It),n={};for(let t=0;t<i.length;t++){if(0===i[t][1].length)return Bt("InvalidAttr","Attribute '"+i[t][2]+"' has no space in starting.",Nt(i[t]));if(void 0!==i[t][3]&&void 0===i[t][4])return Bt("InvalidAttr","Attribute '"+i[t][2]+"' is without value.",Nt(i[t]));if(void 0===i[t][3]&&!e.allowBooleanAttributes)return Bt("InvalidAttr","boolean attribute '"+i[t][2]+"' is not allowed.",Nt(i[t]));const s=i[t][2];if(!Ot(s))return Bt("InvalidAttr","Attribute '"+s+"' is an invalid name.",Nt(i[t]));if(n.hasOwnProperty(s))return Bt("InvalidAttr","Attribute '"+s+"' is repeated.",Nt(i[t]));n[s]=1}return!0}function kt(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 Bt(t,e,i){return{err:{code:t,msg:e,line:i.line||i,col:i.col}}}function Ot(t){return St(t)}function Vt(t){return St(t)}function Lt(t,e){const i=t.substring(0,e).split(/\r?\n/);return{line:i.length,col:i[i.length-1].length+1}}function Nt(t){return t.startIndex+t[1].length}const Ft={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,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(t,e,i){return t},captureMetaData:!1};function Rt(t){return"boolean"==typeof t?{enabled:t,maxEntitySize:1e4,maxExpansionDepth:10,maxTotalExpansions:1e3,maxExpandedLength:1e5,allowedTags:null,tagFilter:null}:"object"==typeof t&&null!==t?{enabled:!1!==t.enabled,maxEntitySize:t.maxEntitySize??1e4,maxExpansionDepth:t.maxExpansionDepth??10,maxTotalExpansions:t.maxTotalExpansions??1e3,maxExpandedLength:t.maxExpandedLength??1e5,allowedTags:t.allowedTags??null,tagFilter:t.tagFilter??null}:Rt(!0)}const Ut=function(t){const e=Object.assign({},Ft,t);return e.processEntities=Rt(e.processEntities),e};let jt;jt="function"!=typeof Symbol?"@@xmlMetadata":Symbol("XML Node Metadata");class $t{constructor(t){this.tagname=t,this.child=[],this[":@"]={}}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][jt]={startIndex:e})}static getMetaDataSymbol(){return jt}}class Wt{constructor(t){this.suppressValidationErr=!t,this.options=t}readDocType(t,e){const i={};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 n=1,s=!1,r=!1,o="";for(;e<t.length;e++)if("<"!==t[e]||r)if(">"===t[e]){if(r?"-"===t[e-1]&&"-"===t[e-2]&&(r=!1,n--):n--,0===n)break}else"["===t[e]?s=!0:o+=t[e];else{if(s&&Ht(t,"!ENTITY",e)){let n,s;if(e+=7,[n,s,e]=this.readEntityExp(t,e+1,this.suppressValidationErr),-1===s.indexOf("&")){const t=n.replace(/[.\-+*:]/g,"\\.");i[n]={regx:RegExp(`&${t};`,"g"),val:s}}}else if(s&&Ht(t,"!ELEMENT",e)){e+=8;const{index:i}=this.readElementExp(t,e+1);e=i}else if(s&&Ht(t,"!ATTLIST",e))e+=8;else if(s&&Ht(t,"!NOTATION",e)){e+=9;const{index:i}=this.readNotationExp(t,e+1,this.suppressValidationErr);e=i}else{if(!Ht(t,"!--",e))throw new Error("Invalid DOCTYPE");r=!0}n++,o=""}if(0!==n)throw new Error("Unclosed DOCTYPE")}return{entities:i,i:e}}readEntityExp(t,e){e=Gt(t,e);let i="";for(;e<t.length&&!/\s/.test(t[e])&&'"'!==t[e]&&"'"!==t[e];)i+=t[e],e++;if(qt(i),e=Gt(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 n="";if([e,n]=this.readIdentifierVal(t,e,"entity"),!1!==this.options.enabled&&this.options.maxEntitySize&&n.length>this.options.maxEntitySize)throw new Error(`Entity "${i}" size (${n.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`);return[i,n,--e]}readNotationExp(t,e){e=Gt(t,e);let i="";for(;e<t.length&&!/\s/.test(t[e]);)i+=t[e],e++;!this.suppressValidationErr&&qt(i),e=Gt(t,e);const n=t.substring(e,e+6).toUpperCase();if(!this.suppressValidationErr&&"SYSTEM"!==n&&"PUBLIC"!==n)throw new Error(`Expected SYSTEM or PUBLIC, found "${n}"`);e+=n.length,e=Gt(t,e);let s=null,r=null;if("PUBLIC"===n)[e,s]=this.readIdentifierVal(t,e,"publicIdentifier"),'"'!==t[e=Gt(t,e)]&&"'"!==t[e]||([e,r]=this.readIdentifierVal(t,e,"systemIdentifier"));else if("SYSTEM"===n&&([e,r]=this.readIdentifierVal(t,e,"systemIdentifier"),!this.suppressValidationErr&&!r))throw new Error("Missing mandatory system identifier for SYSTEM notation");return{notationName:i,publicIdentifier:s,systemIdentifier:r,index:--e}}readIdentifierVal(t,e,i){let n="";const s=t[e];if('"'!==s&&"'"!==s)throw new Error(`Expected quoted string, found "${s}"`);for(e++;e<t.length&&t[e]!==s;)n+=t[e],e++;if(t[e]!==s)throw new Error(`Unterminated ${i} value`);return[++e,n]}readElementExp(t,e){e=Gt(t,e);let i="";for(;e<t.length&&!/\s/.test(t[e]);)i+=t[e],e++;if(!this.suppressValidationErr&&!St(i))throw new Error(`Invalid element name: "${i}"`);let n="";if("E"===t[e=Gt(t,e)]&&Ht(t,"MPTY",e))e+=4;else if("A"===t[e]&&Ht(t,"NY",e))e+=2;else if("("===t[e]){for(e++;e<t.length&&")"!==t[e];)n+=t[e],e++;if(")"!==t[e])throw new Error("Unterminated content model")}else if(!this.suppressValidationErr)throw new Error(`Invalid Element Expression, found "${t[e]}"`);return{elementName:i,contentModel:n.trim(),index:e}}readAttlistExp(t,e){e=Gt(t,e);let i="";for(;e<t.length&&!/\s/.test(t[e]);)i+=t[e],e++;qt(i),e=Gt(t,e);let n="";for(;e<t.length&&!/\s/.test(t[e]);)n+=t[e],e++;if(!qt(n))throw new Error(`Invalid attribute name: "${n}"`);e=Gt(t,e);let s="";if("NOTATION"===t.substring(e,e+8).toUpperCase()){if(s="NOTATION","("!==t[e=Gt(t,e+=8)])throw new Error(`Expected '(', found "${t[e]}"`);e++;let i=[];for(;e<t.length&&")"!==t[e];){let n="";for(;e<t.length&&"|"!==t[e]&&")"!==t[e];)n+=t[e],e++;if(n=n.trim(),!qt(n))throw new Error(`Invalid notation name: "${n}"`);i.push(n),"|"===t[e]&&(e++,e=Gt(t,e))}if(")"!==t[e])throw new Error("Unterminated list of notations");e++,s+=" ("+i.join("|")+")"}else{for(;e<t.length&&!/\s/.test(t[e]);)s+=t[e],e++;const i=["CDATA","ID","IDREF","IDREFS","ENTITY","ENTITIES","NMTOKEN","NMTOKENS"];if(!this.suppressValidationErr&&!i.includes(s.toUpperCase()))throw new Error(`Invalid attribute type: "${s}"`)}e=Gt(t,e);let r="";return"#REQUIRED"===t.substring(e,e+8).toUpperCase()?(r="#REQUIRED",e+=8):"#IMPLIED"===t.substring(e,e+7).toUpperCase()?(r="#IMPLIED",e+=7):[e,r]=this.readIdentifierVal(t,e,"ATTLIST"),{elementName:i,attributeName:n,attributeType:s,defaultValue:r,index:e}}}const Gt=(t,e)=>{for(;e<t.length&&/\s/.test(t[e]);)e++;return e};function Ht(t,e,i){for(let n=0;n<e.length;n++)if(e[n]!==t[i+n+1])return!1;return!0}function qt(t){if(St(t))return t;throw new Error(`Invalid entity name ${t}`)}const Zt=/^[-+]?0x[a-fA-F0-9]+$/,Yt=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,Xt={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function Kt(t,e={}){if(e=Object.assign({},Xt,e),!t||"string"!=typeof t)return t;let i=t.trim();if(void 0!==e.skipLike&&e.skipLike.test(i))return t;if("0"===t)return 0;if(e.hex&&Zt.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(i.includes("e")||i.includes("E"))return function(t,e,i){if(!i.eNotation)return t;const n=e.match(Qt);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?i.leadingZeros&&!a?(e=(n[1]||"")+n[3],Number(e)):t:Number(e)}return t}(t,i,e);{const n=Yt.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}}const Qt=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function Jt(t){return"function"==typeof t?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}class te{constructor(t){if(this.options=t,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"¢"},pound:{regex:/&(pound|#163);/g,val:"£"},yen:{regex:/&(yen|#165);/g,val:"¥"},euro:{regex:/&(euro|#8364);/g,val:"€"},copyright:{regex:/&(copy|#169);/g,val:"©"},reg:{regex:/&(reg|#174);/g,val:"®"},inr:{regex:/&(inr|#8377);/g,val:"₹"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(t,e)=>me(e,10,"&#")},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(t,e)=>me(e,16,"&#x")}},this.addExternalEntities=ee,this.parseXml=oe,this.parseTextData=ie,this.resolveNameSpace=ne,this.buildAttributesMap=re,this.isItStopNode=he,this.replaceEntitiesValue=le,this.readStopNodeData=pe,this.saveTextToParentTag=ce,this.addChild=ae,this.ignoreAttributesFn=Jt(this.options.ignoreAttributes),this.entityExpansionCount=0,this.currentExpandedLength=0,this.options.stopNodes&&this.options.stopNodes.length>0){this.stopNodesExact=new Set,this.stopNodesWildcard=new Set;for(let t=0;t<this.options.stopNodes.length;t++){const e=this.options.stopNodes[t];"string"==typeof e&&(e.startsWith("*.")?this.stopNodesWildcard.add(e.substring(2)):this.stopNodesExact.add(e))}}}}function ee(t){const e=Object.keys(t);for(let i=0;i<e.length;i++){const n=e[i],s=n.replace(/[.\-+*:]/g,"\\.");this.lastEntities[n]={regex:new RegExp("&"+s+";","g"),val:t[n]}}}function ie(t,e,i,n,s,r,o){if(void 0!==t&&(this.options.trimValues&&!n&&(t=t.trim()),t.length>0)){o||(t=this.replaceEntitiesValue(t,e,i));const n=this.options.tagValueProcessor(e,t,i,s,r);if(null==n)return t;if(typeof n!=typeof t||n!==t)return n;if(this.options.trimValues)return fe(t,this.options.parseTagValue,this.options.numberParseOptions);return t.trim()===t?fe(t,this.options.parseTagValue,this.options.numberParseOptions):t}}function ne(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 re(t,e,i){if(!0!==this.options.ignoreAttributes&&"string"==typeof t){const n=xt(t,se),s=n.length,r={};for(let t=0;t<s;t++){const s=this.resolveNameSpace(n[t][1]);if(this.ignoreAttributesFn(s,e))continue;let o=n[t][4],a=this.options.attributeNamePrefix+s;if(s.length)if(this.options.transformAttributeName&&(a=this.options.transformAttributeName(a)),"__proto__"===a&&(a="#__proto__"),void 0!==o){this.options.trimValues&&(o=o.trim()),o=this.replaceEntitiesValue(o,i,e);const t=this.options.attributeValueProcessor(s,o,e);r[a]=null==t?o:typeof t!=typeof o||t!==o?t:fe(o,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(r[a]=!0)}if(!Object.keys(r).length)return;if(this.options.attributesGroupName){const t={};return t[this.options.attributesGroupName]=r,t}return r}}const oe=function(t){t=t.replace(/\r\n?/g,"\n");const e=new $t("!xml");let i=e,n="",s="";this.entityExpansionCount=0,this.currentExpandedLength=0;const r=new Wt(this.options.processEntities);for(let o=0;o<t.length;o++){if("<"===t[o])if("/"===t[o+1]){const e=de(t,">",o,"Closing Tag is not closed.");let r=t.substring(o+2,e).trim();if(this.options.removeNSPrefix){const t=r.indexOf(":");-1!==t&&(r=r.substr(t+1))}this.options.transformTagName&&(r=this.options.transformTagName(r)),i&&(n=this.saveTextToParentTag(n,i,s));const a=s.substring(s.lastIndexOf(".")+1);if(r&&-1!==this.options.unpairedTags.indexOf(r))throw new Error(`Unpaired tag can not be used as closing tag: </${r}>`);let l=0;a&&-1!==this.options.unpairedTags.indexOf(a)?(l=s.lastIndexOf(".",s.lastIndexOf(".")-1),this.tagsNodeStack.pop()):l=s.lastIndexOf("."),s=s.substring(0,l),i=this.tagsNodeStack.pop(),n="",o=e}else if("?"===t[o+1]){let e=ue(t,o,!1,"?>");if(!e)throw new Error("Pi Tag is not closed.");if(n=this.saveTextToParentTag(n,i,s),this.options.ignoreDeclaration&&"?xml"===e.tagName||this.options.ignorePiTags);else{const t=new $t(e.tagName);t.add(this.options.textNodeName,""),e.tagName!==e.tagExp&&e.attrExpPresent&&(t[":@"]=this.buildAttributesMap(e.tagExp,s,e.tagName)),this.addChild(i,t,s,o)}o=e.closeIndex+1}else if("!--"===t.substr(o+1,3)){const e=de(t,"--\x3e",o+4,"Comment is not closed.");if(this.options.commentPropName){const r=t.substring(o+4,e-2);n=this.saveTextToParentTag(n,i,s),i.add(this.options.commentPropName,[{[this.options.textNodeName]:r}])}o=e}else if("!D"===t.substr(o+1,2)){const e=r.readDocType(t,o);this.docTypeEntities=e.entities,o=e.i}else if("!["===t.substr(o+1,2)){const e=de(t,"]]>",o,"CDATA is not closed.")-2,r=t.substring(o+9,e);n=this.saveTextToParentTag(n,i,s);let a=this.parseTextData(r,i.tagname,s,!0,!1,!0,!0);null==a&&(a=""),this.options.cdataPropName?i.add(this.options.cdataPropName,[{[this.options.textNodeName]:r}]):i.add(this.options.textNodeName,a),o=e+2}else{let r=ue(t,o,this.options.removeNSPrefix),a=r.tagName;const l=r.rawTagName;let c=r.tagExp,h=r.attrExpPresent,d=r.closeIndex;if(this.options.transformTagName){const t=this.options.transformTagName(a);c===a&&(c=t),a=t}i&&n&&"!xml"!==i.tagname&&(n=this.saveTextToParentTag(n,i,s,!1));const u=i;u&&-1!==this.options.unpairedTags.indexOf(u.tagname)&&(i=this.tagsNodeStack.pop(),s=s.substring(0,s.lastIndexOf("."))),a!==e.tagname&&(s+=s?"."+a:a);const p=o;if(this.isItStopNode(this.stopNodesExact,this.stopNodesWildcard,s,a)){let e="";if(c.length>0&&c.lastIndexOf("/")===c.length-1)"/"===a[a.length-1]?(a=a.substr(0,a.length-1),s=s.substr(0,s.length-1),c=a):c=c.substr(0,c.length-1),o=r.closeIndex;else if(-1!==this.options.unpairedTags.indexOf(a))o=r.closeIndex;else{const i=this.readStopNodeData(t,l,d+1);if(!i)throw new Error(`Unexpected end of ${l}`);o=i.i,e=i.tagContent}const n=new $t(a);a!==c&&h&&(n[":@"]=this.buildAttributesMap(c,s,a)),e&&(e=this.parseTextData(e,a,s,!0,h,!0,!0)),s=s.substr(0,s.lastIndexOf(".")),n.add(this.options.textNodeName,e),this.addChild(i,n,s,p)}else{if(c.length>0&&c.lastIndexOf("/")===c.length-1){if("/"===a[a.length-1]?(a=a.substr(0,a.length-1),s=s.substr(0,s.length-1),c=a):c=c.substr(0,c.length-1),this.options.transformTagName){const t=this.options.transformTagName(a);c===a&&(c=t),a=t}const t=new $t(a);a!==c&&h&&(t[":@"]=this.buildAttributesMap(c,s,a)),this.addChild(i,t,s,p),s=s.substr(0,s.lastIndexOf("."))}else{const t=new $t(a);this.tagsNodeStack.push(i),a!==c&&h&&(t[":@"]=this.buildAttributesMap(c,s,a)),this.addChild(i,t,s,p),i=t}n="",o=d}}else n+=t[o]}return e.child};function ae(t,e,i,n){this.options.captureMetaData||(n=void 0);const s=this.options.updateTag(e.tagname,i,e[":@"]);!1===s||("string"==typeof s?(e.tagname=s,t.addChild(e,n)):t.addChild(e,n))}const le=function(t,e,i){if(-1===t.indexOf("&"))return t;const n=this.options.processEntities;if(!n.enabled)return t;if(n.allowedTags&&!n.allowedTags.includes(e))return t;if(n.tagFilter&&!n.tagFilter(e,i))return t;for(let e in this.docTypeEntities){const i=this.docTypeEntities[e],s=t.match(i.regx);if(s){if(this.entityExpansionCount+=s.length,n.maxTotalExpansions&&this.entityExpansionCount>n.maxTotalExpansions)throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${n.maxTotalExpansions}`);const e=t.length;if(t=t.replace(i.regx,i.val),n.maxExpandedLength&&(this.currentExpandedLength+=t.length-e,this.currentExpandedLength>n.maxExpandedLength))throw new Error(`Total expanded content size exceeded: ${this.currentExpandedLength} > ${n.maxExpandedLength}`)}}if(-1===t.indexOf("&"))return t;for(let e in this.lastEntities){const i=this.lastEntities[e];t=t.replace(i.regex,i.val)}if(-1===t.indexOf("&"))return t;if(this.options.htmlEntities)for(let e in this.htmlEntities){const i=this.htmlEntities[e];t=t.replace(i.regex,i.val)}return t=t.replace(this.ampEntity.regex,this.ampEntity.val)};function ce(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 he(t,e,i,n){return!(!e||!e.has(n))||!(!t||!t.has(i))}function de(t,e,i,n){const s=t.indexOf(e,i);if(-1===s)throw new Error(n);return s+e.length-1}function ue(t,e,i,n=">"){const s=function(t,e,i=">"){let n,s="";for(let r=e;r<t.length;r++){let e=t[r];if(n)e===n&&(n="");else if('"'===e||"'"===e)n=e;else if(e===i[0]){if(!i[1])return{data:s,index:r};if(t[r+1]===i[1])return{data:s,index:r}}else"\t"===e&&(e=" ");s+=e}}(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 pe(t,e,i){const n=i;let s=1;for(;i<t.length;i++)if("<"===t[i])if("/"===t[i+1]){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("?"===t[i+1]){i=de(t,"?>",i+1,"StopNode is not closed.")}else if("!--"===t.substr(i+1,3)){i=de(t,"--\x3e",i+3,"StopNode is not closed.")}else if("!["===t.substr(i+1,2)){i=de(t,"]]>",i,"StopNode is not closed.")-2}else{const n=ue(t,i,">");if(n){(n&&n.tagName)===e&&"/"!==n.tagExp[n.tagExp.length-1]&&s++,i=n.closeIndex}}}function fe(t,e,i){if(e&&"string"==typeof t){const e=t.trim();return"true"===e||"false"!==e&&Kt(t,i)}return void 0!==t?t:""}function me(t,e,i){const n=Number.parseInt(t,e);return n>=0&&n<=1114111?String.fromCodePoint(n):i+t+";"}const ge=$t.getMetaDataSymbol();function we(t,e){return ye(t,e)}function ye(t,e,i){let n;const s={};for(let r=0;r<t.length;r++){const o=t[r],a=_e(o);let l="";if(l=void 0===i?a:i+"."+a,a===e.textNodeName)void 0===n?n=o[a]:n+=""+o[a];else{if(void 0===a)continue;if(o[a]){let t=ye(o[a],e,l);const i=ve(t,e);void 0!==o[ge]&&(t[ge]=o[ge]),o[":@"]?be(t,o[":@"],l,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!==s[a]&&s.hasOwnProperty(a)?(Array.isArray(s[a])||(s[a]=[s[a]]),s[a].push(t)):e.isArray(a,l,i)?s[a]=[t]:s[a]=t}}}return"string"==typeof n?n.length>0&&(s[e.textNodeName]=n):void 0!==n&&(s[e.textNodeName]=n),s}function _e(t){const e=Object.keys(t);for(let t=0;t<e.length;t++){const i=e[t];if(":@"!==i)return i}}function be(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];n.isArray(r,i+"."+r,!0,!0)?t[r]=[e[r]]:t[r]=e[r]}}}function ve(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 xe{constructor(t){this.externalEntities={},this.options=Ut(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({},Tt,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=At(t,r),r.err)return r}else{if("<"!==t[r]){if(Ct(t[r]))continue;return Bt("InvalidChar","char '"+t[r]+"' is not expected.",Lt(t,r))}{let o=r;if(r++,"!"===t[r]){r=Et(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--),!Vt(l)){let e;return e=0===l.trim().length?"Invalid space after '<'.":"Tag '"+l+"' is an invalid name.",Bt("InvalidTag",e,Lt(t,r))}const c=zt(t,r);if(!1===c)return Bt("InvalidAttr","Attributes for '"+l+"' have open quote.",Lt(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=Dt(h,e);if(!0!==s)return Bt(s.err.code,s.err.msg,Lt(t,i+s.err.line));n=!0}else if(a){if(!c.tagClosed)return Bt("InvalidTag","Closing tag '"+l+"' doesn't have proper closing.",Lt(t,r));if(h.trim().length>0)return Bt("InvalidTag","Closing tag '"+l+"' can't have attributes or invalid starting.",Lt(t,o));if(0===i.length)return Bt("InvalidTag","Closing tag '"+l+"' has not been opened.",Lt(t,o));{const e=i.pop();if(l!==e.tagName){let i=Lt(t,e.tagStartPos);return Bt("InvalidTag","Expected closing tag '"+e.tagName+"' (opened in line "+i.line+", col "+i.col+") instead of closing tag '"+l+"'.",Lt(t,o))}0==i.length&&(s=!0)}}else{const a=Dt(h,e);if(!0!==a)return Bt(a.err.code,a.err.msg,Lt(t,r-h.length+a.err.line));if(!0===s)return Bt("InvalidXml","Multiple possible root nodes found.",Lt(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=Et(t,r);continue}if("?"!==t[r+1])break;if(r=At(t,++r),r.err)return r}else if("&"===t[r]){const e=kt(t,r);if(-1==e)return Bt("InvalidChar","char '&' is not expected.",Lt(t,r));r=e}else if(!0===s&&!Ct(t[r]))return Bt("InvalidXml","Extra text at the end",Lt(t,r));"<"===t[r]&&r--}}}return n?1==i.length?Bt("InvalidTag","Unclosed tag '"+i[0].tagName+"'.",Lt(t,i[0].tagStartPos)):!(i.length>0)||Bt("InvalidXml","Invalid '"+JSON.stringify(i.map(t=>t.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):Bt("InvalidXml","Start tag expected.",1)}(t,e);if(!0!==i)throw Error(`${i.err.msg}:${i.err.line}:${i.err.col}`)}const i=new te(this.options);i.addExternalEntities(this.externalEntities);const n=i.parseXml(t);return this.options.preserveOrder||void 0===n?n:we(n,this.options)}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 '
'");if("&"===e)throw new Error("An entity with value '&' is not permitted");this.externalEntities[t]=e}static getMetaDataSymbol(){return $t.getMetaDataSymbol()}}function Se(t,e){let i="";return e.format&&e.indentBy.length>0&&(i="\n"),Te(t,e,"",i)}function Te(t,e,i,n){let s="",r=!1;for(let o=0;o<t.length;o++){const a=t[o],l=Ce(a);if(void 0===l)continue;let c="";if(c=0===i.length?l:`${i}.${l}`,l===e.textNodeName){let t=a[l];Ee(c,e)||(t=e.tagValueProcessor(l,t),t=Me(t,e)),r&&(s+=n),s+=t,r=!1;continue}if(l===e.cdataPropName){r&&(s+=n),s+=`<![CDATA[${a[l][0][e.textNodeName]}]]>`,r=!1;continue}if(l===e.commentPropName){s+=n+`\x3c!--${a[l][0][e.textNodeName]}--\x3e`,r=!0;continue}if("?"===l[0]){const t=Ae(a[":@"],e),i="?xml"===l?"":n;let o=a[l][0][e.textNodeName];o=0!==o.length?" "+o:"",s+=i+`<${l}${o}${t}?>`,r=!0;continue}let h=n;""!==h&&(h+=e.indentBy);const d=n+`<${l}${Ae(a[":@"],e)}`,u=Te(a[l],e,c,h);-1!==e.unpairedTags.indexOf(l)?e.suppressUnpairedNode?s+=d+">":s+=d+"/>":u&&0!==u.length||!e.suppressEmptyNode?u&&u.endsWith(">")?s+=d+`>${u}${n}</${l}>`:(s+=d+">",u&&""!==n&&(u.includes("/>")||u.includes("</"))?s+=n+e.indentBy+u+n:s+=u,s+=`</${l}>`):s+=d+"/>",r=!0}return s}function Ce(t){const e=Object.keys(t);for(let i=0;i<e.length;i++){const n=e[i];if(t.hasOwnProperty(n)&&":@"!==n)return n}}function Ae(t,e){let i="";if(t&&!e.ignoreAttributes)for(let n in t){if(!t.hasOwnProperty(n))continue;let s=e.attributeValueProcessor(n,t[n]);s=Me(s,e),!0===s&&e.suppressBooleanAttributes?i+=` ${n.substr(e.attributeNamePrefix.length)}`:i+=` ${n.substr(e.attributeNamePrefix.length)}="${s}"`}return i}function Ee(t,e){let i=(t=t.substr(0,t.length-e.textNodeName.length-1)).substr(t.lastIndexOf(".")+1);for(let n in e.stopNodes)if(e.stopNodes[n]===t||e.stopNodes[n]==="*."+i)return!0;return!1}function Me(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 Pe={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:"&"},{regex:new RegExp(">","g"),val:">"},{regex:new RegExp("<","g"),val:"<"},{regex:new RegExp("'","g"),val:"'"},{regex:new RegExp('"',"g"),val:"""}],processEntities:!0,stopNodes:[],oneListGroup:!1};function ze(t){this.options=Object.assign({},Pe,t),!0===this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn=Jt(this.options.ignoreAttributes),this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=ke),this.processTextOrObjNode=Ie,this.options.format?(this.indentate=De,this.tagEndChar=">\n",this.newLine="\n"):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}function Ie(t,e,i,n){const s=this.j2x(t,i+1,n.concat(e));return void 0!==t[this.options.textNodeName]&&1===Object.keys(t).length?this.buildTextValNode(t[this.options.textNodeName],e,s.attrStr,i):this.buildObjectNode(s.val,e,s.attrStr,i)}function De(t){return this.options.indentBy.repeat(t)}function ke(t){return!(!t.startsWith(this.options.attributeNamePrefix)||t===this.options.textNodeName)&&t.substr(this.attrPrefixLen)}ze.prototype.build=function(t){return this.options.preserveOrder?Se(t,this.options):(Array.isArray(t)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(t={[this.options.arrayNodeName]:t}),this.j2x(t,0,[]).val)},ze.prototype.j2x=function(t,e,i){let n="",s="";const r=i.join(".");for(let o in t)if(Object.prototype.hasOwnProperty.call(t,o))if(void 0===t[o])this.isAttribute(o)&&(s+="");else if(null===t[o])this.isAttribute(o)||o===this.options.cdataPropName?s+="":"?"===o[0]?s+=this.indentate(e)+"<"+o+"?"+this.tagEndChar:s+=this.indentate(e)+"<"+o+"/"+this.tagEndChar;else if(t[o]instanceof Date)s+=this.buildTextValNode(t[o],o,"",e);else if("object"!=typeof t[o]){const i=this.isAttribute(o);if(i&&!this.ignoreAttributesFn(i,r))n+=this.buildAttrPairStr(i,""+t[o]);else if(!i)if(o===this.options.textNodeName){let e=this.options.tagValueProcessor(o,""+t[o]);s+=this.replaceEntitiesValue(e)}else s+=this.buildTextValNode(t[o],o,"",e)}else if(Array.isArray(t[o])){const n=t[o].length;let r="",a="";for(let l=0;l<n;l++){const n=t[o][l];if(void 0===n);else if(null===n)"?"===o[0]?s+=this.indentate(e)+"<"+o+"?"+this.tagEndChar:s+=this.indentate(e)+"<"+o+"/"+this.tagEndChar;else if("object"==typeof n)if(this.options.oneListGroup){const t=this.j2x(n,e+1,i.concat(o));r+=t.val,this.options.attributesGroupName&&n.hasOwnProperty(this.options.attributesGroupName)&&(a+=t.attrStr)}else r+=this.processTextOrObjNode(n,o,e,i);else if(this.options.oneListGroup){let t=this.options.tagValueProcessor(o,n);t=this.replaceEntitiesValue(t),r+=t}else r+=this.buildTextValNode(n,o,"",e)}this.options.oneListGroup&&(r=this.buildObjectNode(r,o,a,e)),s+=r}else if(this.options.attributesGroupName&&o===this.options.attributesGroupName){const e=Object.keys(t[o]),i=e.length;for(let s=0;s<i;s++)n+=this.buildAttrPairStr(e[s],""+t[o][e[s]])}else s+=this.processTextOrObjNode(t[o],o,e,i);return{attrStr:n,val:s}},ze.prototype.buildAttrPairStr=function(t,e){return e=this.options.attributeValueProcessor(t,""+e),e=this.replaceEntitiesValue(e),this.options.suppressBooleanAttributes&&"true"===e?" "+t:" "+t+'="'+e+'"'},ze.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}},ze.prototype.closeTag=function(t){let e="";return-1!==this.options.unpairedTags.indexOf(t)?this.options.suppressUnpairedNode||(e="/"):e=this.options.suppressEmptyNode?"/":`></${t}`,e},ze.prototype.buildTextValNode=function(t,e,i,n){if(!1!==this.options.cdataPropName&&e===this.options.cdataPropName)return this.indentate(n)+`<![CDATA[${t}]]>`+this.newLine;if(!1!==this.options.commentPropName&&e===this.options.commentPropName)return this.indentate(n)+`\x3c!--${t}--\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}},ze.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 Be{}e(Be,"parser",new xe({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(Be,"builder",new ze({attributeNamePrefix:"$",ignoreAttributes:!1,suppressBooleanAttributes:!1}));class Oe 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(Co).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 Ve{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=Ve.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=Ve.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=Ve.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 Le 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 Ne{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 Fe{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 Re{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(je).list.set(this.uuid,this)}get controls(){return Ne.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(Ne.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(Ne.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 Ue=class t extends ht{constructor(i){super(i),e(this,"list",new n),e(this,"enabled",!0),i.add(t.uuid,this)}};e(Ue,"uuid","b8c764e0-6b24-4e77-9a32-35fa728ee5b4");let je=Ue;class $e{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 We=1.25,Ge=32,He=Math.pow(2,-24),qe=Symbol("SKIP_GENERATION"),Ze={strategy:0,maxDepth:40,maxLeafSize:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null,[qe]:!1};function Ye(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 Xe(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 Ke(t,e){e.set(t)}function Qe(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 Je(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 ti(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 ei(t,e){return 65535===e[t+15]}function ii(t,e){return e[t+6]}function ni(t,e){return e[t+14]}function si(t){return t+8}function ri(t,e){return t+8*e[t+6]}function oi(t,e){return e[t+7]}function ai(t){return t}function li(t,e,i,n,s){let r=1/0,o=1/0,a=1/0,l=-1/0,c=-1/0,h=-1/0,d=1/0,u=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<d&&(d=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<u&&(u=y),y>m&&(m=y);const x=t[n+4],S=t[n+5],T=x-S,C=x+S;T<a&&(a=T),C>h&&(h=C),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]=d,s[1]=u,s[2]=p,s[3]=f,s[4]=m,s[5]=g}const ci=32,hi=(t,e)=>t.candidate-e.candidate,di=new Array(ci).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),ui=new Float32Array(6);class pi{constructor(){this.boundingData=new Float32Array(6)}}let fi,mi,gi,wi;const yi=Math.pow(2,32);function _i(t){return"count"in t?1:1+_i(t.left)+_i(t.right)}function bi(t,e,i){return fi=new Float32Array(i),mi=new Uint32Array(i),gi=new Uint16Array(i),wi=new Uint8Array(i),vi(t,e)}function vi(t,e){const i=t/4,n=t/2,s="count"in e,r=e.boundingData;for(let t=0;t<6;t++)fi[i+t]=r[t];if(s)return e.buffer?(wi.set(new Uint8Array(e.buffer),t),t+e.buffer.byteLength):(mi[i+6]=e.offset,gi[n+14]=e.count,gi[n+15]=65535,t+Ge);{const{left:n,right:s,splitAxis:r}=e;let o=vi(t+Ge,n);const a=o/Ge-t/Ge;if(a>yi)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return mi[i+6]=a,mi[i+7]=r,vi(o,s)}}function xi(t,e,i,n,s,r){const{maxDepth:o,verbose:a,maxLeafSize:l,strategy:c,onProgress:h}=s,d=t.primitiveBuffer,u=t.primitiveBufferStride,p=new Float32Array(6);let f=!1;const m=new pi;return li(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=Xe(e),-1!==o&&(a=(e[o]+e[o+3])/2);else if(1===r)o=Xe(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=ti(t);let l=We*s;const c=i.offset||0,h=6*(n-c),d=6*(n+s-c);for(let t=0;t<3;t++){const n=e[t],c=(e[t+3]-n)/ci;if(s<8){const e=[...di];e.length=s;let n=0;for(let s=h;s<d;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;Je(s,i,o)}e.sort(hi);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<d;n+=6){const s=i[n+2*t];for(let t=0;t<c;t++){const r=e[t];s>=r.candidate?Je(n,i,r.rightCacheBounds):(Je(n,i,r.leftCacheBounds),r.count++)}}for(let i=0;i<c;i++){const n=e[i],c=n.count,h=s-n.count,d=n.leftCacheBounds,u=n.rightCacheBounds;let p=0;0!==c&&(p=ti(d)/r);let f=0;0!==h&&(f=ti(u)/r);const m=1+We*(p*c+f*h);m<l&&(o=t,l=m,a=n.candidate)}}else{for(let t=0;t<ci;t++){const e=di[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<d;e+=6){let s=~~((i[e+2*t]-n)/c);s>=ci&&(s=31);const r=di[s];r.count++,Je(e,i,r.bounds)}const e=di[31];Ke(e.bounds,e.rightCacheBounds);for(let t=30;t>=0;t--){const e=di[t],i=di[t+1];Qe(e.bounds,i.rightCacheBounds,e.rightCacheBounds)}let u=0;for(let e=0;e<31;e++){const i=di[e],n=i.count,c=i.bounds,h=di[e+1].rightCacheBounds;0!==n&&(0===u?Ke(c,ui):Qe(c,ui,ui)),u+=n;let d=0,p=0;0!==u&&(d=ti(ui)/r);const f=s-u;0!==f&&(p=ti(h)/r);const m=1+We*(d*u+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--}}(d,u,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 pi,o=n,a=w-n;i.left=r,li(e,o,a,r.boundingData,p),t(r,o,a,p,h+1);const l=new pi,c=w,d=s-a;i.right=l,li(e,c,d,l.boundingData,p),t(l,c,d,p,h+1)}return i}(m,i,n,p),m;function g(t){h&&h((t-r.offset)/r.count)}}function Si(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=xi(t,a,n.offset,n.count,e,o),r=_i(s),l=new i(Ge*r);return bi(0,s,l),l})}class Ti{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 Ci{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 Ai=new Ci;let Ei,Mi;const Pi=[],zi=new Ti(()=>new a);function Ii(t,e,i,n,s,r){Ei=zi.getPrimitive(),Mi=zi.getPrimitive(),Pi.push(Ei,Mi),Ai.setBuffer(t._roots[e]);const o=Di(0,t.geometry,i,n,s,r);Ai.clearBuffer(),zi.releasePrimitive(Ei),zi.releasePrimitive(Mi),Pi.pop(),Pi.pop();const a=Pi.length;return a>0&&(Mi=Pi[a-1],Ei=Pi[a-2]),o}function Di(t,e,i,n,s=null,r=0,o=0){const{float32Array:a,uint16Array:l,uint32Array:c}=Ai;let h=2*t;if(ei(h,l)){const e=ii(t,c),i=ni(h,l);return Ye(t,a,Ei),n(e,i,!1,o,r+t/8,Ei)}{let h=function(t){const{uint16Array:e,uint32Array:i}=Ai;let n=2*t;for(;!ei(n,e);)n=2*(t=si(t));return ii(t,i)},d=function(t){const{uint16Array:e,uint32Array:i}=Ai;let n=2*t;for(;!ei(n,e);)n=2*(t=ri(t,i));return ii(t,i)+ni(n,e)};const u=si(t),p=ri(t,c);let f,m,g,w,y=u,_=p;if(s&&(g=Ei,w=Mi,Ye(y,a,g),Ye(_,a,w),f=s(g),m=s(w),m<f)){y=p,_=u;const t=f;f=m,m=t,g=w}g||(g=Ei,Ye(y,a,g));const b=i(g,ei(2*y,l),f,o+1,r+y/8);let v;if(2===b){const t=h(y);v=n(t,d(y)-t,!0,o+1,r+y/8,g)}else v=b&&Di(y,e,i,n,s,r,o+1);if(v)return!0;w=Mi,Ye(_,a,w);const x=i(w,ei(2*_,l),m,o+1,r+_/8);let S;if(2===x){const t=h(_);S=n(t,d(_)-t,!0,o+1,r+_/8,w)}else S=x&&Di(_,e,i,n,s,r,o+1);return!!S}}const ki=new Ai.constructor,Bi=new Ai.constructor,Oi=new Ti(()=>new a),Vi=new a,Li=new a,Ni=new a,Fi=new a;let Ri=!1;function Ui(t,e,i,n,s,r=0,o=0,a=0,l=0,c=null,h=!1){let d,u;h?(d=Bi,u=ki):(d=ki,u=Bi);const p=d.float32Array,f=d.uint32Array,m=d.uint16Array,g=u.float32Array,w=u.uint32Array,y=u.uint16Array,_=2*e,b=ei(2*t,m),v=ei(_,y);let x=!1;if(v&&b)x=h?s(ii(e,w),ni(2*e,y),ii(t,f),ni(2*t,m),l,o+e/8,a,r+t/8):s(ii(t,f),ni(2*t,m),ii(e,w),ni(2*e,y),a,r+t/8,l,o+e/8);else if(v){const c=Oi.getPrimitive();Ye(e,g,c),c.applyMatrix4(i);const d=si(t),u=ri(t,f);Ye(d,p,Vi),Ye(u,p,Li);const m=c.intersectsBox(Vi),w=c.intersectsBox(Li);x=m&&Ui(e,d,n,i,s,o,r,l,a+1,c,!h)||w&&Ui(e,u,n,i,s,o,r,l,a+1,c,!h),Oi.releasePrimitive(c)}else{const d=si(e),u=ri(e,w);Ye(d,g,Ni),Ye(u,g,Fi);const m=c.intersectsBox(Ni),y=c.intersectsBox(Fi);if(m&&y)x=Ui(t,d,i,n,s,r,o,a,l+1,c,h)||Ui(t,u,i,n,s,r,o,a,l+1,c,h);else if(m)if(b)x=Ui(t,d,i,n,s,r,o,a,l+1,c,h);else{const e=Oi.getPrimitive();e.copy(Ni).applyMatrix4(i);const c=si(t),u=ri(t,f);Ye(c,p,Vi),Ye(u,p,Li);const m=e.intersectsBox(Vi),g=e.intersectsBox(Li);x=m&&Ui(d,c,n,i,s,o,r,l,a+1,e,!h)||g&&Ui(d,u,n,i,s,o,r,l,a+1,e,!h),Oi.releasePrimitive(e)}else if(y)if(b)x=Ui(t,u,i,n,s,r,o,a,l+1,c,h);else{const e=Oi.getPrimitive();e.copy(Fi).applyMatrix4(i);const c=si(t),d=ri(t,f);Ye(c,p,Vi),Ye(d,p,Li);const m=e.intersectsBox(Vi),g=e.intersectsBox(Li);x=m&&Ui(u,c,n,i,s,o,r,l,a+1,e,!h)||g&&Ui(u,d,n,i,s,o,r,l,a+1,e,!h),Oi.releasePrimitive(e)}}return x}const ji=new a,$i=new Float32Array(6);class Wi{constructor(){this._roots=null,this.primitiveBuffer=null,this.primitiveBufferStride=null}init(t){Si(this,t={...Ze,...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,$i,0);const[t,e,n,h,d,u]=$i;t<s&&(s=t),h>a&&(a=h),e<r&&(r=e),d>l&&(l=d),n<o&&(o=n),u>c&&(c=u)}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,$i,0);const[t,e,r,o,a,l]=$i,c=(t+o)/2,h=(e+a)/2,d=(r+l)/2,u=(o-t)/2,p=(a-e)/2,f=(l-r)/2,m=6*(s-n);i[m+0]=c,i[m+1]=u+(Math.abs(c)+u)*He,i[m+2]=h,i[m+3]=p+(Math.abs(h)+p)*He,i[m+4]=d,i[m+5]=f+(Math.abs(d)+f)*He}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/Ge;for(let e=0;e<o;e++){const i=8*e;ei(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=ei(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=si(r),a=ri(r,n),c=oi(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/Ge-1;t>=0;t--){const e=8*t,i=2*e;if(ei(i,s)){const t=ii(e,n),o=ni(i,s);this.writePrimitiveRangeBounds(t,o,$i,0),r.set($i,e)}else{const t=si(e),i=ri(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=>{Ye(0,new Float32Array(e),ji),t.union(ji)}),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=Ii(this,t,i,n,e,l),a)break;l+=s.byteLength/Ge}return a}bvhcast(t,e,i){let{intersectsRanges:n}=i;return function(t,e,i,n){if(Ri)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");Ri=!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++){ki.setBuffer(s[t]),c=0;const e=Oi.getPrimitive();Ye(ai(0),ki.float32Array,e),e.applyMatrix4(h);for(let t=0,s=r.length;t<s&&(Bi.setBuffer(r[t]),o=Ui(0,0,i,h,n,a,c,0,0,e),Bi.clearBuffer(),c+=r[t].byteLength/Ge,!o);t++);if(Oi.releasePrimitive(e),ki.clearBuffer(),a+=s[t].byteLength/Ge,o)break}return Ri=!1,o}(this,t,e,n)}}function Gi(t){return t.index?t.index.count:t.attributes.position.count}function Hi(t){return Gi(t)/3}function qi(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 Zi(t,e,i){const n=function(t,e,i){const n=Gi(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=Gi(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,d=null;for(const t of c){const e=t.pos;0!==h&&e!==d&&r.push({offset:d,count:e-d}),h+=t.isStart?1:-1,d=e}return r}class Yi extends Wi{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={...Ze,...e})[qe]||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}(Zi(e,t.range,i),t.useSharedArrayBuffer);this._indirectBuffer=n}else qi(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}]:Zi(this.geometry,t,this.primitiveStride)}raycastObject3D(){throw new Error("BVH: raycastObject3D() not implemented")}}class Xi{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}}Xi.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 Ki=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),d=c.dot(a),u=c.dot(c),p=i.dot(a),f=a.dot(a)*u-d*d;let m,g;m=0!==f?(h*d-p*u)/f:0,g=(h+m*d)/u,r.x=m,r.y=g}}(),Qi=function(){const t=new p,e=new h,i=new h;return function(n,s,r,o){Ki(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,d=i;return n.closestPointToPoint(c,!0,e),s.closestPointToPoint(t,!0,i),h.distanceToSquared(c)<=d.distanceToSquared(t)?(r.copy(h),void o.copy(c)):(r.copy(t),void o.copy(d))}}}(),Ji=function(){const t=new h,e=new h,i=new u,n=new d;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 d=r.getPlane(i);if(Math.abs(d.distanceToPoint(a))<=o){const t=d.projectPoint(a,e);if(r.containsPoint(t))return!0}return!1}}(),tn=["x","y","z"],en=1e-15;function nn(t){return Math.abs(t)<en}class sn 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 Xi),this.points=[this.a,this.b,this.c],this.plane=new u,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new d,this.needsUpdate=!0}intersectsSphere(t){return Ji(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],d=r[2];h.subVectors(e,i),d.setFromPoints(h,n);const u=s[3],p=r[3];u.subVectors(i,t),p.setFromPoints(u,n);const f=l.length(),m=h.length(),g=u.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}}sn.prototype.closestPointToSegment=function(){const t=new h,e=new h,i=new d;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]),Qi(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)}}(),sn.prototype.intersectsTriangle=function(){const t=new sn,e=new Xi,i=new Xi,n=new h,s=new h,r=new h,o=new h,a=new d,l=new d,c=new h,u=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 d=s.satBounds,u=s.satAxes;for(let n=1;n<4;n++){const r=d[n],a=u[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 d=o/(o-a);c.x=n+(s-n)*d,h.start.subVectors(e,t).multiplyScalar(d).add(t),d=o/(o-l),c.y=n+(r-n)*d,h.end.subVectors(i,t).multiplyScalar(d).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 nn(o)?nn(a)?m(t,e,i,s):(i&&(i.start.copy(r.start),i.end.copy(r.start)),t.containsPoint(r.start)):nn(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!(!nn(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),d=l.x*c.y-l.y*c.x;if(nn(d))return!1;const u=(h.x*c.y-h.y*c.x)/d,p=-(l.x*h.y-l.y*h.x)/d;return!(u<0||u>1||p<0||p>1)&&(!!nn(o.start.z+l.z*u-(a.start.z+c.z*p))&&(i&&(i.start.copy(o.start).addScaledVector(l,u),i.end.copy(o.start).addScaledVector(l,u)),!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 d=this.plane,p=e.plane;let g=p.distanceToPoint(this.a),v=p.distanceToPoint(this.b),x=p.distanceToPoint(this.c);nn(g)&&(g=0),nn(v)&&(v=0),nn(x)&&(x=0);const S=g*v,T=g*x;if(S>0&&T>0)return!1;let C=d.distanceToPoint(e.a),A=d.distanceToPoint(e.b),E=d.distanceToPoint(e.c);nn(C)&&(C=0),nn(A)&&(A=0),nn(E)&&(E=0);const M=C*A,P=C*E;if(M>0&&P>0)return!1;s.copy(d.normal),r.copy(p.normal);const z=s.cross(r);let I=0,D=Math.abs(z.x);const k=Math.abs(z.y);k>D&&(D=k,I=1);Math.abs(z.z)>D&&(I=2);const B=tn[I],O=this.a[B],V=this.b[B],L=this.c[B],N=e.a[B],F=e.b[B],R=e.c[B];if(w(this,O,V,L,S,T,g,v,x,u,a))return m(this,e,i,o);if(w(e,N,F,R,M,P,C,A,E,f,l))return m(this,e,i,o);if(u.y<u.x){const t=u.y;u.y=u.x,u.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!(u.y<f.x||f.y<u.x)&&(i&&(f.x>u.x?i.start.copy(l.start):i.start.copy(a.start),f.y<u.y?i.end.copy(l.end):i.end.copy(a.end)),!0)}}(),sn.prototype.distanceToPoint=function(){const t=new h;return function(e){return this.closestPointToPoint(e,t),e.distanceTo(t)}}(),sn.prototype.distanceToTriangle=function(){const t=new h,e=new h,i=["a","b","c"],n=new d,s=new d;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],d=i[(l+1)%3];n.set(this[h],this[d]);for(let l=0;l<3;l++){const h=i[l],d=i[(l+1)%3];s.set(r[h],r[d]),Qi(n,s,t,e);const u=t.distanceToSquared(e);u<c&&(c=u,o&&o.copy(t),a&&a.copy(e))}}return Math.sqrt(c)}}();class rn{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 Xi),this.alignedSatBounds=new Array(3).fill().map(()=>new Xi),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}}rn.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}}(),rn.prototype.intersectsBox=function(){const t=new Xi;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}}(),rn.prototype.intersectsTriangle=function(){const t=new sn,e=new Array(3),i=new Xi,n=new Xi,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}}(),rn.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}}(),rn.prototype.distanceToPoint=function(){const t=new h;return function(e){return this.closestPointToPoint(e,t),e.distanceTo(t)}}(),rn.prototype.distanceToBox=function(){const t=["x","y","z"],e=new Array(12).fill().map(()=>new d),i=new Array(12).fill().map(()=>new d),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,d=r.max,u=this.points;let p=1/0;for(let t=0;t<8;t++){const e=u[t];s.copy(e).clamp(h,d);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=u[s<<o|r<<a],p=u[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]:d[g],_[w]=r?h[w]:d[g],b[m]=d[m],b[g]=s?h[g]:d[g],b[w]=r?h[w]:d[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?d.x:h.x,s.y=e?d.y:h.y,s.z=i?d.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];Qi(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 on extends Ti{constructor(){super(()=>new sn)}}const an=new on,ln=new h,cn=new h;const hn=parseInt(w)>=169,dn=parseInt(w)<=161,un=new h,pn=new h,fn=new h,mn=new p,gn=new p,wn=new p,yn=new h,_n=new h,bn=new h,vn=new h;function xn(t,e,i,n,s,r,o,a,l,c,d){un.fromBufferAttribute(e,r),pn.fromBufferAttribute(e,o),fn.fromBufferAttribute(e,a);const u=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,un,pn,fn,vn,l,c,d);if(u){if(n){mn.fromBufferAttribute(n,r),gn.fromBufferAttribute(n,o),wn.fromBufferAttribute(n,a),u.uv=new p;const t=f.getInterpolation(vn,un,pn,fn,mn,gn,wn,u.uv);hn||(u.uv=t)}if(s){mn.fromBufferAttribute(s,r),gn.fromBufferAttribute(s,o),wn.fromBufferAttribute(s,a),u.uv1=new p;const t=f.getInterpolation(vn,un,pn,fn,mn,gn,wn,u.uv1);hn||(u.uv1=t),dn&&(u.uv2=u.uv1)}if(i){yn.fromBufferAttribute(i,r),_n.fromBufferAttribute(i,o),bn.fromBufferAttribute(i,a),u.normal=new h;const e=f.getInterpolation(vn,un,pn,fn,yn,_n,bn,u.normal);u.normal.dot(t.direction)>0&&u.normal.multiplyScalar(-1),hn||(u.normal=e)}const e={a:r,b:o,c:a,normal:new h,materialIndex:0};if(f.getNormal(un,pn,fn,e.normal),u.face=e,u.faceIndex=r,hn){const t=new h;f.getBarycoord(vn,un,pn,fn,t),u.barycoord=t}}return u}function Sn(t){return t&&t.isMaterial?t.side:t}function Tn(t,e,i,n,s,r,o){const a=3*n;let l=a+0,c=a+1,h=a+2;const{index:d,groups:u}=t;t.index&&(l=d.getX(l),c=d.getX(c),h=d.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,d=u.length;a<d;a++){const{start:d,count:w,materialIndex:y}=u[a];if(t>=d&&t<d+w){const t=xn(i,p,f,m,g,l,c,h,Sn(e[y]),r,o);if(t){if(t.faceIndex=n,t.face.materialIndex=y,!s)return t;s.push(t)}}}}else{const t=xn(i,p,f,m,g,l,c,h,Sn(e),r,o);if(t){if(t.faceIndex=n,t.face.materialIndex=0,!s)return t;s.push(t)}}return null}function Cn(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 An(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,Cn(o,3*t,l,c),o.needsUpdate=!0,n(o,t,s,r))return!0}return!1}function En(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),d(0,c),c+=r.byteLength;function d(t,i,r=!1){const c=2*t;if(ei(c,a)){const e=ii(t,o);let i=1/0,r=1/0,h=1/0,d=-1/0,u=-1/0,p=-1/0;for(let t=3*e,o=3*(e+ni(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>d&&(d=o),a<r&&(r=a),a>u&&(u=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]!==d||l[t+4]!==u||l[t+5]!==p)&&(l[t+0]=i,l[t+1]=r,l[t+2]=h,l[t+3]=d,l[t+4]=u,l[t+5]=p,!0)}{const n=si(t),s=ri(t,o);let a=r,c=!1,h=!1;if(e){if(!a){const t=n/8+i/Ge,r=s/8+i/Ge;c=e.has(t),h=e.has(r),a=!c&&!h}}else c=!0,h=!0;const u=a||h;let p=!1;(a||c)&&(p=d(n,i,a));let f=!1;u&&(f=d(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 Mn(t,e,i,n,s){let r,o,a,l,c,h;const d=1/i.direction.x,u=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 d>=0?(r=(w-f)*d,o=(y-f)*d):(r=(y-f)*d,o=(w-f)*d),u>=0?(a=(_-m)*u,l=(b-m)*u):(a=(b-m)*u,l=(_-m)*u),!(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 Pn(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),Cn(o,3*t,l,c),o.needsUpdate=!0,n(o,t,s,r))return!0}return!1}function zn(t,e,i,n,s,r,o){Ai.setBuffer(t._roots[e]),In(0,t,i,n,s,r,o),Ai.clearBuffer()}function In(t,e,i,n,s,r,o){const{float32Array:a,uint16Array:l,uint32Array:c}=Ai,h=2*t;if(ei(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++)Tn(l,e,i,t,r,o,a)}(e,i,n,ii(t,c),ni(h,l),s,r,o)}else{const l=si(t);Mn(l,a,n,r,o)&&In(l,e,i,n,s,r,o);const h=ri(t,c);Mn(h,a,n,r,o)&&In(h,e,i,n,s,r,o)}}const Dn=["x","y","z"];function kn(t,e,i,n,s,r){Ai.setBuffer(t._roots[e]);const o=Bn(0,t,i,n,s,r);return Ai.clearBuffer(),o}function Bn(t,e,i,n,s,r){const{float32Array:o,uint16Array:a,uint32Array:l}=Ai;let c=2*t;if(ei(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=Tn(a,e,i,t,null,r,o),n&&n.distance<c&&(h=n,c=n.distance)}return h}(e,i,n,ii(t,l),ni(c,a),s,r)}{const a=oi(t,l),c=Dn[a],h=n.direction[c]>=0;let d,u;h?(d=si(t),u=ri(t,l)):(d=ri(t,l),u=si(t));const p=Mn(d,o,n,s,r)?Bn(d,e,i,n,s,r):null;if(p){const t=p.point[c];if(h?t<=o[u+a]:t>=o[u+a+3])return p}const f=Mn(u,o,n,s,r)?Bn(u,e,i,n,s,r):null;return p&&f?p.distance<=f.distance?p:f:p||f||null}}const On=new a,Vn=new sn,Ln=new sn,Nn=new l,Fn=new rn,Rn=new rn;function Un(t,e,i,n){Ai.setBuffer(t._roots[e]);const s=jn(0,t,i,n);return Ai.clearBuffer(),s}function jn(t,e,i,n,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=Ai;let l=2*t;null===s&&(i.boundingBox||i.computeBoundingBox(),Fn.set(i.boundingBox.min,i.boundingBox.max,n),s=Fn);if(!ei(l,o)){const o=si(t),l=ri(t,a);Ye(o,r,On);if(s.intersectsBox(On)&&jn(o,e,i,n,s))return!0;Ye(l,r,On);return!!(s.intersectsBox(On)&&jn(l,e,i,n,s))}{const s=e.geometry,c=s.index,h=s.attributes.position,d=i.index,u=i.attributes.position,p=ii(t,a),f=ni(l,o);if(Nn.copy(n).invert(),i.boundsTree){Ye(t,r,Rn),Rn.matrix.copy(Nn),Rn.needsUpdate=!0;return i.boundsTree.shapecast({intersectsBounds:t=>Rn.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(Cn(Ln,e,c,h),Ln.needsUpdate=!0,t.intersectsTriangle(Ln))return!0;return!1}})}{const t=Hi(i);for(let e=3*p,i=3*(f+p);e<i;e+=3){Cn(Vn,e,c,h),Vn.a.applyMatrix4(Nn),Vn.b.applyMatrix4(Nn),Vn.c.applyMatrix4(Nn),Vn.needsUpdate=!0;for(let e=0,i=3*t;e<i;e+=3)if(Cn(Ln,e,d,u),Ln.needsUpdate=!0,Vn.intersectsTriangle(Ln))return!0}}}}const $n=new l,Wn=new rn,Gn=new rn,Hn=new h,qn=new h,Zn=new h,Yn=new h;function Xn(t,e,i,n={},s={},r=0,o=1/0){e.boundingBox||e.computeBoundingBox(),Wn.set(e.boundingBox.min,e.boundingBox.max,i),Wn.needsUpdate=!0;const a=t.geometry,l=a.attributes.position,c=a.index,h=e.attributes.position,d=e.index,u=an.getPrimitive(),p=an.getPrimitive();let f=Hn,m=qn,g=null,w=null;s&&(g=Zn,w=Yn);let y=1/0,_=null,b=null;return $n.copy(i).invert(),Gn.matrix.copy($n),t.shapecast({boundsTraverseOrder:t=>Wn.distanceToBox(t),intersectsBounds:(t,e,i)=>i<y&&i<o&&(e&&(Gn.min.copy(t.min),Gn.max.copy(t.max),Gn.needsUpdate=!0),!0),intersectsRange:(t,n)=>{if(e.boundsTree){return e.boundsTree.shapecast({boundsTraverseOrder:t=>Gn.distanceToBox(t),intersectsBounds:(t,e,i)=>i<y&&i<o,intersectsRange:(e,s)=>{for(let o=e,a=e+s;o<a;o++){Cn(p,3*o,d,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++){Cn(u,3*e,c,l),u.needsUpdate=!0;const t=u.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=Hi(e);s<o;s++){Cn(p,3*s,d,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++){Cn(u,3*e,c,l),u.needsUpdate=!0;const t=u.distanceToTriangle(p,f,g);if(t<y&&(m.copy(f),w&&w.copy(g),y=t,_=e,b=s),t<r)return!0}}}}),an.releasePrimitive(u),an.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($n),m.applyMatrix4($n),s.distance=m.sub(s.point).length(),s.faceIndex=b),n)}function Kn(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),d(0,c),c+=r.byteLength;function d(i,r,c=!1){const h=2*i;if(ei(h,a)){const e=ii(i,o);let r=1/0,c=1/0,d=1/0,u=-1/0,p=-1/0,f=-1/0;for(let i=e,o=e+ni(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>u&&(u=o),a<c&&(c=a),a>p&&(p=a),l<d&&(d=l),l>f&&(f=l)}}return(l[i+0]!==r||l[i+1]!==c||l[i+2]!==d||l[i+3]!==u||l[i+4]!==p||l[i+5]!==f)&&(l[i+0]=r,l[i+1]=c,l[i+2]=d,l[i+3]=u,l[i+4]=p,l[i+5]=f,!0)}{const t=si(i),n=ri(i,o);let s=c,a=!1,h=!1;if(e){if(!s){const i=t/8+r/Ge,o=n/8+r/Ge;a=e.has(i),h=e.has(o),s=!a&&!h}}else a=!0,h=!0;const u=s||h;let p=!1;(s||a)&&(p=d(t,r,s));let f=!1;u&&(f=d(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 Qn(t,e,i,n,s,r,o){Ai.setBuffer(t._roots[e]),Jn(0,t,i,n,s,r,o),Ai.clearBuffer()}function Jn(t,e,i,n,s,r,o){const{float32Array:a,uint16Array:l,uint32Array:c}=Ai,h=2*t;if(ei(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++)Tn(l,e,i,c?c[t]:t,r,o,a)}(e,i,n,ii(t,c),ni(h,l),s,r,o)}else{const l=si(t);Mn(l,a,n,r,o)&&Jn(l,e,i,n,s,r,o);const h=ri(t,c);Mn(h,a,n,r,o)&&Jn(h,e,i,n,s,r,o)}}const ts=["x","y","z"];function es(t,e,i,n,s,r){Ai.setBuffer(t._roots[e]);const o=is(0,t,i,n,s,r);return Ai.clearBuffer(),o}function is(t,e,i,n,s,r){const{float32Array:o,uint16Array:a,uint32Array:l}=Ai;let c=2*t;if(ei(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,d=n+s;t<d;t++){let n;n=Tn(a,e,i,l?l[t]:t,null,r,o),n&&n.distance<c&&(h=n,c=n.distance)}return h}(e,i,n,ii(t,l),ni(c,a),s,r)}{const a=oi(t,l),c=ts[a],h=n.direction[c]>=0;let d,u;h?(d=si(t),u=ri(t,l)):(d=ri(t,l),u=si(t));const p=Mn(d,o,n,s,r)?is(d,e,i,n,s,r):null;if(p){const t=p.point[c];if(h?t<=o[u+a]:t>=o[u+a+3])return p}const f=Mn(u,o,n,s,r)?is(u,e,i,n,s,r):null;return p&&f?p.distance<=f.distance?p:f:p||f||null}}const ns=new a,ss=new sn,rs=new sn,os=new l,as=new rn,ls=new rn;function cs(t,e,i,n){Ai.setBuffer(t._roots[e]);const s=hs(0,t,i,n);return Ai.clearBuffer(),s}function hs(t,e,i,n,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=Ai;let l=2*t;null===s&&(i.boundingBox||i.computeBoundingBox(),as.set(i.boundingBox.min,i.boundingBox.max,n),s=as);if(!ei(l,o)){const o=si(t),l=ri(t,a);Ye(o,r,ns);if(s.intersectsBox(ns)&&hs(o,e,i,n,s))return!0;Ye(l,r,ns);return!!(s.intersectsBox(ns)&&hs(l,e,i,n,s))}{const s=e.geometry,c=s.index,h=s.attributes.position,d=i.index,u=i.attributes.position,p=ii(t,a),f=ni(l,o);if(os.copy(n).invert(),i.boundsTree){Ye(t,r,ls),ls.matrix.copy(os),ls.needsUpdate=!0;return i.boundsTree.shapecast({intersectsBounds:t=>ls.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(Cn(rs,3*e.resolveTriangleIndex(i),c,h),rs.needsUpdate=!0,t.intersectsTriangle(rs))return!0;return!1}})}{const t=Hi(i);for(let i=p,n=f+p;i<n;i++){const n=e.resolveTriangleIndex(i);Cn(ss,3*n,c,h),ss.a.applyMatrix4(os),ss.b.applyMatrix4(os),ss.c.applyMatrix4(os),ss.needsUpdate=!0;for(let e=0,i=3*t;e<i;e+=3)if(Cn(rs,e,d,u),rs.needsUpdate=!0,ss.intersectsTriangle(rs))return!0}}}}const ds=new l,us=new rn,ps=new rn,fs=new h,ms=new h,gs=new h,ws=new h;function ys(t,e,i,n={},s={},r=0,o=1/0){e.boundingBox||e.computeBoundingBox(),us.set(e.boundingBox.min,e.boundingBox.max,i),us.needsUpdate=!0;const a=t.geometry,l=a.attributes.position,c=a.index,h=e.attributes.position,d=e.index,u=an.getPrimitive(),p=an.getPrimitive();let f=fs,m=ms,g=null,w=null;s&&(g=gs,w=ws);let y=1/0,_=null,b=null;return ds.copy(i).invert(),ps.matrix.copy(ds),t.shapecast({boundsTraverseOrder:t=>us.distanceToBox(t),intersectsBounds:(t,e,i)=>i<y&&i<o&&(e&&(ps.min.copy(t.min),ps.max.copy(t.max),ps.needsUpdate=!0),!0),intersectsRange:(n,s)=>{if(e.boundsTree){const a=e.boundsTree;return a.shapecast({boundsTraverseOrder:t=>ps.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);Cn(p,3*e,d,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);Cn(u,3*i,c,l),u.needsUpdate=!0;const n=u.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=Hi(e);o<a;o++){Cn(p,3*o,d,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);Cn(u,3*i,c,l),u.needsUpdate=!0;const n=u.distanceToTriangle(p,f,g);if(n<y&&(m.copy(f),w&&w.copy(g),y=n,_=e,b=o),n<r)return!0}}}}),an.releasePrimitive(u),an.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 _s(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 bs=new rn,vs=new y,xs=new h,Ss=new l,Ts=new h,Cs=["getX","getY","getZ"];class As extends Yi{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/Ge;t<e;t++){const e=8*t;ei(2*e,s)||(n[e+6]=n[e+6]/8-t)}}}(s));const o=new As(e,{...i,[qe]:!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[Cs[t]](l),s=r[Cs[t]](c),o=r[Cs[t]](h);let a=n;s<a&&(a=s),o<a&&(a=o);let d=n;s>d&&(d=s),o>d&&(d=o),e[i+t]=a,e[i+t+3]=d}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 d=["getX","getY","getZ"],u=i.offset;for(let n=t,p=t+e;n<p;n++){const t=3*(s?s[n]:n),e=6*(n-u);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[d[t]](p),s=r[d[t]](f),o=r[d[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 u=(h-c)/2,g=2*t;i[e+g+0]=c+u,i[e+g+1]=u+(Math.abs(c)+u)*He}}return i}raycastObject3D(t,e,i=[]){const{material:n}=t;if(void 0===n)return;Ss.copy(t.matrixWorld).invert(),vs.copy(e.ray).applyMatrix4(Ss),Ts.setFromMatrixScale(t.matrixWorld),xs.copy(vs.direction).multiply(Ts);const s=xs.length(),r=e.near/s,o=e.far/s;if(!0===e.firstHitOnly){let s=this.raycastFirst(vs,n,r,o);s=_s(s,t,e),s&&i.push(s)}else{const s=this.raycast(vs,n,r,o);for(let n=0,r=s.length;n<r;n++){const r=_s(s[n],t,e);r&&i.push(r)}}return i}refit(t=null){return(this.indirect?Kn:En)(this,t)}raycast(t,e=_,i=0,n=1/0){const s=this._roots,r=[],o=this.indirect?Qn:zn;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?es:kn;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?cs:Un;for(let r=0,o=n.length;r<o&&(i=s(this,r,t,e),!i);r++);return i}shapecast(t){const e=an.getPrimitive(),i=super.shapecast({...t,intersectsPrimitive:t.intersectsTriangle,scratchPrimitive:e,iterate:this.indirect?Pn:An});return an.releasePrimitive(e),i}bvhcast(t,e,i){let{intersectsRanges:n,intersectsTriangles:s}=i;const r=an.getPrimitive(),o=this.geometry.index,a=this.geometry.attributes.position,l=this.indirect?t=>{const e=this.resolveTriangleIndex(t);Cn(r,3*e,o,a)}:t=>{Cn(r,3*t,o,a)},c=an.getPrimitive(),h=t.geometry.index,d=t.geometry.attributes.position,u=t.indirect?e=>{const i=t.resolveTriangleIndex(e);Cn(c,3*i,h,d)}:t=>{Cn(c,3*t,h,d)};if(s){if(!(t instanceof As))throw new Error('MeshBVH: "intersectsTriangles" callback can only be used with another MeshBVH.');const i=(t,i,n,o,a,h,d,p)=>{for(let f=n,m=n+o;f<m;f++){u(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,d,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 bs.set(t.min,t.max,e),bs.needsUpdate=!0,this.shapecast({intersectsBounds:t=>bs.intersectsBox(t),intersectsTriangle:t=>bs.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?ys:Xn)(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=>(ln.copy(e).clamp(t.min,t.max),ln.distanceToSquared(e)),intersectsBounds:(t,e,i)=>i<a&&i<o,intersectsTriangle:(t,i)=>{t.closestPointToPoint(e,ln);const n=e.distanceToSquared(ln);return n<a&&(cn.copy(ln),a=n,l=i),n<r}}),a===1/0)return null;const c=Math.sqrt(a);return i.point?i.point.copy(cn):i.point=cn.clone(),i.distance=c,i.faceIndex=l,i}(this,t,e,i,n)}}const Es=new l,Ms=new y,Ps=new Ti(()=>new d),zs=new h,Is=new h,Ds=new a,ks=["getX","getY","getZ"];class Bs extends Yi{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[ks[t]](c),s=o[ks[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=Ps.getPrimitive(),i=super.shapecast({...t,intersectsPrimitive:t.intersectsLine,scratchPrimitive:e,iterate:Os});return Ps.releasePrimitive(e),i}raycastObject3D(t,e,i=[]){const{matrixWorld:n}=t,{firstHitOnly:s}=e;Es.copy(n).invert(),Ms.copy(e.ray).applyMatrix4(Es);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(Ms.origin),intersectsBounds:t=>(Ds.copy(t).expandByScalar(Math.abs(r)),Ms.intersectsBox(Ds)?1:0),intersectsLine:(r,c)=>{if(Ms.distanceSqToSegment(r.start,r.end,zs,Is)>o)return;zs.applyMatrix4(t.matrixWorld);const h=e.ray.origin.distanceTo(zs);h<e.near||h>e.far||s&&h>=l||(l=h,c=this.resolvePrimitiveIndex(c),a={distance:h,point:Is.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 Os(t,e,i,n,s,r,o){const{geometry:a,primitiveStride:l}=i,{index:c}=a,h=a.attributes.position,d=c?c.count:h.count;for(let a=t,u=e+t;a<u;a++){let t=i.resolvePrimitiveIndex(a)*l,e=(t+1)%d;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 Vs={Mesh:b.prototype.raycast,Line:S.prototype.raycast,LineSegments:v.prototype.raycast,LineLoop:x.prototype.raycast,Points:T.prototype.raycast,BatchedMesh:A.prototype.raycast},Ls=new b,Ns=[];function Fs(t,e){if(this.isBatchedMesh)Rs.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=Vs.Mesh;else if(this instanceof v)i=Vs.LineSegments;else if(this instanceof x)i=Vs.LineLoop;else if(this instanceof S)i=Vs.Line;else{if(!(this instanceof T))throw new Error("BVH: Fallback raycast function not found.");i=Vs.Points}i.call(this,t,e)}}}function Rs(t,e){if(this.boundsTrees){const i=this.boundsTrees,n=this._drawInfo||this._instanceInfo,s=this._drawRanges||this._geometryInfo,r=this.matrixWorld;Ls.material=this.material,Ls.geometry=this.geometry;const o=Ls.geometry.boundsTree,a=Ls.geometry.drawRange;null===Ls.geometry.boundingSphere&&(Ls.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(Ls.geometry.boundsTree=i[a],this.getMatrixAt(o,Ls.matrixWorld).premultiply(r),!Ls.geometry.boundsTree){this.getBoundingBoxAt(a,Ls.geometry.boundingBox),this.getBoundingSphereAt(a,Ls.geometry.boundingSphere);const t=s[a];Ls.geometry.setDrawRange(t.start,t.count)}Ls.raycast(t,Ns);for(let t=0,i=Ns.length;t<i;t++){const i=Ns[t];i.object=this,i.batchId=o,e.push(i)}Ns.length=0}Ls.geometry.boundsTree=o,Ls.geometry.drawRange=a,Ls.material=null,Ls.geometry=null}else Vs.BatchedMesh.call(this,t,e)}function Us(t={}){const{type:e=As}=t;return this.boundsTree=new e(this,t),this.boundsTree}function js(){this.boundsTree=null}const $s=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($s,"uuid","fef46874-46a3-461b-8c44-2922ab77c806");let Ws=$s;function Gs(t,e){return t[e]|t[e+1]<<8|t[e+2]<<16}class Hs{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 E,r=new a,o=new M(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),d=Math.ceil(n.z/i),u=Math.ceil(c/l),p=Math.ceil(d/l);o.setSize(Math.ceil(c/u),Math.ceil(d/p)),s.rotation.x=-Math.PI/2,s.far=r.max.y-r.min.y+s.near,s.position.y=r.max.y+s.near;const f=new P,m=new Map,g=new Map,w=[];for(let e=0;e<t.length;e++){const i=t[e];m.set(i,i.material),g.set(i,i.parent);const n=new qs;n.objectId=e,w.push(n),i.material=n,f.add(i)}const y=e.getClearColor(new z),_=e.getClearAlpha(),b=e.getRenderTarget(),v=e.autoClear;e.autoClear=!0,e.setClearColor(0,0),e.setRenderTarget(o);const x=new Uint8Array(o.width*o.height*4),S=new Set,T=n.x/u,C=n.z/p;for(let i=0;i<u;i++)for(let n=0;n<p;n++){const a=r.min.x+T*i,l=a+T,c=r.min.z+C*n,h=(a+l)/2,d=(c+(c+C))/2;s.position.set(h,r.max.y,d);const u=T/2,p=C/2;s.left=-u,s.right=u,s.top=p,s.bottom=-p,s.updateProjectionMatrix(),e.render(f,s);const m=await e.readRenderTargetPixelsAsync(o,0,0,o.width,o.height,x);for(let e=0,i=m.length;e<i;e+=4){if(0===m[e+3])continue;const i=Gs(m,e);S.add(t[i])}}for(const e of t){e.material=m.get(e);const t=g.get(e);t?t.add(e):f.remove(e)}e.setClearColor(y,_),e.setRenderTarget(b),e.autoClear=v;for(const t of w)t.dispose();return o.dispose(),Array.from(S)}}class qs extends I{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,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 Zs=1e-16,Ys=new h(0,1,0),Xs=new h;function Ks(t){return t.delta(Xs).normalize(),Math.abs(Xs.dot(Ys))>=1-Zs}function Qs(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)<=Zs&&(r=!0),!o&&n.distanceToSquared(e)<=Zs&&(o=!0),r&&o)return!0}return r&&o}const Js=new d;function tr(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;Js.start.lerpVectors(i,r,s[e][0]),Js.end.lerpVectors(i,r,s[e][1]),n.push(new Float32Array([Js.start.x,Js.start.y,Js.start.z,Js.end.x,Js.end.y,Js.end.z]))}return n}const er=new h(0,1,0),ir=new h,nr=new h,sr=new h,rr=new f;function*or(t,e=[],i={}){const{projectionDirection:n=er,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,u=[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?(u[0]=l.getX(t),u[1]=l.getX(t+1),u[2]=l.getX(t+2)):(u[0]=t,u[1]=t+1,u[2]=t+2);const{a:i,b:s,c:h}=rr;if(i.fromBufferAttribute(c,u[0]),s.fromBufferAttribute(c,u[1]),h.fromBufferAttribute(c,u[2]),rr.getNormal(sr),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=rr[p[t]],l=rr[p[i]],c=`${s}_${r}`,h=`${r}_${s}`;if(h in m&&m[h]){const t=m[h].normal,i=sr.dot(t)<=a;let s=!1;if(null!==n){let e=n.dot(sr);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 d;t.start.copy(o),t.end.copy(l),e.push(t)}m[h]=null}else c in m||(m[c]={index0:u[t],index1:u[i],normal:sr.clone()})}}for(const t in m)if(m[t]){const{index0:i,index1:n}=m[t];ir.fromBufferAttribute(c,i),nr.fromBufferAttribute(c,n);const s=new d;s.start.copy(ir),s.end.copy(nr),e.push(s)}return e}const ar=new d;function lr(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++){cr(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,ar,!0)||Qs(t,ar)||Qs(e,ar)||n.push(ar.clone())))}),n}function cr(t,e){return t.distanceTo(e)<1e-10}function hr(t){dr(t);let e=[];return t.traverse(t=>{t.geometry&&t.visible&&e.push(t)}),e}const dr=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):dr(i)},ur=new l,pr=new l;class fr{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=hr(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&&(pr.copy(c.matrixWorld).invert(),a.copy(n).transformDirection(pr).normalize());const h=yield*or(c.geometry,[],{projectionDirection:a,thresholdAngle:s,iterationTime:r});mr(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*or(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=hr(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 As(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),d=r.get(c.geometry);ur.copy(l.matrixWorld).invert().multiply(c.matrixWorld);const u=lr(h,d,ur,[]);mr(u,l.matrixWorld);for(let t=0;t<u.length;t++)e.push(u[t]);if(null!==i)for(let t=0;t<u.length;t++)i.push(l)}return e}{let i;return t.isBufferGeometry?i=t.boundsTree||new As(t,{maxLeafSize:1}):(i=t,t=i.geometry),ur.identity(),lr(i,i,ur,e)}}}function mr(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 gr extends Wi{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 wr=new h(0,1,0),yr=new u,_r=new h,br=new h;function vr(t,e,i){t.needsUpdate&&t.update(),yr.copy(t.plane),yr.normal.dot(wr)<0&&(yr.normal.multiplyScalar(-1),yr.constant*=-1);const n=yr.distanceToPoint(e.start),s=yr.distanceToPoint(e.end),r=Math.abs(n)<1e-16,o=n<0,a=s<0;if(e.delta(br).normalize(),Math.abs(yr.normal.dot(br))<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,_r),o)return i.start.copy(e.start),i.end.copy(_r),!0;if(a)return i.end.copy(e.end),i.start.copy(_r),!0}return!1}const xr=new u,Sr=new h,Tr=new h,Cr=new sn,Ar=new d,Er=new d,Mr=new h,Pr=new h,zr=new h;function Ir(t,e,i=new d){if(Cr.copy(e),Cr.a.y=0,Cr.b.y=0,Cr.c.y=0,Cr.update(),Ar.copy(t),Ar.start.y=0,Ar.end.y=0,Cr.getArea()<=1e-16)return null;const n=Ar.distance();Ar.delta(Mr).divideScalar(n),Pr.copy(Mr).cross(Cr.plane.normal).normalize(),xr.setFromNormalAndCoplanarPoint(Pr,Ar.start);let s=0;const{points:r}=Cr;for(let t=0;t<3;t++){const e=r[t],i=r[(t+1)%3],n=xr.distanceToPoint(e),o=xr.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);Sr.lerpVectors(e,i,t),c=!0}if((c&&!l||a)&&(a&&!c&&Sr.copy(e),0===s?Er.start.copy(Sr):Er.end.copy(Sr),s++,2===s))break}if(2===s){if(Er.delta(zr).normalize(),Mr.dot(zr)<0){const t=Er.start;Er.start=Er.end,Er.end=t}const e=0,s=Tr.subVectors(Ar.end,Ar.start).dot(Mr),r=Tr.subVectors(Er.start,Ar.start).dot(Mr),o=Tr.subVectors(Er.end,Ar.start).dot(Mr);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 Dr=new h,kr=new h,Br=new h;function Or(t,e,i){const n=function(t,e){t.delta(Dr),kr.subVectors(e.start,t.start),Br.subVectors(e.end,t.start);const i=Dr.length();let n=kr.length()/i,s=Br.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&&(Vr(n,i),!0)}function Vr(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 Lr=new h(0,1,0),Nr=new d,Fr=new d,Rr=new sn;function Ur(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 d=i,u=a+i;d<u;d++){let i=3*d+0,a=3*d+1,u=3*d+2;r.index&&(i=r.index.getX(i),a=r.index.getX(a),u=r.index.getX(u));const{a:p,b:f,c:w}=Rr;if(p.fromBufferAttribute(r.attributes.position,i).applyMatrix4(o),f.fromBufferAttribute(r.attributes.position,a).applyMatrix4(o),w.fromBufferAttribute(r.attributes.position,u).applyMatrix4(o),Rr.needsUpdate=!0,Rr.update(),l!==g){if(Rr.plane.normal.dot(Lr)!==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=Rr.plane.normal;let v=b.x,x=b.y,S=b.z,T=Rr.plane.constant;x<0&&(v=-v,x=-x,S=-S,T=-T);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,d=p.z-t.start.z,u=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+d*n,b=u*i+m*n,v=g*i+y*n,x=1/e,S=Math.min(_,b,v);if(Math.max(_,b,v)<0||S>x){s&&s.xzBoundsCulled++;continue}const T=h*r+d*c,C=u*r+m*c,A=g*r+y*c,E=Math.min(T,C,A),M=Math.max(T,C,A);if(E>0||M<0){s&&s.xzBoundsCulled++;continue}}const c=v*t.start.x+x*t.start.y+S*t.start.z+T,d=v*t.end.x+x*t.end.y+S*t.end.z+T;if(c>=0&&d>=0)s&&s.planeTrimCulled++;else if(Qs(Rr,t))s&&s.triangleEdgeCulled++;else{if(r<_)Nr.copy(t);else if(!vr(Rr,t,Nr)){s&&s.planeTrimCulled++;continue}Nr.distance()<1e-10?s&&s.distThresholdCulled++:Ir(Nr,Rr,Fr)?(s&&s.used++,Or(t,Fr,n[i])):s&&s.noOverlapCulled++}}}}})}Rr.update=()=>{Rr.plane.setFromCoplanarPoints(...Rr.points)};let jr=!1;const $r={},Wr={};let Gr=null,Hr=0,qr=0;const Zr={get enabled(){return jr},set enabled(t){jr=t},reset(){for(const t in $r)delete $r[t];for(const t in Wr)delete Wr[t];Gr=null,Hr=0,qr=0},setStat(t,e){Wr[t]=e},startTotal(){jr&&(qr=performance.now())},startStep(t){jr&&(null!==Gr&&this.endStep(),Gr=t,Hr=performance.now())},endStep(){if(!jr||null===Gr)return;const t=performance.now()-Hr;$r[Gr]=t,Gr=null},printSummary(){if(!jr)return;null!==Gr&&this.endStep();const t=performance.now()-qr;console.log("\n=== Projection Summary ==="),console.log(`Total time: ${t.toFixed(1)}ms\n`);for(const[e,i]of Object.entries($r)){const n=(i/t*100).toFixed(1);console.log(` ${e}: ${i.toFixed(1)}ms (${n}%)`)}if(Object.keys(Wr).length>0){console.log("\n--- Stats ---");for(const[t,e]of Object.entries(Wr))console.log(` ${t}: ${e}`)}console.log("")}},Yr=1e-5,Xr=1e-16,Kr=1e-16;function Qr(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 Jr=null;async function to(t,e,i,n,s=null){const r=await async function(){return null===Jr&&(Jr=new L.WebGPURenderer,await Jr.init()),Jr}();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=N(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");Zr.enabled&&console.log("Number of meshes:",e.length),Zr.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}}Zr.enabled&&console.log(`Split ${e.length} meshes into ${a.length} batches`);let l=0,c=0,h=0,d=0,u=0;for(let i=0;i<a.length;i++){const{start:p,end:f}=a[i],m=f-p;Zr.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,S=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]+S;x+=s.length,S+=i.attributes.position.count}const T=new Float32Array(16*m);for(let t=p;t<f;t++){const i=t-p;T.set(e[t].matrixWorld.elements,16*i)}const C=[];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];C.push({edgeOffset:t.edgeOffsets[e],edgeCount:t.edgeCounts[e],triOffset:s,triCount:t.meshCounts[e],meshIdx:n})}}if(0===C.length){Zr.enabled&&console.log(` Batch ${i+1}: no groups, skipping`);continue}const A=new Uint32Array(5*C.length);for(let t=0;t<C.length;t++){const e=C[t],i=5*t;A[i+0]=e.edgeOffset,A[i+1]=e.edgeCount,A[i+2]=e.triOffset,A[i+3]=e.triCount,A[i+4]=e.meshIdx}let E=0;for(let t=0;t<C.length;t++)E+=C[t].edgeCount*C[t].triCount;s&&(s.candidates+=E);let M=Math.min(Math.ceil(.1*E),2e6),P=Math.max(M,1e4);Zr.enabled&&console.log(` Batch ${i+1}: ${C.length} groups, ${g/3} vertices, ${w/3} triangles, ${E} pairs, buffer for ${P} overlaps`);const z=performance.now(),I=N(_,"float"),D=N(b,"uint"),k=N(T,"float"),B=N(A,"uint");let O=N(new Uint32Array([0]),"uint").toAtomic(),V=N(new Float32Array(3*P),"float");d+=performance.now()-z;const L=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(I.element(r.mul(3)),I.element(r.mul(3).add(1)),I.element(r.mul(3).add(2))),d=W(I.element(l.mul(3)),I.element(l.mul(3).add(1)),I.element(l.mul(3).add(2))),u=W(I.element(c.mul(3)),I.element(c.mul(3).add(1)),I.element(c.mul(3).add(2))),p=a.mul(G(h,H(1))).xyz,f=a.mul(G(d,H(1))).xyz,m=a.mul(G(u,H(1))).xyz,g=f.sub(p),w=m.sub(p),y=q(g,w),_=y.dot(y);Z(_.lessThan(H(4e-16*Xr)),()=>{Y()}),Z(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);Z(b.lessThanEqual(a),()=>{Y()});const l=Q(y),c=l.dot(p).negate(),h=l.y.lessThan(0),d=J(h,l.negate(),l),u=J(h,c.negate(),c),g=d.dot(s).add(u),w=d.dot(r).add(u),_=g.lessThan(0),v=w.lessThan(0),x=tt(g).lessThan(H(Yr)),S=_.not().and(v.not()),T=w.sub(g),C=tt(T).lessThan(H(Yr)),A=C.and(x.or(_.not()));Z(A,()=>{Y()}),Z(S.and(C.not()),()=>{Y()});const E=g.negate().div(T),M=et(s,r,E),z=W(J(C.or(_),s.x,M.x),J(C.or(_),s.y,M.y),J(C.or(_),s.z,M.z)),I=W(J(C.or(v),r.x,M.x),J(C.or(v),r.y,M.y),J(C.or(v),r.z,M.z)),D=I.sub(z),k=D.dot(D);Z(k.lessThan(H(Yr)),()=>{Y()});const B=s.sub(p),L=s.sub(f),N=s.sub(m),F=r.sub(p),R=r.sub(f),U=r.sub(m),j=B.dot(B).lessThanEqual(H(Yr)),$=L.dot(L).lessThanEqual(H(Yr)),G=N.dot(N).lessThanEqual(H(Yr)),st=F.dot(F).lessThanEqual(H(Yr)),rt=R.dot(R).lessThanEqual(H(Yr)),ot=U.dot(U).lessThanEqual(H(Yr)),at=j.or($).or(G),lt=st.or(rt).or(ot),ct=at.and(lt);Z(ct,()=>{Y()});const ht=W(p.x,H(0),p.z),dt=W(f.x,H(0),f.z),ut=W(m.x,H(0),m.z),pt=W(z.x,H(0),z.z),ft=W(I.x,H(0),I.z),mt=W(s.x,H(0),s.z),gt=W(r.x,H(0),r.z).sub(mt),wt=gt.dot(gt);Z(wt.lessThan(H(Yr)),()=>{Y()});const yt=wt.sqrt(),_t=dt.sub(ht),bt=ut.sub(ht),vt=q(_t,bt),xt=vt.dot(vt);Z(xt.lessThanEqual(H(4e-16*Xr)),()=>{Y()});const St=ft.sub(pt),Tt=St.dot(St);Z(Tt.lessThan(H(Yr)),()=>{Y()});const Ct=Tt.sqrt(),At=St.div(Ct),Et=gt.div(yt),Mt=Q(vt),Pt=q(At,Mt),zt=H(0).toVar(),It=H(0).toVar(),Dt=H(0).toVar(),kt=H(0).toVar(),Bt=it(0).toVar(),Ot=Pt.dot(ht.sub(pt)),Vt=Pt.dot(dt.sub(pt)),Lt=tt(Ot).lessThan(H(Kr)),Nt=tt(Vt).lessThan(H(Kr)),Ft=Lt.not().and(Nt.not()).and(Ot.mul(Vt).lessThan(0));Z(Ft,()=>{const t=Ot.div(Ot.sub(Vt)),e=et(ht.x,dt.x,t),i=et(ht.z,dt.z,t);Z(Bt.equal(0),()=>{zt.assign(e),It.assign(i)}).Else(()=>{Dt.assign(e),kt.assign(i)}),Bt.addAssign(1)}).ElseIf(Lt,()=>{Z(Bt.equal(0),()=>{zt.assign(ht.x),It.assign(ht.z)}).Else(()=>{Dt.assign(ht.x),kt.assign(ht.z)}),Bt.addAssign(1)});const Rt=Vt,Ut=Pt.dot(ut.sub(pt)),jt=Nt,$t=tt(Ut).lessThan(H(Kr)),Wt=jt.not().and($t.not()).and(Rt.mul(Ut).lessThan(0));Z(Bt.lessThan(2),()=>{Z(Wt,()=>{const t=Rt.div(Rt.sub(Ut)),e=et(dt.x,ut.x,t),i=et(dt.z,ut.z,t);Z(Bt.equal(0),()=>{zt.assign(e),It.assign(i)}).Else(()=>{Dt.assign(e),kt.assign(i)}),Bt.addAssign(1)}).ElseIf(jt.and(Ft.not()).and(Lt.not()),()=>{Z(Bt.equal(0),()=>{zt.assign(dt.x),It.assign(dt.z)}).Else(()=>{Dt.assign(dt.x),kt.assign(dt.z)}),Bt.addAssign(1)})});const Gt=Ut,Ht=Ot,qt=$t,Zt=Lt,Yt=qt.not().and(Zt.not()).and(Gt.mul(Ht).lessThan(0));Z(Bt.lessThan(2),()=>{Z(Yt,()=>{const t=Gt.div(Gt.sub(Ht)),e=et(ut.x,ht.x,t),i=et(ut.z,ht.z,t);Z(Bt.equal(0),()=>{zt.assign(e),It.assign(i)}).Else(()=>{Dt.assign(e),kt.assign(i)}),Bt.addAssign(1)}).ElseIf(qt.and(Wt.not()).and(jt.not()),()=>{Z(Bt.equal(0),()=>{zt.assign(ut.x),It.assign(ut.z)}).Else(()=>{Dt.assign(ut.x),kt.assign(ut.z)}),Bt.addAssign(1)})}),Z(Bt.notEqual(2),()=>{Y()});const Xt=W(zt,H(0),It),Kt=W(Dt,H(0),kt).sub(Xt).dot(At),Qt=W(zt,H(0),It).toVar(),Jt=W(Dt,H(0),kt).toVar();Z(Kt.lessThan(0),()=>{const t=zt,e=It;Qt.x.assign(Dt),Qt.z.assign(kt),Jt.x.assign(t),Jt.z.assign(e)});const te=H(0),ee=Ct,ie=Qt.sub(pt).dot(At),ne=Jt.sub(pt).dot(At),se=ee.lessThanEqual(ie).or(ne.lessThanEqual(te));Z(se,()=>{Y()});const re=X(te,ie),oe=K(ee,ne),ae=pt.add(At.mul(re)),le=pt.add(At.mul(oe)),ce=ae.sub(mt).dot(Et).div(yt),he=le.sub(mt).dot(Et).div(yt),de=X(H(0),K(H(1),ce)),ue=X(H(0),K(H(1),he)),pe=tt(ue.sub(de));Z(pe.lessThanEqual(H(Kr)),()=>{Y()});const fe=nt(O.element(0),1);Z(fe.lessThan(it(P)),()=>{const t=fe.mul(3);V.element(t).assign(i.toFloat()),V.element(t.add(1)).assign(de),V.element(t.add(2)).assign(ue)})})})})().compute(C.length);u+=performance.now()-L;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,P)),Zr.enabled&&console.log(` Batch ${i+1}: ${lt} overlaps found (capacity: ${P})`),lt>P&&Zr.enabled&&console.warn(` WARNING: Overlap buffer overflow! ${lt} > ${P}. Some occlusion data lost.`),lt>0){const t=await r.getArrayBufferAsync(V.value),e=new Float32Array(t);c+=performance.now()-ot;const i=performance.now(),s=Math.min(lt,P);for(let t=0;t<s;t++){const i=3*t,s=Math.round(e[i]);Vr([e[i+1],e[i+2]],n[s])}h+=performance.now()-i,Zr.enabled&&console.log(` Processed ${s} overlaps into hiddenOverlapMap`)}else c+=performance.now()-ot}r.dispose(),Jr=null;const p=d+u+l+c+h;Zr.enabled&&(console.log(`WebGPU timing breakdown (total: ${p.toFixed(1)}ms):`),console.log(` Buffer creation: ${d.toFixed(1)}ms`),console.log(` Shader build: ${u.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 io(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 V,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 no{constructor(t,e=!0){this.meshes=hr(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 io(this.visibleEdges,this.groupKeyToIndex?this.visibleGroupIndices:null)}getHiddenLineGeometry(){return io(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();Zr.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 As(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]=[];Zr.startStep("Building line BVH");const h=new gr(t,{maxLeafSize:2,strategy:2});Zr.startStep("BVHcast overlaps"),a=performance.now();const d={candidates:0,backFaceCulled:0,yBoundsCulled:0,xzBoundsCulled:0,triangleEdgeCulled:0,planeTrimCulled:0,distThresholdCulled:0,noOverlapCulled:0,used:0,totalEdges:t.length,totalTriangles:l},u=this.useWebGPU,p={};u&&(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];u?Qr(h,n.get(s.geometry),s,p,t):Ur(h,n.get(s.geometry),s,c,d)}if(u){let t=!1;for(to(p,i,h,c,d).then(()=>{t=!0});!t;)yield}const f=d.totalEdges*d.totalTriangles;if(Zr.setStat("Total edges",d.totalEdges.toLocaleString()),Zr.setStat("Total triangles",d.totalTriangles.toLocaleString()),Zr.setStat("Brute-force pairs (edges × triangles)",f.toLocaleString()),Zr.setStat("BVH candidate pairs",d.candidates.toLocaleString()),f>0&&Zr.setStat("BVH reduction",(d.candidates/f*100).toFixed(3)+"% of brute-force"),d.candidates>0){const t=d.candidates,e=e=>(e/t*100).toFixed(2)+"%";u||(Zr.setStat("Rejected: back-face culling",d.backFaceCulled.toLocaleString()+" ("+e(d.backFaceCulled)+")"),Zr.setStat("Rejected: Y-bounds (tri below edge)",d.yBoundsCulled.toLocaleString()+" ("+e(d.yBoundsCulled)+")"),Zr.setStat("Rejected: XZ-bounds (no 2D overlap)",d.xzBoundsCulled.toLocaleString()+" ("+e(d.xzBoundsCulled)+")"),Zr.setStat("Rejected: edge lies on triangle",d.triangleEdgeCulled.toLocaleString()+" ("+e(d.triangleEdgeCulled)+")"),Zr.setStat("Rejected: line above tri plane",d.planeTrimCulled.toLocaleString()+" ("+e(d.planeTrimCulled)+")"),Zr.setStat("Rejected: trimmed edge too small",d.distThresholdCulled.toLocaleString()+" ("+e(d.distThresholdCulled)+")"),Zr.setStat("Rejected: no projected overlap",d.noOverlapCulled.toLocaleString()+" ("+e(d.noOverlapCulled)+")")),Zr.setStat("Producing overlaps",d.used.toLocaleString()+" ("+e(d.used)+")")}Zr.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(tr(i,n,!1,s),tr(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 so{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(Zr.reset(),Zr.startTotal(),t.isBufferGeometry&&(t=new b(t)),o){Zr.startStep("Visibility culling");let e=!1;for(o.cull(t).then(i=>{(t=new P).children=i,e=!0});!e;)yield}const l=new fr;l.iterationTime=i,l.thresholdAngle=n,l.projectionDirection.copy(eo),Zr.startStep("Generating candidate edges"),r("Generating candidate edges");let c=[],h=a?[]:null;if(yield*l.getEdgesGenerator(t,c,h),s&&(Zr.startStep("Generating intersection edges"),r("Generating intersection edges"),yield*l.getIntersectionEdgesGenerator(t,c,h)),Zr.startStep("Pre-filtering edges"),r("Pre-filtering edges"),h){const t=[],e=[];for(let i=0;i<c.length;i++)Ks(c[i])||(t.push(c[i]),e.push(h[i]));c=t,h=e}else c=c.filter(t=>!Ks(t));yield;const d=new no(t,this.useWebGPU);if(d.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)}d.groupKeyToIndex=t,d.hasGroups=!0}return r("Building BVH & computing overlaps"),yield*d.addEdgesGenerator(c,{onProgress:r?(t,e)=>{r("Building BVH & computing overlaps",t/e,d)}:null}),Zr.printSummary(),d}}new d,new d,new h;const ro=class t extends ht{constructor(i){super(i),e(this,"enabled",!0),e(this,"onDisposed",new at),e(this,"generator",new so),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(Ws),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),d=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 As(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 u=e.renderer.three,p=new Hs(u,{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(d),g.applyMatrix4(d);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(ro,"uuid","f2e76c3a-8b1d-4d5e-9a3f-7c6b2d4e8f1a");let oo=ro;class ao{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 lo=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 ao),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(Ws);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@${Uo.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(lo,"uuid","a659add7-1418-4771-a0d6-7d4d438e4624");let co=lo;const ho=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(Ws),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(Ws);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(Ws);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(ho,"uuid","dd9ccf2d-8a21-4821-b7f6-2949add16a29");let uo=ho;const po=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(Ws),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(Ws);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(Ws);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(po,"uuid","d1444724-dba6-4cdd-a0c7-68ee1450d166");let fo=po;class mo{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(wo),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(wo).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 go=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(Ws),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?Ve.join(r):Ve.intersect(r)}create(t,e){const i=new mo(this.components,e);return this.list.set(t,i),i}async addFromCategories(t){const e=new Set,i=this.components.get(Ws);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(go,"uuid","0da7ad77-f734-42ca-942f-a074adfd1e3a");let wo=go;const yo=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(Ws).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(wo),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=Ve.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(Ws),o=this.components.get(wo),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);Ve.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=Ve.join(t);e.push(r)}return Ve.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(wo),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(Ws).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)Ve.remove(e.map,t);return}for(const[,e]of this.list.entries())for(const[,i]of e)Ve.remove(i.map,t)}async byModel(t){const e=this.components.get(Ws),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(yo,"uuid","e25a7f3c-46c4-4a14-9d3d-5115f24ebeb7");let _o=yo;class bo{constructor(t,i){e(this,"enabled",!0),e(this,"components"),e(this,"onDisposed",new at),e(this,"mouse"),e(this,"world"),e(this,"debugMode",!1),e(this,"colorToModelId",new Map),e(this,"modelIdToColor",new Map),e(this,"renderTarget"),e(this,"renderTargetSize",new o.Vector2),e(this,"debugCanvas"),e(this,"debugContainer"),e(this,"colorMaterials",new Map),e(this,"originalMaterials",new Map),e(this,"originalLodColors",new Map),e(this,"colorsNeedUpdate",!0);const n=i.renderer;if(!n)throw new Error("A renderer is needed for the FastModelPicker to work!");this.world=i,this.mouse=new $e(n.three.domElement),this.components=t,this.setupRenderTarget(),this.setupFragmentListeners()}setupFragmentListeners(){const t=this.components.get(Ws);t.list.onItemSet.add(()=>{this.colorsNeedUpdate=!0}),t.list.onItemDeleted.add(()=>{this.colorsNeedUpdate=!0})}setupRenderTarget(){const t=this.world.renderer.three.getSize(new o.Vector2);this.renderTargetSize.copy(t),this.renderTarget=new o.WebGLRenderTarget(t.x,t.y),this.renderTarget.texture.format=o.RGBAFormat,this.renderTarget.texture.type=o.UnsignedByteType,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)}generateColorForModel(t){let e=0;for(let i=0;i<t.length;i++)e=(e<<5)-e+t.charCodeAt(i),e&=e;let i=Math.abs(e)%16777215;0===i&&(i=1);const n=i>>16&255||1,s=i>>8&255||1,r=255&i||1;return new o.Color(n/255,s/255,r/255)}colorToId(t){return Math.round(255*t.r)<<16|Math.round(255*t.g)<<8|Math.round(255*t.b)}assignColors(){const t=this.components.get(Ws);if(t.initialized){if(!this.colorsNeedUpdate){const e=new Set(t.list.keys()),i=new Set(this.modelIdToColor.keys());(e.size!==i.size||[...e].some(t=>!i.has(t)))&&(this.colorsNeedUpdate=!0)}if(this.colorsNeedUpdate){this.colorToModelId.clear(),this.modelIdToColor.clear();for(const t of this.colorMaterials.values())t.dispose();this.colorMaterials.clear();for(const[e]of t.list){const t=this.generateColorForModel(e),i=this.colorToId(t);this.colorToModelId.set(i,e),this.modelIdToColor.set(e,t);const n=new o.MeshBasicMaterial({color:t,depthTest:!0,depthWrite:!0});this.colorMaterials.set(e,n)}this.colorsNeedUpdate=!1}}}applyColorMaterials(){const t=this.components.get(Ws);if(t.initialized)for(const[e,i]of t.list){const t=this.colorMaterials.get(e);t&&i.object.traverse(e=>{if(e instanceof o.Mesh){if("isLODGeometry"in e.geometry){const i=e.material[0].uniforms.lodColor;return this.originalLodColors.has(i)||this.originalLodColors.set(i,i.value),void(i.value=t.color)}this.originalMaterials.has(e)||this.originalMaterials.set(e,e.material),e.material=t}})}}restoreOriginalMaterials(){for(const[t,e]of this.originalMaterials)t.material=e;for(const[t,e]of this.originalLodColors)t.value=e;this.originalMaterials.clear()}renderColorCoded(){if(!this.renderTarget||!this.world.renderer)throw new Error("Render target not initialized!");const t=this.world.renderer.three,e=this.world.scene.three,i=this.world.camera.three,n=t.getRenderTarget(),s=t.autoClear,r=new o.Color,a=t.getClearAlpha();t.getClearColor(r),this.applyColorMaterials(),t.setRenderTarget(this.renderTarget),t.autoClear=!0,t.setClearColor(0,1),t.clear(!0,!0,!1),t.render(e,i),t.setRenderTarget(n),t.autoClear=s,t.setClearColor(r,a),this.restoreOriginalMaterials(),this.debugMode&&this.debugCanvas&&this.updateDebugCanvas()}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)}async getModelAt(t){if(!this.renderTarget||!this.world.renderer)throw new Error("Render target not initialized!");const e=this.components.get(Ws);if(!e.initialized||0===e.list.size)return null;this.assignColors(),this.renderColorCoded();const i=t||this.mouse.position,n=this.renderTargetSize,s=Math.floor(.5*(i.x+1)*n.x),r=Math.floor(.5*(i.y+1)*(n.y-1)),o=Math.max(0,Math.min(n.x-1,s)),a=Math.max(0,Math.min(n.y-1,r)),l=this.world.renderer.three,c=new Uint8Array(4);l.readRenderTargetPixels(this.renderTarget,o,a,1,1,c);const h=c[0]<<16|c[1]<<8|c[2];return this.colorToModelId.get(h)||null}setDebugMode(t){this.debugMode=t,t?this.setupDebugCanvas():this.removeDebugCanvas()}removeDebugCanvas(){this.debugContainer&&(this.debugContainer.remove(),this.debugContainer=void 0,this.debugCanvas=void 0)}dispose(){this.mouse.dispose(),this.removeDebugCanvas();for(const t of this.colorMaterials.values())t.dispose();this.colorMaterials.clear(),this.renderTarget&&this.renderTarget.dispose(),this.colorToModelId.clear(),this.modelIdToColor.clear(),this.originalMaterials.clear(),this.originalLodColors.clear(),this.onDisposed.trigger(),this.onDisposed.reset()}}const vo=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 bo(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(vo,"uuid","4a82430c-7ff2-49ea-9401-60807502dad6");let xo=vo;class So{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"),e(this,"useFastModelPicking",!1);const n=i.renderer;if(!n)throw new Error("A renderer is needed for the raycaster to work!");this.world=i,this.mouse=new $e(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(Ws),o=this.world.renderer.three.domElement,a=this.mouse.rawPosition;let l=null;if(r.initialized){if(this.useFastModelPicking){const t=this.components.get(xo).get(this.world),i=await t.getModelAt(n);if(i){const t=r.list.get(i);if(t)if(e&&e.length>0){const i=await t.raycastWithSnapping({camera:s,dom:o,mouse:a,snappingClasses:e});l=i&&i.length>0?i[0]:await t.raycast({camera:s,dom:o,mouse:a})}else l=await t.raycast({camera:s,dom:o,mouse:a})}}else l=await r.raycast({camera:s,dom:o,mouse:a,snappingClasses:e});if(0===i.length)return l}this.three.setFromCamera(n,s);const c=this.intersect(i);return l?c&&c.distance<l.distance?c:l:c}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 To=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 So(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(To,"uuid","d5d8bdf0-db25-4952-b951-b643af207ace");let Co=To;class Ao 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,"uuid",_t.create()),e(this,"name"),e(this,"_scene"),e(this,"_camera"),e(this,"_renderer",null),e(this,"onPointerDown",async t=>{if(!this.camera.hasCameraControls())throw new Error("World: can't set dynamic anchor if the camera doesn't have controls.");const e=this.components.get(Co).get(this),i=await e.castRay();i&&i.point&&0===t.button&&this.camera.controls.setOrbitPoint(i.point.x,i.point.y,i.point.z)}),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)}get dynamicAnchor(){return this._dynamicAnchor}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){if(this.enabled=!1,this.isDisposing=!0,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(Oo).list.delete(this.uuid),this.onDisposed.trigger(),this.onDisposed.reset()}}class Eo{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 Mo{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 Po extends Re{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 Mo(this._config,this._component)),e(this,"directionalLight",new Eo(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 zo extends gt{constructor(t){super(t),e(this,"onSetup",new at),e(this,"isSetup",!1),e(this,"three"),e(this,"config",new Po(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(je).list.delete(this.config.uuid)}}var Io=(t=>(t[t.MANUAL=0]="MANUAL",t[t.AUTO=1]="AUTO",t))(Io||{});class Do 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,"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)}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.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.onContainerUpdated.trigger()}}class ko extends ut{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(Ws),i=this.components.get(fo);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:ko.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 Bo=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 Ao(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(Bo,"uuid","fdb61dc4-2ec1-4966-b83d-54ea795fad4a");let Oo=Bo;class Vo extends Re{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 Lo{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 ko&&(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 Vo(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(je).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 ko))return;const e=this.world.camera.controls;t?e.addEventListener("update",this.updateZoom):e.removeEventListener("update",this.updateZoom)}}const No=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 Lo(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(No,"uuid","d1e814d5-b81c-4452-87a2-f039375e0489");let Fo=No;const Ro=class t{constructor(){e(this,"onDisposed",new at),e(this,"list",new n),e(this,"enabled",!1),e(this,"_clock"),e(this,"onInit",new at),e(this,"update",()=>{if(!this.enabled)return;const t=this._clock.getDelta();for(const[e,i]of this.list)i.enabled&&i.isUpdateable()&&i.update(t);requestAnimationFrame(this.update)}),this._clock=new o.Clock,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._clock.start(),this.update(),this.onInit.trigger()}dispose(){let t;this.enabled=!1;for(const[e,i]of this.list)i.enabled=!1,e!==Ws.uuid?i.isDisposeable()&&i.dispose():t=i;null==t||t.dispose(),this._clock.stop(),this.onDisposed.trigger()}static setupBVH(){o.BufferGeometry.prototype.computeBoundsTree=Us,o.BufferGeometry.prototype.disposeBoundsTree=js,o.Mesh.prototype.raycast=Fs,o.LineSegments.prototype.raycast=Fs}};e(Ro,"release","2.4.3");let Uo=Ro;class jo{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 $o{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 Wo{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 Go{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 Ho extends ko{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 Go(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 $o(this)),this._navigationModes.set("FirstPerson",new jo(this)),this._navigationModes.set("Plan",new Wo(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(Ws);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 d=Math.max(c.x,c.y,c.z)*e,u=new o.Sphere(h,d);await this.controls.fitToSphere(u,!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 qo="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Zo(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function Yo(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 Xo={exports:{}};
|
|
2
2
|
/*!
|
|
3
3
|
|
|
4
4
|
JSZip v3.10.1 - A JavaScript class for generating and reading zip files
|