iflow-engine-base 3.7.4 → 3.7.5
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.
|
@@ -4938,7 +4938,7 @@ void main() {
|
|
|
4938
4938
|
`):" "+CA(o[0]):"as no adapter specified";throw new $e("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return s}const MA={getAdapter:kI,adapters:Ru};function ku(n){if(n.cancelToken&&n.cancelToken.throwIfRequested(),n.signal&&n.signal.aborted)throw new uo(null,n)}function EA(n){return ku(n),n.headers=yi.from(n.headers),n.data=Lu.call(n,n.transformRequest),["post","put","patch"].indexOf(n.method)!==-1&&n.headers.setContentType("application/x-www-form-urlencoded",!1),MA.getAdapter(n.adapter||la.adapter,n)(n).then(function(i){return ku(n),i.data=Lu.call(n,n.transformResponse,i),i.headers=yi.from(i.headers),i},function(i){return uA(i)||(ku(n),i&&i.response&&(i.response.data=Lu.call(n,n.transformResponse,i.response),i.response.headers=yi.from(i.response.headers))),Promise.reject(i)})}const IA="1.13.2",Ac={};["object","boolean","number","function","string","symbol"].forEach((n,e)=>{Ac[n]=function(i){return typeof i===n||"a"+(e<1?"n ":" ")+n}});const TA={};Ac.transitional=function(e,t,i){function s(r,o){return"[Axios v"+IA+"] Transitional option '"+r+"'"+o+(i?". "+i:"")}return(r,o,a)=>{if(e===!1)throw new $e(s(o," has been removed"+(t?" in "+t:"")),$e.ERR_DEPRECATED);return t&&!TA[o]&&(TA[o]=!0,console.warn(s(o," has been deprecated since v"+t+" and will be removed in the near future"))),e?e(r,o,a):!0}},Ac.spelling=function(e){return(t,i)=>(console.warn(`${i} is likely a misspelling of ${e}`),!0)};function FI(n,e,t){if(typeof n!="object")throw new $e("options must be an object",$e.ERR_BAD_OPTION_VALUE);const i=Object.keys(n);let s=i.length;for(;s-- >0;){const r=i[s],o=e[r];if(o){const a=n[r],l=a===void 0||o(a,r,n);if(l!==!0)throw new $e("option "+r+" must be "+l,$e.ERR_BAD_OPTION_VALUE);continue}if(t!==!0)throw new $e("Unknown option "+r,$e.ERR_BAD_OPTION)}}const xc={assertOptions:FI,validators:Ac},yn=xc.validators;let hr=class{constructor(e){this.defaults=e||{},this.interceptors={request:new lA,response:new lA}}async request(e,t){try{return await this._request(e,t)}catch(i){if(i instanceof Error){let s={};Error.captureStackTrace?Error.captureStackTrace(s):s=new Error;const r=s.stack?s.stack.replace(/^.+\n/,""):"";try{i.stack?r&&!String(i.stack).endsWith(r.replace(/^.+\n.+\n/,""))&&(i.stack+=`
|
|
4939
4939
|
`+r):i.stack=r}catch{}}throw i}}_request(e,t){typeof e=="string"?(t=t||{},t.url=e):t=e||{},t=cr(this.defaults,t);const{transitional:i,paramsSerializer:s,headers:r}=t;i!==void 0&&xc.assertOptions(i,{silentJSONParsing:yn.transitional(yn.boolean),forcedJSONParsing:yn.transitional(yn.boolean),clarifyTimeoutError:yn.transitional(yn.boolean)},!1),s!=null&&(le.isFunction(s)?t.paramsSerializer={serialize:s}:xc.assertOptions(s,{encode:yn.function,serialize:yn.function},!0)),t.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),xc.assertOptions(t,{baseUrl:yn.spelling("baseURL"),withXsrfToken:yn.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let o=r&&le.merge(r.common,r[t.method]);r&&le.forEach(["delete","get","head","post","put","patch","common"],g=>{delete r[g]}),t.headers=yi.concat(o,r);const a=[];let l=!0;this.interceptors.request.forEach(function(p){typeof p.runWhen=="function"&&p.runWhen(t)===!1||(l=l&&p.synchronous,a.unshift(p.fulfilled,p.rejected))});const c=[];this.interceptors.response.forEach(function(p){c.push(p.fulfilled,p.rejected)});let h,d=0,f;if(!l){const g=[EA.bind(this),void 0];for(g.unshift(...a),g.push(...c),f=g.length,h=Promise.resolve(t);d<f;)h=h.then(g[d++],g[d++]);return h}f=a.length;let u=t;for(;d<f;){const g=a[d++],p=a[d++];try{u=g(u)}catch(m){p.call(this,m);break}}try{h=EA.call(this,u)}catch(g){return Promise.reject(g)}for(d=0,f=c.length;d<f;)h=h.then(c[d++],c[d++]);return h}getUri(e){e=cr(this.defaults,e);const t=mA(e.baseURL,e.url,e.allowAbsoluteUrls);return aA(t,e.params,e.paramsSerializer)}};le.forEach(["delete","get","head","options"],function(e){hr.prototype[e]=function(t,i){return this.request(cr(i||{},{method:e,url:t,data:(i||{}).data}))}}),le.forEach(["post","put","patch"],function(e){function t(i){return function(r,o,a){return this.request(cr(a||{},{method:e,headers:i?{"Content-Type":"multipart/form-data"}:{},url:r,data:o}))}}hr.prototype[e]=t(),hr.prototype[e+"Form"]=t(!0)});let OI=class Kv{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let t;this.promise=new Promise(function(r){t=r});const i=this;this.promise.then(s=>{if(!i._listeners)return;let r=i._listeners.length;for(;r-- >0;)i._listeners[r](s);i._listeners=null}),this.promise.then=s=>{let r;const o=new Promise(a=>{i.subscribe(a),r=a}).then(s);return o.cancel=function(){i.unsubscribe(r)},o},e(function(r,o,a){i.reason||(i.reason=new uo(r,o,a),t(i.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);t!==-1&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=i=>{e.abort(i)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;return{token:new Kv(function(s){e=s}),cancel:e}}};function UI(n){return function(t){return n.apply(null,t)}}function NI(n){return le.isObject(n)&&n.isAxiosError===!0}const Fu={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(Fu).forEach(([n,e])=>{Fu[e]=n});function DA(n){const e=new hr(n),t=Hm(hr.prototype.request,e);return le.extend(t,hr.prototype,e,{allOwnKeys:!0}),le.extend(t,e,null,{allOwnKeys:!0}),t.create=function(s){return DA(cr(n,s))},t}const Mt=DA(la);Mt.Axios=hr,Mt.CanceledError=uo,Mt.CancelToken=OI,Mt.isCancel=uA,Mt.VERSION=IA,Mt.toFormData=fc,Mt.AxiosError=$e,Mt.Cancel=Mt.CanceledError,Mt.all=function(e){return Promise.all(e)},Mt.spread=UI,Mt.isAxiosError=NI,Mt.mergeConfig=cr,Mt.AxiosHeaders=yi,Mt.formToJSON=n=>hA(le.isHTMLForm(n)?new FormData(n):n),Mt.getAdapter=MA.getAdapter,Mt.HttpStatusCode=Fu,Mt.default=Mt;const{Axios:MF,AxiosError:EF,CanceledError:IF,isCancel:TF,CancelToken:DF,VERSION:BF,all:PF,Cancel:LF,isAxiosError:RF,spread:kF,toFormData:FF,AxiosHeaders:OF,HttpStatusCode:UF,formToJSON:NF,getAdapter:zF,mergeConfig:GF}=Mt;class fo{static MAGIC=new TextEncoder().encode("BIMGCM01");static isEncrypted(e){if(e.byteLength<8)return!1;const t=new Uint8Array(e);for(let i=0;i<8;i++)if(t[i]!==fo.MAGIC[i])return!1;return!0}static async decryptPzEnc(e,t){const i=new Uint8Array(e),s=new TextEncoder().encode("BIMGCM01");for(let m=0;m<s.length;m++)if(i[m]!==s[m])throw new Error("magic 不匹配: 不是有效的 pzenc 文件");const r=i[8];if(r!==1)throw new Error(`不支持的 pzenc 版本: ${r}`);const o=i[9],a=i[10],l=11,c=i.slice(l,l+o),h=i.slice(l+o,l+o+a),d=i.slice(l+o+a),f=GI(d,h),u=zI(t);if(u.length!==32)throw new Error("AES-256 密钥必须是 32 字节");const g=await crypto.subtle.importKey("raw",u.buffer,{name:"AES-GCM"},!1,["decrypt"]),p=await crypto.subtle.decrypt({name:"AES-GCM",iv:c.buffer,additionalData:i.slice(0,l).buffer,tagLength:a*8},g,f.buffer);return new Uint8Array(p)}}function zI(n){const e=atob(n),t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.codePointAt(i);return t}function GI(n,e){const t=new Uint8Array(n.length+e.length);return t.set(n,0),t.set(e,n.length),t}function ha(n,e,t,i){Mt({method:"get",responseType:"arraybuffer",url:n}).then(async r=>{let o=r.data;i&&fo.isEncrypted(r.data)&&(o=await fo.decryptPzEnc(r.data,i)),Wm.loadAsync(o).then(a=>{for(let l in a.files){const c=a.file(a.files[l].name);c&&c.async("blob").then(h=>{s(h,"utf-8",function(d,f){e(f)})}).catch(()=>{t()})}}).catch(()=>{t()})}).catch(()=>{t()});function s(r,o,a){var l=new FileReader,c=new Blob([r]);l.onload=function(h){a(null,h.target.result)},l.onerror=function(){a(null,null)},l.readAsText(c,o)}}const Ou=new WeakMap;class VI extends v.Loader{constructor(e){super(e),this.decoderPath="",this.decoderConfig={},this.decoderBinary=null,this.decoderPending=null,this.workerLimit=4,this.workerPool=[],this.workerNextTaskID=1,this.workerSourceURL="",this.defaultAttributeIDs={position:"POSITION",normal:"NORMAL",color:"COLOR",uv:"TEX_COORD"},this.defaultAttributeTypes={position:"Float32Array",normal:"Float32Array",color:"Float32Array",uv:"Float32Array"}}setDecoderPath(e){return this.decoderPath=e,this}setDecoderConfig(e){return this.decoderConfig=e,this}setWorkerLimit(e){return this.workerLimit=e,this}load(e,t,i,s){const r=new v.FileLoader(this.manager);r.setPath(this.path),r.setResponseType("arraybuffer"),r.setRequestHeader(this.requestHeader),r.setWithCredentials(this.withCredentials),r.load(e,o=>{this.parse(o,t,s)},i,s)}parse(e,t,i=()=>{}){this.decodeDracoFile(e,t,null,null,v.SRGBColorSpace,i).catch(i)}decodeDracoFile(e,t,i,s,r=v.LinearSRGBColorSpace,o=()=>{}){const a={attributeIDs:i||this.defaultAttributeIDs,attributeTypes:s||this.defaultAttributeTypes,useUniqueIDs:!!i,vertexColorSpace:r};return this.decodeGeometry(e,a).then(t).catch(o)}decodeGeometry(e,t){const i=JSON.stringify(t);if(Ou.has(e)){const l=Ou.get(e);if(l.key===i)return l.promise;if(e.byteLength===0)throw new Error("THREE.DRACOLoader: Unable to re-decode a buffer with different settings. Buffer has already been transferred.")}let s;const r=this.workerNextTaskID++,o=e.byteLength,a=this._getWorker(r,o).then(l=>(s=l,new Promise((c,h)=>{s._callbacks[r]={resolve:c,reject:h},s.postMessage({type:"decode",id:r,taskConfig:t,buffer:e},[e])}))).then(l=>this._createGeometry(l.geometry));return a.catch(()=>!0).then(()=>{s&&r&&this._releaseTask(s,r)}),Ou.set(e,{key:i,promise:a}),a}_createGeometry(e){const t=new v.BufferGeometry;e.index&&t.setIndex(new v.BufferAttribute(e.index.array,1));for(let i=0;i<e.attributes.length;i++){const{name:s,array:r,itemSize:o,stride:a,vertexColorSpace:l}=e.attributes[i];let c;if(o===a)c=new v.BufferAttribute(r,o);else{const h=new v.InterleavedBuffer(r,a);c=new v.InterleavedBufferAttribute(h,o,0)}s==="color"&&(this._assignVertexColorSpace(c,l),c.normalized=!(r instanceof Float32Array)),t.setAttribute(s,c)}return t}_assignVertexColorSpace(e,t){if(t!==v.SRGBColorSpace)return;const i=new v.Color;for(let s=0,r=e.count;s<r;s++)i.fromBufferAttribute(e,s),v.ColorManagement.colorSpaceToWorking(i,v.SRGBColorSpace),e.setXYZ(s,i.r,i.g,i.b)}_loadLibrary(e,t){const i=new v.FileLoader(this.manager);return i.setPath(this.decoderPath),i.setResponseType(t),i.setWithCredentials(this.withCredentials),new Promise((s,r)=>{i.load(e,s,void 0,r)})}preload(){return this._initDecoder(),this}_initDecoder(){if(this.decoderPending)return this.decoderPending;const e=typeof WebAssembly!="object"||this.decoderConfig.type==="js",t=[];return e?t.push(this._loadLibrary("draco_decoder.js","text")):(t.push(this._loadLibrary("draco_wasm_wrapper.js","text")),t.push(this._loadLibrary("draco_decoder.wasm","arraybuffer"))),this.decoderPending=Promise.all(t).then(i=>{const s=i[0];e||(this.decoderConfig.wasmBinary=i[1]);const r=QI.toString(),o=["/* draco decoder */",s,"","/* worker */",r.substring(r.indexOf("{")+1,r.lastIndexOf("}"))].join(`
|
|
4940
4940
|
`);this.workerSourceURL=URL.createObjectURL(new Blob([o]))}),this.decoderPending}_getWorker(e,t){return this._initDecoder().then(()=>{if(this.workerPool.length<this.workerLimit){const s=new Worker(this.workerSourceURL);s._callbacks={},s._taskCosts={},s._taskLoad=0,s.postMessage({type:"init",decoderConfig:this.decoderConfig}),s.onmessage=function(r){const o=r.data;switch(o.type){case"decode":s._callbacks[o.id].resolve(o);break;case"error":s._callbacks[o.id].reject(o);break;default:console.error('THREE.DRACOLoader: Unexpected message, "'+o.type+'"')}},this.workerPool.push(s)}else this.workerPool.sort(function(s,r){return s._taskLoad>r._taskLoad?-1:1});const i=this.workerPool[this.workerPool.length-1];return i._taskCosts[e]=t,i._taskLoad+=t,i})}_releaseTask(e,t){e._taskLoad-=e._taskCosts[t],delete e._callbacks[t],delete e._taskCosts[t]}debug(){console.log("Task load: ",this.workerPool.map(e=>e._taskLoad))}dispose(){for(let e=0;e<this.workerPool.length;++e)this.workerPool[e].terminate();return this.workerPool.length=0,this.workerSourceURL!==""&&URL.revokeObjectURL(this.workerSourceURL),this}}function QI(){let n,e;onmessage=function(o){const a=o.data;switch(a.type){case"init":n=a.decoderConfig,e=new Promise(function(h){n.onModuleLoaded=function(d){h({draco:d})},DracoDecoderModule(n)});break;case"decode":const l=a.buffer,c=a.taskConfig;e.then(h=>{const d=h.draco,f=new d.Decoder;try{const u=t(d,f,new Int8Array(l),c),g=u.attributes.map(p=>p.array.buffer);u.index&&g.push(u.index.array.buffer),self.postMessage({type:"decode",id:a.id,geometry:u},g)}catch(u){console.error(u),self.postMessage({type:"error",id:a.id,error:u.message})}finally{d.destroy(f)}});break}};function t(o,a,l,c){const h=c.attributeIDs,d=c.attributeTypes;let f,u;const g=a.GetEncodedGeometryType(l);if(g===o.TRIANGULAR_MESH)f=new o.Mesh,u=a.DecodeArrayToMesh(l,l.byteLength,f);else if(g===o.POINT_CLOUD)f=new o.PointCloud,u=a.DecodeArrayToPointCloud(l,l.byteLength,f);else throw new Error("THREE.DRACOLoader: Unexpected geometry type.");if(!u.ok()||f.ptr===0)throw new Error("THREE.DRACOLoader: Decoding failed: "+u.error_msg());const p={index:null,attributes:[]};for(const m in h){const A=self[d[m]];let x,b;if(c.useUniqueIDs)b=h[m],x=a.GetAttributeByUniqueId(f,b);else{if(b=a.GetAttributeId(f,o[h[m]]),b===-1)continue;x=a.GetAttribute(f,b)}const y=s(o,a,f,m,A,x);m==="color"&&(y.vertexColorSpace=c.vertexColorSpace),p.attributes.push(y)}return g===o.TRIANGULAR_MESH&&(p.index=i(o,a,f)),o.destroy(f),p}function i(o,a,l){const h=l.num_faces()*3,d=h*4,f=o._malloc(d);a.GetTrianglesUInt32Array(l,d,f);const u=new Uint32Array(o.HEAPF32.buffer,f,h).slice();return o._free(f),{array:u,itemSize:1}}function s(o,a,l,c,h,d){const f=l.num_points(),u=d.num_components(),g=r(o,h),p=u*h.BYTES_PER_ELEMENT,m=Math.ceil(p/4)*4,A=m/h.BYTES_PER_ELEMENT,x=f*p,b=f*m,y=o._malloc(x);a.GetAttributeDataArrayForAllPoints(l,d,g,x,y);const _=new h(o.HEAPF32.buffer,y,x/h.BYTES_PER_ELEMENT);let S;if(p===m)S=_.slice();else{S=new h(b/h.BYTES_PER_ELEMENT);let C=0;for(let D=0,M=_.length;D<M;D++){for(let I=0;I<u;I++)S[C+I]=_[D*u+I];C+=A}}return o._free(y),{name:c,count:f,itemSize:u,array:S,stride:A}}function r(o,a){switch(a){case Float32Array:return o.DT_FLOAT32;case Int8Array:return o.DT_INT8;case Int16Array:return o.DT_INT16;case Int32Array:return o.DT_INT32;case Uint8Array:return o.DT_UINT8;case Uint16Array:return o.DT_UINT16;case Uint32Array:return o.DT_UINT32}}}var jI=(function(){var n="b9H79Tebbbe8Fv9Gbb9Gvuuuuueu9Giuuub9Geueu9Giuuueuixkbeeeddddillviebeoweuec:W:Odkr;Neqo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bb8A9TW79O9V9Wt9F9KW9J9V9KW9wWVtW949c919M9MWVbeY9TW79O9V9Wt9F9KW9J9V9KW69U9KW949c919M9MWVbdE9TW79O9V9Wt9F9KW9J9V9KW69U9KW949tWG91W9U9JWbiL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9p9JtblK9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9r919HtbvL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVT949WboY9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVJ9V29VVbrl79IV9Rbwq;lZkdbk;jYi5ud9:du8Jjjjjbcj;kb9Rgv8Kjjjjbc9:hodnalTmbcuhoaiRbbgrc;WeGc:Ge9hmbarcsGgwce0mbc9:hoalcufadcd4cbawEgDadfgrcKcaawEgqaraq0Egk6mbaicefhxcj;abad9Uc;WFbGcjdadca0EhmaialfgPar9Rgoadfhsavaoadz:jjjjbgzceVhHcbhOdndninaeaO9nmeaPax9RaD6mdamaeaO9RaOamfgoae6EgAcsfglc9WGhCabaOad2fhXaAcethQaxaDfhiaOaeaoaeao6E9RhLalcl4cifcd4hKazcj;cbfaAfhYcbh8AazcjdfhEaHh3incbhodnawTmbaxa8Acd4fRbbhokaocFeGh5cbh8Eazcj;cbfhqinaih8Fdndndndna5a8Ecet4ciGgoc9:fPdebdkaPa8F9RaA6mrazcj;cbfa8EaA2fa8FaAz:jjjjb8Aa8FaAfhixdkazcj;cbfa8EaA2fcbaAz:kjjjb8Aa8FhixekaPa8F9RaK6mva8FaKfhidnaCTmbaPai9RcK6mbaocdtc:q1jjbfcj1jjbawEhaczhrcbhlinargoc9Wfghaqfhrdndndndndndnaaa8Fahco4fRbbalcoG4ciGcdtfydbPDbedvivvvlvkar9cb83bbarcwf9cb83bbxlkarcbaiRbdai8Xbb9c:c:qj:bw9:9c:q;c1:I1e:d9c:b:c:e1z9:gg9cjjjjjz:dg8J9qE86bbaqaofgrcGfag9c8F1:NghcKtc8F91aicdfa8J9c8N1:Nfg8KRbbG86bbarcVfcba8KahcjeGcr4fghRbbag9cjjjjjl:dg8J9qE86bbarc7fcbaha8J9c8L1:NfghRbbag9cjjjjjd:dg8J9qE86bbarctfcbaha8J9c8K1:NfghRbbag9cjjjjje:dg8J9qE86bbarc91fcbaha8J9c8J1:NfghRbbag9cjjjj;ab:dg8J9qE86bbarc4fcbaha8J9cg1:NfghRbbag9cjjjja:dg8J9qE86bbarc93fcbaha8J9ch1:NfghRbbag9cjjjjz:dgg9qE86bbarc94fcbahag9ca1:NfghRbbai8Xbe9c:c:qj:bw9:9c:q;c1:I1e:d9c:b:c:e1z9:gg9cjjjjjz:dg8J9qE86bbarc95fag9c8F1:NgicKtc8F91aha8J9c8N1:NfghRbbG86bbarc96fcbahaicjeGcr4fgiRbbag9cjjjjjl:dg8J9qE86bbarc97fcbaia8J9c8L1:NfgiRbbag9cjjjjjd:dg8J9qE86bbarc98fcbaia8J9c8K1:NfgiRbbag9cjjjjje:dg8J9qE86bbarc99fcbaia8J9c8J1:NfgiRbbag9cjjjj;ab:dg8J9qE86bbarc9:fcbaia8J9cg1:NfgiRbbag9cjjjja:dg8J9qE86bbarcufcbaia8J9ch1:NfgiRbbag9cjjjjz:dgg9qE86bbaiag9ca1:NfhixikaraiRblaiRbbghco4g8Ka8KciSg8KE86bbaqaofgrcGfaiclfa8Kfg8KRbbahcl4ciGg8La8LciSg8LE86bbarcVfa8Ka8Lfg8KRbbahcd4ciGg8La8LciSg8LE86bbarc7fa8Ka8Lfg8KRbbahciGghahciSghE86bbarctfa8Kahfg8KRbbaiRbeghco4g8La8LciSg8LE86bbarc91fa8Ka8Lfg8KRbbahcl4ciGg8La8LciSg8LE86bbarc4fa8Ka8Lfg8KRbbahcd4ciGg8La8LciSg8LE86bbarc93fa8Ka8Lfg8KRbbahciGghahciSghE86bbarc94fa8Kahfg8KRbbaiRbdghco4g8La8LciSg8LE86bbarc95fa8Ka8Lfg8KRbbahcl4ciGg8La8LciSg8LE86bbarc96fa8Ka8Lfg8KRbbahcd4ciGg8La8LciSg8LE86bbarc97fa8Ka8Lfg8KRbbahciGghahciSghE86bbarc98fa8KahfghRbbaiRbigico4g8Ka8KciSg8KE86bbarc99faha8KfghRbbaicl4ciGg8Ka8KciSg8KE86bbarc9:faha8KfghRbbaicd4ciGg8Ka8KciSg8KE86bbarcufaha8KfgrRbbaiciGgiaiciSgiE86bbaraifhixdkaraiRbwaiRbbghcl4g8Ka8KcsSg8KE86bbaqaofgrcGfaicwfa8Kfg8KRbbahcsGghahcsSghE86bbarcVfa8KahfghRbbaiRbeg8Kcl4g8La8LcsSg8LE86bbarc7faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarctfaha8KfghRbbaiRbdg8Kcl4g8La8LcsSg8LE86bbarc91faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarc4faha8KfghRbbaiRbig8Kcl4g8La8LcsSg8LE86bbarc93faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarc94faha8KfghRbbaiRblg8Kcl4g8La8LcsSg8LE86bbarc95faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarc96faha8KfghRbbaiRbvg8Kcl4g8La8LcsSg8LE86bbarc97faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarc98faha8KfghRbbaiRbog8Kcl4g8La8LcsSg8LE86bbarc99faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarc9:faha8KfghRbbaiRbrgicl4g8Ka8KcsSg8KE86bbarcufaha8KfgrRbbaicsGgiaicsSgiE86bbaraifhixekarai8Pbb83bbarcwfaicwf8Pbb83bbaiczfhikdnaoaC9pmbalcdfhlaoczfhraPai9RcL0mekkaoaC6moaimexokaCmva8FTmvkaqaAfhqa8Ecefg8Ecl9hmbkdndndndnawTmbasa8Acd4fRbbgociGPlbedrbkaATmdaza8Afh8Fazcj;cbfhhcbh8EaEhaina8FRbbhraahocbhlinaoahalfRbbgqce4cbaqceG9R7arfgr86bbaoadfhoaAalcefgl9hmbkaacefhaa8Fcefh8FahaAfhha8Ecefg8Ecl9hmbxikkaATmeaza8Afhaazcj;cbfhhcbhoceh8EaYh8FinaEaofhlaa8Vbbhrcbhoinala8FaofRbbcwtahaofRbbgqVc;:FiGce4cbaqceG9R7arfgr87bbaladfhlaLaocefgofmbka8FaQfh8FcdhoaacdfhaahaQfhha8EceGhlcbh8EalmbxdkkaATmbcbaocl49Rh8Eaza8AfRbbhqcwhoa3hlinalRbbaotaqVhqalcefhlaocwfgoca9hmbkcbhhaEh8FaYhainazcj;cbfahfRbbhrcwhoaahlinalRbbaotarVhralaAfhlaocwfgoca9hmbkara8E93aq7hqcbhoa8Fhlinalaqao486bbalcefhlaocwfgoca9hmbka8Fadfh8FaacefhaahcefghaA9hmbkkaEclfhEa3clfh3a8Aclfg8Aad6mbkaXazcjdfaAad2z:jjjjb8AazazcjdfaAcufad2fadz:jjjjb8AaAaOfhOaihxaimbkc9:hoxdkcbc99aPax9RakSEhoxekc9:hokavcj;kbf8Kjjjjbaok:XseHu8Jjjjjbc;ae9Rgv8Kjjjjbc9:hodnaeci9UgrcHfal0mbcuhoaiRbbgwc;WeGc;Ge9hmbawcsGgDce0mbavc;abfcFecjez:kjjjb8AavcUf9cu83ibavc8Wf9cu83ibavcyf9cu83ibavcaf9cu83ibavcKf9cu83ibavczf9cu83ibav9cu83iwav9cu83ibaialfc9WfhqaicefgwarfhldnaeTmbcmcsaDceSEhkcbhxcbhmcbhrcbhicbhoindnalaq9nmbc9:hoxikdndnawRbbgDc;Ve0mbavc;abfaoaDcu7gPcl4fcsGcitfgsydlhzasydbhHdndnaDcsGgsak9pmbavaiaPfcsGcdtfydbaxasEhDaxasTgOfhxxekdndnascsSmbcehOasc987asamffcefhDxekalcefhDal8SbbgscFeGhPdndnascu9mmbaDhlxekalcvfhlaPcFbGhPcrhsdninaD8SbbgOcFbGastaPVhPaOcu9kmeaDcefhDascrfgsc8J9hmbxdkkaDcefhlkcehOaPce4cbaPceG9R7amfhDkaDhmkavc;abfaocitfgsaDBdbasazBdlavaicdtfaDBdbavc;abfaocefcsGcitfgsaHBdbasaDBdlaocdfhoaOaifhidnadcd9hmbabarcetfgsaH87ebasclfaD87ebascdfaz87ebxdkabarcdtfgsaHBdbascwfaDBdbasclfazBdbxekdnaDcpe0mbaxcefgOavaiaqaDcsGfRbbgscl49RcsGcdtfydbascz6gPEhDavaias9RcsGcdtfydbaOaPfgzascsGgOEhsaOThOdndnadcd9hmbabarcetfgHax87ebaHclfas87ebaHcdfaD87ebxekabarcdtfgHaxBdbaHcwfasBdbaHclfaDBdbkavaicdtfaxBdbavc;abfaocitfgHaDBdbaHaxBdlavaicefgicsGcdtfaDBdbavc;abfaocefcsGcitfgHasBdbaHaDBdlavaiaPfgicsGcdtfasBdbavc;abfaocdfcsGcitfgDaxBdbaDasBdlaocifhoaiaOfhiazaOfhxxekaxcbalRbbgHEgAaDc;:eSgDfhzaHcsGhCaHcl4hXdndnaHcs0mbazcefhOxekazhOavaiaX9RcsGcdtfydbhzkdndnaCmbaOcefhxxekaOhxavaiaH9RcsGcdtfydbhOkdndnaDTmbalcefhDxekalcdfhDal8SbegPcFeGhsdnaPcu9kmbalcofhAascFbGhscrhldninaD8SbbgPcFbGaltasVhsaPcu9kmeaDcefhDalcrfglc8J9hmbkaAhDxekaDcefhDkasce4cbasceG9R7amfgmhAkdndnaXcsSmbaDhsxekaDcefhsaD8SbbglcFeGhPdnalcu9kmbaDcvfhzaPcFbGhPcrhldninas8SbbgDcFbGaltaPVhPaDcu9kmeascefhsalcrfglc8J9hmbkazhsxekascefhskaPce4cbaPceG9R7amfgmhzkdndnaCcsSmbashlxekascefhlas8SbbgDcFeGhPdnaDcu9kmbascvfhOaPcFbGhPcrhDdninal8SbbgscFbGaDtaPVhPascu9kmealcefhlaDcrfgDc8J9hmbkaOhlxekalcefhlkaPce4cbaPceG9R7amfgmhOkdndnadcd9hmbabarcetfgDaA87ebaDclfaO87ebaDcdfaz87ebxekabarcdtfgDaABdbaDcwfaOBdbaDclfazBdbkavc;abfaocitfgDazBdbaDaABdlavaicdtfaABdbavc;abfaocefcsGcitfgDaOBdbaDazBdlavaicefgicsGcdtfazBdbavc;abfaocdfcsGcitfgDaABdbaDaOBdlavaiaHcz6aXcsSVfgicsGcdtfaOBdbaiaCTaCcsSVfhiaocifhokawcefhwaocsGhoaicsGhiarcifgrae6mbkkcbc99alaqSEhokavc;aef8Kjjjjbaok:clevu8Jjjjjbcz9Rhvdnaecvfal9nmbc9:skdnaiRbbc;:eGc;qeSmbcuskav9cb83iwaicefhoaialfc98fhrdnaeTmbdnadcdSmbcbhwindnaoar6mbc9:skaocefhlao8SbbgicFeGhddndnaicu9mmbalhoxekaocvfhoadcFbGhdcrhidninal8SbbgDcFbGaitadVhdaDcu9kmealcefhlaicrfgic8J9hmbxdkkalcefhokabawcdtfadc8Etc8F91adcd47avcwfadceGcdtVglydbfgiBdbalaiBdbawcefgwae9hmbxdkkcbhwindnaoar6mbc9:skaocefhlao8SbbgicFeGhddndnaicu9mmbalhoxekaocvfhoadcFbGhdcrhidninal8SbbgDcFbGaitadVhdaDcu9kmealcefhlaicrfgic8J9hmbxdkkalcefhokabawcetfadc8Etc8F91adcd47avcwfadceGcdtVglydbfgi87ebalaiBdbawcefgwae9hmbkkcbc99aoarSEk:Lvoeue99dud99eud99dndnadcl9hmbaeTmeindndnabcdfgd8Sbb:Yab8Sbbgi:Ygl:l:tabcefgv8Sbbgo:Ygr:l:tgwJbb;:9cawawNJbbbbawawJbbbb9GgDEgq:mgkaqaicb9iEalMgwawNakaqaocb9iEarMgqaqNMM:r:vglNJbbbZJbbb:;aDEMgr:lJbbb9p9DTmbar:Ohixekcjjjj94hikadai86bbdndnaqalNJbbbZJbbb:;aqJbbbb9GEMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkavad86bbdndnawalNJbbbZJbbb:;awJbbbb9GEMgw:lJbbb9p9DTmbaw:Ohdxekcjjjj94hdkabad86bbabclfhbaecufgembxdkkaeTmbindndnabclfgd8Ueb:Yab8Uebgi:Ygl:l:tabcdfgv8Uebgo:Ygr:l:tgwJb;:FSawawNJbbbbawawJbbbb9GgDEgq:mgkaqaicb9iEalMgwawNakaqaocb9iEarMgqaqNMM:r:vglNJbbbZJbbb:;aDEMgr:lJbbb9p9DTmbar:Ohixekcjjjj94hikadai87ebdndnaqalNJbbbZJbbb:;aqJbbbb9GEMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkavad87ebdndnawalNJbbbZJbbb:;awJbbbb9GEMgw:lJbbb9p9DTmbaw:Ohdxekcjjjj94hdkabad87ebabcwfhbaecufgembkkk::ioiue99dud99dud99dnaeTmbcbhiabhlindndnal8Uebgv:YgoJ:ji:1Salcof8UebgrciVgw:Y:vgDNJbbbZJbbb:;avcu9kEMgq:lJbbb9p9DTmbaq:Ohkxekcjjjj94hkkalclf8Uebhvalcdf8UebhxabaiarcefciGfcetfak87ebdndnax:YgqaDNJbbbZJbbb:;axcu9kEMgm:lJbbb9p9DTmbam:Ohxxekcjjjj94hxkabaiarciGfgkcd7cetfax87ebdndnav:YgmaDNJbbbZJbbb:;avcu9kEMgP:lJbbb9p9DTmbaP:Ohvxekcjjjj94hvkabaiarcufciGfcetfav87ebdndnawaw2:ZgPaPMaoaoN:taqaqN:tamamN:tgoJbbbbaoJbbbb9GE:raDNJbbbZMgD:lJbbb9p9DTmbaD:Ohrxekcjjjj94hrkabakcetfar87ebalcwfhlaiclfhiaecufgembkkk9mbdnadcd4ae2gdTmbinababydbgecwtcw91:Yaece91cjjj98Gcjjj;8if::NUdbabclfhbadcufgdmbkkk:Tvirud99eudndnadcl9hmbaeTmeindndnabRbbgiabcefgl8Sbbgvabcdfgo8Sbbgrf9R:YJbbuJabcifgwRbbgdce4adVgDcd4aDVgDcl4aDVgD:Z:vgqNJbbbZMgk:lJbbb9p9DTmbak:Ohxxekcjjjj94hxkaoax86bbdndnaraif:YaqNJbbbZMgk:lJbbb9p9DTmbak:Ohoxekcjjjj94hokalao86bbdndnavaifar9R:YaqNJbbbZMgk:lJbbb9p9DTmbak:Ohixekcjjjj94hikabai86bbdndnaDadcetGadceGV:ZaqNJbbbZMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkawad86bbabclfhbaecufgembxdkkaeTmbindndnab8Vebgiabcdfgl8Uebgvabclfgo8Uebgrf9R:YJbFu9habcofgw8Vebgdce4adVgDcd4aDVgDcl4aDVgDcw4aDVgD:Z:vgqNJbbbZMgk:lJbbb9p9DTmbak:Ohxxekcjjjj94hxkaoax87ebdndnaraif:YaqNJbbbZMgk:lJbbb9p9DTmbak:Ohoxekcjjjj94hokalao87ebdndnavaifar9R:YaqNJbbbZMgk:lJbbb9p9DTmbak:Ohixekcjjjj94hikabai87ebdndnaDadcetGadceGV:ZaqNJbbbZMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkawad87ebabcwfhbaecufgembkkk9teiucbcbyd:K1jjbgeabcifc98GfgbBd:K1jjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaik;teeeudndnaeabVciGTmbabhixekdndnadcz9pmbabhixekabhiinaiaeydbBdbaiaeydlBdlaiaeydwBdwaiaeydxBdxaeczfheaiczfhiadc9Wfgdcs0mbkkadcl6mbinaiaeydbBdbaeclfheaiclfhiadc98fgdci0mbkkdnadTmbinaiaeRbb86bbaicefhiaecefheadcufgdmbkkabk:3eedudndnabciGTmbabhixekaecFeGc:b:c:ew2hldndnadcz9pmbabhixekabhiinaialBdxaialBdwaialBdlaialBdbaiczfhiadc9Wfgdcs0mbkkadcl6mbinaialBdbaiclfhiadc98fgdci0mbkkdnadTmbinaiae86bbaicefhiadcufgdmbkkabkk81dbcjwk8Kbbbbdbbblbbbwbbbbbbbebbbdbbblbbbwbbbbc:Kwkl8WNbb",e="b9H79TebbbeKl9Gbb9Gvuuuuueu9Giuuub9Geueuixkbbebeeddddilve9Weeeviebeoweuec:q:6dkr;Neqo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bb8A9TW79O9V9Wt9F9KW9J9V9KW9wWVtW949c919M9MWVbdY9TW79O9V9Wt9F9KW9J9V9KW69U9KW949c919M9MWVblE9TW79O9V9Wt9F9KW9J9V9KW69U9KW949tWG91W9U9JWbvL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9p9JtboK9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9r919HtbrL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVT949WbwY9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVJ9V29VVbDl79IV9Rbqq:Ctklbzik9:evu8Jjjjjbcz9Rhbcbheincbhdcbhiinabcwfadfaicjuaead4ceGglE86bbaialfhiadcefgdcw9hmbkaec:q:yjjbfai86bbaecitc:q1jjbfab8Piw83ibaecefgecjd9hmbkk:183lYud97dur978Jjjjjbcj;kb9Rgv8Kjjjjbc9:hodnalTmbcuhoaiRbbgrc;WeGc:Ge9hmbarcsGgwce0mbc9:hoalcufadcd4cbawEgDadfgrcKcaawEgqaraq0Egk6mbaicefhxavaialfgmar9Rgoad;8qbbcj;abad9Uc;WFbGcjdadca0EhPdndndnadTmbaoadfhscbhzinaeaz9nmdamax9RaD6miabazad2fhHaxaDfhOaPaeaz9RazaPfae6EgAcsfgocl4cifcd4hCavcj;cbfaoc9WGgXcetfhQavcj;cbfaXci2fhLavcj;cbfaXfhKcbhYaoc;ab6h8AincbhodnawTmbaxaYcd4fRbbhokaocFeGhEcbh3avcj;cbfh5indndndndnaEa3cet4ciGgoc9:fPdebdkamaO9RaX6mwavcj;cbfa3aX2faOaX;8qbbaOaAfhOxdkavcj;cbfa3aX2fcbaX;8kbxekamaO9RaC6moaoclVcbawEhraOaCfhocbhidna8Ambamao9Rc;Gb6mbcbhlina5alfhidndndndndndnaOalco4fRbbgqciGarfPDbedibledibkaipxbbbbbbbbbbbbbbbbpklbxlkaiaopbblaopbbbg8Eclp:mea8EpmbzeHdOiAlCvXoQrLg8Ecdp:mea8EpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9og8Fpxiiiiiiiiiiiiiiiip8Jg8Ep5b9cjF;8;4;W;G;ab9:9cU1:Ngacitc:q1jjbfpbibaac:q:yjjbfRbbgapsa8Ep5e9cjF;8;4;W;G;ab9:9cU1:Nghcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPa8Fa8Ep9spklbaaaoclffahc:q:yjjbfRbbfhoxikaiaopbbwaopbbbg8Eclp:mea8EpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9og8Fpxssssssssssssssssp8Jg8Ep5b9cjF;8;4;W;G;ab9:9cU1:Ngacitc:q1jjbfpbibaac:q:yjjbfRbbgapsa8Ep5e9cjF;8;4;W;G;ab9:9cU1:Nghcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPa8Fa8Ep9spklbaaaocwffahc:q:yjjbfRbbfhoxdkaiaopbbbpklbaoczfhoxekaiaopbbdaoRbbgacitc:q1jjbfpbibaac:q:yjjbfRbbgapsaoRbeghcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPpklbaaaocdffahc:q:yjjbfRbbfhokdndndndndndnaqcd4ciGarfPDbedibledibkaiczfpxbbbbbbbbbbbbbbbbpklbxlkaiczfaopbblaopbbbg8Eclp:mea8EpmbzeHdOiAlCvXoQrLg8Ecdp:mea8EpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9og8Fpxiiiiiiiiiiiiiiiip8Jg8Ep5b9cjF;8;4;W;G;ab9:9cU1:Ngacitc:q1jjbfpbibaac:q:yjjbfRbbgapsa8Ep5e9cjF;8;4;W;G;ab9:9cU1:Nghcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPa8Fa8Ep9spklbaaaoclffahc:q:yjjbfRbbfhoxikaiczfaopbbwaopbbbg8Eclp:mea8EpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9og8Fpxssssssssssssssssp8Jg8Ep5b9cjF;8;4;W;G;ab9:9cU1:Ngacitc:q1jjbfpbibaac:q:yjjbfRbbgapsa8Ep5e9cjF;8;4;W;G;ab9:9cU1:Nghcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPa8Fa8Ep9spklbaaaocwffahc:q:yjjbfRbbfhoxdkaiczfaopbbbpklbaoczfhoxekaiczfaopbbdaoRbbgacitc:q1jjbfpbibaac:q:yjjbfRbbgapsaoRbeghcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPpklbaaaocdffahc:q:yjjbfRbbfhokdndndndndndnaqcl4ciGarfPDbedibledibkaicafpxbbbbbbbbbbbbbbbbpklbxlkaicafaopbblaopbbbg8Eclp:mea8EpmbzeHdOiAlCvXoQrLg8Ecdp:mea8EpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9og8Fpxiiiiiiiiiiiiiiiip8Jg8Ep5b9cjF;8;4;W;G;ab9:9cU1:Ngacitc:q1jjbfpbibaac:q:yjjbfRbbgapsa8Ep5e9cjF;8;4;W;G;ab9:9cU1:Nghcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPa8Fa8Ep9spklbaaaoclffahc:q:yjjbfRbbfhoxikaicafaopbbwaopbbbg8Eclp:mea8EpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9og8Fpxssssssssssssssssp8Jg8Ep5b9cjF;8;4;W;G;ab9:9cU1:Ngacitc:q1jjbfpbibaac:q:yjjbfRbbgapsa8Ep5e9cjF;8;4;W;G;ab9:9cU1:Nghcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPa8Fa8Ep9spklbaaaocwffahc:q:yjjbfRbbfhoxdkaicafaopbbbpklbaoczfhoxekaicafaopbbdaoRbbgacitc:q1jjbfpbibaac:q:yjjbfRbbgapsaoRbeghcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPpklbaaaocdffahc:q:yjjbfRbbfhokdndndndndndnaqco4arfPDbedibledibkaic8Wfpxbbbbbbbbbbbbbbbbpklbxlkaic8Wfaopbblaopbbbg8Eclp:mea8EpmbzeHdOiAlCvXoQrLg8Ecdp:mea8EpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9og8Fpxiiiiiiiiiiiiiiiip8Jg8Ep5b9cjF;8;4;W;G;ab9:9cU1:Ngicitc:q1jjbfpbibaic:q:yjjbfRbbgipsa8Ep5e9cjF;8;4;W;G;ab9:9cU1:Ngqcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPa8Fa8Ep9spklbaiaoclffaqc:q:yjjbfRbbfhoxikaic8Wfaopbbwaopbbbg8Eclp:mea8EpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9og8Fpxssssssssssssssssp8Jg8Ep5b9cjF;8;4;W;G;ab9:9cU1:Ngicitc:q1jjbfpbibaic:q:yjjbfRbbgipsa8Ep5e9cjF;8;4;W;G;ab9:9cU1:Ngqcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPa8Fa8Ep9spklbaiaocwffaqc:q:yjjbfRbbfhoxdkaic8Wfaopbbbpklbaoczfhoxekaic8WfaopbbdaoRbbgicitc:q1jjbfpbibaic:q:yjjbfRbbgipsaoRbegqcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPpklbaiaocdffaqc:q:yjjbfRbbfhokalc;abfhialcjefaX0meaihlamao9Rc;Fb0mbkkdnaiaX9pmbaici4hlinamao9RcK6mwa5aifhqdndndndndndnaOaico4fRbbalcoG4ciGarfPDbedibledibkaqpxbbbbbbbbbbbbbbbbpkbbxlkaqaopbblaopbbbg8Eclp:mea8EpmbzeHdOiAlCvXoQrLg8Ecdp:mea8EpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9og8Fpxiiiiiiiiiiiiiiiip8Jg8Ep5b9cjF;8;4;W;G;ab9:9cU1:Ngacitc:q1jjbfpbibaac:q:yjjbfRbbgapsa8Ep5e9cjF;8;4;W;G;ab9:9cU1:Nghcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPa8Fa8Ep9spkbbaaaoclffahc:q:yjjbfRbbfhoxikaqaopbbwaopbbbg8Eclp:mea8EpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9og8Fpxssssssssssssssssp8Jg8Ep5b9cjF;8;4;W;G;ab9:9cU1:Ngacitc:q1jjbfpbibaac:q:yjjbfRbbgapsa8Ep5e9cjF;8;4;W;G;ab9:9cU1:Nghcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPa8Fa8Ep9spkbbaaaocwffahc:q:yjjbfRbbfhoxdkaqaopbbbpkbbaoczfhoxekaqaopbbdaoRbbgacitc:q1jjbfpbibaac:q:yjjbfRbbgapsaoRbeghcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPpkbbaaaocdffahc:q:yjjbfRbbfhokalcdfhlaiczfgiaX6mbkkaohOaoTmoka5aXfh5a3cefg3cl9hmbkdndndndnawTmbasaYcd4fRbbglciGPlbedwbkaXTmdavcjdfaYfhlavaYfpbdbhgcbhoinalavcj;cbfaofpblbg8JaKaofpblbg8KpmbzeHdOiAlCvXoQrLg8LaQaofpblbg8MaLaofpblbg8NpmbzeHdOiAlCvXoQrLgypmbezHdiOAlvCXorQLg8Ecep9Ta8Epxeeeeeeeeeeeeeeeeg8Fp9op9Hp9rg8Eagp9Uggp9Abbbaladfglaga8Ea8Epmlvorlvorlvorlvorp9Uggp9Abbbaladfglaga8Ea8EpmwDqkwDqkwDqkwDqkp9Uggp9Abbbaladfglaga8Ea8EpmxmPsxmPsxmPsxmPsp9Uggp9Abbbaladfglaga8LaypmwDKYqk8AExm35Ps8E8Fg8Ecep9Ta8Ea8Fp9op9Hp9rg8Ep9Uggp9Abbbaladfglaga8Ea8Epmlvorlvorlvorlvorp9Uggp9Abbbaladfglaga8Ea8EpmwDqkwDqkwDqkwDqkp9Uggp9Abbbaladfglaga8Ea8EpmxmPsxmPsxmPsxmPsp9Uggp9Abbbaladfglaga8Ja8KpmwKDYq8AkEx3m5P8Es8Fg8Ja8Ma8NpmwKDYq8AkEx3m5P8Es8Fg8KpmbezHdiOAlvCXorQLg8Ecep9Ta8Ea8Fp9op9Hp9rg8Ep9Uggp9Abbbaladfglaga8Ea8Epmlvorlvorlvorlvorp9Uggp9Abbbaladfglaga8Ea8EpmwDqkwDqkwDqkwDqkp9Uggp9Abbbaladfglaga8Ea8EpmxmPsxmPsxmPsxmPsp9Uggp9Abbbaladfglaga8Ja8KpmwDKYqk8AExm35Ps8E8Fg8Ecep9Ta8Ea8Fp9op9Hp9rg8Ep9Ug8Fp9Abbbaladfgla8Fa8Ea8Epmlvorlvorlvorlvorp9Ug8Fp9Abbbaladfgla8Fa8Ea8EpmwDqkwDqkwDqkwDqkp9Ug8Fp9Abbbaladfgla8Fa8Ea8EpmxmPsxmPsxmPsxmPsp9Uggp9AbbbaladfhlaoczfgoaX6mbxikkaXTmeavcjdfaYfhlavaYfpbdbhgcbhoinalavcj;cbfaofpblbg8JaKaofpblbg8KpmbzeHdOiAlCvXoQrLg8LaQaofpblbg8MaLaofpblbg8NpmbzeHdOiAlCvXoQrLgypmbezHdiOAlvCXorQLg8Ecep:nea8Epxebebebebebebebebg8Fp9op:bep9rg8Eagp:oeggp9Abbbaladfglaga8Ea8Epmlvorlvorlvorlvorp:oeggp9Abbbaladfglaga8Ea8EpmwDqkwDqkwDqkwDqkp:oeggp9Abbbaladfglaga8Ea8EpmxmPsxmPsxmPsxmPsp:oeggp9Abbbaladfglaga8LaypmwDKYqk8AExm35Ps8E8Fg8Ecep:nea8Ea8Fp9op:bep9rg8Ep:oeggp9Abbbaladfglaga8Ea8Epmlvorlvorlvorlvorp:oeggp9Abbbaladfglaga8Ea8EpmwDqkwDqkwDqkwDqkp:oeggp9Abbbaladfglaga8Ea8EpmxmPsxmPsxmPsxmPsp:oeggp9Abbbaladfglaga8Ja8KpmwKDYq8AkEx3m5P8Es8Fg8Ja8Ma8NpmwKDYq8AkEx3m5P8Es8Fg8KpmbezHdiOAlvCXorQLg8Ecep:nea8Ea8Fp9op:bep9rg8Ep:oeggp9Abbbaladfglaga8Ea8Epmlvorlvorlvorlvorp:oeggp9Abbbaladfglaga8Ea8EpmwDqkwDqkwDqkwDqkp:oeggp9Abbbaladfglaga8Ea8EpmxmPsxmPsxmPsxmPsp:oeggp9Abbbaladfglaga8Ja8KpmwDKYqk8AExm35Ps8E8Fg8Ecep:nea8Ea8Fp9op:bep9rg8Ep:oeg8Fp9Abbbaladfgla8Fa8Ea8Epmlvorlvorlvorlvorp:oeg8Fp9Abbbaladfgla8Fa8Ea8EpmwDqkwDqkwDqkwDqkp:oeg8Fp9Abbbaladfgla8Fa8Ea8EpmxmPsxmPsxmPsxmPsp:oeggp9AbbbaladfhlaoczfgoaX6mbxdkkaXTmbcbhocbalcl4gl9Rc8FGhiavcjdfaYfhravaYfpbdbh8Finaravcj;cbfaofpblbggaKaofpblbg8JpmbzeHdOiAlCvXoQrLg8KaQaofpblbg8LaLaofpblbg8MpmbzeHdOiAlCvXoQrLg8NpmbezHdiOAlvCXorQLg8Eaip:Rea8Ealp:Sep9qg8Ea8Fp9rg8Fp9Abbbaradfgra8Fa8Ea8Epmlvorlvorlvorlvorp9rg8Fp9Abbbaradfgra8Fa8Ea8EpmwDqkwDqkwDqkwDqkp9rg8Fp9Abbbaradfgra8Fa8Ea8EpmxmPsxmPsxmPsxmPsp9rg8Fp9Abbbaradfgra8Fa8Ka8NpmwDKYqk8AExm35Ps8E8Fg8Eaip:Rea8Ealp:Sep9qg8Ep9rg8Fp9Abbbaradfgra8Fa8Ea8Epmlvorlvorlvorlvorp9rg8Fp9Abbbaradfgra8Fa8Ea8EpmwDqkwDqkwDqkwDqkp9rg8Fp9Abbbaradfgra8Fa8Ea8EpmxmPsxmPsxmPsxmPsp9rg8Fp9Abbbaradfgra8Faga8JpmwKDYq8AkEx3m5P8Es8Fgga8La8MpmwKDYq8AkEx3m5P8Es8Fg8JpmbezHdiOAlvCXorQLg8Eaip:Rea8Ealp:Sep9qg8Ep9rg8Fp9Abbbaradfgra8Fa8Ea8Epmlvorlvorlvorlvorp9rg8Fp9Abbbaradfgra8Fa8Ea8EpmwDqkwDqkwDqkwDqkp9rg8Fp9Abbbaradfgra8Fa8Ea8EpmxmPsxmPsxmPsxmPsp9rg8Fp9Abbbaradfgra8Faga8JpmwDKYqk8AExm35Ps8E8Fg8Eaip:Rea8Ealp:Sep9qg8Ep9rg8Fp9Abbbaradfgra8Fa8Ea8Epmlvorlvorlvorlvorp9rg8Fp9Abbbaradfgra8Fa8Ea8EpmwDqkwDqkwDqkwDqkp9rg8Fp9Abbbaradfgra8Fa8Ea8EpmxmPsxmPsxmPsxmPsp9rg8Fp9AbbbaradfhraoczfgoaX6mbkkaYclfgYad6mbkaHavcjdfaAad2;8qbbavavcjdfaAcufad2fad;8qbbaAazfhzc9:hoaOhxaOmbxlkkaeTmbaDalfhrcbhocuhlinaralaD9RglfaD6mdaPaeao9RaoaPfae6Eaofgoae6mbkaial9Rhxkcbc99amax9RakSEhoxekc9:hokavcj;kbf8Kjjjjbaokwbz:bjjjbk:TseHu8Jjjjjbc;ae9Rgv8Kjjjjbc9:hodnaeci9UgrcHfal0mbcuhoaiRbbgwc;WeGc;Ge9hmbawcsGgDce0mbavc;abfcFecje;8kbavcUf9cu83ibavc8Wf9cu83ibavcyf9cu83ibavcaf9cu83ibavcKf9cu83ibavczf9cu83ibav9cu83iwav9cu83ibaialfc9WfhqaicefgwarfhldnaeTmbcmcsaDceSEhkcbhxcbhmcbhrcbhicbhoindnalaq9nmbc9:hoxikdndnawRbbgDc;Ve0mbavc;abfaoaDcu7gPcl4fcsGcitfgsydlhzasydbhHdndnaDcsGgsak9pmbavaiaPfcsGcdtfydbaxasEhDaxasTgOfhxxekdndnascsSmbcehOasc987asamffcefhDxekalcefhDal8SbbgscFeGhPdndnascu9mmbaDhlxekalcvfhlaPcFbGhPcrhsdninaD8SbbgOcFbGastaPVhPaOcu9kmeaDcefhDascrfgsc8J9hmbxdkkaDcefhlkcehOaPce4cbaPceG9R7amfhDkaDhmkavc;abfaocitfgsaDBdbasazBdlavaicdtfaDBdbavc;abfaocefcsGcitfgsaHBdbasaDBdlaocdfhoaOaifhidnadcd9hmbabarcetfgsaH87ebasclfaD87ebascdfaz87ebxdkabarcdtfgsaHBdbascwfaDBdbasclfazBdbxekdnaDcpe0mbaxcefgOavaiaqaDcsGfRbbgscl49RcsGcdtfydbascz6gPEhDavaias9RcsGcdtfydbaOaPfgzascsGgOEhsaOThOdndnadcd9hmbabarcetfgHax87ebaHclfas87ebaHcdfaD87ebxekabarcdtfgHaxBdbaHcwfasBdbaHclfaDBdbkavaicdtfaxBdbavc;abfaocitfgHaDBdbaHaxBdlavaicefgicsGcdtfaDBdbavc;abfaocefcsGcitfgHasBdbaHaDBdlavaiaPfgicsGcdtfasBdbavc;abfaocdfcsGcitfgDaxBdbaDasBdlaocifhoaiaOfhiazaOfhxxekaxcbalRbbgHEgAaDc;:eSgDfhzaHcsGhCaHcl4hXdndnaHcs0mbazcefhOxekazhOavaiaX9RcsGcdtfydbhzkdndnaCmbaOcefhxxekaOhxavaiaH9RcsGcdtfydbhOkdndnaDTmbalcefhDxekalcdfhDal8SbegPcFeGhsdnaPcu9kmbalcofhAascFbGhscrhldninaD8SbbgPcFbGaltasVhsaPcu9kmeaDcefhDalcrfglc8J9hmbkaAhDxekaDcefhDkasce4cbasceG9R7amfgmhAkdndnaXcsSmbaDhsxekaDcefhsaD8SbbglcFeGhPdnalcu9kmbaDcvfhzaPcFbGhPcrhldninas8SbbgDcFbGaltaPVhPaDcu9kmeascefhsalcrfglc8J9hmbkazhsxekascefhskaPce4cbaPceG9R7amfgmhzkdndnaCcsSmbashlxekascefhlas8SbbgDcFeGhPdnaDcu9kmbascvfhOaPcFbGhPcrhDdninal8SbbgscFbGaDtaPVhPascu9kmealcefhlaDcrfgDc8J9hmbkaOhlxekalcefhlkaPce4cbaPceG9R7amfgmhOkdndnadcd9hmbabarcetfgDaA87ebaDclfaO87ebaDcdfaz87ebxekabarcdtfgDaABdbaDcwfaOBdbaDclfazBdbkavc;abfaocitfgDazBdbaDaABdlavaicdtfaABdbavc;abfaocefcsGcitfgDaOBdbaDazBdlavaicefgicsGcdtfazBdbavc;abfaocdfcsGcitfgDaABdbaDaOBdlavaiaHcz6aXcsSVfgicsGcdtfaOBdbaiaCTaCcsSVfhiaocifhokawcefhwaocsGhoaicsGhiarcifgrae6mbkkcbc99alaqSEhokavc;aef8Kjjjjbaok:clevu8Jjjjjbcz9Rhvdnaecvfal9nmbc9:skdnaiRbbc;:eGc;qeSmbcuskav9cb83iwaicefhoaialfc98fhrdnaeTmbdnadcdSmbcbhwindnaoar6mbc9:skaocefhlao8SbbgicFeGhddndnaicu9mmbalhoxekaocvfhoadcFbGhdcrhidninal8SbbgDcFbGaitadVhdaDcu9kmealcefhlaicrfgic8J9hmbxdkkalcefhokabawcdtfadc8Etc8F91adcd47avcwfadceGcdtVglydbfgiBdbalaiBdbawcefgwae9hmbxdkkcbhwindnaoar6mbc9:skaocefhlao8SbbgicFeGhddndnaicu9mmbalhoxekaocvfhoadcFbGhdcrhidninal8SbbgDcFbGaitadVhdaDcu9kmealcefhlaicrfgic8J9hmbxdkkalcefhokabawcetfadc8Etc8F91adcd47avcwfadceGcdtVglydbfgi87ebalaiBdbawcefgwae9hmbkkcbc99aoarSEk:2Pliur97eue978Jjjjjbc8W9Rhiaec98Ghldndnadcl9hmbdnalTmbcbhvabhdinadadpbbbgocKp:RecKp:Sep;6egraocwp:RecKp:Sep;6earp;Geaoczp:RecKp:Sep;6egwp;Gep;Kep;LegDpxbbbbbbbbbbbbbbbbp:2egqarpxbbbjbbbjbbbjbbbjgkp9op9rp;Kegrpxbb;:9cbb;:9cbb;:9cbb;:9cararp;MeaDaDp;Meawaqawakp9op9rp;Kegrarp;Mep;Kep;Kep;Jep;Negwp;Mepxbbn0bbn0bbn0bbn0gqp;KepxFbbbFbbbFbbbFbbbp9oaopxbbbFbbbFbbbFbbbFp9op9qarawp;Meaqp;Kecwp:RepxbFbbbFbbbFbbbFbbp9op9qaDawp;Meaqp;Keczp:RepxbbFbbbFbbbFbbbFbp9op9qpkbbadczfhdavclfgval6mbkkalaeSmeaipxbbbbbbbbbbbbbbbbgqpklbaiabalcdtfgdaeciGglcdtgv;8qbbdnalTmbaiaipblbgocKp:RecKp:Sep;6egraocwp:RecKp:Sep;6earp;Geaoczp:RecKp:Sep;6egwp;Gep;Kep;LegDaqp:2egqarpxbbbjbbbjbbbjbbbjgkp9op9rp;Kegrpxbb;:9cbb;:9cbb;:9cbb;:9cararp;MeaDaDp;Meawaqawakp9op9rp;Kegrarp;Mep;Kep;Kep;Jep;Negwp;Mepxbbn0bbn0bbn0bbn0gqp;KepxFbbbFbbbFbbbFbbbp9oaopxbbbFbbbFbbbFbbbFp9op9qarawp;Meaqp;Kecwp:RepxbFbbbFbbbFbbbFbbp9op9qaDawp;Meaqp;Keczp:RepxbbFbbbFbbbFbbbFbp9op9qpklbkadaiav;8qbbskaipxFubbFubbFubbFubbgxpklbdnalTmbcbhvabhdinadczfgmampbbbgopxbbbbbbFFbbbbbbFFgkp9oadpbbbgDaopmbediwDqkzHOAKY8AEgwczp:Reczp:Sep;6egraipblbaDaopmlvorxmPsCXQL358E8Fp9op;6eawczp:Sep;6egwp;Gearp;Gep;Kep;Legopxbbbbbbbbbbbbbbbbp:2egqarpxbbbjbbbjbbbjbbbjgPp9op9rp;Kegrpxb;:FSb;:FSb;:FSb;:FSararp;Meaoaop;MeawaqawaPp9op9rp;Kegrarp;Mep;Kep;Kep;Jep;Negwp;Mepxbbn0bbn0bbn0bbn0gqp;KepxFFbbFFbbFFbbFFbbp9oaoawp;Meaqp;Keczp:Rep9qgoarawp;Meaqp;KepxFFbbFFbbFFbbFFbbp9ogrpmwDKYqk8AExm35Ps8E8Fp9qpkbbadaDakp9oaoarpmbezHdiOAlvCXorQLp9qpkbbadcafhdavclfgval6mbkkalaeSmbaiczfpxbbbbbbbbbbbbbbbbgopklbaiaopklbaiabalcitfgdaeciGglcitgv;8qbbaiaxpkladnalTmbaiaipblzgopxbbbbbbFFbbbbbbFFgkp9oaipblbgDaopmbediwDqkzHOAKY8AEgwczp:Reczp:Sep;6egraipblaaDaopmlvorxmPsCXQL358E8Fp9op;6eawczp:Sep;6egwp;Gearp;Gep;Kep;Legopxbbbbbbbbbbbbbbbbp:2egqarpxbbbjbbbjbbbjbbbjgPp9op9rp;Kegrpxb;:FSb;:FSb;:FSb;:FSararp;Meaoaop;MeawaqawaPp9op9rp;Kegrarp;Mep;Kep;Kep;Jep;Negwp;Mepxbbn0bbn0bbn0bbn0gqp;KepxFFbbFFbbFFbbFFbbp9oaoawp;Meaqp;Keczp:Rep9qgoarawp;Meaqp;KepxFFbbFFbbFFbbFFbbp9ogrpmwDKYqk8AExm35Ps8E8Fp9qpklzaiaDakp9oaoarpmbezHdiOAlvCXorQLp9qpklbkadaiav;8qbbkk:Iwllue97euo978Jjjjjbca9Rhidnaec98GglTmbcbhvabhoinaocKfpx:ji:1S:ji:1S:ji:1S:ji:1SaopbbbgraoczfgwpbbbgDpmlvorxmPsCXQL358E8Fgqczp:Segkpxibbbibbbibbbibbbp9qgxp;6ep;Negmaxaxp:1ep;7egxaxp;KearaDpmbediwDqkzHOAKY8AEgxczp:Reczp:Sep;6egrarp;Meaxczp:Sep;6egDaDp;Meaqczp:Reczp:Sep;6egqaqp;Mep;Kep;Kep;Lepxbbbbbbbbbbbbbbbbp:4ep;Jep;Mepxbbn0bbn0bbn0bbn0gxp;KepxFFbbFFbbFFbbFFbbgPp9oamaDp;Meaxp;Keczp:Rep9qgDamarp;Meaxp;KeaPp9oamaqp;Meaxp;Keczp:Rep9qgxpmwDKYqk8AExm35Ps8E8Fgrp5eakclp:RegmpEi:T:j83ibawarp5bampEd:T:j83ibaocwfaDaxpmbezHdiOAlvCXorQLgxp5eampEe:T:j83ibaoaxp5bampEb:T:j83ibaocafhoavclfgval6mbkkdnalaeSmbaiczfpxbbbbbbbbbbbbbbbbgmpklbaiampklbaiabalcitfgoaeciGgvcitgw;8qbbdnavTmbaipx:ji:1S:ji:1S:ji:1S:ji:1SaipblbgraipblzgDpmlvorxmPsCXQL358E8Fgqczp:Segkpxibbbibbbibbbibbbp9qgxp;6ep;Negmaxaxp:1ep;7egxaxp;KearaDpmbediwDqkzHOAKY8AEgxczp:Reczp:Sep;6egrarp;Meaxczp:Sep;6egDaDp;Meaqczp:Reczp:Sep;6egqaqp;Mep;Kep;Kep;Lepxbbbbbbbbbbbbbbbbp:4ep;Jep;Mepxbbn0bbn0bbn0bbn0gxp;KepxFFbbFFbbFFbbFFbbgPp9oamaDp;Meaxp;Keczp:Rep9qgDamarp;Meaxp;KeaPp9oamaqp;Meaxp;Keczp:Rep9qgxpmwDKYqk8AExm35Ps8E8Fgrp5eakclp:RegmpEi:T:j83iKaiarp5bampEd:T:j83izaiaDaxpmbezHdiOAlvCXorQLgxp5eampEe:T:j83iwaiaxp5bampEb:T:j83ibkaoaiaw;8qbbkk;uddiue978Jjjjjbc;ab9Rhidnadcd4ae2glc98GgvTmbcbheabhdinadadpbbbgocwp:Recwp:Sep;6eaocep:SepxbbjFbbjFbbjFbbjFp9opxbbjZbbjZbbjZbbjZp:Uep;Mepkbbadczfhdaeclfgeav6mbkkdnavalSmbaic8WfpxbbbbbbbbbbbbbbbbgopklbaicafaopklbaiczfaopklbaiaopklbaiabavcdtfgdalciGgecdtgv;8qbbdnaeTmbaiaipblbgocwp:Recwp:Sep;6eaocep:SepxbbjFbbjFbbjFbbjFp9opxbbjZbbjZbbjZbbjZp:Uep;Mepklbkadaiav;8qbbkk:CPvdue97euw97eu8Jjjjjbc8W9Rhiaec98Ghldndnadcl9hmbaipxbbbbbbbbbbbbbbbbgvpklbdnalTmbcbhoabhdinadpbbbhradpxbbuJbbuJbbuJbbuJaipblbarcKp:Tep9qgwcep:Seawp9qgDcdp:SeaDp9qgDclp:SeaDp9qgqp;6ep;NegDarcwp:RecKp:SegkarpxFbbbFbbbFbbbFbbbgxp9ogmp:Uep;6ep;Mepxbbn0bbn0bbn0bbn0gPp;Kecwp:RepxbFbbbFbbbFbbbFbbp9oaDamakp:Xearczp:RecKp:Segrp:Uep;6ep;MeaPp;Keaxp9op9qaDamakarp:Uep:Xep;6ep;MeaPp;Keczp:RepxbbFbbbFbbbFbbbFbp9op9qaDaqawcep:Rep9oawpxebbbebbbebbbebbbp9op9qp;6ep;MeaPp;KecKp:Rep9qpkbbadczfhdaoclfgoal6mbkkalaeSmeaiavpklaaicafabalcdtfgdaeciGglcdtgo;8qbbaiavpklbdnalTmbaipblahraipxbbuJbbuJbbuJbbuJaipblbarcKp:Tep9qgwcep:Seawp9qgDcdp:SeaDp9qgDclp:SeaDp9qgqp;6ep;NegDarcwp:RecKp:SegkarpxFbbbFbbbFbbbFbbbgxp9ogmp:Uep;6ep;Mepxbbn0bbn0bbn0bbn0gPp;Kecwp:RepxbFbbbFbbbFbbbFbbp9oaDamakp:Xearczp:RecKp:Segrp:Uep;6ep;MeaPp;Keaxp9op9qaDamakarp:Uep:Xep;6ep;MeaPp;Keczp:RepxbbFbbbFbbbFbbbFbp9op9qaDaqawcep:Rep9oawpxebbbebbbebbbebbbp9op9qp;6ep;MeaPp;KecKp:Rep9qpklakadaicafao;8qbbskaipxbbbbbbbbbbbbbbbbgvpklbdnalTmbcbhoabhdinadczfgspxbFu9hbFu9hbFu9hbFu9hadpbbbgDaspbbbgPpmlvorxmPsCXQL358E8Fgmczp:Teaipblbp9qgrcep:Searp9qgwcdp:Seawp9qgwclp:Seawp9qgwcwp:Seawp9qgqp;6ep;NegwaDaPpmbediwDqkzHOAKY8AEgDpxFFbbFFbbFFbbFFbbgPp9ogkaDczp:Segxp:Ueamczp:Reczp:Segmp:Xep;6ep;Mepxbbn0bbn0bbn0bbn0gDp;KeaPp9oawakaxamp:Uep:Xep;6ep;MeaDp;Keczp:Rep9qgxawaqarcep:Rep9oarpxebbbebbbebbbebbbp9op9qp;6ep;MeaDp;Keczp:Reawamakp:Uep;6ep;MeaDp;KeaPp9op9qgrpmwDKYqk8AExm35Ps8E8FpkbbadaxarpmbezHdiOAlvCXorQLpkbbadcafhdaoclfgoal6mbkkalaeSmbaiczfpxbbbbbbbbbbbbbbbbgrpklbaiarpklbaiabalcitfgdaeciGglcitgo;8qbbaiavpkladnalTmbaipxbFu9hbFu9hbFu9hbFu9haipblbgDaipblzgPpmlvorxmPsCXQL358E8Fgmczp:Teaipblap9qgrcep:Searp9qgwcdp:Seawp9qgwclp:Seawp9qgwcwp:Seawp9qgqp;6ep;NegwaDaPpmbediwDqkzHOAKY8AEgDpxFFbbFFbbFFbbFFbbgPp9ogkaDczp:Segxp:Ueamczp:Reczp:Segmp:Xep;6ep;Mepxbbn0bbn0bbn0bbn0gDp;KeaPp9oawakaxamp:Uep:Xep;6ep;MeaDp;Keczp:Rep9qgxawaqarcep:Rep9oarpxebbbebbbebbbebbbp9op9qp;6ep;MeaDp;Keczp:Reawamakp:Uep;6ep;MeaDp;KeaPp9op9qgrpmwDKYqk8AExm35Ps8E8FpklzaiaxarpmbezHdiOAlvCXorQLpklbkadaiao;8qbbkk9teiucbcbydj1jjbgeabcifc98GfgbBdj1jjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaikkkebcjwklz:Dbb",t=new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,3,2,0,0,5,3,1,0,1,12,1,0,10,22,2,12,0,65,0,65,0,65,0,252,10,0,0,11,7,0,65,0,253,15,26,11]),i=new Uint8Array([32,0,65,2,1,106,34,33,3,128,11,4,13,64,6,253,10,7,15,116,127,5,8,12,40,16,19,54,20,9,27,255,113,17,42,67,24,23,146,148,18,14,22,45,70,69,56,114,101,21,25,63,75,136,108,28,118,29,73,115]);if(typeof WebAssembly!="object")return{supported:!1};var s=WebAssembly.validate(t)?a(e):a(n),r,o=WebAssembly.instantiate(s,{}).then(function(A){r=A.instance,r.exports.__wasm_call_ctors()});function a(A){for(var x=new Uint8Array(A.length),b=0;b<A.length;++b){var y=A.charCodeAt(b);x[b]=y>96?y-97:y>64?y-39:y+4}for(var _=0,b=0;b<A.length;++b)x[_++]=x[b]<60?i[x[b]]:(x[b]-60)*64+x[++b];return x.buffer.slice(0,_)}function l(A,x,b,y,_,S,C){var D=A.exports.sbrk,M=y+3&-4,I=D(M*_),L=D(S.length),T=new Uint8Array(A.exports.memory.buffer);T.set(S,L);var R=x(I,y,_,L,S.length);if(R==0&&C&&C(I,M,_),b.set(T.subarray(I,I+y*_)),D(I-D(0)),R!=0)throw new Error("Malformed buffer data: "+R)}var c={NONE:"",OCTAHEDRAL:"meshopt_decodeFilterOct",QUATERNION:"meshopt_decodeFilterQuat",EXPONENTIAL:"meshopt_decodeFilterExp",COLOR:"meshopt_decodeFilterColor"},h={ATTRIBUTES:"meshopt_decodeVertexBuffer",TRIANGLES:"meshopt_decodeIndexBuffer",INDICES:"meshopt_decodeIndexSequence"},d=[],f=0;function u(A){var x={object:new Worker(A),pending:0,requests:{}};return x.object.onmessage=function(b){var y=b.data;x.pending-=y.count,x.requests[y.id][y.action](y.value),delete x.requests[y.id]},x}function g(A){for(var x="self.ready = WebAssembly.instantiate(new Uint8Array(["+new Uint8Array(s)+"]), {}).then(function(result) { result.instance.exports.__wasm_call_ctors(); return result.instance; });self.onmessage = "+m.name+";"+l.toString()+m.toString(),b=new Blob([x],{type:"text/javascript"}),y=URL.createObjectURL(b),_=d.length;_<A;++_)d[_]=u(y);for(var _=A;_<d.length;++_)d[_].object.postMessage({});d.length=A,URL.revokeObjectURL(y)}function p(A,x,b,y,_){for(var S=d[0],C=1;C<d.length;++C)d[C].pending<S.pending&&(S=d[C]);return new Promise(function(D,M){var I=new Uint8Array(b),L=++f;S.pending+=A,S.requests[L]={resolve:D,reject:M},S.object.postMessage({id:L,count:A,size:x,source:I,mode:y,filter:_},[I.buffer])})}function m(A){var x=A.data;if(!x.id)return self.close();self.ready.then(function(b){try{var y=new Uint8Array(x.count*x.size);l(b,b.exports[x.mode],y,x.count,x.size,x.source,b.exports[x.filter]),self.postMessage({id:x.id,count:x.count,action:"resolve",value:y},[y.buffer])}catch(_){self.postMessage({id:x.id,count:x.count,action:"reject",value:_})}})}return{ready:o,supported:!0,useWorkers:function(A){g(A)},decodeVertexBuffer:function(A,x,b,y,_){l(r,r.exports.meshopt_decodeVertexBuffer,A,x,b,y,r.exports[c[_]])},decodeIndexBuffer:function(A,x,b,y){l(r,r.exports.meshopt_decodeIndexBuffer,A,x,b,y)},decodeIndexSequence:function(A,x,b,y){l(r,r.exports.meshopt_decodeIndexSequence,A,x,b,y)},decodeGltfBuffer:function(A,x,b,y,_,S){l(r,r.exports[h[_]],A,x,b,y,r.exports[c[S]])},decodeGltfBufferAsync:function(A,x,b,y,_){return d.length>0?p(A,x,b,h[y],c[_]):o.then(function(){var S=new Uint8Array(A*x);return l(r,r.exports[h[y]],S,A,x,b,r.exports[c[_]]),S})}}})();class WI{constructor(e=4){this.pool=e,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0,this.workerCreator=null}_initWorker(e){if(!this.workers[e]){const t=this.workerCreator();t.addEventListener("message",this._onMessage.bind(this,e)),this.workers[e]=t}}_getIdleWorker(){for(let e=0;e<this.pool;e++)if(!(this.workerStatus&1<<e))return e;return-1}_onMessage(e,t){const i=this.workersResolve[e];if(i&&i(t),this.queue.length){const{resolve:s,msg:r,transfer:o}=this.queue.shift();this.workersResolve[e]=s,this.workers[e].postMessage(r,o)}else this.workerStatus^=1<<e}setWorkerCreator(e){this.workerCreator=e}setWorkerLimit(e){this.pool=e}postMessage(e,t){return new Promise(i=>{const s=this._getIdleWorker();s!==-1?(this._initWorker(s),this.workerStatus|=1<<s,this.workersResolve[s]=i,this.workers[s].postMessage(e,t)):this.queue.push({resolve:i,msg:e,transfer:t})})}dispose(){this.workers.forEach(e=>e.terminate()),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}const HI=0,BA=2,XI=1,PA=2,qI=0,YI=1,KI=10,$I=0,LA=9,RA=15,kA=16,FA=22,OA=37,UA=43,NA=76,zA=83,GA=97,VA=100,QA=103,jA=109,WA=122,HA=123,XA=131,qA=132,YA=133,KA=134,$A=137,JA=138,ZA=139,e0=140,t0=141,i0=142,n0=145,s0=146,r0=148,o0=152,a0=153,l0=154,c0=155,h0=156,d0=157,u0=158,f0=165,p0=166,g0=1000054e3,m0=1000054001,A0=1000054004,x0=1000054005,Uu=1000066e3,b0=1000066004;let da=class{constructor(e,t,i,s){this._dataView=void 0,this._littleEndian=void 0,this._offset=void 0,this._dataView=new DataView(e.buffer,e.byteOffset+t,i),this._littleEndian=s,this._offset=0}_nextUint8(){const e=this._dataView.getUint8(this._offset);return this._offset+=1,e}_nextUint16(){const e=this._dataView.getUint16(this._offset,this._littleEndian);return this._offset+=2,e}_nextUint32(){const e=this._dataView.getUint32(this._offset,this._littleEndian);return this._offset+=4,e}_nextUint64(){const e=this._dataView.getUint32(this._offset,this._littleEndian)+4294967296*this._dataView.getUint32(this._offset+4,this._littleEndian);return this._offset+=8,e}_nextInt32(){const e=this._dataView.getInt32(this._offset,this._littleEndian);return this._offset+=4,e}_nextUint8Array(e){const t=new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+this._offset,e);return this._offset+=e,t}_skip(e){return this._offset+=e,this}_scan(e,t=0){const i=this._offset;let s=0;for(;this._dataView.getUint8(this._offset)!==t&&s<e;)s++,this._offset++;return s<e&&this._offset++,new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+i,s)}};const ai=[171,75,84,88,32,50,48,187,13,10,26,10];function y0(n){return new TextDecoder().decode(n)}function JI(n){const e=new Uint8Array(n.buffer,n.byteOffset,ai.length);if(e[0]!==ai[0]||e[1]!==ai[1]||e[2]!==ai[2]||e[3]!==ai[3]||e[4]!==ai[4]||e[5]!==ai[5]||e[6]!==ai[6]||e[7]!==ai[7]||e[8]!==ai[8]||e[9]!==ai[9]||e[10]!==ai[10]||e[11]!==ai[11])throw new Error("Missing KTX 2.0 identifier.");const t={vkFormat:0,typeSize:1,pixelWidth:0,pixelHeight:0,pixelDepth:0,layerCount:0,faceCount:1,levelCount:0,supercompressionScheme:0,levels:[],dataFormatDescriptor:[{vendorId:0,descriptorType:0,versionNumber:2,colorModel:0,colorPrimaries:1,transferFunction:2,flags:0,texelBlockDimension:[0,0,0,0],bytesPlane:[0,0,0,0,0,0,0,0],samples:[]}],keyValue:{},globalData:null},i=17*Uint32Array.BYTES_PER_ELEMENT,s=new da(n,ai.length,i,!0);t.vkFormat=s._nextUint32(),t.typeSize=s._nextUint32(),t.pixelWidth=s._nextUint32(),t.pixelHeight=s._nextUint32(),t.pixelDepth=s._nextUint32(),t.layerCount=s._nextUint32(),t.faceCount=s._nextUint32(),t.levelCount=s._nextUint32(),t.supercompressionScheme=s._nextUint32();const r=s._nextUint32(),o=s._nextUint32(),a=s._nextUint32(),l=s._nextUint32(),c=s._nextUint64(),h=s._nextUint64(),d=3*Math.max(t.levelCount,1)*8,f=new da(n,ai.length+i,d,!0);for(let G=0,j=Math.max(t.levelCount,1);G<j;G++)t.levels.push({levelData:new Uint8Array(n.buffer,n.byteOffset+f._nextUint64(),f._nextUint64()),uncompressedByteLength:f._nextUint64()});const u=new da(n,r,o,!0);u._skip(4);const g=u._nextUint16(),p=u._nextUint16(),m=u._nextUint16(),A=u._nextUint16(),x={vendorId:g,descriptorType:p,versionNumber:m,colorModel:u._nextUint8(),colorPrimaries:u._nextUint8(),transferFunction:u._nextUint8(),flags:u._nextUint8(),texelBlockDimension:[u._nextUint8(),u._nextUint8(),u._nextUint8(),u._nextUint8()],bytesPlane:[u._nextUint8(),u._nextUint8(),u._nextUint8(),u._nextUint8(),u._nextUint8(),u._nextUint8(),u._nextUint8(),u._nextUint8()],samples:[]},b=(A/4-6)/4;for(let G=0;G<b;G++){const j={bitOffset:u._nextUint16(),bitLength:u._nextUint8(),channelType:u._nextUint8(),samplePosition:[u._nextUint8(),u._nextUint8(),u._nextUint8(),u._nextUint8()],sampleLower:Number.NEGATIVE_INFINITY,sampleUpper:Number.POSITIVE_INFINITY};64&j.channelType?(j.sampleLower=u._nextInt32(),j.sampleUpper=u._nextInt32()):(j.sampleLower=u._nextUint32(),j.sampleUpper=u._nextUint32()),x.samples[G]=j}t.dataFormatDescriptor.length=0,t.dataFormatDescriptor.push(x);const y=new da(n,a,l,!0);for(;y._offset<l;){const G=y._nextUint32(),j=y._scan(G),oe=y0(j);if(t.keyValue[oe]=y._nextUint8Array(G-j.byteLength-1),oe.match(/^ktx/i)){const fe=y0(t.keyValue[oe]);t.keyValue[oe]=fe.substring(0,fe.lastIndexOf("\0"))}y._skip(G%4?4-G%4:0)}if(h<=0)return t;const _=new da(n,c,h,!0),S=_._nextUint16(),C=_._nextUint16(),D=_._nextUint32(),M=_._nextUint32(),I=_._nextUint32(),L=_._nextUint32(),T=[];for(let G=0,j=Math.max(t.levelCount,1);G<j;G++)T.push({imageFlags:_._nextUint32(),rgbSliceByteOffset:_._nextUint32(),rgbSliceByteLength:_._nextUint32(),alphaSliceByteOffset:_._nextUint32(),alphaSliceByteLength:_._nextUint32()});const R=c+_._offset,E=R+D,F=E+M,N=F+I,H=new Uint8Array(n.buffer,n.byteOffset+R,D),V=new Uint8Array(n.buffer,n.byteOffset+E,M),U=new Uint8Array(n.buffer,n.byteOffset+F,I),q=new Uint8Array(n.buffer,n.byteOffset+N,L);return t.globalData={endpointCount:S,selectorCount:C,imageDescs:T,endpointsData:H,selectorsData:V,tablesData:U,extendedData:q},t}let Nu,qn,zu;const Gu={env:{emscripten_notify_memory_growth:function(n){zu=new Uint8Array(qn.exports.memory.buffer)}}};let ZI=class{init(){return Nu||(Nu=typeof fetch<"u"?fetch("data:application/wasm;base64,"+v0).then(e=>e.arrayBuffer()).then(e=>WebAssembly.instantiate(e,Gu)).then(this._init):WebAssembly.instantiate(Buffer.from(v0,"base64"),Gu).then(this._init),Nu)}_init(e){qn=e.instance,Gu.env.emscripten_notify_memory_growth(0)}decode(e,t=0){if(!qn)throw new Error("ZSTDDecoder: Await .init() before decoding.");const i=e.byteLength,s=qn.exports.malloc(i);zu.set(e,s),t=t||Number(qn.exports.ZSTD_findDecompressedSize(s,i));const r=qn.exports.malloc(t),o=qn.exports.ZSTD_decompress(r,t,s,i),a=zu.slice(r,r+o);return qn.exports.free(s),qn.exports.free(r),a}};const v0="AGFzbQEAAAABpQEVYAF/AX9gAn9/AGADf39/AX9gBX9/f39/AX9gAX8AYAJ/fwF/YAR/f39/AX9gA39/fwBgBn9/f39/fwF/YAd/f39/f39/AX9gAn9/AX5gAn5+AX5gAABgBX9/f39/AGAGf39/f39/AGAIf39/f39/f38AYAl/f39/f39/f38AYAABf2AIf39/f39/f38Bf2ANf39/f39/f39/f39/fwF/YAF/AX4CJwEDZW52H2Vtc2NyaXB0ZW5fbm90aWZ5X21lbW9yeV9ncm93dGgABANpaAEFAAAFAgEFCwACAQABAgIFBQcAAwABDgsBAQcAEhMHAAUBDAQEAAANBwQCAgYCBAgDAwMDBgEACQkHBgICAAYGAgQUBwYGAwIGAAMCAQgBBwUGCgoEEQAEBAEIAwgDBQgDEA8IAAcABAUBcAECAgUEAQCAAgYJAX8BQaCgwAILB2AHBm1lbW9yeQIABm1hbGxvYwAoBGZyZWUAJgxaU1REX2lzRXJyb3IAaBlaU1REX2ZpbmREZWNvbXByZXNzZWRTaXplAFQPWlNURF9kZWNvbXByZXNzAEoGX3N0YXJ0ACQJBwEAQQELASQKussBaA8AIAAgACgCBCABajYCBAsZACAAKAIAIAAoAgRBH3F0QQAgAWtBH3F2CwgAIABBiH9LC34BBH9BAyEBIAAoAgQiA0EgTQRAIAAoAggiASAAKAIQTwRAIAAQDQ8LIAAoAgwiAiABRgRAQQFBAiADQSBJGw8LIAAgASABIAJrIANBA3YiBCABIARrIAJJIgEbIgJrIgQ2AgggACADIAJBA3RrNgIEIAAgBCgAADYCAAsgAQsUAQF/IAAgARACIQIgACABEAEgAgv3AQECfyACRQRAIABCADcCACAAQQA2AhAgAEIANwIIQbh/DwsgACABNgIMIAAgAUEEajYCECACQQRPBEAgACABIAJqIgFBfGoiAzYCCCAAIAMoAAA2AgAgAUF/ai0AACIBBEAgAEEIIAEQFGs2AgQgAg8LIABBADYCBEF/DwsgACABNgIIIAAgAS0AACIDNgIAIAJBfmoiBEEBTQRAIARBAWtFBEAgACABLQACQRB0IANyIgM2AgALIAAgAS0AAUEIdCADajYCAAsgASACakF/ai0AACIBRQRAIABBADYCBEFsDwsgAEEoIAEQFCACQQN0ams2AgQgAgsWACAAIAEpAAA3AAAgACABKQAINwAICy8BAX8gAUECdEGgHWooAgAgACgCAEEgIAEgACgCBGprQR9xdnEhAiAAIAEQASACCyEAIAFCz9bTvtLHq9lCfiAAfEIfiUKHla+vmLbem55/fgsdAQF/IAAoAgggACgCDEYEfyAAKAIEQSBGBUEACwuCBAEDfyACQYDAAE8EQCAAIAEgAhBnIAAPCyAAIAJqIQMCQCAAIAFzQQNxRQRAAkAgAkEBSARAIAAhAgwBCyAAQQNxRQRAIAAhAgwBCyAAIQIDQCACIAEtAAA6AAAgAUEBaiEBIAJBAWoiAiADTw0BIAJBA3ENAAsLAkAgA0F8cSIEQcAASQ0AIAIgBEFAaiIFSw0AA0AgAiABKAIANgIAIAIgASgCBDYCBCACIAEoAgg2AgggAiABKAIMNgIMIAIgASgCEDYCECACIAEoAhQ2AhQgAiABKAIYNgIYIAIgASgCHDYCHCACIAEoAiA2AiAgAiABKAIkNgIkIAIgASgCKDYCKCACIAEoAiw2AiwgAiABKAIwNgIwIAIgASgCNDYCNCACIAEoAjg2AjggAiABKAI8NgI8IAFBQGshASACQUBrIgIgBU0NAAsLIAIgBE8NAQNAIAIgASgCADYCACABQQRqIQEgAkEEaiICIARJDQALDAELIANBBEkEQCAAIQIMAQsgA0F8aiIEIABJBEAgACECDAELIAAhAgNAIAIgAS0AADoAACACIAEtAAE6AAEgAiABLQACOgACIAIgAS0AAzoAAyABQQRqIQEgAkEEaiICIARNDQALCyACIANJBEADQCACIAEtAAA6AAAgAUEBaiEBIAJBAWoiAiADRw0ACwsgAAsMACAAIAEpAAA3AAALQQECfyAAKAIIIgEgACgCEEkEQEEDDwsgACAAKAIEIgJBB3E2AgQgACABIAJBA3ZrIgE2AgggACABKAAANgIAQQALDAAgACABKAIANgAAC/cCAQJ/AkAgACABRg0AAkAgASACaiAASwRAIAAgAmoiBCABSw0BCyAAIAEgAhALDwsgACABc0EDcSEDAkACQCAAIAFJBEAgAwRAIAAhAwwDCyAAQQNxRQRAIAAhAwwCCyAAIQMDQCACRQ0EIAMgAS0AADoAACABQQFqIQEgAkF/aiECIANBAWoiA0EDcQ0ACwwBCwJAIAMNACAEQQNxBEADQCACRQ0FIAAgAkF/aiICaiIDIAEgAmotAAA6AAAgA0EDcQ0ACwsgAkEDTQ0AA0AgACACQXxqIgJqIAEgAmooAgA2AgAgAkEDSw0ACwsgAkUNAgNAIAAgAkF/aiICaiABIAJqLQAAOgAAIAINAAsMAgsgAkEDTQ0AIAIhBANAIAMgASgCADYCACABQQRqIQEgA0EEaiEDIARBfGoiBEEDSw0ACyACQQNxIQILIAJFDQADQCADIAEtAAA6AAAgA0EBaiEDIAFBAWohASACQX9qIgINAAsLIAAL8wICAn8BfgJAIAJFDQAgACACaiIDQX9qIAE6AAAgACABOgAAIAJBA0kNACADQX5qIAE6AAAgACABOgABIANBfWogAToAACAAIAE6AAIgAkEHSQ0AIANBfGogAToAACAAIAE6AAMgAkEJSQ0AIABBACAAa0EDcSIEaiIDIAFB/wFxQYGChAhsIgE2AgAgAyACIARrQXxxIgRqIgJBfGogATYCACAEQQlJDQAgAyABNgIIIAMgATYCBCACQXhqIAE2AgAgAkF0aiABNgIAIARBGUkNACADIAE2AhggAyABNgIUIAMgATYCECADIAE2AgwgAkFwaiABNgIAIAJBbGogATYCACACQWhqIAE2AgAgAkFkaiABNgIAIAQgA0EEcUEYciIEayICQSBJDQAgAa0iBUIghiAFhCEFIAMgBGohAQNAIAEgBTcDGCABIAU3AxAgASAFNwMIIAEgBTcDACABQSBqIQEgAkFgaiICQR9LDQALCyAACy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAIajYCACADCy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAFajYCACADCx8AIAAgASACKAIEEAg2AgAgARAEGiAAIAJBCGo2AgQLCAAgAGdBH3MLugUBDX8jAEEQayIKJAACfyAEQQNNBEAgCkEANgIMIApBDGogAyAEEAsaIAAgASACIApBDGpBBBAVIgBBbCAAEAMbIAAgACAESxsMAQsgAEEAIAEoAgBBAXRBAmoQECENQVQgAygAACIGQQ9xIgBBCksNABogAiAAQQVqNgIAIAMgBGoiAkF8aiEMIAJBeWohDiACQXtqIRAgAEEGaiELQQQhBSAGQQR2IQRBICAAdCIAQQFyIQkgASgCACEPQQAhAiADIQYCQANAIAlBAkggAiAPS3JFBEAgAiEHAkAgCARAA0AgBEH//wNxQf//A0YEQCAHQRhqIQcgBiAQSQR/IAZBAmoiBigAACAFdgUgBUEQaiEFIARBEHYLIQQMAQsLA0AgBEEDcSIIQQNGBEAgBUECaiEFIARBAnYhBCAHQQNqIQcMAQsLIAcgCGoiByAPSw0EIAVBAmohBQNAIAIgB0kEQCANIAJBAXRqQQA7AQAgAkEBaiECDAELCyAGIA5LQQAgBiAFQQN1aiIHIAxLG0UEQCAHKAAAIAVBB3EiBXYhBAwCCyAEQQJ2IQQLIAYhBwsCfyALQX9qIAQgAEF/anEiBiAAQQF0QX9qIgggCWsiEUkNABogBCAIcSIEQQAgESAEIABIG2shBiALCyEIIA0gAkEBdGogBkF/aiIEOwEAIAlBASAGayAEIAZBAUgbayEJA0AgCSAASARAIABBAXUhACALQX9qIQsMAQsLAn8gByAOS0EAIAcgBSAIaiIFQQN1aiIGIAxLG0UEQCAFQQdxDAELIAUgDCIGIAdrQQN0awshBSACQQFqIQIgBEUhCCAGKAAAIAVBH3F2IQQMAQsLQWwgCUEBRyAFQSBKcg0BGiABIAJBf2o2AgAgBiAFQQdqQQN1aiADawwBC0FQCyEAIApBEGokACAACwkAQQFBBSAAGwsMACAAIAEoAAA2AAALqgMBCn8jAEHwAGsiCiQAIAJBAWohDiAAQQhqIQtBgIAEIAVBf2p0QRB1IQxBACECQQEhBkEBIAV0IglBf2oiDyEIA0AgAiAORkUEQAJAIAEgAkEBdCINai8BACIHQf//A0YEQCALIAhBA3RqIAI2AgQgCEF/aiEIQQEhBwwBCyAGQQAgDCAHQRB0QRB1ShshBgsgCiANaiAHOwEAIAJBAWohAgwBCwsgACAFNgIEIAAgBjYCACAJQQN2IAlBAXZqQQNqIQxBACEAQQAhBkEAIQIDQCAGIA5GBEADQAJAIAAgCUYNACAKIAsgAEEDdGoiASgCBCIGQQF0aiICIAIvAQAiAkEBajsBACABIAUgAhAUayIIOgADIAEgAiAIQf8BcXQgCWs7AQAgASAEIAZBAnQiAmooAgA6AAIgASACIANqKAIANgIEIABBAWohAAwBCwsFIAEgBkEBdGouAQAhDUEAIQcDQCAHIA1ORQRAIAsgAkEDdGogBjYCBANAIAIgDGogD3EiAiAISw0ACyAHQQFqIQcMAQsLIAZBAWohBgwBCwsgCkHwAGokAAsjAEIAIAEQCSAAhUKHla+vmLbem55/fkLj3MqV/M7y9YV/fAsQACAAQn43AwggACABNgIACyQBAX8gAARAIAEoAgQiAgRAIAEoAgggACACEQEADwsgABAmCwsfACAAIAEgAi8BABAINgIAIAEQBBogACACQQRqNgIEC0oBAX9BoCAoAgAiASAAaiIAQX9MBEBBiCBBMDYCAEF/DwsCQCAAPwBBEHRNDQAgABBmDQBBiCBBMDYCAEF/DwtBoCAgADYCACABC9cBAQh/Qbp/IQoCQCACKAIEIgggAigCACIJaiIOIAEgAGtLDQBBbCEKIAkgBCADKAIAIgtrSw0AIAAgCWoiBCACKAIIIgxrIQ0gACABQWBqIg8gCyAJQQAQKSADIAkgC2o2AgACQAJAIAwgBCAFa00EQCANIQUMAQsgDCAEIAZrSw0CIAcgDSAFayIAaiIBIAhqIAdNBEAgBCABIAgQDxoMAgsgBCABQQAgAGsQDyEBIAIgACAIaiIINgIEIAEgAGshBAsgBCAPIAUgCEEBECkLIA4hCgsgCgubAgEBfyMAQYABayINJAAgDSADNgJ8AkAgAkEDSwRAQX8hCQwBCwJAAkACQAJAIAJBAWsOAwADAgELIAZFBEBBuH8hCQwEC0FsIQkgBS0AACICIANLDQMgACAHIAJBAnQiAmooAgAgAiAIaigCABA7IAEgADYCAEEBIQkMAwsgASAJNgIAQQAhCQwCCyAKRQRAQWwhCQwCC0EAIQkgC0UgDEEZSHINAUEIIAR0QQhqIQBBACECA0AgAiAATw0CIAJBQGshAgwAAAsAC0FsIQkgDSANQfwAaiANQfgAaiAFIAYQFSICEAMNACANKAJ4IgMgBEsNACAAIA0gDSgCfCAHIAggAxAYIAEgADYCACACIQkLIA1BgAFqJAAgCQsLACAAIAEgAhALGgsQACAALwAAIAAtAAJBEHRyCy8AAn9BuH8gAUEISQ0AGkFyIAAoAAQiAEF3Sw0AGkG4fyAAQQhqIgAgACABSxsLCwkAIAAgATsAAAsDAAELigYBBX8gACAAKAIAIgVBfnE2AgBBACAAIAVBAXZqQYQgKAIAIgQgAEYbIQECQAJAIAAoAgQiAkUNACACKAIAIgNBAXENACACQQhqIgUgA0EBdkF4aiIDQQggA0EISxtnQR9zQQJ0QYAfaiIDKAIARgRAIAMgAigCDDYCAAsgAigCCCIDBEAgAyACKAIMNgIECyACKAIMIgMEQCADIAIoAgg2AgALIAIgAigCACAAKAIAQX5xajYCAEGEICEAAkACQCABRQ0AIAEgAjYCBCABKAIAIgNBAXENASADQQF2QXhqIgNBCCADQQhLG2dBH3NBAnRBgB9qIgMoAgAgAUEIakYEQCADIAEoAgw2AgALIAEoAggiAwRAIAMgASgCDDYCBAsgASgCDCIDBEAgAyABKAIINgIAQYQgKAIAIQQLIAIgAigCACABKAIAQX5xajYCACABIARGDQAgASABKAIAQQF2akEEaiEACyAAIAI2AgALIAIoAgBBAXZBeGoiAEEIIABBCEsbZ0Efc0ECdEGAH2oiASgCACEAIAEgBTYCACACIAA2AgwgAkEANgIIIABFDQEgACAFNgIADwsCQCABRQ0AIAEoAgAiAkEBcQ0AIAJBAXZBeGoiAkEIIAJBCEsbZ0Efc0ECdEGAH2oiAigCACABQQhqRgRAIAIgASgCDDYCAAsgASgCCCICBEAgAiABKAIMNgIECyABKAIMIgIEQCACIAEoAgg2AgBBhCAoAgAhBAsgACAAKAIAIAEoAgBBfnFqIgI2AgACQCABIARHBEAgASABKAIAQQF2aiAANgIEIAAoAgAhAgwBC0GEICAANgIACyACQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgIoAgAhASACIABBCGoiAjYCACAAIAE2AgwgAEEANgIIIAFFDQEgASACNgIADwsgBUEBdkF4aiIBQQggAUEISxtnQR9zQQJ0QYAfaiICKAIAIQEgAiAAQQhqIgI2AgAgACABNgIMIABBADYCCCABRQ0AIAEgAjYCAAsLDgAgAARAIABBeGoQJQsLgAIBA38CQCAAQQ9qQXhxQYQgKAIAKAIAQQF2ayICEB1Bf0YNAAJAQYQgKAIAIgAoAgAiAUEBcQ0AIAFBAXZBeGoiAUEIIAFBCEsbZ0Efc0ECdEGAH2oiASgCACAAQQhqRgRAIAEgACgCDDYCAAsgACgCCCIBBEAgASAAKAIMNgIECyAAKAIMIgFFDQAgASAAKAIINgIAC0EBIQEgACAAKAIAIAJBAXRqIgI2AgAgAkEBcQ0AIAJBAXZBeGoiAkEIIAJBCEsbZ0Efc0ECdEGAH2oiAygCACECIAMgAEEIaiIDNgIAIAAgAjYCDCAAQQA2AgggAkUNACACIAM2AgALIAELtwIBA38CQAJAIABBASAAGyICEDgiAA0AAkACQEGEICgCACIARQ0AIAAoAgAiA0EBcQ0AIAAgA0EBcjYCACADQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgEoAgAgAEEIakYEQCABIAAoAgw2AgALIAAoAggiAQRAIAEgACgCDDYCBAsgACgCDCIBBEAgASAAKAIINgIACyACECchAkEAIQFBhCAoAgAhACACDQEgACAAKAIAQX5xNgIAQQAPCyACQQ9qQXhxIgMQHSICQX9GDQIgAkEHakF4cSIAIAJHBEAgACACaxAdQX9GDQMLAkBBhCAoAgAiAUUEQEGAICAANgIADAELIAAgATYCBAtBhCAgADYCACAAIANBAXRBAXI2AgAMAQsgAEUNAQsgAEEIaiEBCyABC7kDAQJ/IAAgA2ohBQJAIANBB0wEQANAIAAgBU8NAiAAIAItAAA6AAAgAEEBaiEAIAJBAWohAgwAAAsACyAEQQFGBEACQCAAIAJrIgZBB00EQCAAIAItAAA6AAAgACACLQABOgABIAAgAi0AAjoAAiAAIAItAAM6AAMgAEEEaiACIAZBAnQiBkHAHmooAgBqIgIQFyACIAZB4B5qKAIAayECDAELIAAgAhAMCyACQQhqIQIgAEEIaiEACwJAAkACQAJAIAUgAU0EQCAAIANqIQEgBEEBRyAAIAJrQQ9Kcg0BA0AgACACEAwgAkEIaiECIABBCGoiACABSQ0ACwwFCyAAIAFLBEAgACEBDAQLIARBAUcgACACa0EPSnINASAAIQMgAiEEA0AgAyAEEAwgBEEIaiEEIANBCGoiAyABSQ0ACwwCCwNAIAAgAhAHIAJBEGohAiAAQRBqIgAgAUkNAAsMAwsgACEDIAIhBANAIAMgBBAHIARBEGohBCADQRBqIgMgAUkNAAsLIAIgASAAa2ohAgsDQCABIAVPDQEgASACLQAAOgAAIAFBAWohASACQQFqIQIMAAALAAsLQQECfyAAIAAoArjgASIDNgLE4AEgACgCvOABIQQgACABNgK84AEgACABIAJqNgK44AEgACABIAQgA2tqNgLA4AELpgEBAX8gACAAKALs4QEQFjYCyOABIABCADcD+OABIABCADcDuOABIABBwOABakIANwMAIABBqNAAaiIBQYyAgOAANgIAIABBADYCmOIBIABCADcDiOEBIABCAzcDgOEBIABBrNABakHgEikCADcCACAAQbTQAWpB6BIoAgA2AgAgACABNgIMIAAgAEGYIGo2AgggACAAQaAwajYCBCAAIABBEGo2AgALYQEBf0G4fyEDAkAgAUEDSQ0AIAIgABAhIgFBA3YiADYCCCACIAFBAXE2AgQgAiABQQF2QQNxIgM2AgACQCADQX9qIgFBAksNAAJAIAFBAWsOAgEAAgtBbA8LIAAhAwsgAwsMACAAIAEgAkEAEC4LiAQCA38CfiADEBYhBCAAQQBBKBAQIQAgBCACSwRAIAQPCyABRQRAQX8PCwJAAkAgA0EBRg0AIAEoAAAiBkGo6r5pRg0AQXYhAyAGQXBxQdDUtMIBRw0BQQghAyACQQhJDQEgAEEAQSgQECEAIAEoAAQhASAAQQE2AhQgACABrTcDAEEADwsgASACIAMQLyIDIAJLDQAgACADNgIYQXIhAyABIARqIgVBf2otAAAiAkEIcQ0AIAJBIHEiBkUEQEFwIQMgBS0AACIFQacBSw0BIAVBB3GtQgEgBUEDdkEKaq2GIgdCA4h+IAd8IQggBEEBaiEECyACQQZ2IQMgAkECdiEFAkAgAkEDcUF/aiICQQJLBEBBACECDAELAkACQAJAIAJBAWsOAgECAAsgASAEai0AACECIARBAWohBAwCCyABIARqLwAAIQIgBEECaiEEDAELIAEgBGooAAAhAiAEQQRqIQQLIAVBAXEhBQJ+AkACQAJAIANBf2oiA0ECTQRAIANBAWsOAgIDAQtCfyAGRQ0DGiABIARqMQAADAMLIAEgBGovAACtQoACfAwCCyABIARqKAAArQwBCyABIARqKQAACyEHIAAgBTYCICAAIAI2AhwgACAHNwMAQQAhAyAAQQA2AhQgACAHIAggBhsiBzcDCCAAIAdCgIAIIAdCgIAIVBs+AhALIAMLWwEBf0G4fyEDIAIQFiICIAFNBH8gACACakF/ai0AACIAQQNxQQJ0QaAeaigCACACaiAAQQZ2IgFBAnRBsB5qKAIAaiAAQSBxIgBFaiABRSAAQQV2cWoFQbh/CwsdACAAKAKQ4gEQWiAAQQA2AqDiASAAQgA3A5DiAQu1AwEFfyMAQZACayIKJABBuH8hBgJAIAVFDQAgBCwAACIIQf8BcSEHAkAgCEF/TARAIAdBgn9qQQF2IgggBU8NAkFsIQYgB0GBf2oiBUGAAk8NAiAEQQFqIQdBACEGA0AgBiAFTwRAIAUhBiAIIQcMAwUgACAGaiAHIAZBAXZqIgQtAABBBHY6AAAgACAGQQFyaiAELQAAQQ9xOgAAIAZBAmohBgwBCwAACwALIAcgBU8NASAAIARBAWogByAKEFMiBhADDQELIAYhBEEAIQYgAUEAQTQQECEJQQAhBQNAIAQgBkcEQCAAIAZqIggtAAAiAUELSwRAQWwhBgwDBSAJIAFBAnRqIgEgASgCAEEBajYCACAGQQFqIQZBASAILQAAdEEBdSAFaiEFDAILAAsLQWwhBiAFRQ0AIAUQFEEBaiIBQQxLDQAgAyABNgIAQQFBASABdCAFayIDEBQiAXQgA0cNACAAIARqIAFBAWoiADoAACAJIABBAnRqIgAgACgCAEEBajYCACAJKAIEIgBBAkkgAEEBcXINACACIARBAWo2AgAgB0EBaiEGCyAKQZACaiQAIAYLxhEBDH8jAEHwAGsiBSQAQWwhCwJAIANBCkkNACACLwAAIQogAi8AAiEJIAIvAAQhByAFQQhqIAQQDgJAIAMgByAJIApqakEGaiIMSQ0AIAUtAAohCCAFQdgAaiACQQZqIgIgChAGIgsQAw0BIAVBQGsgAiAKaiICIAkQBiILEAMNASAFQShqIAIgCWoiAiAHEAYiCxADDQEgBUEQaiACIAdqIAMgDGsQBiILEAMNASAAIAFqIg9BfWohECAEQQRqIQZBASELIAAgAUEDakECdiIDaiIMIANqIgIgA2oiDiEDIAIhBCAMIQcDQCALIAMgEElxBEAgACAGIAVB2ABqIAgQAkECdGoiCS8BADsAACAFQdgAaiAJLQACEAEgCS0AAyELIAcgBiAFQUBrIAgQAkECdGoiCS8BADsAACAFQUBrIAktAAIQASAJLQADIQogBCAGIAVBKGogCBACQQJ0aiIJLwEAOwAAIAVBKGogCS0AAhABIAktAAMhCSADIAYgBUEQaiAIEAJBAnRqIg0vAQA7AAAgBUEQaiANLQACEAEgDS0AAyENIAAgC2oiCyAGIAVB2ABqIAgQAkECdGoiAC8BADsAACAFQdgAaiAALQACEAEgAC0AAyEAIAcgCmoiCiAGIAVBQGsgCBACQQJ0aiIHLwEAOwAAIAVBQGsgBy0AAhABIActAAMhByAEIAlqIgkgBiAFQShqIAgQAkECdGoiBC8BADsAACAFQShqIAQtAAIQASAELQADIQQgAyANaiIDIAYgBUEQaiAIEAJBAnRqIg0vAQA7AAAgBUEQaiANLQACEAEgACALaiEAIAcgCmohByAEIAlqIQQgAyANLQADaiEDIAVB2ABqEA0gBUFAaxANciAFQShqEA1yIAVBEGoQDXJFIQsMAQsLIAQgDksgByACS3INAEFsIQsgACAMSw0BIAxBfWohCQNAQQAgACAJSSAFQdgAahAEGwRAIAAgBiAFQdgAaiAIEAJBAnRqIgovAQA7AAAgBUHYAGogCi0AAhABIAAgCi0AA2oiACAGIAVB2ABqIAgQAkECdGoiCi8BADsAACAFQdgAaiAKLQACEAEgACAKLQADaiEADAEFIAxBfmohCgNAIAVB2ABqEAQgACAKS3JFBEAgACAGIAVB2ABqIAgQAkECdGoiCS8BADsAACAFQdgAaiAJLQACEAEgACAJLQADaiEADAELCwNAIAAgCk0EQCAAIAYgBUHYAGogCBACQQJ0aiIJLwEAOwAAIAVB2ABqIAktAAIQASAAIAktAANqIQAMAQsLAkAgACAMTw0AIAAgBiAFQdgAaiAIEAIiAEECdGoiDC0AADoAACAMLQADQQFGBEAgBUHYAGogDC0AAhABDAELIAUoAlxBH0sNACAFQdgAaiAGIABBAnRqLQACEAEgBSgCXEEhSQ0AIAVBIDYCXAsgAkF9aiEMA0BBACAHIAxJIAVBQGsQBBsEQCAHIAYgBUFAayAIEAJBAnRqIgAvAQA7AAAgBUFAayAALQACEAEgByAALQADaiIAIAYgBUFAayAIEAJBAnRqIgcvAQA7AAAgBUFAayAHLQACEAEgACAHLQADaiEHDAEFIAJBfmohDANAIAVBQGsQBCAHIAxLckUEQCAHIAYgBUFAayAIEAJBAnRqIgAvAQA7AAAgBUFAayAALQACEAEgByAALQADaiEHDAELCwNAIAcgDE0EQCAHIAYgBUFAayAIEAJBAnRqIgAvAQA7AAAgBUFAayAALQACEAEgByAALQADaiEHDAELCwJAIAcgAk8NACAHIAYgBUFAayAIEAIiAEECdGoiAi0AADoAACACLQADQQFGBEAgBUFAayACLQACEAEMAQsgBSgCREEfSw0AIAVBQGsgBiAAQQJ0ai0AAhABIAUoAkRBIUkNACAFQSA2AkQLIA5BfWohAgNAQQAgBCACSSAFQShqEAQbBEAgBCAGIAVBKGogCBACQQJ0aiIALwEAOwAAIAVBKGogAC0AAhABIAQgAC0AA2oiACAGIAVBKGogCBACQQJ0aiIELwEAOwAAIAVBKGogBC0AAhABIAAgBC0AA2ohBAwBBSAOQX5qIQIDQCAFQShqEAQgBCACS3JFBEAgBCAGIAVBKGogCBACQQJ0aiIALwEAOwAAIAVBKGogAC0AAhABIAQgAC0AA2ohBAwBCwsDQCAEIAJNBEAgBCAGIAVBKGogCBACQQJ0aiIALwEAOwAAIAVBKGogAC0AAhABIAQgAC0AA2ohBAwBCwsCQCAEIA5PDQAgBCAGIAVBKGogCBACIgBBAnRqIgItAAA6AAAgAi0AA0EBRgRAIAVBKGogAi0AAhABDAELIAUoAixBH0sNACAFQShqIAYgAEECdGotAAIQASAFKAIsQSFJDQAgBUEgNgIsCwNAQQAgAyAQSSAFQRBqEAQbBEAgAyAGIAVBEGogCBACQQJ0aiIALwEAOwAAIAVBEGogAC0AAhABIAMgAC0AA2oiACAGIAVBEGogCBACQQJ0aiICLwEAOwAAIAVBEGogAi0AAhABIAAgAi0AA2ohAwwBBSAPQX5qIQIDQCAFQRBqEAQgAyACS3JFBEAgAyAGIAVBEGogCBACQQJ0aiIALwEAOwAAIAVBEGogAC0AAhABIAMgAC0AA2ohAwwBCwsDQCADIAJNBEAgAyAGIAVBEGogCBACQQJ0aiIALwEAOwAAIAVBEGogAC0AAhABIAMgAC0AA2ohAwwBCwsCQCADIA9PDQAgAyAGIAVBEGogCBACIgBBAnRqIgItAAA6AAAgAi0AA0EBRgRAIAVBEGogAi0AAhABDAELIAUoAhRBH0sNACAFQRBqIAYgAEECdGotAAIQASAFKAIUQSFJDQAgBUEgNgIUCyABQWwgBUHYAGoQCiAFQUBrEApxIAVBKGoQCnEgBUEQahAKcRshCwwJCwAACwALAAALAAsAAAsACwAACwALQWwhCwsgBUHwAGokACALC7UEAQ5/IwBBEGsiBiQAIAZBBGogABAOQVQhBQJAIARB3AtJDQAgBi0ABCEHIANB8ARqQQBB7AAQECEIIAdBDEsNACADQdwJaiIJIAggBkEIaiAGQQxqIAEgAhAxIhAQA0UEQCAGKAIMIgQgB0sNASADQdwFaiEPIANBpAVqIREgAEEEaiESIANBqAVqIQEgBCEFA0AgBSICQX9qIQUgCCACQQJ0aigCAEUNAAsgAkEBaiEOQQEhBQNAIAUgDk9FBEAgCCAFQQJ0IgtqKAIAIQwgASALaiAKNgIAIAVBAWohBSAKIAxqIQoMAQsLIAEgCjYCAEEAIQUgBigCCCELA0AgBSALRkUEQCABIAUgCWotAAAiDEECdGoiDSANKAIAIg1BAWo2AgAgDyANQQF0aiINIAw6AAEgDSAFOgAAIAVBAWohBQwBCwtBACEBIANBADYCqAUgBEF/cyAHaiEJQQEhBQNAIAUgDk9FBEAgCCAFQQJ0IgtqKAIAIQwgAyALaiABNgIAIAwgBSAJanQgAWohASAFQQFqIQUMAQsLIAcgBEEBaiIBIAJrIgRrQQFqIQgDQEEBIQUgBCAIT0UEQANAIAUgDk9FBEAgBUECdCIJIAMgBEE0bGpqIAMgCWooAgAgBHY2AgAgBUEBaiEFDAELCyAEQQFqIQQMAQsLIBIgByAPIAogESADIAIgARBkIAZBAToABSAGIAc6AAYgACAGKAIENgIACyAQIQULIAZBEGokACAFC8ENAQt/IwBB8ABrIgUkAEFsIQkCQCADQQpJDQAgAi8AACEKIAIvAAIhDCACLwAEIQYgBUEIaiAEEA4CQCADIAYgCiAMampBBmoiDUkNACAFLQAKIQcgBUHYAGogAkEGaiICIAoQBiIJEAMNASAFQUBrIAIgCmoiAiAMEAYiCRADDQEgBUEoaiACIAxqIgIgBhAGIgkQAw0BIAVBEGogAiAGaiADIA1rEAYiCRADDQEgACABaiIOQX1qIQ8gBEEEaiEGQQEhCSAAIAFBA2pBAnYiAmoiCiACaiIMIAJqIg0hAyAMIQQgCiECA0AgCSADIA9JcQRAIAYgBUHYAGogBxACQQF0aiIILQAAIQsgBUHYAGogCC0AARABIAAgCzoAACAGIAVBQGsgBxACQQF0aiIILQAAIQsgBUFAayAILQABEAEgAiALOgAAIAYgBUEoaiAHEAJBAXRqIggtAAAhCyAFQShqIAgtAAEQASAEIAs6AAAgBiAFQRBqIAcQAkEBdGoiCC0AACELIAVBEGogCC0AARABIAMgCzoAACAGIAVB2ABqIAcQAkEBdGoiCC0AACELIAVB2ABqIAgtAAEQASAAIAs6AAEgBiAFQUBrIAcQAkEBdGoiCC0AACELIAVBQGsgCC0AARABIAIgCzoAASAGIAVBKGogBxACQQF0aiIILQAAIQsgBUEoaiAILQABEAEgBCALOgABIAYgBUEQaiAHEAJBAXRqIggtAAAhCyAFQRBqIAgtAAEQASADIAs6AAEgA0ECaiEDIARBAmohBCACQQJqIQIgAEECaiEAIAkgBUHYAGoQDUVxIAVBQGsQDUVxIAVBKGoQDUVxIAVBEGoQDUVxIQkMAQsLIAQgDUsgAiAMS3INAEFsIQkgACAKSw0BIApBfWohCQNAIAVB2ABqEAQgACAJT3JFBEAgBiAFQdgAaiAHEAJBAXRqIggtAAAhCyAFQdgAaiAILQABEAEgACALOgAAIAYgBUHYAGogBxACQQF0aiIILQAAIQsgBUHYAGogCC0AARABIAAgCzoAASAAQQJqIQAMAQsLA0AgBUHYAGoQBCAAIApPckUEQCAGIAVB2ABqIAcQAkEBdGoiCS0AACEIIAVB2ABqIAktAAEQASAAIAg6AAAgAEEBaiEADAELCwNAIAAgCkkEQCAGIAVB2ABqIAcQAkEBdGoiCS0AACEIIAVB2ABqIAktAAEQASAAIAg6AAAgAEEBaiEADAELCyAMQX1qIQADQCAFQUBrEAQgAiAAT3JFBEAgBiAFQUBrIAcQAkEBdGoiCi0AACEJIAVBQGsgCi0AARABIAIgCToAACAGIAVBQGsgBxACQQF0aiIKLQAAIQkgBUFAayAKLQABEAEgAiAJOgABIAJBAmohAgwBCwsDQCAFQUBrEAQgAiAMT3JFBEAgBiAFQUBrIAcQAkEBdGoiAC0AACEKIAVBQGsgAC0AARABIAIgCjoAACACQQFqIQIMAQsLA0AgAiAMSQRAIAYgBUFAayAHEAJBAXRqIgAtAAAhCiAFQUBrIAAtAAEQASACIAo6AAAgAkEBaiECDAELCyANQX1qIQADQCAFQShqEAQgBCAAT3JFBEAgBiAFQShqIAcQAkEBdGoiAi0AACEKIAVBKGogAi0AARABIAQgCjoAACAGIAVBKGogBxACQQF0aiICLQAAIQogBUEoaiACLQABEAEgBCAKOgABIARBAmohBAwBCwsDQCAFQShqEAQgBCANT3JFBEAgBiAFQShqIAcQAkEBdGoiAC0AACECIAVBKGogAC0AARABIAQgAjoAACAEQQFqIQQMAQsLA0AgBCANSQRAIAYgBUEoaiAHEAJBAXRqIgAtAAAhAiAFQShqIAAtAAEQASAEIAI6AAAgBEEBaiEEDAELCwNAIAVBEGoQBCADIA9PckUEQCAGIAVBEGogBxACQQF0aiIALQAAIQIgBUEQaiAALQABEAEgAyACOgAAIAYgBUEQaiAHEAJBAXRqIgAtAAAhAiAFQRBqIAAtAAEQASADIAI6AAEgA0ECaiEDDAELCwNAIAVBEGoQBCADIA5PckUEQCAGIAVBEGogBxACQQF0aiIALQAAIQIgBUEQaiAALQABEAEgAyACOgAAIANBAWohAwwBCwsDQCADIA5JBEAgBiAFQRBqIAcQAkEBdGoiAC0AACECIAVBEGogAC0AARABIAMgAjoAACADQQFqIQMMAQsLIAFBbCAFQdgAahAKIAVBQGsQCnEgBUEoahAKcSAFQRBqEApxGyEJDAELQWwhCQsgBUHwAGokACAJC8oCAQR/IwBBIGsiBSQAIAUgBBAOIAUtAAIhByAFQQhqIAIgAxAGIgIQA0UEQCAEQQRqIQIgACABaiIDQX1qIQQDQCAFQQhqEAQgACAET3JFBEAgAiAFQQhqIAcQAkEBdGoiBi0AACEIIAVBCGogBi0AARABIAAgCDoAACACIAVBCGogBxACQQF0aiIGLQAAIQggBUEIaiAGLQABEAEgACAIOgABIABBAmohAAwBCwsDQCAFQQhqEAQgACADT3JFBEAgAiAFQQhqIAcQAkEBdGoiBC0AACEGIAVBCGogBC0AARABIAAgBjoAACAAQQFqIQAMAQsLA0AgACADT0UEQCACIAVBCGogBxACQQF0aiIELQAAIQYgBUEIaiAELQABEAEgACAGOgAAIABBAWohAAwBCwsgAUFsIAVBCGoQChshAgsgBUEgaiQAIAILtgMBCX8jAEEQayIGJAAgBkEANgIMIAZBADYCCEFUIQQCQAJAIANBQGsiDCADIAZBCGogBkEMaiABIAIQMSICEAMNACAGQQRqIAAQDiAGKAIMIgcgBi0ABEEBaksNASAAQQRqIQogBkEAOgAFIAYgBzoABiAAIAYoAgQ2AgAgB0EBaiEJQQEhBANAIAQgCUkEQCADIARBAnRqIgEoAgAhACABIAU2AgAgACAEQX9qdCAFaiEFIARBAWohBAwBCwsgB0EBaiEHQQAhBSAGKAIIIQkDQCAFIAlGDQEgAyAFIAxqLQAAIgRBAnRqIgBBASAEdEEBdSILIAAoAgAiAWoiADYCACAHIARrIQhBACEEAkAgC0EDTQRAA0AgBCALRg0CIAogASAEakEBdGoiACAIOgABIAAgBToAACAEQQFqIQQMAAALAAsDQCABIABPDQEgCiABQQF0aiIEIAg6AAEgBCAFOgAAIAQgCDoAAyAEIAU6AAIgBCAIOgAFIAQgBToABCAEIAg6AAcgBCAFOgAGIAFBBGohAQwAAAsACyAFQQFqIQUMAAALAAsgAiEECyAGQRBqJAAgBAutAQECfwJAQYQgKAIAIABHIAAoAgBBAXYiAyABa0F4aiICQXhxQQhHcgR/IAIFIAMQJ0UNASACQQhqC0EQSQ0AIAAgACgCACICQQFxIAAgAWpBD2pBeHEiASAAa0EBdHI2AgAgASAANgIEIAEgASgCAEEBcSAAIAJBAXZqIAFrIgJBAXRyNgIAQYQgIAEgAkH/////B3FqQQRqQYQgKAIAIABGGyABNgIAIAEQJQsLygIBBX8CQAJAAkAgAEEIIABBCEsbZ0EfcyAAaUEBR2oiAUEESSAAIAF2cg0AIAFBAnRB/B5qKAIAIgJFDQADQCACQXhqIgMoAgBBAXZBeGoiBSAATwRAIAIgBUEIIAVBCEsbZ0Efc0ECdEGAH2oiASgCAEYEQCABIAIoAgQ2AgALDAMLIARBHksNASAEQQFqIQQgAigCBCICDQALC0EAIQMgAUEgTw0BA0AgAUECdEGAH2ooAgAiAkUEQCABQR5LIQIgAUEBaiEBIAJFDQEMAwsLIAIgAkF4aiIDKAIAQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgEoAgBGBEAgASACKAIENgIACwsgAigCACIBBEAgASACKAIENgIECyACKAIEIgEEQCABIAIoAgA2AgALIAMgAygCAEEBcjYCACADIAAQNwsgAwvhCwINfwV+IwBB8ABrIgckACAHIAAoAvDhASIINgJcIAEgAmohDSAIIAAoAoDiAWohDwJAAkAgBUUEQCABIQQMAQsgACgCxOABIRAgACgCwOABIREgACgCvOABIQ4gAEEBNgKM4QFBACEIA0AgCEEDRwRAIAcgCEECdCICaiAAIAJqQazQAWooAgA2AkQgCEEBaiEIDAELC0FsIQwgB0EYaiADIAQQBhADDQEgB0EsaiAHQRhqIAAoAgAQEyAHQTRqIAdBGGogACgCCBATIAdBPGogB0EYaiAAKAIEEBMgDUFgaiESIAEhBEEAIQwDQCAHKAIwIAcoAixBA3RqKQIAIhRCEIinQf8BcSEIIAcoAkAgBygCPEEDdGopAgAiFUIQiKdB/wFxIQsgBygCOCAHKAI0QQN0aikCACIWQiCIpyEJIBVCIIghFyAUQiCIpyECAkAgFkIQiKdB/wFxIgNBAk8EQAJAIAZFIANBGUlyRQRAIAkgB0EYaiADQSAgBygCHGsiCiAKIANLGyIKEAUgAyAKayIDdGohCSAHQRhqEAQaIANFDQEgB0EYaiADEAUgCWohCQwBCyAHQRhqIAMQBSAJaiEJIAdBGGoQBBoLIAcpAkQhGCAHIAk2AkQgByAYNwNIDAELAkAgA0UEQCACBEAgBygCRCEJDAMLIAcoAkghCQwBCwJAAkAgB0EYakEBEAUgCSACRWpqIgNBA0YEQCAHKAJEQX9qIgMgA0VqIQkMAQsgA0ECdCAHaigCRCIJIAlFaiEJIANBAUYNAQsgByAHKAJINgJMCwsgByAHKAJENgJIIAcgCTYCRAsgF6chAyALBEAgB0EYaiALEAUgA2ohAwsgCCALakEUTwRAIAdBGGoQBBoLIAgEQCAHQRhqIAgQBSACaiECCyAHQRhqEAQaIAcgB0EYaiAUQhiIp0H/AXEQCCAUp0H//wNxajYCLCAHIAdBGGogFUIYiKdB/wFxEAggFadB//8DcWo2AjwgB0EYahAEGiAHIAdBGGogFkIYiKdB/wFxEAggFqdB//8DcWo2AjQgByACNgJgIAcoAlwhCiAHIAk2AmggByADNgJkAkACQAJAIAQgAiADaiILaiASSw0AIAIgCmoiEyAPSw0AIA0gBGsgC0Egak8NAQsgByAHKQNoNwMQIAcgBykDYDcDCCAEIA0gB0EIaiAHQdwAaiAPIA4gESAQEB4hCwwBCyACIARqIQggBCAKEAcgAkERTwRAIARBEGohAgNAIAIgCkEQaiIKEAcgAkEQaiICIAhJDQALCyAIIAlrIQIgByATNgJcIAkgCCAOa0sEQCAJIAggEWtLBEBBbCELDAILIBAgAiAOayICaiIKIANqIBBNBEAgCCAKIAMQDxoMAgsgCCAKQQAgAmsQDyEIIAcgAiADaiIDNgJkIAggAmshCCAOIQILIAlBEE8EQCADIAhqIQMDQCAIIAIQByACQRBqIQIgCEEQaiIIIANJDQALDAELAkAgCUEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgCUECdCIDQcAeaigCAGoiAhAXIAIgA0HgHmooAgBrIQIgBygCZCEDDAELIAggAhAMCyADQQlJDQAgAyAIaiEDIAhBCGoiCCACQQhqIgJrQQ9MBEADQCAIIAIQDCACQQhqIQIgCEEIaiIIIANJDQAMAgALAAsDQCAIIAIQByACQRBqIQIgCEEQaiIIIANJDQALCyAHQRhqEAQaIAsgDCALEAMiAhshDCAEIAQgC2ogAhshBCAFQX9qIgUNAAsgDBADDQFBbCEMIAdBGGoQBEECSQ0BQQAhCANAIAhBA0cEQCAAIAhBAnQiAmpBrNABaiACIAdqKAJENgIAIAhBAWohCAwBCwsgBygCXCEIC0G6fyEMIA8gCGsiACANIARrSw0AIAQEfyAEIAggABALIABqBUEACyABayEMCyAHQfAAaiQAIAwLkRcCFn8FfiMAQdABayIHJAAgByAAKALw4QEiCDYCvAEgASACaiESIAggACgCgOIBaiETAkACQCAFRQRAIAEhAwwBCyAAKALE4AEhESAAKALA4AEhFSAAKAK84AEhDyAAQQE2AozhAUEAIQgDQCAIQQNHBEAgByAIQQJ0IgJqIAAgAmpBrNABaigCADYCVCAIQQFqIQgMAQsLIAcgETYCZCAHIA82AmAgByABIA9rNgJoQWwhECAHQShqIAMgBBAGEAMNASAFQQQgBUEESBshFyAHQTxqIAdBKGogACgCABATIAdBxABqIAdBKGogACgCCBATIAdBzABqIAdBKGogACgCBBATQQAhBCAHQeAAaiEMIAdB5ABqIQoDQCAHQShqEARBAksgBCAXTnJFBEAgBygCQCAHKAI8QQN0aikCACIdQhCIp0H/AXEhCyAHKAJQIAcoAkxBA3RqKQIAIh5CEIinQf8BcSEJIAcoAkggBygCREEDdGopAgAiH0IgiKchCCAeQiCIISAgHUIgiKchAgJAIB9CEIinQf8BcSIDQQJPBEACQCAGRSADQRlJckUEQCAIIAdBKGogA0EgIAcoAixrIg0gDSADSxsiDRAFIAMgDWsiA3RqIQggB0EoahAEGiADRQ0BIAdBKGogAxAFIAhqIQgMAQsgB0EoaiADEAUgCGohCCAHQShqEAQaCyAHKQJUISEgByAINgJUIAcgITcDWAwBCwJAIANFBEAgAgRAIAcoAlQhCAwDCyAHKAJYIQgMAQsCQAJAIAdBKGpBARAFIAggAkVqaiIDQQNGBEAgBygCVEF/aiIDIANFaiEIDAELIANBAnQgB2ooAlQiCCAIRWohCCADQQFGDQELIAcgBygCWDYCXAsLIAcgBygCVDYCWCAHIAg2AlQLICCnIQMgCQRAIAdBKGogCRAFIANqIQMLIAkgC2pBFE8EQCAHQShqEAQaCyALBEAgB0EoaiALEAUgAmohAgsgB0EoahAEGiAHIAcoAmggAmoiCSADajYCaCAKIAwgCCAJSxsoAgAhDSAHIAdBKGogHUIYiKdB/wFxEAggHadB//8DcWo2AjwgByAHQShqIB5CGIinQf8BcRAIIB6nQf//A3FqNgJMIAdBKGoQBBogB0EoaiAfQhiIp0H/AXEQCCEOIAdB8ABqIARBBHRqIgsgCSANaiAIazYCDCALIAg2AgggCyADNgIEIAsgAjYCACAHIA4gH6dB//8DcWo2AkQgBEEBaiEEDAELCyAEIBdIDQEgEkFgaiEYIAdB4ABqIRogB0HkAGohGyABIQMDQCAHQShqEARBAksgBCAFTnJFBEAgBygCQCAHKAI8QQN0aikCACIdQhCIp0H/AXEhCyAHKAJQIAcoAkxBA3RqKQIAIh5CEIinQf8BcSEIIAcoAkggBygCREEDdGopAgAiH0IgiKchCSAeQiCIISAgHUIgiKchDAJAIB9CEIinQf8BcSICQQJPBEACQCAGRSACQRlJckUEQCAJIAdBKGogAkEgIAcoAixrIgogCiACSxsiChAFIAIgCmsiAnRqIQkgB0EoahAEGiACRQ0BIAdBKGogAhAFIAlqIQkMAQsgB0EoaiACEAUgCWohCSAHQShqEAQaCyAHKQJUISEgByAJNgJUIAcgITcDWAwBCwJAIAJFBEAgDARAIAcoAlQhCQwDCyAHKAJYIQkMAQsCQAJAIAdBKGpBARAFIAkgDEVqaiICQQNGBEAgBygCVEF/aiICIAJFaiEJDAELIAJBAnQgB2ooAlQiCSAJRWohCSACQQFGDQELIAcgBygCWDYCXAsLIAcgBygCVDYCWCAHIAk2AlQLICCnIRQgCARAIAdBKGogCBAFIBRqIRQLIAggC2pBFE8EQCAHQShqEAQaCyALBEAgB0EoaiALEAUgDGohDAsgB0EoahAEGiAHIAcoAmggDGoiGSAUajYCaCAbIBogCSAZSxsoAgAhHCAHIAdBKGogHUIYiKdB/wFxEAggHadB//8DcWo2AjwgByAHQShqIB5CGIinQf8BcRAIIB6nQf//A3FqNgJMIAdBKGoQBBogByAHQShqIB9CGIinQf8BcRAIIB+nQf//A3FqNgJEIAcgB0HwAGogBEEDcUEEdGoiDSkDCCIdNwPIASAHIA0pAwAiHjcDwAECQAJAAkAgBygCvAEiDiAepyICaiIWIBNLDQAgAyAHKALEASIKIAJqIgtqIBhLDQAgEiADayALQSBqTw0BCyAHIAcpA8gBNwMQIAcgBykDwAE3AwggAyASIAdBCGogB0G8AWogEyAPIBUgERAeIQsMAQsgAiADaiEIIAMgDhAHIAJBEU8EQCADQRBqIQIDQCACIA5BEGoiDhAHIAJBEGoiAiAISQ0ACwsgCCAdpyIOayECIAcgFjYCvAEgDiAIIA9rSwRAIA4gCCAVa0sEQEFsIQsMAgsgESACIA9rIgJqIhYgCmogEU0EQCAIIBYgChAPGgwCCyAIIBZBACACaxAPIQggByACIApqIgo2AsQBIAggAmshCCAPIQILIA5BEE8EQCAIIApqIQoDQCAIIAIQByACQRBqIQIgCEEQaiIIIApJDQALDAELAkAgDkEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgDkECdCIKQcAeaigCAGoiAhAXIAIgCkHgHmooAgBrIQIgBygCxAEhCgwBCyAIIAIQDAsgCkEJSQ0AIAggCmohCiAIQQhqIgggAkEIaiICa0EPTARAA0AgCCACEAwgAkEIaiECIAhBCGoiCCAKSQ0ADAIACwALA0AgCCACEAcgAkEQaiECIAhBEGoiCCAKSQ0ACwsgCxADBEAgCyEQDAQFIA0gDDYCACANIBkgHGogCWs2AgwgDSAJNgIIIA0gFDYCBCAEQQFqIQQgAyALaiEDDAILAAsLIAQgBUgNASAEIBdrIQtBACEEA0AgCyAFSARAIAcgB0HwAGogC0EDcUEEdGoiAikDCCIdNwPIASAHIAIpAwAiHjcDwAECQAJAAkAgBygCvAEiDCAepyICaiIKIBNLDQAgAyAHKALEASIJIAJqIhBqIBhLDQAgEiADayAQQSBqTw0BCyAHIAcpA8gBNwMgIAcgBykDwAE3AxggAyASIAdBGGogB0G8AWogEyAPIBUgERAeIRAMAQsgAiADaiEIIAMgDBAHIAJBEU8EQCADQRBqIQIDQCACIAxBEGoiDBAHIAJBEGoiAiAISQ0ACwsgCCAdpyIGayECIAcgCjYCvAEgBiAIIA9rSwRAIAYgCCAVa0sEQEFsIRAMAgsgESACIA9rIgJqIgwgCWogEU0EQCAIIAwgCRAPGgwCCyAIIAxBACACaxAPIQggByACIAlqIgk2AsQBIAggAmshCCAPIQILIAZBEE8EQCAIIAlqIQYDQCAIIAIQByACQRBqIQIgCEEQaiIIIAZJDQALDAELAkAgBkEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgBkECdCIGQcAeaigCAGoiAhAXIAIgBkHgHmooAgBrIQIgBygCxAEhCQwBCyAIIAIQDAsgCUEJSQ0AIAggCWohBiAIQQhqIgggAkEIaiICa0EPTARAA0AgCCACEAwgAkEIaiECIAhBCGoiCCAGSQ0ADAIACwALA0AgCCACEAcgAkEQaiECIAhBEGoiCCAGSQ0ACwsgEBADDQMgC0EBaiELIAMgEGohAwwBCwsDQCAEQQNHBEAgACAEQQJ0IgJqQazQAWogAiAHaigCVDYCACAEQQFqIQQMAQsLIAcoArwBIQgLQbp/IRAgEyAIayIAIBIgA2tLDQAgAwR/IAMgCCAAEAsgAGoFQQALIAFrIRALIAdB0AFqJAAgEAslACAAQgA3AgAgAEEAOwEIIABBADoACyAAIAE2AgwgACACOgAKC7QFAQN/IwBBMGsiBCQAIABB/wFqIgVBfWohBgJAIAMvAQIEQCAEQRhqIAEgAhAGIgIQAw0BIARBEGogBEEYaiADEBwgBEEIaiAEQRhqIAMQHCAAIQMDQAJAIARBGGoQBCADIAZPckUEQCADIARBEGogBEEYahASOgAAIAMgBEEIaiAEQRhqEBI6AAEgBEEYahAERQ0BIANBAmohAwsgBUF+aiEFAn8DQEG6fyECIAMiASAFSw0FIAEgBEEQaiAEQRhqEBI6AAAgAUEBaiEDIARBGGoQBEEDRgRAQQIhAiAEQQhqDAILIAMgBUsNBSABIARBCGogBEEYahASOgABIAFBAmohA0EDIQIgBEEYahAEQQNHDQALIARBEGoLIQUgAyAFIARBGGoQEjoAACABIAJqIABrIQIMAwsgAyAEQRBqIARBGGoQEjoAAiADIARBCGogBEEYahASOgADIANBBGohAwwAAAsACyAEQRhqIAEgAhAGIgIQAw0AIARBEGogBEEYaiADEBwgBEEIaiAEQRhqIAMQHCAAIQMDQAJAIARBGGoQBCADIAZPckUEQCADIARBEGogBEEYahAROgAAIAMgBEEIaiAEQRhqEBE6AAEgBEEYahAERQ0BIANBAmohAwsgBUF+aiEFAn8DQEG6fyECIAMiASAFSw0EIAEgBEEQaiAEQRhqEBE6AAAgAUEBaiEDIARBGGoQBEEDRgRAQQIhAiAEQQhqDAILIAMgBUsNBCABIARBCGogBEEYahAROgABIAFBAmohA0EDIQIgBEEYahAEQQNHDQALIARBEGoLIQUgAyAFIARBGGoQEToAACABIAJqIABrIQIMAgsgAyAEQRBqIARBGGoQEToAAiADIARBCGogBEEYahAROgADIANBBGohAwwAAAsACyAEQTBqJAAgAgtpAQF/An8CQAJAIAJBB00NACABKAAAQbfIwuF+Rw0AIAAgASgABDYCmOIBQWIgAEEQaiABIAIQPiIDEAMNAhogAEKBgICAEDcDiOEBIAAgASADaiACIANrECoMAQsgACABIAIQKgtBAAsLrQMBBn8jAEGAAWsiAyQAQWIhCAJAIAJBCUkNACAAQZjQAGogAUEIaiIEIAJBeGogAEGY0AAQMyIFEAMiBg0AIANBHzYCfCADIANB/ABqIANB+ABqIAQgBCAFaiAGGyIEIAEgAmoiAiAEaxAVIgUQAw0AIAMoAnwiBkEfSw0AIAMoAngiB0EJTw0AIABBiCBqIAMgBkGAC0GADCAHEBggA0E0NgJ8IAMgA0H8AGogA0H4AGogBCAFaiIEIAIgBGsQFSIFEAMNACADKAJ8IgZBNEsNACADKAJ4IgdBCk8NACAAQZAwaiADIAZBgA1B4A4gBxAYIANBIzYCfCADIANB/ABqIANB+ABqIAQgBWoiBCACIARrEBUiBRADDQAgAygCfCIGQSNLDQAgAygCeCIHQQpPDQAgACADIAZBwBBB0BEgBxAYIAQgBWoiBEEMaiIFIAJLDQAgAiAFayEFQQAhAgNAIAJBA0cEQCAEKAAAIgZBf2ogBU8NAiAAIAJBAnRqQZzQAWogBjYCACACQQFqIQIgBEEEaiEEDAELCyAEIAFrIQgLIANBgAFqJAAgCAtGAQN/IABBCGohAyAAKAIEIQJBACEAA0AgACACdkUEQCABIAMgAEEDdGotAAJBFktqIQEgAEEBaiEADAELCyABQQggAmt0C4YDAQV/Qbh/IQcCQCADRQ0AIAItAAAiBEUEQCABQQA2AgBBAUG4fyADQQFGGw8LAn8gAkEBaiIFIARBGHRBGHUiBkF/Sg0AGiAGQX9GBEAgA0EDSA0CIAUvAABBgP4BaiEEIAJBA2oMAQsgA0ECSA0BIAItAAEgBEEIdHJBgIB+aiEEIAJBAmoLIQUgASAENgIAIAVBAWoiASACIANqIgNLDQBBbCEHIABBEGogACAFLQAAIgVBBnZBI0EJIAEgAyABa0HAEEHQEUHwEiAAKAKM4QEgACgCnOIBIAQQHyIGEAMiCA0AIABBmCBqIABBCGogBUEEdkEDcUEfQQggASABIAZqIAgbIgEgAyABa0GAC0GADEGAFyAAKAKM4QEgACgCnOIBIAQQHyIGEAMiCA0AIABBoDBqIABBBGogBUECdkEDcUE0QQkgASABIAZqIAgbIgEgAyABa0GADUHgDkGQGSAAKAKM4QEgACgCnOIBIAQQHyIAEAMNACAAIAFqIAJrIQcLIAcLrQMBCn8jAEGABGsiCCQAAn9BUiACQf8BSw0AGkFUIANBDEsNABogAkEBaiELIABBBGohCUGAgAQgA0F/anRBEHUhCkEAIQJBASEEQQEgA3QiB0F/aiIMIQUDQCACIAtGRQRAAkAgASACQQF0Ig1qLwEAIgZB//8DRgRAIAkgBUECdGogAjoAAiAFQX9qIQVBASEGDAELIARBACAKIAZBEHRBEHVKGyEECyAIIA1qIAY7AQAgAkEBaiECDAELCyAAIAQ7AQIgACADOwEAIAdBA3YgB0EBdmpBA2ohBkEAIQRBACECA0AgBCALRkUEQCABIARBAXRqLgEAIQpBACEAA0AgACAKTkUEQCAJIAJBAnRqIAQ6AAIDQCACIAZqIAxxIgIgBUsNAAsgAEEBaiEADAELCyAEQQFqIQQMAQsLQX8gAg0AGkEAIQIDfyACIAdGBH9BAAUgCCAJIAJBAnRqIgAtAAJBAXRqIgEgAS8BACIBQQFqOwEAIAAgAyABEBRrIgU6AAMgACABIAVB/wFxdCAHazsBACACQQFqIQIMAQsLCyEFIAhBgARqJAAgBQvjBgEIf0FsIQcCQCACQQNJDQACQAJAAkACQCABLQAAIgNBA3EiCUEBaw4DAwEAAgsgACgCiOEBDQBBYg8LIAJBBUkNAkEDIQYgASgAACEFAn8CQAJAIANBAnZBA3EiCEF+aiIEQQFNBEAgBEEBaw0BDAILIAVBDnZB/wdxIQQgBUEEdkH/B3EhAyAIRQwCCyAFQRJ2IQRBBCEGIAVBBHZB//8AcSEDQQAMAQsgBUEEdkH//w9xIgNBgIAISw0DIAEtAARBCnQgBUEWdnIhBEEFIQZBAAshBSAEIAZqIgogAksNAgJAIANBgQZJDQAgACgCnOIBRQ0AQQAhAgNAIAJBg4ABSw0BIAJBQGshAgwAAAsACwJ/IAlBA0YEQCABIAZqIQEgAEHw4gFqIQIgACgCDCEGIAUEQCACIAMgASAEIAYQXwwCCyACIAMgASAEIAYQXQwBCyAAQbjQAWohAiABIAZqIQEgAEHw4gFqIQYgAEGo0ABqIQggBQRAIAggBiADIAEgBCACEF4MAQsgCCAGIAMgASAEIAIQXAsQAw0CIAAgAzYCgOIBIABBATYCiOEBIAAgAEHw4gFqNgLw4QEgCUECRgRAIAAgAEGo0ABqNgIMCyAAIANqIgBBiOMBakIANwAAIABBgOMBakIANwAAIABB+OIBakIANwAAIABB8OIBakIANwAAIAoPCwJ/AkACQAJAIANBAnZBA3FBf2oiBEECSw0AIARBAWsOAgACAQtBASEEIANBA3YMAgtBAiEEIAEvAABBBHYMAQtBAyEEIAEQIUEEdgsiAyAEaiIFQSBqIAJLBEAgBSACSw0CIABB8OIBaiABIARqIAMQCyEBIAAgAzYCgOIBIAAgATYC8OEBIAEgA2oiAEIANwAYIABCADcAECAAQgA3AAggAEIANwAAIAUPCyAAIAM2AoDiASAAIAEgBGo2AvDhASAFDwsCfwJAAkACQCADQQJ2QQNxQX9qIgRBAksNACAEQQFrDgIAAgELQQEhByADQQN2DAILQQIhByABLwAAQQR2DAELIAJBBEkgARAhIgJBj4CAAUtyDQFBAyEHIAJBBHYLIQIgAEHw4gFqIAEgB2otAAAgAkEgahAQIQEgACACNgKA4gEgACABNgLw4QEgB0EBaiEHCyAHC0sAIABC+erQ0OfJoeThADcDICAAQgA3AxggAELP1tO+0ser2UI3AxAgAELW64Lu6v2J9eAANwMIIABCADcDACAAQShqQQBBKBAQGgviAgICfwV+IABBKGoiASAAKAJIaiECAn4gACkDACIDQiBaBEAgACkDECIEQgeJIAApAwgiBUIBiXwgACkDGCIGQgyJfCAAKQMgIgdCEol8IAUQGSAEEBkgBhAZIAcQGQwBCyAAKQMYQsXP2bLx5brqJ3wLIAN8IQMDQCABQQhqIgAgAk0EQEIAIAEpAAAQCSADhUIbiUKHla+vmLbem55/fkLj3MqV/M7y9YV/fCEDIAAhAQwBCwsCQCABQQRqIgAgAksEQCABIQAMAQsgASgAAK1Ch5Wvr5i23puef34gA4VCF4lCz9bTvtLHq9lCfkL5893xmfaZqxZ8IQMLA0AgACACSQRAIAAxAABCxc/ZsvHluuonfiADhUILiUKHla+vmLbem55/fiEDIABBAWohAAwBCwsgA0IhiCADhULP1tO+0ser2UJ+IgNCHYggA4VC+fPd8Zn2masWfiIDQiCIIAOFC+8CAgJ/BH4gACAAKQMAIAKtfDcDAAJAAkAgACgCSCIDIAJqIgRBH00EQCABRQ0BIAAgA2pBKGogASACECAgACgCSCACaiEEDAELIAEgAmohAgJ/IAMEQCAAQShqIgQgA2ogAUEgIANrECAgACAAKQMIIAQpAAAQCTcDCCAAIAApAxAgACkAMBAJNwMQIAAgACkDGCAAKQA4EAk3AxggACAAKQMgIABBQGspAAAQCTcDICAAKAJIIQMgAEEANgJIIAEgA2tBIGohAQsgAUEgaiACTQsEQCACQWBqIQMgACkDICEFIAApAxghBiAAKQMQIQcgACkDCCEIA0AgCCABKQAAEAkhCCAHIAEpAAgQCSEHIAYgASkAEBAJIQYgBSABKQAYEAkhBSABQSBqIgEgA00NAAsgACAFNwMgIAAgBjcDGCAAIAc3AxAgACAINwMICyABIAJPDQEgAEEoaiABIAIgAWsiBBAgCyAAIAQ2AkgLCy8BAX8gAEUEQEG2f0EAIAMbDwtBun8hBCADIAFNBH8gACACIAMQEBogAwVBun8LCy8BAX8gAEUEQEG2f0EAIAMbDwtBun8hBCADIAFNBH8gACACIAMQCxogAwVBun8LC6gCAQZ/IwBBEGsiByQAIABB2OABaikDAEKAgIAQViEIQbh/IQUCQCAEQf//B0sNACAAIAMgBBBCIgUQAyIGDQAgACgCnOIBIQkgACAHQQxqIAMgAyAFaiAGGyIKIARBACAFIAYbayIGEEAiAxADBEAgAyEFDAELIAcoAgwhBCABRQRAQbp/IQUgBEEASg0BCyAGIANrIQUgAyAKaiEDAkAgCQRAIABBADYCnOIBDAELAkACQAJAIARBBUgNACAAQdjgAWopAwBCgICACFgNAAwBCyAAQQA2ApziAQwBCyAAKAIIED8hBiAAQQA2ApziASAGQRRPDQELIAAgASACIAMgBSAEIAgQOSEFDAELIAAgASACIAMgBSAEIAgQOiEFCyAHQRBqJAAgBQtnACAAQdDgAWogASACIAAoAuzhARAuIgEQAwRAIAEPC0G4fyECAkAgAQ0AIABB7OABaigCACIBBEBBYCECIAAoApjiASABRw0BC0EAIQIgAEHw4AFqKAIARQ0AIABBkOEBahBDCyACCycBAX8QVyIERQRAQUAPCyAEIAAgASACIAMgBBBLEE8hACAEEFYgAAs/AQF/AkACQAJAIAAoAqDiAUEBaiIBQQJLDQAgAUEBaw4CAAECCyAAEDBBAA8LIABBADYCoOIBCyAAKAKU4gELvAMCB38BfiMAQRBrIgkkAEG4fyEGAkAgBCgCACIIQQVBCSAAKALs4QEiBRtJDQAgAygCACIHQQFBBSAFGyAFEC8iBRADBEAgBSEGDAELIAggBUEDakkNACAAIAcgBRBJIgYQAw0AIAEgAmohCiAAQZDhAWohCyAIIAVrIQIgBSAHaiEHIAEhBQNAIAcgAiAJECwiBhADDQEgAkF9aiICIAZJBEBBuH8hBgwCCyAJKAIAIghBAksEQEFsIQYMAgsgB0EDaiEHAn8CQAJAAkAgCEEBaw4CAgABCyAAIAUgCiAFayAHIAYQSAwCCyAFIAogBWsgByAGEEcMAQsgBSAKIAVrIActAAAgCSgCCBBGCyIIEAMEQCAIIQYMAgsgACgC8OABBEAgCyAFIAgQRQsgAiAGayECIAYgB2ohByAFIAhqIQUgCSgCBEUNAAsgACkD0OABIgxCf1IEQEFsIQYgDCAFIAFrrFINAQsgACgC8OABBEBBaiEGIAJBBEkNASALEEQhDCAHKAAAIAynRw0BIAdBBGohByACQXxqIQILIAMgBzYCACAEIAI2AgAgBSABayEGCyAJQRBqJAAgBgsuACAAECsCf0EAQQAQAw0AGiABRSACRXJFBEBBYiAAIAEgAhA9EAMNARoLQQALCzcAIAEEQCAAIAAoAsTgASABKAIEIAEoAghqRzYCnOIBCyAAECtBABADIAFFckUEQCAAIAEQWwsL0QIBB38jAEEQayIGJAAgBiAENgIIIAYgAzYCDCAFBEAgBSgCBCEKIAUoAgghCQsgASEIAkACQANAIAAoAuzhARAWIQsCQANAIAQgC0kNASADKAAAQXBxQdDUtMIBRgRAIAMgBBAiIgcQAw0EIAQgB2shBCADIAdqIQMMAQsLIAYgAzYCDCAGIAQ2AggCQCAFBEAgACAFEE5BACEHQQAQA0UNAQwFCyAAIAogCRBNIgcQAw0ECyAAIAgQUCAMQQFHQQAgACAIIAIgBkEMaiAGQQhqEEwiByIDa0EAIAMQAxtBCkdyRQRAQbh/IQcMBAsgBxADDQMgAiAHayECIAcgCGohCEEBIQwgBigCDCEDIAYoAgghBAwBCwsgBiADNgIMIAYgBDYCCEG4fyEHIAQNASAIIAFrIQcMAQsgBiADNgIMIAYgBDYCCAsgBkEQaiQAIAcLRgECfyABIAAoArjgASICRwRAIAAgAjYCxOABIAAgATYCuOABIAAoArzgASEDIAAgATYCvOABIAAgASADIAJrajYCwOABCwutAgIEfwF+IwBBQGoiBCQAAkACQCACQQhJDQAgASgAAEFwcUHQ1LTCAUcNACABIAIQIiEBIABCADcDCCAAQQA2AgQgACABNgIADAELIARBGGogASACEC0iAxADBEAgACADEBoMAQsgAwRAIABBuH8QGgwBCyACIAQoAjAiA2shAiABIANqIQMDQAJAIAAgAyACIARBCGoQLCIFEAMEfyAFBSACIAVBA2oiBU8NAUG4fwsQGgwCCyAGQQFqIQYgAiAFayECIAMgBWohAyAEKAIMRQ0ACyAEKAI4BEAgAkEDTQRAIABBuH8QGgwCCyADQQRqIQMLIAQoAighAiAEKQMYIQcgAEEANgIEIAAgAyABazYCACAAIAIgBmytIAcgB0J/URs3AwgLIARBQGskAAslAQF/IwBBEGsiAiQAIAIgACABEFEgAigCACEAIAJBEGokACAAC30BBH8jAEGQBGsiBCQAIARB/wE2AggCQCAEQRBqIARBCGogBEEMaiABIAIQFSIGEAMEQCAGIQUMAQtBVCEFIAQoAgwiB0EGSw0AIAMgBEEQaiAEKAIIIAcQQSIFEAMNACAAIAEgBmogAiAGayADEDwhBQsgBEGQBGokACAFC4cBAgJ/An5BABAWIQMCQANAIAEgA08EQAJAIAAoAABBcHFB0NS0wgFGBEAgACABECIiAhADRQ0BQn4PCyAAIAEQVSIEQn1WDQMgBCAFfCIFIARUIQJCfiEEIAINAyAAIAEQUiICEAMNAwsgASACayEBIAAgAmohAAwBCwtCfiAFIAEbIQQLIAQLPwIBfwF+IwBBMGsiAiQAAn5CfiACQQhqIAAgARAtDQAaQgAgAigCHEEBRg0AGiACKQMICyEDIAJBMGokACADC40BAQJ/IwBBMGsiASQAAkAgAEUNACAAKAKI4gENACABIABB/OEBaigCADYCKCABIAApAvThATcDICAAEDAgACgCqOIBIQIgASABKAIoNgIYIAEgASkDIDcDECACIAFBEGoQGyAAQQA2AqjiASABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALKgECfyMAQRBrIgAkACAAQQA2AgggAEIANwMAIAAQWCEBIABBEGokACABC4cBAQN/IwBBEGsiAiQAAkAgACgCAEUgACgCBEVzDQAgAiAAKAIINgIIIAIgACkCADcDAAJ/IAIoAgAiAQRAIAIoAghBqOMJIAERBQAMAQtBqOMJECgLIgFFDQAgASAAKQIANwL04QEgAUH84QFqIAAoAgg2AgAgARBZIAEhAwsgAkEQaiQAIAMLywEBAn8jAEEgayIBJAAgAEGBgIDAADYCtOIBIABBADYCiOIBIABBADYC7OEBIABCADcDkOIBIABBADYCpOMJIABBADYC3OIBIABCADcCzOIBIABBADYCvOIBIABBADYCxOABIABCADcCnOIBIABBpOIBakIANwIAIABBrOIBakEANgIAIAFCADcCECABQgA3AhggASABKQMYNwMIIAEgASkDEDcDACABKAIIQQh2QQFxIQIgAEEANgLg4gEgACACNgKM4gEgAUEgaiQAC3YBA38jAEEwayIBJAAgAARAIAEgAEHE0AFqIgIoAgA2AiggASAAKQK80AE3AyAgACgCACEDIAEgAigCADYCGCABIAApArzQATcDECADIAFBEGoQGyABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALzAEBAX8gACABKAK00AE2ApjiASAAIAEoAgQiAjYCwOABIAAgAjYCvOABIAAgAiABKAIIaiICNgK44AEgACACNgLE4AEgASgCuNABBEAgAEKBgICAEDcDiOEBIAAgAUGk0ABqNgIMIAAgAUGUIGo2AgggACABQZwwajYCBCAAIAFBDGo2AgAgAEGs0AFqIAFBqNABaigCADYCACAAQbDQAWogAUGs0AFqKAIANgIAIABBtNABaiABQbDQAWooAgA2AgAPCyAAQgA3A4jhAQs7ACACRQRAQbp/DwsgBEUEQEFsDwsgAiAEEGAEQCAAIAEgAiADIAQgBRBhDwsgACABIAIgAyAEIAUQZQtGAQF/IwBBEGsiBSQAIAVBCGogBBAOAn8gBS0ACQRAIAAgASACIAMgBBAyDAELIAAgASACIAMgBBA0CyEAIAVBEGokACAACzQAIAAgAyAEIAUQNiIFEAMEQCAFDwsgBSAESQR/IAEgAiADIAVqIAQgBWsgABA1BUG4fwsLRgEBfyMAQRBrIgUkACAFQQhqIAQQDgJ/IAUtAAkEQCAAIAEgAiADIAQQYgwBCyAAIAEgAiADIAQQNQshACAFQRBqJAAgAAtZAQF/QQ8hAiABIABJBEAgAUEEdCAAbiECCyAAQQh2IgEgAkEYbCIAQYwIaigCAGwgAEGICGooAgBqIgJBA3YgAmogAEGACGooAgAgAEGECGooAgAgAWxqSQs3ACAAIAMgBCAFQYAQEDMiBRADBEAgBQ8LIAUgBEkEfyABIAIgAyAFaiAEIAVrIAAQMgVBuH8LC78DAQN/IwBBIGsiBSQAIAVBCGogAiADEAYiAhADRQRAIAAgAWoiB0F9aiEGIAUgBBAOIARBBGohAiAFLQACIQMDQEEAIAAgBkkgBUEIahAEGwRAIAAgAiAFQQhqIAMQAkECdGoiBC8BADsAACAFQQhqIAQtAAIQASAAIAQtAANqIgQgAiAFQQhqIAMQAkECdGoiAC8BADsAACAFQQhqIAAtAAIQASAEIAAtAANqIQAMAQUgB0F+aiEEA0AgBUEIahAEIAAgBEtyRQRAIAAgAiAFQQhqIAMQAkECdGoiBi8BADsAACAFQQhqIAYtAAIQASAAIAYtAANqIQAMAQsLA0AgACAES0UEQCAAIAIgBUEIaiADEAJBAnRqIgYvAQA7AAAgBUEIaiAGLQACEAEgACAGLQADaiEADAELCwJAIAAgB08NACAAIAIgBUEIaiADEAIiA0ECdGoiAC0AADoAACAALQADQQFGBEAgBUEIaiAALQACEAEMAQsgBSgCDEEfSw0AIAVBCGogAiADQQJ0ai0AAhABIAUoAgxBIUkNACAFQSA2AgwLIAFBbCAFQQhqEAobIQILCwsgBUEgaiQAIAILkgIBBH8jAEFAaiIJJAAgCSADQTQQCyEDAkAgBEECSA0AIAMgBEECdGooAgAhCSADQTxqIAgQIyADQQE6AD8gAyACOgA+QQAhBCADKAI8IQoDQCAEIAlGDQEgACAEQQJ0aiAKNgEAIARBAWohBAwAAAsAC0EAIQkDQCAGIAlGRQRAIAMgBSAJQQF0aiIKLQABIgtBAnRqIgwoAgAhBCADQTxqIAotAABBCHQgCGpB//8DcRAjIANBAjoAPyADIAcgC2siCiACajoAPiAEQQEgASAKa3RqIQogAygCPCELA0AgACAEQQJ0aiALNgEAIARBAWoiBCAKSQ0ACyAMIAo2AgAgCUEBaiEJDAELCyADQUBrJAALowIBCX8jAEHQAGsiCSQAIAlBEGogBUE0EAsaIAcgBmshDyAHIAFrIRADQAJAIAMgCkcEQEEBIAEgByACIApBAXRqIgYtAAEiDGsiCGsiC3QhDSAGLQAAIQ4gCUEQaiAMQQJ0aiIMKAIAIQYgCyAPTwRAIAAgBkECdGogCyAIIAUgCEE0bGogCCAQaiIIQQEgCEEBShsiCCACIAQgCEECdGooAgAiCEEBdGogAyAIayAHIA4QYyAGIA1qIQgMAgsgCUEMaiAOECMgCUEBOgAPIAkgCDoADiAGIA1qIQggCSgCDCELA0AgBiAITw0CIAAgBkECdGogCzYBACAGQQFqIQYMAAALAAsgCUHQAGokAA8LIAwgCDYCACAKQQFqIQoMAAALAAs0ACAAIAMgBCAFEDYiBRADBEAgBQ8LIAUgBEkEfyABIAIgAyAFaiAEIAVrIAAQNAVBuH8LCyMAIAA/AEEQdGtB//8DakEQdkAAQX9GBEBBAA8LQQAQAEEBCzsBAX8gAgRAA0AgACABIAJBgCAgAkGAIEkbIgMQCyEAIAFBgCBqIQEgAEGAIGohACACIANrIgINAAsLCwYAIAAQAwsLqBUJAEGICAsNAQAAAAEAAAACAAAAAgBBoAgLswYBAAAAAQAAAAIAAAACAAAAJgAAAIIAAAAhBQAASgAAAGcIAAAmAAAAwAEAAIAAAABJBQAASgAAAL4IAAApAAAALAIAAIAAAABJBQAASgAAAL4IAAAvAAAAygIAAIAAAACKBQAASgAAAIQJAAA1AAAAcwMAAIAAAACdBQAASgAAAKAJAAA9AAAAgQMAAIAAAADrBQAASwAAAD4KAABEAAAAngMAAIAAAABNBgAASwAAAKoKAABLAAAAswMAAIAAAADBBgAATQAAAB8NAABNAAAAUwQAAIAAAAAjCAAAUQAAAKYPAABUAAAAmQQAAIAAAABLCQAAVwAAALESAABYAAAA2gQAAIAAAABvCQAAXQAAACMUAABUAAAARQUAAIAAAABUCgAAagAAAIwUAABqAAAArwUAAIAAAAB2CQAAfAAAAE4QAAB8AAAA0gIAAIAAAABjBwAAkQAAAJAHAACSAAAAAAAAAAEAAAABAAAABQAAAA0AAAAdAAAAPQAAAH0AAAD9AAAA/QEAAP0DAAD9BwAA/Q8AAP0fAAD9PwAA/X8AAP3/AAD9/wEA/f8DAP3/BwD9/w8A/f8fAP3/PwD9/38A/f//AP3//wH9//8D/f//B/3//w/9//8f/f//P/3//38AAAAAAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAABEAAAASAAAAEwAAABQAAAAVAAAAFgAAABcAAAAYAAAAGQAAABoAAAAbAAAAHAAAAB0AAAAeAAAAHwAAAAMAAAAEAAAABQAAAAYAAAAHAAAACAAAAAkAAAAKAAAACwAAAAwAAAANAAAADgAAAA8AAAAQAAAAEQAAABIAAAATAAAAFAAAABUAAAAWAAAAFwAAABgAAAAZAAAAGgAAABsAAAAcAAAAHQAAAB4AAAAfAAAAIAAAACEAAAAiAAAAIwAAACUAAAAnAAAAKQAAACsAAAAvAAAAMwAAADsAAABDAAAAUwAAAGMAAACDAAAAAwEAAAMCAAADBAAAAwgAAAMQAAADIAAAA0AAAAOAAAADAAEAQeAPC1EBAAAAAQAAAAEAAAABAAAAAgAAAAIAAAADAAAAAwAAAAQAAAAEAAAABQAAAAcAAAAIAAAACQAAAAoAAAALAAAADAAAAA0AAAAOAAAADwAAABAAQcQQC4sBAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAABIAAAAUAAAAFgAAABgAAAAcAAAAIAAAACgAAAAwAAAAQAAAAIAAAAAAAQAAAAIAAAAEAAAACAAAABAAAAAgAAAAQAAAAIAAAAAAAQBBkBIL5gQBAAAAAQAAAAEAAAABAAAAAgAAAAIAAAADAAAAAwAAAAQAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAAAEAAAAEAAAACAAAAAAAAAABAAEBBgAAAAAAAAQAAAAAEAAABAAAAAAgAAAFAQAAAAAAAAUDAAAAAAAABQQAAAAAAAAFBgAAAAAAAAUHAAAAAAAABQkAAAAAAAAFCgAAAAAAAAUMAAAAAAAABg4AAAAAAAEFEAAAAAAAAQUUAAAAAAABBRYAAAAAAAIFHAAAAAAAAwUgAAAAAAAEBTAAAAAgAAYFQAAAAAAABwWAAAAAAAAIBgABAAAAAAoGAAQAAAAADAYAEAAAIAAABAAAAAAAAAAEAQAAAAAAAAUCAAAAIAAABQQAAAAAAAAFBQAAACAAAAUHAAAAAAAABQgAAAAgAAAFCgAAAAAAAAULAAAAAAAABg0AAAAgAAEFEAAAAAAAAQUSAAAAIAABBRYAAAAAAAIFGAAAACAAAwUgAAAAAAADBSgAAAAAAAYEQAAAABAABgRAAAAAIAAHBYAAAAAAAAkGAAIAAAAACwYACAAAMAAABAAAAAAQAAAEAQAAACAAAAUCAAAAIAAABQMAAAAgAAAFBQAAACAAAAUGAAAAIAAABQgAAAAgAAAFCQAAACAAAAULAAAAIAAABQwAAAAAAAAGDwAAACAAAQUSAAAAIAABBRQAAAAgAAIFGAAAACAAAgUcAAAAIAADBSgAAAAgAAQFMAAAAAAAEAYAAAEAAAAPBgCAAAAAAA4GAEAAAAAADQYAIABBgBcLhwIBAAEBBQAAAAAAAAUAAAAAAAAGBD0AAAAAAAkF/QEAAAAADwX9fwAAAAAVBf3/HwAAAAMFBQAAAAAABwR9AAAAAAAMBf0PAAAAABIF/f8DAAAAFwX9/38AAAAFBR0AAAAAAAgE/QAAAAAADgX9PwAAAAAUBf3/DwAAAAIFAQAAABAABwR9AAAAAAALBf0HAAAAABEF/f8BAAAAFgX9/z8AAAAEBQ0AAAAQAAgE/QAAAAAADQX9HwAAAAATBf3/BwAAAAEFAQAAABAABgQ9AAAAAAAKBf0DAAAAABAF/f8AAAAAHAX9//8PAAAbBf3//wcAABoF/f//AwAAGQX9//8BAAAYBf3//wBBkBkLhgQBAAEBBgAAAAAAAAYDAAAAAAAABAQAAAAgAAAFBQAAAAAAAAUGAAAAAAAABQgAAAAAAAAFCQAAAAAAAAULAAAAAAAABg0AAAAAAAAGEAAAAAAAAAYTAAAAAAAABhYAAAAAAAAGGQAAAAAAAAYcAAAAAAAABh8AAAAAAAAGIgAAAAAAAQYlAAAAAAABBikAAAAAAAIGLwAAAAAAAwY7AAAAAAAEBlMAAAAAAAcGgwAAAAAACQYDAgAAEAAABAQAAAAAAAAEBQAAACAAAAUGAAAAAAAABQcAAAAgAAAFCQAAAAAAAAUKAAAAAAAABgwAAAAAAAAGDwAAAAAAAAYSAAAAAAAABhUAAAAAAAAGGAAAAAAAAAYbAAAAAAAABh4AAAAAAAAGIQAAAAAAAQYjAAAAAAABBicAAAAAAAIGKwAAAAAAAwYzAAAAAAAEBkMAAAAAAAUGYwAAAAAACAYDAQAAIAAABAQAAAAwAAAEBAAAABAAAAQFAAAAIAAABQcAAAAgAAAFCAAAACAAAAUKAAAAIAAABQsAAAAAAAAGDgAAAAAAAAYRAAAAAAAABhQAAAAAAAAGFwAAAAAAAAYaAAAAAAAABh0AAAAAAAAGIAAAAAAAEAYDAAEAAAAPBgOAAAAAAA4GA0AAAAAADQYDIAAAAAAMBgMQAAAAAAsGAwgAAAAACgYDBABBpB0L2QEBAAAAAwAAAAcAAAAPAAAAHwAAAD8AAAB/AAAA/wAAAP8BAAD/AwAA/wcAAP8PAAD/HwAA/z8AAP9/AAD//wAA//8BAP//AwD//wcA//8PAP//HwD//z8A//9/AP///wD///8B////A////wf///8P////H////z////9/AAAAAAEAAAACAAAABAAAAAAAAAACAAAABAAAAAgAAAAAAAAAAQAAAAIAAAABAAAABAAAAAQAAAAEAAAABAAAAAgAAAAIAAAACAAAAAcAAAAIAAAACQAAAAoAAAALAEGgIAsDwBBQ",eT="display-p3",tT="display-p3-linear";({...v.ColorManagement.spaces[v.SRGBColorSpace]});const Vu=new WeakMap;let Qu=0,ju;class zi extends v.Loader{constructor(e){super(e),this.transcoderPath="",this.transcoderBinary=null,this.transcoderPending=null,this.workerPool=new WI,this.workerSourceURL="",this.workerConfig=null,typeof MSC_TRANSCODER<"u"&&console.warn('THREE.KTX2Loader: Please update to latest "basis_transcoder". "msc_basis_transcoder" is no longer supported in three.js r125+.')}setTranscoderPath(e){return this.transcoderPath=e,this}setWorkerLimit(e){return this.workerPool.setWorkerLimit(e),this}async detectSupportAsync(e){return console.warn('KTX2Loader: "detectSupportAsync()" has been deprecated. Use "detectSupport()" and "await renderer.init();" when creating the renderer.'),await e.init(),this.detectSupport(e)}detectSupport(e){return e.isWebGPURenderer===!0?this.workerConfig={astcSupported:e.hasFeature("texture-compression-astc"),astcHDRSupported:!1,etc1Supported:e.hasFeature("texture-compression-etc1"),etc2Supported:e.hasFeature("texture-compression-etc2"),dxtSupported:e.hasFeature("texture-compression-s3tc"),bptcSupported:e.hasFeature("texture-compression-bc"),pvrtcSupported:e.hasFeature("texture-compression-pvrtc")}:(this.workerConfig={astcSupported:e.extensions.has("WEBGL_compressed_texture_astc"),astcHDRSupported:e.extensions.has("WEBGL_compressed_texture_astc")&&e.extensions.get("WEBGL_compressed_texture_astc").getSupportedProfiles().includes("hdr"),etc1Supported:e.extensions.has("WEBGL_compressed_texture_etc1"),etc2Supported:e.extensions.has("WEBGL_compressed_texture_etc"),dxtSupported:e.extensions.has("WEBGL_compressed_texture_s3tc"),bptcSupported:e.extensions.has("EXT_texture_compression_bptc"),pvrtcSupported:e.extensions.has("WEBGL_compressed_texture_pvrtc")||e.extensions.has("WEBKIT_WEBGL_compressed_texture_pvrtc")},typeof navigator<"u"&&typeof navigator.platform<"u"&&typeof navigator.userAgent<"u"&&navigator.platform.indexOf("Linux")>=0&&navigator.userAgent.indexOf("Firefox")>=0&&this.workerConfig.astcSupported&&this.workerConfig.etc2Supported&&this.workerConfig.bptcSupported&&this.workerConfig.dxtSupported&&(this.workerConfig.astcSupported=!1,this.workerConfig.etc2Supported=!1)),this}init(){if(!this.transcoderPending){const e=new v.FileLoader(this.manager);e.setPath(this.transcoderPath),e.setWithCredentials(this.withCredentials);const t=e.loadAsync("basis_transcoder.js"),i=new v.FileLoader(this.manager);i.setPath(this.transcoderPath),i.setResponseType("arraybuffer"),i.setWithCredentials(this.withCredentials);const s=i.loadAsync("basis_transcoder.wasm");this.transcoderPending=Promise.all([t,s]).then(([r,o])=>{const a=zi.BasisWorker.toString(),l=["/* constants */","let _EngineFormat = "+JSON.stringify(zi.EngineFormat),"let _EngineType = "+JSON.stringify(zi.EngineType),"let _TranscoderFormat = "+JSON.stringify(zi.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(zi.BasisFormat),"/* basis_transcoder.js */",r,"/* worker */",a.substring(a.indexOf("{")+1,a.lastIndexOf("}"))].join(`
|
|
4941
|
-
`);this.workerSourceURL=URL.createObjectURL(new Blob([l])),this.transcoderBinary=o,this.workerPool.setWorkerCreator(()=>{const c=new Worker(this.workerSourceURL),h=this.transcoderBinary.slice(0);return c.postMessage({type:"init",config:this.workerConfig,transcoderBinary:h},[h]),c})}),Qu>0&&console.warn("THREE.KTX2Loader: Multiple active KTX2 loaders may cause performance issues. Use a single KTX2Loader instance, or call .dispose() on old instances."),Qu++}return this.transcoderPending}load(e,t,i,s){if(this.workerConfig===null)throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.");const r=new v.FileLoader(this.manager);r.setPath(this.path),r.setCrossOrigin(this.crossOrigin),r.setWithCredentials(this.withCredentials),r.setRequestHeader(this.requestHeader),r.setResponseType("arraybuffer"),r.load(e,o=>{this.parse(o,t,s)},i,s)}parse(e,t,i){if(this.workerConfig===null)throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.");if(Vu.has(e))return Vu.get(e).promise.then(t).catch(i);this._createTexture(e).then(s=>t?t(s):null).catch(i)}_createTextureFrom(e,t){const{type:i,error:s,data:{faces:r,width:o,height:a,format:l,type:c,dfdFlags:h}}=e;if(i==="error")return Promise.reject(s);let d;if(t.faceCount===6)d=new v.CompressedCubeTexture(r,l,c);else{const f=r[0].mipmaps;d=t.layerCount>1?new v.CompressedArrayTexture(f,o,a,t.layerCount,l,c):new v.CompressedTexture(f,o,a,l,c)}return d.minFilter=r[0].mipmaps.length===1?v.LinearFilter:v.LinearMipmapLinearFilter,d.magFilter=v.LinearFilter,d.generateMipmaps=!1,d.needsUpdate=!0,d.colorSpace=_0(t),d.premultiplyAlpha=!!(h&XI),d}async _createTexture(e,t={}){const i=JI(new Uint8Array(e)),s=i.vkFormat===Uu&&i.dataFormatDescriptor[0].colorModel===167;if(!(i.vkFormat===$I||s&&!this.workerConfig.astcHDRSupported))return nT(i);const o=t,a=this.init().then(()=>this.workerPool.postMessage({type:"transcode",buffer:e,taskConfig:o},[e])).then(l=>this._createTextureFrom(l.data,i));return Vu.set(e,{promise:a}),a}dispose(){this.workerPool.dispose(),this.workerSourceURL&&URL.revokeObjectURL(this.workerSourceURL),Qu--}}zi.BasisFormat={ETC1S:0,UASTC:1,UASTC_HDR:2},zi.TranscoderFormat={ETC1:0,ETC2:1,BC1:2,BC3:3,BC4:4,BC5:5,BC7_M6_OPAQUE_ONLY:6,BC7_M5:7,PVRTC1_4_RGB:8,PVRTC1_4_RGBA:9,ASTC_4x4:10,ATC_RGB:11,ATC_RGBA_INTERPOLATED_ALPHA:12,RGBA32:13,RGB565:14,BGR565:15,RGBA4444:16,BC6H:22,RGB_HALF:24,RGBA_HALF:25},zi.EngineFormat={RGBAFormat:v.RGBAFormat,RGBA_ASTC_4x4_Format:v.RGBA_ASTC_4x4_Format,RGB_BPTC_UNSIGNED_Format:v.RGB_BPTC_UNSIGNED_Format,RGBA_BPTC_Format:v.RGBA_BPTC_Format,RGBA_ETC2_EAC_Format:v.RGBA_ETC2_EAC_Format,RGBA_PVRTC_4BPPV1_Format:v.RGBA_PVRTC_4BPPV1_Format,RGBA_S3TC_DXT5_Format:v.RGBA_S3TC_DXT5_Format,RGB_ETC1_Format:v.RGB_ETC1_Format,RGB_ETC2_Format:v.RGB_ETC2_Format,RGB_PVRTC_4BPPV1_Format:v.RGB_PVRTC_4BPPV1_Format,RGBA_S3TC_DXT1_Format:v.RGBA_S3TC_DXT1_Format},zi.EngineType={UnsignedByteType:v.UnsignedByteType,HalfFloatType:v.HalfFloatType,FloatType:v.FloatType},zi.BasisWorker=function(){let n,e,t;const i=_EngineFormat,s=_EngineType,r=_TranscoderFormat,o=_BasisFormat;self.addEventListener("message",function(g){const p=g.data;switch(p.type){case"init":n=p.config,a(p.transcoderBinary);break;case"transcode":e.then(()=>{try{const{faces:m,buffers:A,width:x,height:b,hasAlpha:y,format:_,type:S,dfdFlags:C}=l(p.buffer);self.postMessage({type:"transcode",id:p.id,data:{faces:m,width:x,height:b,hasAlpha:y,format:_,type:S,dfdFlags:C}},A)}catch(m){console.error(m),self.postMessage({type:"error",id:p.id,error:m.message})}});break}});function a(g){e=new Promise(p=>{t={wasmBinary:g,onRuntimeInitialized:p},BASIS(t)}).then(()=>{t.initializeBasis(),t.KTX2File===void 0&&console.warn("THREE.KTX2Loader: Please update Basis Universal transcoder.")})}function l(g){const p=new t.KTX2File(new Uint8Array(g));function m(){p.close(),p.delete()}if(!p.isValid())throw m(),new Error("THREE.KTX2Loader: Invalid or unsupported .ktx2 file");let A;if(p.isUASTC())A=o.UASTC;else if(p.isETC1S())A=o.ETC1S;else if(p.isHDR())A=o.UASTC_HDR;else throw new Error("THREE.KTX2Loader: Unknown Basis encoding");const x=p.getWidth(),b=p.getHeight(),y=p.getLayers()||1,_=p.getLevels(),S=p.getFaces(),C=p.getHasAlpha(),D=p.getDFDFlags(),{transcoderFormat:M,engineFormat:I,engineType:L}=d(A,x,b,C);if(!x||!b||!_)throw m(),new Error("THREE.KTX2Loader: Invalid texture");if(!p.startTranscoding())throw m(),new Error("THREE.KTX2Loader: .startTranscoding failed");const T=[],R=[];for(let E=0;E<S;E++){const F=[];for(let N=0;N<_;N++){const H=[];let V,U;for(let G=0;G<y;G++){const j=p.getImageLevelInfo(N,G,E);E===0&&N===0&&G===0&&(j.origWidth%4!==0||j.origHeight%4!==0)&&console.warn("THREE.KTX2Loader: ETC1S and UASTC textures should use multiple-of-four dimensions."),_>1?(V=j.origWidth,U=j.origHeight):(V=j.width,U=j.height);let oe=new Uint8Array(p.getImageTranscodedSizeInBytes(N,G,0,M));const fe=p.transcodeImage(oe,N,G,E,M,0,-1,-1);if(L===s.HalfFloatType&&(oe=new Uint16Array(oe.buffer,oe.byteOffset,oe.byteLength/Uint16Array.BYTES_PER_ELEMENT)),!fe)throw m(),new Error("THREE.KTX2Loader: .transcodeImage failed.");H.push(oe)}const q=u(H);F.push({data:q,width:V,height:U}),R.push(q.buffer)}T.push({mipmaps:F,width:x,height:b,format:I,type:L})}return m(),{faces:T,buffers:R,width:x,height:b,hasAlpha:C,dfdFlags:D,format:I,type:L}}const c=[{if:"astcSupported",basisFormat:[o.UASTC],transcoderFormat:[r.ASTC_4x4,r.ASTC_4x4],engineFormat:[i.RGBA_ASTC_4x4_Format,i.RGBA_ASTC_4x4_Format],engineType:[s.UnsignedByteType],priorityETC1S:1/0,priorityUASTC:1,needsPowerOfTwo:!1},{if:"bptcSupported",basisFormat:[o.ETC1S,o.UASTC],transcoderFormat:[r.BC7_M5,r.BC7_M5],engineFormat:[i.RGBA_BPTC_Format,i.RGBA_BPTC_Format],engineType:[s.UnsignedByteType],priorityETC1S:3,priorityUASTC:2,needsPowerOfTwo:!1},{if:"dxtSupported",basisFormat:[o.ETC1S,o.UASTC],transcoderFormat:[r.BC1,r.BC3],engineFormat:[i.RGBA_S3TC_DXT1_Format,i.RGBA_S3TC_DXT5_Format],engineType:[s.UnsignedByteType],priorityETC1S:4,priorityUASTC:5,needsPowerOfTwo:!1},{if:"etc2Supported",basisFormat:[o.ETC1S,o.UASTC],transcoderFormat:[r.ETC1,r.ETC2],engineFormat:[i.RGB_ETC2_Format,i.RGBA_ETC2_EAC_Format],engineType:[s.UnsignedByteType],priorityETC1S:1,priorityUASTC:3,needsPowerOfTwo:!1},{if:"etc1Supported",basisFormat:[o.ETC1S,o.UASTC],transcoderFormat:[r.ETC1],engineFormat:[i.RGB_ETC1_Format],engineType:[s.UnsignedByteType],priorityETC1S:2,priorityUASTC:4,needsPowerOfTwo:!1},{if:"pvrtcSupported",basisFormat:[o.ETC1S,o.UASTC],transcoderFormat:[r.PVRTC1_4_RGB,r.PVRTC1_4_RGBA],engineFormat:[i.RGB_PVRTC_4BPPV1_Format,i.RGBA_PVRTC_4BPPV1_Format],engineType:[s.UnsignedByteType],priorityETC1S:5,priorityUASTC:6,needsPowerOfTwo:!0},{if:"bptcSupported",basisFormat:[o.UASTC_HDR],transcoderFormat:[r.BC6H],engineFormat:[i.RGB_BPTC_UNSIGNED_Format],engineType:[s.HalfFloatType],priorityHDR:1,needsPowerOfTwo:!1},{basisFormat:[o.ETC1S,o.UASTC],transcoderFormat:[r.RGBA32,r.RGBA32],engineFormat:[i.RGBAFormat,i.RGBAFormat],engineType:[s.UnsignedByteType,s.UnsignedByteType],priorityETC1S:100,priorityUASTC:100,needsPowerOfTwo:!1},{basisFormat:[o.UASTC_HDR],transcoderFormat:[r.RGBA_HALF],engineFormat:[i.RGBAFormat],engineType:[s.HalfFloatType],priorityHDR:100,needsPowerOfTwo:!1}],h={[o.ETC1S]:c.filter(g=>g.basisFormat.includes(o.ETC1S)).sort((g,p)=>g.priorityETC1S-p.priorityETC1S),[o.UASTC]:c.filter(g=>g.basisFormat.includes(o.UASTC)).sort((g,p)=>g.priorityUASTC-p.priorityUASTC),[o.UASTC_HDR]:c.filter(g=>g.basisFormat.includes(o.UASTC_HDR)).sort((g,p)=>g.priorityHDR-p.priorityHDR)};function d(g,p,m,A){const x=h[g];for(let b=0;b<x.length;b++){const y=x[b];if(y.if&&!n[y.if]||!y.basisFormat.includes(g)||A&&y.transcoderFormat.length<2||y.needsPowerOfTwo&&!(f(p)&&f(m)))continue;const _=y.transcoderFormat[A?1:0],S=y.engineFormat[A?1:0],C=y.engineType[0];return{transcoderFormat:_,engineFormat:S,engineType:C}}throw new Error("THREE.KTX2Loader: Failed to identify transcoding target.")}function f(g){return g<=2?!0:(g&g-1)===0&&g!==0}function u(g){if(g.length===1)return g[0];let p=0;for(let x=0;x<g.length;x++){const b=g[x];p+=b.byteLength}const m=new Uint8Array(p);let A=0;for(let x=0;x<g.length;x++){const b=g[x];m.set(b,A),A+=b.byteLength}return m}};const iT=new Set([v.RGBAFormat,v.RGBFormat,v.RGFormat,v.RedFormat]),Wu={[jA]:v.RGBAFormat,[QA]:v.RGFormat,[VA]:v.RedFormat,[GA]:v.RGBAFormat,[zA]:v.RGFormat,[NA]:v.RedFormat,[UA]:v.RGBAFormat,[OA]:v.RGBAFormat,[FA]:v.RGFormat,[kA]:v.RGFormat,[RA]:v.RedFormat,[LA]:v.RedFormat,[HA]:v.RGBFormat,[WA]:v.RGBFormat,[o0]:v.RGBA_ETC2_EAC_Format,[r0]:v.RGB_ETC2_Format,[a0]:v.R11_EAC_Format,[l0]:v.SIGNED_R11_EAC_Format,[c0]:v.RG11_EAC_Format,[h0]:v.SIGNED_RG11_EAC_Format,[Uu]:v.RGBA_ASTC_4x4_Format,[u0]:v.RGBA_ASTC_4x4_Format,[d0]:v.RGBA_ASTC_4x4_Format,[b0]:v.RGBA_ASTC_6x6_Format,[p0]:v.RGBA_ASTC_6x6_Format,[f0]:v.RGBA_ASTC_6x6_Format,[KA]:v.RGBA_S3TC_DXT1_Format,[YA]:v.RGBA_S3TC_DXT1_Format,[qA]:v.RGB_S3TC_DXT1_Format,[XA]:v.RGB_S3TC_DXT1_Format,[JA]:v.RGBA_S3TC_DXT5_Format,[$A]:v.RGBA_S3TC_DXT5_Format,[e0]:v.SIGNED_RED_RGTC1_Format,[ZA]:v.RED_RGTC1_Format,[i0]:v.SIGNED_RED_GREEN_RGTC2_Format,[t0]:v.RED_GREEN_RGTC2_Format,[s0]:v.RGBA_BPTC_Format,[n0]:v.RGBA_BPTC_Format,[x0]:v.RGBA_PVRTC_4BPPV1_Format,[m0]:v.RGBA_PVRTC_4BPPV1_Format,[A0]:v.RGBA_PVRTC_2BPPV1_Format,[g0]:v.RGBA_PVRTC_2BPPV1_Format},po={[jA]:v.FloatType,[QA]:v.FloatType,[VA]:v.FloatType,[GA]:v.HalfFloatType,[zA]:v.HalfFloatType,[NA]:v.HalfFloatType,[UA]:v.UnsignedByteType,[OA]:v.UnsignedByteType,[FA]:v.UnsignedByteType,[kA]:v.UnsignedByteType,[RA]:v.UnsignedByteType,[LA]:v.UnsignedByteType,[HA]:v.UnsignedInt5999Type,[WA]:v.UnsignedInt101111Type,[o0]:v.UnsignedByteType,[r0]:v.UnsignedByteType,[a0]:v.UnsignedByteType,[l0]:v.UnsignedByteType,[c0]:v.UnsignedByteType,[h0]:v.UnsignedByteType,[Uu]:v.HalfFloatType,[u0]:v.UnsignedByteType,[d0]:v.UnsignedByteType,[b0]:v.HalfFloatType,[p0]:v.UnsignedByteType,[f0]:v.UnsignedByteType,[KA]:v.UnsignedByteType,[YA]:v.UnsignedByteType,[qA]:v.UnsignedByteType,[XA]:v.UnsignedByteType,[JA]:v.UnsignedByteType,[$A]:v.UnsignedByteType,[e0]:v.UnsignedByteType,[ZA]:v.UnsignedByteType,[i0]:v.UnsignedByteType,[t0]:v.UnsignedByteType,[s0]:v.UnsignedByteType,[n0]:v.UnsignedByteType,[x0]:v.UnsignedByteType,[m0]:v.UnsignedByteType,[A0]:v.UnsignedByteType,[g0]:v.UnsignedByteType};async function nT(n){const{vkFormat:e}=n;if(Wu[e]===void 0)throw new Error("THREE.KTX2Loader: Unsupported vkFormat: "+e);po[e]===void 0&&console.warn('THREE.KTX2Loader: Missing ".type" for vkFormat: '+e);let t;n.supercompressionScheme===BA&&(ju||(ju=new Promise(async o=>{const a=new ZI;await a.init(),o(a)})),t=await ju);const i=[];for(let o=0;o<n.levels.length;o++){const a=Math.max(1,n.pixelWidth>>o),l=Math.max(1,n.pixelHeight>>o),c=n.pixelDepth?Math.max(1,n.pixelDepth>>o):0,h=n.levels[o];let d;if(n.supercompressionScheme===HI)d=h.levelData;else if(n.supercompressionScheme===BA)d=t.decode(h.levelData,h.uncompressedByteLength);else throw new Error("THREE.KTX2Loader: Unsupported supercompressionScheme.");let f;po[e]===v.FloatType?f=new Float32Array(d.buffer,d.byteOffset,d.byteLength/Float32Array.BYTES_PER_ELEMENT):po[e]===v.HalfFloatType?f=new Uint16Array(d.buffer,d.byteOffset,d.byteLength/Uint16Array.BYTES_PER_ELEMENT):po[e]===v.UnsignedInt5999Type||po[e]===v.UnsignedInt101111Type?f=new Uint32Array(d.buffer,d.byteOffset,d.byteLength/Uint32Array.BYTES_PER_ELEMENT):f=d,i.push({data:f,width:a,height:l,depth:c})}const s=n.levelCount===0||i.length>1;let r;if(iT.has(Wu[e]))r=n.pixelDepth===0?new v.DataTexture(i[0].data,n.pixelWidth,n.pixelHeight):new v.Data3DTexture(i[0].data,n.pixelWidth,n.pixelHeight,n.pixelDepth),r.minFilter=s?v.NearestMipmapNearestFilter:v.NearestFilter,r.magFilter=v.NearestFilter,r.generateMipmaps=n.levelCount===0;else{if(n.pixelDepth>0)throw new Error("THREE.KTX2Loader: Unsupported pixelDepth.");r=new v.CompressedTexture(i,n.pixelWidth,n.pixelHeight),r.minFilter=s?v.LinearMipmapLinearFilter:v.LinearFilter,r.magFilter=v.LinearFilter}return r.mipmaps=i,r.type=po[e],r.format=Wu[e],r.colorSpace=_0(n),r.needsUpdate=!0,Promise.resolve(r)}function _0(n){const e=n.dataFormatDescriptor[0];return e.colorPrimaries===YI?e.transferFunction===PA?v.SRGBColorSpace:v.LinearSRGBColorSpace:e.colorPrimaries===KI?e.transferFunction===PA?eT:tT:(e.colorPrimaries===qI||console.warn(`THREE.KTX2Loader: Unsupported color primaries, "${e.colorPrimaries}"`),v.NoColorSpace)}function sT(n,e,t,i){let s=0,r=0,o=0,a=n.models.find(u=>u.url==t),l=e.circularMeps,c=e.rectMeps?.filter(u=>u.type==="风管"),h=e.rectMeps?.filter(u=>u.type==="桥架"),d=e.ellipseMeps,f=n.scene;if(new w.MeshBasicMaterial,new w.BufferGeometry,l&&l.length){let u=[],g=0;for(let p of l)p.color=p.color.split(",").map(m=>parseInt(m)/255),p.color=new w.Color(p.color[0],p.color[1],p.color[2]),p.position={x:p.startPoint.X*.3048+s,y:p.startPoint.Z*.3048+r,z:-p.startPoint.Y*.3048+o},p.rotation={x:0,y:0,z:0},p.indexes=[[n.scene.children.length,g++,0,0]],a.nodesMap.set(Number(p.id),p),u.push(p);bc("Circle",f,u,t)}if(c&&c.length){let u=[],g=0;for(let p of c)p.color=p.color.split(",").map(m=>parseInt(m)/255),p.color=new w.Color(p.color[0],p.color[1],p.color[2]),p.position={x:p.startPoint.X*.3048+s,y:p.startPoint.Z*.3048+r,z:-p.startPoint.Y*.3048+o},p.rotation={x:0,y:0,z:0},p.indexes=[[n.scene.children.length,g++,0,0]],a.nodesMap.set(Number(p.id),p),u.push(p);bc("Rect",f,u,t)}if(d&&d.length){let u=[],g=0;for(let p of d)p.color=p.color.split(",").map(m=>parseInt(m)/255),p.color=new w.Color(p.color[0],p.color[1],p.color[2]),p.position={x:p.startPoint.X*.3048+s,y:p.startPoint.Z*.3048+r,z:-p.startPoint.Y*.3048+o},p.rotation={x:0,y:0,z:0},p.indexes=[[n.scene.children.length,g++,0,0]],a.nodesMap.set(Number(p.id),p),u.push(p);bc("Ellipse",f,u,t)}if(h&&h.length){let u=[],g=0;for(let p of h)p.color=p.color.split(",").map(m=>parseInt(m)/255),p.color=new w.Color(p.color[0],p.color[1],p.color[2]),p.position={x:p.startPoint.X*.3048+s,y:p.startPoint.Z*.3048+r,z:-p.startPoint.Y*.3048+o},p.rotation={x:0,y:0,z:0},p.indexes=[[n.scene.children.length,g++,0,0]],a.nodesMap.set(Number(p.id),p),u.push(p);bc("Bridge",f,u,t)}}function bc(n,e,t,i,s){let r,o,a={width:1,height:1,length:1,diameter:1,color:new w.Color,position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0}};switch(n){case"Rect":o=yc("Rect",a);break;case"Bridge":o=yc("Bridge",a);break;case"Circle":o=yc("Circle",a);break;case"Ellipse":o=yc("Ellipse",a);break}o&&(r=new w.InstancedMesh(o.geometry,o.material,t.length),r.url=i,e.add(r),r.index=e.children.length-1);let l=[],c=[];for(var h=0;h<t.length;h++){let u=t[h],g=new w.Vector3(u.startPoint.X,0,-u.startPoint.Y),p=new w.Vector3(u.endPoint.X,0,-u.endPoint.Y),m=new w.Vector3(u.startPoint.X,u.startPoint.Z,-u.startPoint.Y),A=new w.Vector3(u.endPoint.X,u.endPoint.Z,-u.endPoint.Y),x=0,b=0,y=0;if(Math.abs(p.clone().sub(g.clone()).z)<.01&&Math.abs(p.clone().sub(g.clone()).x)<.01){if(x=(u.startPoint.Z>u.endPoint.Z?1:-1)*Math.PI*.5,u.base_x!=null){var d=new w.Vector3(u.base_x.X,0,-u.base_x.Y);b=(d.clone().cross(new w.Vector3(0,0,1)).y<=0?1:-1)*d.angleTo(new w.Vector3(0,0,1))+Math.PI*.5}}else b=(p.clone().sub(g.clone()).cross(new w.Vector3(0,0,1)).y>0?-1:1)*p.clone().sub(g.clone()).angleTo(new w.Vector3(0,0,1)),x=(u.startPoint.Z>u.endPoint.Z?1:-1)*p.clone().sub(g.clone()).angleTo(A.clone().sub(m.clone()));let _=new w.Matrix4;const S=new w.Euler(x,b,y,"YXZ");let C=_.clone().makeRotationFromEuler(S),D,M;n==="Circle"?(D=u.diameter,M=u.diameter):(D=u.width,M=u.height);let I=_.clone().makeScale(D,M,u.length);_.multiplyMatrices(C,I),_.setPosition(u.position.x,u.position.y,u.position.z),r.setMatrixAt(h,_.clone()),r.setColorAt(h,u.color),r.geometry.computeBoundingBox();let L=r.geometry.boundingBox.min.clone().applyMatrix4(_.clone()),T=r.geometry.boundingBox.max.clone().applyMatrix4(_.clone()),R=new w.Vector3(Math.min(L.x,T.x),Math.min(L.y,T.y),Math.min(L.z,T.z)),E=new w.Vector3(Math.max(L.x,T.x),Math.max(L.y,T.y),Math.max(L.z,T.z)),F=R.clone().add(E.clone()).multiplyScalar(.5),N={name:u.name,min:R,max:E,center:F,dbid:h,materialName:o.material.name},H=null,V=null;n==="Circle"&&(H={x:u.startPoint.X*.3048,y:u.startPoint.Z*.3048,z:-u.startPoint.Y*.3048},V={x:u.endPoint.X*.3048,y:u.endPoint.Z*.3048,z:-u.endPoint.Y*.3048},N.minC=H,N.maxC=V),r.ids||(r.ids=[]),r.matrixs||(r.matrixs=[]),r.matrixs.push(_.clone()),c.push(_.clone()),r.ids.push(Number(u.id)),l.push(N)}r.castShadow=!0,r.ElementInfos=l,r.name="rootModel",r.TypeName="InstancedMesh-Pipe",r.PipeType=n,r.MeshId=null,r.realMaterial=r.material.clone(),r.originalMaterial=r.material.clone(),r.matrixsClone=c;let f=[];f={geometry:r.geometry,matrix:r.matrix,position:r.position,rotation:r.rotation},r.meshs=f,r.instanceMatrix&&r.instanceMatrix.array&&(r.cloneInstanceMatrix=Array.from(r.instanceMatrix.array))}function yc(n,e,t){let i=new w.Shape;switch(e.width=e.width*.3048,e.height=e.height*.3048,e.diameter=e.diameter*.3048,n){case"Rect":i.moveTo(-e.width/2,-e.height/2),i.lineTo(-e.width/2,e.height/2),i.lineTo(e.width/2,e.height/2),i.lineTo(e.width/2,-e.height/2),i.lineTo(-e.width/2,-e.height/2);break;case"Ellipse":i.moveTo(-e.width/2,-e.height/2),i.lineTo(-e.width/2,e.height/2),i.lineTo(e.width/2,e.height/2),i.lineTo(e.width/2,-e.height/2),i.lineTo(-e.width/2,-e.height/2);break;case"Bridge":i.moveTo(-e.width/2,-e.height/2),i.lineTo(-e.width/2,e.height/2),i.lineTo(-e.width/2+.01,e.height/2),i.lineTo(-e.width/2+.01,-e.height/2+.01),i.lineTo(e.width/2-.01,-e.height/2+.01),i.lineTo(e.width/2-.01,e.height/2),i.lineTo(e.width/2,e.height/2),i.lineTo(e.width/2,-e.height/2),i.lineTo(-e.width/2,-e.height/2);break;case"Circle":i.moveTo(0,0),i.absarc(0,0,e.diameter*.5,0,Math.PI*2,!1);break}const s={depth:e.length*.3048,bevelEnabled:!1};return r(i,s,e.color,e.position,e.rotation);function r(o,a,l,c,h){let d=new w.ExtrudeGeometry(o,a),f=new w.MeshStandardMaterial({color:l,side:w.DoubleSide}),u=new w.Mesh(d,f);return u.position.set(c.x,c.y,c.z),u.rotation._order="YXZ",u.rotation.set(h.x,h.y,h.z),u}}function Yn(n,e=!1){const t=n[0].index!==null,i=new Set(Object.keys(n[0].attributes)),s=new Set(Object.keys(n[0].morphAttributes)),r={},o={},a=n[0].morphTargetsRelative,l=new v.BufferGeometry;let c=0;for(let h=0;h<n.length;++h){const d=n[h];let f=0;if(t!==(d.index!==null))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+h+". All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them."),null;for(const u in d.attributes){if(!i.has(u))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+h+'. All geometries must have compatible attributes; make sure "'+u+'" attribute exists among all geometries, or in none of them.'),null;r[u]===void 0&&(r[u]=[]),r[u].push(d.attributes[u]),f++}if(f!==i.size)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+h+". Make sure all geometries have the same number of attributes."),null;if(a!==d.morphTargetsRelative)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+h+". .morphTargetsRelative must be consistent throughout all geometries."),null;for(const u in d.morphAttributes){if(!s.has(u))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+h+". .morphAttributes must be consistent throughout all geometries."),null;o[u]===void 0&&(o[u]=[]),o[u].push(d.morphAttributes[u])}if(e){let u;if(t)u=d.index.count;else if(d.attributes.position!==void 0)u=d.attributes.position.count;else return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+h+". The geometry must have either an index or a position attribute"),null;l.addGroup(c,u,h),c+=u}}if(t){let h=0;const d=[];for(let f=0;f<n.length;++f){const u=n[f].index;for(let g=0;g<u.count;++g)d.push(u.getX(g)+h);h+=n[f].attributes.position.count}l.setIndex(d)}for(const h in r){const d=w0(r[h]);if(!d)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the "+h+" attribute."),null;l.setAttribute(h,d)}for(const h in o){const d=o[h][0].length;if(d===0)break;l.morphAttributes=l.morphAttributes||{},l.morphAttributes[h]=[];for(let f=0;f<d;++f){const u=[];for(let p=0;p<o[h].length;++p)u.push(o[h][p][f]);const g=w0(u);if(!g)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the "+h+" morphAttribute."),null;l.morphAttributes[h].push(g)}}return l}function w0(n){let e,t,i,s=-1,r=0;for(let c=0;c<n.length;++c){const h=n[c];if(e===void 0&&(e=h.array.constructor),e!==h.array.constructor)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes."),null;if(t===void 0&&(t=h.itemSize),t!==h.itemSize)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes."),null;if(i===void 0&&(i=h.normalized),i!==h.normalized)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes."),null;if(s===-1&&(s=h.gpuType),s!==h.gpuType)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.gpuType must be consistent across matching attributes."),null;r+=h.count*t}const o=new e(r),a=new v.BufferAttribute(o,t,i);let l=0;for(let c=0;c<n.length;++c){const h=n[c];if(h.isInterleavedBufferAttribute){const d=l/t;for(let f=0,u=h.count;f<u;f++)for(let g=0;g<t;g++){const p=h.getComponent(f,g);a.setComponent(f+d,g,p)}}else o.set(h.array,l);l+=h.count*t}return s!==void 0&&(a.gpuType=s),a}function S0(n,e){if(e===v.TrianglesDrawMode)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),n;if(e===v.TriangleFanDrawMode||e===v.TriangleStripDrawMode){let t=n.getIndex();if(t===null){const o=[],a=n.getAttribute("position");if(a!==void 0){for(let l=0;l<a.count;l++)o.push(l);n.setIndex(o),t=n.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),n}const i=t.count-2,s=[];if(e===v.TriangleFanDrawMode)for(let o=1;o<=i;o++)s.push(t.getX(0)),s.push(t.getX(o)),s.push(t.getX(o+1));else for(let o=0;o<i;o++)o%2===0?(s.push(t.getX(o)),s.push(t.getX(o+1)),s.push(t.getX(o+2))):(s.push(t.getX(o+2)),s.push(t.getX(o+1)),s.push(t.getX(o)));s.length/3!==i&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const r=n.clone();return r.setIndex(s),r.clearGroups(),r}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),n}function rT(n){const e=new Map,t=new Map,i=n.clone();return C0(n,i,function(s,r){e.set(r,s),t.set(s,r)}),i.traverse(function(s){if(!s.isSkinnedMesh)return;const r=s,o=e.get(s),a=o.skeleton.bones;r.skeleton=o.skeleton.clone(),r.bindMatrix.copy(o.bindMatrix),r.skeleton.bones=a.map(function(l){return t.get(l)}),r.bind(r.skeleton,r.bindMatrix)}),i}function C0(n,e,t){t(n,e);for(let i=0;i<n.children.length;i++)C0(n.children[i],e.children[i],t)}class oT extends v.Loader{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new dT(t)}),this.register(function(t){return new uT(t)}),this.register(function(t){return new vT(t)}),this.register(function(t){return new _T(t)}),this.register(function(t){return new wT(t)}),this.register(function(t){return new pT(t)}),this.register(function(t){return new gT(t)}),this.register(function(t){return new mT(t)}),this.register(function(t){return new AT(t)}),this.register(function(t){return new hT(t)}),this.register(function(t){return new xT(t)}),this.register(function(t){return new fT(t)}),this.register(function(t){return new yT(t)}),this.register(function(t){return new bT(t)}),this.register(function(t){return new lT(t)}),this.register(function(t){return new M0(t,et.EXT_MESHOPT_COMPRESSION)}),this.register(function(t){return new M0(t,et.KHR_MESHOPT_COMPRESSION)}),this.register(function(t){return new ST(t)})}load(e,t,i,s){const r=this;let o;if(this.resourcePath!=="")o=this.resourcePath;else if(this.path!==""){const c=v.LoaderUtils.extractUrlBase(e);o=v.LoaderUtils.resolveURL(c,this.path)}else o=v.LoaderUtils.extractUrlBase(e);this.manager.itemStart(e);const a=function(c){s?s(c):console.error(c),r.manager.itemError(e),r.manager.itemEnd(e)},l=new v.FileLoader(this.manager);l.setPath(this.path),l.setResponseType("arraybuffer"),l.setRequestHeader(this.requestHeader),l.setWithCredentials(this.withCredentials),l.load(e,function(c){try{r.parse(c,o,function(h){t(h),r.manager.itemEnd(e)},a)}catch(h){a(h)}},i,a)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,i,s){let r;const o={},a={},l=new TextDecoder;if(typeof e=="string")r=JSON.parse(e);else if(e instanceof ArrayBuffer)if(l.decode(new Uint8Array(e,0,4))===E0){try{o[et.KHR_BINARY_GLTF]=new CT(e)}catch(d){s&&s(d);return}r=JSON.parse(o[et.KHR_BINARY_GLTF].content)}else r=JSON.parse(l.decode(e));else r=e;if(r.asset===void 0||r.asset.version[0]<2){s&&s(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const c=new UT(r,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});c.fileLoader.setRequestHeader(this.requestHeader);for(let h=0;h<this.pluginCallbacks.length;h++){const d=this.pluginCallbacks[h](c);d.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),a[d.name]=d,o[d.name]=!0}if(r.extensionsUsed)for(let h=0;h<r.extensionsUsed.length;++h){const d=r.extensionsUsed[h],f=r.extensionsRequired||[];switch(d){case et.KHR_MATERIALS_UNLIT:o[d]=new cT;break;case et.KHR_DRACO_MESH_COMPRESSION:o[d]=new MT(r,this.dracoLoader);break;case et.KHR_TEXTURE_TRANSFORM:o[d]=new ET;break;case et.KHR_MESH_QUANTIZATION:o[d]=new IT;break;default:f.indexOf(d)>=0&&a[d]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+d+'".')}}c.setExtensions(o),c.setPlugins(a),c.parse(i,s)}parseAsync(e,t){const i=this;return new Promise(function(s,r){i.parse(e,t,s,r)})}}function aT(){let n={};return{get:function(e){return n[e]},add:function(e,t){n[e]=t},remove:function(e){delete n[e]},removeAll:function(){n={}}}}function kt(n,e,t){const i=n.json.materials[e];return i.extensions&&i.extensions[t]?i.extensions[t]:null}const et={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",KHR_MESHOPT_COMPRESSION:"KHR_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class lT{constructor(e){this.parser=e,this.name=et.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let i=0,s=t.length;i<s;i++){const r=t[i];r.extensions&&r.extensions[this.name]&&r.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,r.extensions[this.name].light)}}_loadLight(e){const t=this.parser,i="light:"+e;let s=t.cache.get(i);if(s)return s;const r=t.json,l=((r.extensions&&r.extensions[this.name]||{}).lights||[])[e];let c;const h=new v.Color(16777215);l.color!==void 0&&h.setRGB(l.color[0],l.color[1],l.color[2],v.LinearSRGBColorSpace);const d=l.range!==void 0?l.range:0;switch(l.type){case"directional":c=new v.DirectionalLight(h),c.target.position.set(0,0,-1),c.add(c.target);break;case"point":c=new v.PointLight(h),c.distance=d;break;case"spot":c=new v.SpotLight(h),c.distance=d,l.spot=l.spot||{},l.spot.innerConeAngle=l.spot.innerConeAngle!==void 0?l.spot.innerConeAngle:0,l.spot.outerConeAngle=l.spot.outerConeAngle!==void 0?l.spot.outerConeAngle:Math.PI/4,c.angle=l.spot.outerConeAngle,c.penumbra=1-l.spot.innerConeAngle/l.spot.outerConeAngle,c.target.position.set(0,0,-1),c.add(c.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+l.type)}return c.position.set(0,0,0),vn(c,l),l.intensity!==void 0&&(c.intensity=l.intensity),c.name=t.createUniqueName(l.name||"light_"+e),s=Promise.resolve(c),t.cache.add(i,s),s}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){const t=this,i=this.parser,r=i.json.nodes[e],a=(r.extensions&&r.extensions[this.name]||{}).light;return a===void 0?null:this._loadLight(a).then(function(l){return i._getNodeRef(t.cache,a,l)})}}class cT{constructor(){this.name=et.KHR_MATERIALS_UNLIT}getMaterialType(){return v.MeshBasicMaterial}extendParams(e,t,i){const s=[];e.color=new v.Color(1,1,1),e.opacity=1;const r=t.pbrMetallicRoughness;if(r){if(Array.isArray(r.baseColorFactor)){const o=r.baseColorFactor;e.color.setRGB(o[0],o[1],o[2],v.LinearSRGBColorSpace),e.opacity=o[3]}r.baseColorTexture!==void 0&&s.push(i.assignTexture(e,"map",r.baseColorTexture,v.SRGBColorSpace))}return Promise.all(s)}}class hT{constructor(e){this.parser=e,this.name=et.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const i=kt(this.parser,e,this.name);return i===null||i.emissiveStrength!==void 0&&(t.emissiveIntensity=i.emissiveStrength),Promise.resolve()}}class dT{constructor(e){this.parser=e,this.name=et.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){return kt(this.parser,e,this.name)!==null?v.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=kt(this.parser,e,this.name);if(i===null)return Promise.resolve();const s=[];if(i.clearcoatFactor!==void 0&&(t.clearcoat=i.clearcoatFactor),i.clearcoatTexture!==void 0&&s.push(this.parser.assignTexture(t,"clearcoatMap",i.clearcoatTexture)),i.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=i.clearcoatRoughnessFactor),i.clearcoatRoughnessTexture!==void 0&&s.push(this.parser.assignTexture(t,"clearcoatRoughnessMap",i.clearcoatRoughnessTexture)),i.clearcoatNormalTexture!==void 0&&(s.push(this.parser.assignTexture(t,"clearcoatNormalMap",i.clearcoatNormalTexture)),i.clearcoatNormalTexture.scale!==void 0)){const r=i.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new v.Vector2(r,r)}return Promise.all(s)}}class uT{constructor(e){this.parser=e,this.name=et.KHR_MATERIALS_DISPERSION}getMaterialType(e){return kt(this.parser,e,this.name)!==null?v.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=kt(this.parser,e,this.name);return i===null||(t.dispersion=i.dispersion!==void 0?i.dispersion:0),Promise.resolve()}}class fT{constructor(e){this.parser=e,this.name=et.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){return kt(this.parser,e,this.name)!==null?v.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=kt(this.parser,e,this.name);if(i===null)return Promise.resolve();const s=[];return i.iridescenceFactor!==void 0&&(t.iridescence=i.iridescenceFactor),i.iridescenceTexture!==void 0&&s.push(this.parser.assignTexture(t,"iridescenceMap",i.iridescenceTexture)),i.iridescenceIor!==void 0&&(t.iridescenceIOR=i.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),i.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=i.iridescenceThicknessMinimum),i.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=i.iridescenceThicknessMaximum),i.iridescenceThicknessTexture!==void 0&&s.push(this.parser.assignTexture(t,"iridescenceThicknessMap",i.iridescenceThicknessTexture)),Promise.all(s)}}class pT{constructor(e){this.parser=e,this.name=et.KHR_MATERIALS_SHEEN}getMaterialType(e){return kt(this.parser,e,this.name)!==null?v.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=kt(this.parser,e,this.name);if(i===null)return Promise.resolve();const s=[];if(t.sheenColor=new v.Color(0,0,0),t.sheenRoughness=0,t.sheen=1,i.sheenColorFactor!==void 0){const r=i.sheenColorFactor;t.sheenColor.setRGB(r[0],r[1],r[2],v.LinearSRGBColorSpace)}return i.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=i.sheenRoughnessFactor),i.sheenColorTexture!==void 0&&s.push(this.parser.assignTexture(t,"sheenColorMap",i.sheenColorTexture,v.SRGBColorSpace)),i.sheenRoughnessTexture!==void 0&&s.push(this.parser.assignTexture(t,"sheenRoughnessMap",i.sheenRoughnessTexture)),Promise.all(s)}}class gT{constructor(e){this.parser=e,this.name=et.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){return kt(this.parser,e,this.name)!==null?v.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=kt(this.parser,e,this.name);if(i===null)return Promise.resolve();const s=[];return i.transmissionFactor!==void 0&&(t.transmission=i.transmissionFactor),i.transmissionTexture!==void 0&&s.push(this.parser.assignTexture(t,"transmissionMap",i.transmissionTexture)),Promise.all(s)}}class mT{constructor(e){this.parser=e,this.name=et.KHR_MATERIALS_VOLUME}getMaterialType(e){return kt(this.parser,e,this.name)!==null?v.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=kt(this.parser,e,this.name);if(i===null)return Promise.resolve();const s=[];t.thickness=i.thicknessFactor!==void 0?i.thicknessFactor:0,i.thicknessTexture!==void 0&&s.push(this.parser.assignTexture(t,"thicknessMap",i.thicknessTexture)),t.attenuationDistance=i.attenuationDistance||1/0;const r=i.attenuationColor||[1,1,1];return t.attenuationColor=new v.Color().setRGB(r[0],r[1],r[2],v.LinearSRGBColorSpace),Promise.all(s)}}class AT{constructor(e){this.parser=e,this.name=et.KHR_MATERIALS_IOR}getMaterialType(e){return kt(this.parser,e,this.name)!==null?v.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=kt(this.parser,e,this.name);return i===null||(t.ior=i.ior!==void 0?i.ior:1.5),Promise.resolve()}}class xT{constructor(e){this.parser=e,this.name=et.KHR_MATERIALS_SPECULAR}getMaterialType(e){return kt(this.parser,e,this.name)!==null?v.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=kt(this.parser,e,this.name);if(i===null)return Promise.resolve();const s=[];t.specularIntensity=i.specularFactor!==void 0?i.specularFactor:1,i.specularTexture!==void 0&&s.push(this.parser.assignTexture(t,"specularIntensityMap",i.specularTexture));const r=i.specularColorFactor||[1,1,1];return t.specularColor=new v.Color().setRGB(r[0],r[1],r[2],v.LinearSRGBColorSpace),i.specularColorTexture!==void 0&&s.push(this.parser.assignTexture(t,"specularColorMap",i.specularColorTexture,v.SRGBColorSpace)),Promise.all(s)}}class bT{constructor(e){this.parser=e,this.name=et.EXT_MATERIALS_BUMP}getMaterialType(e){return kt(this.parser,e,this.name)!==null?v.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=kt(this.parser,e,this.name);if(i===null)return Promise.resolve();const s=[];return t.bumpScale=i.bumpFactor!==void 0?i.bumpFactor:1,i.bumpTexture!==void 0&&s.push(this.parser.assignTexture(t,"bumpMap",i.bumpTexture)),Promise.all(s)}}class yT{constructor(e){this.parser=e,this.name=et.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){return kt(this.parser,e,this.name)!==null?v.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=kt(this.parser,e,this.name);if(i===null)return Promise.resolve();const s=[];return i.anisotropyStrength!==void 0&&(t.anisotropy=i.anisotropyStrength),i.anisotropyRotation!==void 0&&(t.anisotropyRotation=i.anisotropyRotation),i.anisotropyTexture!==void 0&&s.push(this.parser.assignTexture(t,"anisotropyMap",i.anisotropyTexture)),Promise.all(s)}}class vT{constructor(e){this.parser=e,this.name=et.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,i=t.json,s=i.textures[e];if(!s.extensions||!s.extensions[this.name])return null;const r=s.extensions[this.name],o=t.options.ktx2Loader;if(!o){if(i.extensionsRequired&&i.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,r.source,o)}}class _T{constructor(e){this.parser=e,this.name=et.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,i=this.parser,s=i.json,r=s.textures[e];if(!r.extensions||!r.extensions[t])return null;const o=r.extensions[t],a=s.images[o.source];let l=i.textureLoader;if(a.uri){const c=i.options.manager.getHandler(a.uri);c!==null&&(l=c)}return i.loadTextureImage(e,o.source,l)}}class wT{constructor(e){this.parser=e,this.name=et.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,i=this.parser,s=i.json,r=s.textures[e];if(!r.extensions||!r.extensions[t])return null;const o=r.extensions[t],a=s.images[o.source];let l=i.textureLoader;if(a.uri){const c=i.options.manager.getHandler(a.uri);c!==null&&(l=c)}return i.loadTextureImage(e,o.source,l)}}class M0{constructor(e,t){this.name=t,this.parser=e}loadBufferView(e){const t=this.parser.json,i=t.bufferViews[e];if(i.extensions&&i.extensions[this.name]){const s=i.extensions[this.name],r=this.parser.getDependency("buffer",s.buffer),o=this.parser.options.meshoptDecoder;if(!o||!o.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return r.then(function(a){const l=s.byteOffset||0,c=s.byteLength||0,h=s.count,d=s.byteStride,f=new Uint8Array(a,l,c);return o.decodeGltfBufferAsync?o.decodeGltfBufferAsync(h,d,f,s.mode,s.filter).then(function(u){return u.buffer}):o.ready.then(function(){const u=new ArrayBuffer(h*d);return o.decodeGltfBuffer(new Uint8Array(u),h,d,f,s.mode,s.filter),u})})}else return null}}class ST{constructor(e){this.name=et.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,i=t.nodes[e];if(!i.extensions||!i.extensions[this.name]||i.mesh===void 0)return null;const s=t.meshes[i.mesh];for(const c of s.primitives)if(c.mode!==Gi.TRIANGLES&&c.mode!==Gi.TRIANGLE_STRIP&&c.mode!==Gi.TRIANGLE_FAN&&c.mode!==void 0)return null;const o=i.extensions[this.name].attributes,a=[],l={};for(const c in o)a.push(this.parser.getDependency("accessor",o[c]).then(h=>(l[c]=h,l[c])));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then(c=>{const h=c.pop(),d=h.isGroup?h.children:[h],f=c[0].count,u=[];for(const g of d){const p=new v.Matrix4,m=new v.Vector3,A=new v.Quaternion,x=new v.Vector3(1,1,1),b=new v.InstancedMesh(g.geometry,g.material,f);for(let y=0;y<f;y++)l.TRANSLATION&&m.fromBufferAttribute(l.TRANSLATION,y),l.ROTATION&&A.fromBufferAttribute(l.ROTATION,y),l.SCALE&&x.fromBufferAttribute(l.SCALE,y),b.setMatrixAt(y,p.compose(m,A,x));for(const y in l)if(y==="_COLOR_0"){const _=l[y];b.instanceColor=new v.InstancedBufferAttribute(_.array,_.itemSize,_.normalized)}else y!=="TRANSLATION"&&y!=="ROTATION"&&y!=="SCALE"&&g.geometry.setAttribute(y,l[y]);v.Object3D.prototype.copy.call(b,g),this.parser.assignFinalMaterial(b),u.push(b)}return h.isGroup?(h.clear(),h.add(...u),h):u[0]}))}}const E0="glTF",ua=12,I0={JSON:1313821514,BIN:5130562};class CT{constructor(e){this.name=et.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,ua),i=new TextDecoder;if(this.header={magic:i.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==E0)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const s=this.header.length-ua,r=new DataView(e,ua);let o=0;for(;o<s;){const a=r.getUint32(o,!0);o+=4;const l=r.getUint32(o,!0);if(o+=4,l===I0.JSON){const c=new Uint8Array(e,ua+o,a);this.content=i.decode(c)}else if(l===I0.BIN){const c=ua+o;this.body=e.slice(c,c+a)}o+=a}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class MT{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=et.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const i=this.json,s=this.dracoLoader,r=e.extensions[this.name].bufferView,o=e.extensions[this.name].attributes,a={},l={},c={};for(const h in o){const d=Xu[h]||h.toLowerCase();a[d]=o[h]}for(const h in e.attributes){const d=Xu[h]||h.toLowerCase();if(o[h]!==void 0){const f=i.accessors[e.attributes[h]],u=go[f.componentType];c[d]=u.name,l[d]=f.normalized===!0}}return t.getDependency("bufferView",r).then(function(h){return new Promise(function(d,f){s.decodeDracoFile(h,function(u){for(const g in u.attributes){const p=u.attributes[g],m=l[g];m!==void 0&&(p.normalized=m)}d(u)},a,c,v.LinearSRGBColorSpace,f)})})}}class ET{constructor(){this.name=et.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0||(e=e.clone(),t.texCoord!==void 0&&(e.channel=t.texCoord),t.offset!==void 0&&e.offset.fromArray(t.offset),t.rotation!==void 0&&(e.rotation=t.rotation),t.scale!==void 0&&e.repeat.fromArray(t.scale),e.needsUpdate=!0),e}}class IT{constructor(){this.name=et.KHR_MESH_QUANTIZATION}}class T0 extends v.Interpolant{constructor(e,t,i,s){super(e,t,i,s)}copySampleValue_(e){const t=this.resultBuffer,i=this.sampleValues,s=this.valueSize,r=e*s*3+s;for(let o=0;o!==s;o++)t[o]=i[r+o];return t}interpolate_(e,t,i,s){const r=this.resultBuffer,o=this.sampleValues,a=this.valueSize,l=a*2,c=a*3,h=s-t,d=(i-t)/h,f=d*d,u=f*d,g=e*c,p=g-c,m=-2*u+3*f,A=u-f,x=1-m,b=A-f+d;for(let y=0;y!==a;y++){const _=o[p+y+a],S=o[p+y+l]*h,C=o[g+y+a],D=o[g+y]*h;r[y]=x*_+b*S+m*C+A*D}return r}}const TT=new v.Quaternion;class DT extends T0{interpolate_(e,t,i,s){const r=super.interpolate_(e,t,i,s);return TT.fromArray(r).normalize().toArray(r),r}}const Gi={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},go={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},D0={9728:v.NearestFilter,9729:v.LinearFilter,9984:v.NearestMipmapNearestFilter,9985:v.LinearMipmapNearestFilter,9986:v.NearestMipmapLinearFilter,9987:v.LinearMipmapLinearFilter},B0={33071:v.ClampToEdgeWrapping,33648:v.MirroredRepeatWrapping,10497:v.RepeatWrapping},Hu={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},Xu={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},Ss={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},BT={CUBICSPLINE:void 0,LINEAR:v.InterpolateLinear,STEP:v.InterpolateDiscrete},qu={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function PT(n){return n.DefaultMaterial===void 0&&(n.DefaultMaterial=new v.MeshStandardMaterial({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:v.FrontSide})),n.DefaultMaterial}function dr(n,e,t){for(const i in t.extensions)n[i]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[i]=t.extensions[i])}function vn(n,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(n.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function LT(n,e,t){let i=!1,s=!1,r=!1;for(let c=0,h=e.length;c<h;c++){const d=e[c];if(d.POSITION!==void 0&&(i=!0),d.NORMAL!==void 0&&(s=!0),d.COLOR_0!==void 0&&(r=!0),i&&s&&r)break}if(!i&&!s&&!r)return Promise.resolve(n);const o=[],a=[],l=[];for(let c=0,h=e.length;c<h;c++){const d=e[c];if(i){const f=d.POSITION!==void 0?t.getDependency("accessor",d.POSITION):n.attributes.position;o.push(f)}if(s){const f=d.NORMAL!==void 0?t.getDependency("accessor",d.NORMAL):n.attributes.normal;a.push(f)}if(r){const f=d.COLOR_0!==void 0?t.getDependency("accessor",d.COLOR_0):n.attributes.color;l.push(f)}}return Promise.all([Promise.all(o),Promise.all(a),Promise.all(l)]).then(function(c){const h=c[0],d=c[1],f=c[2];return i&&(n.morphAttributes.position=h),s&&(n.morphAttributes.normal=d),r&&(n.morphAttributes.color=f),n.morphTargetsRelative=!0,n})}function RT(n,e){if(n.updateMorphTargets(),e.weights!==void 0)for(let t=0,i=e.weights.length;t<i;t++)n.morphTargetInfluences[t]=e.weights[t];if(e.extras&&Array.isArray(e.extras.targetNames)){const t=e.extras.targetNames;if(n.morphTargetInfluences.length===t.length){n.morphTargetDictionary={};for(let i=0,s=t.length;i<s;i++)n.morphTargetDictionary[t[i]]=i}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function kT(n){let e;const t=n.extensions&&n.extensions[et.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+Yu(t.attributes):e=n.indices+":"+Yu(n.attributes)+":"+n.mode,n.targets!==void 0)for(let i=0,s=n.targets.length;i<s;i++)e+=":"+Yu(n.targets[i]);return e}function Yu(n){let e="";const t=Object.keys(n).sort();for(let i=0,s=t.length;i<s;i++)e+=t[i]+":"+n[t[i]]+";";return e}function Ku(n){switch(n){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function FT(n){return n.search(/\.jpe?g($|\?)/i)>0||n.search(/^data\:image\/jpeg/)===0?"image/jpeg":n.search(/\.webp($|\?)/i)>0||n.search(/^data\:image\/webp/)===0?"image/webp":n.search(/\.ktx2($|\?)/i)>0||n.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const OT=new v.Matrix4;class UT{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new aT,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let i=!1,s=-1,r=!1,o=-1;if(typeof navigator<"u"&&typeof navigator.userAgent<"u"){const a=navigator.userAgent;i=/^((?!chrome|android).)*safari/i.test(a)===!0;const l=a.match(/Version\/(\d+)/);s=i&&l?parseInt(l[1],10):-1,r=a.indexOf("Firefox")>-1,o=r?a.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||i&&s<17||r&&o<98?this.textureLoader=new v.TextureLoader(this.options.manager):this.textureLoader=new v.ImageBitmapLoader(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new v.FileLoader(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const i=this,s=this.json,r=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(o){return o._markDefs&&o._markDefs()}),Promise.all(this._invokeAll(function(o){return o.beforeRoot&&o.beforeRoot()})).then(function(){return Promise.all([i.getDependencies("scene"),i.getDependencies("animation"),i.getDependencies("camera")])}).then(function(o){const a={scene:o[0][s.scene||0],scenes:o[0],animations:o[1],cameras:o[2],asset:s.asset,parser:i,userData:{}};return dr(r,a,s),vn(a,s),Promise.all(i._invokeAll(function(l){return l.afterRoot&&l.afterRoot(a)})).then(function(){for(const l of a.scenes)l.updateMatrixWorld();e(a)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],i=this.json.meshes||[];for(let s=0,r=t.length;s<r;s++){const o=t[s].joints;for(let a=0,l=o.length;a<l;a++)e[o[a]].isBone=!0}for(let s=0,r=e.length;s<r;s++){const o=e[s];o.mesh!==void 0&&(this._addNodeRef(this.meshCache,o.mesh),o.skin!==void 0&&(i[o.mesh].isSkinnedMesh=!0)),o.camera!==void 0&&this._addNodeRef(this.cameraCache,o.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,i){if(e.refs[t]<=1)return i;const s=i.clone(),r=(o,a)=>{const l=this.associations.get(o);l!=null&&this.associations.set(a,l);for(const[c,h]of o.children.entries())r(h,a.children[c])};return r(i,s),s.name+="_instance_"+e.uses[t]++,s}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let i=0;i<t.length;i++){const s=e(t[i]);if(s)return s}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const i=[];for(let s=0;s<t.length;s++){const r=e(t[s]);r&&i.push(r)}return i}getDependency(e,t){const i=e+":"+t;let s=this.cache.get(i);if(!s){switch(e){case"scene":s=this.loadScene(t);break;case"node":s=this._invokeOne(function(r){return r.loadNode&&r.loadNode(t)});break;case"mesh":s=this._invokeOne(function(r){return r.loadMesh&&r.loadMesh(t)});break;case"accessor":s=this.loadAccessor(t);break;case"bufferView":s=this._invokeOne(function(r){return r.loadBufferView&&r.loadBufferView(t)});break;case"buffer":s=this.loadBuffer(t);break;case"material":s=this._invokeOne(function(r){return r.loadMaterial&&r.loadMaterial(t)});break;case"texture":s=this._invokeOne(function(r){return r.loadTexture&&r.loadTexture(t)});break;case"skin":s=this.loadSkin(t);break;case"animation":s=this._invokeOne(function(r){return r.loadAnimation&&r.loadAnimation(t)});break;case"camera":s=this.loadCamera(t);break;default:if(s=this._invokeOne(function(r){return r!=this&&r.getDependency&&r.getDependency(e,t)}),!s)throw new Error("Unknown type: "+e);break}this.cache.add(i,s)}return s}getDependencies(e){let t=this.cache.get(e);if(!t){const i=this,s=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(s.map(function(r,o){return i.getDependency(e,o)})),this.cache.add(e,t)}return t}loadBuffer(e){const t=this.json.buffers[e],i=this.fileLoader;if(t.type&&t.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[et.KHR_BINARY_GLTF].body);const s=this.options;return new Promise(function(r,o){i.load(v.LoaderUtils.resolveURL(t.uri,s.path),r,void 0,function(){o(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(e){const t=this.json.bufferViews[e];return this.getDependency("buffer",t.buffer).then(function(i){const s=t.byteLength||0,r=t.byteOffset||0;return i.slice(r,r+s)})}loadAccessor(e){const t=this,i=this.json,s=this.json.accessors[e];if(s.bufferView===void 0&&s.sparse===void 0){const o=Hu[s.type],a=go[s.componentType],l=s.normalized===!0,c=new a(s.count*o);return Promise.resolve(new v.BufferAttribute(c,o,l))}const r=[];return s.bufferView!==void 0?r.push(this.getDependency("bufferView",s.bufferView)):r.push(null),s.sparse!==void 0&&(r.push(this.getDependency("bufferView",s.sparse.indices.bufferView)),r.push(this.getDependency("bufferView",s.sparse.values.bufferView))),Promise.all(r).then(function(o){const a=o[0],l=Hu[s.type],c=go[s.componentType],h=c.BYTES_PER_ELEMENT,d=h*l,f=s.byteOffset||0,u=s.bufferView!==void 0?i.bufferViews[s.bufferView].byteStride:void 0,g=s.normalized===!0;let p,m;if(u&&u!==d){const A=Math.floor(f/u),x="InterleavedBuffer:"+s.bufferView+":"+s.componentType+":"+A+":"+s.count;let b=t.cache.get(x);b||(p=new c(a,A*u,s.count*u/h),b=new v.InterleavedBuffer(p,u/h),t.cache.add(x,b)),m=new v.InterleavedBufferAttribute(b,l,f%u/h,g)}else a===null?p=new c(s.count*l):p=new c(a,f,s.count*l),m=new v.BufferAttribute(p,l,g);if(s.sparse!==void 0){const A=Hu.SCALAR,x=go[s.sparse.indices.componentType],b=s.sparse.indices.byteOffset||0,y=s.sparse.values.byteOffset||0,_=new x(o[1],b,s.sparse.count*A),S=new c(o[2],y,s.sparse.count*l);a!==null&&(m=new v.BufferAttribute(m.array.slice(),m.itemSize,m.normalized)),m.normalized=!1;for(let C=0,D=_.length;C<D;C++){const M=_[C];if(m.setX(M,S[C*l]),l>=2&&m.setY(M,S[C*l+1]),l>=3&&m.setZ(M,S[C*l+2]),l>=4&&m.setW(M,S[C*l+3]),l>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}m.normalized=g}return m})}loadTexture(e){const t=this.json,i=this.options,r=t.textures[e].source,o=t.images[r];let a=this.textureLoader;if(o.uri){const l=i.manager.getHandler(o.uri);l!==null&&(a=l)}return this.loadTextureImage(e,r,a)}loadTextureImage(e,t,i){const s=this,r=this.json,o=r.textures[e],a=r.images[t],l=(a.uri||a.bufferView)+":"+o.sampler;if(this.textureCache[l])return this.textureCache[l];const c=this.loadImageSource(t,i).then(function(h){h.flipY=!1,h.name=o.name||a.name||"",h.name===""&&typeof a.uri=="string"&&a.uri.startsWith("data:image/")===!1&&(h.name=a.uri);const f=(r.samplers||{})[o.sampler]||{};return h.magFilter=D0[f.magFilter]||v.LinearFilter,h.minFilter=D0[f.minFilter]||v.LinearMipmapLinearFilter,h.wrapS=B0[f.wrapS]||v.RepeatWrapping,h.wrapT=B0[f.wrapT]||v.RepeatWrapping,h.generateMipmaps=!h.isCompressedTexture&&h.minFilter!==v.NearestFilter&&h.minFilter!==v.LinearFilter,s.associations.set(h,{textures:e}),h}).catch(function(){return null});return this.textureCache[l]=c,c}loadImageSource(e,t){const i=this,s=this.json,r=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(d=>d.clone());const o=s.images[e],a=self.URL||self.webkitURL;let l=o.uri||"",c=!1;if(o.bufferView!==void 0)l=i.getDependency("bufferView",o.bufferView).then(function(d){c=!0;const f=new Blob([d],{type:o.mimeType});return l=a.createObjectURL(f),l});else if(o.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const h=Promise.resolve(l).then(function(d){return new Promise(function(f,u){let g=f;t.isImageBitmapLoader===!0&&(g=function(p){const m=new v.Texture(p);m.needsUpdate=!0,f(m)}),t.load(v.LoaderUtils.resolveURL(d,r.path),g,void 0,u)})}).then(function(d){return c===!0&&a.revokeObjectURL(l),vn(d,o),d.userData.mimeType=o.mimeType||FT(o.uri),d}).catch(function(d){throw console.error("THREE.GLTFLoader: Couldn't load texture",l),d});return this.sourceCache[e]=h,h}assignTexture(e,t,i,s){const r=this;return this.getDependency("texture",i.index).then(function(o){if(!o)return null;if(i.texCoord!==void 0&&i.texCoord>0&&(o=o.clone(),o.channel=i.texCoord),r.extensions[et.KHR_TEXTURE_TRANSFORM]){const a=i.extensions!==void 0?i.extensions[et.KHR_TEXTURE_TRANSFORM]:void 0;if(a){const l=r.associations.get(o);o=r.extensions[et.KHR_TEXTURE_TRANSFORM].extendTexture(o,a),r.associations.set(o,l)}}return s!==void 0&&(o.colorSpace=s),e[t]=o,o})}assignFinalMaterial(e){const t=e.geometry;let i=e.material;const s=t.attributes.tangent===void 0,r=t.attributes.color!==void 0,o=t.attributes.normal===void 0;if(e.isPoints){const a="PointsMaterial:"+i.uuid;let l=this.cache.get(a);l||(l=new v.PointsMaterial,v.Material.prototype.copy.call(l,i),l.color.copy(i.color),l.map=i.map,l.sizeAttenuation=!1,this.cache.add(a,l)),i=l}else if(e.isLine){const a="LineBasicMaterial:"+i.uuid;let l=this.cache.get(a);l||(l=new v.LineBasicMaterial,v.Material.prototype.copy.call(l,i),l.color.copy(i.color),l.map=i.map,this.cache.add(a,l)),i=l}if(s||r||o){let a="ClonedMaterial:"+i.uuid+":";s&&(a+="derivative-tangents:"),r&&(a+="vertex-colors:"),o&&(a+="flat-shading:");let l=this.cache.get(a);l||(l=i.clone(),r&&(l.vertexColors=!0),o&&(l.flatShading=!0),s&&(l.normalScale&&(l.normalScale.y*=-1),l.clearcoatNormalScale&&(l.clearcoatNormalScale.y*=-1)),this.cache.add(a,l),this.associations.set(l,this.associations.get(i))),i=l}e.material=i}getMaterialType(){return v.MeshStandardMaterial}loadMaterial(e){const t=this,i=this.json,s=this.extensions,r=i.materials[e];let o;const a={},l=r.extensions||{},c=[];if(l[et.KHR_MATERIALS_UNLIT]){const d=s[et.KHR_MATERIALS_UNLIT];o=d.getMaterialType(),c.push(d.extendParams(a,r,t))}else{const d=r.pbrMetallicRoughness||{};if(a.color=new v.Color(1,1,1),a.opacity=1,Array.isArray(d.baseColorFactor)){const f=d.baseColorFactor;a.color.setRGB(f[0],f[1],f[2],v.LinearSRGBColorSpace),a.opacity=f[3]}d.baseColorTexture!==void 0&&c.push(t.assignTexture(a,"map",d.baseColorTexture,v.SRGBColorSpace)),a.metalness=d.metallicFactor!==void 0?d.metallicFactor:1,a.roughness=d.roughnessFactor!==void 0?d.roughnessFactor:1,d.metallicRoughnessTexture!==void 0&&(c.push(t.assignTexture(a,"metalnessMap",d.metallicRoughnessTexture)),c.push(t.assignTexture(a,"roughnessMap",d.metallicRoughnessTexture))),o=this._invokeOne(function(f){return f.getMaterialType&&f.getMaterialType(e)}),c.push(Promise.all(this._invokeAll(function(f){return f.extendMaterialParams&&f.extendMaterialParams(e,a)})))}r.doubleSided===!0&&(a.side=v.DoubleSide);const h=r.alphaMode||qu.OPAQUE;if(h===qu.BLEND?(a.transparent=!0,a.depthWrite=!1):(a.transparent=!1,h===qu.MASK&&(a.alphaTest=r.alphaCutoff!==void 0?r.alphaCutoff:.5)),r.normalTexture!==void 0&&o!==v.MeshBasicMaterial&&(c.push(t.assignTexture(a,"normalMap",r.normalTexture)),a.normalScale=new v.Vector2(1,1),r.normalTexture.scale!==void 0)){const d=r.normalTexture.scale;a.normalScale.set(d,d)}if(r.occlusionTexture!==void 0&&o!==v.MeshBasicMaterial&&(c.push(t.assignTexture(a,"aoMap",r.occlusionTexture)),r.occlusionTexture.strength!==void 0&&(a.aoMapIntensity=r.occlusionTexture.strength)),r.emissiveFactor!==void 0&&o!==v.MeshBasicMaterial){const d=r.emissiveFactor;a.emissive=new v.Color().setRGB(d[0],d[1],d[2],v.LinearSRGBColorSpace)}return r.emissiveTexture!==void 0&&o!==v.MeshBasicMaterial&&c.push(t.assignTexture(a,"emissiveMap",r.emissiveTexture,v.SRGBColorSpace)),Promise.all(c).then(function(){const d=new o(a);return r.name&&(d.name=r.name),vn(d,r),t.associations.set(d,{materials:e}),r.extensions&&dr(s,d,r),d})}createUniqueName(e){const t=v.PropertyBinding.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,i=this.extensions,s=this.primitiveCache;function r(a){return i[et.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(a,t).then(function(l){return P0(l,a,t)})}const o=[];for(let a=0,l=e.length;a<l;a++){const c=e[a],h=kT(c),d=s[h];if(d)o.push(d.promise);else{let f;c.extensions&&c.extensions[et.KHR_DRACO_MESH_COMPRESSION]?f=r(c):f=P0(new v.BufferGeometry,c,t),s[h]={primitive:c,promise:f},o.push(f)}}return Promise.all(o)}loadMesh(e){const t=this,i=this.json,s=this.extensions,r=i.meshes[e],o=r.primitives,a=[];for(let l=0,c=o.length;l<c;l++){const h=o[l].material===void 0?PT(this.cache):this.getDependency("material",o[l].material);a.push(h)}return a.push(t.loadGeometries(o)),Promise.all(a).then(function(l){const c=l.slice(0,l.length-1),h=l[l.length-1],d=[];for(let u=0,g=h.length;u<g;u++){const p=h[u],m=o[u];let A;const x=c[u];if(m.mode===Gi.TRIANGLES||m.mode===Gi.TRIANGLE_STRIP||m.mode===Gi.TRIANGLE_FAN||m.mode===void 0)A=r.isSkinnedMesh===!0?new v.SkinnedMesh(p,x):new v.Mesh(p,x),A.isSkinnedMesh===!0&&A.normalizeSkinWeights(),m.mode===Gi.TRIANGLE_STRIP?A.geometry=S0(A.geometry,v.TriangleStripDrawMode):m.mode===Gi.TRIANGLE_FAN&&(A.geometry=S0(A.geometry,v.TriangleFanDrawMode));else if(m.mode===Gi.LINES)A=new v.LineSegments(p,x);else if(m.mode===Gi.LINE_STRIP)A=new v.Line(p,x);else if(m.mode===Gi.LINE_LOOP)A=new v.LineLoop(p,x);else if(m.mode===Gi.POINTS)A=new v.Points(p,x);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+m.mode);Object.keys(A.geometry.morphAttributes).length>0&&RT(A,r),A.name=t.createUniqueName(r.name||"mesh_"+e),vn(A,r),m.extensions&&dr(s,A,m),t.assignFinalMaterial(A),d.push(A)}for(let u=0,g=d.length;u<g;u++)t.associations.set(d[u],{meshes:e,primitives:u});if(d.length===1)return r.extensions&&dr(s,d[0],r),d[0];const f=new v.Group;r.extensions&&dr(s,f,r),t.associations.set(f,{meshes:e});for(let u=0,g=d.length;u<g;u++)f.add(d[u]);return f})}loadCamera(e){let t;const i=this.json.cameras[e],s=i[i.type];if(!s){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return i.type==="perspective"?t=new v.PerspectiveCamera(v.MathUtils.radToDeg(s.yfov),s.aspectRatio||1,s.znear||1,s.zfar||2e6):i.type==="orthographic"&&(t=new v.OrthographicCamera(-s.xmag,s.xmag,s.ymag,-s.ymag,s.znear,s.zfar)),i.name&&(t.name=this.createUniqueName(i.name)),vn(t,i),Promise.resolve(t)}loadSkin(e){const t=this.json.skins[e],i=[];for(let s=0,r=t.joints.length;s<r;s++)i.push(this._loadNodeShallow(t.joints[s]));return t.inverseBindMatrices!==void 0?i.push(this.getDependency("accessor",t.inverseBindMatrices)):i.push(null),Promise.all(i).then(function(s){const r=s.pop(),o=s,a=[],l=[];for(let c=0,h=o.length;c<h;c++){const d=o[c];if(d){a.push(d);const f=new v.Matrix4;r!==null&&f.fromArray(r.array,c*16),l.push(f)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[c])}return new v.Skeleton(a,l)})}loadAnimation(e){const t=this.json,i=this,s=t.animations[e],r=s.name?s.name:"animation_"+e,o=[],a=[],l=[],c=[],h=[];for(let d=0,f=s.channels.length;d<f;d++){const u=s.channels[d],g=s.samplers[u.sampler],p=u.target,m=p.node,A=s.parameters!==void 0?s.parameters[g.input]:g.input,x=s.parameters!==void 0?s.parameters[g.output]:g.output;p.node!==void 0&&(o.push(this.getDependency("node",m)),a.push(this.getDependency("accessor",A)),l.push(this.getDependency("accessor",x)),c.push(g),h.push(p))}return Promise.all([Promise.all(o),Promise.all(a),Promise.all(l),Promise.all(c),Promise.all(h)]).then(function(d){const f=d[0],u=d[1],g=d[2],p=d[3],m=d[4],A=[];for(let b=0,y=f.length;b<y;b++){const _=f[b],S=u[b],C=g[b],D=p[b],M=m[b];if(_===void 0)continue;_.updateMatrix&&_.updateMatrix();const I=i._createAnimationTracks(_,S,C,D,M);if(I)for(let L=0;L<I.length;L++)A.push(I[L])}const x=new v.AnimationClip(r,void 0,A);return vn(x,s),x})}createNodeMesh(e){const t=this.json,i=this,s=t.nodes[e];return s.mesh===void 0?null:i.getDependency("mesh",s.mesh).then(function(r){const o=i._getNodeRef(i.meshCache,s.mesh,r);return s.weights!==void 0&&o.traverse(function(a){if(a.isMesh)for(let l=0,c=s.weights.length;l<c;l++)a.morphTargetInfluences[l]=s.weights[l]}),o})}loadNode(e){const t=this.json,i=this,s=t.nodes[e],r=i._loadNodeShallow(e),o=[],a=s.children||[];for(let c=0,h=a.length;c<h;c++)o.push(i.getDependency("node",a[c]));const l=s.skin===void 0?Promise.resolve(null):i.getDependency("skin",s.skin);return Promise.all([r,Promise.all(o),l]).then(function(c){const h=c[0],d=c[1],f=c[2];f!==null&&h.traverse(function(u){u.isSkinnedMesh&&u.bind(f,OT)});for(let u=0,g=d.length;u<g;u++)h.add(d[u]);if(h.userData.pivot!==void 0&&d.length>0){const u=h.userData.pivot,g=d[0];h.pivot=new v.Vector3().fromArray(u),h.position.x-=u[0],h.position.y-=u[1],h.position.z-=u[2],g.position.set(0,0,0),delete h.userData.pivot}return h})}_loadNodeShallow(e){const t=this.json,i=this.extensions,s=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];const r=t.nodes[e],o=r.name?s.createUniqueName(r.name):"",a=[],l=s._invokeOne(function(c){return c.createNodeMesh&&c.createNodeMesh(e)});return l&&a.push(l),r.camera!==void 0&&a.push(s.getDependency("camera",r.camera).then(function(c){return s._getNodeRef(s.cameraCache,r.camera,c)})),s._invokeAll(function(c){return c.createNodeAttachment&&c.createNodeAttachment(e)}).forEach(function(c){a.push(c)}),this.nodeCache[e]=Promise.all(a).then(function(c){let h;if(r.isBone===!0?h=new v.Bone:c.length>1?h=new v.Group:c.length===1?h=c[0]:h=new v.Object3D,h!==c[0])for(let d=0,f=c.length;d<f;d++)h.add(c[d]);if(r.name&&(h.userData.name=r.name,h.name=o),vn(h,r),r.extensions&&dr(i,h,r),r.matrix!==void 0){const d=new v.Matrix4;d.fromArray(r.matrix),h.applyMatrix4(d)}else r.translation!==void 0&&h.position.fromArray(r.translation),r.rotation!==void 0&&h.quaternion.fromArray(r.rotation),r.scale!==void 0&&h.scale.fromArray(r.scale);if(!s.associations.has(h))s.associations.set(h,{});else if(r.mesh!==void 0&&s.meshCache.refs[r.mesh]>1){const d=s.associations.get(h);s.associations.set(h,{...d})}return s.associations.get(h).nodes=e,h}),this.nodeCache[e]}loadScene(e){const t=this.extensions,i=this.json.scenes[e],s=this,r=new v.Group;i.name&&(r.name=s.createUniqueName(i.name)),vn(r,i),i.extensions&&dr(t,r,i);const o=i.nodes||[],a=[];for(let l=0,c=o.length;l<c;l++)a.push(s.getDependency("node",o[l]));return Promise.all(a).then(function(l){for(let h=0,d=l.length;h<d;h++){const f=l[h];f.parent!==null?r.add(rT(f)):r.add(f)}const c=h=>{const d=new Map;for(const[f,u]of s.associations)(f instanceof v.Material||f instanceof v.Texture)&&d.set(f,u);return h.traverse(f=>{const u=s.associations.get(f);u!=null&&d.set(f,u)}),d};return s.associations=c(r),r})}_createAnimationTracks(e,t,i,s,r){const o=[],a=e.name?e.name:e.uuid,l=[];Ss[r.path]===Ss.weights?e.traverse(function(f){f.morphTargetInfluences&&l.push(f.name?f.name:f.uuid)}):l.push(a);let c;switch(Ss[r.path]){case Ss.weights:c=v.NumberKeyframeTrack;break;case Ss.rotation:c=v.QuaternionKeyframeTrack;break;case Ss.translation:case Ss.scale:c=v.VectorKeyframeTrack;break;default:switch(i.itemSize){case 1:c=v.NumberKeyframeTrack;break;case 2:case 3:default:c=v.VectorKeyframeTrack;break}break}const h=s.interpolation!==void 0?BT[s.interpolation]:v.InterpolateLinear,d=this._getArrayFromAccessor(i);for(let f=0,u=l.length;f<u;f++){const g=new c(l[f]+"."+Ss[r.path],t.array,d,h);s.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(g),o.push(g)}return o}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const i=Ku(t.constructor),s=new Float32Array(t.length);for(let r=0,o=t.length;r<o;r++)s[r]=t[r]*i;t=s}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(i){const s=this instanceof v.QuaternionKeyframeTrack?DT:T0;return new s(this.times,this.values,this.getValueSize()/3,i)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function NT(n,e,t){const i=e.attributes,s=new v.Box3;if(i.POSITION!==void 0){const a=t.json.accessors[i.POSITION],l=a.min,c=a.max;if(l!==void 0&&c!==void 0){if(s.set(new v.Vector3(l[0],l[1],l[2]),new v.Vector3(c[0],c[1],c[2])),a.normalized){const h=Ku(go[a.componentType]);s.min.multiplyScalar(h),s.max.multiplyScalar(h)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const r=e.targets;if(r!==void 0){const a=new v.Vector3,l=new v.Vector3;for(let c=0,h=r.length;c<h;c++){const d=r[c];if(d.POSITION!==void 0){const f=t.json.accessors[d.POSITION],u=f.min,g=f.max;if(u!==void 0&&g!==void 0){if(l.setX(Math.max(Math.abs(u[0]),Math.abs(g[0]))),l.setY(Math.max(Math.abs(u[1]),Math.abs(g[1]))),l.setZ(Math.max(Math.abs(u[2]),Math.abs(g[2]))),f.normalized){const p=Ku(go[f.componentType]);l.multiplyScalar(p)}a.max(l)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}s.expandByVector(a)}n.boundingBox=s;const o=new v.Sphere;s.getCenter(o.center),o.radius=s.min.distanceTo(s.max)/2,n.boundingSphere=o}function P0(n,e,t){const i=e.attributes,s=[];function r(o,a){return t.getDependency("accessor",o).then(function(l){n.setAttribute(a,l)})}for(const o in i){const a=Xu[o]||o.toLowerCase();a in n.attributes||s.push(r(i[o],a))}if(e.indices!==void 0&&!n.index){const o=t.getDependency("accessor",e.indices).then(function(a){n.setIndex(a)});s.push(o)}return v.ColorManagement.workingColorSpace!==v.LinearSRGBColorSpace&&"COLOR_0"in i&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${v.ColorManagement.workingColorSpace}" not supported.`),vn(n,e),NT(n,e,t),Promise.all(s).then(function(){return e.targets!==void 0?LT(n,e.targets,t):n})}var Et=(n=>(n.ModelLoadStart="model-load-start",n.ModelLoadProgress="model-load-progress",n.ModelLoaded="model-loaded",n.ModelError="model-error",n.SelectionChanged="selection-changed",n.HoverChanged="hover-changed",n.Click="click",n.MouseMove="mouse-move",n.CameraChanged="camera-changed",n.CameraIdle="camera-idle",n.EngineFree="engine-free",n.EngineBusy="engine-busy",n.MeasureChanged="measure-changed",n.MeasureClick="measure-click",n.SectionMove="section-move",n.LoadingCompleted="loading_completed",n))(Et||{});let fa=null,pa=null,L0=null;const zT=8,R0=24,GT=24,VT=64,QT=200,jT=10;function k0(){return new URL("draco/",document.baseURI).toString()}function F0(){return new URL("basis/",document.baseURI).toString()}function WT(){return fa==null&&(fa=new VI,fa.setDecoderPath(k0()),fa.preload()),fa}function HT(n){return pa==null&&(pa=new zi,pa.setTranscoderPath(F0())),L0!==n&&(pa.detectSupport(n),L0=n),pa}function XT(n){const e=new oT;return e.setDRACOLoader(WT()),e.setMeshoptDecoder(jI),n?.renderer?.capabilities!=null&&typeof n.renderer.getContext=="function"&&e.setKTX2Loader(HT(n.renderer)),e}function O0(){return new Promise(n=>{if(typeof requestAnimationFrame=="function"){requestAnimationFrame(()=>n());return}setTimeout(n,16)})}function qT(){const n=navigator?.scheduling;return typeof n?.isInputPending=="function"?n.isInputPending():!1}function YT(n){return n?.engineStatus?.isFree===!1||qT()}async function Kn(n,e,t){if(e)return t;const i=performance.now();return YT(n)||i-t>=zT?(await O0(),performance.now()):t}function KT(n,e){return new Promise((t,i)=>{ha(n,s=>{if(s==null){i(new Error(`[loadLightModel] empty zip json: ${n}`));return}t(s)},()=>{i(new Error(`[loadLightModel] failed to load zip json: ${n}`))},e)})}function $T(n,e){return Mt({method:"get",responseType:"arraybuffer",url:n}).then(async t=>{let i=t.data;return fo.isEncrypted(t.data)&&(i=await fo.decryptPzEnc(t.data,e)),Wm.loadAsync(i)})}function U0(n){return n.replace(/\\/g,"/").replace(/^\/+/,"")}function N0(n,e){const t=new Set(e.map(i=>U0(i)));for(const i of Object.keys(n.files))if(t.has(U0(i)))return n.files[i];return null}function z0(n,e){const t=N0(n,e);return t==null||t.dir?Promise.resolve(null):t.async("string")}function JT(n){return n.charCodeAt(0)===65279?n.slice(1):n}function $u(n){return JSON.parse(JT(n))}function ZT(n,e){const t=N0(n,e);return t==null||t.dir?Promise.resolve(null):t.async("arraybuffer")}function e2(n,e){return new Promise((t,i)=>{XT(n).parse(e,document.baseURI,t,i)})}function vc(n,e){return n.models.find(t=>t.url==e)}function G0(n){n.loadStatus==null&&(n.loadStatus={}),n.loadStatus.modelMep==null&&(n.loadStatus.modelMep=!1),n.loadStatus.normal==null&&(n.loadStatus.normal=!1)}function t2(n){return G0(n),n.status==="loaded"&&n.loadStatus.normal===!0&&n.loadStatus.modelMep===!0}function V0(n){const e=n?.engineStatus?.models;!Array.isArray(e)||e.length===0||!e.every(i=>t2(i))||n.__loadingCompletedTriggered===!0||(n.__loadingCompletedTriggered=!0,n.events?.trigger?.(Et.LoadingCompleted,{}))}function Q0(n){return n===!0||n==="loading"}function j0(n){return n.index!=null?n.index.count:n.attributes.position?.count??0}async function i2(n,e,t){let i=performance.now();for(let s=0;s<e.length;s++){const r=e[s];r?.geometry!=null&&r.geometry.computeVertexNormals,(s+1)%GT===0&&(i=await Kn(n,t,i))}}async function n2(n,e,t){const i=[],s=[{node:e.octreeBox,visited:!1}];let r=performance.now();for(;s.length>0;){const o=s.pop();if(o==null||o.node==null||o.node.status===!0)continue;const a=o.node;if(o.visited){const c=Array.isArray(a.children)?a.children:[];(c.length===0||c.findIndex(h=>h.status!=!0)===-1)&&(a.status=!0),r=await Kn(n,t,r);continue}s.push({node:a,visited:!0}),Array.isArray(a.elements)&&i.push(...a.elements);const l=Array.isArray(a.children)?a.children:[];for(let c=l.length-1;c>=0;c--)s.push({node:l[c],visited:!1});r=await Kn(n,t,r)}return i}async function s2(n,e,t,i){const s=vc(n,e.url);if(s?.nodesMap==null)return[];const r=await n2(n,t,i);console.log("[loadLightModel] pending mesh ids",t.path,r.length);const o=[];let a=performance.now(),l=0;for(const c of r){if(!s.nodesMap.has(c))continue;const h=s.nodesMap.get(c),d=Array.isArray(h?.infos)?h.infos:[];for(const f of d){const u=t.glbs?.[f.glb]?.[f.mesh];if(u?.geometry==null||u.material==null)continue;const g=new w.Matrix4;g.elements=f.matrix;const p=u.geometry.clone();p.applyMatrix4(g),p.computeBoundingBox();const m=new w.Mesh(p,u.material);f.box=p.boundingBox?.clone(),f.mesh=m,m.name=Number(c),m.glb=f.glb,m.url=e.url,p.attributes.position!=null&&o.push(m),l++,l%R0===0&&(a=await Kn(n,i,a))}}return o}function r2(n,e,t,i,s){const r=Yn(i.map(a=>a.geometry),!1),o=new w.Mesh(r,s);return o.castShadow=!0,o.receiveShadow=!0,e.scene.add(o),o.index=e.scene.children.length-1,o.url=n,o.glb=t,o.materialClone=s,o.geometrys=i.map(a=>a.geometry),o.geometry.computeVertexNormals(),o}function o2(n,e,t,i){return n.scene.children.find(s=>{const r=s;return s instanceof w.Mesh&&r.url==e&&r.glb==t&&r.materialClone===i})}function a2(n,e){const t=Array.isArray(n.geometrys)?n.geometrys:[],i=e.map(o=>o.geometry),s=[...t,...i],r=Yn(s,!1);n.geometry!=null&&n.geometry.dispose(),n.geometry=r,n.geometrys=s,n.castShadow=!0,n.receiveShadow=!0}async function l2(n,e,t,i){const s=new Map;for(const a of t){const l=s.get(a.glb)??[];l.push(a),s.set(a.glb,l)}const r=vc(e,n);let o=performance.now();for(const[a,l]of s.entries()){const c=i?l.length:QT;for(let h=0;h<l.length;h+=c){const d=l.slice(h,h+c);if(d.length===0)continue;const f=x2(d[0].material,e);let u=o2(e,n,a,f),g=0,p=0;u=null,u!=null?(g=Array.isArray(u.geometrys)?u.geometrys.length:0,p=j0(u.geometry),a2(u,d)):u=r2(n,e,a,d,f);const m=new Map;let A=p;d.forEach((x,b)=>{const y=Number(x.name),_=j0(x.geometry),S=m.get(y)??[];if(S.push([A,A+_]),m.set(y,S),r?.nodesMap?.has(y)){const C=r.nodesMap.get(y);C.indexes==null&&(C.indexes=[]),C.indexes.push([u.index,g+b,A,A+_])}A+=_}),u.indexes==null&&(u.indexes=new Map),m.forEach((x,b)=>{const y=u.indexes.get(b)??[];y.push(...x),u.indexes.set(b,y)}),o=await Kn(e,i,o)}}}async function c2(n,e,t,i,s,r){if(i==null||s==null||s.length===0)return;const o=vc(t,n);if(o==null)return;const a=new w.InstancedMesh(i.geometry,i.material,s.length);t.scene.add(a);const l=new Float32Array(s.length*3);for(let d=0;d<s.length;d++)l[d*3]=1,l[d*3+1]=1,l[d*3+2]=1;a.instanceColor=new w.InstancedBufferAttribute(l,3);let c=performance.now();const h=[];for(let d=0;d<s.length;d++){const f=s[d],u=new w.Matrix4;if(u.elements=f.matrix,a.setMatrixAt(d,u),a.matrixs||(a.matrixs=[]),a.matrixs.push(u.clone()),h.push(u.clone()),o.nodesMap.has(f.id)){const g=o.nodesMap.get(f.id);g.indexes==null&&(g.indexes=[]),g.indexes.push([t.scene.children.length-1,d,0,0])}else o.nodesMap.set(f.id,{instance:!0,info:f,indexes:[[t.scene.children.length-1,d,0,0]]});(d+1)%VT===0&&(c=await Kn(t,r,c))}a.instanceMatrix.needsUpdate=!0,a.instanceColor!=null&&(a.instanceColor.needsUpdate=!0),a.index=t.scene.children.length-1,a.materialClone=i.material,a.url=n,a.glb=i.glb,a.ids=s.map(d=>d.id),a.matrixsClone=h,a.meshIndex=e}async function h2(n,e,t,i){const s=e.instanceNodes;if(s==null)return;let r=performance.now();for(const o in s)if(s[o].isLoaded!==!0){s[o].isLoaded=!0;for(const a of s[o]){const l=e.glbs?.[o]?.[a.mesh];l!=null&&await c2(n.url,a.mesh,t,l,a.children,i)}r=await Kn(t,i,r)}}async function d2(n,e,t,i){if(t.status===!0||t.meshPromise!=null){await t.meshPromise;return}t.meshPromise=(async()=>{console.log(`[loadLightModel] start build lod meshes ${Date.now()-window.startTime}ms`);const s=await s2(n,e,t,i);await l2(e.url,n,s,i),await h2(e,t,n,i),t.status=!0,console.log(`[loadLightModel] *****************************************************finish build lod meshes ${Date.now()-window.startTime}ms`)})().finally(()=>{t.meshPromise=null}),await t.meshPromise}async function u2(n,e,t,i){if(t.loadSuccess!==!0){if(t.preparePromise!=null){await t.preparePromise;return}t.preparePromise=(async()=>{console.log("[loadLightModel] loading GLB bundle",t.path),t.glbs=t.glbs??{};const s=await $T(e.url+t.path,e.key),r=await z0(s,["/nodes.json","nodes.json"]);if(r==null)return;const o=$u(r),a=vc(n,e.url);if(a==null)return;a.nodesMap==null&&(a.nodesMap=new Map);let l=performance.now();for(const h of Object.keys(o)){const d=o[h];for(let u=0;u<d.length;u++){const g=d[u];if(g.glb=h,a.nodesMap.has(g.id)===!1)a.nodesMap.set(g.id,{infos:[g]});else{if(!a.nodesMap.get(g.id).infos)continue;a.nodesMap.get(g.id).infos.push(g)}(u+1)%R0===0&&(l=await Kn(n,i,l))}const f=await ZT(s,[`/${h}.glb`,`${h}.glb`,h+".glb"]);if(f==null){console.error("[loadLightModel] glb not found in zip",{modelUrl:e.url,lodPath:t.path,glbKey:`${h}.glb`,availableFiles:Object.keys(s.files)});continue}try{const u=await e2(n,f);t.glbs[h]=u.scene.children,t.glbs[h].forEach(g=>{g.matrixWorld}),await i2(n,t.glbs[h],i)}catch(u){console.error("[loadLightModel] failed to load glb",{modelUrl:e.url,lodPath:t.path,glbKey:`${h}.glb`,dracoDecoderPath:k0(),basisTranscoderPath:F0(),error:u})}l=await Kn(n,i,l)}const c=await z0(s,["/instances.json","instances.json"]);t.instanceNodes=c!=null?$u(c):null,t.loadSuccess=!0})().finally(()=>{t.preparePromise=null}),await t.preparePromise}}function f2(n,e,t){if(t.boundingBox||(t.boundingBox=new w.Box3,t.boundingBox.min=new w.Vector3(t.octreeBox.min.X,t.octreeBox.min.Z,-t.octreeBox.min.Y),t.boundingBox.max=new w.Vector3(t.octreeBox.max.X,t.octreeBox.max.Z,-t.octreeBox.max.Y)),!t.maxSize)return 1e3;const i=t.boundingBox,s=i.min,r=i.max,o=s.clone().add(r.clone()).multiplyScalar(.5),a=s.distanceTo(r),l=new w.Vector3,c=new w.Vector3,h=new w.Vector3,d=new w.Vector3;if(e.getWorldDirection(h),e.getWorldPosition(d),e.matrixWorld.extractBasis(l,c,new w.Vector3),e instanceof w.OrthographicCamera){const A=Math.max((e.top-e.bottom)/e.zoom,1e-6),x=n?.cameraModule?.perspectiveCamera?.getEffectiveFOV?.()??20,b=w.MathUtils.degToRad(x*.5),y=b>0?A/(2*Math.tan(b)):A;d.copy(o).add(h.clone().multiplyScalar(-y))}if(d.distanceTo(o)<=a*.5)return 1e3;const f=o.clone().sub(d).dot(h);if(f<=0)return 0;const u=d.clone().add(h.multiplyScalar(Math.max(f,a))),g=u.clone().add(l.setLength(t.maxSize)),p=new lt(e,n.renderer,n.scene).worldToScreen(u),m=new lt(e,n.renderer,n.scene).worldToScreen(g);return p.distanceTo(m)}async function p2(n,e,t,i){t.maxSize<1e6&&t.path!="/lod0"&&(!(f2(n,n.camera,t)>=jT)||t.status===!0)||(await u2(n,e,t,i),t.loadSuccess===!0&&await d2(n,e,t,i))}function g2(n,e,t){if(Q0(e.loadStatus.modelMep))return;e.loadStatus.modelMep="loading",e.info.modelMep==null&&(e.info.modelMep={}),(async()=>{t||await O0(),sT(n,e.info.modelMep,e.url),e.loadStatus.modelMep=!0,V0(n)})().catch(s=>{e.loadStatus.modelMep=!1,console.error("[loadLightModel] failed to load mep model",s)})}function m2(n,e,t,i){const s=new w.Group;s.name=e,n.scene.add(s),n.models||(n.models=[]),window.startTime=Date.now();let r="WDDsBNtzVz6aSh/bCFh3CmjjANEDRryoXF1XCJvJjeE=";KT(e+"/info",r).then(o=>{const a=$u(o);n.__loadingCompletedTriggered=!1,n.engineStatus.models.push({type:"light",info:a,name:a.baseInfo.name,status:"loading",url:e,elements:new Map,loadStatus:{modelMep:!1,normal:!1},key:r}),n.models.push({url:e,nodesMap:new Map,grids:a.modelGrid,levels:a.modelLevel,rooms:a.modelRoom,views:a.modelView,name:a.baseInfo.name,boundingBox:{min:new w.Vector3(a.baseInfo.min.X*.3048,a.baseInfo.min.Z*.3048,-a.baseInfo.min.Y*.3048),max:new w.Vector3(a.baseInfo.max.X*.3048,a.baseInfo.max.Z*.3048,-a.baseInfo.max.Y*.3048)}}),n.models.length==i&&(n.viewCube.CameraGoHome(1),setTimeout(()=>{W0(n,null,!1)},100))}).catch(o=>{console.error("[loadLightModel] failed to load model info",{url:e,error:o})})}async function W0(n,e,t=!1){const i=n.engineStatus.models.filter(s=>e==null||s.url==e);for(const s of i)if(G0(s),!(s.status!=="loading"||s.type!=="light")&&(g2(n,s,t),!Q0(s.loadStatus.normal))){s.loadStatus.normal="loading";try{await A2(n,s,t)}finally{const r=Array.isArray(s.info?.lods)&&s.info.lods.every(o=>o.status===!0);s.loadStatus.normal=r,r&&(s.status="loaded"),V0(n)}}}async function A2(n,e,t=!1){if(console.log(`[loadLightModel] start loadNode ${Date.now()-window.startTime}ms`),!(e.info==null||e.info.lods==null))for(const i of e.info.lods)await p2(n,e,i,t)}function x2(n,e){return n.map!=null&&(n.map.colorSpace=w.SRGBColorSpace,n.map.needsUpdate=!0),n.clipShadows=!0,e?.sectionPlane&&(n.clippingPlanes=e.sectionPlane),n}class b2{engine;constructor(e){this.engine=e}async loadModels(e,t){console.log("待加载模型",e);for(const s of e)i(s)==="light"&&m2(this.engine,s,t,e.length);function i(s){const r=s.split(".").pop();return r==="glb"||r==="gltf"?"gltf":"light"}}}var Cs=(n=>(n.ModelLoadStart="model-load-start",n.ModelLoadProgress="model-load-progress",n.ModelLoaded="model-loaded",n.ModelError="model-error",n.SelectionChanged="selection-changed",n.HoverChanged="hover-changed",n.Click="click",n.MouseMove="mouse-move",n.CameraChanged="camera-changed",n.CameraIdle="camera-idle",n.ViewportResize="viewport-resize",n.EngineFree="engine-free",n.EngineBusy="engine-busy",n.MeasureChanged="measure-changed",n.SectionMove="section-move",n.LoadingCompleted="loading_completed",n))(Cs||{});class y2{engine;isFree;isForceFree;highlightModels;hideModels;translucentModels;models;constructor(e){this.engine=e,this.isFree=!0,this.isForceFree=!1,this.highlightModels=[],this.hideModels=[],this.translucentModels=[],this.models=[]}init(){this.engine.events.on(Cs.EngineFree,e=>{this.updateFree(!0),W0(this.engine,e,!1),this.engine?.octreeBox?.requestBvhBuild?.()}),this.engine.events.on(Cs.EngineBusy,()=>{this.updateFree(!1)})}updateFree(e){this.isFree=e}closeAllFunction=()=>{}}let v2=class{listeners=new Map;debugMode=!1;setDebugMode(e){this.debugMode=e}on(e,t){const i=String(e);this.listeners.has(i)||this.listeners.set(i,[]),this.listeners.get(i).push(t),this.debugMode&&console.debug(`[EventModule] 注册事件监听器: ${i}, 当前监听器数量: ${this.listeners.get(i).length}`)}off(e,t){const i=String(e);if(!this.listeners.has(i)){this.debugMode&&console.warn(`[EventModule] 尝试移除不存在的事件监听器: ${i}`);return}const s=this.listeners.get(i),r=s.indexOf(t);r!==-1?(s.splice(r,1),this.debugMode&&console.debug(`[EventModule] 移除事件监听器: ${i}, 剩余监听器数量: ${s.length}`)):this.debugMode&&console.warn(`[EventModule] 尝试移除的回调函数未找到: ${i}`)}trigger(e,t){const i=String(e);if(!this.listeners.has(i)){this.debugMode&&(console.warn(`[EventModule] 触发事件但未找到监听器: ${i}`),console.debug("[EventModule] 当前已注册的事件类型:",Array.from(this.listeners.keys())));return}const s=this.listeners.get(i);this.debugMode&&console.debug(`[EventModule] 触发事件: ${i}, 监听器数量: ${s.length}`,t),s.forEach((r,o)=>{try{r(t)}catch(a){console.error(`[EventModule] 事件监听器执行错误 [${i}] #${o}:`,a)}})}};const _c=1;class _2{engine;constructor(e){this.engine=e}init(){const e=new w.DirectionalLight(16777215,1);e.position.set(100,200,100),e.castShadow=!0,e.shadow.mapSize.width=2048,e.shadow.mapSize.height=2048,e.shadow.camera.near=.1,e.shadow.camera.far=5e3,e.shadow.bias=-5e-5,e.shadow.normalBias=.02;const t=50;e.shadow.camera.left=-t,e.shadow.camera.right=t,e.shadow.camera.top=t,e.shadow.camera.bottom=-t,e.shadow.radius=2,e.shadow.intensity=_c;const i=new w.DirectionalLight(16777215,2);this.engine.scene.add(e),this.engine.scene.add(i),this.engine.scene.dirLight=i;const s=new w.AmbientLight(16777215,2);this.engine.scene.add(s)}}class w2{engine;behavior;isCtrlDown=!1;isShiftDown=!1;hoverOldId=null;timeOutEvent;selectionBox=null;isBoxSelecting=!1;selectionStart=new w.Vector2;selectionEnd=new w.Vector2;suppressClickOnce=!1;selectionThreshold=5;tempInstanceMatrix=new w.Matrix4;tempScale=new w.Vector3;constructor(e){this.engine=e}init(){this.behavior=this.engine.handelBehaved,this.ensureSelectionBox(),this.behavior.init(this)}active(){this.behavior.active()}disActive(){this.cancelBoxSelection(),this.behavior.disActive()}handelKeyCtrlUp(){this.isCtrlDown=!1,this.isBoxSelecting&&this.cancelBoxSelection()}handelKeyCtrlDown(){this.isCtrlDown=!0}handelKeyShiftUp(){this.isShiftDown=!1}handelKeyShiftDown(){this.isShiftDown=!0}handleMouseDown(e){e.button!==0||!this.isBoxSelectionModifierDown()||(this.isBoxSelecting=!0,this.selectionStart.set(e.offsetX,e.offsetY),this.selectionEnd.copy(this.selectionStart),this.suppressClickOnce=!1,this.clearHoverFeedback(),this.updateSelectionBox(),this.engine.controls&&(this.engine.controls.enabled=!1))}handelKeyEscDown(){this.engine.modelToolModule.unhighlightAllModels()}handleMouseMove(e){if(this.clearHoverTimeout(),this.isBoxSelecting){this.selectionEnd.set(e.offsetX,e.offsetY),this.clearHoverFeedback(),this.updateSelectionBox();return}if(e.catch!=null&&(this.engine.hoverHighLight.showModelNameTag(null,null),this.timeOutEvent=setTimeout(()=>{this.hoverOldId=null;const i=this.getCatchMeshs(e,!0);i!=null&&i.length>0&&this.engine.hoverHighLight.showModelNameTag({url:i[0].url,ids:[i[0].name]},e.catch.point)},1e3)),!this.engine.engineStatus.isFree){this.engine.hoverHighLight.clearHighlight();return}const t=this.getCatchMeshs(e);if(t!=null&&t.length>0){this.engine.hoverHighLight.hightMesh(t);return}e.catch==null&&this.engine.hoverHighLight.clearHighlight()}handleMouseUp(e){if(!this.isBoxSelecting)return;this.selectionEnd.set(e.offsetX,e.offsetY);const t=this.hasSelectionBox(),i=t?this.collectModelsInSelection():[];this.isBoxSelecting=!1,this.hideSelectionBox(),this.engine.controls&&(this.engine.controls.enabled=!0),t&&(this.isBoxDeselectMode()?this.applyBoxDeselection(i):this.applyBoxSelection(i),this.suppressClickOnce=!0)}getCatchMeshs(e,t=!1){if(e.catch==null)return this.hoverOldId=null,null;if(e.catch.object.isInstance){const c=e.catch.object,h=e.catch.object.id,f=this.engine.models.find(p=>p.url==c.url)?.nodesMap?.get(h),u=new Map;f?.indexes.forEach(p=>{this.getSceneModel(p[0])instanceof w.InstancedMesh&&(u.has(p[0])||u.set(p[0],[]),u.get(p[0])?.push(p[1]))});const g=[];return u.forEach((p,m)=>{const A=this.getSceneModel(m);p.forEach(x=>{const b=A.geometry.clone();b.applyMatrix4(A.matrixs[x]),g.push(new w.Mesh(b,A.material))})}),this.hoverOldId==h?[]:(this.hoverOldId=h,t||this.engine.hoverHighLight.clearHighlight(),g)}const s=e.catch.object,r=s.name,l=this.engine.models.find(c=>c.url===s.url)?.nodesMap?.get(r)?.infos?.map(c=>c.mesh)??[];return this.hoverOldId==r?[]:(this.hoverOldId=r,t||this.engine.hoverHighLight.clearHighlight(),l)}handleMouseClick(e){if(this.suppressClickOnce){this.suppressClickOnce=!1;return}if(this.isShiftDown){if(e.catch!=null){const s=e.catch.object;this.applyBoxDeselection([{url:s.url,ids:[s.name]}])}return}if(e.catch!=null){const i=e.catch,s=i.object;if(!this.isCtrlDown){this.engine.modelToolModule.unhighlightAllModels();const o=new CustomEvent("D3ElementClick",{detail:{id:-1}});window.dispatchEvent(o)}this.engine.controlModule.orbitControls.origin.set(i.point.x,i.point.y,i.point.z),this.engine.modelToolModule.highlightModel([{url:s.url,ids:[s.name]}]),this.engine.events.trigger(Et.Click,[{url:s.url,ids:[s.name]}]);const r=new CustomEvent("D3ElementClick",{detail:{id:s.name}});window.dispatchEvent(r);return}const t=new CustomEvent("D3ElementClick",{detail:{id:-1}});window.dispatchEvent(t),this.engine.modelToolModule.unhighlightAllModels()}handleMouseDoubleClick(e){if(!e.catch){this.engine.viewCube.CameraGoHome(500);return}const t=e.catch,i=t.object,r=this.engine.models.find(l=>l.url===i.url)?.nodesMap?.get(i.name);if(!r)return;if(t.object.isInstance){const l=t.matrix,c=[];r.indexes.forEach(d=>{const f=this.getSceneModel(d[0]);f?.geometry?.boundingSphere||f?.geometry?.computeBoundingSphere?.();const u=f?.geometry?.boundingSphere;if(!u)return;const g=new w.Box3,p=u.center.clone().applyMatrix4(l),m=u.radius,A=new w.Vector3().setFromMatrixScale(l),x=m*Math.max(A.x,A.y,A.z);g.min.set(p.x-x,p.y-x,p.z-x),g.max.set(p.x+x,p.y+x,p.z+x),c.push(g)});const h=this.getMergedBox(c);h!=null&&this.engine.viewCube.zoomToModel(h);return}const o=r.infos.map(l=>l.box).filter(l=>l instanceof w.Box3),a=this.getMergedBox(o);a!=null&&this.engine.viewCube.zoomToModel(a)}handleMouseClickInstance(e){return e.intersectObjects(this.engine.scene.children.filter(t=>t instanceof w.InstancedMesh),!0)}ensureSelectionBox(){if(this.selectionBox!=null)return;const e=document.createElement("div");e.style.position="absolute",e.style.left="0px",e.style.top="0px",e.style.display="none",e.style.pointerEvents="none",e.style.border="1px dashed #00aaff",e.style.backgroundColor="rgba(0, 170, 255, 0.12)",e.style.boxSizing="border-box",e.style.zIndex="1001",this.engine.container?.appendChild(e),this.selectionBox=e}updateSelectionBox(){if(this.selectionBox==null)return;if(!this.hasSelectionBox()){this.selectionBox.style.display="none";return}const e=this.getSelectionRect();this.selectionBox.style.display="block",this.selectionBox.style.left=`${e.left}px`,this.selectionBox.style.top=`${e.top}px`,this.selectionBox.style.width=`${e.right-e.left}px`,this.selectionBox.style.height=`${e.bottom-e.top}px`}hideSelectionBox(){this.selectionBox!=null&&(this.selectionBox.style.display="none")}cancelBoxSelection(){this.isBoxSelecting=!1,this.hideSelectionBox(),this.engine.controls&&(this.engine.controls.enabled=!0)}clearHoverTimeout(){this.timeOutEvent!=null&&(clearTimeout(this.timeOutEvent),this.timeOutEvent=null)}clearHoverFeedback(){this.hoverOldId=null,this.engine.hoverHighLight.clearHighlight(),this.engine.hoverHighLight.showModelNameTag(null,null)}hasSelectionBox(){return Math.abs(this.selectionEnd.x-this.selectionStart.x)>=this.selectionThreshold&&Math.abs(this.selectionEnd.y-this.selectionStart.y)>=this.selectionThreshold}getSelectionRect(){return{left:Math.min(this.selectionStart.x,this.selectionEnd.x),top:Math.min(this.selectionStart.y,this.selectionEnd.y),right:Math.max(this.selectionStart.x,this.selectionEnd.x),bottom:Math.max(this.selectionStart.y,this.selectionEnd.y)}}isContainMode(){return this.selectionEnd.x>=this.selectionStart.x&&this.selectionEnd.y>=this.selectionStart.y}isBoxSelectionModifierDown(){return this.isCtrlDown}isBoxDeselectMode(){return this.isShiftDown}collectModelsInSelection(){const e=this.getSelectionRect(),t=this.isContainMode(),i=new Map;return this.engine.models?.forEach(s=>{!s?.url||!s?.nodesMap||s.nodesMap.forEach((r,o)=>{const a=this.getNodeWorldBox(r),l=this.projectBoxToScreenRect(a);l==null||!(t?this.containsRect(e,l):this.intersectsRect(e,l))||(i.has(s.url)||i.set(s.url,new Set),i.get(s.url)?.add(o))})}),Array.from(i.entries()).map(([s,r])=>({url:s,ids:Array.from(r)}))}applyBoxSelection(e){const t=this.excludeHighlightedModels(e);t.length!==0&&(this.engine.modelToolModule.highlightModel(t),this.engine.events.trigger(Et.SelectionChanged,t))}applyBoxDeselection(e){const t=this.keepHighlightedModels(e);t.length!==0&&(this.engine.modelToolModule.unhighlightModel(t),this.removeModelsFromHighlightState(t),this.engine.events.trigger(Et.SelectionChanged,t))}excludeHighlightedModels(e){const t=new Map;return(this.engine.engineStatus.highlightModels??[]).forEach(i=>{t.has(i.url)||t.set(i.url,new Set),i.ids.forEach(s=>t.get(i.url)?.add(s))}),e.map(i=>({url:i.url,ids:i.ids.filter(s=>!t.get(i.url)?.has(s))})).filter(i=>i.ids.length>0)}keepHighlightedModels(e){const t=new Map;return(this.engine.engineStatus.highlightModels??[]).forEach(i=>{t.has(i.url)||t.set(i.url,new Set),i.ids.forEach(s=>t.get(i.url)?.add(s))}),e.map(i=>({url:i.url,ids:i.ids.filter(s=>t.get(i.url)?.has(s))})).filter(i=>i.ids.length>0)}removeModelsFromHighlightState(e){const t=new Map;e.forEach(i=>{t.has(i.url)||t.set(i.url,new Set),i.ids.forEach(s=>t.get(i.url)?.add(s))}),this.engine.engineStatus.highlightModels=(this.engine.engineStatus.highlightModels??[]).map(i=>({url:i.url,ids:i.ids.filter(s=>!t.get(i.url)?.has(s))})).filter(i=>i.ids.length>0)}getNodeWorldBox(e){if(Array.isArray(e?.infos)&&e.infos.length>0){const t=e.infos.map(i=>i?.box).filter(i=>i instanceof w.Box3);return this.getMergedBox(t)}if(Array.isArray(e?.indexes)&&e.indexes.length>0){const t=[];return e.indexes.forEach(i=>{const s=this.getSceneModel(i[0]),r=this.getInstanceWorldBox(s,i[1]);r!=null&&t.push(r)}),this.getMergedBox(t)}return null}getInstanceWorldBox(e,t){if(!(e instanceof w.InstancedMesh))return null;e.geometry.boundingBox||e.geometry.computeBoundingBox();const i=e.geometry.boundingBox;if(!i)return null;if(typeof e.getMatrixAt=="function")e.getMatrixAt(t,this.tempInstanceMatrix);else if(e.matrixs?.[t])this.tempInstanceMatrix.copy(e.matrixs[t]);else return null;return this.tempScale.setFromMatrixScale(this.tempInstanceMatrix),Math.abs(this.tempScale.x)+Math.abs(this.tempScale.y)+Math.abs(this.tempScale.z)<1e-6?null:i.clone().applyMatrix4(this.tempInstanceMatrix)}projectBoxToScreenRect(e){if(e==null||e.isEmpty())return null;const t=[new w.Vector3(e.min.x,e.min.y,e.min.z),new w.Vector3(e.min.x,e.min.y,e.max.z),new w.Vector3(e.min.x,e.max.y,e.min.z),new w.Vector3(e.min.x,e.max.y,e.max.z),new w.Vector3(e.max.x,e.min.y,e.min.z),new w.Vector3(e.max.x,e.min.y,e.max.z),new w.Vector3(e.max.x,e.max.y,e.min.z),new w.Vector3(e.max.x,e.max.y,e.max.z)];let i=1/0,s=1/0,r=-1/0,o=-1/0;return t.forEach(a=>{const l=new lt(this.engine.camera,this.engine.renderer,this.engine.scene).worldToScreen(a);!Number.isFinite(l.x)||!Number.isFinite(l.y)||(i=Math.min(i,l.x),s=Math.min(s,l.y),r=Math.max(r,l.x),o=Math.max(o,l.y))}),!Number.isFinite(i)||!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(o)?null:{left:i,top:s,right:r,bottom:o}}containsRect(e,t){return t.left>=e.left&&t.top>=e.top&&t.right<=e.right&&t.bottom<=e.bottom}intersectsRect(e,t){return!(t.right<e.left||t.left>e.right||t.bottom<e.top||t.top>e.bottom)}getMergedBox(e){if(e.length===0)return null;const t=new w.Box3().makeEmpty();return e.forEach(i=>t.union(i)),t.isEmpty()?null:t}getSceneModel(e){return this.engine.scene.children.find(t=>t.index===e)??this.engine.scene.children[e]}}class S2{engine;highlightMaterial;translucentMaterial;constructor(e){this.engine=e,this.highlightMaterial=new w.MeshBasicMaterial({color:43775,depthTest:!1,depthWrite:!1,transparent:!0,opacity:.8,side:w.DoubleSide}),this.translucentMaterial=new w.MeshBasicMaterial({color:16777215,transparent:!0,opacity:.05,side:w.DoubleSide}),this.highlightMaterial.clippingPlanes=this.engine.sectionPlane,this.translucentMaterial.clippingPlanes=this.engine.sectionPlane,this.engine.events?.on?.(Cs.EngineFree,()=>{this.restoreSplitModelsOnIdle()})}split_merge_model(e){if(e.isSplit||e instanceof w.InstancedMesh)return;e.geometry!=null&&(e.__mergedGeometryBackup=e.geometry);let t=e.materialClone.clone(),i=Yn(e.geometrys,!0);i.computeVertexNormals(),i.groups.forEach(s=>{s.materialIndex=0}),e.geometry=i,e.material=[t,this.highlightMaterial,this.translucentMaterial],e.needsUpdate=!0,e.isSplit=!0}un_split_merge_model(e){if(e==null||e instanceof w.InstancedMesh||e.isSplit!==!0||this.shouldKeepSplitState(e))return;const t=e.__mergedGeometryBackup;if(t!=null){const r=e.geometry;e.geometry=t,e.material=e.materialClone?.clone?e.materialClone.clone():e.materialClone,e.needsUpdate=!0,e.isSplit=!1,r&&r!==t&&typeof r.dispose=="function"&&r.dispose(),console.log("merge");return}if(!Array.isArray(e.geometrys)||e.geometrys.length===0)return;const i=e.geometry,s=Yn(e.geometrys,!1);s!=null&&(s.computeVertexNormals(),e.geometry=s,e.material=e.materialClone?.clone?e.materialClone.clone():e.materialClone,e.needsUpdate=!0,e.isSplit=!1,i&&i!==s&&typeof i.dispose=="function"&&i.dispose(),console.log("merge"))}shouldKeepSplitState(e){const t=e?.geometry?.groups;return!Array.isArray(t)||t.length===0?!1:t.some(i=>(typeof i.materialIndex=="number"?i.materialIndex:0)!==0||i.visible===!1)}restoreSplitModelsOnIdle(){this.engine?.scene?.children&&this.engine.scene.children.forEach(e=>{const t=e;t instanceof w.Mesh&&t.isSplit===!0&&this.un_split_merge_model(t)})}getSceneModel(e){return this.engine.scene.children.find(t=>t.index==e)}updateMaterial(){let e=0;this.engine.engineStatus.highlightModels?.forEach(t=>{e=e+t.ids.length}),e>20?(this.highlightMaterial.depthTest=!0,this.highlightMaterial.depthWrite=!0,this.highlightMaterial.transparent=!1):(this.highlightMaterial.depthTest=!1,this.highlightMaterial.depthWrite=!1,this.highlightMaterial.transparent=!0)}highlightModel(e){e.forEach(t=>{let i=new Map;t.ids.forEach(r=>{let o=this.engine.models.find(a=>a.url==t.url).nodesMap.get(r);o!=null&&o.indexes!=null&&o.indexes.forEach(a=>{this.getSceneModel(a[0])instanceof w.InstancedMesh?i.has(a[0])?i.get(a[0])?.push(a[1]):i.set(a[0],[a[1]]):(this.split_merge_model(this.getSceneModel(a[0])),this.getSceneModel(a[0]).geometry.groups[a[1]].materialIndex=1)})}),C2(i,this.engine);let s=this.engine.engineStatus.highlightModels.find(r=>r.url==t.url);s!=null?s.ids.push(...t.ids):this.engine.engineStatus.highlightModels.push(t)}),this.updateMaterial()}unhighlightModel(e){e.forEach(t=>{let i=new Map;t.ids.forEach(s=>{let r=this.engine.models.find(o=>o.url==t.url).nodesMap.get(s);r!=null&&r.indexes!=null&&r.indexes.forEach(o=>{this.getSceneModel(o[0])instanceof w.InstancedMesh?i.has(o[0])?i.get(o[0])?.push(o[1]):i.set(o[0],[o[1]]):this.getSceneModel(o[0]).geometry.groups[o[1]].materialIndex=0})}),H0(i,this.engine,"highlightModel")}),this.updateMaterial()}unhighlightAllModels(e=!0){this.engine.engineStatus.highlightModels.forEach(t=>{this.unhighlightModel([t])}),e&&(this.engine.engineStatus.highlightModels=[]),this.updateMaterial()}hideModel(e){e.forEach(t=>{let i=new Map;t.ids.forEach(r=>{let o=this.engine.models.find(a=>a.url==t.url).nodesMap.get(r);this.engine.modelEdge.hideModelEdge(t.url,r),o!=null&&o.indexes!=null&&o.indexes.forEach(a=>{const l=this.getSceneModel(a[0]);l instanceof w.InstancedMesh?i.has(a[0])?i.get(a[0])?.push(a[1]):i.set(a[0],[a[1]]):(this.split_merge_model(this.getSceneModel(a[0])),l.geometry.groups[a[1]].materialIndex=-1,l.geometry.groups[a[1]].visible=!1)})}),i.size>0&&E2(i,this.engine);let s=this.engine.engineStatus.hideModels.find(r=>r.url==t.url);s!=null?s.ids.push(...t.ids):this.engine.engineStatus.hideModels.push({url:t.url,ids:t.ids}),this.engine.engineStatus.highlightModels=[]})}showModel(e){e.forEach(t=>{let i=new Map;t.ids.forEach(r=>{let o=this.engine.models.find(a=>a.url==t.url).nodesMap.get(r);this.engine.modelEdge.showModelEdge(t.url,r),o!=null&&o.indexes!=null&&o.indexes.forEach(a=>{const l=this.getSceneModel(a[0]);l instanceof w.InstancedMesh?i.has(a[0])?i.get(a[0])?.push(a[1]):i.set(a[0],[a[1]]):(l.geometry.groups[a[1]].materialIndex=0,l.geometry.groups[a[1]].visible=!0)})}),i.size>0&&X0(i,this.engine);let s=this.engine.engineStatus.hideModels.find(r=>r.url==t.url);s&&(t.ids.forEach(r=>{const o=s.ids.indexOf(r);o!==-1&&s.ids.splice(o,1)}),s.ids.length===0&&(this.engine.engineStatus.hideModels=this.engine.engineStatus.hideModels.filter(r=>r!==s)))})}isolateModel(e){let t=[];this.engine.models.forEach(i=>{let s={url:i.url,ids:[]},r=e.find(o=>o.url==i.url);for(let o of i.nodesMap)r==null?s.ids.push(o[0]):r.ids.includes(o[0])||s.ids.push(o[0]);t.push(s)});debugger;this.unhighlightAllModels(),this.hideModel(t)}translucentOtherModel(e){let t=[];this.engine.models.forEach(i=>{let s={url:i.url,ids:[]},r=e.find(o=>o.url==i.url);for(let o of i.nodesMap)r==null?s.ids.push(o[0]):r.ids.includes(o[0])||s.ids.push(o[0]);t.push(s)}),this.translucentModel(t)}setModelColor(e,t){e.material.color.set(t)}setAllModelsColor(e){this.engine.scene.children.forEach(t=>{t.isMesh})}restoreAllModelsColor(){this.engine.scene.children.forEach(e=>{e.isMesh})}translucentModel(e){this.unhighlightAllModels(),e.forEach(t=>{let i=new Map;t.ids.forEach(r=>{let o=this.engine.models.find(a=>a.url==t.url).nodesMap.get(r);o!=null&&o.indexes!=null&&o.indexes.forEach(a=>{const l=this.getSceneModel(a[0]);l instanceof w.InstancedMesh?i.has(a[0])?i.get(a[0])?.push(a[1]):i.set(a[0],[a[1]]):(this.split_merge_model(this.getSceneModel(a[0])),l.geometry.groups[a[1]].materialIndex=2)})}),M2(i,this.engine);let s=this.engine.engineStatus.translucentModels.find(r=>r.url==t.url);s!=null?s.ids.push(...t.ids):this.engine.engineStatus.translucentModels.push({url:t.url,ids:t.ids})}),this.engine.engineStatus.highlightModels=[]}unTranslucentModel(){this.engine.engineStatus.translucentModels.forEach(t=>{let i=new Map;t.ids.forEach(s=>{let r=this.engine.models.find(o=>o.url==t.url).nodesMap.get(s);r!=null&&r.indexes!=null&&r.indexes.forEach(o=>{const a=this.getSceneModel(o[0]);a instanceof w.InstancedMesh?i.has(o[0])?i.get(o[0])?.push(o[1]):i.set(o[0],[o[1]]):(this.split_merge_model(this.getSceneModel(o[0])),a.geometry.groups[o[1]].materialIndex=0)})}),i.size>0&&X0(i,this.engine),H0(i,this.engine,"translucentModel")}),this.engine.engineStatus.translucentModels=[]}showAllModels(){this.engine.engineStatus.hideModels&&this.engine.engineStatus.hideModels.length>0&&this.showModel(this.engine.engineStatus.hideModels),this.engine.engineStatus.hideModels=[],this.unhighlightAllModels()}batchSelectSameLevelTypeModel(e){if(e.length==0)return;let t=e[0],i=this.engine.modelMapperBatch.getModelMapper(t.url,t.ids[0]);this.engine.modelMapperBatch.getModelsWithLevelType(i.levelName,i.typeName,s=>{this.engine.modelToolModule.highlightModel(s)})}batchSelectSameLevelModel(e){if(e.length==0)return;let t=e[0],i=this.engine.modelMapperBatch.getModelMapper(t.url,t.ids[0]);this.engine.modelMapperBatch.getModelsWithLevel(i.levelName,s=>{this.engine.modelToolModule.highlightModel(s)})}batchSelectSameTypeModel(e){if(e.length==0)return;let t=e[0],i=this.engine.modelMapperBatch.getModelMapper(t.url,t.ids[0]);this.engine.modelMapperBatch.getModelsWithType(i.typeName,s=>{this.engine.modelToolModule.highlightModel(s)})}}function C2(n,e){n.forEach((t,i)=>{const s=ga(e,i);if(!(s instanceof w.InstancedMesh))return;const r=s.geometry,o=new w.MeshBasicMaterial({color:43775,depthTest:!1,depthWrite:!1,transparent:!0,opacity:.5,side:w.DoubleSide}),a=new w.InstancedMesh(r,o,t.length);a.name="highlightModel",a.key=i;const l=new Map,c=new w.Matrix4,h=new w.Matrix4;h.makeScale(0,0,0),t.forEach((d,f)=>{s.getMatrixAt(d,c),l.set(d,c.clone()),s.setMatrixAt(d,h),a.setMatrixAt(f,c)}),s.instanceMatrix.needsUpdate=!0,a.instanceMatrix.needsUpdate=!0,e.scene.add(a)})}function H0(n,e,t){n.forEach((i,s)=>{const r=ga(e,s);if(!(r instanceof w.InstancedMesh))return;i.forEach(a=>{const l=r.matrixsClone[a];l&&r.setMatrixAt(a,l)}),r.instanceMatrix.needsUpdate=!0,e.scene.children.filter(a=>a.key==s&&a.name==t).forEach(a=>{e.scene.remove(a)})})}function M2(n,e){n.forEach((t,i)=>{const s=ga(e,i);if(!(s instanceof w.InstancedMesh))return;const r=s.geometry,o=new w.MeshBasicMaterial({color:16777215,transparent:!0,opacity:.05,side:w.DoubleSide}),a=new w.InstancedMesh(r,o,t.length);a.name="translucentModel",a.key=i;const l=new Map,c=new w.Matrix4,h=new w.Matrix4;h.makeScale(0,0,0),t.forEach((d,f)=>{s.getMatrixAt(d,c),l.set(d,c.clone()),s.setMatrixAt(d,h),a.setMatrixAt(f,c)}),s.instanceMatrix.needsUpdate=!0,a.instanceMatrix.needsUpdate=!0,e.scene.add(a)})}function E2(n,e){e.scene.children.filter(t=>t.name=="highlightModel").forEach(t=>{e.scene.remove(t)}),n.forEach((t,i)=>{const s=ga(e,i);if(!(s instanceof w.InstancedMesh))return;const r=new Map,o=new w.Matrix4,a=new w.Matrix4;a.makeScale(0,0,0),t.forEach((l,c)=>{s.getMatrixAt(l,o),r.set(l,o.clone()),s.setMatrixAt(l,a)}),s.instanceMatrix.needsUpdate=!0})}function X0(n,e){n.forEach((t,i)=>{const s=ga(e,i);s instanceof w.InstancedMesh&&(t.forEach(r=>{const o=s.matrixs[r];o&&s.setMatrixAt(r,o)}),s.instanceMatrix.needsUpdate=!0)})}function ga(n,e){return n.scene.children.find(t=>t.index==e)}const q0="advanced";class I2{engine;currentMode="";isManualMode=!1;gtaoPass=null;ssaoPass=null;saturationPass=null;outputPass=null;fxaaPass=null;constructor(e){this.engine=e}init(){this.cachePassReferences(),this.autoSwitch(q0)}switchModel(e){this.isManualMode=!0,this.currentMode=e,this.applyMode(e)}autoSwitch(e){this.isManualMode||(this.currentMode=e,this.applyMode(e))}enableAutoMode(){this.isManualMode=!1}get isManual(){return this.isManualMode}setMode(e){this.isManualMode=!0,this.currentMode=e,this.applyMode(e)}getCurrentMode(){return this.currentMode}cachePassReferences(){this.engine.composerModule?.composer&&(this.engine.composerModule.gtaoPass&&(this.gtaoPass=this.engine.composerModule.gtaoPass),this.engine.composerModule.ssaoPass&&(this.ssaoPass=this.engine.composerModule.ssaoPass),this.engine.composerModule.saturationPass&&(this.saturationPass=this.engine.composerModule.saturationPass),this.engine.composerModule.outputPass&&(this.outputPass=this.engine.composerModule.outputPass),this.engine.composerModule.fxaaPass&&(this.fxaaPass=this.engine.composerModule.fxaaPass))}applyMode(e){switch(e){case"simple":this.setShadows(!1),this.setGTAO(!1),this.setSSAO(!1),this.setSaturation(!0);break;case"balance":this.setShadows(!0),this.setGTAO(!1),this.setSSAO(!1),this.setSaturation(!0);break;case"advanced":this.setShadows(!0),this.setSSAO(!1),this.setGTAO(!0),this.setSaturation(!0);break;default:console.warn(`[EngineModelModule] Unknown mode: ${e}`)}this.engine.updateVersionDisplay?.()}setShadows(e){this.engine.renderer&&(this.engine.renderer.shadowMap.enabled=e);const t=this.engine.scene?.children.find(i=>i instanceof w.DirectionalLight);t&&(t.castShadow=e),this.engine.scene?.traverse(i=>{i.material&&(i.castShadow!==void 0&&(i.castShadow=e),i.receiveShadow!==void 0&&(i.receiveShadow=e))})}setGTAO(e){this.engine.composerModule?.composer&&this.gtaoPass&&(this.gtaoPass.enabled=e)}setSSAO(e){this.engine.composerModule?.composer&&this.ssaoPass&&(this.ssaoPass.enabled=e)}setSaturation(e){this.saturationPass&&(this.saturationPass.enabled=e)}setOutputPass(e){this.outputPass&&(this.outputPass.enabled=e)}setFXAA(e){this.fxaaPass&&(this.fxaaPass.enabled=e)}setPerformanceMode(){this.setMode("simple")}setBalancedMode(){this.setMode("balance")}setQualityMode(){this.setMode("advanced")}setSuperQualityMode(){this.setMode("superAdvanced")}setShadowQuality(e){const t=this.engine.scene?.children.find(r=>r instanceof w.DirectionalLight),s={low:1024,medium:2048,high:2048}[e];t?.shadow&&s&&(t.shadow.mapSize.width=s,t.shadow.mapSize.height=s,t.shadow.map?.dispose(),t.shadow.map=null)}setSaturationValue(e){this.saturationPass&&(this.saturationPass.uniforms.saturation.value=e)}setContrastValue(e){this.saturationPass&&(this.saturationPass.uniforms.contrast.value=e)}setGTAOIntensity(e){this.gtaoPass&&(this.gtaoPass.blendIntensity=e)}}class wc{engine;overlayMaterial;overlayMeshes=[];animState="idle";animStartTime=0;static FADE_IN_MS=200;static FADE_OUT_MS=150;tagDiv;constructor(e){this.engine=e,this.init();const t=document.createElement("div");this.tagDiv=t,t.className="tagDiv",t.style.position="absolute",t.style.top="0px",t.style.left="0px",t.style.borderRadius="10px",t.style.pointerEvents="none",this.engine.container.appendChild(this.tagDiv)}showModelNameTag(e,t){if(e==null){this.tagDiv.style.display="none";return}let i=this.engine.models.find(a=>a.url==e.url);if(i==null){this.tagDiv.style.display="none";return}let s=i.nodesMap.get(e.ids[0]);if(s.infos&&s.infos.length>0){let a=s.infos[0].name.replace(/\s*\[[a-f0-9-]+\]$/,"");this.tagDiv.innerHTML=a}const o=this.engine.worldToScreen.worldToScreen(t);this.tagDiv?(this.tagDiv.style.left=o.x+10+this.engine.reactBoundingClientRect.left+"px",this.tagDiv.style.top=o.y-10+this.engine.reactBoundingClientRect.top+"px",this.tagDiv.style.display="block"):this.tagDiv&&(this.tagDiv.style.display="none")}init(){this.overlayMaterial=new w.MeshBasicMaterial({color:16777215,transparent:!0,opacity:0,blending:w.AdditiveBlending,depthWrite:!1}),this.overlayMaterial.clippingPlanes=this.engine.sectionPlane}hightMesh(e,t=16777215,i=.15){this.animState==="fadeOut"&&this.removeOverlayMeshes();const s=(Array.isArray(e)?e:e?[e]:[]).filter(r=>r?.geometry);if(s.length===0){this.clearHighlight();return}this.overlayMaterial.color.set(t),this.overlayMaterial.opacity=0,this.overlayMaterial.userData.targetOpacity=i;for(const r of s){let o=r.geometry.clone();o.computeVertexNormals();const a=new w.Mesh(o,this.overlayMaterial);r.updateWorldMatrix(!0,!1),a.matrix.copy(r.matrixWorld),a.matrixAutoUpdate=!1,this.engine.scene.add(a),this.overlayMeshes.push(a)}this.animState="fadeIn",this.animStartTime=performance.now()}clearHighlight(){this.overlayMeshes.length===0||this.animState==="fadeOut"||(this.animState="fadeOut",this.animStartTime=performance.now())}update(){if(this.animState==="idle"||this.overlayMeshes.length===0)return;const e=performance.now()-this.animStartTime,t=this.overlayMaterial.userData.targetOpacity??.35;if(this.animState==="fadeIn"){const i=Math.min(e/wc.FADE_IN_MS,1);this.overlayMaterial.opacity=this.easeOutQuad(i)*t,i>=1&&(this.animState="idle")}else if(this.animState==="fadeOut"){const i=Math.min(e/wc.FADE_OUT_MS,1);this.overlayMaterial.opacity=(1-this.easeOutQuad(i))*t,i>=1&&(this.removeOverlayMeshes(),this.animState="idle")}}removeOverlayMeshes(){for(const e of this.overlayMeshes)this.engine.scene.remove(e);this.overlayMeshes=[]}easeOutQuad(e){return 1-(1-e)*(1-e)}dispose(){this.removeOverlayMeshes(),this.overlayMaterial.dispose(),this.animState="idle"}}var Sc={exports:{}},T2=Sc.exports,Y0;function D2(){return Y0||(Y0=1,(function(n,e){(function(t,i){n.exports=i()})(T2,function(){var t=function(){function i(u){return o.appendChild(u.dom),u}function s(u){for(var g=0;g<o.children.length;g++)o.children[g].style.display=g===u?"block":"none";r=u}var r=0,o=document.createElement("div");o.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",o.addEventListener("click",function(u){u.preventDefault(),s(++r%o.children.length)},!1);var a=(performance||Date).now(),l=a,c=0,h=i(new t.Panel("FPS","#0ff","#002")),d=i(new t.Panel("MS","#0f0","#020"));if(self.performance&&self.performance.memory)var f=i(new t.Panel("MB","#f08","#201"));return s(0),{REVISION:16,dom:o,addPanel:i,showPanel:s,begin:function(){a=(performance||Date).now()},end:function(){c++;var u=(performance||Date).now();if(d.update(u-a,200),u>l+1e3&&(h.update(1e3*c/(u-l),100),l=u,c=0,f)){var g=performance.memory;f.update(g.usedJSHeapSize/1048576,g.jsHeapSizeLimit/1048576)}return u},update:function(){a=this.end()},domElement:o,setMode:s}};return t.Panel=function(i,s,r){var o=1/0,a=0,l=Math.round,c=l(window.devicePixelRatio||1),h=80*c,d=48*c,f=3*c,u=2*c,g=3*c,p=15*c,m=74*c,A=30*c,x=document.createElement("canvas");x.width=h,x.height=d,x.style.cssText="width:80px;height:48px";var b=x.getContext("2d");return b.font="bold "+9*c+"px Helvetica,Arial,sans-serif",b.textBaseline="top",b.fillStyle=r,b.fillRect(0,0,h,d),b.fillStyle=s,b.fillText(i,f,u),b.fillRect(g,p,m,A),b.fillStyle=r,b.globalAlpha=.9,b.fillRect(g,p,m,A),{dom:x,update:function(y,_){o=Math.min(o,y),a=Math.max(a,y),b.fillStyle=r,b.globalAlpha=1,b.fillRect(0,0,h,p),b.fillStyle=s,b.fillText(l(y)+" "+i+" ("+l(o)+"-"+l(a)+")",f,u),b.drawImage(x,g+c,p,m-c,A,g,p,m-c,A),b.fillRect(g+m-c,p,c,A),b.fillStyle=r,b.globalAlpha=.9,b.fillRect(g+m-c,p,c,l((1-y/_)*A))}}},t})})(Sc)),Sc.exports}var B2=D2();const P2=Qm(B2);var mo=Object.freeze({Linear:Object.freeze({None:function(n){return n},In:function(n){return n},Out:function(n){return n},InOut:function(n){return n}}),Quadratic:Object.freeze({In:function(n){return n*n},Out:function(n){return n*(2-n)},InOut:function(n){return(n*=2)<1?.5*n*n:-.5*(--n*(n-2)-1)}}),Cubic:Object.freeze({In:function(n){return n*n*n},Out:function(n){return--n*n*n+1},InOut:function(n){return(n*=2)<1?.5*n*n*n:.5*((n-=2)*n*n+2)}}),Quartic:Object.freeze({In:function(n){return n*n*n*n},Out:function(n){return 1- --n*n*n*n},InOut:function(n){return(n*=2)<1?.5*n*n*n*n:-.5*((n-=2)*n*n*n-2)}}),Quintic:Object.freeze({In:function(n){return n*n*n*n*n},Out:function(n){return--n*n*n*n*n+1},InOut:function(n){return(n*=2)<1?.5*n*n*n*n*n:.5*((n-=2)*n*n*n*n+2)}}),Sinusoidal:Object.freeze({In:function(n){return 1-Math.sin((1-n)*Math.PI/2)},Out:function(n){return Math.sin(n*Math.PI/2)},InOut:function(n){return .5*(1-Math.sin(Math.PI*(.5-n)))}}),Exponential:Object.freeze({In:function(n){return n===0?0:Math.pow(1024,n-1)},Out:function(n){return n===1?1:1-Math.pow(2,-10*n)},InOut:function(n){return n===0?0:n===1?1:(n*=2)<1?.5*Math.pow(1024,n-1):.5*(-Math.pow(2,-10*(n-1))+2)}}),Circular:Object.freeze({In:function(n){return 1-Math.sqrt(1-n*n)},Out:function(n){return Math.sqrt(1- --n*n)},InOut:function(n){return(n*=2)<1?-.5*(Math.sqrt(1-n*n)-1):.5*(Math.sqrt(1-(n-=2)*n)+1)}}),Elastic:Object.freeze({In:function(n){return n===0?0:n===1?1:-Math.pow(2,10*(n-1))*Math.sin((n-1.1)*5*Math.PI)},Out:function(n){return n===0?0:n===1?1:Math.pow(2,-10*n)*Math.sin((n-.1)*5*Math.PI)+1},InOut:function(n){return n===0?0:n===1?1:(n*=2,n<1?-.5*Math.pow(2,10*(n-1))*Math.sin((n-1.1)*5*Math.PI):.5*Math.pow(2,-10*(n-1))*Math.sin((n-1.1)*5*Math.PI)+1)}}),Back:Object.freeze({In:function(n){var e=1.70158;return n===1?1:n*n*((e+1)*n-e)},Out:function(n){var e=1.70158;return n===0?0:--n*n*((e+1)*n+e)+1},InOut:function(n){var e=2.5949095;return(n*=2)<1?.5*(n*n*((e+1)*n-e)):.5*((n-=2)*n*((e+1)*n+e)+2)}}),Bounce:Object.freeze({In:function(n){return 1-mo.Bounce.Out(1-n)},Out:function(n){return n<1/2.75?7.5625*n*n:n<2/2.75?7.5625*(n-=1.5/2.75)*n+.75:n<2.5/2.75?7.5625*(n-=2.25/2.75)*n+.9375:7.5625*(n-=2.625/2.75)*n+.984375},InOut:function(n){return n<.5?mo.Bounce.In(n*2)*.5:mo.Bounce.Out(n*2-1)*.5+.5}}),generatePow:function(n){return n===void 0&&(n=4),n=n<Number.EPSILON?Number.EPSILON:n,n=n>1e4?1e4:n,{In:function(e){return Math.pow(e,n)},Out:function(e){return 1-Math.pow(1-e,n)},InOut:function(e){return e<.5?Math.pow(e*2,n)/2:(1-Math.pow(2-e*2,n))/2+.5}}}}),ma=function(){return performance.now()},L2=(function(){function n(){this._tweens={},this._tweensAddedDuringUpdate={}}return n.prototype.getAll=function(){var e=this;return Object.keys(this._tweens).map(function(t){return e._tweens[t]})},n.prototype.removeAll=function(){this._tweens={}},n.prototype.add=function(e){this._tweens[e.getId()]=e,this._tweensAddedDuringUpdate[e.getId()]=e},n.prototype.remove=function(e){delete this._tweens[e.getId()],delete this._tweensAddedDuringUpdate[e.getId()]},n.prototype.update=function(e,t){e===void 0&&(e=ma()),t===void 0&&(t=!1);var i=Object.keys(this._tweens);if(i.length===0)return!1;for(;i.length>0;){this._tweensAddedDuringUpdate={};for(var s=0;s<i.length;s++){var r=this._tweens[i[s]],o=!t;r&&r.update(e,o)===!1&&!t&&delete this._tweens[i[s]]}i=Object.keys(this._tweensAddedDuringUpdate)}return!0},n})(),Ju={Linear:function(n,e){var t=n.length-1,i=t*e,s=Math.floor(i),r=Ju.Utils.Linear;return e<0?r(n[0],n[1],i):e>1?r(n[t],n[t-1],t-i):r(n[s],n[s+1>t?t:s+1],i-s)},Utils:{Linear:function(n,e,t){return(e-n)*t+n}}},K0=(function(){function n(){}return n.nextId=function(){return n._nextId++},n._nextId=0,n})(),Zu=new L2,R2=(function(){function n(e,t){t===void 0&&(t=Zu),this._object=e,this._group=t,this._isPaused=!1,this._pauseStart=0,this._valuesStart={},this._valuesEnd={},this._valuesStartRepeat={},this._duration=1e3,this._isDynamic=!1,this._initialRepeat=0,this._repeat=0,this._yoyo=!1,this._isPlaying=!1,this._reversed=!1,this._delayTime=0,this._startTime=0,this._easingFunction=mo.Linear.None,this._interpolationFunction=Ju.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=K0.nextId(),this._isChainStopped=!1,this._propertiesAreSetUp=!1,this._goToEnd=!1}return n.prototype.getId=function(){return this._id},n.prototype.isPlaying=function(){return this._isPlaying},n.prototype.isPaused=function(){return this._isPaused},n.prototype.getDuration=function(){return this._duration},n.prototype.to=function(e,t){if(t===void 0&&(t=1e3),this._isPlaying)throw new Error("Can not call Tween.to() while Tween is already started or paused. Stop the Tween first.");return this._valuesEnd=e,this._propertiesAreSetUp=!1,this._duration=t<0?0:t,this},n.prototype.duration=function(e){return e===void 0&&(e=1e3),this._duration=e<0?0:e,this},n.prototype.dynamic=function(e){return e===void 0&&(e=!1),this._isDynamic=e,this},n.prototype.start=function(e,t){if(e===void 0&&(e=ma()),t===void 0&&(t=!1),this._isPlaying)return this;if(this._group&&this._group.add(this),this._repeat=this._initialRepeat,this._reversed){this._reversed=!1;for(var i in this._valuesStartRepeat)this._swapEndStartRepeatValues(i),this._valuesStart[i]=this._valuesStartRepeat[i]}if(this._isPlaying=!0,this._isPaused=!1,this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._isChainStopped=!1,this._startTime=e,this._startTime+=this._delayTime,!this._propertiesAreSetUp||t){if(this._propertiesAreSetUp=!0,!this._isDynamic){var s={};for(var r in this._valuesEnd)s[r]=this._valuesEnd[r];this._valuesEnd=s}this._setupProperties(this._object,this._valuesStart,this._valuesEnd,this._valuesStartRepeat,t)}return this},n.prototype.startFromCurrentValues=function(e){return this.start(e,!0)},n.prototype._setupProperties=function(e,t,i,s,r){for(var o in i){var a=e[o],l=Array.isArray(a),c=l?"array":typeof a,h=!l&&Array.isArray(i[o]);if(!(c==="undefined"||c==="function")){if(h){var d=i[o];if(d.length===0)continue;for(var f=[a],u=0,g=d.length;u<g;u+=1){var p=this._handleRelativeValue(a,d[u]);if(isNaN(p)){h=!1,console.warn("Found invalid interpolation list. Skipping.");break}f.push(p)}h&&(i[o]=f)}if((c==="object"||l)&&a&&!h){t[o]=l?[]:{};var m=a;for(var A in m)t[o][A]=m[A];s[o]=l?[]:{};var d=i[o];if(!this._isDynamic){var x={};for(var A in d)x[A]=d[A];i[o]=d=x}this._setupProperties(m,t[o],d,s[o],r)}else(typeof t[o]>"u"||r)&&(t[o]=a),l||(t[o]*=1),h?s[o]=i[o].slice().reverse():s[o]=t[o]||0}}},n.prototype.stop=function(){return this._isChainStopped||(this._isChainStopped=!0,this.stopChainedTweens()),this._isPlaying?(this._group&&this._group.remove(this),this._isPlaying=!1,this._isPaused=!1,this._onStopCallback&&this._onStopCallback(this._object),this):this},n.prototype.end=function(){return this._goToEnd=!0,this.update(1/0),this},n.prototype.pause=function(e){return e===void 0&&(e=ma()),this._isPaused||!this._isPlaying?this:(this._isPaused=!0,this._pauseStart=e,this._group&&this._group.remove(this),this)},n.prototype.resume=function(e){return e===void 0&&(e=ma()),!this._isPaused||!this._isPlaying?this:(this._isPaused=!1,this._startTime+=e-this._pauseStart,this._pauseStart=0,this._group&&this._group.add(this),this)},n.prototype.stopChainedTweens=function(){for(var e=0,t=this._chainedTweens.length;e<t;e++)this._chainedTweens[e].stop();return this},n.prototype.group=function(e){return e===void 0&&(e=Zu),this._group=e,this},n.prototype.delay=function(e){return e===void 0&&(e=0),this._delayTime=e,this},n.prototype.repeat=function(e){return e===void 0&&(e=0),this._initialRepeat=e,this._repeat=e,this},n.prototype.repeatDelay=function(e){return this._repeatDelayTime=e,this},n.prototype.yoyo=function(e){return e===void 0&&(e=!1),this._yoyo=e,this},n.prototype.easing=function(e){return e===void 0&&(e=mo.Linear.None),this._easingFunction=e,this},n.prototype.interpolation=function(e){return e===void 0&&(e=Ju.Linear),this._interpolationFunction=e,this},n.prototype.chain=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this._chainedTweens=e,this},n.prototype.onStart=function(e){return this._onStartCallback=e,this},n.prototype.onEveryStart=function(e){return this._onEveryStartCallback=e,this},n.prototype.onUpdate=function(e){return this._onUpdateCallback=e,this},n.prototype.onRepeat=function(e){return this._onRepeatCallback=e,this},n.prototype.onComplete=function(e){return this._onCompleteCallback=e,this},n.prototype.onStop=function(e){return this._onStopCallback=e,this},n.prototype.update=function(e,t){var i=this,s;if(e===void 0&&(e=ma()),t===void 0&&(t=!0),this._isPaused)return!0;var r,o=this._startTime+this._duration;if(!this._goToEnd&&!this._isPlaying){if(e>o)return!1;t&&this.start(e,!0)}if(this._goToEnd=!1,e<this._startTime)return!0;this._onStartCallbackFired===!1&&(this._onStartCallback&&this._onStartCallback(this._object),this._onStartCallbackFired=!0),this._onEveryStartCallbackFired===!1&&(this._onEveryStartCallback&&this._onEveryStartCallback(this._object),this._onEveryStartCallbackFired=!0);var a=e-this._startTime,l=this._duration+((s=this._repeatDelayTime)!==null&&s!==void 0?s:this._delayTime),c=this._duration+this._repeat*l,h=function(){if(i._duration===0||a>c)return 1;var m=Math.trunc(a/l),A=a-m*l,x=Math.min(A/i._duration,1);return x===0&&a===i._duration?1:x},d=h(),f=this._easingFunction(d);if(this._updateProperties(this._object,this._valuesStart,this._valuesEnd,f),this._onUpdateCallback&&this._onUpdateCallback(this._object,d),this._duration===0||a>=this._duration)if(this._repeat>0){var u=Math.min(Math.trunc((a-this._duration)/l)+1,this._repeat);isFinite(this._repeat)&&(this._repeat-=u);for(r in this._valuesStartRepeat)!this._yoyo&&typeof this._valuesEnd[r]=="string"&&(this._valuesStartRepeat[r]=this._valuesStartRepeat[r]+parseFloat(this._valuesEnd[r])),this._yoyo&&this._swapEndStartRepeatValues(r),this._valuesStart[r]=this._valuesStartRepeat[r];return this._yoyo&&(this._reversed=!this._reversed),this._startTime+=l*u,this._onRepeatCallback&&this._onRepeatCallback(this._object),this._onEveryStartCallbackFired=!1,!0}else{this._onCompleteCallback&&this._onCompleteCallback(this._object);for(var g=0,p=this._chainedTweens.length;g<p;g++)this._chainedTweens[g].start(this._startTime+this._duration,!1);return this._isPlaying=!1,!1}return!0},n.prototype._updateProperties=function(e,t,i,s){for(var r in i)if(t[r]!==void 0){var o=t[r]||0,a=i[r],l=Array.isArray(e[r]),c=Array.isArray(a),h=!l&&c;h?e[r]=this._interpolationFunction(a,s):typeof a=="object"&&a?this._updateProperties(e[r],o,a,s):(a=this._handleRelativeValue(o,a),typeof a=="number"&&(e[r]=o+(a-o)*s))}},n.prototype._handleRelativeValue=function(e,t){return typeof t!="string"?t:t.charAt(0)==="+"||t.charAt(0)==="-"?e+parseFloat(t):parseFloat(t)},n.prototype._swapEndStartRepeatValues=function(e){var t=this._valuesStartRepeat[e],i=this._valuesEnd[e];typeof i=="string"?this._valuesStartRepeat[e]=this._valuesStartRepeat[e]+parseFloat(i):this._valuesStartRepeat[e]=this._valuesEnd[e],this._valuesEnd[e]=t},n})();K0.nextId;var _n=Zu;_n.getAll.bind(_n),_n.removeAll.bind(_n),_n.add.bind(_n),_n.remove.bind(_n),_n.update.bind(_n);var Aa={Easing:mo,Tween:R2};const $0={type:"change"},ef={type:"start"},J0={type:"end"},Cc=new v.Ray,Z0=new v.Plane,k2=Math.cos(70*v.MathUtils.DEG2RAD),jt=new v.Vector3,vi=2*Math.PI,mt={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},tf=1e-6;class F2 extends v.Controls{constructor(e,t=null){super(e,t),this.state=mt.NONE,this.target=new v.Vector3,this.cursor=new v.Vector3,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:v.MOUSE.ROTATE,MIDDLE:v.MOUSE.DOLLY,RIGHT:v.MOUSE.PAN},this.touches={ONE:v.TOUCH.ROTATE,TWO:v.TOUCH.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._cursorStyle="auto",this._domElementKeyEvents=null,this._lastPosition=new v.Vector3,this._lastQuaternion=new v.Quaternion,this._lastTargetPosition=new v.Vector3,this._quat=new v.Quaternion().setFromUnitVectors(e.up,new v.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new v.Spherical,this._sphericalDelta=new v.Spherical,this._scale=1,this._panOffset=new v.Vector3,this._rotateStart=new v.Vector2,this._rotateEnd=new v.Vector2,this._rotateDelta=new v.Vector2,this._panStart=new v.Vector2,this._panEnd=new v.Vector2,this._panDelta=new v.Vector2,this._dollyStart=new v.Vector2,this._dollyEnd=new v.Vector2,this._dollyDelta=new v.Vector2,this._dollyDirection=new v.Vector3,this._mouse=new v.Vector2,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=U2.bind(this),this._onPointerDown=O2.bind(this),this._onPointerUp=N2.bind(this),this._onContextMenu=H2.bind(this),this._onMouseWheel=V2.bind(this),this._onKeyDown=Q2.bind(this),this._onTouchStart=j2.bind(this),this._onTouchMove=W2.bind(this),this._onMouseDown=z2.bind(this),this._onMouseMove=G2.bind(this),this._interceptControlDown=X2.bind(this),this._interceptControlUp=q2.bind(this),this.domElement!==null&&this.connect(this.domElement),this.update()}set cursorStyle(e){this._cursorStyle=e,e==="grab"?this.domElement.style.cursor="grab":this.domElement.style.cursor="auto"}get cursorStyle(){return this._cursorStyle}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents(),this.domElement.getRootNode().removeEventListener("keydown",this._interceptControlDown,{capture:!0}),this.domElement.style.touchAction="auto"}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){this._domElementKeyEvents!==null&&(this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null)}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent($0),this.update(),this.state=mt.NONE}pan(e,t){this._pan(e,t),this.update()}dollyIn(e){this._dollyIn(e),this.update()}dollyOut(e){this._dollyOut(e),this.update()}rotateLeft(e){this._rotateLeft(e),this.update()}rotateUp(e){this._rotateUp(e),this.update()}update(e=null){const t=this.object.position;jt.copy(t).sub(this.target),jt.applyQuaternion(this._quat),this._spherical.setFromVector3(jt),this.autoRotate&&this.state===mt.NONE&&this._rotateLeft(this._getAutoRotationAngle(e)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let i=this.minAzimuthAngle,s=this.maxAzimuthAngle;isFinite(i)&&isFinite(s)&&(i<-Math.PI?i+=vi:i>Math.PI&&(i-=vi),s<-Math.PI?s+=vi:s>Math.PI&&(s-=vi),i<=s?this._spherical.theta=Math.max(i,Math.min(s,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(i+s)/2?Math.max(i,this._spherical.theta):Math.min(s,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let r=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const o=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),r=o!=this._spherical.radius}if(jt.setFromSpherical(this._spherical),jt.applyQuaternion(this._quatInverse),t.copy(this.target).add(jt),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let o=null;if(this.object.isPerspectiveCamera){const a=jt.length();o=this._clampDistance(a*this._scale);const l=a-o;this.object.position.addScaledVector(this._dollyDirection,l),this.object.updateMatrixWorld(),r=!!l}else if(this.object.isOrthographicCamera){const a=new v.Vector3(this._mouse.x,this._mouse.y,0);a.unproject(this.object);const l=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),r=l!==this.object.zoom;const c=new v.Vector3(this._mouse.x,this._mouse.y,0);c.unproject(this.object),this.object.position.sub(c).add(a),this.object.updateMatrixWorld(),o=jt.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;o!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(o).add(this.object.position):(Cc.origin.copy(this.object.position),Cc.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(Cc.direction))<k2?this.object.lookAt(this.target):(Z0.setFromNormalAndCoplanarPoint(this.object.up,this.target),Cc.intersectPlane(Z0,this.target))))}else if(this.object.isOrthographicCamera){const o=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),o!==this.object.zoom&&(this.object.updateProjectionMatrix(),r=!0)}return this._scale=1,this._performCursorZoom=!1,r||this._lastPosition.distanceToSquared(this.object.position)>tf||8*(1-this._lastQuaternion.dot(this.object.quaternion))>tf||this._lastTargetPosition.distanceToSquared(this.target)>tf?(this.dispatchEvent($0),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?vi/60*this.autoRotateSpeed*e:vi/60/60*this.autoRotateSpeed}_getZoomScale(e){const t=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){jt.setFromMatrixColumn(t,0),jt.multiplyScalar(-e),this._panOffset.add(jt)}_panUp(e,t){this.screenSpacePanning===!0?jt.setFromMatrixColumn(t,1):(jt.setFromMatrixColumn(t,0),jt.crossVectors(this.object.up,jt)),jt.multiplyScalar(e),this._panOffset.add(jt)}_pan(e,t){const i=this.domElement;if(this.object.isPerspectiveCamera){const s=this.object.position;jt.copy(s).sub(this.target);let r=jt.length();r*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*r/i.clientHeight,this.object.matrix),this._panUp(2*t*r/i.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/i.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/i.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const i=this.domElement.getBoundingClientRect(),s=e-i.left,r=t-i.top,o=i.width,a=i.height;this._mouse.x=s/o*2-1,this._mouse.y=-(r/a)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(vi*this._rotateDelta.x/t.clientHeight),this._rotateUp(vi*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(vi*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-vi*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(vi*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-vi*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0;break}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._rotateStart.set(i,s)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panStart.set(i,s)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),i=e.pageX-t.x,s=e.pageY-t.y,r=Math.sqrt(i*i+s*s);this._dollyStart.set(0,r)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const i=this._getSecondPointerPosition(e),s=.5*(e.pageX+i.x),r=.5*(e.pageY+i.y);this._rotateEnd.set(s,r)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(vi*this._rotateDelta.x/t.clientHeight),this._rotateUp(vi*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panEnd.set(i,s)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),i=e.pageX-t.x,s=e.pageY-t.y,r=Math.sqrt(i*i+s*s);this._dollyEnd.set(0,r),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const o=(e.pageX+t.x)*.5,a=(e.pageY+t.y)*.5;this._updateZoomParameters(o,a)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId){this._pointers.splice(t,1);return}}_isTrackingPointer(e){for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return!0;return!1}_trackPointer(e){let t=this._pointerPositions[e.pointerId];t===void 0&&(t=new v.Vector2,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){const t=e.deltaMode,i={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:i.deltaY*=16;break;case 2:i.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(i.deltaY*=10),i}}function O2(n){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(n.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(n)&&(this._addPointer(n),n.pointerType==="touch"?this._onTouchStart(n):this._onMouseDown(n),this._cursorStyle==="grab"&&(this.domElement.style.cursor="grabbing")))}function U2(n){this.enabled!==!1&&(n.pointerType==="touch"?this._onTouchMove(n):this._onMouseMove(n))}function N2(n){switch(this._removePointer(n),this._pointers.length){case 0:this.domElement.releasePointerCapture(n.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(J0),this.state=mt.NONE,this._cursorStyle==="grab"&&(this.domElement.style.cursor="grab");break;case 1:const e=this._pointers[0],t=this._pointerPositions[e];this._onTouchStart({pointerId:e,pageX:t.x,pageY:t.y});break}}function z2(n){let e;switch(n.button){case 0:e=this.mouseButtons.LEFT;break;case 1:e=this.mouseButtons.MIDDLE;break;case 2:e=this.mouseButtons.RIGHT;break;default:e=-1}switch(e){case v.MOUSE.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(n),this.state=mt.DOLLY;break;case v.MOUSE.ROTATE:if(n.ctrlKey||n.metaKey||n.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(n),this.state=mt.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(n),this.state=mt.ROTATE}break;case v.MOUSE.PAN:if(n.ctrlKey||n.metaKey||n.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(n),this.state=mt.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(n),this.state=mt.PAN}break;default:this.state=mt.NONE}this.state!==mt.NONE&&this.dispatchEvent(ef)}function G2(n){switch(this.state){case mt.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(n);break;case mt.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(n);break;case mt.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(n);break}}function V2(n){this.enabled===!1||this.enableZoom===!1||this.state!==mt.NONE||(n.preventDefault(),this.dispatchEvent(ef),this._handleMouseWheel(this._customWheelEvent(n)),this.dispatchEvent(J0))}function Q2(n){this.enabled!==!1&&this._handleKeyDown(n)}function j2(n){switch(this._trackPointer(n),this._pointers.length){case 1:switch(this.touches.ONE){case v.TOUCH.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(n),this.state=mt.TOUCH_ROTATE;break;case v.TOUCH.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(n),this.state=mt.TOUCH_PAN;break;default:this.state=mt.NONE}break;case 2:switch(this.touches.TWO){case v.TOUCH.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(n),this.state=mt.TOUCH_DOLLY_PAN;break;case v.TOUCH.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(n),this.state=mt.TOUCH_DOLLY_ROTATE;break;default:this.state=mt.NONE}break;default:this.state=mt.NONE}this.state!==mt.NONE&&this.dispatchEvent(ef)}function W2(n){switch(this._trackPointer(n),this.state){case mt.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(n),this.update();break;case mt.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(n),this.update();break;case mt.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(n),this.update();break;case mt.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(n),this.update();break;default:this.state=mt.NONE}}function H2(n){this.enabled!==!1&&n.preventDefault()}function X2(n){n.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function q2(n){n.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}const ur=new v.Raycaster,ti=new v.Vector3,Ms=new v.Vector3,wt=new v.Quaternion,ex={X:new v.Vector3(1,0,0),Y:new v.Vector3(0,1,0),Z:new v.Vector3(0,0,1)},nf={type:"change"},tx={type:"mouseDown",mode:null},ix={type:"mouseUp",mode:null},nx={type:"objectChange"};class sx extends v.Controls{constructor(e,t=null){super(void 0,t);const i=new eD(this);this._root=i;const s=new tD;this._gizmo=s,i.add(s);const r=new iD;this._plane=r,i.add(r);const o=this;function a(b,y){let _=y;Object.defineProperty(o,b,{get:function(){return _!==void 0?_:y},set:function(S){_!==S&&(_=S,r[b]=S,s[b]=S,o.dispatchEvent({type:b+"-changed",value:S}),o.dispatchEvent(nf))}}),o[b]=y,r[b]=y,s[b]=y}a("camera",e),a("object",void 0),a("enabled",!0),a("axis",null),a("mode","translate"),a("translationSnap",null),a("rotationSnap",null),a("scaleSnap",null),a("space","world"),a("size",1),a("dragging",!1),a("showX",!0),a("showY",!0),a("showZ",!0),a("minX",-1/0),a("maxX",1/0),a("minY",-1/0),a("maxY",1/0),a("minZ",-1/0),a("maxZ",1/0);const l=new v.Vector3,c=new v.Vector3,h=new v.Quaternion,d=new v.Quaternion,f=new v.Vector3,u=new v.Quaternion,g=new v.Vector3,p=new v.Vector3,m=new v.Vector3,A=0,x=new v.Vector3;a("worldPosition",l),a("worldPositionStart",c),a("worldQuaternion",h),a("worldQuaternionStart",d),a("cameraPosition",f),a("cameraQuaternion",u),a("pointStart",g),a("pointEnd",p),a("rotationAxis",m),a("rotationAngle",A),a("eye",x),this._offset=new v.Vector3,this._startNorm=new v.Vector3,this._endNorm=new v.Vector3,this._cameraScale=new v.Vector3,this._parentPosition=new v.Vector3,this._parentQuaternion=new v.Quaternion,this._parentQuaternionInv=new v.Quaternion,this._parentScale=new v.Vector3,this._worldScaleStart=new v.Vector3,this._worldQuaternionInv=new v.Quaternion,this._worldScale=new v.Vector3,this._positionStart=new v.Vector3,this._quaternionStart=new v.Quaternion,this._scaleStart=new v.Vector3,this._getPointer=Y2.bind(this),this._onPointerDown=$2.bind(this),this._onPointerHover=K2.bind(this),this._onPointerMove=J2.bind(this),this._onPointerUp=Z2.bind(this),t!==null&&this.connect(t)}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointermove",this._onPointerHover),this.domElement.addEventListener("pointerup",this._onPointerUp),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerHover),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.domElement.style.touchAction="auto"}getHelper(){return this._root}pointerHover(e){if(this.object===void 0||this.dragging===!0)return;e!==null&&ur.setFromCamera(e,this.camera);const t=sf(this._gizmo.picker[this.mode],ur);t?this.axis=t.object.name:this.axis=null}pointerDown(e){if(!(this.object===void 0||this.dragging===!0||e!=null&&e.button!==0)&&this.axis!==null){e!==null&&ur.setFromCamera(e,this.camera);const t=sf(this._plane,ur,!0);t&&(this.object.updateMatrixWorld(),this.object.parent.updateMatrixWorld(),this._positionStart.copy(this.object.position),this._quaternionStart.copy(this.object.quaternion),this._scaleStart.copy(this.object.scale),this.object.matrixWorld.decompose(this.worldPositionStart,this.worldQuaternionStart,this._worldScaleStart),this.pointStart.copy(t.point).sub(this.worldPositionStart)),this.dragging=!0,tx.mode=this.mode,this.dispatchEvent(tx)}}pointerMove(e){const t=this.axis,i=this.mode,s=this.object;let r=this.space;if(i==="scale"?r="local":(t==="E"||t==="XYZE"||t==="XYZ")&&(r="world"),s===void 0||t===null||this.dragging===!1||e!==null&&e.button!==-1)return;e!==null&&ur.setFromCamera(e,this.camera);const o=sf(this._plane,ur,!0);if(o){if(this.pointEnd.copy(o.point).sub(this.worldPositionStart),i==="translate")this._offset.copy(this.pointEnd).sub(this.pointStart),r==="local"&&t!=="XYZ"&&this._offset.applyQuaternion(this._worldQuaternionInv),t.indexOf("X")===-1&&(this._offset.x=0),t.indexOf("Y")===-1&&(this._offset.y=0),t.indexOf("Z")===-1&&(this._offset.z=0),r==="local"&&t!=="XYZ"?this._offset.applyQuaternion(this._quaternionStart).divide(this._parentScale):this._offset.applyQuaternion(this._parentQuaternionInv).divide(this._parentScale),s.position.copy(this._offset).add(this._positionStart),this.translationSnap&&(r==="local"&&(s.position.applyQuaternion(wt.copy(this._quaternionStart).invert()),t.search("X")!==-1&&(s.position.x=Math.round(s.position.x/this.translationSnap)*this.translationSnap),t.search("Y")!==-1&&(s.position.y=Math.round(s.position.y/this.translationSnap)*this.translationSnap),t.search("Z")!==-1&&(s.position.z=Math.round(s.position.z/this.translationSnap)*this.translationSnap),s.position.applyQuaternion(this._quaternionStart)),r==="world"&&(s.parent&&s.position.add(ti.setFromMatrixPosition(s.parent.matrixWorld)),t.search("X")!==-1&&(s.position.x=Math.round(s.position.x/this.translationSnap)*this.translationSnap),t.search("Y")!==-1&&(s.position.y=Math.round(s.position.y/this.translationSnap)*this.translationSnap),t.search("Z")!==-1&&(s.position.z=Math.round(s.position.z/this.translationSnap)*this.translationSnap),s.parent&&s.position.sub(ti.setFromMatrixPosition(s.parent.matrixWorld)))),s.position.x=Math.max(this.minX,Math.min(this.maxX,s.position.x)),s.position.y=Math.max(this.minY,Math.min(this.maxY,s.position.y)),s.position.z=Math.max(this.minZ,Math.min(this.maxZ,s.position.z));else if(i==="scale"){if(t.search("XYZ")!==-1){let a=this.pointEnd.length()/this.pointStart.length();this.pointEnd.dot(this.pointStart)<0&&(a*=-1),Ms.set(a,a,a)}else ti.copy(this.pointStart),Ms.copy(this.pointEnd),ti.applyQuaternion(this._worldQuaternionInv),Ms.applyQuaternion(this._worldQuaternionInv),Ms.divide(ti),t.search("X")===-1&&(Ms.x=1),t.search("Y")===-1&&(Ms.y=1),t.search("Z")===-1&&(Ms.z=1);s.scale.copy(this._scaleStart).multiply(Ms),this.scaleSnap&&(t.search("X")!==-1&&(s.scale.x=Math.round(s.scale.x/this.scaleSnap)*this.scaleSnap||this.scaleSnap),t.search("Y")!==-1&&(s.scale.y=Math.round(s.scale.y/this.scaleSnap)*this.scaleSnap||this.scaleSnap),t.search("Z")!==-1&&(s.scale.z=Math.round(s.scale.z/this.scaleSnap)*this.scaleSnap||this.scaleSnap))}else if(i==="rotate"){this._offset.copy(this.pointEnd).sub(this.pointStart);const a=20/this.worldPosition.distanceTo(ti.setFromMatrixPosition(this.camera.matrixWorld));let l=!1;t==="XYZE"?(this.rotationAxis.copy(this._offset).cross(this.eye).normalize(),this.rotationAngle=this._offset.dot(ti.copy(this.rotationAxis).cross(this.eye))*a):(t==="X"||t==="Y"||t==="Z")&&(this.rotationAxis.copy(ex[t]),ti.copy(ex[t]),r==="local"&&ti.applyQuaternion(this.worldQuaternion),ti.cross(this.eye),ti.length()===0?l=!0:this.rotationAngle=this._offset.dot(ti.normalize())*a),(t==="E"||l)&&(this.rotationAxis.copy(this.eye),this.rotationAngle=this.pointEnd.angleTo(this.pointStart),this._startNorm.copy(this.pointStart).normalize(),this._endNorm.copy(this.pointEnd).normalize(),this.rotationAngle*=this._endNorm.cross(this._startNorm).dot(this.eye)<0?1:-1),this.rotationSnap&&(this.rotationAngle=Math.round(this.rotationAngle/this.rotationSnap)*this.rotationSnap),r==="local"&&t!=="E"&&t!=="XYZE"?(s.quaternion.copy(this._quaternionStart),s.quaternion.multiply(wt.setFromAxisAngle(this.rotationAxis,this.rotationAngle)).normalize()):(this.rotationAxis.applyQuaternion(this._parentQuaternionInv),s.quaternion.copy(wt.setFromAxisAngle(this.rotationAxis,this.rotationAngle)),s.quaternion.multiply(this._quaternionStart).normalize())}this.dispatchEvent(nf),this.dispatchEvent(nx)}}pointerUp(e){e!==null&&e.button!==0||(this.dragging&&this.axis!==null&&(ix.mode=this.mode,this.dispatchEvent(ix)),this.dragging=!1,this.axis=null)}dispose(){this.disconnect(),this._root.dispose()}attach(e){return this.object=e,this._root.visible=!0,this}detach(){return this.object=void 0,this.axis=null,this._root.visible=!1,this}reset(){this.enabled&&this.dragging&&(this.object.position.copy(this._positionStart),this.object.quaternion.copy(this._quaternionStart),this.object.scale.copy(this._scaleStart),this.dispatchEvent(nf),this.dispatchEvent(nx),this.pointStart.copy(this.pointEnd))}getRaycaster(){return ur}getMode(){return this.mode}setMode(e){this.mode=e}setTranslationSnap(e){this.translationSnap=e}setRotationSnap(e){this.rotationSnap=e}setScaleSnap(e){this.scaleSnap=e}setSize(e){this.size=e}setSpace(e){this.space=e}setColors(e,t,i,s){const r=this._gizmo.materialLib;r.xAxis.color.set(e),r.yAxis.color.set(t),r.zAxis.color.set(i),r.active.color.set(s),r.xAxisTransparent.color.set(e),r.yAxisTransparent.color.set(t),r.zAxisTransparent.color.set(i),r.activeTransparent.color.set(s),r.xAxis._color&&r.xAxis._color.set(e),r.yAxis._color&&r.yAxis._color.set(t),r.zAxis._color&&r.zAxis._color.set(i),r.active._color&&r.active._color.set(s),r.xAxisTransparent._color&&r.xAxisTransparent._color.set(e),r.yAxisTransparent._color&&r.yAxisTransparent._color.set(t),r.zAxisTransparent._color&&r.zAxisTransparent._color.set(i),r.activeTransparent._color&&r.activeTransparent._color.set(s)}}function Y2(n){if(this.domElement.ownerDocument.pointerLockElement)return{x:0,y:0,button:n.button};{const e=this.domElement.getBoundingClientRect();return{x:(n.clientX-e.left)/e.width*2-1,y:-(n.clientY-e.top)/e.height*2+1,button:n.button}}}function K2(n){if(this.enabled)switch(n.pointerType){case"mouse":case"pen":this.pointerHover(this._getPointer(n));break}}function $2(n){this.enabled&&(document.pointerLockElement||this.domElement.setPointerCapture(n.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.pointerHover(this._getPointer(n)),this.pointerDown(this._getPointer(n)))}function J2(n){this.enabled&&this.pointerMove(this._getPointer(n))}function Z2(n){this.enabled&&(this.domElement.releasePointerCapture(n.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.pointerUp(this._getPointer(n)))}function sf(n,e,t){const i=e.intersectObject(n,!0);for(let s=0;s<i.length;s++)if(i[s].object.visible||t)return i[s];return!1}const Mc=new v.Euler,At=new v.Vector3(0,1,0),rx=new v.Vector3(0,0,0),ox=new v.Matrix4,Ec=new v.Quaternion,Ic=new v.Quaternion,wn=new v.Vector3,ax=new v.Matrix4,xa=new v.Vector3(1,0,0),fr=new v.Vector3(0,1,0),ba=new v.Vector3(0,0,1),Tc=new v.Vector3,ya=new v.Vector3,va=new v.Vector3;class eD extends v.Object3D{constructor(e){super(),this.isTransformControlsRoot=!0,this.controls=e,this.visible=!1}updateMatrixWorld(e){const t=this.controls;t.object!==void 0&&(t.object.updateMatrixWorld(),t.object.parent===null?console.error("TransformControls: The attached 3D object must be a part of the scene graph."):t.object.parent.matrixWorld.decompose(t._parentPosition,t._parentQuaternion,t._parentScale),t.object.matrixWorld.decompose(t.worldPosition,t.worldQuaternion,t._worldScale),t._parentQuaternionInv.copy(t._parentQuaternion).invert(),t._worldQuaternionInv.copy(t.worldQuaternion).invert()),t.camera.updateMatrixWorld(),t.camera.matrixWorld.decompose(t.cameraPosition,t.cameraQuaternion,t._cameraScale),t.camera.isOrthographicCamera?t.camera.getWorldDirection(t.eye).negate():t.eye.copy(t.cameraPosition).sub(t.worldPosition).normalize(),super.updateMatrixWorld(e)}dispose(){this.traverse(function(e){e.geometry&&e.geometry.dispose(),e.material&&e.material.dispose()})}}class tD extends v.Object3D{constructor(){super(),this.isTransformControlsGizmo=!0,this.type="TransformControlsGizmo";const e=new v.MeshBasicMaterial({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),t=new v.LineBasicMaterial({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),i=e.clone();i.opacity=.15;const s=t.clone();s.opacity=.5;const r=e.clone();r.color.setHex(16711680);const o=e.clone();o.color.setHex(65280);const a=e.clone();a.color.setHex(255);const l=e.clone();l.color.setHex(16711680),l.opacity=.5;const c=e.clone();c.color.setHex(65280),c.opacity=.5;const h=e.clone();h.color.setHex(255),h.opacity=.5;const d=e.clone();d.opacity=.25;const f=e.clone();f.color.setHex(16776960),f.opacity=.25;const u=e.clone();u.color.setHex(16776960);const g=e.clone();g.color.setHex(7895160),this.materialLib={xAxis:r,yAxis:o,zAxis:a,active:u,xAxisTransparent:l,yAxisTransparent:c,zAxisTransparent:h,activeTransparent:f};const p=new v.CylinderGeometry(0,.04,.1,12);p.translate(0,.05,0);const m=new v.BoxGeometry(.08,.08,.08);m.translate(0,.04,0);const A=new v.BufferGeometry;A.setAttribute("position",new v.Float32BufferAttribute([0,0,0,1,0,0],3));const x=new v.CylinderGeometry(.0075,.0075,.5,3);x.translate(0,.25,0);function b(F,N){const H=new v.TorusGeometry(F,.0075,3,64,N*Math.PI*2);return H.rotateY(Math.PI/2),H.rotateX(Math.PI/2),H}function y(){const F=new v.BufferGeometry;return F.setAttribute("position",new v.Float32BufferAttribute([0,0,0,1,1,1],3)),F}const _={X:[[new v.Mesh(p,r),[.5,0,0],[0,0,-Math.PI/2]],[new v.Mesh(p,r),[-.5,0,0],[0,0,Math.PI/2]],[new v.Mesh(x,r),[0,0,0],[0,0,-Math.PI/2]]],Y:[[new v.Mesh(p,o),[0,.5,0]],[new v.Mesh(p,o),[0,-.5,0],[Math.PI,0,0]],[new v.Mesh(x,o)]],Z:[[new v.Mesh(p,a),[0,0,.5],[Math.PI/2,0,0]],[new v.Mesh(p,a),[0,0,-.5],[-Math.PI/2,0,0]],[new v.Mesh(x,a),null,[Math.PI/2,0,0]]],XYZ:[[new v.Mesh(new v.OctahedronGeometry(.1,0),d),[0,0,0]]],XY:[[new v.Mesh(new v.BoxGeometry(.15,.15,.01),h),[.15,.15,0]]],YZ:[[new v.Mesh(new v.BoxGeometry(.15,.15,.01),l),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new v.Mesh(new v.BoxGeometry(.15,.15,.01),c),[.15,0,.15],[-Math.PI/2,0,0]]]},S={X:[[new v.Mesh(new v.CylinderGeometry(.2,0,.6,4),i),[.3,0,0],[0,0,-Math.PI/2]],[new v.Mesh(new v.CylinderGeometry(.2,0,.6,4),i),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new v.Mesh(new v.CylinderGeometry(.2,0,.6,4),i),[0,.3,0]],[new v.Mesh(new v.CylinderGeometry(.2,0,.6,4),i),[0,-.3,0],[0,0,Math.PI]]],Z:[[new v.Mesh(new v.CylinderGeometry(.2,0,.6,4),i),[0,0,.3],[Math.PI/2,0,0]],[new v.Mesh(new v.CylinderGeometry(.2,0,.6,4),i),[0,0,-.3],[-Math.PI/2,0,0]]],XYZ:[[new v.Mesh(new v.OctahedronGeometry(.2,0),i)]],XY:[[new v.Mesh(new v.BoxGeometry(.2,.2,.01),i),[.15,.15,0]]],YZ:[[new v.Mesh(new v.BoxGeometry(.2,.2,.01),i),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new v.Mesh(new v.BoxGeometry(.2,.2,.01),i),[.15,0,.15],[-Math.PI/2,0,0]]]},C={START:[[new v.Mesh(new v.OctahedronGeometry(.01,2),s),null,null,null,"helper"]],END:[[new v.Mesh(new v.OctahedronGeometry(.01,2),s),null,null,null,"helper"]],DELTA:[[new v.Line(y(),s),null,null,null,"helper"]],X:[[new v.Line(A,s),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new v.Line(A,s),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new v.Line(A,s),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},D={XYZE:[[new v.Mesh(b(.5,1),g),null,[0,Math.PI/2,0]]],X:[[new v.Mesh(b(.5,.5),r)]],Y:[[new v.Mesh(b(.5,.5),o),null,[0,0,-Math.PI/2]]],Z:[[new v.Mesh(b(.5,.5),a),null,[0,Math.PI/2,0]]],E:[[new v.Mesh(b(.75,1),f),null,[0,Math.PI/2,0]]]},M={AXIS:[[new v.Line(A,s),[-1e3,0,0],null,[1e6,1,1],"helper"]]},I={XYZE:[[new v.Mesh(new v.SphereGeometry(.25,10,8),i)]],X:[[new v.Mesh(new v.TorusGeometry(.5,.1,4,24),i),[0,0,0],[0,-Math.PI/2,-Math.PI/2]]],Y:[[new v.Mesh(new v.TorusGeometry(.5,.1,4,24),i),[0,0,0],[Math.PI/2,0,0]]],Z:[[new v.Mesh(new v.TorusGeometry(.5,.1,4,24),i),[0,0,0],[0,0,-Math.PI/2]]],E:[[new v.Mesh(new v.TorusGeometry(.75,.1,2,24),i)]]},L={X:[[new v.Mesh(m,r),[.5,0,0],[0,0,-Math.PI/2]],[new v.Mesh(x,r),[0,0,0],[0,0,-Math.PI/2]],[new v.Mesh(m,r),[-.5,0,0],[0,0,Math.PI/2]]],Y:[[new v.Mesh(m,o),[0,.5,0]],[new v.Mesh(x,o)],[new v.Mesh(m,o),[0,-.5,0],[0,0,Math.PI]]],Z:[[new v.Mesh(m,a),[0,0,.5],[Math.PI/2,0,0]],[new v.Mesh(x,a),[0,0,0],[Math.PI/2,0,0]],[new v.Mesh(m,a),[0,0,-.5],[-Math.PI/2,0,0]]],XY:[[new v.Mesh(new v.BoxGeometry(.15,.15,.01),h),[.15,.15,0]]],YZ:[[new v.Mesh(new v.BoxGeometry(.15,.15,.01),l),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new v.Mesh(new v.BoxGeometry(.15,.15,.01),c),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new v.Mesh(new v.BoxGeometry(.1,.1,.1),d)]]},T={X:[[new v.Mesh(new v.CylinderGeometry(.2,0,.6,4),i),[.3,0,0],[0,0,-Math.PI/2]],[new v.Mesh(new v.CylinderGeometry(.2,0,.6,4),i),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new v.Mesh(new v.CylinderGeometry(.2,0,.6,4),i),[0,.3,0]],[new v.Mesh(new v.CylinderGeometry(.2,0,.6,4),i),[0,-.3,0],[0,0,Math.PI]]],Z:[[new v.Mesh(new v.CylinderGeometry(.2,0,.6,4),i),[0,0,.3],[Math.PI/2,0,0]],[new v.Mesh(new v.CylinderGeometry(.2,0,.6,4),i),[0,0,-.3],[-Math.PI/2,0,0]]],XY:[[new v.Mesh(new v.BoxGeometry(.2,.2,.01),i),[.15,.15,0]]],YZ:[[new v.Mesh(new v.BoxGeometry(.2,.2,.01),i),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new v.Mesh(new v.BoxGeometry(.2,.2,.01),i),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new v.Mesh(new v.BoxGeometry(.2,.2,.2),i),[0,0,0]]]},R={X:[[new v.Line(A,s),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new v.Line(A,s),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new v.Line(A,s),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]};function E(F){const N=new v.Object3D;for(const H in F)for(let V=F[H].length;V--;){const U=F[H][V][0].clone(),q=F[H][V][1],G=F[H][V][2],j=F[H][V][3],oe=F[H][V][4];U.name=H,U.tag=oe,q&&U.position.set(q[0],q[1],q[2]),G&&U.rotation.set(G[0],G[1],G[2]),j&&U.scale.set(j[0],j[1],j[2]),U.updateMatrix();const fe=U.geometry.clone();fe.applyMatrix4(U.matrix),U.geometry=fe,U.renderOrder=1/0,U.position.set(0,0,0),U.rotation.set(0,0,0),U.scale.set(1,1,1),N.add(U)}return N}this.gizmo={},this.picker={},this.helper={},this.add(this.gizmo.translate=E(_)),this.add(this.gizmo.rotate=E(D)),this.add(this.gizmo.scale=E(L)),this.add(this.picker.translate=E(S)),this.add(this.picker.rotate=E(I)),this.add(this.picker.scale=E(T)),this.add(this.helper.translate=E(C)),this.add(this.helper.rotate=E(M)),this.add(this.helper.scale=E(R)),this.picker.translate.visible=!1,this.picker.rotate.visible=!1,this.picker.scale.visible=!1}updateMatrixWorld(e){const i=(this.mode==="scale"?"local":this.space)==="local"?this.worldQuaternion:Ic;this.gizmo.translate.visible=this.mode==="translate",this.gizmo.rotate.visible=this.mode==="rotate",this.gizmo.scale.visible=this.mode==="scale",this.helper.translate.visible=this.mode==="translate",this.helper.rotate.visible=this.mode==="rotate",this.helper.scale.visible=this.mode==="scale";let s=[];s=s.concat(this.picker[this.mode].children),s=s.concat(this.gizmo[this.mode].children),s=s.concat(this.helper[this.mode].children);for(let r=0;r<s.length;r++){const o=s[r];o.visible=!0,o.rotation.set(0,0,0),o.position.copy(this.worldPosition);let a;if(this.camera.isOrthographicCamera?a=(this.camera.top-this.camera.bottom)/this.camera.zoom:a=this.worldPosition.distanceTo(this.cameraPosition)*Math.min(1.9*Math.tan(Math.PI*this.camera.fov/360)/this.camera.zoom,7),o.scale.set(1,1,1).multiplyScalar(a*this.size/4),o.tag==="helper"){o.visible=!1,o.name==="AXIS"?(o.visible=!!this.axis,this.axis==="X"&&(wt.setFromEuler(Mc.set(0,0,0)),o.quaternion.copy(i).multiply(wt),Math.abs(At.copy(xa).applyQuaternion(i).dot(this.eye))>.9&&(o.visible=!1)),this.axis==="Y"&&(wt.setFromEuler(Mc.set(0,0,Math.PI/2)),o.quaternion.copy(i).multiply(wt),Math.abs(At.copy(fr).applyQuaternion(i).dot(this.eye))>.9&&(o.visible=!1)),this.axis==="Z"&&(wt.setFromEuler(Mc.set(0,Math.PI/2,0)),o.quaternion.copy(i).multiply(wt),Math.abs(At.copy(ba).applyQuaternion(i).dot(this.eye))>.9&&(o.visible=!1)),this.axis==="XYZE"&&(wt.setFromEuler(Mc.set(0,Math.PI/2,0)),At.copy(this.rotationAxis),o.quaternion.setFromRotationMatrix(ox.lookAt(rx,At,fr)),o.quaternion.multiply(wt),o.visible=this.dragging),this.axis==="E"&&(o.visible=!1)):o.name==="START"?(o.position.copy(this.worldPositionStart),o.visible=this.dragging):o.name==="END"?(o.position.copy(this.worldPosition),o.visible=this.dragging):o.name==="DELTA"?(o.position.copy(this.worldPositionStart),o.quaternion.copy(this.worldQuaternionStart),ti.set(1e-10,1e-10,1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1),ti.applyQuaternion(this.worldQuaternionStart.clone().invert()),o.scale.copy(ti),o.visible=this.dragging):(o.quaternion.copy(i),this.dragging?o.position.copy(this.worldPositionStart):o.position.copy(this.worldPosition),this.axis&&(o.visible=this.axis.search(o.name)!==-1));continue}o.quaternion.copy(i),this.mode==="translate"||this.mode==="scale"?(o.name==="X"&&Math.abs(At.copy(xa).applyQuaternion(i).dot(this.eye))>.99&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="Y"&&Math.abs(At.copy(fr).applyQuaternion(i).dot(this.eye))>.99&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="Z"&&Math.abs(At.copy(ba).applyQuaternion(i).dot(this.eye))>.99&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="XY"&&Math.abs(At.copy(ba).applyQuaternion(i).dot(this.eye))<.2&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="YZ"&&Math.abs(At.copy(xa).applyQuaternion(i).dot(this.eye))<.2&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="XZ"&&Math.abs(At.copy(fr).applyQuaternion(i).dot(this.eye))<.2&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1)):this.mode==="rotate"&&(Ec.copy(i),At.copy(this.eye).applyQuaternion(wt.copy(i).invert()),o.name.search("E")!==-1&&o.quaternion.setFromRotationMatrix(ox.lookAt(this.eye,rx,fr)),o.name==="X"&&(wt.setFromAxisAngle(xa,Math.atan2(-At.y,At.z)),wt.multiplyQuaternions(Ec,wt),o.quaternion.copy(wt)),o.name==="Y"&&(wt.setFromAxisAngle(fr,Math.atan2(At.x,At.z)),wt.multiplyQuaternions(Ec,wt),o.quaternion.copy(wt)),o.name==="Z"&&(wt.setFromAxisAngle(ba,Math.atan2(At.y,At.x)),wt.multiplyQuaternions(Ec,wt),o.quaternion.copy(wt))),o.visible=o.visible&&(o.name.indexOf("X")===-1||this.showX),o.visible=o.visible&&(o.name.indexOf("Y")===-1||this.showY),o.visible=o.visible&&(o.name.indexOf("Z")===-1||this.showZ),o.visible=o.visible&&(o.name.indexOf("E")===-1||this.showX&&this.showY&&this.showZ),o.material._color=o.material._color||o.material.color.clone(),o.material._opacity=o.material._opacity||o.material.opacity,o.material.color.copy(o.material._color),o.material.opacity=o.material._opacity,this.enabled&&this.axis&&(o.name===this.axis?(o.material.color.copy(this.materialLib.active.color),o.material.opacity=1):this.axis.split("").some(function(l){return o.name===l})&&(o.material.color.copy(this.materialLib.active.color),o.material.opacity=1))}super.updateMatrixWorld(e)}}class iD extends v.Mesh{constructor(){super(new v.PlaneGeometry(1e5,1e5,2,2),new v.MeshBasicMaterial({visible:!1,wireframe:!0,side:v.DoubleSide,transparent:!0,opacity:.1,toneMapped:!1})),this.isTransformControlsPlane=!0,this.type="TransformControlsPlane"}updateMatrixWorld(e){let t=this.space;switch(this.position.copy(this.worldPosition),this.mode==="scale"&&(t="local"),Tc.copy(xa).applyQuaternion(t==="local"?this.worldQuaternion:Ic),ya.copy(fr).applyQuaternion(t==="local"?this.worldQuaternion:Ic),va.copy(ba).applyQuaternion(t==="local"?this.worldQuaternion:Ic),At.copy(ya),this.mode){case"translate":case"scale":switch(this.axis){case"X":At.copy(this.eye).cross(Tc),wn.copy(Tc).cross(At);break;case"Y":At.copy(this.eye).cross(ya),wn.copy(ya).cross(At);break;case"Z":At.copy(this.eye).cross(va),wn.copy(va).cross(At);break;case"XY":wn.copy(va);break;case"YZ":wn.copy(Tc);break;case"XZ":At.copy(va),wn.copy(ya);break;case"XYZ":case"E":wn.set(0,0,0);break}break;case"rotate":default:wn.set(0,0,0)}wn.length()===0?this.quaternion.copy(this.cameraQuaternion):(ax.lookAt(ti.set(0,0,0),wn,At),this.quaternion.setFromRotationMatrix(ax)),super.updateMatrixWorld(e)}}class nD extends v.DataTextureLoader{constructor(e){super(e),this.type=v.HalfFloatType}parse(e){const o=function(D,M){switch(D){case 1:throw new Error("THREE.HDRLoader: Read Error: "+(M||""));case 2:throw new Error("THREE.HDRLoader: Write Error: "+(M||""));case 3:throw new Error("THREE.HDRLoader: Bad File Format: "+(M||""));default:case 4:throw new Error("THREE.HDRLoader: Memory Error: "+(M||""))}},d=function(D,M,I){M=M||1024;let T=D.pos,R=-1,E=0,F="",N=String.fromCharCode.apply(null,new Uint16Array(D.subarray(T,T+128)));for(;0>(R=N.indexOf(`
|
|
4941
|
+
`);this.workerSourceURL=URL.createObjectURL(new Blob([l])),this.transcoderBinary=o,this.workerPool.setWorkerCreator(()=>{const c=new Worker(this.workerSourceURL),h=this.transcoderBinary.slice(0);return c.postMessage({type:"init",config:this.workerConfig,transcoderBinary:h},[h]),c})}),Qu>0&&console.warn("THREE.KTX2Loader: Multiple active KTX2 loaders may cause performance issues. Use a single KTX2Loader instance, or call .dispose() on old instances."),Qu++}return this.transcoderPending}load(e,t,i,s){if(this.workerConfig===null)throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.");const r=new v.FileLoader(this.manager);r.setPath(this.path),r.setCrossOrigin(this.crossOrigin),r.setWithCredentials(this.withCredentials),r.setRequestHeader(this.requestHeader),r.setResponseType("arraybuffer"),r.load(e,o=>{this.parse(o,t,s)},i,s)}parse(e,t,i){if(this.workerConfig===null)throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.");if(Vu.has(e))return Vu.get(e).promise.then(t).catch(i);this._createTexture(e).then(s=>t?t(s):null).catch(i)}_createTextureFrom(e,t){const{type:i,error:s,data:{faces:r,width:o,height:a,format:l,type:c,dfdFlags:h}}=e;if(i==="error")return Promise.reject(s);let d;if(t.faceCount===6)d=new v.CompressedCubeTexture(r,l,c);else{const f=r[0].mipmaps;d=t.layerCount>1?new v.CompressedArrayTexture(f,o,a,t.layerCount,l,c):new v.CompressedTexture(f,o,a,l,c)}return d.minFilter=r[0].mipmaps.length===1?v.LinearFilter:v.LinearMipmapLinearFilter,d.magFilter=v.LinearFilter,d.generateMipmaps=!1,d.needsUpdate=!0,d.colorSpace=_0(t),d.premultiplyAlpha=!!(h&XI),d}async _createTexture(e,t={}){const i=JI(new Uint8Array(e)),s=i.vkFormat===Uu&&i.dataFormatDescriptor[0].colorModel===167;if(!(i.vkFormat===$I||s&&!this.workerConfig.astcHDRSupported))return nT(i);const o=t,a=this.init().then(()=>this.workerPool.postMessage({type:"transcode",buffer:e,taskConfig:o},[e])).then(l=>this._createTextureFrom(l.data,i));return Vu.set(e,{promise:a}),a}dispose(){this.workerPool.dispose(),this.workerSourceURL&&URL.revokeObjectURL(this.workerSourceURL),Qu--}}zi.BasisFormat={ETC1S:0,UASTC:1,UASTC_HDR:2},zi.TranscoderFormat={ETC1:0,ETC2:1,BC1:2,BC3:3,BC4:4,BC5:5,BC7_M6_OPAQUE_ONLY:6,BC7_M5:7,PVRTC1_4_RGB:8,PVRTC1_4_RGBA:9,ASTC_4x4:10,ATC_RGB:11,ATC_RGBA_INTERPOLATED_ALPHA:12,RGBA32:13,RGB565:14,BGR565:15,RGBA4444:16,BC6H:22,RGB_HALF:24,RGBA_HALF:25},zi.EngineFormat={RGBAFormat:v.RGBAFormat,RGBA_ASTC_4x4_Format:v.RGBA_ASTC_4x4_Format,RGB_BPTC_UNSIGNED_Format:v.RGB_BPTC_UNSIGNED_Format,RGBA_BPTC_Format:v.RGBA_BPTC_Format,RGBA_ETC2_EAC_Format:v.RGBA_ETC2_EAC_Format,RGBA_PVRTC_4BPPV1_Format:v.RGBA_PVRTC_4BPPV1_Format,RGBA_S3TC_DXT5_Format:v.RGBA_S3TC_DXT5_Format,RGB_ETC1_Format:v.RGB_ETC1_Format,RGB_ETC2_Format:v.RGB_ETC2_Format,RGB_PVRTC_4BPPV1_Format:v.RGB_PVRTC_4BPPV1_Format,RGBA_S3TC_DXT1_Format:v.RGBA_S3TC_DXT1_Format},zi.EngineType={UnsignedByteType:v.UnsignedByteType,HalfFloatType:v.HalfFloatType,FloatType:v.FloatType},zi.BasisWorker=function(){let n,e,t;const i=_EngineFormat,s=_EngineType,r=_TranscoderFormat,o=_BasisFormat;self.addEventListener("message",function(g){const p=g.data;switch(p.type){case"init":n=p.config,a(p.transcoderBinary);break;case"transcode":e.then(()=>{try{const{faces:m,buffers:A,width:x,height:b,hasAlpha:y,format:_,type:S,dfdFlags:C}=l(p.buffer);self.postMessage({type:"transcode",id:p.id,data:{faces:m,width:x,height:b,hasAlpha:y,format:_,type:S,dfdFlags:C}},A)}catch(m){console.error(m),self.postMessage({type:"error",id:p.id,error:m.message})}});break}});function a(g){e=new Promise(p=>{t={wasmBinary:g,onRuntimeInitialized:p},BASIS(t)}).then(()=>{t.initializeBasis(),t.KTX2File===void 0&&console.warn("THREE.KTX2Loader: Please update Basis Universal transcoder.")})}function l(g){const p=new t.KTX2File(new Uint8Array(g));function m(){p.close(),p.delete()}if(!p.isValid())throw m(),new Error("THREE.KTX2Loader: Invalid or unsupported .ktx2 file");let A;if(p.isUASTC())A=o.UASTC;else if(p.isETC1S())A=o.ETC1S;else if(p.isHDR())A=o.UASTC_HDR;else throw new Error("THREE.KTX2Loader: Unknown Basis encoding");const x=p.getWidth(),b=p.getHeight(),y=p.getLayers()||1,_=p.getLevels(),S=p.getFaces(),C=p.getHasAlpha(),D=p.getDFDFlags(),{transcoderFormat:M,engineFormat:I,engineType:L}=d(A,x,b,C);if(!x||!b||!_)throw m(),new Error("THREE.KTX2Loader: Invalid texture");if(!p.startTranscoding())throw m(),new Error("THREE.KTX2Loader: .startTranscoding failed");const T=[],R=[];for(let E=0;E<S;E++){const F=[];for(let N=0;N<_;N++){const H=[];let V,U;for(let G=0;G<y;G++){const j=p.getImageLevelInfo(N,G,E);E===0&&N===0&&G===0&&(j.origWidth%4!==0||j.origHeight%4!==0)&&console.warn("THREE.KTX2Loader: ETC1S and UASTC textures should use multiple-of-four dimensions."),_>1?(V=j.origWidth,U=j.origHeight):(V=j.width,U=j.height);let oe=new Uint8Array(p.getImageTranscodedSizeInBytes(N,G,0,M));const fe=p.transcodeImage(oe,N,G,E,M,0,-1,-1);if(L===s.HalfFloatType&&(oe=new Uint16Array(oe.buffer,oe.byteOffset,oe.byteLength/Uint16Array.BYTES_PER_ELEMENT)),!fe)throw m(),new Error("THREE.KTX2Loader: .transcodeImage failed.");H.push(oe)}const q=u(H);F.push({data:q,width:V,height:U}),R.push(q.buffer)}T.push({mipmaps:F,width:x,height:b,format:I,type:L})}return m(),{faces:T,buffers:R,width:x,height:b,hasAlpha:C,dfdFlags:D,format:I,type:L}}const c=[{if:"astcSupported",basisFormat:[o.UASTC],transcoderFormat:[r.ASTC_4x4,r.ASTC_4x4],engineFormat:[i.RGBA_ASTC_4x4_Format,i.RGBA_ASTC_4x4_Format],engineType:[s.UnsignedByteType],priorityETC1S:1/0,priorityUASTC:1,needsPowerOfTwo:!1},{if:"bptcSupported",basisFormat:[o.ETC1S,o.UASTC],transcoderFormat:[r.BC7_M5,r.BC7_M5],engineFormat:[i.RGBA_BPTC_Format,i.RGBA_BPTC_Format],engineType:[s.UnsignedByteType],priorityETC1S:3,priorityUASTC:2,needsPowerOfTwo:!1},{if:"dxtSupported",basisFormat:[o.ETC1S,o.UASTC],transcoderFormat:[r.BC1,r.BC3],engineFormat:[i.RGBA_S3TC_DXT1_Format,i.RGBA_S3TC_DXT5_Format],engineType:[s.UnsignedByteType],priorityETC1S:4,priorityUASTC:5,needsPowerOfTwo:!1},{if:"etc2Supported",basisFormat:[o.ETC1S,o.UASTC],transcoderFormat:[r.ETC1,r.ETC2],engineFormat:[i.RGB_ETC2_Format,i.RGBA_ETC2_EAC_Format],engineType:[s.UnsignedByteType],priorityETC1S:1,priorityUASTC:3,needsPowerOfTwo:!1},{if:"etc1Supported",basisFormat:[o.ETC1S,o.UASTC],transcoderFormat:[r.ETC1],engineFormat:[i.RGB_ETC1_Format],engineType:[s.UnsignedByteType],priorityETC1S:2,priorityUASTC:4,needsPowerOfTwo:!1},{if:"pvrtcSupported",basisFormat:[o.ETC1S,o.UASTC],transcoderFormat:[r.PVRTC1_4_RGB,r.PVRTC1_4_RGBA],engineFormat:[i.RGB_PVRTC_4BPPV1_Format,i.RGBA_PVRTC_4BPPV1_Format],engineType:[s.UnsignedByteType],priorityETC1S:5,priorityUASTC:6,needsPowerOfTwo:!0},{if:"bptcSupported",basisFormat:[o.UASTC_HDR],transcoderFormat:[r.BC6H],engineFormat:[i.RGB_BPTC_UNSIGNED_Format],engineType:[s.HalfFloatType],priorityHDR:1,needsPowerOfTwo:!1},{basisFormat:[o.ETC1S,o.UASTC],transcoderFormat:[r.RGBA32,r.RGBA32],engineFormat:[i.RGBAFormat,i.RGBAFormat],engineType:[s.UnsignedByteType,s.UnsignedByteType],priorityETC1S:100,priorityUASTC:100,needsPowerOfTwo:!1},{basisFormat:[o.UASTC_HDR],transcoderFormat:[r.RGBA_HALF],engineFormat:[i.RGBAFormat],engineType:[s.HalfFloatType],priorityHDR:100,needsPowerOfTwo:!1}],h={[o.ETC1S]:c.filter(g=>g.basisFormat.includes(o.ETC1S)).sort((g,p)=>g.priorityETC1S-p.priorityETC1S),[o.UASTC]:c.filter(g=>g.basisFormat.includes(o.UASTC)).sort((g,p)=>g.priorityUASTC-p.priorityUASTC),[o.UASTC_HDR]:c.filter(g=>g.basisFormat.includes(o.UASTC_HDR)).sort((g,p)=>g.priorityHDR-p.priorityHDR)};function d(g,p,m,A){const x=h[g];for(let b=0;b<x.length;b++){const y=x[b];if(y.if&&!n[y.if]||!y.basisFormat.includes(g)||A&&y.transcoderFormat.length<2||y.needsPowerOfTwo&&!(f(p)&&f(m)))continue;const _=y.transcoderFormat[A?1:0],S=y.engineFormat[A?1:0],C=y.engineType[0];return{transcoderFormat:_,engineFormat:S,engineType:C}}throw new Error("THREE.KTX2Loader: Failed to identify transcoding target.")}function f(g){return g<=2?!0:(g&g-1)===0&&g!==0}function u(g){if(g.length===1)return g[0];let p=0;for(let x=0;x<g.length;x++){const b=g[x];p+=b.byteLength}const m=new Uint8Array(p);let A=0;for(let x=0;x<g.length;x++){const b=g[x];m.set(b,A),A+=b.byteLength}return m}};const iT=new Set([v.RGBAFormat,v.RGBFormat,v.RGFormat,v.RedFormat]),Wu={[jA]:v.RGBAFormat,[QA]:v.RGFormat,[VA]:v.RedFormat,[GA]:v.RGBAFormat,[zA]:v.RGFormat,[NA]:v.RedFormat,[UA]:v.RGBAFormat,[OA]:v.RGBAFormat,[FA]:v.RGFormat,[kA]:v.RGFormat,[RA]:v.RedFormat,[LA]:v.RedFormat,[HA]:v.RGBFormat,[WA]:v.RGBFormat,[o0]:v.RGBA_ETC2_EAC_Format,[r0]:v.RGB_ETC2_Format,[a0]:v.R11_EAC_Format,[l0]:v.SIGNED_R11_EAC_Format,[c0]:v.RG11_EAC_Format,[h0]:v.SIGNED_RG11_EAC_Format,[Uu]:v.RGBA_ASTC_4x4_Format,[u0]:v.RGBA_ASTC_4x4_Format,[d0]:v.RGBA_ASTC_4x4_Format,[b0]:v.RGBA_ASTC_6x6_Format,[p0]:v.RGBA_ASTC_6x6_Format,[f0]:v.RGBA_ASTC_6x6_Format,[KA]:v.RGBA_S3TC_DXT1_Format,[YA]:v.RGBA_S3TC_DXT1_Format,[qA]:v.RGB_S3TC_DXT1_Format,[XA]:v.RGB_S3TC_DXT1_Format,[JA]:v.RGBA_S3TC_DXT5_Format,[$A]:v.RGBA_S3TC_DXT5_Format,[e0]:v.SIGNED_RED_RGTC1_Format,[ZA]:v.RED_RGTC1_Format,[i0]:v.SIGNED_RED_GREEN_RGTC2_Format,[t0]:v.RED_GREEN_RGTC2_Format,[s0]:v.RGBA_BPTC_Format,[n0]:v.RGBA_BPTC_Format,[x0]:v.RGBA_PVRTC_4BPPV1_Format,[m0]:v.RGBA_PVRTC_4BPPV1_Format,[A0]:v.RGBA_PVRTC_2BPPV1_Format,[g0]:v.RGBA_PVRTC_2BPPV1_Format},po={[jA]:v.FloatType,[QA]:v.FloatType,[VA]:v.FloatType,[GA]:v.HalfFloatType,[zA]:v.HalfFloatType,[NA]:v.HalfFloatType,[UA]:v.UnsignedByteType,[OA]:v.UnsignedByteType,[FA]:v.UnsignedByteType,[kA]:v.UnsignedByteType,[RA]:v.UnsignedByteType,[LA]:v.UnsignedByteType,[HA]:v.UnsignedInt5999Type,[WA]:v.UnsignedInt101111Type,[o0]:v.UnsignedByteType,[r0]:v.UnsignedByteType,[a0]:v.UnsignedByteType,[l0]:v.UnsignedByteType,[c0]:v.UnsignedByteType,[h0]:v.UnsignedByteType,[Uu]:v.HalfFloatType,[u0]:v.UnsignedByteType,[d0]:v.UnsignedByteType,[b0]:v.HalfFloatType,[p0]:v.UnsignedByteType,[f0]:v.UnsignedByteType,[KA]:v.UnsignedByteType,[YA]:v.UnsignedByteType,[qA]:v.UnsignedByteType,[XA]:v.UnsignedByteType,[JA]:v.UnsignedByteType,[$A]:v.UnsignedByteType,[e0]:v.UnsignedByteType,[ZA]:v.UnsignedByteType,[i0]:v.UnsignedByteType,[t0]:v.UnsignedByteType,[s0]:v.UnsignedByteType,[n0]:v.UnsignedByteType,[x0]:v.UnsignedByteType,[m0]:v.UnsignedByteType,[A0]:v.UnsignedByteType,[g0]:v.UnsignedByteType};async function nT(n){const{vkFormat:e}=n;if(Wu[e]===void 0)throw new Error("THREE.KTX2Loader: Unsupported vkFormat: "+e);po[e]===void 0&&console.warn('THREE.KTX2Loader: Missing ".type" for vkFormat: '+e);let t;n.supercompressionScheme===BA&&(ju||(ju=new Promise(async o=>{const a=new ZI;await a.init(),o(a)})),t=await ju);const i=[];for(let o=0;o<n.levels.length;o++){const a=Math.max(1,n.pixelWidth>>o),l=Math.max(1,n.pixelHeight>>o),c=n.pixelDepth?Math.max(1,n.pixelDepth>>o):0,h=n.levels[o];let d;if(n.supercompressionScheme===HI)d=h.levelData;else if(n.supercompressionScheme===BA)d=t.decode(h.levelData,h.uncompressedByteLength);else throw new Error("THREE.KTX2Loader: Unsupported supercompressionScheme.");let f;po[e]===v.FloatType?f=new Float32Array(d.buffer,d.byteOffset,d.byteLength/Float32Array.BYTES_PER_ELEMENT):po[e]===v.HalfFloatType?f=new Uint16Array(d.buffer,d.byteOffset,d.byteLength/Uint16Array.BYTES_PER_ELEMENT):po[e]===v.UnsignedInt5999Type||po[e]===v.UnsignedInt101111Type?f=new Uint32Array(d.buffer,d.byteOffset,d.byteLength/Uint32Array.BYTES_PER_ELEMENT):f=d,i.push({data:f,width:a,height:l,depth:c})}const s=n.levelCount===0||i.length>1;let r;if(iT.has(Wu[e]))r=n.pixelDepth===0?new v.DataTexture(i[0].data,n.pixelWidth,n.pixelHeight):new v.Data3DTexture(i[0].data,n.pixelWidth,n.pixelHeight,n.pixelDepth),r.minFilter=s?v.NearestMipmapNearestFilter:v.NearestFilter,r.magFilter=v.NearestFilter,r.generateMipmaps=n.levelCount===0;else{if(n.pixelDepth>0)throw new Error("THREE.KTX2Loader: Unsupported pixelDepth.");r=new v.CompressedTexture(i,n.pixelWidth,n.pixelHeight),r.minFilter=s?v.LinearMipmapLinearFilter:v.LinearFilter,r.magFilter=v.LinearFilter}return r.mipmaps=i,r.type=po[e],r.format=Wu[e],r.colorSpace=_0(n),r.needsUpdate=!0,Promise.resolve(r)}function _0(n){const e=n.dataFormatDescriptor[0];return e.colorPrimaries===YI?e.transferFunction===PA?v.SRGBColorSpace:v.LinearSRGBColorSpace:e.colorPrimaries===KI?e.transferFunction===PA?eT:tT:(e.colorPrimaries===qI||console.warn(`THREE.KTX2Loader: Unsupported color primaries, "${e.colorPrimaries}"`),v.NoColorSpace)}function sT(n,e,t,i){let s=0,r=0,o=0,a=n.models.find(u=>u.url==t),l=e.circularMeps,c=e.rectMeps?.filter(u=>u.type==="风管"),h=e.rectMeps?.filter(u=>u.type==="桥架"),d=e.ellipseMeps,f=n.scene;if(new w.MeshBasicMaterial,new w.BufferGeometry,l&&l.length){let u=[],g=0;for(let p of l)p.color=p.color.split(",").map(m=>parseInt(m)/255),p.color=new w.Color(p.color[0],p.color[1],p.color[2]),p.position={x:p.startPoint.X*.3048+s,y:p.startPoint.Z*.3048+r,z:-p.startPoint.Y*.3048+o},p.rotation={x:0,y:0,z:0},p.indexes=[[n.scene.children.length,g++,0,0]],a.nodesMap.set(Number(p.id),p),u.push(p);bc("Circle",f,u,t)}if(c&&c.length){let u=[],g=0;for(let p of c)p.color=p.color.split(",").map(m=>parseInt(m)/255),p.color=new w.Color(p.color[0],p.color[1],p.color[2]),p.position={x:p.startPoint.X*.3048+s,y:p.startPoint.Z*.3048+r,z:-p.startPoint.Y*.3048+o},p.rotation={x:0,y:0,z:0},p.indexes=[[n.scene.children.length,g++,0,0]],a.nodesMap.set(Number(p.id),p),u.push(p);bc("Rect",f,u,t)}if(d&&d.length){let u=[],g=0;for(let p of d)p.color=p.color.split(",").map(m=>parseInt(m)/255),p.color=new w.Color(p.color[0],p.color[1],p.color[2]),p.position={x:p.startPoint.X*.3048+s,y:p.startPoint.Z*.3048+r,z:-p.startPoint.Y*.3048+o},p.rotation={x:0,y:0,z:0},p.indexes=[[n.scene.children.length,g++,0,0]],a.nodesMap.set(Number(p.id),p),u.push(p);bc("Ellipse",f,u,t)}if(h&&h.length){let u=[],g=0;for(let p of h)p.color=p.color.split(",").map(m=>parseInt(m)/255),p.color=new w.Color(p.color[0],p.color[1],p.color[2]),p.position={x:p.startPoint.X*.3048+s,y:p.startPoint.Z*.3048+r,z:-p.startPoint.Y*.3048+o},p.rotation={x:0,y:0,z:0},p.indexes=[[n.scene.children.length,g++,0,0]],a.nodesMap.set(Number(p.id),p),u.push(p);bc("Bridge",f,u,t)}}function bc(n,e,t,i,s){let r,o,a={width:1,height:1,length:1,diameter:1,color:new w.Color,position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0}};switch(n){case"Rect":o=yc("Rect",a);break;case"Bridge":o=yc("Bridge",a);break;case"Circle":o=yc("Circle",a);break;case"Ellipse":o=yc("Ellipse",a);break}o&&(r=new w.InstancedMesh(o.geometry,o.material,t.length),r.url=i,e.add(r),r.index=e.children.length-1);let l=[],c=[];for(var h=0;h<t.length;h++){let u=t[h],g=new w.Vector3(u.startPoint.X,0,-u.startPoint.Y),p=new w.Vector3(u.endPoint.X,0,-u.endPoint.Y),m=new w.Vector3(u.startPoint.X,u.startPoint.Z,-u.startPoint.Y),A=new w.Vector3(u.endPoint.X,u.endPoint.Z,-u.endPoint.Y),x=0,b=0,y=0;if(Math.abs(p.clone().sub(g.clone()).z)<.01&&Math.abs(p.clone().sub(g.clone()).x)<.01){if(x=(u.startPoint.Z>u.endPoint.Z?1:-1)*Math.PI*.5,u.base_x!=null){var d=new w.Vector3(u.base_x.X,0,-u.base_x.Y);b=(d.clone().cross(new w.Vector3(0,0,1)).y<=0?1:-1)*d.angleTo(new w.Vector3(0,0,1))+Math.PI*.5}}else b=(p.clone().sub(g.clone()).cross(new w.Vector3(0,0,1)).y>0?-1:1)*p.clone().sub(g.clone()).angleTo(new w.Vector3(0,0,1)),x=(u.startPoint.Z>u.endPoint.Z?1:-1)*p.clone().sub(g.clone()).angleTo(A.clone().sub(m.clone()));let _=new w.Matrix4;const S=new w.Euler(x,b,y,"YXZ");let C=_.clone().makeRotationFromEuler(S),D,M;n==="Circle"?(D=u.diameter,M=u.diameter):(D=u.width,M=u.height);let I=_.clone().makeScale(D,M,u.length);_.multiplyMatrices(C,I),_.setPosition(u.position.x,u.position.y,u.position.z),r.setMatrixAt(h,_.clone()),r.setColorAt(h,u.color),r.geometry.computeBoundingBox();let L=r.geometry.boundingBox.min.clone().applyMatrix4(_.clone()),T=r.geometry.boundingBox.max.clone().applyMatrix4(_.clone()),R=new w.Vector3(Math.min(L.x,T.x),Math.min(L.y,T.y),Math.min(L.z,T.z)),E=new w.Vector3(Math.max(L.x,T.x),Math.max(L.y,T.y),Math.max(L.z,T.z)),F=R.clone().add(E.clone()).multiplyScalar(.5),N={name:u.name,min:R,max:E,center:F,dbid:h,materialName:o.material.name},H=null,V=null;n==="Circle"&&(H={x:u.startPoint.X*.3048,y:u.startPoint.Z*.3048,z:-u.startPoint.Y*.3048},V={x:u.endPoint.X*.3048,y:u.endPoint.Z*.3048,z:-u.endPoint.Y*.3048},N.minC=H,N.maxC=V),r.ids||(r.ids=[]),r.matrixs||(r.matrixs=[]),r.matrixs.push(_.clone()),c.push(_.clone()),r.ids.push(Number(u.id)),l.push(N)}r.castShadow=!0,r.ElementInfos=l,r.name="rootModel",r.TypeName="InstancedMesh-Pipe",r.PipeType=n,r.MeshId=null,r.realMaterial=r.material.clone(),r.originalMaterial=r.material.clone(),r.matrixsClone=c;let f=[];f={geometry:r.geometry,matrix:r.matrix,position:r.position,rotation:r.rotation},r.meshs=f,r.instanceMatrix&&r.instanceMatrix.array&&(r.cloneInstanceMatrix=Array.from(r.instanceMatrix.array))}function yc(n,e,t){let i=new w.Shape;switch(e.width=e.width*.3048,e.height=e.height*.3048,e.diameter=e.diameter*.3048,n){case"Rect":i.moveTo(-e.width/2,-e.height/2),i.lineTo(-e.width/2,e.height/2),i.lineTo(e.width/2,e.height/2),i.lineTo(e.width/2,-e.height/2),i.lineTo(-e.width/2,-e.height/2);break;case"Ellipse":i.moveTo(-e.width/2,-e.height/2),i.lineTo(-e.width/2,e.height/2),i.lineTo(e.width/2,e.height/2),i.lineTo(e.width/2,-e.height/2),i.lineTo(-e.width/2,-e.height/2);break;case"Bridge":i.moveTo(-e.width/2,-e.height/2),i.lineTo(-e.width/2,e.height/2),i.lineTo(-e.width/2+.01,e.height/2),i.lineTo(-e.width/2+.01,-e.height/2+.01),i.lineTo(e.width/2-.01,-e.height/2+.01),i.lineTo(e.width/2-.01,e.height/2),i.lineTo(e.width/2,e.height/2),i.lineTo(e.width/2,-e.height/2),i.lineTo(-e.width/2,-e.height/2);break;case"Circle":i.moveTo(0,0),i.absarc(0,0,e.diameter*.5,0,Math.PI*2,!1);break}const s={depth:e.length*.3048,bevelEnabled:!1};return r(i,s,e.color,e.position,e.rotation);function r(o,a,l,c,h){let d=new w.ExtrudeGeometry(o,a),f=new w.MeshStandardMaterial({color:l,side:w.DoubleSide}),u=new w.Mesh(d,f);return u.position.set(c.x,c.y,c.z),u.rotation._order="YXZ",u.rotation.set(h.x,h.y,h.z),u}}function Yn(n,e=!1){const t=n[0].index!==null,i=new Set(Object.keys(n[0].attributes)),s=new Set(Object.keys(n[0].morphAttributes)),r={},o={},a=n[0].morphTargetsRelative,l=new v.BufferGeometry;let c=0;for(let h=0;h<n.length;++h){const d=n[h];let f=0;if(t!==(d.index!==null))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+h+". All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them."),null;for(const u in d.attributes){if(!i.has(u))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+h+'. All geometries must have compatible attributes; make sure "'+u+'" attribute exists among all geometries, or in none of them.'),null;r[u]===void 0&&(r[u]=[]),r[u].push(d.attributes[u]),f++}if(f!==i.size)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+h+". Make sure all geometries have the same number of attributes."),null;if(a!==d.morphTargetsRelative)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+h+". .morphTargetsRelative must be consistent throughout all geometries."),null;for(const u in d.morphAttributes){if(!s.has(u))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+h+". .morphAttributes must be consistent throughout all geometries."),null;o[u]===void 0&&(o[u]=[]),o[u].push(d.morphAttributes[u])}if(e){let u;if(t)u=d.index.count;else if(d.attributes.position!==void 0)u=d.attributes.position.count;else return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+h+". The geometry must have either an index or a position attribute"),null;l.addGroup(c,u,h),c+=u}}if(t){let h=0;const d=[];for(let f=0;f<n.length;++f){const u=n[f].index;for(let g=0;g<u.count;++g)d.push(u.getX(g)+h);h+=n[f].attributes.position.count}l.setIndex(d)}for(const h in r){const d=w0(r[h]);if(!d)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the "+h+" attribute."),null;l.setAttribute(h,d)}for(const h in o){const d=o[h][0].length;if(d===0)break;l.morphAttributes=l.morphAttributes||{},l.morphAttributes[h]=[];for(let f=0;f<d;++f){const u=[];for(let p=0;p<o[h].length;++p)u.push(o[h][p][f]);const g=w0(u);if(!g)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the "+h+" morphAttribute."),null;l.morphAttributes[h].push(g)}}return l}function w0(n){let e,t,i,s=-1,r=0;for(let c=0;c<n.length;++c){const h=n[c];if(e===void 0&&(e=h.array.constructor),e!==h.array.constructor)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes."),null;if(t===void 0&&(t=h.itemSize),t!==h.itemSize)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes."),null;if(i===void 0&&(i=h.normalized),i!==h.normalized)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes."),null;if(s===-1&&(s=h.gpuType),s!==h.gpuType)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.gpuType must be consistent across matching attributes."),null;r+=h.count*t}const o=new e(r),a=new v.BufferAttribute(o,t,i);let l=0;for(let c=0;c<n.length;++c){const h=n[c];if(h.isInterleavedBufferAttribute){const d=l/t;for(let f=0,u=h.count;f<u;f++)for(let g=0;g<t;g++){const p=h.getComponent(f,g);a.setComponent(f+d,g,p)}}else o.set(h.array,l);l+=h.count*t}return s!==void 0&&(a.gpuType=s),a}function S0(n,e){if(e===v.TrianglesDrawMode)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),n;if(e===v.TriangleFanDrawMode||e===v.TriangleStripDrawMode){let t=n.getIndex();if(t===null){const o=[],a=n.getAttribute("position");if(a!==void 0){for(let l=0;l<a.count;l++)o.push(l);n.setIndex(o),t=n.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),n}const i=t.count-2,s=[];if(e===v.TriangleFanDrawMode)for(let o=1;o<=i;o++)s.push(t.getX(0)),s.push(t.getX(o)),s.push(t.getX(o+1));else for(let o=0;o<i;o++)o%2===0?(s.push(t.getX(o)),s.push(t.getX(o+1)),s.push(t.getX(o+2))):(s.push(t.getX(o+2)),s.push(t.getX(o+1)),s.push(t.getX(o)));s.length/3!==i&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const r=n.clone();return r.setIndex(s),r.clearGroups(),r}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),n}function rT(n){const e=new Map,t=new Map,i=n.clone();return C0(n,i,function(s,r){e.set(r,s),t.set(s,r)}),i.traverse(function(s){if(!s.isSkinnedMesh)return;const r=s,o=e.get(s),a=o.skeleton.bones;r.skeleton=o.skeleton.clone(),r.bindMatrix.copy(o.bindMatrix),r.skeleton.bones=a.map(function(l){return t.get(l)}),r.bind(r.skeleton,r.bindMatrix)}),i}function C0(n,e,t){t(n,e);for(let i=0;i<n.children.length;i++)C0(n.children[i],e.children[i],t)}class oT extends v.Loader{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new dT(t)}),this.register(function(t){return new uT(t)}),this.register(function(t){return new vT(t)}),this.register(function(t){return new _T(t)}),this.register(function(t){return new wT(t)}),this.register(function(t){return new pT(t)}),this.register(function(t){return new gT(t)}),this.register(function(t){return new mT(t)}),this.register(function(t){return new AT(t)}),this.register(function(t){return new hT(t)}),this.register(function(t){return new xT(t)}),this.register(function(t){return new fT(t)}),this.register(function(t){return new yT(t)}),this.register(function(t){return new bT(t)}),this.register(function(t){return new lT(t)}),this.register(function(t){return new M0(t,et.EXT_MESHOPT_COMPRESSION)}),this.register(function(t){return new M0(t,et.KHR_MESHOPT_COMPRESSION)}),this.register(function(t){return new ST(t)})}load(e,t,i,s){const r=this;let o;if(this.resourcePath!=="")o=this.resourcePath;else if(this.path!==""){const c=v.LoaderUtils.extractUrlBase(e);o=v.LoaderUtils.resolveURL(c,this.path)}else o=v.LoaderUtils.extractUrlBase(e);this.manager.itemStart(e);const a=function(c){s?s(c):console.error(c),r.manager.itemError(e),r.manager.itemEnd(e)},l=new v.FileLoader(this.manager);l.setPath(this.path),l.setResponseType("arraybuffer"),l.setRequestHeader(this.requestHeader),l.setWithCredentials(this.withCredentials),l.load(e,function(c){try{r.parse(c,o,function(h){t(h),r.manager.itemEnd(e)},a)}catch(h){a(h)}},i,a)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,i,s){let r;const o={},a={},l=new TextDecoder;if(typeof e=="string")r=JSON.parse(e);else if(e instanceof ArrayBuffer)if(l.decode(new Uint8Array(e,0,4))===E0){try{o[et.KHR_BINARY_GLTF]=new CT(e)}catch(d){s&&s(d);return}r=JSON.parse(o[et.KHR_BINARY_GLTF].content)}else r=JSON.parse(l.decode(e));else r=e;if(r.asset===void 0||r.asset.version[0]<2){s&&s(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const c=new UT(r,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});c.fileLoader.setRequestHeader(this.requestHeader);for(let h=0;h<this.pluginCallbacks.length;h++){const d=this.pluginCallbacks[h](c);d.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),a[d.name]=d,o[d.name]=!0}if(r.extensionsUsed)for(let h=0;h<r.extensionsUsed.length;++h){const d=r.extensionsUsed[h],f=r.extensionsRequired||[];switch(d){case et.KHR_MATERIALS_UNLIT:o[d]=new cT;break;case et.KHR_DRACO_MESH_COMPRESSION:o[d]=new MT(r,this.dracoLoader);break;case et.KHR_TEXTURE_TRANSFORM:o[d]=new ET;break;case et.KHR_MESH_QUANTIZATION:o[d]=new IT;break;default:f.indexOf(d)>=0&&a[d]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+d+'".')}}c.setExtensions(o),c.setPlugins(a),c.parse(i,s)}parseAsync(e,t){const i=this;return new Promise(function(s,r){i.parse(e,t,s,r)})}}function aT(){let n={};return{get:function(e){return n[e]},add:function(e,t){n[e]=t},remove:function(e){delete n[e]},removeAll:function(){n={}}}}function kt(n,e,t){const i=n.json.materials[e];return i.extensions&&i.extensions[t]?i.extensions[t]:null}const et={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",KHR_MESHOPT_COMPRESSION:"KHR_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class lT{constructor(e){this.parser=e,this.name=et.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let i=0,s=t.length;i<s;i++){const r=t[i];r.extensions&&r.extensions[this.name]&&r.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,r.extensions[this.name].light)}}_loadLight(e){const t=this.parser,i="light:"+e;let s=t.cache.get(i);if(s)return s;const r=t.json,l=((r.extensions&&r.extensions[this.name]||{}).lights||[])[e];let c;const h=new v.Color(16777215);l.color!==void 0&&h.setRGB(l.color[0],l.color[1],l.color[2],v.LinearSRGBColorSpace);const d=l.range!==void 0?l.range:0;switch(l.type){case"directional":c=new v.DirectionalLight(h),c.target.position.set(0,0,-1),c.add(c.target);break;case"point":c=new v.PointLight(h),c.distance=d;break;case"spot":c=new v.SpotLight(h),c.distance=d,l.spot=l.spot||{},l.spot.innerConeAngle=l.spot.innerConeAngle!==void 0?l.spot.innerConeAngle:0,l.spot.outerConeAngle=l.spot.outerConeAngle!==void 0?l.spot.outerConeAngle:Math.PI/4,c.angle=l.spot.outerConeAngle,c.penumbra=1-l.spot.innerConeAngle/l.spot.outerConeAngle,c.target.position.set(0,0,-1),c.add(c.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+l.type)}return c.position.set(0,0,0),vn(c,l),l.intensity!==void 0&&(c.intensity=l.intensity),c.name=t.createUniqueName(l.name||"light_"+e),s=Promise.resolve(c),t.cache.add(i,s),s}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){const t=this,i=this.parser,r=i.json.nodes[e],a=(r.extensions&&r.extensions[this.name]||{}).light;return a===void 0?null:this._loadLight(a).then(function(l){return i._getNodeRef(t.cache,a,l)})}}class cT{constructor(){this.name=et.KHR_MATERIALS_UNLIT}getMaterialType(){return v.MeshBasicMaterial}extendParams(e,t,i){const s=[];e.color=new v.Color(1,1,1),e.opacity=1;const r=t.pbrMetallicRoughness;if(r){if(Array.isArray(r.baseColorFactor)){const o=r.baseColorFactor;e.color.setRGB(o[0],o[1],o[2],v.LinearSRGBColorSpace),e.opacity=o[3]}r.baseColorTexture!==void 0&&s.push(i.assignTexture(e,"map",r.baseColorTexture,v.SRGBColorSpace))}return Promise.all(s)}}class hT{constructor(e){this.parser=e,this.name=et.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const i=kt(this.parser,e,this.name);return i===null||i.emissiveStrength!==void 0&&(t.emissiveIntensity=i.emissiveStrength),Promise.resolve()}}class dT{constructor(e){this.parser=e,this.name=et.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){return kt(this.parser,e,this.name)!==null?v.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=kt(this.parser,e,this.name);if(i===null)return Promise.resolve();const s=[];if(i.clearcoatFactor!==void 0&&(t.clearcoat=i.clearcoatFactor),i.clearcoatTexture!==void 0&&s.push(this.parser.assignTexture(t,"clearcoatMap",i.clearcoatTexture)),i.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=i.clearcoatRoughnessFactor),i.clearcoatRoughnessTexture!==void 0&&s.push(this.parser.assignTexture(t,"clearcoatRoughnessMap",i.clearcoatRoughnessTexture)),i.clearcoatNormalTexture!==void 0&&(s.push(this.parser.assignTexture(t,"clearcoatNormalMap",i.clearcoatNormalTexture)),i.clearcoatNormalTexture.scale!==void 0)){const r=i.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new v.Vector2(r,r)}return Promise.all(s)}}class uT{constructor(e){this.parser=e,this.name=et.KHR_MATERIALS_DISPERSION}getMaterialType(e){return kt(this.parser,e,this.name)!==null?v.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=kt(this.parser,e,this.name);return i===null||(t.dispersion=i.dispersion!==void 0?i.dispersion:0),Promise.resolve()}}class fT{constructor(e){this.parser=e,this.name=et.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){return kt(this.parser,e,this.name)!==null?v.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=kt(this.parser,e,this.name);if(i===null)return Promise.resolve();const s=[];return i.iridescenceFactor!==void 0&&(t.iridescence=i.iridescenceFactor),i.iridescenceTexture!==void 0&&s.push(this.parser.assignTexture(t,"iridescenceMap",i.iridescenceTexture)),i.iridescenceIor!==void 0&&(t.iridescenceIOR=i.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),i.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=i.iridescenceThicknessMinimum),i.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=i.iridescenceThicknessMaximum),i.iridescenceThicknessTexture!==void 0&&s.push(this.parser.assignTexture(t,"iridescenceThicknessMap",i.iridescenceThicknessTexture)),Promise.all(s)}}class pT{constructor(e){this.parser=e,this.name=et.KHR_MATERIALS_SHEEN}getMaterialType(e){return kt(this.parser,e,this.name)!==null?v.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=kt(this.parser,e,this.name);if(i===null)return Promise.resolve();const s=[];if(t.sheenColor=new v.Color(0,0,0),t.sheenRoughness=0,t.sheen=1,i.sheenColorFactor!==void 0){const r=i.sheenColorFactor;t.sheenColor.setRGB(r[0],r[1],r[2],v.LinearSRGBColorSpace)}return i.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=i.sheenRoughnessFactor),i.sheenColorTexture!==void 0&&s.push(this.parser.assignTexture(t,"sheenColorMap",i.sheenColorTexture,v.SRGBColorSpace)),i.sheenRoughnessTexture!==void 0&&s.push(this.parser.assignTexture(t,"sheenRoughnessMap",i.sheenRoughnessTexture)),Promise.all(s)}}class gT{constructor(e){this.parser=e,this.name=et.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){return kt(this.parser,e,this.name)!==null?v.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=kt(this.parser,e,this.name);if(i===null)return Promise.resolve();const s=[];return i.transmissionFactor!==void 0&&(t.transmission=i.transmissionFactor),i.transmissionTexture!==void 0&&s.push(this.parser.assignTexture(t,"transmissionMap",i.transmissionTexture)),Promise.all(s)}}class mT{constructor(e){this.parser=e,this.name=et.KHR_MATERIALS_VOLUME}getMaterialType(e){return kt(this.parser,e,this.name)!==null?v.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=kt(this.parser,e,this.name);if(i===null)return Promise.resolve();const s=[];t.thickness=i.thicknessFactor!==void 0?i.thicknessFactor:0,i.thicknessTexture!==void 0&&s.push(this.parser.assignTexture(t,"thicknessMap",i.thicknessTexture)),t.attenuationDistance=i.attenuationDistance||1/0;const r=i.attenuationColor||[1,1,1];return t.attenuationColor=new v.Color().setRGB(r[0],r[1],r[2],v.LinearSRGBColorSpace),Promise.all(s)}}class AT{constructor(e){this.parser=e,this.name=et.KHR_MATERIALS_IOR}getMaterialType(e){return kt(this.parser,e,this.name)!==null?v.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=kt(this.parser,e,this.name);return i===null||(t.ior=i.ior!==void 0?i.ior:1.5),Promise.resolve()}}class xT{constructor(e){this.parser=e,this.name=et.KHR_MATERIALS_SPECULAR}getMaterialType(e){return kt(this.parser,e,this.name)!==null?v.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=kt(this.parser,e,this.name);if(i===null)return Promise.resolve();const s=[];t.specularIntensity=i.specularFactor!==void 0?i.specularFactor:1,i.specularTexture!==void 0&&s.push(this.parser.assignTexture(t,"specularIntensityMap",i.specularTexture));const r=i.specularColorFactor||[1,1,1];return t.specularColor=new v.Color().setRGB(r[0],r[1],r[2],v.LinearSRGBColorSpace),i.specularColorTexture!==void 0&&s.push(this.parser.assignTexture(t,"specularColorMap",i.specularColorTexture,v.SRGBColorSpace)),Promise.all(s)}}class bT{constructor(e){this.parser=e,this.name=et.EXT_MATERIALS_BUMP}getMaterialType(e){return kt(this.parser,e,this.name)!==null?v.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=kt(this.parser,e,this.name);if(i===null)return Promise.resolve();const s=[];return t.bumpScale=i.bumpFactor!==void 0?i.bumpFactor:1,i.bumpTexture!==void 0&&s.push(this.parser.assignTexture(t,"bumpMap",i.bumpTexture)),Promise.all(s)}}class yT{constructor(e){this.parser=e,this.name=et.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){return kt(this.parser,e,this.name)!==null?v.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=kt(this.parser,e,this.name);if(i===null)return Promise.resolve();const s=[];return i.anisotropyStrength!==void 0&&(t.anisotropy=i.anisotropyStrength),i.anisotropyRotation!==void 0&&(t.anisotropyRotation=i.anisotropyRotation),i.anisotropyTexture!==void 0&&s.push(this.parser.assignTexture(t,"anisotropyMap",i.anisotropyTexture)),Promise.all(s)}}class vT{constructor(e){this.parser=e,this.name=et.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,i=t.json,s=i.textures[e];if(!s.extensions||!s.extensions[this.name])return null;const r=s.extensions[this.name],o=t.options.ktx2Loader;if(!o){if(i.extensionsRequired&&i.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,r.source,o)}}class _T{constructor(e){this.parser=e,this.name=et.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,i=this.parser,s=i.json,r=s.textures[e];if(!r.extensions||!r.extensions[t])return null;const o=r.extensions[t],a=s.images[o.source];let l=i.textureLoader;if(a.uri){const c=i.options.manager.getHandler(a.uri);c!==null&&(l=c)}return i.loadTextureImage(e,o.source,l)}}class wT{constructor(e){this.parser=e,this.name=et.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,i=this.parser,s=i.json,r=s.textures[e];if(!r.extensions||!r.extensions[t])return null;const o=r.extensions[t],a=s.images[o.source];let l=i.textureLoader;if(a.uri){const c=i.options.manager.getHandler(a.uri);c!==null&&(l=c)}return i.loadTextureImage(e,o.source,l)}}class M0{constructor(e,t){this.name=t,this.parser=e}loadBufferView(e){const t=this.parser.json,i=t.bufferViews[e];if(i.extensions&&i.extensions[this.name]){const s=i.extensions[this.name],r=this.parser.getDependency("buffer",s.buffer),o=this.parser.options.meshoptDecoder;if(!o||!o.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return r.then(function(a){const l=s.byteOffset||0,c=s.byteLength||0,h=s.count,d=s.byteStride,f=new Uint8Array(a,l,c);return o.decodeGltfBufferAsync?o.decodeGltfBufferAsync(h,d,f,s.mode,s.filter).then(function(u){return u.buffer}):o.ready.then(function(){const u=new ArrayBuffer(h*d);return o.decodeGltfBuffer(new Uint8Array(u),h,d,f,s.mode,s.filter),u})})}else return null}}class ST{constructor(e){this.name=et.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,i=t.nodes[e];if(!i.extensions||!i.extensions[this.name]||i.mesh===void 0)return null;const s=t.meshes[i.mesh];for(const c of s.primitives)if(c.mode!==Gi.TRIANGLES&&c.mode!==Gi.TRIANGLE_STRIP&&c.mode!==Gi.TRIANGLE_FAN&&c.mode!==void 0)return null;const o=i.extensions[this.name].attributes,a=[],l={};for(const c in o)a.push(this.parser.getDependency("accessor",o[c]).then(h=>(l[c]=h,l[c])));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then(c=>{const h=c.pop(),d=h.isGroup?h.children:[h],f=c[0].count,u=[];for(const g of d){const p=new v.Matrix4,m=new v.Vector3,A=new v.Quaternion,x=new v.Vector3(1,1,1),b=new v.InstancedMesh(g.geometry,g.material,f);for(let y=0;y<f;y++)l.TRANSLATION&&m.fromBufferAttribute(l.TRANSLATION,y),l.ROTATION&&A.fromBufferAttribute(l.ROTATION,y),l.SCALE&&x.fromBufferAttribute(l.SCALE,y),b.setMatrixAt(y,p.compose(m,A,x));for(const y in l)if(y==="_COLOR_0"){const _=l[y];b.instanceColor=new v.InstancedBufferAttribute(_.array,_.itemSize,_.normalized)}else y!=="TRANSLATION"&&y!=="ROTATION"&&y!=="SCALE"&&g.geometry.setAttribute(y,l[y]);v.Object3D.prototype.copy.call(b,g),this.parser.assignFinalMaterial(b),u.push(b)}return h.isGroup?(h.clear(),h.add(...u),h):u[0]}))}}const E0="glTF",ua=12,I0={JSON:1313821514,BIN:5130562};class CT{constructor(e){this.name=et.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,ua),i=new TextDecoder;if(this.header={magic:i.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==E0)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const s=this.header.length-ua,r=new DataView(e,ua);let o=0;for(;o<s;){const a=r.getUint32(o,!0);o+=4;const l=r.getUint32(o,!0);if(o+=4,l===I0.JSON){const c=new Uint8Array(e,ua+o,a);this.content=i.decode(c)}else if(l===I0.BIN){const c=ua+o;this.body=e.slice(c,c+a)}o+=a}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class MT{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=et.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const i=this.json,s=this.dracoLoader,r=e.extensions[this.name].bufferView,o=e.extensions[this.name].attributes,a={},l={},c={};for(const h in o){const d=Xu[h]||h.toLowerCase();a[d]=o[h]}for(const h in e.attributes){const d=Xu[h]||h.toLowerCase();if(o[h]!==void 0){const f=i.accessors[e.attributes[h]],u=go[f.componentType];c[d]=u.name,l[d]=f.normalized===!0}}return t.getDependency("bufferView",r).then(function(h){return new Promise(function(d,f){s.decodeDracoFile(h,function(u){for(const g in u.attributes){const p=u.attributes[g],m=l[g];m!==void 0&&(p.normalized=m)}d(u)},a,c,v.LinearSRGBColorSpace,f)})})}}class ET{constructor(){this.name=et.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0||(e=e.clone(),t.texCoord!==void 0&&(e.channel=t.texCoord),t.offset!==void 0&&e.offset.fromArray(t.offset),t.rotation!==void 0&&(e.rotation=t.rotation),t.scale!==void 0&&e.repeat.fromArray(t.scale),e.needsUpdate=!0),e}}class IT{constructor(){this.name=et.KHR_MESH_QUANTIZATION}}class T0 extends v.Interpolant{constructor(e,t,i,s){super(e,t,i,s)}copySampleValue_(e){const t=this.resultBuffer,i=this.sampleValues,s=this.valueSize,r=e*s*3+s;for(let o=0;o!==s;o++)t[o]=i[r+o];return t}interpolate_(e,t,i,s){const r=this.resultBuffer,o=this.sampleValues,a=this.valueSize,l=a*2,c=a*3,h=s-t,d=(i-t)/h,f=d*d,u=f*d,g=e*c,p=g-c,m=-2*u+3*f,A=u-f,x=1-m,b=A-f+d;for(let y=0;y!==a;y++){const _=o[p+y+a],S=o[p+y+l]*h,C=o[g+y+a],D=o[g+y]*h;r[y]=x*_+b*S+m*C+A*D}return r}}const TT=new v.Quaternion;class DT extends T0{interpolate_(e,t,i,s){const r=super.interpolate_(e,t,i,s);return TT.fromArray(r).normalize().toArray(r),r}}const Gi={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},go={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},D0={9728:v.NearestFilter,9729:v.LinearFilter,9984:v.NearestMipmapNearestFilter,9985:v.LinearMipmapNearestFilter,9986:v.NearestMipmapLinearFilter,9987:v.LinearMipmapLinearFilter},B0={33071:v.ClampToEdgeWrapping,33648:v.MirroredRepeatWrapping,10497:v.RepeatWrapping},Hu={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},Xu={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},Ss={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},BT={CUBICSPLINE:void 0,LINEAR:v.InterpolateLinear,STEP:v.InterpolateDiscrete},qu={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function PT(n){return n.DefaultMaterial===void 0&&(n.DefaultMaterial=new v.MeshStandardMaterial({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:v.FrontSide})),n.DefaultMaterial}function dr(n,e,t){for(const i in t.extensions)n[i]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[i]=t.extensions[i])}function vn(n,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(n.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function LT(n,e,t){let i=!1,s=!1,r=!1;for(let c=0,h=e.length;c<h;c++){const d=e[c];if(d.POSITION!==void 0&&(i=!0),d.NORMAL!==void 0&&(s=!0),d.COLOR_0!==void 0&&(r=!0),i&&s&&r)break}if(!i&&!s&&!r)return Promise.resolve(n);const o=[],a=[],l=[];for(let c=0,h=e.length;c<h;c++){const d=e[c];if(i){const f=d.POSITION!==void 0?t.getDependency("accessor",d.POSITION):n.attributes.position;o.push(f)}if(s){const f=d.NORMAL!==void 0?t.getDependency("accessor",d.NORMAL):n.attributes.normal;a.push(f)}if(r){const f=d.COLOR_0!==void 0?t.getDependency("accessor",d.COLOR_0):n.attributes.color;l.push(f)}}return Promise.all([Promise.all(o),Promise.all(a),Promise.all(l)]).then(function(c){const h=c[0],d=c[1],f=c[2];return i&&(n.morphAttributes.position=h),s&&(n.morphAttributes.normal=d),r&&(n.morphAttributes.color=f),n.morphTargetsRelative=!0,n})}function RT(n,e){if(n.updateMorphTargets(),e.weights!==void 0)for(let t=0,i=e.weights.length;t<i;t++)n.morphTargetInfluences[t]=e.weights[t];if(e.extras&&Array.isArray(e.extras.targetNames)){const t=e.extras.targetNames;if(n.morphTargetInfluences.length===t.length){n.morphTargetDictionary={};for(let i=0,s=t.length;i<s;i++)n.morphTargetDictionary[t[i]]=i}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function kT(n){let e;const t=n.extensions&&n.extensions[et.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+Yu(t.attributes):e=n.indices+":"+Yu(n.attributes)+":"+n.mode,n.targets!==void 0)for(let i=0,s=n.targets.length;i<s;i++)e+=":"+Yu(n.targets[i]);return e}function Yu(n){let e="";const t=Object.keys(n).sort();for(let i=0,s=t.length;i<s;i++)e+=t[i]+":"+n[t[i]]+";";return e}function Ku(n){switch(n){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function FT(n){return n.search(/\.jpe?g($|\?)/i)>0||n.search(/^data\:image\/jpeg/)===0?"image/jpeg":n.search(/\.webp($|\?)/i)>0||n.search(/^data\:image\/webp/)===0?"image/webp":n.search(/\.ktx2($|\?)/i)>0||n.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const OT=new v.Matrix4;class UT{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new aT,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let i=!1,s=-1,r=!1,o=-1;if(typeof navigator<"u"&&typeof navigator.userAgent<"u"){const a=navigator.userAgent;i=/^((?!chrome|android).)*safari/i.test(a)===!0;const l=a.match(/Version\/(\d+)/);s=i&&l?parseInt(l[1],10):-1,r=a.indexOf("Firefox")>-1,o=r?a.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||i&&s<17||r&&o<98?this.textureLoader=new v.TextureLoader(this.options.manager):this.textureLoader=new v.ImageBitmapLoader(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new v.FileLoader(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const i=this,s=this.json,r=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(o){return o._markDefs&&o._markDefs()}),Promise.all(this._invokeAll(function(o){return o.beforeRoot&&o.beforeRoot()})).then(function(){return Promise.all([i.getDependencies("scene"),i.getDependencies("animation"),i.getDependencies("camera")])}).then(function(o){const a={scene:o[0][s.scene||0],scenes:o[0],animations:o[1],cameras:o[2],asset:s.asset,parser:i,userData:{}};return dr(r,a,s),vn(a,s),Promise.all(i._invokeAll(function(l){return l.afterRoot&&l.afterRoot(a)})).then(function(){for(const l of a.scenes)l.updateMatrixWorld();e(a)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],i=this.json.meshes||[];for(let s=0,r=t.length;s<r;s++){const o=t[s].joints;for(let a=0,l=o.length;a<l;a++)e[o[a]].isBone=!0}for(let s=0,r=e.length;s<r;s++){const o=e[s];o.mesh!==void 0&&(this._addNodeRef(this.meshCache,o.mesh),o.skin!==void 0&&(i[o.mesh].isSkinnedMesh=!0)),o.camera!==void 0&&this._addNodeRef(this.cameraCache,o.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,i){if(e.refs[t]<=1)return i;const s=i.clone(),r=(o,a)=>{const l=this.associations.get(o);l!=null&&this.associations.set(a,l);for(const[c,h]of o.children.entries())r(h,a.children[c])};return r(i,s),s.name+="_instance_"+e.uses[t]++,s}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let i=0;i<t.length;i++){const s=e(t[i]);if(s)return s}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const i=[];for(let s=0;s<t.length;s++){const r=e(t[s]);r&&i.push(r)}return i}getDependency(e,t){const i=e+":"+t;let s=this.cache.get(i);if(!s){switch(e){case"scene":s=this.loadScene(t);break;case"node":s=this._invokeOne(function(r){return r.loadNode&&r.loadNode(t)});break;case"mesh":s=this._invokeOne(function(r){return r.loadMesh&&r.loadMesh(t)});break;case"accessor":s=this.loadAccessor(t);break;case"bufferView":s=this._invokeOne(function(r){return r.loadBufferView&&r.loadBufferView(t)});break;case"buffer":s=this.loadBuffer(t);break;case"material":s=this._invokeOne(function(r){return r.loadMaterial&&r.loadMaterial(t)});break;case"texture":s=this._invokeOne(function(r){return r.loadTexture&&r.loadTexture(t)});break;case"skin":s=this.loadSkin(t);break;case"animation":s=this._invokeOne(function(r){return r.loadAnimation&&r.loadAnimation(t)});break;case"camera":s=this.loadCamera(t);break;default:if(s=this._invokeOne(function(r){return r!=this&&r.getDependency&&r.getDependency(e,t)}),!s)throw new Error("Unknown type: "+e);break}this.cache.add(i,s)}return s}getDependencies(e){let t=this.cache.get(e);if(!t){const i=this,s=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(s.map(function(r,o){return i.getDependency(e,o)})),this.cache.add(e,t)}return t}loadBuffer(e){const t=this.json.buffers[e],i=this.fileLoader;if(t.type&&t.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[et.KHR_BINARY_GLTF].body);const s=this.options;return new Promise(function(r,o){i.load(v.LoaderUtils.resolveURL(t.uri,s.path),r,void 0,function(){o(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(e){const t=this.json.bufferViews[e];return this.getDependency("buffer",t.buffer).then(function(i){const s=t.byteLength||0,r=t.byteOffset||0;return i.slice(r,r+s)})}loadAccessor(e){const t=this,i=this.json,s=this.json.accessors[e];if(s.bufferView===void 0&&s.sparse===void 0){const o=Hu[s.type],a=go[s.componentType],l=s.normalized===!0,c=new a(s.count*o);return Promise.resolve(new v.BufferAttribute(c,o,l))}const r=[];return s.bufferView!==void 0?r.push(this.getDependency("bufferView",s.bufferView)):r.push(null),s.sparse!==void 0&&(r.push(this.getDependency("bufferView",s.sparse.indices.bufferView)),r.push(this.getDependency("bufferView",s.sparse.values.bufferView))),Promise.all(r).then(function(o){const a=o[0],l=Hu[s.type],c=go[s.componentType],h=c.BYTES_PER_ELEMENT,d=h*l,f=s.byteOffset||0,u=s.bufferView!==void 0?i.bufferViews[s.bufferView].byteStride:void 0,g=s.normalized===!0;let p,m;if(u&&u!==d){const A=Math.floor(f/u),x="InterleavedBuffer:"+s.bufferView+":"+s.componentType+":"+A+":"+s.count;let b=t.cache.get(x);b||(p=new c(a,A*u,s.count*u/h),b=new v.InterleavedBuffer(p,u/h),t.cache.add(x,b)),m=new v.InterleavedBufferAttribute(b,l,f%u/h,g)}else a===null?p=new c(s.count*l):p=new c(a,f,s.count*l),m=new v.BufferAttribute(p,l,g);if(s.sparse!==void 0){const A=Hu.SCALAR,x=go[s.sparse.indices.componentType],b=s.sparse.indices.byteOffset||0,y=s.sparse.values.byteOffset||0,_=new x(o[1],b,s.sparse.count*A),S=new c(o[2],y,s.sparse.count*l);a!==null&&(m=new v.BufferAttribute(m.array.slice(),m.itemSize,m.normalized)),m.normalized=!1;for(let C=0,D=_.length;C<D;C++){const M=_[C];if(m.setX(M,S[C*l]),l>=2&&m.setY(M,S[C*l+1]),l>=3&&m.setZ(M,S[C*l+2]),l>=4&&m.setW(M,S[C*l+3]),l>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}m.normalized=g}return m})}loadTexture(e){const t=this.json,i=this.options,r=t.textures[e].source,o=t.images[r];let a=this.textureLoader;if(o.uri){const l=i.manager.getHandler(o.uri);l!==null&&(a=l)}return this.loadTextureImage(e,r,a)}loadTextureImage(e,t,i){const s=this,r=this.json,o=r.textures[e],a=r.images[t],l=(a.uri||a.bufferView)+":"+o.sampler;if(this.textureCache[l])return this.textureCache[l];const c=this.loadImageSource(t,i).then(function(h){h.flipY=!1,h.name=o.name||a.name||"",h.name===""&&typeof a.uri=="string"&&a.uri.startsWith("data:image/")===!1&&(h.name=a.uri);const f=(r.samplers||{})[o.sampler]||{};return h.magFilter=D0[f.magFilter]||v.LinearFilter,h.minFilter=D0[f.minFilter]||v.LinearMipmapLinearFilter,h.wrapS=B0[f.wrapS]||v.RepeatWrapping,h.wrapT=B0[f.wrapT]||v.RepeatWrapping,h.generateMipmaps=!h.isCompressedTexture&&h.minFilter!==v.NearestFilter&&h.minFilter!==v.LinearFilter,s.associations.set(h,{textures:e}),h}).catch(function(){return null});return this.textureCache[l]=c,c}loadImageSource(e,t){const i=this,s=this.json,r=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(d=>d.clone());const o=s.images[e],a=self.URL||self.webkitURL;let l=o.uri||"",c=!1;if(o.bufferView!==void 0)l=i.getDependency("bufferView",o.bufferView).then(function(d){c=!0;const f=new Blob([d],{type:o.mimeType});return l=a.createObjectURL(f),l});else if(o.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const h=Promise.resolve(l).then(function(d){return new Promise(function(f,u){let g=f;t.isImageBitmapLoader===!0&&(g=function(p){const m=new v.Texture(p);m.needsUpdate=!0,f(m)}),t.load(v.LoaderUtils.resolveURL(d,r.path),g,void 0,u)})}).then(function(d){return c===!0&&a.revokeObjectURL(l),vn(d,o),d.userData.mimeType=o.mimeType||FT(o.uri),d}).catch(function(d){throw console.error("THREE.GLTFLoader: Couldn't load texture",l),d});return this.sourceCache[e]=h,h}assignTexture(e,t,i,s){const r=this;return this.getDependency("texture",i.index).then(function(o){if(!o)return null;if(i.texCoord!==void 0&&i.texCoord>0&&(o=o.clone(),o.channel=i.texCoord),r.extensions[et.KHR_TEXTURE_TRANSFORM]){const a=i.extensions!==void 0?i.extensions[et.KHR_TEXTURE_TRANSFORM]:void 0;if(a){const l=r.associations.get(o);o=r.extensions[et.KHR_TEXTURE_TRANSFORM].extendTexture(o,a),r.associations.set(o,l)}}return s!==void 0&&(o.colorSpace=s),e[t]=o,o})}assignFinalMaterial(e){const t=e.geometry;let i=e.material;const s=t.attributes.tangent===void 0,r=t.attributes.color!==void 0,o=t.attributes.normal===void 0;if(e.isPoints){const a="PointsMaterial:"+i.uuid;let l=this.cache.get(a);l||(l=new v.PointsMaterial,v.Material.prototype.copy.call(l,i),l.color.copy(i.color),l.map=i.map,l.sizeAttenuation=!1,this.cache.add(a,l)),i=l}else if(e.isLine){const a="LineBasicMaterial:"+i.uuid;let l=this.cache.get(a);l||(l=new v.LineBasicMaterial,v.Material.prototype.copy.call(l,i),l.color.copy(i.color),l.map=i.map,this.cache.add(a,l)),i=l}if(s||r||o){let a="ClonedMaterial:"+i.uuid+":";s&&(a+="derivative-tangents:"),r&&(a+="vertex-colors:"),o&&(a+="flat-shading:");let l=this.cache.get(a);l||(l=i.clone(),r&&(l.vertexColors=!0),o&&(l.flatShading=!0),s&&(l.normalScale&&(l.normalScale.y*=-1),l.clearcoatNormalScale&&(l.clearcoatNormalScale.y*=-1)),this.cache.add(a,l),this.associations.set(l,this.associations.get(i))),i=l}e.material=i}getMaterialType(){return v.MeshStandardMaterial}loadMaterial(e){const t=this,i=this.json,s=this.extensions,r=i.materials[e];let o;const a={},l=r.extensions||{},c=[];if(l[et.KHR_MATERIALS_UNLIT]){const d=s[et.KHR_MATERIALS_UNLIT];o=d.getMaterialType(),c.push(d.extendParams(a,r,t))}else{const d=r.pbrMetallicRoughness||{};if(a.color=new v.Color(1,1,1),a.opacity=1,Array.isArray(d.baseColorFactor)){const f=d.baseColorFactor;a.color.setRGB(f[0],f[1],f[2],v.LinearSRGBColorSpace),a.opacity=f[3]}d.baseColorTexture!==void 0&&c.push(t.assignTexture(a,"map",d.baseColorTexture,v.SRGBColorSpace)),a.metalness=d.metallicFactor!==void 0?d.metallicFactor:1,a.roughness=d.roughnessFactor!==void 0?d.roughnessFactor:1,d.metallicRoughnessTexture!==void 0&&(c.push(t.assignTexture(a,"metalnessMap",d.metallicRoughnessTexture)),c.push(t.assignTexture(a,"roughnessMap",d.metallicRoughnessTexture))),o=this._invokeOne(function(f){return f.getMaterialType&&f.getMaterialType(e)}),c.push(Promise.all(this._invokeAll(function(f){return f.extendMaterialParams&&f.extendMaterialParams(e,a)})))}r.doubleSided===!0&&(a.side=v.DoubleSide);const h=r.alphaMode||qu.OPAQUE;if(h===qu.BLEND?(a.transparent=!0,a.depthWrite=!1):(a.transparent=!1,h===qu.MASK&&(a.alphaTest=r.alphaCutoff!==void 0?r.alphaCutoff:.5)),r.normalTexture!==void 0&&o!==v.MeshBasicMaterial&&(c.push(t.assignTexture(a,"normalMap",r.normalTexture)),a.normalScale=new v.Vector2(1,1),r.normalTexture.scale!==void 0)){const d=r.normalTexture.scale;a.normalScale.set(d,d)}if(r.occlusionTexture!==void 0&&o!==v.MeshBasicMaterial&&(c.push(t.assignTexture(a,"aoMap",r.occlusionTexture)),r.occlusionTexture.strength!==void 0&&(a.aoMapIntensity=r.occlusionTexture.strength)),r.emissiveFactor!==void 0&&o!==v.MeshBasicMaterial){const d=r.emissiveFactor;a.emissive=new v.Color().setRGB(d[0],d[1],d[2],v.LinearSRGBColorSpace)}return r.emissiveTexture!==void 0&&o!==v.MeshBasicMaterial&&c.push(t.assignTexture(a,"emissiveMap",r.emissiveTexture,v.SRGBColorSpace)),Promise.all(c).then(function(){const d=new o(a);return r.name&&(d.name=r.name),vn(d,r),t.associations.set(d,{materials:e}),r.extensions&&dr(s,d,r),d})}createUniqueName(e){const t=v.PropertyBinding.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,i=this.extensions,s=this.primitiveCache;function r(a){return i[et.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(a,t).then(function(l){return P0(l,a,t)})}const o=[];for(let a=0,l=e.length;a<l;a++){const c=e[a],h=kT(c),d=s[h];if(d)o.push(d.promise);else{let f;c.extensions&&c.extensions[et.KHR_DRACO_MESH_COMPRESSION]?f=r(c):f=P0(new v.BufferGeometry,c,t),s[h]={primitive:c,promise:f},o.push(f)}}return Promise.all(o)}loadMesh(e){const t=this,i=this.json,s=this.extensions,r=i.meshes[e],o=r.primitives,a=[];for(let l=0,c=o.length;l<c;l++){const h=o[l].material===void 0?PT(this.cache):this.getDependency("material",o[l].material);a.push(h)}return a.push(t.loadGeometries(o)),Promise.all(a).then(function(l){const c=l.slice(0,l.length-1),h=l[l.length-1],d=[];for(let u=0,g=h.length;u<g;u++){const p=h[u],m=o[u];let A;const x=c[u];if(m.mode===Gi.TRIANGLES||m.mode===Gi.TRIANGLE_STRIP||m.mode===Gi.TRIANGLE_FAN||m.mode===void 0)A=r.isSkinnedMesh===!0?new v.SkinnedMesh(p,x):new v.Mesh(p,x),A.isSkinnedMesh===!0&&A.normalizeSkinWeights(),m.mode===Gi.TRIANGLE_STRIP?A.geometry=S0(A.geometry,v.TriangleStripDrawMode):m.mode===Gi.TRIANGLE_FAN&&(A.geometry=S0(A.geometry,v.TriangleFanDrawMode));else if(m.mode===Gi.LINES)A=new v.LineSegments(p,x);else if(m.mode===Gi.LINE_STRIP)A=new v.Line(p,x);else if(m.mode===Gi.LINE_LOOP)A=new v.LineLoop(p,x);else if(m.mode===Gi.POINTS)A=new v.Points(p,x);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+m.mode);Object.keys(A.geometry.morphAttributes).length>0&&RT(A,r),A.name=t.createUniqueName(r.name||"mesh_"+e),vn(A,r),m.extensions&&dr(s,A,m),t.assignFinalMaterial(A),d.push(A)}for(let u=0,g=d.length;u<g;u++)t.associations.set(d[u],{meshes:e,primitives:u});if(d.length===1)return r.extensions&&dr(s,d[0],r),d[0];const f=new v.Group;r.extensions&&dr(s,f,r),t.associations.set(f,{meshes:e});for(let u=0,g=d.length;u<g;u++)f.add(d[u]);return f})}loadCamera(e){let t;const i=this.json.cameras[e],s=i[i.type];if(!s){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return i.type==="perspective"?t=new v.PerspectiveCamera(v.MathUtils.radToDeg(s.yfov),s.aspectRatio||1,s.znear||1,s.zfar||2e6):i.type==="orthographic"&&(t=new v.OrthographicCamera(-s.xmag,s.xmag,s.ymag,-s.ymag,s.znear,s.zfar)),i.name&&(t.name=this.createUniqueName(i.name)),vn(t,i),Promise.resolve(t)}loadSkin(e){const t=this.json.skins[e],i=[];for(let s=0,r=t.joints.length;s<r;s++)i.push(this._loadNodeShallow(t.joints[s]));return t.inverseBindMatrices!==void 0?i.push(this.getDependency("accessor",t.inverseBindMatrices)):i.push(null),Promise.all(i).then(function(s){const r=s.pop(),o=s,a=[],l=[];for(let c=0,h=o.length;c<h;c++){const d=o[c];if(d){a.push(d);const f=new v.Matrix4;r!==null&&f.fromArray(r.array,c*16),l.push(f)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[c])}return new v.Skeleton(a,l)})}loadAnimation(e){const t=this.json,i=this,s=t.animations[e],r=s.name?s.name:"animation_"+e,o=[],a=[],l=[],c=[],h=[];for(let d=0,f=s.channels.length;d<f;d++){const u=s.channels[d],g=s.samplers[u.sampler],p=u.target,m=p.node,A=s.parameters!==void 0?s.parameters[g.input]:g.input,x=s.parameters!==void 0?s.parameters[g.output]:g.output;p.node!==void 0&&(o.push(this.getDependency("node",m)),a.push(this.getDependency("accessor",A)),l.push(this.getDependency("accessor",x)),c.push(g),h.push(p))}return Promise.all([Promise.all(o),Promise.all(a),Promise.all(l),Promise.all(c),Promise.all(h)]).then(function(d){const f=d[0],u=d[1],g=d[2],p=d[3],m=d[4],A=[];for(let b=0,y=f.length;b<y;b++){const _=f[b],S=u[b],C=g[b],D=p[b],M=m[b];if(_===void 0)continue;_.updateMatrix&&_.updateMatrix();const I=i._createAnimationTracks(_,S,C,D,M);if(I)for(let L=0;L<I.length;L++)A.push(I[L])}const x=new v.AnimationClip(r,void 0,A);return vn(x,s),x})}createNodeMesh(e){const t=this.json,i=this,s=t.nodes[e];return s.mesh===void 0?null:i.getDependency("mesh",s.mesh).then(function(r){const o=i._getNodeRef(i.meshCache,s.mesh,r);return s.weights!==void 0&&o.traverse(function(a){if(a.isMesh)for(let l=0,c=s.weights.length;l<c;l++)a.morphTargetInfluences[l]=s.weights[l]}),o})}loadNode(e){const t=this.json,i=this,s=t.nodes[e],r=i._loadNodeShallow(e),o=[],a=s.children||[];for(let c=0,h=a.length;c<h;c++)o.push(i.getDependency("node",a[c]));const l=s.skin===void 0?Promise.resolve(null):i.getDependency("skin",s.skin);return Promise.all([r,Promise.all(o),l]).then(function(c){const h=c[0],d=c[1],f=c[2];f!==null&&h.traverse(function(u){u.isSkinnedMesh&&u.bind(f,OT)});for(let u=0,g=d.length;u<g;u++)h.add(d[u]);if(h.userData.pivot!==void 0&&d.length>0){const u=h.userData.pivot,g=d[0];h.pivot=new v.Vector3().fromArray(u),h.position.x-=u[0],h.position.y-=u[1],h.position.z-=u[2],g.position.set(0,0,0),delete h.userData.pivot}return h})}_loadNodeShallow(e){const t=this.json,i=this.extensions,s=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];const r=t.nodes[e],o=r.name?s.createUniqueName(r.name):"",a=[],l=s._invokeOne(function(c){return c.createNodeMesh&&c.createNodeMesh(e)});return l&&a.push(l),r.camera!==void 0&&a.push(s.getDependency("camera",r.camera).then(function(c){return s._getNodeRef(s.cameraCache,r.camera,c)})),s._invokeAll(function(c){return c.createNodeAttachment&&c.createNodeAttachment(e)}).forEach(function(c){a.push(c)}),this.nodeCache[e]=Promise.all(a).then(function(c){let h;if(r.isBone===!0?h=new v.Bone:c.length>1?h=new v.Group:c.length===1?h=c[0]:h=new v.Object3D,h!==c[0])for(let d=0,f=c.length;d<f;d++)h.add(c[d]);if(r.name&&(h.userData.name=r.name,h.name=o),vn(h,r),r.extensions&&dr(i,h,r),r.matrix!==void 0){const d=new v.Matrix4;d.fromArray(r.matrix),h.applyMatrix4(d)}else r.translation!==void 0&&h.position.fromArray(r.translation),r.rotation!==void 0&&h.quaternion.fromArray(r.rotation),r.scale!==void 0&&h.scale.fromArray(r.scale);if(!s.associations.has(h))s.associations.set(h,{});else if(r.mesh!==void 0&&s.meshCache.refs[r.mesh]>1){const d=s.associations.get(h);s.associations.set(h,{...d})}return s.associations.get(h).nodes=e,h}),this.nodeCache[e]}loadScene(e){const t=this.extensions,i=this.json.scenes[e],s=this,r=new v.Group;i.name&&(r.name=s.createUniqueName(i.name)),vn(r,i),i.extensions&&dr(t,r,i);const o=i.nodes||[],a=[];for(let l=0,c=o.length;l<c;l++)a.push(s.getDependency("node",o[l]));return Promise.all(a).then(function(l){for(let h=0,d=l.length;h<d;h++){const f=l[h];f.parent!==null?r.add(rT(f)):r.add(f)}const c=h=>{const d=new Map;for(const[f,u]of s.associations)(f instanceof v.Material||f instanceof v.Texture)&&d.set(f,u);return h.traverse(f=>{const u=s.associations.get(f);u!=null&&d.set(f,u)}),d};return s.associations=c(r),r})}_createAnimationTracks(e,t,i,s,r){const o=[],a=e.name?e.name:e.uuid,l=[];Ss[r.path]===Ss.weights?e.traverse(function(f){f.morphTargetInfluences&&l.push(f.name?f.name:f.uuid)}):l.push(a);let c;switch(Ss[r.path]){case Ss.weights:c=v.NumberKeyframeTrack;break;case Ss.rotation:c=v.QuaternionKeyframeTrack;break;case Ss.translation:case Ss.scale:c=v.VectorKeyframeTrack;break;default:switch(i.itemSize){case 1:c=v.NumberKeyframeTrack;break;case 2:case 3:default:c=v.VectorKeyframeTrack;break}break}const h=s.interpolation!==void 0?BT[s.interpolation]:v.InterpolateLinear,d=this._getArrayFromAccessor(i);for(let f=0,u=l.length;f<u;f++){const g=new c(l[f]+"."+Ss[r.path],t.array,d,h);s.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(g),o.push(g)}return o}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const i=Ku(t.constructor),s=new Float32Array(t.length);for(let r=0,o=t.length;r<o;r++)s[r]=t[r]*i;t=s}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(i){const s=this instanceof v.QuaternionKeyframeTrack?DT:T0;return new s(this.times,this.values,this.getValueSize()/3,i)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function NT(n,e,t){const i=e.attributes,s=new v.Box3;if(i.POSITION!==void 0){const a=t.json.accessors[i.POSITION],l=a.min,c=a.max;if(l!==void 0&&c!==void 0){if(s.set(new v.Vector3(l[0],l[1],l[2]),new v.Vector3(c[0],c[1],c[2])),a.normalized){const h=Ku(go[a.componentType]);s.min.multiplyScalar(h),s.max.multiplyScalar(h)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const r=e.targets;if(r!==void 0){const a=new v.Vector3,l=new v.Vector3;for(let c=0,h=r.length;c<h;c++){const d=r[c];if(d.POSITION!==void 0){const f=t.json.accessors[d.POSITION],u=f.min,g=f.max;if(u!==void 0&&g!==void 0){if(l.setX(Math.max(Math.abs(u[0]),Math.abs(g[0]))),l.setY(Math.max(Math.abs(u[1]),Math.abs(g[1]))),l.setZ(Math.max(Math.abs(u[2]),Math.abs(g[2]))),f.normalized){const p=Ku(go[f.componentType]);l.multiplyScalar(p)}a.max(l)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}s.expandByVector(a)}n.boundingBox=s;const o=new v.Sphere;s.getCenter(o.center),o.radius=s.min.distanceTo(s.max)/2,n.boundingSphere=o}function P0(n,e,t){const i=e.attributes,s=[];function r(o,a){return t.getDependency("accessor",o).then(function(l){n.setAttribute(a,l)})}for(const o in i){const a=Xu[o]||o.toLowerCase();a in n.attributes||s.push(r(i[o],a))}if(e.indices!==void 0&&!n.index){const o=t.getDependency("accessor",e.indices).then(function(a){n.setIndex(a)});s.push(o)}return v.ColorManagement.workingColorSpace!==v.LinearSRGBColorSpace&&"COLOR_0"in i&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${v.ColorManagement.workingColorSpace}" not supported.`),vn(n,e),NT(n,e,t),Promise.all(s).then(function(){return e.targets!==void 0?LT(n,e.targets,t):n})}var Et=(n=>(n.ModelLoadStart="model-load-start",n.ModelLoadProgress="model-load-progress",n.ModelLoaded="model-loaded",n.ModelError="model-error",n.SelectionChanged="selection-changed",n.HoverChanged="hover-changed",n.Click="click",n.MouseMove="mouse-move",n.CameraChanged="camera-changed",n.CameraIdle="camera-idle",n.EngineFree="engine-free",n.EngineBusy="engine-busy",n.MeasureChanged="measure-changed",n.MeasureClick="measure-click",n.SectionMove="section-move",n.LoadingCompleted="loading_completed",n))(Et||{});let fa=null,pa=null,L0=null;const zT=8,R0=24,GT=24,VT=64,QT=200,jT=10;function k0(){return new URL("draco/",document.baseURI).toString()}function F0(){return new URL("basis/",document.baseURI).toString()}function WT(){return fa==null&&(fa=new VI,fa.setDecoderPath(k0()),fa.preload()),fa}function HT(n){return pa==null&&(pa=new zi,pa.setTranscoderPath(F0())),L0!==n&&(pa.detectSupport(n),L0=n),pa}function XT(n){const e=new oT;return e.setDRACOLoader(WT()),e.setMeshoptDecoder(jI),n?.renderer?.capabilities!=null&&typeof n.renderer.getContext=="function"&&e.setKTX2Loader(HT(n.renderer)),e}function O0(){return new Promise(n=>{if(typeof requestAnimationFrame=="function"){requestAnimationFrame(()=>n());return}setTimeout(n,16)})}function qT(){const n=navigator?.scheduling;return typeof n?.isInputPending=="function"?n.isInputPending():!1}function YT(n){return n?.engineStatus?.isFree===!1||qT()}async function Kn(n,e,t){if(e)return t;const i=performance.now();return YT(n)||i-t>=zT?(await O0(),performance.now()):t}function KT(n,e){return new Promise((t,i)=>{ha(n,s=>{if(s==null){i(new Error(`[loadLightModel] empty zip json: ${n}`));return}t(s)},()=>{i(new Error(`[loadLightModel] failed to load zip json: ${n}`))},e)})}function $T(n,e){return Mt({method:"get",responseType:"arraybuffer",url:n}).then(async t=>{let i=t.data;return fo.isEncrypted(t.data)&&(i=await fo.decryptPzEnc(t.data,e)),Wm.loadAsync(i)})}function U0(n){return n.replace(/\\/g,"/").replace(/^\/+/,"")}function N0(n,e){const t=new Set(e.map(i=>U0(i)));for(const i of Object.keys(n.files))if(t.has(U0(i)))return n.files[i];return null}function z0(n,e){const t=N0(n,e);return t==null||t.dir?Promise.resolve(null):t.async("string")}function JT(n){return n.charCodeAt(0)===65279?n.slice(1):n}function $u(n){return JSON.parse(JT(n))}function ZT(n,e){const t=N0(n,e);return t==null||t.dir?Promise.resolve(null):t.async("arraybuffer")}function e2(n,e){return new Promise((t,i)=>{XT(n).parse(e,document.baseURI,t,i)})}function vc(n,e){return n.models.find(t=>t.url==e)}function G0(n){n.loadStatus==null&&(n.loadStatus={}),n.loadStatus.modelMep==null&&(n.loadStatus.modelMep=!1),n.loadStatus.normal==null&&(n.loadStatus.normal=!1)}function t2(n){return G0(n),n.status==="loaded"&&n.loadStatus.normal===!0&&n.loadStatus.modelMep===!0}function V0(n){const e=n?.engineStatus?.models;!Array.isArray(e)||e.length===0||!e.every(i=>t2(i))||n.__loadingCompletedTriggered===!0||(n.__loadingCompletedTriggered=!0,n.events?.trigger?.(Et.LoadingCompleted,{}))}function Q0(n){return n===!0||n==="loading"}function j0(n){return n.index!=null?n.index.count:n.attributes.position?.count??0}async function i2(n,e,t){let i=performance.now();for(let s=0;s<e.length;s++){const r=e[s];r?.geometry!=null&&r.geometry.computeVertexNormals,(s+1)%GT===0&&(i=await Kn(n,t,i))}}async function n2(n,e,t){const i=[],s=[{node:e.octreeBox,visited:!1}];let r=performance.now();for(;s.length>0;){const o=s.pop();if(o==null||o.node==null||o.node.status===!0)continue;const a=o.node;if(o.visited){const c=Array.isArray(a.children)?a.children:[];(c.length===0||c.findIndex(h=>h.status!=!0)===-1)&&(a.status=!0),r=await Kn(n,t,r);continue}s.push({node:a,visited:!0}),Array.isArray(a.elements)&&i.push(...a.elements);const l=Array.isArray(a.children)?a.children:[];for(let c=l.length-1;c>=0;c--)s.push({node:l[c],visited:!1});r=await Kn(n,t,r)}return i}async function s2(n,e,t,i){const s=vc(n,e.url);if(s?.nodesMap==null)return[];const r=await n2(n,t,i);console.log("[loadLightModel] pending mesh ids",t.path,r.length);const o=[];let a=performance.now(),l=0;for(const c of r){if(!s.nodesMap.has(c))continue;const h=s.nodesMap.get(c),d=Array.isArray(h?.infos)?h.infos:[];for(const f of d){const u=t.glbs?.[f.glb]?.[f.mesh];if(u?.geometry==null||u.material==null)continue;const g=new w.Matrix4;g.elements=f.matrix;const p=u.geometry.clone();p.applyMatrix4(g),p.computeBoundingBox();const m=new w.Mesh(p,u.material);f.box=p.boundingBox?.clone(),f.mesh=m,m.name=Number(c),m.glb=f.glb,m.url=e.url,p.attributes.position!=null&&o.push(m),l++,l%R0===0&&(a=await Kn(n,i,a))}}return o}function r2(n,e,t,i,s){const r=Yn(i.map(a=>a.geometry),!1),o=new w.Mesh(r,s);return o.castShadow=!0,o.receiveShadow=!0,e.scene.add(o),o.index=e.scene.children.length-1,o.url=n,o.glb=t,o.materialClone=s,o.geometrys=i.map(a=>a.geometry),o.geometry.computeVertexNormals(),o}function o2(n,e,t,i){return n.scene.children.find(s=>{const r=s;return s instanceof w.Mesh&&r.url==e&&r.glb==t&&r.materialClone===i})}function a2(n,e){const t=Array.isArray(n.geometrys)?n.geometrys:[],i=e.map(o=>o.geometry),s=[...t,...i],r=Yn(s,!1);n.geometry!=null&&n.geometry.dispose(),n.geometry=r,n.geometrys=s,n.castShadow=!0,n.receiveShadow=!0}async function l2(n,e,t,i){const s=new Map;for(const a of t){const l=s.get(a.glb)??[];l.push(a),s.set(a.glb,l)}const r=vc(e,n);let o=performance.now();for(const[a,l]of s.entries()){const c=i?l.length:QT;for(let h=0;h<l.length;h+=c){const d=l.slice(h,h+c);if(d.length===0)continue;const f=x2(d[0].material,e);let u=o2(e,n,a,f),g=0,p=0;u=null,u!=null?(g=Array.isArray(u.geometrys)?u.geometrys.length:0,p=j0(u.geometry),a2(u,d)):u=r2(n,e,a,d,f);const m=new Map;let A=p;d.forEach((x,b)=>{const y=Number(x.name),_=j0(x.geometry),S=m.get(y)??[];if(S.push([A,A+_]),m.set(y,S),r?.nodesMap?.has(y)){const C=r.nodesMap.get(y);C.indexes==null&&(C.indexes=[]),C.indexes.push([u.index,g+b,A,A+_])}A+=_}),u.indexes==null&&(u.indexes=new Map),m.forEach((x,b)=>{const y=u.indexes.get(b)??[];y.push(...x),u.indexes.set(b,y)}),o=await Kn(e,i,o)}}}async function c2(n,e,t,i,s,r){if(i==null||s==null||s.length===0)return;const o=vc(t,n);if(o==null)return;const a=new w.InstancedMesh(i.geometry,i.material,s.length);t.scene.add(a);const l=new Float32Array(s.length*3);for(let d=0;d<s.length;d++)l[d*3]=1,l[d*3+1]=1,l[d*3+2]=1;a.instanceColor=new w.InstancedBufferAttribute(l,3);let c=performance.now();const h=[];for(let d=0;d<s.length;d++){const f=s[d],u=new w.Matrix4;if(u.elements=f.matrix,a.setMatrixAt(d,u),a.matrixs||(a.matrixs=[]),a.matrixs.push(u.clone()),h.push(u.clone()),o.nodesMap.has(f.id)){const g=o.nodesMap.get(f.id);g.indexes==null&&(g.indexes=[]),g.indexes.push([t.scene.children.length-1,d,0,0])}else o.nodesMap.set(f.id,{instance:!0,info:f,indexes:[[t.scene.children.length-1,d,0,0]]});(d+1)%VT===0&&(c=await Kn(t,r,c))}a.instanceMatrix.needsUpdate=!0,a.instanceColor!=null&&(a.instanceColor.needsUpdate=!0),a.index=t.scene.children.length-1,a.materialClone=i.material,a.url=n,a.glb=i.glb,a.ids=s.map(d=>d.id),a.matrixsClone=h,a.meshIndex=e}async function h2(n,e,t,i){const s=e.instanceNodes;if(s==null)return;let r=performance.now();for(const o in s)if(s[o].isLoaded!==!0){s[o].isLoaded=!0;for(const a of s[o]){const l=e.glbs?.[o]?.[a.mesh];l!=null&&await c2(n.url,a.mesh,t,l,a.children,i)}r=await Kn(t,i,r)}}async function d2(n,e,t,i){if(t.status===!0||t.meshPromise!=null){await t.meshPromise;return}t.meshPromise=(async()=>{console.log(`[loadLightModel] start build lod meshes ${Date.now()-window.startTime}ms`);const s=await s2(n,e,t,i);await l2(e.url,n,s,i),await h2(e,t,n,i),t.status=!0,console.log(`[loadLightModel] *****************************************************finish build lod meshes ${Date.now()-window.startTime}ms`)})().finally(()=>{t.meshPromise=null}),await t.meshPromise}async function u2(n,e,t,i){if(t.loadSuccess!==!0){if(t.preparePromise!=null){await t.preparePromise;return}t.preparePromise=(async()=>{console.log("[loadLightModel] loading GLB bundle",t.path),t.glbs=t.glbs??{};const s=await $T(e.url+t.path,e.key),r=await z0(s,["/nodes.json","nodes.json"]);if(r==null)return;const o=$u(r),a=vc(n,e.url);if(a==null)return;a.nodesMap==null&&(a.nodesMap=new Map);let l=performance.now();for(const h of Object.keys(o)){const d=o[h];for(let u=0;u<d.length;u++){const g=d[u];if(g.glb=h,a.nodesMap.has(g.id)===!1)a.nodesMap.set(g.id,{infos:[g]});else{if(!a.nodesMap.get(g.id).infos)continue;a.nodesMap.get(g.id).infos.push(g)}(u+1)%R0===0&&(l=await Kn(n,i,l))}const f=await ZT(s,[`/${h}.glb`,`${h}.glb`,h+".glb"]);if(f==null){console.error("[loadLightModel] glb not found in zip",{modelUrl:e.url,lodPath:t.path,glbKey:`${h}.glb`,availableFiles:Object.keys(s.files)});continue}try{const u=await e2(n,f);t.glbs[h]=u.scene.children,t.glbs[h].forEach(g=>{g.matrixWorld}),await i2(n,t.glbs[h],i)}catch(u){console.error("[loadLightModel] failed to load glb",{modelUrl:e.url,lodPath:t.path,glbKey:`${h}.glb`,dracoDecoderPath:k0(),basisTranscoderPath:F0(),error:u})}l=await Kn(n,i,l)}const c=await z0(s,["/instances.json","instances.json"]);t.instanceNodes=c!=null?$u(c):null,t.loadSuccess=!0})().finally(()=>{t.preparePromise=null}),await t.preparePromise}}function f2(n,e,t){if(t.boundingBox||(t.boundingBox=new w.Box3,t.boundingBox.min=new w.Vector3(t.octreeBox.min.X,t.octreeBox.min.Z,-t.octreeBox.min.Y),t.boundingBox.max=new w.Vector3(t.octreeBox.max.X,t.octreeBox.max.Z,-t.octreeBox.max.Y)),!t.maxSize)return 1e3;const i=t.boundingBox,s=i.min,r=i.max,o=s.clone().add(r.clone()).multiplyScalar(.5),a=s.distanceTo(r),l=new w.Vector3,c=new w.Vector3,h=new w.Vector3,d=new w.Vector3;if(e.getWorldDirection(h),e.getWorldPosition(d),e.matrixWorld.extractBasis(l,c,new w.Vector3),e instanceof w.OrthographicCamera){const A=Math.max((e.top-e.bottom)/e.zoom,1e-6),x=n?.cameraModule?.perspectiveCamera?.getEffectiveFOV?.()??20,b=w.MathUtils.degToRad(x*.5),y=b>0?A/(2*Math.tan(b)):A;d.copy(o).add(h.clone().multiplyScalar(-y))}if(d.distanceTo(o)<=a*.5)return 1e3;const f=o.clone().sub(d).dot(h);if(f<=0)return 0;const u=d.clone().add(h.multiplyScalar(Math.max(f,a))),g=u.clone().add(l.setLength(t.maxSize)),p=new lt(e,n.renderer,n.scene).worldToScreen(u),m=new lt(e,n.renderer,n.scene).worldToScreen(g);return p.distanceTo(m)}async function p2(n,e,t,i){t.maxSize<1e6&&t.path!="/lod0"&&(!(f2(n,n.camera,t)>=jT)||t.status===!0)||(await u2(n,e,t,i),t.loadSuccess===!0&&await d2(n,e,t,i))}function g2(n,e,t){if(Q0(e.loadStatus.modelMep))return;e.loadStatus.modelMep="loading",e.info.modelMep==null&&(e.info.modelMep={}),(async()=>{t||await O0(),sT(n,e.info.modelMep,e.url),e.loadStatus.modelMep=!0,V0(n)})().catch(s=>{e.loadStatus.modelMep=!1,console.error("[loadLightModel] failed to load mep model",s)})}function m2(n,e,t,i){const s=new w.Group;s.name=e,n.scene.add(s),n.models||(n.models=[]),window.startTime=Date.now();let r="WDDsBNtzVz6aSh/bCFh3CmjjANEDRryoXF1XCJvJjeE=";KT(e+"/info",r).then(o=>{const a=$u(o);n.__loadingCompletedTriggered=!1,n.engineStatus.models.push({type:"light",info:a,name:a.baseInfo.name,status:"loading",url:e,elements:new Map,loadStatus:{modelMep:!1,normal:!1},key:r}),n.models.push({url:e,nodesMap:new Map,grids:a.modelGrid,levels:a.modelLevel,rooms:a.modelRoom,views:a.modelView,name:a.baseInfo.name,boundingBox:{min:new w.Vector3(a.baseInfo.min.X*.3048,a.baseInfo.min.Z*.3048,-a.baseInfo.min.Y*.3048),max:new w.Vector3(a.baseInfo.max.X*.3048,a.baseInfo.max.Z*.3048,-a.baseInfo.max.Y*.3048)}}),n.models.length==i&&(n.viewCube.CameraGoHome(1),setTimeout(()=>{W0(n,null,!1)},100))}).catch(o=>{console.error("[loadLightModel] failed to load model info",{url:e,error:o})})}async function W0(n,e,t=!1){const i=n.engineStatus.models.filter(s=>e==null||s.url==e);for(const s of i)if(G0(s),!(s.status!=="loading"||s.type!=="light")&&(g2(n,s,t),!Q0(s.loadStatus.normal))){s.loadStatus.normal="loading";try{await A2(n,s,t)}finally{const r=Array.isArray(s.info?.lods)&&s.info.lods.every(o=>o.status===!0);s.loadStatus.normal=r,r&&(s.status="loaded"),V0(n)}}}async function A2(n,e,t=!1){if(console.log(`[loadLightModel] start loadNode ${Date.now()-window.startTime}ms`),!(e.info==null||e.info.lods==null))for(const i of e.info.lods)await p2(n,e,i,t)}function x2(n,e){return n.map!=null&&(n.map.colorSpace=w.SRGBColorSpace,n.map.needsUpdate=!0),n.clipShadows=!0,e?.sectionPlane&&(n.clippingPlanes=e.sectionPlane),n}class b2{engine;constructor(e){this.engine=e}async loadModels(e,t){console.log("待加载模型",e);for(const s of e)i(s)==="light"&&m2(this.engine,s,t,e.length);function i(s){const r=s.split(".").pop();return r==="glb"||r==="gltf"?"gltf":"light"}}}var Cs=(n=>(n.ModelLoadStart="model-load-start",n.ModelLoadProgress="model-load-progress",n.ModelLoaded="model-loaded",n.ModelError="model-error",n.SelectionChanged="selection-changed",n.HoverChanged="hover-changed",n.Click="click",n.MouseMove="mouse-move",n.CameraChanged="camera-changed",n.CameraIdle="camera-idle",n.ViewportResize="viewport-resize",n.EngineFree="engine-free",n.EngineBusy="engine-busy",n.MeasureChanged="measure-changed",n.SectionMove="section-move",n.LoadingCompleted="loading_completed",n))(Cs||{});class y2{engine;isFree;isForceFree;highlightModels;hideModels;translucentModels;models;constructor(e){this.engine=e,this.isFree=!0,this.isForceFree=!1,this.highlightModels=[],this.hideModels=[],this.translucentModels=[],this.models=[]}init(){this.engine.events.on(Cs.EngineFree,e=>{this.updateFree(!0),W0(this.engine,e,!1),this.engine?.octreeBox?.requestBvhBuild?.()}),this.engine.events.on(Cs.EngineBusy,()=>{this.updateFree(!1)})}updateFree(e){this.isFree=e}closeAllFunction=()=>{}}let v2=class{listeners=new Map;debugMode=!1;setDebugMode(e){this.debugMode=e}on(e,t){const i=String(e);this.listeners.has(i)||this.listeners.set(i,[]),this.listeners.get(i).push(t),this.debugMode&&console.debug(`[EventModule] 注册事件监听器: ${i}, 当前监听器数量: ${this.listeners.get(i).length}`)}off(e,t){const i=String(e);if(!this.listeners.has(i)){this.debugMode&&console.warn(`[EventModule] 尝试移除不存在的事件监听器: ${i}`);return}const s=this.listeners.get(i),r=s.indexOf(t);r!==-1?(s.splice(r,1),this.debugMode&&console.debug(`[EventModule] 移除事件监听器: ${i}, 剩余监听器数量: ${s.length}`)):this.debugMode&&console.warn(`[EventModule] 尝试移除的回调函数未找到: ${i}`)}trigger(e,t){const i=String(e);if(!this.listeners.has(i)){this.debugMode&&(console.warn(`[EventModule] 触发事件但未找到监听器: ${i}`),console.debug("[EventModule] 当前已注册的事件类型:",Array.from(this.listeners.keys())));return}const s=this.listeners.get(i);this.debugMode&&console.debug(`[EventModule] 触发事件: ${i}, 监听器数量: ${s.length}`,t),s.forEach((r,o)=>{try{r(t)}catch(a){console.error(`[EventModule] 事件监听器执行错误 [${i}] #${o}:`,a)}})}};const _c=1;class _2{engine;constructor(e){this.engine=e}init(){const e=new w.DirectionalLight(16777215,1);e.position.set(100,200,100),e.castShadow=!0,e.shadow.mapSize.width=2048,e.shadow.mapSize.height=2048,e.shadow.camera.near=.1,e.shadow.camera.far=5e3,e.shadow.bias=-5e-5,e.shadow.normalBias=.02;const t=50;e.shadow.camera.left=-t,e.shadow.camera.right=t,e.shadow.camera.top=t,e.shadow.camera.bottom=-t,e.shadow.radius=2,e.shadow.intensity=_c;const i=new w.DirectionalLight(16777215,2);this.engine.scene.add(e),this.engine.scene.add(i),this.engine.scene.dirLight=i;const s=new w.AmbientLight(16777215,2);this.engine.scene.add(s)}}class w2{engine;behavior;isCtrlDown=!1;isShiftDown=!1;hoverOldId=null;timeOutEvent;selectionBox=null;isBoxSelecting=!1;selectionStart=new w.Vector2;selectionEnd=new w.Vector2;suppressClickOnce=!1;selectionThreshold=5;tempInstanceMatrix=new w.Matrix4;tempScale=new w.Vector3;constructor(e){this.engine=e}init(){this.behavior=this.engine.handelBehaved,this.ensureSelectionBox(),this.behavior.init(this)}active(){this.behavior.active()}disActive(){this.cancelBoxSelection(),this.behavior.disActive()}handelKeyCtrlUp(){this.isCtrlDown=!1,this.isBoxSelecting&&this.cancelBoxSelection()}handelKeyCtrlDown(){this.isCtrlDown=!0}handelKeyShiftUp(){this.isShiftDown=!1}handelKeyShiftDown(){this.isShiftDown=!0}handleMouseDown(e){e.button!==0||!this.isBoxSelectionModifierDown()||(this.isBoxSelecting=!0,this.selectionStart.set(e.offsetX,e.offsetY),this.selectionEnd.copy(this.selectionStart),this.suppressClickOnce=!1,this.clearHoverFeedback(),this.updateSelectionBox(),this.engine.controls&&(this.engine.controls.enabled=!1))}handelKeyEscDown(){this.engine.modelToolModule.unhighlightAllModels()}handleMouseMove(e){if(this.clearHoverTimeout(),this.isBoxSelecting){this.selectionEnd.set(e.offsetX,e.offsetY),this.clearHoverFeedback(),this.updateSelectionBox();return}if(e.catch!=null&&(this.engine.hoverHighLight.showModelNameTag(null,null),this.timeOutEvent=setTimeout(()=>{this.hoverOldId=null;const i=this.getCatchMeshs(e,!0);i!=null&&i.length>0&&this.engine.hoverHighLight.showModelNameTag({url:i[0].url,ids:[i[0].name]},e.catch.point)},1e3)),!this.engine.engineStatus.isFree){this.engine.hoverHighLight.clearHighlight();return}const t=this.getCatchMeshs(e);if(t!=null&&t.length>0){this.engine.hoverHighLight.hightMesh(t);return}e.catch==null&&this.engine.hoverHighLight.clearHighlight()}handleMouseUp(e){if(!this.isBoxSelecting)return;this.selectionEnd.set(e.offsetX,e.offsetY);const t=this.hasSelectionBox(),i=t?this.collectModelsInSelection():[];this.isBoxSelecting=!1,this.hideSelectionBox(),this.engine.controls&&(this.engine.controls.enabled=!0),t&&(this.isBoxDeselectMode()?this.applyBoxDeselection(i):this.applyBoxSelection(i),this.suppressClickOnce=!0)}getCatchMeshs(e,t=!1){if(e.catch==null)return this.hoverOldId=null,null;if(e.catch.object.isInstance){const c=e.catch.object,h=e.catch.object.id,f=this.engine.models.find(p=>p.url==c.url)?.nodesMap?.get(h),u=new Map;f?.indexes.forEach(p=>{this.getSceneModel(p[0])instanceof w.InstancedMesh&&(u.has(p[0])||u.set(p[0],[]),u.get(p[0])?.push(p[1]))});const g=[];return u.forEach((p,m)=>{const A=this.getSceneModel(m);p.forEach(x=>{const b=A.geometry.clone();b.applyMatrix4(A.matrixs[x]),g.push(new w.Mesh(b,A.material))})}),this.hoverOldId==h?[]:(this.hoverOldId=h,t||this.engine.hoverHighLight.clearHighlight(),g)}const s=e.catch.object,r=s.name,l=this.engine.models.find(c=>c.url===s.url)?.nodesMap?.get(r)?.infos?.map(c=>c.mesh)??[];return this.hoverOldId==r?[]:(this.hoverOldId=r,t||this.engine.hoverHighLight.clearHighlight(),l)}handleMouseClick(e){if(this.suppressClickOnce){this.suppressClickOnce=!1;return}if(this.isShiftDown){if(e.catch!=null){const s=e.catch.object;this.applyBoxDeselection([{url:s.url,ids:[s.name]}])}return}if(e.catch!=null){const i=e.catch,s=i.object;if(!this.isCtrlDown){this.engine.modelToolModule.unhighlightAllModels();const o=new CustomEvent("D3ElementClick",{detail:{id:-1}});window.dispatchEvent(o)}this.engine.controlModule.orbitControls.origin.set(i.point.x,i.point.y,i.point.z),this.engine.modelToolModule.highlightModel([{url:s.url,ids:[s.name]}]),this.engine.events.trigger(Et.Click,[{url:s.url,ids:[s.name]}]);const r=new CustomEvent("D3ElementClick",{detail:{id:s.name}});window.dispatchEvent(r);return}const t=new CustomEvent("D3ElementClick",{detail:{id:-1}});window.dispatchEvent(t),this.engine.modelToolModule.unhighlightAllModels()}handleMouseDoubleClick(e){if(!e.catch){this.engine.viewCube.CameraGoHome(500);return}const t=e.catch,i=t.object,r=this.engine.models.find(l=>l.url===i.url)?.nodesMap?.get(i.name);if(!r)return;if(t.object.isInstance){const l=t.matrix,c=[];r.indexes.forEach(d=>{const f=this.getSceneModel(d[0]);f?.geometry?.boundingSphere||f?.geometry?.computeBoundingSphere?.();const u=f?.geometry?.boundingSphere;if(!u)return;const g=new w.Box3,p=u.center.clone().applyMatrix4(l),m=u.radius,A=new w.Vector3().setFromMatrixScale(l),x=m*Math.max(A.x,A.y,A.z);g.min.set(p.x-x,p.y-x,p.z-x),g.max.set(p.x+x,p.y+x,p.z+x),c.push(g)});const h=this.getMergedBox(c);h!=null&&this.engine.viewCube.zoomToModel(h);return}const o=r.infos.map(l=>l.box).filter(l=>l instanceof w.Box3),a=this.getMergedBox(o);a!=null&&this.engine.viewCube.zoomToModel(a)}handleMouseClickInstance(e){return e.intersectObjects(this.engine.scene.children.filter(t=>t instanceof w.InstancedMesh),!0)}ensureSelectionBox(){if(this.selectionBox!=null)return;const e=document.createElement("div");e.style.position="absolute",e.style.left="0px",e.style.top="0px",e.style.display="none",e.style.pointerEvents="none",e.style.border="1px dashed #00aaff",e.style.backgroundColor="rgba(0, 170, 255, 0.12)",e.style.boxSizing="border-box",e.style.zIndex="1001",this.engine.container?.appendChild(e),this.selectionBox=e}updateSelectionBox(){if(this.selectionBox==null)return;if(!this.hasSelectionBox()){this.selectionBox.style.display="none";return}const e=this.getSelectionRect();this.selectionBox.style.display="block",this.selectionBox.style.left=`${e.left}px`,this.selectionBox.style.top=`${e.top}px`,this.selectionBox.style.width=`${e.right-e.left}px`,this.selectionBox.style.height=`${e.bottom-e.top}px`}hideSelectionBox(){this.selectionBox!=null&&(this.selectionBox.style.display="none")}cancelBoxSelection(){this.isBoxSelecting=!1,this.hideSelectionBox(),this.engine.controls&&(this.engine.controls.enabled=!0)}clearHoverTimeout(){this.timeOutEvent!=null&&(clearTimeout(this.timeOutEvent),this.timeOutEvent=null)}clearHoverFeedback(){this.hoverOldId=null,this.engine.hoverHighLight.clearHighlight(),this.engine.hoverHighLight.showModelNameTag(null,null)}hasSelectionBox(){return Math.abs(this.selectionEnd.x-this.selectionStart.x)>=this.selectionThreshold&&Math.abs(this.selectionEnd.y-this.selectionStart.y)>=this.selectionThreshold}getSelectionRect(){return{left:Math.min(this.selectionStart.x,this.selectionEnd.x),top:Math.min(this.selectionStart.y,this.selectionEnd.y),right:Math.max(this.selectionStart.x,this.selectionEnd.x),bottom:Math.max(this.selectionStart.y,this.selectionEnd.y)}}isContainMode(){return this.selectionEnd.x>=this.selectionStart.x&&this.selectionEnd.y>=this.selectionStart.y}isBoxSelectionModifierDown(){return this.isCtrlDown}isBoxDeselectMode(){return this.isShiftDown}collectModelsInSelection(){const e=this.getSelectionRect(),t=this.isContainMode(),i=new Map;return this.engine.models?.forEach(s=>{!s?.url||!s?.nodesMap||s.nodesMap.forEach((r,o)=>{const a=this.getNodeWorldBox(r),l=this.projectBoxToScreenRect(a);l==null||!(t?this.containsRect(e,l):this.intersectsRect(e,l))||(i.has(s.url)||i.set(s.url,new Set),i.get(s.url)?.add(o))})}),Array.from(i.entries()).map(([s,r])=>({url:s,ids:Array.from(r)}))}applyBoxSelection(e){const t=this.excludeHighlightedModels(e);t.length!==0&&(this.engine.modelToolModule.highlightModel(t),this.engine.events.trigger(Et.SelectionChanged,t))}applyBoxDeselection(e){const t=this.keepHighlightedModels(e);t.length!==0&&(this.engine.modelToolModule.unhighlightModel(t),this.removeModelsFromHighlightState(t),this.engine.events.trigger(Et.SelectionChanged,t))}excludeHighlightedModels(e){const t=new Map;return(this.engine.engineStatus.highlightModels??[]).forEach(i=>{t.has(i.url)||t.set(i.url,new Set),i.ids.forEach(s=>t.get(i.url)?.add(s))}),e.map(i=>({url:i.url,ids:i.ids.filter(s=>!t.get(i.url)?.has(s))})).filter(i=>i.ids.length>0)}keepHighlightedModels(e){const t=new Map;return(this.engine.engineStatus.highlightModels??[]).forEach(i=>{t.has(i.url)||t.set(i.url,new Set),i.ids.forEach(s=>t.get(i.url)?.add(s))}),e.map(i=>({url:i.url,ids:i.ids.filter(s=>t.get(i.url)?.has(s))})).filter(i=>i.ids.length>0)}removeModelsFromHighlightState(e){const t=new Map;e.forEach(i=>{t.has(i.url)||t.set(i.url,new Set),i.ids.forEach(s=>t.get(i.url)?.add(s))}),this.engine.engineStatus.highlightModels=(this.engine.engineStatus.highlightModels??[]).map(i=>({url:i.url,ids:i.ids.filter(s=>!t.get(i.url)?.has(s))})).filter(i=>i.ids.length>0)}getNodeWorldBox(e){if(Array.isArray(e?.infos)&&e.infos.length>0){const t=e.infos.map(i=>i?.box).filter(i=>i instanceof w.Box3);return this.getMergedBox(t)}if(Array.isArray(e?.indexes)&&e.indexes.length>0){const t=[];return e.indexes.forEach(i=>{const s=this.getSceneModel(i[0]),r=this.getInstanceWorldBox(s,i[1]);r!=null&&t.push(r)}),this.getMergedBox(t)}return null}getInstanceWorldBox(e,t){if(!(e instanceof w.InstancedMesh))return null;e.geometry.boundingBox||e.geometry.computeBoundingBox();const i=e.geometry.boundingBox;if(!i)return null;if(typeof e.getMatrixAt=="function")e.getMatrixAt(t,this.tempInstanceMatrix);else if(e.matrixs?.[t])this.tempInstanceMatrix.copy(e.matrixs[t]);else return null;return this.tempScale.setFromMatrixScale(this.tempInstanceMatrix),Math.abs(this.tempScale.x)+Math.abs(this.tempScale.y)+Math.abs(this.tempScale.z)<1e-6?null:i.clone().applyMatrix4(this.tempInstanceMatrix)}projectBoxToScreenRect(e){if(e==null||e.isEmpty())return null;const t=[new w.Vector3(e.min.x,e.min.y,e.min.z),new w.Vector3(e.min.x,e.min.y,e.max.z),new w.Vector3(e.min.x,e.max.y,e.min.z),new w.Vector3(e.min.x,e.max.y,e.max.z),new w.Vector3(e.max.x,e.min.y,e.min.z),new w.Vector3(e.max.x,e.min.y,e.max.z),new w.Vector3(e.max.x,e.max.y,e.min.z),new w.Vector3(e.max.x,e.max.y,e.max.z)];let i=1/0,s=1/0,r=-1/0,o=-1/0;return t.forEach(a=>{const l=new lt(this.engine.camera,this.engine.renderer,this.engine.scene).worldToScreen(a);!Number.isFinite(l.x)||!Number.isFinite(l.y)||(i=Math.min(i,l.x),s=Math.min(s,l.y),r=Math.max(r,l.x),o=Math.max(o,l.y))}),!Number.isFinite(i)||!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(o)?null:{left:i,top:s,right:r,bottom:o}}containsRect(e,t){return t.left>=e.left&&t.top>=e.top&&t.right<=e.right&&t.bottom<=e.bottom}intersectsRect(e,t){return!(t.right<e.left||t.left>e.right||t.bottom<e.top||t.top>e.bottom)}getMergedBox(e){if(e.length===0)return null;const t=new w.Box3().makeEmpty();return e.forEach(i=>t.union(i)),t.isEmpty()?null:t}getSceneModel(e){return this.engine.scene.children.find(t=>t.index===e)??this.engine.scene.children[e]}}class S2{engine;highlightMaterial;translucentMaterial;constructor(e){this.engine=e,this.highlightMaterial=new w.MeshBasicMaterial({color:43775,depthTest:!1,depthWrite:!1,transparent:!0,opacity:.8,side:w.DoubleSide}),this.translucentMaterial=new w.MeshBasicMaterial({color:16777215,transparent:!0,opacity:.05,side:w.DoubleSide}),this.highlightMaterial.clippingPlanes=this.engine.sectionPlane,this.translucentMaterial.clippingPlanes=this.engine.sectionPlane,this.engine.events?.on?.(Cs.EngineFree,()=>{this.restoreSplitModelsOnIdle()})}split_merge_model(e){if(e.isSplit||e instanceof w.InstancedMesh)return;e.geometry!=null&&(e.__mergedGeometryBackup=e.geometry);let t=e.materialClone.clone(),i=Yn(e.geometrys,!0);i.computeVertexNormals(),i.groups.forEach(s=>{s.materialIndex=0}),e.geometry=i,e.material=[t,this.highlightMaterial,this.translucentMaterial],e.needsUpdate=!0,e.isSplit=!0}un_split_merge_model(e){if(e==null||e instanceof w.InstancedMesh||e.isSplit!==!0||this.shouldKeepSplitState(e))return;const t=e.__mergedGeometryBackup;if(t!=null){const r=e.geometry;e.geometry=t,e.material=e.materialClone?.clone?e.materialClone.clone():e.materialClone,e.needsUpdate=!0,e.isSplit=!1,r&&r!==t&&typeof r.dispose=="function"&&r.dispose(),console.log("merge");return}if(!Array.isArray(e.geometrys)||e.geometrys.length===0)return;const i=e.geometry,s=Yn(e.geometrys,!1);s!=null&&(s.computeVertexNormals(),e.geometry=s,e.material=e.materialClone?.clone?e.materialClone.clone():e.materialClone,e.needsUpdate=!0,e.isSplit=!1,i&&i!==s&&typeof i.dispose=="function"&&i.dispose(),console.log("merge"))}shouldKeepSplitState(e){const t=e?.geometry?.groups;return!Array.isArray(t)||t.length===0?!1:t.some(i=>(typeof i.materialIndex=="number"?i.materialIndex:0)!==0||i.visible===!1)}restoreSplitModelsOnIdle(){this.engine?.scene?.children&&this.engine.scene.children.forEach(e=>{const t=e;t instanceof w.Mesh&&t.isSplit===!0&&this.un_split_merge_model(t)})}getSceneModel(e){return this.engine.scene.children.find(t=>t.index==e)}updateMaterial(){let e=0;this.engine.engineStatus.highlightModels?.forEach(t=>{e=e+t.ids.length}),e>20?(this.highlightMaterial.depthTest=!0,this.highlightMaterial.depthWrite=!0,this.highlightMaterial.transparent=!1):(this.highlightMaterial.depthTest=!1,this.highlightMaterial.depthWrite=!1,this.highlightMaterial.transparent=!0)}highlightModel(e){e.forEach(t=>{let i=new Map;t.ids.forEach(r=>{let o=this.engine.models.find(a=>a.url==t.url).nodesMap.get(r);o!=null&&o.indexes!=null&&o.indexes.forEach(a=>{this.getSceneModel(a[0])instanceof w.InstancedMesh?i.has(a[0])?i.get(a[0])?.push(a[1]):i.set(a[0],[a[1]]):(this.split_merge_model(this.getSceneModel(a[0])),this.getSceneModel(a[0]).geometry.groups[a[1]].materialIndex=1)})}),C2(i,this.engine);let s=this.engine.engineStatus.highlightModels.find(r=>r.url==t.url);s!=null?s.ids.push(...t.ids):this.engine.engineStatus.highlightModels.push(t)}),this.updateMaterial()}unhighlightModel(e){e.forEach(t=>{let i=new Map;t.ids.forEach(s=>{let r=this.engine.models.find(o=>o.url==t.url).nodesMap.get(s);r!=null&&r.indexes!=null&&r.indexes.forEach(o=>{this.getSceneModel(o[0])instanceof w.InstancedMesh?i.has(o[0])?i.get(o[0])?.push(o[1]):i.set(o[0],[o[1]]):this.getSceneModel(o[0]).geometry.groups[o[1]].materialIndex=0})}),H0(i,this.engine,"highlightModel")}),this.updateMaterial()}unhighlightAllModels(e=!0){this.engine.engineStatus.highlightModels.forEach(t=>{this.unhighlightModel([t])}),e&&(this.engine.engineStatus.highlightModels=[]),this.updateMaterial()}hideModel(e){e.forEach(t=>{let i=new Map;t.ids.forEach(r=>{let o=this.engine.models.find(a=>a.url==t.url).nodesMap.get(r);this.engine.modelEdge.hideModelEdge(t.url,r),o!=null&&o.indexes!=null&&o.indexes.forEach(a=>{const l=this.getSceneModel(a[0]);l instanceof w.InstancedMesh?i.has(a[0])?i.get(a[0])?.push(a[1]):i.set(a[0],[a[1]]):(this.split_merge_model(this.getSceneModel(a[0])),l.geometry.groups[a[1]].materialIndex=-1,l.geometry.groups[a[1]].visible=!1)})}),i.size>0&&E2(i,this.engine);let s=this.engine.engineStatus.hideModels.find(r=>r.url==t.url);s!=null?s.ids.push(...t.ids):this.engine.engineStatus.hideModels.push({url:t.url,ids:t.ids}),this.engine.engineStatus.highlightModels=[]})}showModel(e){e.forEach(t=>{let i=new Map;t.ids.forEach(r=>{let o=this.engine.models.find(a=>a.url==t.url).nodesMap.get(r);this.engine.modelEdge.showModelEdge(t.url,r),o!=null&&o.indexes!=null&&o.indexes.forEach(a=>{const l=this.getSceneModel(a[0]);l instanceof w.InstancedMesh?i.has(a[0])?i.get(a[0])?.push(a[1]):i.set(a[0],[a[1]]):(l.geometry.groups[a[1]].materialIndex=0,l.geometry.groups[a[1]].visible=!0)})}),i.size>0&&X0(i,this.engine);let s=this.engine.engineStatus.hideModels.find(r=>r.url==t.url);s&&(t.ids.forEach(r=>{const o=s.ids.indexOf(r);o!==-1&&s.ids.splice(o,1)}),s.ids.length===0&&(this.engine.engineStatus.hideModels=this.engine.engineStatus.hideModels.filter(r=>r!==s)))})}isolateModel(e){let t=[];this.engine.models.forEach(i=>{let s={url:i.url,ids:[]},r=e.find(o=>o.url==i.url);for(let o of i.nodesMap)r==null?s.ids.push(o[0]):r.ids.includes(o[0])||s.ids.push(o[0]);t.push(s)});debugger;this.unhighlightAllModels(),this.hideModel(t)}translucentOtherModel(e){let t=[];this.engine.models.forEach(i=>{let s={url:i.url,ids:[]},r=e.find(o=>o.url==i.url);for(let o of i.nodesMap)r==null?s.ids.push(o[0]):r.ids.includes(o[0])||s.ids.push(o[0]);t.push(s)}),this.translucentModel(t)}setModelColor(e,t){e.material.color.set(t)}setAllModelsColor(e){this.engine.scene.children.forEach(t=>{t.isMesh})}restoreAllModelsColor(){this.engine.scene.children.forEach(e=>{e.isMesh})}translucentModel(e){this.unhighlightAllModels(),e.forEach(t=>{let i=new Map;t.ids.forEach(r=>{let o=this.engine.models.find(a=>a.url==t.url).nodesMap.get(r);o!=null&&o.indexes!=null&&o.indexes.forEach(a=>{const l=this.getSceneModel(a[0]);l instanceof w.InstancedMesh?i.has(a[0])?i.get(a[0])?.push(a[1]):i.set(a[0],[a[1]]):(this.split_merge_model(this.getSceneModel(a[0])),l.geometry.groups[a[1]].materialIndex=2)})}),M2(i,this.engine);let s=this.engine.engineStatus.translucentModels.find(r=>r.url==t.url);s!=null?s.ids.push(...t.ids):this.engine.engineStatus.translucentModels.push({url:t.url,ids:t.ids})}),this.engine.engineStatus.highlightModels=[]}unTranslucentModel(){this.engine.engineStatus.translucentModels.forEach(t=>{let i=new Map;t.ids.forEach(s=>{let r=this.engine.models.find(o=>o.url==t.url).nodesMap.get(s);r!=null&&r.indexes!=null&&r.indexes.forEach(o=>{const a=this.getSceneModel(o[0]);a instanceof w.InstancedMesh?i.has(o[0])?i.get(o[0])?.push(o[1]):i.set(o[0],[o[1]]):(this.split_merge_model(this.getSceneModel(o[0])),a.geometry.groups[o[1]].materialIndex=0)})}),i.size>0&&X0(i,this.engine),H0(i,this.engine,"translucentModel")}),this.engine.engineStatus.translucentModels=[]}showAllModels(){this.engine.engineStatus.hideModels&&this.engine.engineStatus.hideModels.length>0&&this.showModel(this.engine.engineStatus.hideModels),this.engine.engineStatus.hideModels=[],this.unhighlightAllModels()}batchSelectSameLevelTypeModel(e){if(e.length==0)return;let t=e[0],i=this.engine.modelMapperBatch.getModelMapper(t.url,t.ids[0]);this.engine.modelMapperBatch.getModelsWithLevelType(i.levelName,i.typeName,s=>{this.engine.modelToolModule.highlightModel(s)})}batchSelectSameLevelModel(e){if(e.length==0)return;let t=e[0],i=this.engine.modelMapperBatch.getModelMapper(t.url,t.ids[0]);this.engine.modelMapperBatch.getModelsWithLevel(i.levelName,s=>{this.engine.modelToolModule.highlightModel(s)})}batchSelectSameTypeModel(e){if(e.length==0)return;let t=e[0],i=this.engine.modelMapperBatch.getModelMapper(t.url,t.ids[0]);this.engine.modelMapperBatch.getModelsWithType(i.typeName,s=>{this.engine.modelToolModule.highlightModel(s)})}}function C2(n,e){n.forEach((t,i)=>{const s=ga(e,i);if(!(s instanceof w.InstancedMesh))return;const r=s.geometry,o=new w.MeshBasicMaterial({color:43775,depthTest:!1,depthWrite:!1,transparent:!0,opacity:.5,side:w.DoubleSide}),a=new w.InstancedMesh(r,o,t.length);a.name="highlightModel",a.key=i;const l=new Map,c=new w.Matrix4,h=new w.Matrix4;h.makeScale(0,0,0),t.forEach((d,f)=>{s.getMatrixAt(d,c),l.set(d,c.clone()),s.setMatrixAt(d,h),a.setMatrixAt(f,c)}),s.instanceMatrix.needsUpdate=!0,a.instanceMatrix.needsUpdate=!0,e.scene.add(a)})}function H0(n,e,t){n.forEach((i,s)=>{const r=ga(e,s);if(!(r instanceof w.InstancedMesh))return;i.forEach(a=>{const l=r.matrixsClone[a];l&&r.setMatrixAt(a,l)}),r.instanceMatrix.needsUpdate=!0,e.scene.children.filter(a=>a.key==s&&a.name==t).forEach(a=>{e.scene.remove(a)})})}function M2(n,e){n.forEach((t,i)=>{const s=ga(e,i);if(!(s instanceof w.InstancedMesh))return;const r=s.geometry,o=new w.MeshBasicMaterial({color:16777215,transparent:!0,opacity:.05,side:w.DoubleSide}),a=new w.InstancedMesh(r,o,t.length);a.name="translucentModel",a.key=i;const l=new Map,c=new w.Matrix4,h=new w.Matrix4;h.makeScale(0,0,0),t.forEach((d,f)=>{s.getMatrixAt(d,c),l.set(d,c.clone()),s.setMatrixAt(d,h),a.setMatrixAt(f,c)}),s.instanceMatrix.needsUpdate=!0,a.instanceMatrix.needsUpdate=!0,e.scene.add(a)})}function E2(n,e){e.scene.children.filter(t=>t.name=="highlightModel").forEach(t=>{e.scene.remove(t)}),n.forEach((t,i)=>{const s=ga(e,i);if(!(s instanceof w.InstancedMesh))return;const r=new Map,o=new w.Matrix4,a=new w.Matrix4;a.makeScale(0,0,0),t.forEach((l,c)=>{s.getMatrixAt(l,o),r.set(l,o.clone()),s.setMatrixAt(l,a)}),s.instanceMatrix.needsUpdate=!0})}function X0(n,e){n.forEach((t,i)=>{const s=ga(e,i);s instanceof w.InstancedMesh&&(t.forEach(r=>{const o=s.matrixs[r];o&&s.setMatrixAt(r,o)}),s.instanceMatrix.needsUpdate=!0)})}function ga(n,e){return n.scene.children.find(t=>t.index==e)}const q0="advanced";class I2{engine;currentMode="";isManualMode=!1;gtaoPass=null;ssaoPass=null;saturationPass=null;outputPass=null;fxaaPass=null;constructor(e){this.engine=e}init(){this.cachePassReferences(),this.autoSwitch(q0)}switchModel(e){this.isManualMode=!0,this.currentMode=e,this.applyMode(e)}autoSwitch(e){this.isManualMode||(this.currentMode=e,this.applyMode(e))}enableAutoMode(){this.isManualMode=!1}get isManual(){return this.isManualMode}setMode(e){this.isManualMode=!0,this.currentMode=e,this.applyMode(e)}getCurrentMode(){return this.currentMode}cachePassReferences(){this.engine.composerModule?.composer&&(this.engine.composerModule.gtaoPass&&(this.gtaoPass=this.engine.composerModule.gtaoPass),this.engine.composerModule.ssaoPass&&(this.ssaoPass=this.engine.composerModule.ssaoPass),this.engine.composerModule.saturationPass&&(this.saturationPass=this.engine.composerModule.saturationPass),this.engine.composerModule.outputPass&&(this.outputPass=this.engine.composerModule.outputPass),this.engine.composerModule.fxaaPass&&(this.fxaaPass=this.engine.composerModule.fxaaPass))}applyMode(e){switch(e){case"simple":this.setShadows(!1),this.setGTAO(!1),this.setSSAO(!1),this.setSaturation(!0);break;case"balance":this.setShadows(!0),this.setGTAO(!1),this.setSSAO(!1),this.setSaturation(!0);break;case"advanced":this.setShadows(!0),this.setGTAO(!0),this.setSSAO(!1),this.setSaturation(!0);break;default:console.warn(`[EngineModelModule] Unknown mode: ${e}`)}this.engine.updateVersionDisplay?.()}setShadows(e){this.engine.renderer&&(this.engine.renderer.shadowMap.enabled=e);const t=this.engine.scene?.children.find(i=>i instanceof w.DirectionalLight);t&&(t.castShadow=e),this.engine.scene?.traverse(i=>{i.material&&(i.castShadow!==void 0&&(i.castShadow=e),i.receiveShadow!==void 0&&(i.receiveShadow=e))})}setGTAO(e){this.engine.composerModule?.composer&&this.gtaoPass&&(this.gtaoPass.enabled=e)}setSSAO(e){this.engine.composerModule?.composer&&this.ssaoPass&&(this.ssaoPass.enabled=e)}setSaturation(e){this.saturationPass&&(this.saturationPass.enabled=e)}setOutputPass(e){this.outputPass&&(this.outputPass.enabled=e)}setFXAA(e){this.fxaaPass&&(this.fxaaPass.enabled=e)}setPerformanceMode(){this.setMode("simple")}setBalancedMode(){this.setMode("balance")}setQualityMode(){this.setMode("advanced")}setSuperQualityMode(){this.setMode("superAdvanced")}setShadowQuality(e){const t=this.engine.scene?.children.find(r=>r instanceof w.DirectionalLight),s={low:1024,medium:2048,high:2048}[e];t?.shadow&&s&&(t.shadow.mapSize.width=s,t.shadow.mapSize.height=s,t.shadow.map?.dispose(),t.shadow.map=null)}setSaturationValue(e){this.saturationPass&&(this.saturationPass.uniforms.saturation.value=e)}setContrastValue(e){this.saturationPass&&(this.saturationPass.uniforms.contrast.value=e)}setGTAOIntensity(e){this.gtaoPass&&(this.gtaoPass.blendIntensity=e)}}class wc{engine;overlayMaterial;overlayMeshes=[];animState="idle";animStartTime=0;static FADE_IN_MS=200;static FADE_OUT_MS=150;tagDiv;constructor(e){this.engine=e,this.init();const t=document.createElement("div");this.tagDiv=t,t.className="tagDiv",t.style.position="absolute",t.style.top="0px",t.style.left="0px",t.style.borderRadius="10px",t.style.pointerEvents="none",this.engine.container.appendChild(this.tagDiv)}showModelNameTag(e,t){if(e==null){this.tagDiv.style.display="none";return}let i=this.engine.models.find(a=>a.url==e.url);if(i==null){this.tagDiv.style.display="none";return}let s=i.nodesMap.get(e.ids[0]);if(s.infos&&s.infos.length>0){let a=s.infos[0].name.replace(/\s*\[[a-f0-9-]+\]$/,"");this.tagDiv.innerHTML=a}const o=this.engine.worldToScreen.worldToScreen(t);this.tagDiv?(this.tagDiv.style.left=o.x+10+this.engine.reactBoundingClientRect.left+"px",this.tagDiv.style.top=o.y-10+this.engine.reactBoundingClientRect.top+"px",this.tagDiv.style.display="block"):this.tagDiv&&(this.tagDiv.style.display="none")}init(){this.overlayMaterial=new w.MeshBasicMaterial({color:16777215,transparent:!0,opacity:0,blending:w.AdditiveBlending,depthWrite:!1}),this.overlayMaterial.clippingPlanes=this.engine.sectionPlane}hightMesh(e,t=16777215,i=.15){this.animState==="fadeOut"&&this.removeOverlayMeshes();const s=(Array.isArray(e)?e:e?[e]:[]).filter(r=>r?.geometry);if(s.length===0){this.clearHighlight();return}this.overlayMaterial.color.set(t),this.overlayMaterial.opacity=0,this.overlayMaterial.userData.targetOpacity=i;for(const r of s){let o=r.geometry.clone();o.computeVertexNormals();const a=new w.Mesh(o,this.overlayMaterial);r.updateWorldMatrix(!0,!1),a.matrix.copy(r.matrixWorld),a.matrixAutoUpdate=!1,this.engine.scene.add(a),this.overlayMeshes.push(a)}this.animState="fadeIn",this.animStartTime=performance.now()}clearHighlight(){this.overlayMeshes.length===0||this.animState==="fadeOut"||(this.animState="fadeOut",this.animStartTime=performance.now())}update(){if(this.animState==="idle"||this.overlayMeshes.length===0)return;const e=performance.now()-this.animStartTime,t=this.overlayMaterial.userData.targetOpacity??.35;if(this.animState==="fadeIn"){const i=Math.min(e/wc.FADE_IN_MS,1);this.overlayMaterial.opacity=this.easeOutQuad(i)*t,i>=1&&(this.animState="idle")}else if(this.animState==="fadeOut"){const i=Math.min(e/wc.FADE_OUT_MS,1);this.overlayMaterial.opacity=(1-this.easeOutQuad(i))*t,i>=1&&(this.removeOverlayMeshes(),this.animState="idle")}}removeOverlayMeshes(){for(const e of this.overlayMeshes)this.engine.scene.remove(e);this.overlayMeshes=[]}easeOutQuad(e){return 1-(1-e)*(1-e)}dispose(){this.removeOverlayMeshes(),this.overlayMaterial.dispose(),this.animState="idle"}}var Sc={exports:{}},T2=Sc.exports,Y0;function D2(){return Y0||(Y0=1,(function(n,e){(function(t,i){n.exports=i()})(T2,function(){var t=function(){function i(u){return o.appendChild(u.dom),u}function s(u){for(var g=0;g<o.children.length;g++)o.children[g].style.display=g===u?"block":"none";r=u}var r=0,o=document.createElement("div");o.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",o.addEventListener("click",function(u){u.preventDefault(),s(++r%o.children.length)},!1);var a=(performance||Date).now(),l=a,c=0,h=i(new t.Panel("FPS","#0ff","#002")),d=i(new t.Panel("MS","#0f0","#020"));if(self.performance&&self.performance.memory)var f=i(new t.Panel("MB","#f08","#201"));return s(0),{REVISION:16,dom:o,addPanel:i,showPanel:s,begin:function(){a=(performance||Date).now()},end:function(){c++;var u=(performance||Date).now();if(d.update(u-a,200),u>l+1e3&&(h.update(1e3*c/(u-l),100),l=u,c=0,f)){var g=performance.memory;f.update(g.usedJSHeapSize/1048576,g.jsHeapSizeLimit/1048576)}return u},update:function(){a=this.end()},domElement:o,setMode:s}};return t.Panel=function(i,s,r){var o=1/0,a=0,l=Math.round,c=l(window.devicePixelRatio||1),h=80*c,d=48*c,f=3*c,u=2*c,g=3*c,p=15*c,m=74*c,A=30*c,x=document.createElement("canvas");x.width=h,x.height=d,x.style.cssText="width:80px;height:48px";var b=x.getContext("2d");return b.font="bold "+9*c+"px Helvetica,Arial,sans-serif",b.textBaseline="top",b.fillStyle=r,b.fillRect(0,0,h,d),b.fillStyle=s,b.fillText(i,f,u),b.fillRect(g,p,m,A),b.fillStyle=r,b.globalAlpha=.9,b.fillRect(g,p,m,A),{dom:x,update:function(y,_){o=Math.min(o,y),a=Math.max(a,y),b.fillStyle=r,b.globalAlpha=1,b.fillRect(0,0,h,p),b.fillStyle=s,b.fillText(l(y)+" "+i+" ("+l(o)+"-"+l(a)+")",f,u),b.drawImage(x,g+c,p,m-c,A,g,p,m-c,A),b.fillRect(g+m-c,p,c,A),b.fillStyle=r,b.globalAlpha=.9,b.fillRect(g+m-c,p,c,l((1-y/_)*A))}}},t})})(Sc)),Sc.exports}var B2=D2();const P2=Qm(B2);var mo=Object.freeze({Linear:Object.freeze({None:function(n){return n},In:function(n){return n},Out:function(n){return n},InOut:function(n){return n}}),Quadratic:Object.freeze({In:function(n){return n*n},Out:function(n){return n*(2-n)},InOut:function(n){return(n*=2)<1?.5*n*n:-.5*(--n*(n-2)-1)}}),Cubic:Object.freeze({In:function(n){return n*n*n},Out:function(n){return--n*n*n+1},InOut:function(n){return(n*=2)<1?.5*n*n*n:.5*((n-=2)*n*n+2)}}),Quartic:Object.freeze({In:function(n){return n*n*n*n},Out:function(n){return 1- --n*n*n*n},InOut:function(n){return(n*=2)<1?.5*n*n*n*n:-.5*((n-=2)*n*n*n-2)}}),Quintic:Object.freeze({In:function(n){return n*n*n*n*n},Out:function(n){return--n*n*n*n*n+1},InOut:function(n){return(n*=2)<1?.5*n*n*n*n*n:.5*((n-=2)*n*n*n*n+2)}}),Sinusoidal:Object.freeze({In:function(n){return 1-Math.sin((1-n)*Math.PI/2)},Out:function(n){return Math.sin(n*Math.PI/2)},InOut:function(n){return .5*(1-Math.sin(Math.PI*(.5-n)))}}),Exponential:Object.freeze({In:function(n){return n===0?0:Math.pow(1024,n-1)},Out:function(n){return n===1?1:1-Math.pow(2,-10*n)},InOut:function(n){return n===0?0:n===1?1:(n*=2)<1?.5*Math.pow(1024,n-1):.5*(-Math.pow(2,-10*(n-1))+2)}}),Circular:Object.freeze({In:function(n){return 1-Math.sqrt(1-n*n)},Out:function(n){return Math.sqrt(1- --n*n)},InOut:function(n){return(n*=2)<1?-.5*(Math.sqrt(1-n*n)-1):.5*(Math.sqrt(1-(n-=2)*n)+1)}}),Elastic:Object.freeze({In:function(n){return n===0?0:n===1?1:-Math.pow(2,10*(n-1))*Math.sin((n-1.1)*5*Math.PI)},Out:function(n){return n===0?0:n===1?1:Math.pow(2,-10*n)*Math.sin((n-.1)*5*Math.PI)+1},InOut:function(n){return n===0?0:n===1?1:(n*=2,n<1?-.5*Math.pow(2,10*(n-1))*Math.sin((n-1.1)*5*Math.PI):.5*Math.pow(2,-10*(n-1))*Math.sin((n-1.1)*5*Math.PI)+1)}}),Back:Object.freeze({In:function(n){var e=1.70158;return n===1?1:n*n*((e+1)*n-e)},Out:function(n){var e=1.70158;return n===0?0:--n*n*((e+1)*n+e)+1},InOut:function(n){var e=2.5949095;return(n*=2)<1?.5*(n*n*((e+1)*n-e)):.5*((n-=2)*n*((e+1)*n+e)+2)}}),Bounce:Object.freeze({In:function(n){return 1-mo.Bounce.Out(1-n)},Out:function(n){return n<1/2.75?7.5625*n*n:n<2/2.75?7.5625*(n-=1.5/2.75)*n+.75:n<2.5/2.75?7.5625*(n-=2.25/2.75)*n+.9375:7.5625*(n-=2.625/2.75)*n+.984375},InOut:function(n){return n<.5?mo.Bounce.In(n*2)*.5:mo.Bounce.Out(n*2-1)*.5+.5}}),generatePow:function(n){return n===void 0&&(n=4),n=n<Number.EPSILON?Number.EPSILON:n,n=n>1e4?1e4:n,{In:function(e){return Math.pow(e,n)},Out:function(e){return 1-Math.pow(1-e,n)},InOut:function(e){return e<.5?Math.pow(e*2,n)/2:(1-Math.pow(2-e*2,n))/2+.5}}}}),ma=function(){return performance.now()},L2=(function(){function n(){this._tweens={},this._tweensAddedDuringUpdate={}}return n.prototype.getAll=function(){var e=this;return Object.keys(this._tweens).map(function(t){return e._tweens[t]})},n.prototype.removeAll=function(){this._tweens={}},n.prototype.add=function(e){this._tweens[e.getId()]=e,this._tweensAddedDuringUpdate[e.getId()]=e},n.prototype.remove=function(e){delete this._tweens[e.getId()],delete this._tweensAddedDuringUpdate[e.getId()]},n.prototype.update=function(e,t){e===void 0&&(e=ma()),t===void 0&&(t=!1);var i=Object.keys(this._tweens);if(i.length===0)return!1;for(;i.length>0;){this._tweensAddedDuringUpdate={};for(var s=0;s<i.length;s++){var r=this._tweens[i[s]],o=!t;r&&r.update(e,o)===!1&&!t&&delete this._tweens[i[s]]}i=Object.keys(this._tweensAddedDuringUpdate)}return!0},n})(),Ju={Linear:function(n,e){var t=n.length-1,i=t*e,s=Math.floor(i),r=Ju.Utils.Linear;return e<0?r(n[0],n[1],i):e>1?r(n[t],n[t-1],t-i):r(n[s],n[s+1>t?t:s+1],i-s)},Utils:{Linear:function(n,e,t){return(e-n)*t+n}}},K0=(function(){function n(){}return n.nextId=function(){return n._nextId++},n._nextId=0,n})(),Zu=new L2,R2=(function(){function n(e,t){t===void 0&&(t=Zu),this._object=e,this._group=t,this._isPaused=!1,this._pauseStart=0,this._valuesStart={},this._valuesEnd={},this._valuesStartRepeat={},this._duration=1e3,this._isDynamic=!1,this._initialRepeat=0,this._repeat=0,this._yoyo=!1,this._isPlaying=!1,this._reversed=!1,this._delayTime=0,this._startTime=0,this._easingFunction=mo.Linear.None,this._interpolationFunction=Ju.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=K0.nextId(),this._isChainStopped=!1,this._propertiesAreSetUp=!1,this._goToEnd=!1}return n.prototype.getId=function(){return this._id},n.prototype.isPlaying=function(){return this._isPlaying},n.prototype.isPaused=function(){return this._isPaused},n.prototype.getDuration=function(){return this._duration},n.prototype.to=function(e,t){if(t===void 0&&(t=1e3),this._isPlaying)throw new Error("Can not call Tween.to() while Tween is already started or paused. Stop the Tween first.");return this._valuesEnd=e,this._propertiesAreSetUp=!1,this._duration=t<0?0:t,this},n.prototype.duration=function(e){return e===void 0&&(e=1e3),this._duration=e<0?0:e,this},n.prototype.dynamic=function(e){return e===void 0&&(e=!1),this._isDynamic=e,this},n.prototype.start=function(e,t){if(e===void 0&&(e=ma()),t===void 0&&(t=!1),this._isPlaying)return this;if(this._group&&this._group.add(this),this._repeat=this._initialRepeat,this._reversed){this._reversed=!1;for(var i in this._valuesStartRepeat)this._swapEndStartRepeatValues(i),this._valuesStart[i]=this._valuesStartRepeat[i]}if(this._isPlaying=!0,this._isPaused=!1,this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._isChainStopped=!1,this._startTime=e,this._startTime+=this._delayTime,!this._propertiesAreSetUp||t){if(this._propertiesAreSetUp=!0,!this._isDynamic){var s={};for(var r in this._valuesEnd)s[r]=this._valuesEnd[r];this._valuesEnd=s}this._setupProperties(this._object,this._valuesStart,this._valuesEnd,this._valuesStartRepeat,t)}return this},n.prototype.startFromCurrentValues=function(e){return this.start(e,!0)},n.prototype._setupProperties=function(e,t,i,s,r){for(var o in i){var a=e[o],l=Array.isArray(a),c=l?"array":typeof a,h=!l&&Array.isArray(i[o]);if(!(c==="undefined"||c==="function")){if(h){var d=i[o];if(d.length===0)continue;for(var f=[a],u=0,g=d.length;u<g;u+=1){var p=this._handleRelativeValue(a,d[u]);if(isNaN(p)){h=!1,console.warn("Found invalid interpolation list. Skipping.");break}f.push(p)}h&&(i[o]=f)}if((c==="object"||l)&&a&&!h){t[o]=l?[]:{};var m=a;for(var A in m)t[o][A]=m[A];s[o]=l?[]:{};var d=i[o];if(!this._isDynamic){var x={};for(var A in d)x[A]=d[A];i[o]=d=x}this._setupProperties(m,t[o],d,s[o],r)}else(typeof t[o]>"u"||r)&&(t[o]=a),l||(t[o]*=1),h?s[o]=i[o].slice().reverse():s[o]=t[o]||0}}},n.prototype.stop=function(){return this._isChainStopped||(this._isChainStopped=!0,this.stopChainedTweens()),this._isPlaying?(this._group&&this._group.remove(this),this._isPlaying=!1,this._isPaused=!1,this._onStopCallback&&this._onStopCallback(this._object),this):this},n.prototype.end=function(){return this._goToEnd=!0,this.update(1/0),this},n.prototype.pause=function(e){return e===void 0&&(e=ma()),this._isPaused||!this._isPlaying?this:(this._isPaused=!0,this._pauseStart=e,this._group&&this._group.remove(this),this)},n.prototype.resume=function(e){return e===void 0&&(e=ma()),!this._isPaused||!this._isPlaying?this:(this._isPaused=!1,this._startTime+=e-this._pauseStart,this._pauseStart=0,this._group&&this._group.add(this),this)},n.prototype.stopChainedTweens=function(){for(var e=0,t=this._chainedTweens.length;e<t;e++)this._chainedTweens[e].stop();return this},n.prototype.group=function(e){return e===void 0&&(e=Zu),this._group=e,this},n.prototype.delay=function(e){return e===void 0&&(e=0),this._delayTime=e,this},n.prototype.repeat=function(e){return e===void 0&&(e=0),this._initialRepeat=e,this._repeat=e,this},n.prototype.repeatDelay=function(e){return this._repeatDelayTime=e,this},n.prototype.yoyo=function(e){return e===void 0&&(e=!1),this._yoyo=e,this},n.prototype.easing=function(e){return e===void 0&&(e=mo.Linear.None),this._easingFunction=e,this},n.prototype.interpolation=function(e){return e===void 0&&(e=Ju.Linear),this._interpolationFunction=e,this},n.prototype.chain=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this._chainedTweens=e,this},n.prototype.onStart=function(e){return this._onStartCallback=e,this},n.prototype.onEveryStart=function(e){return this._onEveryStartCallback=e,this},n.prototype.onUpdate=function(e){return this._onUpdateCallback=e,this},n.prototype.onRepeat=function(e){return this._onRepeatCallback=e,this},n.prototype.onComplete=function(e){return this._onCompleteCallback=e,this},n.prototype.onStop=function(e){return this._onStopCallback=e,this},n.prototype.update=function(e,t){var i=this,s;if(e===void 0&&(e=ma()),t===void 0&&(t=!0),this._isPaused)return!0;var r,o=this._startTime+this._duration;if(!this._goToEnd&&!this._isPlaying){if(e>o)return!1;t&&this.start(e,!0)}if(this._goToEnd=!1,e<this._startTime)return!0;this._onStartCallbackFired===!1&&(this._onStartCallback&&this._onStartCallback(this._object),this._onStartCallbackFired=!0),this._onEveryStartCallbackFired===!1&&(this._onEveryStartCallback&&this._onEveryStartCallback(this._object),this._onEveryStartCallbackFired=!0);var a=e-this._startTime,l=this._duration+((s=this._repeatDelayTime)!==null&&s!==void 0?s:this._delayTime),c=this._duration+this._repeat*l,h=function(){if(i._duration===0||a>c)return 1;var m=Math.trunc(a/l),A=a-m*l,x=Math.min(A/i._duration,1);return x===0&&a===i._duration?1:x},d=h(),f=this._easingFunction(d);if(this._updateProperties(this._object,this._valuesStart,this._valuesEnd,f),this._onUpdateCallback&&this._onUpdateCallback(this._object,d),this._duration===0||a>=this._duration)if(this._repeat>0){var u=Math.min(Math.trunc((a-this._duration)/l)+1,this._repeat);isFinite(this._repeat)&&(this._repeat-=u);for(r in this._valuesStartRepeat)!this._yoyo&&typeof this._valuesEnd[r]=="string"&&(this._valuesStartRepeat[r]=this._valuesStartRepeat[r]+parseFloat(this._valuesEnd[r])),this._yoyo&&this._swapEndStartRepeatValues(r),this._valuesStart[r]=this._valuesStartRepeat[r];return this._yoyo&&(this._reversed=!this._reversed),this._startTime+=l*u,this._onRepeatCallback&&this._onRepeatCallback(this._object),this._onEveryStartCallbackFired=!1,!0}else{this._onCompleteCallback&&this._onCompleteCallback(this._object);for(var g=0,p=this._chainedTweens.length;g<p;g++)this._chainedTweens[g].start(this._startTime+this._duration,!1);return this._isPlaying=!1,!1}return!0},n.prototype._updateProperties=function(e,t,i,s){for(var r in i)if(t[r]!==void 0){var o=t[r]||0,a=i[r],l=Array.isArray(e[r]),c=Array.isArray(a),h=!l&&c;h?e[r]=this._interpolationFunction(a,s):typeof a=="object"&&a?this._updateProperties(e[r],o,a,s):(a=this._handleRelativeValue(o,a),typeof a=="number"&&(e[r]=o+(a-o)*s))}},n.prototype._handleRelativeValue=function(e,t){return typeof t!="string"?t:t.charAt(0)==="+"||t.charAt(0)==="-"?e+parseFloat(t):parseFloat(t)},n.prototype._swapEndStartRepeatValues=function(e){var t=this._valuesStartRepeat[e],i=this._valuesEnd[e];typeof i=="string"?this._valuesStartRepeat[e]=this._valuesStartRepeat[e]+parseFloat(i):this._valuesStartRepeat[e]=this._valuesEnd[e],this._valuesEnd[e]=t},n})();K0.nextId;var _n=Zu;_n.getAll.bind(_n),_n.removeAll.bind(_n),_n.add.bind(_n),_n.remove.bind(_n),_n.update.bind(_n);var Aa={Easing:mo,Tween:R2};const $0={type:"change"},ef={type:"start"},J0={type:"end"},Cc=new v.Ray,Z0=new v.Plane,k2=Math.cos(70*v.MathUtils.DEG2RAD),jt=new v.Vector3,vi=2*Math.PI,mt={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},tf=1e-6;class F2 extends v.Controls{constructor(e,t=null){super(e,t),this.state=mt.NONE,this.target=new v.Vector3,this.cursor=new v.Vector3,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:v.MOUSE.ROTATE,MIDDLE:v.MOUSE.DOLLY,RIGHT:v.MOUSE.PAN},this.touches={ONE:v.TOUCH.ROTATE,TWO:v.TOUCH.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._cursorStyle="auto",this._domElementKeyEvents=null,this._lastPosition=new v.Vector3,this._lastQuaternion=new v.Quaternion,this._lastTargetPosition=new v.Vector3,this._quat=new v.Quaternion().setFromUnitVectors(e.up,new v.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new v.Spherical,this._sphericalDelta=new v.Spherical,this._scale=1,this._panOffset=new v.Vector3,this._rotateStart=new v.Vector2,this._rotateEnd=new v.Vector2,this._rotateDelta=new v.Vector2,this._panStart=new v.Vector2,this._panEnd=new v.Vector2,this._panDelta=new v.Vector2,this._dollyStart=new v.Vector2,this._dollyEnd=new v.Vector2,this._dollyDelta=new v.Vector2,this._dollyDirection=new v.Vector3,this._mouse=new v.Vector2,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=U2.bind(this),this._onPointerDown=O2.bind(this),this._onPointerUp=N2.bind(this),this._onContextMenu=H2.bind(this),this._onMouseWheel=V2.bind(this),this._onKeyDown=Q2.bind(this),this._onTouchStart=j2.bind(this),this._onTouchMove=W2.bind(this),this._onMouseDown=z2.bind(this),this._onMouseMove=G2.bind(this),this._interceptControlDown=X2.bind(this),this._interceptControlUp=q2.bind(this),this.domElement!==null&&this.connect(this.domElement),this.update()}set cursorStyle(e){this._cursorStyle=e,e==="grab"?this.domElement.style.cursor="grab":this.domElement.style.cursor="auto"}get cursorStyle(){return this._cursorStyle}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents(),this.domElement.getRootNode().removeEventListener("keydown",this._interceptControlDown,{capture:!0}),this.domElement.style.touchAction="auto"}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){this._domElementKeyEvents!==null&&(this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null)}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent($0),this.update(),this.state=mt.NONE}pan(e,t){this._pan(e,t),this.update()}dollyIn(e){this._dollyIn(e),this.update()}dollyOut(e){this._dollyOut(e),this.update()}rotateLeft(e){this._rotateLeft(e),this.update()}rotateUp(e){this._rotateUp(e),this.update()}update(e=null){const t=this.object.position;jt.copy(t).sub(this.target),jt.applyQuaternion(this._quat),this._spherical.setFromVector3(jt),this.autoRotate&&this.state===mt.NONE&&this._rotateLeft(this._getAutoRotationAngle(e)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let i=this.minAzimuthAngle,s=this.maxAzimuthAngle;isFinite(i)&&isFinite(s)&&(i<-Math.PI?i+=vi:i>Math.PI&&(i-=vi),s<-Math.PI?s+=vi:s>Math.PI&&(s-=vi),i<=s?this._spherical.theta=Math.max(i,Math.min(s,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(i+s)/2?Math.max(i,this._spherical.theta):Math.min(s,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let r=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const o=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),r=o!=this._spherical.radius}if(jt.setFromSpherical(this._spherical),jt.applyQuaternion(this._quatInverse),t.copy(this.target).add(jt),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let o=null;if(this.object.isPerspectiveCamera){const a=jt.length();o=this._clampDistance(a*this._scale);const l=a-o;this.object.position.addScaledVector(this._dollyDirection,l),this.object.updateMatrixWorld(),r=!!l}else if(this.object.isOrthographicCamera){const a=new v.Vector3(this._mouse.x,this._mouse.y,0);a.unproject(this.object);const l=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),r=l!==this.object.zoom;const c=new v.Vector3(this._mouse.x,this._mouse.y,0);c.unproject(this.object),this.object.position.sub(c).add(a),this.object.updateMatrixWorld(),o=jt.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;o!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(o).add(this.object.position):(Cc.origin.copy(this.object.position),Cc.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(Cc.direction))<k2?this.object.lookAt(this.target):(Z0.setFromNormalAndCoplanarPoint(this.object.up,this.target),Cc.intersectPlane(Z0,this.target))))}else if(this.object.isOrthographicCamera){const o=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),o!==this.object.zoom&&(this.object.updateProjectionMatrix(),r=!0)}return this._scale=1,this._performCursorZoom=!1,r||this._lastPosition.distanceToSquared(this.object.position)>tf||8*(1-this._lastQuaternion.dot(this.object.quaternion))>tf||this._lastTargetPosition.distanceToSquared(this.target)>tf?(this.dispatchEvent($0),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?vi/60*this.autoRotateSpeed*e:vi/60/60*this.autoRotateSpeed}_getZoomScale(e){const t=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){jt.setFromMatrixColumn(t,0),jt.multiplyScalar(-e),this._panOffset.add(jt)}_panUp(e,t){this.screenSpacePanning===!0?jt.setFromMatrixColumn(t,1):(jt.setFromMatrixColumn(t,0),jt.crossVectors(this.object.up,jt)),jt.multiplyScalar(e),this._panOffset.add(jt)}_pan(e,t){const i=this.domElement;if(this.object.isPerspectiveCamera){const s=this.object.position;jt.copy(s).sub(this.target);let r=jt.length();r*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*r/i.clientHeight,this.object.matrix),this._panUp(2*t*r/i.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/i.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/i.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const i=this.domElement.getBoundingClientRect(),s=e-i.left,r=t-i.top,o=i.width,a=i.height;this._mouse.x=s/o*2-1,this._mouse.y=-(r/a)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(vi*this._rotateDelta.x/t.clientHeight),this._rotateUp(vi*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(vi*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-vi*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(vi*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-vi*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0;break}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._rotateStart.set(i,s)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panStart.set(i,s)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),i=e.pageX-t.x,s=e.pageY-t.y,r=Math.sqrt(i*i+s*s);this._dollyStart.set(0,r)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const i=this._getSecondPointerPosition(e),s=.5*(e.pageX+i.x),r=.5*(e.pageY+i.y);this._rotateEnd.set(s,r)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(vi*this._rotateDelta.x/t.clientHeight),this._rotateUp(vi*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panEnd.set(i,s)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),i=e.pageX-t.x,s=e.pageY-t.y,r=Math.sqrt(i*i+s*s);this._dollyEnd.set(0,r),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const o=(e.pageX+t.x)*.5,a=(e.pageY+t.y)*.5;this._updateZoomParameters(o,a)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId){this._pointers.splice(t,1);return}}_isTrackingPointer(e){for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return!0;return!1}_trackPointer(e){let t=this._pointerPositions[e.pointerId];t===void 0&&(t=new v.Vector2,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){const t=e.deltaMode,i={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:i.deltaY*=16;break;case 2:i.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(i.deltaY*=10),i}}function O2(n){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(n.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(n)&&(this._addPointer(n),n.pointerType==="touch"?this._onTouchStart(n):this._onMouseDown(n),this._cursorStyle==="grab"&&(this.domElement.style.cursor="grabbing")))}function U2(n){this.enabled!==!1&&(n.pointerType==="touch"?this._onTouchMove(n):this._onMouseMove(n))}function N2(n){switch(this._removePointer(n),this._pointers.length){case 0:this.domElement.releasePointerCapture(n.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(J0),this.state=mt.NONE,this._cursorStyle==="grab"&&(this.domElement.style.cursor="grab");break;case 1:const e=this._pointers[0],t=this._pointerPositions[e];this._onTouchStart({pointerId:e,pageX:t.x,pageY:t.y});break}}function z2(n){let e;switch(n.button){case 0:e=this.mouseButtons.LEFT;break;case 1:e=this.mouseButtons.MIDDLE;break;case 2:e=this.mouseButtons.RIGHT;break;default:e=-1}switch(e){case v.MOUSE.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(n),this.state=mt.DOLLY;break;case v.MOUSE.ROTATE:if(n.ctrlKey||n.metaKey||n.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(n),this.state=mt.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(n),this.state=mt.ROTATE}break;case v.MOUSE.PAN:if(n.ctrlKey||n.metaKey||n.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(n),this.state=mt.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(n),this.state=mt.PAN}break;default:this.state=mt.NONE}this.state!==mt.NONE&&this.dispatchEvent(ef)}function G2(n){switch(this.state){case mt.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(n);break;case mt.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(n);break;case mt.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(n);break}}function V2(n){this.enabled===!1||this.enableZoom===!1||this.state!==mt.NONE||(n.preventDefault(),this.dispatchEvent(ef),this._handleMouseWheel(this._customWheelEvent(n)),this.dispatchEvent(J0))}function Q2(n){this.enabled!==!1&&this._handleKeyDown(n)}function j2(n){switch(this._trackPointer(n),this._pointers.length){case 1:switch(this.touches.ONE){case v.TOUCH.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(n),this.state=mt.TOUCH_ROTATE;break;case v.TOUCH.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(n),this.state=mt.TOUCH_PAN;break;default:this.state=mt.NONE}break;case 2:switch(this.touches.TWO){case v.TOUCH.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(n),this.state=mt.TOUCH_DOLLY_PAN;break;case v.TOUCH.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(n),this.state=mt.TOUCH_DOLLY_ROTATE;break;default:this.state=mt.NONE}break;default:this.state=mt.NONE}this.state!==mt.NONE&&this.dispatchEvent(ef)}function W2(n){switch(this._trackPointer(n),this.state){case mt.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(n),this.update();break;case mt.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(n),this.update();break;case mt.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(n),this.update();break;case mt.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(n),this.update();break;default:this.state=mt.NONE}}function H2(n){this.enabled!==!1&&n.preventDefault()}function X2(n){n.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function q2(n){n.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}const ur=new v.Raycaster,ti=new v.Vector3,Ms=new v.Vector3,wt=new v.Quaternion,ex={X:new v.Vector3(1,0,0),Y:new v.Vector3(0,1,0),Z:new v.Vector3(0,0,1)},nf={type:"change"},tx={type:"mouseDown",mode:null},ix={type:"mouseUp",mode:null},nx={type:"objectChange"};class sx extends v.Controls{constructor(e,t=null){super(void 0,t);const i=new eD(this);this._root=i;const s=new tD;this._gizmo=s,i.add(s);const r=new iD;this._plane=r,i.add(r);const o=this;function a(b,y){let _=y;Object.defineProperty(o,b,{get:function(){return _!==void 0?_:y},set:function(S){_!==S&&(_=S,r[b]=S,s[b]=S,o.dispatchEvent({type:b+"-changed",value:S}),o.dispatchEvent(nf))}}),o[b]=y,r[b]=y,s[b]=y}a("camera",e),a("object",void 0),a("enabled",!0),a("axis",null),a("mode","translate"),a("translationSnap",null),a("rotationSnap",null),a("scaleSnap",null),a("space","world"),a("size",1),a("dragging",!1),a("showX",!0),a("showY",!0),a("showZ",!0),a("minX",-1/0),a("maxX",1/0),a("minY",-1/0),a("maxY",1/0),a("minZ",-1/0),a("maxZ",1/0);const l=new v.Vector3,c=new v.Vector3,h=new v.Quaternion,d=new v.Quaternion,f=new v.Vector3,u=new v.Quaternion,g=new v.Vector3,p=new v.Vector3,m=new v.Vector3,A=0,x=new v.Vector3;a("worldPosition",l),a("worldPositionStart",c),a("worldQuaternion",h),a("worldQuaternionStart",d),a("cameraPosition",f),a("cameraQuaternion",u),a("pointStart",g),a("pointEnd",p),a("rotationAxis",m),a("rotationAngle",A),a("eye",x),this._offset=new v.Vector3,this._startNorm=new v.Vector3,this._endNorm=new v.Vector3,this._cameraScale=new v.Vector3,this._parentPosition=new v.Vector3,this._parentQuaternion=new v.Quaternion,this._parentQuaternionInv=new v.Quaternion,this._parentScale=new v.Vector3,this._worldScaleStart=new v.Vector3,this._worldQuaternionInv=new v.Quaternion,this._worldScale=new v.Vector3,this._positionStart=new v.Vector3,this._quaternionStart=new v.Quaternion,this._scaleStart=new v.Vector3,this._getPointer=Y2.bind(this),this._onPointerDown=$2.bind(this),this._onPointerHover=K2.bind(this),this._onPointerMove=J2.bind(this),this._onPointerUp=Z2.bind(this),t!==null&&this.connect(t)}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointermove",this._onPointerHover),this.domElement.addEventListener("pointerup",this._onPointerUp),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerHover),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.domElement.style.touchAction="auto"}getHelper(){return this._root}pointerHover(e){if(this.object===void 0||this.dragging===!0)return;e!==null&&ur.setFromCamera(e,this.camera);const t=sf(this._gizmo.picker[this.mode],ur);t?this.axis=t.object.name:this.axis=null}pointerDown(e){if(!(this.object===void 0||this.dragging===!0||e!=null&&e.button!==0)&&this.axis!==null){e!==null&&ur.setFromCamera(e,this.camera);const t=sf(this._plane,ur,!0);t&&(this.object.updateMatrixWorld(),this.object.parent.updateMatrixWorld(),this._positionStart.copy(this.object.position),this._quaternionStart.copy(this.object.quaternion),this._scaleStart.copy(this.object.scale),this.object.matrixWorld.decompose(this.worldPositionStart,this.worldQuaternionStart,this._worldScaleStart),this.pointStart.copy(t.point).sub(this.worldPositionStart)),this.dragging=!0,tx.mode=this.mode,this.dispatchEvent(tx)}}pointerMove(e){const t=this.axis,i=this.mode,s=this.object;let r=this.space;if(i==="scale"?r="local":(t==="E"||t==="XYZE"||t==="XYZ")&&(r="world"),s===void 0||t===null||this.dragging===!1||e!==null&&e.button!==-1)return;e!==null&&ur.setFromCamera(e,this.camera);const o=sf(this._plane,ur,!0);if(o){if(this.pointEnd.copy(o.point).sub(this.worldPositionStart),i==="translate")this._offset.copy(this.pointEnd).sub(this.pointStart),r==="local"&&t!=="XYZ"&&this._offset.applyQuaternion(this._worldQuaternionInv),t.indexOf("X")===-1&&(this._offset.x=0),t.indexOf("Y")===-1&&(this._offset.y=0),t.indexOf("Z")===-1&&(this._offset.z=0),r==="local"&&t!=="XYZ"?this._offset.applyQuaternion(this._quaternionStart).divide(this._parentScale):this._offset.applyQuaternion(this._parentQuaternionInv).divide(this._parentScale),s.position.copy(this._offset).add(this._positionStart),this.translationSnap&&(r==="local"&&(s.position.applyQuaternion(wt.copy(this._quaternionStart).invert()),t.search("X")!==-1&&(s.position.x=Math.round(s.position.x/this.translationSnap)*this.translationSnap),t.search("Y")!==-1&&(s.position.y=Math.round(s.position.y/this.translationSnap)*this.translationSnap),t.search("Z")!==-1&&(s.position.z=Math.round(s.position.z/this.translationSnap)*this.translationSnap),s.position.applyQuaternion(this._quaternionStart)),r==="world"&&(s.parent&&s.position.add(ti.setFromMatrixPosition(s.parent.matrixWorld)),t.search("X")!==-1&&(s.position.x=Math.round(s.position.x/this.translationSnap)*this.translationSnap),t.search("Y")!==-1&&(s.position.y=Math.round(s.position.y/this.translationSnap)*this.translationSnap),t.search("Z")!==-1&&(s.position.z=Math.round(s.position.z/this.translationSnap)*this.translationSnap),s.parent&&s.position.sub(ti.setFromMatrixPosition(s.parent.matrixWorld)))),s.position.x=Math.max(this.minX,Math.min(this.maxX,s.position.x)),s.position.y=Math.max(this.minY,Math.min(this.maxY,s.position.y)),s.position.z=Math.max(this.minZ,Math.min(this.maxZ,s.position.z));else if(i==="scale"){if(t.search("XYZ")!==-1){let a=this.pointEnd.length()/this.pointStart.length();this.pointEnd.dot(this.pointStart)<0&&(a*=-1),Ms.set(a,a,a)}else ti.copy(this.pointStart),Ms.copy(this.pointEnd),ti.applyQuaternion(this._worldQuaternionInv),Ms.applyQuaternion(this._worldQuaternionInv),Ms.divide(ti),t.search("X")===-1&&(Ms.x=1),t.search("Y")===-1&&(Ms.y=1),t.search("Z")===-1&&(Ms.z=1);s.scale.copy(this._scaleStart).multiply(Ms),this.scaleSnap&&(t.search("X")!==-1&&(s.scale.x=Math.round(s.scale.x/this.scaleSnap)*this.scaleSnap||this.scaleSnap),t.search("Y")!==-1&&(s.scale.y=Math.round(s.scale.y/this.scaleSnap)*this.scaleSnap||this.scaleSnap),t.search("Z")!==-1&&(s.scale.z=Math.round(s.scale.z/this.scaleSnap)*this.scaleSnap||this.scaleSnap))}else if(i==="rotate"){this._offset.copy(this.pointEnd).sub(this.pointStart);const a=20/this.worldPosition.distanceTo(ti.setFromMatrixPosition(this.camera.matrixWorld));let l=!1;t==="XYZE"?(this.rotationAxis.copy(this._offset).cross(this.eye).normalize(),this.rotationAngle=this._offset.dot(ti.copy(this.rotationAxis).cross(this.eye))*a):(t==="X"||t==="Y"||t==="Z")&&(this.rotationAxis.copy(ex[t]),ti.copy(ex[t]),r==="local"&&ti.applyQuaternion(this.worldQuaternion),ti.cross(this.eye),ti.length()===0?l=!0:this.rotationAngle=this._offset.dot(ti.normalize())*a),(t==="E"||l)&&(this.rotationAxis.copy(this.eye),this.rotationAngle=this.pointEnd.angleTo(this.pointStart),this._startNorm.copy(this.pointStart).normalize(),this._endNorm.copy(this.pointEnd).normalize(),this.rotationAngle*=this._endNorm.cross(this._startNorm).dot(this.eye)<0?1:-1),this.rotationSnap&&(this.rotationAngle=Math.round(this.rotationAngle/this.rotationSnap)*this.rotationSnap),r==="local"&&t!=="E"&&t!=="XYZE"?(s.quaternion.copy(this._quaternionStart),s.quaternion.multiply(wt.setFromAxisAngle(this.rotationAxis,this.rotationAngle)).normalize()):(this.rotationAxis.applyQuaternion(this._parentQuaternionInv),s.quaternion.copy(wt.setFromAxisAngle(this.rotationAxis,this.rotationAngle)),s.quaternion.multiply(this._quaternionStart).normalize())}this.dispatchEvent(nf),this.dispatchEvent(nx)}}pointerUp(e){e!==null&&e.button!==0||(this.dragging&&this.axis!==null&&(ix.mode=this.mode,this.dispatchEvent(ix)),this.dragging=!1,this.axis=null)}dispose(){this.disconnect(),this._root.dispose()}attach(e){return this.object=e,this._root.visible=!0,this}detach(){return this.object=void 0,this.axis=null,this._root.visible=!1,this}reset(){this.enabled&&this.dragging&&(this.object.position.copy(this._positionStart),this.object.quaternion.copy(this._quaternionStart),this.object.scale.copy(this._scaleStart),this.dispatchEvent(nf),this.dispatchEvent(nx),this.pointStart.copy(this.pointEnd))}getRaycaster(){return ur}getMode(){return this.mode}setMode(e){this.mode=e}setTranslationSnap(e){this.translationSnap=e}setRotationSnap(e){this.rotationSnap=e}setScaleSnap(e){this.scaleSnap=e}setSize(e){this.size=e}setSpace(e){this.space=e}setColors(e,t,i,s){const r=this._gizmo.materialLib;r.xAxis.color.set(e),r.yAxis.color.set(t),r.zAxis.color.set(i),r.active.color.set(s),r.xAxisTransparent.color.set(e),r.yAxisTransparent.color.set(t),r.zAxisTransparent.color.set(i),r.activeTransparent.color.set(s),r.xAxis._color&&r.xAxis._color.set(e),r.yAxis._color&&r.yAxis._color.set(t),r.zAxis._color&&r.zAxis._color.set(i),r.active._color&&r.active._color.set(s),r.xAxisTransparent._color&&r.xAxisTransparent._color.set(e),r.yAxisTransparent._color&&r.yAxisTransparent._color.set(t),r.zAxisTransparent._color&&r.zAxisTransparent._color.set(i),r.activeTransparent._color&&r.activeTransparent._color.set(s)}}function Y2(n){if(this.domElement.ownerDocument.pointerLockElement)return{x:0,y:0,button:n.button};{const e=this.domElement.getBoundingClientRect();return{x:(n.clientX-e.left)/e.width*2-1,y:-(n.clientY-e.top)/e.height*2+1,button:n.button}}}function K2(n){if(this.enabled)switch(n.pointerType){case"mouse":case"pen":this.pointerHover(this._getPointer(n));break}}function $2(n){this.enabled&&(document.pointerLockElement||this.domElement.setPointerCapture(n.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.pointerHover(this._getPointer(n)),this.pointerDown(this._getPointer(n)))}function J2(n){this.enabled&&this.pointerMove(this._getPointer(n))}function Z2(n){this.enabled&&(this.domElement.releasePointerCapture(n.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.pointerUp(this._getPointer(n)))}function sf(n,e,t){const i=e.intersectObject(n,!0);for(let s=0;s<i.length;s++)if(i[s].object.visible||t)return i[s];return!1}const Mc=new v.Euler,At=new v.Vector3(0,1,0),rx=new v.Vector3(0,0,0),ox=new v.Matrix4,Ec=new v.Quaternion,Ic=new v.Quaternion,wn=new v.Vector3,ax=new v.Matrix4,xa=new v.Vector3(1,0,0),fr=new v.Vector3(0,1,0),ba=new v.Vector3(0,0,1),Tc=new v.Vector3,ya=new v.Vector3,va=new v.Vector3;class eD extends v.Object3D{constructor(e){super(),this.isTransformControlsRoot=!0,this.controls=e,this.visible=!1}updateMatrixWorld(e){const t=this.controls;t.object!==void 0&&(t.object.updateMatrixWorld(),t.object.parent===null?console.error("TransformControls: The attached 3D object must be a part of the scene graph."):t.object.parent.matrixWorld.decompose(t._parentPosition,t._parentQuaternion,t._parentScale),t.object.matrixWorld.decompose(t.worldPosition,t.worldQuaternion,t._worldScale),t._parentQuaternionInv.copy(t._parentQuaternion).invert(),t._worldQuaternionInv.copy(t.worldQuaternion).invert()),t.camera.updateMatrixWorld(),t.camera.matrixWorld.decompose(t.cameraPosition,t.cameraQuaternion,t._cameraScale),t.camera.isOrthographicCamera?t.camera.getWorldDirection(t.eye).negate():t.eye.copy(t.cameraPosition).sub(t.worldPosition).normalize(),super.updateMatrixWorld(e)}dispose(){this.traverse(function(e){e.geometry&&e.geometry.dispose(),e.material&&e.material.dispose()})}}class tD extends v.Object3D{constructor(){super(),this.isTransformControlsGizmo=!0,this.type="TransformControlsGizmo";const e=new v.MeshBasicMaterial({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),t=new v.LineBasicMaterial({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),i=e.clone();i.opacity=.15;const s=t.clone();s.opacity=.5;const r=e.clone();r.color.setHex(16711680);const o=e.clone();o.color.setHex(65280);const a=e.clone();a.color.setHex(255);const l=e.clone();l.color.setHex(16711680),l.opacity=.5;const c=e.clone();c.color.setHex(65280),c.opacity=.5;const h=e.clone();h.color.setHex(255),h.opacity=.5;const d=e.clone();d.opacity=.25;const f=e.clone();f.color.setHex(16776960),f.opacity=.25;const u=e.clone();u.color.setHex(16776960);const g=e.clone();g.color.setHex(7895160),this.materialLib={xAxis:r,yAxis:o,zAxis:a,active:u,xAxisTransparent:l,yAxisTransparent:c,zAxisTransparent:h,activeTransparent:f};const p=new v.CylinderGeometry(0,.04,.1,12);p.translate(0,.05,0);const m=new v.BoxGeometry(.08,.08,.08);m.translate(0,.04,0);const A=new v.BufferGeometry;A.setAttribute("position",new v.Float32BufferAttribute([0,0,0,1,0,0],3));const x=new v.CylinderGeometry(.0075,.0075,.5,3);x.translate(0,.25,0);function b(F,N){const H=new v.TorusGeometry(F,.0075,3,64,N*Math.PI*2);return H.rotateY(Math.PI/2),H.rotateX(Math.PI/2),H}function y(){const F=new v.BufferGeometry;return F.setAttribute("position",new v.Float32BufferAttribute([0,0,0,1,1,1],3)),F}const _={X:[[new v.Mesh(p,r),[.5,0,0],[0,0,-Math.PI/2]],[new v.Mesh(p,r),[-.5,0,0],[0,0,Math.PI/2]],[new v.Mesh(x,r),[0,0,0],[0,0,-Math.PI/2]]],Y:[[new v.Mesh(p,o),[0,.5,0]],[new v.Mesh(p,o),[0,-.5,0],[Math.PI,0,0]],[new v.Mesh(x,o)]],Z:[[new v.Mesh(p,a),[0,0,.5],[Math.PI/2,0,0]],[new v.Mesh(p,a),[0,0,-.5],[-Math.PI/2,0,0]],[new v.Mesh(x,a),null,[Math.PI/2,0,0]]],XYZ:[[new v.Mesh(new v.OctahedronGeometry(.1,0),d),[0,0,0]]],XY:[[new v.Mesh(new v.BoxGeometry(.15,.15,.01),h),[.15,.15,0]]],YZ:[[new v.Mesh(new v.BoxGeometry(.15,.15,.01),l),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new v.Mesh(new v.BoxGeometry(.15,.15,.01),c),[.15,0,.15],[-Math.PI/2,0,0]]]},S={X:[[new v.Mesh(new v.CylinderGeometry(.2,0,.6,4),i),[.3,0,0],[0,0,-Math.PI/2]],[new v.Mesh(new v.CylinderGeometry(.2,0,.6,4),i),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new v.Mesh(new v.CylinderGeometry(.2,0,.6,4),i),[0,.3,0]],[new v.Mesh(new v.CylinderGeometry(.2,0,.6,4),i),[0,-.3,0],[0,0,Math.PI]]],Z:[[new v.Mesh(new v.CylinderGeometry(.2,0,.6,4),i),[0,0,.3],[Math.PI/2,0,0]],[new v.Mesh(new v.CylinderGeometry(.2,0,.6,4),i),[0,0,-.3],[-Math.PI/2,0,0]]],XYZ:[[new v.Mesh(new v.OctahedronGeometry(.2,0),i)]],XY:[[new v.Mesh(new v.BoxGeometry(.2,.2,.01),i),[.15,.15,0]]],YZ:[[new v.Mesh(new v.BoxGeometry(.2,.2,.01),i),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new v.Mesh(new v.BoxGeometry(.2,.2,.01),i),[.15,0,.15],[-Math.PI/2,0,0]]]},C={START:[[new v.Mesh(new v.OctahedronGeometry(.01,2),s),null,null,null,"helper"]],END:[[new v.Mesh(new v.OctahedronGeometry(.01,2),s),null,null,null,"helper"]],DELTA:[[new v.Line(y(),s),null,null,null,"helper"]],X:[[new v.Line(A,s),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new v.Line(A,s),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new v.Line(A,s),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},D={XYZE:[[new v.Mesh(b(.5,1),g),null,[0,Math.PI/2,0]]],X:[[new v.Mesh(b(.5,.5),r)]],Y:[[new v.Mesh(b(.5,.5),o),null,[0,0,-Math.PI/2]]],Z:[[new v.Mesh(b(.5,.5),a),null,[0,Math.PI/2,0]]],E:[[new v.Mesh(b(.75,1),f),null,[0,Math.PI/2,0]]]},M={AXIS:[[new v.Line(A,s),[-1e3,0,0],null,[1e6,1,1],"helper"]]},I={XYZE:[[new v.Mesh(new v.SphereGeometry(.25,10,8),i)]],X:[[new v.Mesh(new v.TorusGeometry(.5,.1,4,24),i),[0,0,0],[0,-Math.PI/2,-Math.PI/2]]],Y:[[new v.Mesh(new v.TorusGeometry(.5,.1,4,24),i),[0,0,0],[Math.PI/2,0,0]]],Z:[[new v.Mesh(new v.TorusGeometry(.5,.1,4,24),i),[0,0,0],[0,0,-Math.PI/2]]],E:[[new v.Mesh(new v.TorusGeometry(.75,.1,2,24),i)]]},L={X:[[new v.Mesh(m,r),[.5,0,0],[0,0,-Math.PI/2]],[new v.Mesh(x,r),[0,0,0],[0,0,-Math.PI/2]],[new v.Mesh(m,r),[-.5,0,0],[0,0,Math.PI/2]]],Y:[[new v.Mesh(m,o),[0,.5,0]],[new v.Mesh(x,o)],[new v.Mesh(m,o),[0,-.5,0],[0,0,Math.PI]]],Z:[[new v.Mesh(m,a),[0,0,.5],[Math.PI/2,0,0]],[new v.Mesh(x,a),[0,0,0],[Math.PI/2,0,0]],[new v.Mesh(m,a),[0,0,-.5],[-Math.PI/2,0,0]]],XY:[[new v.Mesh(new v.BoxGeometry(.15,.15,.01),h),[.15,.15,0]]],YZ:[[new v.Mesh(new v.BoxGeometry(.15,.15,.01),l),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new v.Mesh(new v.BoxGeometry(.15,.15,.01),c),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new v.Mesh(new v.BoxGeometry(.1,.1,.1),d)]]},T={X:[[new v.Mesh(new v.CylinderGeometry(.2,0,.6,4),i),[.3,0,0],[0,0,-Math.PI/2]],[new v.Mesh(new v.CylinderGeometry(.2,0,.6,4),i),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new v.Mesh(new v.CylinderGeometry(.2,0,.6,4),i),[0,.3,0]],[new v.Mesh(new v.CylinderGeometry(.2,0,.6,4),i),[0,-.3,0],[0,0,Math.PI]]],Z:[[new v.Mesh(new v.CylinderGeometry(.2,0,.6,4),i),[0,0,.3],[Math.PI/2,0,0]],[new v.Mesh(new v.CylinderGeometry(.2,0,.6,4),i),[0,0,-.3],[-Math.PI/2,0,0]]],XY:[[new v.Mesh(new v.BoxGeometry(.2,.2,.01),i),[.15,.15,0]]],YZ:[[new v.Mesh(new v.BoxGeometry(.2,.2,.01),i),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new v.Mesh(new v.BoxGeometry(.2,.2,.01),i),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new v.Mesh(new v.BoxGeometry(.2,.2,.2),i),[0,0,0]]]},R={X:[[new v.Line(A,s),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new v.Line(A,s),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new v.Line(A,s),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]};function E(F){const N=new v.Object3D;for(const H in F)for(let V=F[H].length;V--;){const U=F[H][V][0].clone(),q=F[H][V][1],G=F[H][V][2],j=F[H][V][3],oe=F[H][V][4];U.name=H,U.tag=oe,q&&U.position.set(q[0],q[1],q[2]),G&&U.rotation.set(G[0],G[1],G[2]),j&&U.scale.set(j[0],j[1],j[2]),U.updateMatrix();const fe=U.geometry.clone();fe.applyMatrix4(U.matrix),U.geometry=fe,U.renderOrder=1/0,U.position.set(0,0,0),U.rotation.set(0,0,0),U.scale.set(1,1,1),N.add(U)}return N}this.gizmo={},this.picker={},this.helper={},this.add(this.gizmo.translate=E(_)),this.add(this.gizmo.rotate=E(D)),this.add(this.gizmo.scale=E(L)),this.add(this.picker.translate=E(S)),this.add(this.picker.rotate=E(I)),this.add(this.picker.scale=E(T)),this.add(this.helper.translate=E(C)),this.add(this.helper.rotate=E(M)),this.add(this.helper.scale=E(R)),this.picker.translate.visible=!1,this.picker.rotate.visible=!1,this.picker.scale.visible=!1}updateMatrixWorld(e){const i=(this.mode==="scale"?"local":this.space)==="local"?this.worldQuaternion:Ic;this.gizmo.translate.visible=this.mode==="translate",this.gizmo.rotate.visible=this.mode==="rotate",this.gizmo.scale.visible=this.mode==="scale",this.helper.translate.visible=this.mode==="translate",this.helper.rotate.visible=this.mode==="rotate",this.helper.scale.visible=this.mode==="scale";let s=[];s=s.concat(this.picker[this.mode].children),s=s.concat(this.gizmo[this.mode].children),s=s.concat(this.helper[this.mode].children);for(let r=0;r<s.length;r++){const o=s[r];o.visible=!0,o.rotation.set(0,0,0),o.position.copy(this.worldPosition);let a;if(this.camera.isOrthographicCamera?a=(this.camera.top-this.camera.bottom)/this.camera.zoom:a=this.worldPosition.distanceTo(this.cameraPosition)*Math.min(1.9*Math.tan(Math.PI*this.camera.fov/360)/this.camera.zoom,7),o.scale.set(1,1,1).multiplyScalar(a*this.size/4),o.tag==="helper"){o.visible=!1,o.name==="AXIS"?(o.visible=!!this.axis,this.axis==="X"&&(wt.setFromEuler(Mc.set(0,0,0)),o.quaternion.copy(i).multiply(wt),Math.abs(At.copy(xa).applyQuaternion(i).dot(this.eye))>.9&&(o.visible=!1)),this.axis==="Y"&&(wt.setFromEuler(Mc.set(0,0,Math.PI/2)),o.quaternion.copy(i).multiply(wt),Math.abs(At.copy(fr).applyQuaternion(i).dot(this.eye))>.9&&(o.visible=!1)),this.axis==="Z"&&(wt.setFromEuler(Mc.set(0,Math.PI/2,0)),o.quaternion.copy(i).multiply(wt),Math.abs(At.copy(ba).applyQuaternion(i).dot(this.eye))>.9&&(o.visible=!1)),this.axis==="XYZE"&&(wt.setFromEuler(Mc.set(0,Math.PI/2,0)),At.copy(this.rotationAxis),o.quaternion.setFromRotationMatrix(ox.lookAt(rx,At,fr)),o.quaternion.multiply(wt),o.visible=this.dragging),this.axis==="E"&&(o.visible=!1)):o.name==="START"?(o.position.copy(this.worldPositionStart),o.visible=this.dragging):o.name==="END"?(o.position.copy(this.worldPosition),o.visible=this.dragging):o.name==="DELTA"?(o.position.copy(this.worldPositionStart),o.quaternion.copy(this.worldQuaternionStart),ti.set(1e-10,1e-10,1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1),ti.applyQuaternion(this.worldQuaternionStart.clone().invert()),o.scale.copy(ti),o.visible=this.dragging):(o.quaternion.copy(i),this.dragging?o.position.copy(this.worldPositionStart):o.position.copy(this.worldPosition),this.axis&&(o.visible=this.axis.search(o.name)!==-1));continue}o.quaternion.copy(i),this.mode==="translate"||this.mode==="scale"?(o.name==="X"&&Math.abs(At.copy(xa).applyQuaternion(i).dot(this.eye))>.99&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="Y"&&Math.abs(At.copy(fr).applyQuaternion(i).dot(this.eye))>.99&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="Z"&&Math.abs(At.copy(ba).applyQuaternion(i).dot(this.eye))>.99&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="XY"&&Math.abs(At.copy(ba).applyQuaternion(i).dot(this.eye))<.2&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="YZ"&&Math.abs(At.copy(xa).applyQuaternion(i).dot(this.eye))<.2&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="XZ"&&Math.abs(At.copy(fr).applyQuaternion(i).dot(this.eye))<.2&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1)):this.mode==="rotate"&&(Ec.copy(i),At.copy(this.eye).applyQuaternion(wt.copy(i).invert()),o.name.search("E")!==-1&&o.quaternion.setFromRotationMatrix(ox.lookAt(this.eye,rx,fr)),o.name==="X"&&(wt.setFromAxisAngle(xa,Math.atan2(-At.y,At.z)),wt.multiplyQuaternions(Ec,wt),o.quaternion.copy(wt)),o.name==="Y"&&(wt.setFromAxisAngle(fr,Math.atan2(At.x,At.z)),wt.multiplyQuaternions(Ec,wt),o.quaternion.copy(wt)),o.name==="Z"&&(wt.setFromAxisAngle(ba,Math.atan2(At.y,At.x)),wt.multiplyQuaternions(Ec,wt),o.quaternion.copy(wt))),o.visible=o.visible&&(o.name.indexOf("X")===-1||this.showX),o.visible=o.visible&&(o.name.indexOf("Y")===-1||this.showY),o.visible=o.visible&&(o.name.indexOf("Z")===-1||this.showZ),o.visible=o.visible&&(o.name.indexOf("E")===-1||this.showX&&this.showY&&this.showZ),o.material._color=o.material._color||o.material.color.clone(),o.material._opacity=o.material._opacity||o.material.opacity,o.material.color.copy(o.material._color),o.material.opacity=o.material._opacity,this.enabled&&this.axis&&(o.name===this.axis?(o.material.color.copy(this.materialLib.active.color),o.material.opacity=1):this.axis.split("").some(function(l){return o.name===l})&&(o.material.color.copy(this.materialLib.active.color),o.material.opacity=1))}super.updateMatrixWorld(e)}}class iD extends v.Mesh{constructor(){super(new v.PlaneGeometry(1e5,1e5,2,2),new v.MeshBasicMaterial({visible:!1,wireframe:!0,side:v.DoubleSide,transparent:!0,opacity:.1,toneMapped:!1})),this.isTransformControlsPlane=!0,this.type="TransformControlsPlane"}updateMatrixWorld(e){let t=this.space;switch(this.position.copy(this.worldPosition),this.mode==="scale"&&(t="local"),Tc.copy(xa).applyQuaternion(t==="local"?this.worldQuaternion:Ic),ya.copy(fr).applyQuaternion(t==="local"?this.worldQuaternion:Ic),va.copy(ba).applyQuaternion(t==="local"?this.worldQuaternion:Ic),At.copy(ya),this.mode){case"translate":case"scale":switch(this.axis){case"X":At.copy(this.eye).cross(Tc),wn.copy(Tc).cross(At);break;case"Y":At.copy(this.eye).cross(ya),wn.copy(ya).cross(At);break;case"Z":At.copy(this.eye).cross(va),wn.copy(va).cross(At);break;case"XY":wn.copy(va);break;case"YZ":wn.copy(Tc);break;case"XZ":At.copy(va),wn.copy(ya);break;case"XYZ":case"E":wn.set(0,0,0);break}break;case"rotate":default:wn.set(0,0,0)}wn.length()===0?this.quaternion.copy(this.cameraQuaternion):(ax.lookAt(ti.set(0,0,0),wn,At),this.quaternion.setFromRotationMatrix(ax)),super.updateMatrixWorld(e)}}class nD extends v.DataTextureLoader{constructor(e){super(e),this.type=v.HalfFloatType}parse(e){const o=function(D,M){switch(D){case 1:throw new Error("THREE.HDRLoader: Read Error: "+(M||""));case 2:throw new Error("THREE.HDRLoader: Write Error: "+(M||""));case 3:throw new Error("THREE.HDRLoader: Bad File Format: "+(M||""));default:case 4:throw new Error("THREE.HDRLoader: Memory Error: "+(M||""))}},d=function(D,M,I){M=M||1024;let T=D.pos,R=-1,E=0,F="",N=String.fromCharCode.apply(null,new Uint16Array(D.subarray(T,T+128)));for(;0>(R=N.indexOf(`
|
|
4942
4942
|
`))&&E<M&&T<D.byteLength;)F+=N,E+=N.length,T+=128,N+=String.fromCharCode.apply(null,new Uint16Array(D.subarray(T,T+128)));return-1<R?(D.pos+=E+R+1,F+N.slice(0,R)):!1},f=function(D){const M=/^#\?(\S+)/,I=/^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/,L=/^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/,T=/^\s*FORMAT=(\S+)\s*$/,R=/^\s*\-Y\s+(\d+)\s+\+X\s+(\d+)\s*$/,E={valid:0,string:"",comments:"",programtype:"RGBE",format:"",gamma:1,exposure:1,width:0,height:0};let F,N;for((D.pos>=D.byteLength||!(F=d(D)))&&o(1,"no header found"),(N=F.match(M))||o(3,"bad initial token"),E.valid|=1,E.programtype=N[1],E.string+=F+`
|
|
4943
4943
|
`;F=d(D),F!==!1;){if(E.string+=F+`
|
|
4944
4944
|
`,F.charAt(0)==="#"){E.comments+=F+`
|
|
@@ -5257,7 +5257,7 @@ void main() {
|
|
|
5257
5257
|
#include <tonemapping_fragment>
|
|
5258
5258
|
#include <colorspace_fragment>
|
|
5259
5259
|
|
|
5260
|
-
}`};const gx={turbidity:10,rayleigh:3,mieCoefficient:.005,mieDirectionalG:.7,elevation:2,azimuth:180,exposure:.5,orthoExposureScale:1.5,cloudCoverage:.4,cloudDensity:.4,cloudElevation:.5,showSunDisc:!0},lf="sunrise_clear",mx=.2,cf=[{id:"sunrise_clear",names:["晴朗日出","晴朗日出","Clear Sunrise"],params:{turbidity:4,rayleigh:1.8,mieCoefficient:.004,mieDirectionalG:.72,elevation:8,azimuth:105,exposure:.42,cloudCoverage:.12,cloudDensity:.2,cloudElevation:.45,showSunDisc:!0}},{id:"morning_mist",names:["晨雾薄云","晨雾薄云","Misty Morning"],params:{turbidity:14,rayleigh:2.4,mieCoefficient:.018,mieDirectionalG:.68,elevation:12,azimuth:120,exposure:.35,cloudCoverage:.45,cloudDensity:.5,cloudElevation:.35,showSunDisc:!0}},{id:"noon_clear",names:["晴空正午","晴空正午","Clear Noon"],params:{turbidity:2,rayleigh:1,mieCoefficient:.002,mieDirectionalG:.82,elevation:68,azimuth:180,exposure:.58,cloudCoverage:.05,cloudDensity:.12,cloudElevation:.55,showSunDisc:!0}},{id:"afternoon_cloudy",names:["午后多云","午后多云","Cloudy Afternoon"],params:{turbidity:8,rayleigh:1.7,mieCoefficient:.008,mieDirectionalG:.74,elevation:42,azimuth:220,exposure:.5,cloudCoverage:.48,cloudDensity:.42,cloudElevation:.52,showSunDisc:!0}},{id:"sunset_glow",names:["落日晚霞","落日晚霞","Sunset Glow"],params:{turbidity:10,rayleigh:2,mieCoefficient:.006,mieDirectionalG:.7,elevation:6,azimuth:245,exposure:.6,cloudCoverage:.3,cloudDensity:.36,cloudElevation:.5,showSunDisc:!0}},{id:"blue_hour",names:["暮色蓝调","暮色蓝调","Blue Hour"],params:{turbidity:7,rayleigh:1.2,mieCoefficient:.003,mieDirectionalG:.76,elevation:-4,azimuth:255,exposure:.22,cloudCoverage:.2,cloudDensity:.24,cloudElevation:.48,showSunDisc:!1}},{id:"overcast_day",names:["阴天白昼","阴天白昼","Overcast Day"],params:{turbidity:20,rayleigh:2,mieCoefficient:.02,mieDirectionalG:.6,elevation:32,azimuth:180,exposure:.38,cloudCoverage:.86,cloudDensity:.68,cloudElevation:.4,showSunDisc:!1}},{id:"storm_rain",names:["暴雨雷云","暴雨雷云","Storm Rain"],params:{turbidity:19,rayleigh:.9,mieCoefficient:.03,mieDirectionalG:.58,elevation:18,azimuth:210,exposure:.2,cloudCoverage:.95,cloudDensity:.9,cloudElevation:.28,showSunDisc:!1}},{id:"snow_day",names:["雪天漫射","雪天漫射","Snowy Day"],params:{turbidity:15,rayleigh:2.6,mieCoefficient:.012,mieDirectionalG:.65,elevation:24,azimuth:170,exposure:.5,cloudCoverage:.78,cloudDensity:.72,cloudElevation:.43,showSunDisc:!1}},{id:"moonlit_night",names:["月夜星空","月夜星空","Moonlit Night"],params:{turbidity:4,rayleigh:.35,mieCoefficient:.001,mieDirectionalG:.82,elevation:-18,azimuth:160,exposure:.14,cloudCoverage:.1,cloudDensity:.14,cloudElevation:.55,showSunDisc:!1}}],Ax=cf.reduce((n,e)=>(n[e.id]=e,n),{}),xx=2e6;class yD{engine;sky=null;sun=new w.Vector3;params={...gx,...Ax[lf].params};currentPreset=lf;currentIntensity=mx;currentEnvironmentTarget=null;skyScale=45e4;skyName="bim_engine_sky";savedCameraFar=null;previousBackground=null;previousEnvironment=null;previousBackgroundIntensity=1;previousEnvironmentIntensity=1;previousToneMapping=w.NoToneMapping;previousToneMappingExposure=1;hasCapturedSceneState=!1;constructor(e){this.engine=e}activate(){if(!this.engine?.scene)return;if(this.sky){this.sky.visible=!0,this._captureSceneState(),this._expandCameraFarForSky(),this._applyParamsToSky();return}const e=new Dc;e.scale.setScalar(this.skyScale),e.name=this.skyName,this.sky=e,this.engine.scene.add(e),this._captureSceneState(),this._expandCameraFarForSky(),this.engine.renderer&&(this.engine.renderer.toneMapping=w.ACESFilmicToneMapping,this.engine.scene.background=null),this._applyParamsToSky()}close(e=!0){this.sky&&(this._restoreCameraFar(),this._restoreSceneState(e),e?(this.engine?.scene?.remove(this.sky),this.sky.material.dispose(),this.sky.geometry.dispose(),this.sky=null):this.sky.visible=!1)}isActive(){return this.sky!=null&&this.engine?.scene?.children?.includes(this.sky)}getParams(){return{...this.params}}setParams(e){Object.assign(this.params,e),this._applyParamsToSky(),this.engine?.renderer&&(e.exposure!==void 0||e.orthoExposureScale!==void 0)&&(this.engine.renderer.toneMappingExposure=this._getEffectiveExposure())}setPreset(e){const t=Ax[e];t&&(this.currentPreset=e,this.params={...gx,...t.params},this._applyParamsToSky(),this.engine?.renderer&&(this.engine.renderer.toneMappingExposure=this._getEffectiveExposure()))}getCurrentPreset(){return this.currentPreset}getPresetNames(){return cf.map(e=>e.id)}getPresetList(){return cf.map(e=>({id:e.id,names:[...e.names],params:{...e.params}}))}setIntensity(e){if(this.currentIntensity=Math.max(e,0),!(!this.sky?.visible||!this.engine?.scene)){if(!this.currentEnvironmentTarget){this._refreshEnvironmentMap();return}this.engine.scene.environmentIntensity=this.currentIntensity}}getIntensity(){return this.currentIntensity}update(e){if(!this.sky?.visible)return;const t=this.sky.material.uniforms;t&&"time"in t&&(t.time.value=e??performance.now()*.001),this.engine?.renderer&&(this.engine.renderer.toneMappingExposure=this._getEffectiveExposure())}_isOrthographicCamera(){const e=this.engine?.camera;return e!=null&&e.type==="OrthographicCamera"}_getEffectiveExposure(){const e=this.params.exposure;return this._isOrthographicCamera()?e*this.params.orthoExposureScale:e}_expandCameraFarForSky(){const e=this.engine?.camera;if(!e||typeof e.far!="number")return;const t=e.far;t>=xx||(this.savedCameraFar==null&&(this.savedCameraFar=t),e.far=xx,typeof e.updateProjectionMatrix=="function"&&e.updateProjectionMatrix())}_restoreCameraFar(){if(this.savedCameraFar==null||!this.engine?.camera)return;const e=this.engine.camera;typeof e.far=="number"&&(e.far=this.savedCameraFar,typeof e.updateProjectionMatrix=="function"&&e.updateProjectionMatrix(),this.savedCameraFar=null)}_applyParamsToSky(){if(!this.sky)return;const e=this.sky.material.uniforms;this._setUniformValue(e,"turbidity",this.params.turbidity),this._setUniformValue(e,"rayleigh",this.params.rayleigh),this._setUniformValue(e,"mieCoefficient",this.params.mieCoefficient),this._setUniformValue(e,"mieDirectionalG",this.params.mieDirectionalG),this._setUniformValue(e,"cloudCoverage",this.params.cloudCoverage),this._setUniformValue(e,"cloudDensity",this.params.cloudDensity),this._setUniformValue(e,"cloudElevation",this.params.cloudElevation),this._setUniformValue(e,"showSunDisc",this.params.showSunDisc?1:0);const t=w.MathUtils.degToRad(90-this.params.elevation),i=w.MathUtils.degToRad(this.params.azimuth);this.sun.setFromSphericalCoords(1,t,i),this._setUniformValue(e,"sunPosition",this.sun),this.engine?.renderer&&(this.engine.renderer.toneMapping=w.ACESFilmicToneMapping,this.engine.renderer.toneMappingExposure=this._getEffectiveExposure(),this.sky.visible&&this._refreshEnvironmentMap())}_captureSceneState(){this.hasCapturedSceneState||!this.engine?.scene||(this.previousBackground=this.engine.scene.background,this.previousEnvironment=this.engine.scene.environment,this.previousBackgroundIntensity=this.engine.scene.backgroundIntensity??1,this.previousEnvironmentIntensity=this.engine.scene.environmentIntensity??1,this.previousToneMapping=this.engine.renderer?.toneMapping??w.NoToneMapping,this.previousToneMappingExposure=this.engine.renderer?.toneMappingExposure??1,this.hasCapturedSceneState=!0)}_restoreSceneState(e){!this.hasCapturedSceneState||!this.engine?.scene||(this.engine.scene.background=this.previousBackground,this.engine.scene.environment=this.previousEnvironment,this.engine.scene.backgroundIntensity=this.previousBackgroundIntensity,this.engine.scene.environmentIntensity=this.previousEnvironmentIntensity,this.engine.renderer&&(this.engine.renderer.toneMapping=this.previousToneMapping,this.engine.renderer.toneMappingExposure=this.previousToneMappingExposure),e&&(this._disposeEnvironmentTarget(),this.previousBackground=null,this.previousEnvironment=null,this.previousBackgroundIntensity=1,this.previousEnvironmentIntensity=1,this.previousToneMapping=w.NoToneMapping,this.previousToneMappingExposure=1,this.hasCapturedSceneState=!1))}_refreshEnvironmentMap(){if(!this.sky||!this.engine?.renderer||!this.engine?.scene)return;this._disposeEnvironmentTarget();const e=new w.Scene,t=this.sky.clone();t.material=this.sky.material.clone(),e.add(t);const i=new w.PMREMGenerator(this.engine.renderer);this.currentEnvironmentTarget=i.fromScene(e,0,.1,this.skyScale*2),i.dispose(),this.engine.scene.background=null,this.engine.scene.environment=this.currentEnvironmentTarget.texture,this.engine.scene.environmentIntensity=this.currentIntensity,t.material.dispose()}_disposeEnvironmentTarget(){this.currentEnvironmentTarget?.dispose(),this.currentEnvironmentTarget=null}_setUniformValue(e,t,i){const s=e[t];s&&(i instanceof w.Vector3&&typeof s.value?.copy=="function"?s.value.copy(i):s.value=i)}}class vD{engine;defaultSettings;settings;environmentApplyVersion=0;constructor(e){this.engine=e,this.defaultSettings=this._buildDefaultSettingsFromModules(),this.settings=this._clone(this.defaultSettings)}init(){this.defaultSettings=this._buildDefaultSettingsFromModules(),this.settings=this._clone(this.defaultSettings)}getSettings(){return this._syncSettingsFromModules(),this._clone(this.settings)}getPresetLists(){const e=this.engine.ground?.getGroundList()||[],t=this.engine.hdr?.getHdrList()||[],i=this.engine.skyManager?.getPresetList()||[];return{ground:e.map(s=>this._toPresetItem(s)),hdr:t.map(s=>this._toPresetItem(s)),sky:i.map(s=>this._toPresetItem(s))}}async setSettings(e){e.render&&(Object.assign(this.settings.render,e.render),this._applyRenderSettings(this.settings.render)),e.display&&(Object.assign(this.settings.display,e.display),this._applyDisplaySettings(this.settings.display)),e.environment&&(this._mergeEnvironmentSettings(e.environment),await this._applyEnvironmentSettings(this._clone(this.settings.environment)))}async resetToDefault(){this.settings=this._clone(this.defaultSettings),this._applyRenderSettings(this.settings.render),this._applyDisplaySettings(this.settings.display),await this._applyEnvironmentSettings(this._clone(this.settings.environment))}setRenderMode(e){this.settings.render.mode=e,this.engine.engineModelModule?.switchModel(e)}setContrast(e){this.settings.render.contrast=e,this.engine.engineModelModule?.setContrastValue(.5+e/100)}setSaturation(e){this.settings.render.saturation=e,this.engine.engineModelModule?.setSaturationValue(.5+e/100)}setShadowIntensity(e){this.settings.render.shadowIntensity=e,this._updateDirectionalLight(t=>{t.shadow.intensity=e/100*2})}setLightIntensity(e){this.settings.render.lightIntensity=e,this.setAmbientLightIntensity(e/100)}setGTAOIntensity(e){this.settings.render.gtaoIntensity=e,this.engine.engineModelModule?.setGTAOIntensity(e/100)}setShowEdge(e){this.settings.display.showEdge=e,e?this.engine.modelEdge?.active():this.engine.modelEdge?.disActive()}setEdgeOpacity(e){this.settings.display.edgeOpacity=e,this.engine.modelEdge?.setOpacity(e/100)}setShowGrid(e){this.settings.display.showGrid=e,e?this.engine.grid?.show():this.engine.grid?.hide()}setShowLevel(e){this.settings.display.showLevel=e,e?this.engine.level?.show():this.engine.level?.hide()}setShowGround(e){this.settings.display.showGround=e,e?this.engine.ground?.show():this.engine.ground?.hide()}setGroundId(e){this.settings.display.groundId=e,this.engine.ground?.setGround(e)}setGroundHeight(e){this.settings.display.groundHeight=e,this.engine.ground?.setHeight(e)}async setEnvironmentType(e){this.settings.environment.type=e,await this._applyEnvironmentSettings(this._clone(this.settings.environment))}async setHdrId(e){this.settings.environment.hdrId=e,this.settings.environment.type==="hdr"&&await this._applyEnvironmentSettings(this._clone(this.settings.environment))}setHdrIntensity(e){this.settings.environment.hdrIntensity=e,this.settings.environment.type==="hdr"&&this.engine.hdr?.setIntensity(e/100)}setSkyPreset(e){this.settings.environment.skyPreset=e,this.settings.environment.skyParams={},this.settings.environment.type==="sky"&&this.engine.skyManager?.setPreset(e)}setSkyParams(e){this.settings.environment.skyParams=this._clone(e),this.settings.environment.type==="sky"&&this.engine.skyManager?.setParams(this.settings.environment.skyParams)}setSkyIntensity(e){this.settings.environment.skyIntensity=e,this.settings.environment.type==="sky"&&this.engine.skyManager?.setIntensity(e/100)}setAmbientLightIntensity(e){this.engine.renderer.toneMappingExposure=2*e}_syncSettingsFromModules(){this.settings=this._readCurrentSettingsFromModules()}_buildDefaultSettingsFromModules(){const e=this.engine.composerModule?.saturationPass?.uniforms?.saturation?.value,t=this.engine.composerModule?.saturationPass?.uniforms?.contrast?.value,i=this.engine.composerModule?.gtaoPass?.blendIntensity,s=this.engine.renderer?.toneMappingExposure,r=this.engine.modelEdge?.getOpacity?.(),o=this.engine.hdr?.getCurrentHdrId?.()??Sn,a=this.engine.hdr?.getIntensity?.(),l=this.engine.skyManager?.getIntensity?.(),c=this.engine.skyManager?.getCurrentPreset?.()??lf,h=this.engine.skyManager?.isActive?.()===!0;return{render:{mode:this._toRenderMode(this.engine.engineModelModule?.getCurrentMode?.()),contrast:this._uniformToPercent(t,Vm),saturation:this._uniformToPercent(e,Gm),shadowIntensity:this._shadowToPercent(this._getDirectionalLightShadowIntensity(),_c),lightIntensity:this._exposureToPercent(s,Pm),gtaoIntensity:this._unitToPercent(i,zm)},display:{showEdge:this.engine.modelEdge?.isEnabled?.()??af,edgeOpacity:this._unitToPercent(r,px),showGrid:this.engine.grid?.getVisible?.()??rf,showLevel:this.engine.level?.getVisible?.()??fx,showGround:this.engine.ground?.getVisible?.()??dx,groundId:this.engine.ground?.getCurrentId?.()??cx,groundHeight:this.engine.ground?.getHeight?.()??hx},environment:{type:h?"sky":o!==Sn?"hdr":"none",hdrId:o,hdrIntensity:this._unitToPercent(a,ux),skyPreset:c,skyParams:{},skyIntensity:this._unitToPercent(l,mx)}}}_readCurrentSettingsFromModules(){const e=this.engine.composerModule?.saturationPass?.uniforms?.saturation?.value,t=this.engine.composerModule?.saturationPass?.uniforms?.contrast?.value,i=this.engine.composerModule?.gtaoPass?.blendIntensity,s=this.engine.renderer?.toneMappingExposure,r=this.engine.modelEdge?.getOpacity?.(),o=this.engine.hdr?.getCurrentHdrId?.()??this.settings.environment.hdrId,a=this.engine.hdr?.getIntensity?.(),l=this.engine.skyManager?.getIntensity?.(),c=this.engine.skyManager?.getCurrentPreset?.()??this.settings.environment.skyPreset,h=this.engine.skyManager?.getParams?.(),d=this.engine.skyManager?.isActive?.()===!0;return{render:{mode:this._toRenderMode(this.engine.engineModelModule?.getCurrentMode?.()??this.settings.render.mode),contrast:this._uniformToPercent(t,this.settings.render.contrast/100+.5),saturation:this._uniformToPercent(e,this.settings.render.saturation/100+.5),shadowIntensity:this._shadowToPercent(this._getDirectionalLightShadowIntensity(),this.settings.render.shadowIntensity/50),lightIntensity:this._exposureToPercent(s,this.settings.render.lightIntensity/50),gtaoIntensity:this._unitToPercent(i,this.settings.render.gtaoIntensity/100)},display:{showEdge:this.engine.modelEdge?.isEnabled?.()??this.settings.display.showEdge,edgeOpacity:this._unitToPercent(r,this.settings.display.edgeOpacity/100),showGrid:this.engine.grid?.getVisible?.()??this.settings.display.showGrid,showLevel:this.engine.level?.getVisible?.()??this.settings.display.showLevel,showGround:this.engine.ground?.getVisible?.()??this.settings.display.showGround,groundId:this.engine.ground?.getCurrentId?.()??this.settings.display.groundId,groundHeight:this.engine.ground?.getHeight?.()??this.settings.display.groundHeight},environment:{type:d?"sky":o!==Sn?"hdr":"none",hdrId:o,hdrIntensity:this._unitToPercent(a,this.settings.environment.hdrIntensity/100),skyPreset:c,skyParams:h?this._clone(h):this._clone(this.settings.environment.skyParams),skyIntensity:this._unitToPercent(l,this.settings.environment.skyIntensity/100)}}}_toRenderMode(e){return e==="simple"||e==="balance"||e==="advanced"?e:q0}_uniformToPercent(e,t){const i=typeof e=="number"?e:t;return this._clampPercent((i-.5)*100)}_shadowToPercent(e,t){const i=typeof e=="number"?e:t;return this._clampPercent(i*50)}_exposureToPercent(e,t){const i=typeof e=="number"?e:t;return this._clampPercent(i*50)}_unitToPercent(e,t){const i=typeof e=="number"?e:t;return this._clampPercent(i*100)}_clampPercent(e){return Math.min(100,Math.max(0,Math.round(e)))}_getDirectionalLightShadowIntensity(){const e=this.engine.scene?.children?.filter(i=>i instanceof w.DirectionalLight);return!e||e.length===0?_c:(e.find(i=>i.castShadow)??e[0]).shadow?.intensity??_c}_applyRenderSettings(e){this.setRenderMode(e.mode),this.setContrast(e.contrast),this.setSaturation(e.saturation),this.setShadowIntensity(e.shadowIntensity),this.setLightIntensity(e.lightIntensity),this.setGTAOIntensity(e.gtaoIntensity)}_applyDisplaySettings(e){this.setShowEdge(e.showEdge),this.setEdgeOpacity(e.edgeOpacity),this.setShowGrid(e.showGrid),this.setShowLevel(e.showLevel),this.setShowGround(e.showGround),this.setGroundId(e.groundId),this.setGroundHeight(e.groundHeight)}async _applyEnvironmentSettings(e){const t=++this.environmentApplyVersion;if(await this.engine.hdr?.setHdr(Sn),t===this.environmentApplyVersion&&(this.engine.skyManager?.close(!0),t===this.environmentApplyVersion))switch(e.type){case"none":break;case"hdr":if(e.hdrId!==Sn){if(await this.engine.hdr?.setHdr(e.hdrId),t!==this.environmentApplyVersion){this._applyEnvironmentSettings(this._clone(this.settings.environment));return}this.engine.hdr?.setIntensity(e.hdrIntensity/100)}break;case"sky":this.engine.skyManager?.activate(),this.engine.skyManager?.setPreset(e.skyPreset),Object.keys(e.skyParams).length>0&&this.engine.skyManager?.setParams(this._clone(e.skyParams)),this.engine.skyManager?.setIntensity(e.skyIntensity/100);break}}_updateDirectionalLight(e){const t=this.engine.scene?.children.find(i=>i instanceof w.DirectionalLight);t&&e(t)}_mergeEnvironmentSettings(e){Object.assign(this.settings.environment,e),e.skyPreset!==void 0&&e.skyParams===void 0&&(this.settings.environment.skyParams={}),e.skyParams!==void 0&&(this.settings.environment.skyParams=this._clone(e.skyParams))}_toPresetItem(e){const t=Array.isArray(e.names)?[...e.names]:[];return{id:e.id,name:t[0]??e.id,names:t}}_clone(e){return JSON.parse(JSON.stringify(e))}}function $n(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(n){var e=Math.random()*16|0,t=n=="x"?e:e&3|8;return t.toString(16)})}class Jn{engine;handelBehaved;setting;constructor(e){this.engine=e,this.handelBehaved=wu(e),this.handelBehaved.init(this,null),this.setting={unit:"m",precision:3}}getSetting(){return this.setting}saveSetting(e){this.setting=e}active(){this.handelBehaved.active()}disActive(){this.handelBehaved.disActive()}getMeasureText(e,t){if(e==null)return null;let i=this.setting.unit,s=i;return t==1?i=="mm"?e=e*1e3:i=="cm"?e=e*100:i=="dm"?e=e*10:i=="m"?e=e*1:i=="km"&&(e=e*.001):t==2&&(i=="mm"?e=e*1e3*1e3:i=="cm"?e=e*100*100:i=="dm"?e=e*10*10:i=="m"?e=e*1*1:i=="km"&&(e=e*.001*.001),s=s+"²"),e.toFixed(this.setting.precision)+" "+s}cancelCurrentSelectedAnnotation(){let e=this.engine.measure.annotationData;for(let t in e)e[t].forEach(i=>{i.highlight==!0&&(i.highlight=!1,i.container.classList.remove("Hight"),i.container.getElementsByTagName("svg")[0].classList.remove("Hight"))})}handelKeyEscDown(){this.cancelCurrentSelectedAnnotation();let e=this.engine.measure.annotationData;for(let t in e)for(let i=e[t].length-1;i>=0;i--){let s=e[t][i];s.isSelect==!0&&(s.container.remove(),e[t].splice(i,1))}this.engine.measure.clearAllPoints()}handelKeyDeleteDown(){let e=this.engine.measure.annotationData;for(let t in e)for(let i=e[t].length-1;i>=0;i--){let s=e[t][i];s.highlight==!0&&(s.container.remove(),e[t].splice(i,1))}}clearHighlight(){let e=this.engine.measure.annotationData;for(let t in e)e[t].forEach(i=>{i.highlight=!1,i.container.classList.remove("Hight"),i.container.getElementsByTagName("svg")[0].classList.remove("Hight")})}drawNormalAnnotation(){let e=this;this.engine.measure.annotationData.normalAnnotation.forEach(g=>{u(g)}),this.engine.measure.annotationData.elevationAnnotation.forEach(g=>{f(g)}),this.engine.measure.annotationData.coordinateAnnotation.forEach(g=>{d(g)}),this.engine.measure.annotationData.angleAnnotation.forEach(g=>{l(g)}),this.engine.measure.annotationData.areaAnnotation.forEach(g=>{c(g)}),this.engine.measure.annotationData.slopeAnnotation.forEach(g=>{h(g)});function l(g){if(g.container==null){let C=['<svg class="measureSvg">','<circle class="measurePointer" cx="50" cy="50" r="5" fill="#f99d0b" />','<circle class="measurePointer" cx="50" cy="50" r="5" fill="#f99d0b" />','<circle class="measurePointer" cx="50" cy="50" r="5" fill="#f99d0b" />','<polyline class="measureLine" stroke="orange" stroke-width="2" points="0,0 0,0" style="fill: none; opacity: 1;"/>','<polyline class="measureLine" stroke="orange" stroke-width="2" points="0,0 0,0" style="fill: none; opacity: 1;"/>','<rect x="0" y="0" width="100" height="25" class="measureBack" />','<text x="50" y="16" text-anchor="middle" class="measureLabel">'+g.text+"</text>","</svg>"].join("");g.container=document.createElement("div"),g.container.className="angle-annotation",g.container.id=g.id,g.container.style.pointerEvents="none",g.container.innerHTML=C,e.engine.measure.annotationContainer.appendChild(g.container),g.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),g.container.getElementsByTagName("svg")[0].classList.add("Hight"),g.highlight=!0,e.engine.events.trigger(Et.MeasureClick,g)}),g.isSelect&&(g.container.getElementsByTagName("svg")[0].classList.add("Hight"),g.highlight=!0)}let p=new lt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(g.point1),m=new lt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(g.point2),A=new lt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(g.point3),x=e.engine.reactBoundingClientRect.left,b=e.engine.reactBoundingClientRect.top;p.x+=x,p.y+=b,m.x+=x,m.y+=b,A.x+=x,A.y+=b;let y=g.container;y.getElementsByTagName("circle")[0].setAttribute("cx",p.x),y.getElementsByTagName("circle")[0].setAttribute("cy",p.y),y.getElementsByTagName("circle")[1].setAttribute("cx",m.x),y.getElementsByTagName("circle")[1].setAttribute("cy",m.y),y.getElementsByTagName("circle")[2].setAttribute("cx",A.x),y.getElementsByTagName("circle")[2].setAttribute("cy",A.y),y.getElementsByTagName("polyline")[0].setAttribute("points",p.x+","+p.y+" "+m.x+","+m.y),y.getElementsByTagName("polyline")[1].setAttribute("points",m.x+","+m.y+" "+A.x+","+A.y);let _=m.x,S=m.y-30;y.getElementsByTagName("rect")[0].setAttribute("x",_-40),y.getElementsByTagName("rect")[0].setAttribute("y",S-12.5),y.getElementsByTagName("text")[0].setAttribute("x",_),y.getElementsByTagName("text")[0].setAttribute("y",S+4),y.getElementsByTagName("text")[0].innerHTML=g.text,y.style.top="0px",y.style.left="0px"}function c(g){if(g.container==null){let D=['<svg class="measureSvg">','<polygon fill="rgba(0, 0, 255, 0.1)" stroke="orange" stroke-width="2" points="" style="opacity: 0.3;"/>','<polyline class="measureLine" stroke="orange" stroke-width="2" points="" style="fill: none; opacity: 1;"/>','<rect x="0" y="0" width="100" height="25" class="measureBack" />','<text x="50" y="16" text-anchor="middle" class="measureLabel"> '+e.getMeasureText(g.text,2)+"</text>","</svg>"].join("");g.container=document.createElement("div"),g.container.className="area-annotation",g.container.id=g.id,g.container.innerHTML=D,e.engine.measure.annotationContainer.appendChild(g.container),g.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),g.container.getElementsByTagName("svg")[0].classList.add("Hight"),g.highlight=!0,e.engine.events.trigger(Et.MeasureClick,g)}),g.isSelect&&(g.container.getElementsByTagName("svg")[0].classList.add("Hight"),g.highlight=!0)}if(!g.points||g.points.length<3)return;let p=e.engine.reactBoundingClientRect.left,m=e.engine.reactBoundingClientRect.top,A=[],x=0,b=0;for(let D=0;D<g.points.length;D++){let M=new lt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(g.points[D]);M.x+=p,M.y+=m,A.push(M),x+=M.x,b+=M.y}x=x/A.length,b=b/A.length;let y=A.map(D=>D.x+","+D.y).join(" "),_=g.container;_.getElementsByTagName("polygon")[0].setAttribute("points",y),_.getElementsByTagName("polyline")[0].setAttribute("points",y);let S=x,C=b;_.getElementsByTagName("rect")[0].setAttribute("x",S-40),_.getElementsByTagName("rect")[0].setAttribute("y",C-12.5),_.getElementsByTagName("text")[0].setAttribute("x",S+10),_.getElementsByTagName("text")[0].setAttribute("y",C+4),_.getElementsByTagName("text")[0].innerHTML=e.getMeasureText(g.text,2),_.style.top="0px",_.style.left="0px"}function h(g){if(g.container==null){let S=['<svg class="measureSvg">',"<defs>",'<marker id="slope-arrow-'+g.id+'" markerWidth="10" markerHeight="10" refX="9" refY="3" orient="auto" markerUnits="strokeWidth">','<path class="measureLine" d="M0,0 L0,6 L9,3 z"/>',"</marker>","</defs>",'<polyline class="measureLine" stroke="orange" stroke-width="2" points="0,0 0,0" marker-end="url(#slope-arrow-'+g.id+')" style="fill: none; opacity: 1;"/>','<rect x="0" y="0" width="100" height="25" class="measureBack" />','<text x="50" y="16" text-anchor="middle" class="measureLabel"> '+g.text+"</text>","</svg>"].join("");g.container=document.createElement("div"),g.container.className="slope-annotation",g.container.id=g.id,g.container.innerHTML=S,e.engine.measure.annotationContainer.appendChild(g.container),g.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),g.container.getElementsByTagName("svg")[0].classList.add("Hight"),g.highlight=!0,e.engine.events.trigger(Et.MeasureClick,g)}),g.isSelect&&(g.container.getElementsByTagName("svg")[0].classList.add("Hight"),g.highlight=!0)}let p=new lt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(g.point1),m=new lt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(g.point2),A=e.engine.reactBoundingClientRect.left,x=e.engine.reactBoundingClientRect.top;p.x+=A,p.y+=x,m.x+=A,m.y+=x;let b=g.container;b.getElementsByTagName("polyline")[0].setAttribute("points",p.x+","+p.y+" "+m.x+","+m.y);let y=(p.x+m.x)/2,_=(p.y+m.y)/2-30;b.getElementsByTagName("rect")[0].setAttribute("x",y-50),b.getElementsByTagName("rect")[0].setAttribute("y",_-12.5),b.getElementsByTagName("text")[0].setAttribute("x",y),b.getElementsByTagName("text")[0].setAttribute("y",_+4),b.getElementsByTagName("text")[0].innerHTML=g.text,b.style.top="0px",b.style.left="0px"}function d(g){if(g.container==null){let C=['<svg class="measureSvg">','<circle class="measurePointer" cx="0" cy="0" r="5" fill="#f99d0b" />','<rect x="0" y="-25" width="100" height="25" class="measureBack" />','<text x="50" y="-11" text-anchor="middle" class="measureLabel"> X: '+e.getMeasureText(g.textX,1)+"</text>",'<rect x="0" y="-10" width="100" height="25" class="measureBack" />','<text x="50" y="25" text-anchor="middle" class="measureLabel"> Y: '+e.getMeasureText(-g.textZ,1)+"</text>",'<rect x="0" y="10" width="100" height="25" class="measureBack" />','<text x="50" y="51" text-anchor="middle" class="measureLabel"> Z: '+e.getMeasureText(g.textY,1)+"</text>","</svg>"].join("");g.container=document.createElement("div"),g.container.className="coordinate-annotation",g.container.id=g.id,g.container.style.position="absolute",g.container.style.pointerEvents="none",g.container.innerHTML=C,e.engine.measure.annotationContainer.appendChild(g.container),g.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),g.container.getElementsByTagName("svg")[0].classList.add("Hight"),g.highlight=!0,e.engine.events.trigger(Et.MeasureClick,g)}),g.isSelect&&(g.container.getElementsByTagName("svg")[0].classList.add("Hight"),g.highlight=!0)}let p=g.container,m=new lt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(g.point),A=e.engine.reactBoundingClientRect.left,x=e.engine.reactBoundingClientRect.top;m.x+=A,m.y+=x,p.style.top="0px",p.style.left="0px";let b=p.getElementsByTagName("circle")[0];b&&(b.setAttribute("cx",m.x),b.setAttribute("cy",m.y));let y=p.getElementsByTagName("rect"),_=p.getElementsByTagName("text"),S=-55;y[0]&&(y[0].setAttribute("x",m.x+10),y[0].setAttribute("y",m.y+10+S)),_[0]&&(_[0].setAttribute("x",m.x+10+50),_[0].setAttribute("y",m.y+10+16+S)),y[1]&&(y[1].setAttribute("x",m.x+10),y[1].setAttribute("y",m.y+10+30+S)),_[1]&&(_[1].setAttribute("x",m.x+10+50),_[1].setAttribute("y",m.y+10+46+S)),y[2]&&(y[2].setAttribute("x",m.x+10),y[2].setAttribute("y",m.y+10+60+S)),_[2]&&(_[2].setAttribute("x",m.x+10+50),_[2].setAttribute("y",m.y+10+76+S)),_[0]&&(_[0].innerHTML="X: "+e.getMeasureText(g.textX,1)),_[1]&&(_[1].innerHTML="Y: "+e.getMeasureText(-g.textZ,1)),_[2]&&(_[2].innerHTML="Z: "+e.getMeasureText(g.textY,1))}function f(g){if(g.container==null){let b=['<svg width="100" height="50" class="measureSvg">','<rect x="0" y="0" width="100" height="25" class="measureBack" />','<text x="50" y="16" text-anchor="middle" class="measureLabel"> '+e.getMeasureText(g.text,1)+"</text>",'<polyline class="measureLine" stroke-width="2" points="80,32 0,32 16,48 32,32" style="fill: none; opacity: 1;"/>',"</svg>"].join("");g.container=document.createElement("div"),g.container.className="elevation-annotation",g.container.id=g.id,g.container.style.position="absolute",g.container.style.pointerEvents="none",g.container.innerHTML=b,e.engine.measure.annotationContainer.appendChild(g.container),g.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),g.container.getElementsByTagName("svg")[0].classList.add("Hight"),g.highlight=!0,e.engine.events.trigger(Et.MeasureClick,g)}),g.isSelect&&(g.container.getElementsByTagName("svg")[0].classList.add("Hight"),g.highlight=!0)}let p=g.container,m=new lt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(g.point),A=e.engine.reactBoundingClientRect.left,x=e.engine.reactBoundingClientRect.top;p.style.top=m.y+x-48+"px",p.style.left=m.x+A-16+"px",p.getElementsByTagName("text")[0].innerHTML=e.getMeasureText(g.text,1)}function u(g){if(g.container==null){let y=['<svg class="measureSvg">','<circle class="measurePointer" cx="50" cy="50" r="5" fill="#f99d0b" />','<circle class="measurePointer" cx="50" cy="50" r="5" fill="#f99d0b" />','<polyline class="measureLine" stroke="orange" stroke-width="2" points="80,32 0,32" style="fill: none; opacity: 1;"/>','<rect x="0" y="0" width="100" height="25" class="measureBack" />','<text x="50" y="16" text-anchor="middle" class="measureLabel"> '+e.getMeasureText(g.text,1)+"</text>","</svg>"].join("");g.container=document.createElement("div"),g.container.className="normal-annotation",g.container.id=g.id,g.container.innerHTML=y,e.engine.measure.annotationContainer.appendChild(g.container),g.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),g.container.getElementsByTagName("svg")[0].classList.add("Hight"),g.highlight=!0,e.engine.events.trigger(Et.MeasureClick,g)}),g.isSelect&&(g.container.getElementsByTagName("svg")[0].classList.add("Hight"),g.highlight=!0)}let p=g.container;if(g.point1==null||g.point2==null){p.style.display="none";return}else p.style.display="block";let m=new lt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(g.point1),A=new lt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(g.point2),x=e.engine.reactBoundingClientRect.left,b=e.engine.reactBoundingClientRect.top;m.x+=x,m.y+=b,A.x+=x,A.y+=b,p.getElementsByTagName("polyline")[0].setAttribute("points",m.x+","+m.y+" "+A.x+","+A.y),p.getElementsByTagName("circle")[0].setAttribute("cx",m.x),p.getElementsByTagName("circle")[0].setAttribute("cy",m.y),p.getElementsByTagName("circle")[1].setAttribute("cx",A.x),p.getElementsByTagName("circle")[1].setAttribute("cy",A.y),p.getElementsByTagName("rect")[0].setAttribute("x",m.x*.5+A.x*.5-40),p.getElementsByTagName("rect")[0].setAttribute("y",m.y*.5+A.y*.5-12.5),p.getElementsByTagName("text")[0].setAttribute("x",m.x*.5+A.x*.5+50-40),p.getElementsByTagName("text")[0].setAttribute("y",m.y*.5+A.y*.5+16-12.5),p.getElementsByTagName("text")[0].innerHTML=e.getMeasureText(g.text,1),p.style.top="0px",p.style.left="0px"}}}class _D{engine;isActive=!1;tools;points=[];behavior;catchDir=0;type="point";constructor(e){this.engine=e,this.tools=new Jn(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.isActive=!0,this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1;let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}setDirection(e){this.catchDir=e}setSelectType(e){this.type=e}getMeshesMinMaxY(e){if(!Array.isArray(e)||e.length===0)return null;let t=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY;for(let s=0;s<e.length;s++){const r=e[s];if(!r)continue;typeof r.updateMatrixWorld=="function"&&r.updateMatrixWorld(!0);const o=new w.Box3().setFromObject(r);!Number.isFinite(o.min.y)||!Number.isFinite(o.max.y)||(o.min.y<t&&(t=o.min.y),o.max.y>i&&(i=o.max.y))}return!Number.isFinite(t)||!Number.isFinite(i)?null:{minY:t,maxY:i}}handleMouseClick(e){if(e.catch==null)return;let t=e.catch.point;if(this.type=="element"){let r=this.engine.interactionModule.getCatchMeshs(e);var i=this.getMeshesMinMaxY(r);this.catchDir==0?t.set(t.x,i?.minY,t.z):t.set(t.x,i?.maxY,t.z)}else t=e.catch.point;if(this.points.length==0){this.engine.measure.tools.clearHighlight(),this.points.push(t);return}let s=this.engine.measure.annotationData.normalAnnotation.find(r=>r.isSelect==!0);s!=null&&(s.isSelect=!1)}handleMouseMove(e){if(e.catch==null||this.points.length==0)return;let t=this.engine.measure.annotationData.normalAnnotation.find(s=>s.isSelect==!0);t==null&&(t={text:null,id:$n(),isSelect:!0,type:"clear-height"},this.engine.measure.annotationData.normalAnnotation.push(t));let i=e.catch;if(this.type=="element"){let s=e.catch.point.clone();s.set(s.x,this.points[0].y,s.z);let r=new w.Raycaster(s.add(new w.Vector3(0,.01,0)),new w.Vector3(0,this.catchDir==0?-1:1,0));i.point=this.points[0];const o=this.engine.clipping?.filterIntersectionsByClipping(this.engine.octreeBox.rayInterationModel(r))??this.engine.octreeBox.rayInterationModel(r);if(o.length===0){t.point2=null;return}t.point1=s,t.point2=o[0].point,t.text=t.point1.clone().distanceTo(t.point2.clone()),this.engine.events.trigger(Et.MeasureChanged,t)}else{let s=new w.Raycaster(e.catch.point.clone().add(new w.Vector3(0,.01,0)),new w.Vector3(0,this.catchDir==0?-1:1,0));const r=this.engine.clipping?.filterIntersectionsByClipping(this.engine.octreeBox.rayInterationModel(s))??this.engine.octreeBox.rayInterationModel(s);if(r.length===0){t.point2=null;return}t.point1=i.point,t.point2=r[0].point,t.text=t.point1.clone().distanceTo(t.point2.clone()),this.engine.events.trigger(Et.MeasureChanged,t)}}}class wD{engine;tools;isActive=!1;points=[];behavior;constructor(e){this.engine=e,this.tools=new Jn(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.isActive=!0,this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1;let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.isActive=!1,this.engine.handelBehaved.disActive()}clearAllPoints(){this.points=[]}handleMouseClick(e){if(e.catch==null)return;let t=e.catch;if(this.points.length==0)this.engine.measure.tools.clearHighlight(),this.points.push(t.point);else if(this.points.length==1){let i=this.engine.measure.annotationData.normalAnnotation.find(s=>s.isSelect==!0);if(i==null)return;i.point2=t.point,i.isSelect=!1,this.points=[],this.engine.events.trigger(Et.MeasureChanged,i)}}handleMouseMove(e){if(e.catch==null)return;let t=e.catch;if(t!=null&&this.points.length==1){let i=this.engine.measure.annotationData.normalAnnotation.find(s=>s.isSelect==!0);i==null&&(i={id:$n(),point1:this.points[0].clone(),point2:t.point.clone(),text:this.points[0].clone().distanceTo(t.point.clone()),type:"distance",isSelect:!0},this.engine.measure.annotationData.normalAnnotation.push(i)),i.point2=t.point,i.text=i.point1.clone().distanceTo(i.point2.clone())}}}class SD{engine;isActive=!1;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new Jn(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.isActive=!0,this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1;let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}handleMouseClick(e){if(e.catch==null)return;if(this.points.length==0){this.engine.measure.tools.clearHighlight(),this.points.push(e.catch.point);return}let t=this.engine.measure.annotationData.normalAnnotation.find(i=>i.isSelect==!0);t!=null&&(t.isSelect=!1)}handleMouseMove(e){if(e.catch==null||this.points.length==0)return;let t=this.engine.measure.annotationData.normalAnnotation.find(o=>o.isSelect==!0);t==null&&(t={text:null,id:$n(),isSelect:!0,type:"clear-distance"},this.engine.measure.annotationData.normalAnnotation.push(t));let i=new w.Raycaster(e.catch.point.clone().add(e.catch.face.normal.clone().setLength(.01)),e.catch.face.normal);const s=this.engine.clipping?.filterIntersectionsByClipping(this.engine.octreeBox.rayInterationModel(i))??this.engine.octreeBox.rayInterationModel(i);if(s.length==0){t.point2=null;return}let r=e.catch;t.point1=r.point,t.point2=s[0].point,t.text=t.point1.clone().distanceTo(t.point2.clone()),this.engine.events.trigger(Et.MeasureChanged,t)}}class CD{engine;isActive=!1;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new Jn(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1,this.isActive=!0;let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}handleMouseMove(e){if(e.catch==null)return;let t=this.engine.measure.annotationData.elevationAnnotation.find(i=>i.isSelect==!0);t==null&&(t={id:$n(),point:e.catch.point.clone(),text:e.catch.point.y,isSelect:!0,type:"elevation"},this.engine.measure.annotationData.elevationAnnotation.push(t)),t.point=e.catch.point.clone(),t.text=e.catch.point.y}handleMouseClick(e){if(e.catch==null)return;this.engine.measure.tools.clearHighlight();let t=this.engine.measure.annotationData.elevationAnnotation.find(i=>i.isSelect==!0);t!=null&&(t.isSelect=!1,t.point=e.catch.point.clone(),t.text=e.catch.point.y,this.engine.events.trigger(Et.MeasureChanged,t))}}class MD{engine;isActive=!1;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new Jn(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1,this.isActive=!0;let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}handleMouseUp(e){this.engine.deviceType!="PC"&&this.createMeasure()}handleMouseMove(e){if(e.catch==null)return;let t=this.engine.measure.annotationData.coordinateAnnotation.find(i=>i.isSelect==!0);t!=null&&(t.point=e.catch.point.clone(),t.textX=e.catch.point.x,t.textY=e.catch.point.y,t.textZ=e.catch.point.z)}handleMouseClick(e){if(e.catch==null)return;this.engine.measure.tools.clearHighlight();let t=this.engine.measure.annotationData.coordinateAnnotation.find(i=>i.isSelect==!0);if(t==null){t={id:$n(),point:e.catch.point.clone(),text:Math.round(e.catch.point.y)+" m",isSelect:!0,type:"point"},this.engine.measure.annotationData.coordinateAnnotation.push(t);return}t.point=e.catch.point.clone(),t.textX=e.catch.point.x,t.textY=e.catch.point.y,t.textZ=e.catch.point.z,t.isSelect=!1,this.engine.events.trigger(Et.MeasureChanged,t)}createMeasure(){let e=this.engine.measure.annotationData.coordinateAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1,this.engine.events.trigger(Et.MeasureChanged,e))}}class ED{engine;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new Jn(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1;let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.behavior?.disActive()}clearAllPoints(){this.points=[]}calculateAngle(e,t,i){const s=new w.Vector3().subVectors(e,t),r=new w.Vector3().subVectors(i,t),o=s.length(),a=r.length();if(o===0||a===0)return 0;const c=s.dot(r)/(o*a),h=Math.max(-1,Math.min(1,c));return Math.acos(h)*(180/Math.PI)}handleMouseClick(e){if(e.catch==null)return;let t=e.catch;if(this.points.length==0)this.engine.measure.tools.clearHighlight(),this.points.push(t.point);else if(this.points.length==1)this.points.push(t.point);else if(this.points.length==2){let i=this.engine.measure.annotationData.angleAnnotation.find(s=>s.isSelect==!0);if(i==null)return;i.point3=t.point.clone(),i.angle=this.calculateAngle(i.point1,i.point2,i.point3),i.text=i.angle.toFixed(2)+"°",i.isSelect=!1,i.type="angle",this.points=[],this.engine.events.trigger(Et.MeasureChanged,i)}}handleMouseMove(e){if(e.catch!=null&&this.points.length!=1&&this.points.length==2){let t=this.engine.measure.annotationData.angleAnnotation.find(i=>i.isSelect==!0);t==null&&(t={id:$n(),point1:this.points[0].clone(),point2:this.points[1].clone(),point3:e.catch.point.clone(),angle:0,text:"0.00°",isSelect:!0,type:"angle"},this.engine.measure.annotationData.angleAnnotation.push(t)),t.point3=e.catch.point.clone(),t.angle=this.calculateAngle(t.point1,t.point2,t.point3),t.text=t.angle.toFixed(2)+"°",console.log("角度",t.text)}}}class ID{engine;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new Jn(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1;let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.behavior?.disActive()}clearAllPoints(){this.points=[]}calculateArea(e){if(e.length<3)return 0;const t=e.length,i=new w.Vector3(0,0,0);for(let s=0;s<t;s++){const r=(s+1)%t;i.x+=(e[s].y-e[r].y)*(e[s].z+e[r].z),i.y+=(e[s].z-e[r].z)*(e[s].x+e[r].x),i.z+=(e[s].x-e[r].x)*(e[s].y+e[r].y)}return i.length()/2}handleRightMouseClick(){this.finishMeasure()}handleMouseClick(e){if(e.catch==null)return;let t=e.catch;if(this.points.push(t.point.clone()),this.points.length>=3){let i=this.engine.measure.annotationData.areaAnnotation.find(s=>s.isSelect==!0);i==null?(i={id:$n(),points:this.points.map(s=>s.clone()),area:0,text:0,isSelect:!0,type:"area"},this.engine.measure.annotationData.areaAnnotation.push(i)):(this.points.push(t.point.clone()),i.points=this.points.map(s=>s.clone())),i.area=this.calculateArea(i.points),i.text=i.area,console.log("面积",i.text)}else this.engine.measure.tools.clearHighlight()}handleMouseMove(e){if(e.catch!=null&&this.points.length>=2){let t=this.engine.measure.annotationData.areaAnnotation.find(i=>i.isSelect==!0);if(t==null){if(this.points.length>=2){let i=this.points.map(s=>s.clone());i.push(e.catch.point.clone()),i.length>=3&&(t={id:$n(),points:i,area:0,text:0,isSelect:!0,type:"area"},this.engine.measure.annotationData.areaAnnotation.push(t))}}else if(t.points.length>0){const i=t.points.length-1;t.points[i]=e.catch.point.clone()}else t.points=this.points.map(i=>i.clone()),t.points.push(e.catch.point.clone());t&&t.points.length>=3&&(t.area=this.calculateArea(t.points),t.text=t.area)}}handelKeyEnterDown(){this.finishMeasure()}finishMeasure(){this.points=this.points.slice(0,this.points.length-1);let e=this.engine.measure.annotationData.areaAnnotation.find(t=>t.isSelect==!0);e!=null&&e.points.length>3?(e.points.length>this.points.length&&(e.points=this.points.map(t=>t.clone())),e.area=this.calculateArea(e.points),e.text=e.area,e.isSelect=!1,this.points=[],this.engine.events.trigger(Et.MeasureChanged,e)):this.engine.measure.tools.handelKeyEscDown()}}class TD{engine;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new Jn(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1;let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.behavior?.disActive()}clearAllPoints(){this.points=[]}calculateSlope(e,t){const i=t.y-e.y,s=t.x-e.x,r=t.z-e.z,o=Math.sqrt(s*s+r*r);if(o===0)return{percentage:0,angle:0,heightDiff:i,horizontalDist:0,type:"slope"};const a=i/o*100,c=Math.atan(i/o)*(180/Math.PI);return{percentage:a,angle:c,heightDiff:i,horizontalDist:o,type:"slope"}}handleMouseClick(e){if(e.catch==null)return;let t=e.catch;if(this.points.length==0)this.engine.measure.tools.clearHighlight(),this.points.push(t.point);else if(this.points.length==1){let i=this.engine.measure.annotationData.slopeAnnotation.find(r=>r.isSelect==!0);if(i==null)return;console.log("进来了"),i.point2=t.point.clone();const s=this.calculateSlope(i.point1,i.point2);i.slopePercentage=s.percentage,i.slopeAngle=s.angle,i.heightDiff=s.heightDiff,i.horizontalDist=s.horizontalDist,i.text=s.percentage.toFixed(2)+"%",i.isSelect=!1,this.points=[],this.engine.events.trigger(Et.MeasureChanged,i)}}handleMouseMove(e){if(e.catch==null)return;let t=e.catch;if(t!=null&&this.points.length==1){let i=this.engine.measure.annotationData.slopeAnnotation.find(r=>r.isSelect==!0);i==null&&(i={id:$n(),point1:this.points[0].clone(),point2:t.point.clone(),slopePercentage:0,slopeAngle:0,heightDiff:0,horizontalDist:0,text:"0.00%",isSelect:!0,type:"slope"},this.engine.measure.annotationData.slopeAnnotation.push(i)),i.point2=t.point.clone();const s=this.calculateSlope(i.point1,i.point2);i.slopePercentage=s.percentage,i.slopeAngle=s.angle,i.heightDiff=s.heightDiff,i.horizontalDist=s.horizontalDist,i.text=s.percentage.toFixed(2)+"%"}}}class DD{isActive=!1;engine;clearHeightMeasure;distanceMeasure;clearDistanceMeasure;elevationMeasure;pointMeasure;angleMeasure;areaMeasure;slopeMeasure;tools;annotationContainer;annotationData={normalAnnotation:[],textAnnotation:[],coordinateAnnotation:[],angleAnnotation:[],distanceAnnotation:[],areaAnnotation:[],slopeAnnotation:[],elevationAnnotation:[],volumeAnnotation:[]};constructor(e){this.engine=e,this.clearHeightMeasure=new _D(e),this.distanceMeasure=new wD(e),this.clearDistanceMeasure=new SD(e),this.elevationMeasure=new CD(e),this.pointMeasure=new MD(e),this.angleMeasure=new ED(e),this.areaMeasure=new ID(e),this.slopeMeasure=new TD(e),this.tools=new Jn(e),this.annotationContainer=document.createElement("div"),this.annotationContainer.className="annotation-container",e.container.appendChild(this.annotationContainer)}active(){this.isActive=!0,this.engine.modelEdge.loadModelEdge(),this.tools.active()}disActive(){this.tools.disActive(),this.clearAll(),this.isActive=!1,this.clearHeightMeasure.disActive(),this.distanceMeasure.disActive(),this.clearDistanceMeasure.disActive(),this.elevationMeasure.disActive(),this.pointMeasure.disActive(),this.angleMeasure.disActive(),this.areaMeasure.disActive(),this.slopeMeasure.disActive(),this.engine.interactionModule.init(),this.engine.interactionModule.active()}clearAllPoints(){this.clearHeightMeasure.clearAllPoints(),this.distanceMeasure.clearAllPoints(),this.clearDistanceMeasure.clearAllPoints(),this.elevationMeasure.clearAllPoints(),this.pointMeasure.clearAllPoints(),this.angleMeasure.clearAllPoints(),this.areaMeasure.clearAllPoints(),this.slopeMeasure.clearAllPoints()}clearAll(){e(this.annotationData.normalAnnotation),e(this.annotationData.textAnnotation),e(this.annotationData.coordinateAnnotation),e(this.annotationData.angleAnnotation),e(this.annotationData.distanceAnnotation),e(this.annotationData.areaAnnotation),e(this.annotationData.slopeAnnotation),e(this.annotationData.elevationAnnotation),e(this.annotationData.volumeAnnotation);function e(t){for(let i=0;i<t.length;i++)t[i].container.remove();t=[]}}saveSetting(e){this.tools.saveSetting(e)}getSetting(){return this.tools.getSetting()}update(){this.isActive&&this.tools.drawNormalAnnotation()}}class BD{engine;isActive=!1;isCtrlDown=!1;listenersAttached=!1;box;pickPoint;pickNormal;pickMesh;box_;plane;meshs;isDrag=!1;maxBox;faceIdleOpacity=0;faceHoverOpacity=.05;transformControls=new Map;transformAnchors=new Map;transformHelpers=new Map;faceMetaMap=new Map;isSyncingTransform=!1;transformHandleSize=1.05;transformHandleColor=16777215;transformHandleHoverColor=16776960;handleNativeMouseDown=e=>{if(e.button!==0||!(this.isCtrlDown||e.ctrlKey))return;const t=this.createRaycasterFromMouseEvent(e),i=t.intersectObjects(this.getInteractiveMeshes(),!1);i.length!==0&&(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseDown({button:e.button,raycaster:t,intersects:i}))};handleNativeMouseMove=e=>{if(!this.isDrag&&!(this.isCtrlDown||e.ctrlKey)){this.resetMeshOpacity();return}const t=this.createRaycasterFromMouseEvent(e),i=t.intersectObjects(this.getInteractiveMeshes(),!1);this.isDrag&&(e.preventDefault(),e.stopImmediatePropagation()),this.handleMouseMove({raycaster:t,intersects:i})};handleNativeMouseUp=e=>{e.button!==0||!this.isDrag||(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseUp({button:e.button}))};handleNativeKeyDown=e=>{e.key==="Control"&&(this.isCtrlDown=!0)};handleNativeKeyUp=e=>{e.key==="Control"&&(this.isCtrlDown=!1,this.isDrag&&this.handleMouseUp({button:0}),this.resetMeshOpacity())};constructor(e,t){this.engine=e,this.meshs=[]}active(){this.isActive||(this.attachListeners(),this.init(),this.setTransformControlsVisible(!0),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")||(t.visible=!0)})}),this.isActive=!0)}disActive(){this.init(!1),this.isActive=!1,this.detachListeners(),this.handleMouseUp({button:0},!1),this.setTransformControlsVisible(!1),this.clearClippingBoxFill(),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")||(t.visible=!1)})})}disabled(){this.isActive=!1,this.detachListeners(),this.handleMouseUp({button:0},!1),this.setTransformControlsVisible(!1),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")||(t.visible=!1)})})}recover(){this.isActive||(this.attachListeners(),this.setTransformControlsVisible(!0),this.updateClippingBoxFill(),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")||(t.visible=!0)})}),this.isActive=!0)}init(e=!0){const t=this.engine.octreeBox.getBoundingBox();t.min.x-=.1,t.min.y-=.1,t.min.z-=.1,t.max.x+=.1,t.max.y+=.1,t.max.z+=.1,this.maxBox=JSON.parse(JSON.stringify(t)),this.box=t,this.updata_face(t),e&&this.updateClippingBoxFill()}getboxXyz(){return{minX:this.box.min.x,minY:this.box.min.y,minZ:this.box.min.z,maxX:this.box.max.x,maxY:this.box.max.y,maxZ:this.box.max.z}}setboxXyz(e){this.box.min.x=e.minX,this.box.min.y=e.minY,this.box.min.z=e.minZ,this.box.max.x=e.maxX,this.box.max.y=e.maxY,this.box.max.z=e.maxZ,this.updata_face(this.box),this.updateClippingBoxFill()}setBox(e){this.box=e,this.updata_face(e),this.updateClippingBoxFill()}reverseBox(){}handleMouseDown(e){const t=e.intersects??e.raycaster.intersectObjects(this.getInteractiveMeshes(),!1);if(t!=null&&t.length>0){this.clearClippingBoxFill();const i=t[0];this.isDrag=!0,this.pickPoint=i.point.clone(),this.pickMesh=i.object;const s=this.pickMesh?.userData?.dragNormal?.clone?.(),r=i.face?.normal?.clone?.();if(this.pickNormal=(s??r??new w.Vector3(0,0,1)).clone().normalize(),this.engine.controls.enabled=!1,this.box_={min:this.box.min.clone(),max:this.box.max.clone()},this.pickNormal.y==0){const o=new w.Plane;o.setFromNormalAndCoplanarPoint(new w.Vector3(0,1,0),this.pickPoint),this.plane=o}else{const o=new w.Vector3(this.engine.camera.position.x,this.pickPoint.y,this.engine.camera.position.z),a=new w.Plane;a.setFromNormalAndCoplanarPoint(o.clone().sub(this.pickPoint.clone()).setLength(1),this.pickPoint),this.plane=a}}else this.isDrag=!1}handleMouseUp(e,t=!0){this.isDrag=!1,this.pickPoint=null,this.pickNormal=null,this.pickMesh=null,this.plane=null,this.engine.controls.enabled=!0,t&&this.updateClippingBoxFill()}clampVector3(e,t,i){return new w.Vector3(Math.max(t.x,Math.min(i.x,e.x)),Math.max(t.y,Math.min(i.y,e.y)),Math.max(t.z,Math.min(i.z,e.z)))}handleMouseMove(e){this.resetMeshOpacity();const t=e.intersects??e.raycaster.intersectObjects(this.getInteractiveMeshes(),!1);if(t!=null&&t.length>0&&(t[0].object.material.opacity=this.faceHoverOpacity),this.pickPoint!=null){const i=new w.Vector3;if(e.raycaster.ray.intersectPlane(this.plane,i)){const s=i.clone().sub(this.pickPoint.clone()).dot(this.pickNormal.clone());if(!!this.pickMesh?.userData?.isMinFace){const o=this.box_.min.clone().add(this.pickNormal.clone().setLength(s));this.box.min=this.clampVector3(o,this.maxBox.min,this.box.max)}else{const o=this.box_.max.clone().add(this.pickNormal.clone().setLength(s));this.box.max=this.clampVector3(o,this.box.min,this.maxBox.max)}this.updata_face(this.box),this.calculate_ratio()}}}calculate_ratio(){const e=this.maxBox.max.x-this.maxBox.min.x,t=this.maxBox.max.y-this.maxBox.min.y,i=this.maxBox.max.z-this.maxBox.min.z,s=this.toPercent((this.box.min.x-this.maxBox.min.x)/e*100),r=this.toPercent((this.box.max.x-this.maxBox.min.x)/e*100),o=this.toPercent((this.box.min.y-this.maxBox.min.y)/t*100),a=this.toPercent((this.box.max.y-this.maxBox.min.y)/t*100),l=this.toPercent((this.box.min.z-this.maxBox.min.z)/i*100),c=this.toPercent((this.box.max.z-this.maxBox.min.z)/i*100),h={x:{min:s,max:r},y:{min:o,max:a},z:{min:l,max:c}};this.engine.events.trigger(Et.SectionMove,h)}toPercent(e){return e<0?0:e>100?100:e}getInteractiveMeshes(){return this.meshs.filter(e=>e.type==="Mesh")}createRaycasterFromMouseEvent(e){const t=new w.Raycaster,i=new w.Vector2,s=this.engine.renderer.domElement.clientWidth,r=this.engine.renderer.domElement.clientHeight;return i.x=e.offsetX/s*2-1,i.y=-(e.offsetY/r)*2+1,t.setFromCamera(i,this.engine.camera),t}attachListeners(){if(this.listenersAttached)return;const e=this.engine.renderer?.domElement;e&&(e.addEventListener("mousedown",this.handleNativeMouseDown,!0),e.addEventListener("mousemove",this.handleNativeMouseMove,!0),e.addEventListener("mouseup",this.handleNativeMouseUp,!0),window.addEventListener("keydown",this.handleNativeKeyDown),window.addEventListener("keyup",this.handleNativeKeyUp),this.listenersAttached=!0)}detachListeners(){if(!this.listenersAttached)return;const e=this.engine.renderer?.domElement;e&&(e.removeEventListener("mousedown",this.handleNativeMouseDown,!0),e.removeEventListener("mousemove",this.handleNativeMouseMove,!0),e.removeEventListener("mouseup",this.handleNativeMouseUp,!0)),window.removeEventListener("keydown",this.handleNativeKeyDown),window.removeEventListener("keyup",this.handleNativeKeyUp),this.listenersAttached=!1,this.isCtrlDown=!1}resetMeshOpacity(){this.getInteractiveMeshes().forEach(e=>{e.material&&(e.material.opacity=this.faceIdleOpacity)})}updateClippingBoxFill(){const e=(Array.isArray(this.engine.sectionPlane)?this.engine.sectionPlane:[]).slice(0,6).filter(t=>t instanceof w.Plane);if(e.length===0){this.clearClippingBoxFill();return}this.engine.clipping?.clippingCSGSimple?.updataFaces?.(e)}clearClippingBoxFill(){this.engine.clipping?.clippingCSGSimple?.clear?.()}getFaceTransformOffset(){if(!this.box)return .06;const e=this.box.min.distanceTo(this.box.max);return Math.max(e*.015,.06)}keepSingleDirectionArrow(e,t="X"){const i=e.getHelper(),s=[];i.traverse(r=>{if(r?.name!==t||!r.geometry)return;const o=r.geometry;o.boundingBox||o.computeBoundingBox();const a=o.boundingBox;if(!a)return;const l=a.getCenter(new w.Vector3);if(!(t==="X"&&l.x<0||t==="Y"&&l.y<0||t==="Z"&&l.z<0))return;const h=o.parameters,d=h&&h.radiusTop===0&&h.radiusBottom===.04&&h.height===.1,f=h&&h.radiusTop===.2&&h.radiusBottom===0&&h.height===.6;(d||f)&&s.push(r)}),s.forEach(r=>{r.parent?.remove(r)})}setTransformControlsVisible(e){this.transformControls.forEach(t=>{t.enabled=e}),this.transformHelpers.forEach(t=>{t.visible=e}),this.transformAnchors.forEach(t=>{t.visible=e}),e||(this.engine.controls.enabled=!0)}ensureFaceTransformControl(e){if(this.transformControls.has(e)&&this.transformAnchors.has(e))return;const t=this.engine.renderer?.domElement,i=this.engine.camera;if(!t||!i)return;const s=new w.Object3D;s.name=`SectionBoxTransformAnchor_${e}`,s.visible=this.isActive,this.engine.scene.add(s);const r=new sx(i,t);r.name=`SectionBoxTransformControl_${e}`,r.setMode("translate"),r.setSpace("local"),r.showX=!0,r.showY=!1,r.showZ=!1,r.size=this.transformHandleSize,r.setColors(this.transformHandleColor,this.transformHandleColor,this.transformHandleColor,this.transformHandleHoverColor),r.enabled=this.isActive,r.attach(s),this.keepSingleDirectionArrow(r,"X"),r.addEventListener("dragging-changed",a=>{this.engine.controls.enabled=!a.value,a.value===!0?this.clearClippingBoxFill():this.updateClippingBoxFill()}),r.addEventListener("objectChange",()=>{this.handleTransformObjectChange(e)});const o=r.getHelper();o.visible=this.isActive,this.engine.scene.add(o),this.transformAnchors.set(e,s),this.transformControls.set(e,r),this.transformHelpers.set(e,o)}updateFaceTransformControl(e,t,i,s){this.ensureFaceTransformControl(e);const r=this.transformAnchors.get(e),o=this.transformControls.get(e);if(!r||!o)return;const a=this.getFaceTransformOffset(),l=new w.Quaternion().setFromUnitVectors(new w.Vector3(1,0,0),t.clone().normalize()),c=i.clone().add(t.clone().setLength(a));this.faceMetaMap.set(e,{normal:t.clone().normalize(),isMinFace:s,center:i.clone()}),this.isSyncingTransform=!0,r.position.copy(c),r.quaternion.copy(l),r.visible=this.isActive,o.object!==r&&o.attach(r),o.enabled=this.isActive;const h=this.transformHelpers.get(e);h&&(h.visible=this.isActive),this.isSyncingTransform=!1}getDominantAxis(e){const t=Math.abs(e.x),i=Math.abs(e.y),s=Math.abs(e.z);return t>=i&&t>=s?"x":i>=t&&i>=s?"y":"z"}handleTransformObjectChange(e){if(this.isSyncingTransform)return;const t=this.transformAnchors.get(e),i=this.faceMetaMap.get(e);if(!t||!i||!this.box||!this.maxBox)return;const s=i.normal,r=this.getDominantAxis(s),o=this.getFaceTransformOffset(),a=s[r],l=t.position[r]-a*o;if(i.isMinFace){const c=this.maxBox.min[r],h=this.box.max[r];this.box.min[r]=Math.max(c,Math.min(h,l))}else{const c=this.box.min[r],h=this.maxBox.max[r];this.box.max[r]=Math.max(c,Math.min(h,l))}this.updata_face(this.box),this.calculate_ratio()}updata_face(e){let t=this.engine.scene.children.find(s=>s.type=="Group"&&s.name=="ClippingBox");t==null&&(t=new w.Group,t.name="ClippingBox",this.engine.scene.add(t)),[{name:"前",normal:new w.Vector3(0,0,-1),isMinFace:!0,planePoint:e.min,vertices:[new w.Vector3(e.min.x,e.max.y,e.min.z),new w.Vector3(e.max.x,e.max.y,e.min.z),new w.Vector3(e.max.x,e.min.y,e.min.z),new w.Vector3(e.min.x,e.min.y,e.min.z)]},{name:"后",normal:new w.Vector3(0,0,1),isMinFace:!1,planePoint:e.max,vertices:[new w.Vector3(e.min.x,e.min.y,e.max.z),new w.Vector3(e.max.x,e.min.y,e.max.z),new w.Vector3(e.max.x,e.max.y,e.max.z),new w.Vector3(e.min.x,e.max.y,e.max.z)]},{name:"右",normal:new w.Vector3(1,0,0),isMinFace:!1,planePoint:e.max,vertices:[new w.Vector3(e.max.x,e.min.y,e.max.z),new w.Vector3(e.max.x,e.min.y,e.min.z),new w.Vector3(e.max.x,e.max.y,e.min.z),new w.Vector3(e.max.x,e.max.y,e.max.z)]},{name:"左",normal:new w.Vector3(-1,0,0),isMinFace:!0,planePoint:e.min,vertices:[new w.Vector3(e.min.x,e.min.y,e.min.z),new w.Vector3(e.min.x,e.min.y,e.max.z),new w.Vector3(e.min.x,e.max.y,e.max.z),new w.Vector3(e.min.x,e.max.y,e.min.z)]},{name:"顶",normal:new w.Vector3(0,1,0),isMinFace:!1,planePoint:e.max,vertices:[new w.Vector3(e.min.x,e.max.y,e.max.z),new w.Vector3(e.max.x,e.max.y,e.max.z),new w.Vector3(e.max.x,e.max.y,e.min.z),new w.Vector3(e.min.x,e.max.y,e.min.z)]},{name:"底",normal:new w.Vector3(0,-1,0),isMinFace:!0,planePoint:e.min,vertices:[new w.Vector3(e.min.x,e.min.y,e.min.z),new w.Vector3(e.max.x,e.min.y,e.min.z),new w.Vector3(e.max.x,e.min.y,e.max.z),new w.Vector3(e.min.x,e.min.y,e.max.z)]}].forEach(s=>{this.createFace(t,s.vertices,s.normal,s.name,s.isMinFace,s.planePoint)}),this.engine.scene.children.filter(s=>s.type=="Mesh"&&s.url).forEach(s=>{s.material&&Array.isArray(s.material)?s.material.forEach(r=>{r.clippingPlanes=this.engine.sectionPlane}):s.material.clippingPlanes=this.engine.sectionPlane})}createFace(e,t,i,s,r,o){const a=new w.BufferGeometry,l=new Float32Array([t[0].x,t[0].y,t[0].z,t[1].x,t[1].y,t[1].z,t[2].x,t[2].y,t[2].z,t[3].x,t[3].y,t[3].z]),c=[0,2,1,0,3,2];a.setAttribute("position",new w.BufferAttribute(l,3)),a.setIndex(c);let h=this.meshs.find(A=>A.name===s);if(h==null){const A=new w.MeshBasicMaterial({color:65280,transparent:!0,opacity:this.faceIdleOpacity,side:w.DoubleSide});A.polygonOffset=!0,A.polygonOffsetFactor=1,A.polygonOffsetUnits=4,h=new w.Mesh(a,A),h.name=s,e.add(h),this.meshs.push(h)}else h.geometry=a;h.userData={dragNormal:i.clone(),isMinFace:r,faceName:s};const d=new Float32Array([t[0].x,t[0].y,t[0].z,t[1].x,t[1].y,t[1].z,t[2].x,t[2].y,t[2].z,t[3].x,t[3].y,t[3].z,t[0].x,t[0].y,t[0].z]),f=new w.LineBasicMaterial({color:255}),u=new w.BufferGeometry;u.setAttribute("position",new w.BufferAttribute(d,3));let g=this.meshs.find(A=>A.name===s+"Line");g==null?(g=new w.Line(u,f),g.name=s+"Line",e.add(g),this.meshs.push(g)):(g.geometry=u,g.material=f);const p=new w.Vector3;t.forEach(A=>p.add(A)),p.multiplyScalar(1/t.length),this.updateFaceTransformControl(s,i,p,r);const m=this.engine.sectionPlane.find(A=>A.name==s);m&&m.setFromNormalAndCoplanarPoint(i.clone().setLength(-1),o)}}class PD{engine;isActive=!1;isDrag=!1;isCtrlDown=!1;listenersAttached=!1;meshs=[];box=null;pickPoint=null;pickNormal=null;plane=null;angleX=0;angleY=0;angleZ=0;direction=1;normal=new w.Vector3(0,0,1);distance=0;center=null;current_center=null;dragStartDistance=0;idleOpacity=.02;hoverOpacity=.05;transformControl=null;transformAnchor=null;transformHelper=null;isSyncingTransformControl=!1;moveEpsilon=1e-5;transformHandleSize=1.15;transformHandleColor=16777215;transformHandleHoverColor=16776960;handleNativeMouseDown=e=>{if(e.button!==0||!(this.isCtrlDown||e.ctrlKey))return;const t=this.createRaycasterFromMouseEvent(e),i=t.intersectObjects(this.getInteractiveMeshes(),!1);i.length!==0&&(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseDown({button:e.button,raycaster:t,intersects:i}))};handleNativeMouseMove=e=>{if(!this.isDrag&&!(this.isCtrlDown||e.ctrlKey)){this.resetMeshOpacity();return}const t=this.createRaycasterFromMouseEvent(e),i=t.intersectObjects(this.getInteractiveMeshes(),!1);this.isDrag&&(e.preventDefault(),e.stopImmediatePropagation()),this.handleMouseMove({raycaster:t,intersects:i})};handleNativeMouseUp=e=>{e.button!==0||!this.isDrag||(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseUp({button:e.button}))};handleNativeKeyDown=e=>{e.key==="Control"&&(this.isCtrlDown=!0)};handleNativeKeyUp=e=>{e.key==="Control"&&(this.isCtrlDown=!1,this.isDrag&&this.handleMouseUp({button:0}),this.resetMeshOpacity())};handleTransformObjectChange=()=>{if(this.isSyncingTransformControl||!this.transformAnchor||!this.center)return;const e=this.normal.clone().normalize(),t=this.getDistanceRange(e),i=this.getTransformHandleOffset(),s=this.transformAnchor.position.clone().sub(this.center).dot(e)-i,r=Math.min(t.max,Math.max(t.min,s));Math.abs(r-Number(this.distance))>this.moveEpsilon?this.updata_face(r):Math.abs(s-r)>this.moveEpsilon&&this.updateTransformControl(e)};constructor(e){this.engine=e,this.meshs=[],this.box=null}active(){if(this.isActive==!0)return;this.isActive=!0,this.engine.scene.children.filter(t=>t.type=="Group"&&t.name=="ClippingBox").forEach(t=>{t.children.forEach(i=>{i.name.includes("face")&&(i.visible=!0)})}),this.attachListeners(),this.ensureTransformControl(),this.setTransformControlVisible(!0);const e=this;e.engine.scene.children.filter(t=>t.type=="Mesh"&&t.url).forEach(t=>{t.material&&Array.isArray(t.material)?t.material.forEach(i=>{i.clippingPlanes=e.engine.sectionPlane}):t.material.clippingPlanes=e.engine.sectionPlane,e.engine.clipping.clippingStencil?.addMesh(e.engine.sectionPlane.find(i=>i.name=="face"),t)}),this.init()}disActive(){this.init(),this.isActive=!1,this.detachListeners(),this.handleMouseUp({button:0},!1),this.setTransformControlVisible(!1),this.clearClippingFaceFill();const e=this.engine.sectionPlane.find(t=>t.name=="face");e&&(e.constant=1e5),this.engine.scene.children.filter(t=>t.type=="Group"&&t.name=="ClippingBox").forEach(t=>{t.children.forEach(i=>{i.name.includes("face")&&(i.visible=!1)})})}init(e){const t=this.engine.octreeBox.getBoundingBox();this.box=t,this.distance=0,this.center=new w.Vector3((t.min.x+t.max.x)/2,(t.min.y+t.max.y)/2,(t.min.z+t.max.z)/2),this.current_center=this.center.clone(),!e&&this.updata_face(0)}disabled(){this.isActive=!1,this.detachListeners(),this.handleMouseUp({button:0},!1),this.setTransformControlVisible(!1),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")&&(t.visible=!1)})})}recover(){this.isActive||(this.attachListeners(),this.setTransformControlVisible(!0),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")&&(t.visible=!0)})}),this.isActive=!0)}setFaceAngle(e,t,i){this.angleX=e,this.angleY=t,this.angleZ=i,this.distance=0,this.normal=new w.Vector3(0,1,0).applyAxisAngle(new w.Vector3(1,0,0),e).applyAxisAngle(new w.Vector3(0,0,1),t).applyAxisAngle(new w.Vector3(0,1,0),i).normalize(),this.updata_face(0),this.updateClippingFaceFill()}setFaceNormal(e,t=0){this.normal=e.clone().normalize(),this.distance=t,this.updata_face(t),this.updateClippingFaceFill()}setFaceNormalPlaneOnly(e,t){if(this.normal=e.clone().normalize(),this.distance=t,!this.center||!this.box)return;const i=this.engine.sectionPlane?.find(s=>s.name==="face");if(i){const s=this.center.clone().add(this.normal.clone().multiplyScalar(t));i.setFromNormalAndCoplanarPoint(this.normal.clone().multiplyScalar(this.direction),s)}this.updateClippingFaceFill()}activateClippingOnly(){if(this.isActive)return;this.isActive=!0;const e=this;e.engine.scene.children.filter(t=>t.type==="Mesh"&&t.url).forEach(t=>{t.material&&Array.isArray(t.material)?t.material.forEach(i=>{i.clippingPlanes=e.engine.sectionPlane}):t.material.clippingPlanes=e.engine.sectionPlane,e.engine.clipping.clippingStencil?.addMesh(e.engine.sectionPlane.find(i=>i.name==="face"),t)})}reverse(){this.direction=this.direction*-1,this.updata_face(this.distance),this.updateClippingFaceFill()}getFaceAngle(){return{angleX:this.angleX,angleY:this.angleY,angleZ:this.angleZ,direction:this.direction}}updata_face(e){if(!this.box)return;this.distance=e;let t=this.engine.scene.children.find(b=>b.type=="Group"&&b.name=="ClippingBox");t==null&&(t=new w.Group,t.name="ClippingBox",this.engine.scene.add(t));const i=this.normal.clone().normalize(),s=this.center??new w.Vector3((this.box.min.x+this.box.max.x)/2,(this.box.min.y+this.box.max.y)/2,(this.box.min.z+this.box.max.z)/2);this.center=s.clone();const{tangent:r,bitangent:o}=this.getPlaneBasis(i),a=this.getBoxCorners(this.box),l=this.box.min.distanceTo(this.box.max),c=Math.max(l*.02,.01);let h=1/0,d=-1/0,f=1/0,u=-1/0;a.forEach(b=>{const y=b.clone().sub(s),_=y.dot(r),S=y.dot(o);h=Math.min(h,_),d=Math.max(d,_),f=Math.min(f,S),u=Math.max(u,S)}),h-=c,d+=c,f-=c,u+=c;const g=i.clone().multiplyScalar(e),p=s.clone().add(r.clone().multiplyScalar(h)).add(o.clone().multiplyScalar(f)).add(g),m=s.clone().add(r.clone().multiplyScalar(d)).add(o.clone().multiplyScalar(f)).add(g),A=s.clone().add(r.clone().multiplyScalar(d)).add(o.clone().multiplyScalar(u)).add(g),x=s.clone().add(r.clone().multiplyScalar(h)).add(o.clone().multiplyScalar(u)).add(g);this.current_center=s.clone().add(g),this.createFace(t,[p,m,A,x],i,"face"),this.updateTransformControl(i)}createFace(e,t,i,s){const r=new w.BufferGeometry,o=new Float32Array([t[0].x,t[0].y,t[0].z,t[1].x,t[1].y,t[1].z,t[2].x,t[2].y,t[2].z,t[3].x,t[3].y,t[3].z]),a=[0,1,2,0,2,3];r.setAttribute("position",new w.BufferAttribute(o,3)),r.setIndex(a);let l=this.meshs.find(g=>g.name==s);if(l==null){const g=new w.MeshBasicMaterial({color:65280,transparent:!0,opacity:this.idleOpacity,side:w.DoubleSide});g.polygonOffset=!0,g.polygonOffsetFactor=1,g.polygonOffsetUnits=4,l=new w.Mesh(r,g),l.name=s,e.add(l),this.meshs.push(l)}else l.geometry=r;l.normal=i.clone();const c=new Float32Array([t[0].x,t[0].y,t[0].z,t[1].x,t[1].y,t[1].z,t[2].x,t[2].y,t[2].z,t[3].x,t[3].y,t[3].z,t[0].x,t[0].y,t[0].z]),h=new w.LineBasicMaterial({color:255}),d=new w.BufferGeometry;d.setAttribute("position",new w.BufferAttribute(c,3));let f=this.meshs.find(g=>g.name==s+"Line");f==null?(f=new w.Line(d,h),f.name=s+"Line",e.add(f),this.meshs.push(f)):(f.geometry=d,f.material=h);const u=this.engine.sectionPlane.find(g=>g.name==s);u&&this.current_center&&u.setFromNormalAndCoplanarPoint(i.clone().setLength(this.direction),this.current_center)}getPlaneBasis(e){const t=new w.Vector3(1,0,0),i=new w.Vector3(0,1,0),s=new w.Vector3(0,0,1),r=Math.abs(e.dot(t)),o=Math.abs(e.dot(i)),a=Math.abs(e.dot(s));let l=t;o<=r&&o<=a?l=i:a<=r&&a<=o&&(l=s),l=l.clone().sub(e.clone().multiplyScalar(l.dot(e))).normalize();const c=new w.Vector3().crossVectors(e,l).normalize();return{tangent:l,bitangent:c}}getBoxCorners(e){return[new w.Vector3(e.min.x,e.min.y,e.min.z),new w.Vector3(e.min.x,e.min.y,e.max.z),new w.Vector3(e.min.x,e.max.y,e.min.z),new w.Vector3(e.min.x,e.max.y,e.max.z),new w.Vector3(e.max.x,e.min.y,e.min.z),new w.Vector3(e.max.x,e.min.y,e.max.z),new w.Vector3(e.max.x,e.max.y,e.min.z),new w.Vector3(e.max.x,e.max.y,e.max.z)]}getDistanceRange(e){if(!this.box)return{min:0,max:0};const t=this.center??new w.Vector3((this.box.min.x+this.box.max.x)/2,(this.box.min.y+this.box.max.y)/2,(this.box.min.z+this.box.max.z)/2),i=this.getBoxCorners(this.box);let s=1/0,r=-1/0;return i.forEach(o=>{const a=o.clone().sub(t).dot(e);s=Math.min(s,a),r=Math.max(r,a)}),{min:s,max:r}}getInteractiveMeshes(){return this.meshs.filter(e=>e.type==="Mesh")}getTransformHandleOffset(){if(!this.box)return .06;const e=this.box.min.distanceTo(this.box.max);return Math.max(e*.015,.06)}keepSingleDirectionArrow(e,t="X"){const i=e.getHelper(),s=[];i.traverse(r=>{if(r?.name!==t||!r.geometry)return;const o=r.geometry;o.boundingBox||o.computeBoundingBox();const a=o.boundingBox;if(!a)return;const l=a.getCenter(new w.Vector3);if(!(t==="X"&&l.x<0||t==="Y"&&l.y<0||t==="Z"&&l.z<0))return;const h=o.parameters,d=h&&h.radiusTop===0&&h.radiusBottom===.04&&h.height===.1,f=h&&h.radiusTop===.2&&h.radiusBottom===0&&h.height===.6;(d||f)&&s.push(r)}),s.forEach(r=>{r.parent?.remove(r)})}ensureTransformControl(){if(this.transformControl&&this.transformAnchor)return;const e=this.engine.renderer?.domElement,t=this.engine.camera;if(!e||!t)return;const i=new w.Object3D;i.name="SectionFaceTransformAnchor",i.visible=this.isActive,this.engine.scene.add(i);const s=new sx(t,e);s.name="SectionFaceTransformControl",s.setMode("translate"),s.setSpace("local"),s.showX=!0,s.showY=!1,s.showZ=!1,s.size=this.transformHandleSize,s.setColors(this.transformHandleColor,this.transformHandleColor,this.transformHandleColor,this.transformHandleHoverColor),s.enabled=this.isActive,s.attach(i),this.keepSingleDirectionArrow(s,"X"),s.addEventListener("dragging-changed",o=>{this.engine.controls.enabled=!o.value,o.value===!0?this.clearClippingFaceFill():this.updateClippingFaceFill()}),s.addEventListener("objectChange",this.handleTransformObjectChange);const r=s.getHelper();r.visible=this.isActive,this.engine.scene.add(r),this.transformAnchor=i,this.transformControl=s,this.transformHelper=r}setTransformControlVisible(e){this.ensureTransformControl(),this.transformControl&&(this.transformControl.enabled=e),this.transformHelper&&(this.transformHelper.visible=e),this.transformAnchor&&(this.transformAnchor.visible=e),e||(this.engine.controls.enabled=!0)}updateTransformControl(e){if(this.ensureTransformControl(),!this.transformControl||!this.transformAnchor||!this.current_center)return;const t=this.getTransformHandleOffset(),i=this.current_center.clone().add(e.clone().setLength(t)),s=new w.Quaternion().setFromUnitVectors(new w.Vector3(1,0,0),e.clone().normalize().multiplyScalar(-1));this.isSyncingTransformControl=!0,this.transformAnchor.position.copy(i),this.transformAnchor.quaternion.copy(s),this.transformAnchor.visible=this.isActive,this.transformControl.object!==this.transformAnchor&&this.transformControl.attach(this.transformAnchor),this.transformControl.enabled=this.isActive,this.transformHelper&&(this.transformHelper.visible=this.isActive),this.isSyncingTransformControl=!1}createRaycasterFromMouseEvent(e){const t=new w.Raycaster,i=new w.Vector2,s=this.engine.renderer.domElement.clientWidth,r=this.engine.renderer.domElement.clientHeight;return i.x=e.offsetX/s*2-1,i.y=-(e.offsetY/r)*2+1,t.setFromCamera(i,this.engine.camera),t}attachListeners(){if(this.listenersAttached)return;const e=this.engine.renderer?.domElement;e&&(e.addEventListener("mousedown",this.handleNativeMouseDown,!0),e.addEventListener("mousemove",this.handleNativeMouseMove,!0),e.addEventListener("mouseup",this.handleNativeMouseUp,!0),window.addEventListener("keydown",this.handleNativeKeyDown),window.addEventListener("keyup",this.handleNativeKeyUp),this.listenersAttached=!0)}detachListeners(){if(!this.listenersAttached)return;const e=this.engine.renderer?.domElement;e&&(e.removeEventListener("mousedown",this.handleNativeMouseDown,!0),e.removeEventListener("mousemove",this.handleNativeMouseMove,!0),e.removeEventListener("mouseup",this.handleNativeMouseUp,!0)),window.removeEventListener("keydown",this.handleNativeKeyDown),window.removeEventListener("keyup",this.handleNativeKeyUp),this.listenersAttached=!1,this.isCtrlDown=!1}resetMeshOpacity(){this.getInteractiveMeshes().forEach(e=>{e.material&&(e.material.opacity=this.idleOpacity)})}updateClippingFaceFill(){const e=this.engine.sectionPlane?.find?.(t=>t.name==="face");if(e){this.engine.clipping?.clippingCSGSimple?.updataFace?.(e);return}this.clearClippingFaceFill()}clearClippingFaceFill(){this.engine.clipping?.clippingCSGSimple?.clear?.()}handleMouseDown(e){const t=e.intersects??e.raycaster.intersectObjects(this.getInteractiveMeshes(),!1);if(t!=null&&t.length>0){this.clearClippingFaceFill();const i=t[0],s=i.point.clone();this.isDrag=!0,this.pickPoint=s;const o=(i.face?.normal?.clone()??this.normal.clone()).clone();if(o.dot(this.normal)<0&&o.multiplyScalar(-1),o.normalize(),this.pickNormal=o,this.engine.controls.enabled=!1,this.dragStartDistance=Number(this.distance)||0,o.y==0){const a=new w.Plane;a.setFromNormalAndCoplanarPoint(new w.Vector3(0,1,0),s),this.plane=a}else{const a=new w.Vector3(this.engine.camera.position.x,s.y,this.engine.camera.position.z),l=new w.Plane;l.setFromNormalAndCoplanarPoint(a.clone().sub(s.clone()).setLength(1),s),this.plane=l}}else this.isDrag=!1}handleMouseUp(e,t=!0){this.isDrag=!1,this.pickPoint=null,this.pickNormal=null,this.plane=null,this.engine.controls.enabled=!0,t&&this.updateClippingFaceFill()}handleMouseMove(e){this.resetMeshOpacity();const t=e.intersects??e.raycaster.intersectObjects(this.getInteractiveMeshes(),!1);t!=null&&t.length>0&&(t[0].object.material.opacity=this.hoverOpacity);const i=this.pickPoint,s=this.pickNormal,r=this.plane;if(i!=null&&s!=null&&r!=null){const o=new w.Vector3;if(e.raycaster.ray.intersectPlane(r,o)){const a=o.clone().sub(i.clone()).dot(s.clone()),l=this.getDistanceRange(this.normal.clone().normalize()),c=this.dragStartDistance+a;this.distance=Math.min(l.max,Math.max(l.min,c)),this.updata_face(this.distance)}}}}class LD{engine;callback_;constructor(e){this.engine=e}init(){this.engine.handelBehaved.init(this,{showCatch:!0}),this.engine.handelBehaved.active()}catch_face(e){this.callback_=e}handleMouseMove(e){}handleMouseClick(e){if(e.catch?.normal==null&&(e.catch.normal=e.catch.face?.normal),!e.catch?.normal||!e.catch?.point)return;let t=e.catch.normal.setLength(-1);this.engine.handelBehaved.disActive(),this.callback_({dir:t,position:e.catch.point})}}const bx=0,RD=1,kD=2,yx=2,hf=1.25,vx=1,li=32,Ht=li/4,_x=65535,FD=Math.pow(2,-24),df=Symbol("SKIP_GENERATION");function OD(n){return n.index?n.index.count:n.attributes.position.count}function pr(n){return OD(n)/3}function UD(n,e=ArrayBuffer){return n>65535?new Uint32Array(new e(4*n)):new Uint16Array(new e(2*n))}function ND(n,e){if(!n.index){const t=n.attributes.position.count,i=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,s=UD(t,i);n.setIndex(new v.BufferAttribute(s,1));for(let r=0;r<t;r++)s[r]=r}}function wx(n,e){const t=pr(n),i=e||n.drawRange,s=i.start/3,r=(i.start+i.count)/3,o=Math.max(0,s),a=Math.min(t,r)-o;return[{offset:Math.floor(o),count:Math.floor(a)}]}function Sx(n,e){if(!n.groups||!n.groups.length)return wx(n,e);const t=[],i=e||n.drawRange,s=i.start/3,r=(i.start+i.count)/3,o=pr(n),a=[];for(const h of n.groups){const{start:d,count:f}=h,u=d/3,g=isFinite(f)?f:o*3-d,p=(d+g)/3;u<r&&p>s&&(a.push({pos:Math.max(s,u),isStart:!0}),a.push({pos:Math.min(r,p),isStart:!1}))}a.sort((h,d)=>h.pos!==d.pos?h.pos-d.pos:h.type==="end"?-1:1);let l=0,c=null;for(const h of a){const d=h.pos;l!==0&&d!==c&&t.push({offset:c,count:d-c}),l+=h.isStart?1:-1,c=d}return t}function uf(n,e,t,i,s){let r=1/0,o=1/0,a=1/0,l=-1/0,c=-1/0,h=-1/0,d=1/0,f=1/0,u=1/0,g=-1/0,p=-1/0,m=-1/0;const A=n.offset||0;for(let x=(e-A)*6,b=(e+t-A)*6;x<b;x+=6){const y=n[x+0],_=n[x+1],S=y-_,C=y+_;S<r&&(r=S),C>l&&(l=C),y<d&&(d=y),y>g&&(g=y);const D=n[x+2],M=n[x+3],I=D-M,L=D+M;I<o&&(o=I),L>c&&(c=L),D<f&&(f=D),D>p&&(p=D);const T=n[x+4],R=n[x+5],E=T-R,F=T+R;E<a&&(a=E),F>h&&(h=F),T<u&&(u=T),T>m&&(m=T)}i[0]=r,i[1]=o,i[2]=a,i[3]=l,i[4]=c,i[5]=h,s[0]=d,s[1]=f,s[2]=u,s[3]=g,s[4]=p,s[5]=m}function Cx(n,e,t=null,i=null,s=null){const r=n.attributes.position,o=n.index?n.index.array:null,a=r.normalized;if(s===null)s=new Float32Array(t*6),s.offset=e;else if(e<0||t+e>s.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"],f=s.offset;for(let u=e,g=e+t;u<g;u++){const m=(i?i[u]:u)*3,A=(u-f)*6;let x=m+0,b=m+1,y=m+2;o&&(x=o[x],b=o[b],y=o[y]),a||(x=x*h+c,b=b*h+c,y=y*h+c);for(let _=0;_<3;_++){let S,C,D;a?(S=r[d[_]](x),C=r[d[_]](b),D=r[d[_]](y)):(S=l[x+_],C=l[b+_],D=l[y+_]);let M=S;C<M&&(M=C),D<M&&(M=D);let I=S;C>I&&(I=C),D>I&&(I=D);const L=(I-M)/2,T=_*2;s[A+T+0]=M+L,s[A+T+1]=L+(Math.abs(M)+L)*FD}}return s}function It(n,e,t){return t.min.x=e[n],t.min.y=e[n+1],t.min.z=e[n+2],t.max.x=e[n+3],t.max.y=e[n+4],t.max.z=e[n+5],t}function Mx(n){let e=-1,t=-1/0;for(let i=0;i<3;i++){const s=n[i+3]-n[i];s>t&&(t=s,e=i)}return e}function Ex(n,e){e.set(n)}function Ix(n,e,t){let i,s;for(let r=0;r<3;r++){const o=r+3;i=n[r],s=e[r],t[r]=i<s?i:s,i=n[o],s=e[o],t[o]=i>s?i:s}}function Bc(n,e,t){for(let i=0;i<3;i++){const s=e[n+2*i],r=e[n+2*i+1],o=s-r,a=s+r;o<t[i]&&(t[i]=o),a>t[i+3]&&(t[i+3]=a)}}function _a(n){const e=n[3]-n[0],t=n[4]-n[1],i=n[5]-n[2];return 2*(e*t+t*i+i*e)}const Zn=32,zD=(n,e)=>n.candidate-e.candidate,Es=new Array(Zn).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),Pc=new Float32Array(6);function GD(n,e,t,i,s,r){let o=-1,a=0;if(r===bx)o=Mx(e),o!==-1&&(a=(e[o]+e[o+3])/2);else if(r===RD)o=Mx(n),o!==-1&&(a=VD(t,i,s,o));else if(r===kD){const l=_a(n);let c=hf*s;const h=t.offset||0,d=(i-h)*6,f=(i+s-h)*6;for(let u=0;u<3;u++){const g=e[u],A=(e[u+3]-g)/Zn;if(s<Zn/4){const x=[...Es];x.length=s;let b=0;for(let _=d;_<f;_+=6,b++){const S=x[b];S.candidate=t[_+2*u],S.count=0;const{bounds:C,leftCacheBounds:D,rightCacheBounds:M}=S;for(let I=0;I<3;I++)M[I]=1/0,M[I+3]=-1/0,D[I]=1/0,D[I+3]=-1/0,C[I]=1/0,C[I+3]=-1/0;Bc(_,t,C)}x.sort(zD);let y=s;for(let _=0;_<y;_++){const S=x[_];for(;_+1<y&&x[_+1].candidate===S.candidate;)x.splice(_+1,1),y--}for(let _=d;_<f;_+=6){const S=t[_+2*u];for(let C=0;C<y;C++){const D=x[C];S>=D.candidate?Bc(_,t,D.rightCacheBounds):(Bc(_,t,D.leftCacheBounds),D.count++)}}for(let _=0;_<y;_++){const S=x[_],C=S.count,D=s-S.count,M=S.leftCacheBounds,I=S.rightCacheBounds;let L=0;C!==0&&(L=_a(M)/l);let T=0;D!==0&&(T=_a(I)/l);const R=vx+hf*(L*C+T*D);R<c&&(o=u,c=R,a=S.candidate)}}else{for(let y=0;y<Zn;y++){const _=Es[y];_.count=0,_.candidate=g+A+y*A;const S=_.bounds;for(let C=0;C<3;C++)S[C]=1/0,S[C+3]=-1/0}for(let y=d;y<f;y+=6){let C=~~((t[y+2*u]-g)/A);C>=Zn&&(C=Zn-1);const D=Es[C];D.count++,Bc(y,t,D.bounds)}const x=Es[Zn-1];Ex(x.bounds,x.rightCacheBounds);for(let y=Zn-2;y>=0;y--){const _=Es[y],S=Es[y+1];Ix(_.bounds,S.rightCacheBounds,_.rightCacheBounds)}let b=0;for(let y=0;y<Zn-1;y++){const _=Es[y],S=_.count,C=_.bounds,M=Es[y+1].rightCacheBounds;S!==0&&(b===0?Ex(C,Pc):Ix(C,Pc,Pc)),b+=S;let I=0,L=0;b!==0&&(I=_a(Pc)/l);const T=s-b;T!==0&&(L=_a(M)/l);const R=vx+hf*(I*b+L*T);R<c&&(o=u,c=R,a=_.candidate)}}}}else console.warn(`MeshBVH: Invalid build strategy value ${r} used.`);return{axis:o,pos:a}}function VD(n,e,t,i){let s=0;const r=n.offset;for(let o=e,a=e+t;o<a;o++)s+=n[(o-r)*6+i*2];return s/t}class ff{constructor(){this.boundingData=new Float32Array(6)}}function QD(n,e,t,i,s,r){let o=i,a=i+s-1;const l=r.pos,c=r.axis*2,h=t.offset||0;for(;;){for(;o<=a&&t[(o-h)*6+c]<l;)o++;for(;o<=a&&t[(a-h)*6+c]>=l;)a--;if(o<a){for(let d=0;d<3;d++){let f=e[o*3+d];e[o*3+d]=e[a*3+d],e[a*3+d]=f}for(let d=0;d<6;d++){const f=o-h,u=a-h,g=t[f*6+d];t[f*6+d]=t[u*6+d],t[u*6+d]=g}o++,a--}else return o}}function jD(n,e,t,i,s,r){let o=i,a=i+s-1;const l=r.pos,c=r.axis*2,h=t.offset||0;for(;;){for(;o<=a&&t[(o-h)*6+c]<l;)o++;for(;o<=a&&t[(a-h)*6+c]>=l;)a--;if(o<a){let d=n[o];n[o]=n[a],n[a]=d;for(let f=0;f<6;f++){const u=o-h,g=a-h,p=t[u*6+f];t[u*6+f]=t[g*6+f],t[g*6+f]=p}o++,a--}else return o}}let Tx,Lc,pf,Dx;const WD=Math.pow(2,32);function gf(n){return"count"in n?1:1+gf(n.left)+gf(n.right)}function HD(n,e,t){return Tx=new Float32Array(t),Lc=new Uint32Array(t),pf=new Uint16Array(t),Dx=new Uint8Array(t),mf(n,e)}function mf(n,e){const t=n/4,i=n/2,s="count"in e,r=e.boundingData;for(let o=0;o<6;o++)Tx[t+o]=r[o];if(s)return e.buffer?(Dx.set(new Uint8Array(e.buffer),n),n+e.buffer.byteLength):(Lc[t+6]=e.offset,pf[i+14]=e.count,pf[i+15]=_x,n+li);{const{left:o,right:a,splitAxis:l}=e,c=n+li;let h=mf(c,o);const d=n/li,u=h/li-d;if(u>WD)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return Lc[t+6]=u,Lc[t+7]=l,mf(h,a)}}function XD(n,e,t){const s=(n.index?n.index.count:n.attributes.position.count)/3>2**16,r=t.reduce((h,d)=>h+d.count,0),o=s?4:2,a=e?new SharedArrayBuffer(r*o):new ArrayBuffer(r*o),l=s?new Uint32Array(a):new Uint16Array(a);let c=0;for(let h=0;h<t.length;h++){const{offset:d,count:f}=t[h];for(let u=0;u<f;u++)l[c+u]=d+u;c+=f}return l}function qD(n,e,t,i,s){const{maxDepth:r,verbose:o,maxLeafTris:a,strategy:l,onProgress:c,indirect:h}=s,d=n._indirectBuffer,f=n.geometry,u=f.index?f.index.array:null,g=h?jD:QD,p=pr(f),m=new Float32Array(6);let A=!1;const x=new ff;return uf(e,t,i,x.boundingData,m),y(x,t,i,m),x;function b(_){c&&c(_/p)}function y(_,S,C,D=null,M=0){if(!A&&M>=r&&(A=!0,o&&(console.warn(`MeshBVH: Max depth of ${r} reached when generating BVH. Consider increasing maxDepth.`),console.warn(f))),C<=a||M>=r)return b(S+C),_.offset=S,_.count=C,_;const I=GD(_.boundingData,D,e,S,C,l);if(I.axis===-1)return b(S+C),_.offset=S,_.count=C,_;const L=g(d,u,e,S,C,I);if(L===S||L===S+C)b(S+C),_.offset=S,_.count=C;else{_.splitAxis=I.axis;const T=new ff,R=S,E=L-S;_.left=T,uf(e,R,E,T.boundingData,m),y(T,R,E,m,M+1);const F=new ff,N=L,H=C-E;_.right=F,uf(e,N,H,F.boundingData,m),y(F,N,H,m,M+1)}return _}}function YD(n,e){const t=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,i=n.geometry;let s,r;if(e.indirect){const o=Sx(i,e.range),a=XD(i,e.useSharedArrayBuffer,o);n._indirectBuffer=a,s=Cx(i,0,a.length,a),r=[{offset:0,count:a.length}]}else{ND(i,e);const o=wx(i,e.range)[0];s=Cx(i,o.offset,o.count),r=Sx(i,e.range)}n._roots=r.map(o=>{const a=qD(n,s,o.offset,o.count,e),l=gf(a),c=new t(li*l);return HD(0,a,c),c})}class es{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(e,t){let i=1/0,s=-1/0;for(let r=0,o=e.length;r<o;r++){const l=e[r][t];i=l<i?l:i,s=l>s?l:s}this.min=i,this.max=s}setFromPoints(e,t){let i=1/0,s=-1/0;for(let r=0,o=t.length;r<o;r++){const a=t[r],l=e.dot(a);i=l<i?l:i,s=l>s?l:s}this.min=i,this.max=s}isSeparated(e){return this.min>e.max||e.min>this.max}}es.prototype.setFromBox=(function(){const n=new v.Vector3;return function(t,i){const s=i.min,r=i.max;let o=1/0,a=-1/0;for(let l=0;l<=1;l++)for(let c=0;c<=1;c++)for(let h=0;h<=1;h++){n.x=s.x*l+r.x*(1-l),n.y=s.y*c+r.y*(1-c),n.z=s.z*h+r.z*(1-h);const d=t.dot(n);o=Math.min(d,o),a=Math.max(d,a)}this.min=o,this.max=a}})();const KD=(function(){const n=new v.Vector3,e=new v.Vector3,t=new v.Vector3;return function(s,r,o){const a=s.start,l=n,c=r.start,h=e;t.subVectors(a,c),n.subVectors(s.end,s.start),e.subVectors(r.end,r.start);const d=t.dot(h),f=h.dot(l),u=h.dot(h),g=t.dot(l),m=l.dot(l)*u-f*f;let A,x;m!==0?A=(d*f-g*u)/m:A=0,x=(d+A*f)/u,o.x=A,o.y=x}})(),Af=(function(){const n=new v.Vector2,e=new v.Vector3,t=new v.Vector3;return function(s,r,o,a){KD(s,r,n);let l=n.x,c=n.y;if(l>=0&&l<=1&&c>=0&&c<=1){s.at(l,o),r.at(c,a);return}else if(l>=0&&l<=1){c<0?r.at(0,a):r.at(1,a),s.closestPointToPoint(a,!0,o);return}else if(c>=0&&c<=1){l<0?s.at(0,o):s.at(1,o),r.closestPointToPoint(o,!0,a);return}else{let h;l<0?h=s.start:h=s.end;let d;c<0?d=r.start:d=r.end;const f=e,u=t;if(s.closestPointToPoint(d,!0,e),r.closestPointToPoint(h,!0,t),f.distanceToSquared(d)<=u.distanceToSquared(h)){o.copy(f),a.copy(d);return}else{o.copy(h),a.copy(u);return}}}})(),$D=(function(){const n=new v.Vector3,e=new v.Vector3,t=new v.Plane,i=new v.Line3;return function(r,o){const{radius:a,center:l}=r,{a:c,b:h,c:d}=o;if(i.start=c,i.end=h,i.closestPointToPoint(l,!0,n).distanceTo(l)<=a||(i.start=c,i.end=d,i.closestPointToPoint(l,!0,n).distanceTo(l)<=a)||(i.start=h,i.end=d,i.closestPointToPoint(l,!0,n).distanceTo(l)<=a))return!0;const p=o.getPlane(t);if(Math.abs(p.distanceToPoint(l))<=a){const A=p.projectPoint(l,e);if(o.containsPoint(A))return!0}return!1}})(),JD=["x","y","z"],ts=1e-15,Bx=ts*ts;function Vi(n){return Math.abs(n)<ts}class Qi extends v.Triangle{constructor(...e){super(...e),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new v.Vector3),this.satBounds=new Array(4).fill().map(()=>new es),this.points=[this.a,this.b,this.c],this.plane=new v.Plane,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new v.Line3,this.needsUpdate=!0}intersectsSphere(e){return $D(e,this)}update(){const e=this.a,t=this.b,i=this.c,s=this.points,r=this.satAxes,o=this.satBounds,a=r[0],l=o[0];this.getNormal(a),l.setFromPoints(a,s);const c=r[1],h=o[1];c.subVectors(e,t),h.setFromPoints(c,s);const d=r[2],f=o[2];d.subVectors(t,i),f.setFromPoints(d,s);const u=r[3],g=o[3];u.subVectors(i,e),g.setFromPoints(u,s);const p=c.length(),m=d.length(),A=u.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,p<ts?m<ts||A<ts?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(i)):m<ts?A<ts?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(e)):A<ts&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(i),this.degenerateSegment.end.copy(t)),this.plane.setFromNormalAndCoplanarPoint(a,e),this.needsUpdate=!1}}Qi.prototype.closestPointToSegment=(function(){const n=new v.Vector3,e=new v.Vector3,t=new v.Line3;return function(s,r=null,o=null){const{start:a,end:l}=s,c=this.points;let h,d=1/0;for(let f=0;f<3;f++){const u=(f+1)%3;t.start.copy(c[f]),t.end.copy(c[u]),Af(t,s,n,e),h=n.distanceToSquared(e),h<d&&(d=h,r&&r.copy(n),o&&o.copy(e))}return this.closestPointToPoint(a,n),h=a.distanceToSquared(n),h<d&&(d=h,r&&r.copy(n),o&&o.copy(a)),this.closestPointToPoint(l,n),h=l.distanceToSquared(n),h<d&&(d=h,r&&r.copy(n),o&&o.copy(l)),Math.sqrt(d)}})(),Qi.prototype.intersectsTriangle=(function(){const n=new Qi,e=new es,t=new es,i=new v.Vector3,s=new v.Vector3,r=new v.Vector3,o=new v.Vector3,a=new v.Line3,l=new v.Line3,c=new v.Vector3,h=new v.Vector2,d=new v.Vector2;function f(b,y,_,S){const C=i;!b.isDegenerateIntoPoint&&!b.isDegenerateIntoSegment?C.copy(b.plane.normal):C.copy(y.plane.normal);const D=b.satBounds,M=b.satAxes;for(let T=1;T<4;T++){const R=D[T],E=M[T];if(e.setFromPoints(E,y.points),R.isSeparated(e)||(o.copy(C).cross(E),e.setFromPoints(o,b.points),t.setFromPoints(o,y.points),e.isSeparated(t)))return!1}const I=y.satBounds,L=y.satAxes;for(let T=1;T<4;T++){const R=I[T],E=L[T];if(e.setFromPoints(E,b.points),R.isSeparated(e)||(o.crossVectors(C,E),e.setFromPoints(o,b.points),t.setFromPoints(o,y.points),e.isSeparated(t)))return!1}return _&&(S||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),_.start.set(0,0,0),_.end.set(0,0,0)),!0}function u(b,y,_,S,C,D,M,I,L,T,R){let E=M/(M-I);T.x=S+(C-S)*E,R.start.subVectors(y,b).multiplyScalar(E).add(b),E=M/(M-L),T.y=S+(D-S)*E,R.end.subVectors(_,b).multiplyScalar(E).add(b)}function g(b,y,_,S,C,D,M,I,L,T,R){if(C>0)u(b.c,b.a,b.b,S,y,_,L,M,I,T,R);else if(D>0)u(b.b,b.a,b.c,_,y,S,I,M,L,T,R);else if(I*L>0||M!=0)u(b.a,b.b,b.c,y,_,S,M,I,L,T,R);else if(I!=0)u(b.b,b.a,b.c,_,y,S,I,M,L,T,R);else if(L!=0)u(b.c,b.a,b.b,S,y,_,L,M,I,T,R);else return!0;return!1}function p(b,y,_,S){const C=y.degenerateSegment,D=b.plane.distanceToPoint(C.start),M=b.plane.distanceToPoint(C.end);return Vi(D)?Vi(M)?f(b,y,_,S):(_&&(_.start.copy(C.start),_.end.copy(C.start)),b.containsPoint(C.start)):Vi(M)?(_&&(_.start.copy(C.end),_.end.copy(C.end)),b.containsPoint(C.end)):b.plane.intersectLine(C,i)!=null?(_&&(_.start.copy(i),_.end.copy(i)),b.containsPoint(i)):!1}function m(b,y,_){const S=y.a;return Vi(b.plane.distanceToPoint(S))&&b.containsPoint(S)?(_&&(_.start.copy(S),_.end.copy(S)),!0):!1}function A(b,y,_){const S=b.degenerateSegment,C=y.a;return S.closestPointToPoint(C,!0,i),C.distanceToSquared(i)<Bx?(_&&(_.start.copy(C),_.end.copy(C)),!0):!1}function x(b,y,_,S){if(b.isDegenerateIntoSegment)if(y.isDegenerateIntoSegment){const C=b.degenerateSegment,D=y.degenerateSegment,M=s,I=r;C.delta(M),D.delta(I);const L=i.subVectors(D.start,C.start),T=M.x*I.y-M.y*I.x;if(Vi(T))return!1;const R=(L.x*I.y-L.y*I.x)/T,E=-(M.x*L.y-M.y*L.x)/T;if(R<0||R>1||E<0||E>1)return!1;const F=C.start.z+M.z*R,N=D.start.z+I.z*E;return Vi(F-N)?(_&&(_.start.copy(C.start).addScaledVector(M,R),_.end.copy(C.start).addScaledVector(M,R)),!0):!1}else return y.isDegenerateIntoPoint?A(b,y,_):p(y,b,_,S);else{if(b.isDegenerateIntoPoint)return y.isDegenerateIntoPoint?y.a.distanceToSquared(b.a)<Bx?(_&&(_.start.copy(b.a),_.end.copy(b.a)),!0):!1:y.isDegenerateIntoSegment?A(y,b,_):m(y,b,_);if(y.isDegenerateIntoPoint)return m(b,y,_);if(y.isDegenerateIntoSegment)return p(b,y,_,S)}}return function(y,_=null,S=!1){this.needsUpdate&&this.update(),y.isExtendedTriangle?y.needsUpdate&&y.update():(n.copy(y),n.update(),y=n);const C=x(this,y,_,S);if(C!==void 0)return C;const D=this.plane,M=y.plane;let I=M.distanceToPoint(this.a),L=M.distanceToPoint(this.b),T=M.distanceToPoint(this.c);Vi(I)&&(I=0),Vi(L)&&(L=0),Vi(T)&&(T=0);const R=I*L,E=I*T;if(R>0&&E>0)return!1;let F=D.distanceToPoint(y.a),N=D.distanceToPoint(y.b),H=D.distanceToPoint(y.c);Vi(F)&&(F=0),Vi(N)&&(N=0),Vi(H)&&(H=0);const V=F*N,U=F*H;if(V>0&&U>0)return!1;s.copy(D.normal),r.copy(M.normal);const q=s.cross(r);let G=0,j=Math.abs(q.x);const oe=Math.abs(q.y);oe>j&&(j=oe,G=1),Math.abs(q.z)>j&&(G=2);const ue=JD[G],se=this.a[ue],he=this.b[ue],Ae=this.c[ue],_e=y.a[ue],Me=y.b[ue],Oe=y.c[ue];if(g(this,se,he,Ae,R,E,I,L,T,h,a))return f(this,y,_,S);if(g(y,_e,Me,Oe,V,U,F,N,H,d,l))return f(this,y,_,S);if(h.y<h.x){const it=h.y;h.y=h.x,h.x=it,c.copy(a.start),a.start.copy(a.end),a.end.copy(c)}if(d.y<d.x){const it=d.y;d.y=d.x,d.x=it,c.copy(l.start),l.start.copy(l.end),l.end.copy(c)}return h.y<d.x||d.y<h.x?!1:(_&&(d.x>h.x?_.start.copy(l.start):_.start.copy(a.start),d.y<h.y?_.end.copy(l.end):_.end.copy(a.end)),!0)}})(),Qi.prototype.distanceToPoint=(function(){const n=new v.Vector3;return function(t){return this.closestPointToPoint(t,n),t.distanceTo(n)}})(),Qi.prototype.distanceToTriangle=(function(){const n=new v.Vector3,e=new v.Vector3,t=["a","b","c"],i=new v.Line3,s=new v.Line3;return function(o,a=null,l=null){const c=a||l?i:null;if(this.intersectsTriangle(o,c))return(a||l)&&(a&&c.getCenter(a),l&&c.getCenter(l)),0;let h=1/0;for(let d=0;d<3;d++){let f;const u=t[d],g=o[u];this.closestPointToPoint(g,n),f=g.distanceToSquared(n),f<h&&(h=f,a&&a.copy(n),l&&l.copy(g));const p=this[u];o.closestPointToPoint(p,n),f=p.distanceToSquared(n),f<h&&(h=f,a&&a.copy(p),l&&l.copy(n))}for(let d=0;d<3;d++){const f=t[d],u=t[(d+1)%3];i.set(this[f],this[u]);for(let g=0;g<3;g++){const p=t[g],m=t[(g+1)%3];s.set(o[p],o[m]),Af(i,s,n,e);const A=n.distanceToSquared(e);A<h&&(h=A,a&&a.copy(n),l&&l.copy(e))}}return Math.sqrt(h)}})();class ci{constructor(e,t,i){this.isOrientedBox=!0,this.min=new v.Vector3,this.max=new v.Vector3,this.matrix=new v.Matrix4,this.invMatrix=new v.Matrix4,this.points=new Array(8).fill().map(()=>new v.Vector3),this.satAxes=new Array(3).fill().map(()=>new v.Vector3),this.satBounds=new Array(3).fill().map(()=>new es),this.alignedSatBounds=new Array(3).fill().map(()=>new es),this.needsUpdate=!1,e&&this.min.copy(e),t&&this.max.copy(t),i&&this.matrix.copy(i)}set(e,t,i){this.min.copy(e),this.max.copy(t),this.matrix.copy(i),this.needsUpdate=!0}copy(e){this.min.copy(e.min),this.max.copy(e.max),this.matrix.copy(e.matrix),this.needsUpdate=!0}}ci.prototype.update=(function(){return function(){const e=this.matrix,t=this.min,i=this.max,s=this.points;for(let c=0;c<=1;c++)for(let h=0;h<=1;h++)for(let d=0;d<=1;d++){const f=1*c|2*h|4*d,u=s[f];u.x=c?i.x:t.x,u.y=h?i.y:t.y,u.z=d?i.z:t.z,u.applyMatrix4(e)}const r=this.satBounds,o=this.satAxes,a=s[0];for(let c=0;c<3;c++){const h=o[c],d=r[c],f=1<<c,u=s[f];h.subVectors(a,u),d.setFromPoints(h,s)}const l=this.alignedSatBounds;l[0].setFromPointsField(s,"x"),l[1].setFromPointsField(s,"y"),l[2].setFromPointsField(s,"z"),this.invMatrix.copy(this.matrix).invert(),this.needsUpdate=!1}})(),ci.prototype.intersectsBox=(function(){const n=new es;return function(t){this.needsUpdate&&this.update();const i=t.min,s=t.max,r=this.satBounds,o=this.satAxes,a=this.alignedSatBounds;if(n.min=i.x,n.max=s.x,a[0].isSeparated(n)||(n.min=i.y,n.max=s.y,a[1].isSeparated(n))||(n.min=i.z,n.max=s.z,a[2].isSeparated(n)))return!1;for(let l=0;l<3;l++){const c=o[l],h=r[l];if(n.setFromBox(c,t),h.isSeparated(n))return!1}return!0}})(),ci.prototype.intersectsTriangle=(function(){const n=new Qi,e=new Array(3),t=new es,i=new es,s=new v.Vector3;return function(o){this.needsUpdate&&this.update(),o.isExtendedTriangle?o.needsUpdate&&o.update():(n.copy(o),n.update(),o=n);const a=this.satBounds,l=this.satAxes;e[0]=o.a,e[1]=o.b,e[2]=o.c;for(let f=0;f<3;f++){const u=a[f],g=l[f];if(t.setFromPoints(g,e),u.isSeparated(t))return!1}const c=o.satBounds,h=o.satAxes,d=this.points;for(let f=0;f<3;f++){const u=c[f],g=h[f];if(t.setFromPoints(g,d),u.isSeparated(t))return!1}for(let f=0;f<3;f++){const u=l[f];for(let g=0;g<4;g++){const p=h[g];if(s.crossVectors(u,p),t.setFromPoints(s,e),i.setFromPoints(s,d),t.isSeparated(i))return!1}}return!0}})(),ci.prototype.closestPointToPoint=(function(){return function(e,t){return this.needsUpdate&&this.update(),t.copy(e).applyMatrix4(this.invMatrix).clamp(this.min,this.max).applyMatrix4(this.matrix),t}})(),ci.prototype.distanceToPoint=(function(){const n=new v.Vector3;return function(t){return this.closestPointToPoint(t,n),t.distanceTo(n)}})(),ci.prototype.distanceToBox=(function(){const n=["x","y","z"],e=new Array(12).fill().map(()=>new v.Line3),t=new Array(12).fill().map(()=>new v.Line3),i=new v.Vector3,s=new v.Vector3;return function(o,a=0,l=null,c=null){if(this.needsUpdate&&this.update(),this.intersectsBox(o))return(l||c)&&(o.getCenter(s),this.closestPointToPoint(s,i),o.closestPointToPoint(i,s),l&&l.copy(i),c&&c.copy(s)),0;const h=a*a,d=o.min,f=o.max,u=this.points;let g=1/0;for(let m=0;m<8;m++){const A=u[m];s.copy(A).clamp(d,f);const x=A.distanceToSquared(s);if(x<g&&(g=x,l&&l.copy(A),c&&c.copy(s),x<h))return Math.sqrt(x)}let p=0;for(let m=0;m<3;m++)for(let A=0;A<=1;A++)for(let x=0;x<=1;x++){const b=(m+1)%3,y=(m+2)%3,_=A<<b|x<<y,S=1<<m|A<<b|x<<y,C=u[_],D=u[S];e[p].set(C,D);const I=n[m],L=n[b],T=n[y],R=t[p],E=R.start,F=R.end;E[I]=d[I],E[L]=A?d[L]:f[L],E[T]=x?d[T]:f[L],F[I]=f[I],F[L]=A?d[L]:f[L],F[T]=x?d[T]:f[L],p++}for(let m=0;m<=1;m++)for(let A=0;A<=1;A++)for(let x=0;x<=1;x++){s.x=m?f.x:d.x,s.y=A?f.y:d.y,s.z=x?f.z:d.z,this.closestPointToPoint(s,i);const b=s.distanceToSquared(i);if(b<g&&(g=b,l&&l.copy(i),c&&c.copy(s),b<h))return Math.sqrt(b)}for(let m=0;m<12;m++){const A=e[m];for(let x=0;x<12;x++){const b=t[x];Af(A,b,i,s);const y=i.distanceToSquared(s);if(y<g&&(g=y,l&&l.copy(i),c&&c.copy(s),y<h))return Math.sqrt(y)}}return Math.sqrt(g)}})();class xf{constructor(e){this._getNewPrimitive=e,this._primitives=[]}getPrimitive(){const e=this._primitives;return e.length===0?this._getNewPrimitive():e.pop()}releasePrimitive(e){this._primitives.push(e)}}class ZD extends xf{constructor(){super(()=>new Qi)}}const ji=new ZD;function Xt(n,e){return e[n+15]===_x}function Ti(n,e){return e[n+6]}function Wi(n,e){return e[n+14]}function Yt(n){return n+Ht}function Kt(n,e){const t=e[n+6];return n+t*Ht}function bf(n,e){return e[n+7]}function VF(n){return n}class eB{constructor(){this.float32Array=null,this.uint16Array=null,this.uint32Array=null;const e=[];let t=null;this.setBuffer=i=>{t&&e.push(t),t=i,this.float32Array=new Float32Array(i),this.uint16Array=new Uint16Array(i),this.uint32Array=new Uint32Array(i)},this.clearBuffer=()=>{t=null,this.float32Array=null,this.uint16Array=null,this.uint32Array=null,e.length!==0&&this.setBuffer(e.pop())}}}const _t=new eB;let Is,Ao;const xo=[],Rc=new xf(()=>new v.Box3);function tB(n,e,t,i,s,r){Is=Rc.getPrimitive(),Ao=Rc.getPrimitive(),xo.push(Is,Ao),_t.setBuffer(n._roots[e]);const o=yf(0,n.geometry,t,i,s,r);_t.clearBuffer(),Rc.releasePrimitive(Is),Rc.releasePrimitive(Ao),xo.pop(),xo.pop();const a=xo.length;return a>0&&(Ao=xo[a-1],Is=xo[a-2]),o}function yf(n,e,t,i,s=null,r=0,o=0){const{float32Array:a,uint16Array:l,uint32Array:c}=_t;let h=n*2;if(Xt(h,l)){const f=Ti(n,c),u=Wi(h,l);return It(n,a,Is),i(f,u,!1,o,r+n/Ht,Is)}else{let I=function(T){const{uint16Array:R,uint32Array:E}=_t;let F=T*2;for(;!Xt(F,R);)T=Yt(T),F=T*2;return Ti(T,E)},L=function(T){const{uint16Array:R,uint32Array:E}=_t;let F=T*2;for(;!Xt(F,R);)T=Kt(T,E),F=T*2;return Ti(T,E)+Wi(F,R)};const f=Yt(n),u=Kt(n,c);let g=f,p=u,m,A,x,b;if(s&&(x=Is,b=Ao,It(g,a,x),It(p,a,b),m=s(x),A=s(b),A<m)){g=u,p=f;const T=m;m=A,A=T,x=b}x||(x=Is,It(g,a,x));const y=Xt(g*2,l),_=t(x,y,m,o+1,r+g/Ht);let S;if(_===yx){const T=I(g),E=L(g)-T;S=i(T,E,!0,o+1,r+g/Ht,x)}else S=_&&yf(g,e,t,i,s,r,o+1);if(S)return!0;b=Ao,It(p,a,b);const C=Xt(p*2,l),D=t(b,C,A,o+1,r+p/Ht);let M;if(D===yx){const T=I(p),E=L(p)-T;M=i(T,E,!0,o+1,r+p/Ht,b)}else M=D&&yf(p,e,t,i,s,r,o+1);return!!M}}const wa=new v.Vector3,vf=new v.Vector3;function iB(n,e,t={},i=0,s=1/0){const r=i*i,o=s*s;let a=1/0,l=null;if(n.shapecast({boundsTraverseOrder:h=>(wa.copy(e).clamp(h.min,h.max),wa.distanceToSquared(e)),intersectsBounds:(h,d,f)=>f<a&&f<o,intersectsTriangle:(h,d)=>{h.closestPointToPoint(e,wa);const f=e.distanceToSquared(wa);return f<a&&(vf.copy(wa),a=f,l=d),f<r}}),a===1/0)return null;const c=Math.sqrt(a);return t.point?t.point.copy(vf):t.point=vf.clone(),t.distance=c,t.faceIndex=l,t}const kc=parseInt(v.REVISION)>=169,nB=parseInt(v.REVISION)<=161,gr=new v.Vector3,mr=new v.Vector3,Ar=new v.Vector3,Fc=new v.Vector2,Oc=new v.Vector2,Uc=new v.Vector2,Px=new v.Vector3,Lx=new v.Vector3,Rx=new v.Vector3,Sa=new v.Vector3;function sB(n,e,t,i,s,r,o,a){let l;if(r===v.BackSide?l=n.intersectTriangle(i,t,e,!0,s):l=n.intersectTriangle(e,t,i,r!==v.DoubleSide,s),l===null)return null;const c=n.origin.distanceTo(s);return c<o||c>a?null:{distance:c,point:s.clone()}}function kx(n,e,t,i,s,r,o,a,l,c,h){gr.fromBufferAttribute(e,r),mr.fromBufferAttribute(e,o),Ar.fromBufferAttribute(e,a);const d=sB(n,gr,mr,Ar,Sa,l,c,h);if(d){if(i){Fc.fromBufferAttribute(i,r),Oc.fromBufferAttribute(i,o),Uc.fromBufferAttribute(i,a),d.uv=new v.Vector2;const u=v.Triangle.getInterpolation(Sa,gr,mr,Ar,Fc,Oc,Uc,d.uv);kc||(d.uv=u)}if(s){Fc.fromBufferAttribute(s,r),Oc.fromBufferAttribute(s,o),Uc.fromBufferAttribute(s,a),d.uv1=new v.Vector2;const u=v.Triangle.getInterpolation(Sa,gr,mr,Ar,Fc,Oc,Uc,d.uv1);kc||(d.uv1=u),nB&&(d.uv2=d.uv1)}if(t){Px.fromBufferAttribute(t,r),Lx.fromBufferAttribute(t,o),Rx.fromBufferAttribute(t,a),d.normal=new v.Vector3;const u=v.Triangle.getInterpolation(Sa,gr,mr,Ar,Px,Lx,Rx,d.normal);d.normal.dot(n.direction)>0&&d.normal.multiplyScalar(-1),kc||(d.normal=u)}const f={a:r,b:o,c:a,normal:new v.Vector3,materialIndex:0};if(v.Triangle.getNormal(gr,mr,Ar,f.normal),d.face=f,d.faceIndex=r,kc){const u=new v.Vector3;v.Triangle.getBarycoord(Sa,gr,mr,Ar,u),d.barycoord=u}}return d}function Fx(n){return n&&n.isMaterial?n.side:n}function Nc(n,e,t,i,s,r,o){const a=i*3;let l=a+0,c=a+1,h=a+2;const{index:d,groups:f}=n;n.index&&(l=d.getX(l),c=d.getX(c),h=d.getX(h));const{position:u,normal:g,uv:p,uv1:m}=n.attributes;if(Array.isArray(e)){const A=i*3;for(let x=0,b=f.length;x<b;x++){const{start:y,count:_,materialIndex:S}=f[x];if(A>=y&&A<y+_){const C=Fx(e[S]),D=kx(t,u,g,p,m,l,c,h,C,r,o);if(D)if(D.faceIndex=i,D.face.materialIndex=S,s)s.push(D);else return D}}}else{const A=Fx(e),x=kx(t,u,g,p,m,l,c,h,A,r,o);if(x)if(x.faceIndex=i,x.face.materialIndex=0,s)s.push(x);else return x}return null}function Nt(n,e,t,i){const s=n.a,r=n.b,o=n.c;let a=e,l=e+1,c=e+2;t&&(a=t.getX(a),l=t.getX(l),c=t.getX(c)),s.x=i.getX(a),s.y=i.getY(a),s.z=i.getZ(a),r.x=i.getX(l),r.y=i.getY(l),r.z=i.getZ(l),o.x=i.getX(c),o.y=i.getY(c),o.z=i.getZ(c)}function rB(n,e,t,i,s,r,o,a){const{geometry:l,_indirectBuffer:c}=n;for(let h=i,d=i+s;h<d;h++)Nc(l,e,t,h,r,o,a)}function oB(n,e,t,i,s,r,o){const{geometry:a,_indirectBuffer:l}=n;let c=1/0,h=null;for(let d=i,f=i+s;d<f;d++){let u;u=Nc(a,e,t,d,null,r,o),u&&u.distance<c&&(h=u,c=u.distance)}return h}function aB(n,e,t,i,s,r,o){const{geometry:a}=t,{index:l}=a,c=a.attributes.position;for(let h=n,d=e+n;h<d;h++){let f;if(f=h,Nt(o,f*3,l,c),o.needsUpdate=!0,i(o,f,s,r))return!0}return!1}function lB(n,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=n.geometry,i=t.index?t.index.array:null,s=t.attributes.position;let r,o,a,l,c=0;const h=n._roots;for(let f=0,u=h.length;f<u;f++)r=h[f],o=new Uint32Array(r),a=new Uint16Array(r),l=new Float32Array(r),d(0,c),c+=r.byteLength;function d(f,u,g=!1){const p=f*2;if(Xt(p,a)){const m=o[f+6],A=a[p+14];let x=1/0,b=1/0,y=1/0,_=-1/0,S=-1/0,C=-1/0;for(let D=3*m,M=3*(m+A);D<M;D++){let I=i[D];const L=s.getX(I),T=s.getY(I),R=s.getZ(I);L<x&&(x=L),L>_&&(_=L),T<b&&(b=T),T>S&&(S=T),R<y&&(y=R),R>C&&(C=R)}return l[f+0]!==x||l[f+1]!==b||l[f+2]!==y||l[f+3]!==_||l[f+4]!==S||l[f+5]!==C?(l[f+0]=x,l[f+1]=b,l[f+2]=y,l[f+3]=_,l[f+4]=S,l[f+5]=C,!0):!1}else{const m=Yt(f),A=Kt(f,o);let x=g,b=!1,y=!1;if(e){if(!x){const I=m/Ht+u/li,L=A/Ht+u/li;b=e.has(I),y=e.has(L),x=!b&&!y}}else b=!0,y=!0;const _=x||b,S=x||y;let C=!1;_&&(C=d(m,u,x));let D=!1;S&&(D=d(A,u,x));const M=C||D;if(M)for(let I=0;I<3;I++){const L=m+I,T=A+I,R=l[L],E=l[L+3],F=l[T],N=l[T+3];l[f+I]=R<F?R:F,l[f+I+3]=E>N?E:N}return M}}}function Ts(n,e,t,i,s){let r,o,a,l,c,h;const d=1/t.direction.x,f=1/t.direction.y,u=1/t.direction.z,g=t.origin.x,p=t.origin.y,m=t.origin.z;let A=e[n],x=e[n+3],b=e[n+1],y=e[n+3+1],_=e[n+2],S=e[n+3+2];return d>=0?(r=(A-g)*d,o=(x-g)*d):(r=(x-g)*d,o=(A-g)*d),f>=0?(a=(b-p)*f,l=(y-p)*f):(a=(y-p)*f,l=(b-p)*f),r>l||a>o||((a>r||isNaN(r))&&(r=a),(l<o||isNaN(o))&&(o=l),u>=0?(c=(_-m)*u,h=(S-m)*u):(c=(S-m)*u,h=(_-m)*u),r>h||c>o)?!1:((c>r||r!==r)&&(r=c),(h<o||o!==o)&&(o=h),r<=s&&o>=i)}function cB(n,e,t,i,s,r,o,a){const{geometry:l,_indirectBuffer:c}=n;for(let h=i,d=i+s;h<d;h++){let f=c?c[h]:h;Nc(l,e,t,f,r,o,a)}}function hB(n,e,t,i,s,r,o){const{geometry:a,_indirectBuffer:l}=n;let c=1/0,h=null;for(let d=i,f=i+s;d<f;d++){let u;u=Nc(a,e,t,l?l[d]:d,null,r,o),u&&u.distance<c&&(h=u,c=u.distance)}return h}function dB(n,e,t,i,s,r,o){const{geometry:a}=t,{index:l}=a,c=a.attributes.position;for(let h=n,d=e+n;h<d;h++){let f;if(f=t.resolveTriangleIndex(h),Nt(o,f*3,l,c),o.needsUpdate=!0,i(o,f,s,r))return!0}return!1}function uB(n,e,t,i,s,r,o){_t.setBuffer(n._roots[e]),_f(0,n,t,i,s,r,o),_t.clearBuffer()}function _f(n,e,t,i,s,r,o){const{float32Array:a,uint16Array:l,uint32Array:c}=_t,h=n*2;if(Xt(h,l)){const f=Ti(n,c),u=Wi(h,l);rB(e,t,i,f,u,s,r,o)}else{const f=Yt(n);Ts(f,a,i,r,o)&&_f(f,e,t,i,s,r,o);const u=Kt(n,c);Ts(u,a,i,r,o)&&_f(u,e,t,i,s,r,o)}}const fB=["x","y","z"];function pB(n,e,t,i,s,r){_t.setBuffer(n._roots[e]);const o=wf(0,n,t,i,s,r);return _t.clearBuffer(),o}function wf(n,e,t,i,s,r){const{float32Array:o,uint16Array:a,uint32Array:l}=_t;let c=n*2;if(Xt(c,a)){const d=Ti(n,l),f=Wi(c,a);return oB(e,t,i,d,f,s,r)}else{const d=bf(n,l),f=fB[d],g=i.direction[f]>=0;let p,m;g?(p=Yt(n),m=Kt(n,l)):(p=Kt(n,l),m=Yt(n));const x=Ts(p,o,i,s,r)?wf(p,e,t,i,s,r):null;if(x){const _=x.point[f];if(g?_<=o[m+d]:_>=o[m+d+3])return x}const y=Ts(m,o,i,s,r)?wf(m,e,t,i,s,r):null;return x&&y?x.distance<=y.distance?x:y:x||y||null}}const zc=new v.Box3,bo=new Qi,yo=new Qi,Ca=new v.Matrix4,Ox=new ci,Gc=new ci;function gB(n,e,t,i){_t.setBuffer(n._roots[e]);const s=Sf(0,n,t,i);return _t.clearBuffer(),s}function Sf(n,e,t,i,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=_t;let l=n*2;if(s===null&&(t.boundingBox||t.computeBoundingBox(),Ox.set(t.boundingBox.min,t.boundingBox.max,i),s=Ox),Xt(l,o)){const h=e.geometry,d=h.index,f=h.attributes.position,u=t.index,g=t.attributes.position,p=Ti(n,a),m=Wi(l,o);if(Ca.copy(i).invert(),t.boundsTree)return It(n,r,Gc),Gc.matrix.copy(Ca),Gc.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:x=>Gc.intersectsBox(x),intersectsTriangle:x=>{x.a.applyMatrix4(i),x.b.applyMatrix4(i),x.c.applyMatrix4(i),x.needsUpdate=!0;for(let b=p*3,y=(m+p)*3;b<y;b+=3)if(Nt(yo,b,d,f),yo.needsUpdate=!0,x.intersectsTriangle(yo))return!0;return!1}});{const A=pr(t);for(let x=p*3,b=(m+p)*3;x<b;x+=3){Nt(bo,x,d,f),bo.a.applyMatrix4(Ca),bo.b.applyMatrix4(Ca),bo.c.applyMatrix4(Ca),bo.needsUpdate=!0;for(let y=0,_=A*3;y<_;y+=3)if(Nt(yo,y,u,g),yo.needsUpdate=!0,bo.intersectsTriangle(yo))return!0}}}else{const h=Yt(n),d=Kt(n,a);return It(h,r,zc),!!(s.intersectsBox(zc)&&Sf(h,e,t,i,s)||(It(d,r,zc),s.intersectsBox(zc)&&Sf(d,e,t,i,s)))}}const Vc=new v.Matrix4,Cf=new ci,Ma=new ci,mB=new v.Vector3,AB=new v.Vector3,xB=new v.Vector3,bB=new v.Vector3;function yB(n,e,t,i={},s={},r=0,o=1/0){e.boundingBox||e.computeBoundingBox(),Cf.set(e.boundingBox.min,e.boundingBox.max,t),Cf.needsUpdate=!0;const a=n.geometry,l=a.attributes.position,c=a.index,h=e.attributes.position,d=e.index,f=ji.getPrimitive(),u=ji.getPrimitive();let g=mB,p=AB,m=null,A=null;s&&(m=xB,A=bB);let x=1/0,b=null,y=null;return Vc.copy(t).invert(),Ma.matrix.copy(Vc),n.shapecast({boundsTraverseOrder:_=>Cf.distanceToBox(_),intersectsBounds:(_,S,C)=>C<x&&C<o?(S&&(Ma.min.copy(_.min),Ma.max.copy(_.max),Ma.needsUpdate=!0),!0):!1,intersectsRange:(_,S)=>{if(e.boundsTree)return e.boundsTree.shapecast({boundsTraverseOrder:D=>Ma.distanceToBox(D),intersectsBounds:(D,M,I)=>I<x&&I<o,intersectsRange:(D,M)=>{for(let I=D,L=D+M;I<L;I++){Nt(u,3*I,d,h),u.a.applyMatrix4(t),u.b.applyMatrix4(t),u.c.applyMatrix4(t),u.needsUpdate=!0;for(let T=_,R=_+S;T<R;T++){Nt(f,3*T,c,l),f.needsUpdate=!0;const E=f.distanceToTriangle(u,g,m);if(E<x&&(p.copy(g),A&&A.copy(m),x=E,b=T,y=I),E<r)return!0}}}});{const C=pr(e);for(let D=0,M=C;D<M;D++){Nt(u,3*D,d,h),u.a.applyMatrix4(t),u.b.applyMatrix4(t),u.c.applyMatrix4(t),u.needsUpdate=!0;for(let I=_,L=_+S;I<L;I++){Nt(f,3*I,c,l),f.needsUpdate=!0;const T=f.distanceToTriangle(u,g,m);if(T<x&&(p.copy(g),A&&A.copy(m),x=T,b=I,y=D),T<r)return!0}}}}}),ji.releasePrimitive(f),ji.releasePrimitive(u),x===1/0?null:(i.point?i.point.copy(p):i.point=p.clone(),i.distance=x,i.faceIndex=b,s&&(s.point?s.point.copy(A):s.point=A.clone(),s.point.applyMatrix4(Vc),p.applyMatrix4(Vc),s.distance=p.sub(s.point).length(),s.faceIndex=y),i)}function vB(n,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=n.geometry,i=t.index?t.index.array:null,s=t.attributes.position;let r,o,a,l,c=0;const h=n._roots;for(let f=0,u=h.length;f<u;f++)r=h[f],o=new Uint32Array(r),a=new Uint16Array(r),l=new Float32Array(r),d(0,c),c+=r.byteLength;function d(f,u,g=!1){const p=f*2;if(Xt(p,a)){const m=o[f+6],A=a[p+14];let x=1/0,b=1/0,y=1/0,_=-1/0,S=-1/0,C=-1/0;for(let D=m,M=m+A;D<M;D++){const I=3*n.resolveTriangleIndex(D);for(let L=0;L<3;L++){let T=I+L;T=i?i[T]:T;const R=s.getX(T),E=s.getY(T),F=s.getZ(T);R<x&&(x=R),R>_&&(_=R),E<b&&(b=E),E>S&&(S=E),F<y&&(y=F),F>C&&(C=F)}}return l[f+0]!==x||l[f+1]!==b||l[f+2]!==y||l[f+3]!==_||l[f+4]!==S||l[f+5]!==C?(l[f+0]=x,l[f+1]=b,l[f+2]=y,l[f+3]=_,l[f+4]=S,l[f+5]=C,!0):!1}else{const m=Yt(f),A=Kt(f,o);let x=g,b=!1,y=!1;if(e){if(!x){const I=m/Ht+u/li,L=A/Ht+u/li;b=e.has(I),y=e.has(L),x=!b&&!y}}else b=!0,y=!0;const _=x||b,S=x||y;let C=!1;_&&(C=d(m,u,x));let D=!1;S&&(D=d(A,u,x));const M=C||D;if(M)for(let I=0;I<3;I++){const L=m+I,T=A+I,R=l[L],E=l[L+3],F=l[T],N=l[T+3];l[f+I]=R<F?R:F,l[f+I+3]=E>N?E:N}return M}}}function _B(n,e,t,i,s,r,o){_t.setBuffer(n._roots[e]),Mf(0,n,t,i,s,r,o),_t.clearBuffer()}function Mf(n,e,t,i,s,r,o){const{float32Array:a,uint16Array:l,uint32Array:c}=_t,h=n*2;if(Xt(h,l)){const f=Ti(n,c),u=Wi(h,l);cB(e,t,i,f,u,s,r,o)}else{const f=Yt(n);Ts(f,a,i,r,o)&&Mf(f,e,t,i,s,r,o);const u=Kt(n,c);Ts(u,a,i,r,o)&&Mf(u,e,t,i,s,r,o)}}const wB=["x","y","z"];function SB(n,e,t,i,s,r){_t.setBuffer(n._roots[e]);const o=Ef(0,n,t,i,s,r);return _t.clearBuffer(),o}function Ef(n,e,t,i,s,r){const{float32Array:o,uint16Array:a,uint32Array:l}=_t;let c=n*2;if(Xt(c,a)){const d=Ti(n,l),f=Wi(c,a);return hB(e,t,i,d,f,s,r)}else{const d=bf(n,l),f=wB[d],g=i.direction[f]>=0;let p,m;g?(p=Yt(n),m=Kt(n,l)):(p=Kt(n,l),m=Yt(n));const x=Ts(p,o,i,s,r)?Ef(p,e,t,i,s,r):null;if(x){const _=x.point[f];if(g?_<=o[m+d]:_>=o[m+d+3])return x}const y=Ts(m,o,i,s,r)?Ef(m,e,t,i,s,r):null;return x&&y?x.distance<=y.distance?x:y:x||y||null}}const Qc=new v.Box3,vo=new Qi,_o=new Qi,Ea=new v.Matrix4,Ux=new ci,jc=new ci;function CB(n,e,t,i){_t.setBuffer(n._roots[e]);const s=If(0,n,t,i);return _t.clearBuffer(),s}function If(n,e,t,i,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=_t;let l=n*2;if(s===null&&(t.boundingBox||t.computeBoundingBox(),Ux.set(t.boundingBox.min,t.boundingBox.max,i),s=Ux),Xt(l,o)){const h=e.geometry,d=h.index,f=h.attributes.position,u=t.index,g=t.attributes.position,p=Ti(n,a),m=Wi(l,o);if(Ea.copy(i).invert(),t.boundsTree)return It(n,r,jc),jc.matrix.copy(Ea),jc.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:x=>jc.intersectsBox(x),intersectsTriangle:x=>{x.a.applyMatrix4(i),x.b.applyMatrix4(i),x.c.applyMatrix4(i),x.needsUpdate=!0;for(let b=p,y=m+p;b<y;b++)if(Nt(_o,3*e.resolveTriangleIndex(b),d,f),_o.needsUpdate=!0,x.intersectsTriangle(_o))return!0;return!1}});{const A=pr(t);for(let x=p,b=m+p;x<b;x++){const y=e.resolveTriangleIndex(x);Nt(vo,3*y,d,f),vo.a.applyMatrix4(Ea),vo.b.applyMatrix4(Ea),vo.c.applyMatrix4(Ea),vo.needsUpdate=!0;for(let _=0,S=A*3;_<S;_+=3)if(Nt(_o,_,u,g),_o.needsUpdate=!0,vo.intersectsTriangle(_o))return!0}}}else{const h=Yt(n),d=Kt(n,a);return It(h,r,Qc),!!(s.intersectsBox(Qc)&&If(h,e,t,i,s)||(It(d,r,Qc),s.intersectsBox(Qc)&&If(d,e,t,i,s)))}}const Wc=new v.Matrix4,Tf=new ci,Ia=new ci,MB=new v.Vector3,EB=new v.Vector3,IB=new v.Vector3,TB=new v.Vector3;function DB(n,e,t,i={},s={},r=0,o=1/0){e.boundingBox||e.computeBoundingBox(),Tf.set(e.boundingBox.min,e.boundingBox.max,t),Tf.needsUpdate=!0;const a=n.geometry,l=a.attributes.position,c=a.index,h=e.attributes.position,d=e.index,f=ji.getPrimitive(),u=ji.getPrimitive();let g=MB,p=EB,m=null,A=null;s&&(m=IB,A=TB);let x=1/0,b=null,y=null;return Wc.copy(t).invert(),Ia.matrix.copy(Wc),n.shapecast({boundsTraverseOrder:_=>Tf.distanceToBox(_),intersectsBounds:(_,S,C)=>C<x&&C<o?(S&&(Ia.min.copy(_.min),Ia.max.copy(_.max),Ia.needsUpdate=!0),!0):!1,intersectsRange:(_,S)=>{if(e.boundsTree){const C=e.boundsTree;return C.shapecast({boundsTraverseOrder:D=>Ia.distanceToBox(D),intersectsBounds:(D,M,I)=>I<x&&I<o,intersectsRange:(D,M)=>{for(let I=D,L=D+M;I<L;I++){const T=C.resolveTriangleIndex(I);Nt(u,3*T,d,h),u.a.applyMatrix4(t),u.b.applyMatrix4(t),u.c.applyMatrix4(t),u.needsUpdate=!0;for(let R=_,E=_+S;R<E;R++){const F=n.resolveTriangleIndex(R);Nt(f,3*F,c,l),f.needsUpdate=!0;const N=f.distanceToTriangle(u,g,m);if(N<x&&(p.copy(g),A&&A.copy(m),x=N,b=R,y=I),N<r)return!0}}}})}else{const C=pr(e);for(let D=0,M=C;D<M;D++){Nt(u,3*D,d,h),u.a.applyMatrix4(t),u.b.applyMatrix4(t),u.c.applyMatrix4(t),u.needsUpdate=!0;for(let I=_,L=_+S;I<L;I++){const T=n.resolveTriangleIndex(I);Nt(f,3*T,c,l),f.needsUpdate=!0;const R=f.distanceToTriangle(u,g,m);if(R<x&&(p.copy(g),A&&A.copy(m),x=R,b=I,y=D),R<r)return!0}}}}}),ji.releasePrimitive(f),ji.releasePrimitive(u),x===1/0?null:(i.point?i.point.copy(p):i.point=p.clone(),i.distance=x,i.faceIndex=b,s&&(s.point?s.point.copy(A):s.point=A.clone(),s.point.applyMatrix4(Wc),p.applyMatrix4(Wc),s.distance=p.sub(s.point).length(),s.faceIndex=y),i)}function BB(){return typeof SharedArrayBuffer<"u"}const Ta=new _t.constructor,Hc=new _t.constructor,Ds=new xf(()=>new v.Box3),wo=new v.Box3,So=new v.Box3,Df=new v.Box3,Bf=new v.Box3;let Pf=!1;function PB(n,e,t,i){if(Pf)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");Pf=!0;const s=n._roots,r=e._roots;let o,a=0,l=0;const c=new v.Matrix4().copy(t).invert();for(let h=0,d=s.length;h<d;h++){Ta.setBuffer(s[h]),l=0;const f=Ds.getPrimitive();It(0,Ta.float32Array,f),f.applyMatrix4(c);for(let u=0,g=r.length;u<g&&(Hc.setBuffer(r[u]),o=rn(0,0,t,c,i,a,l,0,0,f),Hc.clearBuffer(),l+=r[u].byteLength/li,!o);u++);if(Ds.releasePrimitive(f),Ta.clearBuffer(),a+=s[h].byteLength/li,o)break}return Pf=!1,o}function rn(n,e,t,i,s,r=0,o=0,a=0,l=0,c=null,h=!1){let d,f;h?(d=Hc,f=Ta):(d=Ta,f=Hc);const u=d.float32Array,g=d.uint32Array,p=d.uint16Array,m=f.float32Array,A=f.uint32Array,x=f.uint16Array,b=n*2,y=e*2,_=Xt(b,p),S=Xt(y,x);let C=!1;if(S&&_)h?C=s(Ti(e,A),Wi(e*2,x),Ti(n,g),Wi(n*2,p),l,o+e/Ht,a,r+n/Ht):C=s(Ti(n,g),Wi(n*2,p),Ti(e,A),Wi(e*2,x),a,r+n/Ht,l,o+e/Ht);else if(S){const D=Ds.getPrimitive();It(e,m,D),D.applyMatrix4(t);const M=Yt(n),I=Kt(n,g);It(M,u,wo),It(I,u,So);const L=D.intersectsBox(wo),T=D.intersectsBox(So);C=L&&rn(e,M,i,t,s,o,r,l,a+1,D,!h)||T&&rn(e,I,i,t,s,o,r,l,a+1,D,!h),Ds.releasePrimitive(D)}else{const D=Yt(e),M=Kt(e,A);It(D,m,Df),It(M,m,Bf);const I=c.intersectsBox(Df),L=c.intersectsBox(Bf);if(I&&L)C=rn(n,D,t,i,s,r,o,a,l+1,c,h)||rn(n,M,t,i,s,r,o,a,l+1,c,h);else if(I)if(_)C=rn(n,D,t,i,s,r,o,a,l+1,c,h);else{const T=Ds.getPrimitive();T.copy(Df).applyMatrix4(t);const R=Yt(n),E=Kt(n,g);It(R,u,wo),It(E,u,So);const F=T.intersectsBox(wo),N=T.intersectsBox(So);C=F&&rn(D,R,i,t,s,o,r,l,a+1,T,!h)||N&&rn(D,E,i,t,s,o,r,l,a+1,T,!h),Ds.releasePrimitive(T)}else if(L)if(_)C=rn(n,M,t,i,s,r,o,a,l+1,c,h);else{const T=Ds.getPrimitive();T.copy(Bf).applyMatrix4(t);const R=Yt(n),E=Kt(n,g);It(R,u,wo),It(E,u,So);const F=T.intersectsBox(wo),N=T.intersectsBox(So);C=F&&rn(M,R,i,t,s,o,r,l,a+1,T,!h)||N&&rn(M,E,i,t,s,o,r,l,a+1,T,!h),Ds.releasePrimitive(T)}}return C}const Xc=new ci,Nx=new v.Box3,LB={strategy:bx,maxDepth:40,maxLeafTris:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null};class Lf{static serialize(e,t={}){t={cloneBuffers:!0,...t};const i=e.geometry,s=e._roots,r=e._indirectBuffer,o=i.getIndex(),a={version:1,roots:null,index:null,indirectBuffer:null};return t.cloneBuffers?(a.roots=s.map(l=>l.slice()),a.index=o?o.array.slice():null,a.indirectBuffer=r?r.slice():null):(a.roots=s,a.index=o?o.array:null,a.indirectBuffer=r),a}static deserialize(e,t,i={}){i={setIndex:!0,indirect:!!e.indirectBuffer,...i};const{index:s,roots:r,indirectBuffer:o}=e;e.version||(console.warn("MeshBVH.deserialize: Serialization format has been changed and will be fixed up. It is recommended to regenerate any stored serialized data."),l(r));const a=new Lf(t,{...i,[df]:!0});if(a._roots=r,a._indirectBuffer=o||null,i.setIndex){const c=t.getIndex();if(c===null){const h=new v.BufferAttribute(e.index,1,!1);t.setIndex(h)}else c.array!==s&&(c.array.set(s),c.needsUpdate=!0)}return a;function l(c){for(let h=0;h<c.length;h++){const d=c[h],f=new Uint32Array(d),u=new Uint16Array(d);for(let g=0,p=d.byteLength/li;g<p;g++){const m=Ht*g,A=2*m;Xt(A,u)||(f[m+6]=f[m+6]/Ht-g)}}}}get indirect(){return!!this._indirectBuffer}constructor(e,t={}){if(e.isBufferGeometry){if(e.index&&e.index.isInterleavedBufferAttribute)throw new Error("MeshBVH: InterleavedBufferAttribute is not supported for the index attribute.")}else throw new Error("MeshBVH: Only BufferGeometries are supported.");if(t=Object.assign({...LB,[df]:!1},t),t.useSharedArrayBuffer&&!BB())throw new Error("MeshBVH: SharedArrayBuffer is not available.");this.geometry=e,this._roots=null,this._indirectBuffer=null,t[df]||(YD(this,t),!e.boundingBox&&t.setBoundingBox&&(e.boundingBox=this.getBoundingBox(new v.Box3))),this.resolveTriangleIndex=t.indirect?i=>this._indirectBuffer[i]:i=>i}shiftTriangleOffsets(e){const t=this._indirectBuffer;if(t)for(let i=0,s=t.length;i<s;i++)t[i]+=e;else{const i=this._roots;for(let s=0;s<i.length;s++){const r=i[s],o=new Uint32Array(r),a=new Uint16Array(r),l=r.byteLength/li;for(let c=0;c<l;c++){const h=Ht*c,d=2*h;Xt(d,a)&&(o[h+6]+=e)}}}}refit(e=null){return(this.indirect?vB:lB)(this,e)}traverse(e,t=0){const i=this._roots[t],s=new Uint32Array(i),r=new Uint16Array(i);o(0);function o(a,l=0){const c=a*2,h=Xt(c,r);if(h){const d=s[a+6],f=r[c+14];e(l,h,new Float32Array(i,a*4,6),d,f)}else{const d=Yt(a),f=Kt(a,s),u=bf(a,s);e(l,h,new Float32Array(i,a*4,6),u)||(o(d,l+1),o(f,l+1))}}}raycast(e,t=v.FrontSide,i=0,s=1/0){const r=this._roots,o=[],a=this.indirect?_B:uB;for(let l=0,c=r.length;l<c;l++)a(this,l,t,e,o,i,s);return o}raycastFirst(e,t=v.FrontSide,i=0,s=1/0){const r=this._roots;let o=null;const a=this.indirect?SB:pB;for(let l=0,c=r.length;l<c;l++){const h=a(this,l,t,e,i,s);h!=null&&(o==null||h.distance<o.distance)&&(o=h)}return o}intersectsGeometry(e,t){let i=!1;const s=this._roots,r=this.indirect?CB:gB;for(let o=0,a=s.length;o<a&&(i=r(this,o,e,t),!i);o++);return i}shapecast(e){const t=ji.getPrimitive(),i=this.indirect?dB:aB;let{boundsTraverseOrder:s,intersectsBounds:r,intersectsRange:o,intersectsTriangle:a}=e;if(o&&a){const d=o;o=(f,u,g,p,m)=>d(f,u,g,p,m)?!0:i(f,u,this,a,g,p,t)}else o||(a?o=(d,f,u,g)=>i(d,f,this,a,u,g,t):o=(d,f,u)=>u);let l=!1,c=0;const h=this._roots;for(let d=0,f=h.length;d<f;d++){const u=h[d];if(l=tB(this,d,r,o,s,c),l)break;c+=u.byteLength/li}return ji.releasePrimitive(t),l}bvhcast(e,t,i){let{intersectsRanges:s,intersectsTriangles:r}=i;const o=ji.getPrimitive(),a=this.geometry.index,l=this.geometry.attributes.position,c=this.indirect?g=>{const p=this.resolveTriangleIndex(g);Nt(o,p*3,a,l)}:g=>{Nt(o,g*3,a,l)},h=ji.getPrimitive(),d=e.geometry.index,f=e.geometry.attributes.position,u=e.indirect?g=>{const p=e.resolveTriangleIndex(g);Nt(h,p*3,d,f)}:g=>{Nt(h,g*3,d,f)};if(r){const g=(p,m,A,x,b,y,_,S)=>{for(let C=A,D=A+x;C<D;C++){u(C),h.a.applyMatrix4(t),h.b.applyMatrix4(t),h.c.applyMatrix4(t),h.needsUpdate=!0;for(let M=p,I=p+m;M<I;M++)if(c(M),o.needsUpdate=!0,r(o,h,M,C,b,y,_,S))return!0}return!1};if(s){const p=s;s=function(m,A,x,b,y,_,S,C){return p(m,A,x,b,y,_,S,C)?!0:g(m,A,x,b,y,_,S,C)}}else s=g}return PB(this,e,t,s)}intersectsBox(e,t){return Xc.set(e.min,e.max,t),Xc.needsUpdate=!0,this.shapecast({intersectsBounds:i=>Xc.intersectsBox(i),intersectsTriangle:i=>Xc.intersectsTriangle(i)})}intersectsSphere(e){return this.shapecast({intersectsBounds:t=>e.intersectsBox(t),intersectsTriangle:t=>t.intersectsSphere(e)})}closestPointToGeometry(e,t,i={},s={},r=0,o=1/0){return(this.indirect?DB:yB)(this,e,t,i,s,r,o)}closestPointToPoint(e,t={},i=0,s=1/0){return iB(this,e,t,i,s)}getBoundingBox(e){return e.makeEmpty(),this._roots.forEach(i=>{It(0,new Float32Array(i),Nx),e.union(Nx)}),e}}const zx=1e-6,RB=zx*.5,Gx=Math.pow(10,-Math.log10(zx)),kB=RB*Gx;function Cn(n){return~~(n*Gx+kB)}function FB(n){return`${Cn(n.x)},${Cn(n.y)}`}function Vx(n){return`${Cn(n.x)},${Cn(n.y)},${Cn(n.z)}`}function OB(n){return`${Cn(n.x)},${Cn(n.y)},${Cn(n.z)},${Cn(n.w)}`}function UB(n,e,t){t.direction.subVectors(e,n).normalize();const i=n.dot(t.direction);return t.origin.copy(n).addScaledVector(t.direction,-i),t}function Qx(){return typeof SharedArrayBuffer<"u"}function NB(n){if(n.buffer instanceof SharedArrayBuffer)return n;const e=n.constructor,t=n.buffer,i=new SharedArrayBuffer(t.byteLength),s=new Uint8Array(t);return new Uint8Array(i).set(s,0),new e(i)}function zB(n,e=ArrayBuffer){return n>65535?new Uint32Array(new e(4*n)):new Uint16Array(new e(2*n))}function GB(n,e){if(!n.index){const t=n.attributes.position.count,i=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,s=zB(t,i);n.setIndex(new v.BufferAttribute(s,1));for(let r=0;r<t;r++)s[r]=r}}function VB(n){return n.index?n.index.count:n.attributes.position.count}function Rf(n){return VB(n)/3}const QB=1e-8,jB=new v.Vector3;function WB(n){return~~(n/3)}function HB(n){return n%3}function jx(n,e){return n.start-e.start}function Wx(n,e){return jB.subVectors(e,n.origin).dot(n.direction)}function XB(n,e,t,i=QB){n.sort(jx),e.sort(jx);for(let a=0;a<n.length;a++){const l=n[a];for(let c=0;c<e.length;c++){const h=e[c];if(!(h.start>l.end)){if(l.end<h.start||h.end<l.start)continue;if(l.start<=h.start&&l.end>=h.end)r(h.end,l.end)||n.splice(a+1,0,{start:h.end,end:l.end,index:l.index}),l.end=h.start,h.start=0,h.end=0;else if(l.start>=h.start&&l.end<=h.end)r(l.end,h.end)||e.splice(c+1,0,{start:l.end,end:h.end,index:h.index}),h.end=l.start,l.start=0,l.end=0;else if(l.start<=h.start&&l.end<=h.end){const d=l.end;l.end=h.start,h.start=d}else if(l.start>=h.start&&l.end>=h.end){const d=h.end;h.end=l.start,l.start=d}else throw new Error}if(t.has(l.index)||t.set(l.index,[]),t.has(h.index)||t.set(h.index,[]),t.get(l.index).push(h.index),t.get(h.index).push(l.index),o(h)&&(e.splice(c,1),c--),o(l)){n.splice(a,1),a--;break}}}s(n),s(e);function s(a){for(let l=0;l<a.length;l++)o(a[l])&&(a.splice(l,1),l--)}function r(a,l){return Math.abs(l-a)<i}function o(a){return Math.abs(a.end-a.start)<i}}const Hx=1e-5,Xx=1e-4;class qB{constructor(){this._rays=[]}addRay(e){this._rays.push(e)}findClosestRay(e){const t=this._rays,i=e.clone();i.direction.multiplyScalar(-1);let s=1/0,r=null;for(let l=0,c=t.length;l<c;l++){const h=t[l];if(o(h,e)&&o(h,i))continue;const d=a(h,e),f=a(h,i),u=Math.min(d,f);u<s&&(s=u,r=h)}return r;function o(l,c){const h=l.origin.distanceTo(c.origin)>Hx;return l.direction.angleTo(c.direction)>Xx||h}function a(l,c){const h=l.origin.distanceTo(c.origin),d=l.direction.angleTo(c.direction);return h/Hx+d/Xx}}}const kf=new v.Vector3,Ff=new v.Vector3,qc=new v.Ray;function YB(n,e,t){const i=n.attributes,s=n.index,r=i.position,o=new Map,a=new Map,l=Array.from(e),c=new qB;for(let h=0,d=l.length;h<d;h++){const f=l[h],u=WB(f),g=HB(f);let p=3*u+g,m=3*u+(g+1)%3;s&&(p=s.getX(p),m=s.getX(m)),kf.fromBufferAttribute(r,p),Ff.fromBufferAttribute(r,m),UB(kf,Ff,qc);let A,x=c.findClosestRay(qc);x===null&&(x=qc.clone(),c.addRay(x)),a.has(x)||a.set(x,{forward:[],reverse:[],ray:x}),A=a.get(x);let b=Wx(x,kf),y=Wx(x,Ff);b>y&&([b,y]=[y,b]),qc.direction.dot(x.direction)<0?A.reverse.push({start:b,end:y,index:f}):A.forward.push({start:b,end:y,index:f})}return a.forEach(({forward:h,reverse:d},f)=>{XB(h,d,o,t),h.length===0&&d.length===0&&a.delete(f)}),{disjointConnectivityMap:o,fragmentMap:a}}const KB=new v.Vector2,Of=new v.Vector3,$B=new v.Vector4,Uf=["","",""];class JB{constructor(e=null){this.data=null,this.disjointConnections=null,this.unmatchedDisjointEdges=null,this.unmatchedEdges=-1,this.matchedEdges=-1,this.useDrawRange=!0,this.useAllAttributes=!1,this.matchDisjointEdges=!1,this.degenerateEpsilon=1e-8,e&&this.updateFrom(e)}getSiblingTriangleIndex(e,t){const i=this.data[e*3+t];return i===-1?-1:~~(i/3)}getSiblingEdgeIndex(e,t){const i=this.data[e*3+t];return i===-1?-1:i%3}getDisjointSiblingTriangleIndices(e,t){const i=e*3+t,s=this.disjointConnections.get(i);return s?s.map(r=>~~(r/3)):[]}getDisjointSiblingEdgeIndices(e,t){const i=e*3+t,s=this.disjointConnections.get(i);return s?s.map(r=>r%3):[]}isFullyConnected(){return this.unmatchedEdges===0}updateFrom(e){const{useAllAttributes:t,useDrawRange:i,matchDisjointEdges:s,degenerateEpsilon:r}=this,o=t?b:x,a=new Map,{attributes:l}=e,c=t?Object.keys(l):null,h=e.index,d=l.position;let f=Rf(e);const u=f;let g=0;i&&(g=e.drawRange.start,e.drawRange.count!==1/0&&(f=~~(e.drawRange.count/3)));let p=this.data;(!p||p.length<3*u)&&(p=new Int32Array(3*u)),p.fill(-1);let m=0,A=new Set;for(let y=g,_=f*3+g;y<_;y+=3){const S=y;for(let C=0;C<3;C++){let D=S+C;h&&(D=h.getX(D)),Uf[C]=o(D)}for(let C=0;C<3;C++){const D=(C+1)%3,M=Uf[C],I=Uf[D],L=`${I}_${M}`;if(a.has(L)){const T=S+C,R=a.get(L);p[T]=R,p[R]=T,a.delete(L),m+=2,A.delete(R)}else{const T=`${M}_${I}`,R=S+C;a.set(T,R),A.add(R)}}}if(s){const{fragmentMap:y,disjointConnectivityMap:_}=YB(e,A,r);A.clear(),y.forEach(({forward:S,reverse:C})=>{S.forEach(({index:D})=>A.add(D)),C.forEach(({index:D})=>A.add(D))}),this.unmatchedDisjointEdges=y,this.disjointConnections=_,m=f*3-A.size}this.matchedEdges=m,this.unmatchedEdges=A.size,this.data=p;function x(y){return Of.fromBufferAttribute(d,y),Vx(Of)}function b(y){let _="";for(let S=0,C=c.length;S<C;S++){const D=l[c[S]];let M;switch(D.itemSize){case 1:M=Cn(D.getX(y));break;case 2:M=FB(KB.fromBufferAttribute(D,y));break;case 3:M=Vx(Of.fromBufferAttribute(D,y));break;case 4:M=OB($B.fromBufferAttribute(D,y));break}_!==""&&(_+="|"),_+=M}return _}}}class Yc extends v.Mesh{constructor(...e){super(...e),this.isBrush=!0,this._previousMatrix=new v.Matrix4,this._previousMatrix.elements.fill(0)}markUpdated(){this._previousMatrix.copy(this.matrix)}isDirty(){const{matrix:e,_previousMatrix:t}=this,i=e.elements,s=t.elements;for(let r=0;r<16;r++)if(i[r]!==s[r])return!0;return!1}prepareGeometry(){const e=this.geometry,t=e.attributes,i=Qx();if(i)for(const s in t){const r=t[s];if(r.isInterleavedBufferAttribute)throw new Error("Brush: InterleavedBufferAttributes are not supported.");r.array=NB(r.array)}if(e.boundsTree||(GB(e,{useSharedArrayBuffer:i}),e.boundsTree=new Lf(e,{maxLeafTris:3,indirect:!0,useSharedArrayBuffer:i})),e.halfEdges||(e.halfEdges=new JB(e)),!e.groupIndices){const s=Rf(e),r=new Uint16Array(s),o=e.groups;for(let a=0,l=o.length;a<l;a++){const{start:c,count:h}=o[a];for(let d=c/3,f=(c+h)/3;d<f;d++)r[d]=a}e.groupIndices=r}}disposeCacheData(){const{geometry:e}=this;e.halfEdges=null,e.boundsTree=null,e.groupIndices=null}}const ZB=1e-14,Nf=new v.Vector3,qx=new v.Vector3,Yx=new v.Vector3;function Bs(n,e=ZB){Nf.subVectors(n.b,n.a),qx.subVectors(n.c,n.a),Yx.subVectors(n.b,n.c);const t=Nf.angleTo(qx),i=Nf.angleTo(Yx),s=Math.PI-t-i;return Math.abs(t)<e||Math.abs(i)<e||Math.abs(s)<e||n.a.distanceToSquared(n.b)<e||n.a.distanceToSquared(n.c)<e||n.b.distanceToSquared(n.c)<e}const zf=1e-10,Da=1e-10,eP=1e-10,is=new v.Line3,Ft=new v.Line3,ns=new v.Vector3,Gf=new v.Vector3,Kx=new v.Vector3,Kc=new v.Plane,Vf=new Qi;class tP{constructor(){this._pool=[],this._index=0}getTriangle(){return this._index>=this._pool.length&&this._pool.push(new v.Triangle),this._pool[this._index++]}clear(){this._index=0}reset(){this._pool.length=0,this._index=0}}class iP{constructor(){this.trianglePool=new tP,this.triangles=[],this.normal=new v.Vector3,this.coplanarTriangleUsed=!1}initialize(e){this.reset();const{triangles:t,trianglePool:i,normal:s}=this;if(Array.isArray(e))for(let r=0,o=e.length;r<o;r++){const a=e[r];if(r===0)a.getNormal(s);else if(Math.abs(1-a.getNormal(ns).dot(s))>zf)throw new Error("Triangle Splitter: Cannot initialize with triangles that have different normals.");const l=i.getTriangle();l.copy(a),t.push(l)}else{e.getNormal(s);const r=i.getTriangle();r.copy(e),t.push(r)}}splitByTriangle(e){const{normal:t,triangles:i}=this;if(e.getNormal(Gf).normalize(),Math.abs(1-Math.abs(Gf.dot(t)))<eP){this.coplanarTriangleUsed=!0;for(let r=0,o=i.length;r<o;r++){const a=i[r];a.coplanarCount=0}const s=[e.a,e.b,e.c];for(let r=0;r<3;r++){const o=(r+1)%3,a=s[r],l=s[o];ns.subVectors(l,a).normalize(),Kx.crossVectors(Gf,ns),Kc.setFromNormalAndCoplanarPoint(Kx,a),this.splitByPlane(Kc,e)}}else e.getPlane(Kc),this.splitByPlane(Kc,e)}splitByPlane(e,t){const{triangles:i,trianglePool:s}=this;Vf.copy(t),Vf.needsUpdate=!0;for(let r=0,o=i.length;r<o;r++){const a=i[r];if(!Vf.intersectsTriangle(a,is,!0))continue;const{a:l,b:c,c:h}=a;let d=0,f=-1,u=!1,g=[],p=[];const m=[l,c,h];for(let A=0;A<3;A++){const x=(A+1)%3;is.start.copy(m[A]),is.end.copy(m[x]);const b=e.distanceToPoint(is.start),y=e.distanceToPoint(is.end);if(Math.abs(b)<Da&&Math.abs(y)<Da){u=!0;break}if(b>0?g.push(A):p.push(A),Math.abs(b)<Da)continue;let _=!!e.intersectLine(is,ns);!_&&Math.abs(y)<Da&&(ns.copy(is.end),_=!0),_&&!(ns.distanceTo(is.start)<zf)&&(ns.distanceTo(is.end)<zf&&(f=A),d===0?Ft.start.copy(ns):Ft.end.copy(ns),d++)}if(!u&&d===2&&Ft.distance()>Da)if(f!==-1){f=(f+1)%3;let A=0;A===f&&(A=(A+1)%3);let x=A+1;x===f&&(x=(x+1)%3);const b=s.getTriangle();b.a.copy(m[x]),b.b.copy(Ft.end),b.c.copy(Ft.start),Bs(b)||i.push(b),a.a.copy(m[A]),a.b.copy(Ft.start),a.c.copy(Ft.end),Bs(a)&&(i.splice(r,1),r--,o--)}else{const A=g.length>=2?p[0]:g[0];if(A===0){let S=Ft.start;Ft.start=Ft.end,Ft.end=S}const x=(A+1)%3,b=(A+2)%3,y=s.getTriangle(),_=s.getTriangle();m[x].distanceToSquared(Ft.start)<m[b].distanceToSquared(Ft.end)?(y.a.copy(m[x]),y.b.copy(Ft.start),y.c.copy(Ft.end),_.a.copy(m[x]),_.b.copy(m[b]),_.c.copy(Ft.start)):(y.a.copy(m[b]),y.b.copy(Ft.start),y.c.copy(Ft.end),_.a.copy(m[x]),_.b.copy(m[b]),_.c.copy(Ft.end)),a.a.copy(m[A]),a.b.copy(Ft.end),a.c.copy(Ft.start),Bs(y)||i.push(y),Bs(_)||i.push(_),Bs(a)&&(i.splice(r,1),r--,o--)}else d===3&&console.warn("TriangleClipper: Coplanar clip not handled")}}reset(){this.triangles.length=0,this.trianglePool.clear(),this.coplanarTriangleUsed=!1}}function nP(n){return n=~~n,n+4-n%4}class $x{constructor(e,t=500){this.expansionFactor=1.5,this.type=e,this.length=0,this.array=null,this.setSize(t)}setType(e){if(this.length!==0)throw new Error("TypeBackedArray: Cannot change the type while there is used data in the buffer.");const t=this.array.buffer;this.array=new e(t),this.type=e}setSize(e){if(this.array&&e===this.array.length)return;const t=this.type,i=Qx()?SharedArrayBuffer:ArrayBuffer,s=new t(new i(nP(e*t.BYTES_PER_ELEMENT)));this.array&&s.set(this.array,0),this.array=s}expand(){const{array:e,expansionFactor:t}=this;this.setSize(e.length*t)}push(...e){let{array:t,length:i}=this;i+e.length>t.length&&(this.expand(),t=this.array);for(let s=0,r=e.length;s<r;s++)t[i+s]=e[s];this.length+=e.length}clear(){this.length=0}}class sP{constructor(){this.groupAttributes=[{}],this.groupCount=0}getType(e){return this.groupAttributes[0][e].type}getItemSize(e){return this.groupAttributes[0][e].itemSize}getNormalized(e){return this.groupAttributes[0][e].normalized}getCount(e){if(this.groupCount<=e)return 0;const t=this.getGroupAttrArray("position",e);return t.length/t.itemSize}getTotalLength(e){const{groupCount:t,groupAttributes:i}=this;let s=0;for(let r=0;r<t;r++){const o=i[r];s+=o[e].length}return s}getGroupAttrSet(e=0){const{groupAttributes:t}=this;if(t[e])return this.groupCount=Math.max(this.groupCount,e+1),t[e];const i=t[0];for(this.groupCount=Math.max(this.groupCount,e+1);e>=t.length;){const s={};t.push(s);for(const r in i){const o=i[r],a=new $x(o.type);a.itemSize=o.itemSize,a.normalized=o.normalized,s[r]=a}}return t[e]}getGroupAttrArray(e,t=0){const{groupAttributes:i}=this;if(!i[0][e])throw new Error(`TypedAttributeData: Attribute with "${e}" has not been initialized`);return this.getGroupAttrSet(t)[e]}initializeArray(e,t,i,s){const{groupAttributes:r}=this,a=r[0][e];if(a){if(a.type!==t)for(let l=0,c=r.length;l<c;l++){const h=r[l][e];h.setType(t),h.itemSize=i,h.normalized=s}}else for(let l=0,c=r.length;l<c;l++){const h=new $x(t);h.itemSize=i,h.normalized=s,r[l][e]=h}}clear(){this.groupCount=0;const{groupAttributes:e}=this;e.forEach(t=>{for(const i in t)t[i].clear()})}delete(e){this.groupAttributes.forEach(t=>{delete t[e]})}reset(){this.groupAttributes=[],this.groupCount=0}}class Jx{constructor(){this.intersectionSet={},this.ids=[]}add(e,t){const{intersectionSet:i,ids:s}=this;i[e]||(i[e]=[],s.push(e)),i[e].push(t)}}const rP=0,oP=1,aP=2,Zx=3,lP=4,eb=5,tb=6,Hi=new v.Ray,ib=new v.Matrix4,hi=new v.Triangle,ss=new v.Vector3,nb=new v.Vector4,sb=new v.Vector4,rb=new v.Vector4,Qf=new v.Vector4,$c=new v.Vector4,Jc=new v.Vector4,ob=new v.Line3,jf=new v.Vector3,Wf=1e-8,cP=1e-15,xr=-1,br=1,Zc=-2,eh=2,Ba=0,yr=1,Hf=2,hP=1e-14;let th=null;function ab(n){th=n}function lb(n,e){n.getMidpoint(Hi.origin),n.getNormal(Hi.direction);const t=e.raycastFirst(Hi,v.DoubleSide);return!!(t&&Hi.direction.dot(t.face.normal)>0)?xr:br}function dP(n,e){function t(){return Math.random()-.5}n.getNormal(jf),Hi.direction.copy(jf),n.getMidpoint(Hi.origin);const i=3;let s=0,r=1/0;for(let o=0;o<i;o++){Hi.direction.x+=t()*Wf,Hi.direction.y+=t()*Wf,Hi.direction.z+=t()*Wf,Hi.direction.multiplyScalar(-1);const a=e.raycastFirst(Hi,v.DoubleSide);if(!!(a&&Hi.direction.dot(a.face.normal)>0)&&s++,a!==null&&(r=Math.min(r,a.distance)),r<=cP)return a.face.normal.dot(jf)>0?eh:Zc;if(s/i>.5||(o-s+1)/i>.5)break}return s/i>.5?xr:br}function uP(n,e){const t=new Jx,i=new Jx;return ib.copy(n.matrixWorld).invert().multiply(e.matrixWorld),n.geometry.boundsTree.bvhcast(e.geometry.boundsTree,ib,{intersectsTriangles(s,r,o,a){if(!Bs(s)&&!Bs(r)){let l=s.intersectsTriangle(r,ob,!0);if(!l){const c=s.plane,h=r.plane,d=c.normal,f=h.normal;d.dot(f)===1&&Math.abs(c.constant-h.constant)<hP&&(l=!0)}if(l){let c=n.geometry.boundsTree.resolveTriangleIndex(o),h=e.geometry.boundsTree.resolveTriangleIndex(a);t.add(c,h),i.add(h,c),th&&(th.addEdge(ob),th.addIntersectingTriangles(o,s,a,r))}}return!1}}),{aIntersections:t,bIntersections:i}}function fP(n,e,t,i,s,r,o=!1){const a=t.attributes,l=t.index,c=n*3,h=l.getX(c+0),d=l.getX(c+1),f=l.getX(c+2);for(const u in r){const g=a[u],p=r[u];if(!(u in a))throw new Error(`CSG Operations: Attribute ${u} not available on geometry.`);const m=g.itemSize;u==="position"?(hi.a.fromBufferAttribute(g,h).applyMatrix4(i),hi.b.fromBufferAttribute(g,d).applyMatrix4(i),hi.c.fromBufferAttribute(g,f).applyMatrix4(i),Xf(hi.a,hi.b,hi.c,e,3,p,o)):u==="normal"?(hi.a.fromBufferAttribute(g,h).applyNormalMatrix(s),hi.b.fromBufferAttribute(g,d).applyNormalMatrix(s),hi.c.fromBufferAttribute(g,f).applyNormalMatrix(s),o&&(hi.a.multiplyScalar(-1),hi.b.multiplyScalar(-1),hi.c.multiplyScalar(-1)),Xf(hi.a,hi.b,hi.c,e,3,p,o,!0)):(nb.fromBufferAttribute(g,h),sb.fromBufferAttribute(g,d),rb.fromBufferAttribute(g,f),Xf(nb,sb,rb,e,m,p,o))}}function pP(n,e,t,i,s,r,o,a=!1){qf(n,i,s,r,o,a),qf(a?t:e,i,s,r,o,a),qf(a?e:t,i,s,r,o,a)}function cb(n,e,t=!1){switch(n){case rP:if(e===br||e===eh&&!t)return yr;break;case oP:if(t){if(e===xr)return Ba}else if(e===br||e===Zc)return yr;break;case aP:if(t){if(e===br||e===Zc)return yr}else if(e===xr)return Ba;break;case lP:if(e===xr)return Ba;if(e===br)return yr;break;case Zx:if(e===xr||e===eh&&!t)return yr;break;case eb:if(!t&&(e===br||e===Zc))return yr;break;case tb:if(!t&&(e===xr||e===eh))return yr;break;default:throw new Error(`Unrecognized CSG operation enum "${n}".`)}return Hf}function Xf(n,e,t,i,s,r,o=!1,a=!1){const l=c=>{r.push(c.x),s>1&&r.push(c.y),s>2&&r.push(c.z),s>3&&r.push(c.w)};Qf.set(0,0,0,0).addScaledVector(n,i.a.x).addScaledVector(e,i.a.y).addScaledVector(t,i.a.z),$c.set(0,0,0,0).addScaledVector(n,i.b.x).addScaledVector(e,i.b.y).addScaledVector(t,i.b.z),Jc.set(0,0,0,0).addScaledVector(n,i.c.x).addScaledVector(e,i.c.y).addScaledVector(t,i.c.z),a&&(Qf.normalize(),$c.normalize(),Jc.normalize()),l(Qf),o?(l(Jc),l($c)):(l($c),l(Jc))}function qf(n,e,t,i,s,r=!1){for(const o in s){const a=e[o],l=s[o];if(!(o in e))throw new Error(`CSG Operations: Attribute ${o} no available on geometry.`);const c=a.itemSize;o==="position"?(ss.fromBufferAttribute(a,n).applyMatrix4(t),l.push(ss.x,ss.y,ss.z)):o==="normal"?(ss.fromBufferAttribute(a,n).applyNormalMatrix(i),r&&ss.multiplyScalar(-1),l.push(ss.x,ss.y,ss.z)):(l.push(a.getX(n)),c>1&&l.push(a.getY(n)),c>2&&l.push(a.getZ(n)),c>3&&l.push(a.getW(n)))}}class gP{constructor(e){this.triangle=new v.Triangle().copy(e),this.intersects={}}addTriangle(e,t){this.intersects[e]=new v.Triangle().copy(t)}getIntersectArray(){const e=[],{intersects:t}=this;for(const i in t)e.push(t[i]);return e}}class hb{constructor(){this.data={}}addTriangleIntersection(e,t,i,s){const{data:r}=this;r[e]||(r[e]=new gP(t)),r[e].addTriangle(i,s)}getTrianglesAsArray(e=null){const{data:t}=this,i=[];if(e!==null)e in t&&i.push(t[e].triangle);else for(const s in t)i.push(t[s].triangle);return i}getTriangleIndices(){return Object.keys(this.data).map(e=>parseInt(e))}getIntersectionIndices(e){const{data:t}=this;return t[e]?Object.keys(t[e].intersects).map(i=>parseInt(i)):[]}getIntersectionsAsArray(e=null,t=null){const{data:i}=this,s=new Set,r=[],o=a=>{if(i[a])if(t!==null)i[a].intersects[t]&&r.push(i[a].intersects[t]);else{const l=i[a].intersects;for(const c in l)s.has(c)||(s.add(c),r.push(l[c]))}};if(e!==null)o(e);else for(const a in i)o(a);return r}reset(){this.data={}}}class mP{constructor(){this.enabled=!1,this.triangleIntersectsA=new hb,this.triangleIntersectsB=new hb,this.intersectionEdges=[]}addIntersectingTriangles(e,t,i,s){const{triangleIntersectsA:r,triangleIntersectsB:o}=this;r.addTriangleIntersection(e,t,i,s),o.addTriangleIntersection(i,s,e,t)}addEdge(e){this.intersectionEdges.push(e.clone())}reset(){this.triangleIntersectsA.reset(),this.triangleIntersectsB.reset(),this.intersectionEdges=[]}init(){this.enabled&&(this.reset(),ab(this))}complete(){this.enabled&&ab(null)}}const Ps=new v.Matrix4,ih=new v.Matrix3,vr=new v.Triangle,nh=new v.Triangle,Ls=new v.Triangle,sh=new v.Triangle,on=[],_r=[];function AP(n){for(const e of n)return e}function xP(n,e,t,i,s,r={}){const{useGroups:o=!0}=r,{aIntersections:a,bIntersections:l}=uP(n,e),c=[];let h=null,d;return d=o?0:-1,db(n,e,a,t,!1,i,s,d),ub(n,e,a,t,!1,s,d),t.findIndex(u=>u!==tb&&u!==eb)!==-1&&(d=o?n.geometry.groups.length||1:-1,db(e,n,l,t,!0,i,s,d),ub(e,n,l,t,!0,s,d)),on.length=0,_r.length=0,{groups:c,materials:h}}function db(n,e,t,i,s,r,o,a=0){const l=n.matrixWorld.determinant()<0;Ps.copy(e.matrixWorld).invert().multiply(n.matrixWorld),ih.getNormalMatrix(n.matrixWorld).multiplyScalar(l?-1:1);const c=n.geometry.groupIndices,h=n.geometry.index,d=n.geometry.attributes.position,f=e.geometry.boundsTree,u=e.geometry.index,g=e.geometry.attributes.position,p=t.ids,m=t.intersectionSet;for(let A=0,x=p.length;A<x;A++){const b=p[A],y=a===-1?0:c[b]+a,_=3*b,S=h.getX(_+0),C=h.getX(_+1),D=h.getX(_+2);vr.a.fromBufferAttribute(d,S).applyMatrix4(Ps),vr.b.fromBufferAttribute(d,C).applyMatrix4(Ps),vr.c.fromBufferAttribute(d,D).applyMatrix4(Ps),r.reset(),r.initialize(vr);const M=m[b];for(let L=0,T=M.length;L<T;L++){const R=3*M[L],E=u.getX(R+0),F=u.getX(R+1),N=u.getX(R+2);nh.a.fromBufferAttribute(g,E),nh.b.fromBufferAttribute(g,F),nh.c.fromBufferAttribute(g,N),r.splitByTriangle(nh)}const I=r.triangles;for(let L=0,T=I.length;L<T;L++){const R=I[L],E=r.coplanarTriangleUsed?dP(R,f):lb(R,f);on.length=0,_r.length=0;for(let F=0,N=i.length;F<N;F++){const H=cb(i[F],E,s);H!==Hf&&(_r.push(H),on.push(o[F].getGroupAttrSet(y)))}if(on.length!==0){vr.getBarycoord(R.a,sh.a),vr.getBarycoord(R.b,sh.b),vr.getBarycoord(R.c,sh.c);for(let F=0,N=on.length;F<N;F++){const H=on[F],U=_r[F]===Ba;fP(b,sh,n.geometry,n.matrixWorld,ih,H,l!==U)}}}}return p.length}function ub(n,e,t,i,s,r,o=0){const a=n.matrixWorld.determinant()<0;Ps.copy(e.matrixWorld).invert().multiply(n.matrixWorld),ih.getNormalMatrix(n.matrixWorld).multiplyScalar(a?-1:1);const l=e.geometry.boundsTree,c=n.geometry.groupIndices,h=n.geometry.index,d=n.geometry.attributes,f=d.position,u=[],g=n.geometry.halfEdges,p=new Set,m=Rf(n.geometry);for(let A=0,x=m;A<x;A++)A in t.intersectionSet||p.add(A);for(;p.size>0;){const A=AP(p);p.delete(A),u.push(A);const x=3*A,b=h.getX(x+0),y=h.getX(x+1),_=h.getX(x+2);Ls.a.fromBufferAttribute(f,b).applyMatrix4(Ps),Ls.b.fromBufferAttribute(f,y).applyMatrix4(Ps),Ls.c.fromBufferAttribute(f,_).applyMatrix4(Ps);const S=lb(Ls,l);_r.length=0,on.length=0;for(let C=0,D=i.length;C<D;C++){const M=cb(i[C],S,s);M!==Hf&&(_r.push(M),on.push(r[C]))}for(;u.length>0;){const C=u.pop();for(let D=0;D<3;D++){const M=g.getSiblingTriangleIndex(C,D);M!==-1&&p.has(M)&&(u.push(M),p.delete(M))}if(on.length!==0){const D=3*C,M=h.getX(D+0),I=h.getX(D+1),L=h.getX(D+2),T=o===-1?0:c[C]+o;if(Ls.a.fromBufferAttribute(f,M),Ls.b.fromBufferAttribute(f,I),Ls.c.fromBufferAttribute(f,L),!Bs(Ls))for(let R=0,E=on.length;R<E;R++){const F=_r[R],N=on[R].getGroupAttrSet(T),H=F===Ba;pP(M,I,L,d,n.matrixWorld,ih,N,H!==a)}}}}}function bP(n){for(let e=0;e<n.length-1;e++){const t=n[e],i=n[e+1];if(t.materialIndex===i.materialIndex){const s=t.start,r=i.start+i.count;i.start=s,i.count=r-s,n.splice(e,1),e--}}}function yP(n,e,t,i){t.clear();const s=n.attributes;for(let r=0,o=i.length;r<o;r++){const a=i[r],l=s[a];t.initializeArray(a,l.array.constructor,l.itemSize,l.normalized)}for(const r in t.attributes)i.includes(r)||t.delete(r);for(const r in e.attributes)i.includes(r)||(e.deleteAttribute(r),e.dispose())}function vP(n,e,t){let i=!1,s=-1;const r=n.attributes,o=e.groupAttributes[0];for(const l in o){const c=e.getTotalLength(l),h=e.getType(l),d=e.getItemSize(l),f=e.getNormalized(l);let u=r[l];(!u||u.array.length<c)&&(u=new v.BufferAttribute(new h(c),d,f),n.setAttribute(l,u),i=!0);let g=0;for(let p=0,m=Math.min(t.length,e.groupCount);p<m;p++){const A=t[p].index,{array:x,type:b,length:y}=e.groupAttributes[A][l],_=new b(x.buffer,0,y);u.array.set(_,g),g+=_.length}u.needsUpdate=!0,s=c/u.itemSize}if(n.index){const l=n.index.array;if(l.length<s)n.index=null,i=!0;else for(let c=0,h=l.length;c<h;c++)l[c]=c}let a=0;n.clearGroups();for(let l=0,c=Math.min(t.length,e.groupCount);l<c;l++){const{index:h,materialIndex:d}=t[l],f=e.getCount(h);f!==0&&(n.addGroup(a,f,d),a+=f)}n.setDrawRange(0,s),n.boundsTree=null,i&&n.dispose()}function fb(n,e){let t=e;return Array.isArray(e)||(t=[],n.forEach(i=>{t[i.materialIndex]=e})),t}class _P{constructor(){this.triangleSplitter=new iP,this.attributeData=[],this.attributes=["position","uv","normal"],this.useGroups=!0,this.consolidateGroups=!0,this.debug=new mP}getGroupRanges(e){return!this.useGroups||e.groups.length===0?[{start:0,count:1/0,materialIndex:0}]:e.groups.map(t=>({...t}))}evaluate(e,t,i,s=new Yc){let r=!0;if(Array.isArray(i)||(i=[i]),Array.isArray(s)||(s=[s],r=!1),s.length!==i.length)throw new Error("Evaluator: operations and target array passed as different sizes.");e.prepareGeometry(),t.prepareGeometry();const{triangleSplitter:o,attributeData:a,attributes:l,useGroups:c,consolidateGroups:h,debug:d}=this;for(;a.length<s.length;)a.push(new sP);s.forEach((A,x)=>{yP(e.geometry,A.geometry,a[x],l)}),d.init(),xP(e,t,i,o,a,{useGroups:c}),d.complete();const f=this.getGroupRanges(e.geometry),u=fb(f,e.material),g=this.getGroupRanges(t.geometry),p=fb(g,t.material);g.forEach(A=>A.materialIndex+=u.length);let m=[...f,...g].map((A,x)=>({...A,index:x}));if(c){const A=[...u,...p];h&&(m=m.map(b=>{const y=A[b.materialIndex];return b.materialIndex=A.indexOf(y),b}).sort((b,y)=>b.materialIndex-y.materialIndex));const x=[];for(let b=0,y=A.length;b<y;b++){let _=!1;for(let S=0,C=m.length;S<C;S++){const D=m[S];D.materialIndex===b&&(_=!0,D.materialIndex=x.length)}_&&x.push(A[b])}s.forEach(b=>{b.material=x})}else m=[{start:0,count:1/0,index:0,materialIndex:0}],s.forEach(A=>{A.material=u[0]});return s.forEach((A,x)=>{const b=A.geometry;vP(b,a[x],m),h&&bP(b.groups)}),r?s:s[0]}evaluateHierarchy(e,t=new Yc){e.updateMatrixWorld(!0);const i=(r,o)=>{const a=r.children;for(let l=0,c=a.length;l<c;l++){const h=a[l];h.isOperationGroup?i(h,o):o(h)}},s=r=>{const o=r.children;let a=!1;for(let c=0,h=o.length;c<h;c++){const d=o[c];a=s(d)||a}const l=r.isDirty();if(l&&r.markUpdated(),a&&!r.isOperationGroup){let c;return i(r,h=>{c?c=this.evaluate(c,h,h.operation):c=this.evaluate(r,h,h.operation)}),r._cachedGeometry=c.geometry,r._cachedMaterials=c.material,!0}else return a||l};return s(e),t.geometry=e._cachedGeometry,t.material=e._cachedMaterials,t}reset(){this.triangleSplitter.reset()}}class wP{engine;evaluator;fillMeshName="ClippingFaceFillMesh";fillMeshes=new Map;maxCandidates=22e5;maxTriangleCountPerMesh=12e4;fillMaterial;fillTextureRepeat=60;fillTextureRotation=0;constructor(e){this.engine=e,this.evaluator=new _P;const t=new URL("/texture/fill.png",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,i=new w.TextureLoader().load(t);i.wrapS=w.RepeatWrapping,i.wrapT=w.RepeatWrapping,i.center.set(.5,.5),i.rotation=this.fillTextureRotation,this.fillMaterial=new w.MeshStandardMaterial({color:16112010,map:i,side:w.DoubleSide,toneMapped:!1}),this.fillMaterial.clipShadows=!0,this.fillMaterial.clippingPlanes=e.sectionPlane}clear(){this.fillMeshes.forEach(e=>{e.parent?.remove(e),e.geometry?.dispose?.();const t=e.material;Array.isArray(t)?t.forEach(i=>i.dispose?.()):t&&t!==this.fillMaterial&&t.dispose?.()}),this.fillMeshes.clear()}updataFace(e){this.clear(),e instanceof w.Plane&&this.engine.clipping.fillCutFace&&this.buildSinglePlaneFill(e,"face")}updataFaces(e){this.clear(),!(!Array.isArray(e)||e.length===0)&&this.engine.clipping.fillCutFace&&e.forEach((t,i)=>{if(!(t instanceof w.Plane))return;const s=`plane-${i}-${String(t.name??i)}`;this.buildSinglePlaneFill(t,s)})}buildSinglePlaneFill(e,t){const i=this.engine?.octreeBox?.getBoundingBox?.();if(i==null||i.min==null||i.max==null)return;const s=this.collectCandidateMeshesFromOctree(e);if(s.length===0)return;const r=this.filterMeshesByBoxAndComplexity(e,s);if(r.length===0)return;const o=i.min.distanceTo(i.max),a=o*5,l=.1,c=this.createPlaneBrush(e,a,l),h=[];for(const p of r.slice(0,this.maxCandidates)){const m=this.createWorldBrushFromMesh(p);if(m!=null)try{const x=this.evaluator.evaluate(m,c,Zx)?.geometry;if(!x)continue;const b=this.extractPlaneCapGeometry(x,e,l);b&&h.push(b),x.dispose()}catch{}finally{m.geometry.dispose()}}if(c.geometry.dispose(),h.length===0)return;const d=Yn(h,!1);if(h.forEach(p=>p.dispose()),!d)return;this.applyPlanarUv(d,e);const f=this.getFaceOffsetDistance(o),u=this.getFaceOffsetSign();d.translate(e.normal.x*f*u,e.normal.y*f*u,e.normal.z*f*u);const g=new w.Mesh(d,this.fillMaterial);g.name=`${this.fillMeshName}_${t}`,g.frustumCulled=!1,g.renderOrder=20,g.castShadow=!1,g.receiveShadow=!1,this.engine.scene.add(g),this.fillMeshes.set(t,g)}getFaceOffsetDistance(e){return-.001}getFaceOffsetSign(){const e=this.engine?.engineStatus?.clippingFaceOffsetSign;return e===1||e===-1?e:-1}collectCandidateMeshesFromOctree(e){const t=[],i=new Set,s=Array.isArray(this.engine?.engineStatus?.models)?this.engine.engineStatus.models:[];for(const r of s){const o=this.engine.models?.find?.(c=>c.url===r.url);if(!o?.nodesMap)continue;const a=this.getIgnoredIds(r.url),l=Array.isArray(r?.info?.lods)?r.info.lods:[];for(const c of l){const h=c?.octreeBox;if(!h)continue;const d=this.collectIntersectElementIds(h,e);for(const f of d){if(a.has(f))continue;const u=o.nodesMap.get(f);if(!(u?.instance===!0||!Array.isArray(u?.infos)))for(const g of u.infos){const p=g?.mesh;p instanceof w.Mesh&&(i.has(p.uuid)||(i.add(p.uuid),t.push(p)))}}}}return t}getIgnoredIds(e){const t=new Set,i=Array.isArray(this.engine?.engineStatus?.hideModels)?this.engine.engineStatus.hideModels:[],s=Array.isArray(this.engine?.engineStatus?.translucentModels)?this.engine.engineStatus.translucentModels:[],r=i.find(a=>a.url===e)?.ids;Array.isArray(r)&&r.forEach(a=>t.add(a));const o=s.find(a=>a.url===e)?.ids;return Array.isArray(o)&&o.forEach(a=>t.add(a)),t}collectIntersectElementIds(e,t){const i=new Set,s=[e];for(;s.length>0;){const r=s.pop();if(!r)continue;const o=this.octreeNodeToBox3(r);!o||!t.intersectsBox(o)||(Array.isArray(r.elements)&&r.elements.forEach(a=>i.add(a)),Array.isArray(r.children)&&r.children.forEach(a=>s.push(a)))}return i}octreeNodeToBox3(e){if(!e?.min||!e?.max)return null;const t=new w.Vector3(e.min.X*.3048,e.min.Z*.3048,-e.min.Y*.3048),i=new w.Vector3(e.max.X*.3048,e.max.Z*.3048,-e.max.Y*.3048),s=new w.Vector3(Math.min(t.x,i.x),Math.min(t.y,i.y),Math.min(t.z,i.z)),r=new w.Vector3(Math.max(t.x,i.x),Math.max(t.y,i.y),Math.max(t.z,i.z));return new w.Box3(s,r)}filterMeshesByBoxAndComplexity(e,t){const i=[],s=new w.Box3;for(const r of t){const o=r.geometry,a=o?.attributes?.position;!o||!a||a.count===0||(o.index?Math.floor(o.index.count/3):Math.floor(a.count/3))>this.maxTriangleCountPerMesh||(o.boundingBox||o.computeBoundingBox(),o.boundingBox&&(s.copy(o.boundingBox),r.updateWorldMatrix(!0,!1),s.applyMatrix4(r.matrixWorld),e.intersectsBox(s)&&(r.geometry.attributes.position.count>500||i.push(r))))}return i}createPlaneBrush(e,t,i){const s=new w.BoxGeometry(t,t,i),r=e.coplanarPoint(new w.Vector3),o=new w.Quaternion().setFromUnitVectors(new w.Vector3(0,0,1),e.normal.clone().normalize()),a=new w.Matrix4().compose(r,o,new w.Vector3(1,1,1));s.applyMatrix4(a);const l=this.toCsgReadyGeometry(s);return s.dispose(),new Yc(l)}createWorldBrushFromMesh(e){const t=e.geometry;if(!t||!t.attributes?.position)return null;e.updateWorldMatrix(!0,!1);const i=t.clone();i.applyMatrix4(e.matrixWorld);const s=this.toCsgReadyGeometry(i);return i.dispose(),new Yc(s)}toCsgReadyGeometry(e){const t=e.index?e.toNonIndexed():e.clone();t.getAttribute("normal")||t.computeVertexNormals();const i=t.getAttribute("position");if(i&&!t.getAttribute("uv")){const r=new Float32Array(i.count*2);t.setAttribute("uv",new w.Float32BufferAttribute(r,2))}const s=new Set(["position","normal","uv"]);return Object.keys(t.attributes).forEach(r=>{s.has(r)||t.deleteAttribute(r)}),t}extractPlaneCapGeometry(e,t,i){const s=e.index?e.toNonIndexed():e.clone(),r=s.getAttribute("position");if(!r||r.count<3)return s.dispose(),null;const o=t.normal.clone().normalize(),a=new w.Vector3,l=new w.Vector3,c=new w.Vector3,h=new w.Vector3,d=new w.Vector3,f=new w.Vector3,u=new w.Vector3,g=new w.Vector3,p=new w.Vector3,m=Math.max(i*.35,1e-4),A=Math.max(i*.7,1e-4),x=[];for(let y=0;y<r.count;y+=3){if(h.fromBufferAttribute(r,y),d.fromBufferAttribute(r,y+1),f.fromBufferAttribute(r,y+2),l.subVectors(d,h),c.subVectors(f,h),a.crossVectors(l,c),a.lengthSq()<1e-14||(a.normalize(),Math.abs(a.dot(o))<.9))continue;const _=t.distanceToPoint(h),S=t.distanceToPoint(d),C=t.distanceToPoint(f),D=Math.min(_,S,C);if(Math.max(_,S,C)-D>m)continue;const I=(_+S+C)/3;Math.abs(I)>A||I<0||(u.copy(h).addScaledVector(o,-_),g.copy(d).addScaledVector(o,-S),p.copy(f).addScaledVector(o,-C),a.dot(o)<=0?(x.push(u.x,u.y,u.z),x.push(g.x,g.y,g.z),x.push(p.x,p.y,p.z)):(x.push(u.x,u.y,u.z),x.push(p.x,p.y,p.z),x.push(g.x,g.y,g.z)))}if(s.dispose(),x.length<9)return null;const b=new w.BufferGeometry;return b.setAttribute("position",new w.Float32BufferAttribute(x,3)),b.computeVertexNormals(),b}applyPlanarUv(e,t){const i=e.getAttribute("position");if(!i||i.count===0)return;const{tangent:s,bitangent:r}=this.getPlaneBasis(t.normal.clone().normalize()),o=new w.Vector3,a=new Float32Array(i.count*2);let l=1/0,c=-1/0,h=1/0,d=-1/0;for(let g=0;g<i.count;g++){o.fromBufferAttribute(i,g);const p=o.dot(s),m=o.dot(r),A=g*2;a[A]=p,a[A+1]=m,l=Math.min(l,p),c=Math.max(c,p),h=Math.min(h,m),d=Math.max(d,m)}const f=Math.max(c-l,1e-6),u=Math.max(d-h,1e-6);for(let g=0;g<a.length;g+=2)a[g]=(a[g]-l)/f*this.fillTextureRepeat,a[g+1]=(a[g+1]-h)/u*this.fillTextureRepeat;e.setAttribute("uv",new w.BufferAttribute(a,2))}getPlaneBasis(e){const t=new w.Vector3(1,0,0),i=new w.Vector3(0,1,0),s=new w.Vector3(0,0,1),r=Math.abs(e.dot(t)),o=Math.abs(e.dot(i)),a=Math.abs(e.dot(s));let l=t;o<=r&&o<=a?l=i:a<=r&&a<=o&&(l=s),l=l.clone().sub(e.clone().multiplyScalar(l.dot(e))).normalize();const c=new w.Vector3().crossVectors(e,l).normalize();return{tangent:l,bitangent:c}}}class SP{engine;clippingTolerance=1e-4;sectionBox;sectionFace;clippingStencil;clippingCSGSimple=null;currentClippingMode="";fillCutFace=!0;constructor(e){this.engine=e;let t=new w.Plane(new w.Vector3(0,0,1),1e5);t.name="前";let i=new w.Plane(new w.Vector3(0,0,1),1e5);i.name="左";let s=new w.Plane(new w.Vector3(0,0,1),1e5);s.name="后";let r=new w.Plane(new w.Vector3(0,0,1),1e5);r.name="右";let o=new w.Plane(new w.Vector3(0,0,1),1e5);o.name="顶";let a=new w.Plane(new w.Vector3(0,0,1),1e5);a.name="底";let l=new w.Plane(new w.Vector3(0,0,1),1e5);l.name="face",this.engine.sectionPlane=[t,i,s,r,o,a,l]}init(){this.sectionBox=new BD(this.engine),this.sectionFace=new PD(this.engine),this.clippingCSGSimple=new wP(this.engine)}scaleBox(){let e=this.engine.octreeBox.getBoundingBox();this.sectionBox.setBox(e)}setFillCutFace(e){this.fillCutFace=e}getFillCutFace(){return this.fillCutFace}clippingModel(e){let t=[];e.forEach(r=>{let o=this.engine.models.find(a=>a.url===r.url);r.ids.forEach(a=>{o.nodesMap.get(a).infos.forEach(l=>{t.push(l.box)})})}),this.active("box");let i=s(t);this.sectionBox.setBox(i);function s(r){let o=new w.Vector3(1e8,1e9,1e10),a=new w.Vector3(-1e8,-1e9,-1e10);return r.forEach(l=>{l.min.x<o.x&&(o.x=l.min.x),l.min.y<o.y&&(o.y=l.min.y),l.min.z<o.z&&(o.z=l.min.z),l.max.x>a.x&&(a.x=l.max.x),l.max.y>a.y&&(a.y=l.max.y),l.max.z>a.z&&(a.z=l.max.z)}),new w.Box3(o,a)}}updateClippingValue(e){let t=this.sectionBox.maxBox,i=t.min.x+(t.max.x-t.min.x)*e.x.min*.01,s=t.min.y+(t.max.y-t.min.y)*e.y.min*.01,r=t.min.z+(t.max.z-t.min.z)*e.z.min*.01,o=t.min.x+(t.max.x-t.min.x)*e.x.max*.01,a=t.min.y+(t.max.y-t.min.y)*e.y.max*.01,l=t.min.z+(t.max.z-t.min.z)*e.z.max*.01;this.sectionBox.setboxXyz({minX:i,minY:s,minZ:r,maxX:o,maxY:a,maxZ:l})}active(e){if(this.engine.engineStatus.isForceFree=!0,this.sectionFace.disActive(),this.sectionBox.disActive(),this.currentClippingMode=e,e=="x")this.sectionFace.init(),this.sectionFace.active(),this.sectionFace.setFaceNormal(new w.Vector3(-1,0,0));else if(e=="y")this.sectionFace.init(),this.sectionFace.active(),this.sectionFace.setFaceNormal(new w.Vector3(0,0,-1));else if(e=="z")this.sectionFace.init(),this.sectionFace.active(),this.sectionFace.setFaceNormal(new w.Vector3(0,-1,0));else if(e=="box")this.sectionBox.init(),this.sectionBox.active();else if(e=="face"){let t=new LD(this.engine);t.init(),t.catch_face(i=>{this.sectionFace.init(),this.sectionFace.active();let s=this.engine.octreeBox.getBoundingBox(),r=s.min.clone().add(s.max.clone()).multiplyScalar(.5),o=i.position.clone().sub(r),a=new w.Vector3(i.dir.x,i.dir.y,i.dir.z),l=o.dot(a);this.sectionFace.setFaceNormal(i.dir,l)})}}disabled(){this.currentClippingMode=="box"?this.sectionBox.disabled():this.sectionFace.disabled(),this.engine.engineStatus.isForceFree=!1}recover(){this.currentClippingMode=="box"?this.sectionBox.recover():this.sectionFace.recover()}reverse(){this.sectionFace.reverse()}disActive(){this.sectionFace.disActive(),this.sectionBox.disActive(),this.clippingCSGSimple?.clear(),this.currentClippingMode="",this.engine.engineStatus.isForceFree=!1}isPointInClippingRange(e,t=this.clippingTolerance){if(!this.isVector3Like(e))return!1;const i=this.getEffectiveClippingPlanes();return i.length===0?!0:i.every(s=>s.distanceToPoint(e)>=-t)}filterIntersectionsByClipping(e,t=this.clippingTolerance){return!Array.isArray(e)||e.length===0?[]:e.filter(i=>this.isPointInClippingRange(i?.point,t))}getEffectiveClippingPlanes(){const e=Array.isArray(this.engine.sectionPlane)?this.engine.sectionPlane:[];if(this.currentClippingMode==="box")return e.slice(0,6).filter(t=>t instanceof w.Plane);if(this.currentClippingMode==="x"||this.currentClippingMode==="y"||this.currentClippingMode==="z"||this.currentClippingMode==="face"){const t=e[6];return t instanceof w.Plane?[t]:[]}return[]}isVector3Like(e){return e!=null&&typeof e.x=="number"&&typeof e.y=="number"&&typeof e.z=="number"}setSectionByView(e,t){this.sectionFace.disActive(),this.sectionBox.disActive(),this.scaleBox(),this.sectionFace.init(!0);const i=this.engine.octreeBox.getBoundingBox(),s=new w.Vector3((i.min.x+i.max.x)/2,(i.min.y+i.max.y)/2,(i.min.z+i.max.z)/2),o=new w.Vector3(t.x,t.y,t.z).normalize().clone().negate(),l=new w.Vector3(e.x,e.y,e.z).clone().sub(s).dot(o);this.sectionFace.setFaceNormalPlaneOnly(o,l),this.sectionFace.activateClippingOnly(),this.currentClippingMode="face"}}class CP{engine;constructor(e){this.engine=e}getLevelTreeData(){let e=[];return this.engine.engineStatus.models.forEach(t=>{e.push({children:t.info.modelTree.modelTreeLevel,name:t.info.baseInfo.name,url:t.url})}),e}getTypeTreeData(){let e=[];return this.engine.engineStatus.models.forEach(t=>{e.push({children:t.info.modelTree.modelTreeType,name:t.info.baseInfo.name,url:t.url})}),e}getMajorTreeData(){let e=[];return this.engine.engineStatus.models.forEach(t=>{e.push({children:t.info.modelTree.modelTreeMajor,name:t.info.baseInfo.name,url:t.url})}),e}}class MP{engine;constructor(e){this.engine=e}getEngineInfo(){let e=0,t=0,i=0;return!this.engine||!this.engine.scene?{totalVertices:0,totalTriangles:0,meshCount:0}:(this.engine.scene.traverse(s=>{if(s instanceof w.Mesh){const r=s.geometry;if(r&&r.attributes){const o=r.attributes.position;if(o){const a=o.count;e+=a;let l=0;r.index?l=r.index.count/3:l=a/3,t+=l}}}}),this.engine.engineStatus.models.forEach(s=>{i=i+(Array.isArray(s?.info?.modelEdge)?s.info.modelEdge.length:0)}),{totalVertices:Math.floor(e),totalTriangles:Math.floor(t),meshCount:i})}}class EP{engine;extended=new Map;constructor(e){this.engine=e}init(){}updateExtended(e,t){let i=this.extended.get(e);i==null?this.extended.set(e,t):t.forEach((s,r)=>{i.set(r,s)})}getModelPropertiesWithName(e,t,i,s){let r=this.extended.get(e),o=this.engine.engineStatus.models.find(l=>l.url===e);o.properties==null?ha(e+"/property",l=>{let c=JSON.parse(l);o.properties=c,setTimeout(()=>{a(c,i,t,s)},100)},()=>{},o?.key):a(o.properties,i,t,s);function a(l,c,h,d){let f={};l.models[h.toString()||""].forEach(g=>{i.includes(l.names[g[1]])&&(f[l.names[g[1]]]=l.values[g[2]])}),r!=null&&r.has(h)&&f.push(r.get(h)),d?.({id:h,properties:f})}}getModelProperties(e,t,i){let s=this.extended.get(e),r=this.engine.engineStatus.models.find(a=>a.url===e);r.properties==null&&ha(e+"/property",a=>{let l=JSON.parse(a);r.properties=l,setTimeout(()=>{o(l,t,i)},100)},()=>{},r?.key),o(r.properties,t,i);function o(a,l,c){let h=[],d=a.models[l.toString()||""],f=d.map(u=>u[0]);f=f.filter((u,g)=>f.indexOf(u)===g),f.forEach(u=>{let g={name:a.categorys[u],children:[]};h.push(g),d.filter(p=>p[0]===u).forEach(p=>{g.children.push({name:a.names[p[1]],value:a.values[p[2]]})})}),s!=null&&s.has(l)&&h.push(s.get(l)),c?.({properties:h,materials:h})}}}class IP{engine;constructor(e){this.engine=e}getModelTypes(){let e=[];return this.engine.engineStatus.models.forEach(t=>{t.info.modelMapper.forEach(s=>{e.push(s.typeName)})}),e=e.filter((t,i,s)=>s.indexOf(t)===i),e}getModelMajors(){let e=[];return this.engine.engineStatus.models.forEach(t=>{t.info.modelMapper.forEach(s=>{e.push(s.majorName)})}),e=e.filter((t,i,s)=>s.indexOf(t)===i),e}getModelLevels(){let e=[];return this.engine.engineStatus.models.forEach(t=>{t.info.modelMapper.forEach(s=>{e.push(s.levelName)})}),e=e.filter((t,i,s)=>s.indexOf(t)===i),e}getModelMappers(e){}getModelMapper(e,t){let i=this.engine.engineStatus.models.find(o=>o.url==e);return i?i.info.modelMapper.find(o=>o.id==t):null}getModelsWithLevelType(e,t,i=null){let s=[];return this.engine.engineStatus.models.forEach(r=>{let o={url:r.url,ids:[]};s.push(o),r.info.modelMapper.filter(l=>l.levelName===e&&l.typeName===t).forEach(l=>{o.ids.push(Number(l.id))})}),i&&i(s),s}getModelsWithType(e,t=null){let i=[];return this.engine.engineStatus.models.forEach(s=>{let r={url:s.url,ids:[]};i.push(r),s.info.modelMapper.filter(a=>a.typeName===e).forEach(a=>{r.ids.push(Number(a.id))})}),t&&t(i),i}getModelsWithLevel(e,t){let i=[];return this.engine.engineStatus.models.forEach(s=>{let r={url:s.url,ids:[]};i.push(r),s.info.modelMapper.filter(a=>a.levelName===e).forEach(a=>{r.ids.push(Number(a.id))})}),t&&t(i),i}getModelsWithMajor(e,t){let i=[];return this.engine.engineStatus.models.forEach(s=>{let r={url:s.url,ids:[]};i.push(r),s.info.modelMapper.filter(a=>a.majorName===e).forEach(a=>{r.ids.push(Number(a.id))})}),t&&t(i),i}}class TP{config;constructor(e){this.config={temperature:.7,maxTokens:2e4,timeout:3e5,...e}}async chat(e){const t=new AbortController,i=setTimeout(()=>t.abort(),this.config.timeout);try{const s=await fetch(`${this.config.baseURL}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({model:this.config.model,messages:e,temperature:this.config.temperature,max_tokens:this.config.maxTokens,stream:!1}),signal:t.signal});if(clearTimeout(i),!s.ok){const o=await s.json().catch(()=>({}));throw new Error(`API请求失败 (${s.status}): ${o.error?.message||o.message||s.statusText}`)}return(await s.json()).choices?.[0]?.message?.content||""}catch(s){throw clearTimeout(i),s.name==="AbortError"?new Error("请求超时,请重试"):s.message.includes("Failed to fetch")?new Error(`网络请求失败,请检查:
|
|
5260
|
+
}`};const gx={turbidity:10,rayleigh:3,mieCoefficient:.005,mieDirectionalG:.7,elevation:2,azimuth:180,exposure:.5,orthoExposureScale:1.5,cloudCoverage:.4,cloudDensity:.4,cloudElevation:.5,showSunDisc:!0},lf="sunrise_clear",mx=.2,cf=[{id:"sunrise_clear",names:["晴朗日出","晴朗日出","Clear Sunrise"],params:{turbidity:4,rayleigh:1.8,mieCoefficient:.004,mieDirectionalG:.72,elevation:8,azimuth:105,exposure:.42,cloudCoverage:.12,cloudDensity:.2,cloudElevation:.45,showSunDisc:!0}},{id:"morning_mist",names:["晨雾薄云","晨雾薄云","Misty Morning"],params:{turbidity:14,rayleigh:2.4,mieCoefficient:.018,mieDirectionalG:.68,elevation:12,azimuth:120,exposure:.35,cloudCoverage:.45,cloudDensity:.5,cloudElevation:.35,showSunDisc:!0}},{id:"noon_clear",names:["晴空正午","晴空正午","Clear Noon"],params:{turbidity:2,rayleigh:1,mieCoefficient:.002,mieDirectionalG:.82,elevation:68,azimuth:180,exposure:.58,cloudCoverage:.05,cloudDensity:.12,cloudElevation:.55,showSunDisc:!0}},{id:"afternoon_cloudy",names:["午后多云","午后多云","Cloudy Afternoon"],params:{turbidity:8,rayleigh:1.7,mieCoefficient:.008,mieDirectionalG:.74,elevation:42,azimuth:220,exposure:.5,cloudCoverage:.48,cloudDensity:.42,cloudElevation:.52,showSunDisc:!0}},{id:"sunset_glow",names:["落日晚霞","落日晚霞","Sunset Glow"],params:{turbidity:10,rayleigh:2,mieCoefficient:.006,mieDirectionalG:.7,elevation:6,azimuth:245,exposure:.6,cloudCoverage:.3,cloudDensity:.36,cloudElevation:.5,showSunDisc:!0}},{id:"blue_hour",names:["暮色蓝调","暮色蓝调","Blue Hour"],params:{turbidity:7,rayleigh:1.2,mieCoefficient:.003,mieDirectionalG:.76,elevation:-4,azimuth:255,exposure:.22,cloudCoverage:.2,cloudDensity:.24,cloudElevation:.48,showSunDisc:!1}},{id:"overcast_day",names:["阴天白昼","阴天白昼","Overcast Day"],params:{turbidity:20,rayleigh:2,mieCoefficient:.02,mieDirectionalG:.6,elevation:32,azimuth:180,exposure:.38,cloudCoverage:.86,cloudDensity:.68,cloudElevation:.4,showSunDisc:!1}},{id:"storm_rain",names:["暴雨雷云","暴雨雷云","Storm Rain"],params:{turbidity:19,rayleigh:.9,mieCoefficient:.03,mieDirectionalG:.58,elevation:18,azimuth:210,exposure:.2,cloudCoverage:.95,cloudDensity:.9,cloudElevation:.28,showSunDisc:!1}},{id:"snow_day",names:["雪天漫射","雪天漫射","Snowy Day"],params:{turbidity:15,rayleigh:2.6,mieCoefficient:.012,mieDirectionalG:.65,elevation:24,azimuth:170,exposure:.5,cloudCoverage:.78,cloudDensity:.72,cloudElevation:.43,showSunDisc:!1}},{id:"moonlit_night",names:["月夜星空","月夜星空","Moonlit Night"],params:{turbidity:4,rayleigh:.35,mieCoefficient:.001,mieDirectionalG:.82,elevation:-18,azimuth:160,exposure:.14,cloudCoverage:.1,cloudDensity:.14,cloudElevation:.55,showSunDisc:!1}}],Ax=cf.reduce((n,e)=>(n[e.id]=e,n),{}),xx=2e6;class yD{engine;sky=null;sun=new w.Vector3;params={...gx,...Ax[lf].params};currentPreset=lf;currentIntensity=mx;currentEnvironmentTarget=null;skyScale=45e4;skyName="bim_engine_sky";savedCameraFar=null;previousBackground=null;previousEnvironment=null;previousBackgroundIntensity=1;previousEnvironmentIntensity=1;previousToneMapping=w.NoToneMapping;previousToneMappingExposure=1;hasCapturedSceneState=!1;constructor(e){this.engine=e}activate(){if(!this.engine?.scene)return;if(this.sky){this.sky.visible=!0,this._captureSceneState(),this._expandCameraFarForSky(),this._applyParamsToSky();return}const e=new Dc;e.scale.setScalar(this.skyScale),e.name=this.skyName,this.sky=e,this.engine.scene.add(e),this._captureSceneState(),this._expandCameraFarForSky(),this.engine.renderer&&(this.engine.renderer.toneMapping=w.ACESFilmicToneMapping,this.engine.scene.background=null),this._applyParamsToSky()}close(e=!0){this.sky&&(this._restoreCameraFar(),this._restoreSceneState(e),e?(this.engine?.scene?.remove(this.sky),this.sky.material.dispose(),this.sky.geometry.dispose(),this.sky=null):this.sky.visible=!1)}isActive(){return this.sky!=null&&this.engine?.scene?.children?.includes(this.sky)}getParams(){return{...this.params}}setParams(e){Object.assign(this.params,e),this._applyParamsToSky(),this.engine?.renderer&&(e.exposure!==void 0||e.orthoExposureScale!==void 0)&&(this.engine.renderer.toneMappingExposure=this._getEffectiveExposure())}setPreset(e){const t=Ax[e];t&&(this.currentPreset=e,this.params={...gx,...t.params},this._applyParamsToSky(),this.engine?.renderer&&(this.engine.renderer.toneMappingExposure=this._getEffectiveExposure()))}getCurrentPreset(){return this.currentPreset}getPresetNames(){return cf.map(e=>e.id)}getPresetList(){return cf.map(e=>({id:e.id,names:[...e.names],params:{...e.params}}))}setIntensity(e){if(this.currentIntensity=Math.max(e,0),!(!this.sky?.visible||!this.engine?.scene)){if(!this.currentEnvironmentTarget){this._refreshEnvironmentMap();return}this.engine.scene.environmentIntensity=this.currentIntensity}}getIntensity(){return this.currentIntensity}update(e){if(!this.sky?.visible)return;const t=this.sky.material.uniforms;t&&"time"in t&&(t.time.value=e??performance.now()*.001),this.engine?.renderer&&(this.engine.renderer.toneMappingExposure=this._getEffectiveExposure())}_isOrthographicCamera(){const e=this.engine?.camera;return e!=null&&e.type==="OrthographicCamera"}_getEffectiveExposure(){const e=this.params.exposure;return this._isOrthographicCamera()?e*this.params.orthoExposureScale:e}_expandCameraFarForSky(){const e=this.engine?.camera;if(!e||typeof e.far!="number")return;const t=e.far;t>=xx||(this.savedCameraFar==null&&(this.savedCameraFar=t),e.far=xx,typeof e.updateProjectionMatrix=="function"&&e.updateProjectionMatrix())}_restoreCameraFar(){if(this.savedCameraFar==null||!this.engine?.camera)return;const e=this.engine.camera;typeof e.far=="number"&&(e.far=this.savedCameraFar,typeof e.updateProjectionMatrix=="function"&&e.updateProjectionMatrix(),this.savedCameraFar=null)}_applyParamsToSky(){if(!this.sky)return;const e=this.sky.material.uniforms;this._setUniformValue(e,"turbidity",this.params.turbidity),this._setUniformValue(e,"rayleigh",this.params.rayleigh),this._setUniformValue(e,"mieCoefficient",this.params.mieCoefficient),this._setUniformValue(e,"mieDirectionalG",this.params.mieDirectionalG),this._setUniformValue(e,"cloudCoverage",this.params.cloudCoverage),this._setUniformValue(e,"cloudDensity",this.params.cloudDensity),this._setUniformValue(e,"cloudElevation",this.params.cloudElevation),this._setUniformValue(e,"showSunDisc",this.params.showSunDisc?1:0);const t=w.MathUtils.degToRad(90-this.params.elevation),i=w.MathUtils.degToRad(this.params.azimuth);this.sun.setFromSphericalCoords(1,t,i),this._setUniformValue(e,"sunPosition",this.sun),this.engine?.renderer&&(this.engine.renderer.toneMapping=w.ACESFilmicToneMapping,this.engine.renderer.toneMappingExposure=this._getEffectiveExposure(),this.sky.visible&&this._refreshEnvironmentMap())}_captureSceneState(){this.hasCapturedSceneState||!this.engine?.scene||(this.previousBackground=this.engine.scene.background,this.previousEnvironment=this.engine.scene.environment,this.previousBackgroundIntensity=this.engine.scene.backgroundIntensity??1,this.previousEnvironmentIntensity=this.engine.scene.environmentIntensity??1,this.previousToneMapping=this.engine.renderer?.toneMapping??w.NoToneMapping,this.previousToneMappingExposure=this.engine.renderer?.toneMappingExposure??1,this.hasCapturedSceneState=!0)}_restoreSceneState(e){!this.hasCapturedSceneState||!this.engine?.scene||(this.engine.scene.background=this.previousBackground,this.engine.scene.environment=this.previousEnvironment,this.engine.scene.backgroundIntensity=this.previousBackgroundIntensity,this.engine.scene.environmentIntensity=this.previousEnvironmentIntensity,this.engine.renderer&&(this.engine.renderer.toneMapping=this.previousToneMapping,this.engine.renderer.toneMappingExposure=this.previousToneMappingExposure),e&&(this._disposeEnvironmentTarget(),this.previousBackground=null,this.previousEnvironment=null,this.previousBackgroundIntensity=1,this.previousEnvironmentIntensity=1,this.previousToneMapping=w.NoToneMapping,this.previousToneMappingExposure=1,this.hasCapturedSceneState=!1))}_refreshEnvironmentMap(){if(!this.sky||!this.engine?.renderer||!this.engine?.scene)return;this._disposeEnvironmentTarget();const e=new w.Scene,t=this.sky.clone();t.material=this.sky.material.clone(),e.add(t);const i=new w.PMREMGenerator(this.engine.renderer);this.currentEnvironmentTarget=i.fromScene(e,0,.1,this.skyScale*2),i.dispose(),this.engine.scene.background=null,this.engine.scene.environment=this.currentEnvironmentTarget.texture,this.engine.scene.environmentIntensity=this.currentIntensity,t.material.dispose()}_disposeEnvironmentTarget(){this.currentEnvironmentTarget?.dispose(),this.currentEnvironmentTarget=null}_setUniformValue(e,t,i){const s=e[t];s&&(i instanceof w.Vector3&&typeof s.value?.copy=="function"?s.value.copy(i):s.value=i)}}class vD{engine;defaultSettings;settings;environmentApplyVersion=0;constructor(e){this.engine=e,this.defaultSettings=this._buildDefaultSettingsFromModules(),this.settings=this._clone(this.defaultSettings)}init(){this.defaultSettings=this._buildDefaultSettingsFromModules(),this.settings=this._clone(this.defaultSettings)}getSettings(){return this._syncSettingsFromModules(),this._clone(this.settings)}getPresetLists(){const e=this.engine.ground?.getGroundList()||[],t=this.engine.hdr?.getHdrList()||[],i=this.engine.skyManager?.getPresetList()||[];return{ground:e.map(s=>this._toPresetItem(s)),hdr:t.map(s=>this._toPresetItem(s)),sky:i.map(s=>this._toPresetItem(s))}}async setSettings(e){e.render&&(Object.assign(this.settings.render,e.render),this._applyRenderSettings(this.settings.render)),e.display&&(Object.assign(this.settings.display,e.display),this._applyDisplaySettings(this.settings.display)),e.environment&&(this._mergeEnvironmentSettings(e.environment),await this._applyEnvironmentSettings(this._clone(this.settings.environment)))}async resetToDefault(){this.settings=this._clone(this.defaultSettings),this._applyRenderSettings(this.settings.render),this._applyDisplaySettings(this.settings.display),await this._applyEnvironmentSettings(this._clone(this.settings.environment))}setRenderMode(e){this.settings.render.mode=e,this.engine.engineModelModule?.switchModel(e)}setContrast(e){this.settings.render.contrast=e,this.engine.engineModelModule?.setContrastValue(.5+e/100)}setSaturation(e){this.settings.render.saturation=e,this.engine.engineModelModule?.setSaturationValue(.5+e/100)}setShadowIntensity(e){this.settings.render.shadowIntensity=e,this._updateDirectionalLight(t=>{t.shadow.intensity=e/100*2})}setLightIntensity(e){this.settings.render.lightIntensity=e,this.setAmbientLightIntensity(e/100)}setGTAOIntensity(e){this.settings.render.gtaoIntensity=e,this.engine.engineModelModule?.setGTAOIntensity(e/100)}setShowEdge(e){this.settings.display.showEdge=e,e?this.engine.modelEdge?.active():this.engine.modelEdge?.disActive()}setEdgeOpacity(e){this.settings.display.edgeOpacity=e,this.engine.modelEdge?.setOpacity(e/100)}setShowGrid(e){this.settings.display.showGrid=e,e?this.engine.grid?.show():this.engine.grid?.hide()}setShowLevel(e){this.settings.display.showLevel=e,e?this.engine.level?.show():this.engine.level?.hide()}setShowGround(e){this.settings.display.showGround=e,e?this.engine.ground?.show():this.engine.ground?.hide()}setGroundId(e){this.settings.display.groundId=e,this.engine.ground?.setGround(e)}setGroundHeight(e){this.settings.display.groundHeight=e,this.engine.ground?.setHeight(e)}async setEnvironmentType(e){this.settings.environment.type=e,await this._applyEnvironmentSettings(this._clone(this.settings.environment))}async setHdrId(e){this.settings.environment.hdrId=e,this.settings.environment.type==="hdr"&&await this._applyEnvironmentSettings(this._clone(this.settings.environment))}setHdrIntensity(e){this.settings.environment.hdrIntensity=e,this.settings.environment.type==="hdr"&&this.engine.hdr?.setIntensity(e/100)}setSkyPreset(e){this.settings.environment.skyPreset=e,this.settings.environment.skyParams={},this.settings.environment.type==="sky"&&this.engine.skyManager?.setPreset(e)}setSkyParams(e){this.settings.environment.skyParams=this._clone(e),this.settings.environment.type==="sky"&&this.engine.skyManager?.setParams(this.settings.environment.skyParams)}setSkyIntensity(e){this.settings.environment.skyIntensity=e,this.settings.environment.type==="sky"&&this.engine.skyManager?.setIntensity(e/100)}setAmbientLightIntensity(e){const t=this.engine.renderer;t&&(t.toneMapping===w.NoToneMapping&&(t.toneMapping=w.ACESFilmicToneMapping),t.toneMappingExposure=2*e,t.toneMappingExposure==1?this.engine.renderer.toneMapping=0:this.engine.renderer.toneMapping=w.ACESFilmicToneMapping)}_syncSettingsFromModules(){this.settings=this._readCurrentSettingsFromModules()}_buildDefaultSettingsFromModules(){const e=this.engine.composerModule?.saturationPass?.uniforms?.saturation?.value,t=this.engine.composerModule?.saturationPass?.uniforms?.contrast?.value,i=this.engine.composerModule?.gtaoPass?.blendIntensity,s=this.engine.renderer?.toneMappingExposure,r=this.engine.modelEdge?.getOpacity?.(),o=this.engine.hdr?.getCurrentHdrId?.()??Sn,a=this.engine.hdr?.getIntensity?.(),l=this.engine.skyManager?.getIntensity?.(),c=this.engine.skyManager?.getCurrentPreset?.()??lf,h=this.engine.skyManager?.isActive?.()===!0;return{render:{mode:this._toRenderMode(this.engine.engineModelModule?.getCurrentMode?.()),contrast:this._uniformToPercent(t,Vm),saturation:this._uniformToPercent(e,Gm),shadowIntensity:this._shadowToPercent(this._getDirectionalLightShadowIntensity(),_c),lightIntensity:this._exposureToPercent(s,Pm),gtaoIntensity:this._unitToPercent(i,zm)},display:{showEdge:this.engine.modelEdge?.isEnabled?.()??af,edgeOpacity:this._unitToPercent(r,px),showGrid:this.engine.grid?.getVisible?.()??rf,showLevel:this.engine.level?.getVisible?.()??fx,showGround:this.engine.ground?.getVisible?.()??dx,groundId:this.engine.ground?.getCurrentId?.()??cx,groundHeight:this.engine.ground?.getHeight?.()??hx},environment:{type:h?"sky":o!==Sn?"hdr":"none",hdrId:o,hdrIntensity:this._unitToPercent(a,ux),skyPreset:c,skyParams:{},skyIntensity:this._unitToPercent(l,mx)}}}_readCurrentSettingsFromModules(){const e=this.engine.composerModule?.saturationPass?.uniforms?.saturation?.value,t=this.engine.composerModule?.saturationPass?.uniforms?.contrast?.value,i=this.engine.composerModule?.gtaoPass?.blendIntensity,s=this.engine.renderer?.toneMappingExposure,r=this.engine.modelEdge?.getOpacity?.(),o=this.engine.hdr?.getCurrentHdrId?.()??this.settings.environment.hdrId,a=this.engine.hdr?.getIntensity?.(),l=this.engine.skyManager?.getIntensity?.(),c=this.engine.skyManager?.getCurrentPreset?.()??this.settings.environment.skyPreset,h=this.engine.skyManager?.getParams?.(),d=this.engine.skyManager?.isActive?.()===!0;return{render:{mode:this._toRenderMode(this.engine.engineModelModule?.getCurrentMode?.()??this.settings.render.mode),contrast:this._uniformToPercent(t,this.settings.render.contrast/100+.5),saturation:this._uniformToPercent(e,this.settings.render.saturation/100+.5),shadowIntensity:this._shadowToPercent(this._getDirectionalLightShadowIntensity(),this.settings.render.shadowIntensity/50),lightIntensity:this._exposureToPercent(s,this.settings.render.lightIntensity/50),gtaoIntensity:this._unitToPercent(i,this.settings.render.gtaoIntensity/100)},display:{showEdge:this.engine.modelEdge?.isEnabled?.()??this.settings.display.showEdge,edgeOpacity:this._unitToPercent(r,this.settings.display.edgeOpacity/100),showGrid:this.engine.grid?.getVisible?.()??this.settings.display.showGrid,showLevel:this.engine.level?.getVisible?.()??this.settings.display.showLevel,showGround:this.engine.ground?.getVisible?.()??this.settings.display.showGround,groundId:this.engine.ground?.getCurrentId?.()??this.settings.display.groundId,groundHeight:this.engine.ground?.getHeight?.()??this.settings.display.groundHeight},environment:{type:d?"sky":o!==Sn?"hdr":"none",hdrId:o,hdrIntensity:this._unitToPercent(a,this.settings.environment.hdrIntensity/100),skyPreset:c,skyParams:h?this._clone(h):this._clone(this.settings.environment.skyParams),skyIntensity:this._unitToPercent(l,this.settings.environment.skyIntensity/100)}}}_toRenderMode(e){return e==="simple"||e==="balance"||e==="advanced"?e:q0}_uniformToPercent(e,t){const i=typeof e=="number"?e:t;return this._clampPercent((i-.5)*100)}_shadowToPercent(e,t){const i=typeof e=="number"?e:t;return this._clampPercent(i*50)}_exposureToPercent(e,t){const i=typeof e=="number"?e:t;return this._clampPercent(i*50)}_unitToPercent(e,t){const i=typeof e=="number"?e:t;return this._clampPercent(i*100)}_clampPercent(e){return Math.min(100,Math.max(0,Math.round(e)))}_getDirectionalLightShadowIntensity(){const e=this.engine.scene?.children?.filter(i=>i instanceof w.DirectionalLight);return!e||e.length===0?_c:(e.find(i=>i.castShadow)??e[0]).shadow?.intensity??_c}_applyRenderSettings(e){this.setRenderMode(e.mode),this.setContrast(e.contrast),this.setSaturation(e.saturation),this.setShadowIntensity(e.shadowIntensity),this.setLightIntensity(e.lightIntensity),this.setGTAOIntensity(e.gtaoIntensity)}_applyDisplaySettings(e){this.setShowEdge(e.showEdge),this.setEdgeOpacity(e.edgeOpacity),this.setShowGrid(e.showGrid),this.setShowLevel(e.showLevel),this.setShowGround(e.showGround),this.setGroundId(e.groundId),this.setGroundHeight(e.groundHeight)}async _applyEnvironmentSettings(e){const t=++this.environmentApplyVersion;if(await this.engine.hdr?.setHdr(Sn),t===this.environmentApplyVersion&&(this.engine.skyManager?.close(!0),t===this.environmentApplyVersion))switch(e.type){case"none":break;case"hdr":if(e.hdrId!==Sn){if(await this.engine.hdr?.setHdr(e.hdrId),t!==this.environmentApplyVersion){this._applyEnvironmentSettings(this._clone(this.settings.environment));return}this.engine.hdr?.setIntensity(e.hdrIntensity/100)}break;case"sky":this.engine.skyManager?.activate(),this.engine.skyManager?.setPreset(e.skyPreset),Object.keys(e.skyParams).length>0&&this.engine.skyManager?.setParams(this._clone(e.skyParams)),this.engine.skyManager?.setIntensity(e.skyIntensity/100);break}}_updateDirectionalLight(e){const t=this.engine.scene?.children.find(i=>i instanceof w.DirectionalLight);t&&e(t)}_mergeEnvironmentSettings(e){Object.assign(this.settings.environment,e),e.skyPreset!==void 0&&e.skyParams===void 0&&(this.settings.environment.skyParams={}),e.skyParams!==void 0&&(this.settings.environment.skyParams=this._clone(e.skyParams))}_toPresetItem(e){const t=Array.isArray(e.names)?[...e.names]:[];return{id:e.id,name:t[0]??e.id,names:t}}_clone(e){return JSON.parse(JSON.stringify(e))}}function $n(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(n){var e=Math.random()*16|0,t=n=="x"?e:e&3|8;return t.toString(16)})}class Jn{engine;handelBehaved;setting;constructor(e){this.engine=e,this.handelBehaved=wu(e),this.handelBehaved.init(this,null),this.setting={unit:"m",precision:3}}getSetting(){return this.setting}saveSetting(e){this.setting=e}active(){this.handelBehaved.active()}disActive(){this.handelBehaved.disActive()}getMeasureText(e,t){if(e==null)return null;let i=this.setting.unit,s=i;return t==1?i=="mm"?e=e*1e3:i=="cm"?e=e*100:i=="dm"?e=e*10:i=="m"?e=e*1:i=="km"&&(e=e*.001):t==2&&(i=="mm"?e=e*1e3*1e3:i=="cm"?e=e*100*100:i=="dm"?e=e*10*10:i=="m"?e=e*1*1:i=="km"&&(e=e*.001*.001),s=s+"²"),e.toFixed(this.setting.precision)+" "+s}cancelCurrentSelectedAnnotation(){let e=this.engine.measure.annotationData;for(let t in e)e[t].forEach(i=>{i.highlight==!0&&(i.highlight=!1,i.container.classList.remove("Hight"),i.container.getElementsByTagName("svg")[0].classList.remove("Hight"))})}handelKeyEscDown(){this.cancelCurrentSelectedAnnotation();let e=this.engine.measure.annotationData;for(let t in e)for(let i=e[t].length-1;i>=0;i--){let s=e[t][i];s.isSelect==!0&&(s.container.remove(),e[t].splice(i,1))}this.engine.measure.clearAllPoints()}handelKeyDeleteDown(){let e=this.engine.measure.annotationData;for(let t in e)for(let i=e[t].length-1;i>=0;i--){let s=e[t][i];s.highlight==!0&&(s.container.remove(),e[t].splice(i,1))}}clearHighlight(){let e=this.engine.measure.annotationData;for(let t in e)e[t].forEach(i=>{i.highlight=!1,i.container.classList.remove("Hight"),i.container.getElementsByTagName("svg")[0].classList.remove("Hight")})}drawNormalAnnotation(){let e=this;this.engine.measure.annotationData.normalAnnotation.forEach(g=>{u(g)}),this.engine.measure.annotationData.elevationAnnotation.forEach(g=>{f(g)}),this.engine.measure.annotationData.coordinateAnnotation.forEach(g=>{d(g)}),this.engine.measure.annotationData.angleAnnotation.forEach(g=>{l(g)}),this.engine.measure.annotationData.areaAnnotation.forEach(g=>{c(g)}),this.engine.measure.annotationData.slopeAnnotation.forEach(g=>{h(g)});function l(g){if(g.container==null){let C=['<svg class="measureSvg">','<circle class="measurePointer" cx="50" cy="50" r="5" fill="#f99d0b" />','<circle class="measurePointer" cx="50" cy="50" r="5" fill="#f99d0b" />','<circle class="measurePointer" cx="50" cy="50" r="5" fill="#f99d0b" />','<polyline class="measureLine" stroke="orange" stroke-width="2" points="0,0 0,0" style="fill: none; opacity: 1;"/>','<polyline class="measureLine" stroke="orange" stroke-width="2" points="0,0 0,0" style="fill: none; opacity: 1;"/>','<rect x="0" y="0" width="100" height="25" class="measureBack" />','<text x="50" y="16" text-anchor="middle" class="measureLabel">'+g.text+"</text>","</svg>"].join("");g.container=document.createElement("div"),g.container.className="angle-annotation",g.container.id=g.id,g.container.style.pointerEvents="none",g.container.innerHTML=C,e.engine.measure.annotationContainer.appendChild(g.container),g.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),g.container.getElementsByTagName("svg")[0].classList.add("Hight"),g.highlight=!0,e.engine.events.trigger(Et.MeasureClick,g)}),g.isSelect&&(g.container.getElementsByTagName("svg")[0].classList.add("Hight"),g.highlight=!0)}let p=new lt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(g.point1),m=new lt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(g.point2),A=new lt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(g.point3),x=e.engine.reactBoundingClientRect.left,b=e.engine.reactBoundingClientRect.top;p.x+=x,p.y+=b,m.x+=x,m.y+=b,A.x+=x,A.y+=b;let y=g.container;y.getElementsByTagName("circle")[0].setAttribute("cx",p.x),y.getElementsByTagName("circle")[0].setAttribute("cy",p.y),y.getElementsByTagName("circle")[1].setAttribute("cx",m.x),y.getElementsByTagName("circle")[1].setAttribute("cy",m.y),y.getElementsByTagName("circle")[2].setAttribute("cx",A.x),y.getElementsByTagName("circle")[2].setAttribute("cy",A.y),y.getElementsByTagName("polyline")[0].setAttribute("points",p.x+","+p.y+" "+m.x+","+m.y),y.getElementsByTagName("polyline")[1].setAttribute("points",m.x+","+m.y+" "+A.x+","+A.y);let _=m.x,S=m.y-30;y.getElementsByTagName("rect")[0].setAttribute("x",_-40),y.getElementsByTagName("rect")[0].setAttribute("y",S-12.5),y.getElementsByTagName("text")[0].setAttribute("x",_),y.getElementsByTagName("text")[0].setAttribute("y",S+4),y.getElementsByTagName("text")[0].innerHTML=g.text,y.style.top="0px",y.style.left="0px"}function c(g){if(g.container==null){let D=['<svg class="measureSvg">','<polygon fill="rgba(0, 0, 255, 0.1)" stroke="orange" stroke-width="2" points="" style="opacity: 0.3;"/>','<polyline class="measureLine" stroke="orange" stroke-width="2" points="" style="fill: none; opacity: 1;"/>','<rect x="0" y="0" width="100" height="25" class="measureBack" />','<text x="50" y="16" text-anchor="middle" class="measureLabel"> '+e.getMeasureText(g.text,2)+"</text>","</svg>"].join("");g.container=document.createElement("div"),g.container.className="area-annotation",g.container.id=g.id,g.container.innerHTML=D,e.engine.measure.annotationContainer.appendChild(g.container),g.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),g.container.getElementsByTagName("svg")[0].classList.add("Hight"),g.highlight=!0,e.engine.events.trigger(Et.MeasureClick,g)}),g.isSelect&&(g.container.getElementsByTagName("svg")[0].classList.add("Hight"),g.highlight=!0)}if(!g.points||g.points.length<3)return;let p=e.engine.reactBoundingClientRect.left,m=e.engine.reactBoundingClientRect.top,A=[],x=0,b=0;for(let D=0;D<g.points.length;D++){let M=new lt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(g.points[D]);M.x+=p,M.y+=m,A.push(M),x+=M.x,b+=M.y}x=x/A.length,b=b/A.length;let y=A.map(D=>D.x+","+D.y).join(" "),_=g.container;_.getElementsByTagName("polygon")[0].setAttribute("points",y),_.getElementsByTagName("polyline")[0].setAttribute("points",y);let S=x,C=b;_.getElementsByTagName("rect")[0].setAttribute("x",S-40),_.getElementsByTagName("rect")[0].setAttribute("y",C-12.5),_.getElementsByTagName("text")[0].setAttribute("x",S+10),_.getElementsByTagName("text")[0].setAttribute("y",C+4),_.getElementsByTagName("text")[0].innerHTML=e.getMeasureText(g.text,2),_.style.top="0px",_.style.left="0px"}function h(g){if(g.container==null){let S=['<svg class="measureSvg">',"<defs>",'<marker id="slope-arrow-'+g.id+'" markerWidth="10" markerHeight="10" refX="9" refY="3" orient="auto" markerUnits="strokeWidth">','<path class="measureLine" d="M0,0 L0,6 L9,3 z"/>',"</marker>","</defs>",'<polyline class="measureLine" stroke="orange" stroke-width="2" points="0,0 0,0" marker-end="url(#slope-arrow-'+g.id+')" style="fill: none; opacity: 1;"/>','<rect x="0" y="0" width="100" height="25" class="measureBack" />','<text x="50" y="16" text-anchor="middle" class="measureLabel"> '+g.text+"</text>","</svg>"].join("");g.container=document.createElement("div"),g.container.className="slope-annotation",g.container.id=g.id,g.container.innerHTML=S,e.engine.measure.annotationContainer.appendChild(g.container),g.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),g.container.getElementsByTagName("svg")[0].classList.add("Hight"),g.highlight=!0,e.engine.events.trigger(Et.MeasureClick,g)}),g.isSelect&&(g.container.getElementsByTagName("svg")[0].classList.add("Hight"),g.highlight=!0)}let p=new lt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(g.point1),m=new lt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(g.point2),A=e.engine.reactBoundingClientRect.left,x=e.engine.reactBoundingClientRect.top;p.x+=A,p.y+=x,m.x+=A,m.y+=x;let b=g.container;b.getElementsByTagName("polyline")[0].setAttribute("points",p.x+","+p.y+" "+m.x+","+m.y);let y=(p.x+m.x)/2,_=(p.y+m.y)/2-30;b.getElementsByTagName("rect")[0].setAttribute("x",y-50),b.getElementsByTagName("rect")[0].setAttribute("y",_-12.5),b.getElementsByTagName("text")[0].setAttribute("x",y),b.getElementsByTagName("text")[0].setAttribute("y",_+4),b.getElementsByTagName("text")[0].innerHTML=g.text,b.style.top="0px",b.style.left="0px"}function d(g){if(g.container==null){let C=['<svg class="measureSvg">','<circle class="measurePointer" cx="0" cy="0" r="5" fill="#f99d0b" />','<rect x="0" y="-25" width="100" height="25" class="measureBack" />','<text x="50" y="-11" text-anchor="middle" class="measureLabel"> X: '+e.getMeasureText(g.textX,1)+"</text>",'<rect x="0" y="-10" width="100" height="25" class="measureBack" />','<text x="50" y="25" text-anchor="middle" class="measureLabel"> Y: '+e.getMeasureText(-g.textZ,1)+"</text>",'<rect x="0" y="10" width="100" height="25" class="measureBack" />','<text x="50" y="51" text-anchor="middle" class="measureLabel"> Z: '+e.getMeasureText(g.textY,1)+"</text>","</svg>"].join("");g.container=document.createElement("div"),g.container.className="coordinate-annotation",g.container.id=g.id,g.container.style.position="absolute",g.container.style.pointerEvents="none",g.container.innerHTML=C,e.engine.measure.annotationContainer.appendChild(g.container),g.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),g.container.getElementsByTagName("svg")[0].classList.add("Hight"),g.highlight=!0,e.engine.events.trigger(Et.MeasureClick,g)}),g.isSelect&&(g.container.getElementsByTagName("svg")[0].classList.add("Hight"),g.highlight=!0)}let p=g.container,m=new lt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(g.point),A=e.engine.reactBoundingClientRect.left,x=e.engine.reactBoundingClientRect.top;m.x+=A,m.y+=x,p.style.top="0px",p.style.left="0px";let b=p.getElementsByTagName("circle")[0];b&&(b.setAttribute("cx",m.x),b.setAttribute("cy",m.y));let y=p.getElementsByTagName("rect"),_=p.getElementsByTagName("text"),S=-55;y[0]&&(y[0].setAttribute("x",m.x+10),y[0].setAttribute("y",m.y+10+S)),_[0]&&(_[0].setAttribute("x",m.x+10+50),_[0].setAttribute("y",m.y+10+16+S)),y[1]&&(y[1].setAttribute("x",m.x+10),y[1].setAttribute("y",m.y+10+30+S)),_[1]&&(_[1].setAttribute("x",m.x+10+50),_[1].setAttribute("y",m.y+10+46+S)),y[2]&&(y[2].setAttribute("x",m.x+10),y[2].setAttribute("y",m.y+10+60+S)),_[2]&&(_[2].setAttribute("x",m.x+10+50),_[2].setAttribute("y",m.y+10+76+S)),_[0]&&(_[0].innerHTML="X: "+e.getMeasureText(g.textX,1)),_[1]&&(_[1].innerHTML="Y: "+e.getMeasureText(-g.textZ,1)),_[2]&&(_[2].innerHTML="Z: "+e.getMeasureText(g.textY,1))}function f(g){if(g.container==null){let b=['<svg width="100" height="50" class="measureSvg">','<rect x="0" y="0" width="100" height="25" class="measureBack" />','<text x="50" y="16" text-anchor="middle" class="measureLabel"> '+e.getMeasureText(g.text,1)+"</text>",'<polyline class="measureLine" stroke-width="2" points="80,32 0,32 16,48 32,32" style="fill: none; opacity: 1;"/>',"</svg>"].join("");g.container=document.createElement("div"),g.container.className="elevation-annotation",g.container.id=g.id,g.container.style.position="absolute",g.container.style.pointerEvents="none",g.container.innerHTML=b,e.engine.measure.annotationContainer.appendChild(g.container),g.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),g.container.getElementsByTagName("svg")[0].classList.add("Hight"),g.highlight=!0,e.engine.events.trigger(Et.MeasureClick,g)}),g.isSelect&&(g.container.getElementsByTagName("svg")[0].classList.add("Hight"),g.highlight=!0)}let p=g.container,m=new lt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(g.point),A=e.engine.reactBoundingClientRect.left,x=e.engine.reactBoundingClientRect.top;p.style.top=m.y+x-48+"px",p.style.left=m.x+A-16+"px",p.getElementsByTagName("text")[0].innerHTML=e.getMeasureText(g.text,1)}function u(g){if(g.container==null){let y=['<svg class="measureSvg">','<circle class="measurePointer" cx="50" cy="50" r="5" fill="#f99d0b" />','<circle class="measurePointer" cx="50" cy="50" r="5" fill="#f99d0b" />','<polyline class="measureLine" stroke="orange" stroke-width="2" points="80,32 0,32" style="fill: none; opacity: 1;"/>','<rect x="0" y="0" width="100" height="25" class="measureBack" />','<text x="50" y="16" text-anchor="middle" class="measureLabel"> '+e.getMeasureText(g.text,1)+"</text>","</svg>"].join("");g.container=document.createElement("div"),g.container.className="normal-annotation",g.container.id=g.id,g.container.innerHTML=y,e.engine.measure.annotationContainer.appendChild(g.container),g.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),g.container.getElementsByTagName("svg")[0].classList.add("Hight"),g.highlight=!0,e.engine.events.trigger(Et.MeasureClick,g)}),g.isSelect&&(g.container.getElementsByTagName("svg")[0].classList.add("Hight"),g.highlight=!0)}let p=g.container;if(g.point1==null||g.point2==null){p.style.display="none";return}else p.style.display="block";let m=new lt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(g.point1),A=new lt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(g.point2),x=e.engine.reactBoundingClientRect.left,b=e.engine.reactBoundingClientRect.top;m.x+=x,m.y+=b,A.x+=x,A.y+=b,p.getElementsByTagName("polyline")[0].setAttribute("points",m.x+","+m.y+" "+A.x+","+A.y),p.getElementsByTagName("circle")[0].setAttribute("cx",m.x),p.getElementsByTagName("circle")[0].setAttribute("cy",m.y),p.getElementsByTagName("circle")[1].setAttribute("cx",A.x),p.getElementsByTagName("circle")[1].setAttribute("cy",A.y),p.getElementsByTagName("rect")[0].setAttribute("x",m.x*.5+A.x*.5-40),p.getElementsByTagName("rect")[0].setAttribute("y",m.y*.5+A.y*.5-12.5),p.getElementsByTagName("text")[0].setAttribute("x",m.x*.5+A.x*.5+50-40),p.getElementsByTagName("text")[0].setAttribute("y",m.y*.5+A.y*.5+16-12.5),p.getElementsByTagName("text")[0].innerHTML=e.getMeasureText(g.text,1),p.style.top="0px",p.style.left="0px"}}}class _D{engine;isActive=!1;tools;points=[];behavior;catchDir=0;type="point";constructor(e){this.engine=e,this.tools=new Jn(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.isActive=!0,this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1;let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}setDirection(e){this.catchDir=e}setSelectType(e){this.type=e}getMeshesMinMaxY(e){if(!Array.isArray(e)||e.length===0)return null;let t=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY;for(let s=0;s<e.length;s++){const r=e[s];if(!r)continue;typeof r.updateMatrixWorld=="function"&&r.updateMatrixWorld(!0);const o=new w.Box3().setFromObject(r);!Number.isFinite(o.min.y)||!Number.isFinite(o.max.y)||(o.min.y<t&&(t=o.min.y),o.max.y>i&&(i=o.max.y))}return!Number.isFinite(t)||!Number.isFinite(i)?null:{minY:t,maxY:i}}handleMouseClick(e){if(e.catch==null)return;let t=e.catch.point;if(this.type=="element"){let r=this.engine.interactionModule.getCatchMeshs(e);var i=this.getMeshesMinMaxY(r);this.catchDir==0?t.set(t.x,i?.minY,t.z):t.set(t.x,i?.maxY,t.z)}else t=e.catch.point;if(this.points.length==0){this.engine.measure.tools.clearHighlight(),this.points.push(t);return}let s=this.engine.measure.annotationData.normalAnnotation.find(r=>r.isSelect==!0);s!=null&&(s.isSelect=!1)}handleMouseMove(e){if(e.catch==null||this.points.length==0)return;let t=this.engine.measure.annotationData.normalAnnotation.find(s=>s.isSelect==!0);t==null&&(t={text:null,id:$n(),isSelect:!0,type:"clear-height"},this.engine.measure.annotationData.normalAnnotation.push(t));let i=e.catch;if(this.type=="element"){let s=e.catch.point.clone();s.set(s.x,this.points[0].y,s.z);let r=new w.Raycaster(s.add(new w.Vector3(0,.01,0)),new w.Vector3(0,this.catchDir==0?-1:1,0));i.point=this.points[0];const o=this.engine.clipping?.filterIntersectionsByClipping(this.engine.octreeBox.rayInterationModel(r))??this.engine.octreeBox.rayInterationModel(r);if(o.length===0){t.point2=null;return}t.point1=s,t.point2=o[0].point,t.text=t.point1.clone().distanceTo(t.point2.clone()),this.engine.events.trigger(Et.MeasureChanged,t)}else{let s=new w.Raycaster(e.catch.point.clone().add(new w.Vector3(0,.01,0)),new w.Vector3(0,this.catchDir==0?-1:1,0));const r=this.engine.clipping?.filterIntersectionsByClipping(this.engine.octreeBox.rayInterationModel(s))??this.engine.octreeBox.rayInterationModel(s);if(r.length===0){t.point2=null;return}t.point1=i.point,t.point2=r[0].point,t.text=t.point1.clone().distanceTo(t.point2.clone()),this.engine.events.trigger(Et.MeasureChanged,t)}}}class wD{engine;tools;isActive=!1;points=[];behavior;constructor(e){this.engine=e,this.tools=new Jn(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.isActive=!0,this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1;let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.isActive=!1,this.engine.handelBehaved.disActive()}clearAllPoints(){this.points=[]}handleMouseClick(e){if(e.catch==null)return;let t=e.catch;if(this.points.length==0)this.engine.measure.tools.clearHighlight(),this.points.push(t.point);else if(this.points.length==1){let i=this.engine.measure.annotationData.normalAnnotation.find(s=>s.isSelect==!0);if(i==null)return;i.point2=t.point,i.isSelect=!1,this.points=[],this.engine.events.trigger(Et.MeasureChanged,i)}}handleMouseMove(e){if(e.catch==null)return;let t=e.catch;if(t!=null&&this.points.length==1){let i=this.engine.measure.annotationData.normalAnnotation.find(s=>s.isSelect==!0);i==null&&(i={id:$n(),point1:this.points[0].clone(),point2:t.point.clone(),text:this.points[0].clone().distanceTo(t.point.clone()),type:"distance",isSelect:!0},this.engine.measure.annotationData.normalAnnotation.push(i)),i.point2=t.point,i.text=i.point1.clone().distanceTo(i.point2.clone())}}}class SD{engine;isActive=!1;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new Jn(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.isActive=!0,this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1;let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}handleMouseClick(e){if(e.catch==null)return;if(this.points.length==0){this.engine.measure.tools.clearHighlight(),this.points.push(e.catch.point);return}let t=this.engine.measure.annotationData.normalAnnotation.find(i=>i.isSelect==!0);t!=null&&(t.isSelect=!1)}handleMouseMove(e){if(e.catch==null||this.points.length==0)return;let t=this.engine.measure.annotationData.normalAnnotation.find(o=>o.isSelect==!0);t==null&&(t={text:null,id:$n(),isSelect:!0,type:"clear-distance"},this.engine.measure.annotationData.normalAnnotation.push(t));let i=new w.Raycaster(e.catch.point.clone().add(e.catch.face.normal.clone().setLength(.01)),e.catch.face.normal);const s=this.engine.clipping?.filterIntersectionsByClipping(this.engine.octreeBox.rayInterationModel(i))??this.engine.octreeBox.rayInterationModel(i);if(s.length==0){t.point2=null;return}let r=e.catch;t.point1=r.point,t.point2=s[0].point,t.text=t.point1.clone().distanceTo(t.point2.clone()),this.engine.events.trigger(Et.MeasureChanged,t)}}class CD{engine;isActive=!1;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new Jn(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1,this.isActive=!0;let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}handleMouseMove(e){if(e.catch==null)return;let t=this.engine.measure.annotationData.elevationAnnotation.find(i=>i.isSelect==!0);t==null&&(t={id:$n(),point:e.catch.point.clone(),text:e.catch.point.y,isSelect:!0,type:"elevation"},this.engine.measure.annotationData.elevationAnnotation.push(t)),t.point=e.catch.point.clone(),t.text=e.catch.point.y}handleMouseClick(e){if(e.catch==null)return;this.engine.measure.tools.clearHighlight();let t=this.engine.measure.annotationData.elevationAnnotation.find(i=>i.isSelect==!0);t!=null&&(t.isSelect=!1,t.point=e.catch.point.clone(),t.text=e.catch.point.y,this.engine.events.trigger(Et.MeasureChanged,t))}}class MD{engine;isActive=!1;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new Jn(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1,this.isActive=!0;let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}handleMouseUp(e){this.engine.deviceType!="PC"&&this.createMeasure()}handleMouseMove(e){if(e.catch==null)return;let t=this.engine.measure.annotationData.coordinateAnnotation.find(i=>i.isSelect==!0);t!=null&&(t.point=e.catch.point.clone(),t.textX=e.catch.point.x,t.textY=e.catch.point.y,t.textZ=e.catch.point.z)}handleMouseClick(e){if(e.catch==null)return;this.engine.measure.tools.clearHighlight();let t=this.engine.measure.annotationData.coordinateAnnotation.find(i=>i.isSelect==!0);if(t==null){t={id:$n(),point:e.catch.point.clone(),text:Math.round(e.catch.point.y)+" m",isSelect:!0,type:"point"},this.engine.measure.annotationData.coordinateAnnotation.push(t);return}t.point=e.catch.point.clone(),t.textX=e.catch.point.x,t.textY=e.catch.point.y,t.textZ=e.catch.point.z,t.isSelect=!1,this.engine.events.trigger(Et.MeasureChanged,t)}createMeasure(){let e=this.engine.measure.annotationData.coordinateAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1,this.engine.events.trigger(Et.MeasureChanged,e))}}class ED{engine;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new Jn(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1;let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.behavior?.disActive()}clearAllPoints(){this.points=[]}calculateAngle(e,t,i){const s=new w.Vector3().subVectors(e,t),r=new w.Vector3().subVectors(i,t),o=s.length(),a=r.length();if(o===0||a===0)return 0;const c=s.dot(r)/(o*a),h=Math.max(-1,Math.min(1,c));return Math.acos(h)*(180/Math.PI)}handleMouseClick(e){if(e.catch==null)return;let t=e.catch;if(this.points.length==0)this.engine.measure.tools.clearHighlight(),this.points.push(t.point);else if(this.points.length==1)this.points.push(t.point);else if(this.points.length==2){let i=this.engine.measure.annotationData.angleAnnotation.find(s=>s.isSelect==!0);if(i==null)return;i.point3=t.point.clone(),i.angle=this.calculateAngle(i.point1,i.point2,i.point3),i.text=i.angle.toFixed(2)+"°",i.isSelect=!1,i.type="angle",this.points=[],this.engine.events.trigger(Et.MeasureChanged,i)}}handleMouseMove(e){if(e.catch!=null&&this.points.length!=1&&this.points.length==2){let t=this.engine.measure.annotationData.angleAnnotation.find(i=>i.isSelect==!0);t==null&&(t={id:$n(),point1:this.points[0].clone(),point2:this.points[1].clone(),point3:e.catch.point.clone(),angle:0,text:"0.00°",isSelect:!0,type:"angle"},this.engine.measure.annotationData.angleAnnotation.push(t)),t.point3=e.catch.point.clone(),t.angle=this.calculateAngle(t.point1,t.point2,t.point3),t.text=t.angle.toFixed(2)+"°",console.log("角度",t.text)}}}class ID{engine;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new Jn(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1;let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.behavior?.disActive()}clearAllPoints(){this.points=[]}calculateArea(e){if(e.length<3)return 0;const t=e.length,i=new w.Vector3(0,0,0);for(let s=0;s<t;s++){const r=(s+1)%t;i.x+=(e[s].y-e[r].y)*(e[s].z+e[r].z),i.y+=(e[s].z-e[r].z)*(e[s].x+e[r].x),i.z+=(e[s].x-e[r].x)*(e[s].y+e[r].y)}return i.length()/2}handleRightMouseClick(){this.finishMeasure()}handleMouseClick(e){if(e.catch==null)return;let t=e.catch;if(this.points.push(t.point.clone()),this.points.length>=3){let i=this.engine.measure.annotationData.areaAnnotation.find(s=>s.isSelect==!0);i==null?(i={id:$n(),points:this.points.map(s=>s.clone()),area:0,text:0,isSelect:!0,type:"area"},this.engine.measure.annotationData.areaAnnotation.push(i)):(this.points.push(t.point.clone()),i.points=this.points.map(s=>s.clone())),i.area=this.calculateArea(i.points),i.text=i.area,console.log("面积",i.text)}else this.engine.measure.tools.clearHighlight()}handleMouseMove(e){if(e.catch!=null&&this.points.length>=2){let t=this.engine.measure.annotationData.areaAnnotation.find(i=>i.isSelect==!0);if(t==null){if(this.points.length>=2){let i=this.points.map(s=>s.clone());i.push(e.catch.point.clone()),i.length>=3&&(t={id:$n(),points:i,area:0,text:0,isSelect:!0,type:"area"},this.engine.measure.annotationData.areaAnnotation.push(t))}}else if(t.points.length>0){const i=t.points.length-1;t.points[i]=e.catch.point.clone()}else t.points=this.points.map(i=>i.clone()),t.points.push(e.catch.point.clone());t&&t.points.length>=3&&(t.area=this.calculateArea(t.points),t.text=t.area)}}handelKeyEnterDown(){this.finishMeasure()}finishMeasure(){this.points=this.points.slice(0,this.points.length-1);let e=this.engine.measure.annotationData.areaAnnotation.find(t=>t.isSelect==!0);e!=null&&e.points.length>3?(e.points.length>this.points.length&&(e.points=this.points.map(t=>t.clone())),e.area=this.calculateArea(e.points),e.text=e.area,e.isSelect=!1,this.points=[],this.engine.events.trigger(Et.MeasureChanged,e)):this.engine.measure.tools.handelKeyEscDown()}}class TD{engine;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new Jn(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1;let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.behavior?.disActive()}clearAllPoints(){this.points=[]}calculateSlope(e,t){const i=t.y-e.y,s=t.x-e.x,r=t.z-e.z,o=Math.sqrt(s*s+r*r);if(o===0)return{percentage:0,angle:0,heightDiff:i,horizontalDist:0,type:"slope"};const a=i/o*100,c=Math.atan(i/o)*(180/Math.PI);return{percentage:a,angle:c,heightDiff:i,horizontalDist:o,type:"slope"}}handleMouseClick(e){if(e.catch==null)return;let t=e.catch;if(this.points.length==0)this.engine.measure.tools.clearHighlight(),this.points.push(t.point);else if(this.points.length==1){let i=this.engine.measure.annotationData.slopeAnnotation.find(r=>r.isSelect==!0);if(i==null)return;console.log("进来了"),i.point2=t.point.clone();const s=this.calculateSlope(i.point1,i.point2);i.slopePercentage=s.percentage,i.slopeAngle=s.angle,i.heightDiff=s.heightDiff,i.horizontalDist=s.horizontalDist,i.text=s.percentage.toFixed(2)+"%",i.isSelect=!1,this.points=[],this.engine.events.trigger(Et.MeasureChanged,i)}}handleMouseMove(e){if(e.catch==null)return;let t=e.catch;if(t!=null&&this.points.length==1){let i=this.engine.measure.annotationData.slopeAnnotation.find(r=>r.isSelect==!0);i==null&&(i={id:$n(),point1:this.points[0].clone(),point2:t.point.clone(),slopePercentage:0,slopeAngle:0,heightDiff:0,horizontalDist:0,text:"0.00%",isSelect:!0,type:"slope"},this.engine.measure.annotationData.slopeAnnotation.push(i)),i.point2=t.point.clone();const s=this.calculateSlope(i.point1,i.point2);i.slopePercentage=s.percentage,i.slopeAngle=s.angle,i.heightDiff=s.heightDiff,i.horizontalDist=s.horizontalDist,i.text=s.percentage.toFixed(2)+"%"}}}class DD{isActive=!1;engine;clearHeightMeasure;distanceMeasure;clearDistanceMeasure;elevationMeasure;pointMeasure;angleMeasure;areaMeasure;slopeMeasure;tools;annotationContainer;annotationData={normalAnnotation:[],textAnnotation:[],coordinateAnnotation:[],angleAnnotation:[],distanceAnnotation:[],areaAnnotation:[],slopeAnnotation:[],elevationAnnotation:[],volumeAnnotation:[]};constructor(e){this.engine=e,this.clearHeightMeasure=new _D(e),this.distanceMeasure=new wD(e),this.clearDistanceMeasure=new SD(e),this.elevationMeasure=new CD(e),this.pointMeasure=new MD(e),this.angleMeasure=new ED(e),this.areaMeasure=new ID(e),this.slopeMeasure=new TD(e),this.tools=new Jn(e),this.annotationContainer=document.createElement("div"),this.annotationContainer.className="annotation-container",e.container.appendChild(this.annotationContainer)}active(){this.isActive=!0,this.engine.modelEdge.loadModelEdge(),this.tools.active()}disActive(){this.tools.disActive(),this.clearAll(),this.isActive=!1,this.clearHeightMeasure.disActive(),this.distanceMeasure.disActive(),this.clearDistanceMeasure.disActive(),this.elevationMeasure.disActive(),this.pointMeasure.disActive(),this.angleMeasure.disActive(),this.areaMeasure.disActive(),this.slopeMeasure.disActive(),this.engine.interactionModule.init(),this.engine.interactionModule.active()}clearAllPoints(){this.clearHeightMeasure.clearAllPoints(),this.distanceMeasure.clearAllPoints(),this.clearDistanceMeasure.clearAllPoints(),this.elevationMeasure.clearAllPoints(),this.pointMeasure.clearAllPoints(),this.angleMeasure.clearAllPoints(),this.areaMeasure.clearAllPoints(),this.slopeMeasure.clearAllPoints()}clearAll(){e(this.annotationData.normalAnnotation),e(this.annotationData.textAnnotation),e(this.annotationData.coordinateAnnotation),e(this.annotationData.angleAnnotation),e(this.annotationData.distanceAnnotation),e(this.annotationData.areaAnnotation),e(this.annotationData.slopeAnnotation),e(this.annotationData.elevationAnnotation),e(this.annotationData.volumeAnnotation);function e(t){for(let i=0;i<t.length;i++)t[i].container.remove();t=[]}}saveSetting(e){this.tools.saveSetting(e)}getSetting(){return this.tools.getSetting()}update(){this.isActive&&this.tools.drawNormalAnnotation()}}class BD{engine;isActive=!1;isCtrlDown=!1;listenersAttached=!1;box;pickPoint;pickNormal;pickMesh;box_;plane;meshs;isDrag=!1;maxBox;faceIdleOpacity=0;faceHoverOpacity=.05;transformControls=new Map;transformAnchors=new Map;transformHelpers=new Map;faceMetaMap=new Map;isSyncingTransform=!1;transformHandleSize=1.05;transformHandleColor=16777215;transformHandleHoverColor=16776960;handleNativeMouseDown=e=>{if(e.button!==0||!(this.isCtrlDown||e.ctrlKey))return;const t=this.createRaycasterFromMouseEvent(e),i=t.intersectObjects(this.getInteractiveMeshes(),!1);i.length!==0&&(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseDown({button:e.button,raycaster:t,intersects:i}))};handleNativeMouseMove=e=>{if(!this.isDrag&&!(this.isCtrlDown||e.ctrlKey)){this.resetMeshOpacity();return}const t=this.createRaycasterFromMouseEvent(e),i=t.intersectObjects(this.getInteractiveMeshes(),!1);this.isDrag&&(e.preventDefault(),e.stopImmediatePropagation()),this.handleMouseMove({raycaster:t,intersects:i})};handleNativeMouseUp=e=>{e.button!==0||!this.isDrag||(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseUp({button:e.button}))};handleNativeKeyDown=e=>{e.key==="Control"&&(this.isCtrlDown=!0)};handleNativeKeyUp=e=>{e.key==="Control"&&(this.isCtrlDown=!1,this.isDrag&&this.handleMouseUp({button:0}),this.resetMeshOpacity())};constructor(e,t){this.engine=e,this.meshs=[]}active(){this.isActive||(this.attachListeners(),this.init(),this.setTransformControlsVisible(!0),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")||(t.visible=!0)})}),this.isActive=!0)}disActive(){this.init(!1),this.isActive=!1,this.detachListeners(),this.handleMouseUp({button:0},!1),this.setTransformControlsVisible(!1),this.clearClippingBoxFill(),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")||(t.visible=!1)})})}disabled(){this.isActive=!1,this.detachListeners(),this.handleMouseUp({button:0},!1),this.setTransformControlsVisible(!1),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")||(t.visible=!1)})})}recover(){this.isActive||(this.attachListeners(),this.setTransformControlsVisible(!0),this.updateClippingBoxFill(),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")||(t.visible=!0)})}),this.isActive=!0)}init(e=!0){const t=this.engine.octreeBox.getBoundingBox();t.min.x-=.1,t.min.y-=.1,t.min.z-=.1,t.max.x+=.1,t.max.y+=.1,t.max.z+=.1,this.maxBox=JSON.parse(JSON.stringify(t)),this.box=t,this.updata_face(t),e&&this.updateClippingBoxFill()}getboxXyz(){return{minX:this.box.min.x,minY:this.box.min.y,minZ:this.box.min.z,maxX:this.box.max.x,maxY:this.box.max.y,maxZ:this.box.max.z}}setboxXyz(e){this.box.min.x=e.minX,this.box.min.y=e.minY,this.box.min.z=e.minZ,this.box.max.x=e.maxX,this.box.max.y=e.maxY,this.box.max.z=e.maxZ,this.updata_face(this.box),this.updateClippingBoxFill()}setBox(e){this.box=e,this.updata_face(e),this.updateClippingBoxFill()}reverseBox(){}handleMouseDown(e){const t=e.intersects??e.raycaster.intersectObjects(this.getInteractiveMeshes(),!1);if(t!=null&&t.length>0){this.clearClippingBoxFill();const i=t[0];this.isDrag=!0,this.pickPoint=i.point.clone(),this.pickMesh=i.object;const s=this.pickMesh?.userData?.dragNormal?.clone?.(),r=i.face?.normal?.clone?.();if(this.pickNormal=(s??r??new w.Vector3(0,0,1)).clone().normalize(),this.engine.controls.enabled=!1,this.box_={min:this.box.min.clone(),max:this.box.max.clone()},this.pickNormal.y==0){const o=new w.Plane;o.setFromNormalAndCoplanarPoint(new w.Vector3(0,1,0),this.pickPoint),this.plane=o}else{const o=new w.Vector3(this.engine.camera.position.x,this.pickPoint.y,this.engine.camera.position.z),a=new w.Plane;a.setFromNormalAndCoplanarPoint(o.clone().sub(this.pickPoint.clone()).setLength(1),this.pickPoint),this.plane=a}}else this.isDrag=!1}handleMouseUp(e,t=!0){this.isDrag=!1,this.pickPoint=null,this.pickNormal=null,this.pickMesh=null,this.plane=null,this.engine.controls.enabled=!0,t&&this.updateClippingBoxFill()}clampVector3(e,t,i){return new w.Vector3(Math.max(t.x,Math.min(i.x,e.x)),Math.max(t.y,Math.min(i.y,e.y)),Math.max(t.z,Math.min(i.z,e.z)))}handleMouseMove(e){this.resetMeshOpacity();const t=e.intersects??e.raycaster.intersectObjects(this.getInteractiveMeshes(),!1);if(t!=null&&t.length>0&&(t[0].object.material.opacity=this.faceHoverOpacity),this.pickPoint!=null){const i=new w.Vector3;if(e.raycaster.ray.intersectPlane(this.plane,i)){const s=i.clone().sub(this.pickPoint.clone()).dot(this.pickNormal.clone());if(!!this.pickMesh?.userData?.isMinFace){const o=this.box_.min.clone().add(this.pickNormal.clone().setLength(s));this.box.min=this.clampVector3(o,this.maxBox.min,this.box.max)}else{const o=this.box_.max.clone().add(this.pickNormal.clone().setLength(s));this.box.max=this.clampVector3(o,this.box.min,this.maxBox.max)}this.updata_face(this.box),this.calculate_ratio()}}}calculate_ratio(){const e=this.maxBox.max.x-this.maxBox.min.x,t=this.maxBox.max.y-this.maxBox.min.y,i=this.maxBox.max.z-this.maxBox.min.z,s=this.toPercent((this.box.min.x-this.maxBox.min.x)/e*100),r=this.toPercent((this.box.max.x-this.maxBox.min.x)/e*100),o=this.toPercent((this.box.min.y-this.maxBox.min.y)/t*100),a=this.toPercent((this.box.max.y-this.maxBox.min.y)/t*100),l=this.toPercent((this.box.min.z-this.maxBox.min.z)/i*100),c=this.toPercent((this.box.max.z-this.maxBox.min.z)/i*100),h={x:{min:s,max:r},y:{min:o,max:a},z:{min:l,max:c}};this.engine.events.trigger(Et.SectionMove,h)}toPercent(e){return e<0?0:e>100?100:e}getInteractiveMeshes(){return this.meshs.filter(e=>e.type==="Mesh")}createRaycasterFromMouseEvent(e){const t=new w.Raycaster,i=new w.Vector2,s=this.engine.renderer.domElement.clientWidth,r=this.engine.renderer.domElement.clientHeight;return i.x=e.offsetX/s*2-1,i.y=-(e.offsetY/r)*2+1,t.setFromCamera(i,this.engine.camera),t}attachListeners(){if(this.listenersAttached)return;const e=this.engine.renderer?.domElement;e&&(e.addEventListener("mousedown",this.handleNativeMouseDown,!0),e.addEventListener("mousemove",this.handleNativeMouseMove,!0),e.addEventListener("mouseup",this.handleNativeMouseUp,!0),window.addEventListener("keydown",this.handleNativeKeyDown),window.addEventListener("keyup",this.handleNativeKeyUp),this.listenersAttached=!0)}detachListeners(){if(!this.listenersAttached)return;const e=this.engine.renderer?.domElement;e&&(e.removeEventListener("mousedown",this.handleNativeMouseDown,!0),e.removeEventListener("mousemove",this.handleNativeMouseMove,!0),e.removeEventListener("mouseup",this.handleNativeMouseUp,!0)),window.removeEventListener("keydown",this.handleNativeKeyDown),window.removeEventListener("keyup",this.handleNativeKeyUp),this.listenersAttached=!1,this.isCtrlDown=!1}resetMeshOpacity(){this.getInteractiveMeshes().forEach(e=>{e.material&&(e.material.opacity=this.faceIdleOpacity)})}updateClippingBoxFill(){const e=(Array.isArray(this.engine.sectionPlane)?this.engine.sectionPlane:[]).slice(0,6).filter(t=>t instanceof w.Plane);if(e.length===0){this.clearClippingBoxFill();return}this.engine.clipping?.clippingCSGSimple?.updataFaces?.(e)}clearClippingBoxFill(){this.engine.clipping?.clippingCSGSimple?.clear?.()}getFaceTransformOffset(){if(!this.box)return .06;const e=this.box.min.distanceTo(this.box.max);return Math.max(e*.015,.06)}keepSingleDirectionArrow(e,t="X"){const i=e.getHelper(),s=[];i.traverse(r=>{if(r?.name!==t||!r.geometry)return;const o=r.geometry;o.boundingBox||o.computeBoundingBox();const a=o.boundingBox;if(!a)return;const l=a.getCenter(new w.Vector3);if(!(t==="X"&&l.x<0||t==="Y"&&l.y<0||t==="Z"&&l.z<0))return;const h=o.parameters,d=h&&h.radiusTop===0&&h.radiusBottom===.04&&h.height===.1,f=h&&h.radiusTop===.2&&h.radiusBottom===0&&h.height===.6;(d||f)&&s.push(r)}),s.forEach(r=>{r.parent?.remove(r)})}setTransformControlsVisible(e){this.transformControls.forEach(t=>{t.enabled=e}),this.transformHelpers.forEach(t=>{t.visible=e}),this.transformAnchors.forEach(t=>{t.visible=e}),e||(this.engine.controls.enabled=!0)}ensureFaceTransformControl(e){if(this.transformControls.has(e)&&this.transformAnchors.has(e))return;const t=this.engine.renderer?.domElement,i=this.engine.camera;if(!t||!i)return;const s=new w.Object3D;s.name=`SectionBoxTransformAnchor_${e}`,s.visible=this.isActive,this.engine.scene.add(s);const r=new sx(i,t);r.name=`SectionBoxTransformControl_${e}`,r.setMode("translate"),r.setSpace("local"),r.showX=!0,r.showY=!1,r.showZ=!1,r.size=this.transformHandleSize,r.setColors(this.transformHandleColor,this.transformHandleColor,this.transformHandleColor,this.transformHandleHoverColor),r.enabled=this.isActive,r.attach(s),this.keepSingleDirectionArrow(r,"X"),r.addEventListener("dragging-changed",a=>{this.engine.controls.enabled=!a.value,a.value===!0?this.clearClippingBoxFill():this.updateClippingBoxFill()}),r.addEventListener("objectChange",()=>{this.handleTransformObjectChange(e)});const o=r.getHelper();o.visible=this.isActive,this.engine.scene.add(o),this.transformAnchors.set(e,s),this.transformControls.set(e,r),this.transformHelpers.set(e,o)}updateFaceTransformControl(e,t,i,s){this.ensureFaceTransformControl(e);const r=this.transformAnchors.get(e),o=this.transformControls.get(e);if(!r||!o)return;const a=this.getFaceTransformOffset(),l=new w.Quaternion().setFromUnitVectors(new w.Vector3(1,0,0),t.clone().normalize()),c=i.clone().add(t.clone().setLength(a));this.faceMetaMap.set(e,{normal:t.clone().normalize(),isMinFace:s,center:i.clone()}),this.isSyncingTransform=!0,r.position.copy(c),r.quaternion.copy(l),r.visible=this.isActive,o.object!==r&&o.attach(r),o.enabled=this.isActive;const h=this.transformHelpers.get(e);h&&(h.visible=this.isActive),this.isSyncingTransform=!1}getDominantAxis(e){const t=Math.abs(e.x),i=Math.abs(e.y),s=Math.abs(e.z);return t>=i&&t>=s?"x":i>=t&&i>=s?"y":"z"}handleTransformObjectChange(e){if(this.isSyncingTransform)return;const t=this.transformAnchors.get(e),i=this.faceMetaMap.get(e);if(!t||!i||!this.box||!this.maxBox)return;const s=i.normal,r=this.getDominantAxis(s),o=this.getFaceTransformOffset(),a=s[r],l=t.position[r]-a*o;if(i.isMinFace){const c=this.maxBox.min[r],h=this.box.max[r];this.box.min[r]=Math.max(c,Math.min(h,l))}else{const c=this.box.min[r],h=this.maxBox.max[r];this.box.max[r]=Math.max(c,Math.min(h,l))}this.updata_face(this.box),this.calculate_ratio()}updata_face(e){let t=this.engine.scene.children.find(s=>s.type=="Group"&&s.name=="ClippingBox");t==null&&(t=new w.Group,t.name="ClippingBox",this.engine.scene.add(t)),[{name:"前",normal:new w.Vector3(0,0,-1),isMinFace:!0,planePoint:e.min,vertices:[new w.Vector3(e.min.x,e.max.y,e.min.z),new w.Vector3(e.max.x,e.max.y,e.min.z),new w.Vector3(e.max.x,e.min.y,e.min.z),new w.Vector3(e.min.x,e.min.y,e.min.z)]},{name:"后",normal:new w.Vector3(0,0,1),isMinFace:!1,planePoint:e.max,vertices:[new w.Vector3(e.min.x,e.min.y,e.max.z),new w.Vector3(e.max.x,e.min.y,e.max.z),new w.Vector3(e.max.x,e.max.y,e.max.z),new w.Vector3(e.min.x,e.max.y,e.max.z)]},{name:"右",normal:new w.Vector3(1,0,0),isMinFace:!1,planePoint:e.max,vertices:[new w.Vector3(e.max.x,e.min.y,e.max.z),new w.Vector3(e.max.x,e.min.y,e.min.z),new w.Vector3(e.max.x,e.max.y,e.min.z),new w.Vector3(e.max.x,e.max.y,e.max.z)]},{name:"左",normal:new w.Vector3(-1,0,0),isMinFace:!0,planePoint:e.min,vertices:[new w.Vector3(e.min.x,e.min.y,e.min.z),new w.Vector3(e.min.x,e.min.y,e.max.z),new w.Vector3(e.min.x,e.max.y,e.max.z),new w.Vector3(e.min.x,e.max.y,e.min.z)]},{name:"顶",normal:new w.Vector3(0,1,0),isMinFace:!1,planePoint:e.max,vertices:[new w.Vector3(e.min.x,e.max.y,e.max.z),new w.Vector3(e.max.x,e.max.y,e.max.z),new w.Vector3(e.max.x,e.max.y,e.min.z),new w.Vector3(e.min.x,e.max.y,e.min.z)]},{name:"底",normal:new w.Vector3(0,-1,0),isMinFace:!0,planePoint:e.min,vertices:[new w.Vector3(e.min.x,e.min.y,e.min.z),new w.Vector3(e.max.x,e.min.y,e.min.z),new w.Vector3(e.max.x,e.min.y,e.max.z),new w.Vector3(e.min.x,e.min.y,e.max.z)]}].forEach(s=>{this.createFace(t,s.vertices,s.normal,s.name,s.isMinFace,s.planePoint)}),this.engine.scene.children.filter(s=>s.type=="Mesh"&&s.url).forEach(s=>{s.material&&Array.isArray(s.material)?s.material.forEach(r=>{r.clippingPlanes=this.engine.sectionPlane}):s.material.clippingPlanes=this.engine.sectionPlane})}createFace(e,t,i,s,r,o){const a=new w.BufferGeometry,l=new Float32Array([t[0].x,t[0].y,t[0].z,t[1].x,t[1].y,t[1].z,t[2].x,t[2].y,t[2].z,t[3].x,t[3].y,t[3].z]),c=[0,2,1,0,3,2];a.setAttribute("position",new w.BufferAttribute(l,3)),a.setIndex(c);let h=this.meshs.find(A=>A.name===s);if(h==null){const A=new w.MeshBasicMaterial({color:65280,transparent:!0,opacity:this.faceIdleOpacity,side:w.DoubleSide});A.polygonOffset=!0,A.polygonOffsetFactor=1,A.polygonOffsetUnits=4,h=new w.Mesh(a,A),h.name=s,e.add(h),this.meshs.push(h)}else h.geometry=a;h.userData={dragNormal:i.clone(),isMinFace:r,faceName:s};const d=new Float32Array([t[0].x,t[0].y,t[0].z,t[1].x,t[1].y,t[1].z,t[2].x,t[2].y,t[2].z,t[3].x,t[3].y,t[3].z,t[0].x,t[0].y,t[0].z]),f=new w.LineBasicMaterial({color:255}),u=new w.BufferGeometry;u.setAttribute("position",new w.BufferAttribute(d,3));let g=this.meshs.find(A=>A.name===s+"Line");g==null?(g=new w.Line(u,f),g.name=s+"Line",e.add(g),this.meshs.push(g)):(g.geometry=u,g.material=f);const p=new w.Vector3;t.forEach(A=>p.add(A)),p.multiplyScalar(1/t.length),this.updateFaceTransformControl(s,i,p,r);const m=this.engine.sectionPlane.find(A=>A.name==s);m&&m.setFromNormalAndCoplanarPoint(i.clone().setLength(-1),o)}}class PD{engine;isActive=!1;isDrag=!1;isCtrlDown=!1;listenersAttached=!1;meshs=[];box=null;pickPoint=null;pickNormal=null;plane=null;angleX=0;angleY=0;angleZ=0;direction=1;normal=new w.Vector3(0,0,1);distance=0;center=null;current_center=null;dragStartDistance=0;idleOpacity=.02;hoverOpacity=.05;transformControl=null;transformAnchor=null;transformHelper=null;isSyncingTransformControl=!1;moveEpsilon=1e-5;transformHandleSize=1.15;transformHandleColor=16777215;transformHandleHoverColor=16776960;handleNativeMouseDown=e=>{if(e.button!==0||!(this.isCtrlDown||e.ctrlKey))return;const t=this.createRaycasterFromMouseEvent(e),i=t.intersectObjects(this.getInteractiveMeshes(),!1);i.length!==0&&(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseDown({button:e.button,raycaster:t,intersects:i}))};handleNativeMouseMove=e=>{if(!this.isDrag&&!(this.isCtrlDown||e.ctrlKey)){this.resetMeshOpacity();return}const t=this.createRaycasterFromMouseEvent(e),i=t.intersectObjects(this.getInteractiveMeshes(),!1);this.isDrag&&(e.preventDefault(),e.stopImmediatePropagation()),this.handleMouseMove({raycaster:t,intersects:i})};handleNativeMouseUp=e=>{e.button!==0||!this.isDrag||(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseUp({button:e.button}))};handleNativeKeyDown=e=>{e.key==="Control"&&(this.isCtrlDown=!0)};handleNativeKeyUp=e=>{e.key==="Control"&&(this.isCtrlDown=!1,this.isDrag&&this.handleMouseUp({button:0}),this.resetMeshOpacity())};handleTransformObjectChange=()=>{if(this.isSyncingTransformControl||!this.transformAnchor||!this.center)return;const e=this.normal.clone().normalize(),t=this.getDistanceRange(e),i=this.getTransformHandleOffset(),s=this.transformAnchor.position.clone().sub(this.center).dot(e)-i,r=Math.min(t.max,Math.max(t.min,s));Math.abs(r-Number(this.distance))>this.moveEpsilon?this.updata_face(r):Math.abs(s-r)>this.moveEpsilon&&this.updateTransformControl(e)};constructor(e){this.engine=e,this.meshs=[],this.box=null}active(){if(this.isActive==!0)return;this.isActive=!0,this.engine.scene.children.filter(t=>t.type=="Group"&&t.name=="ClippingBox").forEach(t=>{t.children.forEach(i=>{i.name.includes("face")&&(i.visible=!0)})}),this.attachListeners(),this.ensureTransformControl(),this.setTransformControlVisible(!0);const e=this;e.engine.scene.children.filter(t=>t.type=="Mesh"&&t.url).forEach(t=>{t.material&&Array.isArray(t.material)?t.material.forEach(i=>{i.clippingPlanes=e.engine.sectionPlane}):t.material.clippingPlanes=e.engine.sectionPlane,e.engine.clipping.clippingStencil?.addMesh(e.engine.sectionPlane.find(i=>i.name=="face"),t)}),this.init()}disActive(){this.init(),this.isActive=!1,this.detachListeners(),this.handleMouseUp({button:0},!1),this.setTransformControlVisible(!1),this.clearClippingFaceFill();const e=this.engine.sectionPlane.find(t=>t.name=="face");e&&(e.constant=1e5),this.engine.scene.children.filter(t=>t.type=="Group"&&t.name=="ClippingBox").forEach(t=>{t.children.forEach(i=>{i.name.includes("face")&&(i.visible=!1)})})}init(e){const t=this.engine.octreeBox.getBoundingBox();this.box=t,this.distance=0,this.center=new w.Vector3((t.min.x+t.max.x)/2,(t.min.y+t.max.y)/2,(t.min.z+t.max.z)/2),this.current_center=this.center.clone(),!e&&this.updata_face(0)}disabled(){this.isActive=!1,this.detachListeners(),this.handleMouseUp({button:0},!1),this.setTransformControlVisible(!1),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")&&(t.visible=!1)})})}recover(){this.isActive||(this.attachListeners(),this.setTransformControlVisible(!0),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")&&(t.visible=!0)})}),this.isActive=!0)}setFaceAngle(e,t,i){this.angleX=e,this.angleY=t,this.angleZ=i,this.distance=0,this.normal=new w.Vector3(0,1,0).applyAxisAngle(new w.Vector3(1,0,0),e).applyAxisAngle(new w.Vector3(0,0,1),t).applyAxisAngle(new w.Vector3(0,1,0),i).normalize(),this.updata_face(0),this.updateClippingFaceFill()}setFaceNormal(e,t=0){this.normal=e.clone().normalize(),this.distance=t,this.updata_face(t),this.updateClippingFaceFill()}setFaceNormalPlaneOnly(e,t){if(this.normal=e.clone().normalize(),this.distance=t,!this.center||!this.box)return;const i=this.engine.sectionPlane?.find(s=>s.name==="face");if(i){const s=this.center.clone().add(this.normal.clone().multiplyScalar(t));i.setFromNormalAndCoplanarPoint(this.normal.clone().multiplyScalar(this.direction),s)}this.updateClippingFaceFill()}activateClippingOnly(){if(this.isActive)return;this.isActive=!0;const e=this;e.engine.scene.children.filter(t=>t.type==="Mesh"&&t.url).forEach(t=>{t.material&&Array.isArray(t.material)?t.material.forEach(i=>{i.clippingPlanes=e.engine.sectionPlane}):t.material.clippingPlanes=e.engine.sectionPlane,e.engine.clipping.clippingStencil?.addMesh(e.engine.sectionPlane.find(i=>i.name==="face"),t)})}reverse(){this.direction=this.direction*-1,this.updata_face(this.distance),this.updateClippingFaceFill()}getFaceAngle(){return{angleX:this.angleX,angleY:this.angleY,angleZ:this.angleZ,direction:this.direction}}updata_face(e){if(!this.box)return;this.distance=e;let t=this.engine.scene.children.find(b=>b.type=="Group"&&b.name=="ClippingBox");t==null&&(t=new w.Group,t.name="ClippingBox",this.engine.scene.add(t));const i=this.normal.clone().normalize(),s=this.center??new w.Vector3((this.box.min.x+this.box.max.x)/2,(this.box.min.y+this.box.max.y)/2,(this.box.min.z+this.box.max.z)/2);this.center=s.clone();const{tangent:r,bitangent:o}=this.getPlaneBasis(i),a=this.getBoxCorners(this.box),l=this.box.min.distanceTo(this.box.max),c=Math.max(l*.02,.01);let h=1/0,d=-1/0,f=1/0,u=-1/0;a.forEach(b=>{const y=b.clone().sub(s),_=y.dot(r),S=y.dot(o);h=Math.min(h,_),d=Math.max(d,_),f=Math.min(f,S),u=Math.max(u,S)}),h-=c,d+=c,f-=c,u+=c;const g=i.clone().multiplyScalar(e),p=s.clone().add(r.clone().multiplyScalar(h)).add(o.clone().multiplyScalar(f)).add(g),m=s.clone().add(r.clone().multiplyScalar(d)).add(o.clone().multiplyScalar(f)).add(g),A=s.clone().add(r.clone().multiplyScalar(d)).add(o.clone().multiplyScalar(u)).add(g),x=s.clone().add(r.clone().multiplyScalar(h)).add(o.clone().multiplyScalar(u)).add(g);this.current_center=s.clone().add(g),this.createFace(t,[p,m,A,x],i,"face"),this.updateTransformControl(i)}createFace(e,t,i,s){const r=new w.BufferGeometry,o=new Float32Array([t[0].x,t[0].y,t[0].z,t[1].x,t[1].y,t[1].z,t[2].x,t[2].y,t[2].z,t[3].x,t[3].y,t[3].z]),a=[0,1,2,0,2,3];r.setAttribute("position",new w.BufferAttribute(o,3)),r.setIndex(a);let l=this.meshs.find(g=>g.name==s);if(l==null){const g=new w.MeshBasicMaterial({color:65280,transparent:!0,opacity:this.idleOpacity,side:w.DoubleSide});g.polygonOffset=!0,g.polygonOffsetFactor=1,g.polygonOffsetUnits=4,l=new w.Mesh(r,g),l.name=s,e.add(l),this.meshs.push(l)}else l.geometry=r;l.normal=i.clone();const c=new Float32Array([t[0].x,t[0].y,t[0].z,t[1].x,t[1].y,t[1].z,t[2].x,t[2].y,t[2].z,t[3].x,t[3].y,t[3].z,t[0].x,t[0].y,t[0].z]),h=new w.LineBasicMaterial({color:255}),d=new w.BufferGeometry;d.setAttribute("position",new w.BufferAttribute(c,3));let f=this.meshs.find(g=>g.name==s+"Line");f==null?(f=new w.Line(d,h),f.name=s+"Line",e.add(f),this.meshs.push(f)):(f.geometry=d,f.material=h);const u=this.engine.sectionPlane.find(g=>g.name==s);u&&this.current_center&&u.setFromNormalAndCoplanarPoint(i.clone().setLength(this.direction),this.current_center)}getPlaneBasis(e){const t=new w.Vector3(1,0,0),i=new w.Vector3(0,1,0),s=new w.Vector3(0,0,1),r=Math.abs(e.dot(t)),o=Math.abs(e.dot(i)),a=Math.abs(e.dot(s));let l=t;o<=r&&o<=a?l=i:a<=r&&a<=o&&(l=s),l=l.clone().sub(e.clone().multiplyScalar(l.dot(e))).normalize();const c=new w.Vector3().crossVectors(e,l).normalize();return{tangent:l,bitangent:c}}getBoxCorners(e){return[new w.Vector3(e.min.x,e.min.y,e.min.z),new w.Vector3(e.min.x,e.min.y,e.max.z),new w.Vector3(e.min.x,e.max.y,e.min.z),new w.Vector3(e.min.x,e.max.y,e.max.z),new w.Vector3(e.max.x,e.min.y,e.min.z),new w.Vector3(e.max.x,e.min.y,e.max.z),new w.Vector3(e.max.x,e.max.y,e.min.z),new w.Vector3(e.max.x,e.max.y,e.max.z)]}getDistanceRange(e){if(!this.box)return{min:0,max:0};const t=this.center??new w.Vector3((this.box.min.x+this.box.max.x)/2,(this.box.min.y+this.box.max.y)/2,(this.box.min.z+this.box.max.z)/2),i=this.getBoxCorners(this.box);let s=1/0,r=-1/0;return i.forEach(o=>{const a=o.clone().sub(t).dot(e);s=Math.min(s,a),r=Math.max(r,a)}),{min:s,max:r}}getInteractiveMeshes(){return this.meshs.filter(e=>e.type==="Mesh")}getTransformHandleOffset(){if(!this.box)return .06;const e=this.box.min.distanceTo(this.box.max);return Math.max(e*.015,.06)}keepSingleDirectionArrow(e,t="X"){const i=e.getHelper(),s=[];i.traverse(r=>{if(r?.name!==t||!r.geometry)return;const o=r.geometry;o.boundingBox||o.computeBoundingBox();const a=o.boundingBox;if(!a)return;const l=a.getCenter(new w.Vector3);if(!(t==="X"&&l.x<0||t==="Y"&&l.y<0||t==="Z"&&l.z<0))return;const h=o.parameters,d=h&&h.radiusTop===0&&h.radiusBottom===.04&&h.height===.1,f=h&&h.radiusTop===.2&&h.radiusBottom===0&&h.height===.6;(d||f)&&s.push(r)}),s.forEach(r=>{r.parent?.remove(r)})}ensureTransformControl(){if(this.transformControl&&this.transformAnchor)return;const e=this.engine.renderer?.domElement,t=this.engine.camera;if(!e||!t)return;const i=new w.Object3D;i.name="SectionFaceTransformAnchor",i.visible=this.isActive,this.engine.scene.add(i);const s=new sx(t,e);s.name="SectionFaceTransformControl",s.setMode("translate"),s.setSpace("local"),s.showX=!0,s.showY=!1,s.showZ=!1,s.size=this.transformHandleSize,s.setColors(this.transformHandleColor,this.transformHandleColor,this.transformHandleColor,this.transformHandleHoverColor),s.enabled=this.isActive,s.attach(i),this.keepSingleDirectionArrow(s,"X"),s.addEventListener("dragging-changed",o=>{this.engine.controls.enabled=!o.value,o.value===!0?this.clearClippingFaceFill():this.updateClippingFaceFill()}),s.addEventListener("objectChange",this.handleTransformObjectChange);const r=s.getHelper();r.visible=this.isActive,this.engine.scene.add(r),this.transformAnchor=i,this.transformControl=s,this.transformHelper=r}setTransformControlVisible(e){this.ensureTransformControl(),this.transformControl&&(this.transformControl.enabled=e),this.transformHelper&&(this.transformHelper.visible=e),this.transformAnchor&&(this.transformAnchor.visible=e),e||(this.engine.controls.enabled=!0)}updateTransformControl(e){if(this.ensureTransformControl(),!this.transformControl||!this.transformAnchor||!this.current_center)return;const t=this.getTransformHandleOffset(),i=this.current_center.clone().add(e.clone().setLength(t)),s=new w.Quaternion().setFromUnitVectors(new w.Vector3(1,0,0),e.clone().normalize().multiplyScalar(-1));this.isSyncingTransformControl=!0,this.transformAnchor.position.copy(i),this.transformAnchor.quaternion.copy(s),this.transformAnchor.visible=this.isActive,this.transformControl.object!==this.transformAnchor&&this.transformControl.attach(this.transformAnchor),this.transformControl.enabled=this.isActive,this.transformHelper&&(this.transformHelper.visible=this.isActive),this.isSyncingTransformControl=!1}createRaycasterFromMouseEvent(e){const t=new w.Raycaster,i=new w.Vector2,s=this.engine.renderer.domElement.clientWidth,r=this.engine.renderer.domElement.clientHeight;return i.x=e.offsetX/s*2-1,i.y=-(e.offsetY/r)*2+1,t.setFromCamera(i,this.engine.camera),t}attachListeners(){if(this.listenersAttached)return;const e=this.engine.renderer?.domElement;e&&(e.addEventListener("mousedown",this.handleNativeMouseDown,!0),e.addEventListener("mousemove",this.handleNativeMouseMove,!0),e.addEventListener("mouseup",this.handleNativeMouseUp,!0),window.addEventListener("keydown",this.handleNativeKeyDown),window.addEventListener("keyup",this.handleNativeKeyUp),this.listenersAttached=!0)}detachListeners(){if(!this.listenersAttached)return;const e=this.engine.renderer?.domElement;e&&(e.removeEventListener("mousedown",this.handleNativeMouseDown,!0),e.removeEventListener("mousemove",this.handleNativeMouseMove,!0),e.removeEventListener("mouseup",this.handleNativeMouseUp,!0)),window.removeEventListener("keydown",this.handleNativeKeyDown),window.removeEventListener("keyup",this.handleNativeKeyUp),this.listenersAttached=!1,this.isCtrlDown=!1}resetMeshOpacity(){this.getInteractiveMeshes().forEach(e=>{e.material&&(e.material.opacity=this.idleOpacity)})}updateClippingFaceFill(){const e=this.engine.sectionPlane?.find?.(t=>t.name==="face");if(e){this.engine.clipping?.clippingCSGSimple?.updataFace?.(e);return}this.clearClippingFaceFill()}clearClippingFaceFill(){this.engine.clipping?.clippingCSGSimple?.clear?.()}handleMouseDown(e){const t=e.intersects??e.raycaster.intersectObjects(this.getInteractiveMeshes(),!1);if(t!=null&&t.length>0){this.clearClippingFaceFill();const i=t[0],s=i.point.clone();this.isDrag=!0,this.pickPoint=s;const o=(i.face?.normal?.clone()??this.normal.clone()).clone();if(o.dot(this.normal)<0&&o.multiplyScalar(-1),o.normalize(),this.pickNormal=o,this.engine.controls.enabled=!1,this.dragStartDistance=Number(this.distance)||0,o.y==0){const a=new w.Plane;a.setFromNormalAndCoplanarPoint(new w.Vector3(0,1,0),s),this.plane=a}else{const a=new w.Vector3(this.engine.camera.position.x,s.y,this.engine.camera.position.z),l=new w.Plane;l.setFromNormalAndCoplanarPoint(a.clone().sub(s.clone()).setLength(1),s),this.plane=l}}else this.isDrag=!1}handleMouseUp(e,t=!0){this.isDrag=!1,this.pickPoint=null,this.pickNormal=null,this.plane=null,this.engine.controls.enabled=!0,t&&this.updateClippingFaceFill()}handleMouseMove(e){this.resetMeshOpacity();const t=e.intersects??e.raycaster.intersectObjects(this.getInteractiveMeshes(),!1);t!=null&&t.length>0&&(t[0].object.material.opacity=this.hoverOpacity);const i=this.pickPoint,s=this.pickNormal,r=this.plane;if(i!=null&&s!=null&&r!=null){const o=new w.Vector3;if(e.raycaster.ray.intersectPlane(r,o)){const a=o.clone().sub(i.clone()).dot(s.clone()),l=this.getDistanceRange(this.normal.clone().normalize()),c=this.dragStartDistance+a;this.distance=Math.min(l.max,Math.max(l.min,c)),this.updata_face(this.distance)}}}}class LD{engine;callback_;constructor(e){this.engine=e}init(){this.engine.handelBehaved.init(this,{showCatch:!0}),this.engine.handelBehaved.active()}catch_face(e){this.callback_=e}handleMouseMove(e){}handleMouseClick(e){if(e.catch?.normal==null&&(e.catch.normal=e.catch.face?.normal),!e.catch?.normal||!e.catch?.point)return;let t=e.catch.normal.setLength(-1);this.engine.handelBehaved.disActive(),this.callback_({dir:t,position:e.catch.point})}}const bx=0,RD=1,kD=2,yx=2,hf=1.25,vx=1,li=32,Ht=li/4,_x=65535,FD=Math.pow(2,-24),df=Symbol("SKIP_GENERATION");function OD(n){return n.index?n.index.count:n.attributes.position.count}function pr(n){return OD(n)/3}function UD(n,e=ArrayBuffer){return n>65535?new Uint32Array(new e(4*n)):new Uint16Array(new e(2*n))}function ND(n,e){if(!n.index){const t=n.attributes.position.count,i=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,s=UD(t,i);n.setIndex(new v.BufferAttribute(s,1));for(let r=0;r<t;r++)s[r]=r}}function wx(n,e){const t=pr(n),i=e||n.drawRange,s=i.start/3,r=(i.start+i.count)/3,o=Math.max(0,s),a=Math.min(t,r)-o;return[{offset:Math.floor(o),count:Math.floor(a)}]}function Sx(n,e){if(!n.groups||!n.groups.length)return wx(n,e);const t=[],i=e||n.drawRange,s=i.start/3,r=(i.start+i.count)/3,o=pr(n),a=[];for(const h of n.groups){const{start:d,count:f}=h,u=d/3,g=isFinite(f)?f:o*3-d,p=(d+g)/3;u<r&&p>s&&(a.push({pos:Math.max(s,u),isStart:!0}),a.push({pos:Math.min(r,p),isStart:!1}))}a.sort((h,d)=>h.pos!==d.pos?h.pos-d.pos:h.type==="end"?-1:1);let l=0,c=null;for(const h of a){const d=h.pos;l!==0&&d!==c&&t.push({offset:c,count:d-c}),l+=h.isStart?1:-1,c=d}return t}function uf(n,e,t,i,s){let r=1/0,o=1/0,a=1/0,l=-1/0,c=-1/0,h=-1/0,d=1/0,f=1/0,u=1/0,g=-1/0,p=-1/0,m=-1/0;const A=n.offset||0;for(let x=(e-A)*6,b=(e+t-A)*6;x<b;x+=6){const y=n[x+0],_=n[x+1],S=y-_,C=y+_;S<r&&(r=S),C>l&&(l=C),y<d&&(d=y),y>g&&(g=y);const D=n[x+2],M=n[x+3],I=D-M,L=D+M;I<o&&(o=I),L>c&&(c=L),D<f&&(f=D),D>p&&(p=D);const T=n[x+4],R=n[x+5],E=T-R,F=T+R;E<a&&(a=E),F>h&&(h=F),T<u&&(u=T),T>m&&(m=T)}i[0]=r,i[1]=o,i[2]=a,i[3]=l,i[4]=c,i[5]=h,s[0]=d,s[1]=f,s[2]=u,s[3]=g,s[4]=p,s[5]=m}function Cx(n,e,t=null,i=null,s=null){const r=n.attributes.position,o=n.index?n.index.array:null,a=r.normalized;if(s===null)s=new Float32Array(t*6),s.offset=e;else if(e<0||t+e>s.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"],f=s.offset;for(let u=e,g=e+t;u<g;u++){const m=(i?i[u]:u)*3,A=(u-f)*6;let x=m+0,b=m+1,y=m+2;o&&(x=o[x],b=o[b],y=o[y]),a||(x=x*h+c,b=b*h+c,y=y*h+c);for(let _=0;_<3;_++){let S,C,D;a?(S=r[d[_]](x),C=r[d[_]](b),D=r[d[_]](y)):(S=l[x+_],C=l[b+_],D=l[y+_]);let M=S;C<M&&(M=C),D<M&&(M=D);let I=S;C>I&&(I=C),D>I&&(I=D);const L=(I-M)/2,T=_*2;s[A+T+0]=M+L,s[A+T+1]=L+(Math.abs(M)+L)*FD}}return s}function It(n,e,t){return t.min.x=e[n],t.min.y=e[n+1],t.min.z=e[n+2],t.max.x=e[n+3],t.max.y=e[n+4],t.max.z=e[n+5],t}function Mx(n){let e=-1,t=-1/0;for(let i=0;i<3;i++){const s=n[i+3]-n[i];s>t&&(t=s,e=i)}return e}function Ex(n,e){e.set(n)}function Ix(n,e,t){let i,s;for(let r=0;r<3;r++){const o=r+3;i=n[r],s=e[r],t[r]=i<s?i:s,i=n[o],s=e[o],t[o]=i>s?i:s}}function Bc(n,e,t){for(let i=0;i<3;i++){const s=e[n+2*i],r=e[n+2*i+1],o=s-r,a=s+r;o<t[i]&&(t[i]=o),a>t[i+3]&&(t[i+3]=a)}}function _a(n){const e=n[3]-n[0],t=n[4]-n[1],i=n[5]-n[2];return 2*(e*t+t*i+i*e)}const Zn=32,zD=(n,e)=>n.candidate-e.candidate,Es=new Array(Zn).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),Pc=new Float32Array(6);function GD(n,e,t,i,s,r){let o=-1,a=0;if(r===bx)o=Mx(e),o!==-1&&(a=(e[o]+e[o+3])/2);else if(r===RD)o=Mx(n),o!==-1&&(a=VD(t,i,s,o));else if(r===kD){const l=_a(n);let c=hf*s;const h=t.offset||0,d=(i-h)*6,f=(i+s-h)*6;for(let u=0;u<3;u++){const g=e[u],A=(e[u+3]-g)/Zn;if(s<Zn/4){const x=[...Es];x.length=s;let b=0;for(let _=d;_<f;_+=6,b++){const S=x[b];S.candidate=t[_+2*u],S.count=0;const{bounds:C,leftCacheBounds:D,rightCacheBounds:M}=S;for(let I=0;I<3;I++)M[I]=1/0,M[I+3]=-1/0,D[I]=1/0,D[I+3]=-1/0,C[I]=1/0,C[I+3]=-1/0;Bc(_,t,C)}x.sort(zD);let y=s;for(let _=0;_<y;_++){const S=x[_];for(;_+1<y&&x[_+1].candidate===S.candidate;)x.splice(_+1,1),y--}for(let _=d;_<f;_+=6){const S=t[_+2*u];for(let C=0;C<y;C++){const D=x[C];S>=D.candidate?Bc(_,t,D.rightCacheBounds):(Bc(_,t,D.leftCacheBounds),D.count++)}}for(let _=0;_<y;_++){const S=x[_],C=S.count,D=s-S.count,M=S.leftCacheBounds,I=S.rightCacheBounds;let L=0;C!==0&&(L=_a(M)/l);let T=0;D!==0&&(T=_a(I)/l);const R=vx+hf*(L*C+T*D);R<c&&(o=u,c=R,a=S.candidate)}}else{for(let y=0;y<Zn;y++){const _=Es[y];_.count=0,_.candidate=g+A+y*A;const S=_.bounds;for(let C=0;C<3;C++)S[C]=1/0,S[C+3]=-1/0}for(let y=d;y<f;y+=6){let C=~~((t[y+2*u]-g)/A);C>=Zn&&(C=Zn-1);const D=Es[C];D.count++,Bc(y,t,D.bounds)}const x=Es[Zn-1];Ex(x.bounds,x.rightCacheBounds);for(let y=Zn-2;y>=0;y--){const _=Es[y],S=Es[y+1];Ix(_.bounds,S.rightCacheBounds,_.rightCacheBounds)}let b=0;for(let y=0;y<Zn-1;y++){const _=Es[y],S=_.count,C=_.bounds,M=Es[y+1].rightCacheBounds;S!==0&&(b===0?Ex(C,Pc):Ix(C,Pc,Pc)),b+=S;let I=0,L=0;b!==0&&(I=_a(Pc)/l);const T=s-b;T!==0&&(L=_a(M)/l);const R=vx+hf*(I*b+L*T);R<c&&(o=u,c=R,a=_.candidate)}}}}else console.warn(`MeshBVH: Invalid build strategy value ${r} used.`);return{axis:o,pos:a}}function VD(n,e,t,i){let s=0;const r=n.offset;for(let o=e,a=e+t;o<a;o++)s+=n[(o-r)*6+i*2];return s/t}class ff{constructor(){this.boundingData=new Float32Array(6)}}function QD(n,e,t,i,s,r){let o=i,a=i+s-1;const l=r.pos,c=r.axis*2,h=t.offset||0;for(;;){for(;o<=a&&t[(o-h)*6+c]<l;)o++;for(;o<=a&&t[(a-h)*6+c]>=l;)a--;if(o<a){for(let d=0;d<3;d++){let f=e[o*3+d];e[o*3+d]=e[a*3+d],e[a*3+d]=f}for(let d=0;d<6;d++){const f=o-h,u=a-h,g=t[f*6+d];t[f*6+d]=t[u*6+d],t[u*6+d]=g}o++,a--}else return o}}function jD(n,e,t,i,s,r){let o=i,a=i+s-1;const l=r.pos,c=r.axis*2,h=t.offset||0;for(;;){for(;o<=a&&t[(o-h)*6+c]<l;)o++;for(;o<=a&&t[(a-h)*6+c]>=l;)a--;if(o<a){let d=n[o];n[o]=n[a],n[a]=d;for(let f=0;f<6;f++){const u=o-h,g=a-h,p=t[u*6+f];t[u*6+f]=t[g*6+f],t[g*6+f]=p}o++,a--}else return o}}let Tx,Lc,pf,Dx;const WD=Math.pow(2,32);function gf(n){return"count"in n?1:1+gf(n.left)+gf(n.right)}function HD(n,e,t){return Tx=new Float32Array(t),Lc=new Uint32Array(t),pf=new Uint16Array(t),Dx=new Uint8Array(t),mf(n,e)}function mf(n,e){const t=n/4,i=n/2,s="count"in e,r=e.boundingData;for(let o=0;o<6;o++)Tx[t+o]=r[o];if(s)return e.buffer?(Dx.set(new Uint8Array(e.buffer),n),n+e.buffer.byteLength):(Lc[t+6]=e.offset,pf[i+14]=e.count,pf[i+15]=_x,n+li);{const{left:o,right:a,splitAxis:l}=e,c=n+li;let h=mf(c,o);const d=n/li,u=h/li-d;if(u>WD)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return Lc[t+6]=u,Lc[t+7]=l,mf(h,a)}}function XD(n,e,t){const s=(n.index?n.index.count:n.attributes.position.count)/3>2**16,r=t.reduce((h,d)=>h+d.count,0),o=s?4:2,a=e?new SharedArrayBuffer(r*o):new ArrayBuffer(r*o),l=s?new Uint32Array(a):new Uint16Array(a);let c=0;for(let h=0;h<t.length;h++){const{offset:d,count:f}=t[h];for(let u=0;u<f;u++)l[c+u]=d+u;c+=f}return l}function qD(n,e,t,i,s){const{maxDepth:r,verbose:o,maxLeafTris:a,strategy:l,onProgress:c,indirect:h}=s,d=n._indirectBuffer,f=n.geometry,u=f.index?f.index.array:null,g=h?jD:QD,p=pr(f),m=new Float32Array(6);let A=!1;const x=new ff;return uf(e,t,i,x.boundingData,m),y(x,t,i,m),x;function b(_){c&&c(_/p)}function y(_,S,C,D=null,M=0){if(!A&&M>=r&&(A=!0,o&&(console.warn(`MeshBVH: Max depth of ${r} reached when generating BVH. Consider increasing maxDepth.`),console.warn(f))),C<=a||M>=r)return b(S+C),_.offset=S,_.count=C,_;const I=GD(_.boundingData,D,e,S,C,l);if(I.axis===-1)return b(S+C),_.offset=S,_.count=C,_;const L=g(d,u,e,S,C,I);if(L===S||L===S+C)b(S+C),_.offset=S,_.count=C;else{_.splitAxis=I.axis;const T=new ff,R=S,E=L-S;_.left=T,uf(e,R,E,T.boundingData,m),y(T,R,E,m,M+1);const F=new ff,N=L,H=C-E;_.right=F,uf(e,N,H,F.boundingData,m),y(F,N,H,m,M+1)}return _}}function YD(n,e){const t=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,i=n.geometry;let s,r;if(e.indirect){const o=Sx(i,e.range),a=XD(i,e.useSharedArrayBuffer,o);n._indirectBuffer=a,s=Cx(i,0,a.length,a),r=[{offset:0,count:a.length}]}else{ND(i,e);const o=wx(i,e.range)[0];s=Cx(i,o.offset,o.count),r=Sx(i,e.range)}n._roots=r.map(o=>{const a=qD(n,s,o.offset,o.count,e),l=gf(a),c=new t(li*l);return HD(0,a,c),c})}class es{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(e,t){let i=1/0,s=-1/0;for(let r=0,o=e.length;r<o;r++){const l=e[r][t];i=l<i?l:i,s=l>s?l:s}this.min=i,this.max=s}setFromPoints(e,t){let i=1/0,s=-1/0;for(let r=0,o=t.length;r<o;r++){const a=t[r],l=e.dot(a);i=l<i?l:i,s=l>s?l:s}this.min=i,this.max=s}isSeparated(e){return this.min>e.max||e.min>this.max}}es.prototype.setFromBox=(function(){const n=new v.Vector3;return function(t,i){const s=i.min,r=i.max;let o=1/0,a=-1/0;for(let l=0;l<=1;l++)for(let c=0;c<=1;c++)for(let h=0;h<=1;h++){n.x=s.x*l+r.x*(1-l),n.y=s.y*c+r.y*(1-c),n.z=s.z*h+r.z*(1-h);const d=t.dot(n);o=Math.min(d,o),a=Math.max(d,a)}this.min=o,this.max=a}})();const KD=(function(){const n=new v.Vector3,e=new v.Vector3,t=new v.Vector3;return function(s,r,o){const a=s.start,l=n,c=r.start,h=e;t.subVectors(a,c),n.subVectors(s.end,s.start),e.subVectors(r.end,r.start);const d=t.dot(h),f=h.dot(l),u=h.dot(h),g=t.dot(l),m=l.dot(l)*u-f*f;let A,x;m!==0?A=(d*f-g*u)/m:A=0,x=(d+A*f)/u,o.x=A,o.y=x}})(),Af=(function(){const n=new v.Vector2,e=new v.Vector3,t=new v.Vector3;return function(s,r,o,a){KD(s,r,n);let l=n.x,c=n.y;if(l>=0&&l<=1&&c>=0&&c<=1){s.at(l,o),r.at(c,a);return}else if(l>=0&&l<=1){c<0?r.at(0,a):r.at(1,a),s.closestPointToPoint(a,!0,o);return}else if(c>=0&&c<=1){l<0?s.at(0,o):s.at(1,o),r.closestPointToPoint(o,!0,a);return}else{let h;l<0?h=s.start:h=s.end;let d;c<0?d=r.start:d=r.end;const f=e,u=t;if(s.closestPointToPoint(d,!0,e),r.closestPointToPoint(h,!0,t),f.distanceToSquared(d)<=u.distanceToSquared(h)){o.copy(f),a.copy(d);return}else{o.copy(h),a.copy(u);return}}}})(),$D=(function(){const n=new v.Vector3,e=new v.Vector3,t=new v.Plane,i=new v.Line3;return function(r,o){const{radius:a,center:l}=r,{a:c,b:h,c:d}=o;if(i.start=c,i.end=h,i.closestPointToPoint(l,!0,n).distanceTo(l)<=a||(i.start=c,i.end=d,i.closestPointToPoint(l,!0,n).distanceTo(l)<=a)||(i.start=h,i.end=d,i.closestPointToPoint(l,!0,n).distanceTo(l)<=a))return!0;const p=o.getPlane(t);if(Math.abs(p.distanceToPoint(l))<=a){const A=p.projectPoint(l,e);if(o.containsPoint(A))return!0}return!1}})(),JD=["x","y","z"],ts=1e-15,Bx=ts*ts;function Vi(n){return Math.abs(n)<ts}class Qi extends v.Triangle{constructor(...e){super(...e),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new v.Vector3),this.satBounds=new Array(4).fill().map(()=>new es),this.points=[this.a,this.b,this.c],this.plane=new v.Plane,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new v.Line3,this.needsUpdate=!0}intersectsSphere(e){return $D(e,this)}update(){const e=this.a,t=this.b,i=this.c,s=this.points,r=this.satAxes,o=this.satBounds,a=r[0],l=o[0];this.getNormal(a),l.setFromPoints(a,s);const c=r[1],h=o[1];c.subVectors(e,t),h.setFromPoints(c,s);const d=r[2],f=o[2];d.subVectors(t,i),f.setFromPoints(d,s);const u=r[3],g=o[3];u.subVectors(i,e),g.setFromPoints(u,s);const p=c.length(),m=d.length(),A=u.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,p<ts?m<ts||A<ts?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(i)):m<ts?A<ts?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(e)):A<ts&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(i),this.degenerateSegment.end.copy(t)),this.plane.setFromNormalAndCoplanarPoint(a,e),this.needsUpdate=!1}}Qi.prototype.closestPointToSegment=(function(){const n=new v.Vector3,e=new v.Vector3,t=new v.Line3;return function(s,r=null,o=null){const{start:a,end:l}=s,c=this.points;let h,d=1/0;for(let f=0;f<3;f++){const u=(f+1)%3;t.start.copy(c[f]),t.end.copy(c[u]),Af(t,s,n,e),h=n.distanceToSquared(e),h<d&&(d=h,r&&r.copy(n),o&&o.copy(e))}return this.closestPointToPoint(a,n),h=a.distanceToSquared(n),h<d&&(d=h,r&&r.copy(n),o&&o.copy(a)),this.closestPointToPoint(l,n),h=l.distanceToSquared(n),h<d&&(d=h,r&&r.copy(n),o&&o.copy(l)),Math.sqrt(d)}})(),Qi.prototype.intersectsTriangle=(function(){const n=new Qi,e=new es,t=new es,i=new v.Vector3,s=new v.Vector3,r=new v.Vector3,o=new v.Vector3,a=new v.Line3,l=new v.Line3,c=new v.Vector3,h=new v.Vector2,d=new v.Vector2;function f(b,y,_,S){const C=i;!b.isDegenerateIntoPoint&&!b.isDegenerateIntoSegment?C.copy(b.plane.normal):C.copy(y.plane.normal);const D=b.satBounds,M=b.satAxes;for(let T=1;T<4;T++){const R=D[T],E=M[T];if(e.setFromPoints(E,y.points),R.isSeparated(e)||(o.copy(C).cross(E),e.setFromPoints(o,b.points),t.setFromPoints(o,y.points),e.isSeparated(t)))return!1}const I=y.satBounds,L=y.satAxes;for(let T=1;T<4;T++){const R=I[T],E=L[T];if(e.setFromPoints(E,b.points),R.isSeparated(e)||(o.crossVectors(C,E),e.setFromPoints(o,b.points),t.setFromPoints(o,y.points),e.isSeparated(t)))return!1}return _&&(S||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),_.start.set(0,0,0),_.end.set(0,0,0)),!0}function u(b,y,_,S,C,D,M,I,L,T,R){let E=M/(M-I);T.x=S+(C-S)*E,R.start.subVectors(y,b).multiplyScalar(E).add(b),E=M/(M-L),T.y=S+(D-S)*E,R.end.subVectors(_,b).multiplyScalar(E).add(b)}function g(b,y,_,S,C,D,M,I,L,T,R){if(C>0)u(b.c,b.a,b.b,S,y,_,L,M,I,T,R);else if(D>0)u(b.b,b.a,b.c,_,y,S,I,M,L,T,R);else if(I*L>0||M!=0)u(b.a,b.b,b.c,y,_,S,M,I,L,T,R);else if(I!=0)u(b.b,b.a,b.c,_,y,S,I,M,L,T,R);else if(L!=0)u(b.c,b.a,b.b,S,y,_,L,M,I,T,R);else return!0;return!1}function p(b,y,_,S){const C=y.degenerateSegment,D=b.plane.distanceToPoint(C.start),M=b.plane.distanceToPoint(C.end);return Vi(D)?Vi(M)?f(b,y,_,S):(_&&(_.start.copy(C.start),_.end.copy(C.start)),b.containsPoint(C.start)):Vi(M)?(_&&(_.start.copy(C.end),_.end.copy(C.end)),b.containsPoint(C.end)):b.plane.intersectLine(C,i)!=null?(_&&(_.start.copy(i),_.end.copy(i)),b.containsPoint(i)):!1}function m(b,y,_){const S=y.a;return Vi(b.plane.distanceToPoint(S))&&b.containsPoint(S)?(_&&(_.start.copy(S),_.end.copy(S)),!0):!1}function A(b,y,_){const S=b.degenerateSegment,C=y.a;return S.closestPointToPoint(C,!0,i),C.distanceToSquared(i)<Bx?(_&&(_.start.copy(C),_.end.copy(C)),!0):!1}function x(b,y,_,S){if(b.isDegenerateIntoSegment)if(y.isDegenerateIntoSegment){const C=b.degenerateSegment,D=y.degenerateSegment,M=s,I=r;C.delta(M),D.delta(I);const L=i.subVectors(D.start,C.start),T=M.x*I.y-M.y*I.x;if(Vi(T))return!1;const R=(L.x*I.y-L.y*I.x)/T,E=-(M.x*L.y-M.y*L.x)/T;if(R<0||R>1||E<0||E>1)return!1;const F=C.start.z+M.z*R,N=D.start.z+I.z*E;return Vi(F-N)?(_&&(_.start.copy(C.start).addScaledVector(M,R),_.end.copy(C.start).addScaledVector(M,R)),!0):!1}else return y.isDegenerateIntoPoint?A(b,y,_):p(y,b,_,S);else{if(b.isDegenerateIntoPoint)return y.isDegenerateIntoPoint?y.a.distanceToSquared(b.a)<Bx?(_&&(_.start.copy(b.a),_.end.copy(b.a)),!0):!1:y.isDegenerateIntoSegment?A(y,b,_):m(y,b,_);if(y.isDegenerateIntoPoint)return m(b,y,_);if(y.isDegenerateIntoSegment)return p(b,y,_,S)}}return function(y,_=null,S=!1){this.needsUpdate&&this.update(),y.isExtendedTriangle?y.needsUpdate&&y.update():(n.copy(y),n.update(),y=n);const C=x(this,y,_,S);if(C!==void 0)return C;const D=this.plane,M=y.plane;let I=M.distanceToPoint(this.a),L=M.distanceToPoint(this.b),T=M.distanceToPoint(this.c);Vi(I)&&(I=0),Vi(L)&&(L=0),Vi(T)&&(T=0);const R=I*L,E=I*T;if(R>0&&E>0)return!1;let F=D.distanceToPoint(y.a),N=D.distanceToPoint(y.b),H=D.distanceToPoint(y.c);Vi(F)&&(F=0),Vi(N)&&(N=0),Vi(H)&&(H=0);const V=F*N,U=F*H;if(V>0&&U>0)return!1;s.copy(D.normal),r.copy(M.normal);const q=s.cross(r);let G=0,j=Math.abs(q.x);const oe=Math.abs(q.y);oe>j&&(j=oe,G=1),Math.abs(q.z)>j&&(G=2);const ue=JD[G],se=this.a[ue],he=this.b[ue],Ae=this.c[ue],_e=y.a[ue],Me=y.b[ue],Oe=y.c[ue];if(g(this,se,he,Ae,R,E,I,L,T,h,a))return f(this,y,_,S);if(g(y,_e,Me,Oe,V,U,F,N,H,d,l))return f(this,y,_,S);if(h.y<h.x){const it=h.y;h.y=h.x,h.x=it,c.copy(a.start),a.start.copy(a.end),a.end.copy(c)}if(d.y<d.x){const it=d.y;d.y=d.x,d.x=it,c.copy(l.start),l.start.copy(l.end),l.end.copy(c)}return h.y<d.x||d.y<h.x?!1:(_&&(d.x>h.x?_.start.copy(l.start):_.start.copy(a.start),d.y<h.y?_.end.copy(l.end):_.end.copy(a.end)),!0)}})(),Qi.prototype.distanceToPoint=(function(){const n=new v.Vector3;return function(t){return this.closestPointToPoint(t,n),t.distanceTo(n)}})(),Qi.prototype.distanceToTriangle=(function(){const n=new v.Vector3,e=new v.Vector3,t=["a","b","c"],i=new v.Line3,s=new v.Line3;return function(o,a=null,l=null){const c=a||l?i:null;if(this.intersectsTriangle(o,c))return(a||l)&&(a&&c.getCenter(a),l&&c.getCenter(l)),0;let h=1/0;for(let d=0;d<3;d++){let f;const u=t[d],g=o[u];this.closestPointToPoint(g,n),f=g.distanceToSquared(n),f<h&&(h=f,a&&a.copy(n),l&&l.copy(g));const p=this[u];o.closestPointToPoint(p,n),f=p.distanceToSquared(n),f<h&&(h=f,a&&a.copy(p),l&&l.copy(n))}for(let d=0;d<3;d++){const f=t[d],u=t[(d+1)%3];i.set(this[f],this[u]);for(let g=0;g<3;g++){const p=t[g],m=t[(g+1)%3];s.set(o[p],o[m]),Af(i,s,n,e);const A=n.distanceToSquared(e);A<h&&(h=A,a&&a.copy(n),l&&l.copy(e))}}return Math.sqrt(h)}})();class ci{constructor(e,t,i){this.isOrientedBox=!0,this.min=new v.Vector3,this.max=new v.Vector3,this.matrix=new v.Matrix4,this.invMatrix=new v.Matrix4,this.points=new Array(8).fill().map(()=>new v.Vector3),this.satAxes=new Array(3).fill().map(()=>new v.Vector3),this.satBounds=new Array(3).fill().map(()=>new es),this.alignedSatBounds=new Array(3).fill().map(()=>new es),this.needsUpdate=!1,e&&this.min.copy(e),t&&this.max.copy(t),i&&this.matrix.copy(i)}set(e,t,i){this.min.copy(e),this.max.copy(t),this.matrix.copy(i),this.needsUpdate=!0}copy(e){this.min.copy(e.min),this.max.copy(e.max),this.matrix.copy(e.matrix),this.needsUpdate=!0}}ci.prototype.update=(function(){return function(){const e=this.matrix,t=this.min,i=this.max,s=this.points;for(let c=0;c<=1;c++)for(let h=0;h<=1;h++)for(let d=0;d<=1;d++){const f=1*c|2*h|4*d,u=s[f];u.x=c?i.x:t.x,u.y=h?i.y:t.y,u.z=d?i.z:t.z,u.applyMatrix4(e)}const r=this.satBounds,o=this.satAxes,a=s[0];for(let c=0;c<3;c++){const h=o[c],d=r[c],f=1<<c,u=s[f];h.subVectors(a,u),d.setFromPoints(h,s)}const l=this.alignedSatBounds;l[0].setFromPointsField(s,"x"),l[1].setFromPointsField(s,"y"),l[2].setFromPointsField(s,"z"),this.invMatrix.copy(this.matrix).invert(),this.needsUpdate=!1}})(),ci.prototype.intersectsBox=(function(){const n=new es;return function(t){this.needsUpdate&&this.update();const i=t.min,s=t.max,r=this.satBounds,o=this.satAxes,a=this.alignedSatBounds;if(n.min=i.x,n.max=s.x,a[0].isSeparated(n)||(n.min=i.y,n.max=s.y,a[1].isSeparated(n))||(n.min=i.z,n.max=s.z,a[2].isSeparated(n)))return!1;for(let l=0;l<3;l++){const c=o[l],h=r[l];if(n.setFromBox(c,t),h.isSeparated(n))return!1}return!0}})(),ci.prototype.intersectsTriangle=(function(){const n=new Qi,e=new Array(3),t=new es,i=new es,s=new v.Vector3;return function(o){this.needsUpdate&&this.update(),o.isExtendedTriangle?o.needsUpdate&&o.update():(n.copy(o),n.update(),o=n);const a=this.satBounds,l=this.satAxes;e[0]=o.a,e[1]=o.b,e[2]=o.c;for(let f=0;f<3;f++){const u=a[f],g=l[f];if(t.setFromPoints(g,e),u.isSeparated(t))return!1}const c=o.satBounds,h=o.satAxes,d=this.points;for(let f=0;f<3;f++){const u=c[f],g=h[f];if(t.setFromPoints(g,d),u.isSeparated(t))return!1}for(let f=0;f<3;f++){const u=l[f];for(let g=0;g<4;g++){const p=h[g];if(s.crossVectors(u,p),t.setFromPoints(s,e),i.setFromPoints(s,d),t.isSeparated(i))return!1}}return!0}})(),ci.prototype.closestPointToPoint=(function(){return function(e,t){return this.needsUpdate&&this.update(),t.copy(e).applyMatrix4(this.invMatrix).clamp(this.min,this.max).applyMatrix4(this.matrix),t}})(),ci.prototype.distanceToPoint=(function(){const n=new v.Vector3;return function(t){return this.closestPointToPoint(t,n),t.distanceTo(n)}})(),ci.prototype.distanceToBox=(function(){const n=["x","y","z"],e=new Array(12).fill().map(()=>new v.Line3),t=new Array(12).fill().map(()=>new v.Line3),i=new v.Vector3,s=new v.Vector3;return function(o,a=0,l=null,c=null){if(this.needsUpdate&&this.update(),this.intersectsBox(o))return(l||c)&&(o.getCenter(s),this.closestPointToPoint(s,i),o.closestPointToPoint(i,s),l&&l.copy(i),c&&c.copy(s)),0;const h=a*a,d=o.min,f=o.max,u=this.points;let g=1/0;for(let m=0;m<8;m++){const A=u[m];s.copy(A).clamp(d,f);const x=A.distanceToSquared(s);if(x<g&&(g=x,l&&l.copy(A),c&&c.copy(s),x<h))return Math.sqrt(x)}let p=0;for(let m=0;m<3;m++)for(let A=0;A<=1;A++)for(let x=0;x<=1;x++){const b=(m+1)%3,y=(m+2)%3,_=A<<b|x<<y,S=1<<m|A<<b|x<<y,C=u[_],D=u[S];e[p].set(C,D);const I=n[m],L=n[b],T=n[y],R=t[p],E=R.start,F=R.end;E[I]=d[I],E[L]=A?d[L]:f[L],E[T]=x?d[T]:f[L],F[I]=f[I],F[L]=A?d[L]:f[L],F[T]=x?d[T]:f[L],p++}for(let m=0;m<=1;m++)for(let A=0;A<=1;A++)for(let x=0;x<=1;x++){s.x=m?f.x:d.x,s.y=A?f.y:d.y,s.z=x?f.z:d.z,this.closestPointToPoint(s,i);const b=s.distanceToSquared(i);if(b<g&&(g=b,l&&l.copy(i),c&&c.copy(s),b<h))return Math.sqrt(b)}for(let m=0;m<12;m++){const A=e[m];for(let x=0;x<12;x++){const b=t[x];Af(A,b,i,s);const y=i.distanceToSquared(s);if(y<g&&(g=y,l&&l.copy(i),c&&c.copy(s),y<h))return Math.sqrt(y)}}return Math.sqrt(g)}})();class xf{constructor(e){this._getNewPrimitive=e,this._primitives=[]}getPrimitive(){const e=this._primitives;return e.length===0?this._getNewPrimitive():e.pop()}releasePrimitive(e){this._primitives.push(e)}}class ZD extends xf{constructor(){super(()=>new Qi)}}const ji=new ZD;function Xt(n,e){return e[n+15]===_x}function Ti(n,e){return e[n+6]}function Wi(n,e){return e[n+14]}function Yt(n){return n+Ht}function Kt(n,e){const t=e[n+6];return n+t*Ht}function bf(n,e){return e[n+7]}function VF(n){return n}class eB{constructor(){this.float32Array=null,this.uint16Array=null,this.uint32Array=null;const e=[];let t=null;this.setBuffer=i=>{t&&e.push(t),t=i,this.float32Array=new Float32Array(i),this.uint16Array=new Uint16Array(i),this.uint32Array=new Uint32Array(i)},this.clearBuffer=()=>{t=null,this.float32Array=null,this.uint16Array=null,this.uint32Array=null,e.length!==0&&this.setBuffer(e.pop())}}}const _t=new eB;let Is,Ao;const xo=[],Rc=new xf(()=>new v.Box3);function tB(n,e,t,i,s,r){Is=Rc.getPrimitive(),Ao=Rc.getPrimitive(),xo.push(Is,Ao),_t.setBuffer(n._roots[e]);const o=yf(0,n.geometry,t,i,s,r);_t.clearBuffer(),Rc.releasePrimitive(Is),Rc.releasePrimitive(Ao),xo.pop(),xo.pop();const a=xo.length;return a>0&&(Ao=xo[a-1],Is=xo[a-2]),o}function yf(n,e,t,i,s=null,r=0,o=0){const{float32Array:a,uint16Array:l,uint32Array:c}=_t;let h=n*2;if(Xt(h,l)){const f=Ti(n,c),u=Wi(h,l);return It(n,a,Is),i(f,u,!1,o,r+n/Ht,Is)}else{let I=function(T){const{uint16Array:R,uint32Array:E}=_t;let F=T*2;for(;!Xt(F,R);)T=Yt(T),F=T*2;return Ti(T,E)},L=function(T){const{uint16Array:R,uint32Array:E}=_t;let F=T*2;for(;!Xt(F,R);)T=Kt(T,E),F=T*2;return Ti(T,E)+Wi(F,R)};const f=Yt(n),u=Kt(n,c);let g=f,p=u,m,A,x,b;if(s&&(x=Is,b=Ao,It(g,a,x),It(p,a,b),m=s(x),A=s(b),A<m)){g=u,p=f;const T=m;m=A,A=T,x=b}x||(x=Is,It(g,a,x));const y=Xt(g*2,l),_=t(x,y,m,o+1,r+g/Ht);let S;if(_===yx){const T=I(g),E=L(g)-T;S=i(T,E,!0,o+1,r+g/Ht,x)}else S=_&&yf(g,e,t,i,s,r,o+1);if(S)return!0;b=Ao,It(p,a,b);const C=Xt(p*2,l),D=t(b,C,A,o+1,r+p/Ht);let M;if(D===yx){const T=I(p),E=L(p)-T;M=i(T,E,!0,o+1,r+p/Ht,b)}else M=D&&yf(p,e,t,i,s,r,o+1);return!!M}}const wa=new v.Vector3,vf=new v.Vector3;function iB(n,e,t={},i=0,s=1/0){const r=i*i,o=s*s;let a=1/0,l=null;if(n.shapecast({boundsTraverseOrder:h=>(wa.copy(e).clamp(h.min,h.max),wa.distanceToSquared(e)),intersectsBounds:(h,d,f)=>f<a&&f<o,intersectsTriangle:(h,d)=>{h.closestPointToPoint(e,wa);const f=e.distanceToSquared(wa);return f<a&&(vf.copy(wa),a=f,l=d),f<r}}),a===1/0)return null;const c=Math.sqrt(a);return t.point?t.point.copy(vf):t.point=vf.clone(),t.distance=c,t.faceIndex=l,t}const kc=parseInt(v.REVISION)>=169,nB=parseInt(v.REVISION)<=161,gr=new v.Vector3,mr=new v.Vector3,Ar=new v.Vector3,Fc=new v.Vector2,Oc=new v.Vector2,Uc=new v.Vector2,Px=new v.Vector3,Lx=new v.Vector3,Rx=new v.Vector3,Sa=new v.Vector3;function sB(n,e,t,i,s,r,o,a){let l;if(r===v.BackSide?l=n.intersectTriangle(i,t,e,!0,s):l=n.intersectTriangle(e,t,i,r!==v.DoubleSide,s),l===null)return null;const c=n.origin.distanceTo(s);return c<o||c>a?null:{distance:c,point:s.clone()}}function kx(n,e,t,i,s,r,o,a,l,c,h){gr.fromBufferAttribute(e,r),mr.fromBufferAttribute(e,o),Ar.fromBufferAttribute(e,a);const d=sB(n,gr,mr,Ar,Sa,l,c,h);if(d){if(i){Fc.fromBufferAttribute(i,r),Oc.fromBufferAttribute(i,o),Uc.fromBufferAttribute(i,a),d.uv=new v.Vector2;const u=v.Triangle.getInterpolation(Sa,gr,mr,Ar,Fc,Oc,Uc,d.uv);kc||(d.uv=u)}if(s){Fc.fromBufferAttribute(s,r),Oc.fromBufferAttribute(s,o),Uc.fromBufferAttribute(s,a),d.uv1=new v.Vector2;const u=v.Triangle.getInterpolation(Sa,gr,mr,Ar,Fc,Oc,Uc,d.uv1);kc||(d.uv1=u),nB&&(d.uv2=d.uv1)}if(t){Px.fromBufferAttribute(t,r),Lx.fromBufferAttribute(t,o),Rx.fromBufferAttribute(t,a),d.normal=new v.Vector3;const u=v.Triangle.getInterpolation(Sa,gr,mr,Ar,Px,Lx,Rx,d.normal);d.normal.dot(n.direction)>0&&d.normal.multiplyScalar(-1),kc||(d.normal=u)}const f={a:r,b:o,c:a,normal:new v.Vector3,materialIndex:0};if(v.Triangle.getNormal(gr,mr,Ar,f.normal),d.face=f,d.faceIndex=r,kc){const u=new v.Vector3;v.Triangle.getBarycoord(Sa,gr,mr,Ar,u),d.barycoord=u}}return d}function Fx(n){return n&&n.isMaterial?n.side:n}function Nc(n,e,t,i,s,r,o){const a=i*3;let l=a+0,c=a+1,h=a+2;const{index:d,groups:f}=n;n.index&&(l=d.getX(l),c=d.getX(c),h=d.getX(h));const{position:u,normal:g,uv:p,uv1:m}=n.attributes;if(Array.isArray(e)){const A=i*3;for(let x=0,b=f.length;x<b;x++){const{start:y,count:_,materialIndex:S}=f[x];if(A>=y&&A<y+_){const C=Fx(e[S]),D=kx(t,u,g,p,m,l,c,h,C,r,o);if(D)if(D.faceIndex=i,D.face.materialIndex=S,s)s.push(D);else return D}}}else{const A=Fx(e),x=kx(t,u,g,p,m,l,c,h,A,r,o);if(x)if(x.faceIndex=i,x.face.materialIndex=0,s)s.push(x);else return x}return null}function Nt(n,e,t,i){const s=n.a,r=n.b,o=n.c;let a=e,l=e+1,c=e+2;t&&(a=t.getX(a),l=t.getX(l),c=t.getX(c)),s.x=i.getX(a),s.y=i.getY(a),s.z=i.getZ(a),r.x=i.getX(l),r.y=i.getY(l),r.z=i.getZ(l),o.x=i.getX(c),o.y=i.getY(c),o.z=i.getZ(c)}function rB(n,e,t,i,s,r,o,a){const{geometry:l,_indirectBuffer:c}=n;for(let h=i,d=i+s;h<d;h++)Nc(l,e,t,h,r,o,a)}function oB(n,e,t,i,s,r,o){const{geometry:a,_indirectBuffer:l}=n;let c=1/0,h=null;for(let d=i,f=i+s;d<f;d++){let u;u=Nc(a,e,t,d,null,r,o),u&&u.distance<c&&(h=u,c=u.distance)}return h}function aB(n,e,t,i,s,r,o){const{geometry:a}=t,{index:l}=a,c=a.attributes.position;for(let h=n,d=e+n;h<d;h++){let f;if(f=h,Nt(o,f*3,l,c),o.needsUpdate=!0,i(o,f,s,r))return!0}return!1}function lB(n,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=n.geometry,i=t.index?t.index.array:null,s=t.attributes.position;let r,o,a,l,c=0;const h=n._roots;for(let f=0,u=h.length;f<u;f++)r=h[f],o=new Uint32Array(r),a=new Uint16Array(r),l=new Float32Array(r),d(0,c),c+=r.byteLength;function d(f,u,g=!1){const p=f*2;if(Xt(p,a)){const m=o[f+6],A=a[p+14];let x=1/0,b=1/0,y=1/0,_=-1/0,S=-1/0,C=-1/0;for(let D=3*m,M=3*(m+A);D<M;D++){let I=i[D];const L=s.getX(I),T=s.getY(I),R=s.getZ(I);L<x&&(x=L),L>_&&(_=L),T<b&&(b=T),T>S&&(S=T),R<y&&(y=R),R>C&&(C=R)}return l[f+0]!==x||l[f+1]!==b||l[f+2]!==y||l[f+3]!==_||l[f+4]!==S||l[f+5]!==C?(l[f+0]=x,l[f+1]=b,l[f+2]=y,l[f+3]=_,l[f+4]=S,l[f+5]=C,!0):!1}else{const m=Yt(f),A=Kt(f,o);let x=g,b=!1,y=!1;if(e){if(!x){const I=m/Ht+u/li,L=A/Ht+u/li;b=e.has(I),y=e.has(L),x=!b&&!y}}else b=!0,y=!0;const _=x||b,S=x||y;let C=!1;_&&(C=d(m,u,x));let D=!1;S&&(D=d(A,u,x));const M=C||D;if(M)for(let I=0;I<3;I++){const L=m+I,T=A+I,R=l[L],E=l[L+3],F=l[T],N=l[T+3];l[f+I]=R<F?R:F,l[f+I+3]=E>N?E:N}return M}}}function Ts(n,e,t,i,s){let r,o,a,l,c,h;const d=1/t.direction.x,f=1/t.direction.y,u=1/t.direction.z,g=t.origin.x,p=t.origin.y,m=t.origin.z;let A=e[n],x=e[n+3],b=e[n+1],y=e[n+3+1],_=e[n+2],S=e[n+3+2];return d>=0?(r=(A-g)*d,o=(x-g)*d):(r=(x-g)*d,o=(A-g)*d),f>=0?(a=(b-p)*f,l=(y-p)*f):(a=(y-p)*f,l=(b-p)*f),r>l||a>o||((a>r||isNaN(r))&&(r=a),(l<o||isNaN(o))&&(o=l),u>=0?(c=(_-m)*u,h=(S-m)*u):(c=(S-m)*u,h=(_-m)*u),r>h||c>o)?!1:((c>r||r!==r)&&(r=c),(h<o||o!==o)&&(o=h),r<=s&&o>=i)}function cB(n,e,t,i,s,r,o,a){const{geometry:l,_indirectBuffer:c}=n;for(let h=i,d=i+s;h<d;h++){let f=c?c[h]:h;Nc(l,e,t,f,r,o,a)}}function hB(n,e,t,i,s,r,o){const{geometry:a,_indirectBuffer:l}=n;let c=1/0,h=null;for(let d=i,f=i+s;d<f;d++){let u;u=Nc(a,e,t,l?l[d]:d,null,r,o),u&&u.distance<c&&(h=u,c=u.distance)}return h}function dB(n,e,t,i,s,r,o){const{geometry:a}=t,{index:l}=a,c=a.attributes.position;for(let h=n,d=e+n;h<d;h++){let f;if(f=t.resolveTriangleIndex(h),Nt(o,f*3,l,c),o.needsUpdate=!0,i(o,f,s,r))return!0}return!1}function uB(n,e,t,i,s,r,o){_t.setBuffer(n._roots[e]),_f(0,n,t,i,s,r,o),_t.clearBuffer()}function _f(n,e,t,i,s,r,o){const{float32Array:a,uint16Array:l,uint32Array:c}=_t,h=n*2;if(Xt(h,l)){const f=Ti(n,c),u=Wi(h,l);rB(e,t,i,f,u,s,r,o)}else{const f=Yt(n);Ts(f,a,i,r,o)&&_f(f,e,t,i,s,r,o);const u=Kt(n,c);Ts(u,a,i,r,o)&&_f(u,e,t,i,s,r,o)}}const fB=["x","y","z"];function pB(n,e,t,i,s,r){_t.setBuffer(n._roots[e]);const o=wf(0,n,t,i,s,r);return _t.clearBuffer(),o}function wf(n,e,t,i,s,r){const{float32Array:o,uint16Array:a,uint32Array:l}=_t;let c=n*2;if(Xt(c,a)){const d=Ti(n,l),f=Wi(c,a);return oB(e,t,i,d,f,s,r)}else{const d=bf(n,l),f=fB[d],g=i.direction[f]>=0;let p,m;g?(p=Yt(n),m=Kt(n,l)):(p=Kt(n,l),m=Yt(n));const x=Ts(p,o,i,s,r)?wf(p,e,t,i,s,r):null;if(x){const _=x.point[f];if(g?_<=o[m+d]:_>=o[m+d+3])return x}const y=Ts(m,o,i,s,r)?wf(m,e,t,i,s,r):null;return x&&y?x.distance<=y.distance?x:y:x||y||null}}const zc=new v.Box3,bo=new Qi,yo=new Qi,Ca=new v.Matrix4,Ox=new ci,Gc=new ci;function gB(n,e,t,i){_t.setBuffer(n._roots[e]);const s=Sf(0,n,t,i);return _t.clearBuffer(),s}function Sf(n,e,t,i,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=_t;let l=n*2;if(s===null&&(t.boundingBox||t.computeBoundingBox(),Ox.set(t.boundingBox.min,t.boundingBox.max,i),s=Ox),Xt(l,o)){const h=e.geometry,d=h.index,f=h.attributes.position,u=t.index,g=t.attributes.position,p=Ti(n,a),m=Wi(l,o);if(Ca.copy(i).invert(),t.boundsTree)return It(n,r,Gc),Gc.matrix.copy(Ca),Gc.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:x=>Gc.intersectsBox(x),intersectsTriangle:x=>{x.a.applyMatrix4(i),x.b.applyMatrix4(i),x.c.applyMatrix4(i),x.needsUpdate=!0;for(let b=p*3,y=(m+p)*3;b<y;b+=3)if(Nt(yo,b,d,f),yo.needsUpdate=!0,x.intersectsTriangle(yo))return!0;return!1}});{const A=pr(t);for(let x=p*3,b=(m+p)*3;x<b;x+=3){Nt(bo,x,d,f),bo.a.applyMatrix4(Ca),bo.b.applyMatrix4(Ca),bo.c.applyMatrix4(Ca),bo.needsUpdate=!0;for(let y=0,_=A*3;y<_;y+=3)if(Nt(yo,y,u,g),yo.needsUpdate=!0,bo.intersectsTriangle(yo))return!0}}}else{const h=Yt(n),d=Kt(n,a);return It(h,r,zc),!!(s.intersectsBox(zc)&&Sf(h,e,t,i,s)||(It(d,r,zc),s.intersectsBox(zc)&&Sf(d,e,t,i,s)))}}const Vc=new v.Matrix4,Cf=new ci,Ma=new ci,mB=new v.Vector3,AB=new v.Vector3,xB=new v.Vector3,bB=new v.Vector3;function yB(n,e,t,i={},s={},r=0,o=1/0){e.boundingBox||e.computeBoundingBox(),Cf.set(e.boundingBox.min,e.boundingBox.max,t),Cf.needsUpdate=!0;const a=n.geometry,l=a.attributes.position,c=a.index,h=e.attributes.position,d=e.index,f=ji.getPrimitive(),u=ji.getPrimitive();let g=mB,p=AB,m=null,A=null;s&&(m=xB,A=bB);let x=1/0,b=null,y=null;return Vc.copy(t).invert(),Ma.matrix.copy(Vc),n.shapecast({boundsTraverseOrder:_=>Cf.distanceToBox(_),intersectsBounds:(_,S,C)=>C<x&&C<o?(S&&(Ma.min.copy(_.min),Ma.max.copy(_.max),Ma.needsUpdate=!0),!0):!1,intersectsRange:(_,S)=>{if(e.boundsTree)return e.boundsTree.shapecast({boundsTraverseOrder:D=>Ma.distanceToBox(D),intersectsBounds:(D,M,I)=>I<x&&I<o,intersectsRange:(D,M)=>{for(let I=D,L=D+M;I<L;I++){Nt(u,3*I,d,h),u.a.applyMatrix4(t),u.b.applyMatrix4(t),u.c.applyMatrix4(t),u.needsUpdate=!0;for(let T=_,R=_+S;T<R;T++){Nt(f,3*T,c,l),f.needsUpdate=!0;const E=f.distanceToTriangle(u,g,m);if(E<x&&(p.copy(g),A&&A.copy(m),x=E,b=T,y=I),E<r)return!0}}}});{const C=pr(e);for(let D=0,M=C;D<M;D++){Nt(u,3*D,d,h),u.a.applyMatrix4(t),u.b.applyMatrix4(t),u.c.applyMatrix4(t),u.needsUpdate=!0;for(let I=_,L=_+S;I<L;I++){Nt(f,3*I,c,l),f.needsUpdate=!0;const T=f.distanceToTriangle(u,g,m);if(T<x&&(p.copy(g),A&&A.copy(m),x=T,b=I,y=D),T<r)return!0}}}}}),ji.releasePrimitive(f),ji.releasePrimitive(u),x===1/0?null:(i.point?i.point.copy(p):i.point=p.clone(),i.distance=x,i.faceIndex=b,s&&(s.point?s.point.copy(A):s.point=A.clone(),s.point.applyMatrix4(Vc),p.applyMatrix4(Vc),s.distance=p.sub(s.point).length(),s.faceIndex=y),i)}function vB(n,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=n.geometry,i=t.index?t.index.array:null,s=t.attributes.position;let r,o,a,l,c=0;const h=n._roots;for(let f=0,u=h.length;f<u;f++)r=h[f],o=new Uint32Array(r),a=new Uint16Array(r),l=new Float32Array(r),d(0,c),c+=r.byteLength;function d(f,u,g=!1){const p=f*2;if(Xt(p,a)){const m=o[f+6],A=a[p+14];let x=1/0,b=1/0,y=1/0,_=-1/0,S=-1/0,C=-1/0;for(let D=m,M=m+A;D<M;D++){const I=3*n.resolveTriangleIndex(D);for(let L=0;L<3;L++){let T=I+L;T=i?i[T]:T;const R=s.getX(T),E=s.getY(T),F=s.getZ(T);R<x&&(x=R),R>_&&(_=R),E<b&&(b=E),E>S&&(S=E),F<y&&(y=F),F>C&&(C=F)}}return l[f+0]!==x||l[f+1]!==b||l[f+2]!==y||l[f+3]!==_||l[f+4]!==S||l[f+5]!==C?(l[f+0]=x,l[f+1]=b,l[f+2]=y,l[f+3]=_,l[f+4]=S,l[f+5]=C,!0):!1}else{const m=Yt(f),A=Kt(f,o);let x=g,b=!1,y=!1;if(e){if(!x){const I=m/Ht+u/li,L=A/Ht+u/li;b=e.has(I),y=e.has(L),x=!b&&!y}}else b=!0,y=!0;const _=x||b,S=x||y;let C=!1;_&&(C=d(m,u,x));let D=!1;S&&(D=d(A,u,x));const M=C||D;if(M)for(let I=0;I<3;I++){const L=m+I,T=A+I,R=l[L],E=l[L+3],F=l[T],N=l[T+3];l[f+I]=R<F?R:F,l[f+I+3]=E>N?E:N}return M}}}function _B(n,e,t,i,s,r,o){_t.setBuffer(n._roots[e]),Mf(0,n,t,i,s,r,o),_t.clearBuffer()}function Mf(n,e,t,i,s,r,o){const{float32Array:a,uint16Array:l,uint32Array:c}=_t,h=n*2;if(Xt(h,l)){const f=Ti(n,c),u=Wi(h,l);cB(e,t,i,f,u,s,r,o)}else{const f=Yt(n);Ts(f,a,i,r,o)&&Mf(f,e,t,i,s,r,o);const u=Kt(n,c);Ts(u,a,i,r,o)&&Mf(u,e,t,i,s,r,o)}}const wB=["x","y","z"];function SB(n,e,t,i,s,r){_t.setBuffer(n._roots[e]);const o=Ef(0,n,t,i,s,r);return _t.clearBuffer(),o}function Ef(n,e,t,i,s,r){const{float32Array:o,uint16Array:a,uint32Array:l}=_t;let c=n*2;if(Xt(c,a)){const d=Ti(n,l),f=Wi(c,a);return hB(e,t,i,d,f,s,r)}else{const d=bf(n,l),f=wB[d],g=i.direction[f]>=0;let p,m;g?(p=Yt(n),m=Kt(n,l)):(p=Kt(n,l),m=Yt(n));const x=Ts(p,o,i,s,r)?Ef(p,e,t,i,s,r):null;if(x){const _=x.point[f];if(g?_<=o[m+d]:_>=o[m+d+3])return x}const y=Ts(m,o,i,s,r)?Ef(m,e,t,i,s,r):null;return x&&y?x.distance<=y.distance?x:y:x||y||null}}const Qc=new v.Box3,vo=new Qi,_o=new Qi,Ea=new v.Matrix4,Ux=new ci,jc=new ci;function CB(n,e,t,i){_t.setBuffer(n._roots[e]);const s=If(0,n,t,i);return _t.clearBuffer(),s}function If(n,e,t,i,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=_t;let l=n*2;if(s===null&&(t.boundingBox||t.computeBoundingBox(),Ux.set(t.boundingBox.min,t.boundingBox.max,i),s=Ux),Xt(l,o)){const h=e.geometry,d=h.index,f=h.attributes.position,u=t.index,g=t.attributes.position,p=Ti(n,a),m=Wi(l,o);if(Ea.copy(i).invert(),t.boundsTree)return It(n,r,jc),jc.matrix.copy(Ea),jc.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:x=>jc.intersectsBox(x),intersectsTriangle:x=>{x.a.applyMatrix4(i),x.b.applyMatrix4(i),x.c.applyMatrix4(i),x.needsUpdate=!0;for(let b=p,y=m+p;b<y;b++)if(Nt(_o,3*e.resolveTriangleIndex(b),d,f),_o.needsUpdate=!0,x.intersectsTriangle(_o))return!0;return!1}});{const A=pr(t);for(let x=p,b=m+p;x<b;x++){const y=e.resolveTriangleIndex(x);Nt(vo,3*y,d,f),vo.a.applyMatrix4(Ea),vo.b.applyMatrix4(Ea),vo.c.applyMatrix4(Ea),vo.needsUpdate=!0;for(let _=0,S=A*3;_<S;_+=3)if(Nt(_o,_,u,g),_o.needsUpdate=!0,vo.intersectsTriangle(_o))return!0}}}else{const h=Yt(n),d=Kt(n,a);return It(h,r,Qc),!!(s.intersectsBox(Qc)&&If(h,e,t,i,s)||(It(d,r,Qc),s.intersectsBox(Qc)&&If(d,e,t,i,s)))}}const Wc=new v.Matrix4,Tf=new ci,Ia=new ci,MB=new v.Vector3,EB=new v.Vector3,IB=new v.Vector3,TB=new v.Vector3;function DB(n,e,t,i={},s={},r=0,o=1/0){e.boundingBox||e.computeBoundingBox(),Tf.set(e.boundingBox.min,e.boundingBox.max,t),Tf.needsUpdate=!0;const a=n.geometry,l=a.attributes.position,c=a.index,h=e.attributes.position,d=e.index,f=ji.getPrimitive(),u=ji.getPrimitive();let g=MB,p=EB,m=null,A=null;s&&(m=IB,A=TB);let x=1/0,b=null,y=null;return Wc.copy(t).invert(),Ia.matrix.copy(Wc),n.shapecast({boundsTraverseOrder:_=>Tf.distanceToBox(_),intersectsBounds:(_,S,C)=>C<x&&C<o?(S&&(Ia.min.copy(_.min),Ia.max.copy(_.max),Ia.needsUpdate=!0),!0):!1,intersectsRange:(_,S)=>{if(e.boundsTree){const C=e.boundsTree;return C.shapecast({boundsTraverseOrder:D=>Ia.distanceToBox(D),intersectsBounds:(D,M,I)=>I<x&&I<o,intersectsRange:(D,M)=>{for(let I=D,L=D+M;I<L;I++){const T=C.resolveTriangleIndex(I);Nt(u,3*T,d,h),u.a.applyMatrix4(t),u.b.applyMatrix4(t),u.c.applyMatrix4(t),u.needsUpdate=!0;for(let R=_,E=_+S;R<E;R++){const F=n.resolveTriangleIndex(R);Nt(f,3*F,c,l),f.needsUpdate=!0;const N=f.distanceToTriangle(u,g,m);if(N<x&&(p.copy(g),A&&A.copy(m),x=N,b=R,y=I),N<r)return!0}}}})}else{const C=pr(e);for(let D=0,M=C;D<M;D++){Nt(u,3*D,d,h),u.a.applyMatrix4(t),u.b.applyMatrix4(t),u.c.applyMatrix4(t),u.needsUpdate=!0;for(let I=_,L=_+S;I<L;I++){const T=n.resolveTriangleIndex(I);Nt(f,3*T,c,l),f.needsUpdate=!0;const R=f.distanceToTriangle(u,g,m);if(R<x&&(p.copy(g),A&&A.copy(m),x=R,b=I,y=D),R<r)return!0}}}}}),ji.releasePrimitive(f),ji.releasePrimitive(u),x===1/0?null:(i.point?i.point.copy(p):i.point=p.clone(),i.distance=x,i.faceIndex=b,s&&(s.point?s.point.copy(A):s.point=A.clone(),s.point.applyMatrix4(Wc),p.applyMatrix4(Wc),s.distance=p.sub(s.point).length(),s.faceIndex=y),i)}function BB(){return typeof SharedArrayBuffer<"u"}const Ta=new _t.constructor,Hc=new _t.constructor,Ds=new xf(()=>new v.Box3),wo=new v.Box3,So=new v.Box3,Df=new v.Box3,Bf=new v.Box3;let Pf=!1;function PB(n,e,t,i){if(Pf)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");Pf=!0;const s=n._roots,r=e._roots;let o,a=0,l=0;const c=new v.Matrix4().copy(t).invert();for(let h=0,d=s.length;h<d;h++){Ta.setBuffer(s[h]),l=0;const f=Ds.getPrimitive();It(0,Ta.float32Array,f),f.applyMatrix4(c);for(let u=0,g=r.length;u<g&&(Hc.setBuffer(r[u]),o=rn(0,0,t,c,i,a,l,0,0,f),Hc.clearBuffer(),l+=r[u].byteLength/li,!o);u++);if(Ds.releasePrimitive(f),Ta.clearBuffer(),a+=s[h].byteLength/li,o)break}return Pf=!1,o}function rn(n,e,t,i,s,r=0,o=0,a=0,l=0,c=null,h=!1){let d,f;h?(d=Hc,f=Ta):(d=Ta,f=Hc);const u=d.float32Array,g=d.uint32Array,p=d.uint16Array,m=f.float32Array,A=f.uint32Array,x=f.uint16Array,b=n*2,y=e*2,_=Xt(b,p),S=Xt(y,x);let C=!1;if(S&&_)h?C=s(Ti(e,A),Wi(e*2,x),Ti(n,g),Wi(n*2,p),l,o+e/Ht,a,r+n/Ht):C=s(Ti(n,g),Wi(n*2,p),Ti(e,A),Wi(e*2,x),a,r+n/Ht,l,o+e/Ht);else if(S){const D=Ds.getPrimitive();It(e,m,D),D.applyMatrix4(t);const M=Yt(n),I=Kt(n,g);It(M,u,wo),It(I,u,So);const L=D.intersectsBox(wo),T=D.intersectsBox(So);C=L&&rn(e,M,i,t,s,o,r,l,a+1,D,!h)||T&&rn(e,I,i,t,s,o,r,l,a+1,D,!h),Ds.releasePrimitive(D)}else{const D=Yt(e),M=Kt(e,A);It(D,m,Df),It(M,m,Bf);const I=c.intersectsBox(Df),L=c.intersectsBox(Bf);if(I&&L)C=rn(n,D,t,i,s,r,o,a,l+1,c,h)||rn(n,M,t,i,s,r,o,a,l+1,c,h);else if(I)if(_)C=rn(n,D,t,i,s,r,o,a,l+1,c,h);else{const T=Ds.getPrimitive();T.copy(Df).applyMatrix4(t);const R=Yt(n),E=Kt(n,g);It(R,u,wo),It(E,u,So);const F=T.intersectsBox(wo),N=T.intersectsBox(So);C=F&&rn(D,R,i,t,s,o,r,l,a+1,T,!h)||N&&rn(D,E,i,t,s,o,r,l,a+1,T,!h),Ds.releasePrimitive(T)}else if(L)if(_)C=rn(n,M,t,i,s,r,o,a,l+1,c,h);else{const T=Ds.getPrimitive();T.copy(Bf).applyMatrix4(t);const R=Yt(n),E=Kt(n,g);It(R,u,wo),It(E,u,So);const F=T.intersectsBox(wo),N=T.intersectsBox(So);C=F&&rn(M,R,i,t,s,o,r,l,a+1,T,!h)||N&&rn(M,E,i,t,s,o,r,l,a+1,T,!h),Ds.releasePrimitive(T)}}return C}const Xc=new ci,Nx=new v.Box3,LB={strategy:bx,maxDepth:40,maxLeafTris:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null};class Lf{static serialize(e,t={}){t={cloneBuffers:!0,...t};const i=e.geometry,s=e._roots,r=e._indirectBuffer,o=i.getIndex(),a={version:1,roots:null,index:null,indirectBuffer:null};return t.cloneBuffers?(a.roots=s.map(l=>l.slice()),a.index=o?o.array.slice():null,a.indirectBuffer=r?r.slice():null):(a.roots=s,a.index=o?o.array:null,a.indirectBuffer=r),a}static deserialize(e,t,i={}){i={setIndex:!0,indirect:!!e.indirectBuffer,...i};const{index:s,roots:r,indirectBuffer:o}=e;e.version||(console.warn("MeshBVH.deserialize: Serialization format has been changed and will be fixed up. It is recommended to regenerate any stored serialized data."),l(r));const a=new Lf(t,{...i,[df]:!0});if(a._roots=r,a._indirectBuffer=o||null,i.setIndex){const c=t.getIndex();if(c===null){const h=new v.BufferAttribute(e.index,1,!1);t.setIndex(h)}else c.array!==s&&(c.array.set(s),c.needsUpdate=!0)}return a;function l(c){for(let h=0;h<c.length;h++){const d=c[h],f=new Uint32Array(d),u=new Uint16Array(d);for(let g=0,p=d.byteLength/li;g<p;g++){const m=Ht*g,A=2*m;Xt(A,u)||(f[m+6]=f[m+6]/Ht-g)}}}}get indirect(){return!!this._indirectBuffer}constructor(e,t={}){if(e.isBufferGeometry){if(e.index&&e.index.isInterleavedBufferAttribute)throw new Error("MeshBVH: InterleavedBufferAttribute is not supported for the index attribute.")}else throw new Error("MeshBVH: Only BufferGeometries are supported.");if(t=Object.assign({...LB,[df]:!1},t),t.useSharedArrayBuffer&&!BB())throw new Error("MeshBVH: SharedArrayBuffer is not available.");this.geometry=e,this._roots=null,this._indirectBuffer=null,t[df]||(YD(this,t),!e.boundingBox&&t.setBoundingBox&&(e.boundingBox=this.getBoundingBox(new v.Box3))),this.resolveTriangleIndex=t.indirect?i=>this._indirectBuffer[i]:i=>i}shiftTriangleOffsets(e){const t=this._indirectBuffer;if(t)for(let i=0,s=t.length;i<s;i++)t[i]+=e;else{const i=this._roots;for(let s=0;s<i.length;s++){const r=i[s],o=new Uint32Array(r),a=new Uint16Array(r),l=r.byteLength/li;for(let c=0;c<l;c++){const h=Ht*c,d=2*h;Xt(d,a)&&(o[h+6]+=e)}}}}refit(e=null){return(this.indirect?vB:lB)(this,e)}traverse(e,t=0){const i=this._roots[t],s=new Uint32Array(i),r=new Uint16Array(i);o(0);function o(a,l=0){const c=a*2,h=Xt(c,r);if(h){const d=s[a+6],f=r[c+14];e(l,h,new Float32Array(i,a*4,6),d,f)}else{const d=Yt(a),f=Kt(a,s),u=bf(a,s);e(l,h,new Float32Array(i,a*4,6),u)||(o(d,l+1),o(f,l+1))}}}raycast(e,t=v.FrontSide,i=0,s=1/0){const r=this._roots,o=[],a=this.indirect?_B:uB;for(let l=0,c=r.length;l<c;l++)a(this,l,t,e,o,i,s);return o}raycastFirst(e,t=v.FrontSide,i=0,s=1/0){const r=this._roots;let o=null;const a=this.indirect?SB:pB;for(let l=0,c=r.length;l<c;l++){const h=a(this,l,t,e,i,s);h!=null&&(o==null||h.distance<o.distance)&&(o=h)}return o}intersectsGeometry(e,t){let i=!1;const s=this._roots,r=this.indirect?CB:gB;for(let o=0,a=s.length;o<a&&(i=r(this,o,e,t),!i);o++);return i}shapecast(e){const t=ji.getPrimitive(),i=this.indirect?dB:aB;let{boundsTraverseOrder:s,intersectsBounds:r,intersectsRange:o,intersectsTriangle:a}=e;if(o&&a){const d=o;o=(f,u,g,p,m)=>d(f,u,g,p,m)?!0:i(f,u,this,a,g,p,t)}else o||(a?o=(d,f,u,g)=>i(d,f,this,a,u,g,t):o=(d,f,u)=>u);let l=!1,c=0;const h=this._roots;for(let d=0,f=h.length;d<f;d++){const u=h[d];if(l=tB(this,d,r,o,s,c),l)break;c+=u.byteLength/li}return ji.releasePrimitive(t),l}bvhcast(e,t,i){let{intersectsRanges:s,intersectsTriangles:r}=i;const o=ji.getPrimitive(),a=this.geometry.index,l=this.geometry.attributes.position,c=this.indirect?g=>{const p=this.resolveTriangleIndex(g);Nt(o,p*3,a,l)}:g=>{Nt(o,g*3,a,l)},h=ji.getPrimitive(),d=e.geometry.index,f=e.geometry.attributes.position,u=e.indirect?g=>{const p=e.resolveTriangleIndex(g);Nt(h,p*3,d,f)}:g=>{Nt(h,g*3,d,f)};if(r){const g=(p,m,A,x,b,y,_,S)=>{for(let C=A,D=A+x;C<D;C++){u(C),h.a.applyMatrix4(t),h.b.applyMatrix4(t),h.c.applyMatrix4(t),h.needsUpdate=!0;for(let M=p,I=p+m;M<I;M++)if(c(M),o.needsUpdate=!0,r(o,h,M,C,b,y,_,S))return!0}return!1};if(s){const p=s;s=function(m,A,x,b,y,_,S,C){return p(m,A,x,b,y,_,S,C)?!0:g(m,A,x,b,y,_,S,C)}}else s=g}return PB(this,e,t,s)}intersectsBox(e,t){return Xc.set(e.min,e.max,t),Xc.needsUpdate=!0,this.shapecast({intersectsBounds:i=>Xc.intersectsBox(i),intersectsTriangle:i=>Xc.intersectsTriangle(i)})}intersectsSphere(e){return this.shapecast({intersectsBounds:t=>e.intersectsBox(t),intersectsTriangle:t=>t.intersectsSphere(e)})}closestPointToGeometry(e,t,i={},s={},r=0,o=1/0){return(this.indirect?DB:yB)(this,e,t,i,s,r,o)}closestPointToPoint(e,t={},i=0,s=1/0){return iB(this,e,t,i,s)}getBoundingBox(e){return e.makeEmpty(),this._roots.forEach(i=>{It(0,new Float32Array(i),Nx),e.union(Nx)}),e}}const zx=1e-6,RB=zx*.5,Gx=Math.pow(10,-Math.log10(zx)),kB=RB*Gx;function Cn(n){return~~(n*Gx+kB)}function FB(n){return`${Cn(n.x)},${Cn(n.y)}`}function Vx(n){return`${Cn(n.x)},${Cn(n.y)},${Cn(n.z)}`}function OB(n){return`${Cn(n.x)},${Cn(n.y)},${Cn(n.z)},${Cn(n.w)}`}function UB(n,e,t){t.direction.subVectors(e,n).normalize();const i=n.dot(t.direction);return t.origin.copy(n).addScaledVector(t.direction,-i),t}function Qx(){return typeof SharedArrayBuffer<"u"}function NB(n){if(n.buffer instanceof SharedArrayBuffer)return n;const e=n.constructor,t=n.buffer,i=new SharedArrayBuffer(t.byteLength),s=new Uint8Array(t);return new Uint8Array(i).set(s,0),new e(i)}function zB(n,e=ArrayBuffer){return n>65535?new Uint32Array(new e(4*n)):new Uint16Array(new e(2*n))}function GB(n,e){if(!n.index){const t=n.attributes.position.count,i=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,s=zB(t,i);n.setIndex(new v.BufferAttribute(s,1));for(let r=0;r<t;r++)s[r]=r}}function VB(n){return n.index?n.index.count:n.attributes.position.count}function Rf(n){return VB(n)/3}const QB=1e-8,jB=new v.Vector3;function WB(n){return~~(n/3)}function HB(n){return n%3}function jx(n,e){return n.start-e.start}function Wx(n,e){return jB.subVectors(e,n.origin).dot(n.direction)}function XB(n,e,t,i=QB){n.sort(jx),e.sort(jx);for(let a=0;a<n.length;a++){const l=n[a];for(let c=0;c<e.length;c++){const h=e[c];if(!(h.start>l.end)){if(l.end<h.start||h.end<l.start)continue;if(l.start<=h.start&&l.end>=h.end)r(h.end,l.end)||n.splice(a+1,0,{start:h.end,end:l.end,index:l.index}),l.end=h.start,h.start=0,h.end=0;else if(l.start>=h.start&&l.end<=h.end)r(l.end,h.end)||e.splice(c+1,0,{start:l.end,end:h.end,index:h.index}),h.end=l.start,l.start=0,l.end=0;else if(l.start<=h.start&&l.end<=h.end){const d=l.end;l.end=h.start,h.start=d}else if(l.start>=h.start&&l.end>=h.end){const d=h.end;h.end=l.start,l.start=d}else throw new Error}if(t.has(l.index)||t.set(l.index,[]),t.has(h.index)||t.set(h.index,[]),t.get(l.index).push(h.index),t.get(h.index).push(l.index),o(h)&&(e.splice(c,1),c--),o(l)){n.splice(a,1),a--;break}}}s(n),s(e);function s(a){for(let l=0;l<a.length;l++)o(a[l])&&(a.splice(l,1),l--)}function r(a,l){return Math.abs(l-a)<i}function o(a){return Math.abs(a.end-a.start)<i}}const Hx=1e-5,Xx=1e-4;class qB{constructor(){this._rays=[]}addRay(e){this._rays.push(e)}findClosestRay(e){const t=this._rays,i=e.clone();i.direction.multiplyScalar(-1);let s=1/0,r=null;for(let l=0,c=t.length;l<c;l++){const h=t[l];if(o(h,e)&&o(h,i))continue;const d=a(h,e),f=a(h,i),u=Math.min(d,f);u<s&&(s=u,r=h)}return r;function o(l,c){const h=l.origin.distanceTo(c.origin)>Hx;return l.direction.angleTo(c.direction)>Xx||h}function a(l,c){const h=l.origin.distanceTo(c.origin),d=l.direction.angleTo(c.direction);return h/Hx+d/Xx}}}const kf=new v.Vector3,Ff=new v.Vector3,qc=new v.Ray;function YB(n,e,t){const i=n.attributes,s=n.index,r=i.position,o=new Map,a=new Map,l=Array.from(e),c=new qB;for(let h=0,d=l.length;h<d;h++){const f=l[h],u=WB(f),g=HB(f);let p=3*u+g,m=3*u+(g+1)%3;s&&(p=s.getX(p),m=s.getX(m)),kf.fromBufferAttribute(r,p),Ff.fromBufferAttribute(r,m),UB(kf,Ff,qc);let A,x=c.findClosestRay(qc);x===null&&(x=qc.clone(),c.addRay(x)),a.has(x)||a.set(x,{forward:[],reverse:[],ray:x}),A=a.get(x);let b=Wx(x,kf),y=Wx(x,Ff);b>y&&([b,y]=[y,b]),qc.direction.dot(x.direction)<0?A.reverse.push({start:b,end:y,index:f}):A.forward.push({start:b,end:y,index:f})}return a.forEach(({forward:h,reverse:d},f)=>{XB(h,d,o,t),h.length===0&&d.length===0&&a.delete(f)}),{disjointConnectivityMap:o,fragmentMap:a}}const KB=new v.Vector2,Of=new v.Vector3,$B=new v.Vector4,Uf=["","",""];class JB{constructor(e=null){this.data=null,this.disjointConnections=null,this.unmatchedDisjointEdges=null,this.unmatchedEdges=-1,this.matchedEdges=-1,this.useDrawRange=!0,this.useAllAttributes=!1,this.matchDisjointEdges=!1,this.degenerateEpsilon=1e-8,e&&this.updateFrom(e)}getSiblingTriangleIndex(e,t){const i=this.data[e*3+t];return i===-1?-1:~~(i/3)}getSiblingEdgeIndex(e,t){const i=this.data[e*3+t];return i===-1?-1:i%3}getDisjointSiblingTriangleIndices(e,t){const i=e*3+t,s=this.disjointConnections.get(i);return s?s.map(r=>~~(r/3)):[]}getDisjointSiblingEdgeIndices(e,t){const i=e*3+t,s=this.disjointConnections.get(i);return s?s.map(r=>r%3):[]}isFullyConnected(){return this.unmatchedEdges===0}updateFrom(e){const{useAllAttributes:t,useDrawRange:i,matchDisjointEdges:s,degenerateEpsilon:r}=this,o=t?b:x,a=new Map,{attributes:l}=e,c=t?Object.keys(l):null,h=e.index,d=l.position;let f=Rf(e);const u=f;let g=0;i&&(g=e.drawRange.start,e.drawRange.count!==1/0&&(f=~~(e.drawRange.count/3)));let p=this.data;(!p||p.length<3*u)&&(p=new Int32Array(3*u)),p.fill(-1);let m=0,A=new Set;for(let y=g,_=f*3+g;y<_;y+=3){const S=y;for(let C=0;C<3;C++){let D=S+C;h&&(D=h.getX(D)),Uf[C]=o(D)}for(let C=0;C<3;C++){const D=(C+1)%3,M=Uf[C],I=Uf[D],L=`${I}_${M}`;if(a.has(L)){const T=S+C,R=a.get(L);p[T]=R,p[R]=T,a.delete(L),m+=2,A.delete(R)}else{const T=`${M}_${I}`,R=S+C;a.set(T,R),A.add(R)}}}if(s){const{fragmentMap:y,disjointConnectivityMap:_}=YB(e,A,r);A.clear(),y.forEach(({forward:S,reverse:C})=>{S.forEach(({index:D})=>A.add(D)),C.forEach(({index:D})=>A.add(D))}),this.unmatchedDisjointEdges=y,this.disjointConnections=_,m=f*3-A.size}this.matchedEdges=m,this.unmatchedEdges=A.size,this.data=p;function x(y){return Of.fromBufferAttribute(d,y),Vx(Of)}function b(y){let _="";for(let S=0,C=c.length;S<C;S++){const D=l[c[S]];let M;switch(D.itemSize){case 1:M=Cn(D.getX(y));break;case 2:M=FB(KB.fromBufferAttribute(D,y));break;case 3:M=Vx(Of.fromBufferAttribute(D,y));break;case 4:M=OB($B.fromBufferAttribute(D,y));break}_!==""&&(_+="|"),_+=M}return _}}}class Yc extends v.Mesh{constructor(...e){super(...e),this.isBrush=!0,this._previousMatrix=new v.Matrix4,this._previousMatrix.elements.fill(0)}markUpdated(){this._previousMatrix.copy(this.matrix)}isDirty(){const{matrix:e,_previousMatrix:t}=this,i=e.elements,s=t.elements;for(let r=0;r<16;r++)if(i[r]!==s[r])return!0;return!1}prepareGeometry(){const e=this.geometry,t=e.attributes,i=Qx();if(i)for(const s in t){const r=t[s];if(r.isInterleavedBufferAttribute)throw new Error("Brush: InterleavedBufferAttributes are not supported.");r.array=NB(r.array)}if(e.boundsTree||(GB(e,{useSharedArrayBuffer:i}),e.boundsTree=new Lf(e,{maxLeafTris:3,indirect:!0,useSharedArrayBuffer:i})),e.halfEdges||(e.halfEdges=new JB(e)),!e.groupIndices){const s=Rf(e),r=new Uint16Array(s),o=e.groups;for(let a=0,l=o.length;a<l;a++){const{start:c,count:h}=o[a];for(let d=c/3,f=(c+h)/3;d<f;d++)r[d]=a}e.groupIndices=r}}disposeCacheData(){const{geometry:e}=this;e.halfEdges=null,e.boundsTree=null,e.groupIndices=null}}const ZB=1e-14,Nf=new v.Vector3,qx=new v.Vector3,Yx=new v.Vector3;function Bs(n,e=ZB){Nf.subVectors(n.b,n.a),qx.subVectors(n.c,n.a),Yx.subVectors(n.b,n.c);const t=Nf.angleTo(qx),i=Nf.angleTo(Yx),s=Math.PI-t-i;return Math.abs(t)<e||Math.abs(i)<e||Math.abs(s)<e||n.a.distanceToSquared(n.b)<e||n.a.distanceToSquared(n.c)<e||n.b.distanceToSquared(n.c)<e}const zf=1e-10,Da=1e-10,eP=1e-10,is=new v.Line3,Ft=new v.Line3,ns=new v.Vector3,Gf=new v.Vector3,Kx=new v.Vector3,Kc=new v.Plane,Vf=new Qi;class tP{constructor(){this._pool=[],this._index=0}getTriangle(){return this._index>=this._pool.length&&this._pool.push(new v.Triangle),this._pool[this._index++]}clear(){this._index=0}reset(){this._pool.length=0,this._index=0}}class iP{constructor(){this.trianglePool=new tP,this.triangles=[],this.normal=new v.Vector3,this.coplanarTriangleUsed=!1}initialize(e){this.reset();const{triangles:t,trianglePool:i,normal:s}=this;if(Array.isArray(e))for(let r=0,o=e.length;r<o;r++){const a=e[r];if(r===0)a.getNormal(s);else if(Math.abs(1-a.getNormal(ns).dot(s))>zf)throw new Error("Triangle Splitter: Cannot initialize with triangles that have different normals.");const l=i.getTriangle();l.copy(a),t.push(l)}else{e.getNormal(s);const r=i.getTriangle();r.copy(e),t.push(r)}}splitByTriangle(e){const{normal:t,triangles:i}=this;if(e.getNormal(Gf).normalize(),Math.abs(1-Math.abs(Gf.dot(t)))<eP){this.coplanarTriangleUsed=!0;for(let r=0,o=i.length;r<o;r++){const a=i[r];a.coplanarCount=0}const s=[e.a,e.b,e.c];for(let r=0;r<3;r++){const o=(r+1)%3,a=s[r],l=s[o];ns.subVectors(l,a).normalize(),Kx.crossVectors(Gf,ns),Kc.setFromNormalAndCoplanarPoint(Kx,a),this.splitByPlane(Kc,e)}}else e.getPlane(Kc),this.splitByPlane(Kc,e)}splitByPlane(e,t){const{triangles:i,trianglePool:s}=this;Vf.copy(t),Vf.needsUpdate=!0;for(let r=0,o=i.length;r<o;r++){const a=i[r];if(!Vf.intersectsTriangle(a,is,!0))continue;const{a:l,b:c,c:h}=a;let d=0,f=-1,u=!1,g=[],p=[];const m=[l,c,h];for(let A=0;A<3;A++){const x=(A+1)%3;is.start.copy(m[A]),is.end.copy(m[x]);const b=e.distanceToPoint(is.start),y=e.distanceToPoint(is.end);if(Math.abs(b)<Da&&Math.abs(y)<Da){u=!0;break}if(b>0?g.push(A):p.push(A),Math.abs(b)<Da)continue;let _=!!e.intersectLine(is,ns);!_&&Math.abs(y)<Da&&(ns.copy(is.end),_=!0),_&&!(ns.distanceTo(is.start)<zf)&&(ns.distanceTo(is.end)<zf&&(f=A),d===0?Ft.start.copy(ns):Ft.end.copy(ns),d++)}if(!u&&d===2&&Ft.distance()>Da)if(f!==-1){f=(f+1)%3;let A=0;A===f&&(A=(A+1)%3);let x=A+1;x===f&&(x=(x+1)%3);const b=s.getTriangle();b.a.copy(m[x]),b.b.copy(Ft.end),b.c.copy(Ft.start),Bs(b)||i.push(b),a.a.copy(m[A]),a.b.copy(Ft.start),a.c.copy(Ft.end),Bs(a)&&(i.splice(r,1),r--,o--)}else{const A=g.length>=2?p[0]:g[0];if(A===0){let S=Ft.start;Ft.start=Ft.end,Ft.end=S}const x=(A+1)%3,b=(A+2)%3,y=s.getTriangle(),_=s.getTriangle();m[x].distanceToSquared(Ft.start)<m[b].distanceToSquared(Ft.end)?(y.a.copy(m[x]),y.b.copy(Ft.start),y.c.copy(Ft.end),_.a.copy(m[x]),_.b.copy(m[b]),_.c.copy(Ft.start)):(y.a.copy(m[b]),y.b.copy(Ft.start),y.c.copy(Ft.end),_.a.copy(m[x]),_.b.copy(m[b]),_.c.copy(Ft.end)),a.a.copy(m[A]),a.b.copy(Ft.end),a.c.copy(Ft.start),Bs(y)||i.push(y),Bs(_)||i.push(_),Bs(a)&&(i.splice(r,1),r--,o--)}else d===3&&console.warn("TriangleClipper: Coplanar clip not handled")}}reset(){this.triangles.length=0,this.trianglePool.clear(),this.coplanarTriangleUsed=!1}}function nP(n){return n=~~n,n+4-n%4}class $x{constructor(e,t=500){this.expansionFactor=1.5,this.type=e,this.length=0,this.array=null,this.setSize(t)}setType(e){if(this.length!==0)throw new Error("TypeBackedArray: Cannot change the type while there is used data in the buffer.");const t=this.array.buffer;this.array=new e(t),this.type=e}setSize(e){if(this.array&&e===this.array.length)return;const t=this.type,i=Qx()?SharedArrayBuffer:ArrayBuffer,s=new t(new i(nP(e*t.BYTES_PER_ELEMENT)));this.array&&s.set(this.array,0),this.array=s}expand(){const{array:e,expansionFactor:t}=this;this.setSize(e.length*t)}push(...e){let{array:t,length:i}=this;i+e.length>t.length&&(this.expand(),t=this.array);for(let s=0,r=e.length;s<r;s++)t[i+s]=e[s];this.length+=e.length}clear(){this.length=0}}class sP{constructor(){this.groupAttributes=[{}],this.groupCount=0}getType(e){return this.groupAttributes[0][e].type}getItemSize(e){return this.groupAttributes[0][e].itemSize}getNormalized(e){return this.groupAttributes[0][e].normalized}getCount(e){if(this.groupCount<=e)return 0;const t=this.getGroupAttrArray("position",e);return t.length/t.itemSize}getTotalLength(e){const{groupCount:t,groupAttributes:i}=this;let s=0;for(let r=0;r<t;r++){const o=i[r];s+=o[e].length}return s}getGroupAttrSet(e=0){const{groupAttributes:t}=this;if(t[e])return this.groupCount=Math.max(this.groupCount,e+1),t[e];const i=t[0];for(this.groupCount=Math.max(this.groupCount,e+1);e>=t.length;){const s={};t.push(s);for(const r in i){const o=i[r],a=new $x(o.type);a.itemSize=o.itemSize,a.normalized=o.normalized,s[r]=a}}return t[e]}getGroupAttrArray(e,t=0){const{groupAttributes:i}=this;if(!i[0][e])throw new Error(`TypedAttributeData: Attribute with "${e}" has not been initialized`);return this.getGroupAttrSet(t)[e]}initializeArray(e,t,i,s){const{groupAttributes:r}=this,a=r[0][e];if(a){if(a.type!==t)for(let l=0,c=r.length;l<c;l++){const h=r[l][e];h.setType(t),h.itemSize=i,h.normalized=s}}else for(let l=0,c=r.length;l<c;l++){const h=new $x(t);h.itemSize=i,h.normalized=s,r[l][e]=h}}clear(){this.groupCount=0;const{groupAttributes:e}=this;e.forEach(t=>{for(const i in t)t[i].clear()})}delete(e){this.groupAttributes.forEach(t=>{delete t[e]})}reset(){this.groupAttributes=[],this.groupCount=0}}class Jx{constructor(){this.intersectionSet={},this.ids=[]}add(e,t){const{intersectionSet:i,ids:s}=this;i[e]||(i[e]=[],s.push(e)),i[e].push(t)}}const rP=0,oP=1,aP=2,Zx=3,lP=4,eb=5,tb=6,Hi=new v.Ray,ib=new v.Matrix4,hi=new v.Triangle,ss=new v.Vector3,nb=new v.Vector4,sb=new v.Vector4,rb=new v.Vector4,Qf=new v.Vector4,$c=new v.Vector4,Jc=new v.Vector4,ob=new v.Line3,jf=new v.Vector3,Wf=1e-8,cP=1e-15,xr=-1,br=1,Zc=-2,eh=2,Ba=0,yr=1,Hf=2,hP=1e-14;let th=null;function ab(n){th=n}function lb(n,e){n.getMidpoint(Hi.origin),n.getNormal(Hi.direction);const t=e.raycastFirst(Hi,v.DoubleSide);return!!(t&&Hi.direction.dot(t.face.normal)>0)?xr:br}function dP(n,e){function t(){return Math.random()-.5}n.getNormal(jf),Hi.direction.copy(jf),n.getMidpoint(Hi.origin);const i=3;let s=0,r=1/0;for(let o=0;o<i;o++){Hi.direction.x+=t()*Wf,Hi.direction.y+=t()*Wf,Hi.direction.z+=t()*Wf,Hi.direction.multiplyScalar(-1);const a=e.raycastFirst(Hi,v.DoubleSide);if(!!(a&&Hi.direction.dot(a.face.normal)>0)&&s++,a!==null&&(r=Math.min(r,a.distance)),r<=cP)return a.face.normal.dot(jf)>0?eh:Zc;if(s/i>.5||(o-s+1)/i>.5)break}return s/i>.5?xr:br}function uP(n,e){const t=new Jx,i=new Jx;return ib.copy(n.matrixWorld).invert().multiply(e.matrixWorld),n.geometry.boundsTree.bvhcast(e.geometry.boundsTree,ib,{intersectsTriangles(s,r,o,a){if(!Bs(s)&&!Bs(r)){let l=s.intersectsTriangle(r,ob,!0);if(!l){const c=s.plane,h=r.plane,d=c.normal,f=h.normal;d.dot(f)===1&&Math.abs(c.constant-h.constant)<hP&&(l=!0)}if(l){let c=n.geometry.boundsTree.resolveTriangleIndex(o),h=e.geometry.boundsTree.resolveTriangleIndex(a);t.add(c,h),i.add(h,c),th&&(th.addEdge(ob),th.addIntersectingTriangles(o,s,a,r))}}return!1}}),{aIntersections:t,bIntersections:i}}function fP(n,e,t,i,s,r,o=!1){const a=t.attributes,l=t.index,c=n*3,h=l.getX(c+0),d=l.getX(c+1),f=l.getX(c+2);for(const u in r){const g=a[u],p=r[u];if(!(u in a))throw new Error(`CSG Operations: Attribute ${u} not available on geometry.`);const m=g.itemSize;u==="position"?(hi.a.fromBufferAttribute(g,h).applyMatrix4(i),hi.b.fromBufferAttribute(g,d).applyMatrix4(i),hi.c.fromBufferAttribute(g,f).applyMatrix4(i),Xf(hi.a,hi.b,hi.c,e,3,p,o)):u==="normal"?(hi.a.fromBufferAttribute(g,h).applyNormalMatrix(s),hi.b.fromBufferAttribute(g,d).applyNormalMatrix(s),hi.c.fromBufferAttribute(g,f).applyNormalMatrix(s),o&&(hi.a.multiplyScalar(-1),hi.b.multiplyScalar(-1),hi.c.multiplyScalar(-1)),Xf(hi.a,hi.b,hi.c,e,3,p,o,!0)):(nb.fromBufferAttribute(g,h),sb.fromBufferAttribute(g,d),rb.fromBufferAttribute(g,f),Xf(nb,sb,rb,e,m,p,o))}}function pP(n,e,t,i,s,r,o,a=!1){qf(n,i,s,r,o,a),qf(a?t:e,i,s,r,o,a),qf(a?e:t,i,s,r,o,a)}function cb(n,e,t=!1){switch(n){case rP:if(e===br||e===eh&&!t)return yr;break;case oP:if(t){if(e===xr)return Ba}else if(e===br||e===Zc)return yr;break;case aP:if(t){if(e===br||e===Zc)return yr}else if(e===xr)return Ba;break;case lP:if(e===xr)return Ba;if(e===br)return yr;break;case Zx:if(e===xr||e===eh&&!t)return yr;break;case eb:if(!t&&(e===br||e===Zc))return yr;break;case tb:if(!t&&(e===xr||e===eh))return yr;break;default:throw new Error(`Unrecognized CSG operation enum "${n}".`)}return Hf}function Xf(n,e,t,i,s,r,o=!1,a=!1){const l=c=>{r.push(c.x),s>1&&r.push(c.y),s>2&&r.push(c.z),s>3&&r.push(c.w)};Qf.set(0,0,0,0).addScaledVector(n,i.a.x).addScaledVector(e,i.a.y).addScaledVector(t,i.a.z),$c.set(0,0,0,0).addScaledVector(n,i.b.x).addScaledVector(e,i.b.y).addScaledVector(t,i.b.z),Jc.set(0,0,0,0).addScaledVector(n,i.c.x).addScaledVector(e,i.c.y).addScaledVector(t,i.c.z),a&&(Qf.normalize(),$c.normalize(),Jc.normalize()),l(Qf),o?(l(Jc),l($c)):(l($c),l(Jc))}function qf(n,e,t,i,s,r=!1){for(const o in s){const a=e[o],l=s[o];if(!(o in e))throw new Error(`CSG Operations: Attribute ${o} no available on geometry.`);const c=a.itemSize;o==="position"?(ss.fromBufferAttribute(a,n).applyMatrix4(t),l.push(ss.x,ss.y,ss.z)):o==="normal"?(ss.fromBufferAttribute(a,n).applyNormalMatrix(i),r&&ss.multiplyScalar(-1),l.push(ss.x,ss.y,ss.z)):(l.push(a.getX(n)),c>1&&l.push(a.getY(n)),c>2&&l.push(a.getZ(n)),c>3&&l.push(a.getW(n)))}}class gP{constructor(e){this.triangle=new v.Triangle().copy(e),this.intersects={}}addTriangle(e,t){this.intersects[e]=new v.Triangle().copy(t)}getIntersectArray(){const e=[],{intersects:t}=this;for(const i in t)e.push(t[i]);return e}}class hb{constructor(){this.data={}}addTriangleIntersection(e,t,i,s){const{data:r}=this;r[e]||(r[e]=new gP(t)),r[e].addTriangle(i,s)}getTrianglesAsArray(e=null){const{data:t}=this,i=[];if(e!==null)e in t&&i.push(t[e].triangle);else for(const s in t)i.push(t[s].triangle);return i}getTriangleIndices(){return Object.keys(this.data).map(e=>parseInt(e))}getIntersectionIndices(e){const{data:t}=this;return t[e]?Object.keys(t[e].intersects).map(i=>parseInt(i)):[]}getIntersectionsAsArray(e=null,t=null){const{data:i}=this,s=new Set,r=[],o=a=>{if(i[a])if(t!==null)i[a].intersects[t]&&r.push(i[a].intersects[t]);else{const l=i[a].intersects;for(const c in l)s.has(c)||(s.add(c),r.push(l[c]))}};if(e!==null)o(e);else for(const a in i)o(a);return r}reset(){this.data={}}}class mP{constructor(){this.enabled=!1,this.triangleIntersectsA=new hb,this.triangleIntersectsB=new hb,this.intersectionEdges=[]}addIntersectingTriangles(e,t,i,s){const{triangleIntersectsA:r,triangleIntersectsB:o}=this;r.addTriangleIntersection(e,t,i,s),o.addTriangleIntersection(i,s,e,t)}addEdge(e){this.intersectionEdges.push(e.clone())}reset(){this.triangleIntersectsA.reset(),this.triangleIntersectsB.reset(),this.intersectionEdges=[]}init(){this.enabled&&(this.reset(),ab(this))}complete(){this.enabled&&ab(null)}}const Ps=new v.Matrix4,ih=new v.Matrix3,vr=new v.Triangle,nh=new v.Triangle,Ls=new v.Triangle,sh=new v.Triangle,on=[],_r=[];function AP(n){for(const e of n)return e}function xP(n,e,t,i,s,r={}){const{useGroups:o=!0}=r,{aIntersections:a,bIntersections:l}=uP(n,e),c=[];let h=null,d;return d=o?0:-1,db(n,e,a,t,!1,i,s,d),ub(n,e,a,t,!1,s,d),t.findIndex(u=>u!==tb&&u!==eb)!==-1&&(d=o?n.geometry.groups.length||1:-1,db(e,n,l,t,!0,i,s,d),ub(e,n,l,t,!0,s,d)),on.length=0,_r.length=0,{groups:c,materials:h}}function db(n,e,t,i,s,r,o,a=0){const l=n.matrixWorld.determinant()<0;Ps.copy(e.matrixWorld).invert().multiply(n.matrixWorld),ih.getNormalMatrix(n.matrixWorld).multiplyScalar(l?-1:1);const c=n.geometry.groupIndices,h=n.geometry.index,d=n.geometry.attributes.position,f=e.geometry.boundsTree,u=e.geometry.index,g=e.geometry.attributes.position,p=t.ids,m=t.intersectionSet;for(let A=0,x=p.length;A<x;A++){const b=p[A],y=a===-1?0:c[b]+a,_=3*b,S=h.getX(_+0),C=h.getX(_+1),D=h.getX(_+2);vr.a.fromBufferAttribute(d,S).applyMatrix4(Ps),vr.b.fromBufferAttribute(d,C).applyMatrix4(Ps),vr.c.fromBufferAttribute(d,D).applyMatrix4(Ps),r.reset(),r.initialize(vr);const M=m[b];for(let L=0,T=M.length;L<T;L++){const R=3*M[L],E=u.getX(R+0),F=u.getX(R+1),N=u.getX(R+2);nh.a.fromBufferAttribute(g,E),nh.b.fromBufferAttribute(g,F),nh.c.fromBufferAttribute(g,N),r.splitByTriangle(nh)}const I=r.triangles;for(let L=0,T=I.length;L<T;L++){const R=I[L],E=r.coplanarTriangleUsed?dP(R,f):lb(R,f);on.length=0,_r.length=0;for(let F=0,N=i.length;F<N;F++){const H=cb(i[F],E,s);H!==Hf&&(_r.push(H),on.push(o[F].getGroupAttrSet(y)))}if(on.length!==0){vr.getBarycoord(R.a,sh.a),vr.getBarycoord(R.b,sh.b),vr.getBarycoord(R.c,sh.c);for(let F=0,N=on.length;F<N;F++){const H=on[F],U=_r[F]===Ba;fP(b,sh,n.geometry,n.matrixWorld,ih,H,l!==U)}}}}return p.length}function ub(n,e,t,i,s,r,o=0){const a=n.matrixWorld.determinant()<0;Ps.copy(e.matrixWorld).invert().multiply(n.matrixWorld),ih.getNormalMatrix(n.matrixWorld).multiplyScalar(a?-1:1);const l=e.geometry.boundsTree,c=n.geometry.groupIndices,h=n.geometry.index,d=n.geometry.attributes,f=d.position,u=[],g=n.geometry.halfEdges,p=new Set,m=Rf(n.geometry);for(let A=0,x=m;A<x;A++)A in t.intersectionSet||p.add(A);for(;p.size>0;){const A=AP(p);p.delete(A),u.push(A);const x=3*A,b=h.getX(x+0),y=h.getX(x+1),_=h.getX(x+2);Ls.a.fromBufferAttribute(f,b).applyMatrix4(Ps),Ls.b.fromBufferAttribute(f,y).applyMatrix4(Ps),Ls.c.fromBufferAttribute(f,_).applyMatrix4(Ps);const S=lb(Ls,l);_r.length=0,on.length=0;for(let C=0,D=i.length;C<D;C++){const M=cb(i[C],S,s);M!==Hf&&(_r.push(M),on.push(r[C]))}for(;u.length>0;){const C=u.pop();for(let D=0;D<3;D++){const M=g.getSiblingTriangleIndex(C,D);M!==-1&&p.has(M)&&(u.push(M),p.delete(M))}if(on.length!==0){const D=3*C,M=h.getX(D+0),I=h.getX(D+1),L=h.getX(D+2),T=o===-1?0:c[C]+o;if(Ls.a.fromBufferAttribute(f,M),Ls.b.fromBufferAttribute(f,I),Ls.c.fromBufferAttribute(f,L),!Bs(Ls))for(let R=0,E=on.length;R<E;R++){const F=_r[R],N=on[R].getGroupAttrSet(T),H=F===Ba;pP(M,I,L,d,n.matrixWorld,ih,N,H!==a)}}}}}function bP(n){for(let e=0;e<n.length-1;e++){const t=n[e],i=n[e+1];if(t.materialIndex===i.materialIndex){const s=t.start,r=i.start+i.count;i.start=s,i.count=r-s,n.splice(e,1),e--}}}function yP(n,e,t,i){t.clear();const s=n.attributes;for(let r=0,o=i.length;r<o;r++){const a=i[r],l=s[a];t.initializeArray(a,l.array.constructor,l.itemSize,l.normalized)}for(const r in t.attributes)i.includes(r)||t.delete(r);for(const r in e.attributes)i.includes(r)||(e.deleteAttribute(r),e.dispose())}function vP(n,e,t){let i=!1,s=-1;const r=n.attributes,o=e.groupAttributes[0];for(const l in o){const c=e.getTotalLength(l),h=e.getType(l),d=e.getItemSize(l),f=e.getNormalized(l);let u=r[l];(!u||u.array.length<c)&&(u=new v.BufferAttribute(new h(c),d,f),n.setAttribute(l,u),i=!0);let g=0;for(let p=0,m=Math.min(t.length,e.groupCount);p<m;p++){const A=t[p].index,{array:x,type:b,length:y}=e.groupAttributes[A][l],_=new b(x.buffer,0,y);u.array.set(_,g),g+=_.length}u.needsUpdate=!0,s=c/u.itemSize}if(n.index){const l=n.index.array;if(l.length<s)n.index=null,i=!0;else for(let c=0,h=l.length;c<h;c++)l[c]=c}let a=0;n.clearGroups();for(let l=0,c=Math.min(t.length,e.groupCount);l<c;l++){const{index:h,materialIndex:d}=t[l],f=e.getCount(h);f!==0&&(n.addGroup(a,f,d),a+=f)}n.setDrawRange(0,s),n.boundsTree=null,i&&n.dispose()}function fb(n,e){let t=e;return Array.isArray(e)||(t=[],n.forEach(i=>{t[i.materialIndex]=e})),t}class _P{constructor(){this.triangleSplitter=new iP,this.attributeData=[],this.attributes=["position","uv","normal"],this.useGroups=!0,this.consolidateGroups=!0,this.debug=new mP}getGroupRanges(e){return!this.useGroups||e.groups.length===0?[{start:0,count:1/0,materialIndex:0}]:e.groups.map(t=>({...t}))}evaluate(e,t,i,s=new Yc){let r=!0;if(Array.isArray(i)||(i=[i]),Array.isArray(s)||(s=[s],r=!1),s.length!==i.length)throw new Error("Evaluator: operations and target array passed as different sizes.");e.prepareGeometry(),t.prepareGeometry();const{triangleSplitter:o,attributeData:a,attributes:l,useGroups:c,consolidateGroups:h,debug:d}=this;for(;a.length<s.length;)a.push(new sP);s.forEach((A,x)=>{yP(e.geometry,A.geometry,a[x],l)}),d.init(),xP(e,t,i,o,a,{useGroups:c}),d.complete();const f=this.getGroupRanges(e.geometry),u=fb(f,e.material),g=this.getGroupRanges(t.geometry),p=fb(g,t.material);g.forEach(A=>A.materialIndex+=u.length);let m=[...f,...g].map((A,x)=>({...A,index:x}));if(c){const A=[...u,...p];h&&(m=m.map(b=>{const y=A[b.materialIndex];return b.materialIndex=A.indexOf(y),b}).sort((b,y)=>b.materialIndex-y.materialIndex));const x=[];for(let b=0,y=A.length;b<y;b++){let _=!1;for(let S=0,C=m.length;S<C;S++){const D=m[S];D.materialIndex===b&&(_=!0,D.materialIndex=x.length)}_&&x.push(A[b])}s.forEach(b=>{b.material=x})}else m=[{start:0,count:1/0,index:0,materialIndex:0}],s.forEach(A=>{A.material=u[0]});return s.forEach((A,x)=>{const b=A.geometry;vP(b,a[x],m),h&&bP(b.groups)}),r?s:s[0]}evaluateHierarchy(e,t=new Yc){e.updateMatrixWorld(!0);const i=(r,o)=>{const a=r.children;for(let l=0,c=a.length;l<c;l++){const h=a[l];h.isOperationGroup?i(h,o):o(h)}},s=r=>{const o=r.children;let a=!1;for(let c=0,h=o.length;c<h;c++){const d=o[c];a=s(d)||a}const l=r.isDirty();if(l&&r.markUpdated(),a&&!r.isOperationGroup){let c;return i(r,h=>{c?c=this.evaluate(c,h,h.operation):c=this.evaluate(r,h,h.operation)}),r._cachedGeometry=c.geometry,r._cachedMaterials=c.material,!0}else return a||l};return s(e),t.geometry=e._cachedGeometry,t.material=e._cachedMaterials,t}reset(){this.triangleSplitter.reset()}}class wP{engine;evaluator;fillMeshName="ClippingFaceFillMesh";fillMeshes=new Map;maxCandidates=22e5;maxTriangleCountPerMesh=12e4;fillMaterial;fillTextureRepeat=60;fillTextureRotation=0;constructor(e){this.engine=e,this.evaluator=new _P;const t=new URL("/texture/fill.png",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,i=new w.TextureLoader().load(t);i.wrapS=w.RepeatWrapping,i.wrapT=w.RepeatWrapping,i.center.set(.5,.5),i.rotation=this.fillTextureRotation,this.fillMaterial=new w.MeshStandardMaterial({color:16112010,map:i,side:w.DoubleSide,toneMapped:!1}),this.fillMaterial.clipShadows=!0,this.fillMaterial.clippingPlanes=e.sectionPlane}clear(){this.fillMeshes.forEach(e=>{e.parent?.remove(e),e.geometry?.dispose?.();const t=e.material;Array.isArray(t)?t.forEach(i=>i.dispose?.()):t&&t!==this.fillMaterial&&t.dispose?.()}),this.fillMeshes.clear()}updataFace(e){this.clear(),e instanceof w.Plane&&this.engine.clipping.fillCutFace&&this.buildSinglePlaneFill(e,"face")}updataFaces(e){this.clear(),!(!Array.isArray(e)||e.length===0)&&this.engine.clipping.fillCutFace&&e.forEach((t,i)=>{if(!(t instanceof w.Plane))return;const s=`plane-${i}-${String(t.name??i)}`;this.buildSinglePlaneFill(t,s)})}buildSinglePlaneFill(e,t){const i=this.engine?.octreeBox?.getBoundingBox?.();if(i==null||i.min==null||i.max==null)return;const s=this.collectCandidateMeshesFromOctree(e);if(s.length===0)return;const r=this.filterMeshesByBoxAndComplexity(e,s);if(r.length===0)return;const o=i.min.distanceTo(i.max),a=o*5,l=.1,c=this.createPlaneBrush(e,a,l),h=[];for(const p of r.slice(0,this.maxCandidates)){const m=this.createWorldBrushFromMesh(p);if(m!=null)try{const x=this.evaluator.evaluate(m,c,Zx)?.geometry;if(!x)continue;const b=this.extractPlaneCapGeometry(x,e,l);b&&h.push(b),x.dispose()}catch{}finally{m.geometry.dispose()}}if(c.geometry.dispose(),h.length===0)return;const d=Yn(h,!1);if(h.forEach(p=>p.dispose()),!d)return;this.applyPlanarUv(d,e);const f=this.getFaceOffsetDistance(o),u=this.getFaceOffsetSign();d.translate(e.normal.x*f*u,e.normal.y*f*u,e.normal.z*f*u);const g=new w.Mesh(d,this.fillMaterial);g.name=`${this.fillMeshName}_${t}`,g.frustumCulled=!1,g.renderOrder=20,g.castShadow=!1,g.receiveShadow=!1,this.engine.scene.add(g),this.fillMeshes.set(t,g)}getFaceOffsetDistance(e){return-.001}getFaceOffsetSign(){const e=this.engine?.engineStatus?.clippingFaceOffsetSign;return e===1||e===-1?e:-1}collectCandidateMeshesFromOctree(e){const t=[],i=new Set,s=Array.isArray(this.engine?.engineStatus?.models)?this.engine.engineStatus.models:[];for(const r of s){const o=this.engine.models?.find?.(c=>c.url===r.url);if(!o?.nodesMap)continue;const a=this.getIgnoredIds(r.url),l=Array.isArray(r?.info?.lods)?r.info.lods:[];for(const c of l){const h=c?.octreeBox;if(!h)continue;const d=this.collectIntersectElementIds(h,e);for(const f of d){if(a.has(f))continue;const u=o.nodesMap.get(f);if(!(u?.instance===!0||!Array.isArray(u?.infos)))for(const g of u.infos){const p=g?.mesh;p instanceof w.Mesh&&(i.has(p.uuid)||(i.add(p.uuid),t.push(p)))}}}}return t}getIgnoredIds(e){const t=new Set,i=Array.isArray(this.engine?.engineStatus?.hideModels)?this.engine.engineStatus.hideModels:[],s=Array.isArray(this.engine?.engineStatus?.translucentModels)?this.engine.engineStatus.translucentModels:[],r=i.find(a=>a.url===e)?.ids;Array.isArray(r)&&r.forEach(a=>t.add(a));const o=s.find(a=>a.url===e)?.ids;return Array.isArray(o)&&o.forEach(a=>t.add(a)),t}collectIntersectElementIds(e,t){const i=new Set,s=[e];for(;s.length>0;){const r=s.pop();if(!r)continue;const o=this.octreeNodeToBox3(r);!o||!t.intersectsBox(o)||(Array.isArray(r.elements)&&r.elements.forEach(a=>i.add(a)),Array.isArray(r.children)&&r.children.forEach(a=>s.push(a)))}return i}octreeNodeToBox3(e){if(!e?.min||!e?.max)return null;const t=new w.Vector3(e.min.X*.3048,e.min.Z*.3048,-e.min.Y*.3048),i=new w.Vector3(e.max.X*.3048,e.max.Z*.3048,-e.max.Y*.3048),s=new w.Vector3(Math.min(t.x,i.x),Math.min(t.y,i.y),Math.min(t.z,i.z)),r=new w.Vector3(Math.max(t.x,i.x),Math.max(t.y,i.y),Math.max(t.z,i.z));return new w.Box3(s,r)}filterMeshesByBoxAndComplexity(e,t){const i=[],s=new w.Box3;for(const r of t){const o=r.geometry,a=o?.attributes?.position;!o||!a||a.count===0||(o.index?Math.floor(o.index.count/3):Math.floor(a.count/3))>this.maxTriangleCountPerMesh||(o.boundingBox||o.computeBoundingBox(),o.boundingBox&&(s.copy(o.boundingBox),r.updateWorldMatrix(!0,!1),s.applyMatrix4(r.matrixWorld),e.intersectsBox(s)&&(r.geometry.attributes.position.count>500||i.push(r))))}return i}createPlaneBrush(e,t,i){const s=new w.BoxGeometry(t,t,i),r=e.coplanarPoint(new w.Vector3),o=new w.Quaternion().setFromUnitVectors(new w.Vector3(0,0,1),e.normal.clone().normalize()),a=new w.Matrix4().compose(r,o,new w.Vector3(1,1,1));s.applyMatrix4(a);const l=this.toCsgReadyGeometry(s);return s.dispose(),new Yc(l)}createWorldBrushFromMesh(e){const t=e.geometry;if(!t||!t.attributes?.position)return null;e.updateWorldMatrix(!0,!1);const i=t.clone();i.applyMatrix4(e.matrixWorld);const s=this.toCsgReadyGeometry(i);return i.dispose(),new Yc(s)}toCsgReadyGeometry(e){const t=e.index?e.toNonIndexed():e.clone();t.getAttribute("normal")||t.computeVertexNormals();const i=t.getAttribute("position");if(i&&!t.getAttribute("uv")){const r=new Float32Array(i.count*2);t.setAttribute("uv",new w.Float32BufferAttribute(r,2))}const s=new Set(["position","normal","uv"]);return Object.keys(t.attributes).forEach(r=>{s.has(r)||t.deleteAttribute(r)}),t}extractPlaneCapGeometry(e,t,i){const s=e.index?e.toNonIndexed():e.clone(),r=s.getAttribute("position");if(!r||r.count<3)return s.dispose(),null;const o=t.normal.clone().normalize(),a=new w.Vector3,l=new w.Vector3,c=new w.Vector3,h=new w.Vector3,d=new w.Vector3,f=new w.Vector3,u=new w.Vector3,g=new w.Vector3,p=new w.Vector3,m=Math.max(i*.35,1e-4),A=Math.max(i*.7,1e-4),x=[];for(let y=0;y<r.count;y+=3){if(h.fromBufferAttribute(r,y),d.fromBufferAttribute(r,y+1),f.fromBufferAttribute(r,y+2),l.subVectors(d,h),c.subVectors(f,h),a.crossVectors(l,c),a.lengthSq()<1e-14||(a.normalize(),Math.abs(a.dot(o))<.9))continue;const _=t.distanceToPoint(h),S=t.distanceToPoint(d),C=t.distanceToPoint(f),D=Math.min(_,S,C);if(Math.max(_,S,C)-D>m)continue;const I=(_+S+C)/3;Math.abs(I)>A||I<0||(u.copy(h).addScaledVector(o,-_),g.copy(d).addScaledVector(o,-S),p.copy(f).addScaledVector(o,-C),a.dot(o)<=0?(x.push(u.x,u.y,u.z),x.push(g.x,g.y,g.z),x.push(p.x,p.y,p.z)):(x.push(u.x,u.y,u.z),x.push(p.x,p.y,p.z),x.push(g.x,g.y,g.z)))}if(s.dispose(),x.length<9)return null;const b=new w.BufferGeometry;return b.setAttribute("position",new w.Float32BufferAttribute(x,3)),b.computeVertexNormals(),b}applyPlanarUv(e,t){const i=e.getAttribute("position");if(!i||i.count===0)return;const{tangent:s,bitangent:r}=this.getPlaneBasis(t.normal.clone().normalize()),o=new w.Vector3,a=new Float32Array(i.count*2);let l=1/0,c=-1/0,h=1/0,d=-1/0;for(let g=0;g<i.count;g++){o.fromBufferAttribute(i,g);const p=o.dot(s),m=o.dot(r),A=g*2;a[A]=p,a[A+1]=m,l=Math.min(l,p),c=Math.max(c,p),h=Math.min(h,m),d=Math.max(d,m)}const f=Math.max(c-l,1e-6),u=Math.max(d-h,1e-6);for(let g=0;g<a.length;g+=2)a[g]=(a[g]-l)/f*this.fillTextureRepeat,a[g+1]=(a[g+1]-h)/u*this.fillTextureRepeat;e.setAttribute("uv",new w.BufferAttribute(a,2))}getPlaneBasis(e){const t=new w.Vector3(1,0,0),i=new w.Vector3(0,1,0),s=new w.Vector3(0,0,1),r=Math.abs(e.dot(t)),o=Math.abs(e.dot(i)),a=Math.abs(e.dot(s));let l=t;o<=r&&o<=a?l=i:a<=r&&a<=o&&(l=s),l=l.clone().sub(e.clone().multiplyScalar(l.dot(e))).normalize();const c=new w.Vector3().crossVectors(e,l).normalize();return{tangent:l,bitangent:c}}}class SP{engine;clippingTolerance=1e-4;sectionBox;sectionFace;clippingStencil;clippingCSGSimple=null;currentClippingMode="";fillCutFace=!0;constructor(e){this.engine=e;let t=new w.Plane(new w.Vector3(0,0,1),1e5);t.name="前";let i=new w.Plane(new w.Vector3(0,0,1),1e5);i.name="左";let s=new w.Plane(new w.Vector3(0,0,1),1e5);s.name="后";let r=new w.Plane(new w.Vector3(0,0,1),1e5);r.name="右";let o=new w.Plane(new w.Vector3(0,0,1),1e5);o.name="顶";let a=new w.Plane(new w.Vector3(0,0,1),1e5);a.name="底";let l=new w.Plane(new w.Vector3(0,0,1),1e5);l.name="face",this.engine.sectionPlane=[t,i,s,r,o,a,l]}init(){this.sectionBox=new BD(this.engine),this.sectionFace=new PD(this.engine),this.clippingCSGSimple=new wP(this.engine)}scaleBox(){let e=this.engine.octreeBox.getBoundingBox();this.sectionBox.setBox(e)}setFillCutFace(e){this.fillCutFace=e}getFillCutFace(){return this.fillCutFace}clippingModel(e){let t=[];e.forEach(r=>{let o=this.engine.models.find(a=>a.url===r.url);r.ids.forEach(a=>{o.nodesMap.get(a).infos.forEach(l=>{t.push(l.box)})})}),this.active("box");let i=s(t);this.sectionBox.setBox(i);function s(r){let o=new w.Vector3(1e8,1e9,1e10),a=new w.Vector3(-1e8,-1e9,-1e10);return r.forEach(l=>{l.min.x<o.x&&(o.x=l.min.x),l.min.y<o.y&&(o.y=l.min.y),l.min.z<o.z&&(o.z=l.min.z),l.max.x>a.x&&(a.x=l.max.x),l.max.y>a.y&&(a.y=l.max.y),l.max.z>a.z&&(a.z=l.max.z)}),new w.Box3(o,a)}}updateClippingValue(e){let t=this.sectionBox.maxBox,i=t.min.x+(t.max.x-t.min.x)*e.x.min*.01,s=t.min.y+(t.max.y-t.min.y)*e.y.min*.01,r=t.min.z+(t.max.z-t.min.z)*e.z.min*.01,o=t.min.x+(t.max.x-t.min.x)*e.x.max*.01,a=t.min.y+(t.max.y-t.min.y)*e.y.max*.01,l=t.min.z+(t.max.z-t.min.z)*e.z.max*.01;this.sectionBox.setboxXyz({minX:i,minY:s,minZ:r,maxX:o,maxY:a,maxZ:l})}active(e){if(this.engine.engineStatus.isForceFree=!0,this.sectionFace.disActive(),this.sectionBox.disActive(),this.currentClippingMode=e,e=="x")this.sectionFace.init(),this.sectionFace.active(),this.sectionFace.setFaceNormal(new w.Vector3(-1,0,0));else if(e=="y")this.sectionFace.init(),this.sectionFace.active(),this.sectionFace.setFaceNormal(new w.Vector3(0,0,-1));else if(e=="z")this.sectionFace.init(),this.sectionFace.active(),this.sectionFace.setFaceNormal(new w.Vector3(0,-1,0));else if(e=="box")this.sectionBox.init(),this.sectionBox.active();else if(e=="face"){let t=new LD(this.engine);t.init(),t.catch_face(i=>{this.sectionFace.init(),this.sectionFace.active();let s=this.engine.octreeBox.getBoundingBox(),r=s.min.clone().add(s.max.clone()).multiplyScalar(.5),o=i.position.clone().sub(r),a=new w.Vector3(i.dir.x,i.dir.y,i.dir.z),l=o.dot(a);this.sectionFace.setFaceNormal(i.dir,l)})}}disabled(){this.currentClippingMode=="box"?this.sectionBox.disabled():this.sectionFace.disabled(),this.engine.engineStatus.isForceFree=!1}recover(){this.currentClippingMode=="box"?this.sectionBox.recover():this.sectionFace.recover()}reverse(){this.sectionFace.reverse()}disActive(){this.sectionFace.disActive(),this.sectionBox.disActive(),this.clippingCSGSimple?.clear(),this.currentClippingMode="",this.engine.engineStatus.isForceFree=!1}isPointInClippingRange(e,t=this.clippingTolerance){if(!this.isVector3Like(e))return!1;const i=this.getEffectiveClippingPlanes();return i.length===0?!0:i.every(s=>s.distanceToPoint(e)>=-t)}filterIntersectionsByClipping(e,t=this.clippingTolerance){return!Array.isArray(e)||e.length===0?[]:e.filter(i=>this.isPointInClippingRange(i?.point,t))}getEffectiveClippingPlanes(){const e=Array.isArray(this.engine.sectionPlane)?this.engine.sectionPlane:[];if(this.currentClippingMode==="box")return e.slice(0,6).filter(t=>t instanceof w.Plane);if(this.currentClippingMode==="x"||this.currentClippingMode==="y"||this.currentClippingMode==="z"||this.currentClippingMode==="face"){const t=e[6];return t instanceof w.Plane?[t]:[]}return[]}isVector3Like(e){return e!=null&&typeof e.x=="number"&&typeof e.y=="number"&&typeof e.z=="number"}setSectionByView(e,t){this.sectionFace.disActive(),this.sectionBox.disActive(),this.scaleBox(),this.sectionFace.init(!0);const i=this.engine.octreeBox.getBoundingBox(),s=new w.Vector3((i.min.x+i.max.x)/2,(i.min.y+i.max.y)/2,(i.min.z+i.max.z)/2),o=new w.Vector3(t.x,t.y,t.z).normalize().clone().negate(),l=new w.Vector3(e.x,e.y,e.z).clone().sub(s).dot(o);this.sectionFace.setFaceNormalPlaneOnly(o,l),this.sectionFace.activateClippingOnly(),this.currentClippingMode="face"}}class CP{engine;constructor(e){this.engine=e}getLevelTreeData(){let e=[];return this.engine.engineStatus.models.forEach(t=>{e.push({children:t.info.modelTree.modelTreeLevel,name:t.info.baseInfo.name,url:t.url})}),e}getTypeTreeData(){let e=[];return this.engine.engineStatus.models.forEach(t=>{e.push({children:t.info.modelTree.modelTreeType,name:t.info.baseInfo.name,url:t.url})}),e}getMajorTreeData(){let e=[];return this.engine.engineStatus.models.forEach(t=>{e.push({children:t.info.modelTree.modelTreeMajor,name:t.info.baseInfo.name,url:t.url})}),e}}class MP{engine;constructor(e){this.engine=e}getEngineInfo(){let e=0,t=0,i=0;return!this.engine||!this.engine.scene?{totalVertices:0,totalTriangles:0,meshCount:0}:(this.engine.scene.traverse(s=>{if(s instanceof w.Mesh){const r=s.geometry;if(r&&r.attributes){const o=r.attributes.position;if(o){const a=o.count;e+=a;let l=0;r.index?l=r.index.count/3:l=a/3,t+=l}}}}),this.engine.engineStatus.models.forEach(s=>{i=i+(Array.isArray(s?.info?.modelEdge)?s.info.modelEdge.length:0)}),{totalVertices:Math.floor(e),totalTriangles:Math.floor(t),meshCount:i})}}class EP{engine;extended=new Map;constructor(e){this.engine=e}init(){}updateExtended(e,t){let i=this.extended.get(e);i==null?this.extended.set(e,t):t.forEach((s,r)=>{i.set(r,s)})}getModelPropertiesWithName(e,t,i,s){let r=this.extended.get(e),o=this.engine.engineStatus.models.find(l=>l.url===e);o.properties==null?ha(e+"/property",l=>{let c=JSON.parse(l);o.properties=c,setTimeout(()=>{a(c,i,t,s)},100)},()=>{},o?.key):a(o.properties,i,t,s);function a(l,c,h,d){let f={};l.models[h.toString()||""].forEach(g=>{i.includes(l.names[g[1]])&&(f[l.names[g[1]]]=l.values[g[2]])}),r!=null&&r.has(h)&&f.push(r.get(h)),d?.({id:h,properties:f})}}getModelProperties(e,t,i){let s=this.extended.get(e),r=this.engine.engineStatus.models.find(a=>a.url===e);r.properties==null&&ha(e+"/property",a=>{let l=JSON.parse(a);r.properties=l,setTimeout(()=>{o(l,t,i)},100)},()=>{},r?.key),o(r.properties,t,i);function o(a,l,c){let h=[],d=a.models[l.toString()||""],f=d.map(u=>u[0]);f=f.filter((u,g)=>f.indexOf(u)===g),f.forEach(u=>{let g={name:a.categorys[u],children:[]};h.push(g),d.filter(p=>p[0]===u).forEach(p=>{g.children.push({name:a.names[p[1]],value:a.values[p[2]]})})}),s!=null&&s.has(l)&&h.push(s.get(l)),c?.({properties:h,materials:h})}}}class IP{engine;constructor(e){this.engine=e}getModelTypes(){let e=[];return this.engine.engineStatus.models.forEach(t=>{t.info.modelMapper.forEach(s=>{e.push(s.typeName)})}),e=e.filter((t,i,s)=>s.indexOf(t)===i),e}getModelMajors(){let e=[];return this.engine.engineStatus.models.forEach(t=>{t.info.modelMapper.forEach(s=>{e.push(s.majorName)})}),e=e.filter((t,i,s)=>s.indexOf(t)===i),e}getModelLevels(){let e=[];return this.engine.engineStatus.models.forEach(t=>{t.info.modelMapper.forEach(s=>{e.push(s.levelName)})}),e=e.filter((t,i,s)=>s.indexOf(t)===i),e}getModelMappers(e){}getModelMapper(e,t){let i=this.engine.engineStatus.models.find(o=>o.url==e);return i?i.info.modelMapper.find(o=>o.id==t):null}getModelsWithLevelType(e,t,i=null){let s=[];return this.engine.engineStatus.models.forEach(r=>{let o={url:r.url,ids:[]};s.push(o),r.info.modelMapper.filter(l=>l.levelName===e&&l.typeName===t).forEach(l=>{o.ids.push(Number(l.id))})}),i&&i(s),s}getModelsWithType(e,t=null){let i=[];return this.engine.engineStatus.models.forEach(s=>{let r={url:s.url,ids:[]};i.push(r),s.info.modelMapper.filter(a=>a.typeName===e).forEach(a=>{r.ids.push(Number(a.id))})}),t&&t(i),i}getModelsWithLevel(e,t){let i=[];return this.engine.engineStatus.models.forEach(s=>{let r={url:s.url,ids:[]};i.push(r),s.info.modelMapper.filter(a=>a.levelName===e).forEach(a=>{r.ids.push(Number(a.id))})}),t&&t(i),i}getModelsWithMajor(e,t){let i=[];return this.engine.engineStatus.models.forEach(s=>{let r={url:s.url,ids:[]};i.push(r),s.info.modelMapper.filter(a=>a.majorName===e).forEach(a=>{r.ids.push(Number(a.id))})}),t&&t(i),i}}class TP{config;constructor(e){this.config={temperature:.7,maxTokens:2e4,timeout:3e5,...e}}async chat(e){const t=new AbortController,i=setTimeout(()=>t.abort(),this.config.timeout);try{const s=await fetch(`${this.config.baseURL}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({model:this.config.model,messages:e,temperature:this.config.temperature,max_tokens:this.config.maxTokens,stream:!1}),signal:t.signal});if(clearTimeout(i),!s.ok){const o=await s.json().catch(()=>({}));throw new Error(`API请求失败 (${s.status}): ${o.error?.message||o.message||s.statusText}`)}return(await s.json()).choices?.[0]?.message?.content||""}catch(s){throw clearTimeout(i),s.name==="AbortError"?new Error("请求超时,请重试"):s.message.includes("Failed to fetch")?new Error(`网络请求失败,请检查:
|
|
5261
5261
|
1. 网络连接
|
|
5262
5262
|
2. API地址是否正确
|
|
5263
5263
|
3. 是否有CORS限制`):s}}async chatStream(e,t){const i=new AbortController,s=setTimeout(()=>i.abort(),this.config.timeout);try{const r=await fetch(`${this.config.baseURL}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({model:this.config.model,messages:e,temperature:this.config.temperature,max_tokens:this.config.maxTokens,stream:!0}),signal:i.signal});if(clearTimeout(s),!r.ok){const c=await r.json().catch(()=>({}));throw new Error(`API请求失败 (${r.status}): ${c.error?.message||c.message||r.statusText}`)}const o=r.body?.getReader();if(!o)throw new Error("无法读取响应流");const a=new TextDecoder;let l="";for(;;){const{done:c,value:h}=await o.read();if(c){t("",!0);break}l+=a.decode(h,{stream:!0});const d=l.split(`
|
|
@@ -6053,7 +6053,7 @@ void main() {
|
|
|
6053
6053
|
color.b += max != color.b ? (max - color.b) * amt : 0.00;
|
|
6054
6054
|
gl_FragColor = color;
|
|
6055
6055
|
}
|
|
6056
|
-
`}applyTo2d({imageData:{data:n}}){let e=-this.vibrance;for(let t=0;t<n.length;t+=4){let i=n[t],s=n[t+1],r=n[t+2],o=Math.max(i,s,r),a=(i+s+r)/3,l=2*Math.abs(o-a)/255*e;n[t]+=o===i?0:(o-i)*l,n[t+1]+=o===s?0:(o-s)*l,n[t+2]+=o===r?0:(o-r)*l}}sendUniformData(n,e){n.uniform1f(e.uVibrance,-this.vibrance)}isNeutralState(){return this.vibrance===0}};K(dl,"type","Vibrance"),K(dl,"defaults",{vibrance:0}),K(dl,"uniformLocations",["uVibrance"]),ke.setClass(dl),La({BaseFilter:()=>zt,BlackWhite:()=>vR,BlendColor:()=>$a,BlendImage:()=>Ja,Blur:()=>Za,Brightness:()=>el,Brownie:()=>gR,ColorMatrix:()=>kr,Composed:()=>Hp,Contrast:()=>tl,Convolute:()=>il,Gamma:()=>nl,Grayscale:()=>sl,HueRotation:()=>zh,Invert:()=>rl,Kodachrome:()=>AR,Noise:()=>ol,Pixelate:()=>al,Polaroid:()=>bR,RemoveColor:()=>ll,Resize:()=>cl,Saturation:()=>hl,Sepia:()=>yR,Technicolor:()=>xR,Vibrance:()=>dl,Vintage:()=>mR});function CR(n,e,t="bim-snapshot.png"){const i=n?.renderer,s=i?.domElement;if(!i||!s||!e)return null;const r=s.width||s.clientWidth,o=s.height||s.clientHeight;if(r<=0||o<=0)return null;let a=MR(s,r,o);if(!ER(a)){const f=IR(n,r,o);f&&(a=f)}const l=document.createElement("canvas");l.width=r,l.height=o;const c=l.getContext("2d");if(!c)return null;c.drawImage(a,0,0,r,o),c.drawImage(e,0,0,r,o);const h=l.toDataURL("image/png"),d=document.createElement("a");return d.href=h,d.download=t.toLowerCase().endsWith(".png")?t:`${t}.png`,d.click(),h}function MR(n,e,t){const i=document.createElement("canvas");i.width=e,i.height=t;const s=i.getContext("2d");return s&&s.drawImage(n,0,0,e,t),i}function ER(n){const e=n.getContext("2d");if(!e||n.width<=0||n.height<=0)return!1;const t=Math.min(32,n.width),i=Math.min(32,n.height),s=Math.max(1,Math.floor(n.width/t)),r=Math.max(1,Math.floor(n.height/i));for(let o=0;o<n.height;o+=r)for(let a=0;a<n.width;a+=s){const l=e.getImageData(a,o,1,1).data;if(l[0]!==0||l[1]!==0||l[2]!==0||l[3]!==0)return!0}return!1}function IR(n,e,t){const i=n?.renderer,s=n?.scene,r=n?.camera;if(!i||!s||!r)return null;const o=new w.WebGLRenderTarget(e,t,{minFilter:w.LinearFilter,magFilter:w.LinearFilter,format:w.RGBAFormat,depthBuffer:!0,stencilBuffer:!0}),a=i.getRenderTarget(),l=i.autoClear,c=i.xr?.enabled??!1;try{i.xr&&(i.xr.enabled=!1),i.autoClear=!0,i.setRenderTarget(o),i.clear(!0,!0,!0),i.render(s,r);const h=new Uint8Array(e*t*4);return i.readRenderTargetPixels(o,0,0,e,t,h),TR(h,e,t)}catch{return null}finally{i.setRenderTarget(a),i.autoClear=l,i.xr&&(i.xr.enabled=c),o.dispose()}}function TR(n,e,t){const i=document.createElement("canvas");i.width=e,i.height=t;const s=i.getContext("2d");if(!s)return i;const r=s.createImageData(e,t),o=e*4;for(let a=0;a<t;a++){const l=(t-1-a)*o,c=a*o;for(let h=0;h<o;h++)r.data[c+h]=n[l+h]}return s.putImageData(r,0,0),i}const DR={none:new URL("/assets/icon/%E9%80%89%E6%8B%A9.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,line:new URL("/assets/icon/%E7%BA%BF.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,arrow:new URL("/assets/icon/%E7%AE%AD%E5%A4%B4.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,rect:new URL("/assets/icon/%E7%9F%A9%E5%BD%A2.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,circle:new URL("/assets/icon/%E5%9C%86%E5%BD%A2.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,text:new URL("/assets/icon/%E6%96%87%E5%AD%97.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,cloudline:new URL("/assets/icon/%E4%BA%91%E7%BA%BF.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href},BR=new URL("/assets/icon/%E6%B5%8B%E8%B7%9D.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,PR=new URL("/assets/icon/%E6%88%AA%E5%9B%BE.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,LR=new URL("/assets/icon/%E7%BA%BF%E5%AE%BD.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,RR=new URL("/assets/icon/%E5%AD%97%E5%8F%B7.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,kR=[{type:"distance",label:"距离"},{type:"clearDistance",label:"垂距"},{type:"clearHeight",label:"净高"},{type:"elevation",label:"标高"},{type:"point",label:"坐标"},{type:"angle",label:"角度"},{type:"area",label:"面积"},{type:"slope",label:"坡度"}],FR={distance:new URL("/assets/icon/%E8%B7%9D%E7%A6%BB.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,clearDistance:new URL("/assets/icon/%E5%87%80%E8%B7%9D.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,clearHeight:new URL("/assets/icon/%E5%87%80%E9%AB%98.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,elevation:new URL("/assets/icon/%E6%A0%87%E9%AB%98.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,point:new URL("/assets/icon/%E5%9D%90%E6%A0%87.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,angle:new URL("/assets/icon/%E8%A7%92%E5%BA%A6.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,area:new URL("/assets/icon/%E9%9D%A2%E7%A7%AF.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,slope:new URL("/assets/icon/%E5%9D%A1%E5%BA%A6.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href};class OR{constructor(e,t){this.handlers=e,this.root=document.createElement("div"),this.root.style.position="absolute",this.root.style.top="8px",this.root.style.left="50%",this.root.style.transform="translateX(-50%)",this.root.style.display="none",this.root.style.padding="6px",this.root.style.background="#ffffff",this.root.style.border="1px solid #d9d9d9",this.root.style.borderRadius="8px",this.root.style.pointerEvents="auto",this.root.style.userSelect="none",this.root.style.boxShadow="0 4px 14px rgba(0, 0, 0, 0.12)",this.root.style.zIndex="1300",this.editPanel=document.createElement("div"),this.editPanel.style.display="flex",this.editPanel.style.flexDirection="column",this.editPanel.style.gap="6px",this.viewPanel=document.createElement("div"),this.viewPanel.style.display="none",this.viewPanel.style.alignItems="center",this.viewPanel.style.gap="6px";const i=document.createElement("div");i.style.display="flex",i.style.alignItems="center",i.style.gap="6px",i.style.flexWrap="wrap",[{type:"none",label:"选择"},{type:"line",label:"线"},{type:"arrow",label:"箭头"},{type:"rect",label:"矩形"},{type:"circle",label:"圆形"},{type:"text",label:"文字"},{type:"cloudline",label:"云线"}].forEach(c=>{const h=this.createIconButton(c.label,DR[c.type]);h.onclick=()=>this.handlers.onDrawTypeChange(c.type),this.drawButtons[c.type]=h,i.appendChild(h)}),this.colorInput=document.createElement("input"),this.colorInput.type="color",this.colorInput.value=t.stroke,this.colorInput.style.width="32px",this.colorInput.style.height="24px",this.colorInput.style.padding="0",this.colorInput.style.border="1px solid #d9d9d9",this.colorInput.style.borderRadius="4px",this.colorInput.style.background="#ffffff",this.colorInput.oninput=()=>this.handlers.onColorChange(this.colorInput.value),i.appendChild(this.createField("",this.colorInput)),this.strokeWidthInput=document.createElement("input"),this.strokeWidthInput.type="number",this.strokeWidthInput.min="1",this.strokeWidthInput.max="20",this.strokeWidthInput.step="1",this.strokeWidthInput.value=String(t.strokeWidth),this.strokeWidthInput.style.width="46px",this.strokeWidthInput.oninput=()=>this.handlers.onStrokeWidthChange(this.strokeWidthInput.value),i.appendChild(this.createField("",this.strokeWidthInput,LR,"线宽")),this.fontSizeInput=document.createElement("input"),this.fontSizeInput.type="number",this.fontSizeInput.min="10",this.fontSizeInput.max="96",this.fontSizeInput.step="1",this.fontSizeInput.value=String(t.fontSize),this.fontSizeInput.style.width="46px",this.fontSizeInput.oninput=()=>this.handlers.onFontSizeChange(this.fontSizeInput.value),i.appendChild(this.createField("",this.fontSizeInput,RR,"字号")),this.distanceButton=this.createIconButton("测量",BR),this.distanceButton.onclick=()=>this.handlers.onMeasureToggle(),i.appendChild(this.distanceButton);const r=this.createIconButton("截图",PR);r.onclick=()=>this.handlers.onScreenshot(),i.appendChild(r);const o=this.createTextButton("×","取消");o.onclick=()=>this.handlers.onCancel(),o.style.background="#ff4d4f",o.style.borderColor="#ff4d4f",o.style.color="#ffffff",i.appendChild(o);const a=this.createTextButton("✔","确定");a.onclick=()=>this.handlers.onConfirm(),a.style.background="#52c41a",a.style.borderColor="#52c41a",a.style.color="#ffffff",i.appendChild(a),this.measureSubPanel=document.createElement("div"),this.measureSubPanel.style.display="none",this.measureSubPanel.style.alignItems="center",this.measureSubPanel.style.gap="6px",this.measureSubPanel.style.flexWrap="wrap",this.measureSubPanel.style.paddingTop="2px",kR.forEach(c=>{const h=this.createSmallIconButton(c.label,FR[c.type]);h.onclick=()=>this.handlers.onMeasureTypeChange(c.type),this.measureTypeButtons[c.type]=h,this.measureSubPanel.appendChild(h)}),this.editPanel.appendChild(i),this.editPanel.appendChild(this.measureSubPanel);const l=this.createTextButton("关闭","关闭");l.onclick=()=>this.handlers.onClose(),this.viewPanel.appendChild(l),this.root.appendChild(this.editPanel),this.root.appendChild(this.viewPanel),this.setMode("edit")}root;drawButtons={};measureTypeButtons={};distanceButton;colorInput;strokeWidthInput;fontSizeInput;editPanel;viewPanel;measureSubPanel;mode="edit";mount(e){e.appendChild(this.root)}show(){this.root.style.display="block"}hide(){this.root.style.display="none"}setMode(e){this.mode=e,this.editPanel.style.display=e==="edit"?"flex":"none",this.viewPanel.style.display=e==="view"?"flex":"none",e==="view"&&this.setMeasurePanelVisible(!1)}setDrawType(e){for(const t in this.drawButtons){const i=this.drawButtons[t];if(!i)continue;const s=t===e;i.style.background=s?"#eaf2ff":"#ffffff",i.style.borderColor=s?"#2f80ed":"#d9d9d9"}}setMeasurePanelVisible(e){if(this.mode!=="edit"){this.measureSubPanel.style.display="none";return}this.measureSubPanel.style.display=e?"flex":"none"}setMeasureState(e,t){this.distanceButton.style.background=e?"#eaf2ff":"#ffffff",this.distanceButton.style.borderColor=e?"#2f80ed":"#d9d9d9";for(const i in this.measureTypeButtons){const s=this.measureTypeButtons[i];if(!s)continue;const r=e&&t===i;s.style.background=r?"#eaf2ff":"#ffffff",s.style.borderColor=r?"#2f80ed":"#d9d9d9"}}setStyleValues(e){e.stroke&&(this.colorInput.value=e.stroke),typeof e.strokeWidth=="number"&&(this.strokeWidthInput.value=String(e.strokeWidth)),typeof e.fontSize=="number"&&(this.fontSizeInput.value=String(e.fontSize))}dispose(){this.colorInput.oninput=null,this.strokeWidthInput.oninput=null,this.fontSizeInput.oninput=null,this.root.remove()}createField(e,t,i,s=""){const r=document.createElement("div");if(r.style.display="flex",r.style.alignItems="center",r.style.gap="4px",r.style.padding="0 2px",r.style.color="#333333",r.style.fontSize="12px",e){const o=document.createElement("span");o.textContent=e,r.appendChild(o)}if(i){const o=document.createElement("img");o.src=i,o.alt=s,o.style.width="14px",o.style.height="14px",o.style.display="block",r.appendChild(o)}return t.style.height="24px",t.style.border="1px solid #d9d9d9",t.style.borderRadius="4px",t.style.background="#ffffff",t.style.color="#333333",t.style.outline="none",t.style.padding="0 4px",r.appendChild(t),r}createIconButton(e,t){const i=document.createElement("button");i.type="button",i.style.width="28px",i.style.height="28px",i.style.padding="0",i.style.display="flex",i.style.alignItems="center",i.style.justifyContent="center",i.style.border="1px solid #d9d9d9",i.style.borderRadius="4px",i.style.background="#ffffff",i.style.cursor="pointer";const s=document.createElement("img");return s.src=t,s.alt=e,s.style.width="16px",s.style.height="16px",s.style.display="block",i.appendChild(s),i}createSmallIconButton(e,t){const i=document.createElement("button");i.type="button",i.style.width="26px",i.style.height="26px",i.style.padding="0",i.style.display="flex",i.style.alignItems="center",i.style.justifyContent="center",i.style.border="1px solid #d9d9d9",i.style.borderRadius="4px",i.style.background="#ffffff",i.style.cursor="pointer";const s=document.createElement("img");return s.src=t,s.alt=e,s.style.width="14px",s.style.height="14px",s.style.display="block",i.appendChild(s),i}createTextButton(e,t){const i=document.createElement("button");return i.type="button",i.textContent=e,i.style.width="28px",i.style.height="28px",i.style.padding="0 10px",i.style.border="1px solid #d9d9d9",i.style.borderRadius="4px",i.style.background="#ffffff",i.style.color="#333333",i.style.fontSize="13px",i.style.lineHeight="1",i.style.cursor="pointer",i}}class UR{engine;wrapper;canvasEl;canvas;toolbar;isActive=!1;isVisible=!0;isDistanceMeasureMode=!1;isMeasurePanelExpanded=!1;drawType="none";mode="edit";currentMeasureType=null;sessionSnapshot=null;actionHandlers={};drawStyle={stroke:"#ff4d4f",strokeWidth:2,fill:"rgba(255, 77, 79, 0.08)",fontSize:16,text:"文本",cloudRadius:10};startPoint=null;tempObject=null;cloudPoints=[];onMouseDown=e=>this.handleMouseDown(e);onMouseMove=e=>this.handleMouseMove(e);onMouseUp=e=>this.handleMouseUp(e);onMouseDblClick=e=>this.handleMouseDblClick(e);onSelectionChanged=()=>this.syncStyleFromSelection();onKeyDown=e=>this.handleKeyDown(e);constructor(e){this.engine=e;const t=this.engine.container;if(!t)throw new Error("FabricDraw: engine container not found.");this.wrapper=document.createElement("div"),this.wrapper.className="fabric-draw-layer",this.wrapper.style.position="absolute",this.wrapper.style.left="0",this.wrapper.style.top="0",this.wrapper.style.right="0",this.wrapper.style.bottom="0",this.wrapper.style.zIndex="1200",this.wrapper.style.pointerEvents="none",this.canvasEl=document.createElement("canvas"),this.canvasEl.style.width="100%",this.canvasEl.style.height="100%",this.wrapper.appendChild(this.canvasEl),this.toolbar=new OR({onDrawTypeChange:i=>this.setDrawType(i),onMeasureToggle:()=>this.toggleMeasurePanel(),onMeasureTypeChange:i=>this.activateDistanceMeasure(i),onScreenshot:()=>{this.saveScreenshot(this.createScreenshotFileName())},onColorChange:i=>this.handleColorInputChange(i),onStrokeWidthChange:i=>this.handleStrokeWidthInputChange(i),onFontSizeChange:i=>this.handleFontSizeInputChange(i),onCancel:()=>{this.handleCancelClick()},onConfirm:()=>this.handleConfirmClick(),onClose:()=>{this.handleCloseClick()}},{stroke:this.drawStyle.stroke,strokeWidth:this.drawStyle.strokeWidth,fontSize:this.drawStyle.fontSize}),this.toolbar.mount(this.wrapper),t.appendChild(this.wrapper),this.canvas=new Up(this.canvasEl,{selection:!0,preserveObjectStacking:!0}),this.resize(),this.canvas.on("mouse:down",this.onMouseDown),this.canvas.on("mouse:move",this.onMouseMove),this.canvas.on("mouse:up",this.onMouseUp),this.canvas.on("mouse:dblclick",this.onMouseDblClick),this.canvas.on("selection:created",this.onSelectionChanged),this.canvas.on("selection:updated",this.onSelectionChanged),this.canvas.on("selection:cleared",this.onSelectionChanged),window.addEventListener("keydown",this.onKeyDown),this.refreshToolbarState()}active(e="edit"){this.isActive=!0,this.mode=e,this.drawType="none",this.isMeasurePanelExpanded=!1,this.currentMeasureType=null,this.canvas.defaultCursor="default",this.sessionSnapshot=e==="edit"?this.cloneJson(this.getAllShapes()):null,this.toolbar.setMode(e),this.applyCanvasInteractive(e==="edit"),this.isVisible&&this.toolbar.show(),this.updateOverlayPointerEvents(),this.refreshToolbarState()}disActive(){this.isActive=!1,this.startPoint=null,this.cloudPoints=[],this.tempObject=null,this.drawType="none",this.mode="edit",this.isMeasurePanelExpanded=!1,this.currentMeasureType=null,this.sessionSnapshot=null,this.stopDistanceMeasureMode(),this.canvas.defaultCursor="default",this.canvas.discardActiveObject(),this.applyCanvasInteractive(!0),this.canvas.requestRenderAll(),this.toolbar.setMode("edit"),this.toolbar.hide(),this.updateOverlayPointerEvents(),this.refreshToolbarState()}close(){this.disActive()}hide(){this.isVisible=!1,this.wrapper.style.display="none",this.toolbar.hide()}show(){this.isVisible=!0,this.wrapper.style.display="block",this.isActive&&this.toolbar.show(),this.resize()}isShown(){return this.isVisible}setDrawType(e,t){this.mode!=="view"&&(this.stopDistanceMeasureMode(),this.isMeasurePanelExpanded=!1,this.currentMeasureType=null,this.drawType=e,t&&(this.drawStyle={...this.drawStyle,...t}),this.canvas.defaultCursor=e==="none"?"default":"crosshair",this.updateOverlayPointerEvents(),this.refreshToolbarState())}getDrawType(){return this.drawType}setActionHandlers(e){this.actionHandlers={...e}}drawLine(e,t,i){const s=this.mergeStyle(i),r=this.createLineObject(e,t,s,!0);return this.canvas.add(r),this.canvas.requestRenderAll(),r}drawArrow(e,t,i){const s=this.mergeStyle(i),r=this.createArrowObject(e,t,s,!0);return this.canvas.add(r),this.canvas.requestRenderAll(),r}drawRect(e,t,i){const s=this.mergeStyle(i),r=this.createRectObject(e,t,s,!0);return this.canvas.add(r),this.canvas.requestRenderAll(),r}drawCircle(e,t,i){const s=this.mergeStyle(i),r=this.createCircleObject(e,t,s,!0);return this.canvas.add(r),this.canvas.requestRenderAll(),r}drawText(e,t,i){const s=this.mergeStyle(i),r=new Lr(t??s.text,{left:e.x,top:e.y,fontSize:s.fontSize,fill:s.stroke,selectable:!0,evented:!0,objectCaching:!1});return r.annotationType="text",this.canvas.add(r),this.canvas.requestRenderAll(),r}drawCloudLine(e,t){if(e.length<2)return null;const i=this.mergeStyle(t),s=this.createCloudObject(e,i,!0);return s?(this.canvas.add(s),this.canvas.requestRenderAll(),s):null}getAllShapes(){return this.canvas.toObject(["annotationType"])}clearAllShapes(){this.canvas.clear(),this.canvas.requestRenderAll()}async restoreAllShapes(e){await this.canvas.loadFromJSON(e),this.canvas.requestRenderAll()}saveScreenshot(e="bim-snapshot.png"){const t=this.canvas.lowerCanvasEl;return t?CR(this.engine,t,e):null}resize(e,t){const i=this.engine.container;if(!i)return;const s=e??i.clientWidth??1,r=t??i.clientHeight??1;this.canvas.setDimensions({width:s,height:r}),this.canvas.requestRenderAll()}dispose(){this.stopDistanceMeasureMode(),window.removeEventListener("keydown",this.onKeyDown),this.canvas.off("mouse:down",this.onMouseDown),this.canvas.off("mouse:move",this.onMouseMove),this.canvas.off("mouse:up",this.onMouseUp),this.canvas.off("mouse:dblclick",this.onMouseDblClick),this.canvas.off("selection:created",this.onSelectionChanged),this.canvas.off("selection:updated",this.onSelectionChanged),this.canvas.off("selection:cleared",this.onSelectionChanged),this.toolbar.dispose(),this.canvas.dispose(),this.wrapper.remove()}handleMouseDown(e){if(!this.isActive||this.mode==="view"||this.drawType==="none"||e?.target)return;const t=this.getPointFromEvent(e);if(this.drawType==="text"){const s=this.drawText(t);this.canvas.setActiveObject(s),this.canvas.requestRenderAll(),setTimeout(()=>{s.enterEditing(),s.hiddenTextarea?.focus(),s.selectAll()},0);return}this.startPoint=t,this.cloudPoints=[t],this.canvas.selection=!1,this.canvas.discardActiveObject();const i=this.createDraftObject(t,t);i&&(this.tempObject=i,this.canvas.add(i),this.canvas.requestRenderAll())}handleMouseMove(e){if(!this.isActive||this.mode==="view"||!this.startPoint||!this.tempObject)return;const t=this.getPointFromEvent(e),i=this.drawStyle;if(this.drawType==="cloudline"){if(this.shouldAppendCloudPoint(t)){this.cloudPoints.push(t),this.canvas.remove(this.tempObject);const s=this.createCloudObject(this.cloudPoints,i,!1);if(!s)return;this.tempObject=s,this.canvas.add(s),this.canvas.requestRenderAll()}return}if(this.drawType==="arrow"){this.canvas.remove(this.tempObject),this.tempObject=this.createArrowObject(this.startPoint,t,i,!1),this.canvas.add(this.tempObject),this.canvas.requestRenderAll();return}this.updateDraftObject(this.startPoint,t),this.canvas.requestRenderAll()}handleMouseUp(e){if(!this.isActive||this.mode==="view"||!this.startPoint)return;const t=this.getPointFromEvent(e);this.drawType==="cloudline"&&this.cloudPoints.length===1&&(this.cloudPoints.push(t),this.canvas.remove(this.tempObject),this.tempObject=this.createCloudObject(this.cloudPoints,this.drawStyle,!0),this.tempObject&&this.canvas.add(this.tempObject)),this.tempObject&&(this.tempObject.set({selectable:!0,evented:!0}),this.tempObject.setCoords?.(),this.canvas.requestRenderAll()),this.startPoint=null,this.tempObject=null,this.cloudPoints=[],this.canvas.selection=!0}handleMouseDblClick(e){const t=e?.target;this.isTextObject(t)&&(t.enterEditing(),t.hiddenTextarea?.focus(),t.selectAll?.())}handleKeyDown(e){if(!this.isActive)return;const t=this.canvas.getActiveObject();if(this.isTextObject(t)&&t?.isEditing||this.isInputElement(e.target))return;if(e.key==="Escape"){e.preventDefault(),this.mode==="view"?this.handleCloseClick():this.handleCancelClick();return}if(e.key==="Enter"){this.mode==="edit"&&(e.preventDefault(),this.handleConfirmClick());return}if(e.key!=="Delete"&&e.key!=="Backspace"||!t)return;e.preventDefault(),this.canvas.getActiveObjects().forEach(r=>this.canvas.remove(r)),this.canvas.discardActiveObject(),this.canvas.requestRenderAll()}getPointFromEvent(e){if(e?.e){const i=this.canvas.getScenePoint(e.e);return{x:i.x,y:i.y}}const t=e?.scenePoint??e?.pointer??e?.absolutePointer;return t?{x:t.x,y:t.y}:{x:0,y:0}}shouldAppendCloudPoint(e){if(this.cloudPoints.length===0)return!0;const t=this.cloudPoints[this.cloudPoints.length-1],i=e.x-t.x,s=e.y-t.y;return Math.sqrt(i*i+s*s)>=6}createDraftObject(e,t){const i=this.drawStyle;switch(this.drawType){case"line":return this.createLineObject(e,t,i,!1);case"arrow":return this.createArrowObject(e,t,i,!1);case"rect":return this.createRectObject(e,t,i,!1);case"circle":return this.createCircleObject(e,t,i,!1);case"cloudline":return this.createCloudObject([e,t],i,!1);default:return null}}updateDraftObject(e,t){if(this.tempObject){if(this.drawType==="line"){this.tempObject.set({x2:t.x,y2:t.y});return}if(this.drawType==="rect"){const i=this.getBoxFromPoints(e,t);this.tempObject.set({left:i.left,top:i.top,width:i.width,height:i.height});return}if(this.drawType==="circle"){const i=this.getCircleFromPoints(e,t);this.tempObject.set({left:i.left,top:i.top,radius:i.radius})}}}mergeStyle(e){return{...this.drawStyle,...e??{}}}createObjectBase(e,t){return{stroke:e.stroke,strokeWidth:e.strokeWidth,fill:e.fill,selectable:t,evented:t,objectCaching:!1}}createLineObject(e,t,i,s){const r=new js([e.x,e.y,t.x,t.y],{...this.createObjectBase(i,s),fill:"",strokeLineCap:"round"});return r.annotationType="line",r}createRectObject(e,t,i,s){const r=this.getBoxFromPoints(e,t),o=new Gs({...this.createObjectBase(i,s),left:r.left,top:r.top,width:r.width,height:r.height,originX:"left",originY:"top"});return o.annotationType="rect",o}createCircleObject(e,t,i,s){const r=this.getCircleFromPoints(e,t),o=new Pr({...this.createObjectBase(i,s),left:r.left,top:r.top,radius:r.radius,originX:"left",originY:"top"});return o.annotationType="circle",o}createArrowObject(e,t,i,s){const r=t.x-e.x,o=t.y-e.y,a=Math.sqrt(r*r+o*o);if(a<1e-6){const D=new js([e.x,e.y,t.x,t.y],{stroke:i.stroke,strokeWidth:i.strokeWidth,fill:"",selectable:s,evented:s}),M=new Vs([D],{selectable:s,evented:s,objectCaching:!1});return M.annotationType="arrow",M}const l=r/a,c=o/a,h=-c,d=l,f=Math.max(10,i.strokeWidth*6),u=f*.72,g=t.x-l*f,p=t.y-c*f,m=g+h*(u*.5),A=p+d*(u*.5),x=g-h*(u*.5),b=p-d*(u*.5),y=new js([e.x,e.y,t.x,t.y],{stroke:i.stroke,strokeWidth:i.strokeWidth,fill:"",strokeLineCap:"round",selectable:!1,evented:!1}),_=`M ${t.x} ${t.y} L ${m} ${A} L ${x} ${b} Z`,S=new Br(_,{fill:i.stroke,stroke:i.stroke,strokeWidth:1,selectable:!1,evented:!1,objectCaching:!1}),C=new Vs([y,S],{selectable:s,evented:s,objectCaching:!1});return C.annotationType="arrow",C}createCloudObject(e,t,i){const s=this.buildCloudPath(e,t.cloudRadius);if(!s)return null;const r=new Br(s,{stroke:t.stroke,strokeWidth:t.strokeWidth,fill:"",strokeLineCap:"round",strokeLineJoin:"round",selectable:i,evented:i});return r.annotationType="cloudline",r}getBoxFromPoints(e,t){return{left:Math.min(e.x,t.x),top:Math.min(e.y,t.y),width:Math.abs(t.x-e.x),height:Math.abs(t.y-e.y)}}getCircleFromPoints(e,t){const i=t.x-e.x,s=t.y-e.y,r=Math.max(Math.abs(i),Math.abs(s)),o=i>=0?e.x:e.x-r,a=s>=0?e.y:e.y-r;return{left:o,top:a,radius:Math.max(r/2,1)}}buildCloudPath(e,t){if(e.length<2)return"";const i=Math.max(2,t),s=i*1.4;let r=`M ${e[0].x} ${e[0].y}`,o=1;for(let a=1;a<e.length;a++){const l=e[a-1],c=e[a],h=c.x-l.x,d=c.y-l.y,f=Math.sqrt(h*h+d*d);if(f<.1)continue;const u=-d/f,g=h/f,p=Math.max(1,Math.round(f/s));for(let m=1;m<=p;m++){const A=m/p,x=l.x+h*A,b=l.y+d*A,y=o%2===0?-1:1,_=x+u*i*y,S=b+g*i*y;r+=` Q ${_} ${S} ${x} ${b}`,o++}}return r}handleColorInputChange(e){this.drawStyle.stroke=e||this.drawStyle.stroke,this.drawStyle.fill=this.colorToAlpha(this.drawStyle.stroke,.08),this.applyCurrentStyleToSelection(),this.refreshToolbarStyleValues()}handleStrokeWidthInputChange(e){const t=this.parseNumber(e,this.drawStyle.strokeWidth,1,20);this.drawStyle.strokeWidth=t,this.applyCurrentStyleToSelection(),this.refreshToolbarStyleValues()}handleFontSizeInputChange(e){const t=this.parseNumber(e,this.drawStyle.fontSize,10,96);this.drawStyle.fontSize=t,this.applyCurrentStyleToSelection(),this.refreshToolbarStyleValues()}applyCurrentStyleToSelection(){const e=this.canvas.getActiveObjects();e.length!==0&&(e.forEach(t=>this.applyStyleToObject(t)),this.canvas.requestRenderAll())}applyStyleToObject(e){if(!e)return;if(e.annotationType==="arrow"&&Array.isArray(e._objects)){e._objects.forEach(i=>{if(i?.type==="triangle"||i?.type==="path"){i.set({fill:this.drawStyle.stroke,stroke:this.drawStyle.stroke,strokeWidth:1});return}i?.set({stroke:this.drawStyle.stroke,strokeWidth:this.drawStyle.strokeWidth,strokeLineCap:"round"})}),e.set({dirty:!0}),e.setCoords?.();return}if(this.isTextObject(e)){e.set({fill:this.drawStyle.stroke,fontSize:this.drawStyle.fontSize}),e.setCoords?.();return}const t={stroke:this.drawStyle.stroke,strokeWidth:this.drawStyle.strokeWidth};e?.type==="line"||e?.type==="path"?t.fill="":t.fill=this.drawStyle.fill,e.set(t),e.setCoords?.()}syncStyleFromSelection(){const e=this.canvas.getActiveObject();if(!e)return;const t=this.readStyleFromObject(e);t.stroke&&(this.drawStyle.stroke=t.stroke,this.drawStyle.fill=this.colorToAlpha(t.stroke,.08)),typeof t.strokeWidth=="number"&&(this.drawStyle.strokeWidth=t.strokeWidth),typeof t.fontSize=="number"&&(this.drawStyle.fontSize=t.fontSize),this.refreshToolbarStyleValues()}readStyleFromObject(e){if(!e)return{};if(e.annotationType==="arrow"&&Array.isArray(e._objects)){const t=e._objects.find(i=>i?.type==="line")??e._objects[0];return{stroke:t?.stroke,strokeWidth:t?.strokeWidth}}return this.isTextObject(e)?{stroke:e.fill??this.drawStyle.stroke,fontSize:e.fontSize??this.drawStyle.fontSize}:{stroke:e.stroke??this.drawStyle.stroke,strokeWidth:e.strokeWidth??this.drawStyle.strokeWidth}}isTextObject(e){return e?e.type==="i-text"||e.type==="textbox"||e.annotationType==="text":!1}isInputElement(e){const t=e;if(!t||!t.tagName)return!1;const i=t.tagName.toLowerCase();return i==="input"||i==="textarea"||!!t.isContentEditable}applyCanvasInteractive(e){this.canvas.selection=e,this.canvas.getObjects().forEach(t=>{t.set({selectable:e,evented:e}),t.setCoords?.()}),this.canvas.discardActiveObject(),this.canvas.requestRenderAll()}parseNumber(e,t,i,s){const r=Number(e);return Number.isFinite(r)?Math.min(s,Math.max(i,r)):t}colorToAlpha(e,t){const i=e.trim(),s=/^#([0-9a-fA-F]{3})$/.exec(i);if(s){const o=s[1],a=parseInt(o[0]+o[0],16),l=parseInt(o[1]+o[1],16),c=parseInt(o[2]+o[2],16);return`rgba(${a}, ${l}, ${c}, ${t})`}const r=/^#([0-9a-fA-F]{6})$/.exec(i);if(r){const o=r[1],a=parseInt(o.slice(0,2),16),l=parseInt(o.slice(2,4),16),c=parseInt(o.slice(4,6),16);return`rgba(${a}, ${l}, ${c}, ${t})`}return this.drawStyle.fill}toggleMeasurePanel(){!this.isActive||this.mode!=="edit"||(this.isMeasurePanelExpanded=!this.isMeasurePanelExpanded,this.refreshToolbarState())}activateDistanceMeasure(e){if(!this.isActive||this.mode!=="edit")return;this.drawType="none",this.canvas.defaultCursor="default",this.isDistanceMeasureMode=!0,this.isMeasurePanelExpanded=!0,this.currentMeasureType=e,this.canvas.discardActiveObject(),this.canvas.requestRenderAll();const t=this.engine.measure;t?.active?.(),this.disActiveMeasureTools(t),this.activeMeasureTool(t,e),this.updateOverlayPointerEvents(),this.refreshToolbarState()}stopDistanceMeasureMode(){if(!this.isDistanceMeasureMode)return;const e=this.engine.measure;this.disActiveMeasureTools(e),this.isDistanceMeasureMode=!1,this.currentMeasureType=null,this.updateOverlayPointerEvents(),this.refreshToolbarState()}disActiveMeasureTools(e){e?.distanceMeasure?.disActive?.(),e?.clearDistanceMeasure?.disActive?.(),e?.clearHeightMeasure?.disActive?.(),e?.elevationMeasure?.disActive?.(),e?.pointMeasure?.disActive?.(),e?.angleMeasure?.disActive?.(),e?.areaMeasure?.disActive?.(),e?.slopeMeasure?.disActive?.()}activeMeasureTool(e,t){const s={distance:"distanceMeasure",clearDistance:"clearDistanceMeasure",clearHeight:"clearHeightMeasure",elevation:"elevationMeasure",point:"pointMeasure",angle:"angleMeasure",area:"areaMeasure",slope:"slopeMeasure"}[t];s&&e?.[s]?.active?.()}updateOverlayPointerEvents(){if(!this.isActive){this.wrapper.style.pointerEvents="none",this.canvasEl.style.pointerEvents="none";return}if(this.mode==="view"||this.isDistanceMeasureMode){this.wrapper.style.pointerEvents="none",this.canvasEl.style.pointerEvents="none",this.toolbar.root.style.pointerEvents="auto";return}this.wrapper.style.pointerEvents="auto",this.canvasEl.style.pointerEvents="auto",this.toolbar.root.style.pointerEvents="auto"}async handleCancelClick(){this.sessionSnapshot&&await this.restoreAllShapes(this.cloneJson(this.sessionSnapshot)),this.actionHandlers.onCancel?.(),this.disActive()}async handleCloseClick(){this.disActive()}handleConfirmClick(){const e=this.cloneJson(this.getAllShapes());this.actionHandlers.onConfirm?.(e),this.disActive()}refreshToolbarStyleValues(){this.toolbar.setStyleValues({stroke:this.drawStyle.stroke,strokeWidth:this.drawStyle.strokeWidth,fontSize:this.drawStyle.fontSize})}refreshToolbarState(){this.toolbar.setDrawType(this.drawType),this.toolbar.setMode(this.mode),this.toolbar.setMeasurePanelVisible(this.isMeasurePanelExpanded),this.toolbar.setMeasureState(this.isDistanceMeasureMode,this.currentMeasureType),this.refreshToolbarStyleValues()}createScreenshotFileName(){const e=new Date,t=e.getFullYear(),i=String(e.getMonth()+1).padStart(2,"0"),s=String(e.getDate()).padStart(2,"0"),r=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),a=String(e.getSeconds()).padStart(2,"0");return`bim-snapshot-${t}${i}${s}-${r}${o}${a}.png`}cloneJson(e){return JSON.parse(JSON.stringify(e))}}class NR{engine;constructor(e){this.engine=e}get(){return{cameraPose:this.engine.cameraModule?.getCameraPose?.()??null,clipping:this.captureClippingState(),measureData:this.captureMeasureData(),annotationData:this.captureAnnotationData()}}async restore(e,t="view"){e&&(e.cameraPose&&this.engine.cameraModule?.restoreCameraPose?.(e.cameraPose),this.restoreClippingState(e.clipping),this.restoreMeasureData(e.measureData),await this.restoreAnnotationData(e.annotationData),this.applyAnnotationMode(t))}create(e){const t=this.engine.fabricDraw;if(!t){e?.(this.get());return}t.setActionHandlers({onConfirm:i=>{const s=this.get();s.annotationData=this.serializeSnapshotValue(i),e?.(s),this.clearAnnotation()},onCancel:()=>{this.clearAnnotation()}}),t.show?.(),t.active?.("edit"),t.setDrawType?.("none")}clearAnnotation(){this.engine.fabricDraw?.clearAllShapes?.(),this.engine.measure.disActive?.()}captureClippingState(){const e=this.engine.clipping,t=e?.sectionFace,i=e?.currentClippingMode??"",s={mode:i,fillCutFace:e?.getFillCutFace?.()??!0};if(i==="box"&&e?.sectionBox?.getboxXyz&&(s.box=e.sectionBox.getboxXyz()),i==="x"||i==="y"||i==="z"||i==="face"){const r=t?.normal;r&&(s.face={normal:{x:Number(r.x)||0,y:Number(r.y)||0,z:Number(r.z)||1},distance:Number(t?.distance)||0,direction:Number(t?.direction)===-1?-1:1})}return s}restoreClippingState(e){const t=this.engine.clipping;if(!t)return;typeof e?.fillCutFace=="boolean"&&t.setFillCutFace?.(e.fillCutFace);const i=e?.mode??"";if(!i){t.disActive?.();return}if(i==="box"){t.active?.("box"),e.box&&t.sectionBox?.setboxXyz?.(e.box);return}if(i==="x"||i==="y"||i==="z"){t.active?.(i),this.applyFaceState(e.face);return}if(i==="face"){this.restoreFaceMode(e.face);return}t.active?.(i)}restoreFaceMode(e){const t=this.engine.clipping,i=t?.sectionFace;!t||!i||(t.sectionBox?.disActive?.(),i.disActive?.(),i.active?.(),t.currentClippingMode="face",this.applyFaceState(e))}applyFaceState(e){if(!e)return;const t=this.engine.clipping?.sectionFace;if(!t)return;const i=new w.Vector3(e.normal.x,e.normal.y,e.normal.z).normalize();t.direction=e.direction===-1?-1:1,t.setFaceNormal?.(i,e.distance??0)}captureMeasureData(){const e=this.engine.measure?.annotationData;return e?this.serializeSnapshotValue(e):null}restoreMeasureData(e){const t=this.engine.measure;if(!t)return;try{t.clearAll?.()}catch{}if(!e)return;const i=this.deserializeSnapshotValue(e);(!t.annotationData||typeof t.annotationData!="object")&&(t.annotationData={}),Object.keys(t.annotationData).forEach(s=>{t.annotationData[s]=[]}),Object.keys(i).forEach(s=>{t.annotationData[s]=Array.isArray(i[s])?i[s]:[]}),t.tools?.drawNormalAnnotation?.()}captureAnnotationData(){const e=this.engine.fabricDraw;return e?.getAllShapes?this.serializeSnapshotValue(e.getAllShapes()):null}async restoreAnnotationData(e){const t=this.engine.fabricDraw;if(!t)return;if(!e){t.clearAllShapes?.();return}const i=this.deserializeSnapshotValue(e);await t.restoreAllShapes?.(i)}applyAnnotationMode(e){const t=this.engine.fabricDraw;t&&(t.setActionHandlers?.({}),t.show?.(),t.active?.(e),t.setDrawType?.("none"))}serializeSnapshotValue(e){if(e==null)return e;if(e instanceof w.Vector3)return{__type:"Vector3",x:e.x,y:e.y,z:e.z};if(Array.isArray(e))return e.map(t=>this.serializeSnapshotValue(t));if(typeof e=="object"){if(e instanceof HTMLElement||e instanceof SVGElement)return;const t={};return Object.keys(e).forEach(i=>{if(i==="container")return;const s=this.serializeSnapshotValue(e[i]);s!==void 0&&(t[i]=s)}),t}if(typeof e!="function")return e}deserializeSnapshotValue(e){if(e==null)return e;if(Array.isArray(e))return e.map(t=>this.deserializeSnapshotValue(t));if(typeof e=="object"){if(e.__type==="Vector3")return new w.Vector3(e.x,e.y,e.z);const t={};return Object.keys(e).forEach(i=>{t[i]=this.deserializeSnapshotValue(e[i])}),t}return e}}class zR{options;deviceType;animationId=null;isRenderingPaused=!1;controlsEnabledBeforePause=!0;animate;onWindowResize;_fpsFrameCount=0;_fpsLastCheck=0;_fpsLastSwitch=0;_lowFpsCount=0;_highFpsCount=0;_fpsCheckInterval=100;_fpsSwitchCooldown=100;_fpsThreshold=30;_fpsUpgradeThreshold=60;_lowFpsRequired=5;_highFpsRequired=.1;isMouseDown=!1;isWheeling=!1;scene;camera;renderer;sceneModule;cameraModule;deviceModule;renderModule;controlModule;composerModule;loaderModule;engineStatus;events;lightModule;interactionModule;modelToolModule;worldToScreen;handelBehaved;octreeBox;controls;stats;catchSvg;engineModelModule;viewTree;merge2d;viewCube;rangeScale;setting;measure;clipping;modelTree;engineInfo;modelProperties;modelMapperBatch;modelEdge;ai;pathRoaming;hoverHighLight;minMap;grid;level;issueReport;text;hdr;ground;skyManager;linkElement2d3d;linkView2d3d;oneClickEncoding;fabricDraw;drawingPin;models=[];reactBoundingClientRect={left:0,top:0};version="3.7.4";versionEl=null;container;constructor(e){if(window.THREE=w,this.options=e,this.container=document.getElementById(e.containerId),!this.container)throw new Error(`Container ${e.containerId} not found`);if(this.engineModelModule=new I2(this),this.engineModelModule.init(),this.ai=new DP(this),this.deviceModule=new s_(this),this.deviceType=this.deviceModule.getDeviceType(),this.cameraModule=new mn(this),this.sceneModule=new n_(this),this.scene=this.sceneModule.scene,this.renderModule=new k1(this),this.renderer=this.renderModule.createRenderer(),this.camera=this.cameraModule.orthographicCamera,this.scene.camera=this.camera,this.renderer){const r=this.renderer;r.interactionCullingEnabled=!0,r.interactionActive=!1,r.interactionRenderScene=this.scene,r.interactionFrameBudgetMs=this.options.interactionFrameBudgetMs??6,r.interactionSkipShadows=this.options.interactionSkipShadows??!0}this.controlModule=new tE(this),this.controlModule.switchDefaultMode(),this.controls=this.controlModule.orbitControls,this.clipping=new SP(this),this.clipping.init(),this.composerModule=new pE(this),this.composerModule.init(),this.events=new v2,this.engineStatus=new y2(this),this.engineStatus.init(),this.loaderModule=new b2(this),this.lightModule=new _2(this),this.lightModule.init(),this.viewCube=new aD(this),this.viewCube.init(),this.options.showViewCube==!1&&this.viewCube.hide(),this.octreeBox=lD(this),this.rangeScale=new cD(this),this.rangeScale.init(),this.setting=new vD(this),this.engineModelModule.init(),this.handelBehaved=wu(this),this.modelMapperBatch=new IP(this),this.measure=new DD(this),this.modelToolModule=new S2(this),this.modelProperties=new EP(this),this.interactionModule=new w2(this),this.interactionModule.init(),this.interactionModule.active(),this.hoverHighLight=new wc(this),this.modelEdge=new bD(this),this.modelTree=new CP(this),this.viewTree=new NP(this),this.merge2d=new XP(this),this.engineInfo=new MP(this),this.pathRoaming=new BP(this),this.pathRoaming.init(),this.oneClickEncoding=new UP(this),this.minMap=new PP(this),this.linkElement2d3d=new kP(this),this.linkView2d3d=new FP(this),this.grid=new uD(this),this.level=new xD(this),this.issueReport=new LP(this),this.fabricDraw=new UR(this),this.drawingPin=new NR(this),this.text=new RP(this),this.hdr=new gD(this),this.ground=new of(this),this.ground.init(),this.skyManager=new yD(this),this.setting.init(),this.worldToScreen=new lt(this.camera,this.renderer,this.scene),this.options.showStats&&(this.stats=new P2,this.stats.showPanel(0),this.stats.dom.style.position="absolute",this.stats.dom.style.top="0px",this.stats.dom.style.left="0px",this.stats.dom.style.zIndex="1000",this.container.appendChild(this.stats.dom));let t=document.createElement("div");t.className="versionText",this.versionEl=t,this.updateVersionDisplay(),this.container.appendChild(t);let i=document.createElementNS("http://www.w3.org/2000/svg","svg");i.style.position="absolute",i.style.zIndex="1000",i.style.left="0px",i.style.top="0px",i.style.pointerEvents="none",this.container.appendChild(i),this.catchSvg=i,this.onWindowResize=()=>{this.handleWindowResize()},window.addEventListener("resize",this.onWindowResize);let s=this;this.controls.addEventListener("start",()=>{s.renderer&&(s.renderer.interactionActive=!0),s.events.trigger(Cs.EngineBusy),s.container&&(s.container.style.cursor="none")}),this.controls.addEventListener("end",()=>{s.renderer&&(s.renderer.interactionActive=!1),s.events.trigger(Cs.EngineFree),s.container&&(s.container.style.cursor="default")}),this.controls.addEventListener("change",()=>{const r=new w.Vector3;s.camera.getWorldDirection(r);const o=Math.atan2(r.x,-r.z);let a=new CustomEvent("D3ViewUpdate",{detail:{position:s.camera.position,rotation:o,type:s.camera.type}});window.dispatchEvent(a)}),this.events.on(Cs.LoadingCompleted,r=>{s.modelEdge.active()}),this.animate=()=>{if(!this.isRenderingPaused)this.animationId=requestAnimationFrame(this.animate);else{this.animationId=null;return}this.stats&&this.stats.begin(),this.composerModule&&this.composerModule.composer.render(),this.viewCube&&this.viewCube.cubeTool.RenderScene(),this.measure.update(),this.ground.update(),this.skyManager.update(),this.hoverHighLight.update(),this.controlModule.update(),this.minMap.update(),this.grid.update(),this.level.update(),this.text&&this.text.update(),this.stats&&this.stats.end(),this._fpsFrameCount++;const r=performance.now();if(r-this._fpsLastCheck>=this._fpsCheckInterval){const o=r-this._fpsLastCheck,a=this._fpsFrameCount/o*1e3;this._fpsFrameCount=0,this._fpsLastCheck=r,a<this._fpsThreshold?(this._lowFpsCount++,this._highFpsCount=0,this._lowFpsCount>=this._lowFpsRequired&&r-this._fpsLastSwitch>this._fpsSwitchCooldown&&(this._adaptiveRenderingDowngrade(),this._fpsLastSwitch=r,this._lowFpsCount=0)):(this._lowFpsCount=0,this._highFpsCount=0)}if(this.scene){let o=this.scene?.dirLight;o&&this.camera&&this.updateLightPosition(this.camera,o)}},this.animate()}updateVersionDisplay(){if(!this.versionEl)return;const e={simple:"simple",balance:"balance",advanced:"advanced"},t=this.engineModelModule?.getCurrentMode()??"",i=e[t]??t;this.versionEl.innerHTML=`v${this.version} | ${i}`}updateLightPosition(e,t){const i=new w.Vector3;e.getWorldDirection(i);const s=100,r=new w.Vector3().copy(i).multiplyScalar(-s),o=new w.Vector3(0,1,0),a=new w.Vector3().crossVectors(i,o).normalize();r.addScaledVector(o,s*.5),r.addScaledVector(a,s*.3),t.position.copy(e.position).add(r);const l=new w.Vector3().copy(e.position).add(i.multiplyScalar(20));t.target.position.copy(l),t.target.updateMatrixWorld()}_adaptiveRenderingDowngrade(){const e=["simple","balance","advanced"],t=this.engineModelModule.getCurrentMode(),i=e.indexOf(t);if(i>0){const s=e[i-1];console.log(`[AdaptiveRendering] FPS低于${this._fpsThreshold},自动降级: ${t} → ${s}`),this.engineModelModule.autoSwitch(s)}}_adaptiveRenderingUpgrade(){const e=["simple","balance","advanced"],t=this.engineModelModule.getCurrentMode(),i=e.indexOf(t);if(i<e.length-1){const s=e[i+1];console.log(`[AdaptiveRendering] FPS高于${this._fpsUpgradeThreshold},自动升级: ${t} → ${s}`),this.engineModelModule.autoSwitch(s)}}pauseRendering(){if(this.isRenderingPaused){console.warn("[BimEngine] Rendering is already paused");return}this.isRenderingPaused=!0,this.controls&&(this.controlsEnabledBeforePause=this.controls.enabled,this.controls.enabled=!1)}resumeRendering(){if(!this.isRenderingPaused){console.warn("[BimEngine] Rendering is not paused");return}this.isRenderingPaused=!1,this.controls&&(this.controls.enabled=this.controlsEnabledBeforePause),this.animationId===null&&this.animate()}isRenderingPausedState(){return this.isRenderingPaused}handleWindowResize(e,t){if(!this.container||!this.renderer||!this.camera)return;if(e===void 0||t===void 0){const s=this.deviceModule.getContainerSize();e=e??s.width,t=t??s.height}if(!e||!t)return;this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.setSize(e,t);const i=e/t;if(this.camera===this.cameraModule.perspectiveCamera)this.cameraModule.perspectiveCamera.aspect=i,this.cameraModule.perspectiveCamera.updateProjectionMatrix(),this.camera=this.cameraModule.perspectiveCamera;else if(this.camera===this.cameraModule.orthographicCamera){const s=this.cameraModule.orthographicCamera,r=this.cameraModule.getOrthographicVisibleHeight(s);this.cameraModule.setOrthographicVisibleHeight(r,s),s.updateProjectionMatrix()}if(this.catchSvg){const s=this.container.clientWidth,r=this.container.clientHeight;this.catchSvg.setAttribute("viewBox",`0 0 ${s} ${r}`)}this.fabricDraw&&this.fabricDraw.resize(e,t),this.events&&this.events.trigger(Cs.ViewportResize,{width:e,height:t})}dispose(){console.log("[BimEngine] Starting engine disposal..."),this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),this.isRenderingPaused=!0,this.onWindowResize&&window.removeEventListener("resize",this.onWindowResize);try{this.measure&&(this.measure.disActive(),this.measure.clearAll(),this.measure.annotationContainer&&this.measure.annotationContainer.remove()),this.hdr&&this.hdr.dispose(),this.minMap&&this.minMap.dispose(),this.text&&this.text.dispose(),this.issueReport&&this.issueReport.dispose(),this.fabricDraw&&this.fabricDraw.dispose(),this.clipping&&this.clipping.disActive(),this.interactionModule&&this.interactionModule.disActive(),this.viewCube&&this.viewCube.cubeTool&&typeof this.viewCube.cubeTool.dispose=="function"&&this.viewCube.cubeTool.dispose()}catch(e){console.warn("[BimEngine] Error disposing managers:",e)}try{this.controlModule&&(this.controlModule.originDiv&&this.controlModule.originDiv.remove(),this.controlModule.orbitControls&&typeof this.controlModule.orbitControls.dispose=="function"&&this.controlModule.orbitControls.dispose(),this.controlModule.firstPersonControls&&typeof this.controlModule.firstPersonControls.dispose=="function"&&this.controlModule.firstPersonControls.dispose())}catch(e){console.warn("[BimEngine] Error disposing controls:",e)}this.scene&&this.clearScene(this.scene);try{this.composerModule&&this.composerModule.composer&&(this.composerModule.composer.passes&&this.composerModule.composer.passes.forEach(e=>{e.dispose&&e.dispose()}),this.composerModule.composer.renderTarget1&&this.composerModule.composer.renderTarget1.dispose(),this.composerModule.composer.renderTarget2&&this.composerModule.composer.renderTarget2.dispose())}catch(e){console.warn("[BimEngine] Error disposing composer:",e)}try{this.renderModule&&this.renderModule.disposeRenderer(),this.renderer&&(this.renderer.domElement&&this.renderer.domElement.parentElement&&this.renderer.domElement.parentElement.removeChild(this.renderer.domElement),this.renderer.dispose(),this.renderer.forceContextLoss())}catch(e){console.warn("[BimEngine] Error disposing renderer:",e)}try{this.stats&&this.stats.dom&&this.stats.dom.parentElement&&this.stats.dom.parentElement.removeChild(this.stats.dom),this.catchSvg&&this.catchSvg.parentElement&&this.catchSvg.parentElement.removeChild(this.catchSvg)}catch(e){console.warn("[BimEngine] Error disposing DOM elements:",e)}try{this.events&&this.events.listeners&&this.events.listeners.clear()}catch(e){console.warn("[BimEngine] Error clearing event listeners:",e)}this.scene=null,this.camera=null,this.renderer=null,this.controls=null,this.models=[],this.container=null,console.log("[BimEngine] Engine disposal completed")}clearScene(e){if(!e)return;[...e.children].forEach(i=>{this.clearScene(i)}),e.parent&&e.parent.remove(e),e instanceof w.Mesh&&(e.geometry&&e.geometry.dispose(),e.material&&(Array.isArray(e.material)?e.material.forEach(i=>this.disposeMaterial(i)):this.disposeMaterial(e.material))),e instanceof w.Line&&(e.geometry&&e.geometry.dispose(),e.material&&this.disposeMaterial(e.material)),e instanceof w.Points&&(e.geometry&&e.geometry.dispose(),e.material&&this.disposeMaterial(e.material)),e instanceof w.InstancedMesh&&(e.geometry&&e.geometry.dispose(),e.material&&(Array.isArray(e.material)?e.material.forEach(i=>this.disposeMaterial(i)):this.disposeMaterial(e.material)),e.instanceMatrix&&(e.instanceMatrix=null),e.instanceColor&&(e.instanceColor=null)),e instanceof w.Sprite&&e.material&&this.disposeMaterial(e.material)}disposeMaterial(e){if(!e)return;["map","lightMap","bumpMap","normalMap","specularMap","envMap","alphaMap","aoMap","displacementMap","emissiveMap","gradientMap","metalnessMap","roughnessMap","clearcoatMap","clearcoatNormalMap","clearcoatRoughnessMap","transmissionMap","thicknessMap","sheenColorMap","sheenRoughnessMap","specularIntensityMap","specularColorMap","iridescenceMap","iridescenceThicknessMap"].forEach(i=>{const s=e[i];s&&s instanceof w.Texture&&s.dispose()}),e.dispose()}}const GR=`
|
|
6056
|
+
`}applyTo2d({imageData:{data:n}}){let e=-this.vibrance;for(let t=0;t<n.length;t+=4){let i=n[t],s=n[t+1],r=n[t+2],o=Math.max(i,s,r),a=(i+s+r)/3,l=2*Math.abs(o-a)/255*e;n[t]+=o===i?0:(o-i)*l,n[t+1]+=o===s?0:(o-s)*l,n[t+2]+=o===r?0:(o-r)*l}}sendUniformData(n,e){n.uniform1f(e.uVibrance,-this.vibrance)}isNeutralState(){return this.vibrance===0}};K(dl,"type","Vibrance"),K(dl,"defaults",{vibrance:0}),K(dl,"uniformLocations",["uVibrance"]),ke.setClass(dl),La({BaseFilter:()=>zt,BlackWhite:()=>vR,BlendColor:()=>$a,BlendImage:()=>Ja,Blur:()=>Za,Brightness:()=>el,Brownie:()=>gR,ColorMatrix:()=>kr,Composed:()=>Hp,Contrast:()=>tl,Convolute:()=>il,Gamma:()=>nl,Grayscale:()=>sl,HueRotation:()=>zh,Invert:()=>rl,Kodachrome:()=>AR,Noise:()=>ol,Pixelate:()=>al,Polaroid:()=>bR,RemoveColor:()=>ll,Resize:()=>cl,Saturation:()=>hl,Sepia:()=>yR,Technicolor:()=>xR,Vibrance:()=>dl,Vintage:()=>mR});function CR(n,e,t="bim-snapshot.png"){const i=n?.renderer,s=i?.domElement;if(!i||!s||!e)return null;const r=s.width||s.clientWidth,o=s.height||s.clientHeight;if(r<=0||o<=0)return null;let a=MR(s,r,o);if(!ER(a)){const f=IR(n,r,o);f&&(a=f)}const l=document.createElement("canvas");l.width=r,l.height=o;const c=l.getContext("2d");if(!c)return null;c.drawImage(a,0,0,r,o),c.drawImage(e,0,0,r,o);const h=l.toDataURL("image/png"),d=document.createElement("a");return d.href=h,d.download=t.toLowerCase().endsWith(".png")?t:`${t}.png`,d.click(),h}function MR(n,e,t){const i=document.createElement("canvas");i.width=e,i.height=t;const s=i.getContext("2d");return s&&s.drawImage(n,0,0,e,t),i}function ER(n){const e=n.getContext("2d");if(!e||n.width<=0||n.height<=0)return!1;const t=Math.min(32,n.width),i=Math.min(32,n.height),s=Math.max(1,Math.floor(n.width/t)),r=Math.max(1,Math.floor(n.height/i));for(let o=0;o<n.height;o+=r)for(let a=0;a<n.width;a+=s){const l=e.getImageData(a,o,1,1).data;if(l[0]!==0||l[1]!==0||l[2]!==0||l[3]!==0)return!0}return!1}function IR(n,e,t){const i=n?.renderer,s=n?.scene,r=n?.camera;if(!i||!s||!r)return null;const o=new w.WebGLRenderTarget(e,t,{minFilter:w.LinearFilter,magFilter:w.LinearFilter,format:w.RGBAFormat,depthBuffer:!0,stencilBuffer:!0}),a=i.getRenderTarget(),l=i.autoClear,c=i.xr?.enabled??!1;try{i.xr&&(i.xr.enabled=!1),i.autoClear=!0,i.setRenderTarget(o),i.clear(!0,!0,!0),i.render(s,r);const h=new Uint8Array(e*t*4);return i.readRenderTargetPixels(o,0,0,e,t,h),TR(h,e,t)}catch{return null}finally{i.setRenderTarget(a),i.autoClear=l,i.xr&&(i.xr.enabled=c),o.dispose()}}function TR(n,e,t){const i=document.createElement("canvas");i.width=e,i.height=t;const s=i.getContext("2d");if(!s)return i;const r=s.createImageData(e,t),o=e*4;for(let a=0;a<t;a++){const l=(t-1-a)*o,c=a*o;for(let h=0;h<o;h++)r.data[c+h]=n[l+h]}return s.putImageData(r,0,0),i}const DR={none:new URL("/assets/icon/%E9%80%89%E6%8B%A9.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,line:new URL("/assets/icon/%E7%BA%BF.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,arrow:new URL("/assets/icon/%E7%AE%AD%E5%A4%B4.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,rect:new URL("/assets/icon/%E7%9F%A9%E5%BD%A2.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,circle:new URL("/assets/icon/%E5%9C%86%E5%BD%A2.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,text:new URL("/assets/icon/%E6%96%87%E5%AD%97.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,cloudline:new URL("/assets/icon/%E4%BA%91%E7%BA%BF.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href},BR=new URL("/assets/icon/%E6%B5%8B%E8%B7%9D.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,PR=new URL("/assets/icon/%E6%88%AA%E5%9B%BE.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,LR=new URL("/assets/icon/%E7%BA%BF%E5%AE%BD.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,RR=new URL("/assets/icon/%E5%AD%97%E5%8F%B7.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,kR=[{type:"distance",label:"距离"},{type:"clearDistance",label:"垂距"},{type:"clearHeight",label:"净高"},{type:"elevation",label:"标高"},{type:"point",label:"坐标"},{type:"angle",label:"角度"},{type:"area",label:"面积"},{type:"slope",label:"坡度"}],FR={distance:new URL("/assets/icon/%E8%B7%9D%E7%A6%BB.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,clearDistance:new URL("/assets/icon/%E5%87%80%E8%B7%9D.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,clearHeight:new URL("/assets/icon/%E5%87%80%E9%AB%98.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,elevation:new URL("/assets/icon/%E6%A0%87%E9%AB%98.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,point:new URL("/assets/icon/%E5%9D%90%E6%A0%87.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,angle:new URL("/assets/icon/%E8%A7%92%E5%BA%A6.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,area:new URL("/assets/icon/%E9%9D%A2%E7%A7%AF.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,slope:new URL("/assets/icon/%E5%9D%A1%E5%BA%A6.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href};class OR{constructor(e,t){this.handlers=e,this.root=document.createElement("div"),this.root.style.position="absolute",this.root.style.top="8px",this.root.style.left="50%",this.root.style.transform="translateX(-50%)",this.root.style.display="none",this.root.style.padding="6px",this.root.style.background="#ffffff",this.root.style.border="1px solid #d9d9d9",this.root.style.borderRadius="8px",this.root.style.pointerEvents="auto",this.root.style.userSelect="none",this.root.style.boxShadow="0 4px 14px rgba(0, 0, 0, 0.12)",this.root.style.zIndex="1300",this.editPanel=document.createElement("div"),this.editPanel.style.display="flex",this.editPanel.style.flexDirection="column",this.editPanel.style.gap="6px",this.viewPanel=document.createElement("div"),this.viewPanel.style.display="none",this.viewPanel.style.alignItems="center",this.viewPanel.style.gap="6px";const i=document.createElement("div");i.style.display="flex",i.style.alignItems="center",i.style.gap="6px",i.style.flexWrap="wrap",[{type:"none",label:"选择"},{type:"line",label:"线"},{type:"arrow",label:"箭头"},{type:"rect",label:"矩形"},{type:"circle",label:"圆形"},{type:"text",label:"文字"},{type:"cloudline",label:"云线"}].forEach(c=>{const h=this.createIconButton(c.label,DR[c.type]);h.onclick=()=>this.handlers.onDrawTypeChange(c.type),this.drawButtons[c.type]=h,i.appendChild(h)}),this.colorInput=document.createElement("input"),this.colorInput.type="color",this.colorInput.value=t.stroke,this.colorInput.style.width="32px",this.colorInput.style.height="24px",this.colorInput.style.padding="0",this.colorInput.style.border="1px solid #d9d9d9",this.colorInput.style.borderRadius="4px",this.colorInput.style.background="#ffffff",this.colorInput.oninput=()=>this.handlers.onColorChange(this.colorInput.value),i.appendChild(this.createField("",this.colorInput)),this.strokeWidthInput=document.createElement("input"),this.strokeWidthInput.type="number",this.strokeWidthInput.min="1",this.strokeWidthInput.max="20",this.strokeWidthInput.step="1",this.strokeWidthInput.value=String(t.strokeWidth),this.strokeWidthInput.style.width="46px",this.strokeWidthInput.oninput=()=>this.handlers.onStrokeWidthChange(this.strokeWidthInput.value),i.appendChild(this.createField("",this.strokeWidthInput,LR,"线宽")),this.fontSizeInput=document.createElement("input"),this.fontSizeInput.type="number",this.fontSizeInput.min="10",this.fontSizeInput.max="96",this.fontSizeInput.step="1",this.fontSizeInput.value=String(t.fontSize),this.fontSizeInput.style.width="46px",this.fontSizeInput.oninput=()=>this.handlers.onFontSizeChange(this.fontSizeInput.value),i.appendChild(this.createField("",this.fontSizeInput,RR,"字号")),this.distanceButton=this.createIconButton("测量",BR),this.distanceButton.onclick=()=>this.handlers.onMeasureToggle(),i.appendChild(this.distanceButton);const r=this.createIconButton("截图",PR);r.onclick=()=>this.handlers.onScreenshot(),i.appendChild(r);const o=this.createTextButton("×","取消");o.onclick=()=>this.handlers.onCancel(),o.style.background="#ff4d4f",o.style.borderColor="#ff4d4f",o.style.color="#ffffff",i.appendChild(o);const a=this.createTextButton("✔","确定");a.onclick=()=>this.handlers.onConfirm(),a.style.background="#52c41a",a.style.borderColor="#52c41a",a.style.color="#ffffff",i.appendChild(a),this.measureSubPanel=document.createElement("div"),this.measureSubPanel.style.display="none",this.measureSubPanel.style.alignItems="center",this.measureSubPanel.style.gap="6px",this.measureSubPanel.style.flexWrap="wrap",this.measureSubPanel.style.paddingTop="2px",kR.forEach(c=>{const h=this.createSmallIconButton(c.label,FR[c.type]);h.onclick=()=>this.handlers.onMeasureTypeChange(c.type),this.measureTypeButtons[c.type]=h,this.measureSubPanel.appendChild(h)}),this.editPanel.appendChild(i),this.editPanel.appendChild(this.measureSubPanel);const l=this.createTextButton("关闭","关闭");l.onclick=()=>this.handlers.onClose(),this.viewPanel.appendChild(l),this.root.appendChild(this.editPanel),this.root.appendChild(this.viewPanel),this.setMode("edit")}root;drawButtons={};measureTypeButtons={};distanceButton;colorInput;strokeWidthInput;fontSizeInput;editPanel;viewPanel;measureSubPanel;mode="edit";mount(e){e.appendChild(this.root)}show(){this.root.style.display="block"}hide(){this.root.style.display="none"}setMode(e){this.mode=e,this.editPanel.style.display=e==="edit"?"flex":"none",this.viewPanel.style.display=e==="view"?"flex":"none",e==="view"&&this.setMeasurePanelVisible(!1)}setDrawType(e){for(const t in this.drawButtons){const i=this.drawButtons[t];if(!i)continue;const s=t===e;i.style.background=s?"#eaf2ff":"#ffffff",i.style.borderColor=s?"#2f80ed":"#d9d9d9"}}setMeasurePanelVisible(e){if(this.mode!=="edit"){this.measureSubPanel.style.display="none";return}this.measureSubPanel.style.display=e?"flex":"none"}setMeasureState(e,t){this.distanceButton.style.background=e?"#eaf2ff":"#ffffff",this.distanceButton.style.borderColor=e?"#2f80ed":"#d9d9d9";for(const i in this.measureTypeButtons){const s=this.measureTypeButtons[i];if(!s)continue;const r=e&&t===i;s.style.background=r?"#eaf2ff":"#ffffff",s.style.borderColor=r?"#2f80ed":"#d9d9d9"}}setStyleValues(e){e.stroke&&(this.colorInput.value=e.stroke),typeof e.strokeWidth=="number"&&(this.strokeWidthInput.value=String(e.strokeWidth)),typeof e.fontSize=="number"&&(this.fontSizeInput.value=String(e.fontSize))}dispose(){this.colorInput.oninput=null,this.strokeWidthInput.oninput=null,this.fontSizeInput.oninput=null,this.root.remove()}createField(e,t,i,s=""){const r=document.createElement("div");if(r.style.display="flex",r.style.alignItems="center",r.style.gap="4px",r.style.padding="0 2px",r.style.color="#333333",r.style.fontSize="12px",e){const o=document.createElement("span");o.textContent=e,r.appendChild(o)}if(i){const o=document.createElement("img");o.src=i,o.alt=s,o.style.width="14px",o.style.height="14px",o.style.display="block",r.appendChild(o)}return t.style.height="24px",t.style.border="1px solid #d9d9d9",t.style.borderRadius="4px",t.style.background="#ffffff",t.style.color="#333333",t.style.outline="none",t.style.padding="0 4px",r.appendChild(t),r}createIconButton(e,t){const i=document.createElement("button");i.type="button",i.style.width="28px",i.style.height="28px",i.style.padding="0",i.style.display="flex",i.style.alignItems="center",i.style.justifyContent="center",i.style.border="1px solid #d9d9d9",i.style.borderRadius="4px",i.style.background="#ffffff",i.style.cursor="pointer";const s=document.createElement("img");return s.src=t,s.alt=e,s.style.width="16px",s.style.height="16px",s.style.display="block",i.appendChild(s),i}createSmallIconButton(e,t){const i=document.createElement("button");i.type="button",i.style.width="26px",i.style.height="26px",i.style.padding="0",i.style.display="flex",i.style.alignItems="center",i.style.justifyContent="center",i.style.border="1px solid #d9d9d9",i.style.borderRadius="4px",i.style.background="#ffffff",i.style.cursor="pointer";const s=document.createElement("img");return s.src=t,s.alt=e,s.style.width="14px",s.style.height="14px",s.style.display="block",i.appendChild(s),i}createTextButton(e,t){const i=document.createElement("button");return i.type="button",i.textContent=e,i.style.width="28px",i.style.height="28px",i.style.padding="0 10px",i.style.border="1px solid #d9d9d9",i.style.borderRadius="4px",i.style.background="#ffffff",i.style.color="#333333",i.style.fontSize="13px",i.style.lineHeight="1",i.style.cursor="pointer",i}}class UR{engine;wrapper;canvasEl;canvas;toolbar;isActive=!1;isVisible=!0;isDistanceMeasureMode=!1;isMeasurePanelExpanded=!1;drawType="none";mode="edit";currentMeasureType=null;sessionSnapshot=null;actionHandlers={};drawStyle={stroke:"#ff4d4f",strokeWidth:2,fill:"rgba(255, 77, 79, 0.08)",fontSize:16,text:"文本",cloudRadius:10};startPoint=null;tempObject=null;cloudPoints=[];onMouseDown=e=>this.handleMouseDown(e);onMouseMove=e=>this.handleMouseMove(e);onMouseUp=e=>this.handleMouseUp(e);onMouseDblClick=e=>this.handleMouseDblClick(e);onSelectionChanged=()=>this.syncStyleFromSelection();onKeyDown=e=>this.handleKeyDown(e);constructor(e){this.engine=e;const t=this.engine.container;if(!t)throw new Error("FabricDraw: engine container not found.");this.wrapper=document.createElement("div"),this.wrapper.className="fabric-draw-layer",this.wrapper.style.position="absolute",this.wrapper.style.left="0",this.wrapper.style.top="0",this.wrapper.style.right="0",this.wrapper.style.bottom="0",this.wrapper.style.zIndex="1200",this.wrapper.style.pointerEvents="none",this.canvasEl=document.createElement("canvas"),this.canvasEl.style.width="100%",this.canvasEl.style.height="100%",this.wrapper.appendChild(this.canvasEl),this.toolbar=new OR({onDrawTypeChange:i=>this.setDrawType(i),onMeasureToggle:()=>this.toggleMeasurePanel(),onMeasureTypeChange:i=>this.activateDistanceMeasure(i),onScreenshot:()=>{this.saveScreenshot(this.createScreenshotFileName())},onColorChange:i=>this.handleColorInputChange(i),onStrokeWidthChange:i=>this.handleStrokeWidthInputChange(i),onFontSizeChange:i=>this.handleFontSizeInputChange(i),onCancel:()=>{this.handleCancelClick()},onConfirm:()=>this.handleConfirmClick(),onClose:()=>{this.handleCloseClick()}},{stroke:this.drawStyle.stroke,strokeWidth:this.drawStyle.strokeWidth,fontSize:this.drawStyle.fontSize}),this.toolbar.mount(this.wrapper),t.appendChild(this.wrapper),this.canvas=new Up(this.canvasEl,{selection:!0,preserveObjectStacking:!0}),this.resize(),this.canvas.on("mouse:down",this.onMouseDown),this.canvas.on("mouse:move",this.onMouseMove),this.canvas.on("mouse:up",this.onMouseUp),this.canvas.on("mouse:dblclick",this.onMouseDblClick),this.canvas.on("selection:created",this.onSelectionChanged),this.canvas.on("selection:updated",this.onSelectionChanged),this.canvas.on("selection:cleared",this.onSelectionChanged),window.addEventListener("keydown",this.onKeyDown),this.refreshToolbarState()}active(e="edit"){this.isActive=!0,this.mode=e,this.drawType="none",this.isMeasurePanelExpanded=!1,this.currentMeasureType=null,this.canvas.defaultCursor="default",this.sessionSnapshot=e==="edit"?this.cloneJson(this.getAllShapes()):null,this.toolbar.setMode(e),this.applyCanvasInteractive(e==="edit"),this.isVisible&&this.toolbar.show(),this.updateOverlayPointerEvents(),this.refreshToolbarState()}disActive(){this.isActive=!1,this.startPoint=null,this.cloudPoints=[],this.tempObject=null,this.drawType="none",this.mode="edit",this.isMeasurePanelExpanded=!1,this.currentMeasureType=null,this.sessionSnapshot=null,this.stopDistanceMeasureMode(),this.canvas.defaultCursor="default",this.canvas.discardActiveObject(),this.applyCanvasInteractive(!0),this.canvas.requestRenderAll(),this.toolbar.setMode("edit"),this.toolbar.hide(),this.updateOverlayPointerEvents(),this.refreshToolbarState()}close(){this.disActive()}hide(){this.isVisible=!1,this.wrapper.style.display="none",this.toolbar.hide()}show(){this.isVisible=!0,this.wrapper.style.display="block",this.isActive&&this.toolbar.show(),this.resize()}isShown(){return this.isVisible}setDrawType(e,t){this.mode!=="view"&&(this.stopDistanceMeasureMode(),this.isMeasurePanelExpanded=!1,this.currentMeasureType=null,this.drawType=e,t&&(this.drawStyle={...this.drawStyle,...t}),this.canvas.defaultCursor=e==="none"?"default":"crosshair",this.updateOverlayPointerEvents(),this.refreshToolbarState())}getDrawType(){return this.drawType}setActionHandlers(e){this.actionHandlers={...e}}drawLine(e,t,i){const s=this.mergeStyle(i),r=this.createLineObject(e,t,s,!0);return this.canvas.add(r),this.canvas.requestRenderAll(),r}drawArrow(e,t,i){const s=this.mergeStyle(i),r=this.createArrowObject(e,t,s,!0);return this.canvas.add(r),this.canvas.requestRenderAll(),r}drawRect(e,t,i){const s=this.mergeStyle(i),r=this.createRectObject(e,t,s,!0);return this.canvas.add(r),this.canvas.requestRenderAll(),r}drawCircle(e,t,i){const s=this.mergeStyle(i),r=this.createCircleObject(e,t,s,!0);return this.canvas.add(r),this.canvas.requestRenderAll(),r}drawText(e,t,i){const s=this.mergeStyle(i),r=new Lr(t??s.text,{left:e.x,top:e.y,fontSize:s.fontSize,fill:s.stroke,selectable:!0,evented:!0,objectCaching:!1});return r.annotationType="text",this.canvas.add(r),this.canvas.requestRenderAll(),r}drawCloudLine(e,t){if(e.length<2)return null;const i=this.mergeStyle(t),s=this.createCloudObject(e,i,!0);return s?(this.canvas.add(s),this.canvas.requestRenderAll(),s):null}getAllShapes(){return this.canvas.toObject(["annotationType"])}clearAllShapes(){this.canvas.clear(),this.canvas.requestRenderAll()}async restoreAllShapes(e){await this.canvas.loadFromJSON(e),this.canvas.requestRenderAll()}saveScreenshot(e="bim-snapshot.png"){const t=this.canvas.lowerCanvasEl;return t?CR(this.engine,t,e):null}resize(e,t){const i=this.engine.container;if(!i)return;const s=e??i.clientWidth??1,r=t??i.clientHeight??1;this.canvas.setDimensions({width:s,height:r}),this.canvas.requestRenderAll()}dispose(){this.stopDistanceMeasureMode(),window.removeEventListener("keydown",this.onKeyDown),this.canvas.off("mouse:down",this.onMouseDown),this.canvas.off("mouse:move",this.onMouseMove),this.canvas.off("mouse:up",this.onMouseUp),this.canvas.off("mouse:dblclick",this.onMouseDblClick),this.canvas.off("selection:created",this.onSelectionChanged),this.canvas.off("selection:updated",this.onSelectionChanged),this.canvas.off("selection:cleared",this.onSelectionChanged),this.toolbar.dispose(),this.canvas.dispose(),this.wrapper.remove()}handleMouseDown(e){if(!this.isActive||this.mode==="view"||this.drawType==="none"||e?.target)return;const t=this.getPointFromEvent(e);if(this.drawType==="text"){const s=this.drawText(t);this.canvas.setActiveObject(s),this.canvas.requestRenderAll(),setTimeout(()=>{s.enterEditing(),s.hiddenTextarea?.focus(),s.selectAll()},0);return}this.startPoint=t,this.cloudPoints=[t],this.canvas.selection=!1,this.canvas.discardActiveObject();const i=this.createDraftObject(t,t);i&&(this.tempObject=i,this.canvas.add(i),this.canvas.requestRenderAll())}handleMouseMove(e){if(!this.isActive||this.mode==="view"||!this.startPoint||!this.tempObject)return;const t=this.getPointFromEvent(e),i=this.drawStyle;if(this.drawType==="cloudline"){if(this.shouldAppendCloudPoint(t)){this.cloudPoints.push(t),this.canvas.remove(this.tempObject);const s=this.createCloudObject(this.cloudPoints,i,!1);if(!s)return;this.tempObject=s,this.canvas.add(s),this.canvas.requestRenderAll()}return}if(this.drawType==="arrow"){this.canvas.remove(this.tempObject),this.tempObject=this.createArrowObject(this.startPoint,t,i,!1),this.canvas.add(this.tempObject),this.canvas.requestRenderAll();return}this.updateDraftObject(this.startPoint,t),this.canvas.requestRenderAll()}handleMouseUp(e){if(!this.isActive||this.mode==="view"||!this.startPoint)return;const t=this.getPointFromEvent(e);this.drawType==="cloudline"&&this.cloudPoints.length===1&&(this.cloudPoints.push(t),this.canvas.remove(this.tempObject),this.tempObject=this.createCloudObject(this.cloudPoints,this.drawStyle,!0),this.tempObject&&this.canvas.add(this.tempObject)),this.tempObject&&(this.tempObject.set({selectable:!0,evented:!0}),this.tempObject.setCoords?.(),this.canvas.requestRenderAll()),this.startPoint=null,this.tempObject=null,this.cloudPoints=[],this.canvas.selection=!0}handleMouseDblClick(e){const t=e?.target;this.isTextObject(t)&&(t.enterEditing(),t.hiddenTextarea?.focus(),t.selectAll?.())}handleKeyDown(e){if(!this.isActive)return;const t=this.canvas.getActiveObject();if(this.isTextObject(t)&&t?.isEditing||this.isInputElement(e.target))return;if(e.key==="Escape"){e.preventDefault(),this.mode==="view"?this.handleCloseClick():this.handleCancelClick();return}if(e.key==="Enter"){this.mode==="edit"&&(e.preventDefault(),this.handleConfirmClick());return}if(e.key!=="Delete"&&e.key!=="Backspace"||!t)return;e.preventDefault(),this.canvas.getActiveObjects().forEach(r=>this.canvas.remove(r)),this.canvas.discardActiveObject(),this.canvas.requestRenderAll()}getPointFromEvent(e){if(e?.e){const i=this.canvas.getScenePoint(e.e);return{x:i.x,y:i.y}}const t=e?.scenePoint??e?.pointer??e?.absolutePointer;return t?{x:t.x,y:t.y}:{x:0,y:0}}shouldAppendCloudPoint(e){if(this.cloudPoints.length===0)return!0;const t=this.cloudPoints[this.cloudPoints.length-1],i=e.x-t.x,s=e.y-t.y;return Math.sqrt(i*i+s*s)>=6}createDraftObject(e,t){const i=this.drawStyle;switch(this.drawType){case"line":return this.createLineObject(e,t,i,!1);case"arrow":return this.createArrowObject(e,t,i,!1);case"rect":return this.createRectObject(e,t,i,!1);case"circle":return this.createCircleObject(e,t,i,!1);case"cloudline":return this.createCloudObject([e,t],i,!1);default:return null}}updateDraftObject(e,t){if(this.tempObject){if(this.drawType==="line"){this.tempObject.set({x2:t.x,y2:t.y});return}if(this.drawType==="rect"){const i=this.getBoxFromPoints(e,t);this.tempObject.set({left:i.left,top:i.top,width:i.width,height:i.height});return}if(this.drawType==="circle"){const i=this.getCircleFromPoints(e,t);this.tempObject.set({left:i.left,top:i.top,radius:i.radius})}}}mergeStyle(e){return{...this.drawStyle,...e??{}}}createObjectBase(e,t){return{stroke:e.stroke,strokeWidth:e.strokeWidth,fill:e.fill,selectable:t,evented:t,objectCaching:!1}}createLineObject(e,t,i,s){const r=new js([e.x,e.y,t.x,t.y],{...this.createObjectBase(i,s),fill:"",strokeLineCap:"round"});return r.annotationType="line",r}createRectObject(e,t,i,s){const r=this.getBoxFromPoints(e,t),o=new Gs({...this.createObjectBase(i,s),left:r.left,top:r.top,width:r.width,height:r.height,originX:"left",originY:"top"});return o.annotationType="rect",o}createCircleObject(e,t,i,s){const r=this.getCircleFromPoints(e,t),o=new Pr({...this.createObjectBase(i,s),left:r.left,top:r.top,radius:r.radius,originX:"left",originY:"top"});return o.annotationType="circle",o}createArrowObject(e,t,i,s){const r=t.x-e.x,o=t.y-e.y,a=Math.sqrt(r*r+o*o);if(a<1e-6){const D=new js([e.x,e.y,t.x,t.y],{stroke:i.stroke,strokeWidth:i.strokeWidth,fill:"",selectable:s,evented:s}),M=new Vs([D],{selectable:s,evented:s,objectCaching:!1});return M.annotationType="arrow",M}const l=r/a,c=o/a,h=-c,d=l,f=Math.max(10,i.strokeWidth*6),u=f*.72,g=t.x-l*f,p=t.y-c*f,m=g+h*(u*.5),A=p+d*(u*.5),x=g-h*(u*.5),b=p-d*(u*.5),y=new js([e.x,e.y,t.x,t.y],{stroke:i.stroke,strokeWidth:i.strokeWidth,fill:"",strokeLineCap:"round",selectable:!1,evented:!1}),_=`M ${t.x} ${t.y} L ${m} ${A} L ${x} ${b} Z`,S=new Br(_,{fill:i.stroke,stroke:i.stroke,strokeWidth:1,selectable:!1,evented:!1,objectCaching:!1}),C=new Vs([y,S],{selectable:s,evented:s,objectCaching:!1});return C.annotationType="arrow",C}createCloudObject(e,t,i){const s=this.buildCloudPath(e,t.cloudRadius);if(!s)return null;const r=new Br(s,{stroke:t.stroke,strokeWidth:t.strokeWidth,fill:"",strokeLineCap:"round",strokeLineJoin:"round",selectable:i,evented:i});return r.annotationType="cloudline",r}getBoxFromPoints(e,t){return{left:Math.min(e.x,t.x),top:Math.min(e.y,t.y),width:Math.abs(t.x-e.x),height:Math.abs(t.y-e.y)}}getCircleFromPoints(e,t){const i=t.x-e.x,s=t.y-e.y,r=Math.max(Math.abs(i),Math.abs(s)),o=i>=0?e.x:e.x-r,a=s>=0?e.y:e.y-r;return{left:o,top:a,radius:Math.max(r/2,1)}}buildCloudPath(e,t){if(e.length<2)return"";const i=Math.max(2,t),s=i*1.4;let r=`M ${e[0].x} ${e[0].y}`,o=1;for(let a=1;a<e.length;a++){const l=e[a-1],c=e[a],h=c.x-l.x,d=c.y-l.y,f=Math.sqrt(h*h+d*d);if(f<.1)continue;const u=-d/f,g=h/f,p=Math.max(1,Math.round(f/s));for(let m=1;m<=p;m++){const A=m/p,x=l.x+h*A,b=l.y+d*A,y=o%2===0?-1:1,_=x+u*i*y,S=b+g*i*y;r+=` Q ${_} ${S} ${x} ${b}`,o++}}return r}handleColorInputChange(e){this.drawStyle.stroke=e||this.drawStyle.stroke,this.drawStyle.fill=this.colorToAlpha(this.drawStyle.stroke,.08),this.applyCurrentStyleToSelection(),this.refreshToolbarStyleValues()}handleStrokeWidthInputChange(e){const t=this.parseNumber(e,this.drawStyle.strokeWidth,1,20);this.drawStyle.strokeWidth=t,this.applyCurrentStyleToSelection(),this.refreshToolbarStyleValues()}handleFontSizeInputChange(e){const t=this.parseNumber(e,this.drawStyle.fontSize,10,96);this.drawStyle.fontSize=t,this.applyCurrentStyleToSelection(),this.refreshToolbarStyleValues()}applyCurrentStyleToSelection(){const e=this.canvas.getActiveObjects();e.length!==0&&(e.forEach(t=>this.applyStyleToObject(t)),this.canvas.requestRenderAll())}applyStyleToObject(e){if(!e)return;if(e.annotationType==="arrow"&&Array.isArray(e._objects)){e._objects.forEach(i=>{if(i?.type==="triangle"||i?.type==="path"){i.set({fill:this.drawStyle.stroke,stroke:this.drawStyle.stroke,strokeWidth:1});return}i?.set({stroke:this.drawStyle.stroke,strokeWidth:this.drawStyle.strokeWidth,strokeLineCap:"round"})}),e.set({dirty:!0}),e.setCoords?.();return}if(this.isTextObject(e)){e.set({fill:this.drawStyle.stroke,fontSize:this.drawStyle.fontSize}),e.setCoords?.();return}const t={stroke:this.drawStyle.stroke,strokeWidth:this.drawStyle.strokeWidth};e?.type==="line"||e?.type==="path"?t.fill="":t.fill=this.drawStyle.fill,e.set(t),e.setCoords?.()}syncStyleFromSelection(){const e=this.canvas.getActiveObject();if(!e)return;const t=this.readStyleFromObject(e);t.stroke&&(this.drawStyle.stroke=t.stroke,this.drawStyle.fill=this.colorToAlpha(t.stroke,.08)),typeof t.strokeWidth=="number"&&(this.drawStyle.strokeWidth=t.strokeWidth),typeof t.fontSize=="number"&&(this.drawStyle.fontSize=t.fontSize),this.refreshToolbarStyleValues()}readStyleFromObject(e){if(!e)return{};if(e.annotationType==="arrow"&&Array.isArray(e._objects)){const t=e._objects.find(i=>i?.type==="line")??e._objects[0];return{stroke:t?.stroke,strokeWidth:t?.strokeWidth}}return this.isTextObject(e)?{stroke:e.fill??this.drawStyle.stroke,fontSize:e.fontSize??this.drawStyle.fontSize}:{stroke:e.stroke??this.drawStyle.stroke,strokeWidth:e.strokeWidth??this.drawStyle.strokeWidth}}isTextObject(e){return e?e.type==="i-text"||e.type==="textbox"||e.annotationType==="text":!1}isInputElement(e){const t=e;if(!t||!t.tagName)return!1;const i=t.tagName.toLowerCase();return i==="input"||i==="textarea"||!!t.isContentEditable}applyCanvasInteractive(e){this.canvas.selection=e,this.canvas.getObjects().forEach(t=>{t.set({selectable:e,evented:e}),t.setCoords?.()}),this.canvas.discardActiveObject(),this.canvas.requestRenderAll()}parseNumber(e,t,i,s){const r=Number(e);return Number.isFinite(r)?Math.min(s,Math.max(i,r)):t}colorToAlpha(e,t){const i=e.trim(),s=/^#([0-9a-fA-F]{3})$/.exec(i);if(s){const o=s[1],a=parseInt(o[0]+o[0],16),l=parseInt(o[1]+o[1],16),c=parseInt(o[2]+o[2],16);return`rgba(${a}, ${l}, ${c}, ${t})`}const r=/^#([0-9a-fA-F]{6})$/.exec(i);if(r){const o=r[1],a=parseInt(o.slice(0,2),16),l=parseInt(o.slice(2,4),16),c=parseInt(o.slice(4,6),16);return`rgba(${a}, ${l}, ${c}, ${t})`}return this.drawStyle.fill}toggleMeasurePanel(){!this.isActive||this.mode!=="edit"||(this.isMeasurePanelExpanded=!this.isMeasurePanelExpanded,this.refreshToolbarState())}activateDistanceMeasure(e){if(!this.isActive||this.mode!=="edit")return;this.drawType="none",this.canvas.defaultCursor="default",this.isDistanceMeasureMode=!0,this.isMeasurePanelExpanded=!0,this.currentMeasureType=e,this.canvas.discardActiveObject(),this.canvas.requestRenderAll();const t=this.engine.measure;t?.active?.(),this.disActiveMeasureTools(t),this.activeMeasureTool(t,e),this.updateOverlayPointerEvents(),this.refreshToolbarState()}stopDistanceMeasureMode(){if(!this.isDistanceMeasureMode)return;const e=this.engine.measure;this.disActiveMeasureTools(e),this.isDistanceMeasureMode=!1,this.currentMeasureType=null,this.updateOverlayPointerEvents(),this.refreshToolbarState()}disActiveMeasureTools(e){e?.distanceMeasure?.disActive?.(),e?.clearDistanceMeasure?.disActive?.(),e?.clearHeightMeasure?.disActive?.(),e?.elevationMeasure?.disActive?.(),e?.pointMeasure?.disActive?.(),e?.angleMeasure?.disActive?.(),e?.areaMeasure?.disActive?.(),e?.slopeMeasure?.disActive?.()}activeMeasureTool(e,t){const s={distance:"distanceMeasure",clearDistance:"clearDistanceMeasure",clearHeight:"clearHeightMeasure",elevation:"elevationMeasure",point:"pointMeasure",angle:"angleMeasure",area:"areaMeasure",slope:"slopeMeasure"}[t];s&&e?.[s]?.active?.()}updateOverlayPointerEvents(){if(!this.isActive){this.wrapper.style.pointerEvents="none",this.canvasEl.style.pointerEvents="none";return}if(this.mode==="view"||this.isDistanceMeasureMode){this.wrapper.style.pointerEvents="none",this.canvasEl.style.pointerEvents="none",this.toolbar.root.style.pointerEvents="auto";return}this.wrapper.style.pointerEvents="auto",this.canvasEl.style.pointerEvents="auto",this.toolbar.root.style.pointerEvents="auto"}async handleCancelClick(){this.sessionSnapshot&&await this.restoreAllShapes(this.cloneJson(this.sessionSnapshot)),this.actionHandlers.onCancel?.(),this.disActive()}async handleCloseClick(){this.disActive()}handleConfirmClick(){const e=this.cloneJson(this.getAllShapes());this.actionHandlers.onConfirm?.(e),this.disActive()}refreshToolbarStyleValues(){this.toolbar.setStyleValues({stroke:this.drawStyle.stroke,strokeWidth:this.drawStyle.strokeWidth,fontSize:this.drawStyle.fontSize})}refreshToolbarState(){this.toolbar.setDrawType(this.drawType),this.toolbar.setMode(this.mode),this.toolbar.setMeasurePanelVisible(this.isMeasurePanelExpanded),this.toolbar.setMeasureState(this.isDistanceMeasureMode,this.currentMeasureType),this.refreshToolbarStyleValues()}createScreenshotFileName(){const e=new Date,t=e.getFullYear(),i=String(e.getMonth()+1).padStart(2,"0"),s=String(e.getDate()).padStart(2,"0"),r=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),a=String(e.getSeconds()).padStart(2,"0");return`bim-snapshot-${t}${i}${s}-${r}${o}${a}.png`}cloneJson(e){return JSON.parse(JSON.stringify(e))}}class NR{engine;constructor(e){this.engine=e}get(){return{cameraPose:this.engine.cameraModule?.getCameraPose?.()??null,clipping:this.captureClippingState(),measureData:this.captureMeasureData(),annotationData:this.captureAnnotationData()}}async restore(e,t="view"){e&&(e.cameraPose&&this.engine.cameraModule?.restoreCameraPose?.(e.cameraPose),this.restoreClippingState(e.clipping),this.restoreMeasureData(e.measureData),await this.restoreAnnotationData(e.annotationData),this.applyAnnotationMode(t))}create(e){const t=this.engine.fabricDraw;if(!t){e?.(this.get());return}t.setActionHandlers({onConfirm:i=>{const s=this.get();s.annotationData=this.serializeSnapshotValue(i),e?.(s),this.clearAnnotation()},onCancel:()=>{this.clearAnnotation()}}),t.show?.(),t.active?.("edit"),t.setDrawType?.("none")}clearAnnotation(){this.engine.fabricDraw?.clearAllShapes?.(),this.engine.measure.disActive?.()}captureClippingState(){const e=this.engine.clipping,t=e?.sectionFace,i=e?.currentClippingMode??"",s={mode:i,fillCutFace:e?.getFillCutFace?.()??!0};if(i==="box"&&e?.sectionBox?.getboxXyz&&(s.box=e.sectionBox.getboxXyz()),i==="x"||i==="y"||i==="z"||i==="face"){const r=t?.normal;r&&(s.face={normal:{x:Number(r.x)||0,y:Number(r.y)||0,z:Number(r.z)||1},distance:Number(t?.distance)||0,direction:Number(t?.direction)===-1?-1:1})}return s}restoreClippingState(e){const t=this.engine.clipping;if(!t)return;typeof e?.fillCutFace=="boolean"&&t.setFillCutFace?.(e.fillCutFace);const i=e?.mode??"";if(!i){t.disActive?.();return}if(i==="box"){t.active?.("box"),e.box&&t.sectionBox?.setboxXyz?.(e.box);return}if(i==="x"||i==="y"||i==="z"){t.active?.(i),this.applyFaceState(e.face);return}if(i==="face"){this.restoreFaceMode(e.face);return}t.active?.(i)}restoreFaceMode(e){const t=this.engine.clipping,i=t?.sectionFace;!t||!i||(t.sectionBox?.disActive?.(),i.disActive?.(),i.active?.(),t.currentClippingMode="face",this.applyFaceState(e))}applyFaceState(e){if(!e)return;const t=this.engine.clipping?.sectionFace;if(!t)return;const i=new w.Vector3(e.normal.x,e.normal.y,e.normal.z).normalize();t.direction=e.direction===-1?-1:1,t.setFaceNormal?.(i,e.distance??0)}captureMeasureData(){const e=this.engine.measure?.annotationData;return e?this.serializeSnapshotValue(e):null}restoreMeasureData(e){const t=this.engine.measure;if(!t)return;try{t.clearAll?.()}catch{}if(!e)return;const i=this.deserializeSnapshotValue(e);(!t.annotationData||typeof t.annotationData!="object")&&(t.annotationData={}),Object.keys(t.annotationData).forEach(s=>{t.annotationData[s]=[]}),Object.keys(i).forEach(s=>{t.annotationData[s]=Array.isArray(i[s])?i[s]:[]}),t.tools?.drawNormalAnnotation?.()}captureAnnotationData(){const e=this.engine.fabricDraw;return e?.getAllShapes?this.serializeSnapshotValue(e.getAllShapes()):null}async restoreAnnotationData(e){const t=this.engine.fabricDraw;if(!t)return;if(!e){t.clearAllShapes?.();return}const i=this.deserializeSnapshotValue(e);await t.restoreAllShapes?.(i)}applyAnnotationMode(e){const t=this.engine.fabricDraw;t&&(t.setActionHandlers?.({}),t.show?.(),t.active?.(e),t.setDrawType?.("none"))}serializeSnapshotValue(e){if(e==null)return e;if(e instanceof w.Vector3)return{__type:"Vector3",x:e.x,y:e.y,z:e.z};if(Array.isArray(e))return e.map(t=>this.serializeSnapshotValue(t));if(typeof e=="object"){if(e instanceof HTMLElement||e instanceof SVGElement)return;const t={};return Object.keys(e).forEach(i=>{if(i==="container")return;const s=this.serializeSnapshotValue(e[i]);s!==void 0&&(t[i]=s)}),t}if(typeof e!="function")return e}deserializeSnapshotValue(e){if(e==null)return e;if(Array.isArray(e))return e.map(t=>this.deserializeSnapshotValue(t));if(typeof e=="object"){if(e.__type==="Vector3")return new w.Vector3(e.x,e.y,e.z);const t={};return Object.keys(e).forEach(i=>{t[i]=this.deserializeSnapshotValue(e[i])}),t}return e}}class zR{options;deviceType;animationId=null;isRenderingPaused=!1;controlsEnabledBeforePause=!0;animate;onWindowResize;_fpsFrameCount=0;_fpsLastCheck=0;_fpsLastSwitch=0;_lowFpsCount=0;_highFpsCount=0;_fpsCheckInterval=100;_fpsSwitchCooldown=100;_fpsThreshold=30;_fpsUpgradeThreshold=60;_lowFpsRequired=5;_highFpsRequired=.1;isMouseDown=!1;isWheeling=!1;scene;camera;renderer;sceneModule;cameraModule;deviceModule;renderModule;controlModule;composerModule;loaderModule;engineStatus;events;lightModule;interactionModule;modelToolModule;worldToScreen;handelBehaved;octreeBox;controls;stats;catchSvg;engineModelModule;viewTree;merge2d;viewCube;rangeScale;setting;measure;clipping;modelTree;engineInfo;modelProperties;modelMapperBatch;modelEdge;ai;pathRoaming;hoverHighLight;minMap;grid;level;issueReport;text;hdr;ground;skyManager;linkElement2d3d;linkView2d3d;oneClickEncoding;fabricDraw;drawingPin;models=[];reactBoundingClientRect={left:0,top:0};version="3.7.5";versionEl=null;container;constructor(e){if(window.THREE=w,this.options=e,this.container=document.getElementById(e.containerId),!this.container)throw new Error(`Container ${e.containerId} not found`);if(this.engineModelModule=new I2(this),this.engineModelModule.init(),this.ai=new DP(this),this.deviceModule=new s_(this),this.deviceType=this.deviceModule.getDeviceType(),this.cameraModule=new mn(this),this.sceneModule=new n_(this),this.scene=this.sceneModule.scene,this.renderModule=new k1(this),this.renderer=this.renderModule.createRenderer(),this.camera=this.cameraModule.orthographicCamera,this.scene.camera=this.camera,this.renderer){const r=this.renderer;r.interactionCullingEnabled=!0,r.interactionActive=!1,r.interactionRenderScene=this.scene,r.interactionFrameBudgetMs=this.options.interactionFrameBudgetMs??6,r.interactionSkipShadows=this.options.interactionSkipShadows??!0}this.controlModule=new tE(this),this.controlModule.switchDefaultMode(),this.controls=this.controlModule.orbitControls,this.clipping=new SP(this),this.clipping.init(),this.composerModule=new pE(this),this.composerModule.init(),this.events=new v2,this.engineStatus=new y2(this),this.engineStatus.init(),this.loaderModule=new b2(this),this.lightModule=new _2(this),this.lightModule.init(),this.viewCube=new aD(this),this.viewCube.init(),this.options.showViewCube==!1&&this.viewCube.hide(),this.octreeBox=lD(this),this.rangeScale=new cD(this),this.rangeScale.init(),this.setting=new vD(this),this.engineModelModule.init(),this.handelBehaved=wu(this),this.modelMapperBatch=new IP(this),this.measure=new DD(this),this.modelToolModule=new S2(this),this.modelProperties=new EP(this),this.interactionModule=new w2(this),this.interactionModule.init(),this.interactionModule.active(),this.hoverHighLight=new wc(this),this.modelEdge=new bD(this),this.modelTree=new CP(this),this.viewTree=new NP(this),this.merge2d=new XP(this),this.engineInfo=new MP(this),this.pathRoaming=new BP(this),this.pathRoaming.init(),this.oneClickEncoding=new UP(this),this.minMap=new PP(this),this.linkElement2d3d=new kP(this),this.linkView2d3d=new FP(this),this.grid=new uD(this),this.level=new xD(this),this.issueReport=new LP(this),this.fabricDraw=new UR(this),this.drawingPin=new NR(this),this.text=new RP(this),this.hdr=new gD(this),this.ground=new of(this),this.ground.init(),this.skyManager=new yD(this),this.setting.init(),this.worldToScreen=new lt(this.camera,this.renderer,this.scene),this.options.showStats&&(this.stats=new P2,this.stats.showPanel(0),this.stats.dom.style.position="absolute",this.stats.dom.style.top="0px",this.stats.dom.style.left="0px",this.stats.dom.style.zIndex="1000",this.container.appendChild(this.stats.dom));let t=document.createElement("div");t.className="versionText",this.versionEl=t,this.updateVersionDisplay(),this.container.appendChild(t);let i=document.createElementNS("http://www.w3.org/2000/svg","svg");i.style.position="absolute",i.style.zIndex="1000",i.style.left="0px",i.style.top="0px",i.style.pointerEvents="none",this.container.appendChild(i),this.catchSvg=i,this.onWindowResize=()=>{this.handleWindowResize()},window.addEventListener("resize",this.onWindowResize);let s=this;this.controls.addEventListener("start",()=>{s.renderer&&(s.renderer.interactionActive=!0),s.events.trigger(Cs.EngineBusy),s.container&&(s.container.style.cursor="none")}),this.controls.addEventListener("end",()=>{s.renderer&&(s.renderer.interactionActive=!1),s.events.trigger(Cs.EngineFree),s.container&&(s.container.style.cursor="default")}),this.controls.addEventListener("change",()=>{const r=new w.Vector3;s.camera.getWorldDirection(r);const o=Math.atan2(r.x,-r.z);let a=new CustomEvent("D3ViewUpdate",{detail:{position:s.camera.position,rotation:o,type:s.camera.type}});window.dispatchEvent(a)}),this.events.on(Cs.LoadingCompleted,r=>{s.modelEdge.active()}),this.animate=()=>{if(!this.isRenderingPaused)this.animationId=requestAnimationFrame(this.animate);else{this.animationId=null;return}this.stats&&this.stats.begin(),this.composerModule&&this.composerModule.composer.render(),this.viewCube&&this.viewCube.cubeTool.RenderScene(),this.measure.update(),this.ground.update(),this.skyManager.update(),this.hoverHighLight.update(),this.controlModule.update(),this.minMap.update(),this.grid.update(),this.level.update(),this.text&&this.text.update(),this.stats&&this.stats.end(),this._fpsFrameCount++;const r=performance.now();if(r-this._fpsLastCheck>=this._fpsCheckInterval){const o=r-this._fpsLastCheck,a=this._fpsFrameCount/o*1e3;this._fpsFrameCount=0,this._fpsLastCheck=r,a<this._fpsThreshold?(this._lowFpsCount++,this._highFpsCount=0,this._lowFpsCount>=this._lowFpsRequired&&r-this._fpsLastSwitch>this._fpsSwitchCooldown&&(this._adaptiveRenderingDowngrade(),this._fpsLastSwitch=r,this._lowFpsCount=0)):(this._lowFpsCount=0,this._highFpsCount=0)}if(this.scene){let o=this.scene?.dirLight;o&&this.camera&&this.updateLightPosition(this.camera,o)}},this.animate()}updateVersionDisplay(){if(!this.versionEl)return;const e={simple:"simple",balance:"balance",advanced:"advanced"},t=this.engineModelModule?.getCurrentMode()??"",i=e[t]??t;this.versionEl.innerHTML=`v${this.version} | ${i}`}updateLightPosition(e,t){const i=new w.Vector3;e.getWorldDirection(i);const s=100,r=new w.Vector3().copy(i).multiplyScalar(-s),o=new w.Vector3(0,1,0),a=new w.Vector3().crossVectors(i,o).normalize();r.addScaledVector(o,s*.5),r.addScaledVector(a,s*.3),t.position.copy(e.position).add(r);const l=new w.Vector3().copy(e.position).add(i.multiplyScalar(20));t.target.position.copy(l),t.target.updateMatrixWorld()}_adaptiveRenderingDowngrade(){const e=["simple","balance","advanced"],t=this.engineModelModule.getCurrentMode(),i=e.indexOf(t);if(i>0){const s=e[i-1];console.log(`[AdaptiveRendering] FPS低于${this._fpsThreshold},自动降级: ${t} → ${s}`),this.engineModelModule.autoSwitch(s)}}_adaptiveRenderingUpgrade(){const e=["simple","balance","advanced"],t=this.engineModelModule.getCurrentMode(),i=e.indexOf(t);if(i<e.length-1){const s=e[i+1];console.log(`[AdaptiveRendering] FPS高于${this._fpsUpgradeThreshold},自动升级: ${t} → ${s}`),this.engineModelModule.autoSwitch(s)}}pauseRendering(){if(this.isRenderingPaused){console.warn("[BimEngine] Rendering is already paused");return}this.isRenderingPaused=!0,this.controls&&(this.controlsEnabledBeforePause=this.controls.enabled,this.controls.enabled=!1)}resumeRendering(){if(!this.isRenderingPaused){console.warn("[BimEngine] Rendering is not paused");return}this.isRenderingPaused=!1,this.controls&&(this.controls.enabled=this.controlsEnabledBeforePause),this.animationId===null&&this.animate()}isRenderingPausedState(){return this.isRenderingPaused}handleWindowResize(e,t){if(!this.container||!this.renderer||!this.camera)return;if(e===void 0||t===void 0){const s=this.deviceModule.getContainerSize();e=e??s.width,t=t??s.height}if(!e||!t)return;this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.setSize(e,t);const i=e/t;if(this.camera===this.cameraModule.perspectiveCamera)this.cameraModule.perspectiveCamera.aspect=i,this.cameraModule.perspectiveCamera.updateProjectionMatrix(),this.camera=this.cameraModule.perspectiveCamera;else if(this.camera===this.cameraModule.orthographicCamera){const s=this.cameraModule.orthographicCamera,r=this.cameraModule.getOrthographicVisibleHeight(s);this.cameraModule.setOrthographicVisibleHeight(r,s),s.updateProjectionMatrix()}if(this.catchSvg){const s=this.container.clientWidth,r=this.container.clientHeight;this.catchSvg.setAttribute("viewBox",`0 0 ${s} ${r}`)}this.fabricDraw&&this.fabricDraw.resize(e,t),this.events&&this.events.trigger(Cs.ViewportResize,{width:e,height:t})}dispose(){console.log("[BimEngine] Starting engine disposal..."),this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),this.isRenderingPaused=!0,this.onWindowResize&&window.removeEventListener("resize",this.onWindowResize);try{this.measure&&(this.measure.disActive(),this.measure.clearAll(),this.measure.annotationContainer&&this.measure.annotationContainer.remove()),this.hdr&&this.hdr.dispose(),this.minMap&&this.minMap.dispose(),this.text&&this.text.dispose(),this.issueReport&&this.issueReport.dispose(),this.fabricDraw&&this.fabricDraw.dispose(),this.clipping&&this.clipping.disActive(),this.interactionModule&&this.interactionModule.disActive(),this.viewCube&&this.viewCube.cubeTool&&typeof this.viewCube.cubeTool.dispose=="function"&&this.viewCube.cubeTool.dispose()}catch(e){console.warn("[BimEngine] Error disposing managers:",e)}try{this.controlModule&&(this.controlModule.originDiv&&this.controlModule.originDiv.remove(),this.controlModule.orbitControls&&typeof this.controlModule.orbitControls.dispose=="function"&&this.controlModule.orbitControls.dispose(),this.controlModule.firstPersonControls&&typeof this.controlModule.firstPersonControls.dispose=="function"&&this.controlModule.firstPersonControls.dispose())}catch(e){console.warn("[BimEngine] Error disposing controls:",e)}this.scene&&this.clearScene(this.scene);try{this.composerModule&&this.composerModule.composer&&(this.composerModule.composer.passes&&this.composerModule.composer.passes.forEach(e=>{e.dispose&&e.dispose()}),this.composerModule.composer.renderTarget1&&this.composerModule.composer.renderTarget1.dispose(),this.composerModule.composer.renderTarget2&&this.composerModule.composer.renderTarget2.dispose())}catch(e){console.warn("[BimEngine] Error disposing composer:",e)}try{this.renderModule&&this.renderModule.disposeRenderer(),this.renderer&&(this.renderer.domElement&&this.renderer.domElement.parentElement&&this.renderer.domElement.parentElement.removeChild(this.renderer.domElement),this.renderer.dispose(),this.renderer.forceContextLoss())}catch(e){console.warn("[BimEngine] Error disposing renderer:",e)}try{this.stats&&this.stats.dom&&this.stats.dom.parentElement&&this.stats.dom.parentElement.removeChild(this.stats.dom),this.catchSvg&&this.catchSvg.parentElement&&this.catchSvg.parentElement.removeChild(this.catchSvg)}catch(e){console.warn("[BimEngine] Error disposing DOM elements:",e)}try{this.events&&this.events.listeners&&this.events.listeners.clear()}catch(e){console.warn("[BimEngine] Error clearing event listeners:",e)}this.scene=null,this.camera=null,this.renderer=null,this.controls=null,this.models=[],this.container=null,console.log("[BimEngine] Engine disposal completed")}clearScene(e){if(!e)return;[...e.children].forEach(i=>{this.clearScene(i)}),e.parent&&e.parent.remove(e),e instanceof w.Mesh&&(e.geometry&&e.geometry.dispose(),e.material&&(Array.isArray(e.material)?e.material.forEach(i=>this.disposeMaterial(i)):this.disposeMaterial(e.material))),e instanceof w.Line&&(e.geometry&&e.geometry.dispose(),e.material&&this.disposeMaterial(e.material)),e instanceof w.Points&&(e.geometry&&e.geometry.dispose(),e.material&&this.disposeMaterial(e.material)),e instanceof w.InstancedMesh&&(e.geometry&&e.geometry.dispose(),e.material&&(Array.isArray(e.material)?e.material.forEach(i=>this.disposeMaterial(i)):this.disposeMaterial(e.material)),e.instanceMatrix&&(e.instanceMatrix=null),e.instanceColor&&(e.instanceColor=null)),e instanceof w.Sprite&&e.material&&this.disposeMaterial(e.material)}disposeMaterial(e){if(!e)return;["map","lightMap","bumpMap","normalMap","specularMap","envMap","alphaMap","aoMap","displacementMap","emissiveMap","gradientMap","metalnessMap","roughnessMap","clearcoatMap","clearcoatNormalMap","clearcoatRoughnessMap","transmissionMap","thicknessMap","sheenColorMap","sheenRoughnessMap","specularIntensityMap","specularColorMap","iridescenceMap","iridescenceThicknessMap"].forEach(i=>{const s=e[i];s&&s instanceof w.Texture&&s.dispose()}),e.dispose()}}const GR=`
|
|
6057
6057
|
varying vec2 vWorldPos;
|
|
6058
6058
|
|
|
6059
6059
|
void main() {
|