@myned-ai/avatar-chat-widget 0.0.1 → 0.0.3

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.
@@ -0,0 +1,2 @@
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).AvatarChat={})}(this,function(e){"use strict";var t,n=Object.defineProperty,i=(e,t,i)=>((e,t,i)=>t in e?n(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i),r="undefined"!=typeof document?document.currentScript:null;const s={auth:{enabled:!1},websocket:{url:void 0!=={url:"undefined"==typeof document&&"undefined"==typeof location?require("url").pathToFileURL(__filename).href:"undefined"==typeof document?location.href:r&&"SCRIPT"===r.tagName.toUpperCase()&&r.src||new URL("avatar-chat-widget.umd.js",document.baseURI).href}&&{}?.VITE_WS_URL||"ws://localhost:8080/ws",reconnectAttempts:5,initialReconnectDelay:1e3,maxReconnectDelay:3e4,heartbeatInterval:3e4,connectionTimeout:1e4},audio:{input:{sampleRate:16e3,channels:1,codec:"audio/webm;codecs=opus",echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},output:{sampleRate:24e3,bufferSize:4096,targetLatency:200,minBufferFrames:3,maxBufferFrames:10}},blendshape:{fps:30,bufferSize:60,interpolation:!0,smoothing:.3},chat:{maxMessages:100,autoScroll:!0,showTimestamps:!0},performance:{enableMonitoring:!0,latencyThreshold:500,frameDropThreshold:5},ui:{avatarBackgroundColor:"0xffffff",useIrisOcclusion:!0}};let a=JSON.parse(JSON.stringify(s));function o(e,t){const n={...e};for(const i in t)void 0!==t[i]&&("object"!=typeof t[i]||null===t[i]||Array.isArray(t[i])||"object"!=typeof e[i]?n[i]=t[i]:n[i]=o(e[i],t[i]));return n}function l(e){a=o(a,e)}const c=new Proxy({},{get:(e,t)=>a[t]}),h=0,u=1,d=2,p=3,f=4,m=(()=>{try{const e={url:"undefined"==typeof document&&"undefined"==typeof location?require("url").pathToFileURL(__filename).href:"undefined"==typeof document?location.href:r&&"SCRIPT"===r.tagName.toUpperCase()&&r.src||new URL("avatar-chat-widget.umd.js",document.baseURI).href};if(e?.env)return!0===e.env.DEV||"development"===e.env.MODE}catch{}return!1})()?f:p;class g{constructor(e,t){this.parent=e,this.scope=t}debug(e,...t){this.parent.debug(`[${this.scope}] ${e}`,...t)}info(e,...t){this.parent.info(`[${this.scope}] ${e}`,...t)}warn(e,...t){this.parent.warn(`[${this.scope}] ${e}`,...t)}error(e,...t){this.parent.error(`[${this.scope}] ${e}`,...t)}}const _=new class{constructor(){this.level=m}setLevel(e){this.level=e}getLevel(){return this.level}debug(e,...t){this.level}info(e,...t){this.level}warn(e,...t){this.level>=d&&console.warn(`[WARN] ${e}`,...t)}error(e,...t){this.level>=u&&console.error(`[ERROR] ${e}`,...t)}scope(e){return new g(this,e)}},v=_.scope("LazyAvatar");class x{constructor(e,t,n={}){this._avatar=null,this._isLoading=!1,this._isLoaded=!1,this._loadPromise=null,this._pendingState="Idle",this._pendingBlendshapes=null,this._liveBlendshapesEnabled=!1,this._container=e,this._assetsPath=t,this._options={preload:!0,...n},this._showPlaceholder(),this._options.preload&&this.load()}_showPlaceholder(){const e=document.createElement("div");e.id="avatar-placeholder",e.style.cssText="\n width: 100%;\n height: 100%;\n display: flex;\n align-items: center;\n justify-content: center;\n background: #ffffff;\n color: #fff;\n font-family: system-ui, sans-serif;\n ",e.innerHTML='\n <div style="text-align: center;">\n <div class="avatar-loader" style="\n width: 60px;\n height: 60px;\n border: 3px solid rgba(255,255,255,0.1);\n border-top-color: #4f46e5;\n border-radius: 50%;\n animation: spin 1s linear infinite;\n margin: 0 auto 16px;\n "></div>\n <div style="opacity: 0.7; font-size: 14px;">Loading avatar...</div>\n </div>\n <style>\n @keyframes spin { to { transform: rotate(360deg); } }\n </style>\n ',this._container.appendChild(e)}_removePlaceholder(){const e=this._container.querySelector("#avatar-placeholder");e&&e.remove()}async load(){return this._isLoaded||this._isLoading?this._loadPromise??Promise.resolve():(this._isLoading=!0,this._options.onLoadingStart?.(),this._loadPromise=this._doLoad(),this._loadPromise)}async _doLoad(){try{const{GaussianAvatar:e}=await Promise.resolve().then(()=>jm);this._removePlaceholder(),this._avatar=new e(this._container,this._assetsPath),await(this._avatar.start?.()),"Idle"!==this._pendingState&&this._avatar.setChatState(this._pendingState),this._liveBlendshapesEnabled&&this._avatar.enableLiveBlendshapes(),this._pendingBlendshapes&&this._avatar.updateBlendshapes(this._pendingBlendshapes),this._isLoaded=!0,this._isLoading=!1,this._options.onReady?.()}catch(e){this._isLoading=!1;const t=e instanceof Error?e:new Error(String(e));throw this._options.onError?.(t),v.error("Failed to load avatar:",t),t}}start(){this._avatar?this._avatar.start?.():this.load()}updateBlendshapes(e){this._avatar?this._avatar.updateBlendshapes(e):this._pendingBlendshapes=e}setChatState(e){this._pendingState=e,this._avatar&&this._avatar.setChatState(e)}getChatState(){return this._avatar?this._avatar.getChatState():this._pendingState}enableLiveBlendshapes(){this._liveBlendshapesEnabled=!0,this._avatar&&this._avatar.enableLiveBlendshapes()}disableLiveBlendshapes(){this._liveBlendshapesEnabled=!1,this._pendingBlendshapes=null,this._avatar&&this._avatar.disableLiveBlendshapes()}pause(){this._avatar&&"pause"in this._avatar&&this._avatar.pause()}resume(){this._avatar&&"resume"in this._avatar&&this._avatar.resume()}dispose(){this._removePlaceholder(),this._avatar&&this._avatar.dispose(),this._avatar=null,this._isLoaded=!1}get isLoaded(){return this._isLoaded}get isLoading(){return this._isLoading}}const y=_.scope("EventEmitter");class S{constructor(){this.events=new Map}on(e,t){this.events.has(e)||this.events.set(e,new Set),this.events.get(e).add(t)}off(e,t){const n=this.events.get(e);n&&(n.delete(t),0===n.size&&this.events.delete(e))}emit(e,t){const n=this.events.get(e);n&&n.forEach(n=>{try{n(t)}catch(i){y.error(`Error in event listener for "${e}":`,i)}})}removeAllListeners(e){e?this.events.delete(e):this.events.clear()}}const A=new class{constructor(){this.errorHandlers=new Map,this.errorCounts=new Map,this.maxErrorsPerContext=10}registerHandler(e,t){this.errorHandlers.set(e,t)}handleError(e,t){console.error(`[${t}]`,e);const n=(this.errorCounts.get(t)||0)+1;if(this.errorCounts.set(t,n),n>this.maxErrorsPerContext)return console.error(`Too many errors in context: ${t}. Circuit breaker triggered.`),void this.notifyUser(`Service temporarily unavailable: ${t}`);const i=this.errorHandlers.get(t);if(i)try{i(e)}catch(r){console.error("Error in error handler:",r)}this.handleSpecificError(e,t)}handleSpecificError(e,t){const n={websocket:"Connection lost. Attempting to reconnect...","audio-input":"Microphone unavailable. Please check permissions.","audio-output":"Audio playback failed. Check your speakers.",blendshape:"Avatar animation paused. Will resume shortly."}[t]||`An error occurred in ${t}`;this.notifyUser(n)}notifyUser(e){const t=new CustomEvent("app-notification",{detail:{message:e,type:"error"}});window.dispatchEvent(t)}reset(e){e?this.errorCounts.delete(e):this.errorCounts.clear()}getErrorCount(e){return this.errorCounts.get(e)||0}},b={1:"ping",2:"audio_input",3:"chat_message",4:"text",129:"pong",130:"audio_chunk",131:"blendshape",132:"sync_frame",133:"text_chunk",134:"state_update",135:"error"},M={ping:1,audio_input:2,chat_message:3,text:4,pong:129,audio_chunk:130,blendshape:131,sync_frame:132,text_chunk:133,state_update:134,error:135};class w{static encode(e){const t=M[e.type];if(void 0===t)throw new Error(`Unknown message type: ${e.type}`);return"audio_input"===e.type&&e.data instanceof ArrayBuffer?this.encodeAudioInput(t,e.data):this.encodeGeneric(t,e)}static decode(e){const t=new DataView(e),n=t.getUint8(0),i=t.getUint32(1,!1),r=b[n];if(!r)throw new Error(`Unknown message type code: ${n}`);switch(n){case 130:return this.decodeAudioChunk(r,i,e);case 131:return this.decodeBlendshape(r,i,e);case 132:return this.decodeSyncFrame(r,i,e);default:return this.decodeGeneric(r,i,e)}}static encodeAudioInput(e,t){const n=5+t.byteLength,i=new ArrayBuffer(n),r=new DataView(i);r.setUint8(0,e),r.setUint32(1,Date.now(),!1);const s=new Uint8Array(i,5),a=new Uint8Array(t);return s.set(a),i}static encodeGeneric(e,t){const n=JSON.stringify(t),i=(new TextEncoder).encode(n),r=9+i.length,s=new ArrayBuffer(r),a=new DataView(s);a.setUint8(0,e),a.setUint32(1,Date.now(),!1),a.setUint32(5,i.length,!1);return new Uint8Array(s,9).set(i),s}static decodeAudioChunk(e,t,n){return{type:e,audio:n.slice(5),timestamp:t}}static decodeBlendshape(e,t,n){const i=new Float32Array(n,5,52),r=new Float32Array(52);return r.set(i),{type:e,weights:Array.from(r),timestamp:t}}static decodeSyncFrame(e,t,n){const i=9+new DataView(n).getUint32(5,!1),r=n.slice(9,i),s=new Float32Array(n,i,52),a=new Float32Array(52);return a.set(s),{type:e,audio:r,weights:Array.from(a),timestamp:t}}static decodeGeneric(e,t,n){const i=new DataView(n).getUint32(5,!1),r=new Uint8Array(n,9,i),s=(new TextDecoder).decode(r);return{...JSON.parse(s),type:e,timestamp:t}}static isBinaryMessage(e){return e instanceof ArrayBuffer}static estimateSavings(e){const t=Math.ceil(1.33*e),n=e+5,i=t-n;return{binarySize:n,savings:i,savingsPercent:i/t*100}}}const T=_.scope("AuthService");class E{constructor(){this.currentToken=null;const e=c.websocket.url.replace("ws://","http://").replace("wss://","https://"),t=e.substring(0,e.lastIndexOf("/ws"));this.tokenEndpoint=`${t}/api/auth/token`}async requestToken(){try{const e=await fetch(this.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/json"}});if(!e.ok){const t=await e.text();throw new Error(`Failed to get auth token: ${e.status} ${t}`)}const t=await e.json();return this.currentToken={token:t.token,ttl:t.ttl,origin:t.origin,expiresAt:Date.now()+1e3*t.ttl},T.debug(`Auth token received (valid for ${t.ttl}s)`),t.token}catch(e){throw A.handleError(e,"auth"),e}}async getToken(){return this.currentToken&&this.isTokenValid()?this.currentToken.token:await this.requestToken()}isTokenValid(){if(!this.currentToken)return!1;return Date.now()+6e4<this.currentToken.expiresAt}clearToken(){this.currentToken=null}getTokenTimeRemaining(){if(!this.currentToken)return null;const e=this.currentToken.expiresAt-Date.now();return Math.max(0,Math.floor(e/1e3))}}const C=_.scope("SocketService");class R extends S{constructor(e=c.websocket.url){super(),this.url=e,this.ws=null,this.connectionState="disconnected",this.reconnectAttempts=0,this.reconnectTimeout=null,this.heartbeatInterval=null,this.messageQueue=[],this.maxQueueSize=100,this.isIntentionallyClosed=!1,this.useBinaryProtocol=!1,this.authService=new E,A.registerHandler("websocket",e=>{this.emit("error",e)})}async connect(){if("connected"===this.connectionState||"connecting"===this.connectionState)return;this.isIntentionallyClosed=!1,this.setConnectionState("connecting");let e=this.url;if(c.auth.enabled)try{const t=await this.authService.getToken(),n=e.includes("?")?"&":"?";e=`${e}${n}token=${encodeURIComponent(t)}`,C.debug("Connecting with authentication token")}catch(t){C.warn("Failed to get auth token, attempting connection without auth:",t)}return new Promise((n,i)=>{let r;try{this.ws=new WebSocket(e),this.ws.binaryType="arraybuffer",r=window.setTimeout(()=>{"connecting"===this.connectionState&&(this.ws?.close(),i(new Error("Connection timeout")))},c.websocket.connectionTimeout),this.ws.onopen=()=>{void 0!==r&&clearTimeout(r),this.onOpen(),n()},this.ws.onmessage=e=>this.onMessage(e),this.ws.onerror=e=>this.onError(e),this.ws.onclose=e=>this.onClose(e)}catch(t){void 0!==r&&clearTimeout(r),this.setConnectionState("error"),A.handleError(t,"websocket"),i(t)}})}onOpen(){C.info("WebSocket connected"),this.setConnectionState("connected"),this.reconnectAttempts=0,this.startHeartbeat(),this.flushMessageQueue(),this.emit("connected")}onMessage(e){try{let t;t=e.data instanceof ArrayBuffer?this.useBinaryProtocol?w.decode(e.data):{type:"audio_chunk",data:e.data,timestamp:Date.now(),sessionId:""}:JSON.parse(e.data),this.emit("message",t),this.emit(t.type,t)}catch(t){A.handleError(t,"websocket")}}onError(e){C.error("WebSocket error:",e),A.handleError(new Error("WebSocket error"),"websocket")}onClose(e){C.info("WebSocket closed:",e.code,e.reason),this.stopHeartbeat(),this.setConnectionState("disconnected"),this.emit("disconnected",e),1008===e.code&&c.auth.enabled&&(C.info("Auth failed, clearing token"),this.authService.clearToken()),!this.isIntentionallyClosed&&this.reconnectAttempts<c.websocket.reconnectAttempts&&this.scheduleReconnect()}scheduleReconnect(){if(null!==this.reconnectTimeout)return;this.setConnectionState("reconnecting");const e=this.calculateReconnectDelay();C.info(`Reconnecting in ${e}ms (attempt ${this.reconnectAttempts+1}/${c.websocket.reconnectAttempts})`),this.reconnectTimeout=window.setTimeout(()=>{this.reconnectTimeout=null,this.reconnectAttempts++,this.connect().catch(e=>{C.error("Reconnection failed:",e)})},e)}calculateReconnectDelay(){return Math.min(c.websocket.initialReconnectDelay*Math.pow(2,this.reconnectAttempts),c.websocket.maxReconnectDelay)}startHeartbeat(){this.heartbeatInterval=window.setInterval(()=>{this.isConnected()&&this.send({type:"ping",timestamp:Date.now()})},c.websocket.heartbeatInterval)}stopHeartbeat(){null!==this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null)}send(e){if(this.isConnected())try{if(this.useBinaryProtocol){const t=w.encode(e);this.ws.send(t)}else if(("audio_input"===e.type||"audio"===e.type)&&e.data instanceof ArrayBuffer){const t=new Uint8Array(e.data);let n="";for(let e=0;e<t.byteLength;e++)n+=String.fromCharCode(t[e]);const i=btoa(n),r={...e,data:i};this.ws.send(JSON.stringify(r))}else this.ws.send(JSON.stringify(e))}catch(t){A.handleError(t,"websocket"),this.queueMessage(e)}else this.queueMessage(e)}queueMessage(e){this.messageQueue.length>=this.maxQueueSize&&(C.warn("Message queue full, dropping oldest message"),this.messageQueue.shift()),this.messageQueue.push(e)}flushMessageQueue(){for(;this.messageQueue.length>0&&this.isConnected();){const e=this.messageQueue.shift();this.send(e)}}isConnected(){return null!==this.ws&&this.ws.readyState===WebSocket.OPEN}getConnectionState(){return this.connectionState}setConnectionState(e){this.connectionState!==e&&(this.connectionState=e,this.emit("connectionStateChanged",e))}disconnect(){this.isIntentionallyClosed=!0,null!==this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.stopHeartbeat(),this.ws&&(this.ws.close(1e3,"Client disconnect"),this.ws=null),this.setConnectionState("disconnected")}dispose(){this.disconnect(),this.removeAllListeners(),this.messageQueue=[]}}const I=_.scope("AudioInput");class P{constructor(){this.mediaStream=null,this.mediaRecorder=null,this.audioContext=null,this.sourceNode=null,this.scriptProcessor=null,this.workletNode=null,this.isRecording=!1,this.onDataAvailable=null,this.audioChunks=[],this.currentFormat="webm",this.useWorklet=!0,this.resampleBuffer=[],this.TARGET_SAMPLE_RATE=24e3,this.TARGET_BUFFER_SIZE=2400}async requestPermission(){try{return(await navigator.mediaDevices.getUserMedia({audio:{sampleRate:c.audio.input.sampleRate,channelCount:c.audio.input.channels,echoCancellation:c.audio.input.echoCancellation,noiseSuppression:c.audio.input.noiseSuppression,autoGainControl:c.audio.input.autoGainControl}})).getTracks().forEach(e=>e.stop()),!0}catch(e){return A.handleError(e,"audio-input"),!1}}async startRecording(e,t="webm"){this.isRecording?I.warn("Already recording"):(this.onDataAvailable=e,this.audioChunks=[],this.currentFormat=t,"pcm16"===t?await this.startPCM16Recording(e):await this.startWebMRecording(e))}async startPCM16Recording(e){try{this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:c.audio.input.echoCancellation,noiseSuppression:c.audio.input.noiseSuppression,autoGainControl:c.audio.input.autoGainControl}}),I.info("Microphone stream obtained");const n=this.mediaStream.getAudioTracks();I.debug(`Audio tracks: ${n.length}`),n.forEach((e,t)=>{I.debug(` Track ${t}: ${e.label}, enabled: ${e.enabled}, muted: ${e.muted}, readyState: ${e.readyState}`);const n=e.getSettings();I.debug(` Settings: sampleRate=${n.sampleRate}, channelCount=${n.channelCount}`)}),this.audioContext=new AudioContext,"suspended"===this.audioContext.state&&await this.audioContext.resume();const i=this.audioContext.sampleRate;if(I.debug(`AudioContext state: ${this.audioContext.state}, sample rate: ${i}Hz`),this.sourceNode=this.audioContext.createMediaStreamSource(this.mediaStream),this.useWorklet&&this.audioContext.audioWorklet)try{await this.startWithAudioWorklet(e,i)}catch(t){I.warn("AudioWorklet failed, falling back to ScriptProcessorNode:",t),this.useWorklet=!1,await this.startWithScriptProcessor(e,i)}else await this.startWithScriptProcessor(e,i);this.isRecording=!0}catch(n){throw A.handleError(n,"audio-input"),this.cleanup(),n}}async startWithAudioWorklet(e,t){if(!this.audioContext||!this.sourceNode)throw new Error("AudioContext not initialized");await this.audioContext.audioWorklet.addModule("/pcm16-processor.worklet.js"),this.workletNode=new AudioWorkletNode(this.audioContext,"pcm16-processor",{numberOfInputs:1,numberOfOutputs:1,channelCount:1}),this.workletNode.port.postMessage({type:"config",sampleRate:t}),this.workletNode.port.onmessage=e=>{if("audio"===e.data.type)this.onDataAvailable&&this.onDataAvailable(e.data.data);else if("debug"===e.data.type){const{counter:t,min:n,max:i,avg:r,samples:s}=e.data.data;I.debug(`[Worklet ${t}] Audio input - min: ${n}, max: ${i}, avg: ${r}, samples: ${s}`)}},I.debug("Connecting audio nodes (AudioWorklet)..."),this.sourceNode.connect(this.workletNode),this.workletNode.connect(this.audioContext.destination),I.info("PCM16 recording started at 24kHz using AudioWorklet (optimized)")}async startWithScriptProcessor(e,t){if(!this.audioContext||!this.sourceNode)throw new Error("AudioContext not initialized");const n=t/this.TARGET_SAMPLE_RATE;I.debug(`Using ScriptProcessorNode with resample ratio: ${n.toFixed(2)}`),this.scriptProcessor=this.audioContext.createScriptProcessor(4096,1,1),this.resampleBuffer=[];let i=0,r=0;I.debug("Setting up onaudioprocess handler..."),this.scriptProcessor.onaudioprocess=e=>{r++;const t=e.inputBuffer.getChannelData(0);if(1===r||r%10==0){let e=0,n=0,i=0;for(let r=0;r<t.length;r++)t[r]>e&&(e=t[r]),t[r]<n&&(n=t[r]),i+=Math.abs(t[r]);const s=i/t.length;I.debug(`[${r}] Audio input - min: ${n.toFixed(4)}, max: ${e.toFixed(4)}, avg: ${s.toFixed(6)}, samples: ${t.length}`)}for(let r=0;r<t.length;r++)i++,i>=n&&(i-=n,this.resampleBuffer.push(t[r]));for(;this.resampleBuffer.length>=this.TARGET_BUFFER_SIZE;){const e=this.resampleBuffer.splice(0,this.TARGET_BUFFER_SIZE),t=new Int16Array(this.TARGET_BUFFER_SIZE);for(let n=0;n<this.TARGET_BUFFER_SIZE;n++){const i=Math.max(-1,Math.min(1,e[n]));t[n]=i<0?32768*i:32767*i}this.onDataAvailable&&this.onDataAvailable(t.buffer)}},I.debug("Connecting audio nodes (ScriptProcessor)..."),this.sourceNode.connect(this.scriptProcessor),this.scriptProcessor.connect(this.audioContext.destination),I.info("PCM16 recording started at 24kHz using ScriptProcessorNode (fallback)")}async startWebMRecording(e){try{this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:c.audio.input.sampleRate,channelCount:c.audio.input.channels,echoCancellation:c.audio.input.echoCancellation,noiseSuppression:c.audio.input.noiseSuppression,autoGainControl:c.audio.input.autoGainControl}});const e=["audio/webm;codecs=opus","audio/webm","audio/ogg;codecs=opus"].find(e=>MediaRecorder.isTypeSupported(e));if(!e)throw new Error("No supported audio codec found");this.mediaRecorder=new MediaRecorder(this.mediaStream,{mimeType:e}),this.mediaRecorder.ondataavailable=e=>{e.data.size>0&&(this.audioChunks.push(e.data),e.data.arrayBuffer().then(e=>{this.onDataAvailable&&this.onDataAvailable(e)}))},this.mediaRecorder.onerror=e=>{A.handleError(new Error(`MediaRecorder error: ${e.error}`),"audio-input")},this.mediaRecorder.start(100),this.isRecording=!0,I.info("Recording started with codec:",e)}catch(t){throw A.handleError(t,"audio-input"),this.cleanup(),t}}stopRecording(){if(this.isRecording){try{"pcm16"===this.currentFormat?(this.workletNode&&(this.workletNode.disconnect(),this.workletNode.port.onmessage=null),this.scriptProcessor&&this.scriptProcessor.disconnect(),this.sourceNode&&this.sourceNode.disconnect(),this.audioContext&&this.audioContext.close()):this.mediaRecorder&&"inactive"!==this.mediaRecorder.state&&this.mediaRecorder.stop()}catch(e){A.handleError(e,"audio-input")}this.isRecording=!1,I.info("Recording stopped")}}pauseRecording(){if(this.isRecording)try{"pcm16"===this.currentFormat?this.audioContext&&"running"===this.audioContext.state&&this.audioContext.suspend():this.mediaRecorder&&"recording"===this.mediaRecorder.state&&this.mediaRecorder.pause()}catch(e){A.handleError(e,"audio-input")}}resumeRecording(){if(this.isRecording)try{"pcm16"===this.currentFormat?this.audioContext&&"suspended"===this.audioContext.state&&this.audioContext.resume():this.mediaRecorder&&"paused"===this.mediaRecorder.state&&this.mediaRecorder.resume()}catch(e){A.handleError(e,"audio-input")}}isCurrentlyRecording(){return"pcm16"===this.currentFormat?this.isRecording&&"running"===this.audioContext?.state:this.isRecording&&"recording"===this.mediaRecorder?.state}getRecordingState(){return"pcm16"===this.currentFormat?this.audioContext?"running"===this.audioContext.state?"recording":"suspended"===this.audioContext.state?"paused":"inactive":"inactive":this.mediaRecorder?this.mediaRecorder.state:"inactive"}getCurrentFormat(){return this.currentFormat}cleanup(){this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.workletNode&&(this.workletNode.disconnect(),this.workletNode.port.onmessage=null,this.workletNode=null),this.scriptProcessor&&(this.scriptProcessor.disconnect(),this.scriptProcessor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.audioContext&&(this.audioContext.close().catch(()=>{}),this.audioContext=null),this.mediaRecorder=null,this.isRecording=!1,this.onDataAvailable=null,this.audioChunks=[]}dispose(){this.stopRecording(),this.cleanup()}}class D{constructor(e){if(this.head=0,this.tail=0,this.count=0,e<=0)throw new Error("Capacity must be positive");this.capacity=e,this.buffer=new Array(e)}push(e){this.buffer[this.tail]=e,this.tail=(this.tail+1)%this.capacity,this.count<this.capacity?this.count++:this.head=(this.head+1)%this.capacity}pop(){if(0===this.count)return;const e=this.buffer[this.head];return this.buffer[this.head]=void 0,this.head=(this.head+1)%this.capacity,this.count--,e}peek(){if(0!==this.count)return this.buffer[this.head]}get size(){return this.count}get isFull(){return this.count===this.capacity}get isEmpty(){return 0===this.count}clear(){for(let e=0;e<this.capacity;e++)this.buffer[e]=void 0;this.head=0,this.tail=0,this.count=0}toArray(){const e=[];let t=this.head;for(let n=0;n<this.count;n++){const n=this.buffer[t];void 0!==n&&e.push(n),t=(t+1)%this.capacity}return e}}const B=_.scope("AdaptiveBuffer");class L{constructor(e=100,t=50,n=500){this.jitterHistory=[],this.underrunCount=0,this.historySize=100,this.adjustmentInterval=5e3,this.lastAdjustmentTime=0,this.targetBufferMs=e,this.minBufferMs=t,this.maxBufferMs=n}recordArrival(e,t=Date.now()){const n=t-e;this.jitterHistory.push({receiveTime:t,sentTime:e,jitter:n}),this.jitterHistory.length>this.historySize&&this.jitterHistory.shift();const i=Date.now();i-this.lastAdjustmentTime>=this.adjustmentInterval&&(this.adjustBufferSize(),this.lastAdjustmentTime=i)}recordUnderrun(){this.underrunCount++;this.targetBufferMs=Math.min(this.maxBufferMs,this.targetBufferMs+50),B.warn(`Buffer underrun detected. Increasing buffer to ${this.targetBufferMs}ms (underrun #${this.underrunCount})`)}adjustBufferSize(){if(this.jitterHistory.length<10)return;const e=this.calculateJitterStats(),t=e.p95,n=e.average;let i=t*(this.underrunCount>3?2:1.5);if(i=Math.max(this.minBufferMs,Math.min(this.maxBufferMs,i)),Math.abs(i-this.targetBufferMs)>20){const e=this.targetBufferMs;this.targetBufferMs=Math.round(i),B.debug(`Adaptive buffer adjustment: ${e}ms -> ${this.targetBufferMs}ms (avg jitter: ${n.toFixed(0)}ms, p95: ${t.toFixed(0)}ms, underruns: ${this.underrunCount})`)}}calculateJitterStats(){if(0===this.jitterHistory.length)return{average:0,p95:0,min:0,max:0};const e=this.jitterHistory.map(e=>e.jitter),t=e.slice().sort((e,t)=>e-t);return{average:e.reduce((e,t)=>e+t,0)/e.length,p95:t[Math.floor(.95*t.length)]||t[t.length-1],min:t[0],max:t[t.length-1]}}getTargetBufferMs(){return this.targetBufferMs}getTargetBufferFrames(e){return Math.ceil(this.targetBufferMs/e)}isBufferHealthy(e){return e>=.8*this.targetBufferMs}getStats(){const e=this.calculateJitterStats();let t;return t=e.p95<50?"excellent":e.p95<100?"good":e.p95<200?"fair":"poor",{currentBufferMs:this.targetBufferMs,targetBufferMs:this.targetBufferMs,minBufferMs:this.minBufferMs,maxBufferMs:this.maxBufferMs,averageJitter:e.average,p95Jitter:e.p95,underrunCount:this.underrunCount,networkQuality:t}}reset(){this.jitterHistory=[],this.underrunCount=0,this.lastAdjustmentTime=0}getMinBufferFramesForStart(e){const t=1.5*this.targetBufferMs;return Math.ceil(t/e)}}const F=_.scope("AudioContextManager"),U=class e{constructor(){this._context=null,this._isResumeListenerAdded=!1,this._resumePromise=null,this._sampleRate=24e3}static getInstance(){return e._instance||(e._instance=new e),e._instance}getContext(e){if(this._context)return this._context;e&&(this._sampleRate=e);try{const e=window.AudioContext||window.webkitAudioContext;this._context=new e({sampleRate:this._sampleRate,latencyHint:"interactive"}),F.info(`AudioContext created: sampleRate=${this._context.sampleRate}, state=${this._context.state}`),this.setupResumeListener(),this._context.onstatechange=()=>{F.debug(`AudioContext state changed: ${this._context?.state}`)}}catch(t){throw A.handleError(t,"audio-context-manager"),t}return this._context}setupResumeListener(){if(this._isResumeListenerAdded)return;const e=async()=>{await this.resume()},t=["click","touchstart","keydown"],n=async()=>{t.forEach(e=>{document.removeEventListener(e,n)}),await e()};t.forEach(e=>{document.addEventListener(e,n,{once:!0,passive:!0})}),this._isResumeListenerAdded=!0,F.debug("Audio resume listeners added")}async resume(){if(this._context&&"running"!==this._context.state)return this._resumePromise||(this._resumePromise=this._context.resume().then(()=>{F.info("AudioContext resumed successfully")}).catch(e=>{F.error("Failed to resume AudioContext:",e),A.handleError(e,"audio-context-manager")}).finally(()=>{this._resumePromise=null})),this._resumePromise}async suspend(){if(this._context&&"running"===this._context.state)try{await this._context.suspend(),F.debug("AudioContext suspended")}catch(e){F.error("Failed to suspend AudioContext:",e)}}getState(){return this._context?.state??"uninitialized"}getSampleRate(){return this._context?.sampleRate??this._sampleRate}getCurrentTime(){return this._context?.currentTime??0}isReady(){return null!==this._context&&"running"===this._context.state}createBufferSource(){return this._context?.createBufferSource()??null}createBuffer(e,t,n){return this._context?this._context.createBuffer(e,t,n??this._context.sampleRate):null}getDestination(){return this._context?.destination??null}async close(){if(this._context){try{await this._context.close(),F.info("AudioContext closed")}catch(e){F.error("Failed to close AudioContext:",e)}this._context=null,this._isResumeListenerAdded=!1}}_reset(){this._context=null,this._isResumeListenerAdded=!1,this._resumePromise=null,e._instance=null}};U._instance=null;const k=U.getInstance(),N=_.scope("AudioOutput");class O{constructor(){this.isPlaying=!1,this.currentSourceNode=null,this.activeSourceNodes=new Set,this.nextPlayTime=0,this.sessionId=null,this.sampleRate=c.audio.output.sampleRate,this.isStopped=!1,this.chunkDurationMs=100,this.audioBuffer=new D(c.audio.output.maxBufferFrames),this.adaptiveBuffer=new L(100,50,500),k.getContext(this.sampleRate)}get audioContext(){return k.getContext()}startSession(e,t){N.info("Audio output session started:",e),this.sessionId=e,this.isStopped=!1,t&&(this.sampleRate=t),this.audioBuffer.clear(),this.isPlaying=!1,this.nextPlayTime=0}addAudioChunk(e,t){if(this.isStopped)return;if(!this.audioContext)return void N.warn("Audio context not initialized");const n=Date.now(),i={data:e,timestamp:t,sampleRate:this.sampleRate};if(this.audioBuffer.push(i),this.adaptiveBuffer.recordArrival(t,n),!this.isPlaying){const e=this.adaptiveBuffer.getMinBufferFramesForStart(this.chunkDurationMs);this.audioBuffer.size>=e&&this.startPlayback()}}async startPlayback(){if(!this.isPlaying&&this.audioContext){this.isPlaying=!0,this.nextPlayTime=this.audioContext.currentTime;try{await this.playNextChunk()}catch(e){N.error("Playback error:",e),this.isPlaying=!1}}}async playNextChunk(){if(!this.isPlaying||this.isStopped)return;const e=this.audioBuffer.pop();if(!e)return N.warn("Audio buffer underrun"),this.adaptiveBuffer.recordUnderrun(),void(this.isPlaying=!1);try{const t=new Int16Array(e.data),n=this.audioContext.createBuffer(1,t.length,this.sampleRate),i=n.getChannelData(0);for(let e=0;e<t.length;e++)i[e]=t[e]/32768;const r=this.audioContext.createBufferSource();r.buffer=n,r.connect(this.audioContext.destination),this.activeSourceNodes.add(r);const s=Math.max(this.nextPlayTime,this.audioContext.currentTime);r.start(s),this.currentSourceNode=r,this.nextPlayTime=s+n.duration,r.onended=()=>{this.activeSourceNodes.delete(r),this.currentSourceNode=null,this.isPlaying&&!this.isStopped&&this.playNextChunk()}}catch(t){N.error("Error playing chunk:",t),this.isPlaying&&!this.isStopped&&setTimeout(()=>this.playNextChunk(),50)}}endSession(e){this.sessionId===e&&(N.info("Audio output session ended:",e),this.audioBuffer.size>0&&!this.isPlaying&&this.startPlayback(),this.sessionId=null)}stop(){N.debug("AudioOutput.stop() called, stopping",this.activeSourceNodes.size,"active sources"),this.isStopped=!0,this.isPlaying=!1;for(const e of this.activeSourceNodes)try{e.stop(),e.disconnect()}catch{}this.activeSourceNodes.clear(),this.currentSourceNode=null,this.audioBuffer.clear(),this.nextPlayTime=0,this.sessionId=null,N.debug("Audio stopped completely")}getBufferSize(){return this.audioBuffer.size}isBufferHealthy(){const e=this.audioBuffer.size*this.chunkDurationMs;return this.adaptiveBuffer.isBufferHealthy(e)}getBufferStats(){return this.adaptiveBuffer.getStats()}dispose(){this.stop()}}const z=_.scope("ObjectPool");class H{constructor(e,t,n=10){this.factory=e,this.reset=t,this.available=[],this.inUse=new Set;for(let i=0;i<n;i++)this.available.push(e())}acquire(){let e=this.available.pop();return e||(e=this.factory()),this.inUse.add(e),e}release(e){this.inUse.has(e)?(this.inUse.delete(e),this.reset(e),this.available.push(e)):z.warn("Attempting to release object not from this pool")}getStats(){return{available:this.available.length,inUse:this.inUse.size,total:this.available.length+this.inUse.size}}clear(){this.available=[],this.inUse.clear()}}class V{constructor(e,t=60){this.arkitNames=e,this.pool=new H(()=>({weights:this.createEmptyWeights(),status:"LISTENING",endOfSpeech:!1}),e=>{const t=this.arkitNames,n=e.weights;for(let i=0;i<t.length;i++)n[t[i]]=0;e.status="LISTENING",e.endOfSpeech=!1},t)}createEmptyWeights(){const e={},t=this.arkitNames;for(let n=0;n<t.length;n++)e[t[n]]=0;return e}acquire(){return this.pool.acquire()}release(e){this.pool.release(e)}getStats(){return this.pool.getStats()}clear(){this.pool.clear()}}const G=["browDownLeft","browDownRight","browInnerUp","browOuterUpLeft","browOuterUpRight","cheekPuff","cheekSquintLeft","cheekSquintRight","eyeBlinkLeft","eyeBlinkRight","eyeLookDownLeft","eyeLookDownRight","eyeLookInLeft","eyeLookInRight","eyeLookOutLeft","eyeLookOutRight","eyeLookUpLeft","eyeLookUpRight","eyeSquintLeft","eyeSquintRight","eyeWideLeft","eyeWideRight","jawForward","jawLeft","jawOpen","jawRight","mouthClose","mouthDimpleLeft","mouthDimpleRight","mouthFrownLeft","mouthFrownRight","mouthFunnel","mouthLeft","mouthLowerDownLeft","mouthLowerDownRight","mouthPressLeft","mouthPressRight","mouthPucker","mouthRight","mouthRollLower","mouthRollUpper","mouthShrugLower","mouthShrugUpper","mouthSmileLeft","mouthSmileRight","mouthStretchLeft","mouthStretchRight","mouthUpperUpLeft","mouthUpperUpRight","noseSneerLeft","noseSneerRight","tongueOut"];function W(){const e={};for(const t of G)e[t]=0;return e}function j(e,t){for(const n of G)t[n]=e[n]??0}const X=_.scope("BlendshapeBuffer");class q{constructor(){this.currentFrame=null,this.sessionId=null,this.lastUpdateTime=0,this.frameInterval=1e3/c.blendshape.fps,this.isSpeaking=!1,this.speechEnded=!1,this.totalFramesReceived=0,this.sessionStartTime=0,this.lastResult=null,this.buffer=new D(c.blendshape.bufferSize),this.neutralWeights=W(),this.resultPool=new V([...G],60)}startSession(e){X.info("Blendshape session started:",e),this.sessionId=e,this.buffer.clear(),this.currentFrame=null,this.lastUpdateTime=0,this.isSpeaking=!0,this.speechEnded=!1,this.totalFramesReceived=0,this.sessionStartTime=performance.now()}addFrame(e,t){const n={weights:e,timestamp:t};this.buffer.push(n),this.totalFramesReceived++,this.buffer.size%30==0&&X.debug("Buffer size:",this.buffer.size)}getFrame(e){this.lastResult&&(this.resultPool.release(this.lastResult),this.lastResult=null);const t=e??performance.now(),n=this.resultPool.acquire();if(t-this.lastUpdateTime<this.frameInterval){return j(this.isSpeaking?this.currentFrame?.weights??this.neutralWeights:this.neutralWeights,n.weights),n.status=this.isSpeaking?"SPEAKING":"LISTENING",n.endOfSpeech=!1,this.lastResult=n,n}this.lastUpdateTime=t;const i=this.buffer.pop();if(!i){const e=this.isSpeaking;return this.speechEnded&&(this.isSpeaking=!1,this.currentFrame=null),j(this.neutralWeights,n.weights),n.status="LISTENING",n.endOfSpeech=e&&this.speechEnded,this.lastResult=n,n}this.isSpeaking=!0,c.blendshape.interpolation&&this.currentFrame?this.currentFrame=this.interpolateFrames(this.currentFrame,i,c.blendshape.smoothing):this.currentFrame=i;const r=this.speechEnded&&0===this.buffer.size;return j(this.currentFrame.weights,n.weights),n.status="SPEAKING",n.endOfSpeech=r,this.lastResult=n,n}getFrameWeights(e){return this.getFrame(e).weights}interpolateFrames(e,t,n){const i={};for(const r of G){const s=e.weights[r]??0,a=t.weights[r]??0;i[r]=s+(a-s)*n}return{weights:i,timestamp:t.timestamp}}getCurrentFrame(){return this.currentFrame}getBufferSize(){return this.buffer.size}isBufferHealthy(){return this.buffer.size>=3}endSession(e){if(this.sessionId!==e)return;const t=(performance.now()-this.sessionStartTime)/1e3,n=Math.floor(t*c.blendshape.fps);X.info(`Blendshape session ended: ${e}`),X.debug(`Received ${this.totalFramesReceived} frames over ${t.toFixed(2)}s (expected ~${n} at ${c.blendshape.fps}fps)`),X.debug(`Buffer remaining: ${this.buffer.size} frames`),this.speechEnded=!0}isSpeakingState(){return this.isSpeaking}getNeutralWeights(){return{...this.neutralWeights}}clear(){this.buffer.clear(),this.currentFrame=null,this.isSpeaking=!1,this.speechEnded=!1,this.lastResult&&(this.resultPool.release(this.lastResult),this.lastResult=null)}dispose(){this.clear(),this.sessionId=null,this.resultPool.clear()}getPoolStats(){return this.resultPool.getStats()}}const Q=_.scope("SyncPlayback");class K{constructor(){this.frameBuffer=[],this.scheduledFrames=[],this.isPlaying=!1,this.isStopped=!1,this.sessionId=null,this.sampleRate=24e3,this.nextPlayTime=0,this.audioStartTime=0,this.activeSourceNodes=new Set,this.currentFrameIndex=0,this.lastBlendshapeUpdate=0,this.onBlendshapeUpdate=null,this.onPlaybackEnd=null,this.minBufferFrames=3,this.lastActiveFrameIndex=0,this.animationFrameId=null,this.maxSamplesPerFrame=2400,this.isVisible=!0,this.neutralWeights=W(),this.currentWeights=W(),this.pcmBuffer=new Int16Array(this.maxSamplesPerFrame),this.floatBuffer=new Float32Array(this.maxSamplesPerFrame),this.visibilityHandler=this.handleVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.visibilityHandler),k.getContext(this.sampleRate)}get audioContext(){return k.getContext(this.sampleRate)}handleVisibilityChange(){this.isVisible="visible"===document.visibilityState,this.isVisible||Q.debug("Tab hidden - reducing animation updates")}setBlendshapeCallback(e){this.onBlendshapeUpdate=e}setPlaybackEndCallback(e){this.onPlaybackEnd=e}startSession(e,t){Q.info("SyncPlayback session started:",e),this.sessionId=e,this.isStopped=!1,this.isPlaying=!1,t&&(this.sampleRate=t),this.frameBuffer=[],this.scheduledFrames=[],this.currentFrameIndex=0,this.nextPlayTime=0,this.audioStartTime=0,this.lastBlendshapeUpdate=0,this.lastActiveFrameIndex=0,this.currentWeights={...this.neutralWeights};for(const n of this.activeSourceNodes)try{n.stop(),n.disconnect()}catch{}this.activeSourceNodes.clear()}addSyncFrame(e){this.isStopped||(this.frameBuffer.push(e),0===e.frameIndex&&Q.debug("First sync frame added:",e.audio.byteLength,"bytes audio"),!this.isPlaying&&this.frameBuffer.length>=this.minBufferFrames&&this.startPlayback())}startPlayback(){!this.isPlaying&&this.audioContext&&0!==this.frameBuffer.length&&(Q.info("Starting synchronized playback with",this.frameBuffer.length,"buffered frames"),this.isPlaying=!0,this.audioStartTime=this.audioContext.currentTime,this.nextPlayTime=this.audioStartTime,this.playbackLoop())}playbackLoop(){if(!this.isPlaying||!this.audioContext||this.isStopped)return;const e=this.audioContext.currentTime;for(;this.frameBuffer.length>0&&this.nextPlayTime<e+.15;){const e=this.frameBuffer.shift();try{this.scheduleAudioFrame(e)}catch(t){Q.error("sync-playback","Error scheduling audio frame",t)}}this.isVisible&&this.updateBlendshapeForCurrentTime(),this.cleanupScheduledFrames(),this.frameBuffer.length>0||this.activeSourceNodes.size>0?this.animationFrameId=requestAnimationFrame(()=>this.playbackLoop()):this.handlePlaybackEnd()}scheduleAudioFrame(e){if(!this.audioContext)return;const t=new Int16Array(e.audio),n=t.length;let i;i=n<=this.maxSamplesPerFrame?this.floatBuffer.subarray(0,n):new Float32Array(n);const r=1/32768;for(let h=0;h<n;h++)i[h]=t[h]*r;const s=this.audioContext.createBuffer(1,n,this.sampleRate);s.getChannelData(0).set(i);const a=this.audioContext.createBufferSource();a.buffer=s,a.connect(this.audioContext.destination);const o=Math.max(this.nextPlayTime,this.audioContext.currentTime);a.start(o),this.activeSourceNodes.add(a);const l=s.duration,c={weights:e.weights,startTime:o,endTime:o+l,frameIndex:e.frameIndex};this.scheduledFrames.push(c),this.nextPlayTime=o+l,this.currentFrameIndex=e.frameIndex,a.onended=()=>{this.activeSourceNodes.delete(a)}}updateBlendshapeForCurrentTime(){if(!this.audioContext||!this.onBlendshapeUpdate)return;const e=this.audioContext.currentTime,t=e-1;for(;this.scheduledFrames.length>0&&this.scheduledFrames[0].endTime<t;)this.scheduledFrames.shift(),this.lastActiveFrameIndex=Math.max(0,this.lastActiveFrameIndex-1);let n=null;for(let i=this.lastActiveFrameIndex;i<this.scheduledFrames.length;i++){const t=this.scheduledFrames[i];if(e>=t.startTime&&e<t.endTime){n=t,this.lastActiveFrameIndex=i;break}}if(!n&&this.lastActiveFrameIndex>0)for(let i=0;i<this.lastActiveFrameIndex;i++){const t=this.scheduledFrames[i];if(e>=t.startTime&&e<t.endTime){n=t,this.lastActiveFrameIndex=i;break}}if(n)this.currentWeights=n.weights,this.onBlendshapeUpdate(n.weights);else if(this.isPlaying&&this.scheduledFrames.length>0){const t=this.scheduledFrames[this.scheduledFrames.length-1];e<t.endTime+.1&&this.onBlendshapeUpdate(t.weights)}}cleanupScheduledFrames(){if(!this.audioContext)return;const e=this.audioContext.currentTime;this.scheduledFrames=this.scheduledFrames.filter(t=>t.endTime>e-.05)}endSession(e){this.sessionId===e&&Q.info("SyncPlayback session ending:",e,"remaining frames:",this.frameBuffer.length)}handlePlaybackEnd(){this.isPlaying&&(Q.info("SyncPlayback complete, total frames:",this.currentFrameIndex+1),this.isPlaying=!1,this.onBlendshapeUpdate&&this.onBlendshapeUpdate(this.neutralWeights),this.onPlaybackEnd&&this.onPlaybackEnd())}stop(){Q.info("SyncPlayback stopped"),this.isStopped=!0,this.isPlaying=!1,this.frameBuffer=[],this.scheduledFrames=[],null!==this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null);for(const e of this.activeSourceNodes)try{e.stop(),e.disconnect()}catch{}this.activeSourceNodes.clear(),this.currentWeights={...this.neutralWeights},this.onBlendshapeUpdate&&this.onBlendshapeUpdate(this.neutralWeights)}getState(){const e=this.audioContext?this.audioContext.currentTime-this.audioStartTime:0;return{isPlaying:this.isPlaying,currentFrameIndex:this.currentFrameIndex,bufferSize:this.frameBuffer.length,audioPlaybackTime:Math.max(0,e)}}getNeutralWeights(){return{...this.neutralWeights}}getPerformanceStats(){return{activeSourceNodes:this.activeSourceNodes.size,scheduledFrames:this.scheduledFrames.length,bufferedFrames:this.frameBuffer.length}}dispose(){this.stop(),document.removeEventListener("visibilitychange",this.visibilityHandler),null!==this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}}const Y=_.scope("FeatureDetection");class Z{static checkWebSocket(){return"WebSocket"in window}static checkMediaRecorder(){return"MediaRecorder"in window}static checkGetUserMedia(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)}static checkWebAudio(){return"AudioContext"in window||"webkitAudioContext"in window}static checkWorker(){return"Worker"in window}static async checkMicrophonePermission(){if(!navigator.permissions)return"prompt";try{return(await navigator.permissions.query({name:"microphone"})).state}catch{return"prompt"}}static getSupportedAudioCodecs(){if(!this.checkMediaRecorder())return[];return["audio/webm;codecs=opus","audio/webm","audio/ogg;codecs=opus","audio/mp4"].filter(e=>MediaRecorder.isTypeSupported(e))}static getAvailableFeatures(){return{audioInput:this.checkGetUserMedia()&&this.checkMediaRecorder(),audioOutput:this.checkWebAudio(),blendshapes:!0,textChat:this.checkWebSocket()}}static getRecommendedMode(){const e=this.getAvailableFeatures();return e.audioInput&&e.audioOutput&&e.textChat?"full":e.audioOutput&&e.textChat?"audio-output-only":e.textChat?"text-only":"degraded"}static logCapabilities(){Y.info("Browser Capabilities:",{webSocket:this.checkWebSocket(),mediaRecorder:this.checkMediaRecorder(),getUserMedia:this.checkGetUserMedia(),webAudio:this.checkWebAudio(),worker:this.checkWorker(),supportedCodecs:this.getSupportedAudioCodecs(),recommendedMode:this.getRecommendedMode()})}}const J=_.scope("ChatManager");class ${constructor(e,t={}){this.currentSessionId=null,this.messages=[],this.isRecording=!1,this.animationFrameId=null,this.useSyncPlayback=!1,this.avatar=e,this.options=t,this.userId=this.generateUserId(),this.socketService=new R,this.audioInput=new P,this.audioOutput=new O,this.blendshapeBuffer=new q,this.syncPlayback=new K,this.syncPlayback.setBlendshapeCallback(e=>{this.avatar.updateBlendshapes(e)}),this.syncPlayback.setPlaybackEndCallback(()=>{J.info("SyncPlayback ended - transitioning to Idle"),this.avatar.setChatState("Idle"),this.avatar.disableLiveBlendshapes()});const n=t.shadowRoot||document;this.chatMessages=t.chatMessages||n.getElementById("chatMessages"),this.chatInput=t.chatInput||n.getElementById("chatInput"),this.sendBtn=t.sendBtn||n.getElementById("sendBtn"),this.micBtn=t.micBtn||n.getElementById("micBtn"),this.setupEventListeners(),this.setupWebSocketHandlers(),this.startBlendshapeSync()}async initialize(){Z.logCapabilities();try{await this.socketService.connect(),J.info("WebSocket connected"),this.avatar.setChatState("Idle")}catch(e){A.handleError(e,"chat-manager"),J.error("Connection failed"),this.options.onError?.(e)}}setupEventListeners(){const e=this.options.shadowRoot||document;this.sendBtn.addEventListener("click",()=>this.sendTextMessage()),this.chatInput.addEventListener("keypress",e=>{"Enter"===e.key&&this.sendTextMessage()}),this.micBtn.addEventListener("click",()=>this.toggleVoiceInput());const t=e.querySelector(".chat-header");this.options.shadowRoot||t?.addEventListener("click",()=>this.toggleChat());const n=e.getElementById?.("minimizeBtn");n?.addEventListener("click",e=>{e.stopPropagation(),this.toggleChat()});const i=e.getElementById?.("chatBubble");i?.addEventListener("click",()=>this.openChat())}setupWebSocketHandlers(){this.socketService.on("connected",()=>{J.debug("WebSocket connected"),this.options.onConnectionChange?.(!0)}),this.socketService.on("disconnected",()=>{J.info("WebSocket disconnected"),this.options.onConnectionChange?.(!1)}),this.socketService.on("connectionStateChanged",e=>{J.debug("Connection state:",e)}),this.socketService.on("text",e=>{"text"===e.type&&this.addMessage(e.data,"assistant")}),this.socketService.on("avatar_state",e=>{if("avatar_state"===e.type){const t={Idle:"Idle",Listening:"Hello",Thinking:"Hello",Responding:"Responding"}[e.state]||"Idle";this.avatar.setChatState(t)}}),this.socketService.on("audio_start",e=>{"audio_start"===e.type&&(J.info("Audio start received:",e.sessionId),this.currentSessionId=e.sessionId,this.syncPlayback.startSession(e.sessionId,e.sampleRate),this.audioOutput.startSession(e.sessionId,e.sampleRate),this.blendshapeBuffer.startSession(e.sessionId),this.useSyncPlayback=!1,this.avatar.enableLiveBlendshapes(),this.avatar.setChatState("Responding"))}),this.socketService.on("audio_chunk",e=>{if("audio_chunk"===e.type){let t;if(e.data instanceof ArrayBuffer)t=e.data;else{if("string"!=typeof e.data)return void J.warn("Unknown audio data format:",typeof e.data);{const n=atob(e.data),i=new Uint8Array(n.length);for(let e=0;e<n.length;e++)i[e]=n.charCodeAt(e);t=i.buffer,J.debug("Audio chunk received:",t.byteLength,"bytes")}}this.audioOutput.addAudioChunk(t,e.timestamp)}}),this.socketService.on("sync_frame",e=>{if("sync_frame"===e.type){this.useSyncPlayback=!0;const t=this.decodeBase64ToArrayBuffer(e.audio);0===e.frameIndex&&J.debug("First sync_frame received:",t.byteLength,"bytes audio + blendshapes");const n={audio:t,weights:e.weights,timestamp:e.timestamp,frameIndex:e.frameIndex};this.syncPlayback.addSyncFrame(n)}}),this.socketService.on("blendshape",e=>{"blendshape"===e.type&&this.blendshapeBuffer.addFrame(e.weights,e.timestamp)}),this.socketService.on("audio_end",e=>{"audio_end"===e.type&&(J.info("Audio end received"),this.useSyncPlayback?this.syncPlayback.endSession(e.sessionId):(this.audioOutput.endSession(e.sessionId),this.blendshapeBuffer.endSession(e.sessionId)),J.debug("Speech ended - buffer will drain naturally to idle"))}),this.socketService.on("interrupt",e=>{"interrupt"===e.type&&(J.info("Interrupt received - stopping audio playback"),this.syncPlayback.stop(),this.audioOutput.stop(),this.blendshapeBuffer.clear(),this.avatar.disableLiveBlendshapes(),this.avatar.setChatState("Hello"))}),this.socketService.on("transcript_delta",e=>{"transcript_delta"===e.type&&J.debug(`Transcript delta [${e.role}]: ${e.text}`)}),this.socketService.on("transcript_done",e=>{"transcript_done"===e.type&&(J.debug(`Transcript complete [${e.role}]: ${e.text}`),e.text&&this.addMessage(e.text,"assistant"===e.role?"assistant":"user"))}),this.socketService.on("error",e=>{J.error("Socket error:",e)})}sendText(e){if(!e.trim())return;this.addMessage(e,"user");const t={type:"text",data:e,userId:this.userId,timestamp:Date.now()};this.socketService.send(t)}sendTextMessage(){const e=this.chatInput.value.trim();if(!e)return;"Idle"===this.avatar.getChatState()&&this.avatar.setChatState("Hello"),this.addMessage(e,"user"),this.chatInput.value="";const t={type:"text",data:e,userId:this.userId,timestamp:Date.now()};this.socketService.send(t)}async toggleVoiceInput(){this.isRecording||this.avatar.setChatState("Hello"),this.isRecording?this.stopRecording():await this.startRecording()}async startRecording(){try{const e="audio/pcm16",t=24e3,n={type:"audio_stream_start",userId:this.userId,format:e,sampleRate:t,timestamp:Date.now()};this.socketService.send(n),await this.audioInput.startRecording(n=>{const i={type:"audio",data:n,format:e,userId:this.userId,timestamp:Date.now(),sampleRate:t};this.socketService.send(i)},"pcm16"),this.isRecording=!0,this.micBtn.classList.add("recording"),this.micBtn.setAttribute("aria-pressed","true")}catch(e){A.handleError(e,"audio-input"),alert("Microphone access denied. Please enable microphone permissions.")}}stopRecording(){this.audioInput.stopRecording();const e={type:"audio_stream_end",userId:this.userId,timestamp:Date.now()};this.socketService.send(e),this.isRecording=!1,this.micBtn.classList.remove("recording"),this.micBtn.setAttribute("aria-pressed","false")}startBlendshapeSync(){const e=()=>{if(!this.useSyncPlayback){const e=this.blendshapeBuffer.getFrame();this.avatar.updateBlendshapes(e.weights),"SPEAKING"===e.status?"Responding"!==this.avatar.getChatState()&&(J.debug("Starting speech - body animation: Responding"),this.avatar.setChatState("Responding")):"LISTENING"===e.status&&e.endOfSpeech&&(J.debug("End of speech - body animation: Hello"),this.avatar.setChatState("Hello"))}this.animationFrameId=requestAnimationFrame(e)};e()}addMessage(e,t){const n={id:Date.now().toString(),text:e,sender:t,timestamp:Date.now()};this.messages.push(n),this.renderMessage(n),this.scrollToBottom(),this.options.onMessage?.({role:t,text:e})}renderMessage(e){const t=document.createElement("div");t.className=`message ${e.sender}`;const n=document.createElement("div");n.className="message-bubble",n.textContent=e.text;const i=document.createElement("div");i.className="message-time",i.textContent=new Date(e.timestamp).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),t.appendChild(n),t.appendChild(i),this.chatMessages.appendChild(t)}scrollToBottom(){this.chatMessages.scrollTop=this.chatMessages.scrollHeight}toggleChat(){const e=document.getElementById("chatWidget"),t=document.getElementById("chatBubble"),n=e?.classList.toggle("minimized");n?(t?.classList.remove("hidden"),this.resetOnMinimize()):t?.classList.add("hidden")}resetOnMinimize(){this.isRecording&&this.stopRecording(),this.syncPlayback.stop(),this.audioOutput.stop(),this.blendshapeBuffer.clear(),this.avatar.disableLiveBlendshapes(),this.avatar.setChatState("Idle"),"pause"in this.avatar&&this.avatar.pause(),J.debug("Chat minimized - reset audio, animation, and avatar state")}openChat(){const e=document.getElementById("chatWidget"),t=document.getElementById("chatBubble");e?.classList.remove("minimized"),t?.classList.add("hidden"),"resume"in this.avatar&&this.avatar.resume(),this.chatInput?.focus()}generateUserId(){return`user_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}decodeBase64ToArrayBuffer(e){const t=atob(e),n=t.length,i=new Uint8Array(n);for(let r=0;r<n;r++)i[r]=t.charCodeAt(r);return i.buffer}dispose(){null!==this.animationFrameId&&cancelAnimationFrame(this.animationFrameId),this.socketService.dispose(),this.audioInput.dispose(),this.audioOutput.dispose(),this.blendshapeBuffer.dispose(),this.syncPlayback.dispose()}}const ee=_.scope("Widget"),te={position:"bottom-right",theme:"light",startCollapsed:!0,width:380,height:550,enableVoice:!0,enableText:!0,avatarUrl:"./asset/nyx.zip",authEnabled:!0,logLevel:"error"};class AvatarChatElement extends HTMLElement{constructor(){super(),this.avatar=null,this.chatManager=null,this._isMounted=!1,this._isConnected=!1,this._isCollapsed=!1,this.shadow=this.attachShadow({mode:"open"})}configure(e){this.config={...te,...e};const t={none:h,error:u,warn:d,info:p,debug:f};_.setLevel(t[this.config.logLevel||"error"]),l({websocket:{url:this.config.serverUrl}})}async mount(){if(this._isMounted)return void ee.warn("Widget already mounted");ee.info("Mounting widget");const e=document.createElement("style");e.textContent="\n/* Reset all inherited styles */\n:host {\n all: initial;\n display: block;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;\n font-size: 14px;\n line-height: 1.5;\n color: #333;\n box-sizing: border-box;\n}\n\n:host *, :host *::before, :host *::after {\n box-sizing: inherit;\n}\n\n/* Position variants */\n:host(.position-bottom-right) { position: fixed; bottom: 20px; right: 20px; z-index: 999999; }\n:host(.position-bottom-left) { position: fixed; bottom: 20px; left: 20px; z-index: 999999; }\n:host(.position-top-right) { position: fixed; top: 20px; right: 20px; z-index: 999999; }\n:host(.position-top-left) { position: fixed; top: 20px; left: 20px; z-index: 999999; }\n:host(.position-inline) { position: relative; }\n:host(.hidden) { display: none !important; }\n\n/* Main container */\n.widget-root {\n width: 100%;\n height: 100%;\n display: flex;\n flex-direction: column;\n background: #ffffff;\n border-radius: 16px;\n box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);\n overflow: hidden;\n transition: all 0.3s ease;\n}\n\n.widget-root.theme-dark {\n background: #1a1a2e;\n color: #e0e0e0;\n}\n\n/* Collapsed bubble state */\n:host(.collapsed) {\n width: 64px !important;\n height: 64px !important;\n}\n\n.chat-bubble {\n width: 64px;\n height: 64px;\n border-radius: 50%;\n background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);\n display: flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n box-shadow: 0 4px 16px rgba(102, 126, 234, 0.4);\n transition: transform 0.2s, box-shadow 0.2s;\n}\n\n.chat-bubble:hover {\n transform: scale(1.08);\n box-shadow: 0 6px 20px rgba(102, 126, 234, 0.5);\n}\n\n.chat-bubble svg {\n width: 28px;\n height: 28px;\n fill: white;\n}\n\n/* Avatar section */\n.avatar-section {\n position: relative;\n flex: 0 0 auto;\n height: 180px;\n background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);\n overflow: hidden;\n}\n\n.theme-dark .avatar-section {\n background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);\n}\n\n.avatar-container {\n width: 100%;\n height: 100%;\n position: relative;\n}\n\n.avatar-render-container {\n width: 400px;\n height: 400px;\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%) scale(0.45);\n transform-origin: center;\n /* OPTIMIZATION: Hint browser to optimize for transform animations */\n will-change: transform;\n}\n\n/* Header */\n.chat-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 10px 16px;\n background: rgba(255, 255, 255, 0.95);\n border-bottom: 1px solid #eee;\n}\n\n.theme-dark .chat-header {\n background: rgba(26, 26, 46, 0.95);\n border-bottom-color: #333;\n}\n\n.status-indicator {\n display: flex;\n align-items: center;\n gap: 8px;\n font-size: 12px;\n color: #666;\n}\n\n.theme-dark .status-indicator { color: #aaa; }\n\n.status-dot {\n width: 8px;\n height: 8px;\n border-radius: 50%;\n background: #ccc;\n transition: background 0.3s;\n}\n\n.status-dot.connected { background: #4caf50; }\n.status-dot.connecting { background: #ff9800; animation: pulse 1s infinite; }\n.status-dot.error { background: #f44336; }\n\n@keyframes pulse {\n 0%, 100% { opacity: 1; }\n 50% { opacity: 0.5; }\n}\n\n.header-actions {\n display: flex;\n gap: 4px;\n}\n\n.icon-btn {\n background: none;\n border: none;\n cursor: pointer;\n padding: 6px;\n border-radius: 6px;\n color: #666;\n transition: background 0.2s;\n display: flex;\n align-items: center;\n justify-content: center;\n}\n\n.icon-btn:hover { background: rgba(0, 0, 0, 0.05); }\n.theme-dark .icon-btn { color: #aaa; }\n.theme-dark .icon-btn:hover { background: rgba(255, 255, 255, 0.1); }\n\n/* Messages */\n.messages-section {\n flex: 1;\n overflow-y: auto;\n padding: 16px;\n display: flex;\n flex-direction: column;\n gap: 10px;\n min-height: 0;\n}\n\n.message {\n max-width: 85%;\n padding: 10px 14px;\n border-radius: 16px;\n word-wrap: break-word;\n font-size: 14px;\n line-height: 1.4;\n}\n\n.message.user {\n align-self: flex-end;\n background: #007bff;\n color: white;\n border-bottom-right-radius: 4px;\n}\n\n.message.assistant {\n align-self: flex-start;\n background: #f0f0f0;\n color: #333;\n border-bottom-left-radius: 4px;\n}\n\n.theme-dark .message.assistant {\n background: #2d2d44;\n color: #e0e0e0;\n}\n\n.message-time {\n font-size: 10px;\n opacity: 0.7;\n margin-top: 4px;\n}\n\n/* Input area */\n.input-section {\n display: flex;\n gap: 8px;\n padding: 12px 16px;\n border-top: 1px solid #eee;\n background: #fafafa;\n}\n\n.theme-dark .input-section {\n background: #16213e;\n border-top-color: #333;\n}\n\n.chat-input {\n flex: 1;\n padding: 10px 14px;\n border: 1px solid #ddd;\n border-radius: 24px;\n outline: none;\n font-size: 14px;\n font-family: inherit;\n transition: border-color 0.2s, box-shadow 0.2s;\n}\n\n.chat-input:focus {\n border-color: #007bff;\n box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);\n}\n\n.theme-dark .chat-input {\n background: #1a1a2e;\n border-color: #444;\n color: #e0e0e0;\n}\n\n.theme-dark .chat-input:focus {\n border-color: #667eea;\n box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.2);\n}\n\n.action-btn {\n width: 40px;\n height: 40px;\n border: none;\n border-radius: 50%;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: background 0.2s, transform 0.1s;\n flex-shrink: 0;\n}\n\n.action-btn:active { transform: scale(0.95); }\n\n.voice-btn {\n background: #f0f0f0;\n color: #666;\n}\n\n.voice-btn:hover { background: #e0e0e0; }\n\n.voice-btn.recording {\n background: #ff4444;\n color: white;\n animation: pulse 1s infinite;\n}\n\n.theme-dark .voice-btn {\n background: #2d2d44;\n color: #aaa;\n}\n\n.theme-dark .voice-btn:hover { background: #3d3d54; }\n\n.send-btn {\n background: #007bff;\n color: white;\n}\n\n.send-btn:hover { background: #0056b3; }\n.send-btn:disabled { background: #ccc; cursor: not-allowed; }\n\n/* Loading states */\n.loading-overlay {\n position: absolute;\n inset: 0;\n background: rgba(255, 255, 255, 0.9);\n display: flex;\n align-items: center;\n justify-content: center;\n flex-direction: column;\n gap: 12px;\n}\n\n.theme-dark .loading-overlay {\n background: rgba(26, 26, 46, 0.9);\n}\n\n.spinner {\n width: 32px;\n height: 32px;\n border: 3px solid #eee;\n border-top-color: #007bff;\n border-radius: 50%;\n animation: spin 0.8s linear infinite;\n}\n\n@keyframes spin {\n to { transform: rotate(360deg); }\n}\n\n/* Accessibility */\n.visually-hidden {\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n margin: -1px;\n overflow: hidden;\n clip: rect(0, 0, 0, 0);\n white-space: nowrap;\n border: 0;\n}\n"+(this.config.customStyles||""),this.shadow.appendChild(e),this.config.position&&"inline"!==this.config.position&&this.classList.add(`position-${this.config.position}`),this.style.width=`${this.config.width}px`,this.style.height=`${this.config.height}px`,this.config.startCollapsed?(this._isCollapsed=!0,this.classList.add("collapsed"),this.renderBubble()):await this.renderWidget(),this._isMounted=!0,this.config.onReady?.()}async renderWidget(){const e=this.shadow.querySelector("style");this.shadow.innerHTML="",e&&this.shadow.appendChild(e);const t=document.createElement("div");t.innerHTML='\n<div class="widget-root">\n <div class="avatar-section">\n <div class="avatar-container">\n <div id="avatarCircle" class="avatar-render-container"></div>\n </div>\n </div>\n \n <div class="chat-header">\n <div class="status-indicator">\n <span class="status-dot connecting"></span>\n <span class="status-text">Connecting...</span>\n </div>\n <div class="header-actions">\n <button class="icon-btn minimize-btn" aria-label="Minimize">\n <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">\n <line x1="5" y1="12" x2="19" y2="12"/>\n </svg>\n </button>\n </div>\n </div>\n \n <div id="chatMessages" class="messages-section" role="log" aria-live="polite" aria-label="Chat messages"></div>\n \n <div class="input-section">\n <input \n type="text" \n id="chatInput"\n class="chat-input" \n placeholder="Type a message..." \n aria-label="Chat message input"\n />\n <button id="micBtn" class="action-btn voice-btn" aria-label="Voice input" aria-pressed="false">\n <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">\n <path d="M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3zm-1 1.93c-3.94-.49-7-3.85-7-7.93h2c0 3.31 2.69 6 6 6s6-2.69 6-6h2c0 4.08-3.06 7.44-7 7.93V20h4v2H8v-2h4v-4.07z"/>\n </svg>\n </button>\n <button id="sendBtn" class="action-btn send-btn" aria-label="Send message">\n <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">\n <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>\n </svg>\n </button>\n </div>\n</div>\n';const n=t.firstElementChild;if(("dark"===this.config.theme||"auto"===this.config.theme&&window.matchMedia("(prefers-color-scheme: dark)").matches)&&n.classList.add("theme-dark"),this.shadow.appendChild(n),this.setupUIEvents(),!this.config.enableVoice){const e=this.shadow.getElementById("micBtn");e&&(e.style.display="none")}if(!this.config.enableText){const e=this.shadow.querySelector(".input-section");e&&(e.style.display="none")}await this.initializeAvatar(),await this.initializeChat()}renderBubble(){const e=this.shadow.querySelector("style");this.shadow.innerHTML="",e&&this.shadow.appendChild(e);const t=document.createElement("div");t.innerHTML='\n<div class="chat-bubble" role="button" aria-label="Open chat" tabindex="0">\n <svg viewBox="0 0 24 24">\n <path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/>\n </svg>\n</div>\n';const n=t.firstElementChild;n.addEventListener("click",()=>this.expand()),n.addEventListener("keypress",e=>{"Enter"===e.key&&this.expand()}),this.shadow.appendChild(n)}async initializeAvatar(){const e=this.shadow.getElementById("avatarCircle");if(!e)return void ee.error("Avatar container not found");const t=document.createElement("div");t.style.width="400px",t.style.height="400px",e.appendChild(t);try{this.avatar=new x(t,this.config.avatarUrl||"./asset/nyx.zip",{preload:!0,onReady:()=>ee.info("Avatar loaded"),onError:e=>{ee.error("Avatar load error:",e),this.config.onError?.(e)}}),this.avatar.start()}catch(n){ee.error("Failed to initialize avatar:",n),this.config.onError?.(n)}}async initializeChat(){if(this.avatar)try{const e=this.shadow.getElementById("chatMessages"),t=this.shadow.getElementById("chatInput"),n=this.shadow.getElementById("sendBtn"),i=this.shadow.getElementById("micBtn");if(!(e&&t&&n&&i))throw new Error("Required DOM elements not found");this.chatManager=new $(this.avatar,{shadowRoot:this.shadow,chatMessages:e,chatInput:t,sendBtn:n,micBtn:i,onConnectionChange:e=>{this._isConnected=e,this.updateConnectionStatus(e),this.config.onConnectionChange?.(e)},onMessage:e=>{this.config.onMessage?.(e)},onError:e=>{this.config.onError?.(e)}}),await this.chatManager.initialize(),ee.info("Chat initialized")}catch(e){ee.error("Failed to initialize chat:",e),this.updateConnectionStatus(!1,"error"),this.config.onError?.(e)}else ee.error("Avatar not initialized")}setupUIEvents(){const e=this.shadow.querySelector(".minimize-btn");e?.addEventListener("click",()=>this.collapse()),"auto"===this.config.theme&&window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",e=>{const t=this.shadow.querySelector(".widget-root");t?.classList.toggle("theme-dark",e.matches)})}updateConnectionStatus(e,t){const n=this.shadow.querySelector(".status-dot"),i=this.shadow.querySelector(".status-text");n&&(n.classList.remove("connected","connecting","error"),"error"===t?n.classList.add("error"):n.classList.add(e?"connected":"connecting")),i&&(i.textContent="error"===t?"Connection failed":e?"Connected":"Connecting...")}collapse(){this._isCollapsed||(this._isCollapsed=!0,this.classList.add("collapsed"),this.renderBubble())}async expand(){this._isCollapsed&&(this._isCollapsed=!1,this.classList.remove("collapsed"),this.style.width=`${this.config.width}px`,this.style.height=`${this.config.height}px`,await this.renderWidget())}show(){this.classList.remove("hidden")}hide(){this.classList.add("hidden")}sendMessage(e){this.chatManager&&e.trim()&&this.chatManager.sendText(e)}isMounted(){return this._isMounted}isServerConnected(){return this._isConnected}destroy(){ee.info("Destroying widget"),this.chatManager&&(this.chatManager.dispose(),this.chatManager=null),this.avatar&&(this.avatar.dispose(),this.avatar=null),this.shadow.innerHTML="",this.remove(),this._isMounted=!1,this._isConnected=!1}}"undefined"==typeof customElements||customElements.get("avatar-chat-widget")||customElements.define("avatar-chat-widget",AvatarChatElement);const AvatarChat={version:"__VERSION__",_instance:null,init(e){if(!e.serverUrl)throw new Error("AvatarChat.init(): serverUrl is required");if(!e.container)throw new Error("AvatarChat.init(): container is required");const t="string"==typeof e.container?document.querySelector(e.container):e.container;if(!t)throw new Error(`AvatarChat.init(): container not found: ${e.container}`);this._instance&&(this._instance.destroy(),this._instance=null);const n=document.createElement("avatar-chat-widget");return n.configure(e),t.appendChild(n),n.mount(),this._instance=n,{sendMessage:e=>n.sendMessage(e),mount:()=>n.mount(),destroy:()=>{n.destroy(),this._instance=null},show:()=>n.show(),hide:()=>n.hide(),expand:()=>n.expand(),collapse:()=>n.collapse(),isMounted:()=>n.isMounted(),isConnected:()=>n.isServerConnected()}},destroy(){this._instance&&(this._instance.destroy(),this._instance=null)},getInstance(){if(!this._instance)return null;const e=this._instance;return{sendMessage:t=>e.sendMessage(t),mount:()=>e.mount(),destroy:()=>{e.destroy(),this._instance=null},show:()=>e.show(),hide:()=>e.hide(),expand:()=>e.expand(),collapse:()=>e.collapse(),isMounted:()=>e.isMounted(),isConnected:()=>e.isServerConnected()}}};"undefined"!=typeof window&&(window.AvatarChat=AvatarChat);const ne="182",ie=0,re=1,se=2,ae=0,oe=1,le=2,ce=3,he=1,ue=3,de=0,pe=1,fe=2,me=100,ge=101,_e=102,ve=200,xe=201,ye=202,Se=203,Ae=204,be=205,Me=206,we=207,Te=208,Ee=209,Ce=210,Re=211,Ie=212,Pe=213,De=214,Be=0,Le=1,Fe=2,Ue=3,ke=4,Ne=5,Oe=6,ze=7,He=0,Ve=1,Ge=2,We=1,je=2,Xe=3,qe=4,Qe=5,Ke=6,Ye=7,Ze="attached",Je=301,$e=302,et=306,tt=1e3,nt=1001,it=1002,rt=1003,st=1004,at=1005,ot=1006,lt=1007,ct=1008,ht=1009,ut=1010,dt=1011,pt=1012,ft=1013,mt=1014,gt=1015,_t=1016,vt=1017,xt=1018,yt=1020,St=35902,At=35899,bt=1023,Mt=1026,wt=1027,Tt=1028,Et=1029,Ct=1030,Rt=1031,It=1033,Pt=33776,Dt=33777,Bt=33778,Lt=33779,Ft=35840,Ut=35841,kt=35842,Nt=35843,Ot=36196,zt=37492,Ht=37496,Vt=37488,Gt=37489,Wt=37490,jt=37491,Xt=37808,qt=37809,Qt=37810,Kt=37811,Yt=37812,Zt=37813,Jt=37814,$t=37815,en=37816,tn=37817,nn=37818,rn=37819,sn=37820,an=37821,on=36492,ln=36494,cn=36495,hn=36283,un=36284,dn=36285,pn=36286,fn=2200,mn=2201,gn=2300,_n=2301,vn=2302,xn=2400,yn=2401,Sn=2402,An=2500,bn="",Mn="srgb",wn="srgb-linear",Tn="linear",En="srgb",Cn=7680,Rn=512,In=513,Pn=514,Dn=515,Bn=516,Ln=517,Fn=518,Un=519,kn=35044,Nn=35048,On="300 es",zn=2e3,Hn=2001;function Vn(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}function Gn(e){return document.createElementNS("http://www.w3.org/1999/xhtml",e)}function Wn(){const e=Gn("canvas");return e.style.display="block",e}const jn={};function Xn(...e){e.shift()}function qn(...e){const t="THREE."+e.shift();console.warn(t,...e)}function Qn(...e){const t="THREE."+e.shift();console.error(t,...e)}function Kn(...e){const t=e.join(" ");t in jn||(jn[t]=!0,qn(...e))}class Yn{addEventListener(e,t){void 0===this._listeners&&(this._listeners={});const n=this._listeners;void 0===n[e]&&(n[e]=[]),-1===n[e].indexOf(t)&&n[e].push(t)}hasEventListener(e,t){const n=this._listeners;return void 0!==n&&(void 0!==n[e]&&-1!==n[e].indexOf(t))}removeEventListener(e,t){const n=this._listeners;if(void 0===n)return;const i=n[e];if(void 0!==i){const e=i.indexOf(t);-1!==e&&i.splice(e,1)}}dispatchEvent(e){const t=this._listeners;if(void 0===t)return;const n=t[e.type];if(void 0!==n){e.target=this;const t=n.slice(0);for(let n=0,i=t.length;n<i;n++)t[n].call(this,e);e.target=null}}}const Zn=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];let Jn=1234567;const $n=Math.PI/180,ei=180/Math.PI;function ti(){const e=4294967295*Math.random()|0,t=4294967295*Math.random()|0,n=4294967295*Math.random()|0,i=4294967295*Math.random()|0;return(Zn[255&e]+Zn[e>>8&255]+Zn[e>>16&255]+Zn[e>>24&255]+"-"+Zn[255&t]+Zn[t>>8&255]+"-"+Zn[t>>16&15|64]+Zn[t>>24&255]+"-"+Zn[63&n|128]+Zn[n>>8&255]+"-"+Zn[n>>16&255]+Zn[n>>24&255]+Zn[255&i]+Zn[i>>8&255]+Zn[i>>16&255]+Zn[i>>24&255]).toLowerCase()}function ni(e,t,n){return Math.max(t,Math.min(n,e))}function ii(e,t){return(e%t+t)%t}function ri(e,t,n){return(1-n)*e+n*t}function si(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:return e/255;case Int32Array:return Math.max(e/2147483647,-1);case Int16Array:return Math.max(e/32767,-1);case Int8Array:return Math.max(e/127,-1);default:throw new Error("Invalid component type.")}}function ai(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return Math.round(4294967295*e);case Uint16Array:return Math.round(65535*e);case Uint8Array:return Math.round(255*e);case Int32Array:return Math.round(2147483647*e);case Int16Array:return Math.round(32767*e);case Int8Array:return Math.round(127*e);default:throw new Error("Invalid component type.")}}const oi={DEG2RAD:$n,RAD2DEG:ei,generateUUID:ti,clamp:ni,euclideanModulo:ii,mapLinear:function(e,t,n,i,r){return i+(e-t)*(r-i)/(n-t)},inverseLerp:function(e,t,n){return e!==t?(n-e)/(t-e):0},lerp:ri,damp:function(e,t,n,i){return ri(e,t,1-Math.exp(-n*i))},pingpong:function(e,t=1){return t-Math.abs(ii(e,2*t)-t)},smoothstep:function(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t))*e*(3-2*e)},smootherstep:function(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t))*e*e*(e*(6*e-15)+10)},randInt:function(e,t){return e+Math.floor(Math.random()*(t-e+1))},randFloat:function(e,t){return e+Math.random()*(t-e)},randFloatSpread:function(e){return e*(.5-Math.random())},seededRandom:function(e){void 0!==e&&(Jn=e);let t=Jn+=1831565813;return t=Math.imul(t^t>>>15,1|t),t^=t+Math.imul(t^t>>>7,61|t),((t^t>>>14)>>>0)/4294967296},degToRad:function(e){return e*$n},radToDeg:function(e){return e*ei},isPowerOfTwo:function(e){return!(e&e-1)&&0!==e},ceilPowerOfTwo:function(e){return Math.pow(2,Math.ceil(Math.log(e)/Math.LN2))},floorPowerOfTwo:function(e){return Math.pow(2,Math.floor(Math.log(e)/Math.LN2))},setQuaternionFromProperEuler:function(e,t,n,i,r){const s=Math.cos,a=Math.sin,o=s(n/2),l=a(n/2),c=s((t+i)/2),h=a((t+i)/2),u=s((t-i)/2),d=a((t-i)/2),p=s((i-t)/2),f=a((i-t)/2);switch(r){case"XYX":e.set(o*h,l*u,l*d,o*c);break;case"YZY":e.set(l*d,o*h,l*u,o*c);break;case"ZXZ":e.set(l*u,l*d,o*h,o*c);break;case"XZX":e.set(o*h,l*f,l*p,o*c);break;case"YXY":e.set(l*p,o*h,l*f,o*c);break;case"ZYZ":e.set(l*f,l*p,o*h,o*c);break;default:qn("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}},normalize:ai,denormalize:si};class li{constructor(e=0,t=0){li.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,n=this.y,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6],this.y=i[1]*t+i[4]*n+i[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=ni(this.x,e.x,t.x),this.y=ni(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=ni(this.x,e,t),this.y=ni(this.y,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(ni(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(0===t)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(ni(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const n=Math.cos(t),i=Math.sin(t),r=this.x-e.x,s=this.y-e.y;return this.x=r*n-s*i+e.x,this.y=r*i+s*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class ci{constructor(e=0,t=0,n=0,i=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=i}static slerpFlat(e,t,n,i,r,s,a){let o=n[i+0],l=n[i+1],c=n[i+2],h=n[i+3],u=r[s+0],d=r[s+1],p=r[s+2],f=r[s+3];if(a<=0)return e[t+0]=o,e[t+1]=l,e[t+2]=c,void(e[t+3]=h);if(a>=1)return e[t+0]=u,e[t+1]=d,e[t+2]=p,void(e[t+3]=f);if(h!==f||o!==u||l!==d||c!==p){let e=o*u+l*d+c*p+h*f;e<0&&(u=-u,d=-d,p=-p,f=-f,e=-e);let t=1-a;if(e<.9995){const n=Math.acos(e),i=Math.sin(n);t=Math.sin(t*n)/i,o=o*t+u*(a=Math.sin(a*n)/i),l=l*t+d*a,c=c*t+p*a,h=h*t+f*a}else{o=o*t+u*a,l=l*t+d*a,c=c*t+p*a,h=h*t+f*a;const e=1/Math.sqrt(o*o+l*l+c*c+h*h);o*=e,l*=e,c*=e,h*=e}}e[t]=o,e[t+1]=l,e[t+2]=c,e[t+3]=h}static multiplyQuaternionsFlat(e,t,n,i,r,s){const a=n[i],o=n[i+1],l=n[i+2],c=n[i+3],h=r[s],u=r[s+1],d=r[s+2],p=r[s+3];return e[t]=a*p+c*h+o*d-l*u,e[t+1]=o*p+c*u+l*h-a*d,e[t+2]=l*p+c*d+a*u-o*h,e[t+3]=c*p-a*h-o*u-l*d,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,i){return this._x=e,this._y=t,this._z=n,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const n=e._x,i=e._y,r=e._z,s=e._order,a=Math.cos,o=Math.sin,l=a(n/2),c=a(i/2),h=a(r/2),u=o(n/2),d=o(i/2),p=o(r/2);switch(s){case"XYZ":this._x=u*c*h+l*d*p,this._y=l*d*h-u*c*p,this._z=l*c*p+u*d*h,this._w=l*c*h-u*d*p;break;case"YXZ":this._x=u*c*h+l*d*p,this._y=l*d*h-u*c*p,this._z=l*c*p-u*d*h,this._w=l*c*h+u*d*p;break;case"ZXY":this._x=u*c*h-l*d*p,this._y=l*d*h+u*c*p,this._z=l*c*p+u*d*h,this._w=l*c*h-u*d*p;break;case"ZYX":this._x=u*c*h-l*d*p,this._y=l*d*h+u*c*p,this._z=l*c*p-u*d*h,this._w=l*c*h+u*d*p;break;case"YZX":this._x=u*c*h+l*d*p,this._y=l*d*h+u*c*p,this._z=l*c*p-u*d*h,this._w=l*c*h-u*d*p;break;case"XZY":this._x=u*c*h-l*d*p,this._y=l*d*h-u*c*p,this._z=l*c*p+u*d*h,this._w=l*c*h+u*d*p;break;default:qn("Quaternion: .setFromEuler() encountered an unknown order: "+s)}return!0===t&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const n=t/2,i=Math.sin(n);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,n=t[0],i=t[4],r=t[8],s=t[1],a=t[5],o=t[9],l=t[2],c=t[6],h=t[10],u=n+a+h;if(u>0){const e=.5/Math.sqrt(u+1);this._w=.25/e,this._x=(c-o)*e,this._y=(r-l)*e,this._z=(s-i)*e}else if(n>a&&n>h){const e=2*Math.sqrt(1+n-a-h);this._w=(c-o)/e,this._x=.25*e,this._y=(i+s)/e,this._z=(r+l)/e}else if(a>h){const e=2*Math.sqrt(1+a-n-h);this._w=(r-l)/e,this._x=(i+s)/e,this._y=.25*e,this._z=(o+c)/e}else{const e=2*Math.sqrt(1+h-n-a);this._w=(s-i)/e,this._x=(r+l)/e,this._y=(o+c)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<1e-8?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(ni(this.dot(e),-1,1)))}rotateTowards(e,t){const n=this.angleTo(e);if(0===n)return this;const i=Math.min(1,t/n);return this.slerp(e,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return 0===e?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const n=e._x,i=e._y,r=e._z,s=e._w,a=t._x,o=t._y,l=t._z,c=t._w;return this._x=n*c+s*a+i*l-r*o,this._y=i*c+s*o+r*a-n*l,this._z=r*c+s*l+n*o-i*a,this._w=s*c-n*a-i*o-r*l,this._onChangeCallback(),this}slerp(e,t){if(t<=0)return this;if(t>=1)return this.copy(e);let n=e._x,i=e._y,r=e._z,s=e._w,a=this.dot(e);a<0&&(n=-n,i=-i,r=-r,s=-s,a=-a);let o=1-t;if(a<.9995){const e=Math.acos(a),l=Math.sin(e);o=Math.sin(o*e)/l,t=Math.sin(t*e)/l,this._x=this._x*o+n*t,this._y=this._y*o+i*t,this._z=this._z*o+r*t,this._w=this._w*o+s*t,this._onChangeCallback()}else this._x=this._x*o+n*t,this._y=this._y*o+i*t,this._z=this._z*o+r*t,this._w=this._w*o+s*t,this.normalize();return this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),i=Math.sqrt(1-n),r=Math.sqrt(n);return this.set(i*Math.sin(e),i*Math.cos(e),r*Math.sin(t),r*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class hi{constructor(e=0,t=0,n=0){hi.prototype.isVector3=!0,this.x=e,this.y=t,this.z=n}set(e,t,n){return void 0===n&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(di.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(di.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,n=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6]*i,this.y=r[1]*t+r[4]*n+r[7]*i,this.z=r[2]*t+r[5]*n+r[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,n=this.y,i=this.z,r=e.elements,s=1/(r[3]*t+r[7]*n+r[11]*i+r[15]);return this.x=(r[0]*t+r[4]*n+r[8]*i+r[12])*s,this.y=(r[1]*t+r[5]*n+r[9]*i+r[13])*s,this.z=(r[2]*t+r[6]*n+r[10]*i+r[14])*s,this}applyQuaternion(e){const t=this.x,n=this.y,i=this.z,r=e.x,s=e.y,a=e.z,o=e.w,l=2*(s*i-a*n),c=2*(a*t-r*i),h=2*(r*n-s*t);return this.x=t+o*l+s*h-a*c,this.y=n+o*c+a*l-r*h,this.z=i+o*h+r*c-s*l,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,n=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[4]*n+r[8]*i,this.y=r[1]*t+r[5]*n+r[9]*i,this.z=r[2]*t+r[6]*n+r[10]*i,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=ni(this.x,e.x,t.x),this.y=ni(this.y,e.y,t.y),this.z=ni(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=ni(this.x,e,t),this.y=ni(this.y,e,t),this.z=ni(this.z,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(ni(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const n=e.x,i=e.y,r=e.z,s=t.x,a=t.y,o=t.z;return this.x=i*o-r*a,this.y=r*s-n*o,this.z=n*a-i*s,this}projectOnVector(e){const t=e.lengthSq();if(0===t)return this.set(0,0,0);const n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return ui.copy(this).projectOnVector(e),this.sub(ui)}reflect(e){return this.sub(ui.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(0===t)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(ni(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y,i=this.z-e.z;return t*t+n*n+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){const i=Math.sin(t)*e;return this.x=i*Math.sin(n),this.y=Math.cos(t)*e,this.z=i*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=i,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,4*t)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,3*t)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=2*Math.random()-1,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const ui=new hi,di=new ci;class pi{constructor(e,t,n,i,r,s,a,o,l){pi.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],void 0!==e&&this.set(e,t,n,i,r,s,a,o,l)}set(e,t,n,i,r,s,a,o,l){const c=this.elements;return c[0]=e,c[1]=i,c[2]=a,c[3]=t,c[4]=r,c[5]=o,c[6]=n,c[7]=s,c[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,i=t.elements,r=this.elements,s=n[0],a=n[3],o=n[6],l=n[1],c=n[4],h=n[7],u=n[2],d=n[5],p=n[8],f=i[0],m=i[3],g=i[6],_=i[1],v=i[4],x=i[7],y=i[2],S=i[5],A=i[8];return r[0]=s*f+a*_+o*y,r[3]=s*m+a*v+o*S,r[6]=s*g+a*x+o*A,r[1]=l*f+c*_+h*y,r[4]=l*m+c*v+h*S,r[7]=l*g+c*x+h*A,r[2]=u*f+d*_+p*y,r[5]=u*m+d*v+p*S,r[8]=u*g+d*x+p*A,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],s=e[4],a=e[5],o=e[6],l=e[7],c=e[8];return t*s*c-t*a*l-n*r*c+n*a*o+i*r*l-i*s*o}invert(){const e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],s=e[4],a=e[5],o=e[6],l=e[7],c=e[8],h=c*s-a*l,u=a*o-c*r,d=l*r-s*o,p=t*h+n*u+i*d;if(0===p)return this.set(0,0,0,0,0,0,0,0,0);const f=1/p;return e[0]=h*f,e[1]=(i*l-c*n)*f,e[2]=(a*n-i*s)*f,e[3]=u*f,e[4]=(c*t-i*o)*f,e[5]=(i*r-a*t)*f,e[6]=d*f,e[7]=(n*o-l*t)*f,e[8]=(s*t-n*r)*f,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,i,r,s,a){const o=Math.cos(r),l=Math.sin(r);return this.set(n*o,n*l,-n*(o*s+l*a)+s+e,-i*l,i*o,-i*(-l*s+o*a)+a+t,0,0,1),this}scale(e,t){return this.premultiply(fi.makeScale(e,t)),this}rotate(e){return this.premultiply(fi.makeRotation(-e)),this}translate(e,t){return this.premultiply(fi.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,n=e.elements;for(let i=0;i<9;i++)if(t[i]!==n[i])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return(new this.constructor).fromArray(this.elements)}}const fi=new pi,mi=(new pi).set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),gi=(new pi).set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function _i(){const e={enabled:!0,workingColorSpace:wn,spaces:{},convert:function(e,t,n){return!1!==this.enabled&&t!==n&&t&&n?(this.spaces[t].transfer===En&&(e.r=xi(e.r),e.g=xi(e.g),e.b=xi(e.b)),this.spaces[t].primaries!==this.spaces[n].primaries&&(e.applyMatrix3(this.spaces[t].toXYZ),e.applyMatrix3(this.spaces[n].fromXYZ)),this.spaces[n].transfer===En&&(e.r=yi(e.r),e.g=yi(e.g),e.b=yi(e.b)),e):e},workingToColorSpace:function(e,t){return this.convert(e,this.workingColorSpace,t)},colorSpaceToWorking:function(e,t){return this.convert(e,t,this.workingColorSpace)},getPrimaries:function(e){return this.spaces[e].primaries},getTransfer:function(e){return e===bn?Tn:this.spaces[e].transfer},getToneMappingMode:function(e){return this.spaces[e].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(e,t=this.workingColorSpace){return e.fromArray(this.spaces[t].luminanceCoefficients)},define:function(e){Object.assign(this.spaces,e)},_getMatrix:function(e,t,n){return e.copy(this.spaces[t].toXYZ).multiply(this.spaces[n].fromXYZ)},_getDrawingBufferColorSpace:function(e){return this.spaces[e].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(e=this.workingColorSpace){return this.spaces[e].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(t,n){return Kn("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),e.workingToColorSpace(t,n)},toWorkingColorSpace:function(t,n){return Kn("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),e.colorSpaceToWorking(t,n)}},t=[.64,.33,.3,.6,.15,.06],n=[.2126,.7152,.0722],i=[.3127,.329];return e.define({[wn]:{primaries:t,whitePoint:i,transfer:Tn,toXYZ:mi,fromXYZ:gi,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:Mn},outputColorSpaceConfig:{drawingBufferColorSpace:Mn}},[Mn]:{primaries:t,whitePoint:i,transfer:En,toXYZ:mi,fromXYZ:gi,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:Mn}}}),e}const vi=_i();function xi(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}function yi(e){return e<.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}let Si;class Ai{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src))return e.src;if("undefined"==typeof HTMLCanvasElement)return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{void 0===Si&&(Si=Gn("canvas")),Si.width=e.width,Si.height=e.height;const t=Si.getContext("2d");e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),n=Si}return n.toDataURL(t)}static sRGBToLinear(e){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap){const t=Gn("canvas");t.width=e.width,t.height=e.height;const n=t.getContext("2d");n.drawImage(e,0,0,e.width,e.height);const i=n.getImageData(0,0,e.width,e.height),r=i.data;for(let e=0;e<r.length;e++)r[e]=255*xi(r[e]/255);return n.putImageData(i,0,0),t}if(e.data){const t=e.data.slice(0);for(let e=0;e<t.length;e++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[e]=Math.floor(255*xi(t[e]/255)):t[e]=xi(t[e]);return{data:t,width:e.width,height:e.height}}return qn("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let bi=0;class Mi{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:bi++}),this.uuid=ti(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){const t=this.data;return"undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight,0):"undefined"!=typeof VideoFrame&&t instanceof VideoFrame?e.set(t.displayHeight,t.displayWidth,0):null!==t?e.set(t.width,t.height,t.depth||0):e.set(0,0,0),e}set needsUpdate(e){!0===e&&this.version++}toJSON(e){const t=void 0===e||"string"==typeof e;if(!t&&void 0!==e.images[this.uuid])return e.images[this.uuid];const n={uuid:this.uuid,url:""},i=this.data;if(null!==i){let e;if(Array.isArray(i)){e=[];for(let t=0,n=i.length;t<n;t++)i[t].isDataTexture?e.push(wi(i[t].image)):e.push(wi(i[t]))}else e=wi(i);n.url=e}return t||(e.images[this.uuid]=n),n}}function wi(e){return"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?Ai.getDataURL(e):e.data?{data:Array.from(e.data),width:e.width,height:e.height,type:e.data.constructor.name}:(qn("Texture: Unable to serialize Texture."),{})}let Ti=0;const Ei=new hi;class Ci extends Yn{constructor(e=Ci.DEFAULT_IMAGE,t=Ci.DEFAULT_MAPPING,n=1001,i=1001,r=1006,s=1008,a=1023,o=ht,l=Ci.DEFAULT_ANISOTROPY,c=""){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:Ti++}),this.uuid=ti(),this.name="",this.source=new Mi(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=n,this.wrapT=i,this.magFilter=r,this.minFilter=s,this.anisotropy=l,this.format=a,this.internalFormat=null,this.type=o,this.offset=new li(0,0),this.repeat=new li(1,1),this.center=new li(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new pi,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=c,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(e&&e.depth&&e.depth>1),this.pmremVersion=0}get width(){return this.source.getSize(Ei).x}get height(){return this.source.getSize(Ei).y}get depth(){return this.source.getSize(Ei).z}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return(new this.constructor).copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(const t in e){const n=e[t];if(void 0===n){qn(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const i=this[t];void 0!==i?i&&n&&i.isVector2&&n.isVector2||i&&n&&i.isVector3&&n.isVector3||i&&n&&i.isMatrix3&&n.isMatrix3?i.copy(n):this[t]=n:qn(`Texture.setValues(): property '${t}' does not exist.`)}}toJSON(e){const t=void 0===e||"string"==typeof e;if(!t&&void 0!==e.textures[this.uuid])return e.textures[this.uuid];const n={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(300!==this.mapping)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case tt:e.x=e.x-Math.floor(e.x);break;case nt:e.x=e.x<0?0:1;break;case it:1===Math.abs(Math.floor(e.x)%2)?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x)}if(e.y<0||e.y>1)switch(this.wrapT){case tt:e.y=e.y-Math.floor(e.y);break;case nt:e.y=e.y<0?0:1;break;case it:1===Math.abs(Math.floor(e.y)%2)?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y)}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){!0===e&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){!0===e&&this.pmremVersion++}}Ci.DEFAULT_IMAGE=null,Ci.DEFAULT_MAPPING=300,Ci.DEFAULT_ANISOTROPY=1;class Ri{constructor(e=0,t=0,n=0,i=1){Ri.prototype.isVector4=!0,this.x=e,this.y=t,this.z=n,this.w=i}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,i){return this.x=e,this.y=t,this.z=n,this.w=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=void 0!==e.w?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,n=this.y,i=this.z,r=this.w,s=e.elements;return this.x=s[0]*t+s[4]*n+s[8]*i+s[12]*r,this.y=s[1]*t+s[5]*n+s[9]*i+s[13]*r,this.z=s[2]*t+s[6]*n+s[10]*i+s[14]*r,this.w=s[3]*t+s[7]*n+s[11]*i+s[15]*r,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,i,r;const s=.01,a=.1,o=e.elements,l=o[0],c=o[4],h=o[8],u=o[1],d=o[5],p=o[9],f=o[2],m=o[6],g=o[10];if(Math.abs(c-u)<s&&Math.abs(h-f)<s&&Math.abs(p-m)<s){if(Math.abs(c+u)<a&&Math.abs(h+f)<a&&Math.abs(p+m)<a&&Math.abs(l+d+g-3)<a)return this.set(1,0,0,0),this;t=Math.PI;const e=(l+1)/2,o=(d+1)/2,_=(g+1)/2,v=(c+u)/4,x=(h+f)/4,y=(p+m)/4;return e>o&&e>_?e<s?(n=0,i=.707106781,r=.707106781):(n=Math.sqrt(e),i=v/n,r=x/n):o>_?o<s?(n=.707106781,i=0,r=.707106781):(i=Math.sqrt(o),n=v/i,r=y/i):_<s?(n=.707106781,i=.707106781,r=0):(r=Math.sqrt(_),n=x/r,i=y/r),this.set(n,i,r,t),this}let _=Math.sqrt((m-p)*(m-p)+(h-f)*(h-f)+(u-c)*(u-c));return Math.abs(_)<.001&&(_=1),this.x=(m-p)/_,this.y=(h-f)/_,this.z=(u-c)/_,this.w=Math.acos((l+d+g-1)/2),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=ni(this.x,e.x,t.x),this.y=ni(this.y,e.y,t.y),this.z=ni(this.z,e.z,t.z),this.w=ni(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=ni(this.x,e,t),this.y=ni(this.y,e,t),this.z=ni(this.z,e,t),this.w=ni(this.w,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(ni(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this.w=e.w+(t.w-e.w)*n,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class Ii extends Yn{constructor(e=1,t=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:ot,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},n),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth,this.scissor=new Ri(0,0,e,t),this.scissorTest=!1,this.viewport=new Ri(0,0,e,t);const i={width:e,height:t,depth:n.depth},r=new Ci(i);this.textures=[];const s=n.count;for(let a=0;a<s;a++)this.textures[a]=r.clone(),this.textures[a].isRenderTargetTexture=!0,this.textures[a].renderTarget=this;this._setTextureOptions(n),this.depthBuffer=n.depthBuffer,this.stencilBuffer=n.stencilBuffer,this.resolveDepthBuffer=n.resolveDepthBuffer,this.resolveStencilBuffer=n.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=n.depthTexture,this.samples=n.samples,this.multiview=n.multiview}_setTextureOptions(e={}){const t={minFilter:ot,generateMipmaps:!1,flipY:!1,internalFormat:null};void 0!==e.mapping&&(t.mapping=e.mapping),void 0!==e.wrapS&&(t.wrapS=e.wrapS),void 0!==e.wrapT&&(t.wrapT=e.wrapT),void 0!==e.wrapR&&(t.wrapR=e.wrapR),void 0!==e.magFilter&&(t.magFilter=e.magFilter),void 0!==e.minFilter&&(t.minFilter=e.minFilter),void 0!==e.format&&(t.format=e.format),void 0!==e.type&&(t.type=e.type),void 0!==e.anisotropy&&(t.anisotropy=e.anisotropy),void 0!==e.colorSpace&&(t.colorSpace=e.colorSpace),void 0!==e.flipY&&(t.flipY=e.flipY),void 0!==e.generateMipmaps&&(t.generateMipmaps=e.generateMipmaps),void 0!==e.internalFormat&&(t.internalFormat=e.internalFormat);for(let n=0;n<this.textures.length;n++){this.textures[n].setValues(t)}}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){null!==this._depthTexture&&(this._depthTexture.renderTarget=null),null!==e&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,n=1){if(this.width!==e||this.height!==t||this.depth!==n){this.width=e,this.height=t,this.depth=n;for(let i=0,r=this.textures.length;i<r;i++)this.textures[i].image.width=e,this.textures[i].image.height=t,this.textures[i].image.depth=n,!0!==this.textures[i].isData3DTexture&&(this.textures[i].isArrayTexture=this.textures[i].image.depth>1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return(new this.constructor).copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,n=e.textures.length;t<n;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;const n=Object.assign({},e.textures[t].image);this.textures[t].source=new Mi(n)}return this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,null!==e.depthTexture&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this}dispose(){this.dispatchEvent({type:"dispose"})}}class Pi extends Ii{constructor(e=1,t=1,n={}){super(e,t,n),this.isWebGLRenderTarget=!0}}class Di extends Ci{constructor(e=null,t=1,n=1,i=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:n,depth:i},this.magFilter=rt,this.minFilter=rt,this.wrapR=nt,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class Bi extends Ci{constructor(e=null,t=1,n=1,i=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:n,depth:i},this.magFilter=rt,this.minFilter=rt,this.wrapR=nt,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class Li{constructor(e=new hi(1/0,1/0,1/0),t=new hi(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t+=3)this.expandByPoint(Ui.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(Ui.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){const n=Ui.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(n),this.max.copy(e).add(n),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return(new this.constructor).copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);const n=e.geometry;if(void 0!==n){const i=n.getAttribute("position");if(!0===t&&void 0!==i&&!0!==e.isInstancedMesh)for(let t=0,n=i.count;t<n;t++)!0===e.isMesh?e.getVertexPosition(t,Ui):Ui.fromBufferAttribute(i,t),Ui.applyMatrix4(e.matrixWorld),this.expandByPoint(Ui);else void 0!==e.boundingBox?(null===e.boundingBox&&e.computeBoundingBox(),ki.copy(e.boundingBox)):(null===n.boundingBox&&n.computeBoundingBox(),ki.copy(n.boundingBox)),ki.applyMatrix4(e.matrixWorld),this.union(ki)}const i=e.children;for(let r=0,s=i.length;r<s;r++)this.expandByObject(i[r],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,Ui),Ui.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Wi),ji.subVectors(this.max,Wi),Ni.subVectors(e.a,Wi),Oi.subVectors(e.b,Wi),zi.subVectors(e.c,Wi),Hi.subVectors(Oi,Ni),Vi.subVectors(zi,Oi),Gi.subVectors(Ni,zi);let t=[0,-Hi.z,Hi.y,0,-Vi.z,Vi.y,0,-Gi.z,Gi.y,Hi.z,0,-Hi.x,Vi.z,0,-Vi.x,Gi.z,0,-Gi.x,-Hi.y,Hi.x,0,-Vi.y,Vi.x,0,-Gi.y,Gi.x,0];return!!Qi(t,Ni,Oi,zi,ji)&&(t=[1,0,0,0,1,0,0,0,1],!!Qi(t,Ni,Oi,zi,ji)&&(Xi.crossVectors(Hi,Vi),t=[Xi.x,Xi.y,Xi.z],Qi(t,Ni,Oi,zi,ji)))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Ui).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=.5*this.getSize(Ui).length()),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()||(Fi[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Fi[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Fi[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Fi[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Fi[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Fi[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Fi[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Fi[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Fi)),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}}const Fi=[new hi,new hi,new hi,new hi,new hi,new hi,new hi,new hi],Ui=new hi,ki=new Li,Ni=new hi,Oi=new hi,zi=new hi,Hi=new hi,Vi=new hi,Gi=new hi,Wi=new hi,ji=new hi,Xi=new hi,qi=new hi;function Qi(e,t,n,i,r){for(let s=0,a=e.length-3;s<=a;s+=3){qi.fromArray(e,s);const a=r.x*Math.abs(qi.x)+r.y*Math.abs(qi.y)+r.z*Math.abs(qi.z),o=t.dot(qi),l=n.dot(qi),c=i.dot(qi);if(Math.max(-Math.max(o,l,c),Math.min(o,l,c))>a)return!1}return!0}const Ki=new Li,Yi=new hi,Zi=new hi;class Ji{constructor(e=new hi,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const n=this.center;void 0!==t?n.copy(t):Ki.setFromPoints(e).getCenter(n);let i=0;for(let r=0,s=e.length;r<s;r++)i=Math.max(i,n.distanceToSquared(e[r]));return this.radius=Math.sqrt(i),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){const t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){const n=this.center.distanceToSquared(e);return t.copy(e),n>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Yi.subVectors(e,this.center);const t=Yi.lengthSq();if(t>this.radius*this.radius){const e=Math.sqrt(t),n=.5*(e-this.radius);this.center.addScaledVector(Yi,n/e),this.radius+=n}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(!0===this.center.equals(e.center)?this.radius=Math.max(this.radius,e.radius):(Zi.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Yi.copy(e.center).add(Zi)),this.expandByPoint(Yi.copy(e.center).sub(Zi))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return(new this.constructor).copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}}const $i=new hi,er=new hi,tr=new hi,nr=new hi,ir=new hi,rr=new hi,sr=new hi;class ar{constructor(e=new hi,t=new hi(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,$i)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=$i.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):($i.copy(this.origin).addScaledVector(this.direction,t),$i.distanceToSquared(e))}distanceSqToSegment(e,t,n,i){er.copy(e).add(t).multiplyScalar(.5),tr.copy(t).sub(e).normalize(),nr.copy(this.origin).sub(er);const r=.5*e.distanceTo(t),s=-this.direction.dot(tr),a=nr.dot(this.direction),o=-nr.dot(tr),l=nr.lengthSq(),c=Math.abs(1-s*s);let h,u,d,p;if(c>0)if(h=s*o-a,u=s*a-o,p=r*c,h>=0)if(u>=-p)if(u<=p){const e=1/c;h*=e,u*=e,d=h*(h+s*u+2*a)+u*(s*h+u+2*o)+l}else u=r,h=Math.max(0,-(s*u+a)),d=-h*h+u*(u+2*o)+l;else u=-r,h=Math.max(0,-(s*u+a)),d=-h*h+u*(u+2*o)+l;else u<=-p?(h=Math.max(0,-(-s*r+a)),u=h>0?-r:Math.min(Math.max(-r,-o),r),d=-h*h+u*(u+2*o)+l):u<=p?(h=0,u=Math.min(Math.max(-r,-o),r),d=u*(u+2*o)+l):(h=Math.max(0,-(s*r+a)),u=h>0?r:Math.min(Math.max(-r,-o),r),d=-h*h+u*(u+2*o)+l);else u=s>0?-r:r,h=Math.max(0,-(s*u+a)),d=-h*h+u*(u+2*o)+l;return n&&n.copy(this.origin).addScaledVector(this.direction,h),i&&i.copy(er).addScaledVector(tr,u),d}intersectSphere(e,t){$i.subVectors(e.center,this.origin);const n=$i.dot(this.direction),i=$i.dot($i)-n*n,r=e.radius*e.radius;if(i>r)return null;const s=Math.sqrt(r-i),a=n-s,o=n+s;return o<0?null:a<0?this.at(o,t):this.at(a,t)}intersectsSphere(e){return!(e.radius<0)&&this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(0===t)return 0===e.distanceToPoint(this.origin)?0:null;const n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){const n=this.distanceToPlane(e);return null===n?null:this.at(n,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);if(0===t)return!0;return e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,i,r,s,a,o;const l=1/this.direction.x,c=1/this.direction.y,h=1/this.direction.z,u=this.origin;return l>=0?(n=(e.min.x-u.x)*l,i=(e.max.x-u.x)*l):(n=(e.max.x-u.x)*l,i=(e.min.x-u.x)*l),c>=0?(r=(e.min.y-u.y)*c,s=(e.max.y-u.y)*c):(r=(e.max.y-u.y)*c,s=(e.min.y-u.y)*c),n>s||r>i?null:((r>n||isNaN(n))&&(n=r),(s<i||isNaN(i))&&(i=s),h>=0?(a=(e.min.z-u.z)*h,o=(e.max.z-u.z)*h):(a=(e.max.z-u.z)*h,o=(e.min.z-u.z)*h),n>o||a>i?null:((a>n||n!=n)&&(n=a),(o<i||i!=i)&&(i=o),i<0?null:this.at(n>=0?n:i,t)))}intersectsBox(e){return null!==this.intersectBox(e,$i)}intersectTriangle(e,t,n,i,r){ir.subVectors(t,e),rr.subVectors(n,e),sr.crossVectors(ir,rr);let s,a=this.direction.dot(sr);if(a>0){if(i)return null;s=1}else{if(!(a<0))return null;s=-1,a=-a}nr.subVectors(this.origin,e);const o=s*this.direction.dot(rr.crossVectors(nr,rr));if(o<0)return null;const l=s*this.direction.dot(ir.cross(nr));if(l<0)return null;if(o+l>a)return null;const c=-s*nr.dot(sr);return c<0?null:this.at(c/a,r)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return(new this.constructor).copy(this)}}class or{constructor(e,t,n,i,r,s,a,o,l,c,h,u,d,p,f,m){or.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],void 0!==e&&this.set(e,t,n,i,r,s,a,o,l,c,h,u,d,p,f,m)}set(e,t,n,i,r,s,a,o,l,c,h,u,d,p,f,m){const g=this.elements;return g[0]=e,g[4]=t,g[8]=n,g[12]=i,g[1]=r,g[5]=s,g[9]=a,g[13]=o,g[2]=l,g[6]=c,g[10]=h,g[14]=u,g[3]=d,g[7]=p,g[11]=f,g[15]=m,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return(new or).fromArray(this.elements)}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){const t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,n){return 0===this.determinant()?(e.set(1,0,0),t.set(0,1,0),n.set(0,0,1),this):(e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this)}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){if(0===e.determinant())return this.identity();const t=this.elements,n=e.elements,i=1/lr.setFromMatrixColumn(e,0).length(),r=1/lr.setFromMatrixColumn(e,1).length(),s=1/lr.setFromMatrixColumn(e,2).length();return t[0]=n[0]*i,t[1]=n[1]*i,t[2]=n[2]*i,t[3]=0,t[4]=n[4]*r,t[5]=n[5]*r,t[6]=n[6]*r,t[7]=0,t[8]=n[8]*s,t[9]=n[9]*s,t[10]=n[10]*s,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,n=e.x,i=e.y,r=e.z,s=Math.cos(n),a=Math.sin(n),o=Math.cos(i),l=Math.sin(i),c=Math.cos(r),h=Math.sin(r);if("XYZ"===e.order){const e=s*c,n=s*h,i=a*c,r=a*h;t[0]=o*c,t[4]=-o*h,t[8]=l,t[1]=n+i*l,t[5]=e-r*l,t[9]=-a*o,t[2]=r-e*l,t[6]=i+n*l,t[10]=s*o}else if("YXZ"===e.order){const e=o*c,n=o*h,i=l*c,r=l*h;t[0]=e+r*a,t[4]=i*a-n,t[8]=s*l,t[1]=s*h,t[5]=s*c,t[9]=-a,t[2]=n*a-i,t[6]=r+e*a,t[10]=s*o}else if("ZXY"===e.order){const e=o*c,n=o*h,i=l*c,r=l*h;t[0]=e-r*a,t[4]=-s*h,t[8]=i+n*a,t[1]=n+i*a,t[5]=s*c,t[9]=r-e*a,t[2]=-s*l,t[6]=a,t[10]=s*o}else if("ZYX"===e.order){const e=s*c,n=s*h,i=a*c,r=a*h;t[0]=o*c,t[4]=i*l-n,t[8]=e*l+r,t[1]=o*h,t[5]=r*l+e,t[9]=n*l-i,t[2]=-l,t[6]=a*o,t[10]=s*o}else if("YZX"===e.order){const e=s*o,n=s*l,i=a*o,r=a*l;t[0]=o*c,t[4]=r-e*h,t[8]=i*h+n,t[1]=h,t[5]=s*c,t[9]=-a*c,t[2]=-l*c,t[6]=n*h+i,t[10]=e-r*h}else if("XZY"===e.order){const e=s*o,n=s*l,i=a*o,r=a*l;t[0]=o*c,t[4]=-h,t[8]=l*c,t[1]=e*h+r,t[5]=s*c,t[9]=n*h-i,t[2]=i*h-n,t[6]=a*c,t[10]=r*h+e}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(hr,e,ur)}lookAt(e,t,n){const i=this.elements;return fr.subVectors(e,t),0===fr.lengthSq()&&(fr.z=1),fr.normalize(),dr.crossVectors(n,fr),0===dr.lengthSq()&&(1===Math.abs(n.z)?fr.x+=1e-4:fr.z+=1e-4,fr.normalize(),dr.crossVectors(n,fr)),dr.normalize(),pr.crossVectors(fr,dr),i[0]=dr.x,i[4]=pr.x,i[8]=fr.x,i[1]=dr.y,i[5]=pr.y,i[9]=fr.y,i[2]=dr.z,i[6]=pr.z,i[10]=fr.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,i=t.elements,r=this.elements,s=n[0],a=n[4],o=n[8],l=n[12],c=n[1],h=n[5],u=n[9],d=n[13],p=n[2],f=n[6],m=n[10],g=n[14],_=n[3],v=n[7],x=n[11],y=n[15],S=i[0],A=i[4],b=i[8],M=i[12],w=i[1],T=i[5],E=i[9],C=i[13],R=i[2],I=i[6],P=i[10],D=i[14],B=i[3],L=i[7],F=i[11],U=i[15];return r[0]=s*S+a*w+o*R+l*B,r[4]=s*A+a*T+o*I+l*L,r[8]=s*b+a*E+o*P+l*F,r[12]=s*M+a*C+o*D+l*U,r[1]=c*S+h*w+u*R+d*B,r[5]=c*A+h*T+u*I+d*L,r[9]=c*b+h*E+u*P+d*F,r[13]=c*M+h*C+u*D+d*U,r[2]=p*S+f*w+m*R+g*B,r[6]=p*A+f*T+m*I+g*L,r[10]=p*b+f*E+m*P+g*F,r[14]=p*M+f*C+m*D+g*U,r[3]=_*S+v*w+x*R+y*B,r[7]=_*A+v*T+x*I+y*L,r[11]=_*b+v*E+x*P+y*F,r[15]=_*M+v*C+x*D+y*U,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[4],i=e[8],r=e[12],s=e[1],a=e[5],o=e[9],l=e[13],c=e[2],h=e[6],u=e[10],d=e[14],p=e[3],f=e[7],m=e[11],g=e[15],_=o*d-l*u,v=a*d-l*h,x=a*u-o*h,y=s*d-l*c,S=s*u-o*c,A=s*h-a*c;return t*(f*_-m*v+g*x)-n*(p*_-m*y+g*S)+i*(p*v-f*y+g*A)-r*(p*x-f*S+m*A)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,n){const i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=t,i[14]=n),this}invert(){const e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],s=e[4],a=e[5],o=e[6],l=e[7],c=e[8],h=e[9],u=e[10],d=e[11],p=e[12],f=e[13],m=e[14],g=e[15],_=h*m*l-f*u*l+f*o*d-a*m*d-h*o*g+a*u*g,v=p*u*l-c*m*l-p*o*d+s*m*d+c*o*g-s*u*g,x=c*f*l-p*h*l+p*a*d-s*f*d-c*a*g+s*h*g,y=p*h*o-c*f*o-p*a*u+s*f*u+c*a*m-s*h*m,S=t*_+n*v+i*x+r*y;if(0===S)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const A=1/S;return e[0]=_*A,e[1]=(f*u*r-h*m*r-f*i*d+n*m*d+h*i*g-n*u*g)*A,e[2]=(a*m*r-f*o*r+f*i*l-n*m*l-a*i*g+n*o*g)*A,e[3]=(h*o*r-a*u*r-h*i*l+n*u*l+a*i*d-n*o*d)*A,e[4]=v*A,e[5]=(c*m*r-p*u*r+p*i*d-t*m*d-c*i*g+t*u*g)*A,e[6]=(p*o*r-s*m*r-p*i*l+t*m*l+s*i*g-t*o*g)*A,e[7]=(s*u*r-c*o*r+c*i*l-t*u*l-s*i*d+t*o*d)*A,e[8]=x*A,e[9]=(p*h*r-c*f*r-p*n*d+t*f*d+c*n*g-t*h*g)*A,e[10]=(s*f*r-p*a*r+p*n*l-t*f*l-s*n*g+t*a*g)*A,e[11]=(c*a*r-s*h*r-c*n*l+t*h*l+s*n*d-t*a*d)*A,e[12]=y*A,e[13]=(c*f*i-p*h*i+p*n*u-t*f*u-c*n*m+t*h*m)*A,e[14]=(p*a*i-s*f*i-p*n*o+t*f*o+s*n*m-t*a*m)*A,e[15]=(s*h*i-c*a*i+c*n*o-t*h*o-s*n*u+t*a*u)*A,this}scale(e){const t=this.elements,n=e.x,i=e.y,r=e.z;return t[0]*=n,t[4]*=i,t[8]*=r,t[1]*=n,t[5]*=i,t[9]*=r,t[2]*=n,t[6]*=i,t[10]*=r,t[3]*=n,t[7]*=i,t[11]*=r,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,i))}makeTranslation(e,t,n){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const n=Math.cos(t),i=Math.sin(t),r=1-n,s=e.x,a=e.y,o=e.z,l=r*s,c=r*a;return this.set(l*s+n,l*a-i*o,l*o+i*a,0,l*a+i*o,c*a+n,c*o-i*s,0,l*o-i*a,c*o+i*s,r*o*o+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,i,r,s){return this.set(1,n,r,0,e,1,s,0,t,i,1,0,0,0,0,1),this}compose(e,t,n){const i=this.elements,r=t._x,s=t._y,a=t._z,o=t._w,l=r+r,c=s+s,h=a+a,u=r*l,d=r*c,p=r*h,f=s*c,m=s*h,g=a*h,_=o*l,v=o*c,x=o*h,y=n.x,S=n.y,A=n.z;return i[0]=(1-(f+g))*y,i[1]=(d+x)*y,i[2]=(p-v)*y,i[3]=0,i[4]=(d-x)*S,i[5]=(1-(u+g))*S,i[6]=(m+_)*S,i[7]=0,i[8]=(p+v)*A,i[9]=(m-_)*A,i[10]=(1-(u+f))*A,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,t,n){const i=this.elements;if(e.x=i[12],e.y=i[13],e.z=i[14],0===this.determinant())return n.set(1,1,1),t.identity(),this;let r=lr.set(i[0],i[1],i[2]).length();const s=lr.set(i[4],i[5],i[6]).length(),a=lr.set(i[8],i[9],i[10]).length();this.determinant()<0&&(r=-r),cr.copy(this);const o=1/r,l=1/s,c=1/a;return cr.elements[0]*=o,cr.elements[1]*=o,cr.elements[2]*=o,cr.elements[4]*=l,cr.elements[5]*=l,cr.elements[6]*=l,cr.elements[8]*=c,cr.elements[9]*=c,cr.elements[10]*=c,t.setFromRotationMatrix(cr),n.x=r,n.y=s,n.z=a,this}makePerspective(e,t,n,i,r,s,a=2e3,o=!1){const l=this.elements,c=2*r/(t-e),h=2*r/(n-i),u=(t+e)/(t-e),d=(n+i)/(n-i);let p,f;if(o)p=r/(s-r),f=s*r/(s-r);else if(a===zn)p=-(s+r)/(s-r),f=-2*s*r/(s-r);else{if(a!==Hn)throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);p=-s/(s-r),f=-s*r/(s-r)}return l[0]=c,l[4]=0,l[8]=u,l[12]=0,l[1]=0,l[5]=h,l[9]=d,l[13]=0,l[2]=0,l[6]=0,l[10]=p,l[14]=f,l[3]=0,l[7]=0,l[11]=-1,l[15]=0,this}makeOrthographic(e,t,n,i,r,s,a=2e3,o=!1){const l=this.elements,c=2/(t-e),h=2/(n-i),u=-(t+e)/(t-e),d=-(n+i)/(n-i);let p,f;if(o)p=1/(s-r),f=s/(s-r);else if(a===zn)p=-2/(s-r),f=-(s+r)/(s-r);else{if(a!==Hn)throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);p=-1/(s-r),f=-r/(s-r)}return l[0]=c,l[4]=0,l[8]=0,l[12]=u,l[1]=0,l[5]=h,l[9]=0,l[13]=d,l[2]=0,l[6]=0,l[10]=p,l[14]=f,l[3]=0,l[7]=0,l[11]=0,l[15]=1,this}equals(e){const t=this.elements,n=e.elements;for(let i=0;i<16;i++)if(t[i]!==n[i])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}}const lr=new hi,cr=new or,hr=new hi(0,0,0),ur=new hi(1,1,1),dr=new hi,pr=new hi,fr=new hi,mr=new or,gr=new ci;class _r{constructor(e=0,t=0,n=0,i=_r.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=n,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,n,i=this._order){return this._x=e,this._y=t,this._z=n,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,n=!0){const i=e.elements,r=i[0],s=i[4],a=i[8],o=i[1],l=i[5],c=i[9],h=i[2],u=i[6],d=i[10];switch(t){case"XYZ":this._y=Math.asin(ni(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-c,d),this._z=Math.atan2(-s,r)):(this._x=Math.atan2(u,l),this._z=0);break;case"YXZ":this._x=Math.asin(-ni(c,-1,1)),Math.abs(c)<.9999999?(this._y=Math.atan2(a,d),this._z=Math.atan2(o,l)):(this._y=Math.atan2(-h,r),this._z=0);break;case"ZXY":this._x=Math.asin(ni(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(-h,d),this._z=Math.atan2(-s,l)):(this._y=0,this._z=Math.atan2(o,r));break;case"ZYX":this._y=Math.asin(-ni(h,-1,1)),Math.abs(h)<.9999999?(this._x=Math.atan2(u,d),this._z=Math.atan2(o,r)):(this._x=0,this._z=Math.atan2(-s,l));break;case"YZX":this._z=Math.asin(ni(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-c,l),this._y=Math.atan2(-h,r)):(this._x=0,this._y=Math.atan2(a,d));break;case"XZY":this._z=Math.asin(-ni(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(u,l),this._y=Math.atan2(a,r)):(this._x=Math.atan2(-c,d),this._y=0);break;default:qn("Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,!0===n&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return mr.makeRotationFromQuaternion(e),this.setFromRotationMatrix(mr,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return gr.setFromEuler(this),this.setFromQuaternion(gr,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],void 0!==e[3]&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}_r.DEFAULT_ORDER="XYZ";class vr{constructor(){this.mask=1}set(e){this.mask=1<<e>>>0}enable(e){this.mask|=1<<e}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e}disable(e){this.mask&=~(1<<e)}disableAll(){this.mask=0}test(e){return 0!==(this.mask&e.mask)}isEnabled(e){return!!(this.mask&1<<e)}}let xr=0;const yr=new hi,Sr=new ci,Ar=new or,br=new hi,Mr=new hi,wr=new hi,Tr=new ci,Er=new hi(1,0,0),Cr=new hi(0,1,0),Rr=new hi(0,0,1),Ir={type:"added"},Pr={type:"removed"},Dr={type:"childadded",child:null},Br={type:"childremoved",child:null};class Lr extends Yn{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:xr++}),this.uuid=ti(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=Lr.DEFAULT_UP.clone();const e=new hi,t=new _r,n=new ci,i=new hi(1,1,1);t._onChange(function(){n.setFromEuler(t,!1)}),n._onChange(function(){t.setFromQuaternion(n,void 0,!1)}),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:t},quaternion:{configurable:!0,enumerable:!0,value:n},scale:{configurable:!0,enumerable:!0,value:i},modelViewMatrix:{value:new or},normalMatrix:{value:new pi}}),this.matrix=new or,this.matrixWorld=new or,this.matrixAutoUpdate=Lr.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=Lr.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new vr,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.userData={}}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return Sr.setFromAxisAngle(e,t),this.quaternion.multiply(Sr),this}rotateOnWorldAxis(e,t){return Sr.setFromAxisAngle(e,t),this.quaternion.premultiply(Sr),this}rotateX(e){return this.rotateOnAxis(Er,e)}rotateY(e){return this.rotateOnAxis(Cr,e)}rotateZ(e){return this.rotateOnAxis(Rr,e)}translateOnAxis(e,t){return yr.copy(e).applyQuaternion(this.quaternion),this.position.add(yr.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(Er,e)}translateY(e){return this.translateOnAxis(Cr,e)}translateZ(e){return this.translateOnAxis(Rr,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(Ar.copy(this.matrixWorld).invert())}lookAt(e,t,n){e.isVector3?br.copy(e):br.set(e,t,n);const i=this.parent;this.updateWorldMatrix(!0,!1),Mr.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Ar.lookAt(Mr,br,this.up):Ar.lookAt(br,Mr,this.up),this.quaternion.setFromRotationMatrix(Ar),i&&(Ar.extractRotation(i.matrixWorld),Sr.setFromRotationMatrix(Ar),this.quaternion.premultiply(Sr.invert()))}add(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return e===this?(Qn("Object3D.add: object can't be added as a child of itself.",e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(Ir),Dr.child=e,this.dispatchEvent(Dr),Dr.child=null):Qn("Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.remove(arguments[e]);return this}const t=this.children.indexOf(e);return-1!==t&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(Pr),Br.child=e,this.dispatchEvent(Br),Br.child=null),this}removeFromParent(){const e=this.parent;return null!==e&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),Ar.copy(this.matrixWorld).invert(),null!==e.parent&&(e.parent.updateWorldMatrix(!0,!1),Ar.multiply(e.parent.matrixWorld)),e.applyMatrix4(Ar),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(Ir),Dr.child=e,this.dispatchEvent(Dr),Dr.child=null,this}getObjectById(e){return this.getObjectByProperty("id",e)}getObjectByName(e){return this.getObjectByProperty("name",e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let n=0,i=this.children.length;n<i;n++){const i=this.children[n].getObjectByProperty(e,t);if(void 0!==i)return i}}getObjectsByProperty(e,t,n=[]){this[e]===t&&n.push(this);const i=this.children;for(let r=0,s=i.length;r<s;r++)i[r].getObjectsByProperty(e,t,n);return n}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Mr,e,wr),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Mr,Tr,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);const t=this.children;for(let n=0,i=t.length;n<i;n++)t[n].traverse(e)}traverseVisible(e){if(!1===this.visible)return;e(this);const t=this.children;for(let n=0,i=t.length;n<i;n++)t[n].traverseVisible(e)}traverseAncestors(e){const t=this.parent;null!==t&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(!0===this.matrixWorldAutoUpdate&&(null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);const t=this.children;for(let n=0,i=t.length;n<i;n++){t[n].updateMatrixWorld(e)}}updateWorldMatrix(e,t){const n=this.parent;if(!0===e&&null!==n&&n.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),!0===this.matrixWorldAutoUpdate&&(null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),!0===t){const e=this.children;for(let t=0,n=e.length;t<n;t++){e[t].updateWorldMatrix(!1,!0)}}}toJSON(e){const t=void 0===e||"string"==typeof e,n={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},n.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});const i={};function r(t,n){return void 0===t[n.uuid]&&(t[n.uuid]=n.toJSON(e)),n.uuid}if(i.uuid=this.uuid,i.type=this.type,""!==this.name&&(i.name=this.name),!0===this.castShadow&&(i.castShadow=!0),!0===this.receiveShadow&&(i.receiveShadow=!0),!1===this.visible&&(i.visible=!1),!1===this.frustumCulled&&(i.frustumCulled=!1),0!==this.renderOrder&&(i.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),!1===this.matrixAutoUpdate&&(i.matrixAutoUpdate=!1),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),null!==this.instanceColor&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.geometryInfo=this._geometryInfo.map(e=>({...e,boundingBox:e.boundingBox?e.boundingBox.toJSON():void 0,boundingSphere:e.boundingSphere?e.boundingSphere.toJSON():void 0})),i.instanceInfo=this._instanceInfo.map(e=>({...e})),i.availableInstanceIds=this._availableInstanceIds.slice(),i.availableGeometryIds=this._availableGeometryIds.slice(),i.nextIndexStart=this._nextIndexStart,i.nextVertexStart=this._nextVertexStart,i.geometryCount=this._geometryCount,i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.matricesTexture=this._matricesTexture.toJSON(e),i.indirectTexture=this._indirectTexture.toJSON(e),null!==this._colorsTexture&&(i.colorsTexture=this._colorsTexture.toJSON(e)),null!==this.boundingSphere&&(i.boundingSphere=this.boundingSphere.toJSON()),null!==this.boundingBox&&(i.boundingBox=this.boundingBox.toJSON())),this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&!0!==this.environment.isRenderTargetTexture&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=r(e.geometries,this.geometry);const t=this.geometry.parameters;if(void 0!==t&&void 0!==t.shapes){const n=t.shapes;if(Array.isArray(n))for(let t=0,i=n.length;t<i;t++){const i=n[t];r(e.shapes,i)}else r(e.shapes,n)}}if(this.isSkinnedMesh&&(i.bindMode=this.bindMode,i.bindMatrix=this.bindMatrix.toArray(),void 0!==this.skeleton&&(r(e.skeletons,this.skeleton),i.skeleton=this.skeleton.uuid)),void 0!==this.material)if(Array.isArray(this.material)){const t=[];for(let n=0,i=this.material.length;n<i;n++)t.push(r(e.materials,this.material[n]));i.material=t}else i.material=r(e.materials,this.material);if(this.children.length>0){i.children=[];for(let t=0;t<this.children.length;t++)i.children.push(this.children[t].toJSON(e).object)}if(this.animations.length>0){i.animations=[];for(let t=0;t<this.animations.length;t++){const n=this.animations[t];i.animations.push(r(e.animations,n))}}if(t){const t=s(e.geometries),i=s(e.materials),r=s(e.textures),a=s(e.images),o=s(e.shapes),l=s(e.skeletons),c=s(e.animations),h=s(e.nodes);t.length>0&&(n.geometries=t),i.length>0&&(n.materials=i),r.length>0&&(n.textures=r),a.length>0&&(n.images=a),o.length>0&&(n.shapes=o),l.length>0&&(n.skeletons=l),c.length>0&&(n.animations=c),h.length>0&&(n.nodes=h)}return n.object=i,n;function s(e){const t=[];for(const n in e){const i=e[n];delete i.metadata,t.push(i)}return t}}clone(e){return(new this.constructor).copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),!0===t)for(let n=0;n<e.children.length;n++){const t=e.children[n];this.add(t.clone())}return this}}Lr.DEFAULT_UP=new hi(0,1,0),Lr.DEFAULT_MATRIX_AUTO_UPDATE=!0,Lr.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const Fr=new hi,Ur=new hi,kr=new hi,Nr=new hi,Or=new hi,zr=new hi,Hr=new hi,Vr=new hi,Gr=new hi,Wr=new hi,jr=new Ri,Xr=new Ri,qr=new Ri;class Qr{constructor(e=new hi,t=new hi,n=new hi){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,i){i.subVectors(n,t),Fr.subVectors(e,t),i.cross(Fr);const r=i.lengthSq();return r>0?i.multiplyScalar(1/Math.sqrt(r)):i.set(0,0,0)}static getBarycoord(e,t,n,i,r){Fr.subVectors(i,t),Ur.subVectors(n,t),kr.subVectors(e,t);const s=Fr.dot(Fr),a=Fr.dot(Ur),o=Fr.dot(kr),l=Ur.dot(Ur),c=Ur.dot(kr),h=s*l-a*a;if(0===h)return r.set(0,0,0),null;const u=1/h,d=(l*o-a*c)*u,p=(s*c-a*o)*u;return r.set(1-d-p,p,d)}static containsPoint(e,t,n,i){return null!==this.getBarycoord(e,t,n,i,Nr)&&(Nr.x>=0&&Nr.y>=0&&Nr.x+Nr.y<=1)}static getInterpolation(e,t,n,i,r,s,a,o){return null===this.getBarycoord(e,t,n,i,Nr)?(o.x=0,o.y=0,"z"in o&&(o.z=0),"w"in o&&(o.w=0),null):(o.setScalar(0),o.addScaledVector(r,Nr.x),o.addScaledVector(s,Nr.y),o.addScaledVector(a,Nr.z),o)}static getInterpolatedAttribute(e,t,n,i,r,s){return jr.setScalar(0),Xr.setScalar(0),qr.setScalar(0),jr.fromBufferAttribute(e,t),Xr.fromBufferAttribute(e,n),qr.fromBufferAttribute(e,i),s.setScalar(0),s.addScaledVector(jr,r.x),s.addScaledVector(Xr,r.y),s.addScaledVector(qr,r.z),s}static isFrontFacing(e,t,n,i){return Fr.subVectors(n,t),Ur.subVectors(e,t),Fr.cross(Ur).dot(i)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,i){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,t,n,i){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,i),this}clone(){return(new this.constructor).copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Fr.subVectors(this.c,this.b),Ur.subVectors(this.a,this.b),.5*Fr.cross(Ur).length()}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Qr.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Qr.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,n,i,r){return Qr.getInterpolation(e,this.a,this.b,this.c,t,n,i,r)}containsPoint(e){return Qr.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Qr.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const n=this.a,i=this.b,r=this.c;let s,a;Or.subVectors(i,n),zr.subVectors(r,n),Vr.subVectors(e,n);const o=Or.dot(Vr),l=zr.dot(Vr);if(o<=0&&l<=0)return t.copy(n);Gr.subVectors(e,i);const c=Or.dot(Gr),h=zr.dot(Gr);if(c>=0&&h<=c)return t.copy(i);const u=o*h-c*l;if(u<=0&&o>=0&&c<=0)return s=o/(o-c),t.copy(n).addScaledVector(Or,s);Wr.subVectors(e,r);const d=Or.dot(Wr),p=zr.dot(Wr);if(p>=0&&d<=p)return t.copy(r);const f=d*l-o*p;if(f<=0&&l>=0&&p<=0)return a=l/(l-p),t.copy(n).addScaledVector(zr,a);const m=c*p-d*h;if(m<=0&&h-c>=0&&d-p>=0)return Hr.subVectors(r,i),a=(h-c)/(h-c+(d-p)),t.copy(i).addScaledVector(Hr,a);const g=1/(m+f+u);return s=f*g,a=u*g,t.copy(n).addScaledVector(Or,s).addScaledVector(zr,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const Kr={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Yr={h:0,s:0,l:0},Zr={h:0,s:0,l:0};function Jr(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+6*(t-e)*(2/3-n):e}class $r{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(void 0===t&&void 0===n){const t=e;t&&t.isColor?this.copy(t):"number"==typeof t?this.setHex(t):"string"==typeof t&&this.setStyle(t)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=Mn){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(255&e)/255,vi.colorSpaceToWorking(this,t),this}setRGB(e,t,n,i=vi.workingColorSpace){return this.r=e,this.g=t,this.b=n,vi.colorSpaceToWorking(this,i),this}setHSL(e,t,n,i=vi.workingColorSpace){if(e=ii(e,1),t=ni(t,0,1),n=ni(n,0,1),0===t)this.r=this.g=this.b=n;else{const i=n<=.5?n*(1+t):n+t-n*t,r=2*n-i;this.r=Jr(r,i,e+1/3),this.g=Jr(r,i,e),this.b=Jr(r,i,e-1/3)}return vi.colorSpaceToWorking(this,i),this}setStyle(e,t=Mn){function n(t){void 0!==t&&parseFloat(t)<1&&qn("Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const s=i[1],a=i[2];switch(s){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,t);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,t);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:qn("Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){const n=i[1],r=n.length;if(3===r)return this.setRGB(parseInt(n.charAt(0),16)/15,parseInt(n.charAt(1),16)/15,parseInt(n.charAt(2),16)/15,t);if(6===r)return this.setHex(parseInt(n,16),t);qn("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Mn){const n=Kr[e.toLowerCase()];return void 0!==n?this.setHex(n,t):qn("Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=xi(e.r),this.g=xi(e.g),this.b=xi(e.b),this}copyLinearToSRGB(e){return this.r=yi(e.r),this.g=yi(e.g),this.b=yi(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Mn){return vi.workingToColorSpace(es.copy(this),e),65536*Math.round(ni(255*es.r,0,255))+256*Math.round(ni(255*es.g,0,255))+Math.round(ni(255*es.b,0,255))}getHexString(e=Mn){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=vi.workingColorSpace){vi.workingToColorSpace(es.copy(this),t);const n=es.r,i=es.g,r=es.b,s=Math.max(n,i,r),a=Math.min(n,i,r);let o,l;const c=(a+s)/2;if(a===s)o=0,l=0;else{const e=s-a;switch(l=c<=.5?e/(s+a):e/(2-s-a),s){case n:o=(i-r)/e+(i<r?6:0);break;case i:o=(r-n)/e+2;break;case r:o=(n-i)/e+4}o/=6}return e.h=o,e.s=l,e.l=c,e}getRGB(e,t=vi.workingColorSpace){return vi.workingToColorSpace(es.copy(this),t),e.r=es.r,e.g=es.g,e.b=es.b,e}getStyle(e=Mn){vi.workingToColorSpace(es.copy(this),e);const t=es.r,n=es.g,i=es.b;return e!==Mn?`color(${e} ${t.toFixed(3)} ${n.toFixed(3)} ${i.toFixed(3)})`:`rgb(${Math.round(255*t)},${Math.round(255*n)},${Math.round(255*i)})`}offsetHSL(e,t,n){return this.getHSL(Yr),this.setHSL(Yr.h+e,Yr.s+t,Yr.l+n)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,n){return this.r=e.r+(t.r-e.r)*n,this.g=e.g+(t.g-e.g)*n,this.b=e.b+(t.b-e.b)*n,this}lerpHSL(e,t){this.getHSL(Yr),e.getHSL(Zr);const n=ri(Yr.h,Zr.h,t),i=ri(Yr.s,Zr.s,t),r=ri(Yr.l,Zr.l,t);return this.setHSL(n,i,r),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const t=this.r,n=this.g,i=this.b,r=e.elements;return this.r=r[0]*t+r[3]*n+r[6]*i,this.g=r[1]*t+r[4]*n+r[7]*i,this.b=r[2]*t+r[5]*n+r[8]*i,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}}const es=new $r;$r.NAMES=Kr;let ts=0;class ns extends Yn{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:ts++}),this.uuid=ti(),this.name="",this.type="Material",this.blending=1,this.side=0,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=204,this.blendDst=205,this.blendEquation=me,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new $r(0,0,0),this.blendAlpha=0,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=Cn,this.stencilZFail=Cn,this.stencilZPass=Cn,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(void 0!==e)for(const t in e){const n=e[t];if(void 0===n){qn(`Material: parameter '${t}' has value of undefined.`);continue}const i=this[t];void 0!==i?i&&i.isColor?i.set(n):i&&i.isVector3&&n&&n.isVector3?i.copy(n):this[t]=n:qn(`Material: '${t}' is not a property of THREE.${this.type}.`)}}toJSON(e){const t=void 0===e||"string"==typeof e;t&&(e={textures:{},images:{}});const n={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};function i(e){const t=[];for(const n in e){const i=e[n];delete i.metadata,t.push(i)}return t}if(n.uuid=this.uuid,n.type=this.type,""!==this.name&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),void 0!==this.roughness&&(n.roughness=this.roughness),void 0!==this.metalness&&(n.metalness=this.metalness),void 0!==this.sheen&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),void 0!==this.sheenRoughness&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),void 0!==this.emissiveIntensity&&1!==this.emissiveIntensity&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),void 0!==this.specularIntensity&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),void 0!==this.shininess&&(n.shininess=this.shininess),void 0!==this.clearcoat&&(n.clearcoat=this.clearcoat),void 0!==this.clearcoatRoughness&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),void 0!==this.dispersion&&(n.dispersion=this.dispersion),void 0!==this.iridescence&&(n.iridescence=this.iridescence),void 0!==this.iridescenceIOR&&(n.iridescenceIOR=this.iridescenceIOR),void 0!==this.iridescenceThicknessRange&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),void 0!==this.anisotropy&&(n.anisotropy=this.anisotropy),void 0!==this.anisotropyRotation&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,void 0!==this.combine&&(n.combine=this.combine)),void 0!==this.envMapRotation&&(n.envMapRotation=this.envMapRotation.toArray()),void 0!==this.envMapIntensity&&(n.envMapIntensity=this.envMapIntensity),void 0!==this.reflectivity&&(n.reflectivity=this.reflectivity),void 0!==this.refractionRatio&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),void 0!==this.transmission&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),void 0!==this.thickness&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),void 0!==this.attenuationDistance&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),void 0!==this.attenuationColor&&(n.attenuationColor=this.attenuationColor.getHex()),void 0!==this.size&&(n.size=this.size),null!==this.shadowSide&&(n.shadowSide=this.shadowSide),void 0!==this.sizeAttenuation&&(n.sizeAttenuation=this.sizeAttenuation),1!==this.blending&&(n.blending=this.blending),0!==this.side&&(n.side=this.side),!0===this.vertexColors&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),!0===this.transparent&&(n.transparent=!0),204!==this.blendSrc&&(n.blendSrc=this.blendSrc),205!==this.blendDst&&(n.blendDst=this.blendDst),this.blendEquation!==me&&(n.blendEquation=this.blendEquation),null!==this.blendSrcAlpha&&(n.blendSrcAlpha=this.blendSrcAlpha),null!==this.blendDstAlpha&&(n.blendDstAlpha=this.blendDstAlpha),null!==this.blendEquationAlpha&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),0!==this.blendAlpha&&(n.blendAlpha=this.blendAlpha),3!==this.depthFunc&&(n.depthFunc=this.depthFunc),!1===this.depthTest&&(n.depthTest=this.depthTest),!1===this.depthWrite&&(n.depthWrite=this.depthWrite),!1===this.colorWrite&&(n.colorWrite=this.colorWrite),255!==this.stencilWriteMask&&(n.stencilWriteMask=this.stencilWriteMask),519!==this.stencilFunc&&(n.stencilFunc=this.stencilFunc),0!==this.stencilRef&&(n.stencilRef=this.stencilRef),255!==this.stencilFuncMask&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Cn&&(n.stencilFail=this.stencilFail),this.stencilZFail!==Cn&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==Cn&&(n.stencilZPass=this.stencilZPass),!0===this.stencilWrite&&(n.stencilWrite=this.stencilWrite),void 0!==this.rotation&&0!==this.rotation&&(n.rotation=this.rotation),!0===this.polygonOffset&&(n.polygonOffset=!0),0!==this.polygonOffsetFactor&&(n.polygonOffsetFactor=this.polygonOffsetFactor),0!==this.polygonOffsetUnits&&(n.polygonOffsetUnits=this.polygonOffsetUnits),void 0!==this.linewidth&&1!==this.linewidth&&(n.linewidth=this.linewidth),void 0!==this.dashSize&&(n.dashSize=this.dashSize),void 0!==this.gapSize&&(n.gapSize=this.gapSize),void 0!==this.scale&&(n.scale=this.scale),!0===this.dithering&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),!0===this.alphaHash&&(n.alphaHash=!0),!0===this.alphaToCoverage&&(n.alphaToCoverage=!0),!0===this.premultipliedAlpha&&(n.premultipliedAlpha=!0),!0===this.forceSinglePass&&(n.forceSinglePass=!0),!1===this.allowOverride&&(n.allowOverride=!1),!0===this.wireframe&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),"round"!==this.wireframeLinecap&&(n.wireframeLinecap=this.wireframeLinecap),"round"!==this.wireframeLinejoin&&(n.wireframeLinejoin=this.wireframeLinejoin),!0===this.flatShading&&(n.flatShading=!0),!1===this.visible&&(n.visible=!1),!1===this.toneMapped&&(n.toneMapped=!1),!1===this.fog&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData),t){const t=i(e.textures),r=i(e.images);t.length>0&&(n.textures=t),r.length>0&&(n.images=r)}return n}clone(){return(new this.constructor).copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let n=null;if(null!==t){const e=t.length;n=new Array(e);for(let i=0;i!==e;++i)n[i]=t[i].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.allowOverride=e.allowOverride,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){!0===e&&this.version++}}class is extends ns{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new $r(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new _r,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const rs=ss();function ss(){const e=new ArrayBuffer(4),t=new Float32Array(e),n=new Uint32Array(e),i=new Uint32Array(512),r=new Uint32Array(512);for(let l=0;l<256;++l){const e=l-127;e<-27?(i[l]=0,i[256|l]=32768,r[l]=24,r[256|l]=24):e<-14?(i[l]=1024>>-e-14,i[256|l]=1024>>-e-14|32768,r[l]=-e-1,r[256|l]=-e-1):e<=15?(i[l]=e+15<<10,i[256|l]=e+15<<10|32768,r[l]=13,r[256|l]=13):e<128?(i[l]=31744,i[256|l]=64512,r[l]=24,r[256|l]=24):(i[l]=31744,i[256|l]=64512,r[l]=13,r[256|l]=13)}const s=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let l=1;l<1024;++l){let e=l<<13,t=0;for(;!(8388608&e);)e<<=1,t-=8388608;e&=-8388609,t+=947912704,s[l]=e|t}for(let l=1024;l<2048;++l)s[l]=939524096+(l-1024<<13);for(let l=1;l<31;++l)a[l]=l<<23;a[31]=1199570944,a[32]=2147483648;for(let l=33;l<63;++l)a[l]=2147483648+(l-32<<23);a[63]=3347054592;for(let l=1;l<64;++l)32!==l&&(o[l]=1024);return{floatView:t,uint32View:n,baseTable:i,shiftTable:r,mantissaTable:s,exponentTable:a,offsetTable:o}}class as{static toHalfFloat(e){return function(e){Math.abs(e)>65504&&qn("DataUtils.toHalfFloat(): Value out of range."),e=ni(e,-65504,65504),rs.floatView[0]=e;const t=rs.uint32View[0],n=t>>23&511;return rs.baseTable[n]+((8388607&t)>>rs.shiftTable[n])}(e)}static fromHalfFloat(e){return function(e){const t=e>>10;return rs.uint32View[0]=rs.mantissaTable[rs.offsetTable[t]+(1023&e)]+rs.exponentTable[t],rs.floatView[0]}(e)}}const os=new hi,ls=new li;let cs=0;class hs{constructor(e,t,n=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:cs++}),this.name="",this.array=e,this.itemSize=t,this.count=void 0!==e?e.length/t:0,this.normalized=n,this.usage=kn,this.updateRanges=[],this.gpuType=gt,this.version=0}onUploadCallback(){}set needsUpdate(e){!0===e&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let i=0,r=this.itemSize;i<r;i++)this.array[e+i]=t.array[n+i];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(2===this.itemSize)for(let t=0,n=this.count;t<n;t++)ls.fromBufferAttribute(this,t),ls.applyMatrix3(e),this.setXY(t,ls.x,ls.y);else if(3===this.itemSize)for(let t=0,n=this.count;t<n;t++)os.fromBufferAttribute(this,t),os.applyMatrix3(e),this.setXYZ(t,os.x,os.y,os.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)os.fromBufferAttribute(this,t),os.applyMatrix4(e),this.setXYZ(t,os.x,os.y,os.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)os.fromBufferAttribute(this,t),os.applyNormalMatrix(e),this.setXYZ(t,os.x,os.y,os.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)os.fromBufferAttribute(this,t),os.transformDirection(e),this.setXYZ(t,os.x,os.y,os.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let n=this.array[e*this.itemSize+t];return this.normalized&&(n=si(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=ai(n,this.array)),this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=si(t,this.array)),t}setX(e,t){return this.normalized&&(t=ai(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=si(t,this.array)),t}setY(e,t){return this.normalized&&(t=ai(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=si(t,this.array)),t}setZ(e,t){return this.normalized&&(t=ai(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=si(t,this.array)),t}setW(e,t){return this.normalized&&(t=ai(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=ai(t,this.array),n=ai(n,this.array)),this.array[e+0]=t,this.array[e+1]=n,this}setXYZ(e,t,n,i){return e*=this.itemSize,this.normalized&&(t=ai(t,this.array),n=ai(n,this.array),i=ai(i,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=i,this}setXYZW(e,t,n,i,r){return e*=this.itemSize,this.normalized&&(t=ai(t,this.array),n=ai(n,this.array),i=ai(i,this.array),r=ai(r,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=i,this.array[e+3]=r,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return""!==this.name&&(e.name=this.name),this.usage!==kn&&(e.usage=this.usage),e}}class us extends hs{constructor(e,t,n){super(new Uint16Array(e),t,n)}}class ds extends hs{constructor(e,t,n){super(new Uint32Array(e),t,n)}}class ps extends hs{constructor(e,t,n){super(new Float32Array(e),t,n)}}let fs=0;const ms=new or,gs=new Lr,_s=new hi,vs=new Li,xs=new Li,ys=new hi;class Ss extends Yn{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:fs++}),this.uuid=ti(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(Vn(e)?ds:us)(e,1):this.index=e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return void 0!==this.attributes[e]}addGroup(e,t,n=0){this.groups.push({start:e,count:t,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){const t=this.attributes.position;void 0!==t&&(t.applyMatrix4(e),t.needsUpdate=!0);const n=this.attributes.normal;if(void 0!==n){const t=(new pi).getNormalMatrix(e);n.applyNormalMatrix(t),n.needsUpdate=!0}const i=this.attributes.tangent;return void 0!==i&&(i.transformDirection(e),i.needsUpdate=!0),null!==this.boundingBox&&this.computeBoundingBox(),null!==this.boundingSphere&&this.computeBoundingSphere(),this}applyQuaternion(e){return ms.makeRotationFromQuaternion(e),this.applyMatrix4(ms),this}rotateX(e){return ms.makeRotationX(e),this.applyMatrix4(ms),this}rotateY(e){return ms.makeRotationY(e),this.applyMatrix4(ms),this}rotateZ(e){return ms.makeRotationZ(e),this.applyMatrix4(ms),this}translate(e,t,n){return ms.makeTranslation(e,t,n),this.applyMatrix4(ms),this}scale(e,t,n){return ms.makeScale(e,t,n),this.applyMatrix4(ms),this}lookAt(e){return gs.lookAt(e),gs.updateMatrix(),this.applyMatrix4(gs.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(_s).negate(),this.translate(_s.x,_s.y,_s.z),this}setFromPoints(e){const t=this.getAttribute("position");if(void 0===t){const t=[];for(let n=0,i=e.length;n<i;n++){const i=e[n];t.push(i.x,i.y,i.z||0)}this.setAttribute("position",new ps(t,3))}else{const n=Math.min(e.length,t.count);for(let i=0;i<n;i++){const n=e[i];t.setXYZ(i,n.x,n.y,n.z||0)}e.length>t.count&&qn("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){null===this.boundingBox&&(this.boundingBox=new Li);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return Qn("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),void this.boundingBox.set(new hi(-1/0,-1/0,-1/0),new hi(1/0,1/0,1/0));if(void 0!==e){if(this.boundingBox.setFromBufferAttribute(e),t)for(let n=0,i=t.length;n<i;n++){const e=t[n];vs.setFromBufferAttribute(e),this.morphTargetsRelative?(ys.addVectors(this.boundingBox.min,vs.min),this.boundingBox.expandByPoint(ys),ys.addVectors(this.boundingBox.max,vs.max),this.boundingBox.expandByPoint(ys)):(this.boundingBox.expandByPoint(vs.min),this.boundingBox.expandByPoint(vs.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&Qn('BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){null===this.boundingSphere&&(this.boundingSphere=new Ji);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return Qn("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),void this.boundingSphere.set(new hi,1/0);if(e){const n=this.boundingSphere.center;if(vs.setFromBufferAttribute(e),t)for(let e=0,r=t.length;e<r;e++){const n=t[e];xs.setFromBufferAttribute(n),this.morphTargetsRelative?(ys.addVectors(vs.min,xs.min),vs.expandByPoint(ys),ys.addVectors(vs.max,xs.max),vs.expandByPoint(ys)):(vs.expandByPoint(xs.min),vs.expandByPoint(xs.max))}vs.getCenter(n);let i=0;for(let t=0,r=e.count;t<r;t++)ys.fromBufferAttribute(e,t),i=Math.max(i,n.distanceToSquared(ys));if(t)for(let r=0,s=t.length;r<s;r++){const s=t[r],a=this.morphTargetsRelative;for(let t=0,r=s.count;t<r;t++)ys.fromBufferAttribute(s,t),a&&(_s.fromBufferAttribute(e,t),ys.add(_s)),i=Math.max(i,n.distanceToSquared(ys))}this.boundingSphere.radius=Math.sqrt(i),isNaN(this.boundingSphere.radius)&&Qn('BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const e=this.index,t=this.attributes;if(null===e||void 0===t.position||void 0===t.normal||void 0===t.uv)return void Qn("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");const n=t.position,i=t.normal,r=t.uv;!1===this.hasAttribute("tangent")&&this.setAttribute("tangent",new hs(new Float32Array(4*n.count),4));const s=this.getAttribute("tangent"),a=[],o=[];for(let b=0;b<n.count;b++)a[b]=new hi,o[b]=new hi;const l=new hi,c=new hi,h=new hi,u=new li,d=new li,p=new li,f=new hi,m=new hi;function g(e,t,i){l.fromBufferAttribute(n,e),c.fromBufferAttribute(n,t),h.fromBufferAttribute(n,i),u.fromBufferAttribute(r,e),d.fromBufferAttribute(r,t),p.fromBufferAttribute(r,i),c.sub(l),h.sub(l),d.sub(u),p.sub(u);const s=1/(d.x*p.y-p.x*d.y);isFinite(s)&&(f.copy(c).multiplyScalar(p.y).addScaledVector(h,-d.y).multiplyScalar(s),m.copy(h).multiplyScalar(d.x).addScaledVector(c,-p.x).multiplyScalar(s),a[e].add(f),a[t].add(f),a[i].add(f),o[e].add(m),o[t].add(m),o[i].add(m))}let _=this.groups;0===_.length&&(_=[{start:0,count:e.count}]);for(let b=0,M=_.length;b<M;++b){const t=_[b],n=t.start;for(let i=n,r=n+t.count;i<r;i+=3)g(e.getX(i+0),e.getX(i+1),e.getX(i+2))}const v=new hi,x=new hi,y=new hi,S=new hi;function A(e){y.fromBufferAttribute(i,e),S.copy(y);const t=a[e];v.copy(t),v.sub(y.multiplyScalar(y.dot(t))).normalize(),x.crossVectors(S,t);const n=x.dot(o[e])<0?-1:1;s.setXYZW(e,v.x,v.y,v.z,n)}for(let b=0,M=_.length;b<M;++b){const t=_[b],n=t.start;for(let i=n,r=n+t.count;i<r;i+=3)A(e.getX(i+0)),A(e.getX(i+1)),A(e.getX(i+2))}}computeVertexNormals(){const e=this.index,t=this.getAttribute("position");if(void 0!==t){let n=this.getAttribute("normal");if(void 0===n)n=new hs(new Float32Array(3*t.count),3),this.setAttribute("normal",n);else for(let e=0,t=n.count;e<t;e++)n.setXYZ(e,0,0,0);const i=new hi,r=new hi,s=new hi,a=new hi,o=new hi,l=new hi,c=new hi,h=new hi;if(e)for(let u=0,d=e.count;u<d;u+=3){const d=e.getX(u+0),p=e.getX(u+1),f=e.getX(u+2);i.fromBufferAttribute(t,d),r.fromBufferAttribute(t,p),s.fromBufferAttribute(t,f),c.subVectors(s,r),h.subVectors(i,r),c.cross(h),a.fromBufferAttribute(n,d),o.fromBufferAttribute(n,p),l.fromBufferAttribute(n,f),a.add(c),o.add(c),l.add(c),n.setXYZ(d,a.x,a.y,a.z),n.setXYZ(p,o.x,o.y,o.z),n.setXYZ(f,l.x,l.y,l.z)}else for(let e=0,u=t.count;e<u;e+=3)i.fromBufferAttribute(t,e+0),r.fromBufferAttribute(t,e+1),s.fromBufferAttribute(t,e+2),c.subVectors(s,r),h.subVectors(i,r),c.cross(h),n.setXYZ(e+0,c.x,c.y,c.z),n.setXYZ(e+1,c.x,c.y,c.z),n.setXYZ(e+2,c.x,c.y,c.z);this.normalizeNormals(),n.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let t=0,n=e.count;t<n;t++)ys.fromBufferAttribute(e,t),ys.normalize(),e.setXYZ(t,ys.x,ys.y,ys.z)}toNonIndexed(){function e(e,t){const n=e.array,i=e.itemSize,r=e.normalized,s=new n.constructor(t.length*i);let a=0,o=0;for(let l=0,c=t.length;l<c;l++){a=e.isInterleavedBufferAttribute?t[l]*e.data.stride+e.offset:t[l]*i;for(let e=0;e<i;e++)s[o++]=n[a++]}return new hs(s,i,r)}if(null===this.index)return qn("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new Ss,n=this.index.array,i=this.attributes;for(const a in i){const r=e(i[a],n);t.setAttribute(a,r)}const r=this.morphAttributes;for(const a in r){const i=[],s=r[a];for(let t=0,r=s.length;t<r;t++){const r=e(s[t],n);i.push(r)}t.morphAttributes[a]=i}t.morphTargetsRelative=this.morphTargetsRelative;const s=this.groups;for(let a=0,o=s.length;a<o;a++){const e=s[a];t.addGroup(e.start,e.count,e.materialIndex)}return t}toJSON(){const e={metadata:{version:4.7,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(e.uuid=this.uuid,e.type=this.type,""!==this.name&&(e.name=this.name),Object.keys(this.userData).length>0&&(e.userData=this.userData),void 0!==this.parameters){const t=this.parameters;for(const n in t)void 0!==t[n]&&(e[n]=t[n]);return e}e.data={attributes:{}};const t=this.index;null!==t&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const n=this.attributes;for(const o in n){const t=n[o];e.data.attributes[o]=t.toJSON(e.data)}const i={};let r=!1;for(const o in this.morphAttributes){const t=this.morphAttributes[o],n=[];for(let i=0,r=t.length;i<r;i++){const r=t[i];n.push(r.toJSON(e.data))}n.length>0&&(i[o]=n,r=!0)}r&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);const s=this.groups;s.length>0&&(e.data.groups=JSON.parse(JSON.stringify(s)));const a=this.boundingSphere;return null!==a&&(e.data.boundingSphere=a.toJSON()),e}clone(){return(new this.constructor).copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const n=e.index;null!==n&&this.setIndex(n.clone());const i=e.attributes;for(const l in i){const e=i[l];this.setAttribute(l,e.clone(t))}const r=e.morphAttributes;for(const l in r){const e=[],n=r[l];for(let i=0,r=n.length;i<r;i++)e.push(n[i].clone(t));this.morphAttributes[l]=e}this.morphTargetsRelative=e.morphTargetsRelative;const s=e.groups;for(let l=0,c=s.length;l<c;l++){const e=s[l];this.addGroup(e.start,e.count,e.materialIndex)}const a=e.boundingBox;null!==a&&(this.boundingBox=a.clone());const o=e.boundingSphere;return null!==o&&(this.boundingSphere=o.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}}const As=new or,bs=new ar,Ms=new Ji,ws=new hi,Ts=new hi,Es=new hi,Cs=new hi,Rs=new hi,Is=new hi,Ps=new hi,Ds=new hi;class Bs extends Lr{constructor(e=new Ss,t=new is){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),void 0!==e.morphTargetInfluences&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),void 0!==e.morphTargetDictionary&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){const e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){const n=e[t[0]];if(void 0!==n){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e<t;e++){const t=n[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}getVertexPosition(e,t){const n=this.geometry,i=n.attributes.position,r=n.morphAttributes.position,s=n.morphTargetsRelative;t.fromBufferAttribute(i,e);const a=this.morphTargetInfluences;if(r&&a){Is.set(0,0,0);for(let n=0,i=r.length;n<i;n++){const i=a[n],o=r[n];0!==i&&(Rs.fromBufferAttribute(o,e),s?Is.addScaledVector(Rs,i):Is.addScaledVector(Rs.sub(t),i))}t.add(Is)}return t}raycast(e,t){const n=this.geometry,i=this.material,r=this.matrixWorld;if(void 0!==i){if(null===n.boundingSphere&&n.computeBoundingSphere(),Ms.copy(n.boundingSphere),Ms.applyMatrix4(r),bs.copy(e.ray).recast(e.near),!1===Ms.containsPoint(bs.origin)){if(null===bs.intersectSphere(Ms,ws))return;if(bs.origin.distanceToSquared(ws)>(e.far-e.near)**2)return}As.copy(r).invert(),bs.copy(e.ray).applyMatrix4(As),null!==n.boundingBox&&!1===bs.intersectsBox(n.boundingBox)||this._computeIntersections(e,t,bs)}}_computeIntersections(e,t,n){let i;const r=this.geometry,s=this.material,a=r.index,o=r.attributes.position,l=r.attributes.uv,c=r.attributes.uv1,h=r.attributes.normal,u=r.groups,d=r.drawRange;if(null!==a)if(Array.isArray(s))for(let p=0,f=u.length;p<f;p++){const r=u[p],o=s[r.materialIndex];for(let s=Math.max(r.start,d.start),u=Math.min(a.count,Math.min(r.start+r.count,d.start+d.count));s<u;s+=3){i=Ls(this,o,e,n,l,c,h,a.getX(s),a.getX(s+1),a.getX(s+2)),i&&(i.faceIndex=Math.floor(s/3),i.face.materialIndex=r.materialIndex,t.push(i))}}else{for(let r=Math.max(0,d.start),o=Math.min(a.count,d.start+d.count);r<o;r+=3){i=Ls(this,s,e,n,l,c,h,a.getX(r),a.getX(r+1),a.getX(r+2)),i&&(i.faceIndex=Math.floor(r/3),t.push(i))}}else if(void 0!==o)if(Array.isArray(s))for(let p=0,f=u.length;p<f;p++){const r=u[p],a=s[r.materialIndex];for(let s=Math.max(r.start,d.start),u=Math.min(o.count,Math.min(r.start+r.count,d.start+d.count));s<u;s+=3){i=Ls(this,a,e,n,l,c,h,s,s+1,s+2),i&&(i.faceIndex=Math.floor(s/3),i.face.materialIndex=r.materialIndex,t.push(i))}}else{for(let r=Math.max(0,d.start),a=Math.min(o.count,d.start+d.count);r<a;r+=3){i=Ls(this,s,e,n,l,c,h,r,r+1,r+2),i&&(i.faceIndex=Math.floor(r/3),t.push(i))}}}}function Ls(e,t,n,i,r,s,a,o,l,c){e.getVertexPosition(o,Ts),e.getVertexPosition(l,Es),e.getVertexPosition(c,Cs);const h=function(e,t,n,i,r,s,a,o){let l;if(l=1===t.side?i.intersectTriangle(a,s,r,!0,o):i.intersectTriangle(r,s,a,0===t.side,o),null===l)return null;Ds.copy(o),Ds.applyMatrix4(e.matrixWorld);const c=n.ray.origin.distanceTo(Ds);return c<n.near||c>n.far?null:{distance:c,point:Ds.clone(),object:e}}(e,t,n,i,Ts,Es,Cs,Ps);if(h){const e=new hi;Qr.getBarycoord(Ps,Ts,Es,Cs,e),r&&(h.uv=Qr.getInterpolatedAttribute(r,o,l,c,e,new li)),s&&(h.uv1=Qr.getInterpolatedAttribute(s,o,l,c,e,new li)),a&&(h.normal=Qr.getInterpolatedAttribute(a,o,l,c,e,new hi),h.normal.dot(i.direction)>0&&h.normal.multiplyScalar(-1));const t={a:o,b:l,c:c,normal:new hi,materialIndex:0};Qr.getNormal(Ts,Es,Cs,t.normal),h.face=t,h.barycoord=e}return h}class Fs extends Ss{constructor(e=1,t=1,n=1,i=1,r=1,s=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:n,widthSegments:i,heightSegments:r,depthSegments:s};const a=this;i=Math.floor(i),r=Math.floor(r),s=Math.floor(s);const o=[],l=[],c=[],h=[];let u=0,d=0;function p(e,t,n,i,r,s,p,f,m,g,_){const v=s/m,x=p/g,y=s/2,S=p/2,A=f/2,b=m+1,M=g+1;let w=0,T=0;const E=new hi;for(let a=0;a<M;a++){const s=a*x-S;for(let o=0;o<b;o++){const u=o*v-y;E[e]=u*i,E[t]=s*r,E[n]=A,l.push(E.x,E.y,E.z),E[e]=0,E[t]=0,E[n]=f>0?1:-1,c.push(E.x,E.y,E.z),h.push(o/m),h.push(1-a/g),w+=1}}for(let a=0;a<g;a++)for(let e=0;e<m;e++){const t=u+e+b*a,n=u+e+b*(a+1),i=u+(e+1)+b*(a+1),r=u+(e+1)+b*a;o.push(t,n,r),o.push(n,i,r),T+=6}a.addGroup(d,T,_),d+=T,u+=w}p("z","y","x",-1,-1,n,t,e,s,r,0),p("z","y","x",1,-1,n,t,-e,s,r,1),p("x","z","y",1,1,e,n,t,i,s,2),p("x","z","y",1,-1,e,n,-t,i,s,3),p("x","y","z",1,-1,e,t,n,i,r,4),p("x","y","z",-1,-1,e,t,-n,i,r,5),this.setIndex(o),this.setAttribute("position",new ps(l,3)),this.setAttribute("normal",new ps(c,3)),this.setAttribute("uv",new ps(h,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Fs(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}function Us(e){const t={};for(const n in e){t[n]={};for(const i in e[n]){const r=e[n][i];r&&(r.isColor||r.isMatrix3||r.isMatrix4||r.isVector2||r.isVector3||r.isVector4||r.isTexture||r.isQuaternion)?r.isRenderTargetTexture?(qn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),t[n][i]=null):t[n][i]=r.clone():Array.isArray(r)?t[n][i]=r.slice():t[n][i]=r}}return t}function ks(e){const t={};for(let n=0;n<e.length;n++){const i=Us(e[n]);for(const e in i)t[e]=i[e]}return t}function Ns(e){const t=e.getRenderTarget();return null===t?e.outputColorSpace:!0===t.isXRRenderTarget?t.texture.colorSpace:vi.workingColorSpace}const Os={clone:Us,merge:ks};class zs extends ns{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader="void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}",this.fragmentShader="void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}",this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,void 0!==e&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=Us(e.uniforms),this.uniformsGroups=function(e){const t=[];for(let n=0;n<e.length;n++)t.push(e[n].clone());return t}(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this.defaultAttributeValues=Object.assign({},e.defaultAttributeValues),this.index0AttributeName=e.index0AttributeName,this.uniformsNeedUpdate=e.uniformsNeedUpdate,this}toJSON(e){const t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(const i in this.uniforms){const n=this.uniforms[i].value;n&&n.isTexture?t.uniforms[i]={type:"t",value:n.toJSON(e).uuid}:n&&n.isColor?t.uniforms[i]={type:"c",value:n.getHex()}:n&&n.isVector2?t.uniforms[i]={type:"v2",value:n.toArray()}:n&&n.isVector3?t.uniforms[i]={type:"v3",value:n.toArray()}:n&&n.isVector4?t.uniforms[i]={type:"v4",value:n.toArray()}:n&&n.isMatrix3?t.uniforms[i]={type:"m3",value:n.toArray()}:n&&n.isMatrix4?t.uniforms[i]={type:"m4",value:n.toArray()}:t.uniforms[i]={value:n}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const n={};for(const i in this.extensions)!0===this.extensions[i]&&(n[i]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}}class Hs extends Lr{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new or,this.projectionMatrix=new or,this.projectionMatrixInverse=new or,this.coordinateSystem=zn,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return(new this.constructor).copy(this)}}const Vs=new hi,Gs=new li,Ws=new li;class js extends Hs{constructor(e=50,t=1,n=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=n,this.far=i,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=null===e.view?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=2*ei*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(.5*$n*this.fov);return.5*this.getFilmHeight()/e}getEffectiveFOV(){return 2*ei*Math.atan(Math.tan(.5*$n*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,n){Vs.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Vs.x,Vs.y).multiplyScalar(-e/Vs.z),Vs.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(Vs.x,Vs.y).multiplyScalar(-e/Vs.z)}getViewSize(e,t){return this.getViewBounds(e,Gs,Ws),t.subVectors(Ws,Gs)}setViewOffset(e,t,n,i,r,s){this.aspect=e/t,null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=i,this.view.width=r,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(.5*$n*this.fov)/this.zoom,n=2*t,i=this.aspect*n,r=-.5*i;const s=this.view;if(null!==this.view&&this.view.enabled){const e=s.fullWidth,a=s.fullHeight;r+=s.offsetX*i/e,t-=s.offsetY*n/a,i*=s.width/e,n*=s.height/a}const a=this.filmOffset;0!==a&&(r+=e*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+i,t,t-n,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,null!==this.view&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const Xs=-90;class qs extends Lr{constructor(e,t,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new js(Xs,1,e,t);i.layers=this.layers,this.add(i);const r=new js(Xs,1,e,t);r.layers=this.layers,this.add(r);const s=new js(Xs,1,e,t);s.layers=this.layers,this.add(s);const a=new js(Xs,1,e,t);a.layers=this.layers,this.add(a);const o=new js(Xs,1,e,t);o.layers=this.layers,this.add(o);const l=new js(Xs,1,e,t);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[n,i,r,s,a,o]=t;for(const l of t)this.remove(l);if(e===zn)n.up.set(0,1,0),n.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),s.up.set(0,0,1),s.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),o.up.set(0,1,0),o.lookAt(0,0,-1);else{if(e!==Hn)throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);n.up.set(0,-1,0),n.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),s.up.set(0,0,-1),s.lookAt(0,-1,0),a.up.set(0,-1,0),a.lookAt(0,0,1),o.up.set(0,-1,0),o.lookAt(0,0,-1)}for(const l of t)this.add(l),l.updateMatrixWorld()}update(e,t){null===this.parent&&this.updateMatrixWorld();const{renderTarget:n,activeMipmapLevel:i}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[r,s,a,o,l,c]=this.children,h=e.getRenderTarget(),u=e.getActiveCubeFace(),d=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;const f=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,e.setRenderTarget(n,0,i),e.render(t,r),e.setRenderTarget(n,1,i),e.render(t,s),e.setRenderTarget(n,2,i),e.render(t,a),e.setRenderTarget(n,3,i),e.render(t,o),e.setRenderTarget(n,4,i),e.render(t,l),n.texture.generateMipmaps=f,e.setRenderTarget(n,5,i),e.render(t,c),e.setRenderTarget(h,u,d),e.xr.enabled=p,n.texture.needsPMREMUpdate=!0}}class Qs extends Ci{constructor(e=[],t=301,n,i,r,s,a,o,l,c){super(e,t,n,i,r,s,a,o,l,c),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class Ks extends Pi{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const n={width:e,height:e,depth:1},i=[n,n,n,n,n,n];this.texture=new Qs(i),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const n={uniforms:{tEquirect:{value:null}},vertexShader:"\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t\t}\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t\t#include <begin_vertex>\n\t\t\t\t\t#include <project_vertex>\n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\n\t\t\t\tuniform sampler2D tEquirect;\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\t#include <common>\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t\t}\n\t\t\t"},i=new Fs(5,5,5),r=new zs({name:"CubemapFromEquirect",uniforms:Us(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:1,blending:0});r.uniforms.tEquirect.value=t;const s=new Bs(i,r),a=t.minFilter;t.minFilter===ct&&(t.minFilter=ot);return new qs(1,10,this).update(e,s),t.minFilter=a,s.geometry.dispose(),s.material.dispose(),this}clear(e,t=!0,n=!0,i=!0){const r=e.getRenderTarget();for(let s=0;s<6;s++)e.setRenderTarget(this,s),e.clear(t,n,i);e.setRenderTarget(r)}}class Ys extends Lr{constructor(){super(),this.isGroup=!0,this.type="Group"}}const Zs={type:"move"};class Js{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return null===this._hand&&(this._hand=new Ys,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return null===this._targetRay&&(this._targetRay=new Ys,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new hi,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new hi),this._targetRay}getGripSpace(){return null===this._grip&&(this._grip=new Ys,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new hi,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new hi),this._grip}dispatchEvent(e){return null!==this._targetRay&&this._targetRay.dispatchEvent(e),null!==this._grip&&this._grip.dispatchEvent(e),null!==this._hand&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const n of e.hand.values())this._getHandJoint(t,n)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),null!==this._targetRay&&(this._targetRay.visible=!1),null!==this._grip&&(this._grip.visible=!1),null!==this._hand&&(this._hand.visible=!1),this}update(e,t,n){let i=null,r=null,s=null;const a=this._targetRay,o=this._grip,l=this._hand;if(e&&"visible-blurred"!==t.session.visibilityState){if(l&&e.hand){s=!0;for(const s of e.hand.values()){const e=t.getJointPose(s,n),i=this._getHandJoint(l,s);null!==e&&(i.matrix.fromArray(e.transform.matrix),i.matrix.decompose(i.position,i.rotation,i.scale),i.matrixWorldNeedsUpdate=!0,i.jointRadius=e.radius),i.visible=null!==e}const i=l.joints["index-finger-tip"],r=l.joints["thumb-tip"],a=i.position.distanceTo(r.position),o=.02,c=.005;l.inputState.pinching&&a>o+c?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!l.inputState.pinching&&a<=o-c&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else null!==o&&e.gripSpace&&(r=t.getPose(e.gripSpace,n),null!==r&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1));null!==a&&(i=t.getPose(e.targetRaySpace,n),null===i&&null!==r&&(i=r),null!==i&&(a.matrix.fromArray(i.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,i.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(i.linearVelocity)):a.hasLinearVelocity=!1,i.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(i.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(Zs)))}return null!==a&&(a.visible=null!==i),null!==o&&(o.visible=null!==r),null!==l&&(l.visible=null!==s),this}_getHandJoint(e,t){if(void 0===e.joints[t.jointName]){const n=new Ys;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}}class $s extends Lr{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new _r,this.environmentIntensity=1,this.environmentRotation=new _r,this.overrideMaterial=null,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),null!==e.background&&(this.background=e.background.clone()),null!==e.environment&&(this.environment=e.environment.clone()),null!==e.fog&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),null!==e.overrideMaterial&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return null!==this.fog&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),1!==this.backgroundIntensity&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),1!==this.environmentIntensity&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}class ea{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=void 0!==e?e.length/t:0,this.usage=kn,this.updateRanges=[],this.version=0,this.uuid=ti()}onUploadCallback(){}set needsUpdate(e){!0===e&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,n){e*=this.stride,n*=t.stride;for(let i=0,r=this.stride;i<r;i++)this.array[e+i]=t.array[n+i];return this}set(e,t=0){return this.array.set(e,t),this}clone(e){void 0===e.arrayBuffers&&(e.arrayBuffers={}),void 0===this.array.buffer._uuid&&(this.array.buffer._uuid=ti()),void 0===e.arrayBuffers[this.array.buffer._uuid]&&(e.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);const t=new this.array.constructor(e.arrayBuffers[this.array.buffer._uuid]),n=new this.constructor(t,this.stride);return n.setUsage(this.usage),n}onUpload(e){return this.onUploadCallback=e,this}toJSON(e){return void 0===e.arrayBuffers&&(e.arrayBuffers={}),void 0===this.array.buffer._uuid&&(this.array.buffer._uuid=ti()),void 0===e.arrayBuffers[this.array.buffer._uuid]&&(e.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer))),{uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride}}}const ta=new hi;class na{constructor(e,t,n,i=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=e,this.itemSize=t,this.offset=n,this.normalized=i}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate(e){this.data.needsUpdate=e}applyMatrix4(e){for(let t=0,n=this.data.count;t<n;t++)ta.fromBufferAttribute(this,t),ta.applyMatrix4(e),this.setXYZ(t,ta.x,ta.y,ta.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)ta.fromBufferAttribute(this,t),ta.applyNormalMatrix(e),this.setXYZ(t,ta.x,ta.y,ta.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)ta.fromBufferAttribute(this,t),ta.transformDirection(e),this.setXYZ(t,ta.x,ta.y,ta.z);return this}getComponent(e,t){let n=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(n=si(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=ai(n,this.array)),this.data.array[e*this.data.stride+this.offset+t]=n,this}setX(e,t){return this.normalized&&(t=ai(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=ai(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=ai(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=ai(t,this.array)),this.data.array[e*this.data.stride+this.offset+3]=t,this}getX(e){let t=this.data.array[e*this.data.stride+this.offset];return this.normalized&&(t=si(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=si(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=si(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=si(t,this.array)),t}setXY(e,t,n){return e=e*this.data.stride+this.offset,this.normalized&&(t=ai(t,this.array),n=ai(n,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this}setXYZ(e,t,n,i){return e=e*this.data.stride+this.offset,this.normalized&&(t=ai(t,this.array),n=ai(n,this.array),i=ai(i,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=i,this}setXYZW(e,t,n,i,r){return e=e*this.data.stride+this.offset,this.normalized&&(t=ai(t,this.array),n=ai(n,this.array),i=ai(i,this.array),r=ai(r,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=i,this.data.array[e+3]=r,this}clone(e){if(void 0===e){Xn("InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");const e=[];for(let t=0;t<this.count;t++){const n=t*this.data.stride+this.offset;for(let t=0;t<this.itemSize;t++)e.push(this.data.array[n+t])}return new hs(new this.array.constructor(e),this.itemSize,this.normalized)}return void 0===e.interleavedBuffers&&(e.interleavedBuffers={}),void 0===e.interleavedBuffers[this.data.uuid]&&(e.interleavedBuffers[this.data.uuid]=this.data.clone(e)),new na(e.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(void 0===e){Xn("InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");const e=[];for(let t=0;t<this.count;t++){const n=t*this.data.stride+this.offset;for(let t=0;t<this.itemSize;t++)e.push(this.data.array[n+t])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:e,normalized:this.normalized}}return void 0===e.interleavedBuffers&&(e.interleavedBuffers={}),void 0===e.interleavedBuffers[this.data.uuid]&&(e.interleavedBuffers[this.data.uuid]=this.data.toJSON(e)),{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}}const ia=new hi,ra=new Ri,sa=new Ri,aa=new hi,oa=new or,la=new hi,ca=new Ji,ha=new or,ua=new ar;class da extends Bs{constructor(e,t){super(e,t),this.isSkinnedMesh=!0,this.type="SkinnedMesh",this.bindMode=Ze,this.bindMatrix=new or,this.bindMatrixInverse=new or,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){const e=this.geometry;null===this.boundingBox&&(this.boundingBox=new Li),this.boundingBox.makeEmpty();const t=e.getAttribute("position");for(let n=0;n<t.count;n++)this.getVertexPosition(n,la),this.boundingBox.expandByPoint(la)}computeBoundingSphere(){const e=this.geometry;null===this.boundingSphere&&(this.boundingSphere=new Ji),this.boundingSphere.makeEmpty();const t=e.getAttribute("position");for(let n=0;n<t.count;n++)this.getVertexPosition(n,la),this.boundingSphere.expandByPoint(la)}copy(e,t){return super.copy(e,t),this.bindMode=e.bindMode,this.bindMatrix.copy(e.bindMatrix),this.bindMatrixInverse.copy(e.bindMatrixInverse),this.skeleton=e.skeleton,null!==e.boundingBox&&(this.boundingBox=e.boundingBox.clone()),null!==e.boundingSphere&&(this.boundingSphere=e.boundingSphere.clone()),this}raycast(e,t){const n=this.material,i=this.matrixWorld;void 0!==n&&(null===this.boundingSphere&&this.computeBoundingSphere(),ca.copy(this.boundingSphere),ca.applyMatrix4(i),!1!==e.ray.intersectsSphere(ca)&&(ha.copy(i).invert(),ua.copy(e.ray).applyMatrix4(ha),null!==this.boundingBox&&!1===ua.intersectsBox(this.boundingBox)||this._computeIntersections(e,t,ua)))}getVertexPosition(e,t){return super.getVertexPosition(e,t),this.applyBoneTransform(e,t),t}bind(e,t){this.skeleton=e,void 0===t&&(this.updateMatrixWorld(!0),this.skeleton.calculateInverses(),t=this.matrixWorld),this.bindMatrix.copy(t),this.bindMatrixInverse.copy(t).invert()}pose(){this.skeleton.pose()}normalizeSkinWeights(){const e=new Ri,t=this.geometry.attributes.skinWeight;for(let n=0,i=t.count;n<i;n++){e.fromBufferAttribute(t,n);const i=1/e.manhattanLength();i!==1/0?e.multiplyScalar(i):e.set(1,0,0,0),t.setXYZW(n,e.x,e.y,e.z,e.w)}}updateMatrixWorld(e){super.updateMatrixWorld(e),this.bindMode===Ze?this.bindMatrixInverse.copy(this.matrixWorld).invert():"detached"===this.bindMode?this.bindMatrixInverse.copy(this.bindMatrix).invert():qn("SkinnedMesh: Unrecognized bindMode: "+this.bindMode)}applyBoneTransform(e,t){const n=this.skeleton,i=this.geometry;ra.fromBufferAttribute(i.attributes.skinIndex,e),sa.fromBufferAttribute(i.attributes.skinWeight,e),ia.copy(t).applyMatrix4(this.bindMatrix),t.set(0,0,0);for(let r=0;r<4;r++){const e=sa.getComponent(r);if(0!==e){const i=ra.getComponent(r);oa.multiplyMatrices(n.bones[i].matrixWorld,n.boneInverses[i]),t.addScaledVector(aa.copy(ia).applyMatrix4(oa),e)}}return t.applyMatrix4(this.bindMatrixInverse)}}class pa extends Lr{constructor(){super(),this.isBone=!0,this.type="Bone"}}class fa extends Ci{constructor(e=null,t=1,n=1,i,r,s,a,o,l=1003,c=1003,h,u){super(null,s,a,o,l,c,i,r,h,u),this.isDataTexture=!0,this.image={data:e,width:t,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}const ma=new or,ga=new or;class _a{constructor(e=[],t=[]){this.uuid=ti(),this.bones=e.slice(0),this.boneInverses=t,this.boneMatrices=null,this.previousBoneMatrices=null,this.boneTexture=null,this.init()}init(){const e=this.bones,t=this.boneInverses;if(this.boneMatrices=new Float32Array(16*e.length),0===t.length)this.calculateInverses();else if(e.length!==t.length){qn("Skeleton: Number of inverse bone matrices does not match amount of bones."),this.boneInverses=[];for(let e=0,t=this.bones.length;e<t;e++)this.boneInverses.push(new or)}}calculateInverses(){this.boneInverses.length=0;for(let e=0,t=this.bones.length;e<t;e++){const t=new or;this.bones[e]&&t.copy(this.bones[e].matrixWorld).invert(),this.boneInverses.push(t)}}pose(){for(let e=0,t=this.bones.length;e<t;e++){const t=this.bones[e];t&&t.matrixWorld.copy(this.boneInverses[e]).invert()}for(let e=0,t=this.bones.length;e<t;e++){const t=this.bones[e];t&&(t.parent&&t.parent.isBone?(t.matrix.copy(t.parent.matrixWorld).invert(),t.matrix.multiply(t.matrixWorld)):t.matrix.copy(t.matrixWorld),t.matrix.decompose(t.position,t.quaternion,t.scale))}}update(){const e=this.bones,t=this.boneInverses,n=this.boneMatrices,i=this.boneTexture;for(let r=0,s=e.length;r<s;r++){const i=e[r]?e[r].matrixWorld:ga;ma.multiplyMatrices(i,t[r]),ma.toArray(n,16*r)}null!==i&&(i.needsUpdate=!0)}clone(){return new _a(this.bones,this.boneInverses)}computeBoneTexture(){let e=Math.sqrt(4*this.bones.length);e=4*Math.ceil(e/4),e=Math.max(e,4);const t=new Float32Array(e*e*4);t.set(this.boneMatrices);const n=new fa(t,e,e,bt,gt);return n.needsUpdate=!0,this.boneMatrices=t,this.boneTexture=n,this}getBoneByName(e){for(let t=0,n=this.bones.length;t<n;t++){const n=this.bones[t];if(n.name===e)return n}}dispose(){null!==this.boneTexture&&(this.boneTexture.dispose(),this.boneTexture=null)}fromJSON(e,t){this.uuid=e.uuid;for(let n=0,i=e.bones.length;n<i;n++){const i=e.bones[n];let r=t[i];void 0===r&&(qn("Skeleton: No bone found with UUID:",i),r=new pa),this.bones.push(r),this.boneInverses.push((new or).fromArray(e.boneInverses[n]))}return this.init(),this}toJSON(){const e={metadata:{version:4.7,type:"Skeleton",generator:"Skeleton.toJSON"},bones:[],boneInverses:[]};e.uuid=this.uuid;const t=this.bones,n=this.boneInverses;for(let i=0,r=t.length;i<r;i++){const r=t[i];e.bones.push(r.uuid);const s=n[i];e.boneInverses.push(s.toArray())}return e}}class va extends hs{constructor(e,t,n,i=1){super(e,t,n),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=i}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}toJSON(){const e=super.toJSON();return e.meshPerAttribute=this.meshPerAttribute,e.isInstancedBufferAttribute=!0,e}}const xa=new or,ya=new or,Sa=[],Aa=new Li,ba=new or,Ma=new Bs,wa=new Ji;class Ta extends Bs{constructor(e,t,n){super(e,t),this.isInstancedMesh=!0,this.instanceMatrix=new va(new Float32Array(16*n),16),this.instanceColor=null,this.morphTexture=null,this.count=n,this.boundingBox=null,this.boundingSphere=null;for(let i=0;i<n;i++)this.setMatrixAt(i,ba)}computeBoundingBox(){const e=this.geometry,t=this.count;null===this.boundingBox&&(this.boundingBox=new Li),null===e.boundingBox&&e.computeBoundingBox(),this.boundingBox.makeEmpty();for(let n=0;n<t;n++)this.getMatrixAt(n,xa),Aa.copy(e.boundingBox).applyMatrix4(xa),this.boundingBox.union(Aa)}computeBoundingSphere(){const e=this.geometry,t=this.count;null===this.boundingSphere&&(this.boundingSphere=new Ji),null===e.boundingSphere&&e.computeBoundingSphere(),this.boundingSphere.makeEmpty();for(let n=0;n<t;n++)this.getMatrixAt(n,xa),wa.copy(e.boundingSphere).applyMatrix4(xa),this.boundingSphere.union(wa)}copy(e,t){return super.copy(e,t),this.instanceMatrix.copy(e.instanceMatrix),null!==e.morphTexture&&(this.morphTexture=e.morphTexture.clone()),null!==e.instanceColor&&(this.instanceColor=e.instanceColor.clone()),this.count=e.count,null!==e.boundingBox&&(this.boundingBox=e.boundingBox.clone()),null!==e.boundingSphere&&(this.boundingSphere=e.boundingSphere.clone()),this}getColorAt(e,t){t.fromArray(this.instanceColor.array,3*e)}getMatrixAt(e,t){t.fromArray(this.instanceMatrix.array,16*e)}getMorphAt(e,t){const n=t.morphTargetInfluences,i=this.morphTexture.source.data.data,r=e*(n.length+1)+1;for(let s=0;s<n.length;s++)n[s]=i[r+s]}raycast(e,t){const n=this.matrixWorld,i=this.count;if(Ma.geometry=this.geometry,Ma.material=this.material,void 0!==Ma.material&&(null===this.boundingSphere&&this.computeBoundingSphere(),wa.copy(this.boundingSphere),wa.applyMatrix4(n),!1!==e.ray.intersectsSphere(wa)))for(let r=0;r<i;r++){this.getMatrixAt(r,xa),ya.multiplyMatrices(n,xa),Ma.matrixWorld=ya,Ma.raycast(e,Sa);for(let e=0,n=Sa.length;e<n;e++){const n=Sa[e];n.instanceId=r,n.object=this,t.push(n)}Sa.length=0}}setColorAt(e,t){null===this.instanceColor&&(this.instanceColor=new va(new Float32Array(3*this.instanceMatrix.count).fill(1),3)),t.toArray(this.instanceColor.array,3*e)}setMatrixAt(e,t){t.toArray(this.instanceMatrix.array,16*e)}setMorphAt(e,t){const n=t.morphTargetInfluences,i=n.length+1;null===this.morphTexture&&(this.morphTexture=new fa(new Float32Array(i*this.count),i,this.count,Tt,gt));const r=this.morphTexture.source.data.data;let s=0;for(let l=0;l<n.length;l++)s+=n[l];const a=this.geometry.morphTargetsRelative?1:1-s,o=i*e;r[o]=a,r.set(n,o+1)}updateMorphTargets(){}dispose(){this.dispatchEvent({type:"dispose"}),null!==this.morphTexture&&(this.morphTexture.dispose(),this.morphTexture=null)}}const Ea=new hi,Ca=new hi,Ra=new pi;class Ia{constructor(e=new hi(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,i){return this.normal.set(e,t,n),this.constant=i,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){const i=Ea.subVectors(n,t).cross(Ca.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(i,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t){const n=e.delta(Ea),i=this.normal.dot(n);if(0===i)return 0===this.distanceToPoint(e.start)?t.copy(e.start):null;const r=-(e.start.dot(this.normal)+this.constant)/i;return r<0||r>1?null:t.copy(e.start).addScaledVector(n,r)}intersectsLine(e){const t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const n=t||Ra.getNormalMatrix(e),i=this.coplanarPoint(Ea).applyMatrix4(e),r=this.normal.applyMatrix3(n).normalize();return this.constant=-i.dot(r),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return(new this.constructor).copy(this)}}const Pa=new Ji,Da=new li(.5,.5),Ba=new hi;class La{constructor(e=new Ia,t=new Ia,n=new Ia,i=new Ia,r=new Ia,s=new Ia){this.planes=[e,t,n,i,r,s]}set(e,t,n,i,r,s){const a=this.planes;return a[0].copy(e),a[1].copy(t),a[2].copy(n),a[3].copy(i),a[4].copy(r),a[5].copy(s),this}copy(e){const t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=2e3,n=!1){const i=this.planes,r=e.elements,s=r[0],a=r[1],o=r[2],l=r[3],c=r[4],h=r[5],u=r[6],d=r[7],p=r[8],f=r[9],m=r[10],g=r[11],_=r[12],v=r[13],x=r[14],y=r[15];if(i[0].setComponents(l-s,d-c,g-p,y-_).normalize(),i[1].setComponents(l+s,d+c,g+p,y+_).normalize(),i[2].setComponents(l+a,d+h,g+f,y+v).normalize(),i[3].setComponents(l-a,d-h,g-f,y-v).normalize(),n)i[4].setComponents(o,u,m,x).normalize(),i[5].setComponents(l-o,d-u,g-m,y-x).normalize();else if(i[4].setComponents(l-o,d-u,g-m,y-x).normalize(),t===zn)i[5].setComponents(l+o,d+u,g+m,y+x).normalize();else{if(t!==Hn)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);i[5].setComponents(o,u,m,x).normalize()}return this}intersectsObject(e){if(void 0!==e.boundingSphere)null===e.boundingSphere&&e.computeBoundingSphere(),Pa.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;null===t.boundingSphere&&t.computeBoundingSphere(),Pa.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Pa)}intersectsSprite(e){Pa.center.set(0,0,0);const t=Da.distanceTo(e.center);return Pa.radius=.7071067811865476+t,Pa.applyMatrix4(e.matrixWorld),this.intersectsSphere(Pa)}intersectsSphere(e){const t=this.planes,n=e.center,i=-e.radius;for(let r=0;r<6;r++){if(t[r].distanceToPoint(n)<i)return!1}return!0}intersectsBox(e){const t=this.planes;for(let n=0;n<6;n++){const i=t[n];if(Ba.x=i.normal.x>0?e.max.x:e.min.x,Ba.y=i.normal.y>0?e.max.y:e.min.y,Ba.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(Ba)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return(new this.constructor).copy(this)}}class Fa extends ns{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new $r(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}}const Ua=new hi,ka=new hi,Na=new or,Oa=new ar,za=new Ji,Ha=new hi,Va=new hi;class Ga extends Lr{constructor(e=new Ss,t=new Fa){super(),this.isLine=!0,this.type="Line",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}computeLineDistances(){const e=this.geometry;if(null===e.index){const t=e.attributes.position,n=[0];for(let e=1,i=t.count;e<i;e++)Ua.fromBufferAttribute(t,e-1),ka.fromBufferAttribute(t,e),n[e]=n[e-1],n[e]+=Ua.distanceTo(ka);e.setAttribute("lineDistance",new ps(n,1))}else qn("Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}raycast(e,t){const n=this.geometry,i=this.matrixWorld,r=e.params.Line.threshold,s=n.drawRange;if(null===n.boundingSphere&&n.computeBoundingSphere(),za.copy(n.boundingSphere),za.applyMatrix4(i),za.radius+=r,!1===e.ray.intersectsSphere(za))return;Na.copy(i).invert(),Oa.copy(e.ray).applyMatrix4(Na);const a=r/((this.scale.x+this.scale.y+this.scale.z)/3),o=a*a,l=this.isLineSegments?2:1,c=n.index,h=n.attributes.position;if(null!==c){const n=Math.max(0,s.start),i=Math.min(c.count,s.start+s.count);for(let r=n,s=i-1;r<s;r+=l){const n=c.getX(r),i=c.getX(r+1),s=Wa(this,e,Oa,o,n,i,r);s&&t.push(s)}if(this.isLineLoop){const r=c.getX(i-1),s=c.getX(n),a=Wa(this,e,Oa,o,r,s,i-1);a&&t.push(a)}}else{const n=Math.max(0,s.start),i=Math.min(h.count,s.start+s.count);for(let r=n,s=i-1;r<s;r+=l){const n=Wa(this,e,Oa,o,r,r+1,r);n&&t.push(n)}if(this.isLineLoop){const r=Wa(this,e,Oa,o,i-1,n,i-1);r&&t.push(r)}}}updateMorphTargets(){const e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){const n=e[t[0]];if(void 0!==n){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e<t;e++){const t=n[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}}function Wa(e,t,n,i,r,s,a){const o=e.geometry.attributes.position;Ua.fromBufferAttribute(o,r),ka.fromBufferAttribute(o,s);if(n.distanceSqToSegment(Ua,ka,Ha,Va)>i)return;Ha.applyMatrix4(e.matrixWorld);const l=t.ray.origin.distanceTo(Ha);return l<t.near||l>t.far?void 0:{distance:l,point:Va.clone().applyMatrix4(e.matrixWorld),index:a,face:null,faceIndex:null,barycoord:null,object:e}}const ja=new hi,Xa=new hi;class qa extends Ga{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const e=this.geometry;if(null===e.index){const t=e.attributes.position,n=[];for(let e=0,i=t.count;e<i;e+=2)ja.fromBufferAttribute(t,e),Xa.fromBufferAttribute(t,e+1),n[e]=0===e?0:n[e-1],n[e+1]=n[e]+ja.distanceTo(Xa);e.setAttribute("lineDistance",new ps(n,1))}else qn("LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}}class Qa extends Ga{constructor(e,t){super(e,t),this.isLineLoop=!0,this.type="LineLoop"}}class Ka extends ns{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new $r(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.size=e.size,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}const Ya=new or,Za=new ar,Ja=new Ji,$a=new hi;class eo extends Lr{constructor(e=new Ss,t=new Ka){super(),this.isPoints=!0,this.type="Points",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}raycast(e,t){const n=this.geometry,i=this.matrixWorld,r=e.params.Points.threshold,s=n.drawRange;if(null===n.boundingSphere&&n.computeBoundingSphere(),Ja.copy(n.boundingSphere),Ja.applyMatrix4(i),Ja.radius+=r,!1===e.ray.intersectsSphere(Ja))return;Ya.copy(i).invert(),Za.copy(e.ray).applyMatrix4(Ya);const a=r/((this.scale.x+this.scale.y+this.scale.z)/3),o=a*a,l=n.index,c=n.attributes.position;if(null!==l){for(let n=Math.max(0,s.start),r=Math.min(l.count,s.start+s.count);n<r;n++){const r=l.getX(n);$a.fromBufferAttribute(c,r),to($a,r,o,i,e,t,this)}}else{for(let n=Math.max(0,s.start),r=Math.min(c.count,s.start+s.count);n<r;n++)$a.fromBufferAttribute(c,n),to($a,n,o,i,e,t,this)}}updateMorphTargets(){const e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){const n=e[t[0]];if(void 0!==n){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e<t;e++){const t=n[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}}function to(e,t,n,i,r,s,a){const o=Za.distanceSqToPoint(e);if(o<n){const n=new hi;Za.closestPointToPoint(e,n),n.applyMatrix4(i);const l=r.ray.origin.distanceTo(n);if(l<r.near||l>r.far)return;s.push({distance:l,distanceToRay:Math.sqrt(o),point:n,index:t,face:null,faceIndex:null,barycoord:null,object:a})}}class no extends Ci{constructor(e,t,n=1014,i,r,s,a=1003,o=1003,l,c=1026,h=1){if(c!==Mt&&c!==wt)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");super({width:e,height:t,depth:h},i,r,s,a,o,c,n,l),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new Mi(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return null!==this.compareFunction&&(t.compareFunction=this.compareFunction),t}}class io extends no{constructor(e,t=1014,n=301,i,r,s=1003,a=1003,o,l=1026){const c={width:e,height:e,depth:1},h=[c,c,c,c,c,c];super(e,e,t,n,i,r,s,a,o,l),this.image=h,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}}class ro extends Ci{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}}class so extends Ss{constructor(e=1,t=1,n=1,i=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:n,heightSegments:i};const r=e/2,s=t/2,a=Math.floor(n),o=Math.floor(i),l=a+1,c=o+1,h=e/a,u=t/o,d=[],p=[],f=[],m=[];for(let g=0;g<c;g++){const e=g*u-s;for(let t=0;t<l;t++){const n=t*h-r;p.push(n,-e,0),f.push(0,0,1),m.push(t/a),m.push(1-g/o)}}for(let g=0;g<o;g++)for(let e=0;e<a;e++){const t=e+l*g,n=e+l*(g+1),i=e+1+l*(g+1),r=e+1+l*g;d.push(t,n,r),d.push(n,i,r)}this.setIndex(d),this.setAttribute("position",new ps(p,3)),this.setAttribute("normal",new ps(f,3)),this.setAttribute("uv",new ps(m,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new so(e.width,e.height,e.widthSegments,e.heightSegments)}}class ao extends zs{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}}class oo extends ns{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new $r(16777215),this.roughness=1,this.metalness=0,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new $r(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new li(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new _r,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={STANDARD:""},this.color.copy(e.color),this.roughness=e.roughness,this.metalness=e.metalness,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.roughnessMap=e.roughnessMap,this.metalnessMap=e.metalnessMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.envMapIntensity=e.envMapIntensity,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class lo extends oo{constructor(e){super(),this.isMeshPhysicalMaterial=!0,this.defines={STANDARD:"",PHYSICAL:""},this.type="MeshPhysicalMaterial",this.anisotropyRotation=0,this.anisotropyMap=null,this.clearcoatMap=null,this.clearcoatRoughness=0,this.clearcoatRoughnessMap=null,this.clearcoatNormalScale=new li(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return ni(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(e){this.ior=(1+.4*e)/(1-.4*e)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new $r(0),this.sheenColorMap=null,this.sheenRoughness=1,this.sheenRoughnessMap=null,this.transmissionMap=null,this.thickness=0,this.thicknessMap=null,this.attenuationDistance=1/0,this.attenuationColor=new $r(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new $r(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(e)}get anisotropy(){return this._anisotropy}set anisotropy(e){this._anisotropy>0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}}class co extends ns{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=3200,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class ho extends ns{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}function uo(e,t){return e&&e.constructor!==t?"number"==typeof t.BYTES_PER_ELEMENT?new t(e):Array.prototype.slice.call(e):e}function po(e){const t=e.length,n=new Array(t);for(let i=0;i!==t;++i)n[i]=i;return n.sort(function(t,n){return e[t]-e[n]}),n}function fo(e,t,n){const i=e.length,r=new e.constructor(i);for(let s=0,a=0;a!==i;++s){const i=n[s]*t;for(let n=0;n!==t;++n)r[a++]=e[i+n]}return r}function mo(e,t,n,i){let r=1,s=e[0];for(;void 0!==s&&void 0===s[i];)s=e[r++];if(void 0===s)return;let a=s[i];if(void 0!==a)if(Array.isArray(a))do{a=s[i],void 0!==a&&(t.push(s.time),n.push(...a)),s=e[r++]}while(void 0!==s);else if(void 0!==a.toArray)do{a=s[i],void 0!==a&&(t.push(s.time),a.toArray(n,n.length)),s=e[r++]}while(void 0!==s);else do{a=s[i],void 0!==a&&(t.push(s.time),n.push(a)),s=e[r++]}while(void 0!==s)}class go{constructor(e,t,n,i){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=void 0!==i?i:new t.constructor(n),this.sampleValues=t,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(e){const t=this.parameterPositions;let n=this._cachedIndex,i=t[n],r=t[n-1];e:{t:{let s;n:{i:if(!(e<i)){for(let s=n+2;;){if(void 0===i){if(e<r)break i;return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}if(n===s)break;if(r=i,i=t[++n],e<i)break t}s=t.length;break n}if(!(e>=r)){const a=t[1];e<a&&(n=2,r=a);for(let s=n-2;;){if(void 0===r)return this._cachedIndex=0,this.copySampleValue_(0);if(n===s)break;if(i=r,r=t[--n-1],e>=r)break t}s=n,n=0;break n}break e}for(;n<s;){const i=n+s>>>1;e<t[i]?s=i:n=i+1}if(i=t[n],r=t[n-1],void 0===r)return this._cachedIndex=0,this.copySampleValue_(0);if(void 0===i)return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}this._cachedIndex=n,this.intervalChanged_(n,r,i)}return this.interpolate_(n,r,e,i)}getSettings_(){return this.settings||this.DefaultSettings_}copySampleValue_(e){const t=this.resultBuffer,n=this.sampleValues,i=this.valueSize,r=e*i;for(let s=0;s!==i;++s)t[s]=n[r+s];return t}interpolate_(){throw new Error("call to abstract method")}intervalChanged_(){}}class _o extends go{constructor(e,t,n,i){super(e,t,n,i),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0,this.DefaultSettings_={endingStart:xn,endingEnd:xn}}intervalChanged_(e,t,n){const i=this.parameterPositions;let r=e-2,s=e+1,a=i[r],o=i[s];if(void 0===a)switch(this.getSettings_().endingStart){case yn:r=e,a=2*t-n;break;case Sn:r=i.length-2,a=t+i[r]-i[r+1];break;default:r=e,a=n}if(void 0===o)switch(this.getSettings_().endingEnd){case yn:s=e,o=2*n-t;break;case Sn:s=1,o=n+i[1]-i[0];break;default:s=e-1,o=t}const l=.5*(n-t),c=this.valueSize;this._weightPrev=l/(t-a),this._weightNext=l/(o-n),this._offsetPrev=r*c,this._offsetNext=s*c}interpolate_(e,t,n,i){const r=this.resultBuffer,s=this.sampleValues,a=this.valueSize,o=e*a,l=o-a,c=this._offsetPrev,h=this._offsetNext,u=this._weightPrev,d=this._weightNext,p=(n-t)/(i-t),f=p*p,m=f*p,g=-u*m+2*u*f-u*p,_=(1+u)*m+(-1.5-2*u)*f+(-.5+u)*p+1,v=(-1-d)*m+(1.5+d)*f+.5*p,x=d*m-d*f;for(let y=0;y!==a;++y)r[y]=g*s[c+y]+_*s[l+y]+v*s[o+y]+x*s[h+y];return r}}class vo extends go{constructor(e,t,n,i){super(e,t,n,i)}interpolate_(e,t,n,i){const r=this.resultBuffer,s=this.sampleValues,a=this.valueSize,o=e*a,l=o-a,c=(n-t)/(i-t),h=1-c;for(let u=0;u!==a;++u)r[u]=s[l+u]*h+s[o+u]*c;return r}}class xo extends go{constructor(e,t,n,i){super(e,t,n,i)}interpolate_(e){return this.copySampleValue_(e-1)}}class yo{constructor(e,t,n,i){if(void 0===e)throw new Error("THREE.KeyframeTrack: track name is undefined");if(void 0===t||0===t.length)throw new Error("THREE.KeyframeTrack: no keyframes in track named "+e);this.name=e,this.times=uo(t,this.TimeBufferType),this.values=uo(n,this.ValueBufferType),this.setInterpolation(i||this.DefaultInterpolation)}static toJSON(e){const t=e.constructor;let n;if(t.toJSON!==this.toJSON)n=t.toJSON(e);else{n={name:e.name,times:uo(e.times,Array),values:uo(e.values,Array)};const t=e.getInterpolation();t!==e.DefaultInterpolation&&(n.interpolation=t)}return n.type=e.ValueTypeName,n}InterpolantFactoryMethodDiscrete(e){return new xo(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodLinear(e){return new vo(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodSmooth(e){return new _o(this.times,this.values,this.getValueSize(),e)}setInterpolation(e){let t;switch(e){case gn:t=this.InterpolantFactoryMethodDiscrete;break;case _n:t=this.InterpolantFactoryMethodLinear;break;case vn:t=this.InterpolantFactoryMethodSmooth}if(void 0===t){const t="unsupported interpolation for "+this.ValueTypeName+" keyframe track named "+this.name;if(void 0===this.createInterpolant){if(e===this.DefaultInterpolation)throw new Error(t);this.setInterpolation(this.DefaultInterpolation)}return qn("KeyframeTrack:",t),this}return this.createInterpolant=t,this}getInterpolation(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return gn;case this.InterpolantFactoryMethodLinear:return _n;case this.InterpolantFactoryMethodSmooth:return vn}}getValueSize(){return this.values.length/this.times.length}shift(e){if(0!==e){const t=this.times;for(let n=0,i=t.length;n!==i;++n)t[n]+=e}return this}scale(e){if(1!==e){const t=this.times;for(let n=0,i=t.length;n!==i;++n)t[n]*=e}return this}trim(e,t){const n=this.times,i=n.length;let r=0,s=i-1;for(;r!==i&&n[r]<e;)++r;for(;-1!==s&&n[s]>t;)--s;if(++s,0!==r||s!==i){r>=s&&(s=Math.max(s,1),r=s-1);const e=this.getValueSize();this.times=n.slice(r,s),this.values=this.values.slice(r*e,s*e)}return this}validate(){let e=!0;const t=this.getValueSize();t-Math.floor(t)!==0&&(Qn("KeyframeTrack: Invalid value size in track.",this),e=!1);const n=this.times,i=this.values,r=n.length;0===r&&(Qn("KeyframeTrack: Track is empty.",this),e=!1);let s=null;for(let o=0;o!==r;o++){const t=n[o];if("number"==typeof t&&isNaN(t)){Qn("KeyframeTrack: Time is not a valid number.",this,o,t),e=!1;break}if(null!==s&&s>t){Qn("KeyframeTrack: Out of order keys.",this,o,t,s),e=!1;break}s=t}if(void 0!==i&&(a=i,ArrayBuffer.isView(a)&&!(a instanceof DataView)))for(let o=0,l=i.length;o!==l;++o){const t=i[o];if(isNaN(t)){Qn("KeyframeTrack: Value is not a valid number.",this,o,t),e=!1;break}}var a;return e}optimize(){const e=this.times.slice(),t=this.values.slice(),n=this.getValueSize(),i=this.getInterpolation()===vn,r=e.length-1;let s=1;for(let a=1;a<r;++a){let r=!1;const o=e[a];if(o!==e[a+1]&&(1!==a||o!==e[0]))if(i)r=!0;else{const e=a*n,i=e-n,s=e+n;for(let a=0;a!==n;++a){const n=t[e+a];if(n!==t[i+a]||n!==t[s+a]){r=!0;break}}}if(r){if(a!==s){e[s]=e[a];const i=a*n,r=s*n;for(let e=0;e!==n;++e)t[r+e]=t[i+e]}++s}}if(r>0){e[s]=e[r];for(let e=r*n,i=s*n,a=0;a!==n;++a)t[i+a]=t[e+a];++s}return s!==e.length?(this.times=e.slice(0,s),this.values=t.slice(0,s*n)):(this.times=e,this.values=t),this}clone(){const e=this.times.slice(),t=this.values.slice(),n=new(0,this.constructor)(this.name,e,t);return n.createInterpolant=this.createInterpolant,n}}yo.prototype.ValueTypeName="",yo.prototype.TimeBufferType=Float32Array,yo.prototype.ValueBufferType=Float32Array,yo.prototype.DefaultInterpolation=_n;class So extends yo{constructor(e,t,n){super(e,t,n)}}So.prototype.ValueTypeName="bool",So.prototype.ValueBufferType=Array,So.prototype.DefaultInterpolation=gn,So.prototype.InterpolantFactoryMethodLinear=void 0,So.prototype.InterpolantFactoryMethodSmooth=void 0;class Ao extends yo{constructor(e,t,n,i){super(e,t,n,i)}}Ao.prototype.ValueTypeName="color";class bo extends yo{constructor(e,t,n,i){super(e,t,n,i)}}bo.prototype.ValueTypeName="number";class Mo extends go{constructor(e,t,n,i){super(e,t,n,i)}interpolate_(e,t,n,i){const r=this.resultBuffer,s=this.sampleValues,a=this.valueSize,o=(n-t)/(i-t);let l=e*a;for(let c=l+a;l!==c;l+=4)ci.slerpFlat(r,0,s,l-a,s,l,o);return r}}class wo extends yo{constructor(e,t,n,i){super(e,t,n,i)}InterpolantFactoryMethodLinear(e){return new Mo(this.times,this.values,this.getValueSize(),e)}}wo.prototype.ValueTypeName="quaternion",wo.prototype.InterpolantFactoryMethodSmooth=void 0;class To extends yo{constructor(e,t,n){super(e,t,n)}}To.prototype.ValueTypeName="string",To.prototype.ValueBufferType=Array,To.prototype.DefaultInterpolation=gn,To.prototype.InterpolantFactoryMethodLinear=void 0,To.prototype.InterpolantFactoryMethodSmooth=void 0;class Eo extends yo{constructor(e,t,n,i){super(e,t,n,i)}}Eo.prototype.ValueTypeName="vector";class Co{constructor(e="",t=-1,n=[],i=2500){this.name=e,this.tracks=n,this.duration=t,this.blendMode=i,this.uuid=ti(),this.userData={},this.duration<0&&this.resetDuration()}static parse(e){const t=[],n=e.tracks,i=1/(e.fps||1);for(let s=0,a=n.length;s!==a;++s)t.push(Ro(n[s]).scale(i));const r=new this(e.name,e.duration,t,e.blendMode);return r.uuid=e.uuid,r.userData=JSON.parse(e.userData||"{}"),r}static toJSON(e){const t=[],n=e.tracks,i={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode,userData:JSON.stringify(e.userData)};for(let r=0,s=n.length;r!==s;++r)t.push(yo.toJSON(n[r]));return i}static CreateFromMorphTargetSequence(e,t,n,i){const r=t.length,s=[];for(let a=0;a<r;a++){let e=[],o=[];e.push((a+r-1)%r,a,(a+1)%r),o.push(0,1,0);const l=po(e);e=fo(e,1,l),o=fo(o,1,l),i||0!==e[0]||(e.push(r),o.push(o[0])),s.push(new bo(".morphTargetInfluences["+t[a].name+"]",e,o).scale(1/n))}return new this(e,-1,s)}static findByName(e,t){let n=e;if(!Array.isArray(e)){const t=e;n=t.geometry&&t.geometry.animations||t.animations}for(let i=0;i<n.length;i++)if(n[i].name===t)return n[i];return null}static CreateClipsFromMorphTargetSequences(e,t,n){const i={},r=/^([\w-]*?)([\d]+)$/;for(let a=0,o=e.length;a<o;a++){const t=e[a],n=t.name.match(r);if(n&&n.length>1){const e=n[1];let r=i[e];r||(i[e]=r=[]),r.push(t)}}const s=[];for(const a in i)s.push(this.CreateFromMorphTargetSequence(a,i[a],t,n));return s}static parseAnimation(e,t){if(qn("AnimationClip: parseAnimation() is deprecated and will be removed with r185"),!e)return Qn("AnimationClip: No animation in JSONLoader data."),null;const n=function(e,t,n,i,r){if(0!==n.length){const s=[],a=[];mo(n,s,a,i),0!==s.length&&r.push(new e(t,s,a))}},i=[],r=e.name||"default",s=e.fps||30,a=e.blendMode;let o=e.length||-1;const l=e.hierarchy||[];for(let c=0;c<l.length;c++){const e=l[c].keys;if(e&&0!==e.length)if(e[0].morphTargets){const t={};let n;for(n=0;n<e.length;n++)if(e[n].morphTargets)for(let i=0;i<e[n].morphTargets.length;i++)t[e[n].morphTargets[i]]=-1;for(const r in t){const t=[],s=[];for(let i=0;i!==e[n].morphTargets.length;++i){const i=e[n];t.push(i.time),s.push(i.morphTarget===r?1:0)}i.push(new bo(".morphTargetInfluence["+r+"]",t,s))}o=t.length*s}else{const r=".bones["+t[c].name+"]";n(Eo,r+".position",e,"pos",i),n(wo,r+".quaternion",e,"rot",i),n(Eo,r+".scale",e,"scl",i)}}if(0===i.length)return null;return new this(r,o,i,a)}resetDuration(){let e=0;for(let t=0,n=this.tracks.length;t!==n;++t){const n=this.tracks[t];e=Math.max(e,n.times[n.times.length-1])}return this.duration=e,this}trim(){for(let e=0;e<this.tracks.length;e++)this.tracks[e].trim(0,this.duration);return this}validate(){let e=!0;for(let t=0;t<this.tracks.length;t++)e=e&&this.tracks[t].validate();return e}optimize(){for(let e=0;e<this.tracks.length;e++)this.tracks[e].optimize();return this}clone(){const e=[];for(let n=0;n<this.tracks.length;n++)e.push(this.tracks[n].clone());const t=new this.constructor(this.name,this.duration,e,this.blendMode);return t.userData=JSON.parse(JSON.stringify(this.userData)),t}toJSON(){return this.constructor.toJSON(this)}}function Ro(e){if(void 0===e.type)throw new Error("THREE.KeyframeTrack: track type undefined, can not parse");const t=function(e){switch(e.toLowerCase()){case"scalar":case"double":case"float":case"number":case"integer":return bo;case"vector":case"vector2":case"vector3":case"vector4":return Eo;case"color":return Ao;case"quaternion":return wo;case"bool":case"boolean":return So;case"string":return To}throw new Error("THREE.KeyframeTrack: Unsupported typeName: "+e)}(e.type);if(void 0===e.times){const t=[],n=[];mo(e.keys,t,n,"value"),e.times=t,e.values=n}return void 0!==t.parse?t.parse(e):new t(e.name,e.times,e.values,e.interpolation)}const Io={enabled:!1,files:{},add:function(e,t){!1!==this.enabled&&(this.files[e]=t)},get:function(e){if(!1!==this.enabled)return this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}};class Po{constructor(e,t,n){const i=this;let r,s=!1,a=0,o=0;const l=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=n,this._abortController=null,this.itemStart=function(e){o++,!1===s&&void 0!==i.onStart&&i.onStart(e,a,o),s=!0},this.itemEnd=function(e){a++,void 0!==i.onProgress&&i.onProgress(e,a,o),a===o&&(s=!1,void 0!==i.onLoad&&i.onLoad())},this.itemError=function(e){void 0!==i.onError&&i.onError(e)},this.resolveURL=function(e){return r?r(e):e},this.setURLModifier=function(e){return r=e,this},this.addHandler=function(e,t){return l.push(e,t),this},this.removeHandler=function(e){const t=l.indexOf(e);return-1!==t&&l.splice(t,2),this},this.getHandler=function(e){for(let t=0,n=l.length;t<n;t+=2){const n=l[t],i=l[t+1];if(n.global&&(n.lastIndex=0),n.test(e))return i}return null},this.abort=function(){return this.abortController.abort(),this._abortController=null,this}}get abortController(){return this._abortController||(this._abortController=new AbortController),this._abortController}}const Do=new Po;class Bo{constructor(e){this.manager=void 0!==e?e:Do,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={}}load(){}loadAsync(e,t){const n=this;return new Promise(function(i,r){n.load(e,i,t,r)})}parse(){}setCrossOrigin(e){return this.crossOrigin=e,this}setWithCredentials(e){return this.withCredentials=e,this}setPath(e){return this.path=e,this}setResourcePath(e){return this.resourcePath=e,this}setRequestHeader(e){return this.requestHeader=e,this}abort(){return this}}Bo.DEFAULT_MATERIAL_NAME="__DEFAULT";const Lo={};class Fo extends Error{constructor(e,t){super(e),this.response=t}}class Uo extends Bo{constructor(e){super(e),this.mimeType="",this.responseType="",this._abortController=new AbortController}load(e,t,n,i){void 0===e&&(e=""),void 0!==this.path&&(e=this.path+e),e=this.manager.resolveURL(e);const r=Io.get(`file:${e}`);if(void 0!==r)return this.manager.itemStart(e),setTimeout(()=>{t&&t(r),this.manager.itemEnd(e)},0),r;if(void 0!==Lo[e])return void Lo[e].push({onLoad:t,onProgress:n,onError:i});Lo[e]=[],Lo[e].push({onLoad:t,onProgress:n,onError:i});const s=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin",signal:"function"==typeof AbortSignal.any?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal}),a=this.mimeType,o=this.responseType;fetch(s).then(t=>{if(200===t.status||0===t.status){if(0===t.status&&qn("FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===t.body||void 0===t.body.getReader)return t;const n=Lo[e],i=t.body.getReader(),r=t.headers.get("X-File-Size")||t.headers.get("Content-Length"),s=r?parseInt(r):0,a=0!==s;let o=0;const l=new ReadableStream({start(e){!function t(){i.read().then(({done:i,value:r})=>{if(i)e.close();else{o+=r.byteLength;const i=new ProgressEvent("progress",{lengthComputable:a,loaded:o,total:s});for(let e=0,t=n.length;e<t;e++){const t=n[e];t.onProgress&&t.onProgress(i)}e.enqueue(r),t()}},t=>{e.error(t)})}()}});return new Response(l)}throw new Fo(`fetch for "${t.url}" responded with ${t.status}: ${t.statusText}`,t)}).then(e=>{switch(o){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"document":return e.text().then(e=>(new DOMParser).parseFromString(e,a));case"json":return e.json();default:if(""===a)return e.text();{const t=/charset="?([^;"\s]*)"?/i.exec(a),n=t&&t[1]?t[1].toLowerCase():void 0,i=new TextDecoder(n);return e.arrayBuffer().then(e=>i.decode(e))}}}).then(t=>{Io.add(`file:${e}`,t);const n=Lo[e];delete Lo[e];for(let e=0,i=n.length;e<i;e++){const i=n[e];i.onLoad&&i.onLoad(t)}}).catch(t=>{const n=Lo[e];if(void 0===n)throw this.manager.itemError(e),t;delete Lo[e];for(let e=0,i=n.length;e<i;e++){const i=n[e];i.onError&&i.onError(t)}this.manager.itemError(e)}).finally(()=>{this.manager.itemEnd(e)}),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}const ko=new WeakMap;class No extends Bo{constructor(e){super(e)}load(e,t,n,i){void 0!==this.path&&(e=this.path+e),e=this.manager.resolveURL(e);const r=this,s=Io.get(`image:${e}`);if(void 0!==s){if(!0===s.complete)r.manager.itemStart(e),setTimeout(function(){t&&t(s),r.manager.itemEnd(e)},0);else{let e=ko.get(s);void 0===e&&(e=[],ko.set(s,e)),e.push({onLoad:t,onError:i})}return s}const a=Gn("img");function o(){c(),t&&t(this);const n=ko.get(this)||[];for(let e=0;e<n.length;e++){const t=n[e];t.onLoad&&t.onLoad(this)}ko.delete(this),r.manager.itemEnd(e)}function l(t){c(),i&&i(t),Io.remove(`image:${e}`);const n=ko.get(this)||[];for(let e=0;e<n.length;e++){const i=n[e];i.onError&&i.onError(t)}ko.delete(this),r.manager.itemError(e),r.manager.itemEnd(e)}function c(){a.removeEventListener("load",o,!1),a.removeEventListener("error",l,!1)}return a.addEventListener("load",o,!1),a.addEventListener("error",l,!1),"data:"!==e.slice(0,5)&&void 0!==this.crossOrigin&&(a.crossOrigin=this.crossOrigin),Io.add(`image:${e}`,a),r.manager.itemStart(e),a.src=e,a}}class Oo extends Bo{constructor(e){super(e)}load(e,t,n,i){const r=new Ci,s=new No(this.manager);return s.setCrossOrigin(this.crossOrigin),s.setPath(this.path),s.load(e,function(e){r.image=e,r.needsUpdate=!0,void 0!==t&&t(r)},n,i),r}}class zo extends Lr{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new $r(e),this.intensity=t}dispose(){this.dispatchEvent({type:"dispose"})}copy(e,t){return super.copy(e,t),this.color.copy(e.color),this.intensity=e.intensity,this}toJSON(e){const t=super.toJSON(e);return t.object.color=this.color.getHex(),t.object.intensity=this.intensity,t}}const Ho=new or,Vo=new hi,Go=new hi;class Wo{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new li(512,512),this.mapType=ht,this.map=null,this.mapPass=null,this.matrix=new or,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new La,this._frameExtents=new li(1,1),this._viewportCount=1,this._viewports=[new Ri(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){const t=this.camera,n=this.matrix;Vo.setFromMatrixPosition(e.matrixWorld),t.position.copy(Vo),Go.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(Go),t.updateMatrixWorld(),Ho.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(Ho,t.coordinateSystem,t.reversedDepth),t.reversedDepth?n.set(.5,0,0,.5,0,.5,0,.5,0,0,1,0,0,0,0,1):n.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),n.multiply(Ho)}getViewport(e){return this._viewports[e]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(e){return this.camera=e.camera.clone(),this.intensity=e.intensity,this.bias=e.bias,this.radius=e.radius,this.autoUpdate=e.autoUpdate,this.needsUpdate=e.needsUpdate,this.normalBias=e.normalBias,this.blurSamples=e.blurSamples,this.mapSize.copy(e.mapSize),this}clone(){return(new this.constructor).copy(this)}toJSON(){const e={};return 1!==this.intensity&&(e.intensity=this.intensity),0!==this.bias&&(e.bias=this.bias),0!==this.normalBias&&(e.normalBias=this.normalBias),1!==this.radius&&(e.radius=this.radius),512===this.mapSize.x&&512===this.mapSize.y||(e.mapSize=this.mapSize.toArray()),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}}class jo extends Wo{constructor(){super(new js(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1,this.aspect=1}updateMatrices(e){const t=this.camera,n=2*ei*e.angle*this.focus,i=this.mapSize.width/this.mapSize.height*this.aspect,r=e.distance||t.far;n===t.fov&&i===t.aspect&&r===t.far||(t.fov=n,t.aspect=i,t.far=r,t.updateProjectionMatrix()),super.updateMatrices(e)}copy(e){return super.copy(e),this.focus=e.focus,this}}class Xo extends zo{constructor(e,t,n=0,i=Math.PI/3,r=0,s=2){super(e,t),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(Lr.DEFAULT_UP),this.updateMatrix(),this.target=new Lr,this.distance=n,this.angle=i,this.penumbra=r,this.decay=s,this.map=null,this.shadow=new jo}get power(){return this.intensity*Math.PI}set power(e){this.intensity=e/Math.PI}dispose(){super.dispose(),this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.angle=e.angle,this.penumbra=e.penumbra,this.decay=e.decay,this.target=e.target.clone(),this.map=e.map,this.shadow=e.shadow.clone(),this}toJSON(e){const t=super.toJSON(e);return t.object.distance=this.distance,t.object.angle=this.angle,t.object.decay=this.decay,t.object.penumbra=this.penumbra,t.object.target=this.target.uuid,this.map&&this.map.isTexture&&(t.object.map=this.map.toJSON(e).uuid),t.object.shadow=this.shadow.toJSON(),t}}class qo extends Wo{constructor(){super(new js(90,1,.5,500)),this.isPointLightShadow=!0}}class Qo extends zo{constructor(e,t,n=0,i=2){super(e,t),this.isPointLight=!0,this.type="PointLight",this.distance=n,this.decay=i,this.shadow=new qo}get power(){return 4*this.intensity*Math.PI}set power(e){this.intensity=e/(4*Math.PI)}dispose(){super.dispose(),this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.decay=e.decay,this.shadow=e.shadow.clone(),this}toJSON(e){const t=super.toJSON(e);return t.object.distance=this.distance,t.object.decay=this.decay,t.object.shadow=this.shadow.toJSON(),t}}class Ko extends Hs{constructor(e=-1,t=1,n=1,i=-1,r=.1,s=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=n,this.bottom=i,this.near=r,this.far=s,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=null===e.view?null:Object.assign({},e.view),this}setViewOffset(e,t,n,i,r,s){null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=i,this.view.width=r,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,i=(this.top+this.bottom)/2;let r=n-e,s=n+e,a=i+t,o=i-t;if(null!==this.view&&this.view.enabled){const e=(this.right-this.left)/this.view.fullWidth/this.zoom,t=(this.top-this.bottom)/this.view.fullHeight/this.zoom;r+=e*this.view.offsetX,s=r+e*this.view.width,a-=t*this.view.offsetY,o=a-t*this.view.height}this.projectionMatrix.makeOrthographic(r,s,a,o,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,null!==this.view&&(t.object.view=Object.assign({},this.view)),t}}class Yo extends Wo{constructor(){super(new Ko(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class Zo extends zo{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(Lr.DEFAULT_UP),this.updateMatrix(),this.target=new Lr,this.shadow=new Yo}dispose(){super.dispose(),this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}toJSON(e){const t=super.toJSON(e);return t.object.shadow=this.shadow.toJSON(),t.object.target=this.target.uuid,t}}class Jo{static extractUrlBase(e){const t=e.lastIndexOf("/");return-1===t?"./":e.slice(0,t+1)}static resolveURL(e,t){return"string"!=typeof e||""===e?"":(/^https?:\/\//i.test(t)&&/^\//.test(e)&&(t=t.replace(/(^https?:\/\/[^\/]+).*/i,"$1")),/^(https?:)?\/\//i.test(e)||/^data:.*,.*$/i.test(e)||/^blob:.*$/i.test(e)?e:t+e)}}class $o extends Ss{constructor(){super(),this.isInstancedBufferGeometry=!0,this.type="InstancedBufferGeometry",this.instanceCount=1/0}copy(e){return super.copy(e),this.instanceCount=e.instanceCount,this}toJSON(){const e=super.toJSON();return e.instanceCount=this.instanceCount,e.isInstancedBufferGeometry=!0,e}}const el=new WeakMap;class tl extends Bo{constructor(e){super(e),this.isImageBitmapLoader=!0,"undefined"==typeof createImageBitmap&&qn("ImageBitmapLoader: createImageBitmap() not supported."),"undefined"==typeof fetch&&qn("ImageBitmapLoader: fetch() not supported."),this.options={premultiplyAlpha:"none"},this._abortController=new AbortController}setOptions(e){return this.options=e,this}load(e,t,n,i){void 0===e&&(e=""),void 0!==this.path&&(e=this.path+e),e=this.manager.resolveURL(e);const r=this,s=Io.get(`image-bitmap:${e}`);if(void 0!==s)return r.manager.itemStart(e),s.then?void s.then(n=>{if(!0!==el.has(s))return t&&t(n),r.manager.itemEnd(e),n;i&&i(el.get(s)),r.manager.itemError(e),r.manager.itemEnd(e)}):(setTimeout(function(){t&&t(s),r.manager.itemEnd(e)},0),s);const a={};a.credentials="anonymous"===this.crossOrigin?"same-origin":"include",a.headers=this.requestHeader,a.signal="function"==typeof AbortSignal.any?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal;const o=fetch(e,a).then(function(e){return e.blob()}).then(function(e){return createImageBitmap(e,Object.assign(r.options,{colorSpaceConversion:"none"}))}).then(function(n){return Io.add(`image-bitmap:${e}`,n),t&&t(n),r.manager.itemEnd(e),n}).catch(function(t){i&&i(t),el.set(o,t),Io.remove(`image-bitmap:${e}`),r.manager.itemError(e),r.manager.itemEnd(e)});Io.add(`image-bitmap:${e}`,o),r.manager.itemStart(e)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}class nl extends js{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class il{constructor(e=!0){this.autoStart=e,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=performance.now(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let e=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){const t=performance.now();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}}class rl{constructor(e,t,n){let i,r,s;switch(this.binding=e,this.valueSize=n,t){case"quaternion":i=this._slerp,r=this._slerpAdditive,s=this._setAdditiveIdentityQuaternion,this.buffer=new Float64Array(6*n),this._workIndex=5;break;case"string":case"bool":i=this._select,r=this._select,s=this._setAdditiveIdentityOther,this.buffer=new Array(5*n);break;default:i=this._lerp,r=this._lerpAdditive,s=this._setAdditiveIdentityNumeric,this.buffer=new Float64Array(5*n)}this._mixBufferRegion=i,this._mixBufferRegionAdditive=r,this._setIdentity=s,this._origIndex=3,this._addIndex=4,this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,this.useCount=0,this.referenceCount=0}accumulate(e,t){const n=this.buffer,i=this.valueSize,r=e*i+i;let s=this.cumulativeWeight;if(0===s){for(let e=0;e!==i;++e)n[r+e]=n[e];s=t}else{s+=t;const e=t/s;this._mixBufferRegion(n,r,0,e,i)}this.cumulativeWeight=s}accumulateAdditive(e){const t=this.buffer,n=this.valueSize,i=n*this._addIndex;0===this.cumulativeWeightAdditive&&this._setIdentity(),this._mixBufferRegionAdditive(t,i,0,e,n),this.cumulativeWeightAdditive+=e}apply(e){const t=this.valueSize,n=this.buffer,i=e*t+t,r=this.cumulativeWeight,s=this.cumulativeWeightAdditive,a=this.binding;if(this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,r<1){const e=t*this._origIndex;this._mixBufferRegion(n,i,e,1-r,t)}s>0&&this._mixBufferRegionAdditive(n,i,this._addIndex*t,1,t);for(let o=t,l=t+t;o!==l;++o)if(n[o]!==n[o+t]){a.setValue(n,i);break}}saveOriginalState(){const e=this.binding,t=this.buffer,n=this.valueSize,i=n*this._origIndex;e.getValue(t,i);for(let r=n,s=i;r!==s;++r)t[r]=t[i+r%n];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){const e=3*this.valueSize;this.binding.setValue(this.buffer,e)}_setAdditiveIdentityNumeric(){const e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let n=e;n<t;n++)this.buffer[n]=0}_setAdditiveIdentityQuaternion(){this._setAdditiveIdentityNumeric(),this.buffer[this._addIndex*this.valueSize+3]=1}_setAdditiveIdentityOther(){const e=this._origIndex*this.valueSize,t=this._addIndex*this.valueSize;for(let n=0;n<this.valueSize;n++)this.buffer[t+n]=this.buffer[e+n]}_select(e,t,n,i,r){if(i>=.5)for(let s=0;s!==r;++s)e[t+s]=e[n+s]}_slerp(e,t,n,i){ci.slerpFlat(e,t,e,t,e,n,i)}_slerpAdditive(e,t,n,i,r){const s=this._workIndex*r;ci.multiplyQuaternionsFlat(e,s,e,t,e,n),ci.slerpFlat(e,t,e,t,e,s,i)}_lerp(e,t,n,i,r){const s=1-i;for(let a=0;a!==r;++a){const r=t+a;e[r]=e[r]*s+e[n+a]*i}}_lerpAdditive(e,t,n,i,r){for(let s=0;s!==r;++s){const r=t+s;e[r]=e[r]+e[n+s]*i}}}const sl="\\[\\]\\.:\\/",al=new RegExp("["+sl+"]","g"),ol="[^"+sl+"]",ll="[^"+sl.replace("\\.","")+"]",cl=new RegExp("^"+/((?:WC+[\/:])*)/.source.replace("WC",ol)+/(WCOD+)?/.source.replace("WCOD",ll)+/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",ol)+/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",ol)+"$"),hl=["material","materials","bones","map"];class ul{constructor(e,t,n){this.path=t,this.parsedPath=n||ul.parseTrackName(t),this.node=ul.findNode(e,this.parsedPath.nodeName),this.rootNode=e,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(e,t,n){return e&&e.isAnimationObjectGroup?new ul.Composite(e,t,n):new ul(e,t,n)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(al,"")}static parseTrackName(e){const t=cl.exec(e);if(null===t)throw new Error("PropertyBinding: Cannot parse trackName: "+e);const n={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},i=n.nodeName&&n.nodeName.lastIndexOf(".");if(void 0!==i&&-1!==i){const e=n.nodeName.substring(i+1);-1!==hl.indexOf(e)&&(n.nodeName=n.nodeName.substring(0,i),n.objectName=e)}if(null===n.propertyName||0===n.propertyName.length)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+e);return n}static findNode(e,t){if(void 0===t||""===t||"."===t||-1===t||t===e.name||t===e.uuid)return e;if(e.skeleton){const n=e.skeleton.getBoneByName(t);if(void 0!==n)return n}if(e.children){const n=function(e){for(let i=0;i<e.length;i++){const r=e[i];if(r.name===t||r.uuid===t)return r;const s=n(r.children);if(s)return s}return null},i=n(e.children);if(i)return i}return null}_getValue_unavailable(){}_setValue_unavailable(){}_getValue_direct(e,t){e[t]=this.targetObject[this.propertyName]}_getValue_array(e,t){const n=this.resolvedProperty;for(let i=0,r=n.length;i!==r;++i)e[t++]=n[i]}_getValue_arrayElement(e,t){e[t]=this.resolvedProperty[this.propertyIndex]}_getValue_toArray(e,t){this.resolvedProperty.toArray(e,t)}_setValue_direct(e,t){this.targetObject[this.propertyName]=e[t]}_setValue_direct_setNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.needsUpdate=!0}_setValue_direct_setMatrixWorldNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_array(e,t){const n=this.resolvedProperty;for(let i=0,r=n.length;i!==r;++i)n[i]=e[t++]}_setValue_array_setNeedsUpdate(e,t){const n=this.resolvedProperty;for(let i=0,r=n.length;i!==r;++i)n[i]=e[t++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate(e,t){const n=this.resolvedProperty;for(let i=0,r=n.length;i!==r;++i)n[i]=e[t++];this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_arrayElement(e,t){this.resolvedProperty[this.propertyIndex]=e[t]}_setValue_arrayElement_setNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.needsUpdate=!0}_setValue_arrayElement_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_fromArray(e,t){this.resolvedProperty.fromArray(e,t)}_setValue_fromArray_setNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.needsUpdate=!0}_setValue_fromArray_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.matrixWorldNeedsUpdate=!0}_getValue_unbound(e,t){this.bind(),this.getValue(e,t)}_setValue_unbound(e,t){this.bind(),this.setValue(e,t)}bind(){let e=this.node;const t=this.parsedPath,n=t.objectName,i=t.propertyName;let r=t.propertyIndex;if(e||(e=ul.findNode(this.rootNode,t.nodeName),this.node=e),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!e)return void qn("PropertyBinding: No target node found for track: "+this.path+".");if(n){let i=t.objectIndex;switch(n){case"materials":if(!e.material)return void Qn("PropertyBinding: Can not bind to material as node does not have a material.",this);if(!e.material.materials)return void Qn("PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.",this);e=e.material.materials;break;case"bones":if(!e.skeleton)return void Qn("PropertyBinding: Can not bind to bones as node does not have a skeleton.",this);e=e.skeleton.bones;for(let t=0;t<e.length;t++)if(e[t].name===i){i=t;break}break;case"map":if("map"in e){e=e.map;break}if(!e.material)return void Qn("PropertyBinding: Can not bind to material as node does not have a material.",this);if(!e.material.map)return void Qn("PropertyBinding: Can not bind to material.map as node.material does not have a map.",this);e=e.material.map;break;default:if(void 0===e[n])return void Qn("PropertyBinding: Can not bind to objectName of node undefined.",this);e=e[n]}if(void 0!==i){if(void 0===e[i])return void Qn("PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.",this,e);e=e[i]}}const s=e[i];if(void 0===s){return void Qn("PropertyBinding: Trying to update property for track: "+t.nodeName+"."+i+" but it wasn't found.",e)}let a=this.Versioning.None;this.targetObject=e,!0===e.isMaterial?a=this.Versioning.NeedsUpdate:!0===e.isObject3D&&(a=this.Versioning.MatrixWorldNeedsUpdate);let o=this.BindingType.Direct;if(void 0!==r){if("morphTargetInfluences"===i){if(!e.geometry)return void Qn("PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.",this);if(!e.geometry.morphAttributes)return void Qn("PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.",this);void 0!==e.morphTargetDictionary[r]&&(r=e.morphTargetDictionary[r])}o=this.BindingType.ArrayElement,this.resolvedProperty=s,this.propertyIndex=r}else void 0!==s.fromArray&&void 0!==s.toArray?(o=this.BindingType.HasFromToArray,this.resolvedProperty=s):Array.isArray(s)?(o=this.BindingType.EntireArray,this.resolvedProperty=s):this.propertyName=i;this.getValue=this.GetterByBindingType[o],this.setValue=this.SetterByBindingTypeAndVersioning[o][a]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}}ul.Composite=class{constructor(e,t,n){const i=n||ul.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,i)}getValue(e,t){this.bind();const n=this._targetGroup.nCachedObjects_,i=this._bindings[n];void 0!==i&&i.getValue(e,t)}setValue(e,t){const n=this._bindings;for(let i=this._targetGroup.nCachedObjects_,r=n.length;i!==r;++i)n[i].setValue(e,t)}bind(){const e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].bind()}unbind(){const e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].unbind()}},ul.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},ul.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2},ul.prototype.GetterByBindingType=[ul.prototype._getValue_direct,ul.prototype._getValue_array,ul.prototype._getValue_arrayElement,ul.prototype._getValue_toArray],ul.prototype.SetterByBindingTypeAndVersioning=[[ul.prototype._setValue_direct,ul.prototype._setValue_direct_setNeedsUpdate,ul.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[ul.prototype._setValue_array,ul.prototype._setValue_array_setNeedsUpdate,ul.prototype._setValue_array_setMatrixWorldNeedsUpdate],[ul.prototype._setValue_arrayElement,ul.prototype._setValue_arrayElement_setNeedsUpdate,ul.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[ul.prototype._setValue_fromArray,ul.prototype._setValue_fromArray_setNeedsUpdate,ul.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];class dl{constructor(e,t,n=null,i=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=n,this.blendMode=i;const r=t.tracks,s=r.length,a=new Array(s),o={endingStart:xn,endingEnd:xn};for(let l=0;l!==s;++l){const e=r[l].createInterpolant(null);a[l]=e,e.settings=o}this._interpolantSettings=o,this._interpolants=a,this._propertyBindings=new Array(s),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=mn,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&0!==this.timeScale&&null===this._startTime&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(e){return this._startTime=e,this}setLoop(e,t){return this.loop=e,this.repetitions=t,this}setEffectiveWeight(e){return this.weight=e,this._effectiveWeight=this.enabled?e:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(e){return this._scheduleFading(e,0,1)}fadeOut(e){return this._scheduleFading(e,1,0)}crossFadeFrom(e,t,n=!1){if(e.fadeOut(t),this.fadeIn(t),!0===n){const n=this._clip.duration,i=e._clip.duration,r=i/n,s=n/i;e.warp(1,r,t),this.warp(s,1,t)}return this}crossFadeTo(e,t,n=!1){return e.crossFadeFrom(this,t,n)}stopFading(){const e=this._weightInterpolant;return null!==e&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}setEffectiveTimeScale(e){return this.timeScale=e,this._effectiveTimeScale=this.paused?0:e,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(e){return this.timeScale=this._clip.duration/e,this.stopWarping()}syncWith(e){return this.time=e.time,this.timeScale=e.timeScale,this.stopWarping()}halt(e){return this.warp(this._effectiveTimeScale,0,e)}warp(e,t,n){const i=this._mixer,r=i.time,s=this.timeScale;let a=this._timeScaleInterpolant;null===a&&(a=i._lendControlInterpolant(),this._timeScaleInterpolant=a);const o=a.parameterPositions,l=a.sampleValues;return o[0]=r,o[1]=r+n,l[0]=e/s,l[1]=t/s,this}stopWarping(){const e=this._timeScaleInterpolant;return null!==e&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(e,t,n,i){if(!this.enabled)return void this._updateWeight(e);const r=this._startTime;if(null!==r){const i=(e-r)*n;i<0||0===n?t=0:(this._startTime=null,t=n*i)}t*=this._updateTimeScale(e);const s=this._updateTime(t),a=this._updateWeight(e);if(a>0){const e=this._interpolants,t=this._propertyBindings;if(2501===this.blendMode)for(let n=0,i=e.length;n!==i;++n)e[n].evaluate(s),t[n].accumulateAdditive(a);else for(let n=0,r=e.length;n!==r;++n)e[n].evaluate(s),t[n].accumulate(i,a)}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;const n=this._weightInterpolant;if(null!==n){const i=n.evaluate(e)[0];t*=i,e>n.parameterPositions[1]&&(this.stopFading(),0===i&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;const n=this._timeScaleInterpolant;if(null!==n){t*=n.evaluate(e)[0],e>n.parameterPositions[1]&&(this.stopWarping(),0===t?this.paused=!0:this.timeScale=t)}}return this._effectiveTimeScale=t,t}_updateTime(e){const t=this._clip.duration,n=this.loop;let i=this.time+e,r=this._loopCount;const s=2202===n;if(0===e)return-1===r||!s||1&~r?i:t-i;if(n===fn){-1===r&&(this._loopCount=0,this._setEndings(!0,!0,!1));e:{if(i>=t)i=t;else{if(!(i<0)){this.time=i;break e}i=0}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:e<0?-1:1})}}else{if(-1===r&&(e>=0?(r=0,this._setEndings(!0,0===this.repetitions,s)):this._setEndings(0===this.repetitions,!0,s)),i>=t||i<0){const n=Math.floor(i/t);i-=t*n,r+=Math.abs(n);const a=this.repetitions-r;if(a<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,i=e>0?t:0,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:e>0?1:-1});else{if(1===a){const t=e<0;this._setEndings(t,!t,s)}else this._setEndings(!1,!1,s);this._loopCount=r,this.time=i,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:n})}}else this.time=i;if(s&&!(1&~r))return t-i}return i}_setEndings(e,t,n){const i=this._interpolantSettings;n?(i.endingStart=yn,i.endingEnd=yn):(i.endingStart=e?this.zeroSlopeAtStart?yn:xn:Sn,i.endingEnd=t?this.zeroSlopeAtEnd?yn:xn:Sn)}_scheduleFading(e,t,n){const i=this._mixer,r=i.time;let s=this._weightInterpolant;null===s&&(s=i._lendControlInterpolant(),this._weightInterpolant=s);const a=s.parameterPositions,o=s.sampleValues;return a[0]=r,o[0]=t,a[1]=r+e,o[1]=n,this}}const pl=new Float32Array(1);class fl extends Yn{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1}_bindAction(e,t){const n=e._localRoot||this._root,i=e._clip.tracks,r=i.length,s=e._propertyBindings,a=e._interpolants,o=n.uuid,l=this._bindingsByRootAndName;let c=l[o];void 0===c&&(c={},l[o]=c);for(let h=0;h!==r;++h){const e=i[h],r=e.name;let l=c[r];if(void 0!==l)++l.referenceCount,s[h]=l;else{if(l=s[h],void 0!==l){null===l._cacheIndex&&(++l.referenceCount,this._addInactiveBinding(l,o,r));continue}const i=t&&t._propertyBindings[h].binding.parsedPath;l=new rl(ul.create(n,r,i),e.ValueTypeName,e.getValueSize()),++l.referenceCount,this._addInactiveBinding(l,o,r),s[h]=l}a[h].resultBuffer=l.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(null===e._cacheIndex){const t=(e._localRoot||this._root).uuid,n=e._clip.uuid,i=this._actionsByClip[n];this._bindAction(e,i&&i.knownActions[0]),this._addInactiveAction(e,n,t)}const t=e._propertyBindings;for(let e=0,n=t.length;e!==n;++e){const n=t[e];0===n.useCount++&&(this._lendBinding(n),n.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){const t=e._propertyBindings;for(let e=0,n=t.length;e!==n;++e){const n=t[e];0===--n.useCount&&(n.restoreOriginalState(),this._takeBackBinding(n))}this._takeBackAction(e)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;const e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}}}_isActiveAction(e){const t=e._cacheIndex;return null!==t&&t<this._nActiveActions}_addInactiveAction(e,t,n){const i=this._actions,r=this._actionsByClip;let s=r[t];if(void 0===s)s={knownActions:[e],actionByRoot:{}},e._byClipCacheIndex=0,r[t]=s;else{const t=s.knownActions;e._byClipCacheIndex=t.length,t.push(e)}e._cacheIndex=i.length,i.push(e),s.actionByRoot[n]=e}_removeInactiveAction(e){const t=this._actions,n=t[t.length-1],i=e._cacheIndex;n._cacheIndex=i,t[i]=n,t.pop(),e._cacheIndex=null;const r=e._clip.uuid,s=this._actionsByClip,a=s[r],o=a.knownActions,l=o[o.length-1],c=e._byClipCacheIndex;l._byClipCacheIndex=c,o[c]=l,o.pop(),e._byClipCacheIndex=null;delete a.actionByRoot[(e._localRoot||this._root).uuid],0===o.length&&delete s[r],this._removeInactiveBindingsForAction(e)}_removeInactiveBindingsForAction(e){const t=e._propertyBindings;for(let n=0,i=t.length;n!==i;++n){const e=t[n];0===--e.referenceCount&&this._removeInactiveBinding(e)}}_lendAction(e){const t=this._actions,n=e._cacheIndex,i=this._nActiveActions++,r=t[i];e._cacheIndex=i,t[i]=e,r._cacheIndex=n,t[n]=r}_takeBackAction(e){const t=this._actions,n=e._cacheIndex,i=--this._nActiveActions,r=t[i];e._cacheIndex=i,t[i]=e,r._cacheIndex=n,t[n]=r}_addInactiveBinding(e,t,n){const i=this._bindingsByRootAndName,r=this._bindings;let s=i[t];void 0===s&&(s={},i[t]=s),s[n]=e,e._cacheIndex=r.length,r.push(e)}_removeInactiveBinding(e){const t=this._bindings,n=e.binding,i=n.rootNode.uuid,r=n.path,s=this._bindingsByRootAndName,a=s[i],o=t[t.length-1],l=e._cacheIndex;o._cacheIndex=l,t[l]=o,t.pop(),delete a[r],0===Object.keys(a).length&&delete s[i]}_lendBinding(e){const t=this._bindings,n=e._cacheIndex,i=this._nActiveBindings++,r=t[i];e._cacheIndex=i,t[i]=e,r._cacheIndex=n,t[n]=r}_takeBackBinding(e){const t=this._bindings,n=e._cacheIndex,i=--this._nActiveBindings,r=t[i];e._cacheIndex=i,t[i]=e,r._cacheIndex=n,t[n]=r}_lendControlInterpolant(){const e=this._controlInterpolants,t=this._nActiveControlInterpolants++;let n=e[t];return void 0===n&&(n=new vo(new Float32Array(2),new Float32Array(2),1,pl),n.__cacheIndex=t,e[t]=n),n}_takeBackControlInterpolant(e){const t=this._controlInterpolants,n=e.__cacheIndex,i=--this._nActiveControlInterpolants,r=t[i];e.__cacheIndex=i,t[i]=e,r.__cacheIndex=n,t[n]=r}clipAction(e,t,n){const i=t||this._root,r=i.uuid;let s="string"==typeof e?Co.findByName(i,e):e;const a=null!==s?s.uuid:e,o=this._actionsByClip[a];let l=null;if(void 0===n&&(n=null!==s?s.blendMode:An),void 0!==o){const e=o.actionByRoot[r];if(void 0!==e&&e.blendMode===n)return e;l=o.knownActions[0],null===s&&(s=l._clip)}if(null===s)return null;const c=new dl(this,s,t,n);return this._bindAction(c,l),this._addInactiveAction(c,a,r),c}existingAction(e,t){const n=t||this._root,i=n.uuid,r="string"==typeof e?Co.findByName(n,e):e,s=r?r.uuid:e,a=this._actionsByClip[s];return void 0!==a&&a.actionByRoot[i]||null}stopAllAction(){const e=this._actions;for(let t=this._nActiveActions-1;t>=0;--t)e[t].stop();return this}update(e){e*=this.timeScale;const t=this._actions,n=this._nActiveActions,i=this.time+=e,r=Math.sign(e),s=this._accuIndex^=1;for(let l=0;l!==n;++l){t[l]._update(i,e,r,s)}const a=this._bindings,o=this._nActiveBindings;for(let l=0;l!==o;++l)a[l].apply(s);return this}setTime(e){this.time=0;for(let t=0;t<this._actions.length;t++)this._actions[t].time=0;return this.update(e)}getRoot(){return this._root}uncacheClip(e){const t=this._actions,n=e.uuid,i=this._actionsByClip,r=i[n];if(void 0!==r){const e=r.knownActions;for(let n=0,i=e.length;n!==i;++n){const i=e[n];this._deactivateAction(i);const r=i._cacheIndex,s=t[t.length-1];i._cacheIndex=null,i._byClipCacheIndex=null,s._cacheIndex=r,t[r]=s,t.pop(),this._removeInactiveBindingsForAction(i)}delete i[n]}}uncacheRoot(e){const t=e.uuid,n=this._actionsByClip;for(const r in n){const e=n[r].actionByRoot[t];void 0!==e&&(this._deactivateAction(e),this._removeInactiveAction(e))}const i=this._bindingsByRootAndName[t];if(void 0!==i)for(const r in i){const e=i[r];e.restoreOriginalState(),this._removeInactiveBinding(e)}}uncacheAction(e,t){const n=this.existingAction(e,t);null!==n&&(this._deactivateAction(n),this._removeInactiveAction(n))}}class ml{constructor(e=1,t=0,n=0){this.radius=e,this.phi=t,this.theta=n}set(e,t,n){return this.radius=e,this.phi=t,this.theta=n,this}copy(e){return this.radius=e.radius,this.phi=e.phi,this.theta=e.theta,this}makeSafe(){const e=1e-6;return this.phi=ni(this.phi,e,Math.PI-e),this}setFromVector3(e){return this.setFromCartesianCoords(e.x,e.y,e.z)}setFromCartesianCoords(e,t,n){return this.radius=Math.sqrt(e*e+t*t+n*n),0===this.radius?(this.theta=0,this.phi=0):(this.theta=Math.atan2(e,n),this.phi=Math.acos(ni(t/this.radius,-1,1))),this}clone(){return(new this.constructor).copy(this)}}class gl extends Yn{constructor(e,t=null){super(),this.object=e,this.domElement=t,this.enabled=!0,this.state=-1,this.keys={},this.mouseButtons={LEFT:null,MIDDLE:null,RIGHT:null},this.touches={ONE:null,TWO:null}}connect(e){void 0!==e?(null!==this.domElement&&this.disconnect(),this.domElement=e):qn("Controls: connect() now requires an element.")}disconnect(){}dispose(){}update(){}}function _l(e,t,n,i){const r=function(e){switch(e){case ht:case ut:return{byteLength:1,components:1};case pt:case dt:case _t:return{byteLength:2,components:1};case vt:case xt:return{byteLength:2,components:4};case mt:case ft:case gt:return{byteLength:4,components:1};case St:case At:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${e}.`)}(i);switch(n){case 1021:return e*t;case Tt:case Et:return e*t/r.components*r.byteLength;case Ct:case Rt:return e*t*2/r.components*r.byteLength;case 1022:return e*t*3/r.components*r.byteLength;case bt:case It:return e*t*4/r.components*r.byteLength;case Pt:case Dt:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case Bt:case Lt:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case Ut:case Nt:return Math.max(e,16)*Math.max(t,8)/4;case Ft:case kt:return Math.max(e,8)*Math.max(t,8)/2;case Ot:case zt:case Vt:case Gt:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case Ht:case Wt:case jt:case Xt:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case qt:return Math.floor((e+4)/5)*Math.floor((t+3)/4)*16;case Qt:return Math.floor((e+4)/5)*Math.floor((t+4)/5)*16;case Kt:return Math.floor((e+5)/6)*Math.floor((t+4)/5)*16;case Yt:return Math.floor((e+5)/6)*Math.floor((t+5)/6)*16;case Zt:return Math.floor((e+7)/8)*Math.floor((t+4)/5)*16;case Jt:return Math.floor((e+7)/8)*Math.floor((t+5)/6)*16;case $t:return Math.floor((e+7)/8)*Math.floor((t+7)/8)*16;case en:return Math.floor((e+9)/10)*Math.floor((t+4)/5)*16;case tn:return Math.floor((e+9)/10)*Math.floor((t+5)/6)*16;case nn:return Math.floor((e+9)/10)*Math.floor((t+7)/8)*16;case rn:return Math.floor((e+9)/10)*Math.floor((t+9)/10)*16;case sn:return Math.floor((e+11)/12)*Math.floor((t+9)/10)*16;case an:return Math.floor((e+11)/12)*Math.floor((t+11)/12)*16;case on:case ln:case cn:return Math.ceil(e/4)*Math.ceil(t/4)*16;case hn:case un:return Math.ceil(e/4)*Math.ceil(t/4)*8;case dn:case pn:return Math.ceil(e/4)*Math.ceil(t/4)*16}throw new Error(`Unable to determine texture byte length for ${n} format.`)}function vl(){let e=null,t=!1,n=null,i=null;function r(t,s){n(t,s),i=e.requestAnimationFrame(r)}return{start:function(){!0!==t&&null!==n&&(i=e.requestAnimationFrame(r),t=!0)},stop:function(){e.cancelAnimationFrame(i),t=!1},setAnimationLoop:function(e){n=e},setContext:function(t){e=t}}}function xl(e){const t=new WeakMap;return{get:function(e){return e.isInterleavedBufferAttribute&&(e=e.data),t.get(e)},remove:function(n){n.isInterleavedBufferAttribute&&(n=n.data);const i=t.get(n);i&&(e.deleteBuffer(i.buffer),t.delete(n))},update:function(n,i){if(n.isInterleavedBufferAttribute&&(n=n.data),n.isGLBufferAttribute){const e=t.get(n);return void((!e||e.version<n.version)&&t.set(n,{buffer:n.buffer,type:n.type,bytesPerElement:n.elementSize,version:n.version}))}const r=t.get(n);if(void 0===r)t.set(n,function(t,n){const i=t.array,r=t.usage,s=i.byteLength,a=e.createBuffer();let o;if(e.bindBuffer(n,a),e.bufferData(n,i,r),t.onUploadCallback(),i instanceof Float32Array)o=e.FLOAT;else if("undefined"!=typeof Float16Array&&i instanceof Float16Array)o=e.HALF_FLOAT;else if(i instanceof Uint16Array)o=t.isFloat16BufferAttribute?e.HALF_FLOAT:e.UNSIGNED_SHORT;else if(i instanceof Int16Array)o=e.SHORT;else if(i instanceof Uint32Array)o=e.UNSIGNED_INT;else if(i instanceof Int32Array)o=e.INT;else if(i instanceof Int8Array)o=e.BYTE;else if(i instanceof Uint8Array)o=e.UNSIGNED_BYTE;else{if(!(i instanceof Uint8ClampedArray))throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+i);o=e.UNSIGNED_BYTE}return{buffer:a,type:o,bytesPerElement:i.BYTES_PER_ELEMENT,version:t.version,size:s}}(n,i));else if(r.version<n.version){if(r.size!==n.array.byteLength)throw new Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.");!function(t,n,i){const r=n.array,s=n.updateRanges;if(e.bindBuffer(i,t),0===s.length)e.bufferSubData(i,0,r);else{s.sort((e,t)=>e.start-t.start);let t=0;for(let e=1;e<s.length;e++){const n=s[t],i=s[e];i.start<=n.start+n.count+1?n.count=Math.max(n.count,i.start+i.count-n.start):(++t,s[t]=i)}s.length=t+1;for(let n=0,a=s.length;n<a;n++){const t=s[n];e.bufferSubData(i,t.start*r.BYTES_PER_ELEMENT,r,t.start,t.count)}n.clearUpdateRanges()}n.onUploadCallback()}(r.buffer,n,i),r.version=n.version}}}}"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:ne}})),"undefined"!=typeof window&&(window.__THREE__?qn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=ne);const yl={alphahash_fragment:"#ifdef USE_ALPHAHASH\n\tif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif",alphahash_pars_fragment:"#ifdef USE_ALPHAHASH\n\tconst float ALPHA_HASH_SCALE = 0.05;\n\tfloat hash2D( vec2 value ) {\n\t\treturn fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );\n\t}\n\tfloat hash3D( vec3 value ) {\n\t\treturn hash2D( vec2( hash2D( value.xy ), value.z ) );\n\t}\n\tfloat getAlphaHashThreshold( vec3 position ) {\n\t\tfloat maxDeriv = max(\n\t\t\tlength( dFdx( position.xyz ) ),\n\t\t\tlength( dFdy( position.xyz ) )\n\t\t);\n\t\tfloat pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );\n\t\tvec2 pixScales = vec2(\n\t\t\texp2( floor( log2( pixScale ) ) ),\n\t\t\texp2( ceil( log2( pixScale ) ) )\n\t\t);\n\t\tvec2 alpha = vec2(\n\t\t\thash3D( floor( pixScales.x * position.xyz ) ),\n\t\t\thash3D( floor( pixScales.y * position.xyz ) )\n\t\t);\n\t\tfloat lerpFactor = fract( log2( pixScale ) );\n\t\tfloat x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;\n\t\tfloat a = min( lerpFactor, 1.0 - lerpFactor );\n\t\tvec3 cases = vec3(\n\t\t\tx * x / ( 2.0 * a * ( 1.0 - a ) ),\n\t\t\t( x - 0.5 * a ) / ( 1.0 - a ),\n\t\t\t1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )\n\t\t);\n\t\tfloat threshold = ( x < ( 1.0 - a ) )\n\t\t\t? ( ( x < a ) ? cases.x : cases.y )\n\t\t\t: cases.z;\n\t\treturn clamp( threshold , 1.0e-6, 1.0 );\n\t}\n#endif",alphamap_fragment:"#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif",alphamap_pars_fragment:"#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif",alphatest_fragment:"#ifdef USE_ALPHATEST\n\t#ifdef ALPHA_TO_COVERAGE\n\tdiffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );\n\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\tif ( diffuseColor.a < alphaTest ) discard;\n\t#endif\n#endif",alphatest_pars_fragment:"#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif",aomap_fragment:"#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_CLEARCOAT ) \n\t\tclearcoatSpecularIndirect *= ambientOcclusion;\n\t#endif\n\t#if defined( USE_SHEEN ) \n\t\tsheenSpecularIndirect *= ambientOcclusion;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometryNormal, geometryViewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif",aomap_pars_fragment:"#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif",batching_pars_vertex:"#ifdef USE_BATCHING\n\t#if ! defined( GL_ANGLE_multi_draw )\n\t#define gl_DrawID _gl_DrawID\n\tuniform int _gl_DrawID;\n\t#endif\n\tuniform highp sampler2D batchingTexture;\n\tuniform highp usampler2D batchingIdTexture;\n\tmat4 getBatchingMatrix( const in float i ) {\n\t\tint size = textureSize( batchingTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n\tfloat getIndirectIndex( const in int i ) {\n\t\tint size = textureSize( batchingIdTexture, 0 ).x;\n\t\tint x = i % size;\n\t\tint y = i / size;\n\t\treturn float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r );\n\t}\n#endif\n#ifdef USE_BATCHING_COLOR\n\tuniform sampler2D batchingColorTexture;\n\tvec3 getBatchingColor( const in float i ) {\n\t\tint size = textureSize( batchingColorTexture, 0 ).x;\n\t\tint j = int( i );\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\treturn texelFetch( batchingColorTexture, ivec2( x, y ), 0 ).rgb;\n\t}\n#endif",batching_vertex:"#ifdef USE_BATCHING\n\tmat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );\n#endif",begin_vertex:"vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif",beginnormal_vertex:"vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif",bsdfs:"float G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n} // validated",iridescence_fragment:"#ifdef USE_IRIDESCENCE\n\tconst mat3 XYZ_TO_REC709 = mat3(\n\t\t 3.2404542, -0.9692660, 0.0556434,\n\t\t-1.5371385, 1.8760108, -0.2040259,\n\t\t-0.4985314, 0.0415560, 1.0572252\n\t);\n\tvec3 Fresnel0ToIor( vec3 fresnel0 ) {\n\t\tvec3 sqrtF0 = sqrt( fresnel0 );\n\t\treturn ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );\n\t}\n\tvec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );\n\t}\n\tfloat IorToFresnel0( float transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));\n\t}\n\tvec3 evalSensitivity( float OPD, vec3 shift ) {\n\t\tfloat phase = 2.0 * PI * OPD * 1.0e-9;\n\t\tvec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );\n\t\tvec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );\n\t\tvec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );\n\t\tvec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );\n\t\txyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );\n\t\txyz /= 1.0685e-7;\n\t\tvec3 rgb = XYZ_TO_REC709 * xyz;\n\t\treturn rgb;\n\t}\n\tvec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {\n\t\tvec3 I;\n\t\tfloat iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );\n\t\tfloat sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );\n\t\tfloat cosTheta2Sq = 1.0 - sinTheta2Sq;\n\t\tif ( cosTheta2Sq < 0.0 ) {\n\t\t\treturn vec3( 1.0 );\n\t\t}\n\t\tfloat cosTheta2 = sqrt( cosTheta2Sq );\n\t\tfloat R0 = IorToFresnel0( iridescenceIOR, outsideIOR );\n\t\tfloat R12 = F_Schlick( R0, 1.0, cosTheta1 );\n\t\tfloat T121 = 1.0 - R12;\n\t\tfloat phi12 = 0.0;\n\t\tif ( iridescenceIOR < outsideIOR ) phi12 = PI;\n\t\tfloat phi21 = PI - phi12;\n\t\tvec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );\t\tvec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );\n\t\tvec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );\n\t\tvec3 phi23 = vec3( 0.0 );\n\t\tif ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;\n\t\tif ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;\n\t\tif ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;\n\t\tfloat OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;\n\t\tvec3 phi = vec3( phi21 ) + phi23;\n\t\tvec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );\n\t\tvec3 r123 = sqrt( R123 );\n\t\tvec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );\n\t\tvec3 C0 = R12 + Rs;\n\t\tI = C0;\n\t\tvec3 Cm = Rs - T121;\n\t\tfor ( int m = 1; m <= 2; ++ m ) {\n\t\t\tCm *= r123;\n\t\t\tvec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );\n\t\t\tI += Cm * Sm;\n\t\t}\n\t\treturn max( I, vec3( 0.0 ) );\n\t}\n#endif",bumpmap_pars_fragment:"#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vBumpMapUv );\n\t\tvec2 dSTdy = dFdy( vBumpMapUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );\n\t\tvec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif",clipping_planes_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#ifdef ALPHA_TO_COVERAGE\n\t\tfloat distanceToPlane, distanceGradient;\n\t\tfloat clipOpacity = 1.0;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\tclipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\tif ( clipOpacity == 0.0 ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tfloat unionClipOpacity = 1.0;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\t\tunionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tclipOpacity *= 1.0 - unionClipOpacity;\n\t\t#endif\n\t\tdiffuseColor.a *= clipOpacity;\n\t\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tbool clipped = true;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tif ( clipped ) discard;\n\t\t#endif\n\t#endif\n#endif",clipping_planes_pars_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif",clipping_planes_pars_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif",clipping_planes_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif",color_fragment:"#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif",color_pars_fragment:"#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif",color_pars_vertex:"#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvarying vec3 vColor;\n#endif",color_vertex:"#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif\n#ifdef USE_BATCHING_COLOR\n\tvec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) );\n\tvColor.xyz *= batchingColor.xyz;\n#endif",common:"#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\n#ifdef USE_ALPHAHASH\n\tvarying vec3 vPosition;\n#endif\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}\nvec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n} // validated",cube_uv_reflection_fragment:"#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\thighp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define cubeUV_r0 1.0\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= cubeUV_r1 ) {\n\t\t\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n\t\t} else if ( roughness >= cubeUV_r4 ) {\n\t\t\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n\t\t} else if ( roughness >= cubeUV_r5 ) {\n\t\t\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n\t\t} else if ( roughness >= cubeUV_r6 ) {\n\t\t\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif",defaultnormal_vertex:"vec3 transformedNormal = objectNormal;\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = objectTangent;\n#endif\n#ifdef USE_BATCHING\n\tmat3 bm = mat3( batchingMatrix );\n\ttransformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );\n\ttransformedNormal = bm * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = bm * transformedTangent;\n\t#endif\n#endif\n#ifdef USE_INSTANCING\n\tmat3 im = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );\n\ttransformedNormal = im * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = im * transformedTangent;\n\t#endif\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\ttransformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif",displacementmap_pars_vertex:"#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif",displacementmap_vertex:"#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif",emissivemap_fragment:"#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE_EMISSIVE\n\t\temissiveColor = sRGBTransferEOTF( emissiveColor );\n\t#endif\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif",emissivemap_pars_fragment:"#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif",colorspace_fragment:"gl_FragColor = linearToOutputTexel( gl_FragColor );",colorspace_pars_fragment:"vec4 LinearTransferOETF( in vec4 value ) {\n\treturn value;\n}\nvec4 sRGBTransferEOTF( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 sRGBTransferOETF( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}",envmap_fragment:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif",envmap_common_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform mat3 envMapRotation;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n#endif",envmap_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif",envmap_pars_vertex:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif",envmap_physical_pars_fragment:"#ifdef USE_ENVMAP\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, pow4( roughness ) ) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\t#ifdef USE_ANISOTROPY\n\t\tvec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n\t\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\t\tvec3 bentNormal = cross( bitangent, viewDir );\n\t\t\t\tbentNormal = normalize( cross( bentNormal, bitangent ) );\n\t\t\t\tbentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n\t\t\t\treturn getIBLRadiance( viewDir, bentNormal, roughness );\n\t\t\t#else\n\t\t\t\treturn vec3( 0.0 );\n\t\t\t#endif\n\t\t}\n\t#endif\n#endif",envmap_vertex:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif",fog_vertex:"#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif",fog_pars_vertex:"#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif",fog_fragment:"#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif",fog_pars_fragment:"#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif",gradientmap_pars_fragment:"#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\tvec2 fw = fwidth( coord ) * 0.5;\n\t\treturn mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n\t#endif\n}",lightmap_pars_fragment:"#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif",lights_lambert_fragment:"LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;",lights_lambert_pars_fragment:"varying vec3 vViewPosition;\nstruct LambertMaterial {\n\tvec3 diffuseColor;\n\tfloat specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert",lights_pars_begin:"uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\n#if defined( USE_LIGHT_PROBES )\n\tuniform vec3 lightProbe[ 9 ];\n#endif\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif ( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif",lights_toon_fragment:"ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;",lights_toon_pars_fragment:"varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon",lights_phong_fragment:"BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;",lights_phong_pars_fragment:"varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong",lights_physical_fragment:"PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.diffuseContribution = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.metalness = metalnessFactor;\nvec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\tmaterial.ior = ior;\n\t#ifdef USE_SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULAR_COLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;\n\t\t#endif\n\t\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor;\n\tmaterial.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = vec3( 0.04 );\n\tmaterial.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_DISPERSION\n\tmaterial.dispersion = dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.0001, 1.0 );\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\t#ifdef USE_ANISOTROPYMAP\n\t\tmat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );\n\t\tvec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;\n\t\tvec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;\n\t#else\n\t\tvec2 anisotropyV = anisotropyVector;\n\t#endif\n\tmaterial.anisotropy = length( anisotropyV );\n\tif( material.anisotropy == 0.0 ) {\n\t\tanisotropyV = vec2( 1.0, 0.0 );\n\t} else {\n\t\tanisotropyV /= material.anisotropy;\n\t\tmaterial.anisotropy = saturate( material.anisotropy );\n\t}\n\tmaterial.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );\n\tmaterial.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;\n\tmaterial.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;\n#endif",lights_physical_pars_fragment:"uniform sampler2D dfgLUT;\nstruct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tvec3 diffuseContribution;\n\tvec3 specularColor;\n\tvec3 specularColorBlended;\n\tfloat roughness;\n\tfloat metalness;\n\tfloat specularF90;\n\tfloat dispersion;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t\tvec3 iridescenceFresnelDielectric;\n\t\tvec3 iridescenceFresnelMetallic;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat anisotropy;\n\t\tfloat alphaT;\n\t\tvec3 anisotropyT;\n\t\tvec3 anisotropyB;\n\t#endif\n};\nvec3 clearcoatSpecularDirect = vec3( 0.0 );\nvec3 clearcoatSpecularIndirect = vec3( 0.0 );\nvec3 sheenSpecularDirect = vec3( 0.0 );\nvec3 sheenSpecularIndirect = vec3(0.0 );\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\n#ifdef USE_ANISOTROPY\n\tfloat V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {\n\t\tfloat gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );\n\t\tfloat gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );\n\t\tfloat v = 0.5 / ( gv + gl );\n\t\treturn v;\n\t}\n\tfloat D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {\n\t\tfloat a2 = alphaT * alphaB;\n\t\thighp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );\n\t\thighp float v2 = dot( v, v );\n\t\tfloat w2 = a2 / v2;\n\t\treturn RECIPROCAL_PI * a2 * pow2 ( w2 );\n\t}\n#endif\n#ifdef USE_CLEARCOAT\n\tvec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {\n\t\tvec3 f0 = material.clearcoatF0;\n\t\tfloat f90 = material.clearcoatF90;\n\t\tfloat roughness = material.clearcoatRoughness;\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 f0 = material.specularColorBlended;\n\tfloat f90 = material.specularF90;\n\tfloat roughness = material.roughness;\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t#ifdef USE_IRIDESCENCE\n\t\tF = mix( F, material.iridescenceFresnel, material.iridescence );\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat dotTL = dot( material.anisotropyT, lightDir );\n\t\tfloat dotTV = dot( material.anisotropyT, viewDir );\n\t\tfloat dotTH = dot( material.anisotropyT, halfDir );\n\t\tfloat dotBL = dot( material.anisotropyB, lightDir );\n\t\tfloat dotBV = dot( material.anisotropyB, viewDir );\n\t\tfloat dotBH = dot( material.anisotropyB, halfDir );\n\t\tfloat V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );\n\t\tfloat D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );\n\t#else\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t#endif\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transpose( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat rInv = 1.0 / ( roughness + 0.1 );\n\tfloat a = -1.9362 + 1.0678 * roughness + 0.4573 * r2 - 0.8469 * rInv;\n\tfloat b = -0.6014 + 0.5538 * roughness - 0.4670 * r2 - 0.1255 * rInv;\n\tfloat DG = exp( a * dotNV + b );\n\treturn saturate( DG );\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg;\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg;\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\nvec3 BRDF_GGX_Multiscatter( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 singleScatter = BRDF_GGX( lightDir, viewDir, normal, material );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 dfgV = texture2D( dfgLUT, vec2( material.roughness, dotNV ) ).rg;\n\tvec2 dfgL = texture2D( dfgLUT, vec2( material.roughness, dotNL ) ).rg;\n\tvec3 FssEss_V = material.specularColorBlended * dfgV.x + material.specularF90 * dfgV.y;\n\tvec3 FssEss_L = material.specularColorBlended * dfgL.x + material.specularF90 * dfgL.y;\n\tfloat Ess_V = dfgV.x + dfgV.y;\n\tfloat Ess_L = dfgL.x + dfgL.y;\n\tfloat Ems_V = 1.0 - Ess_V;\n\tfloat Ems_L = 1.0 - Ess_L;\n\tvec3 Favg = material.specularColorBlended + ( 1.0 - material.specularColorBlended ) * 0.047619;\n\tvec3 Fms = FssEss_V * FssEss_L * Favg / ( 1.0 - Ems_V * Ems_L * Favg + EPSILON );\n\tfloat compensationFactor = Ems_V * Ems_L;\n\tvec3 multiScatter = Fms * compensationFactor;\n\treturn singleScatter + multiScatter;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometryNormal;\n\t\tvec3 viewDir = geometryViewDir;\n\t\tvec3 position = geometryPosition;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColorBlended * t2.x + ( vec3( 1.0 ) - material.specularColorBlended ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseContribution * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );\n\t#endif\n\t#ifdef USE_SHEEN\n \n \t\tsheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\n \n \t\tfloat sheenAlbedoV = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n \t\tfloat sheenAlbedoL = IBLSheenBRDF( geometryNormal, directLight.direction, material.sheenRoughness );\n \n \t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * max( sheenAlbedoV, sheenAlbedoL );\n \n \t\tirradiance *= sheenEnergyComp;\n \n \t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX_Multiscatter( directLight.direction, geometryViewDir, geometryNormal, material );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseContribution );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 diffuse = irradiance * BRDF_Lambert( material.diffuseContribution );\n\t#ifdef USE_SHEEN\n\t\tfloat sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;\n\t\tdiffuse *= sheenEnergyComp;\n\t#endif\n\treflectedLight.indirectDiffuse += diffuse;\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ) * RECIPROCAL_PI;\n \t#endif\n\tvec3 singleScatteringDielectric = vec3( 0.0 );\n\tvec3 multiScatteringDielectric = vec3( 0.0 );\n\tvec3 singleScatteringMetallic = vec3( 0.0 );\n\tvec3 multiScatteringMetallic = vec3( 0.0 );\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnelDielectric, material.roughness, singleScatteringDielectric, multiScatteringDielectric );\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.iridescence, material.iridescenceFresnelMetallic, material.roughness, singleScatteringMetallic, multiScatteringMetallic );\n\t#else\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScatteringDielectric, multiScatteringDielectric );\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.roughness, singleScatteringMetallic, multiScatteringMetallic );\n\t#endif\n\tvec3 singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, material.metalness );\n\tvec3 multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, material.metalness );\n\tvec3 totalScatteringDielectric = singleScatteringDielectric + multiScatteringDielectric;\n\tvec3 diffuse = material.diffuseContribution * ( 1.0 - totalScatteringDielectric );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tvec3 indirectSpecular = radiance * singleScattering;\n\tindirectSpecular += multiScattering * cosineWeightedIrradiance;\n\tvec3 indirectDiffuse = diffuse * cosineWeightedIrradiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;\n\t\tindirectSpecular *= sheenEnergyComp;\n\t\tindirectDiffuse *= sheenEnergyComp;\n\t#endif\n\treflectedLight.indirectSpecular += indirectSpecular;\n\treflectedLight.indirectDiffuse += indirectDiffuse;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}",lights_fragment_begin:"\nvec3 geometryPosition = - vViewPosition;\nvec3 geometryNormal = normal;\nvec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\nvec3 geometryClearcoatNormal = vec3( 0.0 );\n#ifdef USE_CLEARCOAT\n\tgeometryClearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometryViewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tmaterial.iridescenceFresnelDielectric = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceFresnelMetallic = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.diffuseColor );\n\t\tmaterial.iridescenceFresnel = mix( material.iridescenceFresnelDielectric, material.iridescenceFresnelMetallic, material.metalness );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometryPosition, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometryPosition, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#if defined( USE_LIGHT_PROBES )\n\t\tirradiance += getLightProbeIrradiance( lightProbe, geometryNormal );\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif",lights_fragment_maps:"#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometryNormal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\t#ifdef USE_ANISOTROPY\n\t\tradiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );\n\t#else\n\t\tradiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif",lights_fragment_end:"#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif",logdepthbuf_fragment:"#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )\n\tgl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif",logdepthbuf_pars_fragment:"#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_pars_vertex:"#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_vertex:"#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif",map_fragment:"#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif",map_pars_fragment:"#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif",map_particle_fragment:"#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t#if defined( USE_POINTS_UV )\n\t\tvec2 uv = vUv;\n\t#else\n\t\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif",map_particle_pars_fragment:"#if defined( USE_POINTS_UV )\n\tvarying vec2 vUv;\n#else\n\t#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t\tuniform mat3 uvTransform;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif",metalnessmap_fragment:"float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif",metalnessmap_pars_fragment:"#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif",morphinstance_vertex:"#ifdef USE_INSTANCING_MORPH\n\tfloat morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\tfloat morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tmorphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;\n\t}\n#endif",morphcolor_vertex:"#if defined( USE_MORPHCOLORS )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif",morphnormal_vertex:"#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif",morphtarget_pars_vertex:"#ifdef USE_MORPHTARGETS\n\t#ifndef USE_INSTANCING_MORPH\n\t\tuniform float morphTargetBaseInfluence;\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t#endif\n\tuniform sampler2DArray morphTargetsTexture;\n\tuniform ivec2 morphTargetsTextureSize;\n\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t}\n#endif",morphtarget_vertex:"#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif",normal_fragment_begin:"float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = dFdx( vViewPosition );\n\tvec3 fdy = dFdy( vViewPosition );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal *= faceDirection;\n\t#endif\n#endif\n#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn = getTangentFrame( - vViewPosition, normal,\n\t\t#if defined( USE_NORMALMAP )\n\t\t\tvNormalMapUv\n\t\t#elif defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tvClearcoatNormalMapUv\n\t\t#else\n\t\t\tvUv\n\t\t#endif\n\t\t);\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn[0] *= faceDirection;\n\t\ttbn[1] *= faceDirection;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn2[0] *= faceDirection;\n\t\ttbn2[1] *= faceDirection;\n\t#endif\n#endif\nvec3 nonPerturbedNormal = normal;",normal_fragment_maps:"#ifdef USE_NORMALMAP_OBJECTSPACE\n\tnormal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( USE_NORMALMAP_TANGENTSPACE )\n\tvec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\tnormal = normalize( tbn * mapN );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif",normal_pars_fragment:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_pars_vertex:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_vertex:"#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif",normalmap_pars_fragment:"#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef USE_NORMALMAP_OBJECTSPACE\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )\n\tmat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( uv.st );\n\t\tvec2 st1 = dFdy( uv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );\n\t\treturn mat3( T * scale, B * scale, N );\n\t}\n#endif",clearcoat_normal_fragment_begin:"#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif",clearcoat_normal_fragment_maps:"#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\tclearcoatNormal = normalize( tbn2 * clearcoatMapN );\n#endif",clearcoat_pars_fragment:"#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif",iridescence_pars_fragment:"#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif",opaque_fragment:"#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );",packing:"vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;\nconst float Inv255 = 1. / 255.;\nconst vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );\nconst vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );\nconst vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );\nconst vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );\nvec4 packDepthToRGBA( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec4( 0., 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec4( 1., 1., 1., 1. );\n\tfloat vuf;\n\tfloat af = modf( v * PackFactors.a, vuf );\n\tfloat bf = modf( vuf * ShiftRight8, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );\n}\nvec3 packDepthToRGB( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec3( 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec3( 1., 1., 1. );\n\tfloat vuf;\n\tfloat bf = modf( v * PackFactors.b, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec3( vuf * Inv255, gf * PackUpscale, bf );\n}\nvec2 packDepthToRG( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec2( 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec2( 1., 1. );\n\tfloat vuf;\n\tfloat gf = modf( v * 256., vuf );\n\treturn vec2( vuf * Inv255, gf );\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors4 );\n}\nfloat unpackRGBToDepth( const in vec3 v ) {\n\treturn dot( v, UnpackFactors3 );\n}\nfloat unpackRGToDepth( const in vec2 v ) {\n\treturn v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;\n}\nvec4 pack2HalfToRGBA( const in vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( const in vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn depth * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * depth - far );\n}",premultiplied_alpha_fragment:"#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif",project_vertex:"vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_BATCHING\n\tmvPosition = batchingMatrix * mvPosition;\n#endif\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;",dithering_fragment:"#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif",dithering_pars_fragment:"#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif",roughnessmap_fragment:"float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif",roughnessmap_pars_fragment:"#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif",shadowmap_pars_fragment:"#if NUM_SPOT_LIGHT_COORDS > 0\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n\tuniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform sampler2DShadow directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\t#else\n\t\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform sampler2DShadow spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\t#else\n\t\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform samplerCubeShadow pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\t#elif defined( SHADOWMAP_TYPE_BASIC )\n\t\t\tuniform samplerCube pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\tfloat interleavedGradientNoise( vec2 position ) {\n\t\t\treturn fract( 52.9829189 * fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) );\n\t\t}\n\t\tvec2 vogelDiskSample( int sampleIndex, int samplesCount, float phi ) {\n\t\t\tconst float goldenAngle = 2.399963229728653;\n\t\t\tfloat r = sqrt( ( float( sampleIndex ) + 0.5 ) / float( samplesCount ) );\n\t\t\tfloat theta = float( sampleIndex ) * goldenAngle + phi;\n\t\t\treturn vec2( cos( theta ), sin( theta ) ) * r;\n\t\t}\n\t#endif\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\tfloat getShadow( sampler2DShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\tshadowCoord.z += shadowBias;\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\t\tfloat radius = shadowRadius * texelSize.x;\n\t\t\t\tfloat phi = interleavedGradientNoise( gl_FragCoord.xy ) * 6.28318530718;\n\t\t\t\tshadow = (\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 0, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 1, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 2, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 3, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 4, 5, phi ) * radius, shadowCoord.z ) )\n\t\t\t\t) * 0.2;\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\tshadowCoord.z += shadowBias;\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tvec2 distribution = texture2D( shadowMap, shadowCoord.xy ).rg;\n\t\t\t\tfloat mean = distribution.x;\n\t\t\t\tfloat variance = distribution.y * distribution.y;\n\t\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\t\tfloat hard_shadow = step( mean, shadowCoord.z );\n\t\t\t\t#else\n\t\t\t\t\tfloat hard_shadow = step( shadowCoord.z, mean );\n\t\t\t\t#endif\n\t\t\t\tif ( hard_shadow == 1.0 ) {\n\t\t\t\t\tshadow = 1.0;\n\t\t\t\t} else {\n\t\t\t\t\tvariance = max( variance, 0.0000001 );\n\t\t\t\t\tfloat d = shadowCoord.z - mean;\n\t\t\t\t\tfloat p_max = variance / ( variance + d * d );\n\t\t\t\t\tp_max = clamp( ( p_max - 0.3 ) / 0.65, 0.0, 1.0 );\n\t\t\t\t\tshadow = max( hard_shadow, p_max );\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#else\n\t\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\tshadowCoord.z += shadowBias;\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tfloat depth = texture2D( shadowMap, shadowCoord.xy ).r;\n\t\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\t\tshadow = step( depth, shadowCoord.z );\n\t\t\t\t#else\n\t\t\t\t\tshadow = step( shadowCoord.z, depth );\n\t\t\t\t#endif\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\tfloat getPointShadow( samplerCubeShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tvec3 absVec = abs( lightToPosition );\n\t\tfloat viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );\n\t\tif ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {\n\t\t\tfloat dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\tdp += shadowBias;\n\t\t\tfloat texelSize = shadowRadius / shadowMapSize.x;\n\t\t\tvec3 absDir = abs( bd3D );\n\t\t\tvec3 tangent = absDir.x > absDir.z ? vec3( 0.0, 1.0, 0.0 ) : vec3( 1.0, 0.0, 0.0 );\n\t\t\ttangent = normalize( cross( bd3D, tangent ) );\n\t\t\tvec3 bitangent = cross( bd3D, tangent );\n\t\t\tfloat phi = interleavedGradientNoise( gl_FragCoord.xy ) * 6.28318530718;\n\t\t\tshadow = (\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * vogelDiskSample( 0, 5, phi ).x + bitangent * vogelDiskSample( 0, 5, phi ).y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * vogelDiskSample( 1, 5, phi ).x + bitangent * vogelDiskSample( 1, 5, phi ).y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * vogelDiskSample( 2, 5, phi ).x + bitangent * vogelDiskSample( 2, 5, phi ).y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * vogelDiskSample( 3, 5, phi ).x + bitangent * vogelDiskSample( 3, 5, phi ).y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * vogelDiskSample( 4, 5, phi ).x + bitangent * vogelDiskSample( 4, 5, phi ).y ) * texelSize, dp ) )\n\t\t\t) * 0.2;\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\t#elif defined( SHADOWMAP_TYPE_BASIC )\n\tfloat getPointShadow( samplerCube shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tvec3 absVec = abs( lightToPosition );\n\t\tfloat viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );\n\t\tif ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {\n\t\t\tfloat dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\tdp += shadowBias;\n\t\t\tfloat depth = textureCube( shadowMap, bd3D ).r;\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tshadow = step( depth, dp );\n\t\t\t#else\n\t\t\t\tshadow = step( dp, depth );\n\t\t\t#endif\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\t#endif\n\t#endif\n#endif",shadowmap_pars_vertex:"#if NUM_SPOT_LIGHT_COORDS > 0\n\tuniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif",shadowmap_vertex:"#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\tvec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n#endif",shadowmask_pars_fragment:"float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0 && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}",skinbase_vertex:"#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif",skinning_pars_vertex:"#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tint size = textureSize( boneTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n#endif",skinning_vertex:"#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif",skinnormal_vertex:"#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif",specularmap_fragment:"float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif",specularmap_pars_fragment:"#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif",tonemapping_fragment:"#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif",tonemapping_pars_fragment:"#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn saturate( toneMappingExposure * color );\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 CineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.6605, - 0.1246, - 0.0182 ),\n\tvec3( - 0.5876, 1.1329, - 0.1006 ),\n\tvec3( - 0.0728, - 0.0083, 1.1187 )\n);\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n\tvec3( 0.6274, 0.0691, 0.0164 ),\n\tvec3( 0.3293, 0.9195, 0.0880 ),\n\tvec3( 0.0433, 0.0113, 0.8956 )\n);\nvec3 agxDefaultContrastApprox( vec3 x ) {\n\tvec3 x2 = x * x;\n\tvec3 x4 = x2 * x2;\n\treturn + 15.5 * x4 * x2\n\t\t- 40.14 * x4 * x\n\t\t+ 31.96 * x4\n\t\t- 6.868 * x2 * x\n\t\t+ 0.4298 * x2\n\t\t+ 0.1191 * x\n\t\t- 0.00232;\n}\nvec3 AgXToneMapping( vec3 color ) {\n\tconst mat3 AgXInsetMatrix = mat3(\n\t\tvec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n\t\tvec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n\t\tvec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n\t);\n\tconst mat3 AgXOutsetMatrix = mat3(\n\t\tvec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n\t\tvec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n\t\tvec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n\t);\n\tconst float AgxMinEv = - 12.47393;\tconst float AgxMaxEv = 4.026069;\n\tcolor *= toneMappingExposure;\n\tcolor = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\tcolor = AgXInsetMatrix * color;\n\tcolor = max( color, 1e-10 );\tcolor = log2( color );\n\tcolor = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n\tcolor = clamp( color, 0.0, 1.0 );\n\tcolor = agxDefaultContrastApprox( color );\n\tcolor = AgXOutsetMatrix * color;\n\tcolor = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n\tcolor = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n\tcolor = clamp( color, 0.0, 1.0 );\n\treturn color;\n}\nvec3 NeutralToneMapping( vec3 color ) {\n\tconst float StartCompression = 0.8 - 0.04;\n\tconst float Desaturation = 0.15;\n\tcolor *= toneMappingExposure;\n\tfloat x = min( color.r, min( color.g, color.b ) );\n\tfloat offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n\tcolor -= offset;\n\tfloat peak = max( color.r, max( color.g, color.b ) );\n\tif ( peak < StartCompression ) return color;\n\tfloat d = 1. - StartCompression;\n\tfloat newPeak = 1. - d * d / ( peak + d - StartCompression );\n\tcolor *= newPeak / peak;\n\tfloat g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );\n\treturn mix( color, vec3( newPeak ), g );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }",transmission_fragment:"#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmitted = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseContribution, material.specularColorBlended, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );\n#endif",transmission_pars_fragment:"#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tfloat w0( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\n\t}\n\tfloat w1( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );\n\t}\n\tfloat w2( float a ){\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\n\t}\n\tfloat w3( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * a );\n\t}\n\tfloat g0( float a ) {\n\t\treturn w0( a ) + w1( a );\n\t}\n\tfloat g1( float a ) {\n\t\treturn w2( a ) + w3( a );\n\t}\n\tfloat h0( float a ) {\n\t\treturn - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\n\t}\n\tfloat h1( float a ) {\n\t\treturn 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\n\t}\n\tvec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {\n\t\tuv = uv * texelSize.zw + 0.5;\n\t\tvec2 iuv = floor( uv );\n\t\tvec2 fuv = fract( uv );\n\t\tfloat g0x = g0( fuv.x );\n\t\tfloat g1x = g1( fuv.x );\n\t\tfloat h0x = h0( fuv.x );\n\t\tfloat h1x = h1( fuv.x );\n\t\tfloat h0y = h0( fuv.y );\n\t\tfloat h1y = h1( fuv.y );\n\t\tvec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\treturn g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +\n\t\t\tg1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );\n\t}\n\tvec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {\n\t\tvec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );\n\t\tvec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );\n\t\tvec2 fLodSizeInv = 1.0 / fLodSize;\n\t\tvec2 cLodSizeInv = 1.0 / cLodSize;\n\t\tvec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );\n\t\tvec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );\n\t\treturn mix( fSample, cSample, fract( lod ) );\n\t}\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\treturn textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );\n\t}\n\tvec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn vec3( 1.0 );\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec4 transmittedLight;\n\t\tvec3 transmittance;\n\t\t#ifdef USE_DISPERSION\n\t\t\tfloat halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;\n\t\t\tvec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );\n\t\t\tfor ( int i = 0; i < 3; i ++ ) {\n\t\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );\n\t\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\t\trefractionCoords += 1.0;\n\t\t\t\trefractionCoords /= 2.0;\n\t\t\t\tvec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );\n\t\t\t\ttransmittedLight[ i ] = transmissionSample[ i ];\n\t\t\t\ttransmittedLight.a += transmissionSample.a;\n\t\t\t\ttransmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];\n\t\t\t}\n\t\t\ttransmittedLight.a /= 3.0;\n\t\t#else\n\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\trefractionCoords += 1.0;\n\t\t\trefractionCoords /= 2.0;\n\t\t\ttransmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\t\ttransmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\t#endif\n\t\tvec3 attenuatedColor = transmittance * transmittedLight.rgb;\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\tfloat transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );\n\t}\n#endif",uv_pars_fragment:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif",uv_pars_vertex:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tuniform mat3 mapTransform;\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform mat3 alphaMapTransform;\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tuniform mat3 lightMapTransform;\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tuniform mat3 aoMapTransform;\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tuniform mat3 bumpMapTransform;\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tuniform mat3 normalMapTransform;\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tuniform mat3 displacementMapTransform;\n\tvarying vec2 vDisplacementMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tuniform mat3 emissiveMapTransform;\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tuniform mat3 metalnessMapTransform;\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tuniform mat3 roughnessMapTransform;\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tuniform mat3 anisotropyMapTransform;\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tuniform mat3 clearcoatMapTransform;\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform mat3 clearcoatNormalMapTransform;\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform mat3 clearcoatRoughnessMapTransform;\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tuniform mat3 sheenColorMapTransform;\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tuniform mat3 sheenRoughnessMapTransform;\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tuniform mat3 iridescenceMapTransform;\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform mat3 iridescenceThicknessMapTransform;\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tuniform mat3 specularMapTransform;\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tuniform mat3 specularColorMapTransform;\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tuniform mat3 specularIntensityMapTransform;\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif",uv_vertex:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvUv = vec3( uv, 1 ).xy;\n#endif\n#ifdef USE_MAP\n\tvMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ALPHAMAP\n\tvAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_LIGHTMAP\n\tvLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_AOMAP\n\tvAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_BUMPMAP\n\tvBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_NORMALMAP\n\tvNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tvDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_METALNESSMAP\n\tvMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULARMAP\n\tvSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tvTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_THICKNESSMAP\n\tvThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;\n#endif",worldpos_vertex:"#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_BATCHING\n\t\tworldPosition = batchingMatrix * worldPosition;\n\t#endif\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif",background_vert:"varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}",background_frag:"uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\ttexColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}",backgroundCube_vert:"varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}",backgroundCube_frag:"#ifdef ENVMAP_TYPE_CUBE\n\tuniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n\tuniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nuniform mat3 backgroundRotation;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );\n\t#else\n\t\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}",cube_vert:"varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}",cube_frag:"uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = texColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}",depth_vert:"#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <uv_vertex>\n\t#include <batching_vertex>\n\t#include <skinbase_vertex>\n\t#include <morphinstance_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvHighPrecisionZW = gl_Position.zw;\n}",depth_frag:"#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <clipping_planes_fragment>\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <logdepthbuf_fragment>\n\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\tfloat fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ];\n\t#else\n\t\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5;\n\t#endif\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#elif DEPTH_PACKING == 3202\n\t\tgl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );\n\t#elif DEPTH_PACKING == 3203\n\t\tgl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );\n\t#endif\n}",distance_vert:"#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <batching_vertex>\n\t#include <skinbase_vertex>\n\t#include <morphinstance_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}",distance_frag:"#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <clipping_planes_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = vec4( dist, 0.0, 0.0, 1.0 );\n}",equirect_vert:"varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}",equirect_frag:"uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}",linedashed_vert:"uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}",linedashed_frag:"uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}",meshbasic_vert:"#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinbase_vertex>\n\t\t#include <skinnormal_vertex>\n\t\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}",meshbasic_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshlambert_vert:"#define LAMBERT\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}",meshlambert_frag:"#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_lambert_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_lambert_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshmatcap_vert:"#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}",meshmatcap_frag:"#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshnormal_vert:"#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}",meshnormal_frag:"#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include <uv_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( normalize( normal ) * 0.5 + 0.5, diffuseColor.a );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}",meshphong_vert:"#define PHONG\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}",meshphong_frag:"#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshphysical_vert:"#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}",meshphysical_frag:"#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define USE_SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef USE_SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULAR_COLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_DISPERSION\n\tuniform float dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\tuniform vec2 anisotropyVector;\n\t#ifdef USE_ANISOTROPYMAP\n\t\tuniform sampler2D anisotropyMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <iridescence_fragment>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <transmission_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <iridescence_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n \n\t\toutgoingLight = outgoingLight + sheenSpecularDirect + sheenSpecularIndirect;\n \n \t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;\n\t#endif\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshtoon_vert:"#define TOON\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}",meshtoon_frag:"#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",points_vert:"uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n#ifdef USE_POINTS_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif\nvoid main() {\n\t#ifdef USE_POINTS_UV\n\t\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\t#endif\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}",points_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}",shadow_vert:"#include <common>\n#include <batching_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}",shadow_frag:"uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <logdepthbuf_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\t#include <logdepthbuf_fragment>\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n}",sprite_vert:"uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\tvec4 mvPosition = modelViewMatrix[ 3 ];\n\tvec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}",sprite_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n}"},Sl={common:{diffuse:{value:new $r(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new pi},alphaMap:{value:null},alphaMapTransform:{value:new pi},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new pi}},envmap:{envMap:{value:null},envMapRotation:{value:new pi},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new pi}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new pi}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new pi},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new pi},normalScale:{value:new li(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new pi},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new pi}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new pi}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new pi}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new $r(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new $r(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new pi},alphaTest:{value:0},uvTransform:{value:new pi}},sprite:{diffuse:{value:new $r(16777215)},opacity:{value:1},center:{value:new li(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new pi},alphaMap:{value:null},alphaMapTransform:{value:new pi},alphaTest:{value:0}}},Al={basic:{uniforms:ks([Sl.common,Sl.specularmap,Sl.envmap,Sl.aomap,Sl.lightmap,Sl.fog]),vertexShader:yl.meshbasic_vert,fragmentShader:yl.meshbasic_frag},lambert:{uniforms:ks([Sl.common,Sl.specularmap,Sl.envmap,Sl.aomap,Sl.lightmap,Sl.emissivemap,Sl.bumpmap,Sl.normalmap,Sl.displacementmap,Sl.fog,Sl.lights,{emissive:{value:new $r(0)}}]),vertexShader:yl.meshlambert_vert,fragmentShader:yl.meshlambert_frag},phong:{uniforms:ks([Sl.common,Sl.specularmap,Sl.envmap,Sl.aomap,Sl.lightmap,Sl.emissivemap,Sl.bumpmap,Sl.normalmap,Sl.displacementmap,Sl.fog,Sl.lights,{emissive:{value:new $r(0)},specular:{value:new $r(1118481)},shininess:{value:30}}]),vertexShader:yl.meshphong_vert,fragmentShader:yl.meshphong_frag},standard:{uniforms:ks([Sl.common,Sl.envmap,Sl.aomap,Sl.lightmap,Sl.emissivemap,Sl.bumpmap,Sl.normalmap,Sl.displacementmap,Sl.roughnessmap,Sl.metalnessmap,Sl.fog,Sl.lights,{emissive:{value:new $r(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:yl.meshphysical_vert,fragmentShader:yl.meshphysical_frag},toon:{uniforms:ks([Sl.common,Sl.aomap,Sl.lightmap,Sl.emissivemap,Sl.bumpmap,Sl.normalmap,Sl.displacementmap,Sl.gradientmap,Sl.fog,Sl.lights,{emissive:{value:new $r(0)}}]),vertexShader:yl.meshtoon_vert,fragmentShader:yl.meshtoon_frag},matcap:{uniforms:ks([Sl.common,Sl.bumpmap,Sl.normalmap,Sl.displacementmap,Sl.fog,{matcap:{value:null}}]),vertexShader:yl.meshmatcap_vert,fragmentShader:yl.meshmatcap_frag},points:{uniforms:ks([Sl.points,Sl.fog]),vertexShader:yl.points_vert,fragmentShader:yl.points_frag},dashed:{uniforms:ks([Sl.common,Sl.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:yl.linedashed_vert,fragmentShader:yl.linedashed_frag},depth:{uniforms:ks([Sl.common,Sl.displacementmap]),vertexShader:yl.depth_vert,fragmentShader:yl.depth_frag},normal:{uniforms:ks([Sl.common,Sl.bumpmap,Sl.normalmap,Sl.displacementmap,{opacity:{value:1}}]),vertexShader:yl.meshnormal_vert,fragmentShader:yl.meshnormal_frag},sprite:{uniforms:ks([Sl.sprite,Sl.fog]),vertexShader:yl.sprite_vert,fragmentShader:yl.sprite_frag},background:{uniforms:{uvTransform:{value:new pi},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:yl.background_vert,fragmentShader:yl.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new pi}},vertexShader:yl.backgroundCube_vert,fragmentShader:yl.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:yl.cube_vert,fragmentShader:yl.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:yl.equirect_vert,fragmentShader:yl.equirect_frag},distance:{uniforms:ks([Sl.common,Sl.displacementmap,{referencePosition:{value:new hi},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:yl.distance_vert,fragmentShader:yl.distance_frag},shadow:{uniforms:ks([Sl.lights,Sl.fog,{color:{value:new $r(0)},opacity:{value:1}}]),vertexShader:yl.shadow_vert,fragmentShader:yl.shadow_frag}};Al.physical={uniforms:ks([Al.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new pi},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new pi},clearcoatNormalScale:{value:new li(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new pi},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new pi},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new pi},sheen:{value:0},sheenColor:{value:new $r(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new pi},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new pi},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new pi},transmissionSamplerSize:{value:new li},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new pi},attenuationDistance:{value:0},attenuationColor:{value:new $r(0)},specularColor:{value:new $r(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new pi},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new pi},anisotropyVector:{value:new li},anisotropyMap:{value:null},anisotropyMapTransform:{value:new pi}}]),vertexShader:yl.meshphysical_vert,fragmentShader:yl.meshphysical_frag};const bl={r:0,b:0,g:0},Ml=new _r,wl=new or;function Tl(e,t,n,i,r,s,a){const o=new $r(0);let l,c,h=!0===s?0:1,u=null,d=0,p=null;function f(e){let i=!0===e.isScene?e.background:null;if(i&&i.isTexture){i=(e.backgroundBlurriness>0?n:t).get(i)}return i}function m(t,n){t.getRGB(bl,Ns(e)),i.buffers.color.setClear(bl.r,bl.g,bl.b,n,a)}return{getClearColor:function(){return o},setClearColor:function(e,t=1){o.set(e),h=t,m(o,h)},getClearAlpha:function(){return h},setClearAlpha:function(e){h=e,m(o,h)},render:function(t){let n=!1;const r=f(t);null===r?m(o,h):r&&r.isColor&&(m(r,1),n=!0);const s=e.xr.getEnvironmentBlendMode();"additive"===s?i.buffers.color.setClear(0,0,0,1,a):"alpha-blend"===s&&i.buffers.color.setClear(0,0,0,0,a),(e.autoClear||n)&&(i.buffers.depth.setTest(!0),i.buffers.depth.setMask(!0),i.buffers.color.setMask(!0),e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil))},addToRenderList:function(t,n){const i=f(n);i&&(i.isCubeTexture||i.mapping===et)?(void 0===c&&(c=new Bs(new Fs(1,1,1),new zs({name:"BackgroundCubeMaterial",uniforms:Us(Al.backgroundCube.uniforms),vertexShader:Al.backgroundCube.vertexShader,fragmentShader:Al.backgroundCube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute("normal"),c.geometry.deleteAttribute("uv"),c.onBeforeRender=function(e,t,n){this.matrixWorld.copyPosition(n.matrixWorld)},Object.defineProperty(c.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),r.update(c)),Ml.copy(n.backgroundRotation),Ml.x*=-1,Ml.y*=-1,Ml.z*=-1,i.isCubeTexture&&!1===i.isRenderTargetTexture&&(Ml.y*=-1,Ml.z*=-1),c.material.uniforms.envMap.value=i,c.material.uniforms.flipEnvMap.value=i.isCubeTexture&&!1===i.isRenderTargetTexture?-1:1,c.material.uniforms.backgroundBlurriness.value=n.backgroundBlurriness,c.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,c.material.uniforms.backgroundRotation.value.setFromMatrix4(wl.makeRotationFromEuler(Ml)),c.material.toneMapped=vi.getTransfer(i.colorSpace)!==En,u===i&&d===i.version&&p===e.toneMapping||(c.material.needsUpdate=!0,u=i,d=i.version,p=e.toneMapping),c.layers.enableAll(),t.unshift(c,c.geometry,c.material,0,0,null)):i&&i.isTexture&&(void 0===l&&(l=new Bs(new so(2,2),new zs({name:"BackgroundMaterial",uniforms:Us(Al.background.uniforms),vertexShader:Al.background.vertexShader,fragmentShader:Al.background.fragmentShader,side:0,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),r.update(l)),l.material.uniforms.t2D.value=i,l.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,l.material.toneMapped=vi.getTransfer(i.colorSpace)!==En,!0===i.matrixAutoUpdate&&i.updateMatrix(),l.material.uniforms.uvTransform.value.copy(i.matrix),u===i&&d===i.version&&p===e.toneMapping||(l.material.needsUpdate=!0,u=i,d=i.version,p=e.toneMapping),l.layers.enableAll(),t.unshift(l,l.geometry,l.material,0,0,null))},dispose:function(){void 0!==c&&(c.geometry.dispose(),c.material.dispose(),c=void 0),void 0!==l&&(l.geometry.dispose(),l.material.dispose(),l=void 0)}}}function El(e,t){const n=e.getParameter(e.MAX_VERTEX_ATTRIBS),i={},r=c(null);let s=r,a=!1;function o(t){return e.bindVertexArray(t)}function l(t){return e.deleteVertexArray(t)}function c(e){const t=[],i=[],r=[];for(let s=0;s<n;s++)t[s]=0,i[s]=0,r[s]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:t,enabledAttributes:i,attributeDivisors:r,object:e,attributes:{},index:null}}function h(){const e=s.newAttributes;for(let t=0,n=e.length;t<n;t++)e[t]=0}function u(e){d(e,0)}function d(t,n){const i=s.newAttributes,r=s.enabledAttributes,a=s.attributeDivisors;i[t]=1,0===r[t]&&(e.enableVertexAttribArray(t),r[t]=1),a[t]!==n&&(e.vertexAttribDivisor(t,n),a[t]=n)}function p(){const t=s.newAttributes,n=s.enabledAttributes;for(let i=0,r=n.length;i<r;i++)n[i]!==t[i]&&(e.disableVertexAttribArray(i),n[i]=0)}function f(t,n,i,r,s,a,o){!0===o?e.vertexAttribIPointer(t,n,i,s,a):e.vertexAttribPointer(t,n,i,r,s,a)}function m(){g(),a=!0,s!==r&&(s=r,o(s.object))}function g(){r.geometry=null,r.program=null,r.wireframe=!1}return{setup:function(n,r,l,m,g){let _=!1;const v=function(t,n,r){const s=!0===r.wireframe;let a=i[t.id];void 0===a&&(a={},i[t.id]=a);let o=a[n.id];void 0===o&&(o={},a[n.id]=o);let l=o[s];void 0===l&&(l=c(e.createVertexArray()),o[s]=l);return l}(m,l,r);s!==v&&(s=v,o(s.object)),_=function(e,t,n,i){const r=s.attributes,a=t.attributes;let o=0;const l=n.getAttributes();for(const s in l){if(l[s].location>=0){const t=r[s];let n=a[s];if(void 0===n&&("instanceMatrix"===s&&e.instanceMatrix&&(n=e.instanceMatrix),"instanceColor"===s&&e.instanceColor&&(n=e.instanceColor)),void 0===t)return!0;if(t.attribute!==n)return!0;if(n&&t.data!==n.data)return!0;o++}}return s.attributesNum!==o||s.index!==i}(n,m,l,g),_&&function(e,t,n,i){const r={},a=t.attributes;let o=0;const l=n.getAttributes();for(const s in l){if(l[s].location>=0){let t=a[s];void 0===t&&("instanceMatrix"===s&&e.instanceMatrix&&(t=e.instanceMatrix),"instanceColor"===s&&e.instanceColor&&(t=e.instanceColor));const n={};n.attribute=t,t&&t.data&&(n.data=t.data),r[s]=n,o++}}s.attributes=r,s.attributesNum=o,s.index=i}(n,m,l,g),null!==g&&t.update(g,e.ELEMENT_ARRAY_BUFFER),(_||a)&&(a=!1,function(n,i,r,s){h();const a=s.attributes,o=r.getAttributes(),l=i.defaultAttributeValues;for(const c in o){const i=o[c];if(i.location>=0){let r=a[c];if(void 0===r&&("instanceMatrix"===c&&n.instanceMatrix&&(r=n.instanceMatrix),"instanceColor"===c&&n.instanceColor&&(r=n.instanceColor)),void 0!==r){const a=r.normalized,o=r.itemSize,l=t.get(r);if(void 0===l)continue;const c=l.buffer,h=l.type,p=l.bytesPerElement,m=h===e.INT||h===e.UNSIGNED_INT||r.gpuType===ft;if(r.isInterleavedBufferAttribute){const t=r.data,l=t.stride,g=r.offset;if(t.isInstancedInterleavedBuffer){for(let e=0;e<i.locationSize;e++)d(i.location+e,t.meshPerAttribute);!0!==n.isInstancedMesh&&void 0===s._maxInstanceCount&&(s._maxInstanceCount=t.meshPerAttribute*t.count)}else for(let e=0;e<i.locationSize;e++)u(i.location+e);e.bindBuffer(e.ARRAY_BUFFER,c);for(let e=0;e<i.locationSize;e++)f(i.location+e,o/i.locationSize,h,a,l*p,(g+o/i.locationSize*e)*p,m)}else{if(r.isInstancedBufferAttribute){for(let e=0;e<i.locationSize;e++)d(i.location+e,r.meshPerAttribute);!0!==n.isInstancedMesh&&void 0===s._maxInstanceCount&&(s._maxInstanceCount=r.meshPerAttribute*r.count)}else for(let e=0;e<i.locationSize;e++)u(i.location+e);e.bindBuffer(e.ARRAY_BUFFER,c);for(let e=0;e<i.locationSize;e++)f(i.location+e,o/i.locationSize,h,a,o*p,o/i.locationSize*e*p,m)}}else if(void 0!==l){const t=l[c];if(void 0!==t)switch(t.length){case 2:e.vertexAttrib2fv(i.location,t);break;case 3:e.vertexAttrib3fv(i.location,t);break;case 4:e.vertexAttrib4fv(i.location,t);break;default:e.vertexAttrib1fv(i.location,t)}}}}p()}(n,r,l,m),null!==g&&e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t.get(g).buffer))},reset:m,resetDefaultState:g,dispose:function(){m();for(const e in i){const t=i[e];for(const e in t){const n=t[e];for(const e in n)l(n[e].object),delete n[e];delete t[e]}delete i[e]}},releaseStatesOfGeometry:function(e){if(void 0===i[e.id])return;const t=i[e.id];for(const n in t){const e=t[n];for(const t in e)l(e[t].object),delete e[t];delete t[n]}delete i[e.id]},releaseStatesOfProgram:function(e){for(const t in i){const n=i[t];if(void 0===n[e.id])continue;const r=n[e.id];for(const e in r)l(r[e].object),delete r[e];delete n[e.id]}},initAttributes:h,enableAttribute:u,disableUnusedAttributes:p}}function Cl(e,t,n){let i;function r(t,r,s){0!==s&&(e.drawArraysInstanced(i,t,r,s),n.update(r,i,s))}this.setMode=function(e){i=e},this.render=function(t,r){e.drawArrays(i,t,r),n.update(r,i,1)},this.renderInstances=r,this.renderMultiDraw=function(e,r,s){if(0===s)return;t.get("WEBGL_multi_draw").multiDrawArraysWEBGL(i,e,0,r,0,s);let a=0;for(let t=0;t<s;t++)a+=r[t];n.update(a,i,1)},this.renderMultiDrawInstances=function(e,s,a,o){if(0===a)return;const l=t.get("WEBGL_multi_draw");if(null===l)for(let t=0;t<e.length;t++)r(e[t],s[t],o[t]);else{l.multiDrawArraysInstancedWEBGL(i,e,0,s,0,o,0,a);let t=0;for(let e=0;e<a;e++)t+=s[e]*o[e];n.update(t,i,1)}}}function Rl(e,t,n,i){let r;function s(t){if("highp"===t){if(e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.HIGH_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0)return"highp";t="mediump"}return"mediump"===t&&e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let a=void 0!==n.precision?n.precision:"highp";const o=s(a);o!==a&&(qn("WebGLRenderer:",a,"not supported, using",o,"instead."),a=o);return{isWebGL2:!0,getMaxAnisotropy:function(){if(void 0!==r)return r;if(!0===t.has("EXT_texture_filter_anisotropic")){const n=t.get("EXT_texture_filter_anisotropic");r=e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else r=0;return r},getMaxPrecision:s,textureFormatReadable:function(t){return t===bt||i.convert(t)===e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)},textureTypeReadable:function(n){const r=n===_t&&(t.has("EXT_color_buffer_half_float")||t.has("EXT_color_buffer_float"));return!(n!==ht&&i.convert(n)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)&&n!==gt&&!r)},precision:a,logarithmicDepthBuffer:!0===n.logarithmicDepthBuffer,reversedDepthBuffer:!0===n.reversedDepthBuffer&&t.has("EXT_clip_control"),maxTextures:e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),maxVertexTextures:e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS),maxTextureSize:e.getParameter(e.MAX_TEXTURE_SIZE),maxCubemapSize:e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),maxAttributes:e.getParameter(e.MAX_VERTEX_ATTRIBS),maxVertexUniforms:e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),maxVaryings:e.getParameter(e.MAX_VARYING_VECTORS),maxFragmentUniforms:e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),maxSamples:e.getParameter(e.MAX_SAMPLES),samples:e.getParameter(e.SAMPLES)}}function Il(e){const t=this;let n=null,i=0,r=!1,s=!1;const a=new Ia,o=new pi,l={value:null,needsUpdate:!1};function c(e,n,i,r){const s=null!==e?e.length:0;let c=null;if(0!==s){if(c=l.value,!0!==r||null===c){const t=i+4*s,r=n.matrixWorldInverse;o.getNormalMatrix(r),(null===c||c.length<t)&&(c=new Float32Array(t));for(let n=0,l=i;n!==s;++n,l+=4)a.copy(e[n]).applyMatrix4(r,o),a.normal.toArray(c,l),c[l+3]=a.constant}l.value=c,l.needsUpdate=!0}return t.numPlanes=s,t.numIntersection=0,c}this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(e,t){const n=0!==e.length||t||0!==i||r;return r=t,i=e.length,n},this.beginShadows=function(){s=!0,c(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(e,t){n=c(e,t,0)},this.setState=function(a,o,h){const u=a.clippingPlanes,d=a.clipIntersection,p=a.clipShadows,f=e.get(a);if(!r||null===u||0===u.length||s&&!p)s?c(null):function(){l.value!==n&&(l.value=n,l.needsUpdate=i>0);t.numPlanes=i,t.numIntersection=0}();else{const e=s?0:i,t=4*e;let r=f.clippingState||null;l.value=r,r=c(u,o,t,h);for(let i=0;i!==t;++i)r[i]=n[i];f.clippingState=r,this.numIntersection=d?this.numPlanes:0,this.numPlanes+=e}}}function Pl(e){let t=new WeakMap;function n(e,t){return 303===t?e.mapping=Je:304===t&&(e.mapping=$e),e}function i(e){const n=e.target;n.removeEventListener("dispose",i);const r=t.get(n);void 0!==r&&(t.delete(n),r.dispose())}return{get:function(r){if(r&&r.isTexture){const s=r.mapping;if(303===s||304===s){if(t.has(r)){return n(t.get(r).texture,r.mapping)}{const s=r.image;if(s&&s.height>0){const a=new Ks(s.height);return a.fromEquirectangularTexture(e,r),t.set(r,a),r.addEventListener("dispose",i),n(a.texture,r.mapping)}return null}}}return r},dispose:function(){t=new WeakMap}}}const Dl=[.125,.215,.35,.446,.526,.582],Bl=20,Ll=new Ko,Fl=new $r;let Ul=null,kl=0,Nl=0,Ol=!1;const zl=new hi;class Hl{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._backgroundBox=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null}fromScene(e,t=0,n=.1,i=100,r={}){const{size:s=256,position:a=zl}=r;Ul=this._renderer.getRenderTarget(),kl=this._renderer.getActiveCubeFace(),Nl=this._renderer.getActiveMipmapLevel(),Ol=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(s);const o=this._allocateTargets();return o.depthBuffer=!0,this._sceneToCubeUV(e,n,i,o,a),t>0&&this._blur(o,0,0,t),this._applyPMREM(o),this._cleanup(o),o}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=jl(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=Wl(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),null!==this._cubemapMaterial&&this._cubemapMaterial.dispose(),null!==this._equirectMaterial&&this._equirectMaterial.dispose(),null!==this._backgroundBox&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){null!==this._blurMaterial&&this._blurMaterial.dispose(),null!==this._ggxMaterial&&this._ggxMaterial.dispose(),null!==this._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodMeshes.length;e++)this._lodMeshes[e].geometry.dispose()}_cleanup(e){this._renderer.setRenderTarget(Ul,kl,Nl),this._renderer.xr.enabled=Ol,e.scissorTest=!1,Gl(e,0,0,e.width,e.height)}_fromTexture(e,t){e.mapping===Je||e.mapping===$e?this._setSize(0===e.image.length?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),Ul=this._renderer.getRenderTarget(),kl=this._renderer.getActiveCubeFace(),Nl=this._renderer.getActiveMipmapLevel(),Ol=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;const n=t||this._allocateTargets();return this._textureToCubeUV(e,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTargets(){const e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize,n={magFilter:ot,minFilter:ot,generateMipmaps:!1,type:_t,format:bt,colorSpace:wn,depthBuffer:!1},i=Vl(e,t,n);if(null===this._pingPongRenderTarget||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){null!==this._pingPongRenderTarget&&this._dispose(),this._pingPongRenderTarget=Vl(e,t,n);const{_lodMax:i}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods,sigmas:this._sigmas}=function(e){const t=[],n=[],i=[];let r=e;const s=e-4+1+Dl.length;for(let a=0;a<s;a++){const s=Math.pow(2,r);t.push(s);let o=1/s;a>e-4?o=Dl[a-e+4-1]:0===a&&(o=0),n.push(o);const l=1/(s-2),c=-l,h=1+l,u=[c,c,h,c,h,h,c,c,h,h,c,h],d=6,p=6,f=3,m=2,g=1,_=new Float32Array(f*p*d),v=new Float32Array(m*p*d),x=new Float32Array(g*p*d);for(let e=0;e<d;e++){const t=e%3*2/3-1,n=e>2?0:-1,i=[t,n,0,t+2/3,n,0,t+2/3,n+1,0,t,n,0,t+2/3,n+1,0,t,n+1,0];_.set(i,f*p*e),v.set(u,m*p*e);const r=[e,e,e,e,e,e];x.set(r,g*p*e)}const y=new Ss;y.setAttribute("position",new hs(_,f)),y.setAttribute("uv",new hs(v,m)),y.setAttribute("faceIndex",new hs(x,g)),i.push(new Bs(y,null)),r>4&&r--}return{lodMeshes:i,sizeLods:t,sigmas:n}}(i)),this._blurMaterial=function(e,t,n){const i=new Float32Array(Bl),r=new hi(0,1,0),s=new zs({name:"SphericalGaussianBlur",defines:{n:Bl,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:i},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:r}},vertexShader:Xl(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform int samples;\n\t\t\tuniform float weights[ n ];\n\t\t\tuniform bool latitudinal;\n\t\t\tuniform float dTheta;\n\t\t\tuniform float mipInt;\n\t\t\tuniform vec3 poleAxis;\n\n\t\t\t#define ENVMAP_TYPE_CUBE_UV\n\t\t\t#include <cube_uv_reflection_fragment>\n\n\t\t\tvec3 getSample( float theta, vec3 axis ) {\n\n\t\t\t\tfloat cosTheta = cos( theta );\n\t\t\t\t// Rodrigues' axis-angle rotation\n\t\t\t\tvec3 sampleDirection = vOutputDirection * cosTheta\n\t\t\t\t\t+ cross( axis, vOutputDirection ) * sin( theta )\n\t\t\t\t\t+ axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );\n\n\t\t\t\treturn bilinearCubeUV( envMap, sampleDirection, mipInt );\n\n\t\t\t}\n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );\n\n\t\t\t\tif ( all( equal( axis, vec3( 0.0 ) ) ) ) {\n\n\t\t\t\t\taxis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );\n\n\t\t\t\t}\n\n\t\t\t\taxis = normalize( axis );\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t\t\t\tgl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );\n\n\t\t\t\tfor ( int i = 1; i < n; i++ ) {\n\n\t\t\t\t\tif ( i >= samples ) {\n\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tfloat theta = dTheta * float( i );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( theta, axis );\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1});return s}(i,e,t),this._ggxMaterial=function(e,t,n){const i=new zs({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:256,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:Xl(),fragmentShader:'\n\n\t\t\tprecision highp float;\n\t\t\tprecision highp int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform float roughness;\n\t\t\tuniform float mipInt;\n\n\t\t\t#define ENVMAP_TYPE_CUBE_UV\n\t\t\t#include <cube_uv_reflection_fragment>\n\n\t\t\t#define PI 3.14159265359\n\n\t\t\t// Van der Corput radical inverse\n\t\t\tfloat radicalInverse_VdC(uint bits) {\n\t\t\t\tbits = (bits << 16u) | (bits >> 16u);\n\t\t\t\tbits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);\n\t\t\t\tbits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);\n\t\t\t\tbits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);\n\t\t\t\tbits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);\n\t\t\t\treturn float(bits) * 2.3283064365386963e-10; // / 0x100000000\n\t\t\t}\n\n\t\t\t// Hammersley sequence\n\t\t\tvec2 hammersley(uint i, uint N) {\n\t\t\t\treturn vec2(float(i) / float(N), radicalInverse_VdC(i));\n\t\t\t}\n\n\t\t\t// GGX VNDF importance sampling (Eric Heitz 2018)\n\t\t\t// "Sampling the GGX Distribution of Visible Normals"\n\t\t\t// https://jcgt.org/published/0007/04/01/\n\t\t\tvec3 importanceSampleGGX_VNDF(vec2 Xi, vec3 V, float roughness) {\n\t\t\t\tfloat alpha = roughness * roughness;\n\n\t\t\t\t// Section 3.2: Transform view direction to hemisphere configuration\n\t\t\t\tvec3 Vh = normalize(vec3(alpha * V.x, alpha * V.y, V.z));\n\n\t\t\t\t// Section 4.1: Orthonormal basis\n\t\t\t\tfloat lensq = Vh.x * Vh.x + Vh.y * Vh.y;\n\t\t\t\tvec3 T1 = lensq > 0.0 ? vec3(-Vh.y, Vh.x, 0.0) / sqrt(lensq) : vec3(1.0, 0.0, 0.0);\n\t\t\t\tvec3 T2 = cross(Vh, T1);\n\n\t\t\t\t// Section 4.2: Parameterization of projected area\n\t\t\t\tfloat r = sqrt(Xi.x);\n\t\t\t\tfloat phi = 2.0 * PI * Xi.y;\n\t\t\t\tfloat t1 = r * cos(phi);\n\t\t\t\tfloat t2 = r * sin(phi);\n\t\t\t\tfloat s = 0.5 * (1.0 + Vh.z);\n\t\t\t\tt2 = (1.0 - s) * sqrt(1.0 - t1 * t1) + s * t2;\n\n\t\t\t\t// Section 4.3: Reprojection onto hemisphere\n\t\t\t\tvec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * Vh;\n\n\t\t\t\t// Section 3.4: Transform back to ellipsoid configuration\n\t\t\t\treturn normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z)));\n\t\t\t}\n\n\t\t\tvoid main() {\n\t\t\t\tvec3 N = normalize(vOutputDirection);\n\t\t\t\tvec3 V = N; // Assume view direction equals normal for pre-filtering\n\n\t\t\t\tvec3 prefilteredColor = vec3(0.0);\n\t\t\t\tfloat totalWeight = 0.0;\n\n\t\t\t\t// For very low roughness, just sample the environment directly\n\t\t\t\tif (roughness < 0.001) {\n\t\t\t\t\tgl_FragColor = vec4(bilinearCubeUV(envMap, N, mipInt), 1.0);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// Tangent space basis for VNDF sampling\n\t\t\t\tvec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);\n\t\t\t\tvec3 tangent = normalize(cross(up, N));\n\t\t\t\tvec3 bitangent = cross(N, tangent);\n\n\t\t\t\tfor(uint i = 0u; i < uint(GGX_SAMPLES); i++) {\n\t\t\t\t\tvec2 Xi = hammersley(i, uint(GGX_SAMPLES));\n\n\t\t\t\t\t// For PMREM, V = N, so in tangent space V is always (0, 0, 1)\n\t\t\t\t\tvec3 H_tangent = importanceSampleGGX_VNDF(Xi, vec3(0.0, 0.0, 1.0), roughness);\n\n\t\t\t\t\t// Transform H back to world space\n\t\t\t\t\tvec3 H = normalize(tangent * H_tangent.x + bitangent * H_tangent.y + N * H_tangent.z);\n\t\t\t\t\tvec3 L = normalize(2.0 * dot(V, H) * H - V);\n\n\t\t\t\t\tfloat NdotL = max(dot(N, L), 0.0);\n\n\t\t\t\t\tif(NdotL > 0.0) {\n\t\t\t\t\t\t// Sample environment at fixed mip level\n\t\t\t\t\t\t// VNDF importance sampling handles the distribution filtering\n\t\t\t\t\t\tvec3 sampleColor = bilinearCubeUV(envMap, L, mipInt);\n\n\t\t\t\t\t\t// Weight by NdotL for the split-sum approximation\n\t\t\t\t\t\t// VNDF PDF naturally accounts for the visible microfacet distribution\n\t\t\t\t\t\tprefilteredColor += sampleColor * NdotL;\n\t\t\t\t\t\ttotalWeight += NdotL;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (totalWeight > 0.0) {\n\t\t\t\t\tprefilteredColor = prefilteredColor / totalWeight;\n\t\t\t\t}\n\n\t\t\t\tgl_FragColor = vec4(prefilteredColor, 1.0);\n\t\t\t}\n\t\t',blending:0,depthTest:!1,depthWrite:!1});return i}(i,e,t)}return i}_compileMaterial(e){const t=new Bs(new Ss,e);this._renderer.compile(t,Ll)}_sceneToCubeUV(e,t,n,i,r){const s=new js(90,1,t,n),a=[1,-1,1,1,1,1],o=[1,1,1,-1,-1,-1],l=this._renderer,c=l.autoClear,h=l.toneMapping;l.getClearColor(Fl),l.toneMapping=0,l.autoClear=!1;l.state.buffers.depth.getReversed()&&(l.setRenderTarget(i),l.clearDepth(),l.setRenderTarget(null)),null===this._backgroundBox&&(this._backgroundBox=new Bs(new Fs,new is({name:"PMREM.Background",side:1,depthWrite:!1,depthTest:!1})));const u=this._backgroundBox,d=u.material;let p=!1;const f=e.background;f?f.isColor&&(d.color.copy(f),e.background=null,p=!0):(d.color.copy(Fl),p=!0);for(let m=0;m<6;m++){const t=m%3;0===t?(s.up.set(0,a[m],0),s.position.set(r.x,r.y,r.z),s.lookAt(r.x+o[m],r.y,r.z)):1===t?(s.up.set(0,0,a[m]),s.position.set(r.x,r.y,r.z),s.lookAt(r.x,r.y+o[m],r.z)):(s.up.set(0,a[m],0),s.position.set(r.x,r.y,r.z),s.lookAt(r.x,r.y,r.z+o[m]));const n=this._cubeSize;Gl(i,t*n,m>2?n:0,n,n),l.setRenderTarget(i),p&&l.render(u,s),l.render(e,s)}l.toneMapping=h,l.autoClear=c,e.background=f}_textureToCubeUV(e,t){const n=this._renderer,i=e.mapping===Je||e.mapping===$e;i?(null===this._cubemapMaterial&&(this._cubemapMaterial=jl()),this._cubemapMaterial.uniforms.flipEnvMap.value=!1===e.isRenderTargetTexture?-1:1):null===this._equirectMaterial&&(this._equirectMaterial=Wl());const r=i?this._cubemapMaterial:this._equirectMaterial,s=this._lodMeshes[0];s.material=r;r.uniforms.envMap.value=e;const a=this._cubeSize;Gl(t,0,0,3*a,2*a),n.setRenderTarget(t),n.render(s,Ll)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;const i=this._lodMeshes.length;for(let r=1;r<i;r++)this._applyGGXFilter(e,r-1,r);t.autoClear=n}_applyGGXFilter(e,t,n){const i=this._renderer,r=this._pingPongRenderTarget,s=this._ggxMaterial,a=this._lodMeshes[n];a.material=s;const o=s.uniforms,l=n/(this._lodMeshes.length-1),c=t/(this._lodMeshes.length-1),h=Math.sqrt(l*l-c*c)*(0+1.25*l),{_lodMax:u}=this,d=this._sizeLods[n],p=3*d*(n>u-4?n-u+4:0),f=4*(this._cubeSize-d);o.envMap.value=e.texture,o.roughness.value=h,o.mipInt.value=u-t,Gl(r,p,f,3*d,2*d),i.setRenderTarget(r),i.render(a,Ll),o.envMap.value=r.texture,o.roughness.value=0,o.mipInt.value=u-n,Gl(e,p,f,3*d,2*d),i.setRenderTarget(e),i.render(a,Ll)}_blur(e,t,n,i,r){const s=this._pingPongRenderTarget;this._halfBlur(e,s,t,n,i,"latitudinal",r),this._halfBlur(s,e,n,n,i,"longitudinal",r)}_halfBlur(e,t,n,i,r,s,a){const o=this._renderer,l=this._blurMaterial;"latitudinal"!==s&&"longitudinal"!==s&&Qn("blur direction must be either latitudinal or longitudinal!");const c=this._lodMeshes[i];c.material=l;const h=l.uniforms,u=this._sizeLods[n]-1,d=isFinite(r)?Math.PI/(2*u):2*Math.PI/39,p=r/d,f=isFinite(r)?1+Math.floor(3*p):Bl;f>Bl&&qn(`sigmaRadians, ${r}, is too large and will clip, as it requested ${f} samples when the maximum is set to 20`);const m=[];let g=0;for(let x=0;x<Bl;++x){const e=x/p,t=Math.exp(-e*e/2);m.push(t),0===x?g+=t:x<f&&(g+=2*t)}for(let x=0;x<m.length;x++)m[x]=m[x]/g;h.envMap.value=e.texture,h.samples.value=f,h.weights.value=m,h.latitudinal.value="latitudinal"===s,a&&(h.poleAxis.value=a);const{_lodMax:_}=this;h.dTheta.value=d,h.mipInt.value=_-n;const v=this._sizeLods[i];Gl(t,3*v*(i>_-4?i-_+4:0),4*(this._cubeSize-v),3*v,2*v),o.setRenderTarget(t),o.render(c,Ll)}}function Vl(e,t,n){const i=new Pi(e,t,n);return i.texture.mapping=et,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function Gl(e,t,n,i,r){e.viewport.set(t,n,i,r),e.scissor.set(t,n,i,r)}function Wl(){return new zs({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:Xl(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\n\t\t\t#include <common>\n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 outputDirection = normalize( vOutputDirection );\n\t\t\t\tvec2 uv = equirectUv( outputDirection );\n\n\t\t\t\tgl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1})}function jl(){return new zs({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Xl(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tuniform float flipEnvMap;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform samplerCube envMap;\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1})}function Xl(){return"\n\n\t\tprecision mediump float;\n\t\tprecision mediump int;\n\n\t\tattribute float faceIndex;\n\n\t\tvarying vec3 vOutputDirection;\n\n\t\t// RH coordinate system; PMREM face-indexing convention\n\t\tvec3 getDirection( vec2 uv, float face ) {\n\n\t\t\tuv = 2.0 * uv - 1.0;\n\n\t\t\tvec3 direction = vec3( uv, 1.0 );\n\n\t\t\tif ( face == 0.0 ) {\n\n\t\t\t\tdirection = direction.zyx; // ( 1, v, u ) pos x\n\n\t\t\t} else if ( face == 1.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xz *= -1.0; // ( -u, 1, -v ) pos y\n\n\t\t\t} else if ( face == 2.0 ) {\n\n\t\t\t\tdirection.x *= -1.0; // ( -u, v, 1 ) pos z\n\n\t\t\t} else if ( face == 3.0 ) {\n\n\t\t\t\tdirection = direction.zyx;\n\t\t\t\tdirection.xz *= -1.0; // ( -1, v, -u ) neg x\n\n\t\t\t} else if ( face == 4.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xy *= -1.0; // ( -u, -1, v ) neg y\n\n\t\t\t} else if ( face == 5.0 ) {\n\n\t\t\t\tdirection.z *= -1.0; // ( u, v, -1 ) neg z\n\n\t\t\t}\n\n\t\t\treturn direction;\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\tvOutputDirection = getDirection( uv, faceIndex );\n\t\t\tgl_Position = vec4( position, 1.0 );\n\n\t\t}\n\t"}function ql(e){let t=new WeakMap,n=null;function i(e){const n=e.target;n.removeEventListener("dispose",i);const r=t.get(n);void 0!==r&&(t.delete(n),r.dispose())}return{get:function(r){if(r&&r.isTexture){const s=r.mapping,a=303===s||304===s,o=s===Je||s===$e;if(a||o){let s=t.get(r);const l=void 0!==s?s.texture.pmremVersion:0;if(r.isRenderTargetTexture&&r.pmremVersion!==l)return null===n&&(n=new Hl(e)),s=a?n.fromEquirectangular(r,s):n.fromCubemap(r,s),s.texture.pmremVersion=r.pmremVersion,t.set(r,s),s.texture;if(void 0!==s)return s.texture;{const l=r.image;return a&&l&&l.height>0||o&&l&&function(e){let t=0;const n=6;for(let i=0;i<n;i++)void 0!==e[i]&&t++;return t===n}(l)?(null===n&&(n=new Hl(e)),s=a?n.fromEquirectangular(r):n.fromCubemap(r),s.texture.pmremVersion=r.pmremVersion,t.set(r,s),r.addEventListener("dispose",i),s.texture):null}}}return r},dispose:function(){t=new WeakMap,null!==n&&(n.dispose(),n=null)}}}function Ql(e){const t={};function n(n){if(void 0!==t[n])return t[n];const i=e.getExtension(n);return t[n]=i,i}return{has:function(e){return null!==n(e)},init:function(){n("EXT_color_buffer_float"),n("WEBGL_clip_cull_distance"),n("OES_texture_float_linear"),n("EXT_color_buffer_half_float"),n("WEBGL_multisampled_render_to_texture"),n("WEBGL_render_shared_exponent")},get:function(e){const t=n(e);return null===t&&Kn("WebGLRenderer: "+e+" extension not supported."),t}}}function Kl(e,t,n,i){const r={},s=new WeakMap;function a(e){const o=e.target;null!==o.index&&t.remove(o.index);for(const n in o.attributes)t.remove(o.attributes[n]);o.removeEventListener("dispose",a),delete r[o.id];const l=s.get(o);l&&(t.remove(l),s.delete(o)),i.releaseStatesOfGeometry(o),!0===o.isInstancedBufferGeometry&&delete o._maxInstanceCount,n.memory.geometries--}function o(e){const n=[],i=e.index,r=e.attributes.position;let a=0;if(null!==i){const e=i.array;a=i.version;for(let t=0,i=e.length;t<i;t+=3){const i=e[t+0],r=e[t+1],s=e[t+2];n.push(i,r,r,s,s,i)}}else{if(void 0===r)return;{const e=r.array;a=r.version;for(let t=0,i=e.length/3-1;t<i;t+=3){const e=t+0,i=t+1,r=t+2;n.push(e,i,i,r,r,e)}}}const o=new(Vn(n)?ds:us)(n,1);o.version=a;const l=s.get(e);l&&t.remove(l),s.set(e,o)}return{get:function(e,t){return!0===r[t.id]||(t.addEventListener("dispose",a),r[t.id]=!0,n.memory.geometries++),t},update:function(n){const i=n.attributes;for(const r in i)t.update(i[r],e.ARRAY_BUFFER)},getWireframeAttribute:function(e){const t=s.get(e);if(t){const n=e.index;null!==n&&t.version<n.version&&o(e)}else o(e);return s.get(e)}}}function Yl(e,t,n){let i,r,s;function a(t,a,o){0!==o&&(e.drawElementsInstanced(i,a,r,t*s,o),n.update(a,i,o))}this.setMode=function(e){i=e},this.setIndex=function(e){r=e.type,s=e.bytesPerElement},this.render=function(t,a){e.drawElements(i,a,r,t*s),n.update(a,i,1)},this.renderInstances=a,this.renderMultiDraw=function(e,s,a){if(0===a)return;t.get("WEBGL_multi_draw").multiDrawElementsWEBGL(i,s,0,r,e,0,a);let o=0;for(let t=0;t<a;t++)o+=s[t];n.update(o,i,1)},this.renderMultiDrawInstances=function(e,o,l,c){if(0===l)return;const h=t.get("WEBGL_multi_draw");if(null===h)for(let t=0;t<e.length;t++)a(e[t]/s,o[t],c[t]);else{h.multiDrawElementsInstancedWEBGL(i,o,0,r,e,0,c,0,l);let t=0;for(let e=0;e<l;e++)t+=o[e]*c[e];n.update(t,i,1)}}}function Zl(e){const t={frame:0,calls:0,triangles:0,points:0,lines:0};return{memory:{geometries:0,textures:0},render:t,programs:null,autoReset:!0,reset:function(){t.calls=0,t.triangles=0,t.points=0,t.lines=0},update:function(n,i,r){switch(t.calls++,i){case e.TRIANGLES:t.triangles+=r*(n/3);break;case e.LINES:t.lines+=r*(n/2);break;case e.LINE_STRIP:t.lines+=r*(n-1);break;case e.LINE_LOOP:t.lines+=r*n;break;case e.POINTS:t.points+=r*n;break;default:Qn("WebGLInfo: Unknown draw mode:",i)}}}}function Jl(e,t,n){const i=new WeakMap,r=new Ri;return{update:function(s,a,o){const l=s.morphTargetInfluences,c=a.morphAttributes.position||a.morphAttributes.normal||a.morphAttributes.color,h=void 0!==c?c.length:0;let u=i.get(a);if(void 0===u||u.count!==h){let e=function(){_.dispose(),i.delete(a),a.removeEventListener("dispose",e)};void 0!==u&&u.texture.dispose();const n=void 0!==a.morphAttributes.position,s=void 0!==a.morphAttributes.normal,o=void 0!==a.morphAttributes.color,l=a.morphAttributes.position||[],c=a.morphAttributes.normal||[],d=a.morphAttributes.color||[];let p=0;!0===n&&(p=1),!0===s&&(p=2),!0===o&&(p=3);let f=a.attributes.position.count*p,m=1;f>t.maxTextureSize&&(m=Math.ceil(f/t.maxTextureSize),f=t.maxTextureSize);const g=new Float32Array(f*m*4*h),_=new Di(g,f,m,h);_.type=gt,_.needsUpdate=!0;const v=4*p;for(let t=0;t<h;t++){const e=l[t],i=c[t],a=d[t],h=f*m*4*t;for(let t=0;t<e.count;t++){const l=t*v;!0===n&&(r.fromBufferAttribute(e,t),g[h+l+0]=r.x,g[h+l+1]=r.y,g[h+l+2]=r.z,g[h+l+3]=0),!0===s&&(r.fromBufferAttribute(i,t),g[h+l+4]=r.x,g[h+l+5]=r.y,g[h+l+6]=r.z,g[h+l+7]=0),!0===o&&(r.fromBufferAttribute(a,t),g[h+l+8]=r.x,g[h+l+9]=r.y,g[h+l+10]=r.z,g[h+l+11]=4===a.itemSize?r.w:1)}}u={count:h,texture:_,size:new li(f,m)},i.set(a,u),a.addEventListener("dispose",e)}if(!0===s.isInstancedMesh&&null!==s.morphTexture)o.getUniforms().setValue(e,"morphTexture",s.morphTexture,n);else{let t=0;for(let e=0;e<l.length;e++)t+=l[e];const n=a.morphTargetsRelative?1:1-t;o.getUniforms().setValue(e,"morphTargetBaseInfluence",n),o.getUniforms().setValue(e,"morphTargetInfluences",l)}o.getUniforms().setValue(e,"morphTargetsTexture",u.texture,n),o.getUniforms().setValue(e,"morphTargetsTextureSize",u.size)}}}function $l(e,t,n,i){let r=new WeakMap;function s(e){const t=e.target;t.removeEventListener("dispose",s),n.remove(t.instanceMatrix),null!==t.instanceColor&&n.remove(t.instanceColor)}return{update:function(a){const o=i.render.frame,l=a.geometry,c=t.get(a,l);if(r.get(c)!==o&&(t.update(c),r.set(c,o)),a.isInstancedMesh&&(!1===a.hasEventListener("dispose",s)&&a.addEventListener("dispose",s),r.get(a)!==o&&(n.update(a.instanceMatrix,e.ARRAY_BUFFER),null!==a.instanceColor&&n.update(a.instanceColor,e.ARRAY_BUFFER),r.set(a,o))),a.isSkinnedMesh){const e=a.skeleton;r.get(e)!==o&&(e.update(),r.set(e,o))}return c},dispose:function(){r=new WeakMap}}}const ec={[We]:"LINEAR_TONE_MAPPING",[je]:"REINHARD_TONE_MAPPING",[Xe]:"CINEON_TONE_MAPPING",[qe]:"ACES_FILMIC_TONE_MAPPING",[Ke]:"AGX_TONE_MAPPING",[Ye]:"NEUTRAL_TONE_MAPPING",[Qe]:"CUSTOM_TONE_MAPPING"};function tc(e,t,n,i,r){const s=new Pi(t,n,{type:e,depthBuffer:i,stencilBuffer:r}),a=new Pi(t,n,{type:_t,depthBuffer:!1,stencilBuffer:!1}),o=new Ss;o.setAttribute("position",new ps([-1,3,0,-1,-1,0,3,-1,0],3)),o.setAttribute("uv",new ps([0,2,0,0,2,0],2));const l=new ao({uniforms:{tDiffuse:{value:null}},vertexShader:"\n\t\t\tprecision highp float;\n\n\t\t\tuniform mat4 modelViewMatrix;\n\t\t\tuniform mat4 projectionMatrix;\n\n\t\t\tattribute vec3 position;\n\t\t\tattribute vec2 uv;\n\n\t\t\tvarying vec2 vUv;\n\n\t\t\tvoid main() {\n\t\t\t\tvUv = uv;\n\t\t\t\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\t\t\t}",fragmentShader:"\n\t\t\tprecision highp float;\n\n\t\t\tuniform sampler2D tDiffuse;\n\n\t\t\tvarying vec2 vUv;\n\n\t\t\t#include <tonemapping_pars_fragment>\n\t\t\t#include <colorspace_pars_fragment>\n\n\t\t\tvoid main() {\n\t\t\t\tgl_FragColor = texture2D( tDiffuse, vUv );\n\n\t\t\t\t#ifdef LINEAR_TONE_MAPPING\n\t\t\t\t\tgl_FragColor.rgb = LinearToneMapping( gl_FragColor.rgb );\n\t\t\t\t#elif defined( REINHARD_TONE_MAPPING )\n\t\t\t\t\tgl_FragColor.rgb = ReinhardToneMapping( gl_FragColor.rgb );\n\t\t\t\t#elif defined( CINEON_TONE_MAPPING )\n\t\t\t\t\tgl_FragColor.rgb = CineonToneMapping( gl_FragColor.rgb );\n\t\t\t\t#elif defined( ACES_FILMIC_TONE_MAPPING )\n\t\t\t\t\tgl_FragColor.rgb = ACESFilmicToneMapping( gl_FragColor.rgb );\n\t\t\t\t#elif defined( AGX_TONE_MAPPING )\n\t\t\t\t\tgl_FragColor.rgb = AgXToneMapping( gl_FragColor.rgb );\n\t\t\t\t#elif defined( NEUTRAL_TONE_MAPPING )\n\t\t\t\t\tgl_FragColor.rgb = NeutralToneMapping( gl_FragColor.rgb );\n\t\t\t\t#elif defined( CUSTOM_TONE_MAPPING )\n\t\t\t\t\tgl_FragColor.rgb = CustomToneMapping( gl_FragColor.rgb );\n\t\t\t\t#endif\n\n\t\t\t\t#ifdef SRGB_TRANSFER\n\t\t\t\t\tgl_FragColor = sRGBTransferOETF( gl_FragColor );\n\t\t\t\t#endif\n\t\t\t}",depthTest:!1,depthWrite:!1}),c=new Bs(o,l),h=new Ko(-1,1,1,-1,0,1);let u,d=null,p=null,f=!1,m=null,g=[],_=!1;this.setSize=function(e,t){s.setSize(e,t),a.setSize(e,t);for(let n=0;n<g.length;n++){const i=g[n];i.setSize&&i.setSize(e,t)}},this.setEffects=function(e){g=e,_=g.length>0&&!0===g[0].isRenderPass;const t=s.width,n=s.height;for(let i=0;i<g.length;i++){const e=g[i];e.setSize&&e.setSize(t,n)}},this.begin=function(e,t){if(f)return!1;if(0===e.toneMapping&&0===g.length)return!1;if(m=t,null!==t){const e=t.width,n=t.height;s.width===e&&s.height===n||this.setSize(e,n)}return!1===_&&e.setRenderTarget(s),u=e.toneMapping,e.toneMapping=0,!0},this.hasRenderPass=function(){return _},this.end=function(e,t){e.toneMapping=u,f=!0;let n=s,i=a;for(let r=0;r<g.length;r++){const s=g[r];if(!1!==s.enabled&&(s.render(e,i,n,t),!1!==s.needsSwap)){const e=n;n=i,i=e}}if(d!==e.outputColorSpace||p!==e.toneMapping){d=e.outputColorSpace,p=e.toneMapping,l.defines={},vi.getTransfer(d)===En&&(l.defines.SRGB_TRANSFER="");const t=ec[p];t&&(l.defines[t]=""),l.needsUpdate=!0}l.uniforms.tDiffuse.value=n.texture,e.setRenderTarget(m),e.render(c,h),m=null,f=!1},this.isCompositing=function(){return f},this.dispose=function(){s.dispose(),a.dispose(),o.dispose(),l.dispose()}}const nc=new Ci,ic=new no(1,1),rc=new Di,sc=new Bi,ac=new Qs,oc=[],lc=[],cc=new Float32Array(16),hc=new Float32Array(9),uc=new Float32Array(4);function dc(e,t,n){const i=e[0];if(i<=0||i>0)return e;const r=t*n;let s=oc[r];if(void 0===s&&(s=new Float32Array(r),oc[r]=s),0!==t){i.toArray(s,0);for(let i=1,r=0;i!==t;++i)r+=n,e[i].toArray(s,r)}return s}function pc(e,t){if(e.length!==t.length)return!1;for(let n=0,i=e.length;n<i;n++)if(e[n]!==t[n])return!1;return!0}function fc(e,t){for(let n=0,i=t.length;n<i;n++)e[n]=t[n]}function mc(e,t){let n=lc[t];void 0===n&&(n=new Int32Array(t),lc[t]=n);for(let i=0;i!==t;++i)n[i]=e.allocateTextureUnit();return n}function gc(e,t){const n=this.cache;n[0]!==t&&(e.uniform1f(this.addr,t),n[0]=t)}function _c(e,t){const n=this.cache;if(void 0!==t.x)n[0]===t.x&&n[1]===t.y||(e.uniform2f(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y);else{if(pc(n,t))return;e.uniform2fv(this.addr,t),fc(n,t)}}function vc(e,t){const n=this.cache;if(void 0!==t.x)n[0]===t.x&&n[1]===t.y&&n[2]===t.z||(e.uniform3f(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z);else if(void 0!==t.r)n[0]===t.r&&n[1]===t.g&&n[2]===t.b||(e.uniform3f(this.addr,t.r,t.g,t.b),n[0]=t.r,n[1]=t.g,n[2]=t.b);else{if(pc(n,t))return;e.uniform3fv(this.addr,t),fc(n,t)}}function xc(e,t){const n=this.cache;if(void 0!==t.x)n[0]===t.x&&n[1]===t.y&&n[2]===t.z&&n[3]===t.w||(e.uniform4f(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w);else{if(pc(n,t))return;e.uniform4fv(this.addr,t),fc(n,t)}}function yc(e,t){const n=this.cache,i=t.elements;if(void 0===i){if(pc(n,t))return;e.uniformMatrix2fv(this.addr,!1,t),fc(n,t)}else{if(pc(n,i))return;uc.set(i),e.uniformMatrix2fv(this.addr,!1,uc),fc(n,i)}}function Sc(e,t){const n=this.cache,i=t.elements;if(void 0===i){if(pc(n,t))return;e.uniformMatrix3fv(this.addr,!1,t),fc(n,t)}else{if(pc(n,i))return;hc.set(i),e.uniformMatrix3fv(this.addr,!1,hc),fc(n,i)}}function Ac(e,t){const n=this.cache,i=t.elements;if(void 0===i){if(pc(n,t))return;e.uniformMatrix4fv(this.addr,!1,t),fc(n,t)}else{if(pc(n,i))return;cc.set(i),e.uniformMatrix4fv(this.addr,!1,cc),fc(n,i)}}function bc(e,t){const n=this.cache;n[0]!==t&&(e.uniform1i(this.addr,t),n[0]=t)}function Mc(e,t){const n=this.cache;if(void 0!==t.x)n[0]===t.x&&n[1]===t.y||(e.uniform2i(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y);else{if(pc(n,t))return;e.uniform2iv(this.addr,t),fc(n,t)}}function wc(e,t){const n=this.cache;if(void 0!==t.x)n[0]===t.x&&n[1]===t.y&&n[2]===t.z||(e.uniform3i(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z);else{if(pc(n,t))return;e.uniform3iv(this.addr,t),fc(n,t)}}function Tc(e,t){const n=this.cache;if(void 0!==t.x)n[0]===t.x&&n[1]===t.y&&n[2]===t.z&&n[3]===t.w||(e.uniform4i(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w);else{if(pc(n,t))return;e.uniform4iv(this.addr,t),fc(n,t)}}function Ec(e,t){const n=this.cache;n[0]!==t&&(e.uniform1ui(this.addr,t),n[0]=t)}function Cc(e,t){const n=this.cache;if(void 0!==t.x)n[0]===t.x&&n[1]===t.y||(e.uniform2ui(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y);else{if(pc(n,t))return;e.uniform2uiv(this.addr,t),fc(n,t)}}function Rc(e,t){const n=this.cache;if(void 0!==t.x)n[0]===t.x&&n[1]===t.y&&n[2]===t.z||(e.uniform3ui(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z);else{if(pc(n,t))return;e.uniform3uiv(this.addr,t),fc(n,t)}}function Ic(e,t){const n=this.cache;if(void 0!==t.x)n[0]===t.x&&n[1]===t.y&&n[2]===t.z&&n[3]===t.w||(e.uniform4ui(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w);else{if(pc(n,t))return;e.uniform4uiv(this.addr,t),fc(n,t)}}function Pc(e,t,n){const i=this.cache,r=n.allocateTextureUnit();let s;i[0]!==r&&(e.uniform1i(this.addr,r),i[0]=r),this.type===e.SAMPLER_2D_SHADOW?(ic.compareFunction=n.isReversedDepthBuffer()?518:515,s=ic):s=nc,n.setTexture2D(t||s,r)}function Dc(e,t,n){const i=this.cache,r=n.allocateTextureUnit();i[0]!==r&&(e.uniform1i(this.addr,r),i[0]=r),n.setTexture3D(t||sc,r)}function Bc(e,t,n){const i=this.cache,r=n.allocateTextureUnit();i[0]!==r&&(e.uniform1i(this.addr,r),i[0]=r),n.setTextureCube(t||ac,r)}function Lc(e,t,n){const i=this.cache,r=n.allocateTextureUnit();i[0]!==r&&(e.uniform1i(this.addr,r),i[0]=r),n.setTexture2DArray(t||rc,r)}function Fc(e,t){e.uniform1fv(this.addr,t)}function Uc(e,t){const n=dc(t,this.size,2);e.uniform2fv(this.addr,n)}function kc(e,t){const n=dc(t,this.size,3);e.uniform3fv(this.addr,n)}function Nc(e,t){const n=dc(t,this.size,4);e.uniform4fv(this.addr,n)}function Oc(e,t){const n=dc(t,this.size,4);e.uniformMatrix2fv(this.addr,!1,n)}function zc(e,t){const n=dc(t,this.size,9);e.uniformMatrix3fv(this.addr,!1,n)}function Hc(e,t){const n=dc(t,this.size,16);e.uniformMatrix4fv(this.addr,!1,n)}function Vc(e,t){e.uniform1iv(this.addr,t)}function Gc(e,t){e.uniform2iv(this.addr,t)}function Wc(e,t){e.uniform3iv(this.addr,t)}function jc(e,t){e.uniform4iv(this.addr,t)}function Xc(e,t){e.uniform1uiv(this.addr,t)}function qc(e,t){e.uniform2uiv(this.addr,t)}function Qc(e,t){e.uniform3uiv(this.addr,t)}function Kc(e,t){e.uniform4uiv(this.addr,t)}function Yc(e,t,n){const i=this.cache,r=t.length,s=mc(n,r);let a;pc(i,s)||(e.uniform1iv(this.addr,s),fc(i,s)),a=this.type===e.SAMPLER_2D_SHADOW?ic:nc;for(let o=0;o!==r;++o)n.setTexture2D(t[o]||a,s[o])}function Zc(e,t,n){const i=this.cache,r=t.length,s=mc(n,r);pc(i,s)||(e.uniform1iv(this.addr,s),fc(i,s));for(let a=0;a!==r;++a)n.setTexture3D(t[a]||sc,s[a])}function Jc(e,t,n){const i=this.cache,r=t.length,s=mc(n,r);pc(i,s)||(e.uniform1iv(this.addr,s),fc(i,s));for(let a=0;a!==r;++a)n.setTextureCube(t[a]||ac,s[a])}function $c(e,t,n){const i=this.cache,r=t.length,s=mc(n,r);pc(i,s)||(e.uniform1iv(this.addr,s),fc(i,s));for(let a=0;a!==r;++a)n.setTexture2DArray(t[a]||rc,s[a])}class eh{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.setValue=function(e){switch(e){case 5126:return gc;case 35664:return _c;case 35665:return vc;case 35666:return xc;case 35674:return yc;case 35675:return Sc;case 35676:return Ac;case 5124:case 35670:return bc;case 35667:case 35671:return Mc;case 35668:case 35672:return wc;case 35669:case 35673:return Tc;case 5125:return Ec;case 36294:return Cc;case 36295:return Rc;case 36296:return Ic;case 35678:case 36198:case 36298:case 36306:case 35682:return Pc;case 35679:case 36299:case 36307:return Dc;case 35680:case 36300:case 36308:case 36293:return Bc;case 36289:case 36303:case 36311:case 36292:return Lc}}(t.type)}}class th{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=function(e){switch(e){case 5126:return Fc;case 35664:return Uc;case 35665:return kc;case 35666:return Nc;case 35674:return Oc;case 35675:return zc;case 35676:return Hc;case 5124:case 35670:return Vc;case 35667:case 35671:return Gc;case 35668:case 35672:return Wc;case 35669:case 35673:return jc;case 5125:return Xc;case 36294:return qc;case 36295:return Qc;case 36296:return Kc;case 35678:case 36198:case 36298:case 36306:case 35682:return Yc;case 35679:case 36299:case 36307:return Zc;case 35680:case 36300:case 36308:case 36293:return Jc;case 36289:case 36303:case 36311:case 36292:return $c}}(t.type)}}class nh{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,n){const i=this.seq;for(let r=0,s=i.length;r!==s;++r){const s=i[r];s.setValue(e,t[s.id],n)}}}const ih=/(\w+)(\])?(\[|\.)?/g;function rh(e,t){e.seq.push(t),e.map[t.id]=t}function sh(e,t,n){const i=e.name,r=i.length;for(ih.lastIndex=0;;){const s=ih.exec(i),a=ih.lastIndex;let o=s[1];const l="]"===s[2],c=s[3];if(l&&(o|=0),void 0===c||"["===c&&a+2===r){rh(n,void 0===c?new eh(o,e,t):new th(o,e,t));break}{let e=n.map[o];void 0===e&&(e=new nh(o),rh(n,e)),n=e}}}class ah{constructor(e,t){this.seq=[],this.map={};const n=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let s=0;s<n;++s){const n=e.getActiveUniform(t,s);sh(n,e.getUniformLocation(t,n.name),this)}const i=[],r=[];for(const s of this.seq)s.type===e.SAMPLER_2D_SHADOW||s.type===e.SAMPLER_CUBE_SHADOW||s.type===e.SAMPLER_2D_ARRAY_SHADOW?i.push(s):r.push(s);i.length>0&&(this.seq=i.concat(r))}setValue(e,t,n,i){const r=this.map[t];void 0!==r&&r.setValue(e,n,i)}setOptional(e,t,n){const i=t[n];void 0!==i&&this.setValue(e,n,i)}static upload(e,t,n,i){for(let r=0,s=t.length;r!==s;++r){const s=t[r],a=n[s.id];!1!==a.needsUpdate&&s.setValue(e,a.value,i)}}static seqWithValue(e,t){const n=[];for(let i=0,r=e.length;i!==r;++i){const r=e[i];r.id in t&&n.push(r)}return n}}function oh(e,t,n){const i=e.createShader(t);return e.shaderSource(i,n),e.compileShader(i),i}let lh=0;const ch=new pi;function hh(e,t,n){const i=e.getShaderParameter(t,e.COMPILE_STATUS),r=(e.getShaderInfoLog(t)||"").trim();if(i&&""===r)return"";const s=/ERROR: 0:(\d+)/.exec(r);if(s){const i=parseInt(s[1]);return n.toUpperCase()+"\n\n"+r+"\n\n"+function(e,t){const n=e.split("\n"),i=[],r=Math.max(t-6,0),s=Math.min(t+6,n.length);for(let a=r;a<s;a++){const e=a+1;i.push(`${e===t?">":" "} ${e}: ${n[a]}`)}return i.join("\n")}(e.getShaderSource(t),i)}return r}function uh(e,t){const n=function(e){vi._getMatrix(ch,vi.workingColorSpace,e);const t=`mat3( ${ch.elements.map(e=>e.toFixed(4))} )`;switch(vi.getTransfer(e)){case Tn:return[t,"LinearTransferOETF"];case En:return[t,"sRGBTransferOETF"];default:return qn("WebGLProgram: Unsupported color space: ",e),[t,"LinearTransferOETF"]}}(t);return[`vec4 ${e}( vec4 value ) {`,`\treturn ${n[1]}( vec4( value.rgb * ${n[0]}, value.a ) );`,"}"].join("\n")}const dh={[We]:"Linear",[je]:"Reinhard",[Xe]:"Cineon",[qe]:"ACESFilmic",[Ke]:"AgX",[Ye]:"Neutral",[Qe]:"Custom"};function ph(e,t){const n=dh[t];return void 0===n?(qn("WebGLProgram: Unsupported toneMapping:",t),"vec3 "+e+"( vec3 color ) { return LinearToneMapping( color ); }"):"vec3 "+e+"( vec3 color ) { return "+n+"ToneMapping( color ); }"}const fh=new hi;function mh(){vi.getLuminanceCoefficients(fh);return["float luminance( const in vec3 rgb ) {",`\tconst vec3 weights = vec3( ${fh.x.toFixed(4)}, ${fh.y.toFixed(4)}, ${fh.z.toFixed(4)} );`,"\treturn dot( weights, rgb );","}"].join("\n")}function gh(e){return""!==e}function _h(e,t){const n=t.numSpotLightShadows+t.numSpotLightMaps-t.numSpotLightShadowsWithMaps;return e.replace(/NUM_DIR_LIGHTS/g,t.numDirLights).replace(/NUM_SPOT_LIGHTS/g,t.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,t.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,n).replace(/NUM_RECT_AREA_LIGHTS/g,t.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,t.numPointLights).replace(/NUM_HEMI_LIGHTS/g,t.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,t.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,t.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,t.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,t.numPointLightShadows)}function vh(e,t){return e.replace(/NUM_CLIPPING_PLANES/g,t.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,t.numClippingPlanes-t.numClipIntersection)}const xh=/^[ \t]*#include +<([\w\d./]+)>/gm;function yh(e){return e.replace(xh,Ah)}const Sh=new Map;function Ah(e,t){let n=yl[t];if(void 0===n){const e=Sh.get(t);if(void 0===e)throw new Error("Can not resolve #include <"+t+">");n=yl[e],qn('WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',t,e)}return yh(n)}const bh=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function Mh(e){return e.replace(bh,wh)}function wh(e,t,n,i){let r="";for(let s=parseInt(t);s<parseInt(n);s++)r+=i.replace(/\[\s*i\s*\]/g,"[ "+s+" ]").replace(/UNROLLED_LOOP_INDEX/g,s);return r}function Th(e){let t=`precision ${e.precision} float;\n\tprecision ${e.precision} int;\n\tprecision ${e.precision} sampler2D;\n\tprecision ${e.precision} samplerCube;\n\tprecision ${e.precision} sampler3D;\n\tprecision ${e.precision} sampler2DArray;\n\tprecision ${e.precision} sampler2DShadow;\n\tprecision ${e.precision} samplerCubeShadow;\n\tprecision ${e.precision} sampler2DArrayShadow;\n\tprecision ${e.precision} isampler2D;\n\tprecision ${e.precision} isampler3D;\n\tprecision ${e.precision} isamplerCube;\n\tprecision ${e.precision} isampler2DArray;\n\tprecision ${e.precision} usampler2D;\n\tprecision ${e.precision} usampler3D;\n\tprecision ${e.precision} usamplerCube;\n\tprecision ${e.precision} usampler2DArray;\n\t`;return"highp"===e.precision?t+="\n#define HIGH_PRECISION":"mediump"===e.precision?t+="\n#define MEDIUM_PRECISION":"lowp"===e.precision&&(t+="\n#define LOW_PRECISION"),t}const Eh={[he]:"SHADOWMAP_TYPE_PCF",[ue]:"SHADOWMAP_TYPE_VSM"};const Ch={[Je]:"ENVMAP_TYPE_CUBE",[$e]:"ENVMAP_TYPE_CUBE",[et]:"ENVMAP_TYPE_CUBE_UV"};const Rh={[$e]:"ENVMAP_MODE_REFRACTION"};const Ih={[He]:"ENVMAP_BLENDING_MULTIPLY",[Ve]:"ENVMAP_BLENDING_MIX",[Ge]:"ENVMAP_BLENDING_ADD"};function Ph(e,t,n,i){const r=e.getContext(),s=n.defines;let a=n.vertexShader,o=n.fragmentShader;const l=function(e){return Eh[e.shadowMapType]||"SHADOWMAP_TYPE_BASIC"}(n),c=function(e){return!1===e.envMap?"ENVMAP_TYPE_CUBE":Ch[e.envMapMode]||"ENVMAP_TYPE_CUBE"}(n),h=function(e){return!1===e.envMap?"ENVMAP_MODE_REFLECTION":Rh[e.envMapMode]||"ENVMAP_MODE_REFLECTION"}(n),u=function(e){return!1===e.envMap?"ENVMAP_BLENDING_NONE":Ih[e.combine]||"ENVMAP_BLENDING_NONE"}(n),d=function(e){const t=e.envMapCubeUVHeight;if(null===t)return null;const n=Math.log2(t)-2,i=1/t;return{texelWidth:1/(3*Math.max(Math.pow(2,n),112)),texelHeight:i,maxMip:n}}(n),p=function(e){return[e.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",e.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(gh).join("\n")}(n),f=function(e){const t=[];for(const n in e){const i=e[n];!1!==i&&t.push("#define "+n+" "+i)}return t.join("\n")}(s),m=r.createProgram();let g,_,v=n.glslVersion?"#version "+n.glslVersion+"\n":"";n.isRawShaderMaterial?(g=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,f].filter(gh).join("\n"),g.length>0&&(g+="\n"),_=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,f].filter(gh).join("\n"),_.length>0&&(_+="\n")):(g=[Th(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,f,n.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",n.batching?"#define USE_BATCHING":"",n.batchingColor?"#define USE_BATCHING_COLOR":"",n.instancing?"#define USE_INSTANCING":"",n.instancingColor?"#define USE_INSTANCING_COLOR":"",n.instancingMorph?"#define USE_INSTANCING_MORPH":"",n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.map?"#define USE_MAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+h:"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",n.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",n.displacementMap?"#define USE_DISPLACEMENTMAP":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.anisotropy?"#define USE_ANISOTROPY":"",n.anisotropyMap?"#define USE_ANISOTROPYMAP":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.mapUv?"#define MAP_UV "+n.mapUv:"",n.alphaMapUv?"#define ALPHAMAP_UV "+n.alphaMapUv:"",n.lightMapUv?"#define LIGHTMAP_UV "+n.lightMapUv:"",n.aoMapUv?"#define AOMAP_UV "+n.aoMapUv:"",n.emissiveMapUv?"#define EMISSIVEMAP_UV "+n.emissiveMapUv:"",n.bumpMapUv?"#define BUMPMAP_UV "+n.bumpMapUv:"",n.normalMapUv?"#define NORMALMAP_UV "+n.normalMapUv:"",n.displacementMapUv?"#define DISPLACEMENTMAP_UV "+n.displacementMapUv:"",n.metalnessMapUv?"#define METALNESSMAP_UV "+n.metalnessMapUv:"",n.roughnessMapUv?"#define ROUGHNESSMAP_UV "+n.roughnessMapUv:"",n.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+n.anisotropyMapUv:"",n.clearcoatMapUv?"#define CLEARCOATMAP_UV "+n.clearcoatMapUv:"",n.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+n.clearcoatNormalMapUv:"",n.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+n.clearcoatRoughnessMapUv:"",n.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+n.iridescenceMapUv:"",n.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+n.iridescenceThicknessMapUv:"",n.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+n.sheenColorMapUv:"",n.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+n.sheenRoughnessMapUv:"",n.specularMapUv?"#define SPECULARMAP_UV "+n.specularMapUv:"",n.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+n.specularColorMapUv:"",n.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+n.specularIntensityMapUv:"",n.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+n.transmissionMapUv:"",n.thicknessMapUv?"#define THICKNESSMAP_UV "+n.thicknessMapUv:"",n.vertexTangents&&!1===n.flatShading?"#define USE_TANGENT":"",n.vertexColors?"#define USE_COLOR":"",n.vertexAlphas?"#define USE_COLOR_ALPHA":"",n.vertexUv1s?"#define USE_UV1":"",n.vertexUv2s?"#define USE_UV2":"",n.vertexUv3s?"#define USE_UV3":"",n.pointsUvs?"#define USE_POINTS_UV":"",n.flatShading?"#define FLAT_SHADED":"",n.skinning?"#define USE_SKINNING":"",n.morphTargets?"#define USE_MORPHTARGETS":"",n.morphNormals&&!1===n.flatShading?"#define USE_MORPHNORMALS":"",n.morphColors?"#define USE_MORPHCOLORS":"",n.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+n.morphTextureStride:"",n.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+n.morphTargetsCount:"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+l:"",n.sizeAttenuation?"#define USE_SIZEATTENUATION":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",n.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING","\tattribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR","\tattribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH","\tuniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1","\tattribute vec2 uv1;","#endif","#ifdef USE_UV2","\tattribute vec2 uv2;","#endif","#ifdef USE_UV3","\tattribute vec2 uv3;","#endif","#ifdef USE_TANGENT","\tattribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )","\tattribute vec4 color;","#elif defined( USE_COLOR )","\tattribute vec3 color;","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(gh).join("\n"),_=[Th(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,f,n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",n.map?"#define USE_MAP":"",n.matcap?"#define USE_MATCAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+c:"",n.envMap?"#define "+h:"",n.envMap?"#define "+u:"",d?"#define CUBEUV_TEXEL_WIDTH "+d.texelWidth:"",d?"#define CUBEUV_TEXEL_HEIGHT "+d.texelHeight:"",d?"#define CUBEUV_MAX_MIP "+d.maxMip+".0":"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",n.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.anisotropy?"#define USE_ANISOTROPY":"",n.anisotropyMap?"#define USE_ANISOTROPYMAP":"",n.clearcoat?"#define USE_CLEARCOAT":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.dispersion?"#define USE_DISPERSION":"",n.iridescence?"#define USE_IRIDESCENCE":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaTest?"#define USE_ALPHATEST":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.sheen?"#define USE_SHEEN":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.vertexTangents&&!1===n.flatShading?"#define USE_TANGENT":"",n.vertexColors||n.instancingColor||n.batchingColor?"#define USE_COLOR":"",n.vertexAlphas?"#define USE_COLOR_ALPHA":"",n.vertexUv1s?"#define USE_UV1":"",n.vertexUv2s?"#define USE_UV2":"",n.vertexUv3s?"#define USE_UV3":"",n.pointsUvs?"#define USE_POINTS_UV":"",n.gradientMap?"#define USE_GRADIENTMAP":"",n.flatShading?"#define FLAT_SHADED":"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+l:"",n.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",n.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",n.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",n.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",0!==n.toneMapping?"#define TONE_MAPPING":"",0!==n.toneMapping?yl.tonemapping_pars_fragment:"",0!==n.toneMapping?ph("toneMapping",n.toneMapping):"",n.dithering?"#define DITHERING":"",n.opaque?"#define OPAQUE":"",yl.colorspace_pars_fragment,uh("linearToOutputTexel",n.outputColorSpace),mh(),n.useDepthPacking?"#define DEPTH_PACKING "+n.depthPacking:"","\n"].filter(gh).join("\n")),a=yh(a),a=_h(a,n),a=vh(a,n),o=yh(o),o=_h(o,n),o=vh(o,n),a=Mh(a),o=Mh(o),!0!==n.isRawShaderMaterial&&(v="#version 300 es\n",g=[p,"#define attribute in","#define varying out","#define texture2D texture"].join("\n")+"\n"+g,_=["#define varying in",n.glslVersion===On?"":"layout(location = 0) out highp vec4 pc_fragColor;",n.glslVersion===On?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join("\n")+"\n"+_);const x=v+g+a,y=v+_+o,S=oh(r,r.VERTEX_SHADER,x),A=oh(r,r.FRAGMENT_SHADER,y);function b(t){if(e.debug.checkShaderErrors){const n=r.getProgramInfoLog(m)||"",i=r.getShaderInfoLog(S)||"",s=r.getShaderInfoLog(A)||"",a=n.trim(),o=i.trim(),l=s.trim();let c=!0,h=!0;if(!1===r.getProgramParameter(m,r.LINK_STATUS))if(c=!1,"function"==typeof e.debug.onShaderError)e.debug.onShaderError(r,m,S,A);else{const e=hh(r,S,"vertex"),n=hh(r,A,"fragment");Qn("THREE.WebGLProgram: Shader Error "+r.getError()+" - VALIDATE_STATUS "+r.getProgramParameter(m,r.VALIDATE_STATUS)+"\n\nMaterial Name: "+t.name+"\nMaterial Type: "+t.type+"\n\nProgram Info Log: "+a+"\n"+e+"\n"+n)}else""!==a?qn("WebGLProgram: Program Info Log:",a):""!==o&&""!==l||(h=!1);h&&(t.diagnostics={runnable:c,programLog:a,vertexShader:{log:o,prefix:g},fragmentShader:{log:l,prefix:_}})}r.deleteShader(S),r.deleteShader(A),M=new ah(r,m),w=function(e,t){const n={},i=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let r=0;r<i;r++){const i=e.getActiveAttrib(t,r),s=i.name;let a=1;i.type===e.FLOAT_MAT2&&(a=2),i.type===e.FLOAT_MAT3&&(a=3),i.type===e.FLOAT_MAT4&&(a=4),n[s]={type:i.type,location:e.getAttribLocation(t,s),locationSize:a}}return n}(r,m)}let M,w;r.attachShader(m,S),r.attachShader(m,A),void 0!==n.index0AttributeName?r.bindAttribLocation(m,0,n.index0AttributeName):!0===n.morphTargets&&r.bindAttribLocation(m,0,"position"),r.linkProgram(m),this.getUniforms=function(){return void 0===M&&b(this),M},this.getAttributes=function(){return void 0===w&&b(this),w};let T=!1===n.rendererExtensionParallelShaderCompile;return this.isReady=function(){return!1===T&&(T=r.getProgramParameter(m,37297)),T},this.destroy=function(){i.releaseStatesOfProgram(this),r.deleteProgram(m),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=lh++,this.cacheKey=t,this.usedTimes=1,this.program=m,this.vertexShader=S,this.fragmentShader=A,this}let Dh=0;class Bh{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const t=e.vertexShader,n=e.fragmentShader,i=this._getShaderStage(t),r=this._getShaderStage(n),s=this._getShaderCacheForMaterial(e);return!1===s.has(i)&&(s.add(i),i.usedTimes++),!1===s.has(r)&&(s.add(r),r.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const n of t)n.usedTimes--,0===n.usedTimes&&this.shaderCache.delete(n.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let n=t.get(e);return void 0===n&&(n=new Set,t.set(e,n)),n}_getShaderStage(e){const t=this.shaderCache;let n=t.get(e);return void 0===n&&(n=new Lh(e),t.set(e,n)),n}}class Lh{constructor(e){this.id=Dh++,this.code=e,this.usedTimes=0}}function Fh(e,t,n,i,r,s,a){const o=new vr,l=new Bh,c=new Set,h=[],u=new Map,d=r.logarithmicDepthBuffer;let p=r.precision;const f={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distance",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function m(e){return c.add(e),0===e?"uv":`uv${e}`}return{getParameters:function(s,o,h,u,g){const _=u.fog,v=g.geometry,x=s.isMeshStandardMaterial?u.environment:null,y=(s.isMeshStandardMaterial?n:t).get(s.envMap||x),S=y&&y.mapping===et?y.image.height:null,A=f[s.type];null!==s.precision&&(p=r.getMaxPrecision(s.precision),p!==s.precision&&qn("WebGLProgram.getParameters:",s.precision,"not supported, using",p,"instead."));const b=v.morphAttributes.position||v.morphAttributes.normal||v.morphAttributes.color,M=void 0!==b?b.length:0;let w,T,E,C,R=0;if(void 0!==v.morphAttributes.position&&(R=1),void 0!==v.morphAttributes.normal&&(R=2),void 0!==v.morphAttributes.color&&(R=3),A){const e=Al[A];w=e.vertexShader,T=e.fragmentShader}else w=s.vertexShader,T=s.fragmentShader,l.update(s),E=l.getVertexShaderID(s),C=l.getFragmentShaderID(s);const I=e.getRenderTarget(),P=e.state.buffers.depth.getReversed(),D=!0===g.isInstancedMesh,B=!0===g.isBatchedMesh,L=!!s.map,F=!!s.matcap,U=!!y,k=!!s.aoMap,N=!!s.lightMap,O=!!s.bumpMap,z=!!s.normalMap,H=!!s.displacementMap,V=!!s.emissiveMap,G=!!s.metalnessMap,W=!!s.roughnessMap,j=s.anisotropy>0,X=s.clearcoat>0,q=s.dispersion>0,Q=s.iridescence>0,K=s.sheen>0,Y=s.transmission>0,Z=j&&!!s.anisotropyMap,J=X&&!!s.clearcoatMap,$=X&&!!s.clearcoatNormalMap,ee=X&&!!s.clearcoatRoughnessMap,te=Q&&!!s.iridescenceMap,ne=Q&&!!s.iridescenceThicknessMap,ie=K&&!!s.sheenColorMap,re=K&&!!s.sheenRoughnessMap,se=!!s.specularMap,ae=!!s.specularColorMap,oe=!!s.specularIntensityMap,le=Y&&!!s.transmissionMap,ce=Y&&!!s.thicknessMap,he=!!s.gradientMap,ue=!!s.alphaMap,de=s.alphaTest>0,pe=!!s.alphaHash,fe=!!s.extensions;let me=0;s.toneMapped&&(null!==I&&!0!==I.isXRRenderTarget||(me=e.toneMapping));const ge={shaderID:A,shaderType:s.type,shaderName:s.name,vertexShader:w,fragmentShader:T,defines:s.defines,customVertexShaderID:E,customFragmentShaderID:C,isRawShaderMaterial:!0===s.isRawShaderMaterial,glslVersion:s.glslVersion,precision:p,batching:B,batchingColor:B&&null!==g._colorsTexture,instancing:D,instancingColor:D&&null!==g.instanceColor,instancingMorph:D&&null!==g.morphTexture,outputColorSpace:null===I?e.outputColorSpace:!0===I.isXRRenderTarget?I.texture.colorSpace:wn,alphaToCoverage:!!s.alphaToCoverage,map:L,matcap:F,envMap:U,envMapMode:U&&y.mapping,envMapCubeUVHeight:S,aoMap:k,lightMap:N,bumpMap:O,normalMap:z,displacementMap:H,emissiveMap:V,normalMapObjectSpace:z&&1===s.normalMapType,normalMapTangentSpace:z&&0===s.normalMapType,metalnessMap:G,roughnessMap:W,anisotropy:j,anisotropyMap:Z,clearcoat:X,clearcoatMap:J,clearcoatNormalMap:$,clearcoatRoughnessMap:ee,dispersion:q,iridescence:Q,iridescenceMap:te,iridescenceThicknessMap:ne,sheen:K,sheenColorMap:ie,sheenRoughnessMap:re,specularMap:se,specularColorMap:ae,specularIntensityMap:oe,transmission:Y,transmissionMap:le,thicknessMap:ce,gradientMap:he,opaque:!1===s.transparent&&1===s.blending&&!1===s.alphaToCoverage,alphaMap:ue,alphaTest:de,alphaHash:pe,combine:s.combine,mapUv:L&&m(s.map.channel),aoMapUv:k&&m(s.aoMap.channel),lightMapUv:N&&m(s.lightMap.channel),bumpMapUv:O&&m(s.bumpMap.channel),normalMapUv:z&&m(s.normalMap.channel),displacementMapUv:H&&m(s.displacementMap.channel),emissiveMapUv:V&&m(s.emissiveMap.channel),metalnessMapUv:G&&m(s.metalnessMap.channel),roughnessMapUv:W&&m(s.roughnessMap.channel),anisotropyMapUv:Z&&m(s.anisotropyMap.channel),clearcoatMapUv:J&&m(s.clearcoatMap.channel),clearcoatNormalMapUv:$&&m(s.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:ee&&m(s.clearcoatRoughnessMap.channel),iridescenceMapUv:te&&m(s.iridescenceMap.channel),iridescenceThicknessMapUv:ne&&m(s.iridescenceThicknessMap.channel),sheenColorMapUv:ie&&m(s.sheenColorMap.channel),sheenRoughnessMapUv:re&&m(s.sheenRoughnessMap.channel),specularMapUv:se&&m(s.specularMap.channel),specularColorMapUv:ae&&m(s.specularColorMap.channel),specularIntensityMapUv:oe&&m(s.specularIntensityMap.channel),transmissionMapUv:le&&m(s.transmissionMap.channel),thicknessMapUv:ce&&m(s.thicknessMap.channel),alphaMapUv:ue&&m(s.alphaMap.channel),vertexTangents:!!v.attributes.tangent&&(z||j),vertexColors:s.vertexColors,vertexAlphas:!0===s.vertexColors&&!!v.attributes.color&&4===v.attributes.color.itemSize,pointsUvs:!0===g.isPoints&&!!v.attributes.uv&&(L||ue),fog:!!_,useFog:!0===s.fog,fogExp2:!!_&&_.isFogExp2,flatShading:!0===s.flatShading&&!1===s.wireframe,sizeAttenuation:!0===s.sizeAttenuation,logarithmicDepthBuffer:d,reversedDepthBuffer:P,skinning:!0===g.isSkinnedMesh,morphTargets:void 0!==v.morphAttributes.position,morphNormals:void 0!==v.morphAttributes.normal,morphColors:void 0!==v.morphAttributes.color,morphTargetsCount:M,morphTextureStride:R,numDirLights:o.directional.length,numPointLights:o.point.length,numSpotLights:o.spot.length,numSpotLightMaps:o.spotLightMap.length,numRectAreaLights:o.rectArea.length,numHemiLights:o.hemi.length,numDirLightShadows:o.directionalShadowMap.length,numPointLightShadows:o.pointShadowMap.length,numSpotLightShadows:o.spotShadowMap.length,numSpotLightShadowsWithMaps:o.numSpotLightShadowsWithMaps,numLightProbes:o.numLightProbes,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:s.dithering,shadowMapEnabled:e.shadowMap.enabled&&h.length>0,shadowMapType:e.shadowMap.type,toneMapping:me,decodeVideoTexture:L&&!0===s.map.isVideoTexture&&vi.getTransfer(s.map.colorSpace)===En,decodeVideoTextureEmissive:V&&!0===s.emissiveMap.isVideoTexture&&vi.getTransfer(s.emissiveMap.colorSpace)===En,premultipliedAlpha:s.premultipliedAlpha,doubleSided:2===s.side,flipSided:1===s.side,useDepthPacking:s.depthPacking>=0,depthPacking:s.depthPacking||0,index0AttributeName:s.index0AttributeName,extensionClipCullDistance:fe&&!0===s.extensions.clipCullDistance&&i.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(fe&&!0===s.extensions.multiDraw||B)&&i.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:i.has("KHR_parallel_shader_compile"),customProgramCacheKey:s.customProgramCacheKey()};return ge.vertexUv1s=c.has(1),ge.vertexUv2s=c.has(2),ge.vertexUv3s=c.has(3),c.clear(),ge},getProgramCacheKey:function(t){const n=[];if(t.shaderID?n.push(t.shaderID):(n.push(t.customVertexShaderID),n.push(t.customFragmentShaderID)),void 0!==t.defines)for(const e in t.defines)n.push(e),n.push(t.defines[e]);return!1===t.isRawShaderMaterial&&(!function(e,t){e.push(t.precision),e.push(t.outputColorSpace),e.push(t.envMapMode),e.push(t.envMapCubeUVHeight),e.push(t.mapUv),e.push(t.alphaMapUv),e.push(t.lightMapUv),e.push(t.aoMapUv),e.push(t.bumpMapUv),e.push(t.normalMapUv),e.push(t.displacementMapUv),e.push(t.emissiveMapUv),e.push(t.metalnessMapUv),e.push(t.roughnessMapUv),e.push(t.anisotropyMapUv),e.push(t.clearcoatMapUv),e.push(t.clearcoatNormalMapUv),e.push(t.clearcoatRoughnessMapUv),e.push(t.iridescenceMapUv),e.push(t.iridescenceThicknessMapUv),e.push(t.sheenColorMapUv),e.push(t.sheenRoughnessMapUv),e.push(t.specularMapUv),e.push(t.specularColorMapUv),e.push(t.specularIntensityMapUv),e.push(t.transmissionMapUv),e.push(t.thicknessMapUv),e.push(t.combine),e.push(t.fogExp2),e.push(t.sizeAttenuation),e.push(t.morphTargetsCount),e.push(t.morphAttributeCount),e.push(t.numDirLights),e.push(t.numPointLights),e.push(t.numSpotLights),e.push(t.numSpotLightMaps),e.push(t.numHemiLights),e.push(t.numRectAreaLights),e.push(t.numDirLightShadows),e.push(t.numPointLightShadows),e.push(t.numSpotLightShadows),e.push(t.numSpotLightShadowsWithMaps),e.push(t.numLightProbes),e.push(t.shadowMapType),e.push(t.toneMapping),e.push(t.numClippingPlanes),e.push(t.numClipIntersection),e.push(t.depthPacking)}(n,t),function(e,t){o.disableAll(),t.instancing&&o.enable(0);t.instancingColor&&o.enable(1);t.instancingMorph&&o.enable(2);t.matcap&&o.enable(3);t.envMap&&o.enable(4);t.normalMapObjectSpace&&o.enable(5);t.normalMapTangentSpace&&o.enable(6);t.clearcoat&&o.enable(7);t.iridescence&&o.enable(8);t.alphaTest&&o.enable(9);t.vertexColors&&o.enable(10);t.vertexAlphas&&o.enable(11);t.vertexUv1s&&o.enable(12);t.vertexUv2s&&o.enable(13);t.vertexUv3s&&o.enable(14);t.vertexTangents&&o.enable(15);t.anisotropy&&o.enable(16);t.alphaHash&&o.enable(17);t.batching&&o.enable(18);t.dispersion&&o.enable(19);t.batchingColor&&o.enable(20);t.gradientMap&&o.enable(21);e.push(o.mask),o.disableAll(),t.fog&&o.enable(0);t.useFog&&o.enable(1);t.flatShading&&o.enable(2);t.logarithmicDepthBuffer&&o.enable(3);t.reversedDepthBuffer&&o.enable(4);t.skinning&&o.enable(5);t.morphTargets&&o.enable(6);t.morphNormals&&o.enable(7);t.morphColors&&o.enable(8);t.premultipliedAlpha&&o.enable(9);t.shadowMapEnabled&&o.enable(10);t.doubleSided&&o.enable(11);t.flipSided&&o.enable(12);t.useDepthPacking&&o.enable(13);t.dithering&&o.enable(14);t.transmission&&o.enable(15);t.sheen&&o.enable(16);t.opaque&&o.enable(17);t.pointsUvs&&o.enable(18);t.decodeVideoTexture&&o.enable(19);t.decodeVideoTextureEmissive&&o.enable(20);t.alphaToCoverage&&o.enable(21);e.push(o.mask)}(n,t),n.push(e.outputColorSpace)),n.push(t.customProgramCacheKey),n.join()},getUniforms:function(e){const t=f[e.type];let n;if(t){const e=Al[t];n=Os.clone(e.uniforms)}else n=e.uniforms;return n},acquireProgram:function(t,n){let i=u.get(n);return void 0!==i?++i.usedTimes:(i=new Ph(e,n,t,s),h.push(i),u.set(n,i)),i},releaseProgram:function(e){if(0===--e.usedTimes){const t=h.indexOf(e);h[t]=h[h.length-1],h.pop(),u.delete(e.cacheKey),e.destroy()}},releaseShaderCache:function(e){l.remove(e)},programs:h,dispose:function(){l.dispose()}}}function Uh(){let e=new WeakMap;return{has:function(t){return e.has(t)},get:function(t){let n=e.get(t);return void 0===n&&(n={},e.set(t,n)),n},remove:function(t){e.delete(t)},update:function(t,n,i){e.get(t)[n]=i},dispose:function(){e=new WeakMap}}}function kh(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.material.id!==t.material.id?e.material.id-t.material.id:e.z!==t.z?e.z-t.z:e.id-t.id}function Nh(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.z!==t.z?t.z-e.z:e.id-t.id}function Oh(){const e=[];let t=0;const n=[],i=[],r=[];function s(n,i,r,s,a,o){let l=e[t];return void 0===l?(l={id:n.id,object:n,geometry:i,material:r,groupOrder:s,renderOrder:n.renderOrder,z:a,group:o},e[t]=l):(l.id=n.id,l.object=n,l.geometry=i,l.material=r,l.groupOrder=s,l.renderOrder=n.renderOrder,l.z=a,l.group=o),t++,l}return{opaque:n,transmissive:i,transparent:r,init:function(){t=0,n.length=0,i.length=0,r.length=0},push:function(e,t,a,o,l,c){const h=s(e,t,a,o,l,c);a.transmission>0?i.push(h):!0===a.transparent?r.push(h):n.push(h)},unshift:function(e,t,a,o,l,c){const h=s(e,t,a,o,l,c);a.transmission>0?i.unshift(h):!0===a.transparent?r.unshift(h):n.unshift(h)},finish:function(){for(let n=t,i=e.length;n<i;n++){const t=e[n];if(null===t.id)break;t.id=null,t.object=null,t.geometry=null,t.material=null,t.group=null}},sort:function(e,t){n.length>1&&n.sort(e||kh),i.length>1&&i.sort(t||Nh),r.length>1&&r.sort(t||Nh)}}}function zh(){let e=new WeakMap;return{get:function(t,n){const i=e.get(t);let r;return void 0===i?(r=new Oh,e.set(t,[r])):n>=i.length?(r=new Oh,i.push(r)):r=i[n],r},dispose:function(){e=new WeakMap}}}function Hh(){const e={};return{get:function(t){if(void 0!==e[t.id])return e[t.id];let n;switch(t.type){case"DirectionalLight":n={direction:new hi,color:new $r};break;case"SpotLight":n={position:new hi,direction:new hi,color:new $r,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":n={position:new hi,color:new $r,distance:0,decay:0};break;case"HemisphereLight":n={direction:new hi,skyColor:new $r,groundColor:new $r};break;case"RectAreaLight":n={color:new $r,position:new hi,halfWidth:new hi,halfHeight:new hi}}return e[t.id]=n,n}}}let Vh=0;function Gh(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+(t.map?1:0)-(e.map?1:0)}function Wh(e){const t=new Hh,n=function(){const e={};return{get:function(t){if(void 0!==e[t.id])return e[t.id];let n;switch(t.type){case"DirectionalLight":case"SpotLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new li};break;case"PointLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new li,shadowCameraNear:1,shadowCameraFar:1e3}}return e[t.id]=n,n}}}(),i={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let o=0;o<9;o++)i.probe.push(new hi);const r=new hi,s=new or,a=new or;return{setup:function(r){let s=0,a=0,o=0;for(let e=0;e<9;e++)i.probe[e].set(0,0,0);let l=0,c=0,h=0,u=0,d=0,p=0,f=0,m=0,g=0,_=0,v=0;r.sort(Gh);for(let e=0,y=r.length;e<y;e++){const x=r[e],y=x.color,S=x.intensity,A=x.distance;let b=null;if(x.shadow&&x.shadow.map&&(b=x.shadow.map.texture.format===Ct?x.shadow.map.texture:x.shadow.map.depthTexture||x.shadow.map.texture),x.isAmbientLight)s+=y.r*S,a+=y.g*S,o+=y.b*S;else if(x.isLightProbe){for(let e=0;e<9;e++)i.probe[e].addScaledVector(x.sh.coefficients[e],S);v++}else if(x.isDirectionalLight){const e=t.get(x);if(e.color.copy(x.color).multiplyScalar(x.intensity),x.castShadow){const e=x.shadow,t=n.get(x);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize=e.mapSize,i.directionalShadow[l]=t,i.directionalShadowMap[l]=b,i.directionalShadowMatrix[l]=x.shadow.matrix,p++}i.directional[l]=e,l++}else if(x.isSpotLight){const e=t.get(x);e.position.setFromMatrixPosition(x.matrixWorld),e.color.copy(y).multiplyScalar(S),e.distance=A,e.coneCos=Math.cos(x.angle),e.penumbraCos=Math.cos(x.angle*(1-x.penumbra)),e.decay=x.decay,i.spot[h]=e;const r=x.shadow;if(x.map&&(i.spotLightMap[g]=x.map,g++,r.updateMatrices(x),x.castShadow&&_++),i.spotLightMatrix[h]=r.matrix,x.castShadow){const e=n.get(x);e.shadowIntensity=r.intensity,e.shadowBias=r.bias,e.shadowNormalBias=r.normalBias,e.shadowRadius=r.radius,e.shadowMapSize=r.mapSize,i.spotShadow[h]=e,i.spotShadowMap[h]=b,m++}h++}else if(x.isRectAreaLight){const e=t.get(x);e.color.copy(y).multiplyScalar(S),e.halfWidth.set(.5*x.width,0,0),e.halfHeight.set(0,.5*x.height,0),i.rectArea[u]=e,u++}else if(x.isPointLight){const e=t.get(x);if(e.color.copy(x.color).multiplyScalar(x.intensity),e.distance=x.distance,e.decay=x.decay,x.castShadow){const e=x.shadow,t=n.get(x);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize=e.mapSize,t.shadowCameraNear=e.camera.near,t.shadowCameraFar=e.camera.far,i.pointShadow[c]=t,i.pointShadowMap[c]=b,i.pointShadowMatrix[c]=x.shadow.matrix,f++}i.point[c]=e,c++}else if(x.isHemisphereLight){const e=t.get(x);e.skyColor.copy(x.color).multiplyScalar(S),e.groundColor.copy(x.groundColor).multiplyScalar(S),i.hemi[d]=e,d++}}u>0&&(!0===e.has("OES_texture_float_linear")?(i.rectAreaLTC1=Sl.LTC_FLOAT_1,i.rectAreaLTC2=Sl.LTC_FLOAT_2):(i.rectAreaLTC1=Sl.LTC_HALF_1,i.rectAreaLTC2=Sl.LTC_HALF_2)),i.ambient[0]=s,i.ambient[1]=a,i.ambient[2]=o;const x=i.hash;x.directionalLength===l&&x.pointLength===c&&x.spotLength===h&&x.rectAreaLength===u&&x.hemiLength===d&&x.numDirectionalShadows===p&&x.numPointShadows===f&&x.numSpotShadows===m&&x.numSpotMaps===g&&x.numLightProbes===v||(i.directional.length=l,i.spot.length=h,i.rectArea.length=u,i.point.length=c,i.hemi.length=d,i.directionalShadow.length=p,i.directionalShadowMap.length=p,i.pointShadow.length=f,i.pointShadowMap.length=f,i.spotShadow.length=m,i.spotShadowMap.length=m,i.directionalShadowMatrix.length=p,i.pointShadowMatrix.length=f,i.spotLightMatrix.length=m+g-_,i.spotLightMap.length=g,i.numSpotLightShadowsWithMaps=_,i.numLightProbes=v,x.directionalLength=l,x.pointLength=c,x.spotLength=h,x.rectAreaLength=u,x.hemiLength=d,x.numDirectionalShadows=p,x.numPointShadows=f,x.numSpotShadows=m,x.numSpotMaps=g,x.numLightProbes=v,i.version=Vh++)},setupView:function(e,t){let n=0,o=0,l=0,c=0,h=0;const u=t.matrixWorldInverse;for(let d=0,p=e.length;d<p;d++){const t=e[d];if(t.isDirectionalLight){const e=i.directional[n];e.direction.setFromMatrixPosition(t.matrixWorld),r.setFromMatrixPosition(t.target.matrixWorld),e.direction.sub(r),e.direction.transformDirection(u),n++}else if(t.isSpotLight){const e=i.spot[l];e.position.setFromMatrixPosition(t.matrixWorld),e.position.applyMatrix4(u),e.direction.setFromMatrixPosition(t.matrixWorld),r.setFromMatrixPosition(t.target.matrixWorld),e.direction.sub(r),e.direction.transformDirection(u),l++}else if(t.isRectAreaLight){const e=i.rectArea[c];e.position.setFromMatrixPosition(t.matrixWorld),e.position.applyMatrix4(u),a.identity(),s.copy(t.matrixWorld),s.premultiply(u),a.extractRotation(s),e.halfWidth.set(.5*t.width,0,0),e.halfHeight.set(0,.5*t.height,0),e.halfWidth.applyMatrix4(a),e.halfHeight.applyMatrix4(a),c++}else if(t.isPointLight){const e=i.point[o];e.position.setFromMatrixPosition(t.matrixWorld),e.position.applyMatrix4(u),o++}else if(t.isHemisphereLight){const e=i.hemi[h];e.direction.setFromMatrixPosition(t.matrixWorld),e.direction.transformDirection(u),h++}}},state:i}}function jh(e){const t=new Wh(e),n=[],i=[];const r={lightsArray:n,shadowsArray:i,camera:null,lights:t,transmissionRenderTarget:{}};return{init:function(e){r.camera=e,n.length=0,i.length=0},state:r,setupLights:function(){t.setup(n)},setupLightsView:function(e){t.setupView(n,e)},pushLight:function(e){n.push(e)},pushShadow:function(e){i.push(e)}}}function Xh(e){let t=new WeakMap;return{get:function(n,i=0){const r=t.get(n);let s;return void 0===r?(s=new jh(e),t.set(n,[s])):i>=r.length?(s=new jh(e),r.push(s)):s=r[i],s},dispose:function(){t=new WeakMap}}}const qh=[new hi(1,0,0),new hi(-1,0,0),new hi(0,1,0),new hi(0,-1,0),new hi(0,0,1),new hi(0,0,-1)],Qh=[new hi(0,-1,0),new hi(0,-1,0),new hi(0,0,1),new hi(0,0,-1),new hi(0,-1,0),new hi(0,-1,0)],Kh=new or,Yh=new hi,Zh=new hi;function Jh(e,t,n){let i=new La;const r=new li,s=new li,a=new Ri,o=new co,l=new ho,c={},h=n.maxTextureSize,u={[de]:1,[pe]:0,[fe]:2},d=new zs({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new li},radius:{value:4}},vertexShader:"void main() {\n\tgl_Position = vec4( position, 1.0 );\n}",fragmentShader:"uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ).rg;\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ).r;\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( max( 0.0, squared_mean - mean * mean ) );\n\tgl_FragColor = vec4( mean, std_dev, 0.0, 1.0 );\n}"}),p=d.clone();p.defines.HORIZONTAL_PASS=1;const f=new Ss;f.setAttribute("position",new hs(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const m=new Bs(f,d),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1;let _=this.type;function v(n,i){const s=t.update(m);d.defines.VSM_SAMPLES!==n.blurSamples&&(d.defines.VSM_SAMPLES=n.blurSamples,p.defines.VSM_SAMPLES=n.blurSamples,d.needsUpdate=!0,p.needsUpdate=!0),null===n.mapPass&&(n.mapPass=new Pi(r.x,r.y,{format:Ct,type:_t})),d.uniforms.shadow_pass.value=n.map.depthTexture,d.uniforms.resolution.value=n.mapSize,d.uniforms.radius.value=n.radius,e.setRenderTarget(n.mapPass),e.clear(),e.renderBufferDirect(i,null,s,d,m,null),p.uniforms.shadow_pass.value=n.mapPass.texture,p.uniforms.resolution.value=n.mapSize,p.uniforms.radius.value=n.radius,e.setRenderTarget(n.map),e.clear(),e.renderBufferDirect(i,null,s,p,m,null)}function x(t,n,i,r){let s=null;const a=!0===i.isPointLight?t.customDistanceMaterial:t.customDepthMaterial;if(void 0!==a)s=a;else if(s=!0===i.isPointLight?l:o,e.localClippingEnabled&&!0===n.clipShadows&&Array.isArray(n.clippingPlanes)&&0!==n.clippingPlanes.length||n.displacementMap&&0!==n.displacementScale||n.alphaMap&&n.alphaTest>0||n.map&&n.alphaTest>0||!0===n.alphaToCoverage){const e=s.uuid,t=n.uuid;let i=c[e];void 0===i&&(i={},c[e]=i);let r=i[t];void 0===r&&(r=s.clone(),i[t]=r,n.addEventListener("dispose",S)),s=r}if(s.visible=n.visible,s.wireframe=n.wireframe,s.side=3===r?null!==n.shadowSide?n.shadowSide:n.side:null!==n.shadowSide?n.shadowSide:u[n.side],s.alphaMap=n.alphaMap,s.alphaTest=!0===n.alphaToCoverage?.5:n.alphaTest,s.map=n.map,s.clipShadows=n.clipShadows,s.clippingPlanes=n.clippingPlanes,s.clipIntersection=n.clipIntersection,s.displacementMap=n.displacementMap,s.displacementScale=n.displacementScale,s.displacementBias=n.displacementBias,s.wireframeLinewidth=n.wireframeLinewidth,s.linewidth=n.linewidth,!0===i.isPointLight&&!0===s.isMeshDistanceMaterial){e.properties.get(s).light=i}return s}function y(n,r,s,a,o){if(!1===n.visible)return;if(n.layers.test(r.layers)&&(n.isMesh||n.isLine||n.isPoints)&&(n.castShadow||n.receiveShadow&&3===o)&&(!n.frustumCulled||i.intersectsObject(n))){n.modelViewMatrix.multiplyMatrices(s.matrixWorldInverse,n.matrixWorld);const i=t.update(n),l=n.material;if(Array.isArray(l)){const t=i.groups;for(let c=0,h=t.length;c<h;c++){const h=t[c],u=l[h.materialIndex];if(u&&u.visible){const t=x(n,u,a,o);n.onBeforeShadow(e,n,r,s,i,t,h),e.renderBufferDirect(s,null,i,t,n,h),n.onAfterShadow(e,n,r,s,i,t,h)}}}else if(l.visible){const t=x(n,l,a,o);n.onBeforeShadow(e,n,r,s,i,t,null),e.renderBufferDirect(s,null,i,t,n,null),n.onAfterShadow(e,n,r,s,i,t,null)}}const l=n.children;for(let e=0,t=l.length;e<t;e++)y(l[e],r,s,a,o)}function S(e){e.target.removeEventListener("dispose",S);for(const t in c){const n=c[t],i=e.target.uuid;if(i in n){n[i].dispose(),delete n[i]}}}this.render=function(t,n,o){if(!1===g.enabled)return;if(!1===g.autoUpdate&&!1===g.needsUpdate)return;if(0===t.length)return;2===t.type&&(qn("WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead."),t.type=1);const l=e.getRenderTarget(),c=e.getActiveCubeFace(),u=e.getActiveMipmapLevel(),d=e.state;d.setBlending(0),!0===d.buffers.depth.getReversed()?d.buffers.color.setClear(0,0,0,0):d.buffers.color.setClear(1,1,1,1),d.buffers.depth.setTest(!0),d.setScissorTest(!1);const p=_!==this.type;p&&n.traverse(function(e){e.material&&(Array.isArray(e.material)?e.material.forEach(e=>e.needsUpdate=!0):e.material.needsUpdate=!0)});for(let f=0,m=t.length;f<m;f++){const l=t[f],c=l.shadow;if(void 0===c){qn("WebGLShadowMap:",l,"has no shadow.");continue}if(!1===c.autoUpdate&&!1===c.needsUpdate)continue;r.copy(c.mapSize);const u=c.getFrameExtents();if(r.multiply(u),s.copy(c.mapSize),(r.x>h||r.y>h)&&(r.x>h&&(s.x=Math.floor(h/u.x),r.x=s.x*u.x,c.mapSize.x=s.x),r.y>h&&(s.y=Math.floor(h/u.y),r.y=s.y*u.y,c.mapSize.y=s.y)),null===c.map||!0===p){if(null!==c.map&&(null!==c.map.depthTexture&&(c.map.depthTexture.dispose(),c.map.depthTexture=null),c.map.dispose()),3===this.type){if(l.isPointLight){qn("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}c.map=new Pi(r.x,r.y,{format:Ct,type:_t,minFilter:ot,magFilter:ot,generateMipmaps:!1}),c.map.texture.name=l.name+".shadowMap",c.map.depthTexture=new no(r.x,r.y,gt),c.map.depthTexture.name=l.name+".shadowMapDepth",c.map.depthTexture.format=Mt,c.map.depthTexture.compareFunction=null,c.map.depthTexture.minFilter=rt,c.map.depthTexture.magFilter=rt}else{l.isPointLight?(c.map=new Ks(r.x),c.map.depthTexture=new io(r.x,mt)):(c.map=new Pi(r.x,r.y),c.map.depthTexture=new no(r.x,r.y,mt)),c.map.depthTexture.name=l.name+".shadowMap",c.map.depthTexture.format=Mt;const t=e.state.buffers.depth.getReversed();1===this.type?(c.map.depthTexture.compareFunction=t?518:515,c.map.depthTexture.minFilter=ot,c.map.depthTexture.magFilter=ot):(c.map.depthTexture.compareFunction=null,c.map.depthTexture.minFilter=rt,c.map.depthTexture.magFilter=rt)}c.camera.updateProjectionMatrix()}const m=c.map.isWebGLCubeRenderTarget?6:1;for(let t=0;t<m;t++){if(c.map.isWebGLCubeRenderTarget)e.setRenderTarget(c.map,t),e.clear();else{0===t&&(e.setRenderTarget(c.map),e.clear());const n=c.getViewport(t);a.set(s.x*n.x,s.y*n.y,s.x*n.z,s.y*n.w),d.viewport(a)}if(l.isPointLight){const e=c.camera,n=c.matrix,i=l.distance||e.far;i!==e.far&&(e.far=i,e.updateProjectionMatrix()),Yh.setFromMatrixPosition(l.matrixWorld),e.position.copy(Yh),Zh.copy(e.position),Zh.add(qh[t]),e.up.copy(Qh[t]),e.lookAt(Zh),e.updateMatrixWorld(),n.makeTranslation(-Yh.x,-Yh.y,-Yh.z),Kh.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),c._frustum.setFromProjectionMatrix(Kh,e.coordinateSystem,e.reversedDepth)}else c.updateMatrices(l);i=c.getFrustum(),y(n,o,c.camera,l,this.type)}!0!==c.isPointLightShadow&&3===this.type&&v(c,o),c.needsUpdate=!1}_=this.type,g.needsUpdate=!1,e.setRenderTarget(l,c,u)}}const $h={[Be]:1,[Fe]:6,[ke]:7,[Ue]:5,[Le]:0,[Oe]:2,[ze]:4,[Ne]:3};function eu(e,t){const n=new function(){let t=!1;const n=new Ri;let i=null;const r=new Ri(0,0,0,0);return{setMask:function(n){i===n||t||(e.colorMask(n,n,n,n),i=n)},setLocked:function(e){t=e},setClear:function(t,i,s,a,o){!0===o&&(t*=a,i*=a,s*=a),n.set(t,i,s,a),!1===r.equals(n)&&(e.clearColor(t,i,s,a),r.copy(n))},reset:function(){t=!1,i=null,r.set(-1,0,0,0)}}},i=new function(){let n=!1,i=!1,r=null,s=null,a=null;return{setReversed:function(e){if(i!==e){const n=t.get("EXT_clip_control");e?n.clipControlEXT(n.LOWER_LEFT_EXT,n.ZERO_TO_ONE_EXT):n.clipControlEXT(n.LOWER_LEFT_EXT,n.NEGATIVE_ONE_TO_ONE_EXT),i=e;const r=a;a=null,this.setClear(r)}},getReversed:function(){return i},setTest:function(t){t?z(e.DEPTH_TEST):H(e.DEPTH_TEST)},setMask:function(t){r===t||n||(e.depthMask(t),r=t)},setFunc:function(t){if(i&&(t=$h[t]),s!==t){switch(t){case 0:e.depthFunc(e.NEVER);break;case 1:e.depthFunc(e.ALWAYS);break;case 2:e.depthFunc(e.LESS);break;case 3:default:e.depthFunc(e.LEQUAL);break;case 4:e.depthFunc(e.EQUAL);break;case 5:e.depthFunc(e.GEQUAL);break;case 6:e.depthFunc(e.GREATER);break;case 7:e.depthFunc(e.NOTEQUAL)}s=t}},setLocked:function(e){n=e},setClear:function(t){a!==t&&(i&&(t=1-t),e.clearDepth(t),a=t)},reset:function(){n=!1,r=null,s=null,a=null,i=!1}}},r=new function(){let t=!1,n=null,i=null,r=null,s=null,a=null,o=null,l=null,c=null;return{setTest:function(n){t||(n?z(e.STENCIL_TEST):H(e.STENCIL_TEST))},setMask:function(i){n===i||t||(e.stencilMask(i),n=i)},setFunc:function(t,n,a){i===t&&r===n&&s===a||(e.stencilFunc(t,n,a),i=t,r=n,s=a)},setOp:function(t,n,i){a===t&&o===n&&l===i||(e.stencilOp(t,n,i),a=t,o=n,l=i)},setLocked:function(e){t=e},setClear:function(t){c!==t&&(e.clearStencil(t),c=t)},reset:function(){t=!1,n=null,i=null,r=null,s=null,a=null,o=null,l=null,c=null}}},s=new WeakMap,a=new WeakMap;let o={},l={},c=new WeakMap,h=[],u=null,d=!1,p=null,f=null,m=null,g=null,_=null,v=null,x=null,y=new $r(0,0,0),S=0,A=!1,b=null,M=null,w=null,T=null,E=null;const C=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let R=!1,I=0;const P=e.getParameter(e.VERSION);-1!==P.indexOf("WebGL")?(I=parseFloat(/^WebGL (\d)/.exec(P)[1]),R=I>=1):-1!==P.indexOf("OpenGL ES")&&(I=parseFloat(/^OpenGL ES (\d)/.exec(P)[1]),R=I>=2);let D=null,B={};const L=e.getParameter(e.SCISSOR_BOX),F=e.getParameter(e.VIEWPORT),U=(new Ri).fromArray(L),k=(new Ri).fromArray(F);function N(t,n,i,r){const s=new Uint8Array(4),a=e.createTexture();e.bindTexture(t,a),e.texParameteri(t,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(t,e.TEXTURE_MAG_FILTER,e.NEAREST);for(let o=0;o<i;o++)t===e.TEXTURE_3D||t===e.TEXTURE_2D_ARRAY?e.texImage3D(n,0,e.RGBA,1,1,r,0,e.RGBA,e.UNSIGNED_BYTE,s):e.texImage2D(n+o,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,s);return a}const O={};function z(t){!0!==o[t]&&(e.enable(t),o[t]=!0)}function H(t){!1!==o[t]&&(e.disable(t),o[t]=!1)}O[e.TEXTURE_2D]=N(e.TEXTURE_2D,e.TEXTURE_2D,1),O[e.TEXTURE_CUBE_MAP]=N(e.TEXTURE_CUBE_MAP,e.TEXTURE_CUBE_MAP_POSITIVE_X,6),O[e.TEXTURE_2D_ARRAY]=N(e.TEXTURE_2D_ARRAY,e.TEXTURE_2D_ARRAY,1,1),O[e.TEXTURE_3D]=N(e.TEXTURE_3D,e.TEXTURE_3D,1,1),n.setClear(0,0,0,1),i.setClear(1),r.setClear(0),z(e.DEPTH_TEST),i.setFunc(3),j(!1),X(1),z(e.CULL_FACE),W(0);const V={[me]:e.FUNC_ADD,[ge]:e.FUNC_SUBTRACT,[_e]:e.FUNC_REVERSE_SUBTRACT};V[103]=e.MIN,V[104]=e.MAX;const G={[ve]:e.ZERO,[xe]:e.ONE,[ye]:e.SRC_COLOR,[Ae]:e.SRC_ALPHA,[Ce]:e.SRC_ALPHA_SATURATE,[Te]:e.DST_COLOR,[Me]:e.DST_ALPHA,[Se]:e.ONE_MINUS_SRC_COLOR,[be]:e.ONE_MINUS_SRC_ALPHA,[Ee]:e.ONE_MINUS_DST_COLOR,[we]:e.ONE_MINUS_DST_ALPHA,[Re]:e.CONSTANT_COLOR,[Ie]:e.ONE_MINUS_CONSTANT_COLOR,[Pe]:e.CONSTANT_ALPHA,[De]:e.ONE_MINUS_CONSTANT_ALPHA};function W(t,n,i,r,s,a,o,l,c,h){if(0!==t){if(!1===d&&(z(e.BLEND),d=!0),5===t)s=s||n,a=a||i,o=o||r,n===f&&s===_||(e.blendEquationSeparate(V[n],V[s]),f=n,_=s),i===m&&r===g&&a===v&&o===x||(e.blendFuncSeparate(G[i],G[r],G[a],G[o]),m=i,g=r,v=a,x=o),!1!==l.equals(y)&&c===S||(e.blendColor(l.r,l.g,l.b,c),y.copy(l),S=c),p=t,A=!1;else if(t!==p||h!==A){if(f===me&&_===me||(e.blendEquation(e.FUNC_ADD),f=me,_=me),h)switch(t){case 1:e.blendFuncSeparate(e.ONE,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 2:e.blendFunc(e.ONE,e.ONE);break;case 3:e.blendFuncSeparate(e.ZERO,e.ONE_MINUS_SRC_COLOR,e.ZERO,e.ONE);break;case 4:e.blendFuncSeparate(e.DST_COLOR,e.ONE_MINUS_SRC_ALPHA,e.ZERO,e.ONE);break;default:Qn("WebGLState: Invalid blending: ",t)}else switch(t){case 1:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 2:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE,e.ONE,e.ONE);break;case 3:Qn("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case 4:Qn("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:Qn("WebGLState: Invalid blending: ",t)}m=null,g=null,v=null,x=null,y.set(0,0,0),S=0,p=t,A=h}}else!0===d&&(H(e.BLEND),d=!1)}function j(t){b!==t&&(t?e.frontFace(e.CW):e.frontFace(e.CCW),b=t)}function X(t){0!==t?(z(e.CULL_FACE),t!==M&&(1===t?e.cullFace(e.BACK):2===t?e.cullFace(e.FRONT):e.cullFace(e.FRONT_AND_BACK))):H(e.CULL_FACE),M=t}function q(t,n,i){t?(z(e.POLYGON_OFFSET_FILL),T===n&&E===i||(e.polygonOffset(n,i),T=n,E=i)):H(e.POLYGON_OFFSET_FILL)}return{buffers:{color:n,depth:i,stencil:r},enable:z,disable:H,bindFramebuffer:function(t,n){return l[t]!==n&&(e.bindFramebuffer(t,n),l[t]=n,t===e.DRAW_FRAMEBUFFER&&(l[e.FRAMEBUFFER]=n),t===e.FRAMEBUFFER&&(l[e.DRAW_FRAMEBUFFER]=n),!0)},drawBuffers:function(t,n){let i=h,r=!1;if(t){i=c.get(n),void 0===i&&(i=[],c.set(n,i));const s=t.textures;if(i.length!==s.length||i[0]!==e.COLOR_ATTACHMENT0){for(let t=0,n=s.length;t<n;t++)i[t]=e.COLOR_ATTACHMENT0+t;i.length=s.length,r=!0}}else i[0]!==e.BACK&&(i[0]=e.BACK,r=!0);r&&e.drawBuffers(i)},useProgram:function(t){return u!==t&&(e.useProgram(t),u=t,!0)},setBlending:W,setMaterial:function(t,s){2===t.side?H(e.CULL_FACE):z(e.CULL_FACE);let a=1===t.side;s&&(a=!a),j(a),1===t.blending&&!1===t.transparent?W(0):W(t.blending,t.blendEquation,t.blendSrc,t.blendDst,t.blendEquationAlpha,t.blendSrcAlpha,t.blendDstAlpha,t.blendColor,t.blendAlpha,t.premultipliedAlpha),i.setFunc(t.depthFunc),i.setTest(t.depthTest),i.setMask(t.depthWrite),n.setMask(t.colorWrite);const o=t.stencilWrite;r.setTest(o),o&&(r.setMask(t.stencilWriteMask),r.setFunc(t.stencilFunc,t.stencilRef,t.stencilFuncMask),r.setOp(t.stencilFail,t.stencilZFail,t.stencilZPass)),q(t.polygonOffset,t.polygonOffsetFactor,t.polygonOffsetUnits),!0===t.alphaToCoverage?z(e.SAMPLE_ALPHA_TO_COVERAGE):H(e.SAMPLE_ALPHA_TO_COVERAGE)},setFlipSided:j,setCullFace:X,setLineWidth:function(t){t!==w&&(R&&e.lineWidth(t),w=t)},setPolygonOffset:q,setScissorTest:function(t){t?z(e.SCISSOR_TEST):H(e.SCISSOR_TEST)},activeTexture:function(t){void 0===t&&(t=e.TEXTURE0+C-1),D!==t&&(e.activeTexture(t),D=t)},bindTexture:function(t,n,i){void 0===i&&(i=null===D?e.TEXTURE0+C-1:D);let r=B[i];void 0===r&&(r={type:void 0,texture:void 0},B[i]=r),r.type===t&&r.texture===n||(D!==i&&(e.activeTexture(i),D=i),e.bindTexture(t,n||O[t]),r.type=t,r.texture=n)},unbindTexture:function(){const t=B[D];void 0!==t&&void 0!==t.type&&(e.bindTexture(t.type,null),t.type=void 0,t.texture=void 0)},compressedTexImage2D:function(){try{e.compressedTexImage2D(...arguments)}catch(t){Qn("WebGLState:",t)}},compressedTexImage3D:function(){try{e.compressedTexImage3D(...arguments)}catch(t){Qn("WebGLState:",t)}},texImage2D:function(){try{e.texImage2D(...arguments)}catch(t){Qn("WebGLState:",t)}},texImage3D:function(){try{e.texImage3D(...arguments)}catch(t){Qn("WebGLState:",t)}},updateUBOMapping:function(t,n){let i=a.get(n);void 0===i&&(i=new WeakMap,a.set(n,i));let r=i.get(t);void 0===r&&(r=e.getUniformBlockIndex(n,t.name),i.set(t,r))},uniformBlockBinding:function(t,n){const i=a.get(n).get(t);s.get(n)!==i&&(e.uniformBlockBinding(n,i,t.__bindingPointIndex),s.set(n,i))},texStorage2D:function(){try{e.texStorage2D(...arguments)}catch(t){Qn("WebGLState:",t)}},texStorage3D:function(){try{e.texStorage3D(...arguments)}catch(t){Qn("WebGLState:",t)}},texSubImage2D:function(){try{e.texSubImage2D(...arguments)}catch(t){Qn("WebGLState:",t)}},texSubImage3D:function(){try{e.texSubImage3D(...arguments)}catch(t){Qn("WebGLState:",t)}},compressedTexSubImage2D:function(){try{e.compressedTexSubImage2D(...arguments)}catch(t){Qn("WebGLState:",t)}},compressedTexSubImage3D:function(){try{e.compressedTexSubImage3D(...arguments)}catch(t){Qn("WebGLState:",t)}},scissor:function(t){!1===U.equals(t)&&(e.scissor(t.x,t.y,t.z,t.w),U.copy(t))},viewport:function(t){!1===k.equals(t)&&(e.viewport(t.x,t.y,t.z,t.w),k.copy(t))},reset:function(){e.disable(e.BLEND),e.disable(e.CULL_FACE),e.disable(e.DEPTH_TEST),e.disable(e.POLYGON_OFFSET_FILL),e.disable(e.SCISSOR_TEST),e.disable(e.STENCIL_TEST),e.disable(e.SAMPLE_ALPHA_TO_COVERAGE),e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ZERO),e.blendFuncSeparate(e.ONE,e.ZERO,e.ONE,e.ZERO),e.blendColor(0,0,0,0),e.colorMask(!0,!0,!0,!0),e.clearColor(0,0,0,0),e.depthMask(!0),e.depthFunc(e.LESS),i.setReversed(!1),e.clearDepth(1),e.stencilMask(4294967295),e.stencilFunc(e.ALWAYS,0,4294967295),e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.clearStencil(0),e.cullFace(e.BACK),e.frontFace(e.CCW),e.polygonOffset(0,0),e.activeTexture(e.TEXTURE0),e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),e.bindFramebuffer(e.READ_FRAMEBUFFER,null),e.useProgram(null),e.lineWidth(1),e.scissor(0,0,e.canvas.width,e.canvas.height),e.viewport(0,0,e.canvas.width,e.canvas.height),o={},D=null,B={},l={},c=new WeakMap,h=[],u=null,d=!1,p=null,f=null,m=null,g=null,_=null,v=null,x=null,y=new $r(0,0,0),S=0,A=!1,b=null,M=null,w=null,T=null,E=null,U.set(0,0,e.canvas.width,e.canvas.height),k.set(0,0,e.canvas.width,e.canvas.height),n.reset(),i.reset(),r.reset()}}}function tu(e,t,n,i,r,s,a){const o=t.has("WEBGL_multisampled_render_to_texture")?t.get("WEBGL_multisampled_render_to_texture"):null,l="undefined"!=typeof navigator&&/OculusBrowser/g.test(navigator.userAgent),c=new li,h=new WeakMap;let u;const d=new WeakMap;let p=!1;try{p="undefined"!=typeof OffscreenCanvas&&null!==new OffscreenCanvas(1,1).getContext("2d")}catch(W){}function f(e,t){return p?new OffscreenCanvas(e,t):Gn("canvas")}function m(e,t,n){let i=1;const r=G(e);if((r.width>n||r.height>n)&&(i=n/Math.max(r.width,r.height)),i<1){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof VideoFrame&&e instanceof VideoFrame){const n=Math.floor(i*r.width),s=Math.floor(i*r.height);void 0===u&&(u=f(n,s));const a=t?f(n,s):u;a.width=n,a.height=s;return a.getContext("2d").drawImage(e,0,0,n,s),qn("WebGLRenderer: Texture has been resized from ("+r.width+"x"+r.height+") to ("+n+"x"+s+")."),a}return"data"in e&&qn("WebGLRenderer: Image in DataTexture is too big ("+r.width+"x"+r.height+")."),e}return e}function g(e){return e.generateMipmaps}function _(t){e.generateMipmap(t)}function v(t){return t.isWebGLCubeRenderTarget?e.TEXTURE_CUBE_MAP:t.isWebGL3DRenderTarget?e.TEXTURE_3D:t.isWebGLArrayRenderTarget||t.isCompressedArrayTexture?e.TEXTURE_2D_ARRAY:e.TEXTURE_2D}function x(n,i,r,s,a=!1){if(null!==n){if(void 0!==e[n])return e[n];qn("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+n+"'")}let o=i;if(i===e.RED&&(r===e.FLOAT&&(o=e.R32F),r===e.HALF_FLOAT&&(o=e.R16F),r===e.UNSIGNED_BYTE&&(o=e.R8)),i===e.RED_INTEGER&&(r===e.UNSIGNED_BYTE&&(o=e.R8UI),r===e.UNSIGNED_SHORT&&(o=e.R16UI),r===e.UNSIGNED_INT&&(o=e.R32UI),r===e.BYTE&&(o=e.R8I),r===e.SHORT&&(o=e.R16I),r===e.INT&&(o=e.R32I)),i===e.RG&&(r===e.FLOAT&&(o=e.RG32F),r===e.HALF_FLOAT&&(o=e.RG16F),r===e.UNSIGNED_BYTE&&(o=e.RG8)),i===e.RG_INTEGER&&(r===e.UNSIGNED_BYTE&&(o=e.RG8UI),r===e.UNSIGNED_SHORT&&(o=e.RG16UI),r===e.UNSIGNED_INT&&(o=e.RG32UI),r===e.BYTE&&(o=e.RG8I),r===e.SHORT&&(o=e.RG16I),r===e.INT&&(o=e.RG32I)),i===e.RGB_INTEGER&&(r===e.UNSIGNED_BYTE&&(o=e.RGB8UI),r===e.UNSIGNED_SHORT&&(o=e.RGB16UI),r===e.UNSIGNED_INT&&(o=e.RGB32UI),r===e.BYTE&&(o=e.RGB8I),r===e.SHORT&&(o=e.RGB16I),r===e.INT&&(o=e.RGB32I)),i===e.RGBA_INTEGER&&(r===e.UNSIGNED_BYTE&&(o=e.RGBA8UI),r===e.UNSIGNED_SHORT&&(o=e.RGBA16UI),r===e.UNSIGNED_INT&&(o=e.RGBA32UI),r===e.BYTE&&(o=e.RGBA8I),r===e.SHORT&&(o=e.RGBA16I),r===e.INT&&(o=e.RGBA32I)),i===e.RGB&&(r===e.UNSIGNED_INT_5_9_9_9_REV&&(o=e.RGB9_E5),r===e.UNSIGNED_INT_10F_11F_11F_REV&&(o=e.R11F_G11F_B10F)),i===e.RGBA){const t=a?Tn:vi.getTransfer(s);r===e.FLOAT&&(o=e.RGBA32F),r===e.HALF_FLOAT&&(o=e.RGBA16F),r===e.UNSIGNED_BYTE&&(o=t===En?e.SRGB8_ALPHA8:e.RGBA8),r===e.UNSIGNED_SHORT_4_4_4_4&&(o=e.RGBA4),r===e.UNSIGNED_SHORT_5_5_5_1&&(o=e.RGB5_A1)}return o!==e.R16F&&o!==e.R32F&&o!==e.RG16F&&o!==e.RG32F&&o!==e.RGBA16F&&o!==e.RGBA32F||t.get("EXT_color_buffer_float"),o}function y(t,n){let i;return t?null===n||n===mt||n===yt?i=e.DEPTH24_STENCIL8:n===gt?i=e.DEPTH32F_STENCIL8:n===pt&&(i=e.DEPTH24_STENCIL8,qn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):null===n||n===mt||n===yt?i=e.DEPTH_COMPONENT24:n===gt?i=e.DEPTH_COMPONENT32F:n===pt&&(i=e.DEPTH_COMPONENT16),i}function S(e,t){return!0===g(e)||e.isFramebufferTexture&&e.minFilter!==rt&&e.minFilter!==ot?Math.log2(Math.max(t.width,t.height))+1:void 0!==e.mipmaps&&e.mipmaps.length>0?e.mipmaps.length:e.isCompressedTexture&&Array.isArray(e.image)?t.mipmaps.length:1}function A(e){const t=e.target;t.removeEventListener("dispose",A),function(e){const t=i.get(e);if(void 0===t.__webglInit)return;const n=e.source,r=d.get(n);if(r){const i=r[t.__cacheKey];i.usedTimes--,0===i.usedTimes&&M(e),0===Object.keys(r).length&&d.delete(n)}i.remove(e)}(t),t.isVideoTexture&&h.delete(t)}function b(t){const n=t.target;n.removeEventListener("dispose",b),function(t){const n=i.get(t);t.depthTexture&&(t.depthTexture.dispose(),i.remove(t.depthTexture));if(t.isWebGLCubeRenderTarget)for(let i=0;i<6;i++){if(Array.isArray(n.__webglFramebuffer[i]))for(let t=0;t<n.__webglFramebuffer[i].length;t++)e.deleteFramebuffer(n.__webglFramebuffer[i][t]);else e.deleteFramebuffer(n.__webglFramebuffer[i]);n.__webglDepthbuffer&&e.deleteRenderbuffer(n.__webglDepthbuffer[i])}else{if(Array.isArray(n.__webglFramebuffer))for(let t=0;t<n.__webglFramebuffer.length;t++)e.deleteFramebuffer(n.__webglFramebuffer[t]);else e.deleteFramebuffer(n.__webglFramebuffer);if(n.__webglDepthbuffer&&e.deleteRenderbuffer(n.__webglDepthbuffer),n.__webglMultisampledFramebuffer&&e.deleteFramebuffer(n.__webglMultisampledFramebuffer),n.__webglColorRenderbuffer)for(let t=0;t<n.__webglColorRenderbuffer.length;t++)n.__webglColorRenderbuffer[t]&&e.deleteRenderbuffer(n.__webglColorRenderbuffer[t]);n.__webglDepthRenderbuffer&&e.deleteRenderbuffer(n.__webglDepthRenderbuffer)}const r=t.textures;for(let s=0,o=r.length;s<o;s++){const t=i.get(r[s]);t.__webglTexture&&(e.deleteTexture(t.__webglTexture),a.memory.textures--),i.remove(r[s])}i.remove(t)}(n)}function M(t){const n=i.get(t);e.deleteTexture(n.__webglTexture);const r=t.source;delete d.get(r)[n.__cacheKey],a.memory.textures--}let w=0;function T(t,r){const s=i.get(t);if(t.isVideoTexture&&function(e){const t=a.render.frame;h.get(e)!==t&&(h.set(e,t),e.update())}(t),!1===t.isRenderTargetTexture&&!0!==t.isExternalTexture&&t.version>0&&s.__version!==t.version){const e=t.image;if(null===e)qn("WebGLRenderer: Texture marked for update but no image data found.");else{if(!1!==e.complete)return void B(s,t,r);qn("WebGLRenderer: Texture marked for update but image is incomplete")}}else t.isExternalTexture&&(s.__webglTexture=t.sourceTexture?t.sourceTexture:null);n.bindTexture(e.TEXTURE_2D,s.__webglTexture,e.TEXTURE0+r)}const E={[tt]:e.REPEAT,[nt]:e.CLAMP_TO_EDGE,[it]:e.MIRRORED_REPEAT},C={[rt]:e.NEAREST,[st]:e.NEAREST_MIPMAP_NEAREST,[at]:e.NEAREST_MIPMAP_LINEAR,[ot]:e.LINEAR,[lt]:e.LINEAR_MIPMAP_NEAREST,[ct]:e.LINEAR_MIPMAP_LINEAR},R={[Rn]:e.NEVER,[Un]:e.ALWAYS,[In]:e.LESS,[Dn]:e.LEQUAL,[Pn]:e.EQUAL,[Fn]:e.GEQUAL,[Bn]:e.GREATER,[Ln]:e.NOTEQUAL};function I(n,s){if(s.type!==gt||!1!==t.has("OES_texture_float_linear")||s.magFilter!==ot&&s.magFilter!==lt&&s.magFilter!==at&&s.magFilter!==ct&&s.minFilter!==ot&&s.minFilter!==lt&&s.minFilter!==at&&s.minFilter!==ct||qn("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),e.texParameteri(n,e.TEXTURE_WRAP_S,E[s.wrapS]),e.texParameteri(n,e.TEXTURE_WRAP_T,E[s.wrapT]),n!==e.TEXTURE_3D&&n!==e.TEXTURE_2D_ARRAY||e.texParameteri(n,e.TEXTURE_WRAP_R,E[s.wrapR]),e.texParameteri(n,e.TEXTURE_MAG_FILTER,C[s.magFilter]),e.texParameteri(n,e.TEXTURE_MIN_FILTER,C[s.minFilter]),s.compareFunction&&(e.texParameteri(n,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE),e.texParameteri(n,e.TEXTURE_COMPARE_FUNC,R[s.compareFunction])),!0===t.has("EXT_texture_filter_anisotropic")){if(s.magFilter===rt)return;if(s.minFilter!==at&&s.minFilter!==ct)return;if(s.type===gt&&!1===t.has("OES_texture_float_linear"))return;if(s.anisotropy>1||i.get(s).__currentAnisotropy){const a=t.get("EXT_texture_filter_anisotropic");e.texParameterf(n,a.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(s.anisotropy,r.getMaxAnisotropy())),i.get(s).__currentAnisotropy=s.anisotropy}}}function P(t,n){let i=!1;void 0===t.__webglInit&&(t.__webglInit=!0,n.addEventListener("dispose",A));const r=n.source;let s=d.get(r);void 0===s&&(s={},d.set(r,s));const o=function(e){const t=[];return t.push(e.wrapS),t.push(e.wrapT),t.push(e.wrapR||0),t.push(e.magFilter),t.push(e.minFilter),t.push(e.anisotropy),t.push(e.internalFormat),t.push(e.format),t.push(e.type),t.push(e.generateMipmaps),t.push(e.premultiplyAlpha),t.push(e.flipY),t.push(e.unpackAlignment),t.push(e.colorSpace),t.join()}(n);if(o!==t.__cacheKey){void 0===s[o]&&(s[o]={texture:e.createTexture(),usedTimes:0},a.memory.textures++,i=!0),s[o].usedTimes++;const r=s[t.__cacheKey];void 0!==r&&(s[t.__cacheKey].usedTimes--,0===r.usedTimes&&M(n)),t.__cacheKey=o,t.__webglTexture=s[o].texture}return i}function D(e,t,n){return Math.floor(Math.floor(e/n)/t)}function B(t,a,o){let l=e.TEXTURE_2D;(a.isDataArrayTexture||a.isCompressedArrayTexture)&&(l=e.TEXTURE_2D_ARRAY),a.isData3DTexture&&(l=e.TEXTURE_3D);const c=P(t,a),h=a.source;n.bindTexture(l,t.__webglTexture,e.TEXTURE0+o);const u=i.get(h);if(h.version!==u.__version||!0===c){n.activeTexture(e.TEXTURE0+o);const t=vi.getPrimaries(vi.workingColorSpace),i=a.colorSpace===bn?null:vi.getPrimaries(a.colorSpace),d=a.colorSpace===bn||t===i?e.NONE:e.BROWSER_DEFAULT_WEBGL;e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,a.flipY),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,a.premultiplyAlpha),e.pixelStorei(e.UNPACK_ALIGNMENT,a.unpackAlignment),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,d);let p=m(a.image,!1,r.maxTextureSize);p=V(a,p);const f=s.convert(a.format,a.colorSpace),v=s.convert(a.type);let A,b=x(a.internalFormat,f,v,a.colorSpace,a.isVideoTexture);I(l,a);const M=a.mipmaps,w=!0!==a.isVideoTexture,T=void 0===u.__version||!0===c,E=h.dataReady,C=S(a,p);if(a.isDepthTexture)b=y(a.format===wt,a.type),T&&(w?n.texStorage2D(e.TEXTURE_2D,1,b,p.width,p.height):n.texImage2D(e.TEXTURE_2D,0,b,p.width,p.height,0,f,v,null));else if(a.isDataTexture)if(M.length>0){w&&T&&n.texStorage2D(e.TEXTURE_2D,C,b,M[0].width,M[0].height);for(let t=0,i=M.length;t<i;t++)A=M[t],w?E&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,A.width,A.height,f,v,A.data):n.texImage2D(e.TEXTURE_2D,t,b,A.width,A.height,0,f,v,A.data);a.generateMipmaps=!1}else w?(T&&n.texStorage2D(e.TEXTURE_2D,C,b,p.width,p.height),E&&function(t,i,r,s){const a=t.updateRanges;if(0===a.length)n.texSubImage2D(e.TEXTURE_2D,0,0,0,i.width,i.height,r,s,i.data);else{a.sort((e,t)=>e.start-t.start);let o=0;for(let e=1;e<a.length;e++){const t=a[o],n=a[e],r=t.start+t.count,s=D(n.start,i.width,4),l=D(t.start,i.width,4);n.start<=r+1&&s===l&&D(n.start+n.count-1,i.width,4)===s?t.count=Math.max(t.count,n.start+n.count-t.start):(++o,a[o]=n)}a.length=o+1;const l=e.getParameter(e.UNPACK_ROW_LENGTH),c=e.getParameter(e.UNPACK_SKIP_PIXELS),h=e.getParameter(e.UNPACK_SKIP_ROWS);e.pixelStorei(e.UNPACK_ROW_LENGTH,i.width);for(let t=0,u=a.length;t<u;t++){const o=a[t],l=Math.floor(o.start/4),c=Math.ceil(o.count/4),h=l%i.width,u=Math.floor(l/i.width),d=c,p=1;e.pixelStorei(e.UNPACK_SKIP_PIXELS,h),e.pixelStorei(e.UNPACK_SKIP_ROWS,u),n.texSubImage2D(e.TEXTURE_2D,0,h,u,d,p,r,s,i.data)}t.clearUpdateRanges(),e.pixelStorei(e.UNPACK_ROW_LENGTH,l),e.pixelStorei(e.UNPACK_SKIP_PIXELS,c),e.pixelStorei(e.UNPACK_SKIP_ROWS,h)}}(a,p,f,v)):n.texImage2D(e.TEXTURE_2D,0,b,p.width,p.height,0,f,v,p.data);else if(a.isCompressedTexture)if(a.isCompressedArrayTexture){w&&T&&n.texStorage3D(e.TEXTURE_2D_ARRAY,C,b,M[0].width,M[0].height,p.depth);for(let t=0,i=M.length;t<i;t++)if(A=M[t],a.format!==bt)if(null!==f)if(w){if(E)if(a.layerUpdates.size>0){const i=_l(A.width,A.height,a.format,a.type);for(const r of a.layerUpdates){const s=A.data.subarray(r*i/A.data.BYTES_PER_ELEMENT,(r+1)*i/A.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,r,A.width,A.height,1,f,s)}a.clearLayerUpdates()}else n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,0,A.width,A.height,p.depth,f,A.data)}else n.compressedTexImage3D(e.TEXTURE_2D_ARRAY,t,b,A.width,A.height,p.depth,0,A.data,0,0);else qn("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else w?E&&n.texSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,0,A.width,A.height,p.depth,f,v,A.data):n.texImage3D(e.TEXTURE_2D_ARRAY,t,b,A.width,A.height,p.depth,0,f,v,A.data)}else{w&&T&&n.texStorage2D(e.TEXTURE_2D,C,b,M[0].width,M[0].height);for(let t=0,i=M.length;t<i;t++)A=M[t],a.format!==bt?null!==f?w?E&&n.compressedTexSubImage2D(e.TEXTURE_2D,t,0,0,A.width,A.height,f,A.data):n.compressedTexImage2D(e.TEXTURE_2D,t,b,A.width,A.height,0,A.data):qn("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):w?E&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,A.width,A.height,f,v,A.data):n.texImage2D(e.TEXTURE_2D,t,b,A.width,A.height,0,f,v,A.data)}else if(a.isDataArrayTexture)if(w){if(T&&n.texStorage3D(e.TEXTURE_2D_ARRAY,C,b,p.width,p.height,p.depth),E)if(a.layerUpdates.size>0){const t=_l(p.width,p.height,a.format,a.type);for(const i of a.layerUpdates){const r=p.data.subarray(i*t/p.data.BYTES_PER_ELEMENT,(i+1)*t/p.data.BYTES_PER_ELEMENT);n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,i,p.width,p.height,1,f,v,r)}a.clearLayerUpdates()}else n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,0,p.width,p.height,p.depth,f,v,p.data)}else n.texImage3D(e.TEXTURE_2D_ARRAY,0,b,p.width,p.height,p.depth,0,f,v,p.data);else if(a.isData3DTexture)w?(T&&n.texStorage3D(e.TEXTURE_3D,C,b,p.width,p.height,p.depth),E&&n.texSubImage3D(e.TEXTURE_3D,0,0,0,0,p.width,p.height,p.depth,f,v,p.data)):n.texImage3D(e.TEXTURE_3D,0,b,p.width,p.height,p.depth,0,f,v,p.data);else if(a.isFramebufferTexture){if(T)if(w)n.texStorage2D(e.TEXTURE_2D,C,b,p.width,p.height);else{let t=p.width,i=p.height;for(let r=0;r<C;r++)n.texImage2D(e.TEXTURE_2D,r,b,t,i,0,f,v,null),t>>=1,i>>=1}}else if(M.length>0){if(w&&T){const t=G(M[0]);n.texStorage2D(e.TEXTURE_2D,C,b,t.width,t.height)}for(let t=0,i=M.length;t<i;t++)A=M[t],w?E&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,f,v,A):n.texImage2D(e.TEXTURE_2D,t,b,f,v,A);a.generateMipmaps=!1}else if(w){if(T){const t=G(p);n.texStorage2D(e.TEXTURE_2D,C,b,t.width,t.height)}E&&n.texSubImage2D(e.TEXTURE_2D,0,0,0,f,v,p)}else n.texImage2D(e.TEXTURE_2D,0,b,f,v,p);g(a)&&_(l),u.__version=h.version,a.onUpdate&&a.onUpdate(a)}t.__version=a.version}function L(t,r,a,l,c,h){const u=s.convert(a.format,a.colorSpace),d=s.convert(a.type),p=x(a.internalFormat,u,d,a.colorSpace),f=i.get(r),m=i.get(a);if(m.__renderTarget=r,!f.__hasExternalTextures){const t=Math.max(1,r.width>>h),i=Math.max(1,r.height>>h);c===e.TEXTURE_3D||c===e.TEXTURE_2D_ARRAY?n.texImage3D(c,h,p,t,i,r.depth,0,u,d,null):n.texImage2D(c,h,p,t,i,0,u,d,null)}n.bindFramebuffer(e.FRAMEBUFFER,t),H(r)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,l,c,m.__webglTexture,0,z(r)):(c===e.TEXTURE_2D||c>=e.TEXTURE_CUBE_MAP_POSITIVE_X&&c<=e.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&e.framebufferTexture2D(e.FRAMEBUFFER,l,c,m.__webglTexture,h),n.bindFramebuffer(e.FRAMEBUFFER,null)}function F(t,n,i){if(e.bindRenderbuffer(e.RENDERBUFFER,t),n.depthBuffer){const r=n.depthTexture,s=r&&r.isDepthTexture?r.type:null,a=y(n.stencilBuffer,s),l=n.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;H(n)?o.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,z(n),a,n.width,n.height):i?e.renderbufferStorageMultisample(e.RENDERBUFFER,z(n),a,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,a,n.width,n.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,l,e.RENDERBUFFER,t)}else{const t=n.textures;for(let r=0;r<t.length;r++){const a=t[r],l=s.convert(a.format,a.colorSpace),c=s.convert(a.type),h=x(a.internalFormat,l,c,a.colorSpace);H(n)?o.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,z(n),h,n.width,n.height):i?e.renderbufferStorageMultisample(e.RENDERBUFFER,z(n),h,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,h,n.width,n.height)}}e.bindRenderbuffer(e.RENDERBUFFER,null)}function U(t,r,a){const l=!0===r.isWebGLCubeRenderTarget;if(n.bindFramebuffer(e.FRAMEBUFFER,t),!r.depthTexture||!r.depthTexture.isDepthTexture)throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");const c=i.get(r.depthTexture);if(c.__renderTarget=r,c.__webglTexture&&r.depthTexture.image.width===r.width&&r.depthTexture.image.height===r.height||(r.depthTexture.image.width=r.width,r.depthTexture.image.height=r.height,r.depthTexture.needsUpdate=!0),l){if(void 0===c.__webglInit&&(c.__webglInit=!0,r.depthTexture.addEventListener("dispose",A)),void 0===c.__webglTexture){c.__webglTexture=e.createTexture(),n.bindTexture(e.TEXTURE_CUBE_MAP,c.__webglTexture),I(e.TEXTURE_CUBE_MAP,r.depthTexture);const t=s.convert(r.depthTexture.format),i=s.convert(r.depthTexture.type);let a;r.depthTexture.format===Mt?a=e.DEPTH_COMPONENT24:r.depthTexture.format===wt&&(a=e.DEPTH24_STENCIL8);for(let n=0;n<6;n++)e.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+n,0,a,r.width,r.height,0,t,i,null)}}else T(r.depthTexture,0);const h=c.__webglTexture,u=z(r),d=l?e.TEXTURE_CUBE_MAP_POSITIVE_X+a:e.TEXTURE_2D,p=r.depthTexture.format===wt?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;if(r.depthTexture.format===Mt)H(r)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,p,d,h,0,u):e.framebufferTexture2D(e.FRAMEBUFFER,p,d,h,0);else{if(r.depthTexture.format!==wt)throw new Error("Unknown depthTexture format");H(r)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,p,d,h,0,u):e.framebufferTexture2D(e.FRAMEBUFFER,p,d,h,0)}}function k(t){const r=i.get(t),s=!0===t.isWebGLCubeRenderTarget;if(r.__boundDepthTexture!==t.depthTexture){const e=t.depthTexture;if(r.__depthDisposeCallback&&r.__depthDisposeCallback(),e){const t=()=>{delete r.__boundDepthTexture,delete r.__depthDisposeCallback,e.removeEventListener("dispose",t)};e.addEventListener("dispose",t),r.__depthDisposeCallback=t}r.__boundDepthTexture=e}if(t.depthTexture&&!r.__autoAllocateDepthBuffer)if(s)for(let e=0;e<6;e++)U(r.__webglFramebuffer[e],t,e);else{const e=t.texture.mipmaps;e&&e.length>0?U(r.__webglFramebuffer[0],t,0):U(r.__webglFramebuffer,t,0)}else if(s){r.__webglDepthbuffer=[];for(let i=0;i<6;i++)if(n.bindFramebuffer(e.FRAMEBUFFER,r.__webglFramebuffer[i]),void 0===r.__webglDepthbuffer[i])r.__webglDepthbuffer[i]=e.createRenderbuffer(),F(r.__webglDepthbuffer[i],t,!1);else{const n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,s=r.__webglDepthbuffer[i];e.bindRenderbuffer(e.RENDERBUFFER,s),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,s)}}else{const i=t.texture.mipmaps;if(i&&i.length>0?n.bindFramebuffer(e.FRAMEBUFFER,r.__webglFramebuffer[0]):n.bindFramebuffer(e.FRAMEBUFFER,r.__webglFramebuffer),void 0===r.__webglDepthbuffer)r.__webglDepthbuffer=e.createRenderbuffer(),F(r.__webglDepthbuffer,t,!1);else{const n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,i=r.__webglDepthbuffer;e.bindRenderbuffer(e.RENDERBUFFER,i),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,i)}}n.bindFramebuffer(e.FRAMEBUFFER,null)}const N=[],O=[];function z(e){return Math.min(r.maxSamples,e.samples)}function H(e){const n=i.get(e);return e.samples>0&&!0===t.has("WEBGL_multisampled_render_to_texture")&&!1!==n.__useRenderToTexture}function V(e,t){const n=e.colorSpace,i=e.format,r=e.type;return!0===e.isCompressedTexture||!0===e.isVideoTexture||n!==wn&&n!==bn&&(vi.getTransfer(n)===En?i===bt&&r===ht||qn("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):Qn("WebGLTextures: Unsupported texture color space:",n)),t}function G(e){return"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement?(c.width=e.naturalWidth||e.width,c.height=e.naturalHeight||e.height):"undefined"!=typeof VideoFrame&&e instanceof VideoFrame?(c.width=e.displayWidth,c.height=e.displayHeight):(c.width=e.width,c.height=e.height),c}this.allocateTextureUnit=function(){const e=w;return e>=r.maxTextures&&qn("WebGLTextures: Trying to use "+e+" texture units while this GPU supports only "+r.maxTextures),w+=1,e},this.resetTextureUnits=function(){w=0},this.setTexture2D=T,this.setTexture2DArray=function(t,r){const s=i.get(t);!1===t.isRenderTargetTexture&&t.version>0&&s.__version!==t.version?B(s,t,r):(t.isExternalTexture&&(s.__webglTexture=t.sourceTexture?t.sourceTexture:null),n.bindTexture(e.TEXTURE_2D_ARRAY,s.__webglTexture,e.TEXTURE0+r))},this.setTexture3D=function(t,r){const s=i.get(t);!1===t.isRenderTargetTexture&&t.version>0&&s.__version!==t.version?B(s,t,r):n.bindTexture(e.TEXTURE_3D,s.__webglTexture,e.TEXTURE0+r)},this.setTextureCube=function(t,a){const o=i.get(t);!0!==t.isCubeDepthTexture&&t.version>0&&o.__version!==t.version?function(t,a,o){if(6!==a.image.length)return;const l=P(t,a),c=a.source;n.bindTexture(e.TEXTURE_CUBE_MAP,t.__webglTexture,e.TEXTURE0+o);const h=i.get(c);if(c.version!==h.__version||!0===l){n.activeTexture(e.TEXTURE0+o);const t=vi.getPrimaries(vi.workingColorSpace),i=a.colorSpace===bn?null:vi.getPrimaries(a.colorSpace),u=a.colorSpace===bn||t===i?e.NONE:e.BROWSER_DEFAULT_WEBGL;e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,a.flipY),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,a.premultiplyAlpha),e.pixelStorei(e.UNPACK_ALIGNMENT,a.unpackAlignment),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,u);const d=a.isCompressedTexture||a.image[0].isCompressedTexture,p=a.image[0]&&a.image[0].isDataTexture,f=[];for(let e=0;e<6;e++)f[e]=d||p?p?a.image[e].image:a.image[e]:m(a.image[e],!0,r.maxCubemapSize),f[e]=V(a,f[e]);const v=f[0],y=s.convert(a.format,a.colorSpace),A=s.convert(a.type),b=x(a.internalFormat,y,A,a.colorSpace),M=!0!==a.isVideoTexture,w=void 0===h.__version||!0===l,T=c.dataReady;let E,C=S(a,v);if(I(e.TEXTURE_CUBE_MAP,a),d){M&&w&&n.texStorage2D(e.TEXTURE_CUBE_MAP,C,b,v.width,v.height);for(let t=0;t<6;t++){E=f[t].mipmaps;for(let i=0;i<E.length;i++){const r=E[i];a.format!==bt?null!==y?M?T&&n.compressedTexSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,i,0,0,r.width,r.height,y,r.data):n.compressedTexImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,i,b,r.width,r.height,0,r.data):qn("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):M?T&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,i,0,0,r.width,r.height,y,A,r.data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,i,b,r.width,r.height,0,y,A,r.data)}}}else{if(E=a.mipmaps,M&&w){E.length>0&&C++;const t=G(f[0]);n.texStorage2D(e.TEXTURE_CUBE_MAP,C,b,t.width,t.height)}for(let t=0;t<6;t++)if(p){M?T&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,f[t].width,f[t].height,y,A,f[t].data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,b,f[t].width,f[t].height,0,y,A,f[t].data);for(let i=0;i<E.length;i++){const r=E[i].image[t].image;M?T&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,i+1,0,0,r.width,r.height,y,A,r.data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,i+1,b,r.width,r.height,0,y,A,r.data)}}else{M?T&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,y,A,f[t]):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,b,y,A,f[t]);for(let i=0;i<E.length;i++){const r=E[i];M?T&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,i+1,0,0,y,A,r.image[t]):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,i+1,b,y,A,r.image[t])}}}g(a)&&_(e.TEXTURE_CUBE_MAP),h.__version=c.version,a.onUpdate&&a.onUpdate(a)}t.__version=a.version}(o,t,a):n.bindTexture(e.TEXTURE_CUBE_MAP,o.__webglTexture,e.TEXTURE0+a)},this.rebindTextures=function(t,n,r){const s=i.get(t);void 0!==n&&L(s.__webglFramebuffer,t,t.texture,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,0),void 0!==r&&k(t)},this.setupRenderTarget=function(t){const r=t.texture,o=i.get(t),l=i.get(r);t.addEventListener("dispose",b);const c=t.textures,h=!0===t.isWebGLCubeRenderTarget,u=c.length>1;if(u||(void 0===l.__webglTexture&&(l.__webglTexture=e.createTexture()),l.__version=r.version,a.memory.textures++),h){o.__webglFramebuffer=[];for(let t=0;t<6;t++)if(r.mipmaps&&r.mipmaps.length>0){o.__webglFramebuffer[t]=[];for(let n=0;n<r.mipmaps.length;n++)o.__webglFramebuffer[t][n]=e.createFramebuffer()}else o.__webglFramebuffer[t]=e.createFramebuffer()}else{if(r.mipmaps&&r.mipmaps.length>0){o.__webglFramebuffer=[];for(let t=0;t<r.mipmaps.length;t++)o.__webglFramebuffer[t]=e.createFramebuffer()}else o.__webglFramebuffer=e.createFramebuffer();if(u)for(let t=0,n=c.length;t<n;t++){const n=i.get(c[t]);void 0===n.__webglTexture&&(n.__webglTexture=e.createTexture(),a.memory.textures++)}if(t.samples>0&&!1===H(t)){o.__webglMultisampledFramebuffer=e.createFramebuffer(),o.__webglColorRenderbuffer=[],n.bindFramebuffer(e.FRAMEBUFFER,o.__webglMultisampledFramebuffer);for(let n=0;n<c.length;n++){const i=c[n];o.__webglColorRenderbuffer[n]=e.createRenderbuffer(),e.bindRenderbuffer(e.RENDERBUFFER,o.__webglColorRenderbuffer[n]);const r=s.convert(i.format,i.colorSpace),a=s.convert(i.type),l=x(i.internalFormat,r,a,i.colorSpace,!0===t.isXRRenderTarget),h=z(t);e.renderbufferStorageMultisample(e.RENDERBUFFER,h,l,t.width,t.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+n,e.RENDERBUFFER,o.__webglColorRenderbuffer[n])}e.bindRenderbuffer(e.RENDERBUFFER,null),t.depthBuffer&&(o.__webglDepthRenderbuffer=e.createRenderbuffer(),F(o.__webglDepthRenderbuffer,t,!0)),n.bindFramebuffer(e.FRAMEBUFFER,null)}}if(h){n.bindTexture(e.TEXTURE_CUBE_MAP,l.__webglTexture),I(e.TEXTURE_CUBE_MAP,r);for(let n=0;n<6;n++)if(r.mipmaps&&r.mipmaps.length>0)for(let i=0;i<r.mipmaps.length;i++)L(o.__webglFramebuffer[n][i],t,r,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+n,i);else L(o.__webglFramebuffer[n],t,r,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+n,0);g(r)&&_(e.TEXTURE_CUBE_MAP),n.unbindTexture()}else if(u){for(let r=0,s=c.length;r<s;r++){const s=c[r],a=i.get(s);let l=e.TEXTURE_2D;(t.isWebGL3DRenderTarget||t.isWebGLArrayRenderTarget)&&(l=t.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY),n.bindTexture(l,a.__webglTexture),I(l,s),L(o.__webglFramebuffer,t,s,e.COLOR_ATTACHMENT0+r,l,0),g(s)&&_(l)}n.unbindTexture()}else{let i=e.TEXTURE_2D;if((t.isWebGL3DRenderTarget||t.isWebGLArrayRenderTarget)&&(i=t.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY),n.bindTexture(i,l.__webglTexture),I(i,r),r.mipmaps&&r.mipmaps.length>0)for(let n=0;n<r.mipmaps.length;n++)L(o.__webglFramebuffer[n],t,r,e.COLOR_ATTACHMENT0,i,n);else L(o.__webglFramebuffer,t,r,e.COLOR_ATTACHMENT0,i,0);g(r)&&_(i),n.unbindTexture()}t.depthBuffer&&k(t)},this.updateRenderTargetMipmap=function(e){const t=e.textures;for(let r=0,s=t.length;r<s;r++){const s=t[r];if(g(s)){const t=v(e),r=i.get(s).__webglTexture;n.bindTexture(t,r),_(t),n.unbindTexture()}}},this.updateMultisampleRenderTarget=function(t){if(t.samples>0)if(!1===H(t)){const r=t.textures,s=t.width,a=t.height;let o=e.COLOR_BUFFER_BIT;const c=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,h=i.get(t),u=r.length>1;if(u)for(let t=0;t<r.length;t++)n.bindFramebuffer(e.FRAMEBUFFER,h.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.RENDERBUFFER,null),n.bindFramebuffer(e.FRAMEBUFFER,h.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.TEXTURE_2D,null,0);n.bindFramebuffer(e.READ_FRAMEBUFFER,h.__webglMultisampledFramebuffer);const d=t.texture.mipmaps;d&&d.length>0?n.bindFramebuffer(e.DRAW_FRAMEBUFFER,h.__webglFramebuffer[0]):n.bindFramebuffer(e.DRAW_FRAMEBUFFER,h.__webglFramebuffer);for(let n=0;n<r.length;n++){if(t.resolveDepthBuffer&&(t.depthBuffer&&(o|=e.DEPTH_BUFFER_BIT),t.stencilBuffer&&t.resolveStencilBuffer&&(o|=e.STENCIL_BUFFER_BIT)),u){e.framebufferRenderbuffer(e.READ_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.RENDERBUFFER,h.__webglColorRenderbuffer[n]);const t=i.get(r[n]).__webglTexture;e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)}e.blitFramebuffer(0,0,s,a,0,0,s,a,o,e.NEAREST),!0===l&&(N.length=0,O.length=0,N.push(e.COLOR_ATTACHMENT0+n),t.depthBuffer&&!1===t.resolveDepthBuffer&&(N.push(c),O.push(c),e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,O)),e.invalidateFramebuffer(e.READ_FRAMEBUFFER,N))}if(n.bindFramebuffer(e.READ_FRAMEBUFFER,null),n.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),u)for(let t=0;t<r.length;t++){n.bindFramebuffer(e.FRAMEBUFFER,h.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.RENDERBUFFER,h.__webglColorRenderbuffer[t]);const s=i.get(r[t]).__webglTexture;n.bindFramebuffer(e.FRAMEBUFFER,h.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.TEXTURE_2D,s,0)}n.bindFramebuffer(e.DRAW_FRAMEBUFFER,h.__webglMultisampledFramebuffer)}else if(t.depthBuffer&&!1===t.resolveDepthBuffer&&l){const n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,[n])}},this.setupDepthRenderbuffer=k,this.setupFrameBufferTexture=L,this.useMultisampledRTT=H,this.isReversedDepthBuffer=function(){return n.buffers.depth.getReversed()}}function nu(e,t){return{convert:function(n,i=""){let r;const s=vi.getTransfer(i);if(n===ht)return e.UNSIGNED_BYTE;if(n===vt)return e.UNSIGNED_SHORT_4_4_4_4;if(n===xt)return e.UNSIGNED_SHORT_5_5_5_1;if(n===St)return e.UNSIGNED_INT_5_9_9_9_REV;if(n===At)return e.UNSIGNED_INT_10F_11F_11F_REV;if(n===ut)return e.BYTE;if(n===dt)return e.SHORT;if(n===pt)return e.UNSIGNED_SHORT;if(n===ft)return e.INT;if(n===mt)return e.UNSIGNED_INT;if(n===gt)return e.FLOAT;if(n===_t)return e.HALF_FLOAT;if(1021===n)return e.ALPHA;if(1022===n)return e.RGB;if(n===bt)return e.RGBA;if(n===Mt)return e.DEPTH_COMPONENT;if(n===wt)return e.DEPTH_STENCIL;if(n===Tt)return e.RED;if(n===Et)return e.RED_INTEGER;if(n===Ct)return e.RG;if(n===Rt)return e.RG_INTEGER;if(n===It)return e.RGBA_INTEGER;if(n===Pt||n===Dt||n===Bt||n===Lt)if(s===En){if(r=t.get("WEBGL_compressed_texture_s3tc_srgb"),null===r)return null;if(n===Pt)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===Dt)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===Bt)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===Lt)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(r=t.get("WEBGL_compressed_texture_s3tc"),null===r)return null;if(n===Pt)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===Dt)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===Bt)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===Lt)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(n===Ft||n===Ut||n===kt||n===Nt){if(r=t.get("WEBGL_compressed_texture_pvrtc"),null===r)return null;if(n===Ft)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===Ut)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===kt)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===Nt)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(n===Ot||n===zt||n===Ht||n===Vt||n===Gt||n===Wt||n===jt){if(r=t.get("WEBGL_compressed_texture_etc"),null===r)return null;if(n===Ot||n===zt)return s===En?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(n===Ht)return s===En?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC;if(n===Vt)return r.COMPRESSED_R11_EAC;if(n===Gt)return r.COMPRESSED_SIGNED_R11_EAC;if(n===Wt)return r.COMPRESSED_RG11_EAC;if(n===jt)return r.COMPRESSED_SIGNED_RG11_EAC}if(n===Xt||n===qt||n===Qt||n===Kt||n===Yt||n===Zt||n===Jt||n===$t||n===en||n===tn||n===nn||n===rn||n===sn||n===an){if(r=t.get("WEBGL_compressed_texture_astc"),null===r)return null;if(n===Xt)return s===En?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===qt)return s===En?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===Qt)return s===En?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===Kt)return s===En?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===Yt)return s===En?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===Zt)return s===En?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===Jt)return s===En?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===$t)return s===En?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===en)return s===En?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===tn)return s===En?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===nn)return s===En?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===rn)return s===En?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===sn)return s===En?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===an)return s===En?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}if(n===on||n===ln||n===cn){if(r=t.get("EXT_texture_compression_bptc"),null===r)return null;if(n===on)return s===En?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===ln)return r.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===cn)return r.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}if(n===hn||n===un||n===dn||n===pn){if(r=t.get("EXT_texture_compression_rgtc"),null===r)return null;if(n===hn)return r.COMPRESSED_RED_RGTC1_EXT;if(n===un)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===dn)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===pn)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}return n===yt?e.UNSIGNED_INT_24_8:void 0!==e[n]?e[n]:null}}}class iu{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(null===this.texture){const n=new ro(e.texture);e.depthNear===t.depthNear&&e.depthFar===t.depthFar||(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=n}}getMesh(e){if(null!==this.texture&&null===this.mesh){const t=e.cameras[0].viewport,n=new zs({vertexShader:"\nvoid main() {\n\n\tgl_Position = vec4( position, 1.0 );\n\n}",fragmentShader:"\nuniform sampler2DArray depthColor;\nuniform float depthWidth;\nuniform float depthHeight;\n\nvoid main() {\n\n\tvec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );\n\n\tif ( coord.x >= 1.0 ) {\n\n\t\tgl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;\n\n\t} else {\n\n\t\tgl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;\n\n\t}\n\n}",uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new Bs(new so(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class ru extends Yn{constructor(e,t){super();const n=this;let i=null,r=1,s=null,a="local-floor",o=1,l=null,c=null,h=null,u=null,d=null,p=null;const f="undefined"!=typeof XRWebGLBinding,m=new iu,g={},_=t.getContextAttributes();let v=null,x=null;const y=[],S=[],A=new li;let b=null;const M=new js;M.viewport=new Ri;const w=new js;w.viewport=new Ri;const T=[M,w],E=new nl;let C=null,R=null;function I(e){const t=S.indexOf(e.inputSource);if(-1===t)return;const n=y[t];void 0!==n&&(n.update(e.inputSource,e.frame,l||s),n.dispatchEvent({type:e.type,data:e.inputSource}))}function P(){i.removeEventListener("select",I),i.removeEventListener("selectstart",I),i.removeEventListener("selectend",I),i.removeEventListener("squeeze",I),i.removeEventListener("squeezestart",I),i.removeEventListener("squeezeend",I),i.removeEventListener("end",P),i.removeEventListener("inputsourceschange",D);for(let e=0;e<y.length;e++){const t=S[e];null!==t&&(S[e]=null,y[e].disconnect(t))}C=null,R=null,m.reset();for(const e in g)delete g[e];e.setRenderTarget(v),d=null,u=null,h=null,i=null,x=null,k.stop(),n.isPresenting=!1,e.setPixelRatio(b),e.setSize(A.width,A.height,!1),n.dispatchEvent({type:"sessionend"})}function D(e){for(let t=0;t<e.removed.length;t++){const n=e.removed[t],i=S.indexOf(n);i>=0&&(S[i]=null,y[i].disconnect(n))}for(let t=0;t<e.added.length;t++){const n=e.added[t];let i=S.indexOf(n);if(-1===i){for(let e=0;e<y.length;e++){if(e>=S.length){S.push(n),i=e;break}if(null===S[e]){S[e]=n,i=e;break}}if(-1===i)break}const r=y[i];r&&r.connect(n)}}this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(e){let t=y[e];return void 0===t&&(t=new Js,y[e]=t),t.getTargetRaySpace()},this.getControllerGrip=function(e){let t=y[e];return void 0===t&&(t=new Js,y[e]=t),t.getGripSpace()},this.getHand=function(e){let t=y[e];return void 0===t&&(t=new Js,y[e]=t),t.getHandSpace()},this.setFramebufferScaleFactor=function(e){r=e,!0===n.isPresenting&&qn("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(e){a=e,!0===n.isPresenting&&qn("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return l||s},this.setReferenceSpace=function(e){l=e},this.getBaseLayer=function(){return null!==u?u:d},this.getBinding=function(){return null===h&&f&&(h=new XRWebGLBinding(i,t)),h},this.getFrame=function(){return p},this.getSession=function(){return i},this.setSession=async function(c){if(i=c,null!==i){v=e.getRenderTarget(),i.addEventListener("select",I),i.addEventListener("selectstart",I),i.addEventListener("selectend",I),i.addEventListener("squeeze",I),i.addEventListener("squeezestart",I),i.addEventListener("squeezeend",I),i.addEventListener("end",P),i.addEventListener("inputsourceschange",D),!0!==_.xrCompatible&&await t.makeXRCompatible(),b=e.getPixelRatio(),e.getSize(A);if(f&&"createProjectionLayer"in XRWebGLBinding.prototype){let n=null,s=null,a=null;_.depth&&(a=_.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,n=_.stencil?wt:Mt,s=_.stencil?yt:mt);const o={colorFormat:t.RGBA8,depthFormat:a,scaleFactor:r};h=this.getBinding(),u=h.createProjectionLayer(o),i.updateRenderState({layers:[u]}),e.setPixelRatio(1),e.setSize(u.textureWidth,u.textureHeight,!1),x=new Pi(u.textureWidth,u.textureHeight,{format:bt,type:ht,depthTexture:new no(u.textureWidth,u.textureHeight,s,void 0,void 0,void 0,void 0,void 0,void 0,n),stencilBuffer:_.stencil,colorSpace:e.outputColorSpace,samples:_.antialias?4:0,resolveDepthBuffer:!1===u.ignoreDepthValues,resolveStencilBuffer:!1===u.ignoreDepthValues})}else{const n={antialias:_.antialias,alpha:!0,depth:_.depth,stencil:_.stencil,framebufferScaleFactor:r};d=new XRWebGLLayer(i,t,n),i.updateRenderState({baseLayer:d}),e.setPixelRatio(1),e.setSize(d.framebufferWidth,d.framebufferHeight,!1),x=new Pi(d.framebufferWidth,d.framebufferHeight,{format:bt,type:ht,colorSpace:e.outputColorSpace,stencilBuffer:_.stencil,resolveDepthBuffer:!1===d.ignoreDepthValues,resolveStencilBuffer:!1===d.ignoreDepthValues})}x.isXRRenderTarget=!0,this.setFoveation(o),l=null,s=await i.requestReferenceSpace(a),k.setContext(i),k.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(null!==i)return i.environmentBlendMode},this.getDepthTexture=function(){return m.getDepthTexture()};const B=new hi,L=new hi;function F(e,t){null===t?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}this.updateCamera=function(e){if(null===i)return;let t=e.near,n=e.far;null!==m.texture&&(m.depthNear>0&&(t=m.depthNear),m.depthFar>0&&(n=m.depthFar)),E.near=w.near=M.near=t,E.far=w.far=M.far=n,C===E.near&&R===E.far||(i.updateRenderState({depthNear:E.near,depthFar:E.far}),C=E.near,R=E.far),E.layers.mask=6|e.layers.mask,M.layers.mask=3&E.layers.mask,w.layers.mask=5&E.layers.mask;const r=e.parent,s=E.cameras;F(E,r);for(let i=0;i<s.length;i++)F(s[i],r);2===s.length?function(e,t,n){B.setFromMatrixPosition(t.matrixWorld),L.setFromMatrixPosition(n.matrixWorld);const i=B.distanceTo(L),r=t.projectionMatrix.elements,s=n.projectionMatrix.elements,a=r[14]/(r[10]-1),o=r[14]/(r[10]+1),l=(r[9]+1)/r[5],c=(r[9]-1)/r[5],h=(r[8]-1)/r[0],u=(s[8]+1)/s[0],d=a*h,p=a*u,f=i/(-h+u),m=f*-h;if(t.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.translateX(m),e.translateZ(f),e.matrixWorld.compose(e.position,e.quaternion,e.scale),e.matrixWorldInverse.copy(e.matrixWorld).invert(),-1===r[10])e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse);else{const t=a+f,n=o+f,r=d-m,s=p+(i-m),h=l*o/n*t,u=c*o/n*t;e.projectionMatrix.makePerspective(r,s,h,u,t,n),e.projectionMatrixInverse.copy(e.projectionMatrix).invert()}}(E,M,w):E.projectionMatrix.copy(M.projectionMatrix),function(e,t,n){null===n?e.matrix.copy(t.matrixWorld):(e.matrix.copy(n.matrixWorld),e.matrix.invert(),e.matrix.multiply(t.matrixWorld));e.matrix.decompose(e.position,e.quaternion,e.scale),e.updateMatrixWorld(!0),e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse),e.isPerspectiveCamera&&(e.fov=2*ei*Math.atan(1/e.projectionMatrix.elements[5]),e.zoom=1)}(e,E,r)},this.getCamera=function(){return E},this.getFoveation=function(){if(null!==u||null!==d)return o},this.setFoveation=function(e){o=e,null!==u&&(u.fixedFoveation=e),null!==d&&void 0!==d.fixedFoveation&&(d.fixedFoveation=e)},this.hasDepthSensing=function(){return null!==m.texture},this.getDepthSensingMesh=function(){return m.getMesh(E)},this.getCameraTexture=function(e){return g[e]};let U=null;const k=new vl;k.setAnimationLoop(function(t,r){if(c=r.getViewerPose(l||s),p=r,null!==c){const t=c.views;null!==d&&(e.setRenderTargetFramebuffer(x,d.framebuffer),e.setRenderTarget(x));let r=!1;t.length!==E.cameras.length&&(E.cameras.length=0,r=!0);for(let n=0;n<t.length;n++){const i=t[n];let s=null;if(null!==d)s=d.getViewport(i);else{const t=h.getViewSubImage(u,i);s=t.viewport,0===n&&(e.setRenderTargetTextures(x,t.colorTexture,t.depthStencilTexture),e.setRenderTarget(x))}let a=T[n];void 0===a&&(a=new js,a.layers.enable(n),a.viewport=new Ri,T[n]=a),a.matrix.fromArray(i.transform.matrix),a.matrix.decompose(a.position,a.quaternion,a.scale),a.projectionMatrix.fromArray(i.projectionMatrix),a.projectionMatrixInverse.copy(a.projectionMatrix).invert(),a.viewport.set(s.x,s.y,s.width,s.height),0===n&&(E.matrix.copy(a.matrix),E.matrix.decompose(E.position,E.quaternion,E.scale)),!0===r&&E.cameras.push(a)}const s=i.enabledFeatures;if(s&&s.includes("depth-sensing")&&"gpu-optimized"==i.depthUsage&&f){h=n.getBinding();const e=h.getDepthInformation(t[0]);e&&e.isValid&&e.texture&&m.init(e,i.renderState)}if(s&&s.includes("camera-access")&&f){e.state.unbindTexture(),h=n.getBinding();for(let e=0;e<t.length;e++){const n=t[e].camera;if(n){let e=g[n];e||(e=new ro,g[n]=e);const t=h.getCameraImage(n);e.sourceTexture=t}}}}for(let e=0;e<y.length;e++){const t=S[e],n=y[e];null!==t&&void 0!==n&&n.update(t,r,l||s)}U&&U(t,r),r.detectedPlanes&&n.dispatchEvent({type:"planesdetected",data:r}),p=null}),this.setAnimationLoop=function(e){U=e},this.dispose=function(){}}}const su=new _r,au=new or;function ou(e,t){function n(e,t){!0===e.matrixAutoUpdate&&e.updateMatrix(),t.value.copy(e.matrix)}function i(e,i){e.opacity.value=i.opacity,i.color&&e.diffuse.value.copy(i.color),i.emissive&&e.emissive.value.copy(i.emissive).multiplyScalar(i.emissiveIntensity),i.map&&(e.map.value=i.map,n(i.map,e.mapTransform)),i.alphaMap&&(e.alphaMap.value=i.alphaMap,n(i.alphaMap,e.alphaMapTransform)),i.bumpMap&&(e.bumpMap.value=i.bumpMap,n(i.bumpMap,e.bumpMapTransform),e.bumpScale.value=i.bumpScale,1===i.side&&(e.bumpScale.value*=-1)),i.normalMap&&(e.normalMap.value=i.normalMap,n(i.normalMap,e.normalMapTransform),e.normalScale.value.copy(i.normalScale),1===i.side&&e.normalScale.value.negate()),i.displacementMap&&(e.displacementMap.value=i.displacementMap,n(i.displacementMap,e.displacementMapTransform),e.displacementScale.value=i.displacementScale,e.displacementBias.value=i.displacementBias),i.emissiveMap&&(e.emissiveMap.value=i.emissiveMap,n(i.emissiveMap,e.emissiveMapTransform)),i.specularMap&&(e.specularMap.value=i.specularMap,n(i.specularMap,e.specularMapTransform)),i.alphaTest>0&&(e.alphaTest.value=i.alphaTest);const r=t.get(i),s=r.envMap,a=r.envMapRotation;s&&(e.envMap.value=s,su.copy(a),su.x*=-1,su.y*=-1,su.z*=-1,s.isCubeTexture&&!1===s.isRenderTargetTexture&&(su.y*=-1,su.z*=-1),e.envMapRotation.value.setFromMatrix4(au.makeRotationFromEuler(su)),e.flipEnvMap.value=s.isCubeTexture&&!1===s.isRenderTargetTexture?-1:1,e.reflectivity.value=i.reflectivity,e.ior.value=i.ior,e.refractionRatio.value=i.refractionRatio),i.lightMap&&(e.lightMap.value=i.lightMap,e.lightMapIntensity.value=i.lightMapIntensity,n(i.lightMap,e.lightMapTransform)),i.aoMap&&(e.aoMap.value=i.aoMap,e.aoMapIntensity.value=i.aoMapIntensity,n(i.aoMap,e.aoMapTransform))}return{refreshFogUniforms:function(t,n){n.color.getRGB(t.fogColor.value,Ns(e)),n.isFog?(t.fogNear.value=n.near,t.fogFar.value=n.far):n.isFogExp2&&(t.fogDensity.value=n.density)},refreshMaterialUniforms:function(e,r,s,a,o){r.isMeshBasicMaterial||r.isMeshLambertMaterial?i(e,r):r.isMeshToonMaterial?(i(e,r),function(e,t){t.gradientMap&&(e.gradientMap.value=t.gradientMap)}(e,r)):r.isMeshPhongMaterial?(i(e,r),function(e,t){e.specular.value.copy(t.specular),e.shininess.value=Math.max(t.shininess,1e-4)}(e,r)):r.isMeshStandardMaterial?(i(e,r),function(e,t){e.metalness.value=t.metalness,t.metalnessMap&&(e.metalnessMap.value=t.metalnessMap,n(t.metalnessMap,e.metalnessMapTransform));e.roughness.value=t.roughness,t.roughnessMap&&(e.roughnessMap.value=t.roughnessMap,n(t.roughnessMap,e.roughnessMapTransform));t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)}(e,r),r.isMeshPhysicalMaterial&&function(e,t,i){e.ior.value=t.ior,t.sheen>0&&(e.sheenColor.value.copy(t.sheenColor).multiplyScalar(t.sheen),e.sheenRoughness.value=t.sheenRoughness,t.sheenColorMap&&(e.sheenColorMap.value=t.sheenColorMap,n(t.sheenColorMap,e.sheenColorMapTransform)),t.sheenRoughnessMap&&(e.sheenRoughnessMap.value=t.sheenRoughnessMap,n(t.sheenRoughnessMap,e.sheenRoughnessMapTransform)));t.clearcoat>0&&(e.clearcoat.value=t.clearcoat,e.clearcoatRoughness.value=t.clearcoatRoughness,t.clearcoatMap&&(e.clearcoatMap.value=t.clearcoatMap,n(t.clearcoatMap,e.clearcoatMapTransform)),t.clearcoatRoughnessMap&&(e.clearcoatRoughnessMap.value=t.clearcoatRoughnessMap,n(t.clearcoatRoughnessMap,e.clearcoatRoughnessMapTransform)),t.clearcoatNormalMap&&(e.clearcoatNormalMap.value=t.clearcoatNormalMap,n(t.clearcoatNormalMap,e.clearcoatNormalMapTransform),e.clearcoatNormalScale.value.copy(t.clearcoatNormalScale),1===t.side&&e.clearcoatNormalScale.value.negate()));t.dispersion>0&&(e.dispersion.value=t.dispersion);t.iridescence>0&&(e.iridescence.value=t.iridescence,e.iridescenceIOR.value=t.iridescenceIOR,e.iridescenceThicknessMinimum.value=t.iridescenceThicknessRange[0],e.iridescenceThicknessMaximum.value=t.iridescenceThicknessRange[1],t.iridescenceMap&&(e.iridescenceMap.value=t.iridescenceMap,n(t.iridescenceMap,e.iridescenceMapTransform)),t.iridescenceThicknessMap&&(e.iridescenceThicknessMap.value=t.iridescenceThicknessMap,n(t.iridescenceThicknessMap,e.iridescenceThicknessMapTransform)));t.transmission>0&&(e.transmission.value=t.transmission,e.transmissionSamplerMap.value=i.texture,e.transmissionSamplerSize.value.set(i.width,i.height),t.transmissionMap&&(e.transmissionMap.value=t.transmissionMap,n(t.transmissionMap,e.transmissionMapTransform)),e.thickness.value=t.thickness,t.thicknessMap&&(e.thicknessMap.value=t.thicknessMap,n(t.thicknessMap,e.thicknessMapTransform)),e.attenuationDistance.value=t.attenuationDistance,e.attenuationColor.value.copy(t.attenuationColor));t.anisotropy>0&&(e.anisotropyVector.value.set(t.anisotropy*Math.cos(t.anisotropyRotation),t.anisotropy*Math.sin(t.anisotropyRotation)),t.anisotropyMap&&(e.anisotropyMap.value=t.anisotropyMap,n(t.anisotropyMap,e.anisotropyMapTransform)));e.specularIntensity.value=t.specularIntensity,e.specularColor.value.copy(t.specularColor),t.specularColorMap&&(e.specularColorMap.value=t.specularColorMap,n(t.specularColorMap,e.specularColorMapTransform));t.specularIntensityMap&&(e.specularIntensityMap.value=t.specularIntensityMap,n(t.specularIntensityMap,e.specularIntensityMapTransform))}(e,r,o)):r.isMeshMatcapMaterial?(i(e,r),function(e,t){t.matcap&&(e.matcap.value=t.matcap)}(e,r)):r.isMeshDepthMaterial?i(e,r):r.isMeshDistanceMaterial?(i(e,r),function(e,n){const i=t.get(n).light;e.referencePosition.value.setFromMatrixPosition(i.matrixWorld),e.nearDistance.value=i.shadow.camera.near,e.farDistance.value=i.shadow.camera.far}(e,r)):r.isMeshNormalMaterial?i(e,r):r.isLineBasicMaterial?(function(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform))}(e,r),r.isLineDashedMaterial&&function(e,t){e.dashSize.value=t.dashSize,e.totalSize.value=t.dashSize+t.gapSize,e.scale.value=t.scale}(e,r)):r.isPointsMaterial?function(e,t,i,r){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.size.value=t.size*i,e.scale.value=.5*r,t.map&&(e.map.value=t.map,n(t.map,e.uvTransform));t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform));t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}(e,r,s,a):r.isSpriteMaterial?function(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.rotation.value=t.rotation,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform));t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform));t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}(e,r):r.isShadowMaterial?(e.color.value.copy(r.color),e.opacity.value=r.opacity):r.isShaderMaterial&&(r.uniformsNeedUpdate=!1)}}}function lu(e,t,n,i){let r={},s={},a=[];const o=e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS);function l(e,t,n,i){const r=e.value,s=t+"_"+n;if(void 0===i[s])return i[s]="number"==typeof r||"boolean"==typeof r?r:r.clone(),!0;{const e=i[s];if("number"==typeof r||"boolean"==typeof r){if(e!==r)return i[s]=r,!0}else if(!1===e.equals(r))return e.copy(r),!0}return!1}function c(e){const t={boundary:0,storage:0};return"number"==typeof e||"boolean"==typeof e?(t.boundary=4,t.storage=4):e.isVector2?(t.boundary=8,t.storage=8):e.isVector3||e.isColor?(t.boundary=16,t.storage=12):e.isVector4?(t.boundary=16,t.storage=16):e.isMatrix3?(t.boundary=48,t.storage=48):e.isMatrix4?(t.boundary=64,t.storage=64):e.isTexture?qn("WebGLRenderer: Texture samplers can not be part of an uniforms group."):qn("WebGLRenderer: Unsupported uniform value type.",e),t}function h(t){const n=t.target;n.removeEventListener("dispose",h);const i=a.indexOf(n.__bindingPointIndex);a.splice(i,1),e.deleteBuffer(r[n.id]),delete r[n.id],delete s[n.id]}return{bind:function(e,t){const n=t.program;i.uniformBlockBinding(e,n)},update:function(n,u){let d=r[n.id];void 0===d&&(!function(e){const t=e.uniforms;let n=0;const i=16;for(let s=0,a=t.length;s<a;s++){const e=Array.isArray(t[s])?t[s]:[t[s]];for(let t=0,r=e.length;t<r;t++){const r=e[t],s=Array.isArray(r.value)?r.value:[r.value];for(let e=0,t=s.length;e<t;e++){const t=c(s[e]),a=n%i,o=a%t.boundary,l=a+o;n+=o,0!==l&&i-l<t.storage&&(n+=i-l),r.__data=new Float32Array(t.storage/Float32Array.BYTES_PER_ELEMENT),r.__offset=n,n+=t.storage}}}const r=n%i;r>0&&(n+=i-r);e.__size=n,e.__cache={}}(n),d=function(t){const n=function(){for(let e=0;e<o;e++)if(-1===a.indexOf(e))return a.push(e),e;return Qn("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}();t.__bindingPointIndex=n;const i=e.createBuffer(),r=t.__size,s=t.usage;return e.bindBuffer(e.UNIFORM_BUFFER,i),e.bufferData(e.UNIFORM_BUFFER,r,s),e.bindBuffer(e.UNIFORM_BUFFER,null),e.bindBufferBase(e.UNIFORM_BUFFER,n,i),i}(n),r[n.id]=d,n.addEventListener("dispose",h));const p=u.program;i.updateUBOMapping(n,p);const f=t.render.frame;s[n.id]!==f&&(!function(t){const n=r[t.id],i=t.uniforms,s=t.__cache;e.bindBuffer(e.UNIFORM_BUFFER,n);for(let r=0,a=i.length;r<a;r++){const t=Array.isArray(i[r])?i[r]:[i[r]];for(let n=0,i=t.length;n<i;n++){const i=t[n];if(!0===l(i,r,n,s)){const t=i.__offset,n=Array.isArray(i.value)?i.value:[i.value];let r=0;for(let s=0;s<n.length;s++){const a=n[s],o=c(a);"number"==typeof a||"boolean"==typeof a?(i.__data[0]=a,e.bufferSubData(e.UNIFORM_BUFFER,t+r,i.__data)):a.isMatrix3?(i.__data[0]=a.elements[0],i.__data[1]=a.elements[1],i.__data[2]=a.elements[2],i.__data[3]=0,i.__data[4]=a.elements[3],i.__data[5]=a.elements[4],i.__data[6]=a.elements[5],i.__data[7]=0,i.__data[8]=a.elements[6],i.__data[9]=a.elements[7],i.__data[10]=a.elements[8],i.__data[11]=0):(a.toArray(i.__data,r),r+=o.storage/Float32Array.BYTES_PER_ELEMENT)}e.bufferSubData(e.UNIFORM_BUFFER,t,i.__data)}}}e.bindBuffer(e.UNIFORM_BUFFER,null)}(n),s[n.id]=f)},dispose:function(){for(const t in r)e.deleteBuffer(r[t]);a=[],r={},s={}}}}const cu=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]);let hu=null;class uu{constructor(e={}){const{canvas:t=Wn(),context:n=null,depth:i=!0,stencil:r=!1,alpha:s=!1,antialias:a=!1,premultipliedAlpha:o=!0,preserveDrawingBuffer:l=!1,powerPreference:c="default",failIfMajorPerformanceCaveat:h=!1,reversedDepthBuffer:u=!1,outputBufferType:d=ht}=e;let p;if(this.isWebGLRenderer=!0,null!==n){if("undefined"!=typeof WebGLRenderingContext&&n instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");p=n.getContextAttributes().alpha}else p=s;const f=d,m=new Set([It,Rt,Et]),g=new Set([ht,mt,pt,yt,vt,xt]),_=new Uint32Array(4),v=new Int32Array(4);let x=null,y=null;const S=[],A=[];let b=null;this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=0,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const M=this;let w=!1;this._outputColorSpace=Mn;let T=0,E=0,C=null,R=-1,I=null;const P=new Ri,D=new Ri;let B=null;const L=new $r(0);let F=0,U=t.width,k=t.height,N=1,O=null,z=null;const H=new Ri(0,0,U,k),V=new Ri(0,0,U,k);let G=!1;const W=new La;let j=!1,X=!1;const q=new or,Q=new hi,K=new Ri,Y={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let Z=!1;function J(){return null===C?N:1}let $,ee,te,ie,re,se,ae,oe,le,ce,he,ue,de,pe,fe,me,ge,_e,ve,xe,ye,Se,Ae,be,Me=n;function we(e,n){return t.getContext(e,n)}try{const e={alpha:!0,depth:i,stencil:r,antialias:a,premultipliedAlpha:o,preserveDrawingBuffer:l,powerPreference:c,failIfMajorPerformanceCaveat:h};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${ne}`),t.addEventListener("webglcontextlost",Ce,!1),t.addEventListener("webglcontextrestored",Re,!1),t.addEventListener("webglcontextcreationerror",Ie,!1),null===Me){const t="webgl2";if(Me=we(t,e),null===Me)throw we(t)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(Qe){throw Qn("WebGLRenderer: "+Qe.message),Qe}function Te(){$=new Ql(Me),$.init(),Se=new nu(Me,$),ee=new Rl(Me,$,e,Se),te=new eu(Me,$),ee.reversedDepthBuffer&&u&&te.buffers.depth.setReversed(!0),ie=new Zl(Me),re=new Uh,se=new tu(Me,$,te,re,ee,Se,ie),ae=new Pl(M),oe=new ql(M),le=new xl(Me),Ae=new El(Me,le),ce=new Kl(Me,le,ie,Ae),he=new $l(Me,ce,le,ie),ve=new Jl(Me,ee,se),me=new Il(re),ue=new Fh(M,ae,oe,$,ee,Ae,me),de=new ou(M,re),pe=new zh,fe=new Xh($),_e=new Tl(M,ae,oe,te,he,p,o),ge=new Jh(M,he,ee),be=new lu(Me,ie,ee,te),xe=new Cl(Me,$,ie),ye=new Yl(Me,$,ie),ie.programs=ue.programs,M.capabilities=ee,M.extensions=$,M.properties=re,M.renderLists=pe,M.shadowMap=ge,M.state=te,M.info=ie}Te(),f!==ht&&(b=new tc(f,t.width,t.height,i,r));const Ee=new ru(M,Me);function Ce(e){e.preventDefault(),Xn("WebGLRenderer: Context Lost."),w=!0}function Re(){Xn("WebGLRenderer: Context Restored."),w=!1;const e=ie.autoReset,t=ge.enabled,n=ge.autoUpdate,i=ge.needsUpdate,r=ge.type;Te(),ie.autoReset=e,ge.enabled=t,ge.autoUpdate=n,ge.needsUpdate=i,ge.type=r}function Ie(e){Qn("WebGLRenderer: A WebGL context could not be created. Reason: ",e.statusMessage)}function Pe(e){const t=e.target;t.removeEventListener("dispose",Pe),function(e){(function(e){const t=re.get(e).programs;void 0!==t&&(t.forEach(function(e){ue.releaseProgram(e)}),e.isShaderMaterial&&ue.releaseShaderCache(e))})(e),re.remove(e)}(t)}function De(e,t,n){!0===e.transparent&&2===e.side&&!1===e.forceSinglePass?(e.side=1,e.needsUpdate=!0,Ve(e,t,n),e.side=0,e.needsUpdate=!0,Ve(e,t,n),e.side=2):Ve(e,t,n)}this.xr=Ee,this.getContext=function(){return Me},this.getContextAttributes=function(){return Me.getContextAttributes()},this.forceContextLoss=function(){const e=$.get("WEBGL_lose_context");e&&e.loseContext()},this.forceContextRestore=function(){const e=$.get("WEBGL_lose_context");e&&e.restoreContext()},this.getPixelRatio=function(){return N},this.setPixelRatio=function(e){void 0!==e&&(N=e,this.setSize(U,k,!1))},this.getSize=function(e){return e.set(U,k)},this.setSize=function(e,n,i=!0){Ee.isPresenting?qn("WebGLRenderer: Can't change size while VR device is presenting."):(U=e,k=n,t.width=Math.floor(e*N),t.height=Math.floor(n*N),!0===i&&(t.style.width=e+"px",t.style.height=n+"px"),null!==b&&b.setSize(t.width,t.height),this.setViewport(0,0,e,n))},this.getDrawingBufferSize=function(e){return e.set(U*N,k*N).floor()},this.setDrawingBufferSize=function(e,n,i){U=e,k=n,N=i,t.width=Math.floor(e*i),t.height=Math.floor(n*i),this.setViewport(0,0,e,n)},this.setEffects=function(e){if(f!==ht){if(e)for(let t=0;t<e.length;t++)if(!0===e[t].isOutputPass){console.warn("THREE.WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.");break}b.setEffects(e||[])}else console.error("THREE.WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.")},this.getCurrentViewport=function(e){return e.copy(P)},this.getViewport=function(e){return e.copy(H)},this.setViewport=function(e,t,n,i){e.isVector4?H.set(e.x,e.y,e.z,e.w):H.set(e,t,n,i),te.viewport(P.copy(H).multiplyScalar(N).round())},this.getScissor=function(e){return e.copy(V)},this.setScissor=function(e,t,n,i){e.isVector4?V.set(e.x,e.y,e.z,e.w):V.set(e,t,n,i),te.scissor(D.copy(V).multiplyScalar(N).round())},this.getScissorTest=function(){return G},this.setScissorTest=function(e){te.setScissorTest(G=e)},this.setOpaqueSort=function(e){O=e},this.setTransparentSort=function(e){z=e},this.getClearColor=function(e){return e.copy(_e.getClearColor())},this.setClearColor=function(){_e.setClearColor(...arguments)},this.getClearAlpha=function(){return _e.getClearAlpha()},this.setClearAlpha=function(){_e.setClearAlpha(...arguments)},this.clear=function(e=!0,t=!0,n=!0){let i=0;if(e){let e=!1;if(null!==C){const t=C.texture.format;e=m.has(t)}if(e){const e=C.texture.type,t=g.has(e),n=_e.getClearColor(),i=_e.getClearAlpha(),r=n.r,s=n.g,a=n.b;t?(_[0]=r,_[1]=s,_[2]=a,_[3]=i,Me.clearBufferuiv(Me.COLOR,0,_)):(v[0]=r,v[1]=s,v[2]=a,v[3]=i,Me.clearBufferiv(Me.COLOR,0,v))}else i|=Me.COLOR_BUFFER_BIT}t&&(i|=Me.DEPTH_BUFFER_BIT),n&&(i|=Me.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),Me.clear(i)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){t.removeEventListener("webglcontextlost",Ce,!1),t.removeEventListener("webglcontextrestored",Re,!1),t.removeEventListener("webglcontextcreationerror",Ie,!1),_e.dispose(),pe.dispose(),fe.dispose(),re.dispose(),ae.dispose(),oe.dispose(),he.dispose(),Ae.dispose(),be.dispose(),ue.dispose(),Ee.dispose(),Ee.removeEventListener("sessionstart",Le),Ee.removeEventListener("sessionend",Fe),Ue.stop()},this.renderBufferDirect=function(e,t,n,i,r,s){null===t&&(t=Y);const a=r.isMesh&&r.matrixWorld.determinant()<0,o=function(e,t,n,i,r){!0!==t.isScene&&(t=Y);se.resetTextureUnits();const s=t.fog,a=i.isMeshStandardMaterial?t.environment:null,o=null===C?M.outputColorSpace:!0===C.isXRRenderTarget?C.texture.colorSpace:wn,l=(i.isMeshStandardMaterial?oe:ae).get(i.envMap||a),c=!0===i.vertexColors&&!!n.attributes.color&&4===n.attributes.color.itemSize,h=!!n.attributes.tangent&&(!!i.normalMap||i.anisotropy>0),u=!!n.morphAttributes.position,d=!!n.morphAttributes.normal,p=!!n.morphAttributes.color;let f=0;i.toneMapped&&(null!==C&&!0!==C.isXRRenderTarget||(f=M.toneMapping));const m=n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color,g=void 0!==m?m.length:0,_=re.get(i),v=y.state.lights;if(!0===j&&(!0===X||e!==I)){const t=e===I&&i.id===R;me.setState(i,e,t)}let x=!1;i.version===_.__version?_.needsLights&&_.lightsStateVersion!==v.state.version||_.outputColorSpace!==o||r.isBatchedMesh&&!1===_.batching?x=!0:r.isBatchedMesh||!0!==_.batching?r.isBatchedMesh&&!0===_.batchingColor&&null===r.colorTexture||r.isBatchedMesh&&!1===_.batchingColor&&null!==r.colorTexture||r.isInstancedMesh&&!1===_.instancing?x=!0:r.isInstancedMesh||!0!==_.instancing?r.isSkinnedMesh&&!1===_.skinning?x=!0:r.isSkinnedMesh||!0!==_.skinning?r.isInstancedMesh&&!0===_.instancingColor&&null===r.instanceColor||r.isInstancedMesh&&!1===_.instancingColor&&null!==r.instanceColor||r.isInstancedMesh&&!0===_.instancingMorph&&null===r.morphTexture||r.isInstancedMesh&&!1===_.instancingMorph&&null!==r.morphTexture||_.envMap!==l||!0===i.fog&&_.fog!==s?x=!0:void 0===_.numClippingPlanes||_.numClippingPlanes===me.numPlanes&&_.numIntersection===me.numIntersection?(_.vertexAlphas!==c||_.vertexTangents!==h||_.morphTargets!==u||_.morphNormals!==d||_.morphColors!==p||_.toneMapping!==f||_.morphTargetsCount!==g)&&(x=!0):x=!0:x=!0:x=!0:x=!0:(x=!0,_.__version=i.version);let S=_.currentProgram;!0===x&&(S=Ve(i,t,r));let A=!1,b=!1,w=!1;const T=S.getUniforms(),E=_.uniforms;te.useProgram(S.program)&&(A=!0,b=!0,w=!0);i.id!==R&&(R=i.id,b=!0);if(A||I!==e){te.buffers.depth.getReversed()&&!0!==e.reversedDepth&&(e._reversedDepth=!0,e.updateProjectionMatrix()),T.setValue(Me,"projectionMatrix",e.projectionMatrix),T.setValue(Me,"viewMatrix",e.matrixWorldInverse);const t=T.map.cameraPosition;void 0!==t&&t.setValue(Me,Q.setFromMatrixPosition(e.matrixWorld)),ee.logarithmicDepthBuffer&&T.setValue(Me,"logDepthBufFC",2/(Math.log(e.far+1)/Math.LN2)),(i.isMeshPhongMaterial||i.isMeshToonMaterial||i.isMeshLambertMaterial||i.isMeshBasicMaterial||i.isMeshStandardMaterial||i.isShaderMaterial)&&T.setValue(Me,"isOrthographic",!0===e.isOrthographicCamera),I!==e&&(I=e,b=!0,w=!0)}_.needsLights&&(v.state.directionalShadowMap.length>0&&T.setValue(Me,"directionalShadowMap",v.state.directionalShadowMap,se),v.state.spotShadowMap.length>0&&T.setValue(Me,"spotShadowMap",v.state.spotShadowMap,se),v.state.pointShadowMap.length>0&&T.setValue(Me,"pointShadowMap",v.state.pointShadowMap,se));if(r.isSkinnedMesh){T.setOptional(Me,r,"bindMatrix"),T.setOptional(Me,r,"bindMatrixInverse");const e=r.skeleton;e&&(null===e.boneTexture&&e.computeBoneTexture(),T.setValue(Me,"boneTexture",e.boneTexture,se))}r.isBatchedMesh&&(T.setOptional(Me,r,"batchingTexture"),T.setValue(Me,"batchingTexture",r._matricesTexture,se),T.setOptional(Me,r,"batchingIdTexture"),T.setValue(Me,"batchingIdTexture",r._indirectTexture,se),T.setOptional(Me,r,"batchingColorTexture"),null!==r._colorsTexture&&T.setValue(Me,"batchingColorTexture",r._colorsTexture,se));const P=n.morphAttributes;void 0===P.position&&void 0===P.normal&&void 0===P.color||ve.update(r,n,S);(b||_.receiveShadow!==r.receiveShadow)&&(_.receiveShadow=r.receiveShadow,T.setValue(Me,"receiveShadow",r.receiveShadow));i.isMeshGouraudMaterial&&null!==i.envMap&&(E.envMap.value=l,E.flipEnvMap.value=l.isCubeTexture&&!1===l.isRenderTargetTexture?-1:1);i.isMeshStandardMaterial&&null===i.envMap&&null!==t.environment&&(E.envMapIntensity.value=t.environmentIntensity);void 0!==E.dfgLUT&&(E.dfgLUT.value=(null===hu&&(hu=new fa(cu,16,16,Ct,_t),hu.name="DFG_LUT",hu.minFilter=ot,hu.magFilter=ot,hu.wrapS=nt,hu.wrapT=nt,hu.generateMipmaps=!1,hu.needsUpdate=!0),hu));b&&(T.setValue(Me,"toneMappingExposure",M.toneMappingExposure),_.needsLights&&(B=w,(D=E).ambientLightColor.needsUpdate=B,D.lightProbe.needsUpdate=B,D.directionalLights.needsUpdate=B,D.directionalLightShadows.needsUpdate=B,D.pointLights.needsUpdate=B,D.pointLightShadows.needsUpdate=B,D.spotLights.needsUpdate=B,D.spotLightShadows.needsUpdate=B,D.rectAreaLights.needsUpdate=B,D.hemisphereLights.needsUpdate=B),s&&!0===i.fog&&de.refreshFogUniforms(E,s),de.refreshMaterialUniforms(E,i,N,k,y.state.transmissionRenderTarget[e.id]),ah.upload(Me,Ge(_),E,se));var D,B;i.isShaderMaterial&&!0===i.uniformsNeedUpdate&&(ah.upload(Me,Ge(_),E,se),i.uniformsNeedUpdate=!1);i.isSpriteMaterial&&T.setValue(Me,"center",r.center);if(T.setValue(Me,"modelViewMatrix",r.modelViewMatrix),T.setValue(Me,"normalMatrix",r.normalMatrix),T.setValue(Me,"modelMatrix",r.matrixWorld),i.isShaderMaterial||i.isRawShaderMaterial){const e=i.uniformsGroups;for(let t=0,n=e.length;t<n;t++){const n=e[t];be.update(n,S),be.bind(n,S)}}return S}(e,t,n,i,r);te.setMaterial(i,a);let l=n.index,c=1;if(!0===i.wireframe){if(l=ce.getWireframeAttribute(n),void 0===l)return;c=2}const h=n.drawRange,u=n.attributes.position;let d=h.start*c,p=(h.start+h.count)*c;null!==s&&(d=Math.max(d,s.start*c),p=Math.min(p,(s.start+s.count)*c)),null!==l?(d=Math.max(d,0),p=Math.min(p,l.count)):null!=u&&(d=Math.max(d,0),p=Math.min(p,u.count));const f=p-d;if(f<0||f===1/0)return;let m;Ae.setup(r,i,o,n,l);let g=xe;if(null!==l&&(m=le.get(l),g=ye,g.setIndex(m)),r.isMesh)!0===i.wireframe?(te.setLineWidth(i.wireframeLinewidth*J()),g.setMode(Me.LINES)):g.setMode(Me.TRIANGLES);else if(r.isLine){let e=i.linewidth;void 0===e&&(e=1),te.setLineWidth(e*J()),r.isLineSegments?g.setMode(Me.LINES):r.isLineLoop?g.setMode(Me.LINE_LOOP):g.setMode(Me.LINE_STRIP)}else r.isPoints?g.setMode(Me.POINTS):r.isSprite&&g.setMode(Me.TRIANGLES);if(r.isBatchedMesh)if(null!==r._multiDrawInstances)Kn("WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),g.renderMultiDrawInstances(r._multiDrawStarts,r._multiDrawCounts,r._multiDrawCount,r._multiDrawInstances);else if($.get("WEBGL_multi_draw"))g.renderMultiDraw(r._multiDrawStarts,r._multiDrawCounts,r._multiDrawCount);else{const e=r._multiDrawStarts,t=r._multiDrawCounts,n=r._multiDrawCount,s=l?le.get(l).bytesPerElement:1,a=re.get(i).currentProgram.getUniforms();for(let i=0;i<n;i++)a.setValue(Me,"_gl_DrawID",i),g.render(e[i]/s,t[i])}else if(r.isInstancedMesh)g.renderInstances(d,f,r.count);else if(n.isInstancedBufferGeometry){const e=void 0!==n._maxInstanceCount?n._maxInstanceCount:1/0,t=Math.min(n.instanceCount,e);g.renderInstances(d,f,t)}else g.render(d,f)},this.compile=function(e,t,n=null){null===n&&(n=e),y=fe.get(n),y.init(t),A.push(y),n.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(y.pushLight(e),e.castShadow&&y.pushShadow(e))}),e!==n&&e.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(y.pushLight(e),e.castShadow&&y.pushShadow(e))}),y.setupLights();const i=new Set;return e.traverse(function(e){if(!(e.isMesh||e.isPoints||e.isLine||e.isSprite))return;const t=e.material;if(t)if(Array.isArray(t))for(let r=0;r<t.length;r++){const s=t[r];De(s,n,e),i.add(s)}else De(t,n,e),i.add(t)}),y=A.pop(),i},this.compileAsync=function(e,t,n=null){const i=this.compile(e,t,n);return new Promise(t=>{function n(){i.forEach(function(e){re.get(e).currentProgram.isReady()&&i.delete(e)}),0!==i.size?setTimeout(n,10):t(e)}null!==$.get("KHR_parallel_shader_compile")?n():setTimeout(n,10)})};let Be=null;function Le(){Ue.stop()}function Fe(){Ue.start()}const Ue=new vl;function ke(e,t,n,i){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)n=e.renderOrder;else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)y.pushLight(e),e.castShadow&&y.pushShadow(e);else if(e.isSprite){if(!e.frustumCulled||W.intersectsSprite(e)){i&&K.setFromMatrixPosition(e.matrixWorld).applyMatrix4(q);const t=he.update(e),r=e.material;r.visible&&x.push(e,t,r,n,K.z,null)}}else if((e.isMesh||e.isLine||e.isPoints)&&(!e.frustumCulled||W.intersectsObject(e))){const t=he.update(e),r=e.material;if(i&&(void 0!==e.boundingSphere?(null===e.boundingSphere&&e.computeBoundingSphere(),K.copy(e.boundingSphere.center)):(null===t.boundingSphere&&t.computeBoundingSphere(),K.copy(t.boundingSphere.center)),K.applyMatrix4(e.matrixWorld).applyMatrix4(q)),Array.isArray(r)){const i=t.groups;for(let s=0,a=i.length;s<a;s++){const a=i[s],o=r[a.materialIndex];o&&o.visible&&x.push(e,t,o,n,K.z,a)}}else r.visible&&x.push(e,t,r,n,K.z,null)}const r=e.children;for(let s=0,a=r.length;s<a;s++)ke(r[s],t,n,i)}function Ne(e,t,n,i){const{opaque:r,transmissive:s,transparent:a}=e;y.setupLightsView(n),!0===j&&me.setGlobalState(M.clippingPlanes,n),i&&te.viewport(P.copy(i)),r.length>0&&ze(r,t,n),s.length>0&&ze(s,t,n),a.length>0&&ze(a,t,n),te.buffers.depth.setTest(!0),te.buffers.depth.setMask(!0),te.buffers.color.setMask(!0),te.setPolygonOffset(!1)}function Oe(e,t,n,i){if(null!==(!0===n.isScene?n.overrideMaterial:null))return;if(void 0===y.state.transmissionRenderTarget[i.id]){const e=$.has("EXT_color_buffer_half_float")||$.has("EXT_color_buffer_float");y.state.transmissionRenderTarget[i.id]=new Pi(1,1,{generateMipmaps:!0,type:e?_t:ht,minFilter:ct,samples:ee.samples,stencilBuffer:r,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:vi.workingColorSpace})}const s=y.state.transmissionRenderTarget[i.id],a=i.viewport||P;s.setSize(a.z*M.transmissionResolutionScale,a.w*M.transmissionResolutionScale);const o=M.getRenderTarget(),l=M.getActiveCubeFace(),c=M.getActiveMipmapLevel();M.setRenderTarget(s),M.getClearColor(L),F=M.getClearAlpha(),F<1&&M.setClearColor(16777215,.5),M.clear(),Z&&_e.render(n);const h=M.toneMapping;M.toneMapping=0;const u=i.viewport;if(void 0!==i.viewport&&(i.viewport=void 0),y.setupLightsView(i),!0===j&&me.setGlobalState(M.clippingPlanes,i),ze(e,n,i),se.updateMultisampleRenderTarget(s),se.updateRenderTargetMipmap(s),!1===$.has("WEBGL_multisampled_render_to_texture")){let e=!1;for(let r=0,s=t.length;r<s;r++){const s=t[r],{object:a,geometry:o,material:l,group:c}=s;if(2===l.side&&a.layers.test(i.layers)){const t=l.side;l.side=1,l.needsUpdate=!0,He(a,n,i,o,l,c),l.side=t,l.needsUpdate=!0,e=!0}}!0===e&&(se.updateMultisampleRenderTarget(s),se.updateRenderTargetMipmap(s))}M.setRenderTarget(o,l,c),M.setClearColor(L,F),void 0!==u&&(i.viewport=u),M.toneMapping=h}function ze(e,t,n){const i=!0===t.isScene?t.overrideMaterial:null;for(let r=0,s=e.length;r<s;r++){const s=e[r],{object:a,geometry:o,group:l}=s;let c=s.material;!0===c.allowOverride&&null!==i&&(c=i),a.layers.test(n.layers)&&He(a,t,n,o,c,l)}}function He(e,t,n,i,r,s){e.onBeforeRender(M,t,n,i,r,s),e.modelViewMatrix.multiplyMatrices(n.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix),r.onBeforeRender(M,t,n,i,e,s),!0===r.transparent&&2===r.side&&!1===r.forceSinglePass?(r.side=1,r.needsUpdate=!0,M.renderBufferDirect(n,t,i,r,e,s),r.side=0,r.needsUpdate=!0,M.renderBufferDirect(n,t,i,r,e,s),r.side=2):M.renderBufferDirect(n,t,i,r,e,s),e.onAfterRender(M,t,n,i,r,s)}function Ve(e,t,n){!0!==t.isScene&&(t=Y);const i=re.get(e),r=y.state.lights,s=y.state.shadowsArray,a=r.state.version,o=ue.getParameters(e,r.state,s,t,n),l=ue.getProgramCacheKey(o);let c=i.programs;i.environment=e.isMeshStandardMaterial?t.environment:null,i.fog=t.fog,i.envMap=(e.isMeshStandardMaterial?oe:ae).get(e.envMap||i.environment),i.envMapRotation=null!==i.environment&&null===e.envMap?t.environmentRotation:e.envMapRotation,void 0===c&&(e.addEventListener("dispose",Pe),c=new Map,i.programs=c);let h=c.get(l);if(void 0!==h){if(i.currentProgram===h&&i.lightsStateVersion===a)return We(e,o),h}else o.uniforms=ue.getUniforms(e),e.onBeforeCompile(o,M),h=ue.acquireProgram(o,l),c.set(l,h),i.uniforms=o.uniforms;const u=i.uniforms;return(e.isShaderMaterial||e.isRawShaderMaterial)&&!0!==e.clipping||(u.clippingPlanes=me.uniform),We(e,o),i.needsLights=function(e){return e.isMeshLambertMaterial||e.isMeshToonMaterial||e.isMeshPhongMaterial||e.isMeshStandardMaterial||e.isShadowMaterial||e.isShaderMaterial&&!0===e.lights}(e),i.lightsStateVersion=a,i.needsLights&&(u.ambientLightColor.value=r.state.ambient,u.lightProbe.value=r.state.probe,u.directionalLights.value=r.state.directional,u.directionalLightShadows.value=r.state.directionalShadow,u.spotLights.value=r.state.spot,u.spotLightShadows.value=r.state.spotShadow,u.rectAreaLights.value=r.state.rectArea,u.ltc_1.value=r.state.rectAreaLTC1,u.ltc_2.value=r.state.rectAreaLTC2,u.pointLights.value=r.state.point,u.pointLightShadows.value=r.state.pointShadow,u.hemisphereLights.value=r.state.hemi,u.directionalShadowMap.value=r.state.directionalShadowMap,u.directionalShadowMatrix.value=r.state.directionalShadowMatrix,u.spotShadowMap.value=r.state.spotShadowMap,u.spotLightMatrix.value=r.state.spotLightMatrix,u.spotLightMap.value=r.state.spotLightMap,u.pointShadowMap.value=r.state.pointShadowMap,u.pointShadowMatrix.value=r.state.pointShadowMatrix),i.currentProgram=h,i.uniformsList=null,h}function Ge(e){if(null===e.uniformsList){const t=e.currentProgram.getUniforms();e.uniformsList=ah.seqWithValue(t.seq,e.uniforms)}return e.uniformsList}function We(e,t){const n=re.get(e);n.outputColorSpace=t.outputColorSpace,n.batching=t.batching,n.batchingColor=t.batchingColor,n.instancing=t.instancing,n.instancingColor=t.instancingColor,n.instancingMorph=t.instancingMorph,n.skinning=t.skinning,n.morphTargets=t.morphTargets,n.morphNormals=t.morphNormals,n.morphColors=t.morphColors,n.morphTargetsCount=t.morphTargetsCount,n.numClippingPlanes=t.numClippingPlanes,n.numIntersection=t.numClipIntersection,n.vertexAlphas=t.vertexAlphas,n.vertexTangents=t.vertexTangents,n.toneMapping=t.toneMapping}Ue.setAnimationLoop(function(e){Be&&Be(e)}),"undefined"!=typeof self&&Ue.setContext(self),this.setAnimationLoop=function(e){Be=e,Ee.setAnimationLoop(e),null===e?Ue.stop():Ue.start()},Ee.addEventListener("sessionstart",Le),Ee.addEventListener("sessionend",Fe),this.render=function(e,t){if(void 0!==t&&!0!==t.isCamera)return void Qn("WebGLRenderer.render: camera is not an instance of THREE.Camera.");if(!0===w)return;const n=!0===Ee.enabled&&!0===Ee.isPresenting,i=null!==b&&(null===C||n)&&b.begin(M,C);if(!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&!0===t.matrixWorldAutoUpdate&&t.updateMatrixWorld(),!0!==Ee.enabled||!0!==Ee.isPresenting||null!==b&&!1!==b.isCompositing()||(!0===Ee.cameraAutoUpdate&&Ee.updateCamera(t),t=Ee.getCamera()),!0===e.isScene&&e.onBeforeRender(M,e,t,C),y=fe.get(e,A.length),y.init(t),A.push(y),q.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),W.setFromProjectionMatrix(q,zn,t.reversedDepth),X=this.localClippingEnabled,j=me.init(this.clippingPlanes,X),x=pe.get(e,S.length),x.init(),S.push(x),!0===Ee.enabled&&!0===Ee.isPresenting){const e=M.xr.getDepthSensingMesh();null!==e&&ke(e,t,-1/0,M.sortObjects)}ke(e,t,0,M.sortObjects),x.finish(),!0===M.sortObjects&&x.sort(O,z),Z=!1===Ee.enabled||!1===Ee.isPresenting||!1===Ee.hasDepthSensing(),Z&&_e.addToRenderList(x,e),this.info.render.frame++,!0===j&&me.beginShadows();const r=y.state.shadowsArray;ge.render(r,e,t),!0===j&&me.endShadows(),!0===this.info.autoReset&&this.info.reset();if(!1===(i&&b.hasRenderPass())){const n=x.opaque,i=x.transmissive;if(y.setupLights(),t.isArrayCamera){const r=t.cameras;if(i.length>0)for(let t=0,s=r.length;t<s;t++){Oe(n,i,e,r[t])}Z&&_e.render(e);for(let t=0,n=r.length;t<n;t++){const n=r[t];Ne(x,e,n,n.viewport)}}else i.length>0&&Oe(n,i,e,t),Z&&_e.render(e),Ne(x,e,t)}null!==C&&0===E&&(se.updateMultisampleRenderTarget(C),se.updateRenderTargetMipmap(C)),i&&b.end(M),!0===e.isScene&&e.onAfterRender(M,e,t),Ae.resetDefaultState(),R=-1,I=null,A.pop(),A.length>0?(y=A[A.length-1],!0===j&&me.setGlobalState(M.clippingPlanes,y.state.camera)):y=null,S.pop(),x=S.length>0?S[S.length-1]:null},this.getActiveCubeFace=function(){return T},this.getActiveMipmapLevel=function(){return E},this.getRenderTarget=function(){return C},this.setRenderTargetTextures=function(e,t,n){const i=re.get(e);i.__autoAllocateDepthBuffer=!1===e.resolveDepthBuffer,!1===i.__autoAllocateDepthBuffer&&(i.__useRenderToTexture=!1),re.get(e.texture).__webglTexture=t,re.get(e.depthTexture).__webglTexture=i.__autoAllocateDepthBuffer?void 0:n,i.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(e,t){const n=re.get(e);n.__webglFramebuffer=t,n.__useDefaultFramebuffer=void 0===t};const je=Me.createFramebuffer();this.setRenderTarget=function(e,t=0,n=0){C=e,T=t,E=n;let i=null,r=!1,s=!1;if(e){const a=re.get(e);if(void 0!==a.__useDefaultFramebuffer)return te.bindFramebuffer(Me.FRAMEBUFFER,a.__webglFramebuffer),P.copy(e.viewport),D.copy(e.scissor),B=e.scissorTest,te.viewport(P),te.scissor(D),te.setScissorTest(B),void(R=-1);if(void 0===a.__webglFramebuffer)se.setupRenderTarget(e);else if(a.__hasExternalTextures)se.rebindTextures(e,re.get(e.texture).__webglTexture,re.get(e.depthTexture).__webglTexture);else if(e.depthBuffer){const t=e.depthTexture;if(a.__boundDepthTexture!==t){if(null!==t&&re.has(t)&&(e.width!==t.image.width||e.height!==t.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");se.setupDepthRenderbuffer(e)}}const o=e.texture;(o.isData3DTexture||o.isDataArrayTexture||o.isCompressedArrayTexture)&&(s=!0);const l=re.get(e).__webglFramebuffer;e.isWebGLCubeRenderTarget?(i=Array.isArray(l[t])?l[t][n]:l[t],r=!0):i=e.samples>0&&!1===se.useMultisampledRTT(e)?re.get(e).__webglMultisampledFramebuffer:Array.isArray(l)?l[n]:l,P.copy(e.viewport),D.copy(e.scissor),B=e.scissorTest}else P.copy(H).multiplyScalar(N).floor(),D.copy(V).multiplyScalar(N).floor(),B=G;0!==n&&(i=je);if(te.bindFramebuffer(Me.FRAMEBUFFER,i)&&te.drawBuffers(e,i),te.viewport(P),te.scissor(D),te.setScissorTest(B),r){const i=re.get(e.texture);Me.framebufferTexture2D(Me.FRAMEBUFFER,Me.COLOR_ATTACHMENT0,Me.TEXTURE_CUBE_MAP_POSITIVE_X+t,i.__webglTexture,n)}else if(s){const i=t;for(let t=0;t<e.textures.length;t++){const r=re.get(e.textures[t]);Me.framebufferTextureLayer(Me.FRAMEBUFFER,Me.COLOR_ATTACHMENT0+t,r.__webglTexture,n,i)}}else if(null!==e&&0!==n){const t=re.get(e.texture);Me.framebufferTexture2D(Me.FRAMEBUFFER,Me.COLOR_ATTACHMENT0,Me.TEXTURE_2D,t.__webglTexture,n)}R=-1},this.readRenderTargetPixels=function(e,t,n,i,r,s,a,o=0){if(!e||!e.isWebGLRenderTarget)return void Qn("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let l=re.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&void 0!==a&&(l=l[a]),l){te.bindFramebuffer(Me.FRAMEBUFFER,l);try{const a=e.textures[o],l=a.format,c=a.type;if(!ee.textureFormatReadable(l))return void Qn("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");if(!ee.textureTypeReadable(c))return void Qn("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");t>=0&&t<=e.width-i&&n>=0&&n<=e.height-r&&(e.textures.length>1&&Me.readBuffer(Me.COLOR_ATTACHMENT0+o),Me.readPixels(t,n,i,r,Se.convert(l),Se.convert(c),s))}finally{const e=null!==C?re.get(C).__webglFramebuffer:null;te.bindFramebuffer(Me.FRAMEBUFFER,e)}}},this.readRenderTargetPixelsAsync=async function(e,t,n,i,r,s,a,o=0){if(!e||!e.isWebGLRenderTarget)throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let l=re.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&void 0!==a&&(l=l[a]),l){if(t>=0&&t<=e.width-i&&n>=0&&n<=e.height-r){te.bindFramebuffer(Me.FRAMEBUFFER,l);const a=e.textures[o],c=a.format,h=a.type;if(!ee.textureFormatReadable(c))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!ee.textureTypeReadable(h))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const u=Me.createBuffer();Me.bindBuffer(Me.PIXEL_PACK_BUFFER,u),Me.bufferData(Me.PIXEL_PACK_BUFFER,s.byteLength,Me.STREAM_READ),e.textures.length>1&&Me.readBuffer(Me.COLOR_ATTACHMENT0+o),Me.readPixels(t,n,i,r,Se.convert(c),Se.convert(h),0);const d=null!==C?re.get(C).__webglFramebuffer:null;te.bindFramebuffer(Me.FRAMEBUFFER,d);const p=Me.fenceSync(Me.SYNC_GPU_COMMANDS_COMPLETE,0);return Me.flush(),await function(e,t,n){return new Promise(function(i,r){setTimeout(function s(){switch(e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0)){case e.WAIT_FAILED:r();break;case e.TIMEOUT_EXPIRED:setTimeout(s,n);break;default:i()}},n)})}(Me,p,4),Me.bindBuffer(Me.PIXEL_PACK_BUFFER,u),Me.getBufferSubData(Me.PIXEL_PACK_BUFFER,0,s),Me.deleteBuffer(u),Me.deleteSync(p),s}throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")}},this.copyFramebufferToTexture=function(e,t=null,n=0){const i=Math.pow(2,-n),r=Math.floor(e.image.width*i),s=Math.floor(e.image.height*i),a=null!==t?t.x:0,o=null!==t?t.y:0;se.setTexture2D(e,0),Me.copyTexSubImage2D(Me.TEXTURE_2D,n,0,0,a,o,r,s),te.unbindTexture()};const Xe=Me.createFramebuffer(),qe=Me.createFramebuffer();this.copyTextureToTexture=function(e,t,n=null,i=null,r=0,s=null){let a,o,l,c,h,u,d,p,f;null===s&&(0!==r?(Kn("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),s=r,r=0):s=0);const m=e.isCompressedTexture?e.mipmaps[s]:e.image;if(null!==n)a=n.max.x-n.min.x,o=n.max.y-n.min.y,l=n.isBox3?n.max.z-n.min.z:1,c=n.min.x,h=n.min.y,u=n.isBox3?n.min.z:0;else{const t=Math.pow(2,-r);a=Math.floor(m.width*t),o=Math.floor(m.height*t),l=e.isDataArrayTexture?m.depth:e.isData3DTexture?Math.floor(m.depth*t):1,c=0,h=0,u=0}null!==i?(d=i.x,p=i.y,f=i.z):(d=0,p=0,f=0);const g=Se.convert(t.format),_=Se.convert(t.type);let v;t.isData3DTexture?(se.setTexture3D(t,0),v=Me.TEXTURE_3D):t.isDataArrayTexture||t.isCompressedArrayTexture?(se.setTexture2DArray(t,0),v=Me.TEXTURE_2D_ARRAY):(se.setTexture2D(t,0),v=Me.TEXTURE_2D),Me.pixelStorei(Me.UNPACK_FLIP_Y_WEBGL,t.flipY),Me.pixelStorei(Me.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),Me.pixelStorei(Me.UNPACK_ALIGNMENT,t.unpackAlignment);const x=Me.getParameter(Me.UNPACK_ROW_LENGTH),y=Me.getParameter(Me.UNPACK_IMAGE_HEIGHT),S=Me.getParameter(Me.UNPACK_SKIP_PIXELS),A=Me.getParameter(Me.UNPACK_SKIP_ROWS),b=Me.getParameter(Me.UNPACK_SKIP_IMAGES);Me.pixelStorei(Me.UNPACK_ROW_LENGTH,m.width),Me.pixelStorei(Me.UNPACK_IMAGE_HEIGHT,m.height),Me.pixelStorei(Me.UNPACK_SKIP_PIXELS,c),Me.pixelStorei(Me.UNPACK_SKIP_ROWS,h),Me.pixelStorei(Me.UNPACK_SKIP_IMAGES,u);const M=e.isDataArrayTexture||e.isData3DTexture,w=t.isDataArrayTexture||t.isData3DTexture;if(e.isDepthTexture){const n=re.get(e),i=re.get(t),m=re.get(n.__renderTarget),g=re.get(i.__renderTarget);te.bindFramebuffer(Me.READ_FRAMEBUFFER,m.__webglFramebuffer),te.bindFramebuffer(Me.DRAW_FRAMEBUFFER,g.__webglFramebuffer);for(let _=0;_<l;_++)M&&(Me.framebufferTextureLayer(Me.READ_FRAMEBUFFER,Me.COLOR_ATTACHMENT0,re.get(e).__webglTexture,r,u+_),Me.framebufferTextureLayer(Me.DRAW_FRAMEBUFFER,Me.COLOR_ATTACHMENT0,re.get(t).__webglTexture,s,f+_)),Me.blitFramebuffer(c,h,a,o,d,p,a,o,Me.DEPTH_BUFFER_BIT,Me.NEAREST);te.bindFramebuffer(Me.READ_FRAMEBUFFER,null),te.bindFramebuffer(Me.DRAW_FRAMEBUFFER,null)}else if(0!==r||e.isRenderTargetTexture||re.has(e)){const n=re.get(e),i=re.get(t);te.bindFramebuffer(Me.READ_FRAMEBUFFER,Xe),te.bindFramebuffer(Me.DRAW_FRAMEBUFFER,qe);for(let e=0;e<l;e++)M?Me.framebufferTextureLayer(Me.READ_FRAMEBUFFER,Me.COLOR_ATTACHMENT0,n.__webglTexture,r,u+e):Me.framebufferTexture2D(Me.READ_FRAMEBUFFER,Me.COLOR_ATTACHMENT0,Me.TEXTURE_2D,n.__webglTexture,r),w?Me.framebufferTextureLayer(Me.DRAW_FRAMEBUFFER,Me.COLOR_ATTACHMENT0,i.__webglTexture,s,f+e):Me.framebufferTexture2D(Me.DRAW_FRAMEBUFFER,Me.COLOR_ATTACHMENT0,Me.TEXTURE_2D,i.__webglTexture,s),0!==r?Me.blitFramebuffer(c,h,a,o,d,p,a,o,Me.COLOR_BUFFER_BIT,Me.NEAREST):w?Me.copyTexSubImage3D(v,s,d,p,f+e,c,h,a,o):Me.copyTexSubImage2D(v,s,d,p,c,h,a,o);te.bindFramebuffer(Me.READ_FRAMEBUFFER,null),te.bindFramebuffer(Me.DRAW_FRAMEBUFFER,null)}else w?e.isDataTexture||e.isData3DTexture?Me.texSubImage3D(v,s,d,p,f,a,o,l,g,_,m.data):t.isCompressedArrayTexture?Me.compressedTexSubImage3D(v,s,d,p,f,a,o,l,g,m.data):Me.texSubImage3D(v,s,d,p,f,a,o,l,g,_,m):e.isDataTexture?Me.texSubImage2D(Me.TEXTURE_2D,s,d,p,a,o,g,_,m.data):e.isCompressedTexture?Me.compressedTexSubImage2D(Me.TEXTURE_2D,s,d,p,m.width,m.height,g,m.data):Me.texSubImage2D(Me.TEXTURE_2D,s,d,p,a,o,g,_,m);Me.pixelStorei(Me.UNPACK_ROW_LENGTH,x),Me.pixelStorei(Me.UNPACK_IMAGE_HEIGHT,y),Me.pixelStorei(Me.UNPACK_SKIP_PIXELS,S),Me.pixelStorei(Me.UNPACK_SKIP_ROWS,A),Me.pixelStorei(Me.UNPACK_SKIP_IMAGES,b),0===s&&t.generateMipmaps&&Me.generateMipmap(v),te.unbindTexture()},this.initRenderTarget=function(e){void 0===re.get(e).__webglFramebuffer&&se.setupRenderTarget(e)},this.initTexture=function(e){e.isCubeTexture?se.setTextureCube(e,0):e.isData3DTexture?se.setTexture3D(e,0):e.isDataArrayTexture||e.isCompressedArrayTexture?se.setTexture2DArray(e,0):se.setTexture2D(e,0),te.unbindTexture()},this.resetState=function(){T=0,E=0,C=null,te.reset(),Ae.reset()},"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return zn}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const t=this.getContext();t.drawingBufferColorSpace=vi._getDrawingBufferColorSpace(e),t.unpackColorSpace=vi._getUnpackColorSpace()}}function du(e,t){if(0===t)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),e;if(2===t||1===t){let n=e.getIndex();if(null===n){const t=[],i=e.getAttribute("position");if(void 0===i)return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),e;for(let e=0;e<i.count;e++)t.push(e);e.setIndex(t),n=e.getIndex()}const i=n.count-2,r=[];if(2===t)for(let e=1;e<=i;e++)r.push(n.getX(0)),r.push(n.getX(e)),r.push(n.getX(e+1));else for(let e=0;e<i;e++)e%2==0?(r.push(n.getX(e)),r.push(n.getX(e+1)),r.push(n.getX(e+2))):(r.push(n.getX(e+2)),r.push(n.getX(e+1)),r.push(n.getX(e)));r.length/3!==i&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const s=e.clone();return s.setIndex(r),s.clearGroups(),s}return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",t),e}class pu extends Bo{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(e){return new xu(e)}),this.register(function(e){return new yu(e)}),this.register(function(e){return new Ru(e)}),this.register(function(e){return new Iu(e)}),this.register(function(e){return new Pu(e)}),this.register(function(e){return new Au(e)}),this.register(function(e){return new bu(e)}),this.register(function(e){return new Mu(e)}),this.register(function(e){return new wu(e)}),this.register(function(e){return new vu(e)}),this.register(function(e){return new Tu(e)}),this.register(function(e){return new Su(e)}),this.register(function(e){return new Cu(e)}),this.register(function(e){return new Eu(e)}),this.register(function(e){return new gu(e)}),this.register(function(e){return new Du(e)}),this.register(function(e){return new Bu(e)})}load(e,t,n,i){const r=this;let s;if(""!==this.resourcePath)s=this.resourcePath;else if(""!==this.path){const t=Jo.extractUrlBase(e);s=Jo.resolveURL(t,this.path)}else s=Jo.extractUrlBase(e);this.manager.itemStart(e);const a=function(t){i?i(t):console.error(t),r.manager.itemError(e),r.manager.itemEnd(e)},o=new Uo(this.manager);o.setPath(this.path),o.setResponseType("arraybuffer"),o.setRequestHeader(this.requestHeader),o.setWithCredentials(this.withCredentials),o.load(e,function(n){try{r.parse(n,s,function(n){t(n),r.manager.itemEnd(e)},a)}catch(i){a(i)}},n,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-1===this.pluginCallbacks.indexOf(e)&&this.pluginCallbacks.push(e),this}unregister(e){return-1!==this.pluginCallbacks.indexOf(e)&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,n,i){let r;const s={},a={},o=new TextDecoder;if("string"==typeof e)r=JSON.parse(e);else if(e instanceof ArrayBuffer){if(o.decode(new Uint8Array(e,0,4))===Lu){try{s[mu.KHR_BINARY_GLTF]=new ku(e)}catch(c){return void(i&&i(c))}r=JSON.parse(s[mu.KHR_BINARY_GLTF].content)}else r=JSON.parse(o.decode(e))}else r=e;if(void 0===r.asset||r.asset.version[0]<2)return void(i&&i(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.")));const l=new cd(r,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});l.fileLoader.setRequestHeader(this.requestHeader);for(let h=0;h<this.pluginCallbacks.length;h++){const e=this.pluginCallbacks[h](l);e.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),a[e.name]=e,s[e.name]=!0}if(r.extensionsUsed)for(let h=0;h<r.extensionsUsed.length;++h){const e=r.extensionsUsed[h],t=r.extensionsRequired||[];switch(e){case mu.KHR_MATERIALS_UNLIT:s[e]=new _u;break;case mu.KHR_DRACO_MESH_COMPRESSION:s[e]=new Nu(r,this.dracoLoader);break;case mu.KHR_TEXTURE_TRANSFORM:s[e]=new Ou;break;case mu.KHR_MESH_QUANTIZATION:s[e]=new zu;break;default:t.indexOf(e)>=0&&void 0===a[e]&&console.warn('THREE.GLTFLoader: Unknown extension "'+e+'".')}}l.setExtensions(s),l.setPlugins(a),l.parse(n,i)}parseAsync(e,t){const n=this;return new Promise(function(i,r){n.parse(e,t,i,r)})}}function fu(){let e={};return{get:function(t){return e[t]},add:function(t,n){e[t]=n},remove:function(t){delete e[t]},removeAll:function(){e={}}}}const mu={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",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class gu{constructor(e){this.parser=e,this.name=mu.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let n=0,i=t.length;n<i;n++){const i=t[n];i.extensions&&i.extensions[this.name]&&void 0!==i.extensions[this.name].light&&e._addNodeRef(this.cache,i.extensions[this.name].light)}}_loadLight(e){const t=this.parser,n="light:"+e;let i=t.cache.get(n);if(i)return i;const r=t.json,s=((r.extensions&&r.extensions[this.name]||{}).lights||[])[e];let a;const o=new $r(16777215);void 0!==s.color&&o.setRGB(s.color[0],s.color[1],s.color[2],wn);const l=void 0!==s.range?s.range:0;switch(s.type){case"directional":a=new Zo(o),a.target.position.set(0,0,-1),a.add(a.target);break;case"point":a=new Qo(o),a.distance=l;break;case"spot":a=new Xo(o),a.distance=l,s.spot=s.spot||{},s.spot.innerConeAngle=void 0!==s.spot.innerConeAngle?s.spot.innerConeAngle:0,s.spot.outerConeAngle=void 0!==s.spot.outerConeAngle?s.spot.outerConeAngle:Math.PI/4,a.angle=s.spot.outerConeAngle,a.penumbra=1-s.spot.innerConeAngle/s.spot.outerConeAngle,a.target.position.set(0,0,-1),a.add(a.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+s.type)}return a.position.set(0,0,0),id(a,s),void 0!==s.intensity&&(a.intensity=s.intensity),a.name=t.createUniqueName(s.name||"light_"+e),i=Promise.resolve(a),t.cache.add(n,i),i}getDependency(e,t){if("light"===e)return this._loadLight(t)}createNodeAttachment(e){const t=this,n=this.parser,i=n.json.nodes[e],r=(i.extensions&&i.extensions[this.name]||{}).light;return void 0===r?null:this._loadLight(r).then(function(e){return n._getNodeRef(t.cache,r,e)})}}class _u{constructor(){this.name=mu.KHR_MATERIALS_UNLIT}getMaterialType(){return is}extendParams(e,t,n){const i=[];e.color=new $r(1,1,1),e.opacity=1;const r=t.pbrMetallicRoughness;if(r){if(Array.isArray(r.baseColorFactor)){const t=r.baseColorFactor;e.color.setRGB(t[0],t[1],t[2],wn),e.opacity=t[3]}void 0!==r.baseColorTexture&&i.push(n.assignTexture(e,"map",r.baseColorTexture,Mn))}return Promise.all(i)}}class vu{constructor(e){this.parser=e,this.name=mu.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const n=this.parser.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const i=n.extensions[this.name].emissiveStrength;return void 0!==i&&(t.emissiveIntensity=i),Promise.resolve()}}class xu{constructor(e){this.parser=e,this.name=mu.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?lo:null}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const r=[],s=i.extensions[this.name];if(void 0!==s.clearcoatFactor&&(t.clearcoat=s.clearcoatFactor),void 0!==s.clearcoatTexture&&r.push(n.assignTexture(t,"clearcoatMap",s.clearcoatTexture)),void 0!==s.clearcoatRoughnessFactor&&(t.clearcoatRoughness=s.clearcoatRoughnessFactor),void 0!==s.clearcoatRoughnessTexture&&r.push(n.assignTexture(t,"clearcoatRoughnessMap",s.clearcoatRoughnessTexture)),void 0!==s.clearcoatNormalTexture&&(r.push(n.assignTexture(t,"clearcoatNormalMap",s.clearcoatNormalTexture)),void 0!==s.clearcoatNormalTexture.scale)){const e=s.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new li(e,e)}return Promise.all(r)}}class yu{constructor(e){this.parser=e,this.name=mu.KHR_MATERIALS_DISPERSION}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?lo:null}extendMaterialParams(e,t){const n=this.parser.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const i=n.extensions[this.name];return t.dispersion=void 0!==i.dispersion?i.dispersion:0,Promise.resolve()}}class Su{constructor(e){this.parser=e,this.name=mu.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?lo:null}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const r=[],s=i.extensions[this.name];return void 0!==s.iridescenceFactor&&(t.iridescence=s.iridescenceFactor),void 0!==s.iridescenceTexture&&r.push(n.assignTexture(t,"iridescenceMap",s.iridescenceTexture)),void 0!==s.iridescenceIor&&(t.iridescenceIOR=s.iridescenceIor),void 0===t.iridescenceThicknessRange&&(t.iridescenceThicknessRange=[100,400]),void 0!==s.iridescenceThicknessMinimum&&(t.iridescenceThicknessRange[0]=s.iridescenceThicknessMinimum),void 0!==s.iridescenceThicknessMaximum&&(t.iridescenceThicknessRange[1]=s.iridescenceThicknessMaximum),void 0!==s.iridescenceThicknessTexture&&r.push(n.assignTexture(t,"iridescenceThicknessMap",s.iridescenceThicknessTexture)),Promise.all(r)}}class Au{constructor(e){this.parser=e,this.name=mu.KHR_MATERIALS_SHEEN}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?lo:null}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const r=[];t.sheenColor=new $r(0,0,0),t.sheenRoughness=0,t.sheen=1;const s=i.extensions[this.name];if(void 0!==s.sheenColorFactor){const e=s.sheenColorFactor;t.sheenColor.setRGB(e[0],e[1],e[2],wn)}return void 0!==s.sheenRoughnessFactor&&(t.sheenRoughness=s.sheenRoughnessFactor),void 0!==s.sheenColorTexture&&r.push(n.assignTexture(t,"sheenColorMap",s.sheenColorTexture,Mn)),void 0!==s.sheenRoughnessTexture&&r.push(n.assignTexture(t,"sheenRoughnessMap",s.sheenRoughnessTexture)),Promise.all(r)}}class bu{constructor(e){this.parser=e,this.name=mu.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?lo:null}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const r=[],s=i.extensions[this.name];return void 0!==s.transmissionFactor&&(t.transmission=s.transmissionFactor),void 0!==s.transmissionTexture&&r.push(n.assignTexture(t,"transmissionMap",s.transmissionTexture)),Promise.all(r)}}class Mu{constructor(e){this.parser=e,this.name=mu.KHR_MATERIALS_VOLUME}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?lo:null}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const r=[],s=i.extensions[this.name];t.thickness=void 0!==s.thicknessFactor?s.thicknessFactor:0,void 0!==s.thicknessTexture&&r.push(n.assignTexture(t,"thicknessMap",s.thicknessTexture)),t.attenuationDistance=s.attenuationDistance||1/0;const a=s.attenuationColor||[1,1,1];return t.attenuationColor=(new $r).setRGB(a[0],a[1],a[2],wn),Promise.all(r)}}class wu{constructor(e){this.parser=e,this.name=mu.KHR_MATERIALS_IOR}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?lo:null}extendMaterialParams(e,t){const n=this.parser.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const i=n.extensions[this.name];return t.ior=void 0!==i.ior?i.ior:1.5,Promise.resolve()}}class Tu{constructor(e){this.parser=e,this.name=mu.KHR_MATERIALS_SPECULAR}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?lo:null}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const r=[],s=i.extensions[this.name];t.specularIntensity=void 0!==s.specularFactor?s.specularFactor:1,void 0!==s.specularTexture&&r.push(n.assignTexture(t,"specularIntensityMap",s.specularTexture));const a=s.specularColorFactor||[1,1,1];return t.specularColor=(new $r).setRGB(a[0],a[1],a[2],wn),void 0!==s.specularColorTexture&&r.push(n.assignTexture(t,"specularColorMap",s.specularColorTexture,Mn)),Promise.all(r)}}class Eu{constructor(e){this.parser=e,this.name=mu.EXT_MATERIALS_BUMP}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?lo:null}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const r=[],s=i.extensions[this.name];return t.bumpScale=void 0!==s.bumpFactor?s.bumpFactor:1,void 0!==s.bumpTexture&&r.push(n.assignTexture(t,"bumpMap",s.bumpTexture)),Promise.all(r)}}class Cu{constructor(e){this.parser=e,this.name=mu.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?lo:null}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const r=[],s=i.extensions[this.name];return void 0!==s.anisotropyStrength&&(t.anisotropy=s.anisotropyStrength),void 0!==s.anisotropyRotation&&(t.anisotropyRotation=s.anisotropyRotation),void 0!==s.anisotropyTexture&&r.push(n.assignTexture(t,"anisotropyMap",s.anisotropyTexture)),Promise.all(r)}}class Ru{constructor(e){this.parser=e,this.name=mu.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,n=t.json,i=n.textures[e];if(!i.extensions||!i.extensions[this.name])return null;const r=i.extensions[this.name],s=t.options.ktx2Loader;if(!s){if(n.extensionsRequired&&n.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,s)}}class Iu{constructor(e){this.parser=e,this.name=mu.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,n=this.parser,i=n.json,r=i.textures[e];if(!r.extensions||!r.extensions[t])return null;const s=r.extensions[t],a=i.images[s.source];let o=n.textureLoader;if(a.uri){const e=n.options.manager.getHandler(a.uri);null!==e&&(o=e)}return n.loadTextureImage(e,s.source,o)}}class Pu{constructor(e){this.parser=e,this.name=mu.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,n=this.parser,i=n.json,r=i.textures[e];if(!r.extensions||!r.extensions[t])return null;const s=r.extensions[t],a=i.images[s.source];let o=n.textureLoader;if(a.uri){const e=n.options.manager.getHandler(a.uri);null!==e&&(o=e)}return n.loadTextureImage(e,s.source,o)}}class Du{constructor(e){this.name=mu.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){const t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){const e=n.extensions[this.name],i=this.parser.getDependency("buffer",e.buffer),r=this.parser.options.meshoptDecoder;if(!r||!r.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 i.then(function(t){const n=e.byteOffset||0,i=e.byteLength||0,s=e.count,a=e.byteStride,o=new Uint8Array(t,n,i);return r.decodeGltfBufferAsync?r.decodeGltfBufferAsync(s,a,o,e.mode,e.filter).then(function(e){return e.buffer}):r.ready.then(function(){const t=new ArrayBuffer(s*a);return r.decodeGltfBuffer(new Uint8Array(t),s,a,o,e.mode,e.filter),t})})}return null}}class Bu{constructor(e){this.name=mu.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||void 0===n.mesh)return null;const i=t.meshes[n.mesh];for(const o of i.primitives)if(o.mode!==Wu.TRIANGLES&&o.mode!==Wu.TRIANGLE_STRIP&&o.mode!==Wu.TRIANGLE_FAN&&void 0!==o.mode)return null;const r=n.extensions[this.name].attributes,s=[],a={};for(const o in r)s.push(this.parser.getDependency("accessor",r[o]).then(e=>(a[o]=e,a[o])));return s.length<1?null:(s.push(this.parser.createNodeMesh(e)),Promise.all(s).then(e=>{const t=e.pop(),n=t.isGroup?t.children:[t],i=e[0].count,r=[];for(const s of n){const e=new or,t=new hi,n=new ci,o=new hi(1,1,1),l=new Ta(s.geometry,s.material,i);for(let r=0;r<i;r++)a.TRANSLATION&&t.fromBufferAttribute(a.TRANSLATION,r),a.ROTATION&&n.fromBufferAttribute(a.ROTATION,r),a.SCALE&&o.fromBufferAttribute(a.SCALE,r),l.setMatrixAt(r,e.compose(t,n,o));for(const i in a)if("_COLOR_0"===i){const e=a[i];l.instanceColor=new va(e.array,e.itemSize,e.normalized)}else"TRANSLATION"!==i&&"ROTATION"!==i&&"SCALE"!==i&&s.geometry.setAttribute(i,a[i]);Lr.prototype.copy.call(l,s),this.parser.assignFinalMaterial(l),r.push(l)}return t.isGroup?(t.clear(),t.add(...r),t):r[0]}))}}const Lu="glTF",Fu=1313821514,Uu=5130562;class ku{constructor(e){this.name=mu.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,12),n=new TextDecoder;if(this.header={magic:n.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==Lu)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const i=this.header.length-12,r=new DataView(e,12);let s=0;for(;s<i;){const t=r.getUint32(s,!0);s+=4;const i=r.getUint32(s,!0);if(s+=4,i===Fu){const i=new Uint8Array(e,12+s,t);this.content=n.decode(i)}else if(i===Uu){const n=12+s;this.body=e.slice(n,n+t)}s+=t}if(null===this.content)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class Nu{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=mu.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const n=this.json,i=this.dracoLoader,r=e.extensions[this.name].bufferView,s=e.extensions[this.name].attributes,a={},o={},l={};for(const c in s){const e=Ku[c]||c.toLowerCase();a[e]=s[c]}for(const c in e.attributes){const t=Ku[c]||c.toLowerCase();if(void 0!==s[c]){const i=n.accessors[e.attributes[c]],r=ju[i.componentType];l[t]=r.name,o[t]=!0===i.normalized}}return t.getDependency("bufferView",r).then(function(e){return new Promise(function(t,n){i.decodeDracoFile(e,function(e){for(const t in e.attributes){const n=e.attributes[t],i=o[t];void 0!==i&&(n.normalized=i)}t(e)},a,l,wn,n)})})}}class Ou{constructor(){this.name=mu.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return void 0!==t.texCoord&&t.texCoord!==e.channel||void 0!==t.offset||void 0!==t.rotation||void 0!==t.scale?(e=e.clone(),void 0!==t.texCoord&&(e.channel=t.texCoord),void 0!==t.offset&&e.offset.fromArray(t.offset),void 0!==t.rotation&&(e.rotation=t.rotation),void 0!==t.scale&&e.repeat.fromArray(t.scale),e.needsUpdate=!0,e):e}}class zu{constructor(){this.name=mu.KHR_MESH_QUANTIZATION}}class Hu extends go{constructor(e,t,n,i){super(e,t,n,i)}copySampleValue_(e){const t=this.resultBuffer,n=this.sampleValues,i=this.valueSize,r=e*i*3+i;for(let s=0;s!==i;s++)t[s]=n[r+s];return t}interpolate_(e,t,n,i){const r=this.resultBuffer,s=this.sampleValues,a=this.valueSize,o=2*a,l=3*a,c=i-t,h=(n-t)/c,u=h*h,d=u*h,p=e*l,f=p-l,m=-2*d+3*u,g=d-u,_=1-m,v=g-u+h;for(let x=0;x!==a;x++){const e=s[f+x+a],t=s[f+x+o]*c,n=s[p+x+a],i=s[p+x]*c;r[x]=_*e+v*t+m*n+g*i}return r}}const Vu=new ci;class Gu extends Hu{interpolate_(e,t,n,i){const r=super.interpolate_(e,t,n,i);return Vu.fromArray(r).normalize().toArray(r),r}}const Wu={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},ju={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},Xu={9728:rt,9729:ot,9984:1004,9985:lt,9986:at,9987:ct},qu={33071:nt,33648:it,10497:tt},Qu={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},Ku={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"},Yu={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},Zu={CUBICSPLINE:void 0,LINEAR:_n,STEP:gn},Ju="OPAQUE",$u="MASK",ed="BLEND";function td(e){return void 0===e.DefaultMaterial&&(e.DefaultMaterial=new oo({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:0})),e.DefaultMaterial}function nd(e,t,n){for(const i in n.extensions)void 0===e[i]&&(t.userData.gltfExtensions=t.userData.gltfExtensions||{},t.userData.gltfExtensions[i]=n.extensions[i])}function id(e,t){void 0!==t.extras&&("object"==typeof t.extras?Object.assign(e.userData,t.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+t.extras))}function rd(e,t){if(e.updateMorphTargets(),void 0!==t.weights)for(let n=0,i=t.weights.length;n<i;n++)e.morphTargetInfluences[n]=t.weights[n];if(t.extras&&Array.isArray(t.extras.targetNames)){const n=t.extras.targetNames;if(e.morphTargetInfluences.length===n.length){e.morphTargetDictionary={};for(let t=0,i=n.length;t<i;t++)e.morphTargetDictionary[n[t]]=t}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function sd(e){let t;const n=e.extensions&&e.extensions[mu.KHR_DRACO_MESH_COMPRESSION];if(t=n?"draco:"+n.bufferView+":"+n.indices+":"+ad(n.attributes):e.indices+":"+ad(e.attributes)+":"+e.mode,void 0!==e.targets)for(let i=0,r=e.targets.length;i<r;i++)t+=":"+ad(e.targets[i]);return t}function ad(e){let t="";const n=Object.keys(e).sort();for(let i=0,r=n.length;i<r;i++)t+=n[i]+":"+e[n[i]]+";";return t}function od(e){switch(e){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.")}}const ld=new or;class cd{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new fu,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 n=!1,i=-1,r=!1,s=-1;if("undefined"!=typeof navigator){const e=navigator.userAgent;n=!0===/^((?!chrome|android).)*safari/i.test(e);const t=e.match(/Version\/(\d+)/);i=n&&t?parseInt(t[1],10):-1,r=e.indexOf("Firefox")>-1,s=r?e.match(/Firefox\/([0-9]+)\./)[1]:-1}"undefined"==typeof createImageBitmap||n&&i<17||r&&s<98?this.textureLoader=new Oo(this.options.manager):this.textureLoader=new tl(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new Uo(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),"use-credentials"===this.options.crossOrigin&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const n=this,i=this.json,r=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(e){return e._markDefs&&e._markDefs()}),Promise.all(this._invokeAll(function(e){return e.beforeRoot&&e.beforeRoot()})).then(function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])}).then(function(t){const s={scene:t[0][i.scene||0],scenes:t[0],animations:t[1],cameras:t[2],asset:i.asset,parser:n,userData:{}};return nd(r,s,i),id(s,i),Promise.all(n._invokeAll(function(e){return e.afterRoot&&e.afterRoot(s)})).then(function(){for(const e of s.scenes)e.updateMatrixWorld();e(s)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let i=0,r=t.length;i<r;i++){const n=t[i].joints;for(let t=0,i=n.length;t<i;t++)e[n[t]].isBone=!0}for(let i=0,r=e.length;i<r;i++){const t=e[i];void 0!==t.mesh&&(this._addNodeRef(this.meshCache,t.mesh),void 0!==t.skin&&(n[t.mesh].isSkinnedMesh=!0)),void 0!==t.camera&&this._addNodeRef(this.cameraCache,t.camera)}}_addNodeRef(e,t){void 0!==t&&(void 0===e.refs[t]&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,n){if(e.refs[t]<=1)return n;const i=n.clone(),r=(e,t)=>{const n=this.associations.get(e);null!=n&&this.associations.set(t,n);for(const[i,s]of e.children.entries())r(s,t.children[i])};return r(n,i),i.name+="_instance_"+e.uses[t]++,i}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){const i=e(t[n]);if(i)return i}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const n=[];for(let i=0;i<t.length;i++){const r=e(t[i]);r&&n.push(r)}return n}getDependency(e,t){const n=e+":"+t;let i=this.cache.get(n);if(!i){switch(e){case"scene":i=this.loadScene(t);break;case"node":i=this._invokeOne(function(e){return e.loadNode&&e.loadNode(t)});break;case"mesh":i=this._invokeOne(function(e){return e.loadMesh&&e.loadMesh(t)});break;case"accessor":i=this.loadAccessor(t);break;case"bufferView":i=this._invokeOne(function(e){return e.loadBufferView&&e.loadBufferView(t)});break;case"buffer":i=this.loadBuffer(t);break;case"material":i=this._invokeOne(function(e){return e.loadMaterial&&e.loadMaterial(t)});break;case"texture":i=this._invokeOne(function(e){return e.loadTexture&&e.loadTexture(t)});break;case"skin":i=this.loadSkin(t);break;case"animation":i=this._invokeOne(function(e){return e.loadAnimation&&e.loadAnimation(t)});break;case"camera":i=this.loadCamera(t);break;default:if(i=this._invokeOne(function(n){return n!=this&&n.getDependency&&n.getDependency(e,t)}),!i)throw new Error("Unknown type: "+e)}this.cache.add(n,i)}return i}getDependencies(e){let t=this.cache.get(e);if(!t){const n=this,i=this.json[e+("mesh"===e?"es":"s")]||[];t=Promise.all(i.map(function(t,i){return n.getDependency(e,i)})),this.cache.add(e,t)}return t}loadBuffer(e){const t=this.json.buffers[e],n=this.fileLoader;if(t.type&&"arraybuffer"!==t.type)throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(void 0===t.uri&&0===e)return Promise.resolve(this.extensions[mu.KHR_BINARY_GLTF].body);const i=this.options;return new Promise(function(e,r){n.load(Jo.resolveURL(t.uri,i.path),e,void 0,function(){r(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(e){const n=t.byteLength||0,i=t.byteOffset||0;return e.slice(i,i+n)})}loadAccessor(e){const t=this,n=this.json,i=this.json.accessors[e];if(void 0===i.bufferView&&void 0===i.sparse){const e=Qu[i.type],t=ju[i.componentType],n=!0===i.normalized,r=new t(i.count*e);return Promise.resolve(new hs(r,e,n))}const r=[];return void 0!==i.bufferView?r.push(this.getDependency("bufferView",i.bufferView)):r.push(null),void 0!==i.sparse&&(r.push(this.getDependency("bufferView",i.sparse.indices.bufferView)),r.push(this.getDependency("bufferView",i.sparse.values.bufferView))),Promise.all(r).then(function(e){const r=e[0],s=Qu[i.type],a=ju[i.componentType],o=a.BYTES_PER_ELEMENT,l=o*s,c=i.byteOffset||0,h=void 0!==i.bufferView?n.bufferViews[i.bufferView].byteStride:void 0,u=!0===i.normalized;let d,p;if(h&&h!==l){const e=Math.floor(c/h),n="InterleavedBuffer:"+i.bufferView+":"+i.componentType+":"+e+":"+i.count;let l=t.cache.get(n);l||(d=new a(r,e*h,i.count*h/o),l=new ea(d,h/o),t.cache.add(n,l)),p=new na(l,s,c%h/o,u)}else d=null===r?new a(i.count*s):new a(r,c,i.count*s),p=new hs(d,s,u);if(void 0!==i.sparse){const t=Qu.SCALAR,n=ju[i.sparse.indices.componentType],o=i.sparse.indices.byteOffset||0,l=i.sparse.values.byteOffset||0,c=new n(e[1],o,i.sparse.count*t),h=new a(e[2],l,i.sparse.count*s);null!==r&&(p=new hs(p.array.slice(),p.itemSize,p.normalized)),p.normalized=!1;for(let e=0,i=c.length;e<i;e++){const t=c[e];if(p.setX(t,h[e*s]),s>=2&&p.setY(t,h[e*s+1]),s>=3&&p.setZ(t,h[e*s+2]),s>=4&&p.setW(t,h[e*s+3]),s>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}p.normalized=u}return p})}loadTexture(e){const t=this.json,n=this.options,i=t.textures[e].source,r=t.images[i];let s=this.textureLoader;if(r.uri){const e=n.manager.getHandler(r.uri);null!==e&&(s=e)}return this.loadTextureImage(e,i,s)}loadTextureImage(e,t,n){const i=this,r=this.json,s=r.textures[e],a=r.images[t],o=(a.uri||a.bufferView)+":"+s.sampler;if(this.textureCache[o])return this.textureCache[o];const l=this.loadImageSource(t,n).then(function(t){t.flipY=!1,t.name=s.name||a.name||"",""===t.name&&"string"==typeof a.uri&&!1===a.uri.startsWith("data:image/")&&(t.name=a.uri);const n=(r.samplers||{})[s.sampler]||{};return t.magFilter=Xu[n.magFilter]||ot,t.minFilter=Xu[n.minFilter]||ct,t.wrapS=qu[n.wrapS]||tt,t.wrapT=qu[n.wrapT]||tt,t.generateMipmaps=!t.isCompressedTexture&&t.minFilter!==rt&&t.minFilter!==ot,i.associations.set(t,{textures:e}),t}).catch(function(){return null});return this.textureCache[o]=l,l}loadImageSource(e,t){const n=this,i=this.json,r=this.options;if(void 0!==this.sourceCache[e])return this.sourceCache[e].then(e=>e.clone());const s=i.images[e],a=self.URL||self.webkitURL;let o=s.uri||"",l=!1;if(void 0!==s.bufferView)o=n.getDependency("bufferView",s.bufferView).then(function(e){l=!0;const t=new Blob([e],{type:s.mimeType});return o=a.createObjectURL(t),o});else if(void 0===s.uri)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const c=Promise.resolve(o).then(function(e){return new Promise(function(n,i){let s=n;!0===t.isImageBitmapLoader&&(s=function(e){const t=new Ci(e);t.needsUpdate=!0,n(t)}),t.load(Jo.resolveURL(e,r.path),s,void 0,i)})}).then(function(e){var t;return!0===l&&a.revokeObjectURL(o),id(e,s),e.userData.mimeType=s.mimeType||((t=s.uri).search(/\.jpe?g($|\?)/i)>0||0===t.search(/^data\:image\/jpeg/)?"image/jpeg":t.search(/\.webp($|\?)/i)>0||0===t.search(/^data\:image\/webp/)?"image/webp":t.search(/\.ktx2($|\?)/i)>0||0===t.search(/^data\:image\/ktx2/)?"image/ktx2":"image/png"),e}).catch(function(e){throw console.error("THREE.GLTFLoader: Couldn't load texture",o),e});return this.sourceCache[e]=c,c}assignTexture(e,t,n,i){const r=this;return this.getDependency("texture",n.index).then(function(s){if(!s)return null;if(void 0!==n.texCoord&&n.texCoord>0&&((s=s.clone()).channel=n.texCoord),r.extensions[mu.KHR_TEXTURE_TRANSFORM]){const e=void 0!==n.extensions?n.extensions[mu.KHR_TEXTURE_TRANSFORM]:void 0;if(e){const t=r.associations.get(s);s=r.extensions[mu.KHR_TEXTURE_TRANSFORM].extendTexture(s,e),r.associations.set(s,t)}}return void 0!==i&&(s.colorSpace=i),e[t]=s,s})}assignFinalMaterial(e){const t=e.geometry;let n=e.material;const i=void 0===t.attributes.tangent,r=void 0!==t.attributes.color,s=void 0===t.attributes.normal;if(e.isPoints){const e="PointsMaterial:"+n.uuid;let t=this.cache.get(e);t||(t=new Ka,ns.prototype.copy.call(t,n),t.color.copy(n.color),t.map=n.map,t.sizeAttenuation=!1,this.cache.add(e,t)),n=t}else if(e.isLine){const e="LineBasicMaterial:"+n.uuid;let t=this.cache.get(e);t||(t=new Fa,ns.prototype.copy.call(t,n),t.color.copy(n.color),t.map=n.map,this.cache.add(e,t)),n=t}if(i||r||s){let e="ClonedMaterial:"+n.uuid+":";i&&(e+="derivative-tangents:"),r&&(e+="vertex-colors:"),s&&(e+="flat-shading:");let t=this.cache.get(e);t||(t=n.clone(),r&&(t.vertexColors=!0),s&&(t.flatShading=!0),i&&(t.normalScale&&(t.normalScale.y*=-1),t.clearcoatNormalScale&&(t.clearcoatNormalScale.y*=-1)),this.cache.add(e,t),this.associations.set(t,this.associations.get(n))),n=t}e.material=n}getMaterialType(){return oo}loadMaterial(e){const t=this,n=this.json,i=this.extensions,r=n.materials[e];let s;const a={},o=[];if((r.extensions||{})[mu.KHR_MATERIALS_UNLIT]){const e=i[mu.KHR_MATERIALS_UNLIT];s=e.getMaterialType(),o.push(e.extendParams(a,r,t))}else{const n=r.pbrMetallicRoughness||{};if(a.color=new $r(1,1,1),a.opacity=1,Array.isArray(n.baseColorFactor)){const e=n.baseColorFactor;a.color.setRGB(e[0],e[1],e[2],wn),a.opacity=e[3]}void 0!==n.baseColorTexture&&o.push(t.assignTexture(a,"map",n.baseColorTexture,Mn)),a.metalness=void 0!==n.metallicFactor?n.metallicFactor:1,a.roughness=void 0!==n.roughnessFactor?n.roughnessFactor:1,void 0!==n.metallicRoughnessTexture&&(o.push(t.assignTexture(a,"metalnessMap",n.metallicRoughnessTexture)),o.push(t.assignTexture(a,"roughnessMap",n.metallicRoughnessTexture))),s=this._invokeOne(function(t){return t.getMaterialType&&t.getMaterialType(e)}),o.push(Promise.all(this._invokeAll(function(t){return t.extendMaterialParams&&t.extendMaterialParams(e,a)})))}!0===r.doubleSided&&(a.side=2);const l=r.alphaMode||Ju;if(l===ed?(a.transparent=!0,a.depthWrite=!1):(a.transparent=!1,l===$u&&(a.alphaTest=void 0!==r.alphaCutoff?r.alphaCutoff:.5)),void 0!==r.normalTexture&&s!==is&&(o.push(t.assignTexture(a,"normalMap",r.normalTexture)),a.normalScale=new li(1,1),void 0!==r.normalTexture.scale)){const e=r.normalTexture.scale;a.normalScale.set(e,e)}if(void 0!==r.occlusionTexture&&s!==is&&(o.push(t.assignTexture(a,"aoMap",r.occlusionTexture)),void 0!==r.occlusionTexture.strength&&(a.aoMapIntensity=r.occlusionTexture.strength)),void 0!==r.emissiveFactor&&s!==is){const e=r.emissiveFactor;a.emissive=(new $r).setRGB(e[0],e[1],e[2],wn)}return void 0!==r.emissiveTexture&&s!==is&&o.push(t.assignTexture(a,"emissiveMap",r.emissiveTexture,Mn)),Promise.all(o).then(function(){const n=new s(a);return r.name&&(n.name=r.name),id(n,r),t.associations.set(n,{materials:e}),r.extensions&&nd(i,n,r),n})}createUniqueName(e){const t=ul.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,n=this.extensions,i=this.primitiveCache;function r(e){return n[mu.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(e,t).then(function(n){return hd(n,e,t)})}const s=[];for(let a=0,o=e.length;a<o;a++){const n=e[a],o=sd(n),l=i[o];if(l)s.push(l.promise);else{let e;e=n.extensions&&n.extensions[mu.KHR_DRACO_MESH_COMPRESSION]?r(n):hd(new Ss,n,t),i[o]={primitive:n,promise:e},s.push(e)}}return Promise.all(s)}loadMesh(e){const t=this,n=this.json,i=this.extensions,r=n.meshes[e],s=r.primitives,a=[];for(let o=0,l=s.length;o<l;o++){const e=void 0===s[o].material?td(this.cache):this.getDependency("material",s[o].material);a.push(e)}return a.push(t.loadGeometries(s)),Promise.all(a).then(function(n){const a=n.slice(0,n.length-1),o=n[n.length-1],l=[];for(let h=0,u=o.length;h<u;h++){const n=o[h],c=s[h];let u;const d=a[h];if(c.mode===Wu.TRIANGLES||c.mode===Wu.TRIANGLE_STRIP||c.mode===Wu.TRIANGLE_FAN||void 0===c.mode)u=!0===r.isSkinnedMesh?new da(n,d):new Bs(n,d),!0===u.isSkinnedMesh&&u.normalizeSkinWeights(),c.mode===Wu.TRIANGLE_STRIP?u.geometry=du(u.geometry,1):c.mode===Wu.TRIANGLE_FAN&&(u.geometry=du(u.geometry,2));else if(c.mode===Wu.LINES)u=new qa(n,d);else if(c.mode===Wu.LINE_STRIP)u=new Ga(n,d);else if(c.mode===Wu.LINE_LOOP)u=new Qa(n,d);else{if(c.mode!==Wu.POINTS)throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+c.mode);u=new eo(n,d)}Object.keys(u.geometry.morphAttributes).length>0&&rd(u,r),u.name=t.createUniqueName(r.name||"mesh_"+e),id(u,r),c.extensions&&nd(i,u,c),t.assignFinalMaterial(u),l.push(u)}for(let i=0,r=l.length;i<r;i++)t.associations.set(l[i],{meshes:e,primitives:i});if(1===l.length)return r.extensions&&nd(i,l[0],r),l[0];const c=new Ys;r.extensions&&nd(i,c,r),t.associations.set(c,{meshes:e});for(let e=0,t=l.length;e<t;e++)c.add(l[e]);return c})}loadCamera(e){let t;const n=this.json.cameras[e],i=n[n.type];if(i)return"perspective"===n.type?t=new js(oi.radToDeg(i.yfov),i.aspectRatio||1,i.znear||1,i.zfar||2e6):"orthographic"===n.type&&(t=new Ko(-i.xmag,i.xmag,i.ymag,-i.ymag,i.znear,i.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),id(t,n),Promise.resolve(t);console.warn("THREE.GLTFLoader: Missing camera parameters.")}loadSkin(e){const t=this.json.skins[e],n=[];for(let i=0,r=t.joints.length;i<r;i++)n.push(this._loadNodeShallow(t.joints[i]));return void 0!==t.inverseBindMatrices?n.push(this.getDependency("accessor",t.inverseBindMatrices)):n.push(null),Promise.all(n).then(function(e){const n=e.pop(),i=e,r=[],s=[];for(let a=0,o=i.length;a<o;a++){const e=i[a];if(e){r.push(e);const t=new or;null!==n&&t.fromArray(n.array,16*a),s.push(t)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[a])}return new _a(r,s)})}loadAnimation(e){const t=this.json,n=this,i=t.animations[e],r=i.name?i.name:"animation_"+e,s=[],a=[],o=[],l=[],c=[];for(let h=0,u=i.channels.length;h<u;h++){const e=i.channels[h],t=i.samplers[e.sampler],n=e.target,r=n.node,u=void 0!==i.parameters?i.parameters[t.input]:t.input,d=void 0!==i.parameters?i.parameters[t.output]:t.output;void 0!==n.node&&(s.push(this.getDependency("node",r)),a.push(this.getDependency("accessor",u)),o.push(this.getDependency("accessor",d)),l.push(t),c.push(n))}return Promise.all([Promise.all(s),Promise.all(a),Promise.all(o),Promise.all(l),Promise.all(c)]).then(function(e){const t=e[0],s=e[1],a=e[2],o=e[3],l=e[4],c=[];for(let i=0,r=t.length;i<r;i++){const e=t[i],r=s[i],h=a[i],u=o[i],d=l[i];if(void 0===e)continue;e.updateMatrix&&e.updateMatrix();const p=n._createAnimationTracks(e,r,h,u,d);if(p)for(let t=0;t<p.length;t++)c.push(p[t])}const h=new Co(r,void 0,c);return id(h,i),h})}createNodeMesh(e){const t=this.json,n=this,i=t.nodes[e];return void 0===i.mesh?null:n.getDependency("mesh",i.mesh).then(function(e){const t=n._getNodeRef(n.meshCache,i.mesh,e);return void 0!==i.weights&&t.traverse(function(e){if(e.isMesh)for(let t=0,n=i.weights.length;t<n;t++)e.morphTargetInfluences[t]=i.weights[t]}),t})}loadNode(e){const t=this,n=this.json.nodes[e],i=t._loadNodeShallow(e),r=[],s=n.children||[];for(let o=0,l=s.length;o<l;o++)r.push(t.getDependency("node",s[o]));const a=void 0===n.skin?Promise.resolve(null):t.getDependency("skin",n.skin);return Promise.all([i,Promise.all(r),a]).then(function(e){const t=e[0],n=e[1],i=e[2];null!==i&&t.traverse(function(e){e.isSkinnedMesh&&e.bind(i,ld)});for(let r=0,s=n.length;r<s;r++)t.add(n[r]);return t})}_loadNodeShallow(e){const t=this.json,n=this.extensions,i=this;if(void 0!==this.nodeCache[e])return this.nodeCache[e];const r=t.nodes[e],s=r.name?i.createUniqueName(r.name):"",a=[],o=i._invokeOne(function(t){return t.createNodeMesh&&t.createNodeMesh(e)});return o&&a.push(o),void 0!==r.camera&&a.push(i.getDependency("camera",r.camera).then(function(e){return i._getNodeRef(i.cameraCache,r.camera,e)})),i._invokeAll(function(t){return t.createNodeAttachment&&t.createNodeAttachment(e)}).forEach(function(e){a.push(e)}),this.nodeCache[e]=Promise.all(a).then(function(t){let a;if(a=!0===r.isBone?new pa:t.length>1?new Ys:1===t.length?t[0]:new Lr,a!==t[0])for(let e=0,n=t.length;e<n;e++)a.add(t[e]);if(r.name&&(a.userData.name=r.name,a.name=s),id(a,r),r.extensions&&nd(n,a,r),void 0!==r.matrix){const e=new or;e.fromArray(r.matrix),a.applyMatrix4(e)}else void 0!==r.translation&&a.position.fromArray(r.translation),void 0!==r.rotation&&a.quaternion.fromArray(r.rotation),void 0!==r.scale&&a.scale.fromArray(r.scale);if(i.associations.has(a)){if(void 0!==r.mesh&&i.meshCache.refs[r.mesh]>1){const e=i.associations.get(a);i.associations.set(a,{...e})}}else i.associations.set(a,{});return i.associations.get(a).nodes=e,a}),this.nodeCache[e]}loadScene(e){const t=this.extensions,n=this.json.scenes[e],i=this,r=new Ys;n.name&&(r.name=i.createUniqueName(n.name)),id(r,n),n.extensions&&nd(t,r,n);const s=n.nodes||[],a=[];for(let o=0,l=s.length;o<l;o++)a.push(i.getDependency("node",s[o]));return Promise.all(a).then(function(e){for(let t=0,n=e.length;t<n;t++)r.add(e[t]);return i.associations=(e=>{const t=new Map;for(const[n,r]of i.associations)(n instanceof ns||n instanceof Ci)&&t.set(n,r);return e.traverse(e=>{const n=i.associations.get(e);null!=n&&t.set(e,n)}),t})(r),r})}_createAnimationTracks(e,t,n,i,r){const s=[],a=e.name?e.name:e.uuid,o=[];let l;switch(Yu[r.path]===Yu.weights?e.traverse(function(e){e.morphTargetInfluences&&o.push(e.name?e.name:e.uuid)}):o.push(a),Yu[r.path]){case Yu.weights:l=bo;break;case Yu.rotation:l=wo;break;case Yu.translation:case Yu.scale:l=Eo;break;default:if(1===n.itemSize)l=bo;else l=Eo}const c=void 0!==i.interpolation?Zu[i.interpolation]:_n,h=this._getArrayFromAccessor(n);for(let u=0,d=o.length;u<d;u++){const e=new l(o[u]+"."+Yu[r.path],t.array,h,c);"CUBICSPLINE"===i.interpolation&&this._createCubicSplineTrackInterpolant(e),s.push(e)}return s}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const e=od(t.constructor),n=new Float32Array(t.length);for(let i=0,r=t.length;i<r;i++)n[i]=t[i]*e;t=n}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(e){return new(this instanceof wo?Gu:Hu)(this.times,this.values,this.getValueSize()/3,e)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function hd(e,t,n){const i=t.attributes,r=[];function s(t,i){return n.getDependency("accessor",t).then(function(t){e.setAttribute(i,t)})}for(const a in i){const t=Ku[a]||a.toLowerCase();t in e.attributes||r.push(s(i[a],t))}if(void 0!==t.indices&&!e.index){const i=n.getDependency("accessor",t.indices).then(function(t){e.setIndex(t)});r.push(i)}return vi.workingColorSpace!==wn&&"COLOR_0"in i&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${vi.workingColorSpace}" not supported.`),id(e,t),function(e,t,n){const i=t.attributes,r=new Li;if(void 0===i.POSITION)return;{const e=n.json.accessors[i.POSITION],t=e.min,s=e.max;if(void 0===t||void 0===s)return void console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");if(r.set(new hi(t[0],t[1],t[2]),new hi(s[0],s[1],s[2])),e.normalized){const t=od(ju[e.componentType]);r.min.multiplyScalar(t),r.max.multiplyScalar(t)}}const s=t.targets;if(void 0!==s){const e=new hi,t=new hi;for(let i=0,r=s.length;i<r;i++){const r=s[i];if(void 0!==r.POSITION){const i=n.json.accessors[r.POSITION],s=i.min,a=i.max;if(void 0!==s&&void 0!==a){if(t.setX(Math.max(Math.abs(s[0]),Math.abs(a[0]))),t.setY(Math.max(Math.abs(s[1]),Math.abs(a[1]))),t.setZ(Math.max(Math.abs(s[2]),Math.abs(a[2]))),i.normalized){const e=od(ju[i.componentType]);t.multiplyScalar(e)}e.max(t)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}r.expandByVector(e)}e.boundingBox=r;const a=new Ji;r.getCenter(a.center),a.radius=r.min.distanceTo(r.max)/2,e.boundingSphere=a}(e,t,n),Promise.all(r).then(function(){return void 0!==t.targets?function(e,t,n){let i=!1,r=!1,s=!1;for(let c=0,h=t.length;c<h;c++){const e=t[c];if(void 0!==e.POSITION&&(i=!0),void 0!==e.NORMAL&&(r=!0),void 0!==e.COLOR_0&&(s=!0),i&&r&&s)break}if(!i&&!r&&!s)return Promise.resolve(e);const a=[],o=[],l=[];for(let c=0,h=t.length;c<h;c++){const h=t[c];if(i){const t=void 0!==h.POSITION?n.getDependency("accessor",h.POSITION):e.attributes.position;a.push(t)}if(r){const t=void 0!==h.NORMAL?n.getDependency("accessor",h.NORMAL):e.attributes.normal;o.push(t)}if(s){const t=void 0!==h.COLOR_0?n.getDependency("accessor",h.COLOR_0):e.attributes.color;l.push(t)}}return Promise.all([Promise.all(a),Promise.all(o),Promise.all(l)]).then(function(t){const n=t[0],a=t[1],o=t[2];return i&&(e.morphAttributes.position=n),r&&(e.morphAttributes.normal=a),s&&(e.morphAttributes.color=o),e.morphTargetsRelative=!0,e})}(e,t.targets,n):e})}var ud="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function dd(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function pd(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var fd={exports:{}};fd.exports=function e(t,n,i){function r(a,o){if(!n[a]){if(!t[a]){if(!o&&pd)return pd(a);if(s)return s(a,!0);var l=new Error("Cannot find module '"+a+"'");throw l.code="MODULE_NOT_FOUND",l}var c=n[a]={exports:{}};t[a][0].call(c.exports,function(e){return r(t[a][1][e]||e)},c,c.exports,e,t,n,i)}return n[a].exports}for(var s=pd,a=0;a<i.length;a++)r(i[a]);return r}({1:[function(e,t,n){var i=e("./utils"),r=e("./support"),s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";n.encode=function(e){for(var t,n,r,a,o,l,c,h=[],u=0,d=e.length,p=d,f="string"!==i.getTypeOf(e);u<e.length;)p=d-u,r=f?(t=e[u++],n=u<d?e[u++]:0,u<d?e[u++]:0):(t=e.charCodeAt(u++),n=u<d?e.charCodeAt(u++):0,u<d?e.charCodeAt(u++):0),a=t>>2,o=(3&t)<<4|n>>4,l=1<p?(15&n)<<2|r>>6:64,c=2<p?63&r:64,h.push(s.charAt(a)+s.charAt(o)+s.charAt(l)+s.charAt(c));return h.join("")},n.decode=function(e){var t,n,i,a,o,l,c=0,h=0,u="data:";if(e.substr(0,u.length)===u)throw new Error("Invalid base64 input, it looks like a data url.");var d,p=3*(e=e.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(e.charAt(e.length-1)===s.charAt(64)&&p--,e.charAt(e.length-2)===s.charAt(64)&&p--,p%1!=0)throw new Error("Invalid base64 input, bad content length.");for(d=r.uint8array?new Uint8Array(0|p):new Array(0|p);c<e.length;)t=s.indexOf(e.charAt(c++))<<2|(a=s.indexOf(e.charAt(c++)))>>4,n=(15&a)<<4|(o=s.indexOf(e.charAt(c++)))>>2,i=(3&o)<<6|(l=s.indexOf(e.charAt(c++))),d[h++]=t,64!==o&&(d[h++]=n),64!==l&&(d[h++]=i);return d}},{"./support":30,"./utils":32}],2:[function(e,t,n){var i=e("./external"),r=e("./stream/DataWorker"),s=e("./stream/Crc32Probe"),a=e("./stream/DataLengthProbe");function o(e,t,n,i,r){this.compressedSize=e,this.uncompressedSize=t,this.crc32=n,this.compression=i,this.compressedContent=r}o.prototype={getContentWorker:function(){var e=new r(i.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new a("data_length")),t=this;return e.on("end",function(){if(this.streamInfo.data_length!==t.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),e},getCompressedWorker:function(){return new r(i.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},o.createWorkerFrom=function(e,t,n){return e.pipe(new s).pipe(new a("uncompressedSize")).pipe(t.compressWorker(n)).pipe(new a("compressedSize")).withStreamInfo("compression",t)},t.exports=o},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(e,t,n){var i=e("./stream/GenericWorker");n.STORE={magic:"\0\0",compressWorker:function(){return new i("STORE compression")},uncompressWorker:function(){return new i("STORE decompression")}},n.DEFLATE=e("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(e,t,n){var i=e("./utils"),r=function(){for(var e,t=[],n=0;n<256;n++){e=n;for(var i=0;i<8;i++)e=1&e?3988292384^e>>>1:e>>>1;t[n]=e}return t}();t.exports=function(e,t){return void 0!==e&&e.length?"string"!==i.getTypeOf(e)?function(e,t,n,i){var s=r,a=i+n;e^=-1;for(var o=i;o<a;o++)e=e>>>8^s[255&(e^t[o])];return-1^e}(0|t,e,e.length,0):function(e,t,n,i){var s=r,a=i+n;e^=-1;for(var o=i;o<a;o++)e=e>>>8^s[255&(e^t.charCodeAt(o))];return-1^e}(0|t,e,e.length,0):0}},{"./utils":32}],5:[function(e,t,n){n.base64=!1,n.binary=!1,n.dir=!1,n.createFolders=!0,n.date=null,n.compression=null,n.compressionOptions=null,n.comment=null,n.unixPermissions=null,n.dosPermissions=null},{}],6:[function(e,t,n){var i=null;i="undefined"!=typeof Promise?Promise:e("lie"),t.exports={Promise:i}},{lie:37}],7:[function(e,t,n){var i="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Uint32Array,r=e("pako"),s=e("./utils"),a=e("./stream/GenericWorker"),o=i?"uint8array":"array";function l(e,t){a.call(this,"FlateWorker/"+e),this._pako=null,this._pakoAction=e,this._pakoOptions=t,this.meta={}}n.magic="\b\0",s.inherits(l,a),l.prototype.processChunk=function(e){this.meta=e.meta,null===this._pako&&this._createPako(),this._pako.push(s.transformTo(o,e.data),!1)},l.prototype.flush=function(){a.prototype.flush.call(this),null===this._pako&&this._createPako(),this._pako.push([],!0)},l.prototype.cleanUp=function(){a.prototype.cleanUp.call(this),this._pako=null},l.prototype._createPako=function(){this._pako=new r[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var e=this;this._pako.onData=function(t){e.push({data:t,meta:e.meta})}},n.compressWorker=function(e){return new l("Deflate",e)},n.uncompressWorker=function(){return new l("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(e,t,n){function i(e,t){var n,i="";for(n=0;n<t;n++)i+=String.fromCharCode(255&e),e>>>=8;return i}function r(e,t,n,r,a,h){var u,d,p=e.file,f=e.compression,m=h!==o.utf8encode,g=s.transformTo("string",h(p.name)),_=s.transformTo("string",o.utf8encode(p.name)),v=p.comment,x=s.transformTo("string",h(v)),y=s.transformTo("string",o.utf8encode(v)),S=_.length!==p.name.length,A=y.length!==v.length,b="",M="",w="",T=p.dir,E=p.date,C={crc32:0,compressedSize:0,uncompressedSize:0};t&&!n||(C.crc32=e.crc32,C.compressedSize=e.compressedSize,C.uncompressedSize=e.uncompressedSize);var R=0;t&&(R|=8),m||!S&&!A||(R|=2048);var I,P,D,B=0,L=0;T&&(B|=16),"UNIX"===a?(L=798,B|=(I=p.unixPermissions,P=T,D=I,I||(D=P?16893:33204),(65535&D)<<16)):(L=20,B|=function(e){return 63&(e||0)}(p.dosPermissions)),u=E.getUTCHours(),u<<=6,u|=E.getUTCMinutes(),u<<=5,u|=E.getUTCSeconds()/2,d=E.getUTCFullYear()-1980,d<<=4,d|=E.getUTCMonth()+1,d<<=5,d|=E.getUTCDate(),S&&(M=i(1,1)+i(l(g),4)+_,b+="up"+i(M.length,2)+M),A&&(w=i(1,1)+i(l(x),4)+y,b+="uc"+i(w.length,2)+w);var F="";return F+="\n\0",F+=i(R,2),F+=f.magic,F+=i(u,2),F+=i(d,2),F+=i(C.crc32,4),F+=i(C.compressedSize,4),F+=i(C.uncompressedSize,4),F+=i(g.length,2),F+=i(b.length,2),{fileRecord:c.LOCAL_FILE_HEADER+F+g+b,dirRecord:c.CENTRAL_FILE_HEADER+i(L,2)+F+i(x.length,2)+"\0\0\0\0"+i(B,4)+i(r,4)+g+b+x}}var s=e("../utils"),a=e("../stream/GenericWorker"),o=e("../utf8"),l=e("../crc32"),c=e("../signature");function h(e,t,n,i){a.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=t,this.zipPlatform=n,this.encodeFileName=i,this.streamFiles=e,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}s.inherits(h,a),h.prototype.push=function(e){var t=e.meta.percent||0,n=this.entriesCount,i=this._sources.length;this.accumulate?this.contentBuffer.push(e):(this.bytesWritten+=e.data.length,a.prototype.push.call(this,{data:e.data,meta:{currentFile:this.currentFile,percent:n?(t+100*(n-i-1))/n:100}}))},h.prototype.openedSource=function(e){this.currentSourceOffset=this.bytesWritten,this.currentFile=e.file.name;var t=this.streamFiles&&!e.file.dir;if(t){var n=r(e,t,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:n.fileRecord,meta:{percent:0}})}else this.accumulate=!0},h.prototype.closedSource=function(e){this.accumulate=!1;var t,n=this.streamFiles&&!e.file.dir,s=r(e,n,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(s.dirRecord),n)this.push({data:(t=e,c.DATA_DESCRIPTOR+i(t.crc32,4)+i(t.compressedSize,4)+i(t.uncompressedSize,4)),meta:{percent:100}});else for(this.push({data:s.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},h.prototype.flush=function(){for(var e=this.bytesWritten,t=0;t<this.dirRecords.length;t++)this.push({data:this.dirRecords[t],meta:{percent:100}});var n,r,a,o,l,h,u=this.bytesWritten-e,d=(n=this.dirRecords.length,r=u,a=e,o=this.zipComment,l=this.encodeFileName,h=s.transformTo("string",l(o)),c.CENTRAL_DIRECTORY_END+"\0\0\0\0"+i(n,2)+i(n,2)+i(r,4)+i(a,4)+i(h.length,2)+h);this.push({data:d,meta:{percent:100}})},h.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},h.prototype.registerPrevious=function(e){this._sources.push(e);var t=this;return e.on("data",function(e){t.processChunk(e)}),e.on("end",function(){t.closedSource(t.previous.streamInfo),t._sources.length?t.prepareNextSource():t.end()}),e.on("error",function(e){t.error(e)}),this},h.prototype.resume=function(){return!!a.prototype.resume.call(this)&&(!this.previous&&this._sources.length?(this.prepareNextSource(),!0):this.previous||this._sources.length||this.generatedError?void 0:(this.end(),!0))},h.prototype.error=function(e){var t=this._sources;if(!a.prototype.error.call(this,e))return!1;for(var n=0;n<t.length;n++)try{t[n].error(e)}catch(i){}return!0},h.prototype.lock=function(){a.prototype.lock.call(this);for(var e=this._sources,t=0;t<e.length;t++)e[t].lock()},t.exports=h},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(e,t,n){var i=e("../compressions"),r=e("./ZipFileWorker");n.generateWorker=function(e,t,n){var s=new r(t.streamFiles,n,t.platform,t.encodeFileName),a=0;try{e.forEach(function(e,n){a++;var r=function(e,t){var n=e||t,r=i[n];if(!r)throw new Error(n+" is not a valid compression method !");return r}(n.options.compression,t.compression),o=n.options.compressionOptions||t.compressionOptions||{},l=n.dir,c=n.date;n._compressWorker(r,o).withStreamInfo("file",{name:e,dir:l,date:c,comment:n.comment||"",unixPermissions:n.unixPermissions,dosPermissions:n.dosPermissions}).pipe(s)}),s.entriesCount=a}catch(o){s.error(o)}return s}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(e,t,n){function i(){if(!(this instanceof i))return new i;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");this.files=Object.create(null),this.comment=null,this.root="",this.clone=function(){var e=new i;for(var t in this)"function"!=typeof this[t]&&(e[t]=this[t]);return e}}(i.prototype=e("./object")).loadAsync=e("./load"),i.support=e("./support"),i.defaults=e("./defaults"),i.version="3.10.1",i.loadAsync=function(e,t){return(new i).loadAsync(e,t)},i.external=e("./external"),t.exports=i},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(e,t,n){var i=e("./utils"),r=e("./external"),s=e("./utf8"),a=e("./zipEntries"),o=e("./stream/Crc32Probe"),l=e("./nodejsUtils");function c(e){return new r.Promise(function(t,n){var i=e.decompressed.getContentWorker().pipe(new o);i.on("error",function(e){n(e)}).on("end",function(){i.streamInfo.crc32!==e.decompressed.crc32?n(new Error("Corrupted zip : CRC32 mismatch")):t()}).resume()})}t.exports=function(e,t){var n=this;return t=i.extend(t||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:s.utf8decode}),l.isNode&&l.isStream(e)?r.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):i.prepareContent("the loaded zip file",e,!0,t.optimizedBinaryString,t.base64).then(function(e){var n=new a(t);return n.load(e),n}).then(function(e){var n=[r.Promise.resolve(e)],i=e.files;if(t.checkCRC32)for(var s=0;s<i.length;s++)n.push(c(i[s]));return r.Promise.all(n)}).then(function(e){for(var r=e.shift(),s=r.files,a=0;a<s.length;a++){var o=s[a],l=o.fileNameStr,c=i.resolve(o.fileNameStr);n.file(c,o.decompressed,{binary:!0,optimizedBinaryString:!0,date:o.date,dir:o.dir,comment:o.fileCommentStr.length?o.fileCommentStr:null,unixPermissions:o.unixPermissions,dosPermissions:o.dosPermissions,createFolders:t.createFolders}),o.dir||(n.file(c).unsafeOriginalName=l)}return r.zipComment.length&&(n.comment=r.zipComment),n})}},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(e,t,n){var i=e("../utils"),r=e("../stream/GenericWorker");function s(e,t){r.call(this,"Nodejs stream input adapter for "+e),this._upstreamEnded=!1,this._bindStream(t)}i.inherits(s,r),s.prototype._bindStream=function(e){var t=this;(this._stream=e).pause(),e.on("data",function(e){t.push({data:e,meta:{percent:0}})}).on("error",function(e){t.isPaused?this.generatedError=e:t.error(e)}).on("end",function(){t.isPaused?t._upstreamEnded=!0:t.end()})},s.prototype.pause=function(){return!!r.prototype.pause.call(this)&&(this._stream.pause(),!0)},s.prototype.resume=function(){return!!r.prototype.resume.call(this)&&(this._upstreamEnded?this.end():this._stream.resume(),!0)},t.exports=s},{"../stream/GenericWorker":28,"../utils":32}],13:[function(e,t,n){var i=e("readable-stream").Readable;function r(e,t,n){i.call(this,t),this._helper=e;var r=this;e.on("data",function(e,t){r.push(e)||r._helper.pause(),n&&n(t)}).on("error",function(e){r.emit("error",e)}).on("end",function(){r.push(null)})}e("../utils").inherits(r,i),r.prototype._read=function(){this._helper.resume()},t.exports=r},{"../utils":32,"readable-stream":16}],14:[function(e,t,n){t.exports={isNode:"undefined"!=typeof Buffer,newBufferFrom:function(e,t){if(Buffer.from&&Buffer.from!==Uint8Array.from)return Buffer.from(e,t);if("number"==typeof e)throw new Error('The "data" argument must not be a number');return new Buffer(e,t)},allocBuffer:function(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);return t.fill(0),t},isBuffer:function(e){return Buffer.isBuffer(e)},isStream:function(e){return e&&"function"==typeof e.on&&"function"==typeof e.pause&&"function"==typeof e.resume}}},{}],15:[function(e,t,n){function i(e,t,n){var i,r=s.getTypeOf(t),o=s.extend(n||{},l);o.date=o.date||new Date,null!==o.compression&&(o.compression=o.compression.toUpperCase()),"string"==typeof o.unixPermissions&&(o.unixPermissions=parseInt(o.unixPermissions,8)),o.unixPermissions&&16384&o.unixPermissions&&(o.dir=!0),o.dosPermissions&&16&o.dosPermissions&&(o.dir=!0),o.dir&&(e=m(e)),o.createFolders&&(i=f(e))&&g.call(this,i,!0);var u="string"===r&&!1===o.binary&&!1===o.base64;n&&void 0!==n.binary||(o.binary=!u),(t instanceof c&&0===t.uncompressedSize||o.dir||!t||0===t.length)&&(o.base64=!1,o.binary=!0,t="",o.compression="STORE",r="string");var _=null;_=t instanceof c||t instanceof a?t:d.isNode&&d.isStream(t)?new p(e,t):s.prepareContent(e,t,o.binary,o.optimizedBinaryString,o.base64);var v=new h(e,_,o);this.files[e]=v}var r=e("./utf8"),s=e("./utils"),a=e("./stream/GenericWorker"),o=e("./stream/StreamHelper"),l=e("./defaults"),c=e("./compressedObject"),h=e("./zipObject"),u=e("./generate"),d=e("./nodejsUtils"),p=e("./nodejs/NodejsStreamInputAdapter"),f=function(e){"/"===e.slice(-1)&&(e=e.substring(0,e.length-1));var t=e.lastIndexOf("/");return 0<t?e.substring(0,t):""},m=function(e){return"/"!==e.slice(-1)&&(e+="/"),e},g=function(e,t){return t=void 0!==t?t:l.createFolders,e=m(e),this.files[e]||i.call(this,e,null,{dir:!0,createFolders:t}),this.files[e]};function _(e){return"[object RegExp]"===Object.prototype.toString.call(e)}var v={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(e){var t,n,i;for(t in this.files)i=this.files[t],(n=t.slice(this.root.length,t.length))&&t.slice(0,this.root.length)===this.root&&e(n,i)},filter:function(e){var t=[];return this.forEach(function(n,i){e(n,i)&&t.push(i)}),t},file:function(e,t,n){if(1!==arguments.length)return e=this.root+e,i.call(this,e,t,n),this;if(_(e)){var r=e;return this.filter(function(e,t){return!t.dir&&r.test(e)})}var s=this.files[this.root+e];return s&&!s.dir?s:null},folder:function(e){if(!e)return this;if(_(e))return this.filter(function(t,n){return n.dir&&e.test(t)});var t=this.root+e,n=g.call(this,t),i=this.clone();return i.root=n.name,i},remove:function(e){e=this.root+e;var t=this.files[e];if(t||("/"!==e.slice(-1)&&(e+="/"),t=this.files[e]),t&&!t.dir)delete this.files[e];else for(var n=this.filter(function(t,n){return n.name.slice(0,e.length)===e}),i=0;i<n.length;i++)delete this.files[n[i].name];return this},generate:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(e){var t,n={};try{if((n=s.extend(e||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:r.utf8encode})).type=n.type.toLowerCase(),n.compression=n.compression.toUpperCase(),"binarystring"===n.type&&(n.type="string"),!n.type)throw new Error("No output type specified.");s.checkSupport(n.type),"darwin"!==n.platform&&"freebsd"!==n.platform&&"linux"!==n.platform&&"sunos"!==n.platform||(n.platform="UNIX"),"win32"===n.platform&&(n.platform="DOS");var i=n.comment||this.comment||"";t=u.generateWorker(this,n,i)}catch(l){(t=new a("error")).error(l)}return new o(t,n.type||"string",n.mimeType)},generateAsync:function(e,t){return this.generateInternalStream(e).accumulate(t)},generateNodeStream:function(e,t){return(e=e||{}).type||(e.type="nodebuffer"),this.generateInternalStream(e).toNodejsStream(t)}};t.exports=v},{"./compressedObject":2,"./defaults":5,"./generate":9,"./nodejs/NodejsStreamInputAdapter":12,"./nodejsUtils":14,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31,"./utils":32,"./zipObject":35}],16:[function(e,t,n){t.exports=e("stream")},{stream:void 0}],17:[function(e,t,n){var i=e("./DataReader");function r(e){i.call(this,e);for(var t=0;t<this.data.length;t++)e[t]=255&e[t]}e("../utils").inherits(r,i),r.prototype.byteAt=function(e){return this.data[this.zero+e]},r.prototype.lastIndexOfSignature=function(e){for(var t=e.charCodeAt(0),n=e.charCodeAt(1),i=e.charCodeAt(2),r=e.charCodeAt(3),s=this.length-4;0<=s;--s)if(this.data[s]===t&&this.data[s+1]===n&&this.data[s+2]===i&&this.data[s+3]===r)return s-this.zero;return-1},r.prototype.readAndCheckSignature=function(e){var t=e.charCodeAt(0),n=e.charCodeAt(1),i=e.charCodeAt(2),r=e.charCodeAt(3),s=this.readData(4);return t===s[0]&&n===s[1]&&i===s[2]&&r===s[3]},r.prototype.readData=function(e){if(this.checkOffset(e),0===e)return[];var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=r},{"../utils":32,"./DataReader":18}],18:[function(e,t,n){var i=e("../utils");function r(e){this.data=e,this.length=e.length,this.index=0,this.zero=0}r.prototype={checkOffset:function(e){this.checkIndex(this.index+e)},checkIndex:function(e){if(this.length<this.zero+e||e<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+e+"). Corrupted zip ?")},setIndex:function(e){this.checkIndex(e),this.index=e},skip:function(e){this.setIndex(this.index+e)},byteAt:function(){},readInt:function(e){var t,n=0;for(this.checkOffset(e),t=this.index+e-1;t>=this.index;t--)n=(n<<8)+this.byteAt(t);return this.index+=e,n},readString:function(e){return i.transformTo("string",this.readData(e))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var e=this.readInt(4);return new Date(Date.UTC(1980+(e>>25&127),(e>>21&15)-1,e>>16&31,e>>11&31,e>>5&63,(31&e)<<1))}},t.exports=r},{"../utils":32}],19:[function(e,t,n){var i=e("./Uint8ArrayReader");function r(e){i.call(this,e)}e("../utils").inherits(r,i),r.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=r},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(e,t,n){var i=e("./DataReader");function r(e){i.call(this,e)}e("../utils").inherits(r,i),r.prototype.byteAt=function(e){return this.data.charCodeAt(this.zero+e)},r.prototype.lastIndexOfSignature=function(e){return this.data.lastIndexOf(e)-this.zero},r.prototype.readAndCheckSignature=function(e){return e===this.readData(4)},r.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=r},{"../utils":32,"./DataReader":18}],21:[function(e,t,n){var i=e("./ArrayReader");function r(e){i.call(this,e)}e("../utils").inherits(r,i),r.prototype.readData=function(e){if(this.checkOffset(e),0===e)return new Uint8Array(0);var t=this.data.subarray(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=r},{"../utils":32,"./ArrayReader":17}],22:[function(e,t,n){var i=e("../utils"),r=e("../support"),s=e("./ArrayReader"),a=e("./StringReader"),o=e("./NodeBufferReader"),l=e("./Uint8ArrayReader");t.exports=function(e){var t=i.getTypeOf(e);return i.checkSupport(t),"string"!==t||r.uint8array?"nodebuffer"===t?new o(e):r.uint8array?new l(i.transformTo("uint8array",e)):new s(i.transformTo("array",e)):new a(e)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(e,t,n){n.LOCAL_FILE_HEADER="PK",n.CENTRAL_FILE_HEADER="PK",n.CENTRAL_DIRECTORY_END="PK",n.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK",n.ZIP64_CENTRAL_DIRECTORY_END="PK",n.DATA_DESCRIPTOR="PK\b"},{}],24:[function(e,t,n){var i=e("./GenericWorker"),r=e("../utils");function s(e){i.call(this,"ConvertWorker to "+e),this.destType=e}r.inherits(s,i),s.prototype.processChunk=function(e){this.push({data:r.transformTo(this.destType,e.data),meta:e.meta})},t.exports=s},{"../utils":32,"./GenericWorker":28}],25:[function(e,t,n){var i=e("./GenericWorker"),r=e("../crc32");function s(){i.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}e("../utils").inherits(s,i),s.prototype.processChunk=function(e){this.streamInfo.crc32=r(e.data,this.streamInfo.crc32||0),this.push(e)},t.exports=s},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(e,t,n){var i=e("../utils"),r=e("./GenericWorker");function s(e){r.call(this,"DataLengthProbe for "+e),this.propName=e,this.withStreamInfo(e,0)}i.inherits(s,r),s.prototype.processChunk=function(e){if(e){var t=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=t+e.data.length}r.prototype.processChunk.call(this,e)},t.exports=s},{"../utils":32,"./GenericWorker":28}],27:[function(e,t,n){var i=e("../utils"),r=e("./GenericWorker");function s(e){r.call(this,"DataWorker");var t=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,e.then(function(e){t.dataIsReady=!0,t.data=e,t.max=e&&e.length||0,t.type=i.getTypeOf(e),t.isPaused||t._tickAndRepeat()},function(e){t.error(e)})}i.inherits(s,r),s.prototype.cleanUp=function(){r.prototype.cleanUp.call(this),this.data=null},s.prototype.resume=function(){return!!r.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,i.delay(this._tickAndRepeat,[],this)),!0)},s.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(i.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},s.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var e=null,t=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":e=this.data.substring(this.index,t);break;case"uint8array":e=this.data.subarray(this.index,t);break;case"array":case"nodebuffer":e=this.data.slice(this.index,t)}return this.index=t,this.push({data:e,meta:{percent:this.max?this.index/this.max*100:0}})},t.exports=s},{"../utils":32,"./GenericWorker":28}],28:[function(e,t,n){function i(e){this.name=e||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}i.prototype={push:function(e){this.emit("data",e)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(e){this.emit("error",e)}return!0},error:function(e){return!this.isFinished&&(this.isPaused?this.generatedError=e:(this.isFinished=!0,this.emit("error",e),this.previous&&this.previous.error(e),this.cleanUp()),!0)},on:function(e,t){return this._listeners[e].push(t),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(e,t){if(this._listeners[e])for(var n=0;n<this._listeners[e].length;n++)this._listeners[e][n].call(this,t)},pipe:function(e){return e.registerPrevious(this)},registerPrevious:function(e){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=e.streamInfo,this.mergeStreamInfo(),this.previous=e;var t=this;return e.on("data",function(e){t.processChunk(e)}),e.on("end",function(){t.end()}),e.on("error",function(e){t.error(e)}),this},pause:function(){return!this.isPaused&&!this.isFinished&&(this.isPaused=!0,this.previous&&this.previous.pause(),!0)},resume:function(){if(!this.isPaused||this.isFinished)return!1;var e=this.isPaused=!1;return this.generatedError&&(this.error(this.generatedError),e=!0),this.previous&&this.previous.resume(),!e},flush:function(){},processChunk:function(e){this.push(e)},withStreamInfo:function(e,t){return this.extraStreamInfo[e]=t,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var e in this.extraStreamInfo)Object.prototype.hasOwnProperty.call(this.extraStreamInfo,e)&&(this.streamInfo[e]=this.extraStreamInfo[e])},lock:function(){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.isLocked=!0,this.previous&&this.previous.lock()},toString:function(){var e="Worker "+this.name;return this.previous?this.previous+" -> "+e:e}},t.exports=i},{}],29:[function(e,t,n){var i=e("../utils"),r=e("./ConvertWorker"),s=e("./GenericWorker"),a=e("../base64"),o=e("../support"),l=e("../external"),c=null;if(o.nodestream)try{c=e("../nodejs/NodejsStreamOutputAdapter")}catch(d){}function h(e,t){return new l.Promise(function(n,r){var s=[],o=e._internalType,l=e._outputType,c=e._mimeType;e.on("data",function(e,n){s.push(e),t&&t(n)}).on("error",function(e){s=[],r(e)}).on("end",function(){try{var e=function(e,t,n){switch(e){case"blob":return i.newBlob(i.transformTo("arraybuffer",t),n);case"base64":return a.encode(t);default:return i.transformTo(e,t)}}(l,function(e,t){var n,i=0,r=null,s=0;for(n=0;n<t.length;n++)s+=t[n].length;switch(e){case"string":return t.join("");case"array":return Array.prototype.concat.apply([],t);case"uint8array":for(r=new Uint8Array(s),n=0;n<t.length;n++)r.set(t[n],i),i+=t[n].length;return r;case"nodebuffer":return Buffer.concat(t);default:throw new Error("concat : unsupported type '"+e+"'")}}(o,s),c);n(e)}catch(t){r(t)}s=[]}).resume()})}function u(e,t,n){var a=t;switch(t){case"blob":case"arraybuffer":a="uint8array";break;case"base64":a="string"}try{this._internalType=a,this._outputType=t,this._mimeType=n,i.checkSupport(a),this._worker=e.pipe(new r(a)),e.lock()}catch(o){this._worker=new s("error"),this._worker.error(o)}}u.prototype={accumulate:function(e){return h(this,e)},on:function(e,t){var n=this;return"data"===e?this._worker.on(e,function(e){t.call(n,e.data,e.meta)}):this._worker.on(e,function(){i.delay(t,arguments,n)}),this},resume:function(){return i.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(e){if(i.checkSupport("nodestream"),"nodebuffer"!==this._outputType)throw new Error(this._outputType+" is not supported by this method");return new c(this,{objectMode:"nodebuffer"!==this._outputType},e)}},t.exports=u},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(e,t,n){if(n.base64=!0,n.array=!0,n.string=!0,n.arraybuffer="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array,n.nodebuffer="undefined"!=typeof Buffer,n.uint8array="undefined"!=typeof Uint8Array,"undefined"==typeof ArrayBuffer)n.blob=!1;else{var i=new ArrayBuffer(0);try{n.blob=0===new Blob([i],{type:"application/zip"}).size}catch(s){try{var r=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);r.append(i),n.blob=0===r.getBlob("application/zip").size}catch(a){n.blob=!1}}}try{n.nodestream=!!e("readable-stream").Readable}catch(s){n.nodestream=!1}},{"readable-stream":16}],31:[function(e,t,n){for(var i=e("./utils"),r=e("./support"),s=e("./nodejsUtils"),a=e("./stream/GenericWorker"),o=new Array(256),l=0;l<256;l++)o[l]=252<=l?6:248<=l?5:240<=l?4:224<=l?3:192<=l?2:1;function c(){a.call(this,"utf-8 decode"),this.leftOver=null}function h(){a.call(this,"utf-8 encode")}o[254]=o[254]=1,n.utf8encode=function(e){return r.nodebuffer?s.newBufferFrom(e,"utf-8"):function(e){var t,n,i,s,a,o=e.length,l=0;for(s=0;s<o;s++)55296==(64512&(n=e.charCodeAt(s)))&&s+1<o&&56320==(64512&(i=e.charCodeAt(s+1)))&&(n=65536+(n-55296<<10)+(i-56320),s++),l+=n<128?1:n<2048?2:n<65536?3:4;for(t=r.uint8array?new Uint8Array(l):new Array(l),s=a=0;a<l;s++)55296==(64512&(n=e.charCodeAt(s)))&&s+1<o&&56320==(64512&(i=e.charCodeAt(s+1)))&&(n=65536+(n-55296<<10)+(i-56320),s++),n<128?t[a++]=n:(n<2048?t[a++]=192|n>>>6:(n<65536?t[a++]=224|n>>>12:(t[a++]=240|n>>>18,t[a++]=128|n>>>12&63),t[a++]=128|n>>>6&63),t[a++]=128|63&n);return t}(e)},n.utf8decode=function(e){return r.nodebuffer?i.transformTo("nodebuffer",e).toString("utf-8"):function(e){var t,n,r,s,a=e.length,l=new Array(2*a);for(t=n=0;t<a;)if((r=e[t++])<128)l[n++]=r;else if(4<(s=o[r]))l[n++]=65533,t+=s-1;else{for(r&=2===s?31:3===s?15:7;1<s&&t<a;)r=r<<6|63&e[t++],s--;1<s?l[n++]=65533:r<65536?l[n++]=r:(r-=65536,l[n++]=55296|r>>10&1023,l[n++]=56320|1023&r)}return l.length!==n&&(l.subarray?l=l.subarray(0,n):l.length=n),i.applyFromCharCode(l)}(e=i.transformTo(r.uint8array?"uint8array":"array",e))},i.inherits(c,a),c.prototype.processChunk=function(e){var t=i.transformTo(r.uint8array?"uint8array":"array",e.data);if(this.leftOver&&this.leftOver.length){if(r.uint8array){var s=t;(t=new Uint8Array(s.length+this.leftOver.length)).set(this.leftOver,0),t.set(s,this.leftOver.length)}else t=this.leftOver.concat(t);this.leftOver=null}var a=function(e,t){var n;for((t=t||e.length)>e.length&&(t=e.length),n=t-1;0<=n&&128==(192&e[n]);)n--;return n<0||0===n?t:n+o[e[n]]>t?n:t}(t),l=t;a!==t.length&&(r.uint8array?(l=t.subarray(0,a),this.leftOver=t.subarray(a,t.length)):(l=t.slice(0,a),this.leftOver=t.slice(a,t.length))),this.push({data:n.utf8decode(l),meta:e.meta})},c.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:n.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},n.Utf8DecodeWorker=c,i.inherits(h,a),h.prototype.processChunk=function(e){this.push({data:n.utf8encode(e.data),meta:e.meta})},n.Utf8EncodeWorker=h},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(e,t,n){var i=e("./support"),r=e("./base64"),s=e("./nodejsUtils"),a=e("./external");function o(e){return e}function l(e,t){for(var n=0;n<e.length;++n)t[n]=255&e.charCodeAt(n);return t}e("setimmediate"),n.newBlob=function(e,t){n.checkSupport("blob");try{return new Blob([e],{type:t})}catch(r){try{var i=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return i.append(e),i.getBlob(t)}catch(s){throw new Error("Bug : can't construct the Blob.")}}};var c={stringifyByChunk:function(e,t,n){var i=[],r=0,s=e.length;if(s<=n)return String.fromCharCode.apply(null,e);for(;r<s;)"array"===t||"nodebuffer"===t?i.push(String.fromCharCode.apply(null,e.slice(r,Math.min(r+n,s)))):i.push(String.fromCharCode.apply(null,e.subarray(r,Math.min(r+n,s)))),r+=n;return i.join("")},stringifyByChar:function(e){for(var t="",n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return t},applyCanBeUsed:{uint8array:function(){try{return i.uint8array&&1===String.fromCharCode.apply(null,new Uint8Array(1)).length}catch(e){return!1}}(),nodebuffer:function(){try{return i.nodebuffer&&1===String.fromCharCode.apply(null,s.allocBuffer(1)).length}catch(e){return!1}}()}};function h(e){var t=65536,i=n.getTypeOf(e),r=!0;if("uint8array"===i?r=c.applyCanBeUsed.uint8array:"nodebuffer"===i&&(r=c.applyCanBeUsed.nodebuffer),r)for(;1<t;)try{return c.stringifyByChunk(e,i,t)}catch(s){t=Math.floor(t/2)}return c.stringifyByChar(e)}function u(e,t){for(var n=0;n<e.length;n++)t[n]=e[n];return t}n.applyFromCharCode=h;var d={};d.string={string:o,array:function(e){return l(e,new Array(e.length))},arraybuffer:function(e){return d.string.uint8array(e).buffer},uint8array:function(e){return l(e,new Uint8Array(e.length))},nodebuffer:function(e){return l(e,s.allocBuffer(e.length))}},d.array={string:h,array:o,arraybuffer:function(e){return new Uint8Array(e).buffer},uint8array:function(e){return new Uint8Array(e)},nodebuffer:function(e){return s.newBufferFrom(e)}},d.arraybuffer={string:function(e){return h(new Uint8Array(e))},array:function(e){return u(new Uint8Array(e),new Array(e.byteLength))},arraybuffer:o,uint8array:function(e){return new Uint8Array(e)},nodebuffer:function(e){return s.newBufferFrom(new Uint8Array(e))}},d.uint8array={string:h,array:function(e){return u(e,new Array(e.length))},arraybuffer:function(e){return e.buffer},uint8array:o,nodebuffer:function(e){return s.newBufferFrom(e)}},d.nodebuffer={string:h,array:function(e){return u(e,new Array(e.length))},arraybuffer:function(e){return d.nodebuffer.uint8array(e).buffer},uint8array:function(e){return u(e,new Uint8Array(e.length))},nodebuffer:o},n.transformTo=function(e,t){if(t=t||"",!e)return t;n.checkSupport(e);var i=n.getTypeOf(t);return d[i][e](t)},n.resolve=function(e){for(var t=e.split("/"),n=[],i=0;i<t.length;i++){var r=t[i];"."===r||""===r&&0!==i&&i!==t.length-1||(".."===r?n.pop():n.push(r))}return n.join("/")},n.getTypeOf=function(e){return"string"==typeof e?"string":"[object Array]"===Object.prototype.toString.call(e)?"array":i.nodebuffer&&s.isBuffer(e)?"nodebuffer":i.uint8array&&e instanceof Uint8Array?"uint8array":i.arraybuffer&&e instanceof ArrayBuffer?"arraybuffer":void 0},n.checkSupport=function(e){if(!i[e.toLowerCase()])throw new Error(e+" is not supported by this platform")},n.MAX_VALUE_16BITS=65535,n.MAX_VALUE_32BITS=-1,n.pretty=function(e){var t,n,i="";for(n=0;n<(e||"").length;n++)i+="\\x"+((t=e.charCodeAt(n))<16?"0":"")+t.toString(16).toUpperCase();return i},n.delay=function(e,t,n){setImmediate(function(){e.apply(n||null,t||[])})},n.inherits=function(e,t){function n(){}n.prototype=t.prototype,e.prototype=new n},n.extend=function(){var e,t,n={};for(e=0;e<arguments.length;e++)for(t in arguments[e])Object.prototype.hasOwnProperty.call(arguments[e],t)&&void 0===n[t]&&(n[t]=arguments[e][t]);return n},n.prepareContent=function(e,t,s,o,c){return a.Promise.resolve(t).then(function(e){return i.blob&&(e instanceof Blob||-1!==["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(e)))&&"undefined"!=typeof FileReader?new a.Promise(function(t,n){var i=new FileReader;i.onload=function(e){t(e.target.result)},i.onerror=function(e){n(e.target.error)},i.readAsArrayBuffer(e)}):e}).then(function(t){var h,u=n.getTypeOf(t);return u?("arraybuffer"===u?t=n.transformTo("uint8array",t):"string"===u&&(c?t=r.decode(t):s&&!0!==o&&(t=l(h=t,i.uint8array?new Uint8Array(h.length):new Array(h.length)))),t):a.Promise.reject(new Error("Can't read the data of '"+e+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))})}},{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,setimmediate:54}],33:[function(e,t,n){var i=e("./reader/readerFor"),r=e("./utils"),s=e("./signature"),a=e("./zipEntry"),o=e("./support");function l(e){this.files=[],this.loadOptions=e}l.prototype={checkSignature:function(e){if(!this.reader.readAndCheckSignature(e)){this.reader.index-=4;var t=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+r.pretty(t)+", expected "+r.pretty(e)+")")}},isSignature:function(e,t){var n=this.reader.index;this.reader.setIndex(e);var i=this.reader.readString(4)===t;return this.reader.setIndex(n),i},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2);var e=this.reader.readData(this.zipCommentLength),t=o.uint8array?"uint8array":"array",n=r.transformTo(t,e);this.zipComment=this.loadOptions.decodeFileName(n)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.reader.skip(4),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var e,t,n,i=this.zip64EndOfCentralSize-44;0<i;)e=this.reader.readInt(2),t=this.reader.readInt(4),n=this.reader.readData(t),this.zip64ExtensibleData[e]={id:e,length:t,value:n}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),1<this.disksCount)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var e,t;for(e=0;e<this.files.length;e++)t=this.files[e],this.reader.setIndex(t.localHeaderOffset),this.checkSignature(s.LOCAL_FILE_HEADER),t.readLocalPart(this.reader),t.handleUTF8(),t.processAttributes()},readCentralDir:function(){var e;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(s.CENTRAL_FILE_HEADER);)(e=new a({zip64:this.zip64},this.loadOptions)).readCentralPart(this.reader),this.files.push(e);if(this.centralDirRecords!==this.files.length&&0!==this.centralDirRecords&&0===this.files.length)throw new Error("Corrupted zip or bug: expected "+this.centralDirRecords+" records in central dir, got "+this.files.length)},readEndOfCentral:function(){var e=this.reader.lastIndexOfSignature(s.CENTRAL_DIRECTORY_END);if(e<0)throw this.isSignature(0,s.LOCAL_FILE_HEADER)?new Error("Corrupted zip: can't find end of central directory"):new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html");this.reader.setIndex(e);var t=e;if(this.checkSignature(s.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===r.MAX_VALUE_16BITS||this.diskWithCentralDirStart===r.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===r.MAX_VALUE_16BITS||this.centralDirRecords===r.MAX_VALUE_16BITS||this.centralDirSize===r.MAX_VALUE_32BITS||this.centralDirOffset===r.MAX_VALUE_32BITS){if(this.zip64=!0,(e=this.reader.lastIndexOfSignature(s.ZIP64_CENTRAL_DIRECTORY_LOCATOR))<0)throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");if(this.reader.setIndex(e),this.checkSignature(s.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),!this.isSignature(this.relativeOffsetEndOfZip64CentralDir,s.ZIP64_CENTRAL_DIRECTORY_END)&&(this.relativeOffsetEndOfZip64CentralDir=this.reader.lastIndexOfSignature(s.ZIP64_CENTRAL_DIRECTORY_END),this.relativeOffsetEndOfZip64CentralDir<0))throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir),this.checkSignature(s.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral()}var n=this.centralDirOffset+this.centralDirSize;this.zip64&&(n+=20,n+=12+this.zip64EndOfCentralSize);var i=t-n;if(0<i)this.isSignature(t,s.CENTRAL_FILE_HEADER)||(this.reader.zero=i);else if(i<0)throw new Error("Corrupted zip: missing "+Math.abs(i)+" bytes.")},prepareReader:function(e){this.reader=i(e)},load:function(e){this.prepareReader(e),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}},t.exports=l},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(e,t,n){var i=e("./reader/readerFor"),r=e("./utils"),s=e("./compressedObject"),a=e("./crc32"),o=e("./utf8"),l=e("./compressions"),c=e("./support");function h(e,t){this.options=e,this.loadOptions=t}h.prototype={isEncrypted:function(){return!(1&~this.bitFlag)},useUTF8:function(){return!(2048&~this.bitFlag)},readLocalPart:function(e){var t,n;if(e.skip(22),this.fileNameLength=e.readInt(2),n=e.readInt(2),this.fileName=e.readData(this.fileNameLength),e.skip(n),-1===this.compressedSize||-1===this.uncompressedSize)throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");if(null===(t=function(e){for(var t in l)if(Object.prototype.hasOwnProperty.call(l,t)&&l[t].magic===e)return l[t];return null}(this.compressionMethod)))throw new Error("Corrupted zip : compression "+r.pretty(this.compressionMethod)+" unknown (inner file : "+r.transformTo("string",this.fileName)+")");this.decompressed=new s(this.compressedSize,this.uncompressedSize,this.crc32,t,e.readData(this.compressedSize))},readCentralPart:function(e){this.versionMadeBy=e.readInt(2),e.skip(2),this.bitFlag=e.readInt(2),this.compressionMethod=e.readString(2),this.date=e.readDate(),this.crc32=e.readInt(4),this.compressedSize=e.readInt(4),this.uncompressedSize=e.readInt(4);var t=e.readInt(2);if(this.extraFieldsLength=e.readInt(2),this.fileCommentLength=e.readInt(2),this.diskNumberStart=e.readInt(2),this.internalFileAttributes=e.readInt(2),this.externalFileAttributes=e.readInt(4),this.localHeaderOffset=e.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");e.skip(t),this.readExtraFields(e),this.parseZIP64ExtraField(e),this.fileComment=e.readData(this.fileCommentLength)},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var e=this.versionMadeBy>>8;this.dir=!!(16&this.externalFileAttributes),0==e&&(this.dosPermissions=63&this.externalFileAttributes),3==e&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||"/"!==this.fileNameStr.slice(-1)||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var e=i(this.extraFields[1].value);this.uncompressedSize===r.MAX_VALUE_32BITS&&(this.uncompressedSize=e.readInt(8)),this.compressedSize===r.MAX_VALUE_32BITS&&(this.compressedSize=e.readInt(8)),this.localHeaderOffset===r.MAX_VALUE_32BITS&&(this.localHeaderOffset=e.readInt(8)),this.diskNumberStart===r.MAX_VALUE_32BITS&&(this.diskNumberStart=e.readInt(4))}},readExtraFields:function(e){var t,n,i,r=e.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});e.index+4<r;)t=e.readInt(2),n=e.readInt(2),i=e.readData(n),this.extraFields[t]={id:t,length:n,value:i};e.setIndex(r)},handleUTF8:function(){var e=c.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=o.utf8decode(this.fileName),this.fileCommentStr=o.utf8decode(this.fileComment);else{var t=this.findExtraFieldUnicodePath();if(null!==t)this.fileNameStr=t;else{var n=r.transformTo(e,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(n)}var i=this.findExtraFieldUnicodeComment();if(null!==i)this.fileCommentStr=i;else{var s=r.transformTo(e,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(s)}}},findExtraFieldUnicodePath:function(){var e=this.extraFields[28789];if(e){var t=i(e.value);return 1!==t.readInt(1)||a(this.fileName)!==t.readInt(4)?null:o.utf8decode(t.readData(e.length-5))}return null},findExtraFieldUnicodeComment:function(){var e=this.extraFields[25461];if(e){var t=i(e.value);return 1!==t.readInt(1)||a(this.fileComment)!==t.readInt(4)?null:o.utf8decode(t.readData(e.length-5))}return null}},t.exports=h},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(e,t,n){function i(e,t,n){this.name=e,this.dir=n.dir,this.date=n.date,this.comment=n.comment,this.unixPermissions=n.unixPermissions,this.dosPermissions=n.dosPermissions,this._data=t,this._dataBinary=n.binary,this.options={compression:n.compression,compressionOptions:n.compressionOptions}}var r=e("./stream/StreamHelper"),s=e("./stream/DataWorker"),a=e("./utf8"),o=e("./compressedObject"),l=e("./stream/GenericWorker");i.prototype={internalStream:function(e){var t=null,n="string";try{if(!e)throw new Error("No output type specified.");var i="string"===(n=e.toLowerCase())||"text"===n;"binarystring"!==n&&"text"!==n||(n="string"),t=this._decompressWorker();var s=!this._dataBinary;s&&!i&&(t=t.pipe(new a.Utf8EncodeWorker)),!s&&i&&(t=t.pipe(new a.Utf8DecodeWorker))}catch(o){(t=new l("error")).error(o)}return new r(t,n,"")},async:function(e,t){return this.internalStream(e).accumulate(t)},nodeStream:function(e,t){return this.internalStream(e||"nodebuffer").toNodejsStream(t)},_compressWorker:function(e,t){if(this._data instanceof o&&this._data.compression.magic===e.magic)return this._data.getCompressedWorker();var n=this._decompressWorker();return this._dataBinary||(n=n.pipe(new a.Utf8EncodeWorker)),o.createWorkerFrom(n,e,t)},_decompressWorker:function(){return this._data instanceof o?this._data.getContentWorker():this._data instanceof l?this._data:new s(this._data)}};for(var c=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],h=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},u=0;u<c.length;u++)i.prototype[c[u]]=h;t.exports=i},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(e,t,n){(function(e){var n,i,r=e.MutationObserver||e.WebKitMutationObserver;if(r){var s=0,a=new r(h),o=e.document.createTextNode("");a.observe(o,{characterData:!0}),n=function(){o.data=s=++s%2}}else if(e.setImmediate||void 0===e.MessageChannel)n="document"in e&&"onreadystatechange"in e.document.createElement("script")?function(){var t=e.document.createElement("script");t.onreadystatechange=function(){h(),t.onreadystatechange=null,t.parentNode.removeChild(t),t=null},e.document.documentElement.appendChild(t)}:function(){setTimeout(h,0)};else{var l=new e.MessageChannel;l.port1.onmessage=h,n=function(){l.port2.postMessage(0)}}var c=[];function h(){var e,t;i=!0;for(var n=c.length;n;){for(t=c,c=[],e=-1;++e<n;)t[e]();n=c.length}i=!1}t.exports=function(e){1!==c.push(e)||i||n()}}).call(this,void 0!==ud?ud:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],37:[function(e,t,n){var i=e("immediate");function r(){}var s={},a=["REJECTED"],o=["FULFILLED"],l=["PENDING"];function c(e){if("function"!=typeof e)throw new TypeError("resolver must be a function");this.state=l,this.queue=[],this.outcome=void 0,e!==r&&p(this,e)}function h(e,t,n){this.promise=e,"function"==typeof t&&(this.onFulfilled=t,this.callFulfilled=this.otherCallFulfilled),"function"==typeof n&&(this.onRejected=n,this.callRejected=this.otherCallRejected)}function u(e,t,n){i(function(){var i;try{i=t(n)}catch(r){return s.reject(e,r)}i===e?s.reject(e,new TypeError("Cannot resolve promise with itself")):s.resolve(e,i)})}function d(e){var t=e&&e.then;if(e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof t)return function(){t.apply(e,arguments)}}function p(e,t){var n=!1;function i(t){n||(n=!0,s.reject(e,t))}function r(t){n||(n=!0,s.resolve(e,t))}var a=f(function(){t(r,i)});"error"===a.status&&i(a.value)}function f(e,t){var n={};try{n.value=e(t),n.status="success"}catch(i){n.status="error",n.value=i}return n}(t.exports=c).prototype.finally=function(e){if("function"!=typeof e)return this;var t=this.constructor;return this.then(function(n){return t.resolve(e()).then(function(){return n})},function(n){return t.resolve(e()).then(function(){throw n})})},c.prototype.catch=function(e){return this.then(null,e)},c.prototype.then=function(e,t){if("function"!=typeof e&&this.state===o||"function"!=typeof t&&this.state===a)return this;var n=new this.constructor(r);return this.state!==l?u(n,this.state===o?e:t,this.outcome):this.queue.push(new h(n,e,t)),n},h.prototype.callFulfilled=function(e){s.resolve(this.promise,e)},h.prototype.otherCallFulfilled=function(e){u(this.promise,this.onFulfilled,e)},h.prototype.callRejected=function(e){s.reject(this.promise,e)},h.prototype.otherCallRejected=function(e){u(this.promise,this.onRejected,e)},s.resolve=function(e,t){var n=f(d,t);if("error"===n.status)return s.reject(e,n.value);var i=n.value;if(i)p(e,i);else{e.state=o,e.outcome=t;for(var r=-1,a=e.queue.length;++r<a;)e.queue[r].callFulfilled(t)}return e},s.reject=function(e,t){e.state=a,e.outcome=t;for(var n=-1,i=e.queue.length;++n<i;)e.queue[n].callRejected(t);return e},c.resolve=function(e){return e instanceof this?e:s.resolve(new this(r),e)},c.reject=function(e){var t=new this(r);return s.reject(t,e)},c.all=function(e){var t=this;if("[object Array]"!==Object.prototype.toString.call(e))return this.reject(new TypeError("must be an array"));var n=e.length,i=!1;if(!n)return this.resolve([]);for(var a=new Array(n),o=0,l=-1,c=new this(r);++l<n;)h(e[l],l);return c;function h(e,r){t.resolve(e).then(function(e){a[r]=e,++o!==n||i||(i=!0,s.resolve(c,a))},function(e){i||(i=!0,s.reject(c,e))})}},c.race=function(e){var t=this;if("[object Array]"!==Object.prototype.toString.call(e))return this.reject(new TypeError("must be an array"));var n=e.length,i=!1;if(!n)return this.resolve([]);for(var a,o=-1,l=new this(r);++o<n;)a=e[o],t.resolve(a).then(function(e){i||(i=!0,s.resolve(l,e))},function(e){i||(i=!0,s.reject(l,e))});return l}},{immediate:36}],38:[function(e,t,n){var i={};(0,e("./lib/utils/common").assign)(i,e("./lib/deflate"),e("./lib/inflate"),e("./lib/zlib/constants")),t.exports=i},{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(e,t,n){var i=e("./zlib/deflate"),r=e("./utils/common"),s=e("./utils/strings"),a=e("./zlib/messages"),o=e("./zlib/zstream"),l=Object.prototype.toString,c=0,h=-1,u=0,d=8;function p(e){if(!(this instanceof p))return new p(e);this.options=r.assign({level:h,method:d,chunkSize:16384,windowBits:15,memLevel:8,strategy:u,to:""},e||{});var t=this.options;t.raw&&0<t.windowBits?t.windowBits=-t.windowBits:t.gzip&&0<t.windowBits&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new o,this.strm.avail_out=0;var n=i.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(n!==c)throw new Error(a[n]);if(t.header&&i.deflateSetHeader(this.strm,t.header),t.dictionary){var f;if(f="string"==typeof t.dictionary?s.string2buf(t.dictionary):"[object ArrayBuffer]"===l.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,(n=i.deflateSetDictionary(this.strm,f))!==c)throw new Error(a[n]);this._dict_set=!0}}function f(e,t){var n=new p(t);if(n.push(e,!0),n.err)throw n.msg||a[n.err];return n.result}p.prototype.push=function(e,t){var n,a,o=this.strm,h=this.options.chunkSize;if(this.ended)return!1;a=t===~~t?t:!0===t?4:0,"string"==typeof e?o.input=s.string2buf(e):"[object ArrayBuffer]"===l.call(e)?o.input=new Uint8Array(e):o.input=e,o.next_in=0,o.avail_in=o.input.length;do{if(0===o.avail_out&&(o.output=new r.Buf8(h),o.next_out=0,o.avail_out=h),1!==(n=i.deflate(o,a))&&n!==c)return this.onEnd(n),!(this.ended=!0);0!==o.avail_out&&(0!==o.avail_in||4!==a&&2!==a)||("string"===this.options.to?this.onData(s.buf2binstring(r.shrinkBuf(o.output,o.next_out))):this.onData(r.shrinkBuf(o.output,o.next_out)))}while((0<o.avail_in||0===o.avail_out)&&1!==n);return 4===a?(n=i.deflateEnd(this.strm),this.onEnd(n),this.ended=!0,n===c):2!==a||(this.onEnd(c),!(o.avail_out=0))},p.prototype.onData=function(e){this.chunks.push(e)},p.prototype.onEnd=function(e){e===c&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=r.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},n.Deflate=p,n.deflate=f,n.deflateRaw=function(e,t){return(t=t||{}).raw=!0,f(e,t)},n.gzip=function(e,t){return(t=t||{}).gzip=!0,f(e,t)}},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(e,t,n){var i=e("./zlib/inflate"),r=e("./utils/common"),s=e("./utils/strings"),a=e("./zlib/constants"),o=e("./zlib/messages"),l=e("./zlib/zstream"),c=e("./zlib/gzheader"),h=Object.prototype.toString;function u(e){if(!(this instanceof u))return new u(e);this.options=r.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&0<=t.windowBits&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(0<=t.windowBits&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),15<t.windowBits&&t.windowBits<48&&!(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var n=i.inflateInit2(this.strm,t.windowBits);if(n!==a.Z_OK)throw new Error(o[n]);this.header=new c,i.inflateGetHeader(this.strm,this.header)}function d(e,t){var n=new u(t);if(n.push(e,!0),n.err)throw n.msg||o[n.err];return n.result}u.prototype.push=function(e,t){var n,o,l,c,u,d,p=this.strm,f=this.options.chunkSize,m=this.options.dictionary,g=!1;if(this.ended)return!1;o=t===~~t?t:!0===t?a.Z_FINISH:a.Z_NO_FLUSH,"string"==typeof e?p.input=s.binstring2buf(e):"[object ArrayBuffer]"===h.call(e)?p.input=new Uint8Array(e):p.input=e,p.next_in=0,p.avail_in=p.input.length;do{if(0===p.avail_out&&(p.output=new r.Buf8(f),p.next_out=0,p.avail_out=f),(n=i.inflate(p,a.Z_NO_FLUSH))===a.Z_NEED_DICT&&m&&(d="string"==typeof m?s.string2buf(m):"[object ArrayBuffer]"===h.call(m)?new Uint8Array(m):m,n=i.inflateSetDictionary(this.strm,d)),n===a.Z_BUF_ERROR&&!0===g&&(n=a.Z_OK,g=!1),n!==a.Z_STREAM_END&&n!==a.Z_OK)return this.onEnd(n),!(this.ended=!0);p.next_out&&(0!==p.avail_out&&n!==a.Z_STREAM_END&&(0!==p.avail_in||o!==a.Z_FINISH&&o!==a.Z_SYNC_FLUSH)||("string"===this.options.to?(l=s.utf8border(p.output,p.next_out),c=p.next_out-l,u=s.buf2string(p.output,l),p.next_out=c,p.avail_out=f-c,c&&r.arraySet(p.output,p.output,l,c,0),this.onData(u)):this.onData(r.shrinkBuf(p.output,p.next_out)))),0===p.avail_in&&0===p.avail_out&&(g=!0)}while((0<p.avail_in||0===p.avail_out)&&n!==a.Z_STREAM_END);return n===a.Z_STREAM_END&&(o=a.Z_FINISH),o===a.Z_FINISH?(n=i.inflateEnd(this.strm),this.onEnd(n),this.ended=!0,n===a.Z_OK):o!==a.Z_SYNC_FLUSH||(this.onEnd(a.Z_OK),!(p.avail_out=0))},u.prototype.onData=function(e){this.chunks.push(e)},u.prototype.onEnd=function(e){e===a.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=r.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},n.Inflate=u,n.inflate=d,n.inflateRaw=function(e,t){return(t=t||{}).raw=!0,d(e,t)},n.ungzip=d},{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(e,t,n){var i="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;n.assign=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var n=t.shift();if(n){if("object"!=typeof n)throw new TypeError(n+"must be non-object");for(var i in n)n.hasOwnProperty(i)&&(e[i]=n[i])}}return e},n.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var r={arraySet:function(e,t,n,i,r){if(t.subarray&&e.subarray)e.set(t.subarray(n,n+i),r);else for(var s=0;s<i;s++)e[r+s]=t[n+s]},flattenChunks:function(e){var t,n,i,r,s,a;for(t=i=0,n=e.length;t<n;t++)i+=e[t].length;for(a=new Uint8Array(i),t=r=0,n=e.length;t<n;t++)s=e[t],a.set(s,r),r+=s.length;return a}},s={arraySet:function(e,t,n,i,r){for(var s=0;s<i;s++)e[r+s]=t[n+s]},flattenChunks:function(e){return[].concat.apply([],e)}};n.setTyped=function(e){e?(n.Buf8=Uint8Array,n.Buf16=Uint16Array,n.Buf32=Int32Array,n.assign(n,r)):(n.Buf8=Array,n.Buf16=Array,n.Buf32=Array,n.assign(n,s))},n.setTyped(i)},{}],42:[function(e,t,n){var i=e("./common"),r=!0,s=!0;try{String.fromCharCode.apply(null,[0])}catch(c){r=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(c){s=!1}for(var a=new i.Buf8(256),o=0;o<256;o++)a[o]=252<=o?6:248<=o?5:240<=o?4:224<=o?3:192<=o?2:1;function l(e,t){if(t<65537&&(e.subarray&&s||!e.subarray&&r))return String.fromCharCode.apply(null,i.shrinkBuf(e,t));for(var n="",a=0;a<t;a++)n+=String.fromCharCode(e[a]);return n}a[254]=a[254]=1,n.string2buf=function(e){var t,n,r,s,a,o=e.length,l=0;for(s=0;s<o;s++)55296==(64512&(n=e.charCodeAt(s)))&&s+1<o&&56320==(64512&(r=e.charCodeAt(s+1)))&&(n=65536+(n-55296<<10)+(r-56320),s++),l+=n<128?1:n<2048?2:n<65536?3:4;for(t=new i.Buf8(l),s=a=0;a<l;s++)55296==(64512&(n=e.charCodeAt(s)))&&s+1<o&&56320==(64512&(r=e.charCodeAt(s+1)))&&(n=65536+(n-55296<<10)+(r-56320),s++),n<128?t[a++]=n:(n<2048?t[a++]=192|n>>>6:(n<65536?t[a++]=224|n>>>12:(t[a++]=240|n>>>18,t[a++]=128|n>>>12&63),t[a++]=128|n>>>6&63),t[a++]=128|63&n);return t},n.buf2binstring=function(e){return l(e,e.length)},n.binstring2buf=function(e){for(var t=new i.Buf8(e.length),n=0,r=t.length;n<r;n++)t[n]=e.charCodeAt(n);return t},n.buf2string=function(e,t){var n,i,r,s,o=t||e.length,c=new Array(2*o);for(n=i=0;n<o;)if((r=e[n++])<128)c[i++]=r;else if(4<(s=a[r]))c[i++]=65533,n+=s-1;else{for(r&=2===s?31:3===s?15:7;1<s&&n<o;)r=r<<6|63&e[n++],s--;1<s?c[i++]=65533:r<65536?c[i++]=r:(r-=65536,c[i++]=55296|r>>10&1023,c[i++]=56320|1023&r)}return l(c,i)},n.utf8border=function(e,t){var n;for((t=t||e.length)>e.length&&(t=e.length),n=t-1;0<=n&&128==(192&e[n]);)n--;return n<0||0===n?t:n+a[e[n]]>t?n:t}},{"./common":41}],43:[function(e,t,n){t.exports=function(e,t,n,i){for(var r=65535&e,s=e>>>16&65535,a=0;0!==n;){for(n-=a=2e3<n?2e3:n;s=s+(r=r+t[i++]|0)|0,--a;);r%=65521,s%=65521}return r|s<<16}},{}],44:[function(e,t,n){t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],45:[function(e,t,n){var i=function(){for(var e,t=[],n=0;n<256;n++){e=n;for(var i=0;i<8;i++)e=1&e?3988292384^e>>>1:e>>>1;t[n]=e}return t}();t.exports=function(e,t,n,r){var s=i,a=r+n;e^=-1;for(var o=r;o<a;o++)e=e>>>8^s[255&(e^t[o])];return-1^e}},{}],46:[function(e,t,n){var i,r=e("../utils/common"),s=e("./trees"),a=e("./adler32"),o=e("./crc32"),l=e("./messages"),c=0,h=4,u=0,d=-2,p=-1,f=4,m=2,g=8,_=9,v=286,x=30,y=19,S=2*v+1,A=15,b=3,M=258,w=M+b+1,T=42,E=113,C=1,R=2,I=3,P=4;function D(e,t){return e.msg=l[t],t}function B(e){return(e<<1)-(4<e?9:0)}function L(e){for(var t=e.length;0<=--t;)e[t]=0}function F(e){var t=e.state,n=t.pending;n>e.avail_out&&(n=e.avail_out),0!==n&&(r.arraySet(e.output,t.pending_buf,t.pending_out,n,e.next_out),e.next_out+=n,t.pending_out+=n,e.total_out+=n,e.avail_out-=n,t.pending-=n,0===t.pending&&(t.pending_out=0))}function U(e,t){s._tr_flush_block(e,0<=e.block_start?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,F(e.strm)}function k(e,t){e.pending_buf[e.pending++]=t}function N(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t}function O(e,t){var n,i,r=e.max_chain_length,s=e.strstart,a=e.prev_length,o=e.nice_match,l=e.strstart>e.w_size-w?e.strstart-(e.w_size-w):0,c=e.window,h=e.w_mask,u=e.prev,d=e.strstart+M,p=c[s+a-1],f=c[s+a];e.prev_length>=e.good_match&&(r>>=2),o>e.lookahead&&(o=e.lookahead);do{if(c[(n=t)+a]===f&&c[n+a-1]===p&&c[n]===c[s]&&c[++n]===c[s+1]){s+=2,n++;do{}while(c[++s]===c[++n]&&c[++s]===c[++n]&&c[++s]===c[++n]&&c[++s]===c[++n]&&c[++s]===c[++n]&&c[++s]===c[++n]&&c[++s]===c[++n]&&c[++s]===c[++n]&&s<d);if(i=M-(d-s),s=d-M,a<i){if(e.match_start=t,o<=(a=i))break;p=c[s+a-1],f=c[s+a]}}}while((t=u[t&h])>l&&0!=--r);return a<=e.lookahead?a:e.lookahead}function z(e){var t,n,i,s,l,c,h,u,d,p,f=e.w_size;do{if(s=e.window_size-e.lookahead-e.strstart,e.strstart>=f+(f-w)){for(r.arraySet(e.window,e.window,f,f,0),e.match_start-=f,e.strstart-=f,e.block_start-=f,t=n=e.hash_size;i=e.head[--t],e.head[t]=f<=i?i-f:0,--n;);for(t=n=f;i=e.prev[--t],e.prev[t]=f<=i?i-f:0,--n;);s+=f}if(0===e.strm.avail_in)break;if(c=e.strm,h=e.window,u=e.strstart+e.lookahead,p=void 0,(d=s)<(p=c.avail_in)&&(p=d),n=0===p?0:(c.avail_in-=p,r.arraySet(h,c.input,c.next_in,p,u),1===c.state.wrap?c.adler=a(c.adler,h,p,u):2===c.state.wrap&&(c.adler=o(c.adler,h,p,u)),c.next_in+=p,c.total_in+=p,p),e.lookahead+=n,e.lookahead+e.insert>=b)for(l=e.strstart-e.insert,e.ins_h=e.window[l],e.ins_h=(e.ins_h<<e.hash_shift^e.window[l+1])&e.hash_mask;e.insert&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[l+b-1])&e.hash_mask,e.prev[l&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=l,l++,e.insert--,!(e.lookahead+e.insert<b)););}while(e.lookahead<w&&0!==e.strm.avail_in)}function H(e,t){for(var n,i;;){if(e.lookahead<w){if(z(e),e.lookahead<w&&t===c)return C;if(0===e.lookahead)break}if(n=0,e.lookahead>=b&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+b-1])&e.hash_mask,n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==n&&e.strstart-n<=e.w_size-w&&(e.match_length=O(e,n)),e.match_length>=b)if(i=s._tr_tally(e,e.strstart-e.match_start,e.match_length-b),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=b){for(e.match_length--;e.strstart++,e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+b-1])&e.hash_mask,n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart,0!=--e.match_length;);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+1])&e.hash_mask;else i=s._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(i&&(U(e,!1),0===e.strm.avail_out))return C}return e.insert=e.strstart<b-1?e.strstart:b-1,t===h?(U(e,!0),0===e.strm.avail_out?I:P):e.last_lit&&(U(e,!1),0===e.strm.avail_out)?C:R}function V(e,t){for(var n,i,r;;){if(e.lookahead<w){if(z(e),e.lookahead<w&&t===c)return C;if(0===e.lookahead)break}if(n=0,e.lookahead>=b&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+b-1])&e.hash_mask,n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=b-1,0!==n&&e.prev_length<e.max_lazy_match&&e.strstart-n<=e.w_size-w&&(e.match_length=O(e,n),e.match_length<=5&&(1===e.strategy||e.match_length===b&&4096<e.strstart-e.match_start)&&(e.match_length=b-1)),e.prev_length>=b&&e.match_length<=e.prev_length){for(r=e.strstart+e.lookahead-b,i=s._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-b),e.lookahead-=e.prev_length-1,e.prev_length-=2;++e.strstart<=r&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+b-1])&e.hash_mask,n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!=--e.prev_length;);if(e.match_available=0,e.match_length=b-1,e.strstart++,i&&(U(e,!1),0===e.strm.avail_out))return C}else if(e.match_available){if((i=s._tr_tally(e,0,e.window[e.strstart-1]))&&U(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return C}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(i=s._tr_tally(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<b-1?e.strstart:b-1,t===h?(U(e,!0),0===e.strm.avail_out?I:P):e.last_lit&&(U(e,!1),0===e.strm.avail_out)?C:R}function G(e,t,n,i,r){this.good_length=e,this.max_lazy=t,this.nice_length=n,this.max_chain=i,this.func=r}function W(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=g,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new r.Buf16(2*S),this.dyn_dtree=new r.Buf16(2*(2*x+1)),this.bl_tree=new r.Buf16(2*(2*y+1)),L(this.dyn_ltree),L(this.dyn_dtree),L(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new r.Buf16(A+1),this.heap=new r.Buf16(2*v+1),L(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new r.Buf16(2*v+1),L(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function j(e){var t;return e&&e.state?(e.total_in=e.total_out=0,e.data_type=m,(t=e.state).pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?T:E,e.adler=2===t.wrap?0:1,t.last_flush=c,s._tr_init(t),u):D(e,d)}function X(e){var t,n=j(e);return n===u&&((t=e.state).window_size=2*t.w_size,L(t.head),t.max_lazy_match=i[t.level].max_lazy,t.good_match=i[t.level].good_length,t.nice_match=i[t.level].nice_length,t.max_chain_length=i[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=b-1,t.match_available=0,t.ins_h=0),n}function q(e,t,n,i,s,a){if(!e)return d;var o=1;if(t===p&&(t=6),i<0?(o=0,i=-i):15<i&&(o=2,i-=16),s<1||_<s||n!==g||i<8||15<i||t<0||9<t||a<0||f<a)return D(e,d);8===i&&(i=9);var l=new W;return(e.state=l).strm=e,l.wrap=o,l.gzhead=null,l.w_bits=i,l.w_size=1<<l.w_bits,l.w_mask=l.w_size-1,l.hash_bits=s+7,l.hash_size=1<<l.hash_bits,l.hash_mask=l.hash_size-1,l.hash_shift=~~((l.hash_bits+b-1)/b),l.window=new r.Buf8(2*l.w_size),l.head=new r.Buf16(l.hash_size),l.prev=new r.Buf16(l.w_size),l.lit_bufsize=1<<s+6,l.pending_buf_size=4*l.lit_bufsize,l.pending_buf=new r.Buf8(l.pending_buf_size),l.d_buf=1*l.lit_bufsize,l.l_buf=3*l.lit_bufsize,l.level=t,l.strategy=a,l.method=n,X(e)}i=[new G(0,0,0,0,function(e,t){var n=65535;for(n>e.pending_buf_size-5&&(n=e.pending_buf_size-5);;){if(e.lookahead<=1){if(z(e),0===e.lookahead&&t===c)return C;if(0===e.lookahead)break}e.strstart+=e.lookahead,e.lookahead=0;var i=e.block_start+n;if((0===e.strstart||e.strstart>=i)&&(e.lookahead=e.strstart-i,e.strstart=i,U(e,!1),0===e.strm.avail_out))return C;if(e.strstart-e.block_start>=e.w_size-w&&(U(e,!1),0===e.strm.avail_out))return C}return e.insert=0,t===h?(U(e,!0),0===e.strm.avail_out?I:P):(e.strstart>e.block_start&&(U(e,!1),e.strm.avail_out),C)}),new G(4,4,8,4,H),new G(4,5,16,8,H),new G(4,6,32,32,H),new G(4,4,16,16,V),new G(8,16,32,32,V),new G(8,16,128,128,V),new G(8,32,128,256,V),new G(32,128,258,1024,V),new G(32,258,258,4096,V)],n.deflateInit=function(e,t){return q(e,t,g,15,8,0)},n.deflateInit2=q,n.deflateReset=X,n.deflateResetKeep=j,n.deflateSetHeader=function(e,t){return e&&e.state?2!==e.state.wrap?d:(e.state.gzhead=t,u):d},n.deflate=function(e,t){var n,r,a,l;if(!e||!e.state||5<t||t<0)return e?D(e,d):d;if(r=e.state,!e.output||!e.input&&0!==e.avail_in||666===r.status&&t!==h)return D(e,0===e.avail_out?-5:d);if(r.strm=e,n=r.last_flush,r.last_flush=t,r.status===T)if(2===r.wrap)e.adler=0,k(r,31),k(r,139),k(r,8),r.gzhead?(k(r,(r.gzhead.text?1:0)+(r.gzhead.hcrc?2:0)+(r.gzhead.extra?4:0)+(r.gzhead.name?8:0)+(r.gzhead.comment?16:0)),k(r,255&r.gzhead.time),k(r,r.gzhead.time>>8&255),k(r,r.gzhead.time>>16&255),k(r,r.gzhead.time>>24&255),k(r,9===r.level?2:2<=r.strategy||r.level<2?4:0),k(r,255&r.gzhead.os),r.gzhead.extra&&r.gzhead.extra.length&&(k(r,255&r.gzhead.extra.length),k(r,r.gzhead.extra.length>>8&255)),r.gzhead.hcrc&&(e.adler=o(e.adler,r.pending_buf,r.pending,0)),r.gzindex=0,r.status=69):(k(r,0),k(r,0),k(r,0),k(r,0),k(r,0),k(r,9===r.level?2:2<=r.strategy||r.level<2?4:0),k(r,3),r.status=E);else{var p=g+(r.w_bits-8<<4)<<8;p|=(2<=r.strategy||r.level<2?0:r.level<6?1:6===r.level?2:3)<<6,0!==r.strstart&&(p|=32),p+=31-p%31,r.status=E,N(r,p),0!==r.strstart&&(N(r,e.adler>>>16),N(r,65535&e.adler)),e.adler=1}if(69===r.status)if(r.gzhead.extra){for(a=r.pending;r.gzindex<(65535&r.gzhead.extra.length)&&(r.pending!==r.pending_buf_size||(r.gzhead.hcrc&&r.pending>a&&(e.adler=o(e.adler,r.pending_buf,r.pending-a,a)),F(e),a=r.pending,r.pending!==r.pending_buf_size));)k(r,255&r.gzhead.extra[r.gzindex]),r.gzindex++;r.gzhead.hcrc&&r.pending>a&&(e.adler=o(e.adler,r.pending_buf,r.pending-a,a)),r.gzindex===r.gzhead.extra.length&&(r.gzindex=0,r.status=73)}else r.status=73;if(73===r.status)if(r.gzhead.name){a=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>a&&(e.adler=o(e.adler,r.pending_buf,r.pending-a,a)),F(e),a=r.pending,r.pending===r.pending_buf_size)){l=1;break}l=r.gzindex<r.gzhead.name.length?255&r.gzhead.name.charCodeAt(r.gzindex++):0,k(r,l)}while(0!==l);r.gzhead.hcrc&&r.pending>a&&(e.adler=o(e.adler,r.pending_buf,r.pending-a,a)),0===l&&(r.gzindex=0,r.status=91)}else r.status=91;if(91===r.status)if(r.gzhead.comment){a=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>a&&(e.adler=o(e.adler,r.pending_buf,r.pending-a,a)),F(e),a=r.pending,r.pending===r.pending_buf_size)){l=1;break}l=r.gzindex<r.gzhead.comment.length?255&r.gzhead.comment.charCodeAt(r.gzindex++):0,k(r,l)}while(0!==l);r.gzhead.hcrc&&r.pending>a&&(e.adler=o(e.adler,r.pending_buf,r.pending-a,a)),0===l&&(r.status=103)}else r.status=103;if(103===r.status&&(r.gzhead.hcrc?(r.pending+2>r.pending_buf_size&&F(e),r.pending+2<=r.pending_buf_size&&(k(r,255&e.adler),k(r,e.adler>>8&255),e.adler=0,r.status=E)):r.status=E),0!==r.pending){if(F(e),0===e.avail_out)return r.last_flush=-1,u}else if(0===e.avail_in&&B(t)<=B(n)&&t!==h)return D(e,-5);if(666===r.status&&0!==e.avail_in)return D(e,-5);if(0!==e.avail_in||0!==r.lookahead||t!==c&&666!==r.status){var f=2===r.strategy?function(e,t){for(var n;;){if(0===e.lookahead&&(z(e),0===e.lookahead)){if(t===c)return C;break}if(e.match_length=0,n=s._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,n&&(U(e,!1),0===e.strm.avail_out))return C}return e.insert=0,t===h?(U(e,!0),0===e.strm.avail_out?I:P):e.last_lit&&(U(e,!1),0===e.strm.avail_out)?C:R}(r,t):3===r.strategy?function(e,t){for(var n,i,r,a,o=e.window;;){if(e.lookahead<=M){if(z(e),e.lookahead<=M&&t===c)return C;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=b&&0<e.strstart&&(i=o[r=e.strstart-1])===o[++r]&&i===o[++r]&&i===o[++r]){a=e.strstart+M;do{}while(i===o[++r]&&i===o[++r]&&i===o[++r]&&i===o[++r]&&i===o[++r]&&i===o[++r]&&i===o[++r]&&i===o[++r]&&r<a);e.match_length=M-(a-r),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=b?(n=s._tr_tally(e,1,e.match_length-b),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(n=s._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),n&&(U(e,!1),0===e.strm.avail_out))return C}return e.insert=0,t===h?(U(e,!0),0===e.strm.avail_out?I:P):e.last_lit&&(U(e,!1),0===e.strm.avail_out)?C:R}(r,t):i[r.level].func(r,t);if(f!==I&&f!==P||(r.status=666),f===C||f===I)return 0===e.avail_out&&(r.last_flush=-1),u;if(f===R&&(1===t?s._tr_align(r):5!==t&&(s._tr_stored_block(r,0,0,!1),3===t&&(L(r.head),0===r.lookahead&&(r.strstart=0,r.block_start=0,r.insert=0))),F(e),0===e.avail_out))return r.last_flush=-1,u}return t!==h?u:r.wrap<=0?1:(2===r.wrap?(k(r,255&e.adler),k(r,e.adler>>8&255),k(r,e.adler>>16&255),k(r,e.adler>>24&255),k(r,255&e.total_in),k(r,e.total_in>>8&255),k(r,e.total_in>>16&255),k(r,e.total_in>>24&255)):(N(r,e.adler>>>16),N(r,65535&e.adler)),F(e),0<r.wrap&&(r.wrap=-r.wrap),0!==r.pending?u:1)},n.deflateEnd=function(e){var t;return e&&e.state?(t=e.state.status)!==T&&69!==t&&73!==t&&91!==t&&103!==t&&t!==E&&666!==t?D(e,d):(e.state=null,t===E?D(e,-3):u):d},n.deflateSetDictionary=function(e,t){var n,i,s,o,l,c,h,p,f=t.length;if(!e||!e.state)return d;if(2===(o=(n=e.state).wrap)||1===o&&n.status!==T||n.lookahead)return d;for(1===o&&(e.adler=a(e.adler,t,f,0)),n.wrap=0,f>=n.w_size&&(0===o&&(L(n.head),n.strstart=0,n.block_start=0,n.insert=0),p=new r.Buf8(n.w_size),r.arraySet(p,t,f-n.w_size,n.w_size,0),t=p,f=n.w_size),l=e.avail_in,c=e.next_in,h=e.input,e.avail_in=f,e.next_in=0,e.input=t,z(n);n.lookahead>=b;){for(i=n.strstart,s=n.lookahead-(b-1);n.ins_h=(n.ins_h<<n.hash_shift^n.window[i+b-1])&n.hash_mask,n.prev[i&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=i,i++,--s;);n.strstart=i,n.lookahead=b-1,z(n)}return n.strstart+=n.lookahead,n.block_start=n.strstart,n.insert=n.lookahead,n.lookahead=0,n.match_length=n.prev_length=b-1,n.match_available=0,e.next_in=c,e.input=h,e.avail_in=l,n.wrap=o,u},n.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(e,t,n){t.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],48:[function(e,t,n){t.exports=function(e,t){var n,i,r,s,a,o,l,c,h,u,d,p,f,m,g,_,v,x,y,S,A,b,M,w,T;n=e.state,i=e.next_in,w=e.input,r=i+(e.avail_in-5),s=e.next_out,T=e.output,a=s-(t-e.avail_out),o=s+(e.avail_out-257),l=n.dmax,c=n.wsize,h=n.whave,u=n.wnext,d=n.window,p=n.hold,f=n.bits,m=n.lencode,g=n.distcode,_=(1<<n.lenbits)-1,v=(1<<n.distbits)-1;e:do{f<15&&(p+=w[i++]<<f,f+=8,p+=w[i++]<<f,f+=8),x=m[p&_];t:for(;;){if(p>>>=y=x>>>24,f-=y,0==(y=x>>>16&255))T[s++]=65535&x;else{if(!(16&y)){if(!(64&y)){x=m[(65535&x)+(p&(1<<y)-1)];continue t}if(32&y){n.mode=12;break e}e.msg="invalid literal/length code",n.mode=30;break e}S=65535&x,(y&=15)&&(f<y&&(p+=w[i++]<<f,f+=8),S+=p&(1<<y)-1,p>>>=y,f-=y),f<15&&(p+=w[i++]<<f,f+=8,p+=w[i++]<<f,f+=8),x=g[p&v];n:for(;;){if(p>>>=y=x>>>24,f-=y,!(16&(y=x>>>16&255))){if(!(64&y)){x=g[(65535&x)+(p&(1<<y)-1)];continue n}e.msg="invalid distance code",n.mode=30;break e}if(A=65535&x,f<(y&=15)&&(p+=w[i++]<<f,(f+=8)<y&&(p+=w[i++]<<f,f+=8)),l<(A+=p&(1<<y)-1)){e.msg="invalid distance too far back",n.mode=30;break e}if(p>>>=y,f-=y,(y=s-a)<A){if(h<(y=A-y)&&n.sane){e.msg="invalid distance too far back",n.mode=30;break e}if(M=d,(b=0)===u){if(b+=c-y,y<S){for(S-=y;T[s++]=d[b++],--y;);b=s-A,M=T}}else if(u<y){if(b+=c+u-y,(y-=u)<S){for(S-=y;T[s++]=d[b++],--y;);if(b=0,u<S){for(S-=y=u;T[s++]=d[b++],--y;);b=s-A,M=T}}}else if(b+=u-y,y<S){for(S-=y;T[s++]=d[b++],--y;);b=s-A,M=T}for(;2<S;)T[s++]=M[b++],T[s++]=M[b++],T[s++]=M[b++],S-=3;S&&(T[s++]=M[b++],1<S&&(T[s++]=M[b++]))}else{for(b=s-A;T[s++]=T[b++],T[s++]=T[b++],T[s++]=T[b++],2<(S-=3););S&&(T[s++]=T[b++],1<S&&(T[s++]=T[b++]))}break}}break}}while(i<r&&s<o);i-=S=f>>3,p&=(1<<(f-=S<<3))-1,e.next_in=i,e.next_out=s,e.avail_in=i<r?r-i+5:5-(i-r),e.avail_out=s<o?o-s+257:257-(s-o),n.hold=p,n.bits=f}},{}],49:[function(e,t,n){var i=e("../utils/common"),r=e("./adler32"),s=e("./crc32"),a=e("./inffast"),o=e("./inftrees"),l=1,c=2,h=0,u=-2,d=1,p=852,f=592;function m(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function g(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new i.Buf16(320),this.work=new i.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function _(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=d,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new i.Buf32(p),t.distcode=t.distdyn=new i.Buf32(f),t.sane=1,t.back=-1,h):u}function v(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,_(e)):u}function x(e,t){var n,i;return e&&e.state?(i=e.state,t<0?(n=0,t=-t):(n=1+(t>>4),t<48&&(t&=15)),t&&(t<8||15<t)?u:(null!==i.window&&i.wbits!==t&&(i.window=null),i.wrap=n,i.wbits=t,v(e))):u}function y(e,t){var n,i;return e?(i=new g,(e.state=i).window=null,(n=x(e,t))!==h&&(e.state=null),n):u}var S,A,b=!0;function M(e){if(b){var t;for(S=new i.Buf32(512),A=new i.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(o(l,e.lens,0,288,S,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;o(c,e.lens,0,32,A,0,e.work,{bits:5}),b=!1}e.lencode=S,e.lenbits=9,e.distcode=A,e.distbits=5}function w(e,t,n,r){var s,a=e.state;return null===a.window&&(a.wsize=1<<a.wbits,a.wnext=0,a.whave=0,a.window=new i.Buf8(a.wsize)),r>=a.wsize?(i.arraySet(a.window,t,n-a.wsize,a.wsize,0),a.wnext=0,a.whave=a.wsize):(r<(s=a.wsize-a.wnext)&&(s=r),i.arraySet(a.window,t,n-r,s,a.wnext),(r-=s)?(i.arraySet(a.window,t,n-r,r,0),a.wnext=r,a.whave=a.wsize):(a.wnext+=s,a.wnext===a.wsize&&(a.wnext=0),a.whave<a.wsize&&(a.whave+=s))),0}n.inflateReset=v,n.inflateReset2=x,n.inflateResetKeep=_,n.inflateInit=function(e){return y(e,15)},n.inflateInit2=y,n.inflate=function(e,t){var n,p,f,g,_,v,x,y,S,A,b,T,E,C,R,I,P,D,B,L,F,U,k,N,O=0,z=new i.Buf8(4),H=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&0!==e.avail_in)return u;12===(n=e.state).mode&&(n.mode=13),_=e.next_out,f=e.output,x=e.avail_out,g=e.next_in,p=e.input,v=e.avail_in,y=n.hold,S=n.bits,A=v,b=x,U=h;e:for(;;)switch(n.mode){case d:if(0===n.wrap){n.mode=13;break}for(;S<16;){if(0===v)break e;v--,y+=p[g++]<<S,S+=8}if(2&n.wrap&&35615===y){z[n.check=0]=255&y,z[1]=y>>>8&255,n.check=s(n.check,z,2,0),S=y=0,n.mode=2;break}if(n.flags=0,n.head&&(n.head.done=!1),!(1&n.wrap)||(((255&y)<<8)+(y>>8))%31){e.msg="incorrect header check",n.mode=30;break}if(8!=(15&y)){e.msg="unknown compression method",n.mode=30;break}if(S-=4,F=8+(15&(y>>>=4)),0===n.wbits)n.wbits=F;else if(F>n.wbits){e.msg="invalid window size",n.mode=30;break}n.dmax=1<<F,e.adler=n.check=1,n.mode=512&y?10:12,S=y=0;break;case 2:for(;S<16;){if(0===v)break e;v--,y+=p[g++]<<S,S+=8}if(n.flags=y,8!=(255&n.flags)){e.msg="unknown compression method",n.mode=30;break}if(57344&n.flags){e.msg="unknown header flags set",n.mode=30;break}n.head&&(n.head.text=y>>8&1),512&n.flags&&(z[0]=255&y,z[1]=y>>>8&255,n.check=s(n.check,z,2,0)),S=y=0,n.mode=3;case 3:for(;S<32;){if(0===v)break e;v--,y+=p[g++]<<S,S+=8}n.head&&(n.head.time=y),512&n.flags&&(z[0]=255&y,z[1]=y>>>8&255,z[2]=y>>>16&255,z[3]=y>>>24&255,n.check=s(n.check,z,4,0)),S=y=0,n.mode=4;case 4:for(;S<16;){if(0===v)break e;v--,y+=p[g++]<<S,S+=8}n.head&&(n.head.xflags=255&y,n.head.os=y>>8),512&n.flags&&(z[0]=255&y,z[1]=y>>>8&255,n.check=s(n.check,z,2,0)),S=y=0,n.mode=5;case 5:if(1024&n.flags){for(;S<16;){if(0===v)break e;v--,y+=p[g++]<<S,S+=8}n.length=y,n.head&&(n.head.extra_len=y),512&n.flags&&(z[0]=255&y,z[1]=y>>>8&255,n.check=s(n.check,z,2,0)),S=y=0}else n.head&&(n.head.extra=null);n.mode=6;case 6:if(1024&n.flags&&(v<(T=n.length)&&(T=v),T&&(n.head&&(F=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Array(n.head.extra_len)),i.arraySet(n.head.extra,p,g,T,F)),512&n.flags&&(n.check=s(n.check,p,T,g)),v-=T,g+=T,n.length-=T),n.length))break e;n.length=0,n.mode=7;case 7:if(2048&n.flags){if(0===v)break e;for(T=0;F=p[g+T++],n.head&&F&&n.length<65536&&(n.head.name+=String.fromCharCode(F)),F&&T<v;);if(512&n.flags&&(n.check=s(n.check,p,T,g)),v-=T,g+=T,F)break e}else n.head&&(n.head.name=null);n.length=0,n.mode=8;case 8:if(4096&n.flags){if(0===v)break e;for(T=0;F=p[g+T++],n.head&&F&&n.length<65536&&(n.head.comment+=String.fromCharCode(F)),F&&T<v;);if(512&n.flags&&(n.check=s(n.check,p,T,g)),v-=T,g+=T,F)break e}else n.head&&(n.head.comment=null);n.mode=9;case 9:if(512&n.flags){for(;S<16;){if(0===v)break e;v--,y+=p[g++]<<S,S+=8}if(y!==(65535&n.check)){e.msg="header crc mismatch",n.mode=30;break}S=y=0}n.head&&(n.head.hcrc=n.flags>>9&1,n.head.done=!0),e.adler=n.check=0,n.mode=12;break;case 10:for(;S<32;){if(0===v)break e;v--,y+=p[g++]<<S,S+=8}e.adler=n.check=m(y),S=y=0,n.mode=11;case 11:if(0===n.havedict)return e.next_out=_,e.avail_out=x,e.next_in=g,e.avail_in=v,n.hold=y,n.bits=S,2;e.adler=n.check=1,n.mode=12;case 12:if(5===t||6===t)break e;case 13:if(n.last){y>>>=7&S,S-=7&S,n.mode=27;break}for(;S<3;){if(0===v)break e;v--,y+=p[g++]<<S,S+=8}switch(n.last=1&y,S-=1,3&(y>>>=1)){case 0:n.mode=14;break;case 1:if(M(n),n.mode=20,6!==t)break;y>>>=2,S-=2;break e;case 2:n.mode=17;break;case 3:e.msg="invalid block type",n.mode=30}y>>>=2,S-=2;break;case 14:for(y>>>=7&S,S-=7&S;S<32;){if(0===v)break e;v--,y+=p[g++]<<S,S+=8}if((65535&y)!=(y>>>16^65535)){e.msg="invalid stored block lengths",n.mode=30;break}if(n.length=65535&y,S=y=0,n.mode=15,6===t)break e;case 15:n.mode=16;case 16:if(T=n.length){if(v<T&&(T=v),x<T&&(T=x),0===T)break e;i.arraySet(f,p,g,T,_),v-=T,g+=T,x-=T,_+=T,n.length-=T;break}n.mode=12;break;case 17:for(;S<14;){if(0===v)break e;v--,y+=p[g++]<<S,S+=8}if(n.nlen=257+(31&y),y>>>=5,S-=5,n.ndist=1+(31&y),y>>>=5,S-=5,n.ncode=4+(15&y),y>>>=4,S-=4,286<n.nlen||30<n.ndist){e.msg="too many length or distance symbols",n.mode=30;break}n.have=0,n.mode=18;case 18:for(;n.have<n.ncode;){for(;S<3;){if(0===v)break e;v--,y+=p[g++]<<S,S+=8}n.lens[H[n.have++]]=7&y,y>>>=3,S-=3}for(;n.have<19;)n.lens[H[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,k={bits:n.lenbits},U=o(0,n.lens,0,19,n.lencode,0,n.work,k),n.lenbits=k.bits,U){e.msg="invalid code lengths set",n.mode=30;break}n.have=0,n.mode=19;case 19:for(;n.have<n.nlen+n.ndist;){for(;I=(O=n.lencode[y&(1<<n.lenbits)-1])>>>16&255,P=65535&O,!((R=O>>>24)<=S);){if(0===v)break e;v--,y+=p[g++]<<S,S+=8}if(P<16)y>>>=R,S-=R,n.lens[n.have++]=P;else{if(16===P){for(N=R+2;S<N;){if(0===v)break e;v--,y+=p[g++]<<S,S+=8}if(y>>>=R,S-=R,0===n.have){e.msg="invalid bit length repeat",n.mode=30;break}F=n.lens[n.have-1],T=3+(3&y),y>>>=2,S-=2}else if(17===P){for(N=R+3;S<N;){if(0===v)break e;v--,y+=p[g++]<<S,S+=8}S-=R,F=0,T=3+(7&(y>>>=R)),y>>>=3,S-=3}else{for(N=R+7;S<N;){if(0===v)break e;v--,y+=p[g++]<<S,S+=8}S-=R,F=0,T=11+(127&(y>>>=R)),y>>>=7,S-=7}if(n.have+T>n.nlen+n.ndist){e.msg="invalid bit length repeat",n.mode=30;break}for(;T--;)n.lens[n.have++]=F}}if(30===n.mode)break;if(0===n.lens[256]){e.msg="invalid code -- missing end-of-block",n.mode=30;break}if(n.lenbits=9,k={bits:n.lenbits},U=o(l,n.lens,0,n.nlen,n.lencode,0,n.work,k),n.lenbits=k.bits,U){e.msg="invalid literal/lengths set",n.mode=30;break}if(n.distbits=6,n.distcode=n.distdyn,k={bits:n.distbits},U=o(c,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,k),n.distbits=k.bits,U){e.msg="invalid distances set",n.mode=30;break}if(n.mode=20,6===t)break e;case 20:n.mode=21;case 21:if(6<=v&&258<=x){e.next_out=_,e.avail_out=x,e.next_in=g,e.avail_in=v,n.hold=y,n.bits=S,a(e,b),_=e.next_out,f=e.output,x=e.avail_out,g=e.next_in,p=e.input,v=e.avail_in,y=n.hold,S=n.bits,12===n.mode&&(n.back=-1);break}for(n.back=0;I=(O=n.lencode[y&(1<<n.lenbits)-1])>>>16&255,P=65535&O,!((R=O>>>24)<=S);){if(0===v)break e;v--,y+=p[g++]<<S,S+=8}if(I&&!(240&I)){for(D=R,B=I,L=P;I=(O=n.lencode[L+((y&(1<<D+B)-1)>>D)])>>>16&255,P=65535&O,!(D+(R=O>>>24)<=S);){if(0===v)break e;v--,y+=p[g++]<<S,S+=8}y>>>=D,S-=D,n.back+=D}if(y>>>=R,S-=R,n.back+=R,n.length=P,0===I){n.mode=26;break}if(32&I){n.back=-1,n.mode=12;break}if(64&I){e.msg="invalid literal/length code",n.mode=30;break}n.extra=15&I,n.mode=22;case 22:if(n.extra){for(N=n.extra;S<N;){if(0===v)break e;v--,y+=p[g++]<<S,S+=8}n.length+=y&(1<<n.extra)-1,y>>>=n.extra,S-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=23;case 23:for(;I=(O=n.distcode[y&(1<<n.distbits)-1])>>>16&255,P=65535&O,!((R=O>>>24)<=S);){if(0===v)break e;v--,y+=p[g++]<<S,S+=8}if(!(240&I)){for(D=R,B=I,L=P;I=(O=n.distcode[L+((y&(1<<D+B)-1)>>D)])>>>16&255,P=65535&O,!(D+(R=O>>>24)<=S);){if(0===v)break e;v--,y+=p[g++]<<S,S+=8}y>>>=D,S-=D,n.back+=D}if(y>>>=R,S-=R,n.back+=R,64&I){e.msg="invalid distance code",n.mode=30;break}n.offset=P,n.extra=15&I,n.mode=24;case 24:if(n.extra){for(N=n.extra;S<N;){if(0===v)break e;v--,y+=p[g++]<<S,S+=8}n.offset+=y&(1<<n.extra)-1,y>>>=n.extra,S-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){e.msg="invalid distance too far back",n.mode=30;break}n.mode=25;case 25:if(0===x)break e;if(T=b-x,n.offset>T){if((T=n.offset-T)>n.whave&&n.sane){e.msg="invalid distance too far back",n.mode=30;break}E=T>n.wnext?(T-=n.wnext,n.wsize-T):n.wnext-T,T>n.length&&(T=n.length),C=n.window}else C=f,E=_-n.offset,T=n.length;for(x<T&&(T=x),x-=T,n.length-=T;f[_++]=C[E++],--T;);0===n.length&&(n.mode=21);break;case 26:if(0===x)break e;f[_++]=n.length,x--,n.mode=21;break;case 27:if(n.wrap){for(;S<32;){if(0===v)break e;v--,y|=p[g++]<<S,S+=8}if(b-=x,e.total_out+=b,n.total+=b,b&&(e.adler=n.check=n.flags?s(n.check,f,b,_-b):r(n.check,f,b,_-b)),b=x,(n.flags?y:m(y))!==n.check){e.msg="incorrect data check",n.mode=30;break}S=y=0}n.mode=28;case 28:if(n.wrap&&n.flags){for(;S<32;){if(0===v)break e;v--,y+=p[g++]<<S,S+=8}if(y!==(4294967295&n.total)){e.msg="incorrect length check",n.mode=30;break}S=y=0}n.mode=29;case 29:U=1;break e;case 30:U=-3;break e;case 31:return-4;default:return u}return e.next_out=_,e.avail_out=x,e.next_in=g,e.avail_in=v,n.hold=y,n.bits=S,(n.wsize||b!==e.avail_out&&n.mode<30&&(n.mode<27||4!==t))&&w(e,e.output,e.next_out,b-e.avail_out)?(n.mode=31,-4):(A-=e.avail_in,b-=e.avail_out,e.total_in+=A,e.total_out+=b,n.total+=b,n.wrap&&b&&(e.adler=n.check=n.flags?s(n.check,f,b,e.next_out-b):r(n.check,f,b,e.next_out-b)),e.data_type=n.bits+(n.last?64:0)+(12===n.mode?128:0)+(20===n.mode||15===n.mode?256:0),(0==A&&0===b||4===t)&&U===h&&(U=-5),U)},n.inflateEnd=function(e){if(!e||!e.state)return u;var t=e.state;return t.window&&(t.window=null),e.state=null,h},n.inflateGetHeader=function(e,t){var n;return e&&e.state&&2&(n=e.state).wrap?((n.head=t).done=!1,h):u},n.inflateSetDictionary=function(e,t){var n,i=t.length;return e&&e.state?0!==(n=e.state).wrap&&11!==n.mode?u:11===n.mode&&r(1,t,i,0)!==n.check?-3:w(e,t,i,i)?(n.mode=31,-4):(n.havedict=1,h):u},n.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(e,t,n){var i=e("../utils/common"),r=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],s=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],a=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],o=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];t.exports=function(e,t,n,l,c,h,u,d){var p,f,m,g,_,v,x,y,S,A=d.bits,b=0,M=0,w=0,T=0,E=0,C=0,R=0,I=0,P=0,D=0,B=null,L=0,F=new i.Buf16(16),U=new i.Buf16(16),k=null,N=0;for(b=0;b<=15;b++)F[b]=0;for(M=0;M<l;M++)F[t[n+M]]++;for(E=A,T=15;1<=T&&0===F[T];T--);if(T<E&&(E=T),0===T)return c[h++]=20971520,c[h++]=20971520,d.bits=1,0;for(w=1;w<T&&0===F[w];w++);for(E<w&&(E=w),b=I=1;b<=15;b++)if(I<<=1,(I-=F[b])<0)return-1;if(0<I&&(0===e||1!==T))return-1;for(U[1]=0,b=1;b<15;b++)U[b+1]=U[b]+F[b];for(M=0;M<l;M++)0!==t[n+M]&&(u[U[t[n+M]]++]=M);if(v=0===e?(B=k=u,19):1===e?(B=r,L-=257,k=s,N-=257,256):(B=a,k=o,-1),b=w,_=h,R=M=D=0,m=-1,g=(P=1<<(C=E))-1,1===e&&852<P||2===e&&592<P)return 1;for(;;){for(x=b-R,S=u[M]<v?(y=0,u[M]):u[M]>v?(y=k[N+u[M]],B[L+u[M]]):(y=96,0),p=1<<b-R,w=f=1<<C;c[_+(D>>R)+(f-=p)]=x<<24|y<<16|S,0!==f;);for(p=1<<b-1;D&p;)p>>=1;if(0!==p?(D&=p-1,D+=p):D=0,M++,0==--F[b]){if(b===T)break;b=t[n+u[M]]}if(E<b&&(D&g)!==m){for(0===R&&(R=E),_+=w,I=1<<(C=b-R);C+R<T&&!((I-=F[C+R])<=0);)C++,I<<=1;if(P+=1<<C,1===e&&852<P||2===e&&592<P)return 1;c[m=D&g]=E<<24|C<<16|_-h}}return 0!==D&&(c[_+D]=b-R<<24|64<<16),d.bits=E,0}},{"../utils/common":41}],51:[function(e,t,n){t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],52:[function(e,t,n){var i=e("../utils/common"),r=0,s=1;function a(e){for(var t=e.length;0<=--t;)e[t]=0}var o=0,l=29,c=256,h=c+1+l,u=30,d=19,p=2*h+1,f=15,m=16,g=7,_=256,v=16,x=17,y=18,S=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],A=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],b=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],M=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],w=new Array(2*(h+2));a(w);var T=new Array(2*u);a(T);var E=new Array(512);a(E);var C=new Array(256);a(C);var R=new Array(l);a(R);var I,P,D,B=new Array(u);function L(e,t,n,i,r){this.static_tree=e,this.extra_bits=t,this.extra_base=n,this.elems=i,this.max_length=r,this.has_stree=e&&e.length}function F(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function U(e){return e<256?E[e]:E[256+(e>>>7)]}function k(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255}function N(e,t,n){e.bi_valid>m-n?(e.bi_buf|=t<<e.bi_valid&65535,k(e,e.bi_buf),e.bi_buf=t>>m-e.bi_valid,e.bi_valid+=n-m):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=n)}function O(e,t,n){N(e,n[2*t],n[2*t+1])}function z(e,t){for(var n=0;n|=1&e,e>>>=1,n<<=1,0<--t;);return n>>>1}function H(e,t,n){var i,r,s=new Array(f+1),a=0;for(i=1;i<=f;i++)s[i]=a=a+n[i-1]<<1;for(r=0;r<=t;r++){var o=e[2*r+1];0!==o&&(e[2*r]=z(s[o]++,o))}}function V(e){var t;for(t=0;t<h;t++)e.dyn_ltree[2*t]=0;for(t=0;t<u;t++)e.dyn_dtree[2*t]=0;for(t=0;t<d;t++)e.bl_tree[2*t]=0;e.dyn_ltree[2*_]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0}function G(e){8<e.bi_valid?k(e,e.bi_buf):0<e.bi_valid&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function W(e,t,n,i){var r=2*t,s=2*n;return e[r]<e[s]||e[r]===e[s]&&i[t]<=i[n]}function j(e,t,n){for(var i=e.heap[n],r=n<<1;r<=e.heap_len&&(r<e.heap_len&&W(t,e.heap[r+1],e.heap[r],e.depth)&&r++,!W(t,i,e.heap[r],e.depth));)e.heap[n]=e.heap[r],n=r,r<<=1;e.heap[n]=i}function X(e,t,n){var i,r,s,a,o=0;if(0!==e.last_lit)for(;i=e.pending_buf[e.d_buf+2*o]<<8|e.pending_buf[e.d_buf+2*o+1],r=e.pending_buf[e.l_buf+o],o++,0===i?O(e,r,t):(O(e,(s=C[r])+c+1,t),0!==(a=S[s])&&N(e,r-=R[s],a),O(e,s=U(--i),n),0!==(a=A[s])&&N(e,i-=B[s],a)),o<e.last_lit;);O(e,_,t)}function q(e,t){var n,i,r,s=t.dyn_tree,a=t.stat_desc.static_tree,o=t.stat_desc.has_stree,l=t.stat_desc.elems,c=-1;for(e.heap_len=0,e.heap_max=p,n=0;n<l;n++)0!==s[2*n]?(e.heap[++e.heap_len]=c=n,e.depth[n]=0):s[2*n+1]=0;for(;e.heap_len<2;)s[2*(r=e.heap[++e.heap_len]=c<2?++c:0)]=1,e.depth[r]=0,e.opt_len--,o&&(e.static_len-=a[2*r+1]);for(t.max_code=c,n=e.heap_len>>1;1<=n;n--)j(e,s,n);for(r=l;n=e.heap[1],e.heap[1]=e.heap[e.heap_len--],j(e,s,1),i=e.heap[1],e.heap[--e.heap_max]=n,e.heap[--e.heap_max]=i,s[2*r]=s[2*n]+s[2*i],e.depth[r]=(e.depth[n]>=e.depth[i]?e.depth[n]:e.depth[i])+1,s[2*n+1]=s[2*i+1]=r,e.heap[1]=r++,j(e,s,1),2<=e.heap_len;);e.heap[--e.heap_max]=e.heap[1],function(e,t){var n,i,r,s,a,o,l=t.dyn_tree,c=t.max_code,h=t.stat_desc.static_tree,u=t.stat_desc.has_stree,d=t.stat_desc.extra_bits,m=t.stat_desc.extra_base,g=t.stat_desc.max_length,_=0;for(s=0;s<=f;s++)e.bl_count[s]=0;for(l[2*e.heap[e.heap_max]+1]=0,n=e.heap_max+1;n<p;n++)g<(s=l[2*l[2*(i=e.heap[n])+1]+1]+1)&&(s=g,_++),l[2*i+1]=s,c<i||(e.bl_count[s]++,a=0,m<=i&&(a=d[i-m]),o=l[2*i],e.opt_len+=o*(s+a),u&&(e.static_len+=o*(h[2*i+1]+a)));if(0!==_){do{for(s=g-1;0===e.bl_count[s];)s--;e.bl_count[s]--,e.bl_count[s+1]+=2,e.bl_count[g]--,_-=2}while(0<_);for(s=g;0!==s;s--)for(i=e.bl_count[s];0!==i;)c<(r=e.heap[--n])||(l[2*r+1]!==s&&(e.opt_len+=(s-l[2*r+1])*l[2*r],l[2*r+1]=s),i--)}}(e,t),H(s,c,e.bl_count)}function Q(e,t,n){var i,r,s=-1,a=t[1],o=0,l=7,c=4;for(0===a&&(l=138,c=3),t[2*(n+1)+1]=65535,i=0;i<=n;i++)r=a,a=t[2*(i+1)+1],++o<l&&r===a||(o<c?e.bl_tree[2*r]+=o:0!==r?(r!==s&&e.bl_tree[2*r]++,e.bl_tree[2*v]++):o<=10?e.bl_tree[2*x]++:e.bl_tree[2*y]++,s=r,c=(o=0)===a?(l=138,3):r===a?(l=6,3):(l=7,4))}function K(e,t,n){var i,r,s=-1,a=t[1],o=0,l=7,c=4;for(0===a&&(l=138,c=3),i=0;i<=n;i++)if(r=a,a=t[2*(i+1)+1],!(++o<l&&r===a)){if(o<c)for(;O(e,r,e.bl_tree),0!=--o;);else 0!==r?(r!==s&&(O(e,r,e.bl_tree),o--),O(e,v,e.bl_tree),N(e,o-3,2)):o<=10?(O(e,x,e.bl_tree),N(e,o-3,3)):(O(e,y,e.bl_tree),N(e,o-11,7));s=r,c=(o=0)===a?(l=138,3):r===a?(l=6,3):(l=7,4)}}a(B);var Y=!1;function Z(e,t,n,r){var s,a,l;N(e,(o<<1)+(r?1:0),3),a=t,l=n,G(s=e),k(s,l),k(s,~l),i.arraySet(s.pending_buf,s.window,a,l,s.pending),s.pending+=l}n._tr_init=function(e){Y||(function(){var e,t,n,i,r,s=new Array(f+1);for(i=n=0;i<l-1;i++)for(R[i]=n,e=0;e<1<<S[i];e++)C[n++]=i;for(C[n-1]=i,i=r=0;i<16;i++)for(B[i]=r,e=0;e<1<<A[i];e++)E[r++]=i;for(r>>=7;i<u;i++)for(B[i]=r<<7,e=0;e<1<<A[i]-7;e++)E[256+r++]=i;for(t=0;t<=f;t++)s[t]=0;for(e=0;e<=143;)w[2*e+1]=8,e++,s[8]++;for(;e<=255;)w[2*e+1]=9,e++,s[9]++;for(;e<=279;)w[2*e+1]=7,e++,s[7]++;for(;e<=287;)w[2*e+1]=8,e++,s[8]++;for(H(w,h+1,s),e=0;e<u;e++)T[2*e+1]=5,T[2*e]=z(e,5);I=new L(w,S,c+1,h,f),P=new L(T,A,0,u,f),D=new L(new Array(0),b,0,d,g)}(),Y=!0),e.l_desc=new F(e.dyn_ltree,I),e.d_desc=new F(e.dyn_dtree,P),e.bl_desc=new F(e.bl_tree,D),e.bi_buf=0,e.bi_valid=0,V(e)},n._tr_stored_block=Z,n._tr_flush_block=function(e,t,n,i){var a,o,l=0;0<e.level?(2===e.strm.data_type&&(e.strm.data_type=function(e){var t,n=4093624447;for(t=0;t<=31;t++,n>>>=1)if(1&n&&0!==e.dyn_ltree[2*t])return r;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return s;for(t=32;t<c;t++)if(0!==e.dyn_ltree[2*t])return s;return r}(e)),q(e,e.l_desc),q(e,e.d_desc),l=function(e){var t;for(Q(e,e.dyn_ltree,e.l_desc.max_code),Q(e,e.dyn_dtree,e.d_desc.max_code),q(e,e.bl_desc),t=d-1;3<=t&&0===e.bl_tree[2*M[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}(e),a=e.opt_len+3+7>>>3,(o=e.static_len+3+7>>>3)<=a&&(a=o)):a=o=n+5,n+4<=a&&-1!==t?Z(e,t,n,i):4===e.strategy||o===a?(N(e,2+(i?1:0),3),X(e,w,T)):(N(e,4+(i?1:0),3),function(e,t,n,i){var r;for(N(e,t-257,5),N(e,n-1,5),N(e,i-4,4),r=0;r<i;r++)N(e,e.bl_tree[2*M[r]+1],3);K(e,e.dyn_ltree,t-1),K(e,e.dyn_dtree,n-1)}(e,e.l_desc.max_code+1,e.d_desc.max_code+1,l+1),X(e,e.dyn_ltree,e.dyn_dtree)),V(e),i&&G(e)},n._tr_tally=function(e,t,n){return e.pending_buf[e.d_buf+2*e.last_lit]=t>>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&n,e.last_lit++,0===t?e.dyn_ltree[2*n]++:(e.matches++,t--,e.dyn_ltree[2*(C[n]+c+1)]++,e.dyn_dtree[2*U(t)]++),e.last_lit===e.lit_bufsize-1},n._tr_align=function(e){var t;N(e,2,3),O(e,_,w),16===(t=e).bi_valid?(k(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):8<=t.bi_valid&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)}},{"../utils/common":41}],53:[function(e,t,n){t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(e,t,n){(function(e){!function(e,t){if(!e.setImmediate){var n,i,r,s,a=1,o={},l=!1,c=e.document,h=Object.getPrototypeOf&&Object.getPrototypeOf(e);h=h&&h.setTimeout?h:e,n="[object process]"==={}.toString.call(e.process)?function(e){process.nextTick(function(){d(e)})}:function(){if(e.postMessage&&!e.importScripts){var t=!0,n=e.onmessage;return e.onmessage=function(){t=!1},e.postMessage("","*"),e.onmessage=n,t}}()?(s="setImmediate$"+Math.random()+"$",e.addEventListener?e.addEventListener("message",p,!1):e.attachEvent("onmessage",p),function(t){e.postMessage(s+t,"*")}):e.MessageChannel?((r=new MessageChannel).port1.onmessage=function(e){d(e.data)},function(e){r.port2.postMessage(e)}):c&&"onreadystatechange"in c.createElement("script")?(i=c.documentElement,function(e){var t=c.createElement("script");t.onreadystatechange=function(){d(e),t.onreadystatechange=null,i.removeChild(t),t=null},i.appendChild(t)}):function(e){setTimeout(d,0,e)},h.setImmediate=function(e){"function"!=typeof e&&(e=new Function(""+e));for(var t=new Array(arguments.length-1),i=0;i<t.length;i++)t[i]=arguments[i+1];var r={callback:e,args:t};return o[a]=r,n(a),a++},h.clearImmediate=u}function u(e){delete o[e]}function d(e){if(l)setTimeout(d,0,e);else{var n=o[e];if(n){l=!0;try{!function(e){var n=e.callback,i=e.args;switch(i.length){case 0:n();break;case 1:n(i[0]);break;case 2:n(i[0],i[1]);break;case 3:n(i[0],i[1],i[2]);break;default:n.apply(t,i)}}(n)}finally{u(e),l=!1}}}}function p(t){t.source===e&&"string"==typeof t.data&&0===t.data.indexOf(s)&&d(+t.data.slice(s.length))}}("undefined"==typeof self?void 0===e?this:e:self)}).call(this,void 0!==ud?ud:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}]},{},[10])(10);const md=dd(fd.exports),gd={type:"change"},_d={type:"start"},vd={type:"end"},xd=new ar,yd=new Ia,Sd=Math.cos(70*oi.DEG2RAD),Ad=new hi,bd=2*Math.PI,Md=-1,wd=0,Td=1,Ed=2,Cd=3,Rd=4,Id=5,Pd=6,Dd=1e-6;class Bd extends gl{constructor(e,t=null){super(e,t),this.state=Md,this.target=new hi,this.cursor=new hi,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:ie,MIDDLE:re,RIGHT:se},this.touches={ONE:ae,TWO:le},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this._lastPosition=new hi,this._lastQuaternion=new ci,this._lastTargetPosition=new hi,this._quat=(new ci).setFromUnitVectors(e.up,new hi(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new ml,this._sphericalDelta=new ml,this._scale=1,this._panOffset=new hi,this._rotateStart=new li,this._rotateEnd=new li,this._rotateDelta=new li,this._panStart=new li,this._panEnd=new li,this._panDelta=new li,this._dollyStart=new li,this._dollyEnd=new li,this._dollyDelta=new li,this._dollyDirection=new hi,this._mouse=new li,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=Fd.bind(this),this._onPointerDown=Ld.bind(this),this._onPointerUp=Ud.bind(this),this._onContextMenu=Gd.bind(this),this._onMouseWheel=Od.bind(this),this._onKeyDown=zd.bind(this),this._onTouchStart=Hd.bind(this),this._onTouchMove=Vd.bind(this),this._onMouseDown=kd.bind(this),this._onMouseMove=Nd.bind(this),this._interceptControlDown=Wd.bind(this),this._interceptControlUp=jd.bind(this),null!==this.domElement&&this.connect(this.domElement),this.update()}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(){null!==this._domElementKeyEvents&&(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(gd),this.update(),this.state=Md}update(e=null){const t=this.object.position;Ad.copy(t).sub(this.target),Ad.applyQuaternion(this._quat),this._spherical.setFromVector3(Ad),this.autoRotate&&this.state===Md&&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 n=this.minAzimuthAngle,i=this.maxAzimuthAngle;isFinite(n)&&isFinite(i)&&(n<-Math.PI?n+=bd:n>Math.PI&&(n-=bd),i<-Math.PI?i+=bd:i>Math.PI&&(i-=bd),this._spherical.theta=n<=i?Math.max(n,Math.min(i,this._spherical.theta)):this._spherical.theta>(n+i)/2?Math.max(n,this._spherical.theta):Math.min(i,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),!0===this.enableDamping?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 e=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),r=e!=this._spherical.radius}if(Ad.setFromSpherical(this._spherical),Ad.applyQuaternion(this._quatInverse),t.copy(this.target).add(Ad),this.object.lookAt(this.target),!0===this.enableDamping?(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 e=null;if(this.object.isPerspectiveCamera){const t=Ad.length();e=this._clampDistance(t*this._scale);const n=t-e;this.object.position.addScaledVector(this._dollyDirection,n),this.object.updateMatrixWorld(),r=!!n}else if(this.object.isOrthographicCamera){const t=new hi(this._mouse.x,this._mouse.y,0);t.unproject(this.object);const n=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),r=n!==this.object.zoom;const i=new hi(this._mouse.x,this._mouse.y,0);i.unproject(this.object),this.object.position.sub(i).add(t),this.object.updateMatrixWorld(),e=Ad.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;null!==e&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(e).add(this.object.position):(xd.origin.copy(this.object.position),xd.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(xd.direction))<Sd?this.object.lookAt(this.target):(yd.setFromNormalAndCoplanarPoint(this.object.up,this.target),xd.intersectPlane(yd,this.target))))}else if(this.object.isOrthographicCamera){const e=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),e!==this.object.zoom&&(this.object.updateProjectionMatrix(),r=!0)}return this._scale=1,this._performCursorZoom=!1,!!(r||this._lastPosition.distanceToSquared(this.object.position)>Dd||8*(1-this._lastQuaternion.dot(this.object.quaternion))>Dd||this._lastTargetPosition.distanceToSquared(this.target)>Dd)&&(this.dispatchEvent(gd),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0)}_getAutoRotationAngle(e){return null!==e?bd/60*this.autoRotateSpeed*e:bd/60/60*this.autoRotateSpeed}_getZoomScale(e){const t=Math.abs(.01*e);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){Ad.setFromMatrixColumn(t,0),Ad.multiplyScalar(-e),this._panOffset.add(Ad)}_panUp(e,t){!0===this.screenSpacePanning?Ad.setFromMatrixColumn(t,1):(Ad.setFromMatrixColumn(t,0),Ad.crossVectors(this.object.up,Ad)),Ad.multiplyScalar(e),this._panOffset.add(Ad)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const i=this.object.position;Ad.copy(i).sub(this.target);let r=Ad.length();r*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*r/n.clientHeight,this.object.matrix),this._panUp(2*t*r/n.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/n.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/n.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 n=this.domElement.getBoundingClientRect(),i=e-n.left,r=t-n.top,s=n.width,a=n.height;this._mouse.x=i/s*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(bd*this._rotateDelta.x/t.clientHeight),this._rotateUp(bd*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(bd*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(-bd*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(bd*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(-bd*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(1===this._pointers.length)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._rotateStart.set(n,i)}}_handleTouchStartPan(e){if(1===this._pointers.length)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panStart.set(n,i)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,i=e.pageY-t.y,r=Math.sqrt(n*n+i*i);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(1==this._pointers.length)this._rotateEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._rotateEnd.set(n,i)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(bd*this._rotateDelta.x/t.clientHeight),this._rotateUp(bd*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(1===this._pointers.length)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panEnd.set(n,i)}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),n=e.pageX-t.x,i=e.pageY-t.y,r=Math.sqrt(n*n+i*i);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 s=.5*(e.pageX+t.x),a=.5*(e.pageY+t.y);this._updateZoomParameters(s,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)return void this._pointers.splice(t,1)}_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];void 0===t&&(t=new li,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,n={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:n.deltaY*=16;break;case 2:n.deltaY*=100}return e.ctrlKey&&!this._controlActive&&(n.deltaY*=10),n}}function Ld(e){!1!==this.enabled&&(0===this._pointers.length&&(this.domElement.setPointerCapture(e.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp)),this._isTrackingPointer(e)||(this._addPointer(e),"touch"===e.pointerType?this._onTouchStart(e):this._onMouseDown(e)))}function Fd(e){!1!==this.enabled&&("touch"===e.pointerType?this._onTouchMove(e):this._onMouseMove(e))}function Ud(e){switch(this._removePointer(e),this._pointers.length){case 0:this.domElement.releasePointerCapture(e.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(vd),this.state=Md;break;case 1:const t=this._pointers[0],n=this._pointerPositions[t];this._onTouchStart({pointerId:t,pageX:n.x,pageY:n.y})}}function kd(e){let t;switch(e.button){case 0:t=this.mouseButtons.LEFT;break;case 1:t=this.mouseButtons.MIDDLE;break;case 2:t=this.mouseButtons.RIGHT;break;default:t=-1}switch(t){case re:if(!1===this.enableZoom)return;this._handleMouseDownDolly(e),this.state=Td;break;case ie:if(e.ctrlKey||e.metaKey||e.shiftKey){if(!1===this.enablePan)return;this._handleMouseDownPan(e),this.state=Ed}else{if(!1===this.enableRotate)return;this._handleMouseDownRotate(e),this.state=wd}break;case se:if(e.ctrlKey||e.metaKey||e.shiftKey){if(!1===this.enableRotate)return;this._handleMouseDownRotate(e),this.state=wd}else{if(!1===this.enablePan)return;this._handleMouseDownPan(e),this.state=Ed}break;default:this.state=Md}this.state!==Md&&this.dispatchEvent(_d)}function Nd(e){switch(this.state){case wd:if(!1===this.enableRotate)return;this._handleMouseMoveRotate(e);break;case Td:if(!1===this.enableZoom)return;this._handleMouseMoveDolly(e);break;case Ed:if(!1===this.enablePan)return;this._handleMouseMovePan(e)}}function Od(e){!1!==this.enabled&&!1!==this.enableZoom&&this.state===Md&&(e.preventDefault(),this.dispatchEvent(_d),this._handleMouseWheel(this._customWheelEvent(e)),this.dispatchEvent(vd))}function zd(e){!1!==this.enabled&&this._handleKeyDown(e)}function Hd(e){switch(this._trackPointer(e),this._pointers.length){case 1:switch(this.touches.ONE){case ae:if(!1===this.enableRotate)return;this._handleTouchStartRotate(e),this.state=Cd;break;case oe:if(!1===this.enablePan)return;this._handleTouchStartPan(e),this.state=Rd;break;default:this.state=Md}break;case 2:switch(this.touches.TWO){case le:if(!1===this.enableZoom&&!1===this.enablePan)return;this._handleTouchStartDollyPan(e),this.state=Id;break;case ce:if(!1===this.enableZoom&&!1===this.enableRotate)return;this._handleTouchStartDollyRotate(e),this.state=Pd;break;default:this.state=Md}break;default:this.state=Md}this.state!==Md&&this.dispatchEvent(_d)}function Vd(e){switch(this._trackPointer(e),this.state){case Cd:if(!1===this.enableRotate)return;this._handleTouchMoveRotate(e),this.update();break;case Rd:if(!1===this.enablePan)return;this._handleTouchMovePan(e),this.update();break;case Id:if(!1===this.enableZoom&&!1===this.enablePan)return;this._handleTouchMoveDollyPan(e),this.update();break;case Pd:if(!1===this.enableZoom&&!1===this.enableRotate)return;this._handleTouchMoveDollyRotate(e),this.update();break;default:this.state=Md}}function Gd(e){!1!==this.enabled&&e.preventDefault()}function Wd(e){if("Control"===e.key){this._controlActive=!0;this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}}function jd(e){if("Control"===e.key){this._controlActive=!1;this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}}const Xd=0,qd=3,Qd=0,Kd=2,Yd=0,Zd=e=>e.endsWith(".ply")?Yd:null,Jd=0,$d=2,ep=0,tp=1;let np=(i(t=class{},"DefaultSplatSortDistanceMapPrecision",16),i(t,"MemoryPageSize",65536),i(t,"BytesPerFloat",4),i(t,"BytesPerInt",4),i(t,"MaxScenes",32),i(t,"ProgressiveLoadSectionSize",262144),i(t,"ProgressiveLoadSectionDelayDuration",15),i(t,"SphericalHarmonics8BitCompressionRange",3),t);const ip=np.SphericalHarmonics8BitCompressionRange,rp=0,sp=1,ap=2,op=0,lp=1,cp=2;class hp extends Error{constructor(e,t,n=null){super(e),this.name=this.constructor.name,this.code=t,this.cause=n,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,message:this.message,code:this.code,stack:this.stack,cause:this.cause?{name:this.cause.name,message:this.cause.message}:null}}}class up extends hp{constructor(e,t,n=null){super(e,"VALIDATION_ERROR",n),this.field=t}}class dp extends hp{constructor(e,t=0,n=null){super(e,"NETWORK_ERROR",n),this.statusCode=t}}class pp extends hp{constructor(e,t,n=null){super(e,"ASSET_LOAD_ERROR",n),this.assetPath=t}}class fp extends hp{constructor(e){super(`Cannot use ${e}: resource has been disposed`,"RESOURCE_DISPOSED_ERROR"),this.resourceName=e}}class mp extends hp{constructor(e,t,n=null){super(e,"INITIALIZATION_ERROR",n),this.component=t}}let gp=class extends hp{constructor(e,t,n=null){super(e,"PARSE_ERROR",n),this.dataType=t}};const _p=Object.freeze({DEBUG:0,INFO:1,WARN:2,ERROR:3,NONE:4});class vp{constructor(e,t=_p.INFO){this.namespace=e,this.minLevel=t}setLevel(e){this.minLevel=e}_format(e,t){return[`[${(new Date).toISOString()}] [${e}] [${this.namespace}]`,...t]}debug(...e){this.minLevel<=_p.DEBUG&&this._format("DEBUG",e)}info(...e){this.minLevel<=_p.INFO&&console.info(...this._format("INFO",e))}warn(...e){this.minLevel<=_p.WARN&&console.warn(...this._format("WARN",e))}error(...e){this.minLevel<=_p.ERROR&&console.error(...this._format("ERROR",e))}errorWithTrace(e,t=""){if(this.minLevel<=_p.ERROR){const n=t?` Context: ${t}`:"";console.error(...this._format("ERROR",[`${e.message}${n}`,"\nStack:",e.stack]))}}child(e){return new vp(`${this.namespace}:${e}`,this.minLevel)}}const xp=new Map;let yp=_p.INFO;function Sp(e){return xp.has(e)||xp.set(e,new vp(e,yp)),xp.get(e)}Sp("App");const Ap=Sp("Util");class bp extends Error{constructor(e){super(e),this.name="AbortedPromiseError",this.code="ABORTED"}}const Mp=function(e,t,n){return Math.max(Math.min(e,n),t)},wp=function(){return performance.now()/1e3},Tp=e=>{if(e.geometry&&(e.geometry.dispose(),e.geometry=null),e.material&&(e.material.dispose(),e.material=null),e.children)for(let t of e.children)Tp(t)},Ep=(e,t)=>new Promise(n=>{window.setTimeout(()=>{n(e())},t?1:50)}),Cp=(e=0)=>{switch(e){case 1:return 9;case 2:return 24}return 0},Rp=e=>{let t,n;const i=new Promise((e,i)=>{t=e,n=i});return i.abort=e||(()=>{}),{promise:i,resolve:t,reject:n}};class Ip{constructor(e,t,n){this.major=e,this.minor=t,this.patch=n}toString(){return`${this.major}_${this.minor}_${this.patch}`}}function Pp(){const e=navigator.userAgent;return e.indexOf("iPhone")>0||e.indexOf("iPad")>0}function Dp(){if(Pp()){const e=navigator.userAgent.match(/OS (\d+)_(\d+)_?(\d+)?/);return new Ip(parseInt(e[1]||0,10),parseInt(e[2]||0,10),parseInt(e[3]||0,10))}return null}const Bp=as.toHalfFloat.bind(as),Lp=as.fromHalfFloat.bind(as),Fp=ip/2,Up=(e,t,n)=>{e=Mp(e,t,n);const i=n-t;return Mp(Math.floor((e-t)/i*255),0,255)},kp=(e,t,n)=>e/255*(n-t)+t,Np=(e,t,n)=>Up(Lp(e),t,n),Op=(e,t,n)=>Bp(kp(e,t,n)),zp=function(){const e=e=>e;return function(t,n,i,r=!1){if(n===i)return t;let s=e;return 2===n&&r?1===i?s=Op:0===i&&(s=kp):2===n||1===n?0===i?s=Lp:2===i&&(s=r?Np:e):0===n&&(1===i?s=Bp:2===i&&(s=r?Up:Bp)),s(t)}}();!function(){const e=new Float32Array(1),t=new Int32Array(e.buffer)}();const Hp=function(){const e=new Float32Array(1),t=new Int32Array(e.buffer);return function(n){return e[0]=n,t[0]}}(),Vp=function(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24)},Gp=Object.freeze(["https:","http:","blob:","data:"]);function Wp(e,t){if("string"!=typeof e||0===e.length)throw new up("URL must be a non-empty string","url");let n;try{const i=t||("undefined"!=typeof window?window.location.href:void 0);n=new URL(e,i)}catch(i){throw new up(`Invalid URL format: ${e}`,"url",i)}if(!Gp.includes(n.protocol))throw new up(`Disallowed protocol: ${n.protocol}. Allowed protocols: ${Gp.join(", ")}`,"url.protocol");return n.href}function jp(e,t,n=!0){if(null==e){if(n)throw new up(`${t} is required`,t);return null}if("function"!=typeof e)throw new up(`${t} must be a function`,t);return e}class Xp{constructor(e,t,n=10){this._factory=e,this._reset=t,this._pool=[],this._allocated=0,this._maxSize=10*n;for(let i=0;i<n;i++)this._pool.push(e())}acquire(){return this._allocated++,this._pool.length>0?this._pool.pop():this._factory()}release(e){this._allocated--,this._pool.length<this._maxSize&&(this._reset(e),this._pool.push(e))}releaseAll(e){for(const t of e)this.release(t)}getStats(){return{available:this._pool.length,allocated:this._allocated,maxSize:this._maxSize}}dispose(){this._pool.length=0,this._allocated=0}}new Xp(()=>new hi,e=>e.set(0,0,0),50),new Xp(()=>new or,e=>e.identity(),20),new Xp(()=>new ci,e=>e.set(0,0,0,1),30),new Xp(()=>new _r,e=>e.set(0,0,0),30);const qp=new hi;new hi,new hi,new or,new or;const Qp=Sp("BlobUrlManager");class Kp{constructor(){this._urls=new Map,this._disposed=!1}_assertNotDisposed(){if(this._disposed)throw new Error("BlobUrlManager has been disposed")}createBlobUrl(e,t,n=""){if(this._assertNotDisposed(),"string"!=typeof t||0===t.length)throw new up("mimeType must be a non-empty string","mimeType");let i;if(e instanceof Blob)i=e;else{if(!(e instanceof ArrayBuffer||e instanceof Uint8Array))throw new up("data must be Blob, ArrayBuffer, or Uint8Array","data");i=new Blob([e],{type:t})}const r=URL.createObjectURL(i);return this._urls.set(r,{createdAt:Date.now(),mimeType:t,label:n||"unlabeled",size:i.size}),Qp.debug(`Created blob URL: ${n||r.substring(0,50)}, size: ${i.size} bytes`),r}registerBlobUrl(e,t=""){if(this._assertNotDisposed(),"string"!=typeof e||!e.startsWith("blob:"))throw new up("url must be a valid blob URL","url");this._urls.has(e)||(this._urls.set(e,{createdAt:Date.now(),mimeType:"unknown",label:t||"registered-external",size:0}),Qp.debug(`Registered external blob URL: ${t||e.substring(0,50)}`))}revokeBlobUrl(e){if(this._assertNotDisposed(),this._urls.has(e)){const t=this._urls.get(e);return URL.revokeObjectURL(e),this._urls.delete(e),Qp.debug(`Revoked blob URL: ${t.label}, age: ${Date.now()-t.createdAt}ms`),!0}return!1}revokeAll(){this._assertNotDisposed(),Qp.debug(`Revoking ${this._urls.size} blob URLs`);for(const e of this._urls.keys())URL.revokeObjectURL(e);this._urls.clear()}getMetadata(e){return this._urls.get(e)||null}getAllTrackedUrls(){const e=[];for(const[t,n]of this._urls.entries())e.push({url:t,metadata:n});return e}getStats(){let e=0,t=0;const n=Date.now();for(const i of this._urls.values()){e+=i.size;const r=n-i.createdAt;r>t&&(t=r)}return{count:this._urls.size,totalSize:e,oldestAge:t}}revokeOlderThan(e){this._assertNotDisposed();const t=Date.now(),n=[];for(const[i,r]of this._urls.entries())t-r.createdAt>e&&n.push(i);for(const i of n)this.revokeBlobUrl(i);return n.length>0&&Qp.info(`Revoked ${n.length} blob URLs older than ${e}ms`),n.length}isTracked(e){return this._urls.has(e)}dispose(){this._disposed||(Qp.debug("Disposing BlobUrlManager"),this.revokeAll(),this._disposed=!0)}}Sp("RenderLoop"),Sp("EventEmitter");const Yp="Idle",Zp="Listening",Jp="Responding",$p="Thinking",ef=Sp("AnimationManager");class tf{constructor(e,t){this.isPlaying=!1,this.stage=0,this.actions=e||[],this.blendingTime=.5,this.isGroup=t||!1}dispose(){this.actions=[]}update(e){}}class nf extends tf{constructor(e,t){super(e,t)}update(e){if(this.actions&&0!==this.actions.length&&(void 0===cf.CurPlaying&&e===Yp&&!1===this.isPlaying&&(this.stage=0,this.actions[this.stage].time=0,cf.SetWeight(this.actions[this.stage],1),this.actions[this.stage].loop=mn,this.actions[this.stage].clampWhenFinished=!1,this.actions[this.stage].paused=!1,this.actions[this.stage].play(),void 0!==cf.LastAction&&cf.PrepareCrossFade(cf.LastAction,this.actions[this.stage],this.blendingTime),this.isPlaying=!0),cf.CurPlaying===Yp&&e===Yp&&!0===this.isPlaying&&this.actions[this.stage].time>this.actions[this.stage].getClip().duration-this.blendingTime)){let e=this.stage+1;e>=this.actions.length&&(e=0),this.actions[e].time=0,cf.SetWeight(this.actions[e],1),this.actions[e].loop=mn,this.actions[e].play(),cf.PrepareCrossFade(this.actions[this.stage],this.actions[e],this.blendingTime),this.stage=e}}}class rf extends tf{constructor(e,t){super(e,t)}update(e){this.actions&&0!==this.actions.length&&(void 0===cf.CurPlaying&&e===Yp&&!1===this.isPlaying&&(this.stage=0,this.actions[this.stage].time=0,cf.SetWeight(this.actions[this.stage],1),this.actions[this.stage].loop=mn,this.actions[this.stage].clampWhenFinished=!1,this.actions[this.stage].paused=!1,this.actions[this.stage].play(),void 0!==cf.LastAction&&cf.PrepareCrossFade(cf.LastAction,this.actions[this.stage],this.blendingTime),this.isPlaying=!0),cf.CurPlaying===Yp&&e!==Yp&&!0===this.isPlaying&&0===this.stage&&(this.actions[this.stage].loop=fn,this.actions[this.stage].clampWhenFinished=!0,this.isPlaying=!1,cf.LastAction=this.actions[this.stage]))}}class sf extends tf{constructor(e,t){super(e,t)}update(e){this.actions&&0!==this.actions.length&&(void 0===cf.CurPlaying&&e===Zp&&!1===this.isPlaying&&(this.stage=0,this.actions[this.stage].time=0,this.actions[this.stage].play(),cf.SetWeight(this.actions[this.stage],1),this.actions[this.stage].loop=this.isGroup?fn:mn,this.actions[this.stage].clampWhenFinished=!!this.isGroup,void 0!==cf.LastAction&&cf.PrepareCrossFade(cf.LastAction,this.actions[this.stage],this.blendingTime),this.isPlaying=!0),this.isGroup&&(cf.CurPlaying===Zp&&e===Zp&&!0===this.isPlaying&&0===this.stage&&this.actions[this.stage].time>this.actions[this.stage].getClip().duration-this.blendingTime&&(this.actions[this.stage+1].time=0,cf.SetWeight(this.actions[this.stage+1],1),this.actions[this.stage+1].loop=mn,this.actions[this.stage+1].play(),cf.PrepareCrossFade(this.actions[this.stage],this.actions[this.stage+1],this.blendingTime),this.stage=1),cf.CurPlaying!==Zp||e===Zp||!0!==this.isPlaying||0!==this.stage&&1!==this.stage||(this.actions[2].time=0,this.actions[2].play(),cf.SetWeight(this.actions[2],1),this.actions[2].loop=fn,cf.PrepareCrossFade(this.actions[this.stage],this.actions[2],this.blendingTime),this.stage=2)),cf.CurPlaying===Zp&&e!==Zp&&!0===this.isPlaying&&this.stage===(this.isGroup?this.actions.length-1:0)&&(this.actions[this.stage].loop=fn,this.actions[this.stage].clampWhenFinished=!0,this.isPlaying=!1,cf.LastAction=this.actions[this.stage]))}}class af extends tf{constructor(e,t){super(e,t)}update(e){this.actions&&0!==this.actions.length&&(void 0===cf.CurPlaying&&e===$p&&!1===this.isPlaying&&(this.stage=0,this.actions[this.stage].time=0,this.actions[this.stage].play(),cf.SetWeight(this.actions[this.stage],1),this.actions[this.stage].loop=fn,void 0!==cf.LastAction&&cf.PrepareCrossFade(cf.LastAction,this.actions[this.stage],this.blendingTime),this.isPlaying=!0),this.isGroup&&(cf.CurPlaying===$p&&e===$p&&!0===this.isPlaying&&0===this.stage&&this.actions[this.stage].time>this.actions[this.stage].getClip().duration-this.blendingTime&&(this.actions[this.stage+1].time=0,cf.SetWeight(this.actions[this.stage+1],1),this.actions[this.stage+1].loop=mn,this.actions[this.stage+1].play(),cf.PrepareCrossFade(this.actions[this.stage],this.actions[this.stage+1],this.blendingTime),this.stage=1),cf.CurPlaying!==$p||e===$p||!0!==this.isPlaying||0!==this.stage&&1!==this.stage||(this.actions[2].time=0,this.actions[2].play(),cf.SetWeight(this.actions[2],1),this.actions[2].loop=fn,cf.PrepareCrossFade(this.actions[this.stage],this.actions[2],this.blendingTime),this.stage=2)),cf.CurPlaying===$p&&e!==$p&&!0===this.isPlaying&&this.stage===(this.isGroup?this.actions.length-1:0)&&(this.actions[this.stage].loop=fn,this.actions[this.stage].clampWhenFinished=!0,this.isPlaying=!1,cf.LastAction=this.actions[this.stage]))}}class of extends tf{constructor(e,t){super(e,t),ef.debug("[SPEAK] Initialized with",e?.length||0,"actions, isGroup:",t)}getRandomNumber(e,t){const n=e-t;return t+Math.round(Math.random()*n)}update(e){if(this.actions&&0!==this.actions.length){if(void 0===cf.CurPlaying&&e===Jp&&!1===this.isPlaying&&(this.stage=Math.ceil(this.getRandomNumber(0,this.actions.length-1)),ef.debug("[SPEAK] Starting animation, stage:",this.stage,"of",this.actions.length),this.actions[this.stage].time=0,this.actions[this.stage].play(),cf.SetWeight(this.actions[this.stage],1),this.actions[this.stage].loop=fn,this.actions[this.stage].clampWhenFinished=!0,void 0!==cf.LastAction&&cf.PrepareCrossFade(cf.LastAction,this.actions[this.stage],this.blendingTime),this.isPlaying=!0),cf.CurPlaying===Jp&&e===Jp&&!0===this.isPlaying&&this.actions[this.stage].time>=this.actions[this.stage].getClip().duration-this.blendingTime){const e=this.actions[this.stage];this.stage=(this.stage+Math.ceil(this.getRandomNumber(1,this.actions.length-1)))%this.actions.length,ef.debug("[SPEAK] Cycling to next animation, stage:",this.stage),this.actions[this.stage].time=0,this.actions[this.stage].play(),cf.SetWeight(this.actions[this.stage],1),this.actions[this.stage].loop=fn,this.actions[this.stage].clampWhenFinished=!0,cf.PrepareCrossFade(e,this.actions[this.stage],this.blendingTime)}cf.CurPlaying===Jp&&e!==Jp&&!0===this.isPlaying&&(this.actions[this.stage].loop=fn,this.actions[this.stage].clampWhenFinished=!0,this.isPlaying=!1,cf.LastAction=this.actions[this.stage])}else this._warnedNoActions||(ef.warn("[SPEAK] No actions available!"),this._warnedNoActions=!0)}}const lf=class e{static SetWeight(e,t){e.enabled=!0,e.setEffectiveTimeScale(1),e.setEffectiveWeight(t)}static PrepareCrossFade(t,n,i){const r=i;e.UnPauseAllActions(),e.ExecuteCrossFade(t,n,r),e.IsBlending=!0,setTimeout(()=>{e.IsBlending=!1},i+.1)}static PauseAllActions(){e.actions.forEach(function(e){e.paused=!0})}static UnPauseAllActions(){e.actions.forEach(function(e){e.paused=!1})}static ExecuteCrossFade(t,n,i){e.SetWeight(n,1),n.time=0,t.crossFadeTo(n,i,!0)}constructor(t,n,i){const r=[],s=[],a=[],o=[],l=[];this.mixer=t;const c=i?.hello?.size||0,h=(i?.idle?.size||0)+c,u=(i?.listen?.size||0)+h,d=(i?.speak?.size||0)+u,p=(i?.think?.size||0)+d;if(n&&n.length>0)for(let f=0;f<n.length;f++){const i=n[f],m=t.clipAction(i);f<c?r.push(m):f<h?(s.push(m),u===h&&a.push(t.clipAction(i.clone())),d===u&&o.push(t.clipAction(i.clone())),p===d&&l.push(t.clipAction(i.clone()))):f<u?a.push(m):f<d?o.push(m):f<p&&l.push(m),e.actions.push(m),e.SetWeight(m,0)}this.hello=new nf(r,i?.hello?.isGroup||!1),this.idle=new rf(s,i?.idle?.isGroup||!1),this.listen=new sf(a,i?.listen?.isGroup||!1),this.think=new af(l,i?.think?.isGroup||!1),this.speak=new of(o,i?.speak?.isGroup||!1)}curPlaying(){return this.hello.isPlaying||this.idle.isPlaying?Yp:this.listen.isPlaying?Zp:this.think.isPlaying?$p:this.speak.isPlaying?Jp:void 0}dispose(){this.hello.dispose(),this.idle.dispose(),this.listen.dispose(),this.think.dispose(),this.speak.dispose(),e.actions=[]}resetAllActions(t=!1){switch(this.curPlaying()){case Yp:e.LastAction=this.hello.actions[this.hello.stage];break;case Zp:e.LastAction=this.listen.actions[this.listen.stage];break;case $p:e.LastAction=this.think.actions[this.think.stage];break;case Jp:e.LastAction=this.speak.actions[this.speak.stage];break;default:e.LastAction=void 0}e.LastAction&&(e.LastAction.loop=fn,e.LastAction.clampWhenFinished=!0,e.SetWeight(e.LastAction,1)),t&&(e.PauseAllActions(),e.actions.forEach(function(t){t.time=0,e.SetWeight(t,0)}),e.LastAction=void 0),this.hello.isPlaying=!1,this.idle.isPlaying=!1,this.listen.isPlaying=!1,this.think.isPlaying=!1,this.speak.isPlaying=!1}update(t){if(!e.IsBlending)if(e.CurPlaying=this.curPlaying(),void 0===e.CurPlaying)switch(t){case Yp:this.idle.update(t);break;case Zp:this.listen.update(t);break;case $p:this.think.update(t);break;case Jp:this.speak.update(t);break;default:this.idle.update(t)}else switch(e.CurPlaying){case Yp:this.idle.update(t);break;case Zp:this.listen.update(t);break;case $p:this.think.update(t);break;case Jp:this.speak.update(t);break;default:this.idle.update(t)}}};i(lf,"IsBlending",!1),i(lf,"actions",[]),i(lf,"NeedReset",!1),i(lf,"NeedFullReset",!1),i(lf,"LastAction"),i(lf,"CurPlaying");let cf=lf;class hf extends Lr{constructor(e,t=new hi,n=new ci,i=new hi(1,1,1),r=1,s=1,a=!0){super(),this.splatBuffer=e,this.position.copy(t),this.quaternion.copy(n),this.scale.copy(i),this.transform=new or,this.minimumAlpha=r,this.opacity=s,this.visible=a}copyTransformData(e){this.position.copy(e.position),this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.transform.copy(e.transform)}updateTransform(e){e?(this.matrixWorldAutoUpdate&&this.updateWorldMatrix(!0,!1),this.transform.copy(this.matrixWorld)):(this.matrixAutoUpdate&&this.updateMatrix(),this.transform.copy(this.matrix))}}class uf{static build(e){const t=new Ss;t.setIndex([0,1,2,0,2,3]);const n=new Float32Array(12),i=new hs(n,3);t.setAttribute("position",i),i.setXYZ(0,-1,-1,0),i.setXYZ(1,-1,1,0),i.setXYZ(2,1,1,0),i.setXYZ(3,1,-1,0),i.needsUpdate=!0;const r=(new $o).copy(t),s=new Uint32Array(e),a=new va(s,1,!1);return a.setUsage(Nn),r.setAttribute("splatIndex",a),r.instanceCount=0,r}}class df{constructor(){this.rootNode=null,this.splatMesh=null}static convertWorkerSubTree(e,t){const n=new df;return n.rootNode=e.rootNode,n.splatMesh=t,n}}class pf{constructor(e,t){i(this,"processSplatMesh",(e,t=()=>!0,n,i)=>{this.splatTreeWorker||(this.splatTreeWorker=null),this.splatMesh=e,this.subTrees=[];const r=new hi,s=(n,i)=>{const s=new Float32Array(4*i);let a=0;for(let o=0;o<i;o++){const i=o+n;if(t(i)){e.getSplatCenter(i,r);const t=4*a;s[t]=r.x,s[t+1]=r.y,s[t+2]=r.z,s[t+3]=i,a++}}return s};return new Promise(t=>{const r=()=>!!this.disposed&&(this.diposeSplatTreeWorker(),t(),!0);n&&n(!1),Ep(()=>{if(r())return;const a=[];if(e.dynamicMode){let t=0;for(let n=0;n<e.scenes.length;n++){const i=e.getScene(n).splatBuffer.getSplatCount(),r=s(t,i);a.push(r),t+=i}}else{const t=s(0,e.getSplatCount());a.push(t)}this.splatTreeWorker.onmessage=n=>{r()||n.data.subTrees&&(i&&i(!1),Ep(()=>{if(!r()){for(let t of n.data.subTrees){const n=df.convertWorkerSubTree(t,e);this.subTrees.push(n)}this.diposeSplatTreeWorker(),i&&i(!0),Ep(()=>{t()})}}))},Ep(()=>{if(r())return;n&&n(!0);const e=a.map(e=>e.buffer);var t,i,s,o,l;t=this.splatTreeWorker,i=a,s=e,o=this.maxDepth,l=this.maxCentersPerNode,t&&t.postMessage({process:{centers:i,maxDepth:o,maxCentersPerNode:l}},s)})})})}),this.maxDepth=e,this.maxCentersPerNode=t,this.subTrees=[],this.splatMesh=null}dispose(){this.diposeSplatTreeWorker(),this.disposed=!0}diposeSplatTreeWorker(){this.splatTreeWorker&&this.splatTreeWorker.terminate(),this.splatTreeWorker=null}countLeaves(){let e=0;return this.visitLeaves(()=>{e++}),e}visitLeaves(e){const t=(e,n)=>{0===e.children.length&&n(e);for(let i of e.children)t(i,n)};for(let n of this.subTrees)t(n.rootNode,e)}}class ff{static buildVertexShaderBase(e=!1,t=!1,n=0,i=""){let r="#define USE_SKINNING\n\n precision highp float;\n #include <common>\n\n attribute uint splatIndex;\n uniform highp usampler2D flameModelTexture;\n uniform highp usampler2D boneTexture;\n uniform highp usampler2D boneWeightTexture;\n\n\n uniform highp usampler2D centersColorsTexture;\n uniform highp sampler2D sphericalHarmonicsTexture;\n uniform highp sampler2D sphericalHarmonicsTextureR;\n uniform highp sampler2D sphericalHarmonicsTextureG;\n uniform highp sampler2D sphericalHarmonicsTextureB;\n\n uniform highp usampler2D sceneIndexesTexture;\n uniform vec2 sceneIndexesTextureSize;\n uniform int sceneCount;\n uniform int gaussianSplatCount;\n uniform int bsCount;\n uniform float headBoneIndex;\n #ifdef USE_SKINNING\n attribute vec4 skinIndex;\n attribute vec4 skinWeight;\n #endif\n ";return t&&(r+=`\n uniform float sceneOpacity[${np.MaxScenes}];\n uniform int sceneVisibility[${np.MaxScenes}];\n `),e&&(r+=`\n uniform highp mat4 transforms[${np.MaxScenes}];\n `),r+=`\n ${i}\n uniform vec2 focal;\n uniform float orthoZoom;\n uniform int orthographicMode;\n uniform int pointCloudModeEnabled;\n uniform float inverseFocalAdjustment;\n uniform vec2 viewport;\n uniform vec2 basisViewport;\n uniform vec2 centersColorsTextureSize;\n uniform vec2 flameModelTextureSize;\n uniform vec2 boneWeightTextureSize;\n uniform vec2 boneTextureSize;\n\n uniform int sphericalHarmonicsDegree;\n uniform vec2 sphericalHarmonicsTextureSize;\n uniform int sphericalHarmonics8BitMode;\n uniform int sphericalHarmonicsMultiTextureMode;\n uniform float visibleRegionRadius;\n uniform float visibleRegionFadeStartRadius;\n uniform float firstRenderTime;\n uniform float currentTime;\n uniform int fadeInComplete;\n uniform vec3 sceneCenter;\n uniform float splatScale;\n uniform float sphericalHarmonics8BitCompressionRangeMin[${np.MaxScenes}];\n uniform float sphericalHarmonics8BitCompressionRangeMax[${np.MaxScenes}];\n\n varying vec4 vColor;\n varying vec2 vUv;\n varying vec2 vPosition;\n varying vec2 vSplatIndex;\n #ifdef USE_SKINNING\n uniform mat4 bindMatrix;\n uniform mat4 bindMatrixInverse;\n uniform highp sampler2D boneTexture0;\n mat4 getBoneMatrix0( const in float i ) {\n int size = textureSize( boneTexture0, 0 ).x;\n int j = int( i ) * 4;\n int x = j % size;\n int y = j / size;\n vec4 v1 = texelFetch( boneTexture0, ivec2( x, y ), 0 );\n vec4 v2 = texelFetch( boneTexture0, ivec2( x + 1, y ), 0 );\n vec4 v3 = texelFetch( boneTexture0, ivec2( x + 2, y ), 0 );\n vec4 v4 = texelFetch( boneTexture0, ivec2( x + 3, y ), 0 );\n return mat4( v1, v2, v3, v4 );\n }\n #endif\n\n mat3 quaternionToRotationMatrix(float x, float y, float z, float w) {\n float s = 1.0 / sqrt(w * w + x * x + y * y + z * z);\n \n return mat3(\n 1. - 2. * (y * y + z * z),\n 2. * (x * y + w * z),\n 2. * (x * z - w * y),\n 2. * (x * y - w * z),\n 1. - 2. * (x * x + z * z),\n 2. * (y * z + w * x),\n 2. * (x * z + w * y),\n 2. * (y * z - w * x),\n 1. - 2. * (x * x + y * y)\n );\n }\n\n const float sqrt8 = sqrt(8.0);\n const float minAlpha = 1.0 / 255.0;\n\n const vec4 encodeNorm4 = vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\n const uvec4 mask4 = uvec4(uint(0x000000FF), uint(0x0000FF00), uint(0x00FF0000), uint(0xFF000000));\n const uvec4 shift4 = uvec4(0, 8, 16, 24);\n int internal = 1;//show a gaussian splatting point every internal points.\n vec4 uintToRGBAVec (uint u) {\n uvec4 urgba = mask4 & u;\n urgba = urgba >> shift4;\n vec4 rgba = vec4(urgba) * encodeNorm4;\n return rgba;\n }\n float getRealIndex(int sIndex, int reducedFactor) {\n int remainder = sIndex % reducedFactor;\n\n if(remainder == int(0)) {\n return float(sIndex);\n }\n else\n {\n return float(sIndex - remainder);\n }\n }\n\n vec2 getDataUV(in int stride, in int offset, in vec2 dimensions) {\n vec2 samplerUV = vec2(0.0, 0.0);\n float d = float(uint(getRealIndex(int(splatIndex), internal)) * uint(stride) + uint(offset)) / dimensions.x;\n samplerUV.y = float(floor(d)) / dimensions.y;\n samplerUV.x = fract(d);\n return samplerUV;\n }\n\n vec2 getFlameDataUV(in int stride, in int offset, in vec2 dimensions) {\n vec2 samplerUV = vec2(0.0, 0.0);\n float d = float(uint(int(splatIndex) / internal) * uint(stride) + uint(offset) + uint(gaussianSplatCount * bsCount)) / dimensions.x;\n samplerUV.y = float(floor(d)) / dimensions.y;\n samplerUV.x = fract(d);\n return samplerUV;\n }\n\n vec2 getBoneWeightUV(in int stride, in int offset, in vec2 dimensions) {\n vec2 samplerUV = vec2(0.0, 0.0);\n float d = float(uint(int(splatIndex) / internal) * uint(stride) + uint(offset)) / dimensions.x;\n samplerUV.y = float(floor(d)) / dimensions.y;\n samplerUV.x = fract(d);\n return samplerUV;\n }\n\n vec2 getBSFlameDataUV(in int bsInedex, in int stride, in int offset, in vec2 dimensions) {\n vec2 samplerUV = vec2(0.0, 0.0);\n float d = float(uint(int(splatIndex) / internal) * uint(stride) + uint(offset) + uint(gaussianSplatCount * bsInedex)) / dimensions.x;\n samplerUV.y = float(floor(d)) / dimensions.y;\n samplerUV.x = fract(d);\n return samplerUV;\n }\n\n vec2 getDataUVF(in uint sIndex, in float stride, in uint offset, in vec2 dimensions) {\n vec2 samplerUV = vec2(0.0, 0.0);\n float d = float(uint(float(getRealIndex(int(sIndex), internal)) * stride) + offset) / dimensions.x;\n samplerUV.y = float(floor(d)) / dimensions.y;\n samplerUV.x = fract(d);\n return samplerUV;\n }\n\n const float SH_C1 = 0.4886025119029199f;\n const float[5] SH_C2 = float[](1.0925484, -1.0925484, 0.3153916, -1.0925484, 0.5462742);\n\n mat4 getBoneMatrix( float i ) {\n float y = i;\n float x = 0.0;\n\n vec2 samplerUV = vec2(0.0, 0.0);\n float d = float(i * 4.0) / boneTextureSize.x;//4\n samplerUV.y = float(floor(d)) / boneTextureSize.y;//5\n samplerUV.x = fract(d);\n\n vec4 v1 = uintBitsToFloat(texture( boneTexture, samplerUV ));\n vec4 v2 = uintBitsToFloat(texture( boneTexture, vec2(samplerUV.x + 1.0 / boneTextureSize.x, samplerUV.y)));\n vec4 v3 = uintBitsToFloat(texture( boneTexture, vec2(samplerUV.x + 2.0 / boneTextureSize.x, samplerUV.y) ));\n vec4 v4 = uintBitsToFloat(texture( boneTexture, vec2(samplerUV.x + 3.0 / boneTextureSize.x, samplerUV.y)));\n\n return mat4( v1, v2, v3, v4 );\n }\n\n void main () {\n\n uint oddOffset = splatIndex & uint(0x00000001);\n uint doubleOddOffset = oddOffset * uint(2);\n bool isEven = oddOffset == uint(0);\n uint nearestEvenIndex = splatIndex - oddOffset;\n float fOddOffset = float(oddOffset);\n\n uvec4 sampledCenterColor = texture(centersColorsTexture, getDataUV(1, 0, centersColorsTextureSize));\n // vec3 splatCenter = uintBitsToFloat(uvec3(sampledCenterColor.gba));\n\n uvec3 sampledCenter = texture(centersColorsTexture, getDataUV(1, 0, centersColorsTextureSize)).gba;\n vec3 splatCenter = uintBitsToFloat(uvec3(sampledCenter));\n\n vec2 flameTextureUV = getBSFlameDataUV(bsCount, 1, 0, flameModelTextureSize);\n uvec3 sampledflamePos = texture(flameModelTexture, flameTextureUV).rgb;\n // splatCenter += uintBitsToFloat(uvec3(sampledflamePos.rgb));\n\n for(int i = 0; i < bsCount; ++i) {\n vec2 flameBSTextureUV = getBSFlameDataUV(i, 1, 0, flameModelTextureSize);\n uvec3 sampledBSPos = texture(flameModelTexture, flameBSTextureUV).rgb;\n\n vec2 samplerUV = vec2(0.0, 0.0);\n float d = float(i / 4 + 5 * 4) / boneTextureSize.x;//4\n samplerUV.y = float(floor(d)) / boneTextureSize.y;//32\n samplerUV.x = fract(d);\n\n vec4 bsWeight = uintBitsToFloat(texture(boneTexture, samplerUV));\n float weight = bsWeight.r;\n if(i % 4 == 1) {\n weight = bsWeight.g;\n }\n if(i % 4 == 2) {\n weight = bsWeight.b;\n }\n if(i % 4 == 3) {\n weight = bsWeight.a;\n }\n\n splatCenter = splatCenter + weight * uintBitsToFloat(sampledBSPos);\n }\n\n\n #ifdef USE_SKINNING\n mat4 boneMatX = getBoneMatrix0( skinIndex.x );\n mat4 boneMatY = getBoneMatrix0( skinIndex.y );\n mat4 boneMatZ = getBoneMatrix0( skinIndex.z );\n mat4 boneMatW = getBoneMatrix0( skinIndex.w );\n #endif\n #ifdef USE_SKINNING\n mat4 skinMatrix = mat4( 0.0 );\n skinMatrix += skinWeight.x * boneMatX;\n skinMatrix += skinWeight.y * boneMatY;\n skinMatrix += skinWeight.z * boneMatZ;\n skinMatrix += skinWeight.w * boneMatW;\n // skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n #endif\n vec3 transformed = vec3(splatCenter.xyz);\n #ifdef USE_SKINNING\n // vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n vec4 skinVertex = vec4( transformed, 1.0 );\n\n vec4 skinned = vec4( 0.0 );\n // There is an offset between the Gaussian point and the mesh vertex,\n // which will cause defects in the skeletal animation driving the Gaussian point. \n //In order to circumvent this problem, only the head bone(index is 110 currently) is used to drive\n\n if (headBoneIndex >= 0.0)\n {\n mat4 boneMat = getBoneMatrix0( headBoneIndex );\n skinned += boneMat * skinVertex * 1.0;\n }\n\n // skinned += boneMatX * skinVertex * skinWeight.x;\n // skinned += boneMatY * skinVertex * skinWeight.y;\n // skinned += boneMatZ * skinVertex * skinWeight.z;\n // skinned += boneMatW * skinVertex * skinWeight.w;\n\n // transformed = ( bindMatrixInverse * skinned ).xyz;\n transformed = skinned.xyz;\n\n #endif\n splatCenter = transformed.xyz;\n\n #ifdef USE_FLAME\n mat4 boneMatX = getBoneMatrix( 0.0 );\n mat4 boneMatY = getBoneMatrix( 1.0 );\n mat4 boneMatZ = getBoneMatrix( 2.0 );\n mat4 boneMatW = getBoneMatrix( 3.0 ); \n mat4 boneMat0 = getBoneMatrix( 4.0 ); \n \n vec2 boneWeightUV0 = getBoneWeightUV(2, 0, boneWeightTextureSize);\n vec2 boneWeightUV1 = getBoneWeightUV(2, 1, boneWeightTextureSize);\n\n uvec4 sampledBoneMatrixValue = texture(boneWeightTexture, boneWeightUV0);\n uvec4 sampledBoneMatrixValue0 = texture(boneWeightTexture, boneWeightUV1);\n\n vec4 boneMatrixValue = uintBitsToFloat(sampledBoneMatrixValue);\n vec4 boneMatrixValue0 = uintBitsToFloat(sampledBoneMatrixValue0);\n\n vec4 skinVertex = vec4( splatCenter, 1.0 );\n vec4 skinned = vec4( 0.0 );\n float minWeight = min(boneMatrixValue.x,min(boneMatrixValue.y, min(boneMatrixValue.z, min(boneMatrixValue.w, boneMatrixValue0.x))));\n \n if(boneMatrixValue.x > 0.0 && boneMatrixValue.x > minWeight)\n skinned += boneMatX * skinVertex * boneMatrixValue.x;\n \n if(boneMatrixValue.y > 0.0 && boneMatrixValue.y > minWeight)\n skinned += boneMatY * skinVertex * boneMatrixValue.y;\n \n if(boneMatrixValue.z > 0.0 && boneMatrixValue.z > minWeight)\n skinned += boneMatZ * skinVertex * boneMatrixValue.z;\n \n if(boneMatrixValue.w > 0.0 && boneMatrixValue.w > minWeight)\n skinned += boneMatW * skinVertex * boneMatrixValue.w;\n \n if(boneMatrixValue0.x > 0.0 && boneMatrixValue0.x > minWeight)\n skinned += boneMat0 * skinVertex * boneMatrixValue0.x;\n \n splatCenter = skinned.xyz;\n #endif\n\n uint sceneIndex = uint(0);\n if (sceneCount > 1) {\n sceneIndex = texture(sceneIndexesTexture, getDataUV(1, 0, sceneIndexesTextureSize)).r;\n }\n `,t&&(r+="\n float splatOpacityFromScene = sceneOpacity[sceneIndex];\n int sceneVisible = sceneVisibility[sceneIndex];\n if (splatOpacityFromScene <= 0.01 || sceneVisible == 0) {\n gl_Position = vec4(0.0, 0.0, 2.0, 1.0);\n return;\n }\n "),r+=e?"\n mat4 transform = transforms[sceneIndex];\n mat4 transformModelViewMatrix = viewMatrix * transform;\n #ifdef USE_SKINNING\n transformModelViewMatrix = transformModelViewMatrix * skinMatrix;\n #endif\n ":"mat4 transformModelViewMatrix = modelViewMatrix;",r+="\n float sh8BitCompressionRangeMinForScene = sphericalHarmonics8BitCompressionRangeMin[sceneIndex];\n float sh8BitCompressionRangeMaxForScene = sphericalHarmonics8BitCompressionRangeMax[sceneIndex];\n float sh8BitCompressionRangeForScene = sh8BitCompressionRangeMaxForScene - sh8BitCompressionRangeMinForScene;\n float sh8BitCompressionHalfRangeForScene = sh8BitCompressionRangeForScene / 2.0;\n vec3 vec8BitSHShift = vec3(sh8BitCompressionRangeMinForScene);\n\n vec4 viewCenter = transformModelViewMatrix * vec4(splatCenter, 1.0);\n\n vec4 clipCenter = projectionMatrix * viewCenter;\n\n float clip = 1.2 * clipCenter.w;\n if (clipCenter.z < -clip || clipCenter.x < -clip || clipCenter.x > clip || clipCenter.y < -clip || clipCenter.y > clip) {\n gl_Position = vec4(0.0, 0.0, 2.0, 1.0);\n return;\n }\n\n vec3 ndcCenter = clipCenter.xyz / clipCenter.w;\n\n vPosition = position.xy;\n vSplatIndex = vec2(splatIndex, splatIndex);\n\n vColor = uintToRGBAVec(sampledCenterColor.r);\n ",n>=1&&(r+=" \n if (sphericalHarmonicsDegree >= 1) {\n ",r+=e?"\n vec3 worldViewDir = normalize(splatCenter - vec3(inverse(transform) * vec4(cameraPosition, 1.0)));\n ":"\n vec3 worldViewDir = normalize(splatCenter - cameraPosition);\n ",r+="\n vec3 sh1;\n vec3 sh2;\n vec3 sh3;\n ",n>=2&&(r+="\n vec3 sh4;\n vec3 sh5;\n vec3 sh6;\n vec3 sh7;\n vec3 sh8;\n "),1===n?r+="\n if (sphericalHarmonicsMultiTextureMode == 0) {\n vec2 shUV = getDataUVF(nearestEvenIndex, 2.5, doubleOddOffset, sphericalHarmonicsTextureSize);\n vec4 sampledSH0123 = texture(sphericalHarmonicsTexture, shUV);\n shUV = getDataUVF(nearestEvenIndex, 2.5, doubleOddOffset + uint(1), sphericalHarmonicsTextureSize);\n vec4 sampledSH4567 = texture(sphericalHarmonicsTexture, shUV);\n shUV = getDataUVF(nearestEvenIndex, 2.5, doubleOddOffset + uint(2), sphericalHarmonicsTextureSize);\n vec4 sampledSH891011 = texture(sphericalHarmonicsTexture, shUV);\n sh1 = vec3(sampledSH0123.rgb) * (1.0 - fOddOffset) + vec3(sampledSH0123.ba, sampledSH4567.r) * fOddOffset;\n sh2 = vec3(sampledSH0123.a, sampledSH4567.rg) * (1.0 - fOddOffset) + vec3(sampledSH4567.gba) * fOddOffset;\n sh3 = vec3(sampledSH4567.ba, sampledSH891011.r) * (1.0 - fOddOffset) + vec3(sampledSH891011.rgb) * fOddOffset;\n } else {\n vec2 sampledSH01R = texture(sphericalHarmonicsTextureR, getDataUV(2, 0, sphericalHarmonicsTextureSize)).rg;\n vec2 sampledSH23R = texture(sphericalHarmonicsTextureR, getDataUV(2, 1, sphericalHarmonicsTextureSize)).rg;\n vec2 sampledSH01G = texture(sphericalHarmonicsTextureG, getDataUV(2, 0, sphericalHarmonicsTextureSize)).rg;\n vec2 sampledSH23G = texture(sphericalHarmonicsTextureG, getDataUV(2, 1, sphericalHarmonicsTextureSize)).rg;\n vec2 sampledSH01B = texture(sphericalHarmonicsTextureB, getDataUV(2, 0, sphericalHarmonicsTextureSize)).rg;\n vec2 sampledSH23B = texture(sphericalHarmonicsTextureB, getDataUV(2, 1, sphericalHarmonicsTextureSize)).rg;\n sh1 = vec3(sampledSH01R.rg, sampledSH23R.r);\n sh2 = vec3(sampledSH01G.rg, sampledSH23G.r);\n sh3 = vec3(sampledSH01B.rg, sampledSH23B.r);\n }\n ":2===n&&(r+="\n vec4 sampledSH0123;\n vec4 sampledSH4567;\n vec4 sampledSH891011;\n\n vec4 sampledSH0123R;\n vec4 sampledSH0123G;\n vec4 sampledSH0123B;\n\n if (sphericalHarmonicsMultiTextureMode == 0) {\n sampledSH0123 = texture(sphericalHarmonicsTexture, getDataUV(6, 0, sphericalHarmonicsTextureSize));\n sampledSH4567 = texture(sphericalHarmonicsTexture, getDataUV(6, 1, sphericalHarmonicsTextureSize));\n sampledSH891011 = texture(sphericalHarmonicsTexture, getDataUV(6, 2, sphericalHarmonicsTextureSize));\n sh1 = sampledSH0123.rgb;\n sh2 = vec3(sampledSH0123.a, sampledSH4567.rg);\n sh3 = vec3(sampledSH4567.ba, sampledSH891011.r);\n } else {\n sampledSH0123R = texture(sphericalHarmonicsTextureR, getDataUV(2, 0, sphericalHarmonicsTextureSize));\n sampledSH0123G = texture(sphericalHarmonicsTextureG, getDataUV(2, 0, sphericalHarmonicsTextureSize));\n sampledSH0123B = texture(sphericalHarmonicsTextureB, getDataUV(2, 0, sphericalHarmonicsTextureSize));\n sh1 = vec3(sampledSH0123R.rgb);\n sh2 = vec3(sampledSH0123G.rgb);\n sh3 = vec3(sampledSH0123B.rgb);\n }\n "),r+="\n if (sphericalHarmonics8BitMode == 1) {\n sh1 = sh1 * sh8BitCompressionRangeForScene + vec8BitSHShift;\n sh2 = sh2 * sh8BitCompressionRangeForScene + vec8BitSHShift;\n sh3 = sh3 * sh8BitCompressionRangeForScene + vec8BitSHShift;\n }\n float x = worldViewDir.x;\n float y = worldViewDir.y;\n float z = worldViewDir.z;\n vColor.rgb += SH_C1 * (-sh1 * y + sh2 * z - sh3 * x);\n ",n>=2&&(r+="\n if (sphericalHarmonicsDegree >= 2) {\n float xx = x * x;\n float yy = y * y;\n float zz = z * z;\n float xy = x * y;\n float yz = y * z;\n float xz = x * z;\n ",2===n&&(r+="\n if (sphericalHarmonicsMultiTextureMode == 0) {\n vec4 sampledSH12131415 = texture(sphericalHarmonicsTexture, getDataUV(6, 3, sphericalHarmonicsTextureSize));\n vec4 sampledSH16171819 = texture(sphericalHarmonicsTexture, getDataUV(6, 4, sphericalHarmonicsTextureSize));\n vec4 sampledSH20212223 = texture(sphericalHarmonicsTexture, getDataUV(6, 5, sphericalHarmonicsTextureSize));\n sh4 = sampledSH891011.gba;\n sh5 = sampledSH12131415.rgb;\n sh6 = vec3(sampledSH12131415.a, sampledSH16171819.rg);\n sh7 = vec3(sampledSH16171819.ba, sampledSH20212223.r);\n sh8 = sampledSH20212223.gba;\n } else {\n vec4 sampledSH4567R = texture(sphericalHarmonicsTextureR, getDataUV(2, 1, sphericalHarmonicsTextureSize));\n vec4 sampledSH4567G = texture(sphericalHarmonicsTextureG, getDataUV(2, 1, sphericalHarmonicsTextureSize));\n vec4 sampledSH4567B = texture(sphericalHarmonicsTextureB, getDataUV(2, 1, sphericalHarmonicsTextureSize));\n sh4 = vec3(sampledSH0123R.a, sampledSH4567R.rg);\n sh5 = vec3(sampledSH4567R.ba, sampledSH0123G.a);\n sh6 = vec3(sampledSH4567G.rgb);\n sh7 = vec3(sampledSH4567G.a, sampledSH0123B.a, sampledSH4567B.r);\n sh8 = vec3(sampledSH4567B.gba);\n }\n "),r+="\n if (sphericalHarmonics8BitMode == 1) {\n sh4 = sh4 * sh8BitCompressionRangeForScene + vec8BitSHShift;\n sh5 = sh5 * sh8BitCompressionRangeForScene + vec8BitSHShift;\n sh6 = sh6 * sh8BitCompressionRangeForScene + vec8BitSHShift;\n sh7 = sh7 * sh8BitCompressionRangeForScene + vec8BitSHShift;\n sh8 = sh8 * sh8BitCompressionRangeForScene + vec8BitSHShift;\n }\n\n vColor.rgb +=\n (SH_C2[0] * xy) * sh4 +\n (SH_C2[1] * yz) * sh5 +\n (SH_C2[2] * (2.0 * zz - xx - yy)) * sh6 +\n (SH_C2[3] * xz) * sh7 +\n (SH_C2[4] * (xx - yy)) * sh8;\n }\n "),r+="\n\n vColor.rgb = clamp(vColor.rgb, vec3(0.), vec3(1.));\n\n }\n\n "),r}static getVertexShaderFadeIn(){return"\n if (fadeInComplete == 0) {\n float opacityAdjust = 1.0;\n float centerDist = length(splatCenter - sceneCenter);\n float renderTime = max(currentTime - firstRenderTime, 0.0);\n\n float fadeDistance = 0.75;\n float distanceLoadFadeInFactor = step(visibleRegionFadeStartRadius, centerDist);\n distanceLoadFadeInFactor = (1.0 - distanceLoadFadeInFactor) +\n (1.0 - clamp((centerDist - visibleRegionFadeStartRadius) / fadeDistance, 0.0, 1.0)) *\n distanceLoadFadeInFactor;\n opacityAdjust *= distanceLoadFadeInFactor;\n vColor.a *= opacityAdjust;\n }\n "}static getUniforms(e=!1,t=!1,n=0,i=1,r=!1){const s={sceneCenter:{type:"v3",value:new hi},fadeInComplete:{type:"i",value:0},orthographicMode:{type:"i",value:0},visibleRegionFadeStartRadius:{type:"f",value:0},visibleRegionRadius:{type:"f",value:0},bindMatrix:{type:"m4",value:new or},bindMatrixInverse:{type:"m4",value:new or},currentTime:{type:"f",value:0},firstRenderTime:{type:"f",value:0},centersColorsTexture:{type:"t",value:null},flameModelTexture:{type:"t",value:null},boneTexture:{type:"t",value:null},boneTexture0:{type:"t",value:null},boneWeightTexture:{type:"t",value:null},sphericalHarmonicsTexture:{type:"t",value:null},sphericalHarmonicsTextureR:{type:"t",value:null},sphericalHarmonicsTextureG:{type:"t",value:null},sphericalHarmonicsTextureB:{type:"t",value:null},sphericalHarmonics8BitCompressionRangeMin:{type:"f",value:[]},sphericalHarmonics8BitCompressionRangeMax:{type:"f",value:[]},focal:{type:"v2",value:new li},orthoZoom:{type:"f",value:1},inverseFocalAdjustment:{type:"f",value:1},viewport:{type:"v2",value:new li},basisViewport:{type:"v2",value:new li},debugColor:{type:"v3",value:new $r},centersColorsTextureSize:{type:"v2",value:new li(1024,1024)},flameModelTextureSize:{type:"v2",value:new li(4096,2048)},boneTextureSize:{type:"v2",value:new li(4,32)},boneWeightTextureSize:{type:"v2",value:new li(512,512)},sphericalHarmonicsDegree:{type:"i",value:n},sphericalHarmonicsTextureSize:{type:"v2",value:new li(1024,1024)},sphericalHarmonics8BitMode:{type:"i",value:0},sphericalHarmonicsMultiTextureMode:{type:"i",value:0},splatScale:{type:"f",value:i},pointCloudModeEnabled:{type:"i",value:r?1:0},sceneIndexesTexture:{type:"t",value:null},sceneIndexesTextureSize:{type:"v2",value:new li(1024,1024)},sceneCount:{type:"i",value:1},gaussianSplatCount:{type:"i",value:1},bsCount:{type:"i",value:1},headBoneIndex:{type:"f",value:-1},eyeBlinkLeft:{type:"f",value:0},eyeBlinkRight:{type:"f",value:0}};for(let a=0;a<np.MaxScenes;a++)s.sphericalHarmonics8BitCompressionRangeMin.value.push(-1.5),s.sphericalHarmonics8BitCompressionRangeMax.value.push(np.SphericalHarmonics8BitCompressionRange/2);if(t){const e=[];for(let n=0;n<np.MaxScenes;n++)e.push(1);s.sceneOpacity={type:"f",value:e};const t=[];for(let n=0;n<np.MaxScenes;n++)t.push(1);s.sceneVisibility={type:"i",value:t}}if(e){const e=[];for(let t=0;t<np.MaxScenes;t++)e.push(new or);s.transforms={type:"mat4",value:e}}return s}}class mf{static build(e=!1,t=!1,n=!1,i=2048,r=1,s=!1,a=0,o=.3,l=null){let c=ff.buildVertexShaderBase(e,t,a,"\n uniform vec2 covariancesTextureSize;\n uniform highp sampler2D covariancesTexture;\n uniform highp usampler2D covariancesTextureHalfFloat;\n uniform int covariancesAreHalfFloat;\n\n void fromCovarianceHalfFloatV4(uvec4 val, out vec4 first, out vec4 second) {\n vec2 r = unpackHalf2x16(val.r);\n vec2 g = unpackHalf2x16(val.g);\n vec2 b = unpackHalf2x16(val.b);\n\n first = vec4(r.x, r.y, g.x, g.y);\n second = vec4(b.x, b.y, 0.0, 0.0);\n }\n ");c+=mf.buildVertexShaderProjection(n,t,i,o);const h=mf.buildFragmentShader(l),u=ff.getUniforms(e,t,a,r,s);return u.covariancesTextureSize={type:"v2",value:new li(1024,1024)},u.covariancesTexture={type:"t",value:null},u.covariancesTextureHalfFloat={type:"t",value:null},u.covariancesAreHalfFloat={type:"i",value:0},new zs({uniforms:u,vertexShader:c,fragmentShader:h,transparent:!0,alphaTest:1,blending:1,depthTest:!0,depthWrite:!1,side:2})}static buildVertexShaderProjection(e,t,n,i){let r="\n\n vec4 sampledCovarianceA;\n vec4 sampledCovarianceB;\n vec3 cov3D_M11_M12_M13;\n vec3 cov3D_M22_M23_M33;\n if (covariancesAreHalfFloat == 0) {\n sampledCovarianceA = texture(covariancesTexture, getDataUVF(nearestEvenIndex, 1.5, oddOffset,\n covariancesTextureSize));\n sampledCovarianceB = texture(covariancesTexture, getDataUVF(nearestEvenIndex, 1.5, oddOffset + uint(1),\n covariancesTextureSize));\n\n cov3D_M11_M12_M13 = vec3(sampledCovarianceA.rgb) * (1.0 - fOddOffset) +\n vec3(sampledCovarianceA.ba, sampledCovarianceB.r) * fOddOffset;\n cov3D_M22_M23_M33 = vec3(sampledCovarianceA.a, sampledCovarianceB.rg) * (1.0 - fOddOffset) +\n vec3(sampledCovarianceB.gba) * fOddOffset;\n } else {\n uvec4 sampledCovarianceU = texture(covariancesTextureHalfFloat, getDataUV(1, 0, covariancesTextureSize));\n fromCovarianceHalfFloatV4(sampledCovarianceU, sampledCovarianceA, sampledCovarianceB);\n cov3D_M11_M12_M13 = sampledCovarianceA.rgb;\n cov3D_M22_M23_M33 = vec3(sampledCovarianceA.a, sampledCovarianceB.rg);\n }\n \n // Construct the 3D covariance matrix\n mat3 Vrk = mat3(\n cov3D_M11_M12_M13.x, cov3D_M11_M12_M13.y, cov3D_M11_M12_M13.z,\n cov3D_M11_M12_M13.y, cov3D_M22_M23_M33.x, cov3D_M22_M23_M33.y,\n cov3D_M11_M12_M13.z, cov3D_M22_M23_M33.y, cov3D_M22_M23_M33.z\n );\n\n mat3 J;\n if (orthographicMode == 1) {\n // Since the projection is linear, we don't need an approximation\n J = transpose(mat3(orthoZoom, 0.0, 0.0,\n 0.0, orthoZoom, 0.0,\n 0.0, 0.0, 0.0));\n } else {\n // Construct the Jacobian of the affine approximation of the projection matrix. It will be used to transform the\n // 3D covariance matrix instead of using the actual projection matrix because that transformation would\n // require a non-linear component (perspective division) which would yield a non-gaussian result.\n float s = 1.0 / (viewCenter.z * viewCenter.z);\n J = mat3(\n focal.x / viewCenter.z, 0., -(focal.x * viewCenter.x) * s,\n 0., focal.y / viewCenter.z, -(focal.y * viewCenter.y) * s,\n 0., 0., 0.\n );\n }\n\n // Concatenate the projection approximation with the model-view transformation\n mat3 W = transpose(mat3(transformModelViewMatrix));\n mat3 T = W * J;\n\n // Transform the 3D covariance matrix (Vrk) to compute the 2D covariance matrix\n mat3 cov2Dm = transpose(T) * Vrk * T;\n ";return r+=e?`\n float detOrig = cov2Dm[0][0] * cov2Dm[1][1] - cov2Dm[0][1] * cov2Dm[0][1];\n cov2Dm[0][0] += ${i};\n cov2Dm[1][1] += ${i};\n float detBlur = cov2Dm[0][0] * cov2Dm[1][1] - cov2Dm[0][1] * cov2Dm[0][1];\n vColor.a *= sqrt(max(detOrig / detBlur, 0.0));\n if (vColor.a < minAlpha) return;\n `:`\n cov2Dm[0][0] += ${i};\n cov2Dm[1][1] += ${i};\n `,r+=`\n\n // We are interested in the upper-left 2x2 portion of the projected 3D covariance matrix because\n // we only care about the X and Y values. We want the X-diagonal, cov2Dm[0][0],\n // the Y-diagonal, cov2Dm[1][1], and the correlation between the two cov2Dm[0][1]. We don't\n // need cov2Dm[1][0] because it is a symetric matrix.\n vec3 cov2Dv = vec3(cov2Dm[0][0], cov2Dm[0][1], cov2Dm[1][1]);\n\n // We now need to solve for the eigen-values and eigen vectors of the 2D covariance matrix\n // so that we can determine the 2D basis for the splat. This is done using the method described\n // here: https://people.math.harvard.edu/~knill/teaching/math21b2004/exhibits/2dmatrices/index.html\n // After calculating the eigen-values and eigen-vectors, we calculate the basis for rendering the splat\n // by normalizing the eigen-vectors and then multiplying them by (sqrt(8) * sqrt(eigen-value)), which is\n // equal to scaling them by sqrt(8) standard deviations.\n //\n // This is a different approach than in the original work at INRIA. In that work they compute the\n // max extents of the projected splat in screen space to form a screen-space aligned bounding rectangle\n // which forms the geometry that is actually rasterized. The dimensions of that bounding box are 3.0\n // times the square root of the maximum eigen-value, or 3 standard deviations. They then use the inverse\n // 2D covariance matrix (called 'conic') in the CUDA rendering thread to determine fragment opacity by\n // calculating the full gaussian: exp(-0.5 * (X - mean) * conic * (X - mean)) * splat opacity\n float a = cov2Dv.x;\n float d = cov2Dv.z;\n float b = cov2Dv.y;\n float D = a * d - b * b;\n float trace = a + d;\n float traceOver2 = 0.5 * trace;\n float term2 = sqrt(max(0.1f, traceOver2 * traceOver2 - D));\n float eigenValue1 = traceOver2 + term2;\n float eigenValue2 = traceOver2 - term2;\n\n if (pointCloudModeEnabled == 1) {\n eigenValue1 = eigenValue2 = 0.2;\n }\n\n if (eigenValue2 <= 0.0) return;\n\n vec2 eigenVector1 = normalize(vec2(b, eigenValue1 - a));\n // since the eigen vectors are orthogonal, we derive the second one from the first\n vec2 eigenVector2 = vec2(eigenVector1.y, -eigenVector1.x);\n\n // We use sqrt(8) standard deviations instead of 3 to eliminate more of the splat with a very low opacity.\n vec2 basisVector1 = eigenVector1 * splatScale * min(sqrt8 * sqrt(eigenValue1), ${parseInt(n)}.0);\n vec2 basisVector2 = eigenVector2 * splatScale * min(sqrt8 * sqrt(eigenValue2), ${parseInt(n)}.0);\n `,t&&(r+="\n vColor.a *= splatOpacityFromScene;\n "),r+="\n vec2 ndcOffset = vec2(vPosition.x * basisVector1 + vPosition.y * basisVector2) *\n basisViewport * 2.0 * inverseFocalAdjustment;\n\n vec4 quadPos = vec4(ndcCenter.xy + ndcOffset, ndcCenter.z, 1.0);\n gl_Position = quadPos;\n\n // Scale the position data we send to the fragment shader\n vPosition *= sqrt8;\n ",r+=ff.getVertexShaderFadeIn(),r+="}",r}static buildFragmentShader(e=null){let t="\n precision highp float;\n #include <common>\n\n uniform float eyeBlinkLeft;\n uniform float eyeBlinkRight;\n\n varying vec4 vColor;\n varying vec2 vUv;\n varying vec2 vPosition;\n varying vec2 vSplatIndex;\n ";return t+="\n void main () {\n float A = dot(vPosition, vPosition);\n float opacity = exp(-0.5 * A) * vColor.a;\n if (opacity < 1.0 / 255.0)\n discard;\n ",e&&(e.right_iris||e.left_iris)?(t+="\n float idx = vSplatIndex.x;\n ",e.right_iris&&e.right_iris.length>0?t+=`\n // Check if this splat is part of right iris\n bool isRightIris = ${e.right_iris.map(([e,t])=>`(idx >= ${e}.0 && idx <= ${t}.0)`).join(" ||\n ")};\n `:t+="\n bool isRightIris = false;\n ",e.left_iris&&e.left_iris.length>0?t+=`\n // Check if this splat is part of left iris\n bool isLeftIris = ${e.left_iris.map(([e,t])=>`(idx >= ${e}.0 && idx <= ${t}.0)`).join(" ||\n ")};\n `:t+="\n bool isLeftIris = false;\n ",t+="\n float finalOpacity = opacity;\n\n // Smooth fade: iris fades out as eye closes (blink increases)\n // smoothstep(0.1, 0.5, blink) = 0 when blink<0.1, 1 when blink>0.5\n if (isRightIris) {\n float fadeFactor = 1.0 - smoothstep(0.1, 0.5, eyeBlinkRight);\n finalOpacity = opacity * fadeFactor;\n } else if (isLeftIris) {\n float fadeFactor = 1.0 - smoothstep(0.1, 0.5, eyeBlinkLeft);\n finalOpacity = opacity * fadeFactor;\n }\n\n if (finalOpacity < 1.0 / 255.0)\n discard;\n\n gl_FragColor = vec4(vColor.rgb, finalOpacity);\n }\n "):t+="\n gl_FragColor = vec4(vColor.rgb, opacity);\n }\n ",t}}class gf{static build(e=!1,t=!1,n=1,i=!1,r=0){let s=ff.buildVertexShaderBase(e,t,r,"\n uniform vec2 scaleRotationsTextureSize;\n uniform highp sampler2D scaleRotationsTexture;\n varying mat3 vT;\n varying vec2 vQuadCenter;\n varying vec2 vFragCoord;\n ");s+=gf.buildVertexShaderProjection();const a=gf.buildFragmentShader(),o=ff.getUniforms(e,t,r,n,i);return o.scaleRotationsTexture={type:"t",value:null},o.scaleRotationsTextureSize={type:"v2",value:new li(1024,1024)},new zs({uniforms:o,vertexShader:s,fragmentShader:a,transparent:!0,alphaTest:1,blending:1,depthTest:!0,depthWrite:!1,side:2})}static buildVertexShaderProjection(){let e="\n\n vec4 scaleRotationA = texture(scaleRotationsTexture, getDataUVF(nearestEvenIndex, 1.5,\n oddOffset, scaleRotationsTextureSize));\n vec4 scaleRotationB = texture(scaleRotationsTexture, getDataUVF(nearestEvenIndex, 1.5,\n oddOffset + uint(1), scaleRotationsTextureSize));\n\n vec3 scaleRotation123 = vec3(scaleRotationA.rgb) * (1.0 - fOddOffset) +\n vec3(scaleRotationA.ba, scaleRotationB.r) * fOddOffset;\n vec3 scaleRotation456 = vec3(scaleRotationA.a, scaleRotationB.rg) * (1.0 - fOddOffset) +\n vec3(scaleRotationB.gba) * fOddOffset;\n\n float missingW = sqrt(1.0 - scaleRotation456.x * scaleRotation456.x - scaleRotation456.y *\n scaleRotation456.y - scaleRotation456.z * scaleRotation456.z);\n mat3 R = quaternionToRotationMatrix(scaleRotation456.r, scaleRotation456.g, scaleRotation456.b, missingW);\n mat3 S = mat3(scaleRotation123.r, 0.0, 0.0,\n 0.0, scaleRotation123.g, 0.0,\n 0.0, 0.0, scaleRotation123.b);\n \n mat3 L = R * S;\n\n mat3x4 splat2World = mat3x4(vec4(L[0], 0.0),\n vec4(L[1], 0.0),\n vec4(splatCenter.x, splatCenter.y, splatCenter.z, 1.0));\n\n mat4 world2ndc = transpose(projectionMatrix * transformModelViewMatrix);\n\n mat3x4 ndc2pix = mat3x4(vec4(viewport.x / 2.0, 0.0, 0.0, (viewport.x - 1.0) / 2.0),\n vec4(0.0, viewport.y / 2.0, 0.0, (viewport.y - 1.0) / 2.0),\n vec4(0.0, 0.0, 0.0, 1.0));\n\n mat3 T = transpose(splat2World) * world2ndc * ndc2pix;\n vec3 normal = vec3(viewMatrix * vec4(L[0][2], L[1][2], L[2][2], 0.0));\n ";return e+="\n\n mat4 splat2World4 = mat4(vec4(L[0], 0.0),\n vec4(L[1], 0.0),\n vec4(L[2], 0.0),\n vec4(splatCenter.x, splatCenter.y, splatCenter.z, 1.0));\n\n mat4 Tt = transpose(transpose(splat2World4) * world2ndc);\n\n vec4 tempPoint1 = Tt * vec4(1.0, 0.0, 0.0, 1.0);\n tempPoint1 /= tempPoint1.w;\n\n vec4 tempPoint2 = Tt * vec4(0.0, 1.0, 0.0, 1.0);\n tempPoint2 /= tempPoint2.w;\n\n vec4 center = Tt * vec4(0.0, 0.0, 0.0, 1.0);\n center /= center.w;\n\n vec2 basisVector1 = tempPoint1.xy - center.xy;\n vec2 basisVector2 = tempPoint2.xy - center.xy;\n\n vec2 basisVector1Screen = basisVector1 * 0.5 * viewport;\n vec2 basisVector2Screen = basisVector2 * 0.5 * viewport;\n\n const float minPix = 1.;\n if (length(basisVector1Screen) < minPix || length(basisVector2Screen) < minPix) {\n \n vec3 T0 = vec3(T[0][0], T[0][1], T[0][2]);\n vec3 T1 = vec3(T[1][0], T[1][1], T[1][2]);\n vec3 T3 = vec3(T[2][0], T[2][1], T[2][2]);\n\n vec3 tempPoint = vec3(1.0, 1.0, -1.0);\n float distance = (T3.x * T3.x * tempPoint.x) + (T3.y * T3.y * tempPoint.y) + (T3.z * T3.z * tempPoint.z);\n vec3 f = (1.0 / distance) * tempPoint;\n if (abs(distance) < 0.00001) return;\n\n float pointImageX = (T0.x * T3.x * f.x) + (T0.y * T3.y * f.y) + (T0.z * T3.z * f.z);\n float pointImageY = (T1.x * T3.x * f.x) + (T1.y * T3.y * f.y) + (T1.z * T3.z * f.z);\n vec2 pointImage = vec2(pointImageX, pointImageY);\n\n float tempX = (T0.x * T0.x * f.x) + (T0.y * T0.y * f.y) + (T0.z * T0.z * f.z);\n float tempY = (T1.x * T1.x * f.x) + (T1.y * T1.y * f.y) + (T1.z * T1.z * f.z);\n vec2 temp = vec2(tempX, tempY);\n\n vec2 halfExtend = pointImage * pointImage - temp;\n vec2 extent = sqrt(max(vec2(0.0001), halfExtend));\n float radius = max(extent.x, extent.y);\n\n vec2 ndcOffset = ((position.xy * radius * 3.0) * basisViewport * 2.0);\n\n vec4 quadPos = vec4(ndcCenter.xy + ndcOffset, ndcCenter.z, 1.0);\n gl_Position = quadPos;\n\n vT = T;\n vQuadCenter = pointImage;\n vFragCoord = (quadPos.xy * 0.5 + 0.5) * viewport;\n \n } else {\n vec2 ndcOffset = vec2(position.x * basisVector1 + position.y * basisVector2) * 3.0 * inverseFocalAdjustment;\n vec4 quadPos = vec4(ndcCenter.xy + ndcOffset, ndcCenter.z, 1.0);\n gl_Position = quadPos;\n\n vT = T;\n vQuadCenter = center.xy;\n vFragCoord = (quadPos.xy * 0.5 + 0.5) * viewport;\n }\n ",e+=ff.getVertexShaderFadeIn(),e+="}",e}static buildFragmentShader(){return"\n precision highp float;\n #include <common>\n\n uniform vec3 debugColor;\n\n varying vec4 vColor;\n varying vec2 vUv;\n varying vec2 vPosition;\n varying mat3 vT;\n varying vec2 vQuadCenter;\n varying vec2 vFragCoord;\n\n void main () {\n\n const float FilterInvSquare = 2.0;\n const float near_n = 0.2;\n const float T = 1.0;\n\n vec2 xy = vQuadCenter;\n vec3 Tu = vT[0];\n vec3 Tv = vT[1];\n vec3 Tw = vT[2];\n vec3 k = vFragCoord.x * Tw - Tu;\n vec3 l = vFragCoord.y * Tw - Tv;\n vec3 p = cross(k, l);\n if (p.z == 0.0) discard;\n vec2 s = vec2(p.x / p.z, p.y / p.z);\n float rho3d = (s.x * s.x + s.y * s.y); \n vec2 d = vec2(xy.x - vFragCoord.x, xy.y - vFragCoord.y);\n float rho2d = FilterInvSquare * (d.x * d.x + d.y * d.y); \n\n // compute intersection and depth\n float rho = min(rho3d, rho2d);\n float depth = (rho3d <= rho2d) ? (s.x * Tw.x + s.y * Tw.y) + Tw.z : Tw.z; \n if (depth < near_n) discard;\n // vec4 nor_o = collected_normal_opacity[j];\n // float normal[3] = {nor_o.x, nor_o.y, nor_o.z};\n float opa = vColor.a;\n\n float power = -0.5f * rho;\n if (power > 0.0f) discard;\n\n // Eq. (2) from 3D Gaussian splatting paper.\n // Obtain alpha by multiplying with Gaussian opacity\n // and its exponential falloff from mean.\n // Avoid numerical instabilities (see paper appendix). \n float alpha = min(0.99f, opa * exp(power));\n if (alpha < 1.0f / 255.0f) discard;\n float test_T = T * (1.0 - alpha);\n if (test_T < 0.0001)discard;\n\n float w = alpha * T;\n gl_FragColor = vec4(vColor.rgb, w);\n }\n "}}const _f=Sp("SplatMesh"),vf=new Ss,xf=new is;function yf(e){const t={};function n(n){if(void 0!==t[n])return t[n];let i;switch(n){case"WEBGL_depth_texture":i=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("MOZ_EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":i=e.getExtension("WEBGL_compressed_texture_s3tc")||e.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":i=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:i=e.getExtension(n)}return t[n]=i,i}return{has:function(e){return null!==n(e)},init:function(e){e.isWebGL2?(n("EXT_color_buffer_float"),n("WEBGL_clip_cull_distance")):(n("WEBGL_depth_texture"),n("OES_texture_float"),n("OES_texture_half_float"),n("OES_texture_half_float_linear"),n("OES_standard_derivatives"),n("OES_element_index_uint"),n("OES_vertex_array_object"),n("ANGLE_instanced_arrays")),n("OES_texture_float_linear"),n("EXT_color_buffer_half_float"),n("WEBGL_multisampled_render_to_texture")},get:function(e){const t=n(e);return null===t&&_f.warn("THREE.WebGLRenderer: "+e+" extension not supported."),t}}}function Sf(e,t,n){let i;function r(t){if("highp"===t){if(e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.HIGH_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0)return"highp";t="mediump"}return"mediump"===t&&e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}const s="undefined"!=typeof WebGL2RenderingContext&&"WebGL2RenderingContext"===e.constructor.name;let a=void 0!==n.precision?n.precision:"highp";const o=r(a);o!==a&&(_f.warn("THREE.WebGLRenderer:",a,"not supported, using",o,"instead."),a=o);const l=s||t.has("WEBGL_draw_buffers"),c=!0===n.logarithmicDepthBuffer,h=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),u=e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS),d=e.getParameter(e.MAX_TEXTURE_SIZE),p=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),f=e.getParameter(e.MAX_VERTEX_ATTRIBS),m=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),g=e.getParameter(e.MAX_VARYING_VECTORS),_=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),v=u>0,x=s||t.has("OES_texture_float");return{isWebGL2:s,drawBuffers:l,getMaxAnisotropy:function(){if(void 0!==i)return i;if(!0===t.has("EXT_texture_filter_anisotropic")){const n=t.get("EXT_texture_filter_anisotropic");i=e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else i=0;return i},getMaxPrecision:r,precision:a,logarithmicDepthBuffer:c,maxTextures:h,maxVertexTextures:u,maxTextureSize:d,maxCubemapSize:p,maxAttributes:f,maxVertexUniforms:m,maxVaryings:g,maxFragmentUniforms:_,vertexTextures:v,floatFragmentTextures:x,floatVertexTextures:v&&x,maxSamples:s?e.getParameter(e.MAX_SAMPLES):0}}function Af(e,t,n){const i=n.isWebGL2;return{convert:function(n,r){let s;if(n===ht)return e.UNSIGNED_BYTE;if(1017===n)return e.UNSIGNED_SHORT_4_4_4_4;if(1018===n)return e.UNSIGNED_SHORT_5_5_5_1;if(1010===n)return e.BYTE;if(1011===n)return e.SHORT;if(1012===n)return e.UNSIGNED_SHORT;if(1013===n)return e.INT;if(1014===n)return e.UNSIGNED_INT;if(n===gt)return e.FLOAT;if(n===_t)return i?e.HALF_FLOAT:(s=t.get("OES_texture_half_float"),null!==s?s.HALF_FLOAT_OES:null);if(1021===n)return e.ALPHA;if(1022===n)return e.RGB;if(n===bt)return e.RGBA;if(1024===n)return e.LUMINANCE;if(1025===n)return e.LUMINANCE_ALPHA;if(1026===n)return e.DEPTH_COMPONENT;if(1027===n)return e.DEPTH_STENCIL;if(n===Tt)return e.RED;if(n===Et)return e.RED_INTEGER;if(n===Ct)return e.RG;if(n===Rt)return e.RG_INTEGER;if(1032===n)return e.RGB_INTEGER;if(n===It)return e.RGBA_INTEGER;if(33776===n||33777===n||33778===n||33779===n){if(s=t.get("WEBGL_compressed_texture_s3tc"),null===s)return null;if(33776===n)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(33777===n)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(33778===n)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(33779===n)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(35840===n||35841===n||35842===n||35843===n){if(s=t.get("WEBGL_compressed_texture_pvrtc"),null===s)return null;if(35840===n)return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(35841===n)return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(35842===n)return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(35843===n)return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(36196===n)return s=t.get("WEBGL_compressed_texture_etc1"),null!==s?s.COMPRESSED_RGB_ETC1_WEBGL:null;if(n>=37808&&n<=37814||n>=37840&&n<=37846)return s=t.get("WEBGL_compressed_texture_astc"),null!==s?n:null;if(36492===n||36494===n||36495===n)return s=t.get("EXT_texture_compression_bptc"),null!==s?n:null;if(34042===n)return e.UNSIGNED_INT_24_8;if(i){if(6407===n)return e.RGB;if(6408===n)return e.RGBA}return void 0!==e[n]?e[n]:null}}}const bf=16777216;class Mf extends Bs{constructor(e=ep,t=!1,n=!1,r=!1,s=1,a=!0,o=!1,l=!1,c=1024,h=Xd,u=0,d=1,p=.3){super(vf,xf),i(this,"buildSplatTree",(e=[],t,n)=>new Promise(i=>{this.disposeSplatTree(),this.baseSplatTree=new pf(8,1e3);const r=performance.now(),s=new Ri;this.baseSplatTree.processSplatMesh(this,t=>{this.getSplatColor(t,s);const n=this.getSceneIndexForSplat(t),i=e[n]||1;return s.w>=i},t,n).then(()=>{const e=performance.now()-r;if(this.logLevel>=qd&&_f.info("SplatTree build: "+e+" ms"),this.disposed)i();else{this.splatTree=this.baseSplatTree,this.baseSplatTree=null;let e=0,t=0,n=0;this.splatTree.visitLeaves(i=>{const r=i.data.indexes.length;r>0&&(t+=r,n++,e++)}),this.logLevel>=qd&&(_f.info(`SplatTree leaves: ${this.splatTree.countLeaves()}`),_f.info(`SplatTree leaves with splats:${e}`),t/=n,_f.info(`Avg splat count per node: ${t}`),_f.info(`Total splat count: ${this.getSplatCount()}`)),i()}})})),i(this,"updateUniforms",function(){const e=new li;return function(t,n,i,r,s,a){if(this.getSplatCount()>0){if(e.set(t.x*this.devicePixelRatio,t.y*this.devicePixelRatio),this.material.uniforms.viewport.value.copy(e),this.material.uniforms.basisViewport.value.set(1/e.x,1/e.y),this.material.uniforms.focal.value.set(n,i),this.material.uniforms.orthographicMode.value=r?1:0,this.material.uniforms.orthoZoom.value=s,this.material.uniforms.inverseFocalAdjustment.value=a,this.dynamicMode)for(let e=0;e<this.scenes.length;e++)this.material.uniforms.transforms.value[e].copy(this.getScene(e).transform);if(this.enableOptionalEffects)for(let e=0;e<this.scenes.length;e++)this.material.uniforms.sceneOpacity.value[e]=Mp(this.getScene(e).opacity,0,1),this.material.uniforms.sceneVisibility.value[e]=this.getScene(e).visible?1:0,this.material.uniformsNeedUpdate=!0;this.material.uniformsNeedUpdate=!0}}}()),i(this,"setupDistancesComputationTransformFeedback",function(){let e;return()=>{const t=this.getMaxSplatCount();if(!this.renderer)return;const n=this.lastRenderer!==this.renderer,i=e!==t;if(!n&&!i)return;n?this.disposeDistancesComputationGPUResources():i&&this.disposeDistancesComputationGPUBufferResources();const r=this.renderer.getContext(),s=(e,t,n)=>{const i=e.createShader(t);if(!i)return _f.error("Fatal error: gl could not create a shader object."),null;if(e.shaderSource(i,n),e.compileShader(i),!e.getShaderParameter(i,e.COMPILE_STATUS)){let n="unknown";t===e.VERTEX_SHADER?n="vertex shader":t===e.FRAGMENT_SHADER&&(n="fragement shader");const r=e.getShaderInfoLog(i);return _f.error("Failed to compile "+n+" with these errors:"+r),e.deleteShader(i),null}return i};let a;this.integerBasedDistancesComputation?(a="#version 300 es\n in ivec4 center;\n flat out int distance;",this.dynamicMode?a+=`\n in uint sceneIndex;\n uniform ivec4 transforms[${np.MaxScenes}];\n void main(void) {\n ivec4 transform = transforms[sceneIndex];\n distance = center.x * transform.x + center.y * transform.y + center.z * transform.z + transform.w * center.w;\n }\n `:a+="\n uniform ivec3 modelViewProj;\n void main(void) {\n distance = center.x * modelViewProj.x + center.y * modelViewProj.y + center.z * modelViewProj.z;\n }\n "):(a="#version 300 es\n in vec4 center;\n flat out float distance;",this.dynamicMode?a+=`\n in uint sceneIndex;\n uniform mat4 transforms[${np.MaxScenes}];\n void main(void) {\n vec4 transformedCenter = transforms[sceneIndex] * vec4(center.xyz, 1.0);\n distance = transformedCenter.z;\n }\n `:a+="\n uniform vec3 modelViewProj;\n void main(void) {\n distance = center.x * modelViewProj.x + center.y * modelViewProj.y + center.z * modelViewProj.z;\n }\n ");const o=r.getParameter(r.VERTEX_ARRAY_BINDING),l=r.getParameter(r.CURRENT_PROGRAM),c=!!l&&r.getProgramParameter(l,r.DELETE_STATUS);if(n&&(this.distancesTransformFeedback.vao=r.createVertexArray()),r.bindVertexArray(this.distancesTransformFeedback.vao),n){const e=r.createProgram(),t=s(r,r.VERTEX_SHADER,a),n=s(r,r.FRAGMENT_SHADER,"#version 300 es\n precision lowp float;\n out vec4 fragColor;\n void main(){}\n ");if(!t||!n)throw new Error("Could not compile shaders for distances computation on GPU.");if(r.attachShader(e,t),r.attachShader(e,n),r.transformFeedbackVaryings(e,["distance"],r.SEPARATE_ATTRIBS),r.linkProgram(e),!r.getProgramParameter(e,r.LINK_STATUS)){const i=r.getProgramInfoLog(e);throw _f.error("Fatal error: Failed to link program: "+i),r.deleteProgram(e),r.deleteShader(n),r.deleteShader(t),new Error("Could not link shaders for distances computation on GPU.")}this.distancesTransformFeedback.program=e,this.distancesTransformFeedback.vertexShader=t,this.distancesTransformFeedback.vertexShader=n}if(r.useProgram(this.distancesTransformFeedback.program),this.distancesTransformFeedback.centersLoc=r.getAttribLocation(this.distancesTransformFeedback.program,"center"),this.dynamicMode){this.distancesTransformFeedback.sceneIndexesLoc=r.getAttribLocation(this.distancesTransformFeedback.program,"sceneIndex");for(let e=0;e<this.scenes.length;e++)this.distancesTransformFeedback.transformsLocs[e]=r.getUniformLocation(this.distancesTransformFeedback.program,`transforms[${e}]`)}else this.distancesTransformFeedback.modelViewProjLoc=r.getUniformLocation(this.distancesTransformFeedback.program,"modelViewProj");(n||i)&&(this.distancesTransformFeedback.centersBuffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,this.distancesTransformFeedback.centersBuffer),r.enableVertexAttribArray(this.distancesTransformFeedback.centersLoc),this.integerBasedDistancesComputation?r.vertexAttribIPointer(this.distancesTransformFeedback.centersLoc,4,r.INT,0,0):r.vertexAttribPointer(this.distancesTransformFeedback.centersLoc,4,r.FLOAT,!1,0,0),this.dynamicMode&&(this.distancesTransformFeedback.sceneIndexesBuffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,this.distancesTransformFeedback.sceneIndexesBuffer),r.enableVertexAttribArray(this.distancesTransformFeedback.sceneIndexesLoc),r.vertexAttribIPointer(this.distancesTransformFeedback.sceneIndexesLoc,1,r.UNSIGNED_INT,0,0))),(n||i)&&(this.distancesTransformFeedback.outDistancesBuffer=r.createBuffer()),r.bindBuffer(r.ARRAY_BUFFER,this.distancesTransformFeedback.outDistancesBuffer),r.bufferData(r.ARRAY_BUFFER,4*t,r.STATIC_READ),n&&(this.distancesTransformFeedback.id=r.createTransformFeedback()),r.bindTransformFeedback(r.TRANSFORM_FEEDBACK,this.distancesTransformFeedback.id),r.bindBufferBase(r.TRANSFORM_FEEDBACK_BUFFER,0,this.distancesTransformFeedback.outDistancesBuffer),l&&!0!==c&&r.useProgram(l),o&&r.bindVertexArray(o),this.lastRenderer=this.renderer,e=t}}()),i(this,"fillTransformsArray",function(){const e=[];return function(t){e.length!==t.length&&(e.length=t.length);for(let n=0;n<this.scenes.length;n++){const t=this.getScene(n).transform.elements;for(let i=0;i<16;i++)e[16*n+i]=t[i]}t.set(e)}}()),i(this,"computeDistancesOnGPU",function(){const e=new or;return(t,n)=>{if(!this.renderer)return;const i=this.renderer.getContext(),r=i.getParameter(i.VERTEX_ARRAY_BINDING),s=i.getParameter(i.CURRENT_PROGRAM),a=!!s&&i.getProgramParameter(s,i.DELETE_STATUS);if(i.bindVertexArray(this.distancesTransformFeedback.vao),i.useProgram(this.distancesTransformFeedback.program),i.enable(i.RASTERIZER_DISCARD),this.dynamicMode)for(let c=0;c<this.scenes.length;c++)if(e.copy(this.getScene(c).transform),e.premultiply(t),this.integerBasedDistancesComputation){const t=Mf.getIntegerMatrixArray(e),n=[t[2],t[6],t[10],t[14]];i.uniform4i(this.distancesTransformFeedback.transformsLocs[c],n[0],n[1],n[2],n[3])}else i.uniformMatrix4fv(this.distancesTransformFeedback.transformsLocs[c],!1,e.elements);else if(this.integerBasedDistancesComputation){const e=Mf.getIntegerMatrixArray(t),n=[e[2],e[6],e[10]];i.uniform3i(this.distancesTransformFeedback.modelViewProjLoc,n[0],n[1],n[2])}else{const e=[t.elements[2],t.elements[6],t.elements[10]];i.uniform3f(this.distancesTransformFeedback.modelViewProjLoc,e[0],e[1],e[2])}i.bindBuffer(i.ARRAY_BUFFER,this.distancesTransformFeedback.centersBuffer),i.enableVertexAttribArray(this.distancesTransformFeedback.centersLoc),this.integerBasedDistancesComputation?i.vertexAttribIPointer(this.distancesTransformFeedback.centersLoc,4,i.INT,0,0):i.vertexAttribPointer(this.distancesTransformFeedback.centersLoc,4,i.FLOAT,!1,0,0),this.dynamicMode&&(i.bindBuffer(i.ARRAY_BUFFER,this.distancesTransformFeedback.sceneIndexesBuffer),i.enableVertexAttribArray(this.distancesTransformFeedback.sceneIndexesLoc),i.vertexAttribIPointer(this.distancesTransformFeedback.sceneIndexesLoc,1,i.UNSIGNED_INT,0,0)),i.bindTransformFeedback(i.TRANSFORM_FEEDBACK,this.distancesTransformFeedback.id),i.bindBufferBase(i.TRANSFORM_FEEDBACK_BUFFER,0,this.distancesTransformFeedback.outDistancesBuffer),i.beginTransformFeedback(i.POINTS),i.drawArrays(i.POINTS,0,this.getSplatCount()),i.endTransformFeedback(),i.bindBufferBase(i.TRANSFORM_FEEDBACK_BUFFER,0,null),i.bindTransformFeedback(i.TRANSFORM_FEEDBACK,null),i.disable(i.RASTERIZER_DISCARD);const o=i.fenceSync(i.SYNC_GPU_COMMANDS_COMPLETE,0);i.flush();const l=new Promise(e=>{const t=()=>{if(this.disposed)e();else{const r=0,s=0;switch(i.clientWaitSync(o,s,r)){case i.TIMEOUT_EXPIRED:return this.computeDistancesOnGPUSyncTimeout=setTimeout(t),this.computeDistancesOnGPUSyncTimeout;case i.WAIT_FAILED:throw new Error("should never get here");default:{this.computeDistancesOnGPUSyncTimeout=null,i.deleteSync(o);const t=i.getParameter(i.VERTEX_ARRAY_BINDING);i.bindVertexArray(this.distancesTransformFeedback.vao),i.bindBuffer(i.ARRAY_BUFFER,this.distancesTransformFeedback.outDistancesBuffer),i.getBufferSubData(i.ARRAY_BUFFER,0,n),i.bindBuffer(i.ARRAY_BUFFER,null),t&&i.bindVertexArray(t),e()}}}};this.computeDistancesOnGPUSyncTimeout=setTimeout(t)});return s&&!0!==a&&i.useProgram(s),r&&i.bindVertexArray(r),l}}()),i(this,"morphedMesh"),i(this,"getSplatCenter",function(){const e={};return function(t,n,i,r){this.getLocalSplatParameters(n,e,r),e.splatBuffer.getSplatCenter(t,e.localIndex,i,e.sceneTransform)}}()),i(this,"getSplatScaleAndRotation",function(){const e={},t=new hi;return function(n,i,r,s){this.getLocalSplatParameters(n,e,s),t.x=void 0,t.y=void 0,t.z=void 0,this.splatRenderMode===tp&&(t.z=0),e.splatBuffer.getSplatScaleAndRotation(e.localIndex,i,r,e.sceneTransform,t)}}()),i(this,"getSplatColor",function(){const e={};return function(t,n){this.getLocalSplatParameters(t,e),e.splatBuffer.getSplatColor(e.localIndex,n)}}()),this.renderer=void 0,this.splatRenderMode=e,this.dynamicMode=t,this.enableOptionalEffects=n,this.halfPrecisionCovariancesOnGPU=r,this.devicePixelRatio=s,this.enableDistancesComputationOnGPU=a,this.integerBasedDistancesComputation=o,this.antialiased=l,this.kernel2DSize=p,this.maxScreenSpaceSplatSize=c,this.logLevel=h,this.sphericalHarmonicsDegree=u,this.minSphericalHarmonicsDegree=0,this.sceneFadeInRateMultiplier=d,this.scenes=[],this.splatTree=null,this.baseSplatTree=null,this.splatDataTextures={},this.flameModel=null,this.expressionBSNum=0,this.bsWeight=[],this.bonesMatrix=null,this.bonesNum=null,this.bonesWeight=null,this.gaussianSplatCount=null,this.morphTargetDictionary=null,this.distancesTransformFeedback={id:null,vertexShader:null,fragmentShader:null,program:null,centersBuffer:null,sceneIndexesBuffer:null,outDistancesBuffer:null,centersLoc:-1,modelViewProjLoc:-1,sceneIndexesLoc:-1,transformsLocs:[]},this.globalSplatIndexToLocalSplatIndexMap=[],this.globalSplatIndexToSceneIndexMap=[],this.irisOcclusionConfig=null,this.lastBuildSplatCount=0,this.lastBuildScenes=[],this.lastBuildMaxSplatCount=0,this.lastBuildSceneCount=0,this.firstRenderTime=-1,this.finalBuild=!1,this.webGLUtils=null,this.boundingBox=new Li,this.calculatedSceneCenter=new hi,this.maxSplatDistanceFromSceneCenter=0,this.visibleRegionBufferRadius=0,this.visibleRegionRadius=0,this.visibleRegionFadeStartRadius=0,this.visibleRegionChanging=!1,this.splatScale=1,this.pointCloudModeEnabled=!1,this.disposed=!1,this.lastRenderer=null,this.visible=!1}static buildScenes(e,t,n){const i=[];i.length=t.length;for(let r=0;r<t.length;r++){const s=t[r],a=n[r]||{};let o=a.position||[0,0,0],l=a.rotation||[0,0,0,1],c=a.scale||[1,1,1];const h=(new hi).fromArray(o),u=(new ci).fromArray(l),d=(new hi).fromArray(c),p=Mf.createScene(s,h,u,d,a.splatAlphaRemovalThreshold||1,a.opacity,a.visible);e.add(p),i[r]=p}return i}static createScene(e,t,n,i,r,s=1,a=!0){return new hf(e,t,n,i,r,s,a)}static buildSplatIndexMaps(e){const t=[],n=[];let i=0;for(let r=0;r<e.length;r++){const s=e[r].getMaxSplatCount();for(let e=0;e<s;e++)t[i]=e,n[i]=r,i++}return{localSplatIndexMap:t,sceneIndexMap:n}}build(e,t,n=!0,i=!1,r,s,a=!0){this.sceneOptions=t,this.finalBuild=i;const o=Mf.getTotalMaxSplatCountForSplatBuffers(e),l=Mf.buildScenes(this,e,t);if(n)for(let f=0;f<this.scenes.length&&f<l.length;f++){const e=l[f],t=this.getScene(f);e.copyTransformData(t)}this.scenes=l;let c=3;for(let f of e){const e=f.getMinSphericalHarmonicsDegree();e<c&&(c=e)}this.minSphericalHarmonicsDegree=Math.min(c,this.sphericalHarmonicsDegree);let h=!1;if(e.length!==this.lastBuildScenes.length)h=!0;else for(let f=0;f<e.length;f++)if(e[f]!==this.lastBuildScenes[f].splatBuffer){h=!0;break}let u=!0;if((1!==this.scenes.length||this.lastBuildSceneCount!==this.scenes.length||this.lastBuildMaxSplatCount!==o||h)&&(u=!1),!u){this.boundingBox=new Li,a||(this.maxSplatDistanceFromSceneCenter=0,this.visibleRegionBufferRadius=0,this.visibleRegionRadius=0,this.visibleRegionFadeStartRadius=0,this.firstRenderTime=-1),this.lastBuildScenes=[],this.lastBuildSplatCount=0,this.lastBuildMaxSplatCount=0,this.disposeMeshData(),this.geometry=uf.build(o),this.splatRenderMode===ep?this.material=mf.build(this.dynamicMode,this.enableOptionalEffects,this.antialiased,this.maxScreenSpaceSplatSize,this.splatScale,this.pointCloudModeEnabled,this.minSphericalHarmonicsDegree,this.kernel2DSize,this.irisOcclusionConfig):this.material=gf.build(this.dynamicMode,this.enableOptionalEffects,this.splatScale,this.pointCloudModeEnabled,this.minSphericalHarmonicsDegree);const t=Mf.buildSplatIndexMaps(e);this.globalSplatIndexToLocalSplatIndexMap=t.localSplatIndexMap,this.globalSplatIndexToSceneIndexMap=t.sceneIndexMap}const d=this.getSplatCount(!0);this.enableDistancesComputationOnGPU&&this.setupDistancesComputationTransformFeedback();const p=this.refreshGPUDataFromSplatBuffers(u);for(let f=0;f<this.scenes.length;f++)this.lastBuildScenes[f]=this.scenes[f];return this.lastBuildSplatCount=d,this.lastBuildMaxSplatCount=this.getMaxSplatCount(),this.lastBuildSceneCount=this.scenes.length,this.visible=this.scenes.length>0,p}freeIntermediateSplatData(){const e=e=>{delete e.source.data,delete e.image,e.onUpdate=null};delete this.splatDataTextures.baseData.covariances,delete this.splatDataTextures.baseData.centers,delete this.splatDataTextures.baseData.colors,delete this.splatDataTextures.baseData.sphericalHarmonics,delete this.splatDataTextures.centerColors.data,delete this.splatDataTextures.covariances.data,this.splatDataTextures.sphericalHarmonics&&delete this.splatDataTextures.sphericalHarmonics.data,this.splatDataTextures.sceneIndexes&&delete this.splatDataTextures.sceneIndexes.data,this.splatDataTextures.centerColors.texture.needsUpdate=!0,this.splatDataTextures.centerColors.texture.onUpdate=()=>{e(this.splatDataTextures.centerColors.texture)},this.splatDataTextures.flameModelPosTexture.texture.needsUpdate=!0,this.splatDataTextures.flameModelPosTexture.texture.onUpdate=()=>{e(this.splatDataTextures.flameModelPosTexture.texture)},this.splatDataTextures.covariances.texture.needsUpdate=!0,this.splatDataTextures.covariances.texture.onUpdate=()=>{e(this.splatDataTextures.covariances.texture)},this.splatDataTextures.sphericalHarmonics&&(this.splatDataTextures.sphericalHarmonics.texture?(this.splatDataTextures.sphericalHarmonics.texture.needsUpdate=!0,this.splatDataTextures.sphericalHarmonics.texture.onUpdate=()=>{e(this.splatDataTextures.sphericalHarmonics.texture)}):this.splatDataTextures.sphericalHarmonics.textures.forEach(t=>{t.needsUpdate=!0,t.onUpdate=()=>{e(t)}})),this.splatDataTextures.sceneIndexes&&(this.splatDataTextures.sceneIndexes.texture.needsUpdate=!0,this.splatDataTextures.sceneIndexes.texture.onUpdate=()=>{e(this.splatDataTextures.sceneIndexes.texture)})}dispose(){this.disposeMeshData(),this.disposeTextures(),this.disposeSplatTree(),this.enableDistancesComputationOnGPU&&(this.computeDistancesOnGPUSyncTimeout&&(clearTimeout(this.computeDistancesOnGPUSyncTimeout),this.computeDistancesOnGPUSyncTimeout=null),this.disposeDistancesComputationGPUResources()),this.scenes=[],this.distancesTransformFeedback={id:null,vertexShader:null,fragmentShader:null,program:null,centersBuffer:null,sceneIndexesBuffer:null,outDistancesBuffer:null,centersLoc:-1,modelViewProjLoc:-1,sceneIndexesLoc:-1,transformsLocs:[]},this.renderer=null,this.globalSplatIndexToLocalSplatIndexMap=[],this.globalSplatIndexToSceneIndexMap=[],this.lastBuildSplatCount=0,this.lastBuildScenes=[],this.lastBuildMaxSplatCount=0,this.lastBuildSceneCount=0,this.firstRenderTime=-1,this.finalBuild=!1,this.webGLUtils=null,this.boundingBox=new Li,this.calculatedSceneCenter=new hi,this.maxSplatDistanceFromSceneCenter=0,this.visibleRegionBufferRadius=0,this.visibleRegionRadius=0,this.visibleRegionFadeStartRadius=0,this.visibleRegionChanging=!1,this.splatScale=1,this.pointCloudModeEnabled=!1,this.disposed=!0,this.lastRenderer=null,this.visible=!1}disposeMeshData(){this.geometry&&this.geometry!==vf&&(this.geometry.dispose(),this.geometry=null),this.material&&(this.material.dispose(),this.material=null)}disposeTextures(){for(let e in this.splatDataTextures)if(Object.hasOwn(this.splatDataTextures,e)){const t=this.splatDataTextures[e];t.texture&&(t.texture.dispose(),t.texture=null)}this.splatDataTextures=null}disposeSplatTree(){this.splatTree&&(this.splatTree.dispose(),this.splatTree=null),this.baseSplatTree&&(this.baseSplatTree.dispose(),this.baseSplatTree=null)}getSplatTree(){return this.splatTree}onSplatTreeReady(e){this.onSplatTreeReadyCallback=e}getDataForDistancesComputation(e,t){return{centers:this.integerBasedDistancesComputation?this.getIntegerCenters(e,t,!0):this.getFloatCenters(e,t,!0),sceneIndexes:this.getSceneIndexes(e,t)}}refreshGPUDataFromSplatBuffers(e){const t=this.getSplatCount(!0);this.refreshDataTexturesFromSplatBuffers(e);const n=e?this.lastBuildSplatCount:0,{centers:i,sceneIndexes:r}=this.getDataForDistancesComputation(n,t-1);return this.enableDistancesComputationOnGPU&&this.refreshGPUBuffersForDistancesComputation(i,r,e),{from:n,to:t-1,count:t-n,centers:i,sceneIndexes:r}}refreshGPUBuffersForDistancesComputation(e,t,n=!1){const i=n?this.lastBuildSplatCount:0;this.updateGPUCentersBufferForDistancesComputation(n,e,i),this.updateGPUTransformIndexesBufferForDistancesComputation(n,t,i)}refreshDataTexturesFromSplatBuffers(e){const t=this.getSplatCount(!0),n=this.lastBuildSplatCount,i=t-1;e?this.updateBaseDataFromSplatBuffers(n,i):(this.setupDataTextures(),this.updateBaseDataFromSplatBuffers()),this.updateDataTexturesFromBaseData(n,i),this.updateVisibleRegion(e)}setupDataTextures(){const e=this.getMaxSplatCount(),t=this.getSplatCount(!0);this.disposeTextures();const n=(t,n)=>{const i=new li(4096,1024);for(;i.x*i.y*t<e*n;)i.y*=2;return i},i=e=>{const t=e>=1?6:4;return{elementsPerTexelStored:t,texSize:n(t,6)}};let r=this.getTargetCovarianceCompressionLevel();const s=this.getTargetSphericalHarmonicsCompressionLevel();let a,o,l;if(this.splatRenderMode===ep){const t=i(r);t.texSize.x*t.texSize.y>bf&&0===r&&(r=1),a=new Float32Array(6*e)}else o=new Float32Array(3*e),l=new Float32Array(4*e);const c=new Float32Array(3*e),h=new Uint8Array(4*e);let u=Float32Array;1===s?u=Uint16Array:2===s&&(u=Uint8Array);const d=Cp(this.minSphericalHarmonicsDegree),p=this.minSphericalHarmonicsDegree?new u(e*d):void 0,f=n(4,4),m=new Uint32Array(f.x*f.y*4);Mf.updateCenterColorsPaddedData(0,t-1,c,h,m);const g=new fa(m,f.x,f.y,It,mt);if(g.internalFormat="RGBA32UI",g.needsUpdate=!0,this.material.uniforms.centersColorsTexture.value=g,this.material.uniforms.centersColorsTextureSize.value.copy(f),this.material.uniformsNeedUpdate=!0,this.splatDataTextures={baseData:{covariances:a,scales:o,rotations:l,centers:c,colors:h,sphericalHarmonics:p},centerColors:{data:m,texture:g,size:f}},this.splatRenderMode===ep){const e=i(r),t=e.elementsPerTexelStored,n=e.texSize,s=r>=1?8:4,o=new(r>=1?Uint32Array:Float32Array)(n.x*n.y*s);let l;if(0===r?o.set(a):Mf.updatePaddedCompressedCovariancesTextureData(a,o,0,0,a.length),r>=1)l=new fa(o,n.x,n.y,It,mt),l.internalFormat="RGBA32UI",this.material.uniforms.covariancesTextureHalfFloat.value=l;else{l=new fa(o,n.x,n.y,bt,gt),this.material.uniforms.covariancesTexture.value=l;const e=new fa(new Uint32Array(32),2,2,It,mt);e.internalFormat="RGBA32UI",this.material.uniforms.covariancesTextureHalfFloat.value=e,e.needsUpdate=!0}l.needsUpdate=!0,this.material.uniforms.covariancesAreHalfFloat.value=r>=1?1:0,this.material.uniforms.covariancesTextureSize.value.copy(n),this.splatDataTextures.covariances={data:o,texture:l,size:n,compressionLevel:r,elementsPerTexelStored:t,elementsPerTexelAllocated:s}}else{const e=n(4,6);let i=Float32Array,r=gt;const s=new i(e.x*e.y*4);Mf.updateScaleRotationsPaddedData(0,t-1,o,l,s);const a=new fa(s,e.x,e.y,bt,r);a.needsUpdate=!0,this.material.uniforms.scaleRotationsTexture.value=a,this.material.uniforms.scaleRotationsTextureSize.value.copy(e),this.splatDataTextures.scaleRotations={data:s,texture:a,size:e,compressionLevel:0}}if(p){const e=2===s?ht:_t;let i=d;i%2!=0&&i++;const r=2===this.minSphericalHarmonicsDegree?4:2,a=4===r?bt:Ct;let o=n(r,i);if(o.x*o.y<=bf){const n=new u(o.x*o.y*r);for(let e=0;e<t;e++){const t=d*e,r=i*e;for(let e=0;e<d;e++)n[r+e]=p[t+e]}const l=new fa(n,o.x,o.y,a,e);l.needsUpdate=!0,this.material.uniforms.sphericalHarmonicsTexture.value=l,this.splatDataTextures.sphericalHarmonics={componentCount:d,paddedComponentCount:i,data:n,textureCount:1,texture:l,size:o,compressionLevel:s,elementsPerTexel:r}}else{const l=d/3;i=l,i%2!=0&&i++,o=n(r,i);const c=o.x*o.y*r,h=[this.material.uniforms.sphericalHarmonicsTextureR,this.material.uniforms.sphericalHarmonicsTextureG,this.material.uniforms.sphericalHarmonicsTextureB],f=[],m=[];for(let n=0;n<3;n++){const r=new u(c);f.push(r);for(let e=0;e<t;e++){const t=d*e,s=i*e;if(l>=3){for(let e=0;e<3;e++)r[s+e]=p[t+3*n+e];if(l>=8)for(let e=0;e<5;e++)r[s+3+e]=p[t+9+5*n+e]}}const s=new fa(r,o.x,o.y,a,e);m.push(s),s.needsUpdate=!0,h[n].value=s}this.material.uniforms.sphericalHarmonicsMultiTextureMode.value=1,this.splatDataTextures.sphericalHarmonics={componentCount:d,componentCountPerChannel:l,paddedComponentCount:i,data:f,textureCount:3,textures:m,size:o,compressionLevel:s,elementsPerTexel:r}}this.material.uniforms.sphericalHarmonicsTextureSize.value.copy(o),this.material.uniforms.sphericalHarmonics8BitMode.value=2===s?1:0;for(let t=0;t<this.scenes.length;t++){const e=this.scenes[t].splatBuffer;this.material.uniforms.sphericalHarmonics8BitCompressionRangeMin.value[t]=e.minSphericalHarmonicsCoeff,this.material.uniforms.sphericalHarmonics8BitCompressionRangeMax.value[t]=e.maxSphericalHarmonicsCoeff}this.material.uniformsNeedUpdate=!0}const _=n(1,4),v=new Uint32Array(_.x*_.y*1);for(let y=0;y<t;y++)v[y]=this.globalSplatIndexToSceneIndexMap[y];const x=new fa(v,_.x,_.y,Et,mt);x.internalFormat="R32UI",x.needsUpdate=!0,this.material.uniforms.sceneIndexesTexture.value=x,this.material.uniforms.sceneIndexesTextureSize.value.copy(_),this.material.uniformsNeedUpdate=!0,this.splatDataTextures.sceneIndexes={data:v,texture:x,size:_},this.material.uniforms.sceneCount.value=this.scenes.length,this.flameModel&&this.flameModel.geometry&&this.flameModel.geometry.morphAttributes&&this.flameModel.skeleton&&(this.expressionBSNum=this.flameModel.geometry.morphAttributes.position.length,this.material.uniforms.bsCount.value=this.expressionBSNum,this.flameModel.skeleton.bones.forEach((e,t)=>{"head"==e.name&&(this.material.uniforms.headBoneIndex.value=t)}),this.buildModelTexture(this.flameModel),this.buildBoneMatrixTexture(),this.buildBoneWeightTexture(this.flameModel))}buildBoneMatrixTexture(){if(!this.bsWeight)return;if(!this.flameModel||!this.flameModel.morphTargetDictionary)return;const e=new li(4,32);let t=new Float32Array(this.bonesMatrix),n=new Uint32Array(e.x*e.y*4);this.morphTargetDictionary=this.flameModel.morphTargetDictionary;for(let r=0;r<16*this.bonesNum;r++)n[r]=Hp(t[r]);this.flameModel&&this.flameModel.skeleton&&(this.material.uniforms.boneTexture0.value=this.flameModel.skeleton.boneTexture,this.material.uniforms.bindMatrix.value=this.flameModel.bindMatrix,this.material.uniforms.bindMatrixInverse.value=this.flameModel.bindMatrixInverse);for(const r in this.bsWeight)if(Object.hasOwn(this.bsWeight,r)){const e=this.bsWeight[r];n[this.morphTargetDictionary[r]+16*this.bonesNum]=Hp(e)}const i=new fa(n,e.x,e.y,It,mt);i.internalFormat="RGBA32UI",i.needsUpdate=!0,this.material.uniforms.boneTexture.value=i,this.material.uniforms.boneTextureSize.value.copy(e),this.material.uniformsNeedUpdate=!0,this.splatDataTextures.boneMatrix={data:n,texture:i,size:e},this.splatDataTextures.baseData.boneMatrix=n}updateBoneMatrixTexture(){if(this.bsWeight&&this.morphTargetDictionary){for(const e in this.bsWeight)if(Object.hasOwn(this.bsWeight,e)){const t=this.bsWeight[e],n=this.morphTargetDictionary[e];this.splatDataTextures.baseData.boneMatrix[n+16*this.bonesNum]=Hp(t)}this.splatDataTextures.boneMatrix.texture.data=this.splatDataTextures.baseData.boneMatrix,this.splatDataTextures.boneMatrix.texture.needsUpdate=!0,this.material.uniforms.boneTexture.value=this.splatDataTextures.boneMatrix.texture,this.flameModel.skeleton&&(this.material.uniforms.boneTexture0.value=this.flameModel.skeleton.boneTexture,this.material.uniforms.bindMatrix.value=this.flameModel.bindMatrix,this.material.uniforms.bindMatrixInverse.value=this.flameModel.bindMatrixInverse),this.material.uniformsNeedUpdate=!0}}buildBoneWeightTexture(e){if(!this.bonesWeight)return;let t=e.geometry.attributes.position.array.length/3;const n=new li(512,512);let i=new Float32Array(n.x*n.y*4),r=new Uint32Array(n.x*n.y*4);for(let a=0;a<t;a++)i[8*a+0]=this.bonesWeight[a][0],i[8*a+1]=this.bonesWeight[a][1],i[8*a+2]=this.bonesWeight[a][2],i[8*a+3]=this.bonesWeight[a][3],i[8*a+4]=this.bonesWeight[a][4],r[8*a+0]=Hp(this.bonesWeight[a][0]),r[8*a+1]=Hp(this.bonesWeight[a][1]),r[8*a+2]=Hp(this.bonesWeight[a][2]),r[8*a+3]=Hp(this.bonesWeight[a][3]),r[8*a+4]=Hp(this.bonesWeight[a][4]);const s=new fa(r,n.x,n.y,It,mt);s.internalFormat="RGBA32UI",s.needsUpdate=!0,this.material.uniforms.boneWeightTexture.value=s,this.material.uniforms.boneWeightTextureSize.value.copy(n),this.material.uniformsNeedUpdate=!0,this.splatDataTextures.boneWeight={data:r,texture:s,size:n},this.splatDataTextures.baseData.boneWeight=r}buildModelTexture(e){if(!(e&&e.geometry&&e.geometry.morphAttributes&&e.morphTargetDictionary))return;const t=new li(4096,2048);var n=e.geometry.attributes.position.array,i=[];let r=n.length/3,s=e.geometry.morphAttributes.position.length;Object.keys(e.morphTargetDictionary).forEach((t,n)=>{const r=e.morphTargetDictionary[t];var s=e.geometry.morphAttributes.position[r];i=i.concat(Array.from(s.array))}),i=i.concat(Array.from(n));let a=new Float32Array(t.x*t.y*4),o=new Uint32Array(t.x*t.y*4);for(let c=0;c<r*(s+1);c++)a[4*c+0]=i[3*c+0],a[4*c+1]=i[3*c+1],a[4*c+2]=i[3*c+2],o[4*c+0]=Hp(a[4*c+0]),o[4*c+1]=Hp(a[4*c+1]),o[4*c+2]=Hp(a[4*c+2]);const l=new fa(o,t.x,t.y,It,mt);l.internalFormat="RGBA32UI",l.needsUpdate=!0,this.material.uniforms.flameModelTexture.value=l,this.material.uniforms.flameModelTextureSize.value.copy(t),this.material.uniformsNeedUpdate=!0,this.material.uniforms.gaussianSplatCount.value=this.gaussianSplatCount,this.splatDataTextures.flameModel={data:o,texture:l,size:t},this.splatDataTextures.baseData.flameModelPos=a}updateTetureAfterBSAndSkeleton(e,t){const n=new or;this.getSceneTransform(0,n),this.getScene(0).splatBuffer.fillSplatCenterArray(this.morphedMesh,this.splatDataTextures.baseData.centers,n,e,t,0);const i=this.splatDataTextures.centerColors,r=i.data,s=i.texture;Mf.updateCenterColorsPaddedData(e,t,this.splatDataTextures.baseData.centers,this.splatDataTextures.baseData.colors,r);const a=this.renderer?this.renderer.properties.get(s):null;a&&a.__webglTexture?this.updateDataTexture(r,i.texture,i.size,a,4,4,4,e,t):s.needsUpdate=!0,this.updateBoneMatrixTexture()}updateBaseDataFromSplatBuffers(e,t){const n=this.splatDataTextures.covariances,i=n?n.compressionLevel:void 0,r=this.splatDataTextures.scaleRotations,s=r?r.compressionLevel:void 0,a=this.splatDataTextures.sphericalHarmonics,o=a?a.compressionLevel:0;this.fillSplatDataArrays(this.splatDataTextures.baseData.covariances,this.splatDataTextures.baseData.scales,this.splatDataTextures.baseData.rotations,this.splatDataTextures.baseData.centers,this.splatDataTextures.baseData.colors,this.splatDataTextures.baseData.sphericalHarmonics,this.splatDataTextures.baseData.flameModelPos,void 0,i,s,o,e,t,e)}updateDataTexturesFromBaseData(e,t){const n=this.splatDataTextures.covariances,i=n?n.compressionLevel:void 0,r=this.splatDataTextures.scaleRotations,s=r?r.compressionLevel:void 0,a=this.splatDataTextures.sphericalHarmonics,o=a?a.compressionLevel:0,l=this.splatDataTextures.flameModel,c=l.data,h=l.texture,u=this.renderer?this.renderer.properties.get(h):null;u&&u.__webglTexture?this.updateDataTexture(c,l.texture,l.size,u,4,4,3,e,t):h.needsUpdate=!0;const d=this.splatDataTextures.centerColors,p=d.data,f=d.texture;Mf.updateCenterColorsPaddedData(e,t,this.splatDataTextures.baseData.centers,this.splatDataTextures.baseData.colors,p);const m=this.renderer?this.renderer.properties.get(f):null;if(m&&m.__webglTexture?this.updateDataTexture(p,d.texture,d.size,m,4,4,4,e,t):f.needsUpdate=!0,n){const r=n.texture,s=6*e,a=6*t;if(0===i)for(let e=s;e<=a;e++){const t=this.splatDataTextures.baseData.covariances[e];n.data[e]=t}else Mf.updatePaddedCompressedCovariancesTextureData(this.splatDataTextures.baseData.covariances,n.data,e*n.elementsPerTexelAllocated,s,a);const o=this.renderer?this.renderer.properties.get(r):null;o&&o.__webglTexture?0===i?this.updateDataTexture(n.data,n.texture,n.size,o,n.elementsPerTexelStored,6,4,e,t):this.updateDataTexture(n.data,n.texture,n.size,o,n.elementsPerTexelAllocated,n.elementsPerTexelAllocated,2,e,t):r.needsUpdate=!0}if(r){const n=r.data,i=r.texture,a=6,o=0===s?4:2;Mf.updateScaleRotationsPaddedData(e,t,this.splatDataTextures.baseData.scales,this.splatDataTextures.baseData.rotations,n);const l=this.renderer?this.renderer.properties.get(i):null;l&&l.__webglTexture?this.updateDataTexture(n,r.texture,r.size,l,4,a,o,e,t):i.needsUpdate=!0}const g=this.splatDataTextures.baseData.sphericalHarmonics;if(g){let n=4;1===o?n=2:2===o&&(n=1);const i=(i,r,s,a,o)=>{const l=this.renderer?this.renderer.properties.get(i):null;l&&l.__webglTexture?this.updateDataTexture(a,i,r,l,s,o,n,e,t):i.needsUpdate=!0},r=a.componentCount,s=a.paddedComponentCount;if(1===a.textureCount){const n=a.data;for(let i=e;i<=t;i++){const e=r*i,t=s*i;for(let i=0;i<r;i++)n[t+i]=g[e+i]}i(a.texture,a.size,a.elementsPerTexel,n,s)}else{const n=a.componentCountPerChannel;for(let o=0;o<3;o++){const l=a.data[o];for(let i=e;i<=t;i++){const e=r*i,t=s*i;if(n>=3){for(let n=0;n<3;n++)l[t+n]=g[e+3*o+n];if(n>=8)for(let n=0;n<5;n++)l[t+3+n]=g[e+9+5*o+n]}}i(a.textures[o],a.size,a.elementsPerTexel,l,s)}}}const _=this.splatDataTextures.sceneIndexes,v=_.data;for(let S=this.lastBuildSplatCount;S<=t;S++)v[S]=this.globalSplatIndexToSceneIndexMap[S];const x=_.texture,y=this.renderer?this.renderer.properties.get(x):null;y&&y.__webglTexture?this.updateDataTexture(v,_.texture,_.size,y,1,1,1,this.lastBuildSplatCount,t):x.needsUpdate=!0}getTargetCovarianceCompressionLevel(){return this.halfPrecisionCovariancesOnGPU?1:0}getTargetSphericalHarmonicsCompressionLevel(){return Math.max(1,this.getMaximumSplatBufferCompressionLevel())}getMaximumSplatBufferCompressionLevel(){let e;for(let t=0;t<this.scenes.length;t++){const n=this.getScene(t).splatBuffer;(0===t||n.compressionLevel>e)&&(e=n.compressionLevel)}return e}getMinimumSplatBufferCompressionLevel(){let e;for(let t=0;t<this.scenes.length;t++){const n=this.getScene(t).splatBuffer;(0===t||n.compressionLevel<e)&&(e=n.compressionLevel)}return e}static computeTextureUpdateRegion(e,t,n,i,r){const s=r/i,a=e*s,o=Math.floor(a/n),l=o*n*i,c=t*s,h=Math.floor(c/n);return{dataStart:l,dataEnd:h*n*i+n*i,startRow:o,endRow:h}}updateDataTexture(e,t,n,i,r,s,a,o,l){const c=this.renderer.getContext(),h=Mf.computeTextureUpdateRegion(o,l,n.x,r,s),u=h.dataEnd-h.dataStart,d=new e.constructor(e.buffer,h.dataStart*a,u),p=h.endRow-h.startRow+1,f=this.webGLUtils.convert(t.type),m=this.webGLUtils.convert(t.format,t.colorSpace),g=c.getParameter(c.TEXTURE_BINDING_2D);c.bindTexture(c.TEXTURE_2D,i.__webglTexture),c.texSubImage2D(c.TEXTURE_2D,0,0,h.startRow,n.x,p,m,f,d),c.bindTexture(c.TEXTURE_2D,g)}static updatePaddedCompressedCovariancesTextureData(e,t,n,i,r){let s=new DataView(t.buffer),a=n,o=0;for(let l=i;l<=r;l+=2)s.setUint16(2*a,e[l],!0),s.setUint16(2*a+2,e[l+1],!0),a+=2,o++,o>=3&&(a+=2,o=0)}static updateCenterColorsPaddedData(e,t,n,i,r){for(let s=e;s<=t;s++){const e=4*s,t=3*s,a=4*s;r[a]=Vp(i,e),r[a+1]=Hp(n[t]),r[a+2]=Hp(n[t+1]),r[a+3]=Hp(n[t+2])}}static updateScaleRotationsPaddedData(e,t,n,i,r){for(let s=e;s<=t;s++){const e=3*s,t=4*s,a=6*s;r[a]=n[e],r[a+1]=n[e+1],r[a+2]=n[e+2],r[a+3]=i[t],r[a+4]=i[t+1],r[a+5]=i[t+2]}}updateVisibleRegion(e){const t=this.getSplatCount(!0),n=new hi;if(!e){const e=new hi;this.scenes.forEach(t=>{e.add(t.splatBuffer.sceneCenter)}),e.multiplyScalar(1/this.scenes.length),this.calculatedSceneCenter.copy(e),this.material.uniforms.sceneCenter.value.copy(this.calculatedSceneCenter),this.material.uniformsNeedUpdate=!0}for(let i=e?this.lastBuildSplatCount:0;i<t;i++){this.getSplatCenter(this.morphedMesh,i,n,!0);const e=n.sub(this.calculatedSceneCenter).length();e>this.maxSplatDistanceFromSceneCenter&&(this.maxSplatDistanceFromSceneCenter=e)}this.maxSplatDistanceFromSceneCenter-this.visibleRegionBufferRadius>1&&(this.visibleRegionBufferRadius=this.maxSplatDistanceFromSceneCenter,this.visibleRegionRadius=Math.max(this.visibleRegionBufferRadius-1,0)),this.finalBuild&&(this.visibleRegionRadius=this.visibleRegionBufferRadius=this.maxSplatDistanceFromSceneCenter),this.updateVisibleRegionFadeDistance()}updateVisibleRegionFadeDistance(e=Jd){const t=.012*this.sceneFadeInRateMultiplier,n=.003*this.sceneFadeInRateMultiplier,i=this.finalBuild?t:n,r=e===Jd?i:n;this.visibleRegionFadeStartRadius=(this.visibleRegionRadius-this.visibleRegionFadeStartRadius)*r+this.visibleRegionFadeStartRadius;const s=(this.visibleRegionBufferRadius>0?this.visibleRegionFadeStartRadius/this.visibleRegionBufferRadius:0)>.99,a=s||e===$d?1:0;this.material.uniforms.visibleRegionFadeStartRadius.value=this.visibleRegionFadeStartRadius,this.material.uniforms.visibleRegionRadius.value=this.visibleRegionRadius,this.material.uniforms.firstRenderTime.value=this.firstRenderTime,this.material.uniforms.currentTime.value=performance.now(),this.material.uniforms.fadeInComplete.value=a,this.material.uniformsNeedUpdate=!0,this.visibleRegionChanging=!s}updateRenderIndexes(e,t){const n=this.geometry;n.attributes.splatIndex.set(e),n.attributes.splatIndex.needsUpdate=!0,t>0&&-1===this.firstRenderTime&&(this.firstRenderTime=performance.now()),n.instanceCount=t,n.setDrawRange(0,t)}updateTransforms(){for(let e=0;e<this.scenes.length;e++)this.getScene(e).updateTransform(this.dynamicMode)}setSplatScale(e=1){this.splatScale=e,this.material.uniforms.splatScale.value=e,this.material.uniformsNeedUpdate=!0}getSplatScale(){return this.splatScale}setPointCloudModeEnabled(e){this.pointCloudModeEnabled=e,this.material.uniforms.pointCloudModeEnabled.value=e?1:0,this.material.uniformsNeedUpdate=!0}getPointCloudModeEnabled(){return this.pointCloudModeEnabled}getSplatDataTextures(){return this.splatDataTextures}getSplatCount(e=!1){return e?Mf.getTotalSplatCountForScenes(this.scenes):this.lastBuildSplatCount}static getTotalSplatCountForScenes(e){let t=0;for(let n of e)n&&n.splatBuffer&&(t+=n.splatBuffer.getSplatCount());return t}static getTotalSplatCountForSplatBuffers(e){let t=0;for(let n of e)t+=n.getSplatCount();return t}getMaxSplatCount(){return Mf.getTotalMaxSplatCountForScenes(this.scenes)}static getTotalMaxSplatCountForScenes(e){let t=0;for(let n of e)n&&n.splatBuffer&&(t+=n.splatBuffer.getMaxSplatCount());return t}static getTotalMaxSplatCountForSplatBuffers(e){let t=0;for(let n of e)t+=n.getMaxSplatCount();return t}disposeDistancesComputationGPUResources(){if(!this.renderer)return;const e=this.renderer.getContext();this.distancesTransformFeedback.vao&&(e.deleteVertexArray(this.distancesTransformFeedback.vao),this.distancesTransformFeedback.vao=null),this.distancesTransformFeedback.program&&(e.deleteProgram(this.distancesTransformFeedback.program),e.deleteShader(this.distancesTransformFeedback.vertexShader),e.deleteShader(this.distancesTransformFeedback.fragmentShader),this.distancesTransformFeedback.program=null,this.distancesTransformFeedback.vertexShader=null,this.distancesTransformFeedback.fragmentShader=null),this.disposeDistancesComputationGPUBufferResources(),this.distancesTransformFeedback.id&&(e.deleteTransformFeedback(this.distancesTransformFeedback.id),this.distancesTransformFeedback.id=null)}disposeDistancesComputationGPUBufferResources(){if(!this.renderer)return;const e=this.renderer.getContext();this.distancesTransformFeedback.centersBuffer&&(this.distancesTransformFeedback.centersBuffer=null,e.deleteBuffer(this.distancesTransformFeedback.centersBuffer)),this.distancesTransformFeedback.outDistancesBuffer&&(e.deleteBuffer(this.distancesTransformFeedback.outDistancesBuffer),this.distancesTransformFeedback.outDistancesBuffer=null)}setRenderer(e){if(e!==this.renderer){this.renderer=e;const t=this.renderer.getContext(),n=new yf(t),i=new Sf(t,n,{});if(n.init(i),this.webGLUtils=new Af(t,n,i),this.enableDistancesComputationOnGPU&&this.getSplatCount()>0){this.setupDistancesComputationTransformFeedback();const{centers:e,sceneIndexes:t}=this.getDataForDistancesComputation(0,this.getSplatCount()-1);this.refreshGPUBuffersForDistancesComputation(e,t)}}}updateGPUCentersBufferForDistancesComputation(e,t,n){if(!this.renderer)return;const i=this.renderer.getContext(),r=i.getParameter(i.VERTEX_ARRAY_BINDING);i.bindVertexArray(this.distancesTransformFeedback.vao);const s=this.integerBasedDistancesComputation?Uint32Array:Float32Array,a=16*n;if(i.bindBuffer(i.ARRAY_BUFFER,this.distancesTransformFeedback.centersBuffer),e)i.bufferSubData(i.ARRAY_BUFFER,a,t);else{const e=new s(16*this.getMaxSplatCount());e.set(t),i.bufferData(i.ARRAY_BUFFER,e,i.STATIC_DRAW)}i.bindBuffer(i.ARRAY_BUFFER,null),r&&i.bindVertexArray(r)}updateGPUTransformIndexesBufferForDistancesComputation(e,t,n){if(!this.renderer||!this.dynamicMode)return;const i=this.renderer.getContext(),r=i.getParameter(i.VERTEX_ARRAY_BINDING);i.bindVertexArray(this.distancesTransformFeedback.vao);const s=4*n;if(i.bindBuffer(i.ARRAY_BUFFER,this.distancesTransformFeedback.sceneIndexesBuffer),e)i.bufferSubData(i.ARRAY_BUFFER,s,t);else{const e=new Uint32Array(4*this.getMaxSplatCount());e.set(t),i.bufferData(i.ARRAY_BUFFER,e,i.STATIC_DRAW)}i.bindBuffer(i.ARRAY_BUFFER,null),r&&i.bindVertexArray(r)}getSceneIndexes(e,t){let n;n=new Uint32Array(t-e+1);for(let i=e;i<=t;i++)n[i]=this.globalSplatIndexToSceneIndexMap[i];return n}getLocalSplatParameters(e,t,n){null==n&&(n=!this.dynamicMode),t.splatBuffer=this.getSplatBufferForSplat(e),t.localIndex=this.getSplatLocalIndex(e),t.sceneTransform=n?this.getSceneTransformForSplat(e):null}fillSplatDataArrays(e,t,n,i,r,s,a,o,l=0,c=0,h=1,u,d,p=0,f){const m=new hi;m.x=void 0,m.y=void 0,this.splatRenderMode===ep?m.z=void 0:m.z=1;const g=new or;let _=0,v=this.scenes.length-1;null!=f&&f>=0&&f<=this.scenes.length&&(_=f,v=f);for(let x=_;x<=v;x++){null==o&&(o=!this.dynamicMode);const a=this.getScene(x),f=a.splatBuffer;let _;if(o&&(this.getSceneTransform(x,g),_=g),e&&f.fillSplatCovarianceArray(e,_,u,d,p,l),t||n){if(!t||!n)throw new Error('SplatMesh::fillSplatDataArrays() -> "scales" and "rotations" must both be valid.');f.fillSplatScaleRotationArray(t,n,_,u,d,p,c,m)}i&&f.fillSplatCenterArray(this.morphedMesh,i,_,u,d,p),r&&f.fillSplatColorArray(r,a.minimumAlpha,u,d,p),s&&f.fillSphericalHarmonicsArray(s,this.minSphericalHarmonicsDegree,_,u,d,p,h),p+=f.getSplatCount()}}getIntegerCenters(e,t,n=!1){const i=t-e+1,r=new Float32Array(3*i);let s;this.fillSplatDataArrays(null,null,null,r,null,null,void 0,void 0,void 0,void 0,e);let a=n?4:3;s=new Int32Array(i*a);for(let o=0;o<i;o++){for(let e=0;e<3;e++)s[o*a+e]=Math.round(1e3*r[3*o+e]);n&&(s[o*a+3]=1e3)}return s}getFloatCenters(e,t,n=!1){const i=t-e+1,r=new Float32Array(3*i);if(this.fillSplatDataArrays(null,null,null,r,null,null,void 0,void 0,void 0,void 0,e),!n)return r;let s=new Float32Array(4*i);for(let a=0;a<i;a++){for(let e=0;e<3;e++)s[4*a+e]=r[3*a+e];s[4*a+3]=1}return s}getSceneTransform(e,t){const n=this.getScene(e);n.updateTransform(this.dynamicMode),t.copy(n.transform)}getScene(e){if(e<0||e>=this.scenes.length)throw new Error("SplatMesh::getScene() -> Invalid scene index.");return this.scenes[e]}getSceneCount(){return this.scenes.length}getSplatBufferForSplat(e){return this.getScene(this.globalSplatIndexToSceneIndexMap[e]).splatBuffer}getSceneIndexForSplat(e){return this.globalSplatIndexToSceneIndexMap[e]}getSceneTransformForSplat(e){return this.getScene(this.globalSplatIndexToSceneIndexMap[e]).transform}getSplatLocalIndex(e){return this.globalSplatIndexToLocalSplatIndexMap[e]}static getIntegerMatrixArray(e){const t=e.elements,n=[];for(let i=0;i<16;i++)n[i]=Math.round(1e3*t[i]);return n}computeBoundingBox(e=!1,t){let n=this.getSplatCount();if(null!=t){if(t<0||t>=this.scenes.length)throw new Error("SplatMesh::computeBoundingBox() -> Invalid scene index.");n=this.scenes[t].splatBuffer.getSplatCount()}const i=new Float32Array(3*n);this.fillSplatDataArrays(null,null,null,i,null,null,e,void 0,void 0,void 0,void 0,t);const r=new hi,s=new hi;for(let a=0;a<n;a++){const e=3*a,t=i[e],n=i[e+1],o=i[e+2];(0===a||t<r.x)&&(r.x=t),(0===a||n<r.y)&&(r.y=n),(0===a||o<r.z)&&(r.z=o),(0===a||t>s.x)&&(s.x=t),(0===a||n>s.y)&&(s.y=n),(0===a||o>s.z)&&(s.z=o)}return new Li(r,s)}}class wf extends Error{constructor(e){super(e),this.name="DirectLoadError"}}const Tf=class e{constructor(e=0){this.sphericalHarmonicsDegree=e,this.sphericalHarmonicsCount=Cp(this.sphericalHarmonicsDegree),this.componentCount=this.sphericalHarmonicsCount+14,this.defaultSphericalHarmonics=new Array(this.sphericalHarmonicsCount).fill(0),this.splats=[],this.splatCount=0}static createSplat(e=0){const t=[0,0,0,1,1,1,1,0,0,0,0,0,0,0];let n=Cp(e);for(let i=0;i<n;i++)t.push(0);return t}addSplat(e){this.splats.push(e),this.splatCount++}getSplat(e){return this.splats[e]}addDefaultSplat(){const t=e.createSplat(this.sphericalHarmonicsDegree);return this.addSplat(t),t}addSplatFromComonents(e,t,n,i,r,s,a,o,l,c,h,u,d,p,...f){const m=[e,t,n,i,r,s,a,o,l,c,h,u,d,p,...this.defaultSphericalHarmonics];for(let g=0;g<f.length&&g<this.sphericalHarmonicsCount;g++)m[g]=f[g];return this.addSplat(m),m}addSplatFromArray(t,n){const i=t.splats[n],r=e.createSplat(this.sphericalHarmonicsDegree);for(let e=0;e<this.componentCount&&e<i.length;e++)r[e]=i[e];this.addSplat(r)}};i(Tf,"OFFSET",{X:0,Y:1,Z:2,SCALE0:3,SCALE1:4,SCALE2:5,ROTATION0:6,ROTATION1:7,ROTATION2:8,ROTATION3:9,FDC0:10,FDC1:11,FDC2:12,OPACITY:13,FRC0:14,FRC1:15,FRC2:16,FRC3:17,FRC4:18,FRC5:19,FRC6:20,FRC7:21,FRC8:22,FRC9:23,FRC10:24,FRC11:25,FRC12:26,FRC13:27,FRC14:28,FRC15:29,FRC16:30,FRC17:31,FRC18:32,FRC19:33,FRC20:34,FRC21:35,FRC22:36,FRC23:37});let Ef=Tf;const Cf=(e,t,n,i,r=0)=>{const s=new Uint8Array(e,t),a=new Uint8Array(n,i);for(let o=0;o<r;o++)a[o]=s[o]},Rf=as.toHalfFloat.bind(as),If=as.fromHalfFloat.bind(as),Pf=(e,t,n=!1,i,r)=>0===t?e:1===t||2===t&&!n?as.fromHalfFloat(e):2===t?Bf(e,i,r):void 0,Df=(e,t,n)=>{e=Mp(e,t,n);const i=n-t;return Mp(Math.floor((e-t)/i*255),0,255)},Bf=(e,t,n)=>e/255*(n-t)+t,Lf=(e,t,n,i=!1)=>0===n?e.getFloat32(4*t,!0):1===n||2===n&&!i?e.getUint16(2*t,!0):e.getUint8(t,!0),Ff=class e{constructor(t,n=!0){i(this,"getSplatScaleAndRotation",function(){const t=new or,n=new or,i=new or,r=new hi,s=new hi,a=new ci;return function(o,l,c,h,u){const d=this.globalSplatIndexToSectionMap[o],p=this.sections[d],f=o-p.splatCountOffset,m=p.bytesPerSplat*f+e.CompressionLevels[this.compressionLevel].ScaleOffsetBytes,g=new DataView(this.bufferData,p.dataBase+m);s.set(Pf(Lf(g,0,this.compressionLevel),this.compressionLevel),Pf(Lf(g,1,this.compressionLevel),this.compressionLevel),Pf(Lf(g,2,this.compressionLevel),this.compressionLevel)),u&&(void 0!==u.x&&(s.x=u.x),void 0!==u.y&&(s.y=u.y),void 0!==u.z&&(s.z=u.z)),a.set(Pf(Lf(g,4,this.compressionLevel),this.compressionLevel),Pf(Lf(g,5,this.compressionLevel),this.compressionLevel),Pf(Lf(g,6,this.compressionLevel),this.compressionLevel),Pf(Lf(g,3,this.compressionLevel),this.compressionLevel)),h?(t.makeScale(s.x,s.y,s.z),n.makeRotationFromQuaternion(a),i.copy(t).multiply(n).multiply(h),i.decompose(r,c,l)):(l.copy(s),c.copy(a))}}()),i(this,"fillSplatScaleRotationArray",function(){const t=new or,n=new or,i=new or,r=new hi,s=new ci,a=new hi,o=e=>{const t=e.w<0?-1:1;e.x*=t,e.y*=t,e.z*=t,e.w*=t};return function(l,c,h,u,d,p,f,m){const g=this.splatCount;u=u||0,d=d||g-1,void 0===p&&(p=u);const _=(e,t)=>zp(e,t,f);for(let v=u;v<=d;v++){const d=this.globalSplatIndexToSectionMap[v],f=this.sections[d],g=v-f.splatCountOffset,x=f.bytesPerSplat*g+e.CompressionLevels[this.compressionLevel].ScaleOffsetBytes,y=(v-u+p)*e.ScaleComponentCount,S=(v-u+p)*e.RotationComponentCount,A=new DataView(this.bufferData,f.dataBase+x),b=m&&void 0!==m.x?m.x:Lf(A,0,this.compressionLevel),M=m&&void 0!==m.y?m.y:Lf(A,1,this.compressionLevel),w=m&&void 0!==m.z?m.z:Lf(A,2,this.compressionLevel),T=Lf(A,3,this.compressionLevel),E=Lf(A,4,this.compressionLevel),C=Lf(A,5,this.compressionLevel),R=Lf(A,6,this.compressionLevel);r.set(Pf(b,this.compressionLevel),Pf(M,this.compressionLevel),Pf(w,this.compressionLevel)),s.set(Pf(E,this.compressionLevel),Pf(C,this.compressionLevel),Pf(R,this.compressionLevel),Pf(T,this.compressionLevel)).normalize(),h&&(a.set(0,0,0),t.makeScale(r.x,r.y,r.z),n.makeRotationFromQuaternion(s),i.identity().premultiply(t).premultiply(n),i.premultiply(h),i.decompose(a,s,r),s.normalize()),o(s),l&&(l[y]=_(r.x,0),l[y+1]=_(r.y,0),l[y+2]=_(r.z,0)),c&&(c[S]=_(s.x,0),c[S+1]=_(s.y,0),c[S+2]=_(s.z,0),c[S+3]=_(s.w,0))}}}()),i(this,"fillSphericalHarmonicsArray",function(){for(let e=0;e<15;e++)new hi;const t=new pi,n=new or,i=new hi,r=new hi,s=new ci,a=[],o=[],l=[],c=[],h=[],u=[],d=[],p=[],f=[],m=[],g=[],_=[],v=[],x=[],y=[],S=[],A=[],b=[],M=e=>e,w=(e,t,n,i)=>{e[0]=t,e[1]=n,e[2]=i},T=(e,t,n,i,r)=>{e[0]=Lf(t,i,r,!0),e[1]=Lf(t,i+n,r,!0),e[2]=Lf(t,i+n+n,r,!0)},E=(e,t)=>{t[0]=e[0],t[1]=e[1],t[2]=e[2]},C=(e,t,n,i)=>{t[n]=i(e[0]),t[n+1]=i(e[1]),t[n+2]=i(e[2])},R=(e,t,n,i,r)=>(t[0]=Pf(e[0],n,!0,i,r),t[1]=Pf(e[1],n,!0,i,r),t[2]=Pf(e[2],n,!0,i,r),t);return function(I,P,D,B,L,F,U){const k=this.splatCount;B=B||0,L=L||k-1,void 0===F&&(F=B),D&&P>=1&&(n.copy(D),n.decompose(i,s,r),s.normalize(),n.makeRotationFromQuaternion(s),t.setFromMatrix4(n),w(a,t.elements[4],-t.elements[7],t.elements[1]),w(o,-t.elements[5],t.elements[8],-t.elements[2]),w(l,t.elements[3],-t.elements[6],t.elements[0]));const N=e=>{return t=e,n=this.minSphericalHarmonicsCoeff,i=this.maxSphericalHarmonicsCoeff,Df(If(t),n,i);var t,n,i},O=e=>Df(e,this.minSphericalHarmonicsCoeff,this.maxSphericalHarmonicsCoeff);for(let t=B;t<=L;t++){const n=this.globalSplatIndexToSectionMap[t],i=this.sections[n];P=Math.min(P,i.sphericalHarmonicsDegree);const r=Cp(P),s=t-i.splatCountOffset,w=i.bytesPerSplat*s+e.CompressionLevels[this.compressionLevel].SphericalHarmonicsOffsetBytes,L=new DataView(this.bufferData,i.dataBase+w),k=(t-B+F)*r;let z=D?0:this.compressionLevel,H=M;z!==U&&(1===z?0===U?H=If:2==U&&(H=N):0===z&&(1===U?H=Rf:2==U&&(H=O)));const V=this.minSphericalHarmonicsCoeff,G=this.maxSphericalHarmonicsCoeff;P>=1&&(T(f,L,3,0,this.compressionLevel),T(m,L,3,1,this.compressionLevel),T(g,L,3,2,this.compressionLevel),D?(R(f,f,this.compressionLevel,V,G),R(m,m,this.compressionLevel,V,G),R(g,g,this.compressionLevel,V,G),e.rotateSphericalHarmonics3(f,m,g,a,o,l,x,y,S)):(E(f,x),E(m,y),E(g,S)),C(x,I,k,H),C(y,I,k+3,H),C(S,I,k+6,H),P>=2&&(T(f,L,5,9,this.compressionLevel),T(m,L,5,10,this.compressionLevel),T(g,L,5,11,this.compressionLevel),T(_,L,5,12,this.compressionLevel),T(v,L,5,13,this.compressionLevel),D?(R(f,f,this.compressionLevel,V,G),R(m,m,this.compressionLevel,V,G),R(g,g,this.compressionLevel,V,G),R(_,_,this.compressionLevel,V,G),R(v,v,this.compressionLevel,V,G),e.rotateSphericalHarmonics5(f,m,g,_,v,a,o,l,c,h,u,d,p,x,y,S,A,b)):(E(f,x),E(m,y),E(g,S),E(_,A),E(v,b)),C(x,I,k+9,H),C(y,I,k+12,H),C(S,I,k+15,H),C(A,I,k+18,H),C(b,I,k+21,H)))}}}()),this.constructFromBuffer(t,n)}getSplatCount(){return this.splatCount}getMaxSplatCount(){return this.maxSplatCount}getMinSphericalHarmonicsDegree(){let e=0;for(let t=0;t<this.sections.length;t++){const n=this.sections[t];(0===t||n.sphericalHarmonicsDegree<e)&&(e=n.sphericalHarmonicsDegree)}return e}getBucketIndex(e,t){let n;const i=e.fullBucketCount*e.bucketSize;if(t<i)n=Math.floor(t/e.bucketSize);else{let r=i;n=e.fullBucketCount;let s=0;for(;r<e.splatCount;){let i=e.partiallyFilledBucketLengths[s];if(t>=r&&t<r+i)break;r+=i,n++,s++}}return n}getSplatCenter(t,n,i,r){const s=this.globalSplatIndexToSectionMap[n],a=this.sections[s],o=n-a.splatCountOffset,l=a.bytesPerSplat*o,c=new DataView(this.bufferData,a.dataBase+l),h=Lf(c,0,this.compressionLevel),u=Lf(c,1,this.compressionLevel),d=Lf(c,2,this.compressionLevel);if(this.compressionLevel>=1){const t=this.getBucketIndex(a,o)*e.BucketStorageSizeFloats,n=a.compressionScaleFactor,r=a.compressionScaleRange;i.x=(h-r)*n+a.bucketArray[t],i.y=(u-r)*n+a.bucketArray[t+1],i.z=(d-r)*n+a.bucketArray[t+2]}else i.x=h,i.y=u,i.z=d;i.x+=t[3*n+0],i.y+=t[3*n+1],i.z+=t[3*n+2],r&&i.applyMatrix4(r)}getSplatColor(t,n){const i=this.globalSplatIndexToSectionMap[t],r=this.sections[i],s=t-r.splatCountOffset,a=r.bytesPerSplat*s+e.CompressionLevels[this.compressionLevel].ColorOffsetBytes,o=new Uint8Array(this.bufferData,r.dataBase+a,4);n.set(o[0],o[1],o[2],o[3])}fillSplatCenterArray(t,n,i,r,s,a){const o=this.splatCount;r=r||0,s=s||o-1,void 0===a&&(a=r);const l=new hi;for(let c=r;c<=s;c++){const s=this.globalSplatIndexToSectionMap[c],o=this.sections[s],h=c-o.splatCountOffset,u=(c-r+a)*e.CenterComponentCount,d=o.bytesPerSplat*h,p=new DataView(this.bufferData,o.dataBase+d),f=Lf(p,0,this.compressionLevel),m=Lf(p,1,this.compressionLevel),g=Lf(p,2,this.compressionLevel);if(this.compressionLevel>=1){const t=this.getBucketIndex(o,h)*e.BucketStorageSizeFloats,n=o.compressionScaleFactor,i=o.compressionScaleRange;l.x=(f-i)*n+o.bucketArray[t],l.y=(m-i)*n+o.bucketArray[t+1],l.z=(g-i)*n+o.bucketArray[t+2]}else l.x=f,l.y=m,l.z=g;i&&l.applyMatrix4(i),n[u]=l.x+t[3*c+0],n[u+1]=l.y+t[3*c+1],n[u+2]=l.z+t[3*c+2]}}fillSplatCovarianceArray(t,n,i,r,s,a){const o=this.splatCount,l=new hi,c=new ci;i=i||0,r=r||o-1,void 0===s&&(s=i);for(let h=i;h<=r;h++){const r=this.globalSplatIndexToSectionMap[h],o=this.sections[r],u=h-o.splatCountOffset,d=(h-i+s)*e.CovarianceComponentCount,p=o.bytesPerSplat*u+e.CompressionLevels[this.compressionLevel].ScaleOffsetBytes,f=new DataView(this.bufferData,o.dataBase+p);l.set(Pf(Lf(f,0,this.compressionLevel),this.compressionLevel),Pf(Lf(f,1,this.compressionLevel),this.compressionLevel),Pf(Lf(f,2,this.compressionLevel),this.compressionLevel)),c.set(Pf(Lf(f,4,this.compressionLevel),this.compressionLevel),Pf(Lf(f,5,this.compressionLevel),this.compressionLevel),Pf(Lf(f,6,this.compressionLevel),this.compressionLevel),Pf(Lf(f,3,this.compressionLevel),this.compressionLevel)),e.computeCovariance(l,c,n,t,d,a)}}fillSplatColorArray(t,n,i,r,s){const a=this.splatCount;i=i||0,r=r||a-1,void 0===s&&(s=i);for(let o=i;o<=r;o++){const r=this.globalSplatIndexToSectionMap[o],a=this.sections[r],l=o-a.splatCountOffset,c=(o-i+s)*e.ColorComponentCount,h=a.bytesPerSplat*l+e.CompressionLevels[this.compressionLevel].ColorOffsetBytes,u=new Uint8Array(this.bufferData,a.dataBase+h);let d=u[3];d=d>=n?d:0,t[c]=u[0],t[c+1]=u[1],t[c+2]=u[2],t[c+3]=d}}static parseHeader(t){const n=new Uint8Array(t,0,e.HeaderSizeBytes),i=new Uint16Array(t,0,e.HeaderSizeBytes/2),r=new Uint32Array(t,0,e.HeaderSizeBytes/4),s=new Float32Array(t,0,e.HeaderSizeBytes/4);return{versionMajor:n[0],versionMinor:n[1],maxSectionCount:r[1],sectionCount:r[2],maxSplatCount:r[3],splatCount:r[4],compressionLevel:i[10],sceneCenter:new hi(s[6],s[7],s[8]),minSphericalHarmonicsCoeff:s[9]||-Fp,maxSphericalHarmonicsCoeff:s[10]||Fp}}static writeHeaderCountsToBuffer(t,n,i){const r=new Uint32Array(i,0,e.HeaderSizeBytes/4);r[2]=t,r[4]=n}static writeHeaderToBuffer(t,n){const i=new Uint8Array(n,0,e.HeaderSizeBytes),r=new Uint16Array(n,0,e.HeaderSizeBytes/2),s=new Uint32Array(n,0,e.HeaderSizeBytes/4),a=new Float32Array(n,0,e.HeaderSizeBytes/4);i[0]=t.versionMajor,i[1]=t.versionMinor,i[2]=0,i[3]=0,s[1]=t.maxSectionCount,s[2]=t.sectionCount,s[3]=t.maxSplatCount,s[4]=t.splatCount,r[10]=t.compressionLevel,a[6]=t.sceneCenter.x,a[7]=t.sceneCenter.y,a[8]=t.sceneCenter.z,a[9]=t.minSphericalHarmonicsCoeff||-Fp,a[10]=t.maxSphericalHarmonicsCoeff||Fp}static parseSectionHeaders(t,n,i=0,r){const s=t.compressionLevel,a=t.maxSectionCount,o=new Uint16Array(n,i,a*e.SectionHeaderSizeBytes/2),l=new Uint32Array(n,i,a*e.SectionHeaderSizeBytes/4),c=new Float32Array(n,i,a*e.SectionHeaderSizeBytes/4),h=[];let u=0,d=u/2,p=u/4,f=e.HeaderSizeBytes+t.maxSectionCount*e.SectionHeaderSizeBytes,m=0;for(let g=0;g<a;g++){const t=l[p+1],n=l[p+2],i=l[p+3],a=c[p+4],_=a/2,v=o[d+10],x=l[p+6]||e.CompressionLevels[s].ScaleRange,y=l[p+8],S=l[p+9],A=4*S,b=v*i+A,M=o[d+20],{bytesPerSplat:w}=e.calculateComponentStorage(s,M),T=w*t,E=T+b,C={bytesPerSplat:w,splatCountOffset:m,splatCount:r?t:0,maxSplatCount:t,bucketSize:n,bucketCount:i,bucketBlockSize:a,halfBucketBlockSize:_,bucketStorageSizeBytes:v,bucketsStorageSizeBytes:b,splatDataStorageSizeBytes:T,storageSizeBytes:E,compressionScaleRange:x,compressionScaleFactor:_/x,base:f,bucketsBase:f+A,dataBase:f+b,fullBucketCount:y,partiallyFilledBucketCount:S,sphericalHarmonicsDegree:M};h[g]=C,f+=E,u+=e.SectionHeaderSizeBytes,d=u/2,p=u/4,m+=t}return h}static writeSectionHeaderToBuffer(t,n,i,r=0){const s=new Uint16Array(i,r,e.SectionHeaderSizeBytes/2),a=new Uint32Array(i,r,e.SectionHeaderSizeBytes/4),o=new Float32Array(i,r,e.SectionHeaderSizeBytes/4);a[0]=t.splatCount,a[1]=t.maxSplatCount,a[2]=n>=1?t.bucketSize:0,a[3]=n>=1?t.bucketCount:0,o[4]=n>=1?t.bucketBlockSize:0,s[10]=n>=1?e.BucketStorageSizeBytes:0,a[6]=n>=1?t.compressionScaleRange:0,a[7]=t.storageSizeBytes,a[8]=n>=1?t.fullBucketCount:0,a[9]=n>=1?t.partiallyFilledBucketCount:0,s[20]=t.sphericalHarmonicsDegree}static writeSectionHeaderSplatCountToBuffer(t,n,i=0){new Uint32Array(n,i,e.SectionHeaderSizeBytes/4)[0]=t}constructFromBuffer(t,n){this.bufferData=t,this.globalSplatIndexToLocalSplatIndexMap=[],this.globalSplatIndexToSectionMap=[];const i=e.parseHeader(this.bufferData);this.versionMajor=i.versionMajor,this.versionMinor=i.versionMinor,this.maxSectionCount=i.maxSectionCount,this.sectionCount=n?i.maxSectionCount:0,this.maxSplatCount=i.maxSplatCount,this.splatCount=n?i.maxSplatCount:0,this.compressionLevel=i.compressionLevel,this.sceneCenter=(new hi).copy(i.sceneCenter),this.minSphericalHarmonicsCoeff=i.minSphericalHarmonicsCoeff,this.maxSphericalHarmonicsCoeff=i.maxSphericalHarmonicsCoeff,this.sections=e.parseSectionHeaders(i,this.bufferData,e.HeaderSizeBytes,n),this.linkBufferArrays(),this.buildMaps()}static calculateComponentStorage(t,n){const i=e.CompressionLevels[t].BytesPerCenter,r=e.CompressionLevels[t].BytesPerScale,s=e.CompressionLevels[t].BytesPerRotation,a=e.CompressionLevels[t].BytesPerColor,o=Cp(n),l=e.CompressionLevels[t].BytesPerSphericalHarmonicsComponent*o;return{bytesPerCenter:i,bytesPerScale:r,bytesPerRotation:s,bytesPerColor:a,sphericalHarmonicsComponentsPerSplat:o,sphericalHarmonicsBytesPerSplat:l,bytesPerSplat:i+r+s+a+l}}linkBufferArrays(){for(let t=0;t<this.maxSectionCount;t++){const n=this.sections[t];n.bucketArray=new Float32Array(this.bufferData,n.bucketsBase,n.bucketCount*e.BucketStorageSizeFloats),n.partiallyFilledBucketCount>0&&(n.partiallyFilledBucketLengths=new Uint32Array(this.bufferData,n.base,n.partiallyFilledBucketCount))}}buildMaps(){let e=0;for(let t=0;t<this.maxSectionCount;t++){const n=this.sections[t];for(let i=0;i<n.maxSplatCount;i++){const n=e+i;this.globalSplatIndexToLocalSplatIndexMap[n]=i,this.globalSplatIndexToSectionMap[n]=t}e+=n.maxSplatCount}}updateLoadedCounts(t,n){e.writeHeaderCountsToBuffer(t,n,this.bufferData),this.sectionCount=t,this.splatCount=n}updateSectionLoadedCounts(t,n){const i=e.HeaderSizeBytes+e.SectionHeaderSizeBytes*t;e.writeSectionHeaderSplatCountToBuffer(n,this.bufferData,i),this.sections[t].splatCount=n}static generateFromUncompressedSplatArrays(t,n,i,r,s,a,o=[]){let l,c,h=0;for(let e=0;e<t.length;e++){const n=t[e];h=Math.max(n.sphericalHarmonicsDegree,h)}for(let e=0;e<t.length;e++){const n=t[e];for(let e=0;e<n.splats.length;e++){const t=n.splats[e];for(let e=Ef.OFFSET.FRC0;e<Ef.OFFSET.FRC23&&e<t.length;e++)(!l||t[e]<l)&&(l=t[e]),(!c||t[e]>c)&&(c=t[e])}}l=l||-Fp,c=c||Fp;const{bytesPerSplat:u}=e.calculateComponentStorage(i,h),d=e.CompressionLevels[i].ScaleRange,p=[],f=[];let m=0;for(let y=0;y<t.length;y++){const r=t[y],g=new Ef(h);for(let e=0;e<r.splatCount;e++){const t=r.splats[e];(t[Ef.OFFSET.OPACITY]||0)>=n&&g.addSplat(t)}const _=o[y]||{},v=(_.blockSizeFactor||1)*(s||e.BucketBlockSize),x=Math.ceil((_.bucketSizeFactor||1)*(a||e.BucketSize)),S=e.computeBucketsForUncompressedSplatArray(g,v,x),A=S.fullBuckets.length,b=S.partiallyFullBuckets.map(e=>e.splats.length),M=b.length,w=[...S.fullBuckets,...S.partiallyFullBuckets],T=g.splats.length*u,E=4*M,C=i>=1?w.length*e.BucketStorageSizeBytes+E:0,R=T+C,I=new ArrayBuffer(R),P=d/(.5*v),D=new hi;let B=0;for(let t=0;t<w.length;t++){const n=w[t];D.fromArray(n.center);for(let t=0;t<n.splats.length;t++){let r=n.splats[t];const s=g.splats[r],a=C+B*u;e.writeSplatDataToSectionBuffer(s,I,a,i,h,D,P,d,l,c),B++}}if(m+=B,i>=1){const t=new Uint32Array(I,0,4*b.length);for(let e=0;e<b.length;e++)t[e]=b[e];const n=new Float32Array(I,E,w.length*e.BucketStorageSizeFloats);for(let e=0;e<w.length;e++){const t=w[e],i=3*e;n[i]=t.center[0],n[i+1]=t.center[1],n[i+2]=t.center[2]}}p.push(I);const L=new ArrayBuffer(e.SectionHeaderSizeBytes);e.writeSectionHeaderToBuffer({maxSplatCount:B,splatCount:B,bucketSize:x,bucketCount:w.length,bucketBlockSize:v,compressionScaleRange:d,storageSizeBytes:R,fullBucketCount:A,partiallyFilledBucketCount:M,sphericalHarmonicsDegree:h},i,L,0),f.push(L)}let g=0;for(let e of p)g+=e.byteLength;const _=e.HeaderSizeBytes+e.SectionHeaderSizeBytes*p.length+g,v=new ArrayBuffer(_);e.writeHeaderToBuffer({versionMajor:0,versionMinor:1,maxSectionCount:p.length,sectionCount:p.length,maxSplatCount:m,splatCount:m,compressionLevel:i,sceneCenter:r,minSphericalHarmonicsCoeff:l,maxSphericalHarmonicsCoeff:c},v);let x=e.HeaderSizeBytes;for(let y of f)new Uint8Array(v,x,e.SectionHeaderSizeBytes).set(new Uint8Array(y)),x+=e.SectionHeaderSizeBytes;for(let e of p)new Uint8Array(v,x,e.byteLength).set(new Uint8Array(e)),x+=e.byteLength;return new e(v)}static computeBucketsForUncompressedSplatArray(e,t,n){let i=e.splatCount;const r=t/2,s=new hi,a=new hi;for(let f=0;f<i;f++){const t=e.splats[f],n=[t[Ef.OFFSET.X],t[Ef.OFFSET.Y],t[Ef.OFFSET.Z]];(0===f||n[0]<s.x)&&(s.x=n[0]),(0===f||n[0]>a.x)&&(a.x=n[0]),(0===f||n[1]<s.y)&&(s.y=n[1]),(0===f||n[1]>a.y)&&(a.y=n[1]),(0===f||n[2]<s.z)&&(s.z=n[2]),(0===f||n[2]>a.z)&&(a.z=n[2])}const o=(new hi).copy(a).sub(s),l=Math.ceil(o.y/t),c=Math.ceil(o.z/t),h=new hi,u=[],d={};for(let f=0;f<i;f++){const i=e.splats[f],a=[i[Ef.OFFSET.X],i[Ef.OFFSET.Y],i[Ef.OFFSET.Z]],o=Math.floor((a[0]-s.x)/t),p=Math.floor((a[1]-s.y)/t),m=Math.floor((a[2]-s.z)/t);h.x=o*t+s.x+r,h.y=p*t+s.y+r,h.z=m*t+s.z+r;const g=o*(l*c)+p*c+m;let _=d[g];_||(d[g]=_={splats:[],center:h.toArray()}),_.splats.push(f),_.splats.length>=n&&(u.push(_),d[g]=null)}const p=[];for(let f in d)if(Object.hasOwn(d,f)){const e=d[f];e&&p.push(e)}return{fullBuckets:u,partiallyFullBuckets:p}}};i(Ff,"CurrentMajorVersion",0),i(Ff,"CurrentMinorVersion",1),i(Ff,"CenterComponentCount",3),i(Ff,"ScaleComponentCount",3),i(Ff,"RotationComponentCount",4),i(Ff,"ColorComponentCount",4),i(Ff,"CovarianceComponentCount",6),i(Ff,"SplatScaleOffsetFloat",3),i(Ff,"SplatRotationOffsetFloat",6),i(Ff,"CompressionLevels",{0:{BytesPerCenter:12,BytesPerScale:12,BytesPerRotation:16,BytesPerColor:4,ScaleOffsetBytes:12,RotationffsetBytes:24,ColorOffsetBytes:40,SphericalHarmonicsOffsetBytes:44,ScaleRange:1,BytesPerSphericalHarmonicsComponent:4,SphericalHarmonicsOffsetFloat:11,SphericalHarmonicsDegrees:{0:{BytesPerSplat:44},1:{BytesPerSplat:80},2:{BytesPerSplat:140}}},1:{BytesPerCenter:6,BytesPerScale:6,BytesPerRotation:8,BytesPerColor:4,ScaleOffsetBytes:6,RotationffsetBytes:12,ColorOffsetBytes:20,SphericalHarmonicsOffsetBytes:24,ScaleRange:32767,BytesPerSphericalHarmonicsComponent:2,SphericalHarmonicsOffsetFloat:12,SphericalHarmonicsDegrees:{0:{BytesPerSplat:24},1:{BytesPerSplat:42},2:{BytesPerSplat:72}}},2:{BytesPerCenter:6,BytesPerScale:6,BytesPerRotation:8,BytesPerColor:4,ScaleOffsetBytes:6,RotationffsetBytes:12,ColorOffsetBytes:20,SphericalHarmonicsOffsetBytes:24,ScaleRange:32767,BytesPerSphericalHarmonicsComponent:1,SphericalHarmonicsOffsetFloat:12,SphericalHarmonicsDegrees:{0:{BytesPerSplat:24},1:{BytesPerSplat:33},2:{BytesPerSplat:48}}}}),i(Ff,"CovarianceSizeFloats",6),i(Ff,"HeaderSizeBytes",4096),i(Ff,"SectionHeaderSizeBytes",1024),i(Ff,"BucketStorageSizeBytes",12),i(Ff,"BucketStorageSizeFloats",3),i(Ff,"BucketBlockSize",5),i(Ff,"BucketSize",256),i(Ff,"computeCovariance",function(){const e=new or,t=new pi,n=new pi,i=new pi,r=new pi,s=new pi,a=new pi;return function(o,l,c,h,u=0,d){e.makeScale(o.x,o.y,o.z),t.setFromMatrix4(e),e.makeRotationFromQuaternion(l),n.setFromMatrix4(e),i.copy(n).multiply(t),r.copy(i).transpose().premultiply(i),c&&(s.setFromMatrix4(c),a.copy(s).transpose(),r.multiply(a),r.premultiply(s)),d>=1?(h[u]=Rf(r.elements[0]),h[u+1]=Rf(r.elements[3]),h[u+2]=Rf(r.elements[6]),h[u+3]=Rf(r.elements[4]),h[u+4]=Rf(r.elements[7]),h[u+5]=Rf(r.elements[8])):(h[u]=r.elements[0],h[u+1]=r.elements[3],h[u+2]=r.elements[6],h[u+3]=r.elements[4],h[u+4]=r.elements[7],h[u+5]=r.elements[8])}}()),i(Ff,"dot3",(e,t,n,i,r)=>{r[0]=r[1]=r[2]=0;const s=i[0],a=i[1],o=i[2];Ff.addInto3(e[0]*s,e[1]*s,e[2]*s,r),Ff.addInto3(t[0]*a,t[1]*a,t[2]*a,r),Ff.addInto3(n[0]*o,n[1]*o,n[2]*o,r)}),i(Ff,"addInto3",(e,t,n,i)=>{i[0]=i[0]+e,i[1]=i[1]+t,i[2]=i[2]+n}),i(Ff,"dot5",(e,t,n,i,r,s,a)=>{a[0]=a[1]=a[2]=0;const o=s[0],l=s[1],c=s[2],h=s[3],u=s[4];Ff.addInto3(e[0]*o,e[1]*o,e[2]*o,a),Ff.addInto3(t[0]*l,t[1]*l,t[2]*l,a),Ff.addInto3(n[0]*c,n[1]*c,n[2]*c,a),Ff.addInto3(i[0]*h,i[1]*h,i[2]*h,a),Ff.addInto3(r[0]*u,r[1]*u,r[2]*u,a)}),i(Ff,"rotateSphericalHarmonics3",(e,t,n,i,r,s,a,o,l)=>{Ff.dot3(e,t,n,i,a),Ff.dot3(e,t,n,r,o),Ff.dot3(e,t,n,s,l)}),i(Ff,"rotateSphericalHarmonics5",(e,t,n,i,r,s,a,o,l,c,h,u,d,p,f,m,g,_)=>{const v=Math.sqrt(1/4),x=Math.sqrt(3/4),y=Math.sqrt(1/3),S=Math.sqrt(4/3),A=Math.sqrt(1/12);l[0]=v*(o[2]*s[0]+o[0]*s[2]+(s[2]*o[0]+s[0]*o[2])),l[1]=o[1]*s[0]+s[1]*o[0],l[2]=x*(o[1]*s[1]+s[1]*o[1]),l[3]=o[1]*s[2]+s[1]*o[2],l[4]=v*(o[2]*s[2]-o[0]*s[0]+(s[2]*o[2]-s[0]*o[0])),Ff.dot5(e,t,n,i,r,l,p),c[0]=v*(a[2]*s[0]+a[0]*s[2]+(s[2]*a[0]+s[0]*a[2])),c[1]=a[1]*s[0]+s[1]*a[0],c[2]=x*(a[1]*s[1]+s[1]*a[1]),c[3]=a[1]*s[2]+s[1]*a[2],c[4]=v*(a[2]*s[2]-a[0]*s[0]+(s[2]*a[2]-s[0]*a[0])),Ff.dot5(e,t,n,i,r,c,f),h[0]=y*(a[2]*a[0]+a[0]*a[2])+-A*(o[2]*o[0]+o[0]*o[2]+(s[2]*s[0]+s[0]*s[2])),h[1]=S*a[1]*a[0]+-y*(o[1]*o[0]+s[1]*s[0]),h[2]=a[1]*a[1]+-v*(o[1]*o[1]+s[1]*s[1]),h[3]=S*a[1]*a[2]+-y*(o[1]*o[2]+s[1]*s[2]),h[4]=y*(a[2]*a[2]-a[0]*a[0])+-A*(o[2]*o[2]-o[0]*o[0]+(s[2]*s[2]-s[0]*s[0])),Ff.dot5(e,t,n,i,r,h,m),u[0]=v*(a[2]*o[0]+a[0]*o[2]+(o[2]*a[0]+o[0]*a[2])),u[1]=a[1]*o[0]+o[1]*a[0],u[2]=x*(a[1]*o[1]+o[1]*a[1]),u[3]=a[1]*o[2]+o[1]*a[2],u[4]=v*(a[2]*o[2]-a[0]*o[0]+(o[2]*a[2]-o[0]*a[0])),Ff.dot5(e,t,n,i,r,u,g),d[0]=v*(o[2]*o[0]+o[0]*o[2]-(s[2]*s[0]+s[0]*s[2])),d[1]=o[1]*o[0]-s[1]*s[0],d[2]=x*(o[1]*o[1]-s[1]*s[1]),d[3]=o[1]*o[2]-s[1]*s[2],d[4]=v*(o[2]*o[2]-o[0]*o[0]-(s[2]*s[2]-s[0]*s[0])),Ff.dot5(e,t,n,i,r,d,_)}),i(Ff,"writeSplatDataToSectionBuffer",function(){const e=new ArrayBuffer(12),t=new ArrayBuffer(12),n=new ArrayBuffer(16),i=new ArrayBuffer(4),r=new ArrayBuffer(256),s=new ci,a=new hi,o=new hi,{X:l,Y:c,Z:h,SCALE0:u,SCALE1:d,SCALE2:p,ROTATION0:f,ROTATION1:m,ROTATION2:g,ROTATION3:_,FDC0:v,FDC1:x,FDC2:y,OPACITY:S,FRC0:A,FRC9:b}=Ef.OFFSET,M=(e,t,n)=>{const i=2*n+1;return e=Math.round(e*t)+n,Mp(e,0,i)};return function(w,T,E,C,R,I,P,D,B=-Fp,L=Fp){const F=Cp(R),U=E,k=U+Ff.CompressionLevels[C].BytesPerCenter,N=k+Ff.CompressionLevels[C].BytesPerScale,O=N+Ff.CompressionLevels[C].BytesPerRotation,z=O+Ff.CompressionLevels[C].BytesPerColor;if(void 0!==w[f]?(s.set(w[f],w[m],w[g],w[_]),s.normalize()):s.set(1,0,0,0),void 0!==w[u]?a.set(w[u]||0,w[d]||0,w[p]||0):a.set(0,0,0),0===C){const e=new Float32Array(T,U,Ff.CenterComponentCount),t=new Float32Array(T,N,Ff.RotationComponentCount),n=new Float32Array(T,k,Ff.ScaleComponentCount);if(t.set([s.x,s.y,s.z,s.w]),n.set([a.x,a.y,a.z]),e.set([w[l],w[c],w[h]]),R>0){const e=new Float32Array(T,z,F);if(R>=1){for(let t=0;t<9;t++)e[t]=w[A+t]||0;if(R>=2)for(let t=0;t<15;t++)e[t+9]=w[b+t]||0}}}else{const i=new Uint16Array(e,0,Ff.CenterComponentCount),u=new Uint16Array(n,0,Ff.RotationComponentCount),d=new Uint16Array(t,0,Ff.ScaleComponentCount);if(u.set([Rf(s.x),Rf(s.y),Rf(s.z),Rf(s.w)]),d.set([Rf(a.x),Rf(a.y),Rf(a.z)]),o.set(w[l],w[c],w[h]).sub(I),o.x=M(o.x,P,D),o.y=M(o.y,P,D),o.z=M(o.z,P,D),i.set([o.x,o.y,o.z]),R>0){const e=1===C?2:1,t=new(1===C?Uint16Array:Uint8Array)(r,0,F);if(R>=1){for(let e=0;e<9;e++){const n=w[A+e]||0;t[e]=1===C?Rf(n):Df(n,B,L)}const n=9*e;if(Cf(t.buffer,0,T,z,n),R>=2){for(let e=0;e<15;e++){const n=w[b+e]||0;t[e+9]=1===C?Rf(n):Df(n,B,L)}Cf(t.buffer,n,T,z+n,15*e)}}}Cf(i.buffer,0,T,U,6),Cf(d.buffer,0,T,k,6),Cf(u.buffer,0,T,N,8)}const H=new Uint8ClampedArray(i,0,4);H.set([w[v]||0,w[x]||0,w[y]||0]),H[3]=w[S]||0,Cf(H.buffer,0,T,O,4)}}());let Uf=Ff;class kf{constructor(e,t,n,i){this.sectionCount=e,this.sectionFilters=t,this.groupingParameters=n,this.partitionGenerator=i}partitionUncompressedSplatArray(e){let t,n,i;if(this.partitionGenerator){const r=this.partitionGenerator(e);t=r.groupingParameters,n=r.sectionCount,i=r.sectionFilters}else t=this.groupingParameters,n=this.sectionCount,i=this.sectionFilters;const r=[];for(let s=0;s<n;s++){const t=new Ef(e.sphericalHarmonicsDegree),n=i[s];for(let i=0;i<e.splatCount;i++)n(i)&&t.addSplat(e.splats[i]);r.push(t)}return{splatArrays:r,parameters:t}}static getStandardPartitioner(e=0,t=new hi,n=Uf.BucketBlockSize,i=Uf.BucketSize){return new kf(void 0,void 0,void 0,r=>{const s=Ef.OFFSET.X,a=Ef.OFFSET.Y,o=Ef.OFFSET.Z;e<=0&&(e=r.splatCount);const l=new hi,c=.5;r.splats.forEach(e=>{var n;l.set(e[s],e[a],e[o]).sub(t),(n=l).x=Math.floor(n.x/c)*c,n.y=Math.floor(n.y/c)*c,n.z=Math.floor(n.z/c)*c,e.centerDist=l.lengthSq()}),r.splats.sort((e,t)=>e.centerDist>t.centerDist?1:-1);const h=[],u=[];e=Math.min(r.splatCount,e);const d=Math.ceil(r.splatCount/e);let p=0;for(let t=0;t<d;t++){let t=p;h.push(n=>n>=t&&n<t+e),u.push({blocksSize:n,bucketSize:i}),p+=e}return{sectionCount:h.length,sectionFilters:h,groupingParameters:u}})}}class Nf{constructor(e,t,n,i,r,s,a){this.splatPartitioner=e,this.alphaRemovalThreshold=t,this.compressionLevel=n,this.sectionSize=i,this.sceneCenter=r?(new hi).copy(r):void 0,this.blockSize=s,this.bucketSize=a}generateFromUncompressedSplatArray(e){const t=this.splatPartitioner.partitionUncompressedSplatArray(e);return Uf.generateFromUncompressedSplatArrays(t.splatArrays,this.alphaRemovalThreshold,this.compressionLevel,this.sceneCenter,this.blockSize,this.bucketSize,t.parameters)}static getStandardGenerator(e=1,t=1,n=0,i=new hi,r=Uf.BucketBlockSize,s=Uf.BucketSize){const a=kf.getStandardPartitioner(n,i,r,s);return new Nf(a,e,t,n,i,r,s)}}const Of=0,zf=0,Hf=1,Vf=2,Gf=3,Wf=4,jf=5,Xf=6,qf={double:0,int:1,uint:2,float:3,short:4,ushort:5,uchar:6},Qf={[zf]:8,[Hf]:4,[Vf]:4,[Gf]:4,[Wf]:2,[jf]:2,[Xf]:1},Kf=class e{constructor(){}decodeSectionHeader(t,n,i=0){const r=[];let s=!1,a=-1,o=0,l=!1,c=null;const h=[],u=[],d=[],p={};for(let _=i;_<t.length;_++){const f=t[_].trim();if(f.startsWith("element")){if(s){a--;break}{s=!0,i=_,a=_;const e=f.split(" ");let t=0;for(let n of e){const e=n.trim();e.length>0&&(t++,2===t?c=e:3===t&&(o=parseInt(e)))}}}else if(f.startsWith("property")){const e=f.match(/(\w+)\s+(\w+)\s+(\w+)/);if(e){const t=e[2],i=e[3];d.push(i);const r=n[i];p[i]=t;const s=qf[t];void 0!==r&&(h.push(r),u[r]=s)}}if(f===e.HeaderEndToken){l=!0;break}s&&(r.push(f),a++)}const f=[];let m=0;for(let e of d){const t=p[e];if(Object.hasOwn(p,e)){const t=n[e];void 0!==t&&(f[t]=m)}m+=Qf[qf[t]]}const g=this.decodeSphericalHarmonicsFromSectionHeader(d,n);return{headerLines:r,headerStartLine:i,headerEndLine:a,fieldTypes:u,fieldIds:h,fieldOffsets:f,bytesPerVertex:m,vertexCount:o,dataSizeBytes:m*o,endOfHeader:l,sectionName:c,sphericalHarmonicsDegree:g.degree,sphericalHarmonicsCoefficientsPerChannel:g.coefficientsPerChannel,sphericalHarmonicsDegree1Fields:g.degree1Fields,sphericalHarmonicsDegree2Fields:g.degree2Fields}}decodeSphericalHarmonicsFromSectionHeader(e,t){let n=0,i=0;for(let o of e)o.startsWith("f_rest")&&n++;i=n/3;let r=0;i>=3&&(r=1),i>=8&&(r=2);let s=[],a=[];for(let o=0;o<3;o++){if(r>=1)for(let e=0;e<3;e++)s.push(t["f_rest_"+(e+i*o)]);if(r>=2)for(let e=0;e<5;e++)a.push(t["f_rest_"+(e+i*o+3)])}return{degree:r,coefficientsPerChannel:i,degree1Fields:s,degree2Fields:a}}static getHeaderSectionNames(e){const t=[];for(let n of e)if(n.startsWith("element")){const e=n.split(" ");let i=0;for(let n of e){const e=n.trim();e.length>0&&(i++,2===i&&t.push(e))}}return t}static checkTextForEndHeader(t){return!!t.includes(e.HeaderEndToken)}static checkBufferForEndHeader(t,n,i,r){const s=new Uint8Array(t,Math.max(0,n-i),i),a=r.decode(s);return e.checkTextForEndHeader(a)}static extractHeaderFromBufferToText(t){const n=new TextDecoder;let i=0,r="";for(;;){if(i+100>=t.byteLength)throw new Error("End of file reached while searching for end of header");const s=new Uint8Array(t,i,100);if(r+=n.decode(s),i+=100,e.checkBufferForEndHeader(t,i,200,n))break}return r}readHeaderFromBuffer(t){const n=new TextDecoder;let i=0,r="";for(;;){if(i+100>=t.byteLength)throw new Error("End of file reached while searching for end of header");const s=new Uint8Array(t,i,100);if(r+=n.decode(s),i+=100,e.checkBufferForEndHeader(t,i,200,n))break}return r}static convertHeaderTextToLines(t){const n=t.split("\n"),i=[];for(let r=0;r<n.length;r++){const t=n[r].trim();if(i.push(t),t===e.HeaderEndToken)break}return i}static determineHeaderFormatFromHeaderText(e){return Of}static determineHeaderFormatFromPlyBuffer(t){const n=e.extractHeaderFromBufferToText(t);return e.determineHeaderFormatFromHeaderText(n)}static readVertex(e,t,n,i,r,s,a=!0){const o=n*t.bytesPerVertex+i,l=t.fieldOffsets,c=t.fieldTypes;for(let h of r){const t=c[h];3===t?s[h]=e.getFloat32(o+l[h],!0):4===t?s[h]=e.getInt16(o+l[h],!0):5===t?s[h]=e.getUint16(o+l[h],!0):1===t?s[h]=e.getInt32(o+l[h],!0):2===t?s[h]=e.getUint32(o+l[h],!0):6===t&&(s[h]=a?e.getUint8(o+l[h])/255:e.getUint8(o+l[h]))}}};i(Kf,"HeaderEndToken","end_header");let Yf=Kf;const Zf=["scale_0","scale_1","scale_2","rot_0","rot_1","rot_2","rot_3","x","y","z","f_dc_0","f_dc_1","f_dc_2","opacity","red","green","blue","f_rest_0"],Jf=Zf.map((e,t)=>t),[$f,em,tm,nm,im,rm,sm,am,om,lm,cm,hm,um,dm,pm,fm,mm,gm]=Jf,_m=class e{constructor(){this.plyParserutils=new Yf}decodeHeaderLines(e){let t=0;e.forEach(e=>{e.includes("f_rest_")&&t++});let n=0;t>=45?n=45:t>=24?n=24:t>=9&&(n=9);let i=Array.from(Array(Math.max(n-1,0))).map((e,t)=>`f_rest_${t+1}`);const r=[...Zf,...i],s=r.map((e,t)=>t),a=s.reduce((e,t)=>(e[r[t]]=t,e),{}),o=this.plyParserutils.decodeSectionHeader(e,a,0);return o.splatCount=o.vertexCount,o.bytesPerSplat=o.bytesPerVertex,o.fieldsToReadIndexes=s,o}decodeHeaderText(e){const t=Yf.convertHeaderTextToLines(e),n=this.decodeHeaderLines(t);return n.headerText=e,n.headerSizeBytes=e.indexOf(Yf.HeaderEndToken)+Yf.HeaderEndToken.length+1,n}decodeHeaderFromBuffer(e){const t=this.plyParserutils.readHeaderFromBuffer(e);return this.decodeHeaderText(t)}findSplatData(e,t){return new DataView(e,t.headerSizeBytes)}parseToUncompressedSplatBufferSection(t,n,i,r,s,a,o,l=0){l=Math.min(l,t.sphericalHarmonicsDegree);const c=Uf.CompressionLevels[0].SphericalHarmonicsDegrees[l].BytesPerSplat;for(let h=n;h<=i;h++){const n=e.parseToUncompressedSplat(r,h,t,s,l),i=h*c+o;Uf.writeSplatDataToSectionBuffer(n,a,i,0,l)}}parseToUncompressedSplatArraySection(t,n,i,r,s,a,o=0){o=Math.min(o,t.sphericalHarmonicsDegree);for(let l=n;l<=i;l++){const n=e.parseToUncompressedSplat(r,l,t,s,o);a.addSplat(n)}}decodeSectionSplatData(t,n,i,r){r=Math.min(r,i.sphericalHarmonicsDegree);const s=new Ef(r);for(let a=0;a<n;a++){const n=e.parseToUncompressedSplat(t,a,i,0,r);s.addSplat(n)}return s}static readSplat(e,t,n,i,r){return Yf.readVertex(e,t,n,i,t.fieldsToReadIndexes,r,!0)}parseToUncompressedSplatArray(e,t=0){const n=this.decodeHeaderFromBuffer(e),i=n.splatCount,r=this.findSplatData(e,n);return this.decodeSectionSplatData(r,i,n,t)}};i(_m,"parseToUncompressedSplat",function(){let e=[];const t=new ci,n=Ef.OFFSET.X,i=Ef.OFFSET.Y,r=Ef.OFFSET.Z,s=Ef.OFFSET.SCALE0,a=Ef.OFFSET.SCALE1,o=Ef.OFFSET.SCALE2,l=Ef.OFFSET.ROTATION0,c=Ef.OFFSET.ROTATION1,h=Ef.OFFSET.ROTATION2,u=Ef.OFFSET.ROTATION3,d=Ef.OFFSET.FDC0,p=Ef.OFFSET.FDC1,f=Ef.OFFSET.FDC2,m=Ef.OFFSET.OPACITY,g=[];for(let _=0;_<45;_++)g[_]=Ef.OFFSET.FRC0+_;return function(_,v,x,y=0,S=0){S=Math.min(S,x.sphericalHarmonicsDegree),_m.readSplat(_,x,v,y,e);const A=Ef.createSplat(S);if(void 0!==e[$f]?(A[s]=Math.exp(e[$f]),A[a]=Math.exp(e[em]),A[o]=Math.exp(e[tm])):(A[s]=.01,A[a]=.01,A[o]=.01),void 0!==e[cm]?(A[d]=255*e[cm],A[p]=255*e[hm],A[f]=255*e[um]):void 0!==e[pm]?(A[d]=255*e[pm],A[p]=255*e[fm],A[f]=255*e[mm]):(A[d]=0,A[p]=0,A[f]=0),void 0!==e[dm]&&(A[m]=1/(1+Math.exp(-e[dm]))*255),A[d]=Mp(Math.floor(A[d]),0,255),A[p]=Mp(Math.floor(A[p]),0,255),A[f]=Mp(Math.floor(A[f]),0,255),A[m]=Mp(Math.floor(A[m]),0,255),S>=1&&void 0!==e[gm]){for(let t=0;t<9;t++)A[g[t]]=e[x.sphericalHarmonicsDegree1Fields[t]];if(S>=2)for(let t=0;t<15;t++)A[g[9+t]]=e[x.sphericalHarmonicsDegree2Fields[t]]}return t.set(e[nm],e[im],e[rm],e[sm]),t.normalize(),A[l]=t.x,A[c]=t.y,A[h]=t.z,A[u]=t.w,A[n]=e[am],A[i]=e[om],A[r]=e[lm],A}}());let vm=_m;class xm{static parseToUncompressedSplatArray(e,t=0){return(new vm).parseToUncompressedSplatArray(e,t)}}const ym=Sp("PlyLoader");function Sm(e,t,n,i,r,s,a,o){try{return t?Nf.getStandardGenerator(n,i,r,s,a,o).generateFromUncompressedSplatArray(e):Uf.generateFromUncompressedSplatArrays([e],n,0,new hi)}catch(l){throw new gp(`Failed to finalize splat data: ${l.message}`,"splatData",l)}}class Am{static loadFromURL(e,t,n,i,r,s,a=!0,o=0,l,c,h,u,d){try{Wp(e)}catch(B){throw ym.error("Invalid URL provided to loadFromURL",{fileName:e,error:B}),B}t&&jp(t,"onProgress",!1),i&&jp(i,"onProgressiveLoadSectionProgress",!1),ym.info("Loading PLY from URL",{fileName:e,optimizeSplatData:a,outSphericalHarmonicsDegree:o});let p=n?rp:sp;a&&(p=sp);const f=np.ProgressiveLoadSectionSize,m=Uf.HeaderSizeBytes+Uf.SectionHeaderSizeBytes;let g,_,v,x=0,y=0,S=!1,A=!1;const b=(()=>{let e,t;return{promise:new Promise((n,i)=>{e=n,t=i}),resolve:e,reject:t}})();let M,w=0,T=0,E=0,C="",R=null,I=[];const P=new TextDecoder,D=new vm;if(t)try{t(0,"0%",op)}catch(L){ym.warn("Error in onProgress callback",L)}return function(e,t,n=!0,i){const r=new AbortController,s=r.signal;let a=!1,o=!1;const l=(e,n,i,r)=>{if(t&&!o)try{t(e,n,i,r),100===e&&(o=!0)}catch(s){Ap.error("Error in progress callback:",s)}},c=new Promise((t,r)=>{const o={signal:s};i&&(o.headers=i),fetch(e,o).then(async e=>{if(!e.ok){let t="";try{t=await e.text()}catch{}return void r(new dp(`Fetch failed: ${e.statusText}${t?" - "+t:""}`,e.status))}const i=e.body?.getReader();if(!i)return void r(new dp("Response body is not readable",0));let s=0;const o=e.headers.get("Content-Length"),c=o?parseInt(o,10):void 0,h=[];for(;!a;)try{const{value:e,done:r}=await i.read();if(r){if(l(100,"100%",e,c),n){const e=new Blob(h).arrayBuffer();t(e)}else t();break}let a,o;s+=e.length,void 0!==c&&(a=s/c*100,o=`${a.toFixed(2)}%`),n&&h.push(e),l(a,o,e,c)}catch(u){return void r(new dp(`Error reading response stream: ${u.message}`,0,u))}}).catch(e=>{e instanceof dp?r(e):"AbortError"===e.name?r(new dp("Fetch aborted by user",0,e)):r(new dp(`Fetch failed: ${e.message||"Unknown error"}`,0,e))})});return c.abort=e=>{a=!0,r.abort(e)},c.abortController=r,c}(e,(e,n,r)=>{const s=e>=100;if(r&&(I.push({data:r,sizeBytes:r.byteLength,startBytes:E,endBytes:E+r.byteLength}),E+=r.byteLength),p===ap)s&&b.resolve(I);else{if(!S&&(C+=P.decode(r),Yf.checkTextForEndHeader(C))){try{R=D.decodeHeaderText(C),x=R.splatCount,A=!0,ym.debug("PLY header decoded",{splatCount:x,sphericalHarmonicsDegree:R.sphericalHarmonicsDegree}),o=Math.min(o,R.sphericalHarmonicsDegree)}catch(a){const e=new gp(`Failed to decode PLY header: ${a.message}`,"headerText",a);return ym.error("Header parsing failed",e),void b.reject(e)}const e=Uf.CompressionLevels[0].SphericalHarmonicsDegrees[o],t=m+e.BytesPerSplat*x;p===rp?(_=new ArrayBuffer(t),Uf.writeHeaderToBuffer({versionMajor:Uf.CurrentMajorVersion,versionMinor:Uf.CurrentMinorVersion,maxSectionCount:1,sectionCount:1,maxSplatCount:x,splatCount:y,compressionLevel:0,sceneCenter:new hi},_)):M=new Ef(o),w=R.headerSizeBytes,T=R.headerSizeBytes,S=!0}if(S&&A){if(I.length>0&&(g=function(e,t){let n=0;for(let r of e)n+=r.sizeBytes;(!t||t.byteLength<n)&&(t=new ArrayBuffer(n));let i=0;for(let r of e)new Uint8Array(t,i,r.sizeBytes).set(r.data),i+=r.sizeBytes;return t}(I,g),E-w>f||s)){const e=E-T,t=Math.floor(e/R.bytesPerSplat),n=t*R.bytesPerSplat,r=e-n,l=y+t,c=T-I[0].startBytes,h=new DataView(g,c,n),u=Uf.CompressionLevels[0].SphericalHarmonicsDegrees[o],d=y*u.BytesPerSplat+m;try{p===rp?D.parseToUncompressedSplatBufferSection(R,0,t-1,h,0,_,d,o):D.parseToUncompressedSplatArraySection(R,0,t-1,h,0,M,o)}catch(a){const e=new gp(`Failed to parse splat data section: ${a.message}`,"splatData",a);return ym.error("Splat data parsing failed",{splatCount:y,addedSplatCount:t,error:a}),void b.reject(e)}if(y=l,p===rp&&(v||(Uf.writeSectionHeaderToBuffer({maxSplatCount:x,splatCount:y,bucketSize:0,bucketCount:0,bucketBlockSize:0,compressionScaleRange:0,storageSizeBytes:0,fullBucketCount:0,partiallyFilledBucketCount:0,sphericalHarmonicsDegree:o},0,_,Uf.HeaderSizeBytes),v=new Uf(_,!1)),v.updateLoadedCounts(1,y),i&&i(v,s)),w+=f,T+=n,0===r)I=[];else{let e=[],t=0;for(let n=I.length-1;n>=0;n--){const i=I[n];if(t+=i.sizeBytes,e.unshift(i),t>=r)break}I=e}}s&&(p===rp?b.resolve(v):b.resolve(M))}}if(t)try{t(e,n,op)}catch(l){ym.warn("Error in onProgress callback",l)}},!1,l).then(()=>{if(t)try{t(0,"0%",lp)}catch(L){ym.warn("Error in onProgress callback",L)}return b.promise}).then(n=>{if(t)try{t(100,"100%",cp)}catch(L){ym.warn("Error in onProgress callback",L)}if(ym.debug("PLY data loaded successfully",{internalLoadType:p,splatCount:n?.splatCount||"unknown"}),p===ap){const t=I.map(e=>e.data);return new Blob(t).arrayBuffer().then(e=>Am.loadFromFileData(e,r,s,a,o,c,h,u,d)).catch(t=>{throw new pp(`Failed to process downloaded PLY data: ${t.message}`,e,t)})}return p===rp?n:Ep(()=>Sm(n,a,r,s,c,h,u,d))}).catch(t=>{if(t instanceof up||t instanceof dp||t instanceof gp||t instanceof pp)throw ym.error("PLY loading failed",{fileName:e,errorCode:t.code}),t;throw ym.error("Unexpected error loading PLY",{fileName:e,error:t}),new pp(`Unexpected error loading PLY file: ${t.message}`,e,t)})}static loadFromFileData(e,t,n,i,r=0,s,a,o,l){try{!function(e,t,n=0){if(!(e instanceof ArrayBuffer))throw new up(`${t} must be an ArrayBuffer`,t);if(e.byteLength<n)throw new up(`${t} must be at least ${n} bytes, got ${e.byteLength}`,t)}(e,"plyFileData")}catch(c){return ym.error("Invalid PLY file data",c),Promise.reject(c)}return ym.info("Loading PLY from file data",{sizeBytes:e.byteLength,optimizeSplatData:i,outSphericalHarmonicsDegree:r}),Ep(()=>{try{return xm.parseToUncompressedSplatArray(e,r)}catch(c){throw new gp(`Failed to parse PLY file data: ${c.message}`,"plyFileData",c)}}).then(e=>(ym.debug("PLY parsed successfully",{splatCount:e?.splatCount||"unknown"}),Sm(e,i,t,n,s,a,o,l))).catch(e=>{if(e instanceof up||e instanceof gp)throw ym.error("PLY file data loading failed",{errorCode:e.code}),e;throw ym.error("Unexpected error loading PLY from file data",e),new gp(`Unexpected error parsing PLY data: ${e.message}`,"plyFileData",e)})}}const bm=new hi(1,0,0),Mm=new hi(0,1,0),wm=new hi(0,0,1);class Tm{constructor(e=new hi,t=new hi){i(this,"intersectBox",function(){const e=new hi,t=[],n=[],i=[];return function(r,s){if(n[0]=this.origin.x,n[1]=this.origin.y,n[2]=this.origin.z,i[0]=this.direction.x,i[1]=this.direction.y,i[2]=this.direction.z,this.boxContainsPoint(r,this.origin,1e-4))return s&&(s.origin.copy(this.origin),s.normal.set(0,0,0),s.distance=-1),!0;for(let a=0;a<3;a++){if(0==i[a])continue;const o=0==a?bm:1==a?Mm:wm,l=i[a]<0?r.max:r.min;let c=-Math.sign(i[a]);t[0]=0==a?l.x:1==a?l.y:l.z;let h=t[0]-n[a];if(h*c<0){const l=(a+1)%3,u=(a+2)%3;if(t[2]=i[l]/i[a]*h+n[l],t[1]=i[u]/i[a]*h+n[u],e.set(t[a],t[u],t[l]),this.boxContainsPoint(r,e,1e-4))return s&&(s.origin.copy(e),s.normal.copy(o).multiplyScalar(c),s.distance=e.sub(this.origin).length()),!0}}return!1}}()),i(this,"intersectSphere",function(){const e=new hi;return function(t,n,i){e.copy(t).sub(this.origin);const r=e.dot(this.direction),s=r*r,a=e.dot(e)-s,o=n*n;if(a>o)return!1;const l=Math.sqrt(o-a),c=r-l,h=r+l;if(h<0)return!1;let u=c<0?h:c;return i&&(i.origin.copy(this.origin).addScaledVector(this.direction,u),i.normal.copy(i.origin).sub(t).normalize(),i.distance=u),!0}}()),this.origin=new hi,this.direction=new hi,this.setParameters(e,t)}setParameters(e,t){this.origin.copy(e),this.direction.copy(t).normalize()}boxContainsPoint(e,t,n){return!(t.x<e.min.x-n||t.x>e.max.x+n||t.y<e.min.y-n||t.y>e.max.y+n||t.z<e.min.z-n||t.z>e.max.z+n)}}class Em{constructor(){this.origin=new hi,this.normal=new hi,this.distance=0,this.splatIndex=0}set(e,t,n,i){this.origin.copy(e),this.normal.copy(t),this.distance=n,this.splatIndex=i}clone(){const e=new Em;return e.origin.copy(this.origin),e.normal.copy(this.normal),e.distance=this.distance,e.splatIndex=this.splatIndex,e}}class Cm{constructor(e,t,n=!1){i(this,"setFromCameraAndScreenPosition",function(){const e=new li;return function(t,n,i){if(e.x=n.x/i.x*2-1,e.y=(i.y-n.y)/i.y*2-1,t.isPerspectiveCamera)this.ray.origin.setFromMatrixPosition(t.matrixWorld),this.ray.direction.set(e.x,e.y,.5).unproject(t).sub(this.ray.origin).normalize(),this.camera=t;else{if(!t.isOrthographicCamera)throw new Error("Raycaster::setFromCameraAndScreenPosition() -> Unsupported camera type");this.ray.origin.set(e.x,e.y,(t.near+t.far)/(t.near-t.far)).unproject(t),this.ray.direction.set(0,0,-1).transformDirection(t.matrixWorld),this.camera=t}}}()),i(this,"intersectSplatMesh",function(){const e=new or,t=new or,n=new or,i=new Tm,r=new hi;return function(s,a=[]){const o=s.getSplatTree();if(o){for(let l=0;l<o.subTrees.length;l++){const c=o.subTrees[l];t.copy(s.matrixWorld),s.dynamicMode&&(s.getSceneTransform(l,n),t.multiply(n)),e.copy(t).invert(),i.origin.copy(this.ray.origin).applyMatrix4(e),i.direction.copy(this.ray.origin).add(this.ray.direction),i.direction.applyMatrix4(e).sub(i.origin).normalize();const h=[];c.rootNode&&this.castRayAtSplatTreeNode(i,o,c.rootNode,h),h.forEach(e=>{e.origin.applyMatrix4(t),e.normal.applyMatrix4(t).normalize(),e.distance=r.copy(e.origin).sub(this.ray.origin).length()}),a.push(...h)}return a.sort((e,t)=>e.distance>t.distance?1:-1),a}}}()),i(this,"castRayAtSplatTreeNode",function(){const e=new Ri,t=new hi,n=new hi,i=new ci,r=new Em,s=1e-7,a=new hi(0,0,0),o=new or,l=new or,c=new or,h=new or,u=new or,d=new Tm;return function(p,f,m,g=[]){if(p.intersectBox(m.boundingBox)){if(m.data&&m.data.indexes&&m.data.indexes.length>0)for(let _=0;_<m.data.indexes.length;_++){const v=m.data.indexes[_],x=f.splatMesh.getSceneIndexForSplat(v);if(f.splatMesh.getScene(x).visible&&(f.splatMesh.getSplatColor(v,e),f.splatMesh.getSplatCenter(v,t),f.splatMesh.getSplatScaleAndRotation(v,n,i),!(n.x<=s||n.y<=s||f.splatMesh.splatRenderMode===ep&&n.z<=s)))if(this.raycastAgainstTrueSplatEllipsoid){l.makeScale(n.x,n.y,n.z),c.makeRotationFromQuaternion(i);const s=2*Math.log10(e.w);if(o.makeScale(s,s,s),u.copy(o).multiply(c).multiply(l),h.copy(u).invert(),d.origin.copy(p.origin).sub(t).applyMatrix4(h),d.direction.copy(p.origin).add(p.direction).sub(t),d.direction.applyMatrix4(h).sub(d.origin).normalize(),d.intersectSphere(a,1,r)){const e=r.clone();e.splatIndex=v,e.origin.applyMatrix4(u).add(t),g.push(e)}}else{let e=n.x+n.y,i=2;if(f.splatMesh.splatRenderMode===ep&&(e+=n.z,i=3),e/=i,p.intersectSphere(t,e,r)){const e=r.clone();e.splatIndex=v,g.push(e)}}}if(m.children&&m.children.length>0)for(let e of m.children)this.castRayAtSplatTreeNode(p,f,e,g);return g}}}()),this.ray=new Tm(e,t),this.raycastAgainstTrueSplatEllipsoid=n}}const Rm="AGFzbQEAAAAADwhkeWxpbmsuMAEEAAAAAAEXAmAAAGAQf39/f39/f39/f39/f39/fwACEgEDZW52Bm1lbW9yeQIDAICABAMDAgABBz4DEV9fd2FzbV9jYWxsX2N0b3JzAAAYX193YXNtX2FwcGx5X2RhdGFfcmVsb2NzAAALc29ydEluZGV4ZXMAAQqiDwICAAucDwMBfAd9Bn8gCyAKayEMAkACQCAOBEAgDQRAQfj///8HIQpBiICAgHghDSALIAxNDQMgDCEFA0AgAyAFQQJ0IgFqIAIgACABaigCAEECdGooAgAiATYCACABIAogASAKSBshCiABIA0gASANShshDSAFQQFqIgUgC0cNAAsMAwsgDwRAIAsgDE0NAkF/IQ9B+P///wchCkGIgICAeCENIAwhAgNAIA8gByAAIAJBAnQiGmooAgBBAnQiG2ooAgAiDkcEQAJ/IAUqAjgiESAIIA5BBnRqIg8qAjyUIAUqAigiEiAPKgI4lCAFKgIIIhMgDyoCMJQgBSoCGCIUIA8qAjSUkpKSu0QAAAAAAECPQKIiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLIRgCfyARIA8qAiyUIBIgDyoCKJQgEyAPKgIglCAUIA8qAiSUkpKSu0QAAAAAAECPQKIiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLIRkCfyARIA8qAhyUIBIgDyoCGJQgEyAPKgIQlCAUIA8qAhSUkpKSu0QAAAAAAECPQKIiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLIRwCfyARIA8qAgyUIBIgDyoCCJQgEyAPKgIAlCAUIA8qAgSUkpKSu0QAAAAAAECPQKIiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLIR0gDiEPCyADIBpqIAEgG0ECdGoiDigCBCAcbCAOKAIAIB1saiAOKAIIIBlsaiAOKAIMIBhsaiIONgIAIA4gCiAKIA5KGyEKIA4gDSANIA5IGyENIAJBAWoiAiALRw0ACwwDCwJ/IAUqAii7RAAAAAAAQI9AoiIQmUQAAAAAAADgQWMEQCAQqgwBC0GAgICAeAshAgJ/IAUqAhi7RAAAAAAAQI9AoiIQmUQAAAAAAADgQWMEQCAQqgwBC0GAgICAeAshByALIAxNAn8gBSoCCLtEAAAAAABAj0CiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyEPQfj///8HIQpBiICAgHghDQ0CIAwhBQNAIAMgBUECdCIIaiABIAAgCGooAgBBBHRqIggoAgQgB2wgCCgCACAPbGogCCgCCCACbGoiCDYCACAIIAogCCAKSBshCiAIIA0gCCANShshDSAFQQFqIgUgC0cNAAsMAgsgDQRAQfj///8HIQpBiICAgHghDSALIAxNDQIgDCEFA0AgAyAFQQJ0IgFqAn8gAiAAIAFqKAIAQQJ0aioCALtEAAAAAAAAsECiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyIONgIAIAogDiAKIA5IGyEKIA0gDiANIA5KGyENIAVBAWoiBSALRw0ACwwCCyAPRQRAIAsgDE0NASAFKgIoIREgBSoCGCESIAUqAgghE0H4////ByEKQYiAgIB4IQ0gDCEFA0ACfyARIAEgACAFQQJ0IgdqKAIAQQR0aiICKgIIlCATIAIqAgCUIBIgAioCBJSSkrtEAAAAAAAAsECiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyEOIAMgB2ogDjYCACAKIA4gCiAOSBshCiANIA4gDSAOShshDSAFQQFqIgUgC0cNAAsMAgsgCyAMTQ0AQX8hD0H4////ByEKQYiAgIB4IQ0gDCECA0AgDyAHIAAgAkECdCIYaigCAEECdCIZaigCACIORwRAIAUqAjgiESAIIA5BBnRqIg8qAjyUIAUqAigiEiAPKgI4lCAFKgIIIhMgDyoCMJQgBSoCGCIUIA8qAjSUkpKSIRUgESAPKgIslCASIA8qAiiUIBMgDyoCIJQgFCAPKgIklJKSkiEWIBEgDyoCHJQgEiAPKgIYlCATIA8qAhCUIBQgDyoCFJSSkpIhFyARIA8qAgyUIBIgDyoCCJQgEyAPKgIAlCAUIA8qAgSUkpKSIREgDiEPCyADIBhqAn8gFSABIBlBAnRqIg4qAgyUIBYgDioCCJQgESAOKgIAlCAXIA4qAgSUkpKSu0QAAAAAAACwQKIiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLIg42AgAgCiAOIAogDkgbIQogDSAOIA0gDkobIQ0gAkEBaiICIAtHDQALDAELQYiAgIB4IQ1B+P///wchCgsgCyAMSwRAIAlBAWuzIA2yIAqyk5UhESAMIQ0DQAJ/IBEgAyANQQJ0aiIBKAIAIAprspQiEotDAAAAT10EQCASqAwBC0GAgICAeAshDiABIA42AgAgBCAOQQJ0aiIBIAEoAgBBAWo2AgAgDUEBaiINIAtHDQALCyAJQQJPBEAgBCgCACENQQEhCgNAIAQgCkECdGoiASABKAIAIA1qIg02AgAgCkEBaiIKIAlHDQALCyAMQQBKBEAgDCEKA0AgBiAKQQFrIgFBAnQiAmogACACaigCADYCACAKQQFLIAEhCg0ACwsgCyAMSgRAIAshCgNAIAYgCyAEIAMgCkEBayIKQQJ0IgFqKAIAQQJ0aiICKAIAIgVrQQJ0aiAAIAFqKAIANgIAIAIgBUEBazYCACAKIAxKDQALCws=";function Im(e){let t,n,i,r,s,a,o,l,c,h,u,d,p,f,m,g,_,v,x,y;e.onmessage=S=>{if(S.data.centers){let e=S.data.centers,t=S.data.sceneIndexes;r?new Int32Array(n,f+S.data.range.from*y.BytesPerInt*4,4*S.data.range.count).set(new Int32Array(e)):new Float32Array(n,f+S.data.range.from*y.BytesPerFloat*4,4*S.data.range.count).set(new Float32Array(e)),s&&new Uint32Array(n,c+4*S.data.range.from,S.data.range.count).set(new Uint32Array(t)),x=S.data.range.from+S.data.range.count}else if(S.data.sort){const A=Math.min(S.data.sort.splatRenderCount||0,x),b=Math.min(S.data.sort.splatSortCount||0,x),M=S.data.sort.usePrecomputedDistances;let w,T,E;i||(w=S.data.sort.indexesToSort,E=S.data.sort.transforms,M&&(T=S.data.sort.precomputedDistances)),function(x,S,A,b,M,w,T){const E=performance.now();if(!i&&(new Uint32Array(n,o,M.byteLength/y.BytesPerInt).set(M),new Float32Array(n,h,T.byteLength/y.BytesPerFloat).set(T),b)){let e;e=r?new Int32Array(n,u,w.byteLength/y.BytesPerInt):new Float32Array(n,u,w.byteLength/y.BytesPerFloat),e.set(w)}g||(g=new Uint32Array(v)),new Float32Array(n,m,16).set(A),new Uint32Array(n,p,v).set(g),t.exports.sortIndexes(o,f,u,d,p,m,l,c,h,v,x,S,a,b,r,s);const C={sortDone:!0,splatSortCount:x,splatRenderCount:S,sortTime:0};if(!i){const e=new Uint32Array(n,l,S);(!_||_.length<S)&&(_=new Uint32Array(S)),_.set(e),C.sortedIndexes=_}const R=performance.now();C.sortTime=R-E,e.postMessage(C)}(b,A,S.data.sort.modelViewProj,M,w,T,E)}else if(S.data.init){y=S.data.init.Constants,a=S.data.init.splatCount,i=S.data.init.useSharedMemory,r=S.data.init.integerBasedSort,s=S.data.init.dynamicMode,v=S.data.init.distanceMapRange,x=0;const g=r?4*y.BytesPerInt:4*y.BytesPerFloat,_=new Uint8Array(S.data.init.sorterWasmBytes),A=16*y.BytesPerFloat,b=a*y.BytesPerInt,M=a*g,w=A,T=r?a*y.BytesPerInt:a*y.BytesPerFloat,E=a*y.BytesPerInt,C=a*y.BytesPerInt,R=r?v*y.BytesPerInt*2:v*y.BytesPerFloat*2,I=s?a*y.BytesPerInt:0,P=s?y.MaxScenes*A:0,D=32*y.MemoryPageSize,B=b+M+w+T+E+R+C+I+P+D,L=Math.floor(B/y.MemoryPageSize)+1,F={module:{},env:{memory:new WebAssembly.Memory({initial:L,maximum:L,shared:!0})}};WebAssembly.compile(_).then(e=>WebAssembly.instantiate(e,F)).then(r=>{t=r,o=0,f=o+b,m=f+M,u=m+w,d=u+T,p=d+E,l=p+R,c=l+C,h=c+I,n=F.env.memory.buffer,i?e.postMessage({sortSetupPhase1Complete:!0,indexesToSortBuffer:n,indexesToSortOffset:o,sortedIndexesBuffer:n,sortedIndexesOffset:l,precomputedDistancesBuffer:n,precomputedDistancesOffset:u,transformsBuffer:n,transformsOffset:h}):e.postMessage({sortSetupPhase1Complete:!0})})}}}const Pm=Sp("Viewer");class Dm{constructor(e,t){this.tasks=[]}show(){}hide(){}setContainer(e){}addTask(e){return this.tasks.push(e)}removeTask(e){}removeAllTasks(){this.tasks=[]}setMessageForTask(e,t){}}class Bm{constructor(e){}show(){}hide(){}setContainer(e){}setProgress(e){}}class Lm{constructor(e){this.scene=e,this.meshCursor=null,this.meshCursorVisible=!1,this.focusMarker=null,this.focusMarkerOpacity=0,this.controlPlane=null,this.controlPlaneVisible=!1}setupMeshCursor(){}setupFocusMarker(){}setupControlPlane(){}updateMeshCursor(e,t){}updateFocusMarker(e,t,n){}updateControlPlane(e,t){}setFocusMarkerVisibility(e){}setFocusMarkerOpacity(e){this.focusMarkerOpacity=e}getFocusMarkerOpacity(){return this.focusMarkerOpacity}positionAndOrientFocusMarker(e,t){}positionAndOrientMeshCursor(e,t){}setMeshCursorVisibility(e){this.meshCursorVisible=e}getMeschCursorVisibility(){return this.meshCursorVisible}setControlPlaneVisibility(e){this.controlPlaneVisible=e}positionAndOrientControlPlane(e,t,n){}updateForRenderMode(e,t){}dispose(){}}const Fm=class e{constructor(e={}){if(i(this,"tempForward",new hi),i(this,"tempMatrixLeft",new or),i(this,"tempMatrixRight",new or),i(this,"onKeyDown",e=>{switch(this.tempForward.set(0,0,-1),this.tempForward.transformDirection(this.camera.matrixWorld),this.tempMatrixLeft.makeRotationAxis(this.tempForward,Math.PI/128),this.tempMatrixRight.makeRotationAxis(this.tempForward,-Math.PI/128),e.code){case"KeyG":this.focalAdjustment+=.02,this.forceRenderNextFrame();break;case"KeyF":this.focalAdjustment-=.02,this.forceRenderNextFrame();break;case"ArrowLeft":this.camera.up.transformDirection(this.tempMatrixLeft);break;case"ArrowRight":this.camera.up.transformDirection(this.tempMatrixRight);break;case"KeyC":this.showMeshCursor=!this.showMeshCursor;break;case"KeyU":this.showControlPlane=!this.showControlPlane;break;case"KeyI":this.showInfo=!this.showInfo,this.showInfo;break;case"KeyO":this.usingExternalCamera||this.setOrthographicMode(!this.camera.isOrthographicCamera);break;case"KeyP":this.usingExternalCamera||this.splatMesh.setPointCloudModeEnabled(!this.splatMesh.getPointCloudModeEnabled());break;case"Equal":this.usingExternalCamera||this.splatMesh.setSplatScale(this.splatMesh.getSplatScale()+.05);break;case"Minus":this.usingExternalCamera||this.splatMesh.setSplatScale(Math.max(this.splatMesh.getSplatScale()-.05,0))}}),i(this,"onMouseUp",function(){const e=new li;return function(t){e.copy(this.mousePosition).sub(this.mouseDownPosition),wp()-this.mouseDownTime<.5&&e.length()<2&&this.onMouseClick(t)}}()),i(this,"checkPointRenderDimensions",new li),i(this,"checkPointToNewFocalPoint",new hi),i(this,"checkPointOutHits",[]),i(this,"checkForFocalPointChange",()=>{if(!this.transitioningCameraTarget&&(this.getRenderDimensions(this.checkPointRenderDimensions),this.checkPointOutHits.length=0,this.raycaster.setFromCameraAndScreenPosition(this.camera,this.mousePosition,this.checkPointRenderDimensions),this.raycaster.intersectSplatMesh(this.splatMesh,this.checkPointOutHits),this.checkPointOutHits.length>0)){const e=this.checkPointOutHits[0].origin;this.checkPointToNewFocalPoint.copy(e).sub(this.camera.position),this.checkPointToNewFocalPoint.length()>.5&&(this.previousCameraTarget.copy(this.controls.target),this.nextCameraTarget.copy(e),this.transitioningCameraTarget=!0,this.transitioningCameraTargetStartTime=wp())}}),i(this,"updateSplatMesh",function(){const e=new li;return function(){if(this.splatMesh&&this.splatMesh.getSplatCount()>0){this.splatMesh.updateVisibleRegionFadeDistance(this.sceneRevealMode),this.splatMesh.updateTransforms(),this.getRenderDimensions(e);const t=.5*this.camera.projectionMatrix.elements[0]*this.devicePixelRatio*e.x,n=.5*this.camera.projectionMatrix.elements[5]*this.devicePixelRatio*e.y,i=this.camera.isOrthographicCamera?1/this.devicePixelRatio:1,r=this.focalAdjustment*i,s=1/r;this.adjustForWebXRStereo(e),this.splatMesh.updateUniforms(e,t*r,n*r,this.camera.isOrthographicCamera,this.camera.zoom||1,s)}}}()),i(this,"addSplatBuffers",(e,t=[],n=!0,i=!0,r=!0,s=!1,a=!1,o=!0)=>{if(this.isDisposingOrDisposed())return Promise.resolve();let l=null;const c=()=>{null!==l&&(this.loadingSpinner.removeTask(l),l=null)};return this.splatRenderReady=!1,new Promise(h=>{i&&(l=this.loadingSpinner.addTask("Processing splats...")),Ep(()=>{if(this.isDisposingOrDisposed())h();else{const i=this.addSplatBuffersToMesh(e,t,n,r,s,o),l=this.splatMesh.getMaxSplatCount();this.sortWorker&&this.sortWorker.maxSplatCount!==l&&this.disposeSortWorker(),this.gpuAcceleratedSort||this.preSortMessages.push({centers:i.centers.buffer,sceneIndexes:i.sceneIndexes.buffer,range:{from:i.from,to:i.to,count:i.count}}),(!this.sortWorker&&l>0?this.setupSortWorker(this.splatMesh):Promise.resolve()).then(()=>{this.isDisposingOrDisposed()||this.runSplatSort(!0,!0).then(e=>{this.sortWorker&&e?(a?this.splatRenderReady=!0:this.runAfterNextSort.push(()=>{this.splatRenderReady=!0}),this.runAfterNextSort.push(()=>{c(),h()})):(this.splatRenderReady=!0,c(),h())})})}},!0)})}),i(this,"addSplatBuffersToMesh",function(){let e;return function(t,n,i=!0,r=!1,s=!1,a=!0){if(this.isDisposingOrDisposed())return;let o=[],l=[];s||(o=this.splatMesh.scenes.map(e=>e.splatBuffer)||[],l=this.splatMesh.sceneOptions?this.splatMesh.sceneOptions.map(e=>e):[]),o.push(...t),l.push(...n),this.renderer&&this.splatMesh.setRenderer(this.renderer);const c=this.splatMesh.build(o,l,!0,i,t=>{if(this.isDisposingOrDisposed())return;const n=this.splatMesh.getSplatCount();r&&n>=15e5&&(t||e||(this.loadingSpinner.setMinimized(!0,!0),e=this.loadingSpinner.addTask("Optimizing data structures...")))},t=>{this.isDisposingOrDisposed()||t&&e&&(this.loadingSpinner.removeTask(e),e=null)},a);return i&&this.freeIntermediateSplatData&&this.splatMesh.freeIntermediateSplatData(),c}}()),i(this,"vsyncNum",4),i(this,"shouldRender",function(){let e=0;const t=new hi,n=new ci,i=1e-4;return function(){if(!this.initialized||!this.splatRenderReady||this.isDisposingOrDisposed())return!1;let r=!1,s=!1;if(this.camera){const e=this.camera.position,r=this.camera.quaternion;s=Math.abs(e.x-t.x)>i||Math.abs(e.y-t.y)>i||Math.abs(e.z-t.z)>i||Math.abs(r.x-n.x)>i||Math.abs(r.y-n.y)>i||Math.abs(r.z-n.z)>i||Math.abs(r.w-n.w)>i}return r=this.renderMode!==Kd&&(0===e||this.splatMesh.visibleRegionChanging||s||this.renderMode===Qd||!0===this.dynamicMode||this.renderNextFrame),this.camera&&(t.copy(this.camera.position),n.copy(this.camera.quaternion)),e++,r}}()),i(this,"render",function(){if(!this.initialized||!this.splatRenderReady||this.isDisposingOrDisposed())return;const e=this.renderer.autoClear;(e=>{for(let t of e.children)if(t.visible)return!0;return!1})(this.threeScene)&&(this.renderer.render(this.threeScene,this.camera),this.renderer.autoClear=!1),this.renderer.render(this.splatMesh,this.camera),this.renderer.autoClear=!1,this.sceneHelper.getFocusMarkerOpacity()>0&&this.renderer.render(this.sceneHelper.focusMarker,this.camera),this.showControlPlane&&this.renderer.render(this.sceneHelper.controlPlane,this.camera),this.renderer.autoClear=e}),i(this,"sortedIndexes"),i(this,"lastCalcTime",wp()),i(this,"fpsFrameCount",0),i(this,"updateFPS",()=>{if(this.consecutiveRenderFrames>60){const e=wp();e-this.lastCalcTime>=1?(this.currentFPS=this.fpsFrameCount,this.fpsFrameCount=0,this.lastCalcTime=e):this.fpsFrameCount++}else this.currentFPS=null}),i(this,"updateForRendererSizeChanges",function(){const e=new li,t=new li;let n;return function(){this.usingExternalCamera||(this.renderer.getSize(t),void 0!==n&&n===this.camera.isOrthographicCamera&&t.x===e.x&&t.y===e.y||(this.camera.isOrthographicCamera?(this.camera.left=-t.x/2,this.camera.right=t.x/2,this.camera.top=t.y/2,this.camera.bottom=-t.y/2):this.camera.aspect=t.x/t.y,this.camera.updateProjectionMatrix(),e.copy(t),n=this.camera.isOrthographicCamera))}}()),i(this,"timingSensitiveUpdates",function(){let e;return function(){const t=wp();e||(e=t);const n=t-e;this.updateCameraTransition(t),this.updateFocusMarker(n),e=t}}()),i(this,"tempCameraTarget",new hi),i(this,"toPreviousTarget",new hi),i(this,"toNextTarget",new hi),i(this,"updateCameraTransition",e=>{if(this.transitioningCameraTarget){this.toPreviousTarget.copy(this.previousCameraTarget).sub(this.camera.position).normalize(),this.toNextTarget.copy(this.nextCameraTarget).sub(this.camera.position).normalize();const t=Math.acos(this.toPreviousTarget.dot(this.toNextTarget)),n=(t/(Math.PI/3)*.65+.3)/t*(e-this.transitioningCameraTargetStartTime);this.tempCameraTarget.copy(this.previousCameraTarget).lerp(this.nextCameraTarget,n),this.camera.lookAt(this.tempCameraTarget),this.controls.target.copy(this.tempCameraTarget),n>=1&&(this.transitioningCameraTarget=!1)}}),i(this,"updateFocusMarker",function(){const e=new li;let t=!1;return function(n){if(this.getRenderDimensions(e),this.transitioningCameraTarget){this.sceneHelper.setFocusMarkerVisibility(!0);const i=Math.max(this.sceneHelper.getFocusMarkerOpacity(),0);let r=Math.min(i+.4*n,1);this.sceneHelper.setFocusMarkerOpacity(r),this.sceneHelper.updateFocusMarker(this.nextCameraTarget,this.camera,e),t=!0,this.forceRenderNextFrame()}else{let i;if(i=t?1:Math.min(this.sceneHelper.getFocusMarkerOpacity(),1),i>0){this.sceneHelper.updateFocusMarker(this.nextCameraTarget,this.camera,e);let t=Math.max(i-.12*n,0);this.sceneHelper.setFocusMarkerOpacity(t),0===t&&this.sceneHelper.setFocusMarkerVisibility(!1)}i>0&&this.forceRenderNextFrame(),t=!1}}}()),i(this,"updateMeshCursor",function(){const e=[],t=new li;return function(){this.showMeshCursor?(this.forceRenderNextFrame(),this.getRenderDimensions(t),e.length=0,this.raycaster.setFromCameraAndScreenPosition(this.camera,this.mousePosition,t),this.raycaster.intersectSplatMesh(this.splatMesh,e),e.length>0?(this.sceneHelper.setMeshCursorVisibility(!0),this.sceneHelper.positionAndOrientMeshCursor(e[0].origin,this.camera)):this.sceneHelper.setMeshCursorVisibility(!1)):(this.sceneHelper.getMeschCursorVisibility()&&this.forceRenderNextFrame(),this.sceneHelper.setMeshCursorVisibility(!1))}}()),i(this,"updateInfoPanel",function(){const e=new li;return function(){if(!this.showInfo)return;const t=this.splatMesh.getSplatCount();this.getRenderDimensions(e),this.controls&&this.controls.target,this.showMeshCursor&&this.sceneHelper.meshCursor.position,t>0&&this.splatRenderCount}}()),i(this,"mvpMatrix",new or),i(this,"cameraPositionArray",[]),i(this,"lastSortViewDir",new hi(0,0,-1)),i(this,"sortViewDir",new hi(0,0,-1)),i(this,"lastSortViewPos",new hi),i(this,"sortViewOffset",new hi),i(this,"queuedSorts",[]),i(this,"partialSorts",[{angleThreshold:.55,sortFractions:[.125,.33333,.75]},{angleThreshold:.65,sortFractions:[.33333,.66667]},{angleThreshold:.8,sortFractions:[.5]}]),i(this,"runSplatSort",(e=!1,t=!1)=>{if(!this.initialized)return Promise.resolve(!1);if(this.sortRunning)return Promise.resolve(!0);if(this.splatMesh.getSplatCount()<=0)return this.splatRenderCount=0,Promise.resolve(!1);let n=0,i=0,r=!1,s=!1;if(this.sortViewDir.set(0,0,-1).applyQuaternion(this.camera.quaternion),n=this.sortViewDir.dot(this.lastSortViewDir),i=this.sortViewOffset.copy(this.camera.position).sub(this.lastSortViewPos).length(),!(e||this.splatMesh.dynamicMode||0!==this.queuedSorts.length||(n<=.99&&(r=!0),i>=1&&(s=!0),r||s)))return Promise.resolve(!1);this.sortRunning=!0;let{splatRenderCount:a,shouldSortAll:o}=this.gatherSceneNodesForSort();o=o||t,this.splatRenderCount=a,this.mvpMatrix.copy(this.camera.matrixWorld).invert();const l=this.perspectiveCamera||this.camera;this.mvpMatrix.premultiply(l.projectionMatrix),this.splatMesh.dynamicMode||this.mvpMatrix.multiply(this.splatMesh.matrixWorld);let c=Promise.resolve(!0);return this.gpuAcceleratedSort&&(this.queuedSorts.length<=1||this.queuedSorts.length%2==0)&&(c=this.splatMesh.computeDistancesOnGPU(this.mvpMatrix,this.sortWorkerPrecomputedDistances)),c.then(()=>{if(0===this.queuedSorts.length)if(this.splatMesh.dynamicMode||o)this.queuedSorts.push(this.splatRenderCount);else{for(let e of this.partialSorts)if(n<e.angleThreshold){for(let t of e.sortFractions)this.queuedSorts.push(Math.floor(this.splatRenderCount*t));break}this.queuedSorts.push(this.splatRenderCount)}let e=Math.min(this.queuedSorts.shift(),this.splatRenderCount);this.splatSortCount=e,this.cameraPositionArray[0]=this.camera.position.x,this.cameraPositionArray[1]=this.camera.position.y,this.cameraPositionArray[2]=this.camera.position.z;const t={modelViewProj:this.mvpMatrix.elements,cameraPosition:this.cameraPositionArray,splatRenderCount:this.splatRenderCount,splatSortCount:e,usePrecomputedDistances:this.gpuAcceleratedSort};return this.splatMesh.dynamicMode&&this.splatMesh.fillTransformsArray(this.sortWorkerTransforms),this.sharedMemoryForWorkers||(t.indexesToSort=this.sortWorkerIndexesToSort,t.transforms=this.sortWorkerTransforms,this.gpuAcceleratedSort&&(t.precomputedDistances=this.sortWorkerPrecomputedDistances)),this.sortPromise=new Promise(e=>{this.sortPromiseResolver=e}),this.preSortMessages.length>0&&(this.preSortMessages.forEach(e=>{this.sortWorker.postMessage(e)}),this.preSortMessages=[]),this.sortWorker.postMessage({sort:t}),0===this.queuedSorts.length&&(this.lastSortViewPos.copy(this.camera.position),this.lastSortViewDir.copy(this.sortViewDir)),!0}),c}),i(this,"gatherSceneNodesForSort",function(){const e=[];let t=null;const n=new hi,i=new hi,r=new hi,s=new or,a=new or,o=new or,l=new hi,c=new hi(0,0,-1),h=new hi,u=e=>h.copy(e.max).sub(e.min).length();return function(h=!1){this.getRenderDimensions(l);const d=l.y/2/Math.tan(this.camera.fov/2*oi.DEG2RAD),p=Math.atan(l.x/2/d),f=Math.atan(l.y/2/d),m=Math.cos(p),g=Math.cos(f),_=this.splatMesh.getSplatTree();if(_){a.copy(this.camera.matrixWorld).invert(),this.splatMesh.dynamicMode||a.multiply(this.splatMesh.matrixWorld);let t=0,l=0;for(let p=0;p<_.subTrees.length;p++){const d=_.subTrees[p];s.copy(a),this.splatMesh.dynamicMode&&(this.splatMesh.getSceneTransform(p,o),s.multiply(o));const f=d.nodesWithIndexes.length;for(let a=0;a<f;a++){const o=d.nodesWithIndexes[a];if(!o.data||!o.data.indexes||0===o.data.indexes.length)continue;r.copy(o.center).applyMatrix4(s);const p=r.length();r.normalize(),n.copy(r).setX(0).normalize(),i.copy(r).setY(0).normalize();const f=c.dot(i),_=c.dot(n),v=u(o);!h&&(f<m-.6||_<g-.6)&&p>v||(l+=o.data.indexes.length,e[t]=o,o.data.distanceToNode=p,t++)}}e.length=t,e.sort((e,t)=>e.data.distanceToNode<t.data.distanceToNode?-1:1);let d=l*np.BytesPerInt;for(let n=0;n<t;n++){const t=e[n],i=t.data.indexes.length,r=i*np.BytesPerInt;new Uint32Array(this.sortWorkerIndexesToSort.buffer,d-r,i).set(t.data.indexes),d-=r}return{splatRenderCount:l,shouldSortAll:!1}}{const e=this.splatMesh.getSplatCount();if(!t||t.length!==e){t=new Uint32Array(e);for(let n=0;n<e;n++)t[n]=n}return this.sortWorkerIndexesToSort.set(t),{splatRenderCount:e,shouldSortAll:!0}}}}()),e.cameraUp||(e.cameraUp=[0,1,0]),this.cameraUp=(new hi).fromArray(e.cameraUp),e.initialCameraPosition||(e.initialCameraPosition=[0,10,15]),this.initialCameraPosition=(new hi).fromArray(e.initialCameraPosition),e.initialCameraRotation||(e.initialCameraRotation=[0,0,0]),this.initialCameraRotation=(new hi).fromArray(e.initialCameraRotation),this.backgroundColor=e.backgroundColor,e.initialCameraLookAt||(e.initialCameraLookAt=[0,0,0]),this.initialCameraLookAt=(new hi).fromArray(e.initialCameraLookAt),this.dropInMode=e.dropInMode||!1,void 0!==e.selfDrivenMode&&null!==e.selfDrivenMode||(e.selfDrivenMode=!0),this.selfDrivenMode=e.selfDrivenMode&&!this.dropInMode,this.selfDrivenUpdateFunc=this.selfDrivenUpdate.bind(this),void 0===e.useBuiltInControls&&(e.useBuiltInControls=!0),this.useBuiltInControls=e.useBuiltInControls,this.rootElement=e.rootElement,this.canvas=e.threejsCanvas,this.ignoreDevicePixelRatio=e.ignoreDevicePixelRatio||!1,this.devicePixelRatio=this.ignoreDevicePixelRatio?1:window.devicePixelRatio||1,this.halfPrecisionCovariancesOnGPU=e.halfPrecisionCovariancesOnGPU||!1,this.threeScene=e.threeScene,this.renderer=e.renderer,this.camera=e.camera,this.gpuAcceleratedSort=e.gpuAcceleratedSort||!1,void 0!==e.integerBasedSort&&null!==e.integerBasedSort||(e.integerBasedSort=!0),this.integerBasedSort=e.integerBasedSort,void 0!==e.sharedMemoryForWorkers&&null!==e.sharedMemoryForWorkers||(e.sharedMemoryForWorkers=!0),this.sharedMemoryForWorkers=!1,this.dynamicScene=!!e.dynamicScene,this.antialiased=e.antialiased||!1,this.kernel2DSize=void 0===e.kernel2DSize?.3:e.kernel2DSize,this.renderMode=e.renderMode||Qd,this.sceneRevealMode=e.sceneRevealMode||Jd,this.focalAdjustment=e.focalAdjustment||1,this.maxScreenSpaceSplatSize=e.maxScreenSpaceSplatSize||1024,this.logLevel=e.logLevel||Xd,this.sphericalHarmonicsDegree=e.sphericalHarmonicsDegree||0,this.enableOptionalEffects=e.enableOptionalEffects||!1,void 0!==e.enableSIMDInSort&&null!==e.enableSIMDInSort||(e.enableSIMDInSort=!0),this.enableSIMDInSort=e.enableSIMDInSort,void 0!==e.inMemoryCompressionLevel&&null!==e.inMemoryCompressionLevel||(e.inMemoryCompressionLevel=0),this.inMemoryCompressionLevel=e.inMemoryCompressionLevel,void 0!==e.optimizeSplatData&&null!==e.optimizeSplatData||(e.optimizeSplatData=!0),this.optimizeSplatData=e.optimizeSplatData,void 0!==e.freeIntermediateSplatData&&null!==e.freeIntermediateSplatData||(e.freeIntermediateSplatData=!1),this.freeIntermediateSplatData=e.freeIntermediateSplatData,Pp()){const e=Dp();e.major<17&&(this.enableSIMDInSort=!1),e.major<16&&(this.sharedMemoryForWorkers=!1)}void 0!==e.splatRenderMode&&null!==e.splatRenderMode||(e.splatRenderMode=ep),this.splatRenderMode=e.splatRenderMode,this.sceneFadeInRateMultiplier=e.sceneFadeInRateMultiplier||1,this.splatSortDistanceMapPrecision=e.splatSortDistanceMapPrecision||np.DefaultSplatSortDistanceMapPrecision;const t=this.integerBasedSort?20:24;this.splatSortDistanceMapPrecision=Mp(this.splatSortDistanceMapPrecision,10,t),this.onSplatMeshChangedCallback=null,this.createSplatMesh(),this.controls=null,this.perspectiveControls=null,this.orthographicControls=null,this.orthographicCamera=null,this.perspectiveCamera=null,this.showMeshCursor=!1,this.showControlPlane=!1,this.showInfo=!1,this.sceneHelper=null,this.sortWorker=null,this.sortRunning=!1,this.splatRenderCount=0,this.splatSortCount=0,this.lastSplatSortCount=0,this.sortWorkerIndexesToSort=null,this.sortWorkerSortedIndexes=null,this.sortWorkerPrecomputedDistances=null,this.sortWorkerTransforms=null,this.preSortMessages=[],this.runAfterNextSort=[],this.selfDrivenModeRunning=!1,this.splatRenderReady=!1,this.raycaster=new Cm,this.infoPanel=null,this.startInOrthographicMode=!1,this.currentFPS=0,this.lastSortTime=0,this.consecutiveRenderFrames=0,this.previousCameraTarget=new hi,this.nextCameraTarget=new hi,this.mousePosition=new li,this.mouseDownPosition=new li,this.mouseDownTime=null,this.resizeObserver=null,this.mouseMoveListener=null,this.mouseDownListener=null,this.mouseUpListener=null,this.keyDownListener=null,this.sortPromise=null,this.sortPromiseResolver=null,this.splatSceneDownloadControllers=[],this.splatSceneDownloadPromises={},this.splatSceneDownloadAndBuildPromise=null,this.splatSceneRemovalPromise=null,this.loadingSpinner=new Dm(null,this.rootElement||document.body),this.loadingSpinner.hide(),this.loadingProgressBar=new Bm(this.rootElement||document.body),this.loadingProgressBar.hide(),this.usingExternalCamera=!(!this.dropInMode&&!this.camera),this.usingExternalRenderer=!(!this.dropInMode&&!this.renderer),this.initialized=!1,this.disposing=!1,this.disposed=!1,this.disposePromise=null,this.lastTime=0,this.gaussianSplatCount=0,this.totalFrames=0,this.frame=0,this.avatarMesh=null,this.skinModel=null,this.boneRoot=null,this.baseMesh=null,this.setSkinAttibutes=!1,this.dropInMode||this.init()}createSplatMesh(){this.splatMesh=new Mf(this.splatRenderMode,this.dynamicScene,this.enableOptionalEffects,this.halfPrecisionCovariancesOnGPU,this.devicePixelRatio,this.gpuAcceleratedSort,this.integerBasedSort,this.antialiased,this.maxScreenSpaceSplatSize,this.logLevel,this.sphericalHarmonicsDegree,this.sceneFadeInRateMultiplier,this.kernel2DSize),this.splatMesh.irisOcclusionConfig=this.irisOcclusionConfig,this.splatMesh.frustumCulled=!1,this.onSplatMeshChangedCallback&&this.onSplatMeshChangedCallback()}init(){this.initialized||(this.rootElement||(this.usingExternalRenderer?this.rootElement=this.renderer.domElement||document.body:(this.rootElement=document.createElement("div"),this.rootElement.style.width="100%",this.rootElement.style.height="100%",this.rootElement.style.position="absolute",document.body.appendChild(this.rootElement))),this.setupCamera(),this.setupRenderer(),this.setupEventHandlers(),this.threeScene=this.threeScene||new $s,this.sceneHelper=new Lm(this.threeScene),this.sceneHelper.setupMeshCursor(),this.sceneHelper.setupFocusMarker(),this.sceneHelper.setupControlPlane(),this.loadingProgressBar.setContainer(this.rootElement),this.loadingSpinner.setContainer(this.rootElement),this.initialized=!0)}setupCamera(){if(!this.usingExternalCamera){const e=new li;this.getRenderDimensions(e),this.perspectiveCamera=new js(50,e.x/e.y,.1,1e3),this.orthographicCamera=new Ko(e.x/-2,e.x/2,e.y/2,e.y/-2,.1,1e3),this.camera=this.startInOrthographicMode?this.orthographicCamera:this.perspectiveCamera,this.camera.position.copy(this.initialCameraPosition),this.camera.rotateX(oi.degToRad(this.initialCameraRotation.x)),this.camera.rotateY(oi.degToRad(this.initialCameraRotation.y)),this.camera.rotateZ(oi.degToRad(this.initialCameraRotation.z))}}setupRenderer(){if(!this.usingExternalRenderer){const e=new li;this.getRenderDimensions(e),this.renderer=new uu({antialias:!1,precision:"highp",canvas:this.canvas}),this.renderer.setPixelRatio(this.devicePixelRatio),this.renderer.autoClear=!0,this.renderer.setClearColor(this.backgroundColor,1),this.renderer.setSize(e.x,e.y),this.resizeObserver=new ResizeObserver(()=>{this.getRenderDimensions(e),this.renderer.setSize(e.x,e.y),this.forceRenderNextFrame()}),this.resizeObserver.observe(this.rootElement),this.rootElement.appendChild(this.renderer.domElement)}}setupControls(){if(this.useBuiltInControls){this.usingExternalCamera?this.camera.isOrthographicCamera?this.orthographicControls=new Bd(this.camera,this.renderer.domElement):this.perspectiveControls=new Bd(this.camera,this.renderer.domElement):(this.perspectiveControls=new Bd(this.perspectiveCamera,this.renderer.domElement),this.orthographicControls=new Bd(this.orthographicCamera,this.renderer.domElement));for(let e of[this.orthographicControls,this.perspectiveControls])e&&(e.listenToKeyEvents(window),e.rotateSpeed=.5,e.maxPolarAngle=.5*Math.PI,e.minPolarAngle=.5*Math.PI,e.minAzimuthAngle=-Math.PI/72,e.maxAzimuthAngle=Math.PI/72,e.enableDamping=!0,e.dampingFactor=.05,e.target.copy(this.initialCameraLookAt),e.update());this.controls=this.camera.isOrthographicCamera?this.orthographicControls:this.perspectiveControls,this.controls.update()}}setupEventHandlers(){this.useBuiltInControls&&(this.mouseMoveListener=this.onMouseMove.bind(this),this.renderer.domElement.addEventListener("pointermove",this.mouseMoveListener,!1),this.mouseDownListener=this.onMouseDown.bind(this),this.renderer.domElement.addEventListener("pointerdown",this.mouseDownListener,!1),this.mouseUpListener=this.onMouseUp.bind(this),this.renderer.domElement.addEventListener("pointerup",this.mouseUpListener,!1),this.keyDownListener=this.onKeyDown.bind(this))}removeEventHandlers(){this.useBuiltInControls&&(this.renderer.domElement.removeEventListener("pointermove",this.mouseMoveListener),this.mouseMoveListener=null,this.renderer.domElement.removeEventListener("pointerdown",this.mouseDownListener),this.mouseDownListener=null,this.renderer.domElement.removeEventListener("pointerup",this.mouseUpListener),this.mouseUpListener=null,window.removeEventListener("keydown",this.keyDownListener),this.keyDownListener=null)}setRenderMode(e){this.renderMode=e}setActiveSphericalHarmonicsDegrees(e){this.splatMesh.material.uniforms.sphericalHarmonicsDegree.value=e,this.splatMesh.material.uniformsNeedUpdate=!0}onSplatMeshChanged(e){this.onSplatMeshChangedCallback=e}onMouseMove(e){this.mousePosition.set(e.offsetX,e.offsetY)}onMouseDown(){this.mouseDownPosition.copy(this.mousePosition),this.mouseDownTime=wp()}onMouseClick(e){this.mousePosition.set(e.offsetX,e.offsetY),this.checkForFocalPointChange()}getRenderDimensions(e){this.rootElement?(e.x=this.rootElement.offsetWidth,e.y=this.rootElement.offsetHeight):this.renderer.getSize(e)}setOrthographicMode(t){if(t===this.camera.isOrthographicCamera)return;const n=this.camera,i=t?this.orthographicCamera:this.perspectiveCamera;if(i.position.copy(n.position),i.up.copy(n.up),i.rotation.copy(n.rotation),i.quaternion.copy(n.quaternion),i.matrix.copy(n.matrix),this.camera=i,this.controls){const r=e=>{e.saveState(),e.reset()},s=this.controls,a=t?this.orthographicControls:this.perspectiveControls;r(a),r(s),a.target.copy(s.target),t?e.setCameraZoomFromPosition(i,n,s):e.setCameraPositionFromZoom(i,n,a),this.controls=a,this.camera.lookAt(this.controls.target)}}adjustForWebXRStereo(e){if(this.camera&&this.webXRActive){const t=this.renderer.xr.getCamera().projectionMatrix.elements[0],n=this.camera.projectionMatrix.elements[0];e.x*=n/t}}isLoadingOrUnloading(){return Object.keys(this.splatSceneDownloadPromises).length>0||null!==this.splatSceneDownloadAndBuildPromise||null!==this.splatSceneRemovalPromise}isDisposingOrDisposed(){return this.disposing||this.disposed}addSplatSceneDownloadController(e){this.splatSceneDownloadControllers.push(e)}removeSplatSceneDownloadController(e){const t=this.splatSceneDownloadControllers.indexOf(e);t>-1&&this.splatSceneDownloadControllers.splice(t,1)}addSplatSceneDownloadPromise(e){this.splatSceneDownloadPromises[e.id]=e}removeSplatSceneDownloadPromise(e){delete this.splatSceneDownloadPromises[e.id]}setSplatSceneDownloadAndBuildPromise(e){this.splatSceneDownloadAndBuildPromise=e}clearSplatSceneDownloadAndBuildPromise(){this.splatSceneDownloadAndBuildPromise=null}addSplatScene(t,n={}){if(this.isLoadingOrUnloading())throw new Error("Cannot add splat scene while another load or unload is already in progress.");if(this.isDisposingOrDisposed())throw new Error("Cannot add splat scene after dispose() is called.");n.progressiveLoad&&this.splatMesh.scenes&&this.splatMesh.scenes.length>0&&(Pm.warn('addSplatScene(): "progressiveLoad" option ignore because there are multiple splat scenes'),n.progressiveLoad=!1);const i=void 0!==n.format&&null!==n.format?n.format:Zd(t),r=e.isProgressivelyLoadable(i)&&n.progressiveLoad,s=void 0===n.showLoadingUI||null===n.showLoadingUI||n.showLoadingUI;let a=null;s&&(this.loadingSpinner.removeAllTasks(),a=this.loadingSpinner.addTask("Downloading..."));const o=(e,t,n)=>{if(s)if(n===op)if(100==e)this.loadingSpinner.setMessageForTask(a,"Download complete!");else if(r)this.loadingSpinner.setMessageForTask(a,"Downloading splats...");else{const e=t?`: ${t}`:"...";this.loadingSpinner.setMessageForTask(a,`Downloading${e}`)}else n===lp&&(Pm.debug("loaderStatus === LoaderStatus.Processing"),this.loadingSpinner.setMessageForTask(a,"Processing splats..."))};let l=!1,c=0;const h=(e,t)=>{s&&((e&&r||t&&!r)&&(this.loadingSpinner.removeTask(a),t||l||this.loadingProgressBar.show()),r&&(t?(l=!0,this.loadingProgressBar.hide()):this.loadingProgressBar.setProgress(c)))};return(r?this.downloadAndBuildSingleSplatSceneProgressiveLoad.bind(this):this.downloadAndBuildSingleSplatSceneStandardLoad.bind(this))(t,i,n.splatAlphaRemovalThreshold,((e,t,i)=>{!r&&n.onProgress&&n.onProgress(0,"0%",lp);const a={rotation:n.rotation||n.orientation,position:n.position,scale:n.scale,splatAlphaRemovalThreshold:n.splatAlphaRemovalThreshold};return this.addSplatBuffers([e],[a],i,t&&s,s,r,r).then(()=>{!r&&n.onProgress&&n.onProgress(100,"100%",lp),h(t,i)})}).bind(this),(e,t,i)=>{c=e,o(e,t,i),n.onProgress&&n.onProgress(e,t,i)},(()=>{this.loadingProgressBar.hide(),this.loadingSpinner.removeAllTasks()}).bind(this),n.headers)}downloadAndBuildSingleSplatSceneStandardLoad(e,t,n,i,r,s,a){const o=this.downloadSplatSceneToSplatBuffer(e,n,r,!1,void 0,t,a),l=Rp(o.abort?o.abort.bind(o):void 0);return o.then(e=>(this.removeSplatSceneDownloadPromise(o),i(e,!0,!0).then(()=>{l.resolve(),this.clearSplatSceneDownloadAndBuildPromise()}))).catch(t=>{s&&s(),this.clearSplatSceneDownloadAndBuildPromise(),this.removeSplatSceneDownloadPromise(o);const n=t instanceof bp||"AbortError"===t.name?t:new Error(`Viewer::addSplatScene -> Could not load file ${e}`);l.reject(n)}),this.addSplatSceneDownloadPromise(o),this.setSplatSceneDownloadAndBuildPromise(l.promise),l.promise}downloadAndBuildSingleSplatSceneProgressiveLoad(e,t,n,i,r,s,a){let o=0,l=!1;const c=[],h=()=>{if(c.length>0&&!l&&!this.isDisposingOrDisposed()){l=!0;const e=c.shift();i(e.splatBuffer,e.firstBuild,e.finalBuild).then(()=>{l=!1,e.firstBuild?p.resolve():e.finalBuild&&(f.resolve(),this.clearSplatSceneDownloadAndBuildPromise()),c.length>0&&Ep(()=>h())})}},u=this.downloadSplatSceneToSplatBuffer(e,n,r,!0,(e,t)=>{this.isDisposingOrDisposed()||(t||0===c.length||e.getSplatCount()>c[0].splatBuffer.getSplatCount())&&(c.push({splatBuffer:e,firstBuild:0===o,finalBuild:t}),o++,h())},t,a),d=u.abort?u.abort.bind(u):void 0,p=Rp(d),f=Rp(d);return this.addSplatSceneDownloadPromise(u),this.setSplatSceneDownloadAndBuildPromise(f.promise),u.then(()=>{this.removeSplatSceneDownloadPromise(u)}).catch(e=>{Pm.error("Viewer::addSplatScene actual error:",e),this.clearSplatSceneDownloadAndBuildPromise(),this.removeSplatSceneDownloadPromise(u);const t=e instanceof bp||"AbortError"===e.name?e:new Error(`Viewer::addSplatScene -> Could not load one or more scenes: ${e.message}`);p.reject(t),s&&s(t)}),p.promise}addSplatScenes(e,t=!0,n=void 0){if(this.isLoadingOrUnloading())throw new Error("Cannot add splat scene while another load or unload is already in progress.");if(this.isDisposingOrDisposed())throw new Error("Cannot add splat scene after dispose() is called.");const i=e.length,r=[];let s;t&&(this.loadingSpinner.removeAllTasks(),s=this.loadingSpinner.addTask("Downloading..."));const a=(e,a,o,l)=>{r[e]=a;let c=0;for(let t=0;t<i;t++)c+=r[t]||0;c/=i,o=`${c.toFixed(2)}%`,t&&l===op&&this.loadingSpinner.setMessageForTask(s,100==c?"Download complete!":`Downloading: ${o}`),n&&n(c,o,l)},o=new AbortController,l=o.signal;this.addSplatSceneDownloadController(o);const c=[];for(let u=0;u<e.length;u++){const t=e[u],n=void 0!==t.format&&null!==t.format?t.format:Zd(t.path),i=this.downloadSplatSceneToSplatBuffer(t.path,t.splatAlphaRemovalThreshold,a.bind(this,u),!1,void 0,n,t.headers,l);c.push(i)}const h=Promise.all(c).then(i=>(t&&this.loadingSpinner.removeTask(s),n&&n(0,"0%",lp),this.addSplatBuffers(i,e,!0,t,t,!1,!1).then(()=>{n&&n(100,"100%",lp),this.clearSplatSceneDownloadAndBuildPromise()}))).catch(e=>{throw t&&this.loadingSpinner.removeTask(s),this.clearSplatSceneDownloadAndBuildPromise(),"AbortError"===e.name?e:new Error("Viewer::addSplatScenes -> Could not load one or more splat scenes.")}).finally(()=>{this.removeSplatSceneDownloadController(o)});return this.setSplatSceneDownloadAndBuildPromise(h),h}downloadSplatSceneToSplatBuffer(e,t=1,n=void 0,i=!1,r=void 0,s,a){const o=!i&&this.optimizeSplatData;try{if(s===Yd)return Am.loadFromURL(e,n,i,r,t,this.inMemoryCompressionLevel,o,this.sphericalHarmonicsDegree,a)}catch(l){throw l instanceof wf?new Error("File type or server does not support progressive loading."):l}throw new Error(`Viewer::downloadSplatSceneToSplatBuffer -> File format not supported: ${e}`)}static isProgressivelyLoadable(e){return e===Yd}async setupSortWorker(e){if(this.isDisposingOrDisposed())return;const t=this.integerBasedSort?Int32Array:Float32Array,n=e.getSplatCount(),i=e.getMaxSplatCount();return this.sortWorker=await function(e,t,n,i,r,s=np.DefaultSplatSortDistanceMapPrecision){const a=new Worker(URL.createObjectURL(new Blob(["(",Im.toString(),")(self)"],{type:"application/javascript"})));let o="AGFzbQEAAAAADwhkeWxpbmsuMAEEAAAAAAEbA2AAAGAQf39/f39/f39/f39/f39/fwBgAAF/AhIBA2VudgZtZW1vcnkCAwCAgAQDBAMAAQIHVAQRX193YXNtX2NhbGxfY3RvcnMAABhfX3dhc21fYXBwbHlfZGF0YV9yZWxvY3MAAAtzb3J0SW5kZXhlcwABE2Vtc2NyaXB0ZW5fdGxzX2luaXQAAgqWEAMDAAELihAEAXwDewN/A30gCyAKayEMAkACQCAOBEAgDQRAQfj///8HIQpBiICAgHghDSALIAxNDQMgDCEBA0AgAyABQQJ0IgVqIAIgACAFaigCAEECdGooAgAiBTYCACAFIAogBSAKSBshCiAFIA0gBSANShshDSABQQFqIgEgC0cNAAsMAwsgDwRAIAsgDE0NAkF/IQ9B+P///wchCkGIgICAeCENIAwhAgNAIA8gByAAIAJBAnQiFWooAgAiFkECdGooAgAiFEcEQAJ/IAX9CQI4IAggFEEGdGoiDv0JAgwgDioCHP0gASAOKgIs/SACIA4qAjz9IAP95gEgBf0JAiggDv0JAgggDioCGP0gASAOKgIo/SACIA4qAjj9IAP95gEgBf0JAgggDv0JAgAgDioCEP0gASAOKgIg/SACIA4qAjD9IAP95gEgBf0JAhggDv0JAgQgDioCFP0gASAOKgIk/SACIA4qAjT9IAP95gH95AH95AH95AEiEf1f/QwAAAAAAECPQAAAAAAAQI9AIhL98gEiE/0hASIQmUQAAAAAAADgQWMEQCAQqgwBC0GAgICAeAshDgJ/IBP9IQAiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgL/REgDv0cAQJ/IBEgEf0NCAkKCwwNDg8AAAAAAAAAAP1fIBL98gEiEf0hACIQmUQAAAAAAADgQWMEQCAQqgwBC0GAgICAeAv9HAICfyAR/SEBIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4C/0cAyESIBQhDwsgAyAVaiABIBZBBHRq/QAAACAS/bUBIhH9GwAgEf0bAWogEf0bAmogEf0bA2oiDjYCACAOIAogCiAOShshCiAOIA0gDSAOSBshDSACQQFqIgIgC0cNAAsMAwsCfyAFKgIIu/0UIAUqAhi7/SIB/QwAAAAAAECPQAAAAAAAQI9A/fIBIhH9IQEiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLIQ4CfyAR/SEAIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyECAn8gBSoCKLtEAAAAAABAj0CiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyEFQfj///8HIQpBiICAgHghDSALIAxNDQIgAv0RIA79HAEgBf0cAiESIAwhBQNAIAMgBUECdCICaiABIAAgAmooAgBBBHRq/QAAACAS/bUBIhH9GwAgEf0bAWogEf0bAmoiAjYCACACIAogAiAKSBshCiACIA0gAiANShshDSAFQQFqIgUgC0cNAAsMAgsgDQRAQfj///8HIQpBiICAgHghDSALIAxNDQIgDCEBA0AgAyABQQJ0IgVqAn8gAiAAIAVqKAIAQQJ0aioCALtEAAAAAAAAsECiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyIONgIAIAogDiAKIA5IGyEKIA0gDiANIA5KGyENIAFBAWoiASALRw0ACwwCCyAPRQRAIAsgDE0NASAFKgIoIRcgBSoCGCEYIAUqAgghGUH4////ByEKQYiAgIB4IQ0gDCEFA0ACfyAXIAEgACAFQQJ0IgdqKAIAQQR0aiICKgIIlCAZIAIqAgCUIBggAioCBJSSkrtEAAAAAAAAsECiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyEOIAMgB2ogDjYCACAKIA4gCiAOSBshCiANIA4gDSAOShshDSAFQQFqIgUgC0cNAAsMAgsgCyAMTQ0AQX8hD0H4////ByEKQYiAgIB4IQ0gDCECA0AgDyAHIAAgAkECdCIUaigCAEECdCIVaigCACIORwRAIAX9CQI4IAggDkEGdGoiD/0JAgwgDyoCHP0gASAPKgIs/SACIA8qAjz9IAP95gEgBf0JAiggD/0JAgggDyoCGP0gASAPKgIo/SACIA8qAjj9IAP95gEgBf0JAgggD/0JAgAgDyoCEP0gASAPKgIg/SACIA8qAjD9IAP95gEgBf0JAhggD/0JAgQgDyoCFP0gASAPKgIk/SACIA8qAjT9IAP95gH95AH95AH95AEhESAOIQ8LIAMgFGoCfyAR/R8DIAEgFUECdCIOQQxyaioCAJQgEf0fAiABIA5BCHJqKgIAlCAR/R8AIAEgDmoqAgCUIBH9HwEgASAOQQRyaioCAJSSkpK7RAAAAAAAALBAoiIQmUQAAAAAAADgQWMEQCAQqgwBC0GAgICAeAsiDjYCACAKIA4gCiAOSBshCiANIA4gDSAOShshDSACQQFqIgIgC0cNAAsMAQtBiICAgHghDUH4////ByEKCyALIAxLBEAgCUEBa7MgDbIgCrKTlSEXIAwhDQNAAn8gFyADIA1BAnRqIgEoAgAgCmuylCIYi0MAAABPXQRAIBioDAELQYCAgIB4CyEOIAEgDjYCACAEIA5BAnRqIgEgASgCAEEBajYCACANQQFqIg0gC0cNAAsLIAlBAk8EQCAEKAIAIQ1BASEKA0AgBCAKQQJ0aiIBIAEoAgAgDWoiDTYCACAKQQFqIgogCUcNAAsLIAxBAEoEQCAMIQoDQCAGIApBAWsiAUECdCICaiAAIAJqKAIANgIAIApBAUshAiABIQogAg0ACwsgCyAMSgRAIAshCgNAIAYgCyAEIAMgCkEBayIKQQJ0IgFqKAIAQQJ0aiICKAIAIgVrQQJ0aiAAIAFqKAIANgIAIAIgBUEBazYCACAKIAxKDQALCwsEAEEACw==";const l=Pp()?Dp():null;n||t?n?t||l&&l.major<=16&&l.minor<4&&(o="AGFzbQEAAAAADwhkeWxpbmsuMAEEAAAAAAEXAmAAAGAQf39/f39/f39/f39/f39/fwACDwEDZW52Bm1lbW9yeQIAAAMDAgABBz4DEV9fd2FzbV9jYWxsX2N0b3JzAAAYX193YXNtX2FwcGx5X2RhdGFfcmVsb2NzAAALc29ydEluZGV4ZXMAAQrrDwICAAvlDwQBfAN7B30DfyALIAprIQwCQAJAIA4EQCANBEBB+P///wchCkGIgICAeCENIAsgDE0NAyAMIQUDQCADIAVBAnQiAWogAiAAIAFqKAIAQQJ0aigCACIBNgIAIAEgCiABIApIGyEKIAEgDSABIA1KGyENIAVBAWoiBSALRw0ACwwDCyAPBEAgCyAMTQ0CQX8hD0H4////ByEKQYiAgIB4IQ0gDCECA0AgDyAHIAAgAkECdCIcaigCACIdQQJ0aigCACIbRwRAAn8gBf0JAjggCCAbQQZ0aiIO/QkCDCAOKgIc/SABIA4qAiz9IAIgDioCPP0gA/3mASAF/QkCKCAO/QkCCCAOKgIY/SABIA4qAij9IAIgDioCOP0gA/3mASAF/QkCCCAO/QkCACAOKgIQ/SABIA4qAiD9IAIgDioCMP0gA/3mASAF/QkCGCAO/QkCBCAOKgIU/SABIA4qAiT9IAIgDioCNP0gA/3mAf3kAf3kAf3kASIR/V/9DAAAAAAAQI9AAAAAAABAj0AiEv3yASIT/SEBIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyEOAn8gE/0hACIQmUQAAAAAAADgQWMEQCAQqgwBC0GAgICAeAv9ESAO/RwBAn8gESAR/Q0ICQoLDA0ODwABAgMAAQID/V8gEv3yASIR/SEAIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4C/0cAgJ/IBH9IQEiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgL/RwDIRIgGyEPCyADIBxqIAEgHUEEdGr9AAAAIBL9tQEiEf0bACAR/RsBaiAR/RsCaiAR/RsDaiIONgIAIA4gCiAKIA5KGyEKIA4gDSANIA5IGyENIAJBAWoiAiALRw0ACwwDCwJ/IAUqAgi7/RQgBSoCGLv9IgH9DAAAAAAAQI9AAAAAAABAj0D98gEiEf0hASIQmUQAAAAAAADgQWMEQCAQqgwBC0GAgICAeAshDgJ/IBH9IQAiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLAn8gBSoCKLtEAAAAAABAj0CiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyEFQfj///8HIQpBiICAgHghDSALIAxNDQL9ESAO/RwBIAX9HAIhEiAMIQUDQCADIAVBAnQiAmogASAAIAJqKAIAQQR0av0AAAAgEv21ASIR/RsAIBH9GwFqIBH9GwJqIgI2AgAgAiAKIAIgCkgbIQogAiANIAIgDUobIQ0gBUEBaiIFIAtHDQALDAILIA0EQEH4////ByEKQYiAgIB4IQ0gCyAMTQ0CIAwhBQNAIAMgBUECdCIBagJ/IAIgACABaigCAEECdGoqAgC7RAAAAAAAALBAoiIQmUQAAAAAAADgQWMEQCAQqgwBC0GAgICAeAsiDjYCACAKIA4gCiAOSBshCiANIA4gDSAOShshDSAFQQFqIgUgC0cNAAsMAgsgD0UEQCALIAxNDQEgBSoCKCEUIAUqAhghFSAFKgIIIRZB+P///wchCkGIgICAeCENIAwhBQNAAn8gFCABIAAgBUECdCIHaigCAEEEdGoiAioCCJQgFiACKgIAlCAVIAIqAgSUkpK7RAAAAAAAALBAoiIQmUQAAAAAAADgQWMEQCAQqgwBC0GAgICAeAshDiADIAdqIA42AgAgCiAOIAogDkgbIQogDSAOIA0gDkobIQ0gBUEBaiIFIAtHDQALDAILIAsgDE0NAEF/IQ9B+P///wchCkGIgICAeCENIAwhAgNAIA8gByAAIAJBAnQiG2ooAgBBAnQiHGooAgAiDkcEQCAFKgI4IhQgCCAOQQZ0aiIPKgI8lCAFKgIoIhUgDyoCOJQgBSoCCCIWIA8qAjCUIAUqAhgiFyAPKgI0lJKSkiEYIBQgDyoCLJQgFSAPKgIolCAWIA8qAiCUIBcgDyoCJJSSkpIhGSAUIA8qAhyUIBUgDyoCGJQgFiAPKgIQlCAXIA8qAhSUkpKSIRogFCAPKgIMlCAVIA8qAgiUIBYgDyoCAJQgFyAPKgIElJKSkiEUIA4hDwsgAyAbagJ/IBggASAcQQJ0aiIOKgIMlCAZIA4qAgiUIBQgDioCAJQgGiAOKgIElJKSkrtEAAAAAAAAsECiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyIONgIAIAogDiAKIA5IGyEKIA0gDiANIA5KGyENIAJBAWoiAiALRw0ACwwBC0GIgICAeCENQfj///8HIQoLIAsgDEsEQCAJQQFrsyANsiAKspOVIRQgDCENA0ACfyAUIAMgDUECdGoiASgCACAKa7KUIhWLQwAAAE9dBEAgFagMAQtBgICAgHgLIQ4gASAONgIAIAQgDkECdGoiASABKAIAQQFqNgIAIA1BAWoiDSALRw0ACwsgCUECTwRAIAQoAgAhDUEBIQoDQCAEIApBAnRqIgEgASgCACANaiINNgIAIApBAWoiCiAJRw0ACwsgDEEASgRAIAwhCgNAIAYgCkEBayIBQQJ0IgJqIAAgAmooAgA2AgAgCkEBSyABIQoNAAsLIAsgDEoEQCALIQoDQCAGIAsgBCADIApBAWsiCkECdCIBaigCAEECdGoiAigCACIFa0ECdGogACABaigCADYCACACIAVBAWs2AgAgCiAMSg0ACwsL"):o=Rm:(o=Rm,l&&l.major<=16&&l.minor<4&&(o="AGFzbQEAAAAADwhkeWxpbmsuMAEEAAAAAAEXAmAAAGAQf39/f39/f39/f39/f39/fwACDwEDZW52Bm1lbW9yeQIAAAMDAgABBz4DEV9fd2FzbV9jYWxsX2N0b3JzAAAYX193YXNtX2FwcGx5X2RhdGFfcmVsb2NzAAALc29ydEluZGV4ZXMAAQqiDwICAAucDwMBfAd9Bn8gCyAKayEMAkACQCAOBEAgDQRAQfj///8HIQpBiICAgHghDSALIAxNDQMgDCEFA0AgAyAFQQJ0IgFqIAIgACABaigCAEECdGooAgAiATYCACABIAogASAKSBshCiABIA0gASANShshDSAFQQFqIgUgC0cNAAsMAwsgDwRAIAsgDE0NAkF/IQ9B+P///wchCkGIgICAeCENIAwhAgNAIA8gByAAIAJBAnQiGmooAgBBAnQiG2ooAgAiDkcEQAJ/IAUqAjgiESAIIA5BBnRqIg8qAjyUIAUqAigiEiAPKgI4lCAFKgIIIhMgDyoCMJQgBSoCGCIUIA8qAjSUkpKSu0QAAAAAAECPQKIiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLIRgCfyARIA8qAiyUIBIgDyoCKJQgEyAPKgIglCAUIA8qAiSUkpKSu0QAAAAAAECPQKIiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLIRkCfyARIA8qAhyUIBIgDyoCGJQgEyAPKgIQlCAUIA8qAhSUkpKSu0QAAAAAAECPQKIiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLIRwCfyARIA8qAgyUIBIgDyoCCJQgEyAPKgIAlCAUIA8qAgSUkpKSu0QAAAAAAECPQKIiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLIR0gDiEPCyADIBpqIAEgG0ECdGoiDigCBCAcbCAOKAIAIB1saiAOKAIIIBlsaiAOKAIMIBhsaiIONgIAIA4gCiAKIA5KGyEKIA4gDSANIA5IGyENIAJBAWoiAiALRw0ACwwDCwJ/IAUqAii7RAAAAAAAQI9AoiIQmUQAAAAAAADgQWMEQCAQqgwBC0GAgICAeAshAgJ/IAUqAhi7RAAAAAAAQI9AoiIQmUQAAAAAAADgQWMEQCAQqgwBC0GAgICAeAshByALIAxNAn8gBSoCCLtEAAAAAABAj0CiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyEPQfj///8HIQpBiICAgHghDQ0CIAwhBQNAIAMgBUECdCIIaiABIAAgCGooAgBBBHRqIggoAgQgB2wgCCgCACAPbGogCCgCCCACbGoiCDYCACAIIAogCCAKSBshCiAIIA0gCCANShshDSAFQQFqIgUgC0cNAAsMAgsgDQRAQfj///8HIQpBiICAgHghDSALIAxNDQIgDCEFA0AgAyAFQQJ0IgFqAn8gAiAAIAFqKAIAQQJ0aioCALtEAAAAAAAAsECiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyIONgIAIAogDiAKIA5IGyEKIA0gDiANIA5KGyENIAVBAWoiBSALRw0ACwwCCyAPRQRAIAsgDE0NASAFKgIoIREgBSoCGCESIAUqAgghE0H4////ByEKQYiAgIB4IQ0gDCEFA0ACfyARIAEgACAFQQJ0IgdqKAIAQQR0aiICKgIIlCATIAIqAgCUIBIgAioCBJSSkrtEAAAAAAAAsECiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyEOIAMgB2ogDjYCACAKIA4gCiAOSBshCiANIA4gDSAOShshDSAFQQFqIgUgC0cNAAsMAgsgCyAMTQ0AQX8hD0H4////ByEKQYiAgIB4IQ0gDCECA0AgDyAHIAAgAkECdCIYaigCAEECdCIZaigCACIORwRAIAUqAjgiESAIIA5BBnRqIg8qAjyUIAUqAigiEiAPKgI4lCAFKgIIIhMgDyoCMJQgBSoCGCIUIA8qAjSUkpKSIRUgESAPKgIslCASIA8qAiiUIBMgDyoCIJQgFCAPKgIklJKSkiEWIBEgDyoCHJQgEiAPKgIYlCATIA8qAhCUIBQgDyoCFJSSkpIhFyARIA8qAgyUIBIgDyoCCJQgEyAPKgIAlCAUIA8qAgSUkpKSIREgDiEPCyADIBhqAn8gFSABIBlBAnRqIg4qAgyUIBYgDioCCJQgESAOKgIAlCAXIA4qAgSUkpKSu0QAAAAAAACwQKIiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLIg42AgAgCiAOIAogDkgbIQogDSAOIA0gDkobIQ0gAkEBaiICIAtHDQALDAELQYiAgIB4IQ1B+P///wchCgsgCyAMSwRAIAlBAWuzIA2yIAqyk5UhESAMIQ0DQAJ/IBEgAyANQQJ0aiIBKAIAIAprspQiEotDAAAAT10EQCASqAwBC0GAgICAeAshDiABIA42AgAgBCAOQQJ0aiIBIAEoAgBBAWo2AgAgDUEBaiINIAtHDQALCyAJQQJPBEAgBCgCACENQQEhCgNAIAQgCkECdGoiASABKAIAIA1qIg02AgAgCkEBaiIKIAlHDQALCyAMQQBKBEAgDCEKA0AgBiAKQQFrIgFBAnQiAmogACACaigCADYCACAKQQFLIAEhCg0ACwsgCyAMSgRAIAshCgNAIAYgCyAEIAMgCkEBayIKQQJ0IgFqKAIAQQJ0aiICKAIAIgVrQQJ0aiAAIAFqKAIANgIAIAIgBUEBazYCACAKIAxKDQALCws="));const c=atob(o),h=new Uint8Array(c.length);for(let u=0;u<c.length;u++)h[u]=c.charCodeAt(u);return a.postMessage({init:{sorterWasmBytes:h.buffer,splatCount:e,useSharedMemory:t,integerBasedSort:i,dynamicMode:r,distanceMapRange:1<<s,Constants:{BytesPerFloat:np.BytesPerFloat,BytesPerInt:np.BytesPerInt,MemoryPageSize:np.MemoryPageSize,MaxScenes:np.MaxScenes}}}),a}(i,this.sharedMemoryForWorkers,this.enableSIMDInSort,this.integerBasedSort,this.splatMesh.dynamicMode,this.splatSortDistanceMapPrecision),new Promise(e=>{this.sortWorker.onmessage=r=>{if(r.data.sortDone){if(this.sortRunning=!1,Array.from({length:this.gaussianSplatCount},(e,t)=>t),this.sharedMemoryForWorkers)this.splatMesh.updateRenderIndexes(this.sortWorkerSortedIndexes,r.data.splatRenderCount);else{const e=new Uint32Array(r.data.sortedIndexes.buffer,0,r.data.splatRenderCount);this.splatMesh.updateRenderIndexes(e,r.data.splatRenderCount)}this.lastSplatSortCount=this.splatSortCount,this.lastSortTime=r.data.sortTime,this.sortPromiseResolver(),this.sortPromiseResolver=null,this.forceRenderNextFrame(),this.runAfterNextSort.length>0&&(this.runAfterNextSort.forEach(e=>{e()}),this.runAfterNextSort.length=0)}else if(r.data.sortCanceled)this.sortRunning=!1;else if(r.data.sortSetupPhase1Complete){this.logLevel>=qd&&Pm.info("Sorting web worker WASM setup complete."),this.sharedMemoryForWorkers?(this.sortWorkerSortedIndexes=new Uint32Array(r.data.sortedIndexesBuffer,r.data.sortedIndexesOffset,i),this.sortWorkerIndexesToSort=new Uint32Array(r.data.indexesToSortBuffer,r.data.indexesToSortOffset,i),this.sortWorkerPrecomputedDistances=new t(r.data.precomputedDistancesBuffer,r.data.precomputedDistancesOffset,i),this.sortWorkerTransforms=new Float32Array(r.data.transformsBuffer,r.data.transformsOffset,16*np.MaxScenes)):(this.sortWorkerIndexesToSort=new Uint32Array(i),this.sortWorkerPrecomputedDistances=new t(i),this.sortWorkerTransforms=new Float32Array(16*np.MaxScenes));for(let e=0;e<n;e++)this.sortWorkerIndexesToSort[e]=e;if(this.sortWorker.maxSplatCount=i,this.logLevel>=qd){Pm.info("Sorting web worker ready.");const e=this.splatMesh.getSplatDataTextures(),t=e.covariances.size,n=e.centerColors.size;Pm.info("Covariances texture size: "+t.x+" x "+t.y),Pm.info("Centers/colors texture size: "+n.x+" x "+n.y)}e()}}})}disposeSortWorker(){this.sortWorker&&this.sortWorker.terminate(),this.sortWorker=null,this.sortPromise=null,this.sortPromiseResolver&&(this.sortPromiseResolver(),this.sortPromiseResolver=null),this.preSortMessages=[],this.sortRunning=!1}removeSplatScene(e,t=!0){return this.removeSplatScenes([e],t)}removeSplatScenes(e,t=!0){if(this.isLoadingOrUnloading())throw new Error("Cannot remove splat scene while another load or unload is already in progress.");if(this.isDisposingOrDisposed())throw new Error("Cannot remove splat scene after dispose() is called.");let n;return this.splatSceneRemovalPromise=new Promise((i,r)=>{let s;t&&(this.loadingSpinner.removeAllTasks(),this.loadingSpinner.show(),s=this.loadingSpinner.addTask("Removing splat scene..."));const a=()=>{t&&(this.loadingSpinner.hide(),this.loadingSpinner.removeTask(s))},o=e=>{a(),this.splatSceneRemovalPromise=null,e?r(e):i()},l=()=>!!this.isDisposingOrDisposed()&&(o(),!0);n=this.sortPromise||Promise.resolve(),n.then(()=>{if(l())return;const t=[],i=[],r=[];for(let n=0;n<this.splatMesh.scenes.length;n++){let s=!1;for(let t of e)if(t===n){s=!0;break}if(!s){const e=this.splatMesh.scenes[n];t.push(e.splatBuffer),i.push(this.splatMesh.sceneOptions[n]),r.push({position:e.position.clone(),quaternion:e.quaternion.clone(),scale:e.scale.clone()})}}this.disposeSortWorker(),this.splatMesh.dispose(),this.sceneRevealMode=$d,this.createSplatMesh(),this.addSplatBuffers(t,i,!0,!1,!0).then(()=>{l()||(a(),this.splatMesh.scenes.forEach((e,t)=>{e.position.copy(r[t].position),e.quaternion.copy(r[t].quaternion),e.scale.copy(r[t].scale)}),this.splatMesh.updateTransforms(),this.splatRenderReady=!1,this.runSplatSort(!0).then(()=>{l()?this.splatRenderReady=!0:(n=this.sortPromise||Promise.resolve(),n.then(()=>{this.splatRenderReady=!0,o()}))}))}).catch(e=>{o(e)})})}),this.splatSceneRemovalPromise}start(){if(!this.selfDrivenMode)throw new Error("Cannot start viewer unless it is in self driven mode.");this.requestFrameId=requestAnimationFrame(this.selfDrivenUpdateFunc),this.selfDrivenModeRunning=!0}stop(){this.selfDrivenMode&&this.selfDrivenModeRunning&&(cancelAnimationFrame(this.requestFrameId),this.selfDrivenModeRunning=!1)}async dispose(){if(this.isDisposingOrDisposed())return this.disposePromise;for(let t of this.splatSceneDownloadControllers)t.abort();let e=[];return this.sortPromise&&e.push(this.sortPromise),this.disposing=!0,this.disposePromise=Promise.all(e).finally(()=>{this.stop(),this.orthographicControls&&(this.orthographicControls.dispose(),this.orthographicControls=null),this.perspectiveControls&&(this.perspectiveControls.dispose(),this.perspectiveControls=null),this.controls=null,this.splatMesh&&(this.splatMesh.dispose(),this.splatMesh=null),this.avatarMesh&&(Tp(this.avatarMesh),this.avatarMesh=null),this.sceneHelper&&(this.sceneHelper.dispose(),this.sceneHelper=null),this.resizeObserver&&(this.resizeObserver.unobserve(this.rootElement),this.resizeObserver=null),this.disposeSortWorker(),this.removeEventHandlers(),this.loadingSpinner.removeAllTasks(),this.loadingSpinner.setContainer(null),this.loadingProgressBar.hide(),this.loadingProgressBar.setContainer(null),this.camera=null,this.threeScene=null,this.splatRenderReady=!1,this.initialized=!1,this.renderer&&(this.usingExternalRenderer||(this.rootElement.removeChild(this.renderer.domElement),this.renderer.dispose()),this.renderer=null),this.usingExternalRenderer,this.sortWorkerSortedIndexes=null,this.sortWorkerIndexesToSort=null,this.sortWorkerPrecomputedDistances=null,this.sortWorkerTransforms=null,this.disposed=!0,this.disposing=!1,this.disposePromise=null}),this.disposePromise}selfDrivenUpdate(){this.selfDrivenMode&&(this.requestFrameId=requestAnimationFrame(this.selfDrivenUpdateFunc)),this.vsyncCount++,this.vsyncCount<this.vsyncNum||(this.vsyncCount=0,this.update(),this.shouldRender()?(this.render(),this.consecutiveRenderFrames++):this.consecutiveRenderFrames=0,this.renderNextFrame=!1)}forceRenderNextFrame(){this.renderNextFrame=!0}update(t,n){const i=document.getElementById("fps");i&&(i.textContent=`FPS: ${this.currentFPS}`),this.frame>=this.totalFrames&&(this.frame=0),this.dropInMode&&this.updateForDropInMode(t,n),this.initialized&&this.splatRenderReady&&!this.isDisposingOrDisposed()&&(this.controls&&(this.controls.update(),this.camera.isOrthographicCamera&&!this.usingExternalCamera&&e.setCameraPositionFromZoom(this.camera,this.camera,this.controls)),this.runMorphUpdate(),this.runSplatSort(!0,!0),this.updateForRendererSizeChanges(),this.updateSplatMesh(),this.updateMeshCursor(),this.updateFPS(),this.timingSensitiveUpdates(),this.updateControlPlane())}updateForDropInMode(e,t){this.renderer=e,this.splatMesh&&this.splatMesh.setRenderer(this.renderer),this.camera=t,this.controls&&(this.controls.object=t),this.init()}updateControlPlane(){this.showControlPlane?(this.sceneHelper.setControlPlaneVisibility(!0),this.sceneHelper.positionAndOrientControlPlane(this.controls.target,this.camera.up)):this.sceneHelper.setControlPlaneVisibility(!1)}getSplatMesh(){return this.splatMesh}getSplatScene(e){return this.splatMesh.getScene(e)}getSceneCount(){return this.splatMesh.getSceneCount()}isMobile(){return navigator.userAgent.includes("Mobi")}updateMorphTarget(e){this.avatarMesh=e,this.splatMesh.flameModel=e,this.runMorphUpdate(),this.splatMesh.gaussianSplatCount=this.gaussianSplatCount}runMorphUpdate(){this.gaussianSplatCount=this.avatarMesh.geometry.attributes.position.count;var e=new Float32Array(this.avatarMesh.geometry.attributes.position.array);if(this.splatMesh.bonesNum=5,this.skinModel.skeleton.update(),this.boneRoot.updateMatrixWorld(!0),this.splatMesh.geometry.getAttribute("splatIndex")&&!1===this.setSkinAttibutes){this.setSkinAttibutes=!0;const e=this.splatMesh.geometry,t=this.skinModel.geometry.attributes.skinIndex,n=this.skinModel.geometry.attributes.skinWeight,i=new va(new t.array.constructor(t.array),4,t.normalized,1),r=new va(new n.array.constructor(n.array),4,n.normalized,1);i.setUsage(Nn),r.setUsage(Nn),e.setAttribute("skinIndex",i),e.setAttribute("skinWeight",r)}this.splatMesh.morphedMesh=e;let t=this.splatMesh.morphedMesh.length/3;null!=this.splatMesh.splatDataTextures.flameModel&&this.splatMesh.updateTetureAfterBSAndSkeleton(0,t-1,!1)}};i(Fm,"setCameraPositionFromZoom",function(){const e=new hi;return function(t,n,i){const r=1/(.001*n.zoom);e.copy(i.target).sub(t.position).normalize().multiplyScalar(r).negate(),t.position.copy(i.target).add(e)}}()),i(Fm,"setCameraZoomFromPosition",function(){const e=new hi;return function(t,n,i){const r=e.copy(i.target).sub(n.position).length();t.zoom=1/(.001*r)}}());let Um=Fm;const km=Sp("GaussianSplatRenderer"),Nm="ffffff",Om={offset:{},scale:{}},zm={hello:{size:2,isGroup:!1},idle:{size:1,isGroup:!1},listen:{size:0,isGroup:!1},speak:{size:6,isGroup:!1},think:{size:3,isGroup:!0},other:[]};class Hm{static async create(e,t,n={}){try{(function(e,t){if("undefined"!=typeof HTMLElement&&!(e instanceof HTMLElement))throw new up(`${t} must be a valid HTML element`,t)})(e,"container"),Wp(t),n.downloadProgress&&jp(n.downloadProgress,"options.downloadProgress",!1),n.loadProgress&&jp(n.loadProgress,"options.loadProgress",!1),n.getChatState&&jp(n.getChatState,"options.getChatState",!1),n.getExpressionData&&jp(n.getExpressionData,"options.getExpressionData",!1),n.backgroundColor&&function(e,t){if("string"!=typeof e)throw new up(`${t} must be a string`,t);if(!/^(#|0x)[0-9A-Fa-f]{6}$/i.test(e))throw new up(`${t} must be a valid hex color (e.g., #FFFFFF or 0xFFFFFF)`,t)}(n.backgroundColor,"options.backgroundColor"),km.info("Initializing GaussianSplatRenderer",{assetPath:t});const r=t;let s,a,o,l;try{const e=new URL(r,"undefined"!=typeof window?window.location.href:void 0).pathname.match(/\/([^/]+?)\.zip/);if(s=e?.[1],!s)throw new up("Character model name could not be extracted from path. Expected format: /path/name.zip","assetPath")}catch(i){if(i instanceof up)throw i;throw new up(`Invalid asset path format: ${i.message}`,"assetPath",i)}"undefined"!=typeof NProgress&&NProgress.start(),km.info("Downloading asset ZIP",{path:r});try{if(a=await fetch(r),!a.ok)throw new dp(`Failed to download asset: ${a.statusText}`,a.status)}catch(i){if(i instanceof dp)throw i;throw new dp(`Network error downloading asset: ${i.message}`,0,i)}if(n.downloadProgress)try{n.downloadProgress(1)}catch(i){km.warn("Error in downloadProgress callback",i)}if(n.loadProgress)try{n.loadProgress(.1)}catch(i){km.warn("Error in loadProgress callback",i)}"undefined"!=typeof NProgress&&NProgress.done();try{o=await a.arrayBuffer()}catch(i){throw new dp(`Failed to read response data: ${i.message}`,0,i)}km.debug("Unpacking ZIP archive");try{l=await md.loadAsync(o)}catch(i){throw new pp(`Failed to unpack ZIP archive: ${i.message}`,r,i)}let c="";if(Object.values(l.files).forEach(e=>{e.dir&&(c=e.name?.slice(0,e.name?.length-1))}),!c)throw new pp("No folder found in ZIP archive. Expected ZIP to contain a folder with model files.",r);km.debug("Found model folder in ZIP",{fileName:c}),km.debug("Creating GaussianSplatRenderer instance");const h=new Hm(e,l),u=qp.set(0,1.8,1),d=new hi(-10,0,0);km.debug("Camera setup",{position:{x:u.x,y:u.y,z:u.z},rotation:{x:d.x,y:d.y,z:d.z}});let p,f=16777215;try{if(Nm){const e=parseInt(Nm,16);isNaN(e)?km.warn("Invalid backgroundColor in config, using default",{value:Nm}):f=e}n?.backgroundColor&&(h.isHexColorStrict(n.backgroundColor)?f=parseInt(n.backgroundColor,16):km.warn("Invalid backgroundColor option, using config value",{value:n.backgroundColor}))}catch(i){km.warn("Error parsing backgroundColor, using default",i)}km.debug("Background color set",{backgroundColor:f.toString(16)}),h.getChatState=n?.getChatState,h.getExpressionData=n?.getExpressionData,km.debug("Creating Viewer instance");try{h.viewer=new Um({rootElement:e,threejsCanvas:h._canvas,cameraUp:[0,1,0],initialCameraPosition:[u.x,u.y,u.z],initialCameraRotation:[d.x,d.y,d.z],sphericalHarmonicsDegree:0,backgroundColor:f})}catch(i){throw new mp(`Failed to create Viewer instance: ${i.message}`,i)}km.info("Loading model",{fileName:c});try{await h.loadModel(c,zm,Om)}catch(i){throw new pp(`Failed to load model: ${i.message}`,c,i)}if(n.loadProgress)try{n.loadProgress(.2)}catch(i){km.warn("Error in loadProgress callback",i)}km.debug("Loading offset PLY file");try{p=await h.unpackFileAsBlob(c+"/offset.ply")}catch(i){throw new pp(`Failed to load offset.ply: ${i.message}`,c+"/offset.ply",i)}km.debug("Checking for iris_occlusion.json");let m=null;try{m=await h._loadJsonFromZip(c+"/iris_occlusion.json"),m?(km.info("Iris occlusion configuration loaded",{rightIrisRanges:m.right_iris?.length??0,leftIrisRanges:m.left_iris?.length??0}),h.irisOcclusionConfig=m,h.viewer.irisOcclusionConfig=m):km.debug("No iris_occlusion.json found, iris occlusion will be disabled")}catch(i){km.warn("Failed to load iris_occlusion.json, continuing without it",{error:i.message}),h.irisOcclusionConfig=null}if(n.loadProgress)try{n.loadProgress(.3)}catch(i){km.warn("Error in loadProgress callback",i)}km.debug("Adding splat scene");try{await h.viewer.addSplatScene(p,{progressiveLoad:!0,sharedMemoryForWorkers:!1,showLoadingUI:!1,format:Yd})}catch(i){throw new mp(`Failed to add splat scene: ${i.message}`,i)}try{h.render()}catch(i){km.error("Error in initial render",i)}if(n.loadProgress)try{n.loadProgress(1)}catch(i){km.warn("Error in loadProgress callback",i)}return km.info("GaussianSplatRenderer initialized successfully"),h}catch(i){if(i instanceof up||i instanceof dp||i instanceof pp||i instanceof mp)throw km.error("Initialization failed",{errorCode:i.code,message:i.message}),i;throw km.error("Unexpected error during initialization",i),new mp(`Unexpected error initializing GaussianSplatRenderer: ${i.message}`,i)}}static async getInstance(e,t,n={}){return km.warn("getInstance() is deprecated. Use create() instead. Each call creates a new instance."),this.create(e,t,n)}constructor(e,t){if(km.debug("GaussianSplatRenderer constructor called"),this._disposed=!1,this._blobUrlManager=new Kp,this.zipUrls={urls:new Map,zip:t},this.lastTime=0,this.startTime=0,this.expressionData={},this.chatState=Yp,this._canvas=null,"undefined"!=typeof document&&e){this._canvas=document.createElement("canvas");const{width:t,height:n}=e.getBoundingClientRect();this._canvas.style.visibility="visible",this._canvas.width=t,this._canvas.height=n,e.appendChild(this._canvas),km.debug("Canvas setup",{width:t,height:n})}this.clock=new il,this.startTime=performance.now()/1e3,this.viewer=null,this.mixer=null,this.animManager=null,this.model=null,this.irisOcclusionConfig=null,this.motioncfg=null,this.getChatState=null,this.getExpressionData=null,km.debug("GaussianSplatRenderer instance created")}_assertNotDisposed(){if(this._disposed)throw new fp("GaussianSplatRenderer has been disposed")}dispose(){if(this._disposed)km.warn("GaussianSplatRenderer.dispose() called on already disposed instance");else{km.info("Disposing GaussianSplatRenderer"),this._canvas&&(this._canvas.style.visibility="hidden",this._canvas.parentNode&&this._canvas.parentNode.removeChild(this._canvas),this._canvas=null),this.disposeModel();try{this._blobUrlManager?.dispose()}catch(e){km.error("Error disposing BlobUrlManager",e)}this.zipUrls?.urls&&(this.zipUrls.urls.forEach(e=>{try{URL.revokeObjectURL(e)}catch(t){km.warn("Error revoking blob URL",{url:e,error:t})}}),this.zipUrls.urls.clear()),this.viewer=null,this.mixer=null,this.animManager=null,this.model=null,this.motioncfg=null,this.getChatState=null,this.getExpressionData=null,this.zipUrls=null,this._disposed=!0,Hm.instance=void 0,km.debug("GaussianSplatRenderer disposed successfully")}}disposeModel(){if(km.debug("Disposing model resources"),this.mixer){try{this.mixer.stopAllAction(),this.viewer?.avatarMesh&&this.mixer.uncacheRoot(this.viewer.avatarMesh)}catch(e){km.error("Error disposing animation mixer",e)}this.mixer=null}if(this.animManager){try{this.animManager.dispose()}catch(e){km.error("Error disposing animation manager",e)}this.animManager=null}if(this.viewer){try{this.viewer.dispose()}catch(e){km.error("Error disposing viewer",e)}this.viewer=null}km.debug("Model resources disposed")}getCamera(){return this.viewer?.camera}updateBS(e){let t={browDownLeft:0,browDownRight:0,browInnerUp:0,browOuterUpLeft:0,browOuterUpRight:0,mouthCheekPuff:0,cheekSquintLeft:0,cheekSquintRight:0,eyeBlinkLeft:0,eyeBlinkRight:0,eyeLookDownLeft:0,eyeLookDownRight:0,eyeLookInLeft:0,eyeLookInRight:0,eyeLookOutLeft:0,eyeLookOutRight:0,eyeLookUpLeft:0,eyeLookUpRight:0,eyeSquintLeft:0,eyeSquintRight:0,eyeWideLeft:0,eyeWideRight:0,jawForward:0,jawLeft:0,jawOpen:0,jawRight:0,mouthClose:0,mouthDimpleLeft:0,mouthDimpleRight:0,mouthFrownLeft:0,mouthFrownRight:0,mouthFunnel:0,mouthLeft:0,mouthLowerDownLeft:0,mouthLowerDownRight:0,mouthPressLeft:0,mouthPressRight:0,mouthPucker:0,mouthRight:0,mouthRollLower:0,mouthRollUpper:0,mouthShrugLower:0,mouthShrugUpper:0,mouthSmileLeft:0,mouthSmileRight:0,mouthStretchLeft:0,mouthStretchRight:0,mouthUpperUpLeft:0,mouthUpperUpRight:0,noseSneerLeft:0,noseSneerRight:0,tongueOut:0};return null!=e&&(t=e),t}render(){if(!this.viewer||!this.viewer.selfDrivenMode)throw new Error("Cannot start viewer unless it is in self driven mode.");{this.viewer.requestFrameId=requestAnimationFrame(()=>this.render());const e=1/30,t=performance.now()/1e3,n=this.viewer.totalFrames||1,i=(t-this.startTime)%(n*e),r=Math.floor(i/e);if(this.viewer.frame=r,this.getChatState&&(this.chatState=this.getChatState(),this._lastLoggedState&&this._lastLoggedState===this.chatState||(km.debug("Chat state changed",{newState:this.chatState,hasAnimManager:!!this.animManager}),this._lastLoggedState=this.chatState),this.animManager?.update(this.chatState)),this.getExpressionData&&(this.expressionData=this.updateBS(this.getExpressionData())),this.mixer&&this.animManager){const e=this.clock.getDelta();if(this.mixer.update(e),this.motioncfg)for(const t in this.expressionData){const e=this.motioncfg.offset?.[t],n=this.motioncfg.scale?.[t];void 0!==e&&void 0!==n&&(this.expressionData[t]=this.expressionData[t]*n+e)}this.setExpression()}else this._warnedOnce||(km.warn("Mixer or animManager not initialized, skipping animation update",{hasMixer:!!this.mixer,hasAnimManager:!!this.animManager}),this._warnedOnce=!0),this.setExpression();this.viewer.update(this.viewer.renderer,this.viewer.camera);const s=this.viewer.shouldRender();this._renderLogCount<=3&&km.debug("shouldRender check",{shouldRender:s}),s?(this.viewer.render(),this.viewer.consecutiveRenderFrames++):this.viewer.consecutiveRenderFrames=0,this.viewer.renderNextFrame=!1,this.viewer.selfDrivenModeRunning=!0}}isHexColorStrict(e){return"string"==typeof e&&/^(#|0x)[0-9A-Fa-f]{6}$/i.test(e)}setExpression(){if(this.viewer?.splatMesh){this.viewer.splatMesh.bsWeight=this.expressionData;const e=this.viewer.splatMesh.material;if(e?.uniforms){const t=this.expressionData.eyeBlinkLeft||0,n=this.expressionData.eyeBlinkRight||0;e.uniforms.eyeBlinkLeft&&(e.uniforms.eyeBlinkLeft.value=t),e.uniforms.eyeBlinkRight&&(e.uniforms.eyeBlinkRight.value=n)}}this.model&&this.model.traverse(e=>{if(e.isMesh||e.isSkinnedMesh){const t=e.geometry?.morphAttributes;if(t&&Object.keys(t).length>0){const t=e.morphTargetDictionary;for(const n in t){const i=t[n],r=this.expressionData[n];void 0!==r&&(e.morphTargetInfluences[i]=Math.max(0,Math.min(1,r)))}}}})}async loadModel(e,t,n){const[i,r,s]=await Promise.all([this.unpackAndLoadGlb(e+"/skin.glb"),this.unpackAndLoadGlb(e+"/animation.glb"),this.unpackAndLoadJson(e+"/vertex_order.json")]);if(!this.viewer)throw new Error("render viewer is not initialized");let a,o;i.traverse(e=>{e.isSkinnedMesh&&(a=e),e instanceof pa&&"hip"===e.name&&(o=e)}),this.viewer.sortedIndexes=s,a&&(this.viewer.gaussianSplatCount=a.geometry.attributes.position.count),this.viewer.avatarMesh=i,this.viewer.skinModel=a,this.viewer.boneRoot=o,this.mixer=new fl(i),this.animManager=new cf(this.mixer,r,t),this.motioncfg=n,Array.isArray(r)&&r.length>0&&r[0].duration?this.viewer.totalFrames=Math.floor(30*r[0].duration):this.viewer.totalFrames=1,km.debug("Total frames calculated",{totalFrames:this.viewer.totalFrames}),a&&this.viewer.updateMorphTarget(a),this.viewer.threeScene.add(i),i.visible=!1,a&&a.skeleton.computeBoneTexture()}async unpackFileAsBlob(e){if(this._assertNotDisposed(),this.zipUrls.urls.has(e))return km.debug("Returning cached blob URL",{path:e}),this.zipUrls.urls.get(e);km.debug("Unpacking file from ZIP",{path:e});const t=this.zipUrls.zip?.file(e);if(!t)throw new pp(`File not found in ZIP archive: ${e}`,e);let n;try{n=await t.async("blob")}catch(s){throw new pp(`Failed to extract file from ZIP: ${s.message}`,e,s)}if(!n)throw new pp(`File extracted but blob is empty: ${e}`,e);const i=this._getMimeType(e),r=this._blobUrlManager.createBlobUrl(n,i,`zip:${e}`);return this.zipUrls.urls.set(e,r),km.debug("Blob URL created and cached",{path:e,url:r.substring(0,50)}),r}async _loadJsonFromZip(e){this._assertNotDisposed(),km.debug("Attempting to load JSON from ZIP",{path:e});const t=this.zipUrls.zip?.file(e);if(!t)return km.debug("JSON file not found in ZIP, returning null",{path:e}),null;let n;try{n=await t.async("text")}catch(i){throw new ParseError(`Failed to extract JSON file from ZIP: ${i.message}`,e,i)}try{const t=JSON.parse(n);return km.debug("JSON file loaded successfully",{path:e}),t}catch(i){throw new ParseError(`Failed to parse JSON file: ${i.message}`,e,i)}}async unpackAndLoadGlb(e){if(this._assertNotDisposed(),this.zipUrls.urls.has(e))return km.debug("Using cached GLB URL",{path:e}),this.LoadGLTF(this.zipUrls.urls.get(e));km.debug("Unpacking GLB from ZIP",{path:e});const t=this.zipUrls.zip?.file(e);if(!t)throw new pp(`GLB file not found in ZIP archive: ${e}`,e);let n;try{n=await t.async("arraybuffer")}catch(s){throw new pp(`Failed to extract GLB from ZIP: ${s.message}`,e,s)}if(!n)throw new pp(`GLB extracted but ArrayBuffer is empty: ${e}`,e);const i=new Blob([n],{type:"model/gltf-binary"}),r=this._blobUrlManager.createBlobUrl(i,"model/gltf-binary",`zip:${e}`);return this.zipUrls.urls.set(e,r),km.debug("GLB blob URL created and cached",{path:e}),this.LoadGLTF(r)}_getMimeType(e){const t=e.split(".").pop()?.toLowerCase();return{ply:"model/ply",glb:"model/gltf-binary",gltf:"model/gltf+json",json:"application/json",bin:"application/octet-stream",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg"}[t]||"application/octet-stream"}async unpackAndLoadJson(e){const t=this.zipUrls.zip?.file(e);if(!t)throw new Error(`File not found in ZIP: ${e}`);const n=await t.async("string");if(!n)throw new Error(`Failed to read file from ZIP: ${e}`);return JSON.parse(n)}async LoadGLTF(e){return new Promise((t,n)=>{(new pu).load(e,e=>{e.animations.length>0?t(e.animations):t(e.scene)},void 0,e=>{n(e)})})}}!function(){const e=new Float32Array(1),t=new Int32Array(e.buffer)}(),Sp("FlameAnimator");const Vm=_.scope("GaussianAvatar"),Gm=[[.1,.3,.7,1,.7,.3,.1],[.15,.4,.8,1,.6,.25,.1],[.1,.35,.75,1,.75,.35,.1],[.2,.5,.9,1,.7,.3,.05]],Wm={Idle:[2e3,4e3],Hello:[1800,3500],Responding:[1300,3300]};const jm=Object.freeze(Object.defineProperty({__proto__:null,GaussianAvatar:class{constructor(e,t){this._assetsPath="",this.curState="Idle",this.forceEyesClosed=!1,this.liveBlendshapeData=null,this.isPaused=!1,this.lastBlinkTime=0,this.nextBlinkInterval=2e3,this.blinkFrame=-1,this.currentBlinkPattern=Gm[0],this.blinkIntensity=1,this.lastBlinkFrameTime=0,this.startTime=0,this._avatarDivEle=e,this._assetsPath=t,this.neutralBlendshapes=W(),this._init()}_init(){if(!this._avatarDivEle||!this._assetsPath)throw new Error("Lack of necessary initialization parameters")}async start(){await this.render()}closeEyes(){this.forceEyesClosed=!0}async render(){this._renderer=await Hm.getInstance(this._avatarDivEle,this._assetsPath,{getChatState:this.getChatState.bind(this),getExpressionData:this.getArkitFaceFrame.bind(this),backgroundColor:"0xffffff"}),this.startTime=performance.now()/1e3,Vm.info("Avatar ready, initial state:",this.curState)}pause(){this.isPaused=!0,Vm.debug("Avatar paused")}resume(){this.isPaused=!1,Vm.debug("Avatar resumed")}getChatState(){return this.curState}setChatState(e){if(this.curState!==e){const t=(new Date).toLocaleTimeString();Vm.info(`[${t}] Avatar state: ${this.curState} → ${e}`),this.curState=e}}enableLiveBlendshapes(){Vm.debug("Live blendshapes mode active")}disableLiveBlendshapes(){this.liveBlendshapeData=null,Vm.debug("Live blendshapes cleared")}updateBlendshapes(e){this.liveBlendshapeData=e}getArkitFaceFrame(){if(this.isPaused)return this.neutralBlendshapes;let e;return e=this.liveBlendshapeData?{...this.liveBlendshapeData}:{...this.neutralBlendshapes},this.forceEyesClosed?(e.eyeBlinkLeft=1,e.eyeBlinkRight=1,e):(this.applyBlink(e),e)}applyBlink(e){const t=performance.now(),[n,i]=Wm[this.curState]||Wm.Idle;if(-1===this.blinkFrame&&t-this.lastBlinkTime>=this.nextBlinkInterval&&(this.blinkFrame=0,this.lastBlinkFrameTime=t,this.currentBlinkPattern=Gm[Math.floor(Math.random()*Gm.length)],this.blinkIntensity=.8+.2*Math.random(),this.nextBlinkInterval=n+Math.random()*(i-n)),this.blinkFrame>=0&&this.blinkFrame<7){const n=this.currentBlinkPattern[this.blinkFrame]*this.blinkIntensity;e.eyeBlinkLeft=n,e.eyeBlinkRight=n,t-this.lastBlinkFrameTime>=33&&(this.blinkFrame++,this.lastBlinkFrameTime=t,this.blinkFrame>=7&&(this.blinkFrame=-1,this.lastBlinkTime=t))}else e.eyeBlinkLeft=0,e.eyeBlinkRight=0}dispose(){this.liveBlendshapeData=null,Vm.debug("GaussianAvatar disposed")}}},Symbol.toStringTag,{value:"Module"}));e.AvatarChat=AvatarChat,e.default=AvatarChat,Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
2
+ //# sourceMappingURL=avatar-chat-widget.umd.js.map