@myned-ai/avatar-chat-widget 0.0.1

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),s="undefined"!=typeof document?document.currentScript:null;const r={auth:{enabled:!1},websocket:{url:void 0!=={url:"undefined"==typeof document&&"undefined"==typeof location?require("url").pathToFileURL(__filename).href:"undefined"==typeof document?location.href:s&&"SCRIPT"===s.tagName.toUpperCase()&&s.src||new URL("avatar-chat-widget.umd.cjs",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(r));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:s&&"SCRIPT"===s.tagName.toUpperCase()&&s.src||new URL("avatar-chat-widget.umd.cjs",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 v=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(()=>Vf);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),_.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=v.scope("EventEmitter");class A{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 S=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(s){console.error("Error in error handler:",s)}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),s=b[n];if(!s)throw new Error(`Unknown message type code: ${n}`);switch(n){case 130:return this.decodeAudioChunk(s,i,e);case 131:return this.decodeBlendshape(s,i,e);case 132:return this.decodeSyncFrame(s,i,e);default:return this.decodeGeneric(s,i,e)}}static encodeAudioInput(e,t){const n=5+t.byteLength,i=new ArrayBuffer(n),s=new DataView(i);s.setUint8(0,e),s.setUint32(1,Date.now(),!1);const r=new Uint8Array(i,5),a=new Uint8Array(t);return r.set(a),i}static encodeGeneric(e,t){const n=JSON.stringify(t),i=(new TextEncoder).encode(n),s=9+i.length,r=new ArrayBuffer(s),a=new DataView(r);a.setUint8(0,e),a.setUint32(1,Date.now(),!1),a.setUint32(5,i.length,!1);return new Uint8Array(r,9).set(i),r}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),s=new Float32Array(52);return s.set(i),{type:e,weights:Array.from(s),timestamp:t}}static decodeSyncFrame(e,t,n){const i=9+new DataView(n).getUint32(5,!1),s=n.slice(9,i),r=new Float32Array(n,i,52),a=new Float32Array(52);return a.set(r),{type:e,audio:s,weights:Array.from(a),timestamp:t}}static decodeGeneric(e,t,n){const i=new DataView(n).getUint32(5,!1),s=new Uint8Array(n,9,i),r=(new TextDecoder).decode(s);return{...JSON.parse(r),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=v.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 S.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=v.scope("SocketService");class R extends A{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,S.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 s;try{this.ws=new WebSocket(e),this.ws.binaryType="arraybuffer",s=window.setTimeout(()=>{"connecting"===this.connectionState&&(this.ws?.close(),i(new Error("Connection timeout")))},c.websocket.connectionTimeout),this.ws.onopen=()=>{void 0!==s&&clearTimeout(s),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!==s&&clearTimeout(s),this.setConnectionState("error"),S.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){S.handleError(t,"websocket")}}onError(e){C.error("WebSocket error:",e),S.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),s={...e,data:i};this.ws.send(JSON.stringify(s))}else this.ws.send(JSON.stringify(e))}catch(t){S.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=v.scope("AudioInput");class D{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 S.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 S.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:s,samples:r}=e.data.data;I.debug(`[Worklet ${t}] Audio input - min: ${n}, max: ${i}, avg: ${s}, samples: ${r}`)}},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,s=0;I.debug("Setting up onaudioprocess handler..."),this.scriptProcessor.onaudioprocess=e=>{s++;const t=e.inputBuffer.getChannelData(0);if(1===s||s%10==0){let e=0,n=0,i=0;for(let s=0;s<t.length;s++)t[s]>e&&(e=t[s]),t[s]<n&&(n=t[s]),i+=Math.abs(t[s]);const r=i/t.length;I.debug(`[${s}] Audio input - min: ${n.toFixed(4)}, max: ${e.toFixed(4)}, avg: ${r.toFixed(6)}, samples: ${t.length}`)}for(let s=0;s<t.length;s++)i++,i>=n&&(i-=n,this.resampleBuffer.push(t[s]));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=>{S.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 S.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){S.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){S.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){S.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 P{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=v.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 U=v.scope("AudioContextManager"),F=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"}),U.info(`AudioContext created: sampleRate=${this._context.sampleRate}, state=${this._context.state}`),this.setupResumeListener(),this._context.onstatechange=()=>{U.debug(`AudioContext state changed: ${this._context?.state}`)}}catch(t){throw S.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,U.debug("Audio resume listeners added")}async resume(){if(this._context&&"running"!==this._context.state)return this._resumePromise||(this._resumePromise=this._context.resume().then(()=>{U.info("AudioContext resumed successfully")}).catch(e=>{U.error("Failed to resume AudioContext:",e),S.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(),U.debug("AudioContext suspended")}catch(e){U.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(),U.info("AudioContext closed")}catch(e){U.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}};F._instance=null;const k=F.getInstance(),N=v.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 P(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 s=this.audioContext.createBufferSource();s.buffer=n,s.connect(this.audioContext.destination),this.activeSourceNodes.add(s);const r=Math.max(this.nextPlayTime,this.audioContext.currentTime);s.start(r),this.currentSourceNode=s,this.nextPlayTime=r+n.duration,s.onended=()=>{this.activeSourceNodes.delete(s),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=v.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=v.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 P(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 s=this.speechEnded&&0===this.buffer.size;return j(this.currentFrame.weights,n.weights),n.status="SPEAKING",n.endOfSpeech=s,this.lastResult=n,n}getFrameWeights(e){return this.getFrame(e).weights}interpolateFrames(e,t,n){const i={};for(const s of G){const r=e.weights[s]??0,a=t.weights[s]??0;i[s]=r+(a-r)*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=v.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 s=1/32768;for(let h=0;h<n;h++)i[h]=t[h]*s;const r=this.audioContext.createBuffer(1,n,this.sampleRate);r.getChannelData(0).set(i);const a=this.audioContext.createBufferSource();a.buffer=r,a.connect(this.audioContext.destination);const o=Math.max(this.nextPlayTime,this.audioContext.currentTime);a.start(o),this.activeSourceNodes.add(a);const l=r.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=v.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=v.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 D,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){S.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){S.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 s=0;s<n;s++)i[s]=t.charCodeAt(s);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=v.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};v.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="173",ie=0,se=1,re=2,ae=0,oe=1,le=2,ce=3,he=0,ue=1,de=2,pe=100,fe=101,me=102,ge=200,ve=201,_e=202,xe=203,ye=204,Ae=205,Se=206,be=207,Me=208,we=209,Te=210,Ee=211,Ce=212,Re=213,Ie=214,De=0,Pe=1,Be=2,Le=3,Ue=4,Fe=5,ke=6,Ne=7,Oe="attached",ze=301,He=302,Ve=306,Ge=1e3,We=1001,je=1002,Xe=1003,qe=1004,Qe=1005,Ke=1006,Ye=1007,Ze=1008,Je=1009,$e=1010,et=1011,tt=1012,nt=1013,it=1014,st=1015,rt=1016,at=1017,ot=1018,lt=1020,ct=35902,ht=1023,ut=1026,dt=1027,pt=1028,ft=1029,mt=1030,gt=1031,vt=1033,_t=33776,xt=33777,yt=33778,At=33779,St=35840,bt=35841,Mt=35842,wt=35843,Tt=36196,Et=37492,Ct=37496,Rt=37808,It=37809,Dt=37810,Pt=37811,Bt=37812,Lt=37813,Ut=37814,Ft=37815,kt=37816,Nt=37817,Ot=37818,zt=37819,Ht=37820,Vt=37821,Gt=36492,Wt=36494,jt=36495,Xt=36284,qt=36285,Qt=36286,Kt=2200,Yt=2201,Zt=2300,Jt=2301,$t=2302,en=2400,tn=2401,nn=2402,sn=2500,rn="",an="srgb",on="srgb-linear",ln="linear",cn="srgb",hn=7680,un=512,dn=513,pn=514,fn=515,mn=516,gn=517,vn=518,_n=519,xn=35044,yn=35048,An="300 es",Sn=2e3,bn=2001;class Mn{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 wn=["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 Tn=1234567;const En=Math.PI/180,Cn=180/Math.PI;function Rn(){const e=4294967295*Math.random()|0,t=4294967295*Math.random()|0,n=4294967295*Math.random()|0,i=4294967295*Math.random()|0;return(wn[255&e]+wn[e>>8&255]+wn[e>>16&255]+wn[e>>24&255]+"-"+wn[255&t]+wn[t>>8&255]+"-"+wn[t>>16&15|64]+wn[t>>24&255]+"-"+wn[63&n|128]+wn[n>>8&255]+"-"+wn[n>>16&255]+wn[n>>24&255]+wn[255&i]+wn[i>>8&255]+wn[i>>16&255]+wn[i>>24&255]).toLowerCase()}function In(e,t,n){return Math.max(t,Math.min(n,e))}function Dn(e,t){return(e%t+t)%t}function Pn(e,t,n){return(1-n)*e+n*t}function Bn(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 Ln(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 Un={DEG2RAD:En,RAD2DEG:Cn,generateUUID:Rn,clamp:In,euclideanModulo:Dn,mapLinear:function(e,t,n,i,s){return i+(e-t)*(s-i)/(n-t)},inverseLerp:function(e,t,n){return e!==t?(n-e)/(t-e):0},lerp:Pn,damp:function(e,t,n,i){return Pn(e,t,1-Math.exp(-n*i))},pingpong:function(e,t=1){return t-Math.abs(Dn(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&&(Tn=e);let t=Tn+=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*En},radToDeg:function(e){return e*Cn},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,s){const r=Math.cos,a=Math.sin,o=r(n/2),l=a(n/2),c=r((t+i)/2),h=a((t+i)/2),u=r((t-i)/2),d=a((t-i)/2),p=r((i-t)/2),f=a((i-t)/2);switch(s){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:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+s)}},normalize:Ln,denormalize:Bn};class Fn{constructor(e=0,t=0){Fn.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=In(this.x,e.x,t.x),this.y=In(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=In(this.x,e,t),this.y=In(this.y,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(In(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(In(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),s=this.x-e.x,r=this.y-e.y;return this.x=s*n-r*i+e.x,this.y=s*i+r*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class kn{constructor(e,t,n,i,s,r,a,o,l){kn.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],void 0!==e&&this.set(e,t,n,i,s,r,a,o,l)}set(e,t,n,i,s,r,a,o,l){const c=this.elements;return c[0]=e,c[1]=i,c[2]=a,c[3]=t,c[4]=s,c[5]=o,c[6]=n,c[7]=r,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,s=this.elements,r=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],v=i[1],_=i[4],x=i[7],y=i[2],A=i[5],S=i[8];return s[0]=r*f+a*v+o*y,s[3]=r*m+a*_+o*A,s[6]=r*g+a*x+o*S,s[1]=l*f+c*v+h*y,s[4]=l*m+c*_+h*A,s[7]=l*g+c*x+h*S,s[2]=u*f+d*v+p*y,s[5]=u*m+d*_+p*A,s[8]=u*g+d*x+p*S,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],s=e[3],r=e[4],a=e[5],o=e[6],l=e[7],c=e[8];return t*r*c-t*a*l-n*s*c+n*a*o+i*s*l-i*r*o}invert(){const e=this.elements,t=e[0],n=e[1],i=e[2],s=e[3],r=e[4],a=e[5],o=e[6],l=e[7],c=e[8],h=c*r-a*l,u=a*o-c*s,d=l*s-r*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*r)*f,e[3]=u*f,e[4]=(c*t-i*o)*f,e[5]=(i*s-a*t)*f,e[6]=d*f,e[7]=(n*o-l*t)*f,e[8]=(r*t-n*s)*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,s,r,a){const o=Math.cos(s),l=Math.sin(s);return this.set(n*o,n*l,-n*(o*r+l*a)+r+e,-i*l,i*o,-i*(-l*r+o*a)+a+t,0,0,1),this}scale(e,t){return this.premultiply(Nn.makeScale(e,t)),this}rotate(e){return this.premultiply(Nn.makeRotation(-e)),this}translate(e,t){return this.premultiply(Nn.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 Nn=new kn;function On(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}function zn(e){return document.createElementNS("http://www.w3.org/1999/xhtml",e)}function Hn(){const e=zn("canvas");return e.style.display="block",e}const Vn={};function Gn(e){e in Vn||(Vn[e]=!0,console.warn(e))}const Wn=(new kn).set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),jn=(new kn).set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function Xn(){const e={enabled:!0,workingColorSpace:on,spaces:{},convert:function(e,t,n){return!1!==this.enabled&&t!==n&&t&&n?(this.spaces[t].transfer===cn&&(e.r=Qn(e.r),e.g=Qn(e.g),e.b=Qn(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===cn&&(e.r=Kn(e.r),e.g=Kn(e.g),e.b=Kn(e.b)),e):e},fromWorkingColorSpace:function(e,t){return this.convert(e,this.workingColorSpace,t)},toWorkingColorSpace:function(e,t){return this.convert(e,t,this.workingColorSpace)},getPrimaries:function(e){return this.spaces[e].primaries},getTransfer:function(e){return e===rn?ln:this.spaces[e].transfer},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}},t=[.64,.33,.3,.6,.15,.06],n=[.2126,.7152,.0722],i=[.3127,.329];return e.define({[on]:{primaries:t,whitePoint:i,transfer:ln,toXYZ:Wn,fromXYZ:jn,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:an},outputColorSpaceConfig:{drawingBufferColorSpace:an}},[an]:{primaries:t,whitePoint:i,transfer:cn,toXYZ:Wn,fromXYZ:jn,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:an}}}),e}const qn=Xn();function Qn(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}function Kn(e){return e<.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}let Yn;class Zn{static getDataURL(e){if(/^data:/i.test(e.src))return e.src;if("undefined"==typeof HTMLCanvasElement)return e.src;let t;if(e instanceof HTMLCanvasElement)t=e;else{void 0===Yn&&(Yn=zn("canvas")),Yn.width=e.width,Yn.height=e.height;const n=Yn.getContext("2d");e instanceof ImageData?n.putImageData(e,0,0):n.drawImage(e,0,0,e.width,e.height),t=Yn}return t.toDataURL("image/png")}static sRGBToLinear(e){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap){const t=zn("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),s=i.data;for(let e=0;e<s.length;e++)s[e]=255*Qn(s[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*Qn(t[e]/255)):t[e]=Qn(t[e]);return{data:t,width:e.width,height:e.height}}return console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let Jn=0;class $n{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:Jn++}),this.uuid=Rn(),this.data=e,this.dataReady=!0,this.version=0}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(ei(i[t].image)):e.push(ei(i[t]))}else e=ei(i);n.url=e}return t||(e.images[this.uuid]=n),n}}function ei(e){return"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?Zn.getDataURL(e):e.data?{data:Array.from(e.data),width:e.width,height:e.height,type:e.data.constructor.name}:(console.warn("THREE.Texture: Unable to serialize Texture."),{})}let ti=0;class ni extends Mn{constructor(e=ni.DEFAULT_IMAGE,t=ni.DEFAULT_MAPPING,n=1001,i=1001,s=1006,r=1008,a=1023,o=1009,l=ni.DEFAULT_ANISOTROPY,c=""){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:ti++}),this.uuid=Rn(),this.name="",this.source=new $n(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=n,this.wrapT=i,this.magFilter=s,this.minFilter=r,this.anisotropy=l,this.format=a,this.internalFormat=null,this.type=o,this.offset=new Fn(0,0),this.repeat=new Fn(1,1),this.center=new Fn(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new kn,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=c,this.userData={},this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.pmremVersion=0}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)}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.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}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.6,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 Ge:e.x=e.x-Math.floor(e.x);break;case We:e.x=e.x<0?0:1;break;case je: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 Ge:e.y=e.y-Math.floor(e.y);break;case We:e.y=e.y<0?0:1;break;case je: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++}}ni.DEFAULT_IMAGE=null,ni.DEFAULT_MAPPING=300,ni.DEFAULT_ANISOTROPY=1;class ii{constructor(e=0,t=0,n=0,i=1){ii.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,s=this.w,r=e.elements;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.w=r[3]*t+r[7]*n+r[11]*i+r[15]*s,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,s;const r=.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)<r&&Math.abs(h-f)<r&&Math.abs(p-m)<r){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,v=(g+1)/2,_=(c+u)/4,x=(h+f)/4,y=(p+m)/4;return e>o&&e>v?e<r?(n=0,i=.707106781,s=.707106781):(n=Math.sqrt(e),i=_/n,s=x/n):o>v?o<r?(n=.707106781,i=0,s=.707106781):(i=Math.sqrt(o),n=_/i,s=y/i):v<r?(n=.707106781,i=.707106781,s=0):(s=Math.sqrt(v),n=x/s,i=y/s),this.set(n,i,s,t),this}let v=Math.sqrt((m-p)*(m-p)+(h-f)*(h-f)+(u-c)*(u-c));return Math.abs(v)<.001&&(v=1),this.x=(m-p)/v,this.y=(h-f)/v,this.z=(u-c)/v,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=In(this.x,e.x,t.x),this.y=In(this.y,e.y,t.y),this.z=In(this.z,e.z,t.z),this.w=In(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=In(this.x,e,t),this.y=In(this.y,e,t),this.z=In(this.z,e,t),this.w=In(this.w,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(In(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 si extends Mn{constructor(e=1,t=1,n={}){super(),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=1,this.scissor=new ii(0,0,e,t),this.scissorTest=!1,this.viewport=new ii(0,0,e,t);const i={width:e,height:t,depth:1};n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Ke,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1},n);const s=new ni(i,n.mapping,n.wrapS,n.wrapT,n.magFilter,n.minFilter,n.format,n.type,n.anisotropy,n.colorSpace);s.flipY=!1,s.generateMipmaps=n.generateMipmaps,s.internalFormat=n.internalFormat,this.textures=[];const r=n.count;for(let a=0;a<r;a++)this.textures[a]=s.clone(),this.textures[a].isRenderTargetTexture=!0,this.textures[a].renderTarget=this;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}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,s=this.textures.length;i<s;i++)this.textures[i].image.width=e,this.textures[i].image.height=t,this.textures[i].image.depth=n;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 n=0,i=e.textures.length;n<i;n++)this.textures[n]=e.textures[n].clone(),this.textures[n].isRenderTargetTexture=!0,this.textures[n].renderTarget=this;const t=Object.assign({},e.texture.image);return this.texture.source=new $n(t),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 ri extends si{constructor(e=1,t=1,n={}){super(e,t,n),this.isWebGLRenderTarget=!0}}class ai extends ni{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=Xe,this.minFilter=Xe,this.wrapR=We,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class oi extends ni{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=Xe,this.minFilter=Xe,this.wrapR=We,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class li{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,s,r,a){let o=n[i+0],l=n[i+1],c=n[i+2],h=n[i+3];const u=s[r+0],d=s[r+1],p=s[r+2],f=s[r+3];if(0===a)return e[t+0]=o,e[t+1]=l,e[t+2]=c,void(e[t+3]=h);if(1===a)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=1-a;const t=o*u+l*d+c*p+h*f,n=t>=0?1:-1,i=1-t*t;if(i>Number.EPSILON){const s=Math.sqrt(i),r=Math.atan2(s,t*n);e=Math.sin(e*r)/s,a=Math.sin(a*r)/s}const s=a*n;if(o=o*e+u*s,l=l*e+d*s,c=c*e+p*s,h=h*e+f*s,e===1-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,s,r){const a=n[i],o=n[i+1],l=n[i+2],c=n[i+3],h=s[r],u=s[r+1],d=s[r+2],p=s[r+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,s=e._z,r=e._order,a=Math.cos,o=Math.sin,l=a(n/2),c=a(i/2),h=a(s/2),u=o(n/2),d=o(i/2),p=o(s/2);switch(r){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:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+r)}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],s=t[8],r=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=(s-l)*e,this._z=(r-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+r)/e,this._z=(s+l)/e}else if(a>h){const e=2*Math.sqrt(1+a-n-h);this._w=(s-l)/e,this._x=(i+r)/e,this._y=.25*e,this._z=(o+c)/e}else{const e=2*Math.sqrt(1+h-n-a);this._w=(r-i)/e,this._x=(s+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<Number.EPSILON?(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(In(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,s=e._z,r=e._w,a=t._x,o=t._y,l=t._z,c=t._w;return this._x=n*c+r*a+i*l-s*o,this._y=i*c+r*o+s*a-n*l,this._z=s*c+r*l+n*o-i*a,this._w=r*c-n*a-i*o-s*l,this._onChangeCallback(),this}slerp(e,t){if(0===t)return this;if(1===t)return this.copy(e);const n=this._x,i=this._y,s=this._z,r=this._w;let a=r*e._w+n*e._x+i*e._y+s*e._z;if(a<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,a=-a):this.copy(e),a>=1)return this._w=r,this._x=n,this._y=i,this._z=s,this;const o=1-a*a;if(o<=Number.EPSILON){const e=1-t;return this._w=e*r+t*this._w,this._x=e*n+t*this._x,this._y=e*i+t*this._y,this._z=e*s+t*this._z,this.normalize(),this}const l=Math.sqrt(o),c=Math.atan2(l,a),h=Math.sin((1-t)*c)/l,u=Math.sin(t*c)/l;return this._w=r*h+this._w*u,this._x=n*h+this._x*u,this._y=i*h+this._y*u,this._z=s*h+this._z*u,this._onChangeCallback(),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),s=Math.sqrt(n);return this.set(i*Math.sin(e),i*Math.cos(e),s*Math.sin(t),s*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 ci{constructor(e=0,t=0,n=0){ci.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(ui.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(ui.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,n=this.y,i=this.z,s=e.elements;return this.x=s[0]*t+s[3]*n+s[6]*i,this.y=s[1]*t+s[4]*n+s[7]*i,this.z=s[2]*t+s[5]*n+s[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,n=this.y,i=this.z,s=e.elements,r=1/(s[3]*t+s[7]*n+s[11]*i+s[15]);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}applyQuaternion(e){const t=this.x,n=this.y,i=this.z,s=e.x,r=e.y,a=e.z,o=e.w,l=2*(r*i-a*n),c=2*(a*t-s*i),h=2*(s*n-r*t);return this.x=t+o*l+r*h-a*c,this.y=n+o*c+a*l-s*h,this.z=i+o*h+s*c-r*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,s=e.elements;return this.x=s[0]*t+s[4]*n+s[8]*i,this.y=s[1]*t+s[5]*n+s[9]*i,this.z=s[2]*t+s[6]*n+s[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=In(this.x,e.x,t.x),this.y=In(this.y,e.y,t.y),this.z=In(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=In(this.x,e,t),this.y=In(this.y,e,t),this.z=In(this.z,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(In(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,s=e.z,r=t.x,a=t.y,o=t.z;return this.x=i*o-s*a,this.y=s*r-n*o,this.z=n*a-i*r,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 hi.copy(this).projectOnVector(e),this.sub(hi)}reflect(e){return this.sub(hi.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(In(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 hi=new ci,ui=new li;class di{constructor(e=new ci(1/0,1/0,1/0),t=new ci(-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(fi.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(fi.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=fi.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,fi):fi.fromBufferAttribute(i,t),fi.applyMatrix4(e.matrixWorld),this.expandByPoint(fi);else void 0!==e.boundingBox?(null===e.boundingBox&&e.computeBoundingBox(),mi.copy(e.boundingBox)):(null===n.boundingBox&&n.computeBoundingBox(),mi.copy(n.boundingBox)),mi.applyMatrix4(e.matrixWorld),this.union(mi)}const i=e.children;for(let s=0,r=i.length;s<r;s++)this.expandByObject(i[s],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,fi),fi.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(Si),bi.subVectors(this.max,Si),gi.subVectors(e.a,Si),vi.subVectors(e.b,Si),_i.subVectors(e.c,Si),xi.subVectors(vi,gi),yi.subVectors(_i,vi),Ai.subVectors(gi,_i);let t=[0,-xi.z,xi.y,0,-yi.z,yi.y,0,-Ai.z,Ai.y,xi.z,0,-xi.x,yi.z,0,-yi.x,Ai.z,0,-Ai.x,-xi.y,xi.x,0,-yi.y,yi.x,0,-Ai.y,Ai.x,0];return!!Ti(t,gi,vi,_i,bi)&&(t=[1,0,0,0,1,0,0,0,1],!!Ti(t,gi,vi,_i,bi)&&(Mi.crossVectors(xi,yi),t=[Mi.x,Mi.y,Mi.z],Ti(t,gi,vi,_i,bi)))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,fi).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=.5*this.getSize(fi).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()||(pi[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),pi[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),pi[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),pi[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),pi[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),pi[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),pi[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),pi[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(pi)),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)}}const pi=[new ci,new ci,new ci,new ci,new ci,new ci,new ci,new ci],fi=new ci,mi=new di,gi=new ci,vi=new ci,_i=new ci,xi=new ci,yi=new ci,Ai=new ci,Si=new ci,bi=new ci,Mi=new ci,wi=new ci;function Ti(e,t,n,i,s){for(let r=0,a=e.length-3;r<=a;r+=3){wi.fromArray(e,r);const a=s.x*Math.abs(wi.x)+s.y*Math.abs(wi.y)+s.z*Math.abs(wi.z),o=t.dot(wi),l=n.dot(wi),c=i.dot(wi);if(Math.max(-Math.max(o,l,c),Math.min(o,l,c))>a)return!1}return!0}const Ei=new di,Ci=new ci,Ri=new ci;class Ii{constructor(e=new ci,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):Ei.setFromPoints(e).getCenter(n);let i=0;for(let s=0,r=e.length;s<r;s++)i=Math.max(i,n.distanceToSquared(e[s]));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;Ci.subVectors(e,this.center);const t=Ci.lengthSq();if(t>this.radius*this.radius){const e=Math.sqrt(t),n=.5*(e-this.radius);this.center.addScaledVector(Ci,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):(Ri.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Ci.copy(e.center).add(Ri)),this.expandByPoint(Ci.copy(e.center).sub(Ri))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return(new this.constructor).copy(this)}}const Di=new ci,Pi=new ci,Bi=new ci,Li=new ci,Ui=new ci,Fi=new ci,ki=new ci;let Ni=class{constructor(e=new ci,t=new ci(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,Di)),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=Di.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Di.copy(this.origin).addScaledVector(this.direction,t),Di.distanceToSquared(e))}distanceSqToSegment(e,t,n,i){Pi.copy(e).add(t).multiplyScalar(.5),Bi.copy(t).sub(e).normalize(),Li.copy(this.origin).sub(Pi);const s=.5*e.distanceTo(t),r=-this.direction.dot(Bi),a=Li.dot(this.direction),o=-Li.dot(Bi),l=Li.lengthSq(),c=Math.abs(1-r*r);let h,u,d,p;if(c>0)if(h=r*o-a,u=r*a-o,p=s*c,h>=0)if(u>=-p)if(u<=p){const e=1/c;h*=e,u*=e,d=h*(h+r*u+2*a)+u*(r*h+u+2*o)+l}else u=s,h=Math.max(0,-(r*u+a)),d=-h*h+u*(u+2*o)+l;else u=-s,h=Math.max(0,-(r*u+a)),d=-h*h+u*(u+2*o)+l;else u<=-p?(h=Math.max(0,-(-r*s+a)),u=h>0?-s:Math.min(Math.max(-s,-o),s),d=-h*h+u*(u+2*o)+l):u<=p?(h=0,u=Math.min(Math.max(-s,-o),s),d=u*(u+2*o)+l):(h=Math.max(0,-(r*s+a)),u=h>0?s:Math.min(Math.max(-s,-o),s),d=-h*h+u*(u+2*o)+l);else u=r>0?-s:s,h=Math.max(0,-(r*u+a)),d=-h*h+u*(u+2*o)+l;return n&&n.copy(this.origin).addScaledVector(this.direction,h),i&&i.copy(Pi).addScaledVector(Bi,u),d}intersectSphere(e,t){Di.subVectors(e.center,this.origin);const n=Di.dot(this.direction),i=Di.dot(Di)-n*n,s=e.radius*e.radius;if(i>s)return null;const r=Math.sqrt(s-i),a=n-r,o=n+r;return o<0?null:a<0?this.at(o,t):this.at(a,t)}intersectsSphere(e){return 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,s,r,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?(s=(e.min.y-u.y)*c,r=(e.max.y-u.y)*c):(s=(e.max.y-u.y)*c,r=(e.min.y-u.y)*c),n>r||s>i?null:((s>n||isNaN(n))&&(n=s),(r<i||isNaN(i))&&(i=r),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,Di)}intersectTriangle(e,t,n,i,s){Ui.subVectors(t,e),Fi.subVectors(n,e),ki.crossVectors(Ui,Fi);let r,a=this.direction.dot(ki);if(a>0){if(i)return null;r=1}else{if(!(a<0))return null;r=-1,a=-a}Li.subVectors(this.origin,e);const o=r*this.direction.dot(Fi.crossVectors(Li,Fi));if(o<0)return null;const l=r*this.direction.dot(Ui.cross(Li));if(l<0)return null;if(o+l>a)return null;const c=-r*Li.dot(ki);return c<0?null:this.at(c/a,s)}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 Oi{constructor(e,t,n,i,s,r,a,o,l,c,h,u,d,p,f,m){Oi.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,s,r,a,o,l,c,h,u,d,p,f,m)}set(e,t,n,i,s,r,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]=s,g[5]=r,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 Oi).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 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){const t=this.elements,n=e.elements,i=1/zi.setFromMatrixColumn(e,0).length(),s=1/zi.setFromMatrixColumn(e,1).length(),r=1/zi.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]*s,t[5]=n[5]*s,t[6]=n[6]*s,t[7]=0,t[8]=n[8]*r,t[9]=n[9]*r,t[10]=n[10]*r,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,s=e.z,r=Math.cos(n),a=Math.sin(n),o=Math.cos(i),l=Math.sin(i),c=Math.cos(s),h=Math.sin(s);if("XYZ"===e.order){const e=r*c,n=r*h,i=a*c,s=a*h;t[0]=o*c,t[4]=-o*h,t[8]=l,t[1]=n+i*l,t[5]=e-s*l,t[9]=-a*o,t[2]=s-e*l,t[6]=i+n*l,t[10]=r*o}else if("YXZ"===e.order){const e=o*c,n=o*h,i=l*c,s=l*h;t[0]=e+s*a,t[4]=i*a-n,t[8]=r*l,t[1]=r*h,t[5]=r*c,t[9]=-a,t[2]=n*a-i,t[6]=s+e*a,t[10]=r*o}else if("ZXY"===e.order){const e=o*c,n=o*h,i=l*c,s=l*h;t[0]=e-s*a,t[4]=-r*h,t[8]=i+n*a,t[1]=n+i*a,t[5]=r*c,t[9]=s-e*a,t[2]=-r*l,t[6]=a,t[10]=r*o}else if("ZYX"===e.order){const e=r*c,n=r*h,i=a*c,s=a*h;t[0]=o*c,t[4]=i*l-n,t[8]=e*l+s,t[1]=o*h,t[5]=s*l+e,t[9]=n*l-i,t[2]=-l,t[6]=a*o,t[10]=r*o}else if("YZX"===e.order){const e=r*o,n=r*l,i=a*o,s=a*l;t[0]=o*c,t[4]=s-e*h,t[8]=i*h+n,t[1]=h,t[5]=r*c,t[9]=-a*c,t[2]=-l*c,t[6]=n*h+i,t[10]=e-s*h}else if("XZY"===e.order){const e=r*o,n=r*l,i=a*o,s=a*l;t[0]=o*c,t[4]=-h,t[8]=l*c,t[1]=e*h+s,t[5]=r*c,t[9]=n*h-i,t[2]=i*h-n,t[6]=a*c,t[10]=s*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(Vi,e,Gi)}lookAt(e,t,n){const i=this.elements;return Xi.subVectors(e,t),0===Xi.lengthSq()&&(Xi.z=1),Xi.normalize(),Wi.crossVectors(n,Xi),0===Wi.lengthSq()&&(1===Math.abs(n.z)?Xi.x+=1e-4:Xi.z+=1e-4,Xi.normalize(),Wi.crossVectors(n,Xi)),Wi.normalize(),ji.crossVectors(Xi,Wi),i[0]=Wi.x,i[4]=ji.x,i[8]=Xi.x,i[1]=Wi.y,i[5]=ji.y,i[9]=Xi.y,i[2]=Wi.z,i[6]=ji.z,i[10]=Xi.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,s=this.elements,r=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],v=n[3],_=n[7],x=n[11],y=n[15],A=i[0],S=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],D=i[10],P=i[14],B=i[3],L=i[7],U=i[11],F=i[15];return s[0]=r*A+a*w+o*R+l*B,s[4]=r*S+a*T+o*I+l*L,s[8]=r*b+a*E+o*D+l*U,s[12]=r*M+a*C+o*P+l*F,s[1]=c*A+h*w+u*R+d*B,s[5]=c*S+h*T+u*I+d*L,s[9]=c*b+h*E+u*D+d*U,s[13]=c*M+h*C+u*P+d*F,s[2]=p*A+f*w+m*R+g*B,s[6]=p*S+f*T+m*I+g*L,s[10]=p*b+f*E+m*D+g*U,s[14]=p*M+f*C+m*P+g*F,s[3]=v*A+_*w+x*R+y*B,s[7]=v*S+_*T+x*I+y*L,s[11]=v*b+_*E+x*D+y*U,s[15]=v*M+_*C+x*P+y*F,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],s=e[12],r=e[1],a=e[5],o=e[9],l=e[13],c=e[2],h=e[6],u=e[10],d=e[14];return e[3]*(+s*o*h-i*l*h-s*a*u+n*l*u+i*a*d-n*o*d)+e[7]*(+t*o*d-t*l*u+s*r*u-i*r*d+i*l*c-s*o*c)+e[11]*(+t*l*h-t*a*d-s*r*h+n*r*d+s*a*c-n*l*c)+e[15]*(-i*a*c-t*o*h+t*a*u+i*r*h-n*r*u+n*o*c)}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],s=e[3],r=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],v=h*m*l-f*u*l+f*o*d-a*m*d-h*o*g+a*u*g,_=p*u*l-c*m*l-p*o*d+r*m*d+c*o*g-r*u*g,x=c*f*l-p*h*l+p*a*d-r*f*d-c*a*g+r*h*g,y=p*h*o-c*f*o-p*a*u+r*f*u+c*a*m-r*h*m,A=t*v+n*_+i*x+s*y;if(0===A)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const S=1/A;return e[0]=v*S,e[1]=(f*u*s-h*m*s-f*i*d+n*m*d+h*i*g-n*u*g)*S,e[2]=(a*m*s-f*o*s+f*i*l-n*m*l-a*i*g+n*o*g)*S,e[3]=(h*o*s-a*u*s-h*i*l+n*u*l+a*i*d-n*o*d)*S,e[4]=_*S,e[5]=(c*m*s-p*u*s+p*i*d-t*m*d-c*i*g+t*u*g)*S,e[6]=(p*o*s-r*m*s-p*i*l+t*m*l+r*i*g-t*o*g)*S,e[7]=(r*u*s-c*o*s+c*i*l-t*u*l-r*i*d+t*o*d)*S,e[8]=x*S,e[9]=(p*h*s-c*f*s-p*n*d+t*f*d+c*n*g-t*h*g)*S,e[10]=(r*f*s-p*a*s+p*n*l-t*f*l-r*n*g+t*a*g)*S,e[11]=(c*a*s-r*h*s-c*n*l+t*h*l+r*n*d-t*a*d)*S,e[12]=y*S,e[13]=(c*f*i-p*h*i+p*n*u-t*f*u-c*n*m+t*h*m)*S,e[14]=(p*a*i-r*f*i-p*n*o+t*f*o+r*n*m-t*a*m)*S,e[15]=(r*h*i-c*a*i+c*n*o-t*h*o-r*n*u+t*a*u)*S,this}scale(e){const t=this.elements,n=e.x,i=e.y,s=e.z;return t[0]*=n,t[4]*=i,t[8]*=s,t[1]*=n,t[5]*=i,t[9]*=s,t[2]*=n,t[6]*=i,t[10]*=s,t[3]*=n,t[7]*=i,t[11]*=s,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),s=1-n,r=e.x,a=e.y,o=e.z,l=s*r,c=s*a;return this.set(l*r+n,l*a-i*o,l*o+i*a,0,l*a+i*o,c*a+n,c*o-i*r,0,l*o-i*a,c*o+i*r,s*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,s,r){return this.set(1,n,s,0,e,1,r,0,t,i,1,0,0,0,0,1),this}compose(e,t,n){const i=this.elements,s=t._x,r=t._y,a=t._z,o=t._w,l=s+s,c=r+r,h=a+a,u=s*l,d=s*c,p=s*h,f=r*c,m=r*h,g=a*h,v=o*l,_=o*c,x=o*h,y=n.x,A=n.y,S=n.z;return i[0]=(1-(f+g))*y,i[1]=(d+x)*y,i[2]=(p-_)*y,i[3]=0,i[4]=(d-x)*A,i[5]=(1-(u+g))*A,i[6]=(m+v)*A,i[7]=0,i[8]=(p+_)*S,i[9]=(m-v)*S,i[10]=(1-(u+f))*S,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;let s=zi.set(i[0],i[1],i[2]).length();const r=zi.set(i[4],i[5],i[6]).length(),a=zi.set(i[8],i[9],i[10]).length();this.determinant()<0&&(s=-s),e.x=i[12],e.y=i[13],e.z=i[14],Hi.copy(this);const o=1/s,l=1/r,c=1/a;return Hi.elements[0]*=o,Hi.elements[1]*=o,Hi.elements[2]*=o,Hi.elements[4]*=l,Hi.elements[5]*=l,Hi.elements[6]*=l,Hi.elements[8]*=c,Hi.elements[9]*=c,Hi.elements[10]*=c,t.setFromRotationMatrix(Hi),n.x=s,n.y=r,n.z=a,this}makePerspective(e,t,n,i,s,r,a=2e3){const o=this.elements,l=2*s/(t-e),c=2*s/(n-i),h=(t+e)/(t-e),u=(n+i)/(n-i);let d,p;if(a===Sn)d=-(r+s)/(r-s),p=-2*r*s/(r-s);else{if(a!==bn)throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);d=-r/(r-s),p=-r*s/(r-s)}return o[0]=l,o[4]=0,o[8]=h,o[12]=0,o[1]=0,o[5]=c,o[9]=u,o[13]=0,o[2]=0,o[6]=0,o[10]=d,o[14]=p,o[3]=0,o[7]=0,o[11]=-1,o[15]=0,this}makeOrthographic(e,t,n,i,s,r,a=2e3){const o=this.elements,l=1/(t-e),c=1/(n-i),h=1/(r-s),u=(t+e)*l,d=(n+i)*c;let p,f;if(a===Sn)p=(r+s)*h,f=-2*h;else{if(a!==bn)throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);p=s*h,f=-1*h}return o[0]=2*l,o[4]=0,o[8]=0,o[12]=-u,o[1]=0,o[5]=2*c,o[9]=0,o[13]=-d,o[2]=0,o[6]=0,o[10]=f,o[14]=-p,o[3]=0,o[7]=0,o[11]=0,o[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 zi=new ci,Hi=new Oi,Vi=new ci(0,0,0),Gi=new ci(1,1,1),Wi=new ci,ji=new ci,Xi=new ci,qi=new Oi,Qi=new li;class Ki{constructor(e=0,t=0,n=0,i=Ki.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,s=i[0],r=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(In(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-c,d),this._z=Math.atan2(-r,s)):(this._x=Math.atan2(u,l),this._z=0);break;case"YXZ":this._x=Math.asin(-In(c,-1,1)),Math.abs(c)<.9999999?(this._y=Math.atan2(a,d),this._z=Math.atan2(o,l)):(this._y=Math.atan2(-h,s),this._z=0);break;case"ZXY":this._x=Math.asin(In(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(-h,d),this._z=Math.atan2(-r,l)):(this._y=0,this._z=Math.atan2(o,s));break;case"ZYX":this._y=Math.asin(-In(h,-1,1)),Math.abs(h)<.9999999?(this._x=Math.atan2(u,d),this._z=Math.atan2(o,s)):(this._x=0,this._z=Math.atan2(-r,l));break;case"YZX":this._z=Math.asin(In(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-c,l),this._y=Math.atan2(-h,s)):(this._x=0,this._y=Math.atan2(a,d));break;case"XZY":this._z=Math.asin(-In(r,-1,1)),Math.abs(r)<.9999999?(this._x=Math.atan2(u,l),this._y=Math.atan2(a,s)):(this._x=Math.atan2(-c,d),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,!0===n&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return qi.makeRotationFromQuaternion(e),this.setFromRotationMatrix(qi,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return Qi.setFromEuler(this),this.setFromQuaternion(Qi,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}}Ki.DEFAULT_ORDER="XYZ";class Yi{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 Zi=0;const Ji=new ci,$i=new li,es=new Oi,ts=new ci,ns=new ci,is=new ci,ss=new li,rs=new ci(1,0,0),as=new ci(0,1,0),os=new ci(0,0,1),ls={type:"added"},cs={type:"removed"},hs={type:"childadded",child:null},us={type:"childremoved",child:null};class ds extends Mn{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:Zi++}),this.uuid=Rn(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=ds.DEFAULT_UP.clone();const e=new ci,t=new Ki,n=new li,i=new ci(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 Oi},normalMatrix:{value:new kn}}),this.matrix=new Oi,this.matrixWorld=new Oi,this.matrixAutoUpdate=ds.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=ds.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new Yi,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],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 $i.setFromAxisAngle(e,t),this.quaternion.multiply($i),this}rotateOnWorldAxis(e,t){return $i.setFromAxisAngle(e,t),this.quaternion.premultiply($i),this}rotateX(e){return this.rotateOnAxis(rs,e)}rotateY(e){return this.rotateOnAxis(as,e)}rotateZ(e){return this.rotateOnAxis(os,e)}translateOnAxis(e,t){return Ji.copy(e).applyQuaternion(this.quaternion),this.position.add(Ji.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(rs,e)}translateY(e){return this.translateOnAxis(as,e)}translateZ(e){return this.translateOnAxis(os,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(es.copy(this.matrixWorld).invert())}lookAt(e,t,n){e.isVector3?ts.copy(e):ts.set(e,t,n);const i=this.parent;this.updateWorldMatrix(!0,!1),ns.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?es.lookAt(ns,ts,this.up):es.lookAt(ts,ns,this.up),this.quaternion.setFromRotationMatrix(es),i&&(es.extractRotation(i.matrixWorld),$i.setFromRotationMatrix(es),this.quaternion.premultiply($i.invert()))}add(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return e===this?(console.error("THREE.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(ls),hs.child=e,this.dispatchEvent(hs),hs.child=null):console.error("THREE.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(cs),us.child=e,this.dispatchEvent(us),us.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),es.copy(this.matrixWorld).invert(),null!==e.parent&&(e.parent.updateWorldMatrix(!0,!1),es.multiply(e.parent.matrixWorld)),e.applyMatrix4(es),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(ls),hs.child=e,this.dispatchEvent(hs),hs.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 s=0,r=i.length;s<r;s++)i[s].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(ns,e,is),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(ns,ss,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.6,type:"Object",generator:"Object3D.toJSON"});const i={};function s(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.visibility=this._visibility,i.active=this._active,i.bounds=this._bounds.map(e=>({boxInitialized:e.boxInitialized,boxMin:e.box.min.toArray(),boxMax:e.box.max.toArray(),sphereInitialized:e.sphereInitialized,sphereRadius:e.sphere.radius,sphereCenter:e.sphere.center.toArray()})),i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.geometryCount=this._geometryCount,i.matricesTexture=this._matricesTexture.toJSON(e),null!==this._colorsTexture&&(i.colorsTexture=this._colorsTexture.toJSON(e)),null!==this.boundingSphere&&(i.boundingSphere={center:i.boundingSphere.center.toArray(),radius:i.boundingSphere.radius}),null!==this.boundingBox&&(i.boundingBox={min:i.boundingBox.min.toArray(),max:i.boundingBox.max.toArray()})),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=s(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];s(e.shapes,i)}else s(e.shapes,n)}}if(this.isSkinnedMesh&&(i.bindMode=this.bindMode,i.bindMatrix=this.bindMatrix.toArray(),void 0!==this.skeleton&&(s(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(s(e.materials,this.material[n]));i.material=t}else i.material=s(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(s(e.animations,n))}}if(t){const t=r(e.geometries),i=r(e.materials),s=r(e.textures),a=r(e.images),o=r(e.shapes),l=r(e.skeletons),c=r(e.animations),h=r(e.nodes);t.length>0&&(n.geometries=t),i.length>0&&(n.materials=i),s.length>0&&(n.textures=s),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 r(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}}ds.DEFAULT_UP=new ci(0,1,0),ds.DEFAULT_MATRIX_AUTO_UPDATE=!0,ds.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const ps=new ci,fs=new ci,ms=new ci,gs=new ci,vs=new ci,_s=new ci,xs=new ci,ys=new ci,As=new ci,Ss=new ci,bs=new ii,Ms=new ii,ws=new ii;class Ts{constructor(e=new ci,t=new ci,n=new ci){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,i){i.subVectors(n,t),ps.subVectors(e,t),i.cross(ps);const s=i.lengthSq();return s>0?i.multiplyScalar(1/Math.sqrt(s)):i.set(0,0,0)}static getBarycoord(e,t,n,i,s){ps.subVectors(i,t),fs.subVectors(n,t),ms.subVectors(e,t);const r=ps.dot(ps),a=ps.dot(fs),o=ps.dot(ms),l=fs.dot(fs),c=fs.dot(ms),h=r*l-a*a;if(0===h)return s.set(0,0,0),null;const u=1/h,d=(l*o-a*c)*u,p=(r*c-a*o)*u;return s.set(1-d-p,p,d)}static containsPoint(e,t,n,i){return null!==this.getBarycoord(e,t,n,i,gs)&&(gs.x>=0&&gs.y>=0&&gs.x+gs.y<=1)}static getInterpolation(e,t,n,i,s,r,a,o){return null===this.getBarycoord(e,t,n,i,gs)?(o.x=0,o.y=0,"z"in o&&(o.z=0),"w"in o&&(o.w=0),null):(o.setScalar(0),o.addScaledVector(s,gs.x),o.addScaledVector(r,gs.y),o.addScaledVector(a,gs.z),o)}static getInterpolatedAttribute(e,t,n,i,s,r){return bs.setScalar(0),Ms.setScalar(0),ws.setScalar(0),bs.fromBufferAttribute(e,t),Ms.fromBufferAttribute(e,n),ws.fromBufferAttribute(e,i),r.setScalar(0),r.addScaledVector(bs,s.x),r.addScaledVector(Ms,s.y),r.addScaledVector(ws,s.z),r}static isFrontFacing(e,t,n,i){return ps.subVectors(n,t),fs.subVectors(e,t),ps.cross(fs).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 ps.subVectors(this.c,this.b),fs.subVectors(this.a,this.b),.5*ps.cross(fs).length()}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Ts.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Ts.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,n,i,s){return Ts.getInterpolation(e,this.a,this.b,this.c,t,n,i,s)}containsPoint(e){return Ts.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Ts.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const n=this.a,i=this.b,s=this.c;let r,a;vs.subVectors(i,n),_s.subVectors(s,n),ys.subVectors(e,n);const o=vs.dot(ys),l=_s.dot(ys);if(o<=0&&l<=0)return t.copy(n);As.subVectors(e,i);const c=vs.dot(As),h=_s.dot(As);if(c>=0&&h<=c)return t.copy(i);const u=o*h-c*l;if(u<=0&&o>=0&&c<=0)return r=o/(o-c),t.copy(n).addScaledVector(vs,r);Ss.subVectors(e,s);const d=vs.dot(Ss),p=_s.dot(Ss);if(p>=0&&d<=p)return t.copy(s);const f=d*l-o*p;if(f<=0&&l>=0&&p<=0)return a=l/(l-p),t.copy(n).addScaledVector(_s,a);const m=c*p-d*h;if(m<=0&&h-c>=0&&d-p>=0)return xs.subVectors(s,i),a=(h-c)/(h-c+(d-p)),t.copy(i).addScaledVector(xs,a);const g=1/(m+f+u);return r=f*g,a=u*g,t.copy(n).addScaledVector(vs,r).addScaledVector(_s,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const Es={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},Cs={h:0,s:0,l:0},Rs={h:0,s:0,l:0};function Is(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 Ds{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=an){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(255&e)/255,qn.toWorkingColorSpace(this,t),this}setRGB(e,t,n,i=qn.workingColorSpace){return this.r=e,this.g=t,this.b=n,qn.toWorkingColorSpace(this,i),this}setHSL(e,t,n,i=qn.workingColorSpace){if(e=Dn(e,1),t=In(t,0,1),n=In(n,0,1),0===t)this.r=this.g=this.b=n;else{const i=n<=.5?n*(1+t):n+t-n*t,s=2*n-i;this.r=Is(s,i,e+1/3),this.g=Is(s,i,e),this.b=Is(s,i,e-1/3)}return qn.toWorkingColorSpace(this,i),this}setStyle(e,t=an){function n(t){void 0!==t&&parseFloat(t)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let s;const r=i[1],a=i[2];switch(r){case"rgb":case"rgba":if(s=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(s[4]),this.setRGB(Math.min(255,parseInt(s[1],10))/255,Math.min(255,parseInt(s[2],10))/255,Math.min(255,parseInt(s[3],10))/255,t);if(s=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(s[4]),this.setRGB(Math.min(100,parseInt(s[1],10))/100,Math.min(100,parseInt(s[2],10))/100,Math.min(100,parseInt(s[3],10))/100,t);break;case"hsl":case"hsla":if(s=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(s[4]),this.setHSL(parseFloat(s[1])/360,parseFloat(s[2])/100,parseFloat(s[3])/100,t);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){const n=i[1],s=n.length;if(3===s)return this.setRGB(parseInt(n.charAt(0),16)/15,parseInt(n.charAt(1),16)/15,parseInt(n.charAt(2),16)/15,t);if(6===s)return this.setHex(parseInt(n,16),t);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=an){const n=Es[e.toLowerCase()];return void 0!==n?this.setHex(n,t):console.warn("THREE.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=Qn(e.r),this.g=Qn(e.g),this.b=Qn(e.b),this}copyLinearToSRGB(e){return this.r=Kn(e.r),this.g=Kn(e.g),this.b=Kn(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=an){return qn.fromWorkingColorSpace(Ps.copy(this),e),65536*Math.round(In(255*Ps.r,0,255))+256*Math.round(In(255*Ps.g,0,255))+Math.round(In(255*Ps.b,0,255))}getHexString(e=an){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=qn.workingColorSpace){qn.fromWorkingColorSpace(Ps.copy(this),t);const n=Ps.r,i=Ps.g,s=Ps.b,r=Math.max(n,i,s),a=Math.min(n,i,s);let o,l;const c=(a+r)/2;if(a===r)o=0,l=0;else{const e=r-a;switch(l=c<=.5?e/(r+a):e/(2-r-a),r){case n:o=(i-s)/e+(i<s?6:0);break;case i:o=(s-n)/e+2;break;case s:o=(n-i)/e+4}o/=6}return e.h=o,e.s=l,e.l=c,e}getRGB(e,t=qn.workingColorSpace){return qn.fromWorkingColorSpace(Ps.copy(this),t),e.r=Ps.r,e.g=Ps.g,e.b=Ps.b,e}getStyle(e=an){qn.fromWorkingColorSpace(Ps.copy(this),e);const t=Ps.r,n=Ps.g,i=Ps.b;return e!==an?`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(Cs),this.setHSL(Cs.h+e,Cs.s+t,Cs.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(Cs),e.getHSL(Rs);const n=Pn(Cs.h,Rs.h,t),i=Pn(Cs.s,Rs.s,t),s=Pn(Cs.l,Rs.l,t);return this.setHSL(n,i,s),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,s=e.elements;return this.r=s[0]*t+s[3]*n+s[6]*i,this.g=s[1]*t+s[4]*n+s[7]*i,this.b=s[2]*t+s[5]*n+s[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 Ps=new Ds;Ds.NAMES=Es;let Bs=0;class Ls extends Mn{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:Bs++}),this.uuid=Rn(),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=pe,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new Ds(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=hn,this.stencilZFail=hn,this.stencilZPass=hn,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.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){console.warn(`THREE.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:console.warn(`THREE.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.6,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()),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!==pe&&(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!==hn&&(n.stencilFail=this.stencilFail),this.stencilZFail!==hn&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==hn&&(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),!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),s=i(e.images);t.length>0&&(n.textures=t),s.length>0&&(n.images=s)}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.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++}onBuild(){console.warn("Material: onBuild() has been removed.")}}class Us extends Ls{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Ds(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 Ki,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 Fs=ks();function ks(){const e=new ArrayBuffer(4),t=new Float32Array(e),n=new Uint32Array(e),i=new Uint32Array(512),s=new Uint32Array(512);for(let l=0;l<256;++l){const e=l-127;e<-27?(i[l]=0,i[256|l]=32768,s[l]=24,s[256|l]=24):e<-14?(i[l]=1024>>-e-14,i[256|l]=1024>>-e-14|32768,s[l]=-e-1,s[256|l]=-e-1):e<=15?(i[l]=e+15<<10,i[256|l]=e+15<<10|32768,s[l]=13,s[256|l]=13):e<128?(i[l]=31744,i[256|l]=64512,s[l]=24,s[256|l]=24):(i[l]=31744,i[256|l]=64512,s[l]=13,s[256|l]=13)}const r=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,r[l]=e|t}for(let l=1024;l<2048;++l)r[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:s,mantissaTable:r,exponentTable:a,offsetTable:o}}const Ns={toHalfFloat:function(e){Math.abs(e)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),e=In(e,-65504,65504),Fs.floatView[0]=e;const t=Fs.uint32View[0],n=t>>23&511;return Fs.baseTable[n]+((8388607&t)>>Fs.shiftTable[n])},fromHalfFloat:function(e){const t=e>>10;return Fs.uint32View[0]=Fs.mantissaTable[Fs.offsetTable[t]+(1023&e)]+Fs.exponentTable[t],Fs.floatView[0]}},Os=new ci,zs=new Fn;let Hs=0;class Vs{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:Hs++}),this.name="",this.array=e,this.itemSize=t,this.count=void 0!==e?e.length/t:0,this.normalized=n,this.usage=xn,this.updateRanges=[],this.gpuType=st,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,s=this.itemSize;i<s;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++)zs.fromBufferAttribute(this,t),zs.applyMatrix3(e),this.setXY(t,zs.x,zs.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=Bn(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=Ln(n,this.array)),this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=Bn(t,this.array)),t}setX(e,t){return this.normalized&&(t=Ln(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=Bn(t,this.array)),t}setY(e,t){return this.normalized&&(t=Ln(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=Bn(t,this.array)),t}setZ(e,t){return this.normalized&&(t=Ln(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=Bn(t,this.array)),t}setW(e,t){return this.normalized&&(t=Ln(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=Ln(t,this.array),n=Ln(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=Ln(t,this.array),n=Ln(n,this.array),i=Ln(i,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=i,this}setXYZW(e,t,n,i,s){return e*=this.itemSize,this.normalized&&(t=Ln(t,this.array),n=Ln(n,this.array),i=Ln(i,this.array),s=Ln(s,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=i,this.array[e+3]=s,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!==xn&&(e.usage=this.usage),e}}class Gs extends Vs{constructor(e,t,n){super(new Uint16Array(e),t,n)}}class Ws extends Vs{constructor(e,t,n){super(new Uint32Array(e),t,n)}}class js extends Vs{constructor(e,t,n){super(new Float32Array(e),t,n)}}let Xs=0;const qs=new Oi,Qs=new ds,Ks=new ci,Ys=new di,Zs=new di,Js=new ci;class $s extends Mn{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:Xs++}),this.uuid=Rn(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,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(On(e)?Ws:Gs)(e,1):this.index=e,this}setIndirect(e){return this.indirect=e,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 kn).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 qs.makeRotationFromQuaternion(e),this.applyMatrix4(qs),this}rotateX(e){return qs.makeRotationX(e),this.applyMatrix4(qs),this}rotateY(e){return qs.makeRotationY(e),this.applyMatrix4(qs),this}rotateZ(e){return qs.makeRotationZ(e),this.applyMatrix4(qs),this}translate(e,t,n){return qs.makeTranslation(e,t,n),this.applyMatrix4(qs),this}scale(e,t,n){return qs.makeScale(e,t,n),this.applyMatrix4(qs),this}lookAt(e){return Qs.lookAt(e),Qs.updateMatrix(),this.applyMatrix4(Qs.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Ks).negate(),this.translate(Ks.x,Ks.y,Ks.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 js(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&&console.warn("THREE.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 di);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),void this.boundingBox.set(new ci(-1/0,-1/0,-1/0),new ci(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];Ys.setFromBufferAttribute(e),this.morphTargetsRelative?(Js.addVectors(this.boundingBox.min,Ys.min),this.boundingBox.expandByPoint(Js),Js.addVectors(this.boundingBox.max,Ys.max),this.boundingBox.expandByPoint(Js)):(this.boundingBox.expandByPoint(Ys.min),this.boundingBox.expandByPoint(Ys.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error('THREE.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 Ii);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return console.error("THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),void this.boundingSphere.set(new ci,1/0);if(e){const n=this.boundingSphere.center;if(Ys.setFromBufferAttribute(e),t)for(let e=0,s=t.length;e<s;e++){const n=t[e];Zs.setFromBufferAttribute(n),this.morphTargetsRelative?(Js.addVectors(Ys.min,Zs.min),Ys.expandByPoint(Js),Js.addVectors(Ys.max,Zs.max),Ys.expandByPoint(Js)):(Ys.expandByPoint(Zs.min),Ys.expandByPoint(Zs.max))}Ys.getCenter(n);let i=0;for(let t=0,s=e.count;t<s;t++)Js.fromBufferAttribute(e,t),i=Math.max(i,n.distanceToSquared(Js));if(t)for(let s=0,r=t.length;s<r;s++){const r=t[s],a=this.morphTargetsRelative;for(let t=0,s=r.count;t<s;t++)Js.fromBufferAttribute(r,t),a&&(Ks.fromBufferAttribute(e,t),Js.add(Ks)),i=Math.max(i,n.distanceToSquared(Js))}this.boundingSphere.radius=Math.sqrt(i),isNaN(this.boundingSphere.radius)&&console.error('THREE.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 console.error("THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");const n=t.position,i=t.normal,s=t.uv;!1===this.hasAttribute("tangent")&&this.setAttribute("tangent",new Vs(new Float32Array(4*n.count),4));const r=this.getAttribute("tangent"),a=[],o=[];for(let b=0;b<n.count;b++)a[b]=new ci,o[b]=new ci;const l=new ci,c=new ci,h=new ci,u=new Fn,d=new Fn,p=new Fn,f=new ci,m=new ci;function g(e,t,i){l.fromBufferAttribute(n,e),c.fromBufferAttribute(n,t),h.fromBufferAttribute(n,i),u.fromBufferAttribute(s,e),d.fromBufferAttribute(s,t),p.fromBufferAttribute(s,i),c.sub(l),h.sub(l),d.sub(u),p.sub(u);const r=1/(d.x*p.y-p.x*d.y);isFinite(r)&&(f.copy(c).multiplyScalar(p.y).addScaledVector(h,-d.y).multiplyScalar(r),m.copy(h).multiplyScalar(d.x).addScaledVector(c,-p.x).multiplyScalar(r),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 v=this.groups;0===v.length&&(v=[{start:0,count:e.count}]);for(let b=0,M=v.length;b<M;++b){const t=v[b],n=t.start;for(let i=n,s=n+t.count;i<s;i+=3)g(e.getX(i+0),e.getX(i+1),e.getX(i+2))}const _=new ci,x=new ci,y=new ci,A=new ci;function S(e){y.fromBufferAttribute(i,e),A.copy(y);const t=a[e];_.copy(t),_.sub(y.multiplyScalar(y.dot(t))).normalize(),x.crossVectors(A,t);const n=x.dot(o[e])<0?-1:1;r.setXYZW(e,_.x,_.y,_.z,n)}for(let b=0,M=v.length;b<M;++b){const t=v[b],n=t.start;for(let i=n,s=n+t.count;i<s;i+=3)S(e.getX(i+0)),S(e.getX(i+1)),S(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 Vs(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 ci,s=new ci,r=new ci,a=new ci,o=new ci,l=new ci,c=new ci,h=new ci;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),s.fromBufferAttribute(t,p),r.fromBufferAttribute(t,f),c.subVectors(r,s),h.subVectors(i,s),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),s.fromBufferAttribute(t,e+1),r.fromBufferAttribute(t,e+2),c.subVectors(r,s),h.subVectors(i,s),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++)Js.fromBufferAttribute(e,t),Js.normalize(),e.setXYZ(t,Js.x,Js.y,Js.z)}toNonIndexed(){function e(e,t){const n=e.array,i=e.itemSize,s=e.normalized,r=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++)r[o++]=n[a++]}return new Vs(r,i,s)}if(null===this.index)return console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new $s,n=this.index.array,i=this.attributes;for(const a in i){const s=e(i[a],n);t.setAttribute(a,s)}const s=this.morphAttributes;for(const a in s){const i=[],r=s[a];for(let t=0,s=r.length;t<s;t++){const s=e(r[t],n);i.push(s)}t.morphAttributes[a]=i}t.morphTargetsRelative=this.morphTargetsRelative;const r=this.groups;for(let a=0,o=r.length;a<o;a++){const e=r[a];t.addGroup(e.start,e.count,e.materialIndex)}return t}toJSON(){const e={metadata:{version:4.6,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 s=!1;for(const o in this.morphAttributes){const t=this.morphAttributes[o],n=[];for(let i=0,s=t.length;i<s;i++){const s=t[i];n.push(s.toJSON(e.data))}n.length>0&&(i[o]=n,s=!0)}s&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);const r=this.groups;r.length>0&&(e.data.groups=JSON.parse(JSON.stringify(r)));const a=this.boundingSphere;return null!==a&&(e.data.boundingSphere={center:a.center.toArray(),radius:a.radius}),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(t));const i=e.attributes;for(const l in i){const e=i[l];this.setAttribute(l,e.clone(t))}const s=e.morphAttributes;for(const l in s){const e=[],n=s[l];for(let i=0,s=n.length;i<s;i++)e.push(n[i].clone(t));this.morphAttributes[l]=e}this.morphTargetsRelative=e.morphTargetsRelative;const r=e.groups;for(let l=0,c=r.length;l<c;l++){const e=r[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 er=new Oi,tr=new Ni,nr=new Ii,ir=new ci,sr=new ci,rr=new ci,ar=new ci,or=new ci,lr=new ci,cr=new ci,hr=new ci;class ur extends ds{constructor(e=new $s,t=new Us){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,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,s=n.morphAttributes.position,r=n.morphTargetsRelative;t.fromBufferAttribute(i,e);const a=this.morphTargetInfluences;if(s&&a){lr.set(0,0,0);for(let n=0,i=s.length;n<i;n++){const i=a[n],o=s[n];0!==i&&(or.fromBufferAttribute(o,e),r?lr.addScaledVector(or,i):lr.addScaledVector(or.sub(t),i))}t.add(lr)}return t}raycast(e,t){const n=this.geometry,i=this.material,s=this.matrixWorld;if(void 0!==i){if(null===n.boundingSphere&&n.computeBoundingSphere(),nr.copy(n.boundingSphere),nr.applyMatrix4(s),tr.copy(e.ray).recast(e.near),!1===nr.containsPoint(tr.origin)){if(null===tr.intersectSphere(nr,ir))return;if(tr.origin.distanceToSquared(ir)>(e.far-e.near)**2)return}er.copy(s).invert(),tr.copy(e.ray).applyMatrix4(er),null!==n.boundingBox&&!1===tr.intersectsBox(n.boundingBox)||this._computeIntersections(e,t,tr)}}_computeIntersections(e,t,n){let i;const s=this.geometry,r=this.material,a=s.index,o=s.attributes.position,l=s.attributes.uv,c=s.attributes.uv1,h=s.attributes.normal,u=s.groups,d=s.drawRange;if(null!==a)if(Array.isArray(r))for(let p=0,f=u.length;p<f;p++){const s=u[p],o=r[s.materialIndex];for(let r=Math.max(s.start,d.start),u=Math.min(a.count,Math.min(s.start+s.count,d.start+d.count));r<u;r+=3){i=dr(this,o,e,n,l,c,h,a.getX(r),a.getX(r+1),a.getX(r+2)),i&&(i.faceIndex=Math.floor(r/3),i.face.materialIndex=s.materialIndex,t.push(i))}}else{for(let s=Math.max(0,d.start),o=Math.min(a.count,d.start+d.count);s<o;s+=3){i=dr(this,r,e,n,l,c,h,a.getX(s),a.getX(s+1),a.getX(s+2)),i&&(i.faceIndex=Math.floor(s/3),t.push(i))}}else if(void 0!==o)if(Array.isArray(r))for(let p=0,f=u.length;p<f;p++){const s=u[p],a=r[s.materialIndex];for(let r=Math.max(s.start,d.start),u=Math.min(o.count,Math.min(s.start+s.count,d.start+d.count));r<u;r+=3){i=dr(this,a,e,n,l,c,h,r,r+1,r+2),i&&(i.faceIndex=Math.floor(r/3),i.face.materialIndex=s.materialIndex,t.push(i))}}else{for(let s=Math.max(0,d.start),a=Math.min(o.count,d.start+d.count);s<a;s+=3){i=dr(this,r,e,n,l,c,h,s,s+1,s+2),i&&(i.faceIndex=Math.floor(s/3),t.push(i))}}}}function dr(e,t,n,i,s,r,a,o,l,c){e.getVertexPosition(o,sr),e.getVertexPosition(l,rr),e.getVertexPosition(c,ar);const h=function(e,t,n,i,s,r,a,o){let l;if(l=1===t.side?i.intersectTriangle(a,r,s,!0,o):i.intersectTriangle(s,r,a,0===t.side,o),null===l)return null;hr.copy(o),hr.applyMatrix4(e.matrixWorld);const c=n.ray.origin.distanceTo(hr);return c<n.near||c>n.far?null:{distance:c,point:hr.clone(),object:e}}(e,t,n,i,sr,rr,ar,cr);if(h){const e=new ci;Ts.getBarycoord(cr,sr,rr,ar,e),s&&(h.uv=Ts.getInterpolatedAttribute(s,o,l,c,e,new Fn)),r&&(h.uv1=Ts.getInterpolatedAttribute(r,o,l,c,e,new Fn)),a&&(h.normal=Ts.getInterpolatedAttribute(a,o,l,c,e,new ci),h.normal.dot(i.direction)>0&&h.normal.multiplyScalar(-1));const t={a:o,b:l,c:c,normal:new ci,materialIndex:0};Ts.getNormal(sr,rr,ar,t.normal),h.face=t,h.barycoord=e}return h}class pr extends $s{constructor(e=1,t=1,n=1,i=1,s=1,r=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:n,widthSegments:i,heightSegments:s,depthSegments:r};const a=this;i=Math.floor(i),s=Math.floor(s),r=Math.floor(r);const o=[],l=[],c=[],h=[];let u=0,d=0;function p(e,t,n,i,s,r,p,f,m,g,v){const _=r/m,x=p/g,y=r/2,A=p/2,S=f/2,b=m+1,M=g+1;let w=0,T=0;const E=new ci;for(let a=0;a<M;a++){const r=a*x-A;for(let o=0;o<b;o++){const u=o*_-y;E[e]=u*i,E[t]=r*s,E[n]=S,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),s=u+(e+1)+b*a;o.push(t,n,s),o.push(n,i,s),T+=6}a.addGroup(d,T,v),d+=T,u+=w}p("z","y","x",-1,-1,n,t,e,r,s,0),p("z","y","x",1,-1,n,t,-e,r,s,1),p("x","z","y",1,1,e,n,t,i,r,2),p("x","z","y",1,-1,e,n,-t,i,r,3),p("x","y","z",1,-1,e,t,n,i,s,4),p("x","y","z",-1,-1,e,t,-n,i,s,5),this.setIndex(o),this.setAttribute("position",new js(l,3)),this.setAttribute("normal",new js(c,3)),this.setAttribute("uv",new js(h,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new pr(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}function fr(e){const t={};for(const n in e){t[n]={};for(const i in e[n]){const s=e[n][i];s&&(s.isColor||s.isMatrix3||s.isMatrix4||s.isVector2||s.isVector3||s.isVector4||s.isTexture||s.isQuaternion)?s.isRenderTargetTexture?(console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),t[n][i]=null):t[n][i]=s.clone():Array.isArray(s)?t[n][i]=s.slice():t[n][i]=s}}return t}function mr(e){const t={};for(let n=0;n<e.length;n++){const i=fr(e[n]);for(const e in i)t[e]=i[e]}return t}function gr(e){const t=e.getRenderTarget();return null===t?e.outputColorSpace:!0===t.isXRRenderTarget?t.texture.colorSpace:qn.workingColorSpace}const vr={clone:fr,merge:mr};class _r extends Ls{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=fr(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}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 xr extends ds{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Oi,this.projectionMatrix=new Oi,this.projectionMatrixInverse=new Oi,this.coordinateSystem=Sn}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 yr=new ci,Ar=new Fn,Sr=new Fn;class br extends xr{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*Cn*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(.5*En*this.fov);return.5*this.getFilmHeight()/e}getEffectiveFOV(){return 2*Cn*Math.atan(Math.tan(.5*En*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){yr.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(yr.x,yr.y).multiplyScalar(-e/yr.z),yr.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(yr.x,yr.y).multiplyScalar(-e/yr.z)}getViewSize(e,t){return this.getViewBounds(e,Ar,Sr),t.subVectors(Sr,Ar)}setViewOffset(e,t,n,i,s,r){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=s,this.view.height=r,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(.5*En*this.fov)/this.zoom,n=2*t,i=this.aspect*n,s=-.5*i;const r=this.view;if(null!==this.view&&this.view.enabled){const e=r.fullWidth,a=r.fullHeight;s+=r.offsetX*i/e,t-=r.offsetY*n/a,i*=r.width/e,n*=r.height/a}const a=this.filmOffset;0!==a&&(s+=e*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(s,s+i,t,t-n,e,this.far,this.coordinateSystem),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 Mr=-90;class wr extends ds{constructor(e,t,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new br(Mr,1,e,t);i.layers=this.layers,this.add(i);const s=new br(Mr,1,e,t);s.layers=this.layers,this.add(s);const r=new br(Mr,1,e,t);r.layers=this.layers,this.add(r);const a=new br(Mr,1,e,t);a.layers=this.layers,this.add(a);const o=new br(Mr,1,e,t);o.layers=this.layers,this.add(o);const l=new br(Mr,1,e,t);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[n,i,s,r,a,o]=t;for(const l of t)this.remove(l);if(e===Sn)n.up.set(0,1,0),n.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),s.up.set(0,0,-1),s.lookAt(0,1,0),r.up.set(0,0,1),r.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!==bn)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),s.up.set(0,0,1),s.lookAt(0,1,0),r.up.set(0,0,-1),r.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[s,r,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,s),e.setRenderTarget(n,1,i),e.render(t,r),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 Tr extends ni{constructor(e,t,n,i,s,r,a,o,l,c){super(e=void 0!==e?e:[],t=void 0!==t?t:ze,n,i,s,r,a,o,l,c),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class Er extends ri{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 Tr(i,t.mapping,t.wrapS,t.wrapT,t.magFilter,t.minFilter,t.format,t.type,t.anisotropy,t.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=void 0!==t.generateMipmaps&&t.generateMipmaps,this.texture.minFilter=void 0!==t.minFilter?t.minFilter:Ke}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 pr(5,5,5),s=new _r({name:"CubemapFromEquirect",uniforms:fr(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:1,blending:0});s.uniforms.tEquirect.value=t;const r=new ur(i,s),a=t.minFilter;t.minFilter===Ze&&(t.minFilter=Ke);return new wr(1,10,this).update(e,r),t.minFilter=a,r.geometry.dispose(),r.material.dispose(),this}clear(e,t,n,i){const s=e.getRenderTarget();for(let r=0;r<6;r++)e.setRenderTarget(this,r),e.clear(t,n,i);e.setRenderTarget(s)}}class Cr extends ds{constructor(){super(),this.isGroup=!0,this.type="Group"}}const Rr={type:"move"};class Ir{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return null===this._hand&&(this._hand=new Cr,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 Cr,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new ci,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new ci),this._targetRay}getGripSpace(){return null===this._grip&&(this._grip=new Cr,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new ci,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new ci),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,s=null,r=null;const a=this._targetRay,o=this._grip,l=this._hand;if(e&&"visible-blurred"!==t.session.visibilityState){if(l&&e.hand){r=!0;for(const r of e.hand.values()){const e=t.getJointPose(r,n),i=this._getHandJoint(l,r);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"],s=l.joints["thumb-tip"],a=i.position.distanceTo(s.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&&(s=t.getPose(e.gripSpace,n),null!==s&&(o.matrix.fromArray(s.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,s.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(s.linearVelocity)):o.hasLinearVelocity=!1,s.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(s.angularVelocity)):o.hasAngularVelocity=!1));null!==a&&(i=t.getPose(e.targetRaySpace,n),null===i&&null!==s&&(i=s),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(Rr)))}return null!==a&&(a.visible=null!==i),null!==o&&(o.visible=null!==s),null!==l&&(l.visible=null!==r),this}_getHandJoint(e,t){if(void 0===e.joints[t.jointName]){const n=new Cr;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}}class Dr extends ds{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 Ki,this.environmentIntensity=1,this.environmentRotation=new Ki,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 Pr{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=void 0!==e?e.length/t:0,this.usage=xn,this.updateRanges=[],this.version=0,this.uuid=Rn()}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,s=this.stride;i<s;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=Rn()),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=Rn()),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 Br=new ci;class Lr{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++)Br.fromBufferAttribute(this,t),Br.applyMatrix4(e),this.setXYZ(t,Br.x,Br.y,Br.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)Br.fromBufferAttribute(this,t),Br.applyNormalMatrix(e),this.setXYZ(t,Br.x,Br.y,Br.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)Br.fromBufferAttribute(this,t),Br.transformDirection(e),this.setXYZ(t,Br.x,Br.y,Br.z);return this}getComponent(e,t){let n=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(n=Bn(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=Ln(n,this.array)),this.data.array[e*this.data.stride+this.offset+t]=n,this}setX(e,t){return this.normalized&&(t=Ln(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=Ln(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=Ln(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=Ln(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=Bn(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=Bn(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=Bn(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=Bn(t,this.array)),t}setXY(e,t,n){return e=e*this.data.stride+this.offset,this.normalized&&(t=Ln(t,this.array),n=Ln(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=Ln(t,this.array),n=Ln(n,this.array),i=Ln(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,s){return e=e*this.data.stride+this.offset,this.normalized&&(t=Ln(t,this.array),n=Ln(n,this.array),i=Ln(i,this.array),s=Ln(s,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]=s,this}clone(e){if(void 0===e){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 Vs(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 Lr(e.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(void 0===e){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 Ur=new ci,Fr=new ii,kr=new ii,Nr=new ci,Or=new Oi,zr=new ci,Hr=new Ii,Vr=new Oi,Gr=new Ni;class Wr extends ur{constructor(e,t){super(e,t),this.isSkinnedMesh=!0,this.type="SkinnedMesh",this.bindMode=Oe,this.bindMatrix=new Oi,this.bindMatrixInverse=new Oi,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){const e=this.geometry;null===this.boundingBox&&(this.boundingBox=new di),this.boundingBox.makeEmpty();const t=e.getAttribute("position");for(let n=0;n<t.count;n++)this.getVertexPosition(n,zr),this.boundingBox.expandByPoint(zr)}computeBoundingSphere(){const e=this.geometry;null===this.boundingSphere&&(this.boundingSphere=new Ii),this.boundingSphere.makeEmpty();const t=e.getAttribute("position");for(let n=0;n<t.count;n++)this.getVertexPosition(n,zr),this.boundingSphere.expandByPoint(zr)}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(),Hr.copy(this.boundingSphere),Hr.applyMatrix4(i),!1!==e.ray.intersectsSphere(Hr)&&(Vr.copy(i).invert(),Gr.copy(e.ray).applyMatrix4(Vr),null!==this.boundingBox&&!1===Gr.intersectsBox(this.boundingBox)||this._computeIntersections(e,t,Gr)))}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 ii,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===Oe?this.bindMatrixInverse.copy(this.matrixWorld).invert():"detached"===this.bindMode?this.bindMatrixInverse.copy(this.bindMatrix).invert():console.warn("THREE.SkinnedMesh: Unrecognized bindMode: "+this.bindMode)}applyBoneTransform(e,t){const n=this.skeleton,i=this.geometry;Fr.fromBufferAttribute(i.attributes.skinIndex,e),kr.fromBufferAttribute(i.attributes.skinWeight,e),Ur.copy(t).applyMatrix4(this.bindMatrix),t.set(0,0,0);for(let s=0;s<4;s++){const e=kr.getComponent(s);if(0!==e){const i=Fr.getComponent(s);Or.multiplyMatrices(n.bones[i].matrixWorld,n.boneInverses[i]),t.addScaledVector(Nr.copy(Ur).applyMatrix4(Or),e)}}return t.applyMatrix4(this.bindMatrixInverse)}}class jr extends ds{constructor(){super(),this.isBone=!0,this.type="Bone"}}class Xr extends ni{constructor(e=null,t=1,n=1,i,s,r,a,o,l=1003,c=1003,h,u){super(null,r,a,o,l,c,i,s,h,u),this.isDataTexture=!0,this.image={data:e,width:t,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}const qr=new Oi,Qr=new Oi;class Kr{constructor(e=[],t=[]){this.uuid=Rn(),this.bones=e.slice(0),this.boneInverses=t,this.boneMatrices=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){console.warn("THREE.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 Oi)}}calculateInverses(){this.boneInverses.length=0;for(let e=0,t=this.bones.length;e<t;e++){const t=new Oi;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 s=0,r=e.length;s<r;s++){const i=e[s]?e[s].matrixWorld:Qr;qr.multiplyMatrices(i,t[s]),qr.toArray(n,16*s)}null!==i&&(i.needsUpdate=!0)}clone(){return new Kr(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 Xr(t,e,e,ht,st);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 s=t[i];void 0===s&&(console.warn("THREE.Skeleton: No bone found with UUID:",i),s=new jr),this.bones.push(s),this.boneInverses.push((new Oi).fromArray(e.boneInverses[n]))}return this.init(),this}toJSON(){const e={metadata:{version:4.6,type:"Skeleton",generator:"Skeleton.toJSON"},bones:[],boneInverses:[]};e.uuid=this.uuid;const t=this.bones,n=this.boneInverses;for(let i=0,s=t.length;i<s;i++){const s=t[i];e.bones.push(s.uuid);const r=n[i];e.boneInverses.push(r.toArray())}return e}}class Yr extends Vs{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 Zr=new Oi,Jr=new Oi,$r=[],ea=new di,ta=new Oi,na=new ur,ia=new Ii;class sa extends ur{constructor(e,t,n){super(e,t),this.isInstancedMesh=!0,this.instanceMatrix=new Yr(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,ta)}computeBoundingBox(){const e=this.geometry,t=this.count;null===this.boundingBox&&(this.boundingBox=new di),null===e.boundingBox&&e.computeBoundingBox(),this.boundingBox.makeEmpty();for(let n=0;n<t;n++)this.getMatrixAt(n,Zr),ea.copy(e.boundingBox).applyMatrix4(Zr),this.boundingBox.union(ea)}computeBoundingSphere(){const e=this.geometry,t=this.count;null===this.boundingSphere&&(this.boundingSphere=new Ii),null===e.boundingSphere&&e.computeBoundingSphere(),this.boundingSphere.makeEmpty();for(let n=0;n<t;n++)this.getMatrixAt(n,Zr),ia.copy(e.boundingSphere).applyMatrix4(Zr),this.boundingSphere.union(ia)}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,s=e*(n.length+1)+1;for(let r=0;r<n.length;r++)n[r]=i[s+r]}raycast(e,t){const n=this.matrixWorld,i=this.count;if(na.geometry=this.geometry,na.material=this.material,void 0!==na.material&&(null===this.boundingSphere&&this.computeBoundingSphere(),ia.copy(this.boundingSphere),ia.applyMatrix4(n),!1!==e.ray.intersectsSphere(ia)))for(let s=0;s<i;s++){this.getMatrixAt(s,Zr),Jr.multiplyMatrices(n,Zr),na.matrixWorld=Jr,na.raycast(e,$r);for(let e=0,n=$r.length;e<n;e++){const n=$r[e];n.instanceId=s,n.object=this,t.push(n)}$r.length=0}}setColorAt(e,t){null===this.instanceColor&&(this.instanceColor=new Yr(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 Xr(new Float32Array(i*this.count),i,this.count,pt,st));const s=this.morphTexture.source.data.data;let r=0;for(let l=0;l<n.length;l++)r+=n[l];const a=this.geometry.morphTargetsRelative?1:1-r,o=i*e;s[o]=a,s.set(n,o+1)}updateMorphTargets(){}dispose(){return this.dispatchEvent({type:"dispose"}),null!==this.morphTexture&&(this.morphTexture.dispose(),this.morphTexture=null),this}}const ra=new ci,aa=new ci,oa=new kn;class la{constructor(e=new ci(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=ra.subVectors(n,t).cross(aa.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(ra),i=this.normal.dot(n);if(0===i)return 0===this.distanceToPoint(e.start)?t.copy(e.start):null;const s=-(e.start.dot(this.normal)+this.constant)/i;return s<0||s>1?null:t.copy(e.start).addScaledVector(n,s)}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||oa.getNormalMatrix(e),i=this.coplanarPoint(ra).applyMatrix4(e),s=this.normal.applyMatrix3(n).normalize();return this.constant=-i.dot(s),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 ca=new Ii,ha=new ci;class ua{constructor(e=new la,t=new la,n=new la,i=new la,s=new la,r=new la){this.planes=[e,t,n,i,s,r]}set(e,t,n,i,s,r){const a=this.planes;return a[0].copy(e),a[1].copy(t),a[2].copy(n),a[3].copy(i),a[4].copy(s),a[5].copy(r),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){const n=this.planes,i=e.elements,s=i[0],r=i[1],a=i[2],o=i[3],l=i[4],c=i[5],h=i[6],u=i[7],d=i[8],p=i[9],f=i[10],m=i[11],g=i[12],v=i[13],_=i[14],x=i[15];if(n[0].setComponents(o-s,u-l,m-d,x-g).normalize(),n[1].setComponents(o+s,u+l,m+d,x+g).normalize(),n[2].setComponents(o+r,u+c,m+p,x+v).normalize(),n[3].setComponents(o-r,u-c,m-p,x-v).normalize(),n[4].setComponents(o-a,u-h,m-f,x-_).normalize(),t===Sn)n[5].setComponents(o+a,u+h,m+f,x+_).normalize();else{if(t!==bn)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);n[5].setComponents(a,h,f,_).normalize()}return this}intersectsObject(e){if(void 0!==e.boundingSphere)null===e.boundingSphere&&e.computeBoundingSphere(),ca.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;null===t.boundingSphere&&t.computeBoundingSphere(),ca.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(ca)}intersectsSprite(e){return ca.center.set(0,0,0),ca.radius=.7071067811865476,ca.applyMatrix4(e.matrixWorld),this.intersectsSphere(ca)}intersectsSphere(e){const t=this.planes,n=e.center,i=-e.radius;for(let s=0;s<6;s++){if(t[s].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(ha.x=i.normal.x>0?e.max.x:e.min.x,ha.y=i.normal.y>0?e.max.y:e.min.y,ha.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(ha)<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 da extends Ls{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new Ds(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 pa=new ci,fa=new ci,ma=new Oi,ga=new Ni,va=new Ii,_a=new ci,xa=new ci;class ya extends ds{constructor(e=new $s,t=new da){super(),this.isLine=!0,this.type="Line",this.geometry=e,this.material=t,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++)pa.fromBufferAttribute(t,e-1),fa.fromBufferAttribute(t,e),n[e]=n[e-1],n[e]+=pa.distanceTo(fa);e.setAttribute("lineDistance",new js(n,1))}else console.warn("THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}raycast(e,t){const n=this.geometry,i=this.matrixWorld,s=e.params.Line.threshold,r=n.drawRange;if(null===n.boundingSphere&&n.computeBoundingSphere(),va.copy(n.boundingSphere),va.applyMatrix4(i),va.radius+=s,!1===e.ray.intersectsSphere(va))return;ma.copy(i).invert(),ga.copy(e.ray).applyMatrix4(ma);const a=s/((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,r.start),i=Math.min(c.count,r.start+r.count);for(let s=n,r=i-1;s<r;s+=l){const n=c.getX(s),i=c.getX(s+1),r=Aa(this,e,ga,o,n,i,s);r&&t.push(r)}if(this.isLineLoop){const s=c.getX(i-1),r=c.getX(n),a=Aa(this,e,ga,o,s,r,i-1);a&&t.push(a)}}else{const n=Math.max(0,r.start),i=Math.min(h.count,r.start+r.count);for(let s=n,r=i-1;s<r;s+=l){const n=Aa(this,e,ga,o,s,s+1,s);n&&t.push(n)}if(this.isLineLoop){const s=Aa(this,e,ga,o,i-1,n,i-1);s&&t.push(s)}}}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 Aa(e,t,n,i,s,r,a){const o=e.geometry.attributes.position;pa.fromBufferAttribute(o,s),fa.fromBufferAttribute(o,r);if(n.distanceSqToSegment(pa,fa,_a,xa)>i)return;_a.applyMatrix4(e.matrixWorld);const l=t.ray.origin.distanceTo(_a);return l<t.near||l>t.far?void 0:{distance:l,point:xa.clone().applyMatrix4(e.matrixWorld),index:a,face:null,faceIndex:null,barycoord:null,object:e}}const Sa=new ci,ba=new ci;class Ma extends ya{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)Sa.fromBufferAttribute(t,e),ba.fromBufferAttribute(t,e+1),n[e]=0===e?0:n[e-1],n[e+1]=n[e]+Sa.distanceTo(ba);e.setAttribute("lineDistance",new js(n,1))}else console.warn("THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}}class wa extends ya{constructor(e,t){super(e,t),this.isLineLoop=!0,this.type="LineLoop"}}class Ta extends Ls{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new Ds(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 Ea=new Oi,Ca=new Ni,Ra=new Ii,Ia=new ci;class Da extends ds{constructor(e=new $s,t=new Ta){super(),this.isPoints=!0,this.type="Points",this.geometry=e,this.material=t,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,s=e.params.Points.threshold,r=n.drawRange;if(null===n.boundingSphere&&n.computeBoundingSphere(),Ra.copy(n.boundingSphere),Ra.applyMatrix4(i),Ra.radius+=s,!1===e.ray.intersectsSphere(Ra))return;Ea.copy(i).invert(),Ca.copy(e.ray).applyMatrix4(Ea);const a=s/((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,r.start),s=Math.min(l.count,r.start+r.count);n<s;n++){const s=l.getX(n);Ia.fromBufferAttribute(c,s),Pa(Ia,s,o,i,e,t,this)}}else{for(let n=Math.max(0,r.start),s=Math.min(c.count,r.start+r.count);n<s;n++)Ia.fromBufferAttribute(c,n),Pa(Ia,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 Pa(e,t,n,i,s,r,a){const o=Ca.distanceSqToPoint(e);if(o<n){const n=new ci;Ca.closestPointToPoint(e,n),n.applyMatrix4(i);const l=s.ray.origin.distanceTo(n);if(l<s.near||l>s.far)return;r.push({distance:l,distanceToRay:Math.sqrt(o),point:n,index:t,face:null,faceIndex:null,barycoord:null,object:a})}}class Ba extends ni{constructor(e,t,n,i,s,r,a,o,l,c=1026){if(c!==ut&&c!==dt)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");void 0===n&&c===ut&&(n=it),void 0===n&&c===dt&&(n=lt),super(null,i,s,r,a,o,c,n,l),this.isDepthTexture=!0,this.image={width:e,height:t},this.magFilter=void 0!==a?a:Xe,this.minFilter=void 0!==o?o:Xe,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return null!==this.compareFunction&&(t.compareFunction=this.compareFunction),t}}class La extends $s{constructor(e=1,t=1,n=1,i=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:n,heightSegments:i};const s=e/2,r=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-r;for(let t=0;t<l;t++){const n=t*h-s;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),s=e+1+l*g;d.push(t,n,s),d.push(n,i,s)}this.setIndex(d),this.setAttribute("position",new js(p,3)),this.setAttribute("normal",new js(f,3)),this.setAttribute("uv",new js(m,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new La(e.width,e.height,e.widthSegments,e.heightSegments)}}class Ua extends Ls{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new Ds(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 Ds(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Fn(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 Ki,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 Fa extends Ua{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 Fn(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return In(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 Ds(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 Ds(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new Ds(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 ka extends Ls{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 Na extends Ls{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 Oa(e,t,n){return!e||!n&&e.constructor===t?e:"number"==typeof t.BYTES_PER_ELEMENT?new t(e):Array.prototype.slice.call(e)}function za(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 Ha(e,t,n){const i=e.length,s=new e.constructor(i);for(let r=0,a=0;a!==i;++r){const i=n[r]*t;for(let n=0;n!==t;++n)s[a++]=e[i+n]}return s}function Va(e,t,n,i){let s=1,r=e[0];for(;void 0!==r&&void 0===r[i];)r=e[s++];if(void 0===r)return;let a=r[i];if(void 0!==a)if(Array.isArray(a))do{a=r[i],void 0!==a&&(t.push(r.time),n.push.apply(n,a)),r=e[s++]}while(void 0!==r);else if(void 0!==a.toArray)do{a=r[i],void 0!==a&&(t.push(r.time),a.toArray(n,n.length)),r=e[s++]}while(void 0!==r);else do{a=r[i],void 0!==a&&(t.push(r.time),n.push(a)),r=e[s++]}while(void 0!==r)}class Ga{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],s=t[n-1];e:{t:{let r;n:{i:if(!(e<i)){for(let r=n+2;;){if(void 0===i){if(e<s)break i;return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}if(n===r)break;if(s=i,i=t[++n],e<i)break t}r=t.length;break n}if(!(e>=s)){const a=t[1];e<a&&(n=2,s=a);for(let r=n-2;;){if(void 0===s)return this._cachedIndex=0,this.copySampleValue_(0);if(n===r)break;if(i=s,s=t[--n-1],e>=s)break t}r=n,n=0;break n}break e}for(;n<r;){const i=n+r>>>1;e<t[i]?r=i:n=i+1}if(i=t[n],s=t[n-1],void 0===s)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,s,i)}return this.interpolate_(n,s,e,i)}getSettings_(){return this.settings||this.DefaultSettings_}copySampleValue_(e){const t=this.resultBuffer,n=this.sampleValues,i=this.valueSize,s=e*i;for(let r=0;r!==i;++r)t[r]=n[s+r];return t}interpolate_(){throw new Error("call to abstract method")}intervalChanged_(){}}class Wa extends Ga{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:en,endingEnd:en}}intervalChanged_(e,t,n){const i=this.parameterPositions;let s=e-2,r=e+1,a=i[s],o=i[r];if(void 0===a)switch(this.getSettings_().endingStart){case tn:s=e,a=2*t-n;break;case nn:s=i.length-2,a=t+i[s]-i[s+1];break;default:s=e,a=n}if(void 0===o)switch(this.getSettings_().endingEnd){case tn:r=e,o=2*n-t;break;case nn:r=1,o=n+i[1]-i[0];break;default:r=e-1,o=t}const l=.5*(n-t),c=this.valueSize;this._weightPrev=l/(t-a),this._weightNext=l/(o-n),this._offsetPrev=s*c,this._offsetNext=r*c}interpolate_(e,t,n,i){const s=this.resultBuffer,r=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,v=(1+u)*m+(-1.5-2*u)*f+(-.5+u)*p+1,_=(-1-d)*m+(1.5+d)*f+.5*p,x=d*m-d*f;for(let y=0;y!==a;++y)s[y]=g*r[c+y]+v*r[l+y]+_*r[o+y]+x*r[h+y];return s}}class ja extends Ga{constructor(e,t,n,i){super(e,t,n,i)}interpolate_(e,t,n,i){const s=this.resultBuffer,r=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)s[u]=r[l+u]*h+r[o+u]*c;return s}}class Xa extends Ga{constructor(e,t,n,i){super(e,t,n,i)}interpolate_(e){return this.copySampleValue_(e-1)}}class qa{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=Oa(t,this.TimeBufferType),this.values=Oa(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:Oa(e.times,Array),values:Oa(e.values,Array)};const t=e.getInterpolation();t!==e.DefaultInterpolation&&(n.interpolation=t)}return n.type=e.ValueTypeName,n}InterpolantFactoryMethodDiscrete(e){return new Xa(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodLinear(e){return new ja(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodSmooth(e){return new Wa(this.times,this.values,this.getValueSize(),e)}setInterpolation(e){let t;switch(e){case Zt:t=this.InterpolantFactoryMethodDiscrete;break;case Jt:t=this.InterpolantFactoryMethodLinear;break;case $t: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 console.warn("THREE.KeyframeTrack:",t),this}return this.createInterpolant=t,this}getInterpolation(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return Zt;case this.InterpolantFactoryMethodLinear:return Jt;case this.InterpolantFactoryMethodSmooth:return $t}}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 s=0,r=i-1;for(;s!==i&&n[s]<e;)++s;for(;-1!==r&&n[r]>t;)--r;if(++r,0!==s||r!==i){s>=r&&(r=Math.max(r,1),s=r-1);const e=this.getValueSize();this.times=n.slice(s,r),this.values=this.values.slice(s*e,r*e)}return this}validate(){let e=!0;const t=this.getValueSize();t-Math.floor(t)!==0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),e=!1);const n=this.times,i=this.values,s=n.length;0===s&&(console.error("THREE.KeyframeTrack: Track is empty.",this),e=!1);let r=null;for(let o=0;o!==s;o++){const t=n[o];if("number"==typeof t&&isNaN(t)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,o,t),e=!1;break}if(null!==r&&r>t){console.error("THREE.KeyframeTrack: Out of order keys.",this,o,t,r),e=!1;break}r=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)){console.error("THREE.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()===$t,s=e.length-1;let r=1;for(let a=1;a<s;++a){let s=!1;const o=e[a];if(o!==e[a+1]&&(1!==a||o!==e[0]))if(i)s=!0;else{const e=a*n,i=e-n,r=e+n;for(let a=0;a!==n;++a){const n=t[e+a];if(n!==t[i+a]||n!==t[r+a]){s=!0;break}}}if(s){if(a!==r){e[r]=e[a];const i=a*n,s=r*n;for(let e=0;e!==n;++e)t[s+e]=t[i+e]}++r}}if(s>0){e[r]=e[s];for(let e=s*n,i=r*n,a=0;a!==n;++a)t[i+a]=t[e+a];++r}return r!==e.length?(this.times=e.slice(0,r),this.values=t.slice(0,r*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}}qa.prototype.TimeBufferType=Float32Array,qa.prototype.ValueBufferType=Float32Array,qa.prototype.DefaultInterpolation=Jt;class Qa extends qa{constructor(e,t,n){super(e,t,n)}}Qa.prototype.ValueTypeName="bool",Qa.prototype.ValueBufferType=Array,Qa.prototype.DefaultInterpolation=Zt,Qa.prototype.InterpolantFactoryMethodLinear=void 0,Qa.prototype.InterpolantFactoryMethodSmooth=void 0;class Ka extends qa{}Ka.prototype.ValueTypeName="color";class Ya extends qa{}Ya.prototype.ValueTypeName="number";class Za extends Ga{constructor(e,t,n,i){super(e,t,n,i)}interpolate_(e,t,n,i){const s=this.resultBuffer,r=this.sampleValues,a=this.valueSize,o=(n-t)/(i-t);let l=e*a;for(let c=l+a;l!==c;l+=4)li.slerpFlat(s,0,r,l-a,r,l,o);return s}}class Ja extends qa{InterpolantFactoryMethodLinear(e){return new Za(this.times,this.values,this.getValueSize(),e)}}Ja.prototype.ValueTypeName="quaternion",Ja.prototype.InterpolantFactoryMethodSmooth=void 0;class $a extends qa{constructor(e,t,n){super(e,t,n)}}$a.prototype.ValueTypeName="string",$a.prototype.ValueBufferType=Array,$a.prototype.DefaultInterpolation=Zt,$a.prototype.InterpolantFactoryMethodLinear=void 0,$a.prototype.InterpolantFactoryMethodSmooth=void 0;class eo extends qa{}eo.prototype.ValueTypeName="vector";class to{constructor(e="",t=-1,n=[],i=2500){this.name=e,this.tracks=n,this.duration=t,this.blendMode=i,this.uuid=Rn(),this.duration<0&&this.resetDuration()}static parse(e){const t=[],n=e.tracks,i=1/(e.fps||1);for(let r=0,a=n.length;r!==a;++r)t.push(no(n[r]).scale(i));const s=new this(e.name,e.duration,t,e.blendMode);return s.uuid=e.uuid,s}static toJSON(e){const t=[],n=e.tracks,i={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode};for(let s=0,r=n.length;s!==r;++s)t.push(qa.toJSON(n[s]));return i}static CreateFromMorphTargetSequence(e,t,n,i){const s=t.length,r=[];for(let a=0;a<s;a++){let e=[],o=[];e.push((a+s-1)%s,a,(a+1)%s),o.push(0,1,0);const l=za(e);e=Ha(e,1,l),o=Ha(o,1,l),i||0!==e[0]||(e.push(s),o.push(o[0])),r.push(new Ya(".morphTargetInfluences["+t[a].name+"]",e,o).scale(1/n))}return new this(e,-1,r)}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={},s=/^([\w-]*?)([\d]+)$/;for(let a=0,o=e.length;a<o;a++){const t=e[a],n=t.name.match(s);if(n&&n.length>1){const e=n[1];let s=i[e];s||(i[e]=s=[]),s.push(t)}}const r=[];for(const a in i)r.push(this.CreateFromMorphTargetSequence(a,i[a],t,n));return r}static parseAnimation(e,t){if(!e)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;const n=function(e,t,n,i,s){if(0!==n.length){const r=[],a=[];Va(n,r,a,i),0!==r.length&&s.push(new e(t,r,a))}},i=[],s=e.name||"default",r=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 s in t){const t=[],r=[];for(let i=0;i!==e[n].morphTargets.length;++i){const i=e[n];t.push(i.time),r.push(i.morphTarget===s?1:0)}i.push(new Ya(".morphTargetInfluence["+s+"]",t,r))}o=t.length*r}else{const s=".bones["+t[c].name+"]";n(eo,s+".position",e,"pos",i),n(Ja,s+".quaternion",e,"rot",i),n(eo,s+".scale",e,"scl",i)}}if(0===i.length)return null;return new this(s,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 t=0;t<this.tracks.length;t++)e.push(this.tracks[t].clone());return new this.constructor(this.name,this.duration,e,this.blendMode)}toJSON(){return this.constructor.toJSON(this)}}function no(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 Ya;case"vector":case"vector2":case"vector3":case"vector4":return eo;case"color":return Ka;case"quaternion":return Ja;case"bool":case"boolean":return Qa;case"string":return $a}throw new Error("THREE.KeyframeTrack: Unsupported typeName: "+e)}(e.type);if(void 0===e.times){const t=[],n=[];Va(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 so{constructor(e,t,n){const i=this;let s,r=!1,a=0,o=0;const l=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=n,this.itemStart=function(e){o++,!1===r&&void 0!==i.onStart&&i.onStart(e,a,o),r=!0},this.itemEnd=function(e){a++,void 0!==i.onProgress&&i.onProgress(e,a,o),a===o&&(r=!1,void 0!==i.onLoad&&i.onLoad())},this.itemError=function(e){void 0!==i.onError&&i.onError(e)},this.resolveURL=function(e){return s?s(e):e},this.setURLModifier=function(e){return s=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}}}const ro=new so;class ao{constructor(e){this.manager=void 0!==e?e:ro,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={}}load(){}loadAsync(e,t){const n=this;return new Promise(function(i,s){n.load(e,i,t,s)})}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}}ao.DEFAULT_MATERIAL_NAME="__DEFAULT";const oo={};class lo extends Error{constructor(e,t){super(e),this.response=t}}class co extends ao{constructor(e){super(e)}load(e,t,n,i){void 0===e&&(e=""),void 0!==this.path&&(e=this.path+e),e=this.manager.resolveURL(e);const s=io.get(e);if(void 0!==s)return this.manager.itemStart(e),setTimeout(()=>{t&&t(s),this.manager.itemEnd(e)},0),s;if(void 0!==oo[e])return void oo[e].push({onLoad:t,onProgress:n,onError:i});oo[e]=[],oo[e].push({onLoad:t,onProgress:n,onError:i});const r=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),a=this.mimeType,o=this.responseType;fetch(r).then(t=>{if(200===t.status||0===t.status){if(0===t.status&&console.warn("THREE.FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===t.body||void 0===t.body.getReader)return t;const n=oo[e],i=t.body.getReader(),s=t.headers.get("X-File-Size")||t.headers.get("Content-Length"),r=s?parseInt(s):0,a=0!==r;let o=0;const l=new ReadableStream({start(e){!function t(){i.read().then(({done:i,value:s})=>{if(i)e.close();else{o+=s.byteLength;const i=new ProgressEvent("progress",{lengthComputable:a,loaded:o,total:r});for(let e=0,t=n.length;e<t;e++){const t=n[e];t.onProgress&&t.onProgress(i)}e.enqueue(s),t()}},t=>{e.error(t)})}()}});return new Response(l)}throw new lo(`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(void 0===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(e,t);const n=oo[e];delete oo[e];for(let e=0,i=n.length;e<i;e++){const i=n[e];i.onLoad&&i.onLoad(t)}}).catch(t=>{const n=oo[e];if(void 0===n)throw this.manager.itemError(e),t;delete oo[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}}class ho extends ao{constructor(e){super(e)}load(e,t,n,i){void 0!==this.path&&(e=this.path+e),e=this.manager.resolveURL(e);const s=this,r=io.get(e);if(void 0!==r)return s.manager.itemStart(e),setTimeout(function(){t&&t(r),s.manager.itemEnd(e)},0),r;const a=zn("img");function o(){c(),io.add(e,this),t&&t(this),s.manager.itemEnd(e)}function l(t){c(),i&&i(t),s.manager.itemError(e),s.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),s.manager.itemStart(e),a.src=e,a}}class uo extends ao{constructor(e){super(e)}load(e,t,n,i){const s=new ni,r=new ho(this.manager);return r.setCrossOrigin(this.crossOrigin),r.setPath(this.path),r.load(e,function(e){s.image=e,s.needsUpdate=!0,void 0!==t&&t(s)},n,i),s}}class po extends ds{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new Ds(e),this.intensity=t}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,void 0!==this.groundColor&&(t.object.groundColor=this.groundColor.getHex()),void 0!==this.distance&&(t.object.distance=this.distance),void 0!==this.angle&&(t.object.angle=this.angle),void 0!==this.decay&&(t.object.decay=this.decay),void 0!==this.penumbra&&(t.object.penumbra=this.penumbra),void 0!==this.shadow&&(t.object.shadow=this.shadow.toJSON()),void 0!==this.target&&(t.object.target=this.target.uuid),t}}const fo=new Oi,mo=new ci,go=new ci;class vo{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new Fn(512,512),this.map=null,this.mapPass=null,this.matrix=new Oi,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new ua,this._frameExtents=new Fn(1,1),this._viewportCount=1,this._viewports=[new ii(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){const t=this.camera,n=this.matrix;mo.setFromMatrixPosition(e.matrixWorld),t.position.copy(mo),go.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(go),t.updateMatrixWorld(),fo.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(fo),n.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),n.multiply(fo)}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.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 _o extends vo{constructor(){super(new br(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1}updateMatrices(e){const t=this.camera,n=2*Cn*e.angle*this.focus,i=this.mapSize.width/this.mapSize.height,s=e.distance||t.far;n===t.fov&&i===t.aspect&&s===t.far||(t.fov=n,t.aspect=i,t.far=s,t.updateProjectionMatrix()),super.updateMatrices(e)}copy(e){return super.copy(e),this.focus=e.focus,this}}class xo extends po{constructor(e,t,n=0,i=Math.PI/3,s=0,r=2){super(e,t),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(ds.DEFAULT_UP),this.updateMatrix(),this.target=new ds,this.distance=n,this.angle=i,this.penumbra=s,this.decay=r,this.map=null,this.shadow=new _o}get power(){return this.intensity*Math.PI}set power(e){this.intensity=e/Math.PI}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.shadow=e.shadow.clone(),this}}const yo=new Oi,Ao=new ci,So=new ci;class bo extends vo{constructor(){super(new br(90,1,.5,500)),this.isPointLightShadow=!0,this._frameExtents=new Fn(4,2),this._viewportCount=6,this._viewports=[new ii(2,1,1,1),new ii(0,1,1,1),new ii(3,1,1,1),new ii(1,1,1,1),new ii(3,0,1,1),new ii(1,0,1,1)],this._cubeDirections=[new ci(1,0,0),new ci(-1,0,0),new ci(0,0,1),new ci(0,0,-1),new ci(0,1,0),new ci(0,-1,0)],this._cubeUps=[new ci(0,1,0),new ci(0,1,0),new ci(0,1,0),new ci(0,1,0),new ci(0,0,1),new ci(0,0,-1)]}updateMatrices(e,t=0){const n=this.camera,i=this.matrix,s=e.distance||n.far;s!==n.far&&(n.far=s,n.updateProjectionMatrix()),Ao.setFromMatrixPosition(e.matrixWorld),n.position.copy(Ao),So.copy(n.position),So.add(this._cubeDirections[t]),n.up.copy(this._cubeUps[t]),n.lookAt(So),n.updateMatrixWorld(),i.makeTranslation(-Ao.x,-Ao.y,-Ao.z),yo.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse),this._frustum.setFromProjectionMatrix(yo)}}class Mo extends po{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 bo}get power(){return 4*this.intensity*Math.PI}set power(e){this.intensity=e/(4*Math.PI)}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}}class wo extends xr{constructor(e=-1,t=1,n=1,i=-1,s=.1,r=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=s,this.far=r,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,s,r){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=s,this.view.height=r,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 s=n-e,r=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;s+=e*this.view.offsetX,r=s+e*this.view.width,a-=t*this.view.offsetY,o=a-t*this.view.height}this.projectionMatrix.makeOrthographic(s,r,a,o,this.near,this.far,this.coordinateSystem),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 To extends vo{constructor(){super(new wo(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class Eo extends po{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(ds.DEFAULT_UP),this.updateMatrix(),this.target=new ds,this.shadow=new To}dispose(){this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}}class Co{static decodeText(e){if(console.warn("THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead."),"undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let i=0,s=e.length;i<s;i++)t+=String.fromCharCode(e[i]);try{return decodeURIComponent(escape(t))}catch(n){return t}}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 Ro extends $s{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}}class Io extends ao{constructor(e){super(e),this.isImageBitmapLoader=!0,"undefined"==typeof createImageBitmap&&console.warn("THREE.ImageBitmapLoader: createImageBitmap() not supported."),"undefined"==typeof fetch&&console.warn("THREE.ImageBitmapLoader: fetch() not supported."),this.options={premultiplyAlpha:"none"}}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 s=this,r=io.get(e);if(void 0!==r)return s.manager.itemStart(e),r.then?void r.then(n=>{t&&t(n),s.manager.itemEnd(e)}).catch(e=>{i&&i(e)}):(setTimeout(function(){t&&t(r),s.manager.itemEnd(e)},0),r);const a={};a.credentials="anonymous"===this.crossOrigin?"same-origin":"include",a.headers=this.requestHeader;const o=fetch(e,a).then(function(e){return e.blob()}).then(function(e){return createImageBitmap(e,Object.assign(s.options,{colorSpaceConversion:"none"}))}).then(function(n){return io.add(e,n),t&&t(n),s.manager.itemEnd(e),n}).catch(function(t){i&&i(t),io.remove(e),s.manager.itemError(e),s.manager.itemEnd(e)});io.add(e,o),s.manager.itemStart(e)}}class Do extends br{constructor(e=[]){super(),this.isArrayCamera=!0,this.cameras=e,this.index=0}}class Po{constructor(e=!0){this.autoStart=e,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=Bo(),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=Bo();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}}function Bo(){return performance.now()}class Lo{constructor(e,t,n){let i,s,r;switch(this.binding=e,this.valueSize=n,t){case"quaternion":i=this._slerp,s=this._slerpAdditive,r=this._setAdditiveIdentityQuaternion,this.buffer=new Float64Array(6*n),this._workIndex=5;break;case"string":case"bool":i=this._select,s=this._select,r=this._setAdditiveIdentityOther,this.buffer=new Array(5*n);break;default:i=this._lerp,s=this._lerpAdditive,r=this._setAdditiveIdentityNumeric,this.buffer=new Float64Array(5*n)}this._mixBufferRegion=i,this._mixBufferRegionAdditive=s,this._setIdentity=r,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,s=e*i+i;let r=this.cumulativeWeight;if(0===r){for(let e=0;e!==i;++e)n[s+e]=n[e];r=t}else{r+=t;const e=t/r;this._mixBufferRegion(n,s,0,e,i)}this.cumulativeWeight=r}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,s=this.cumulativeWeight,r=this.cumulativeWeightAdditive,a=this.binding;if(this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,s<1){const e=t*this._origIndex;this._mixBufferRegion(n,i,e,1-s,t)}r>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 s=n,r=i;s!==r;++s)t[s]=t[i+s%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,s){if(i>=.5)for(let r=0;r!==s;++r)e[t+r]=e[n+r]}_slerp(e,t,n,i){li.slerpFlat(e,t,e,t,e,n,i)}_slerpAdditive(e,t,n,i,s){const r=this._workIndex*s;li.multiplyQuaternionsFlat(e,r,e,t,e,n),li.slerpFlat(e,t,e,t,e,r,i)}_lerp(e,t,n,i,s){const r=1-i;for(let a=0;a!==s;++a){const s=t+a;e[s]=e[s]*r+e[n+a]*i}}_lerpAdditive(e,t,n,i,s){for(let r=0;r!==s;++r){const s=t+r;e[s]=e[s]+e[n+r]*i}}}const Uo="\\[\\]\\.:\\/",Fo=new RegExp("["+Uo+"]","g"),ko="[^"+Uo+"]",No="[^"+Uo.replace("\\.","")+"]",Oo=new RegExp("^"+/((?:WC+[\/:])*)/.source.replace("WC",ko)+/(WCOD+)?/.source.replace("WCOD",No)+/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",ko)+/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",ko)+"$"),zo=["material","materials","bones","map"];class Ho{constructor(e,t,n){this.path=t,this.parsedPath=n||Ho.parseTrackName(t),this.node=Ho.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 Ho.Composite(e,t,n):new Ho(e,t,n)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(Fo,"")}static parseTrackName(e){const t=Oo.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!==zo.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 s=e[i];if(s.name===t||s.uuid===t)return s;const r=n(s.children);if(r)return r}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,s=n.length;i!==s;++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,s=n.length;i!==s;++i)n[i]=e[t++]}_setValue_array_setNeedsUpdate(e,t){const n=this.resolvedProperty;for(let i=0,s=n.length;i!==s;++i)n[i]=e[t++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate(e,t){const n=this.resolvedProperty;for(let i=0,s=n.length;i!==s;++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 s=t.propertyIndex;if(e||(e=Ho.findNode(this.rootNode,t.nodeName),this.node=e),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!e)return void console.warn("THREE.PropertyBinding: No target node found for track: "+this.path+".");if(n){let i=t.objectIndex;switch(n){case"materials":if(!e.material)return void console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.",this);if(!e.material.materials)return void console.error("THREE.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 console.error("THREE.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 console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.",this);if(!e.material.map)return void console.error("THREE.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 console.error("THREE.PropertyBinding: Can not bind to objectName of node undefined.",this);e=e[n]}if(void 0!==i){if(void 0===e[i])return void console.error("THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.",this,e);e=e[i]}}const r=e[i];if(void 0===r){const n=t.nodeName;return void console.error("THREE.PropertyBinding: Trying to update property for track: "+n+"."+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!==s){if("morphTargetInfluences"===i){if(!e.geometry)return void console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.",this);if(!e.geometry.morphAttributes)return void console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.",this);void 0!==e.morphTargetDictionary[s]&&(s=e.morphTargetDictionary[s])}o=this.BindingType.ArrayElement,this.resolvedProperty=r,this.propertyIndex=s}else void 0!==r.fromArray&&void 0!==r.toArray?(o=this.BindingType.HasFromToArray,this.resolvedProperty=r):Array.isArray(r)?(o=this.BindingType.EntireArray,this.resolvedProperty=r):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}}Ho.Composite=class{constructor(e,t,n){const i=n||Ho.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_,s=n.length;i!==s;++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()}},Ho.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},Ho.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2},Ho.prototype.GetterByBindingType=[Ho.prototype._getValue_direct,Ho.prototype._getValue_array,Ho.prototype._getValue_arrayElement,Ho.prototype._getValue_toArray],Ho.prototype.SetterByBindingTypeAndVersioning=[[Ho.prototype._setValue_direct,Ho.prototype._setValue_direct_setNeedsUpdate,Ho.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[Ho.prototype._setValue_array,Ho.prototype._setValue_array_setNeedsUpdate,Ho.prototype._setValue_array_setMatrixWorldNeedsUpdate],[Ho.prototype._setValue_arrayElement,Ho.prototype._setValue_arrayElement_setNeedsUpdate,Ho.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[Ho.prototype._setValue_fromArray,Ho.prototype._setValue_fromArray_setNeedsUpdate,Ho.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];class Vo{constructor(e,t,n=null,i=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=n,this.blendMode=i;const s=t.tracks,r=s.length,a=new Array(r),o={endingStart:en,endingEnd:en};for(let l=0;l!==r;++l){const e=s[l].createInterpolant(null);a[l]=e,e.settings=o}this._interpolantSettings=o,this._interpolants=a,this._propertyBindings=new Array(r),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=Yt,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){if(e.fadeOut(t),this.fadeIn(t),n){const n=this._clip.duration,i=e._clip.duration,s=i/n,r=n/i;e.warp(1,s,t),this.warp(r,1,t)}return this}crossFadeTo(e,t,n){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,s=i.time,r=this.timeScale;let a=this._timeScaleInterpolant;null===a&&(a=i._lendControlInterpolant(),this._timeScaleInterpolant=a);const o=a.parameterPositions,l=a.sampleValues;return o[0]=s,o[1]=s+n,l[0]=e/r,l[1]=t/r,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 s=this._startTime;if(null!==s){const i=(e-s)*n;i<0||0===n?t=0:(this._startTime=null,t=n*i)}t*=this._updateTimeScale(e);const r=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(r),t[n].accumulateAdditive(a);else for(let n=0,s=e.length;n!==s;++n)e[n].evaluate(r),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,s=this._loopCount;const r=2202===n;if(0===e)return-1===s||!r||1&~s?i:t-i;if(n===Kt){-1===s&&(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===s&&(e>=0?(s=0,this._setEndings(!0,0===this.repetitions,r)):this._setEndings(0===this.repetitions,!0,r)),i>=t||i<0){const n=Math.floor(i/t);i-=t*n,s+=Math.abs(n);const a=this.repetitions-s;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,r)}else this._setEndings(!1,!1,r);this._loopCount=s,this.time=i,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:n})}}else this.time=i;if(r&&!(1&~s))return t-i}return i}_setEndings(e,t,n){const i=this._interpolantSettings;n?(i.endingStart=tn,i.endingEnd=tn):(i.endingStart=e?this.zeroSlopeAtStart?tn:en:nn,i.endingEnd=t?this.zeroSlopeAtEnd?tn:en:nn)}_scheduleFading(e,t,n){const i=this._mixer,s=i.time;let r=this._weightInterpolant;null===r&&(r=i._lendControlInterpolant(),this._weightInterpolant=r);const a=r.parameterPositions,o=r.sampleValues;return a[0]=s,o[0]=t,a[1]=s+e,o[1]=n,this}}const Go=new Float32Array(1);class Wo extends Mn{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,s=i.length,r=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!==s;++h){const e=i[h],s=e.name;let l=c[s];if(void 0!==l)++l.referenceCount,r[h]=l;else{if(l=r[h],void 0!==l){null===l._cacheIndex&&(++l.referenceCount,this._addInactiveBinding(l,o,s));continue}const i=t&&t._propertyBindings[h].binding.parsedPath;l=new Lo(Ho.create(n,s,i),e.ValueTypeName,e.getValueSize()),++l.referenceCount,this._addInactiveBinding(l,o,s),r[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,s=this._actionsByClip;let r=s[t];if(void 0===r)r={knownActions:[e],actionByRoot:{}},e._byClipCacheIndex=0,s[t]=r;else{const t=r.knownActions;e._byClipCacheIndex=t.length,t.push(e)}e._cacheIndex=i.length,i.push(e),r.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 s=e._clip.uuid,r=this._actionsByClip,a=r[s],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 r[s],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++,s=t[i];e._cacheIndex=i,t[i]=e,s._cacheIndex=n,t[n]=s}_takeBackAction(e){const t=this._actions,n=e._cacheIndex,i=--this._nActiveActions,s=t[i];e._cacheIndex=i,t[i]=e,s._cacheIndex=n,t[n]=s}_addInactiveBinding(e,t,n){const i=this._bindingsByRootAndName,s=this._bindings;let r=i[t];void 0===r&&(r={},i[t]=r),r[n]=e,e._cacheIndex=s.length,s.push(e)}_removeInactiveBinding(e){const t=this._bindings,n=e.binding,i=n.rootNode.uuid,s=n.path,r=this._bindingsByRootAndName,a=r[i],o=t[t.length-1],l=e._cacheIndex;o._cacheIndex=l,t[l]=o,t.pop(),delete a[s],0===Object.keys(a).length&&delete r[i]}_lendBinding(e){const t=this._bindings,n=e._cacheIndex,i=this._nActiveBindings++,s=t[i];e._cacheIndex=i,t[i]=e,s._cacheIndex=n,t[n]=s}_takeBackBinding(e){const t=this._bindings,n=e._cacheIndex,i=--this._nActiveBindings,s=t[i];e._cacheIndex=i,t[i]=e,s._cacheIndex=n,t[n]=s}_lendControlInterpolant(){const e=this._controlInterpolants,t=this._nActiveControlInterpolants++;let n=e[t];return void 0===n&&(n=new ja(new Float32Array(2),new Float32Array(2),1,Go),n.__cacheIndex=t,e[t]=n),n}_takeBackControlInterpolant(e){const t=this._controlInterpolants,n=e.__cacheIndex,i=--this._nActiveControlInterpolants,s=t[i];e.__cacheIndex=i,t[i]=e,s.__cacheIndex=n,t[n]=s}clipAction(e,t,n){const i=t||this._root,s=i.uuid;let r="string"==typeof e?to.findByName(i,e):e;const a=null!==r?r.uuid:e,o=this._actionsByClip[a];let l=null;if(void 0===n&&(n=null!==r?r.blendMode:sn),void 0!==o){const e=o.actionByRoot[s];if(void 0!==e&&e.blendMode===n)return e;l=o.knownActions[0],null===r&&(r=l._clip)}if(null===r)return null;const c=new Vo(this,r,t,n);return this._bindAction(c,l),this._addInactiveAction(c,a,s),c}existingAction(e,t){const n=t||this._root,i=n.uuid,s="string"==typeof e?to.findByName(n,e):e,r=s?s.uuid:e,a=this._actionsByClip[r];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,s=Math.sign(e),r=this._accuIndex^=1;for(let l=0;l!==n;++l){t[l]._update(i,e,s,r)}const a=this._bindings,o=this._nActiveBindings;for(let l=0;l!==o;++l)a[l].apply(r);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,s=i[n];if(void 0!==s){const e=s.knownActions;for(let n=0,i=e.length;n!==i;++n){const i=e[n];this._deactivateAction(i);const s=i._cacheIndex,r=t[t.length-1];i._cacheIndex=null,i._byClipCacheIndex=null,r._cacheIndex=s,t[s]=r,t.pop(),this._removeInactiveBindingsForAction(i)}delete i[n]}}uncacheRoot(e){const t=e.uuid,n=this._actionsByClip;for(const s in n){const e=n[s].actionByRoot[t];void 0!==e&&(this._deactivateAction(e),this._removeInactiveAction(e))}const i=this._bindingsByRootAndName[t];if(void 0!==i)for(const s in i){const e=i[s];e.restoreOriginalState(),this._removeInactiveBinding(e)}}uncacheAction(e,t){const n=this.existingAction(e,t);null!==n&&(this._deactivateAction(n),this._removeInactiveAction(n))}}class jo{constructor(e=1,t=0,n=0){return this.radius=e,this.phi=t,this.theta=n,this}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=In(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(In(t/this.radius,-1,1))),this}clone(){return(new this.constructor).copy(this)}}class Xo extends Mn{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(){}disconnect(){}dispose(){}update(){}}function qo(e,t,n,i){const s=function(e){switch(e){case Je:case $e:return{byteLength:1,components:1};case tt:case et:case rt:return{byteLength:2,components:1};case at:case ot:return{byteLength:2,components:4};case it:case nt:case st:return{byteLength:4,components:1};case ct:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${e}.`)}(i);switch(n){case 1021:case 1024:return e*t;case 1025:return e*t*2;case pt:case ft:return e*t/s.components*s.byteLength;case mt:case gt:return e*t*2/s.components*s.byteLength;case 1022:return e*t*3/s.components*s.byteLength;case ht:case vt:return e*t*4/s.components*s.byteLength;case _t:case xt:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case yt:case At:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case bt:case wt:return Math.max(e,16)*Math.max(t,8)/4;case St:case Mt:return Math.max(e,8)*Math.max(t,8)/2;case Tt:case Et:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case Ct:case Rt:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case It:return Math.floor((e+4)/5)*Math.floor((t+3)/4)*16;case Dt:return Math.floor((e+4)/5)*Math.floor((t+4)/5)*16;case Pt:return Math.floor((e+5)/6)*Math.floor((t+4)/5)*16;case Bt:return Math.floor((e+5)/6)*Math.floor((t+5)/6)*16;case Lt:return Math.floor((e+7)/8)*Math.floor((t+4)/5)*16;case Ut:return Math.floor((e+7)/8)*Math.floor((t+5)/6)*16;case Ft:return Math.floor((e+7)/8)*Math.floor((t+7)/8)*16;case kt:return Math.floor((e+9)/10)*Math.floor((t+4)/5)*16;case Nt:return Math.floor((e+9)/10)*Math.floor((t+5)/6)*16;case Ot:return Math.floor((e+9)/10)*Math.floor((t+7)/8)*16;case zt:return Math.floor((e+9)/10)*Math.floor((t+9)/10)*16;case Ht:return Math.floor((e+11)/12)*Math.floor((t+9)/10)*16;case Vt:return Math.floor((e+11)/12)*Math.floor((t+11)/12)*16;case Gt:case Wt:case jt:return Math.ceil(e/4)*Math.ceil(t/4)*16;case 36283:case Xt:return Math.ceil(e/4)*Math.ceil(t/4)*8;case qt:case Qt:return Math.ceil(e/4)*Math.ceil(t/4)*16}throw new Error(`Unable to determine texture byte length for ${n} format.`)}function Qo(){let e=null,t=!1,n=null,i=null;function s(t,r){n(t,r),i=e.requestAnimationFrame(s)}return{start:function(){!0!==t&&null!==n&&(i=e.requestAnimationFrame(s),t=!0)},stop:function(){e.cancelAnimationFrame(i),t=!1},setAnimationLoop:function(e){n=e},setContext:function(t){e=t}}}function Ko(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 s=t.get(n);if(void 0===s)t.set(n,function(t,n){const i=t.array,s=t.usage,r=i.byteLength,a=e.createBuffer();let o;if(e.bindBuffer(n,a),e.bufferData(n,i,s),t.onUploadCallback(),i instanceof Float32Array)o=e.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:r}}(n,i));else if(s.version<n.version){if(s.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 s=n.array,r=n.updateRanges;if(e.bindBuffer(i,t),0===r.length)e.bufferSubData(i,0,s);else{r.sort((e,t)=>e.start-t.start);let t=0;for(let e=1;e<r.length;e++){const n=r[t],i=r[e];i.start<=n.start+n.count+1?n.count=Math.max(n.count,i.start+i.count-n.start):(++t,r[t]=i)}r.length=t+1;for(let n=0,a=r.length;n<a;n++){const t=r[n];e.bufferSubData(i,t.start*s.BYTES_PER_ELEMENT,s,t.start,t.count)}n.clearUpdateRanges()}n.onUploadCallback()}(s.buffer,n,i),s.version=n.version}}}}"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:ne}})),"undefined"!=typeof window&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=ne);const Yo={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}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\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\t\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, roughness * 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 * ( 1.0 - 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 = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), 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.07, 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:"struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\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#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 saturate(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.specularColor;\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 * transposeMat3( 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 a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\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\tvec2 fab = DFGApprox( normal, viewDir, roughness );\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}\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.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * 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\t\tsheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\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\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\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 );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\t#endif\n\tvec3 totalScattering = singleScattering + multiScattering;\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\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.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\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 )\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_LOGDEPTHBUF )\n\tgl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif",logdepthbuf_pars_fragment:"#if defined( USE_LOGDEPTHBUF )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_pars_vertex:"#ifdef USE_LOGDEPTHBUF\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_vertex:"#ifdef USE_LOGDEPTHBUF\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\tuniform sampler2D directionalShadowMap[ 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\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\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 sampler2D pointShadowMap[ 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\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D 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\t\n\t\tfloat lightToPositionLength = length( lightToPosition );\n\t\tif ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {\n\t\t\tfloat dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\t\tdp += shadowBias;\n\t\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\t\tshadow = (\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t\t) * ( 1.0 / 9.0 );\n\t\t\t#else\n\t\t\t\tshadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t\t#endif\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\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\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.diffuseColor, material.specularColor, 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\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\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}",distanceRGBA_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}",distanceRGBA_frag:"#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\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 <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 = packDepthToRGBA( dist );\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 <packing>\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 <packing>\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( packNormalToRGB( normal ), 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 <packing>\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 <packing>\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\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;\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 <packing>\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 <packing>\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}"},Zo={common:{diffuse:{value:new Ds(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new kn},alphaMap:{value:null},alphaMapTransform:{value:new kn},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new kn}},envmap:{envMap:{value:null},envMapRotation:{value:new kn},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new kn}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new kn}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new kn},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new kn},normalScale:{value:new Fn(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new kn},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new kn}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new kn}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new kn}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Ds(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 Ds(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new kn},alphaTest:{value:0},uvTransform:{value:new kn}},sprite:{diffuse:{value:new Ds(16777215)},opacity:{value:1},center:{value:new Fn(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new kn},alphaMap:{value:null},alphaMapTransform:{value:new kn},alphaTest:{value:0}}},Jo={basic:{uniforms:mr([Zo.common,Zo.specularmap,Zo.envmap,Zo.aomap,Zo.lightmap,Zo.fog]),vertexShader:Yo.meshbasic_vert,fragmentShader:Yo.meshbasic_frag},lambert:{uniforms:mr([Zo.common,Zo.specularmap,Zo.envmap,Zo.aomap,Zo.lightmap,Zo.emissivemap,Zo.bumpmap,Zo.normalmap,Zo.displacementmap,Zo.fog,Zo.lights,{emissive:{value:new Ds(0)}}]),vertexShader:Yo.meshlambert_vert,fragmentShader:Yo.meshlambert_frag},phong:{uniforms:mr([Zo.common,Zo.specularmap,Zo.envmap,Zo.aomap,Zo.lightmap,Zo.emissivemap,Zo.bumpmap,Zo.normalmap,Zo.displacementmap,Zo.fog,Zo.lights,{emissive:{value:new Ds(0)},specular:{value:new Ds(1118481)},shininess:{value:30}}]),vertexShader:Yo.meshphong_vert,fragmentShader:Yo.meshphong_frag},standard:{uniforms:mr([Zo.common,Zo.envmap,Zo.aomap,Zo.lightmap,Zo.emissivemap,Zo.bumpmap,Zo.normalmap,Zo.displacementmap,Zo.roughnessmap,Zo.metalnessmap,Zo.fog,Zo.lights,{emissive:{value:new Ds(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Yo.meshphysical_vert,fragmentShader:Yo.meshphysical_frag},toon:{uniforms:mr([Zo.common,Zo.aomap,Zo.lightmap,Zo.emissivemap,Zo.bumpmap,Zo.normalmap,Zo.displacementmap,Zo.gradientmap,Zo.fog,Zo.lights,{emissive:{value:new Ds(0)}}]),vertexShader:Yo.meshtoon_vert,fragmentShader:Yo.meshtoon_frag},matcap:{uniforms:mr([Zo.common,Zo.bumpmap,Zo.normalmap,Zo.displacementmap,Zo.fog,{matcap:{value:null}}]),vertexShader:Yo.meshmatcap_vert,fragmentShader:Yo.meshmatcap_frag},points:{uniforms:mr([Zo.points,Zo.fog]),vertexShader:Yo.points_vert,fragmentShader:Yo.points_frag},dashed:{uniforms:mr([Zo.common,Zo.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Yo.linedashed_vert,fragmentShader:Yo.linedashed_frag},depth:{uniforms:mr([Zo.common,Zo.displacementmap]),vertexShader:Yo.depth_vert,fragmentShader:Yo.depth_frag},normal:{uniforms:mr([Zo.common,Zo.bumpmap,Zo.normalmap,Zo.displacementmap,{opacity:{value:1}}]),vertexShader:Yo.meshnormal_vert,fragmentShader:Yo.meshnormal_frag},sprite:{uniforms:mr([Zo.sprite,Zo.fog]),vertexShader:Yo.sprite_vert,fragmentShader:Yo.sprite_frag},background:{uniforms:{uvTransform:{value:new kn},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Yo.background_vert,fragmentShader:Yo.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new kn}},vertexShader:Yo.backgroundCube_vert,fragmentShader:Yo.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Yo.cube_vert,fragmentShader:Yo.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Yo.equirect_vert,fragmentShader:Yo.equirect_frag},distanceRGBA:{uniforms:mr([Zo.common,Zo.displacementmap,{referencePosition:{value:new ci},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Yo.distanceRGBA_vert,fragmentShader:Yo.distanceRGBA_frag},shadow:{uniforms:mr([Zo.lights,Zo.fog,{color:{value:new Ds(0)},opacity:{value:1}}]),vertexShader:Yo.shadow_vert,fragmentShader:Yo.shadow_frag}};Jo.physical={uniforms:mr([Jo.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new kn},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new kn},clearcoatNormalScale:{value:new Fn(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new kn},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new kn},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new kn},sheen:{value:0},sheenColor:{value:new Ds(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new kn},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new kn},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new kn},transmissionSamplerSize:{value:new Fn},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new kn},attenuationDistance:{value:0},attenuationColor:{value:new Ds(0)},specularColor:{value:new Ds(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new kn},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new kn},anisotropyVector:{value:new Fn},anisotropyMap:{value:null},anisotropyMapTransform:{value:new kn}}]),vertexShader:Yo.meshphysical_vert,fragmentShader:Yo.meshphysical_frag};const $o={r:0,b:0,g:0},el=new Ki,tl=new Oi;function nl(e,t,n,i,s,r,a){const o=new Ds(0);let l,c,h=!0===r?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($o,gr(e)),i.buffers.color.setClear($o.r,$o.g,$o.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 s=f(t);null===s?m(o,h):s&&s.isColor&&(m(s,1),n=!0);const r=e.xr.getEnvironmentBlendMode();"additive"===r?i.buffers.color.setClear(0,0,0,1,a):"alpha-blend"===r&&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===Ve)?(void 0===c&&(c=new ur(new pr(1,1,1),new _r({name:"BackgroundCubeMaterial",uniforms:fr(Jo.backgroundCube.uniforms),vertexShader:Jo.backgroundCube.vertexShader,fragmentShader:Jo.backgroundCube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!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}}),s.update(c)),el.copy(n.backgroundRotation),el.x*=-1,el.y*=-1,el.z*=-1,i.isCubeTexture&&!1===i.isRenderTargetTexture&&(el.y*=-1,el.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(tl.makeRotationFromEuler(el)),c.material.toneMapped=qn.getTransfer(i.colorSpace)!==cn,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 ur(new La(2,2),new _r({name:"BackgroundMaterial",uniforms:fr(Jo.background.uniforms),vertexShader:Jo.background.vertexShader,fragmentShader:Jo.background.fragmentShader,side:0,depthTest:!1,depthWrite:!1,fog:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),s.update(l)),l.material.uniforms.t2D.value=i,l.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,l.material.toneMapped=qn.getTransfer(i.colorSpace)!==cn,!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 il(e,t){const n=e.getParameter(e.MAX_VERTEX_ATTRIBS),i={},s=c(null);let r=s,a=!1;function o(t){return e.bindVertexArray(t)}function l(t){return e.deleteVertexArray(t)}function c(e){const t=[],i=[],s=[];for(let r=0;r<n;r++)t[r]=0,i[r]=0,s[r]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:t,enabledAttributes:i,attributeDivisors:s,object:e,attributes:{},index:null}}function h(){const e=r.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=r.newAttributes,s=r.enabledAttributes,a=r.attributeDivisors;i[t]=1,0===s[t]&&(e.enableVertexAttribArray(t),s[t]=1),a[t]!==n&&(e.vertexAttribDivisor(t,n),a[t]=n)}function p(){const t=r.newAttributes,n=r.enabledAttributes;for(let i=0,s=n.length;i<s;i++)n[i]!==t[i]&&(e.disableVertexAttribArray(i),n[i]=0)}function f(t,n,i,s,r,a,o){!0===o?e.vertexAttribIPointer(t,n,i,r,a):e.vertexAttribPointer(t,n,i,s,r,a)}function m(){g(),a=!0,r!==s&&(r=s,o(r.object))}function g(){s.geometry=null,s.program=null,s.wireframe=!1}return{setup:function(n,s,l,m,g){let v=!1;const _=function(t,n,s){const r=!0===s.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[r];void 0===l&&(l=c(e.createVertexArray()),o[r]=l);return l}(m,l,s);r!==_&&(r=_,o(r.object)),v=function(e,t,n,i){const s=r.attributes,a=t.attributes;let o=0;const l=n.getAttributes();for(const r in l){if(l[r].location>=0){const t=s[r];let n=a[r];if(void 0===n&&("instanceMatrix"===r&&e.instanceMatrix&&(n=e.instanceMatrix),"instanceColor"===r&&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 r.attributesNum!==o||r.index!==i}(n,m,l,g),v&&function(e,t,n,i){const s={},a=t.attributes;let o=0;const l=n.getAttributes();for(const r in l){if(l[r].location>=0){let t=a[r];void 0===t&&("instanceMatrix"===r&&e.instanceMatrix&&(t=e.instanceMatrix),"instanceColor"===r&&e.instanceColor&&(t=e.instanceColor));const n={};n.attribute=t,t&&t.data&&(n.data=t.data),s[r]=n,o++}}r.attributes=s,r.attributesNum=o,r.index=i}(n,m,l,g),null!==g&&t.update(g,e.ELEMENT_ARRAY_BUFFER),(v||a)&&(a=!1,function(n,i,s,r){h();const a=r.attributes,o=s.getAttributes(),l=i.defaultAttributeValues;for(const c in o){const i=o[c];if(i.location>=0){let s=a[c];if(void 0===s&&("instanceMatrix"===c&&n.instanceMatrix&&(s=n.instanceMatrix),"instanceColor"===c&&n.instanceColor&&(s=n.instanceColor)),void 0!==s){const a=s.normalized,o=s.itemSize,l=t.get(s);if(void 0===l)continue;const c=l.buffer,h=l.type,p=l.bytesPerElement,m=h===e.INT||h===e.UNSIGNED_INT||s.gpuType===nt;if(s.isInterleavedBufferAttribute){const t=s.data,l=t.stride,g=s.offset;if(t.isInstancedInterleavedBuffer){for(let e=0;e<i.locationSize;e++)d(i.location+e,t.meshPerAttribute);!0!==n.isInstancedMesh&&void 0===r._maxInstanceCount&&(r._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(s.isInstancedBufferAttribute){for(let e=0;e<i.locationSize;e++)d(i.location+e,s.meshPerAttribute);!0!==n.isInstancedMesh&&void 0===r._maxInstanceCount&&(r._maxInstanceCount=s.meshPerAttribute*s.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,s,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 s=n[e.id];for(const e in s)l(s[e].object),delete s[e];delete n[e.id]}},initAttributes:h,enableAttribute:u,disableUnusedAttributes:p}}function sl(e,t,n){let i;function s(t,s,r){0!==r&&(e.drawArraysInstanced(i,t,s,r),n.update(s,i,r))}this.setMode=function(e){i=e},this.render=function(t,s){e.drawArrays(i,t,s),n.update(s,i,1)},this.renderInstances=s,this.renderMultiDraw=function(e,s,r){if(0===r)return;t.get("WEBGL_multi_draw").multiDrawArraysWEBGL(i,e,0,s,0,r);let a=0;for(let t=0;t<r;t++)a+=s[t];n.update(a,i,1)},this.renderMultiDrawInstances=function(e,r,a,o){if(0===a)return;const l=t.get("WEBGL_multi_draw");if(null===l)for(let t=0;t<e.length;t++)s(e[t],r[t],o[t]);else{l.multiDrawArraysInstancedWEBGL(i,e,0,r,0,o,0,a);let t=0;for(let e=0;e<a;e++)t+=r[e]*o[e];n.update(t,i,1)}}}function rl(e,t,n,i){let s;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"}let a=void 0!==n.precision?n.precision:"highp";const o=r(a);o!==a&&(console.warn("THREE.WebGLRenderer:",a,"not supported, using",o,"instead."),a=o);const l=!0===n.logarithmicDepthBuffer,c=!0===n.reverseDepthBuffer&&t.has("EXT_clip_control"),h=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),u=e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS);return{isWebGL2:!0,getMaxAnisotropy:function(){if(void 0!==s)return s;if(!0===t.has("EXT_texture_filter_anisotropic")){const n=t.get("EXT_texture_filter_anisotropic");s=e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else s=0;return s},getMaxPrecision:r,textureFormatReadable:function(t){return t===ht||i.convert(t)===e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)},textureTypeReadable:function(n){const s=n===rt&&(t.has("EXT_color_buffer_half_float")||t.has("EXT_color_buffer_float"));return!(n!==Je&&i.convert(n)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)&&n!==st&&!s)},precision:a,logarithmicDepthBuffer:l,reverseDepthBuffer:c,maxTextures:h,maxVertexTextures:u,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),vertexTextures:u>0,maxSamples:e.getParameter(e.MAX_SAMPLES)}}function al(e){const t=this;let n=null,i=0,s=!1,r=!1;const a=new la,o=new kn,l={value:null,needsUpdate:!1};function c(e,n,i,s){const r=null!==e?e.length:0;let c=null;if(0!==r){if(c=l.value,!0!==s||null===c){const t=i+4*r,s=n.matrixWorldInverse;o.getNormalMatrix(s),(null===c||c.length<t)&&(c=new Float32Array(t));for(let n=0,l=i;n!==r;++n,l+=4)a.copy(e[n]).applyMatrix4(s,o),a.normal.toArray(c,l),c[l+3]=a.constant}l.value=c,l.needsUpdate=!0}return t.numPlanes=r,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||s;return s=t,i=e.length,n},this.beginShadows=function(){r=!0,c(null)},this.endShadows=function(){r=!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(!s||null===u||0===u.length||r&&!p)r?c(null):function(){l.value!==n&&(l.value=n,l.needsUpdate=i>0);t.numPlanes=i,t.numIntersection=0}();else{const e=r?0:i,t=4*e;let s=f.clippingState||null;l.value=s,s=c(u,o,t,h);for(let i=0;i!==t;++i)s[i]=n[i];f.clippingState=s,this.numIntersection=d?this.numPlanes:0,this.numPlanes+=e}}}function ol(e){let t=new WeakMap;function n(e,t){return 303===t?e.mapping=ze:304===t&&(e.mapping=He),e}function i(e){const n=e.target;n.removeEventListener("dispose",i);const s=t.get(n);void 0!==s&&(t.delete(n),s.dispose())}return{get:function(s){if(s&&s.isTexture){const r=s.mapping;if(303===r||304===r){if(t.has(s)){return n(t.get(s).texture,s.mapping)}{const r=s.image;if(r&&r.height>0){const a=new Er(r.height);return a.fromEquirectangularTexture(e,s),t.set(s,a),s.addEventListener("dispose",i),n(a.texture,s.mapping)}return null}}}return s},dispose:function(){t=new WeakMap}}}const ll=[.125,.215,.35,.446,.526,.582],cl=20,hl=new wo,ul=new Ds;let dl=null,pl=0,fl=0,ml=!1;const gl=(1+Math.sqrt(5))/2,vl=1/gl,_l=[new ci(-gl,vl,0),new ci(gl,vl,0),new ci(-vl,0,gl),new ci(vl,0,gl),new ci(0,gl,-vl),new ci(0,gl,vl),new ci(-1,1,-1),new ci(1,1,-1),new ci(-1,1,1),new ci(1,1,1)];class xl{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(e,t=0,n=.1,i=100){dl=this._renderer.getRenderTarget(),pl=this._renderer.getActiveCubeFace(),fl=this._renderer.getActiveMipmapLevel(),ml=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(256);const s=this._allocateTargets();return s.depthBuffer=!0,this._sceneToCubeUV(e,n,i,s),t>0&&this._blur(s,0,0,t),this._applyPMREM(s),this._cleanup(s),s}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=bl(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=Sl(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),null!==this._cubemapMaterial&&this._cubemapMaterial.dispose(),null!==this._equirectMaterial&&this._equirectMaterial.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._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodPlanes.length;e++)this._lodPlanes[e].dispose()}_cleanup(e){this._renderer.setRenderTarget(dl,pl,fl),this._renderer.xr.enabled=ml,e.scissorTest=!1,Al(e,0,0,e.width,e.height)}_fromTexture(e,t){e.mapping===ze||e.mapping===He?this._setSize(0===e.image.length?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),dl=this._renderer.getRenderTarget(),pl=this._renderer.getActiveCubeFace(),fl=this._renderer.getActiveMipmapLevel(),ml=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:Ke,minFilter:Ke,generateMipmaps:!1,type:rt,format:ht,colorSpace:on,depthBuffer:!1},i=yl(e,t,n);if(null===this._pingPongRenderTarget||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){null!==this._pingPongRenderTarget&&this._dispose(),this._pingPongRenderTarget=yl(e,t,n);const{_lodMax:i}=this;({sizeLods:this._sizeLods,lodPlanes:this._lodPlanes,sigmas:this._sigmas}=function(e){const t=[],n=[],i=[];let s=e;const r=e-4+1+ll.length;for(let a=0;a<r;a++){const r=Math.pow(2,s);n.push(r);let o=1/r;a>e-4?o=ll[a-e+4-1]:0===a&&(o=0),i.push(o);const l=1/(r-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,v=new Float32Array(f*p*d),_=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];v.set(i,f*p*e),_.set(u,m*p*e);const s=[e,e,e,e,e,e];x.set(s,g*p*e)}const y=new $s;y.setAttribute("position",new Vs(v,f)),y.setAttribute("uv",new Vs(_,m)),y.setAttribute("faceIndex",new Vs(x,g)),t.push(y),s>4&&s--}return{lodPlanes:t,sizeLods:n,sigmas:i}}(i)),this._blurMaterial=function(e,t,n){const i=new Float32Array(cl),s=new ci(0,1,0),r=new _r({name:"SphericalGaussianBlur",defines:{n:cl,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:s}},vertexShader:Ml(),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 r}(i,e,t)}return i}_compileMaterial(e){const t=new ur(this._lodPlanes[0],e);this._renderer.compile(t,hl)}_sceneToCubeUV(e,t,n,i){const s=new br(90,1,t,n),r=[1,-1,1,1,1,1],a=[1,1,1,-1,-1,-1],o=this._renderer,l=o.autoClear,c=o.toneMapping;o.getClearColor(ul),o.toneMapping=0,o.autoClear=!1;const h=new Us({name:"PMREM.Background",side:1,depthWrite:!1,depthTest:!1}),u=new ur(new pr,h);let d=!1;const p=e.background;p?p.isColor&&(h.color.copy(p),e.background=null,d=!0):(h.color.copy(ul),d=!0);for(let f=0;f<6;f++){const t=f%3;0===t?(s.up.set(0,r[f],0),s.lookAt(a[f],0,0)):1===t?(s.up.set(0,0,r[f]),s.lookAt(0,a[f],0)):(s.up.set(0,r[f],0),s.lookAt(0,0,a[f]));const n=this._cubeSize;Al(i,t*n,f>2?n:0,n,n),o.setRenderTarget(i),d&&o.render(u,s),o.render(e,s)}u.geometry.dispose(),u.material.dispose(),o.toneMapping=c,o.autoClear=l,e.background=p}_textureToCubeUV(e,t){const n=this._renderer,i=e.mapping===ze||e.mapping===He;i?(null===this._cubemapMaterial&&(this._cubemapMaterial=bl()),this._cubemapMaterial.uniforms.flipEnvMap.value=!1===e.isRenderTargetTexture?-1:1):null===this._equirectMaterial&&(this._equirectMaterial=Sl());const s=i?this._cubemapMaterial:this._equirectMaterial,r=new ur(this._lodPlanes[0],s);s.uniforms.envMap.value=e;const a=this._cubeSize;Al(t,0,0,3*a,2*a),n.setRenderTarget(t),n.render(r,hl)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;const i=this._lodPlanes.length;for(let s=1;s<i;s++){const t=Math.sqrt(this._sigmas[s]*this._sigmas[s]-this._sigmas[s-1]*this._sigmas[s-1]),n=_l[(i-s-1)%_l.length];this._blur(e,s-1,s,t,n)}t.autoClear=n}_blur(e,t,n,i,s){const r=this._pingPongRenderTarget;this._halfBlur(e,r,t,n,i,"latitudinal",s),this._halfBlur(r,e,n,n,i,"longitudinal",s)}_halfBlur(e,t,n,i,s,r,a){const o=this._renderer,l=this._blurMaterial;"latitudinal"!==r&&"longitudinal"!==r&&console.error("blur direction must be either latitudinal or longitudinal!");const c=new ur(this._lodPlanes[i],l),h=l.uniforms,u=this._sizeLods[n]-1,d=isFinite(s)?Math.PI/(2*u):2*Math.PI/39,p=s/d,f=isFinite(s)?1+Math.floor(3*p):cl;f>cl&&console.warn(`sigmaRadians, ${s}, 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<cl;++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"===r,a&&(h.poleAxis.value=a);const{_lodMax:v}=this;h.dTheta.value=d,h.mipInt.value=v-n;const _=this._sizeLods[i];Al(t,3*_*(i>v-4?i-v+4:0),4*(this._cubeSize-_),3*_,2*_),o.setRenderTarget(t),o.render(c,hl)}}function yl(e,t,n){const i=new ri(e,t,n);return i.texture.mapping=Ve,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function Al(e,t,n,i,s){e.viewport.set(t,n,i,s),e.scissor.set(t,n,i,s)}function Sl(){return new _r({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:Ml(),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 bl(){return new _r({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Ml(),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 Ml(){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 wl(e){let t=new WeakMap,n=null;function i(e){const n=e.target;n.removeEventListener("dispose",i);const s=t.get(n);void 0!==s&&(t.delete(n),s.dispose())}return{get:function(s){if(s&&s.isTexture){const r=s.mapping,a=303===r||304===r,o=r===ze||r===He;if(a||o){let r=t.get(s);const l=void 0!==r?r.texture.pmremVersion:0;if(s.isRenderTargetTexture&&s.pmremVersion!==l)return null===n&&(n=new xl(e)),r=a?n.fromEquirectangular(s,r):n.fromCubemap(s,r),r.texture.pmremVersion=s.pmremVersion,t.set(s,r),r.texture;if(void 0!==r)return r.texture;{const l=s.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 xl(e)),r=a?n.fromEquirectangular(s):n.fromCubemap(s),r.texture.pmremVersion=s.pmremVersion,t.set(s,r),s.addEventListener("dispose",i),r.texture):null}}}return s},dispose:function(){t=new WeakMap,null!==n&&(n.dispose(),n=null)}}}function Tl(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(){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&&Gn("THREE.WebGLRenderer: "+e+" extension not supported."),t}}}function El(e,t,n,i){const s={},r=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 s[o.id];const l=r.get(o);l&&(t.remove(l),r.delete(o)),i.releaseStatesOfGeometry(o),!0===o.isInstancedBufferGeometry&&delete o._maxInstanceCount,n.memory.geometries--}function o(e){const n=[],i=e.index,s=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],s=e[t+1],r=e[t+2];n.push(i,s,s,r,r,i)}}else{if(void 0===s)return;{const e=s.array;a=s.version;for(let t=0,i=e.length/3-1;t<i;t+=3){const e=t+0,i=t+1,s=t+2;n.push(e,i,i,s,s,e)}}}const o=new(On(n)?Ws:Gs)(n,1);o.version=a;const l=r.get(e);l&&t.remove(l),r.set(e,o)}return{get:function(e,t){return!0===s[t.id]||(t.addEventListener("dispose",a),s[t.id]=!0,n.memory.geometries++),t},update:function(n){const i=n.attributes;for(const s in i)t.update(i[s],e.ARRAY_BUFFER)},getWireframeAttribute:function(e){const t=r.get(e);if(t){const n=e.index;null!==n&&t.version<n.version&&o(e)}else o(e);return r.get(e)}}}function Cl(e,t,n){let i,s,r;function a(t,a,o){0!==o&&(e.drawElementsInstanced(i,a,s,t*r,o),n.update(a,i,o))}this.setMode=function(e){i=e},this.setIndex=function(e){s=e.type,r=e.bytesPerElement},this.render=function(t,a){e.drawElements(i,a,s,t*r),n.update(a,i,1)},this.renderInstances=a,this.renderMultiDraw=function(e,r,a){if(0===a)return;t.get("WEBGL_multi_draw").multiDrawElementsWEBGL(i,r,0,s,e,0,a);let o=0;for(let t=0;t<a;t++)o+=r[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]/r,o[t],c[t]);else{h.multiDrawElementsInstancedWEBGL(i,o,0,s,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 Rl(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,s){switch(t.calls++,i){case e.TRIANGLES:t.triangles+=s*(n/3);break;case e.LINES:t.lines+=s*(n/2);break;case e.LINE_STRIP:t.lines+=s*(n-1);break;case e.LINE_LOOP:t.lines+=s*n;break;case e.POINTS:t.points+=s*n;break;default:console.error("THREE.WebGLInfo: Unknown draw mode:",i)}}}}function Il(e,t,n){const i=new WeakMap,s=new ii;return{update:function(r,a,o){const l=r.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(){v.dispose(),i.delete(a),a.removeEventListener("dispose",e)};void 0!==u&&u.texture.dispose();const n=void 0!==a.morphAttributes.position,r=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===r&&(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),v=new ai(g,f,m,h);v.type=st,v.needsUpdate=!0;const _=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*_;!0===n&&(s.fromBufferAttribute(e,t),g[h+l+0]=s.x,g[h+l+1]=s.y,g[h+l+2]=s.z,g[h+l+3]=0),!0===r&&(s.fromBufferAttribute(i,t),g[h+l+4]=s.x,g[h+l+5]=s.y,g[h+l+6]=s.z,g[h+l+7]=0),!0===o&&(s.fromBufferAttribute(a,t),g[h+l+8]=s.x,g[h+l+9]=s.y,g[h+l+10]=s.z,g[h+l+11]=4===a.itemSize?s.w:1)}}u={count:h,texture:v,size:new Fn(f,m)},i.set(a,u),a.addEventListener("dispose",e)}if(!0===r.isInstancedMesh&&null!==r.morphTexture)o.getUniforms().setValue(e,"morphTexture",r.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 Dl(e,t,n,i){let s=new WeakMap;function r(e){const t=e.target;t.removeEventListener("dispose",r),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(s.get(c)!==o&&(t.update(c),s.set(c,o)),a.isInstancedMesh&&(!1===a.hasEventListener("dispose",r)&&a.addEventListener("dispose",r),s.get(a)!==o&&(n.update(a.instanceMatrix,e.ARRAY_BUFFER),null!==a.instanceColor&&n.update(a.instanceColor,e.ARRAY_BUFFER),s.set(a,o))),a.isSkinnedMesh){const e=a.skeleton;s.get(e)!==o&&(e.update(),s.set(e,o))}return c},dispose:function(){s=new WeakMap}}}const Pl=new ni,Bl=new Ba(1,1),Ll=new ai,Ul=new oi,Fl=new Tr,kl=[],Nl=[],Ol=new Float32Array(16),zl=new Float32Array(9),Hl=new Float32Array(4);function Vl(e,t,n){const i=e[0];if(i<=0||i>0)return e;const s=t*n;let r=kl[s];if(void 0===r&&(r=new Float32Array(s),kl[s]=r),0!==t){i.toArray(r,0);for(let i=1,s=0;i!==t;++i)s+=n,e[i].toArray(r,s)}return r}function Gl(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 Wl(e,t){for(let n=0,i=t.length;n<i;n++)e[n]=t[n]}function jl(e,t){let n=Nl[t];void 0===n&&(n=new Int32Array(t),Nl[t]=n);for(let i=0;i!==t;++i)n[i]=e.allocateTextureUnit();return n}function Xl(e,t){const n=this.cache;n[0]!==t&&(e.uniform1f(this.addr,t),n[0]=t)}function ql(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(Gl(n,t))return;e.uniform2fv(this.addr,t),Wl(n,t)}}function Ql(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(Gl(n,t))return;e.uniform3fv(this.addr,t),Wl(n,t)}}function Kl(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(Gl(n,t))return;e.uniform4fv(this.addr,t),Wl(n,t)}}function Yl(e,t){const n=this.cache,i=t.elements;if(void 0===i){if(Gl(n,t))return;e.uniformMatrix2fv(this.addr,!1,t),Wl(n,t)}else{if(Gl(n,i))return;Hl.set(i),e.uniformMatrix2fv(this.addr,!1,Hl),Wl(n,i)}}function Zl(e,t){const n=this.cache,i=t.elements;if(void 0===i){if(Gl(n,t))return;e.uniformMatrix3fv(this.addr,!1,t),Wl(n,t)}else{if(Gl(n,i))return;zl.set(i),e.uniformMatrix3fv(this.addr,!1,zl),Wl(n,i)}}function Jl(e,t){const n=this.cache,i=t.elements;if(void 0===i){if(Gl(n,t))return;e.uniformMatrix4fv(this.addr,!1,t),Wl(n,t)}else{if(Gl(n,i))return;Ol.set(i),e.uniformMatrix4fv(this.addr,!1,Ol),Wl(n,i)}}function $l(e,t){const n=this.cache;n[0]!==t&&(e.uniform1i(this.addr,t),n[0]=t)}function ec(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(Gl(n,t))return;e.uniform2iv(this.addr,t),Wl(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||(e.uniform3i(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z);else{if(Gl(n,t))return;e.uniform3iv(this.addr,t),Wl(n,t)}}function nc(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(Gl(n,t))return;e.uniform4iv(this.addr,t),Wl(n,t)}}function ic(e,t){const n=this.cache;n[0]!==t&&(e.uniform1ui(this.addr,t),n[0]=t)}function sc(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(Gl(n,t))return;e.uniform2uiv(this.addr,t),Wl(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(Gl(n,t))return;e.uniform3uiv(this.addr,t),Wl(n,t)}}function ac(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(Gl(n,t))return;e.uniform4uiv(this.addr,t),Wl(n,t)}}function oc(e,t,n){const i=this.cache,s=n.allocateTextureUnit();let r;i[0]!==s&&(e.uniform1i(this.addr,s),i[0]=s),this.type===e.SAMPLER_2D_SHADOW?(Bl.compareFunction=515,r=Bl):r=Pl,n.setTexture2D(t||r,s)}function lc(e,t,n){const i=this.cache,s=n.allocateTextureUnit();i[0]!==s&&(e.uniform1i(this.addr,s),i[0]=s),n.setTexture3D(t||Ul,s)}function cc(e,t,n){const i=this.cache,s=n.allocateTextureUnit();i[0]!==s&&(e.uniform1i(this.addr,s),i[0]=s),n.setTextureCube(t||Fl,s)}function hc(e,t,n){const i=this.cache,s=n.allocateTextureUnit();i[0]!==s&&(e.uniform1i(this.addr,s),i[0]=s),n.setTexture2DArray(t||Ll,s)}function uc(e,t){e.uniform1fv(this.addr,t)}function dc(e,t){const n=Vl(t,this.size,2);e.uniform2fv(this.addr,n)}function pc(e,t){const n=Vl(t,this.size,3);e.uniform3fv(this.addr,n)}function fc(e,t){const n=Vl(t,this.size,4);e.uniform4fv(this.addr,n)}function mc(e,t){const n=Vl(t,this.size,4);e.uniformMatrix2fv(this.addr,!1,n)}function gc(e,t){const n=Vl(t,this.size,9);e.uniformMatrix3fv(this.addr,!1,n)}function vc(e,t){const n=Vl(t,this.size,16);e.uniformMatrix4fv(this.addr,!1,n)}function _c(e,t){e.uniform1iv(this.addr,t)}function xc(e,t){e.uniform2iv(this.addr,t)}function yc(e,t){e.uniform3iv(this.addr,t)}function Ac(e,t){e.uniform4iv(this.addr,t)}function Sc(e,t){e.uniform1uiv(this.addr,t)}function bc(e,t){e.uniform2uiv(this.addr,t)}function Mc(e,t){e.uniform3uiv(this.addr,t)}function wc(e,t){e.uniform4uiv(this.addr,t)}function Tc(e,t,n){const i=this.cache,s=t.length,r=jl(n,s);Gl(i,r)||(e.uniform1iv(this.addr,r),Wl(i,r));for(let a=0;a!==s;++a)n.setTexture2D(t[a]||Pl,r[a])}function Ec(e,t,n){const i=this.cache,s=t.length,r=jl(n,s);Gl(i,r)||(e.uniform1iv(this.addr,r),Wl(i,r));for(let a=0;a!==s;++a)n.setTexture3D(t[a]||Ul,r[a])}function Cc(e,t,n){const i=this.cache,s=t.length,r=jl(n,s);Gl(i,r)||(e.uniform1iv(this.addr,r),Wl(i,r));for(let a=0;a!==s;++a)n.setTextureCube(t[a]||Fl,r[a])}function Rc(e,t,n){const i=this.cache,s=t.length,r=jl(n,s);Gl(i,r)||(e.uniform1iv(this.addr,r),Wl(i,r));for(let a=0;a!==s;++a)n.setTexture2DArray(t[a]||Ll,r[a])}class Ic{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 Xl;case 35664:return ql;case 35665:return Ql;case 35666:return Kl;case 35674:return Yl;case 35675:return Zl;case 35676:return Jl;case 5124:case 35670:return $l;case 35667:case 35671:return ec;case 35668:case 35672:return tc;case 35669:case 35673:return nc;case 5125:return ic;case 36294:return sc;case 36295:return rc;case 36296:return ac;case 35678:case 36198:case 36298:case 36306:case 35682:return oc;case 35679:case 36299:case 36307:return lc;case 35680:case 36300:case 36308:case 36293:return cc;case 36289:case 36303:case 36311:case 36292:return hc}}(t.type)}}class Dc{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 uc;case 35664:return dc;case 35665:return pc;case 35666:return fc;case 35674:return mc;case 35675:return gc;case 35676:return vc;case 5124:case 35670:return _c;case 35667:case 35671:return xc;case 35668:case 35672:return yc;case 35669:case 35673:return Ac;case 5125:return Sc;case 36294:return bc;case 36295:return Mc;case 36296:return wc;case 35678:case 36198:case 36298:case 36306:case 35682:return Tc;case 35679:case 36299:case 36307:return Ec;case 35680:case 36300:case 36308:case 36293:return Cc;case 36289:case 36303:case 36311:case 36292:return Rc}}(t.type)}}class Pc{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,n){const i=this.seq;for(let s=0,r=i.length;s!==r;++s){const r=i[s];r.setValue(e,t[r.id],n)}}}const Bc=/(\w+)(\])?(\[|\.)?/g;function Lc(e,t){e.seq.push(t),e.map[t.id]=t}function Uc(e,t,n){const i=e.name,s=i.length;for(Bc.lastIndex=0;;){const r=Bc.exec(i),a=Bc.lastIndex;let o=r[1];const l="]"===r[2],c=r[3];if(l&&(o|=0),void 0===c||"["===c&&a+2===s){Lc(n,void 0===c?new Ic(o,e,t):new Dc(o,e,t));break}{let e=n.map[o];void 0===e&&(e=new Pc(o),Lc(n,e)),n=e}}}class Fc{constructor(e,t){this.seq=[],this.map={};const n=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let i=0;i<n;++i){const n=e.getActiveUniform(t,i);Uc(n,e.getUniformLocation(t,n.name),this)}}setValue(e,t,n,i){const s=this.map[t];void 0!==s&&s.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 s=0,r=t.length;s!==r;++s){const r=t[s],a=n[r.id];!1!==a.needsUpdate&&r.setValue(e,a.value,i)}}static seqWithValue(e,t){const n=[];for(let i=0,s=e.length;i!==s;++i){const s=e[i];s.id in t&&n.push(s)}return n}}function kc(e,t,n){const i=e.createShader(t);return e.shaderSource(i,n),e.compileShader(i),i}let Nc=0;const Oc=new kn;function zc(e,t,n){const i=e.getShaderParameter(t,e.COMPILE_STATUS),s=e.getShaderInfoLog(t).trim();if(i&&""===s)return"";const r=/ERROR: 0:(\d+)/.exec(s);if(r){const i=parseInt(r[1]);return n.toUpperCase()+"\n\n"+s+"\n\n"+function(e,t){const n=e.split("\n"),i=[],s=Math.max(t-6,0),r=Math.min(t+6,n.length);for(let a=s;a<r;a++){const e=a+1;i.push(`${e===t?">":" "} ${e}: ${n[a]}`)}return i.join("\n")}(e.getShaderSource(t),i)}return s}function Hc(e,t){const n=function(e){qn._getMatrix(Oc,qn.workingColorSpace,e);const t=`mat3( ${Oc.elements.map(e=>e.toFixed(4))} )`;switch(qn.getTransfer(e)){case ln:return[t,"LinearTransferOETF"];case cn:return[t,"sRGBTransferOETF"];default:return console.warn("THREE.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")}function Vc(e,t){let n;switch(t){case 1:n="Linear";break;case 2:n="Reinhard";break;case 3:n="Cineon";break;case 4:n="ACESFilmic";break;case 6:n="AgX";break;case 7:n="Neutral";break;case 5:n="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",t),n="Linear"}return"vec3 "+e+"( vec3 color ) { return "+n+"ToneMapping( color ); }"}const Gc=new ci;function Wc(){qn.getLuminanceCoefficients(Gc);return["float luminance( const in vec3 rgb ) {",`\tconst vec3 weights = vec3( ${Gc.x.toFixed(4)}, ${Gc.y.toFixed(4)}, ${Gc.z.toFixed(4)} );`,"\treturn dot( weights, rgb );","}"].join("\n")}function jc(e){return""!==e}function Xc(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 qc(e,t){return e.replace(/NUM_CLIPPING_PLANES/g,t.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,t.numClippingPlanes-t.numClipIntersection)}const Qc=/^[ \t]*#include +<([\w\d./]+)>/gm;function Kc(e){return e.replace(Qc,Zc)}const Yc=new Map;function Zc(e,t){let n=Yo[t];if(void 0===n){const e=Yc.get(t);if(void 0===e)throw new Error("Can not resolve #include <"+t+">");n=Yo[e],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',t,e)}return Kc(n)}const Jc=/#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 $c(e){return e.replace(Jc,eh)}function eh(e,t,n,i){let s="";for(let r=parseInt(t);r<parseInt(n);r++)s+=i.replace(/\[\s*i\s*\]/g,"[ "+r+" ]").replace(/UNROLLED_LOOP_INDEX/g,r);return s}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}function nh(e,t,n,i){const s=e.getContext(),r=n.defines;let a=n.vertexShader,o=n.fragmentShader;const l=function(e){let t="SHADOWMAP_TYPE_BASIC";return 1===e.shadowMapType?t="SHADOWMAP_TYPE_PCF":2===e.shadowMapType?t="SHADOWMAP_TYPE_PCF_SOFT":3===e.shadowMapType&&(t="SHADOWMAP_TYPE_VSM"),t}(n),c=function(e){let t="ENVMAP_TYPE_CUBE";if(e.envMap)switch(e.envMapMode){case ze:case He:t="ENVMAP_TYPE_CUBE";break;case Ve:t="ENVMAP_TYPE_CUBE_UV"}return t}(n),h=function(e){let t="ENVMAP_MODE_REFLECTION";e.envMap&&e.envMapMode===He&&(t="ENVMAP_MODE_REFRACTION");return t}(n),u=function(e){let t="ENVMAP_BLENDING_NONE";if(e.envMap)switch(e.combine){case 0:t="ENVMAP_BLENDING_MULTIPLY";break;case 1:t="ENVMAP_BLENDING_MIX";break;case 2:t="ENVMAP_BLENDING_ADD"}return t}(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(jc).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")}(r),m=s.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(jc).join("\n"),g.length>0&&(g+="\n"),v=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,f].filter(jc).join("\n"),v.length>0&&(v+="\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_LOGDEPTHBUF":"",n.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","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(jc).join("\n"),v=[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_LOGDEPTHBUF":"",n.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",0!==n.toneMapping?"#define TONE_MAPPING":"",0!==n.toneMapping?Yo.tonemapping_pars_fragment:"",0!==n.toneMapping?Vc("toneMapping",n.toneMapping):"",n.dithering?"#define DITHERING":"",n.opaque?"#define OPAQUE":"",Yo.colorspace_pars_fragment,Hc("linearToOutputTexel",n.outputColorSpace),Wc(),n.useDepthPacking?"#define DEPTH_PACKING "+n.depthPacking:"","\n"].filter(jc).join("\n")),a=Kc(a),a=Xc(a,n),a=qc(a,n),o=Kc(o),o=Xc(o,n),o=qc(o,n),a=$c(a),o=$c(o),!0!==n.isRawShaderMaterial&&(_="#version 300 es\n",g=[p,"#define attribute in","#define varying out","#define texture2D texture"].join("\n")+"\n"+g,v=["#define varying in",n.glslVersion===An?"":"layout(location = 0) out highp vec4 pc_fragColor;",n.glslVersion===An?"":"#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"+v);const x=_+g+a,y=_+v+o,A=kc(s,s.VERTEX_SHADER,x),S=kc(s,s.FRAGMENT_SHADER,y);function b(t){if(e.debug.checkShaderErrors){const n=s.getProgramInfoLog(m).trim(),i=s.getShaderInfoLog(A).trim(),r=s.getShaderInfoLog(S).trim();let a=!0,o=!0;if(!1===s.getProgramParameter(m,s.LINK_STATUS))if(a=!1,"function"==typeof e.debug.onShaderError)e.debug.onShaderError(s,m,A,S);else{const e=zc(s,A,"vertex"),i=zc(s,S,"fragment");console.error("THREE.WebGLProgram: Shader Error "+s.getError()+" - VALIDATE_STATUS "+s.getProgramParameter(m,s.VALIDATE_STATUS)+"\n\nMaterial Name: "+t.name+"\nMaterial Type: "+t.type+"\n\nProgram Info Log: "+n+"\n"+e+"\n"+i)}else""!==n?console.warn("THREE.WebGLProgram: Program Info Log:",n):""!==i&&""!==r||(o=!1);o&&(t.diagnostics={runnable:a,programLog:n,vertexShader:{log:i,prefix:g},fragmentShader:{log:r,prefix:v}})}s.deleteShader(A),s.deleteShader(S),M=new Fc(s,m),w=function(e,t){const n={},i=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let s=0;s<i;s++){const i=e.getActiveAttrib(t,s),r=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[r]={type:i.type,location:e.getAttribLocation(t,r),locationSize:a}}return n}(s,m)}let M,w;s.attachShader(m,A),s.attachShader(m,S),void 0!==n.index0AttributeName?s.bindAttribLocation(m,0,n.index0AttributeName):!0===n.morphTargets&&s.bindAttribLocation(m,0,"position"),s.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=s.getProgramParameter(m,37297)),T},this.destroy=function(){i.releaseStatesOfProgram(this),s.deleteProgram(m),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=Nc++,this.cacheKey=t,this.usedTimes=1,this.program=m,this.vertexShader=A,this.fragmentShader=S,this}let ih=0;class sh{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const t=e.vertexShader,n=e.fragmentShader,i=this._getShaderStage(t),s=this._getShaderStage(n),r=this._getShaderCacheForMaterial(e);return!1===r.has(i)&&(r.add(i),i.usedTimes++),!1===r.has(s)&&(r.add(s),s.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 rh(e),t.set(e,n)),n}}class rh{constructor(e){this.id=ih++,this.code=e,this.usedTimes=0}}function ah(e,t,n,i,s,r,a){const o=new Yi,l=new sh,c=new Set,h=[],u=s.logarithmicDepthBuffer,d=s.vertexTextures;let p=s.precision;const f={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",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(r,o,h,g,v){const _=g.fog,x=v.geometry,y=r.isMeshStandardMaterial?g.environment:null,A=(r.isMeshStandardMaterial?n:t).get(r.envMap||y),S=A&&A.mapping===Ve?A.image.height:null,b=f[r.type];null!==r.precision&&(p=s.getMaxPrecision(r.precision),p!==r.precision&&console.warn("THREE.WebGLProgram.getParameters:",r.precision,"not supported, using",p,"instead."));const M=x.morphAttributes.position||x.morphAttributes.normal||x.morphAttributes.color,w=void 0!==M?M.length:0;let T,E,C,R,I=0;if(void 0!==x.morphAttributes.position&&(I=1),void 0!==x.morphAttributes.normal&&(I=2),void 0!==x.morphAttributes.color&&(I=3),b){const e=Jo[b];T=e.vertexShader,E=e.fragmentShader}else T=r.vertexShader,E=r.fragmentShader,l.update(r),C=l.getVertexShaderID(r),R=l.getFragmentShaderID(r);const D=e.getRenderTarget(),P=e.state.buffers.depth.getReversed(),B=!0===v.isInstancedMesh,L=!0===v.isBatchedMesh,U=!!r.map,F=!!r.matcap,k=!!A,N=!!r.aoMap,O=!!r.lightMap,z=!!r.bumpMap,H=!!r.normalMap,V=!!r.displacementMap,G=!!r.emissiveMap,W=!!r.metalnessMap,j=!!r.roughnessMap,X=r.anisotropy>0,q=r.clearcoat>0,Q=r.dispersion>0,K=r.iridescence>0,Y=r.sheen>0,Z=r.transmission>0,J=X&&!!r.anisotropyMap,$=q&&!!r.clearcoatMap,ee=q&&!!r.clearcoatNormalMap,te=q&&!!r.clearcoatRoughnessMap,ne=K&&!!r.iridescenceMap,ie=K&&!!r.iridescenceThicknessMap,se=Y&&!!r.sheenColorMap,re=Y&&!!r.sheenRoughnessMap,ae=!!r.specularMap,oe=!!r.specularColorMap,le=!!r.specularIntensityMap,ce=Z&&!!r.transmissionMap,he=Z&&!!r.thicknessMap,ue=!!r.gradientMap,de=!!r.alphaMap,pe=r.alphaTest>0,fe=!!r.alphaHash,me=!!r.extensions;let ge=0;r.toneMapped&&(null!==D&&!0!==D.isXRRenderTarget||(ge=e.toneMapping));const ve={shaderID:b,shaderType:r.type,shaderName:r.name,vertexShader:T,fragmentShader:E,defines:r.defines,customVertexShaderID:C,customFragmentShaderID:R,isRawShaderMaterial:!0===r.isRawShaderMaterial,glslVersion:r.glslVersion,precision:p,batching:L,batchingColor:L&&null!==v._colorsTexture,instancing:B,instancingColor:B&&null!==v.instanceColor,instancingMorph:B&&null!==v.morphTexture,supportsVertexTextures:d,outputColorSpace:null===D?e.outputColorSpace:!0===D.isXRRenderTarget?D.texture.colorSpace:on,alphaToCoverage:!!r.alphaToCoverage,map:U,matcap:F,envMap:k,envMapMode:k&&A.mapping,envMapCubeUVHeight:S,aoMap:N,lightMap:O,bumpMap:z,normalMap:H,displacementMap:d&&V,emissiveMap:G,normalMapObjectSpace:H&&1===r.normalMapType,normalMapTangentSpace:H&&0===r.normalMapType,metalnessMap:W,roughnessMap:j,anisotropy:X,anisotropyMap:J,clearcoat:q,clearcoatMap:$,clearcoatNormalMap:ee,clearcoatRoughnessMap:te,dispersion:Q,iridescence:K,iridescenceMap:ne,iridescenceThicknessMap:ie,sheen:Y,sheenColorMap:se,sheenRoughnessMap:re,specularMap:ae,specularColorMap:oe,specularIntensityMap:le,transmission:Z,transmissionMap:ce,thicknessMap:he,gradientMap:ue,opaque:!1===r.transparent&&1===r.blending&&!1===r.alphaToCoverage,alphaMap:de,alphaTest:pe,alphaHash:fe,combine:r.combine,mapUv:U&&m(r.map.channel),aoMapUv:N&&m(r.aoMap.channel),lightMapUv:O&&m(r.lightMap.channel),bumpMapUv:z&&m(r.bumpMap.channel),normalMapUv:H&&m(r.normalMap.channel),displacementMapUv:V&&m(r.displacementMap.channel),emissiveMapUv:G&&m(r.emissiveMap.channel),metalnessMapUv:W&&m(r.metalnessMap.channel),roughnessMapUv:j&&m(r.roughnessMap.channel),anisotropyMapUv:J&&m(r.anisotropyMap.channel),clearcoatMapUv:$&&m(r.clearcoatMap.channel),clearcoatNormalMapUv:ee&&m(r.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:te&&m(r.clearcoatRoughnessMap.channel),iridescenceMapUv:ne&&m(r.iridescenceMap.channel),iridescenceThicknessMapUv:ie&&m(r.iridescenceThicknessMap.channel),sheenColorMapUv:se&&m(r.sheenColorMap.channel),sheenRoughnessMapUv:re&&m(r.sheenRoughnessMap.channel),specularMapUv:ae&&m(r.specularMap.channel),specularColorMapUv:oe&&m(r.specularColorMap.channel),specularIntensityMapUv:le&&m(r.specularIntensityMap.channel),transmissionMapUv:ce&&m(r.transmissionMap.channel),thicknessMapUv:he&&m(r.thicknessMap.channel),alphaMapUv:de&&m(r.alphaMap.channel),vertexTangents:!!x.attributes.tangent&&(H||X),vertexColors:r.vertexColors,vertexAlphas:!0===r.vertexColors&&!!x.attributes.color&&4===x.attributes.color.itemSize,pointsUvs:!0===v.isPoints&&!!x.attributes.uv&&(U||de),fog:!!_,useFog:!0===r.fog,fogExp2:!!_&&_.isFogExp2,flatShading:!0===r.flatShading,sizeAttenuation:!0===r.sizeAttenuation,logarithmicDepthBuffer:u,reverseDepthBuffer:P,skinning:!0===v.isSkinnedMesh,morphTargets:void 0!==x.morphAttributes.position,morphNormals:void 0!==x.morphAttributes.normal,morphColors:void 0!==x.morphAttributes.color,morphTargetsCount:w,morphTextureStride:I,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:r.dithering,shadowMapEnabled:e.shadowMap.enabled&&h.length>0,shadowMapType:e.shadowMap.type,toneMapping:ge,decodeVideoTexture:U&&!0===r.map.isVideoTexture&&qn.getTransfer(r.map.colorSpace)===cn,decodeVideoTextureEmissive:G&&!0===r.emissiveMap.isVideoTexture&&qn.getTransfer(r.emissiveMap.colorSpace)===cn,premultipliedAlpha:r.premultipliedAlpha,doubleSided:2===r.side,flipSided:1===r.side,useDepthPacking:r.depthPacking>=0,depthPacking:r.depthPacking||0,index0AttributeName:r.index0AttributeName,extensionClipCullDistance:me&&!0===r.extensions.clipCullDistance&&i.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(me&&!0===r.extensions.multiDraw||L)&&i.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:i.has("KHR_parallel_shader_compile"),customProgramCacheKey:r.customProgramCacheKey()};return ve.vertexUv1s=c.has(1),ve.vertexUv2s=c.has(2),ve.vertexUv3s=c.has(3),c.clear(),ve},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.supportsVertexTextures&&o.enable(0);t.instancing&&o.enable(1);t.instancingColor&&o.enable(2);t.instancingMorph&&o.enable(3);t.matcap&&o.enable(4);t.envMap&&o.enable(5);t.normalMapObjectSpace&&o.enable(6);t.normalMapTangentSpace&&o.enable(7);t.clearcoat&&o.enable(8);t.iridescence&&o.enable(9);t.alphaTest&&o.enable(10);t.vertexColors&&o.enable(11);t.vertexAlphas&&o.enable(12);t.vertexUv1s&&o.enable(13);t.vertexUv2s&&o.enable(14);t.vertexUv3s&&o.enable(15);t.vertexTangents&&o.enable(16);t.anisotropy&&o.enable(17);t.alphaHash&&o.enable(18);t.batching&&o.enable(19);t.dispersion&&o.enable(20);t.batchingColor&&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.reverseDepthBuffer&&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=Jo[t];n=vr.clone(e.uniforms)}else n=e.uniforms;return n},acquireProgram:function(t,n){let i;for(let e=0,s=h.length;e<s;e++){const t=h[e];if(t.cacheKey===n){i=t,++i.usedTimes;break}}return void 0===i&&(i=new nh(e,n,t,r),h.push(i)),i},releaseProgram:function(e){if(0===--e.usedTimes){const t=h.indexOf(e);h[t]=h[h.length-1],h.pop(),e.destroy()}},releaseShaderCache:function(e){l.remove(e)},programs:h,dispose:function(){l.dispose()}}}function oh(){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 lh(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 ch(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 hh(){const e=[];let t=0;const n=[],i=[],s=[];function r(n,i,s,r,a,o){let l=e[t];return void 0===l?(l={id:n.id,object:n,geometry:i,material:s,groupOrder:r,renderOrder:n.renderOrder,z:a,group:o},e[t]=l):(l.id=n.id,l.object=n,l.geometry=i,l.material=s,l.groupOrder=r,l.renderOrder=n.renderOrder,l.z=a,l.group=o),t++,l}return{opaque:n,transmissive:i,transparent:s,init:function(){t=0,n.length=0,i.length=0,s.length=0},push:function(e,t,a,o,l,c){const h=r(e,t,a,o,l,c);a.transmission>0?i.push(h):!0===a.transparent?s.push(h):n.push(h)},unshift:function(e,t,a,o,l,c){const h=r(e,t,a,o,l,c);a.transmission>0?i.unshift(h):!0===a.transparent?s.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||lh),i.length>1&&i.sort(t||ch),s.length>1&&s.sort(t||ch)}}}function uh(){let e=new WeakMap;return{get:function(t,n){const i=e.get(t);let s;return void 0===i?(s=new hh,e.set(t,[s])):n>=i.length?(s=new hh,i.push(s)):s=i[n],s},dispose:function(){e=new WeakMap}}}function dh(){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 ci,color:new Ds};break;case"SpotLight":n={position:new ci,direction:new ci,color:new Ds,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":n={position:new ci,color:new Ds,distance:0,decay:0};break;case"HemisphereLight":n={direction:new ci,skyColor:new Ds,groundColor:new Ds};break;case"RectAreaLight":n={color:new Ds,position:new ci,halfWidth:new ci,halfHeight:new ci}}return e[t.id]=n,n}}}let ph=0;function fh(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+(t.map?1:0)-(e.map?1:0)}function mh(e){const t=new dh,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 Fn};break;case"PointLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Fn,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 ci);const s=new ci,r=new Oi,a=new Oi;return{setup:function(s){let r=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,v=0,_=0;s.sort(fh);for(let e=0,y=s.length;e<y;e++){const x=s[e],y=x.color,A=x.intensity,S=x.distance,b=x.shadow&&x.shadow.map?x.shadow.map.texture:null;if(x.isAmbientLight)r+=y.r*A,a+=y.g*A,o+=y.b*A;else if(x.isLightProbe){for(let e=0;e<9;e++)i.probe[e].addScaledVector(x.sh.coefficients[e],A);_++}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(A),e.distance=S,e.coneCos=Math.cos(x.angle),e.penumbraCos=Math.cos(x.angle*(1-x.penumbra)),e.decay=x.decay,i.spot[h]=e;const s=x.shadow;if(x.map&&(i.spotLightMap[g]=x.map,g++,s.updateMatrices(x),x.castShadow&&v++),i.spotLightMatrix[h]=s.matrix,x.castShadow){const e=n.get(x);e.shadowIntensity=s.intensity,e.shadowBias=s.bias,e.shadowNormalBias=s.normalBias,e.shadowRadius=s.radius,e.shadowMapSize=s.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(A),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(A),e.groundColor.copy(x.groundColor).multiplyScalar(A),i.hemi[d]=e,d++}}u>0&&(!0===e.has("OES_texture_float_linear")?(i.rectAreaLTC1=Zo.LTC_FLOAT_1,i.rectAreaLTC2=Zo.LTC_FLOAT_2):(i.rectAreaLTC1=Zo.LTC_HALF_1,i.rectAreaLTC2=Zo.LTC_HALF_2)),i.ambient[0]=r,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===_||(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-v,i.spotLightMap.length=g,i.numSpotLightShadowsWithMaps=v,i.numLightProbes=_,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=_,i.version=ph++)},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),s.setFromMatrixPosition(t.target.matrixWorld),e.direction.sub(s),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),s.setFromMatrixPosition(t.target.matrixWorld),e.direction.sub(s),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(),r.copy(t.matrixWorld),r.premultiply(u),a.extractRotation(r),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 gh(e){const t=new mh(e),n=[],i=[];const s={lightsArray:n,shadowsArray:i,camera:null,lights:t,transmissionRenderTarget:{}};return{init:function(e){s.camera=e,n.length=0,i.length=0},state:s,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 vh(e){let t=new WeakMap;return{get:function(n,i=0){const s=t.get(n);let r;return void 0===s?(r=new gh(e),t.set(n,[r])):i>=s.length?(r=new gh(e),s.push(r)):r=s[i],r},dispose:function(){t=new WeakMap}}}function _h(e,t,n){let i=new ua;const s=new Fn,r=new Fn,a=new ii,o=new ka({depthPacking:3201}),l=new Na,c={},h=n.maxTextureSize,u={[he]:1,[ue]:0,[de]:2},d=new _r({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Fn},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;\n#include <packing>\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 = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\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 = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\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( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}"}),p=d.clone();p.defines.HORIZONTAL_PASS=1;const f=new $s;f.setAttribute("position",new Vs(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const m=new ur(f,d),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1;let v=this.type;function _(n,i){const r=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 ri(s.x,s.y)),d.uniforms.shadow_pass.value=n.map.texture,d.uniforms.resolution.value=n.mapSize,d.uniforms.radius.value=n.radius,e.setRenderTarget(n.mapPass),e.clear(),e.renderBufferDirect(i,null,r,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,r,p,m,null)}function x(t,n,i,s){let r=null;const a=!0===i.isPointLight?t.customDistanceMaterial:t.customDepthMaterial;if(void 0!==a)r=a;else if(r=!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){const e=r.uuid,t=n.uuid;let i=c[e];void 0===i&&(i={},c[e]=i);let s=i[t];void 0===s&&(s=r.clone(),i[t]=s,n.addEventListener("dispose",A)),r=s}if(r.visible=n.visible,r.wireframe=n.wireframe,r.side=3===s?null!==n.shadowSide?n.shadowSide:n.side:null!==n.shadowSide?n.shadowSide:u[n.side],r.alphaMap=n.alphaMap,r.alphaTest=n.alphaTest,r.map=n.map,r.clipShadows=n.clipShadows,r.clippingPlanes=n.clippingPlanes,r.clipIntersection=n.clipIntersection,r.displacementMap=n.displacementMap,r.displacementScale=n.displacementScale,r.displacementBias=n.displacementBias,r.wireframeLinewidth=n.wireframeLinewidth,r.linewidth=n.linewidth,!0===i.isPointLight&&!0===r.isMeshDistanceMaterial){e.properties.get(r).light=i}return r}function y(n,s,r,a,o){if(!1===n.visible)return;if(n.layers.test(s.layers)&&(n.isMesh||n.isLine||n.isPoints)&&(n.castShadow||n.receiveShadow&&3===o)&&(!n.frustumCulled||i.intersectsObject(n))){n.modelViewMatrix.multiplyMatrices(r.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,s,r,i,t,h),e.renderBufferDirect(r,null,i,t,n,h),n.onAfterShadow(e,n,s,r,i,t,h)}}}else if(l.visible){const t=x(n,l,a,o);n.onBeforeShadow(e,n,s,r,i,t,null),e.renderBufferDirect(r,null,i,t,n,null),n.onAfterShadow(e,n,s,r,i,t,null)}}const l=n.children;for(let e=0,t=l.length;e<t;e++)y(l[e],s,r,a,o)}function A(e){e.target.removeEventListener("dispose",A);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;const l=e.getRenderTarget(),c=e.getActiveCubeFace(),u=e.getActiveMipmapLevel(),d=e.state;d.setBlending(0),d.buffers.color.setClear(1,1,1,1),d.buffers.depth.setTest(!0),d.setScissorTest(!1);const p=3!==v&&3===this.type,f=3===v&&3!==this.type;for(let m=0,g=t.length;m<g;m++){const l=t[m],c=l.shadow;if(void 0===c){console.warn("THREE.WebGLShadowMap:",l,"has no shadow.");continue}if(!1===c.autoUpdate&&!1===c.needsUpdate)continue;s.copy(c.mapSize);const u=c.getFrameExtents();if(s.multiply(u),r.copy(c.mapSize),(s.x>h||s.y>h)&&(s.x>h&&(r.x=Math.floor(h/u.x),s.x=r.x*u.x,c.mapSize.x=r.x),s.y>h&&(r.y=Math.floor(h/u.y),s.y=r.y*u.y,c.mapSize.y=r.y)),null===c.map||!0===p||!0===f){const e=3!==this.type?{minFilter:Xe,magFilter:Xe}:{};null!==c.map&&c.map.dispose(),c.map=new ri(s.x,s.y,e),c.map.texture.name=l.name+".shadowMap",c.camera.updateProjectionMatrix()}e.setRenderTarget(c.map),e.clear();const g=c.getViewportCount();for(let e=0;e<g;e++){const t=c.getViewport(e);a.set(r.x*t.x,r.y*t.y,r.x*t.z,r.y*t.w),d.viewport(a),c.updateMatrices(l,e),i=c.getFrustum(),y(n,o,c.camera,l,this.type)}!0!==c.isPointLightShadow&&3===this.type&&_(c,o),c.needsUpdate=!1}v=this.type,g.needsUpdate=!1,e.setRenderTarget(l,c,u)}}const xh={[De]:1,[Be]:6,[Ue]:7,[Le]:5,[Pe]:0,[ke]:2,[Ne]:4,[Fe]:3};function yh(e,t){const n=new function(){let t=!1;const n=new ii;let i=null;const s=new ii(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,r,a,o){!0===o&&(t*=a,i*=a,r*=a),n.set(t,i,r,a),!1===s.equals(n)&&(e.clearColor(t,i,r,a),s.copy(n))},reset:function(){t=!1,i=null,s.set(-1,0,0,0)}}},i=new function(){let n=!1,i=!1,s=null,r=null,a=null;return{setReversed:function(e){if(i!==e){const e=t.get("EXT_clip_control");i?e.clipControlEXT(e.LOWER_LEFT_EXT,e.ZERO_TO_ONE_EXT):e.clipControlEXT(e.LOWER_LEFT_EXT,e.NEGATIVE_ONE_TO_ONE_EXT);const n=a;a=null,this.setClear(n)}i=e},getReversed:function(){return i},setTest:function(t){t?z(e.DEPTH_TEST):H(e.DEPTH_TEST)},setMask:function(t){s===t||n||(e.depthMask(t),s=t)},setFunc:function(t){if(i&&(t=xh[t]),r!==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)}r=t}},setLocked:function(e){n=e},setClear:function(t){a!==t&&(i&&(t=1-t),e.clearDepth(t),a=t)},reset:function(){n=!1,s=null,r=null,a=null,i=!1}}},s=new function(){let t=!1,n=null,i=null,s=null,r=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&&s===n&&r===a||(e.stencilFunc(t,n,a),i=t,s=n,r=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,s=null,r=null,a=null,o=null,l=null,c=null}}},r=new WeakMap,a=new WeakMap;let o={},l={},c=new WeakMap,h=[],u=null,d=!1,p=null,f=null,m=null,g=null,v=null,_=null,x=null,y=new Ds(0,0,0),A=0,S=!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 D=e.getParameter(e.VERSION);-1!==D.indexOf("WebGL")?(I=parseFloat(/^WebGL (\d)/.exec(D)[1]),R=I>=1):-1!==D.indexOf("OpenGL ES")&&(I=parseFloat(/^OpenGL ES (\d)/.exec(D)[1]),R=I>=2);let P=null,B={};const L=e.getParameter(e.SCISSOR_BOX),U=e.getParameter(e.VIEWPORT),F=(new ii).fromArray(L),k=(new ii).fromArray(U);function N(t,n,i,s){const r=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,s,0,e.RGBA,e.UNSIGNED_BYTE,r):e.texImage2D(n+o,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,r);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),s.setClear(0),z(e.DEPTH_TEST),i.setFunc(3),j(!1),X(1),z(e.CULL_FACE),W(0);const V={[pe]:e.FUNC_ADD,[fe]:e.FUNC_SUBTRACT,[me]:e.FUNC_REVERSE_SUBTRACT};V[103]=e.MIN,V[104]=e.MAX;const G={[ge]:e.ZERO,[ve]:e.ONE,[_e]:e.SRC_COLOR,[ye]:e.SRC_ALPHA,[Te]:e.SRC_ALPHA_SATURATE,[Me]:e.DST_COLOR,[Se]:e.DST_ALPHA,[xe]:e.ONE_MINUS_SRC_COLOR,[Ae]:e.ONE_MINUS_SRC_ALPHA,[we]:e.ONE_MINUS_DST_COLOR,[be]:e.ONE_MINUS_DST_ALPHA,[Ee]:e.CONSTANT_COLOR,[Ce]:e.ONE_MINUS_CONSTANT_COLOR,[Re]:e.CONSTANT_ALPHA,[Ie]:e.ONE_MINUS_CONSTANT_ALPHA};function W(t,n,i,s,r,a,o,l,c,h){if(0!==t){if(!1===d&&(z(e.BLEND),d=!0),5===t)r=r||n,a=a||i,o=o||s,n===f&&r===v||(e.blendEquationSeparate(V[n],V[r]),f=n,v=r),i===m&&s===g&&a===_&&o===x||(e.blendFuncSeparate(G[i],G[s],G[a],G[o]),m=i,g=s,_=a,x=o),!1!==l.equals(y)&&c===A||(e.blendColor(l.r,l.g,l.b,c),y.copy(l),A=c),p=t,S=!1;else if(t!==p||h!==S){if(f===pe&&v===pe||(e.blendEquation(e.FUNC_ADD),f=pe,v=pe),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.ZERO,e.SRC_COLOR,e.ZERO,e.SRC_ALPHA);break;default:console.error("THREE.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.blendFunc(e.SRC_ALPHA,e.ONE);break;case 3:e.blendFuncSeparate(e.ZERO,e.ONE_MINUS_SRC_COLOR,e.ZERO,e.ONE);break;case 4:e.blendFunc(e.ZERO,e.SRC_COLOR);break;default:console.error("THREE.WebGLState: Invalid blending: ",t)}m=null,g=null,_=null,x=null,y.set(0,0,0),A=0,p=t,S=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:s},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,s=!1;if(t){i=c.get(n),void 0===i&&(i=[],c.set(n,i));const r=t.textures;if(i.length!==r.length||i[0]!==e.COLOR_ATTACHMENT0){for(let t=0,n=r.length;t<n;t++)i[t]=e.COLOR_ATTACHMENT0+t;i.length=r.length,s=!0}}else i[0]!==e.BACK&&(i[0]=e.BACK,s=!0);s&&e.drawBuffers(i)},useProgram:function(t){return u!==t&&(e.useProgram(t),u=t,!0)},setBlending:W,setMaterial:function(t,r){2===t.side?H(e.CULL_FACE):z(e.CULL_FACE);let a=1===t.side;r&&(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;s.setTest(o),o&&(s.setMask(t.stencilWriteMask),s.setFunc(t.stencilFunc,t.stencilRef,t.stencilFuncMask),s.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),P!==t&&(e.activeTexture(t),P=t)},bindTexture:function(t,n,i){void 0===i&&(i=null===P?e.TEXTURE0+C-1:P);let s=B[i];void 0===s&&(s={type:void 0,texture:void 0},B[i]=s),s.type===t&&s.texture===n||(P!==i&&(e.activeTexture(i),P=i),e.bindTexture(t,n||O[t]),s.type=t,s.texture=n)},unbindTexture:function(){const t=B[P];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.apply(e,arguments)}catch(t){console.error("THREE.WebGLState:",t)}},compressedTexImage3D:function(){try{e.compressedTexImage3D.apply(e,arguments)}catch(t){console.error("THREE.WebGLState:",t)}},texImage2D:function(){try{e.texImage2D.apply(e,arguments)}catch(t){console.error("THREE.WebGLState:",t)}},texImage3D:function(){try{e.texImage3D.apply(e,arguments)}catch(t){console.error("THREE.WebGLState:",t)}},updateUBOMapping:function(t,n){let i=a.get(n);void 0===i&&(i=new WeakMap,a.set(n,i));let s=i.get(t);void 0===s&&(s=e.getUniformBlockIndex(n,t.name),i.set(t,s))},uniformBlockBinding:function(t,n){const i=a.get(n).get(t);r.get(n)!==i&&(e.uniformBlockBinding(n,i,t.__bindingPointIndex),r.set(n,i))},texStorage2D:function(){try{e.texStorage2D.apply(e,arguments)}catch(t){console.error("THREE.WebGLState:",t)}},texStorage3D:function(){try{e.texStorage3D.apply(e,arguments)}catch(t){console.error("THREE.WebGLState:",t)}},texSubImage2D:function(){try{e.texSubImage2D.apply(e,arguments)}catch(t){console.error("THREE.WebGLState:",t)}},texSubImage3D:function(){try{e.texSubImage3D.apply(e,arguments)}catch(t){console.error("THREE.WebGLState:",t)}},compressedTexSubImage2D:function(){try{e.compressedTexSubImage2D.apply(e,arguments)}catch(t){console.error("THREE.WebGLState:",t)}},compressedTexSubImage3D:function(){try{e.compressedTexSubImage3D.apply(e,arguments)}catch(t){console.error("THREE.WebGLState:",t)}},scissor:function(t){!1===F.equals(t)&&(e.scissor(t.x,t.y,t.z,t.w),F.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={},P=null,B={},l={},c=new WeakMap,h=[],u=null,d=!1,p=null,f=null,m=null,g=null,v=null,_=null,x=null,y=new Ds(0,0,0),A=0,S=!1,b=null,M=null,w=null,T=null,E=null,F.set(0,0,e.canvas.width,e.canvas.height),k.set(0,0,e.canvas.width,e.canvas.height),n.reset(),i.reset(),s.reset()}}}function Ah(e,t,n,i,s,r,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 Fn,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(V){}function f(e,t){return p?new OffscreenCanvas(e,t):zn("canvas")}function m(e,t,n){let i=1;const s=H(e);if((s.width>n||s.height>n)&&(i=n/Math.max(s.width,s.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*s.width),r=Math.floor(i*s.height);void 0===u&&(u=f(n,r));const a=t?f(n,r):u;a.width=n,a.height=r;return a.getContext("2d").drawImage(e,0,0,n,r),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+s.width+"x"+s.height+") to ("+n+"x"+r+")."),a}return"data"in e&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+s.width+"x"+s.height+")."),e}return e}function g(e){return e.generateMipmaps}function v(t){e.generateMipmap(t)}function _(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,s,r,a=!1){if(null!==n){if(void 0!==e[n])return e[n];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+n+"'")}let o=i;if(i===e.RED&&(s===e.FLOAT&&(o=e.R32F),s===e.HALF_FLOAT&&(o=e.R16F),s===e.UNSIGNED_BYTE&&(o=e.R8)),i===e.RED_INTEGER&&(s===e.UNSIGNED_BYTE&&(o=e.R8UI),s===e.UNSIGNED_SHORT&&(o=e.R16UI),s===e.UNSIGNED_INT&&(o=e.R32UI),s===e.BYTE&&(o=e.R8I),s===e.SHORT&&(o=e.R16I),s===e.INT&&(o=e.R32I)),i===e.RG&&(s===e.FLOAT&&(o=e.RG32F),s===e.HALF_FLOAT&&(o=e.RG16F),s===e.UNSIGNED_BYTE&&(o=e.RG8)),i===e.RG_INTEGER&&(s===e.UNSIGNED_BYTE&&(o=e.RG8UI),s===e.UNSIGNED_SHORT&&(o=e.RG16UI),s===e.UNSIGNED_INT&&(o=e.RG32UI),s===e.BYTE&&(o=e.RG8I),s===e.SHORT&&(o=e.RG16I),s===e.INT&&(o=e.RG32I)),i===e.RGB_INTEGER&&(s===e.UNSIGNED_BYTE&&(o=e.RGB8UI),s===e.UNSIGNED_SHORT&&(o=e.RGB16UI),s===e.UNSIGNED_INT&&(o=e.RGB32UI),s===e.BYTE&&(o=e.RGB8I),s===e.SHORT&&(o=e.RGB16I),s===e.INT&&(o=e.RGB32I)),i===e.RGBA_INTEGER&&(s===e.UNSIGNED_BYTE&&(o=e.RGBA8UI),s===e.UNSIGNED_SHORT&&(o=e.RGBA16UI),s===e.UNSIGNED_INT&&(o=e.RGBA32UI),s===e.BYTE&&(o=e.RGBA8I),s===e.SHORT&&(o=e.RGBA16I),s===e.INT&&(o=e.RGBA32I)),i===e.RGB&&s===e.UNSIGNED_INT_5_9_9_9_REV&&(o=e.RGB9_E5),i===e.RGBA){const t=a?ln:qn.getTransfer(r);s===e.FLOAT&&(o=e.RGBA32F),s===e.HALF_FLOAT&&(o=e.RGBA16F),s===e.UNSIGNED_BYTE&&(o=t===cn?e.SRGB8_ALPHA8:e.RGBA8),s===e.UNSIGNED_SHORT_4_4_4_4&&(o=e.RGBA4),s===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===it||n===lt?i=e.DEPTH24_STENCIL8:n===st?i=e.DEPTH32F_STENCIL8:n===tt&&(i=e.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):null===n||n===it||n===lt?i=e.DEPTH_COMPONENT24:n===st?i=e.DEPTH_COMPONENT32F:n===tt&&(i=e.DEPTH_COMPONENT16),i}function A(e,t){return!0===g(e)||e.isFramebufferTexture&&e.minFilter!==Xe&&e.minFilter!==Ke?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 S(e){const t=e.target;t.removeEventListener("dispose",S),function(e){const t=i.get(e);if(void 0===t.__webglInit)return;const n=e.source,s=d.get(n);if(s){const i=s[t.__cacheKey];i.usedTimes--,0===i.usedTimes&&M(e),0===Object.keys(s).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 s=t.textures;for(let r=0,o=s.length;r<o;r++){const t=i.get(s[r]);t.__webglTexture&&(e.deleteTexture(t.__webglTexture),a.memory.textures--),i.remove(s[r])}i.remove(t)}(n)}function M(t){const n=i.get(t);e.deleteTexture(n.__webglTexture);const s=t.source;delete d.get(s)[n.__cacheKey],a.memory.textures--}let w=0;function T(t,s){const r=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&&t.version>0&&r.__version!==t.version){const e=t.image;if(null===e)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else{if(!1!==e.complete)return void P(r,t,s);console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete")}}n.bindTexture(e.TEXTURE_2D,r.__webglTexture,e.TEXTURE0+s)}const E={[Ge]:e.REPEAT,[We]:e.CLAMP_TO_EDGE,[je]:e.MIRRORED_REPEAT},C={[Xe]:e.NEAREST,[qe]:e.NEAREST_MIPMAP_NEAREST,[Qe]:e.NEAREST_MIPMAP_LINEAR,[Ke]:e.LINEAR,[Ye]:e.LINEAR_MIPMAP_NEAREST,[Ze]:e.LINEAR_MIPMAP_LINEAR},R={[un]:e.NEVER,[_n]:e.ALWAYS,[dn]:e.LESS,[fn]:e.LEQUAL,[pn]:e.EQUAL,[vn]:e.GEQUAL,[mn]:e.GREATER,[gn]:e.NOTEQUAL};function I(n,r){if(r.type!==st||!1!==t.has("OES_texture_float_linear")||r.magFilter!==Ke&&r.magFilter!==Ye&&r.magFilter!==Qe&&r.magFilter!==Ze&&r.minFilter!==Ke&&r.minFilter!==Ye&&r.minFilter!==Qe&&r.minFilter!==Ze||console.warn("THREE.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[r.wrapS]),e.texParameteri(n,e.TEXTURE_WRAP_T,E[r.wrapT]),n!==e.TEXTURE_3D&&n!==e.TEXTURE_2D_ARRAY||e.texParameteri(n,e.TEXTURE_WRAP_R,E[r.wrapR]),e.texParameteri(n,e.TEXTURE_MAG_FILTER,C[r.magFilter]),e.texParameteri(n,e.TEXTURE_MIN_FILTER,C[r.minFilter]),r.compareFunction&&(e.texParameteri(n,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE),e.texParameteri(n,e.TEXTURE_COMPARE_FUNC,R[r.compareFunction])),!0===t.has("EXT_texture_filter_anisotropic")){if(r.magFilter===Xe)return;if(r.minFilter!==Qe&&r.minFilter!==Ze)return;if(r.type===st&&!1===t.has("OES_texture_float_linear"))return;if(r.anisotropy>1||i.get(r).__currentAnisotropy){const a=t.get("EXT_texture_filter_anisotropic");e.texParameterf(n,a.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(r.anisotropy,s.getMaxAnisotropy())),i.get(r).__currentAnisotropy=r.anisotropy}}}function D(t,n){let i=!1;void 0===t.__webglInit&&(t.__webglInit=!0,n.addEventListener("dispose",S));const s=n.source;let r=d.get(s);void 0===r&&(r={},d.set(s,r));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===r[o]&&(r[o]={texture:e.createTexture(),usedTimes:0},a.memory.textures++,i=!0),r[o].usedTimes++;const s=r[t.__cacheKey];void 0!==s&&(r[t.__cacheKey].usedTimes--,0===s.usedTimes&&M(n)),t.__cacheKey=o,t.__webglTexture=r[o].texture}return i}function P(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=D(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=qn.getPrimaries(qn.workingColorSpace),i=a.colorSpace===rn?null:qn.getPrimaries(a.colorSpace),d=a.colorSpace===rn||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,s.maxTextureSize);p=z(a,p);const f=r.convert(a.format,a.colorSpace),_=r.convert(a.type);let S,b=x(a.internalFormat,f,_,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=A(a,p);if(a.isDepthTexture)b=y(a.format===dt,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,_,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++)S=M[t],w?E&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,S.width,S.height,f,_,S.data):n.texImage2D(e.TEXTURE_2D,t,b,S.width,S.height,0,f,_,S.data);a.generateMipmaps=!1}else w?(T&&n.texStorage2D(e.TEXTURE_2D,C,b,p.width,p.height),E&&n.texSubImage2D(e.TEXTURE_2D,0,0,0,p.width,p.height,f,_,p.data)):n.texImage2D(e.TEXTURE_2D,0,b,p.width,p.height,0,f,_,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(S=M[t],a.format!==ht)if(null!==f)if(w){if(E)if(a.layerUpdates.size>0){const i=qo(S.width,S.height,a.format,a.type);for(const s of a.layerUpdates){const r=S.data.subarray(s*i/S.data.BYTES_PER_ELEMENT,(s+1)*i/S.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,s,S.width,S.height,1,f,r)}a.clearLayerUpdates()}else n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,0,S.width,S.height,p.depth,f,S.data)}else n.compressedTexImage3D(e.TEXTURE_2D_ARRAY,t,b,S.width,S.height,p.depth,0,S.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else w?E&&n.texSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,0,S.width,S.height,p.depth,f,_,S.data):n.texImage3D(e.TEXTURE_2D_ARRAY,t,b,S.width,S.height,p.depth,0,f,_,S.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++)S=M[t],a.format!==ht?null!==f?w?E&&n.compressedTexSubImage2D(e.TEXTURE_2D,t,0,0,S.width,S.height,f,S.data):n.compressedTexImage2D(e.TEXTURE_2D,t,b,S.width,S.height,0,S.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):w?E&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,S.width,S.height,f,_,S.data):n.texImage2D(e.TEXTURE_2D,t,b,S.width,S.height,0,f,_,S.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=qo(p.width,p.height,a.format,a.type);for(const i of a.layerUpdates){const s=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,_,s)}a.clearLayerUpdates()}else n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,0,p.width,p.height,p.depth,f,_,p.data)}else n.texImage3D(e.TEXTURE_2D_ARRAY,0,b,p.width,p.height,p.depth,0,f,_,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,_,p.data)):n.texImage3D(e.TEXTURE_3D,0,b,p.width,p.height,p.depth,0,f,_,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 s=0;s<C;s++)n.texImage2D(e.TEXTURE_2D,s,b,t,i,0,f,_,null),t>>=1,i>>=1}}else if(M.length>0){if(w&&T){const t=H(M[0]);n.texStorage2D(e.TEXTURE_2D,C,b,t.width,t.height)}for(let t=0,i=M.length;t<i;t++)S=M[t],w?E&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,f,_,S):n.texImage2D(e.TEXTURE_2D,t,b,f,_,S);a.generateMipmaps=!1}else if(w){if(T){const t=H(p);n.texStorage2D(e.TEXTURE_2D,C,b,t.width,t.height)}E&&n.texSubImage2D(e.TEXTURE_2D,0,0,0,f,_,p)}else n.texImage2D(e.TEXTURE_2D,0,b,f,_,p);g(a)&&v(l),u.__version=h.version,a.onUpdate&&a.onUpdate(a)}t.__version=a.version}function B(t,s,a,l,c,h){const u=r.convert(a.format,a.colorSpace),d=r.convert(a.type),p=x(a.internalFormat,u,d,a.colorSpace),f=i.get(s),m=i.get(a);if(m.__renderTarget=s,!f.__hasExternalTextures){const t=Math.max(1,s.width>>h),i=Math.max(1,s.height>>h);c===e.TEXTURE_3D||c===e.TEXTURE_2D_ARRAY?n.texImage3D(c,h,p,t,i,s.depth,0,u,d,null):n.texImage2D(c,h,p,t,i,0,u,d,null)}n.bindFramebuffer(e.FRAMEBUFFER,t),O(s)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,l,c,m.__webglTexture,0,N(s)):(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 L(t,n,i){if(e.bindRenderbuffer(e.RENDERBUFFER,t),n.depthBuffer){const s=n.depthTexture,r=s&&s.isDepthTexture?s.type:null,a=y(n.stencilBuffer,r),l=n.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,c=N(n);O(n)?o.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,c,a,n.width,n.height):i?e.renderbufferStorageMultisample(e.RENDERBUFFER,c,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 s=0;s<t.length;s++){const a=t[s],l=r.convert(a.format,a.colorSpace),c=r.convert(a.type),h=x(a.internalFormat,l,c,a.colorSpace),u=N(n);i&&!1===O(n)?e.renderbufferStorageMultisample(e.RENDERBUFFER,u,h,n.width,n.height):O(n)?o.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,u,h,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,h,n.width,n.height)}}e.bindRenderbuffer(e.RENDERBUFFER,null)}function U(t){const s=i.get(t),r=!0===t.isWebGLCubeRenderTarget;if(s.__boundDepthTexture!==t.depthTexture){const e=t.depthTexture;if(s.__depthDisposeCallback&&s.__depthDisposeCallback(),e){const t=()=>{delete s.__boundDepthTexture,delete s.__depthDisposeCallback,e.removeEventListener("dispose",t)};e.addEventListener("dispose",t),s.__depthDisposeCallback=t}s.__boundDepthTexture=e}if(t.depthTexture&&!s.__autoAllocateDepthBuffer){if(r)throw new Error("target.depthTexture not supported in Cube render targets");!function(t,s){if(s&&s.isWebGLCubeRenderTarget)throw new Error("Depth Texture with cube render targets is not supported");if(n.bindFramebuffer(e.FRAMEBUFFER,t),!s.depthTexture||!s.depthTexture.isDepthTexture)throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");const r=i.get(s.depthTexture);r.__renderTarget=s,r.__webglTexture&&s.depthTexture.image.width===s.width&&s.depthTexture.image.height===s.height||(s.depthTexture.image.width=s.width,s.depthTexture.image.height=s.height,s.depthTexture.needsUpdate=!0),T(s.depthTexture,0);const a=r.__webglTexture,l=N(s);if(s.depthTexture.format===ut)O(s)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.TEXTURE_2D,a,0,l):e.framebufferTexture2D(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.TEXTURE_2D,a,0);else{if(s.depthTexture.format!==dt)throw new Error("Unknown depthTexture format");O(s)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,e.TEXTURE_2D,a,0,l):e.framebufferTexture2D(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,e.TEXTURE_2D,a,0)}}(s.__webglFramebuffer,t)}else if(r){s.__webglDepthbuffer=[];for(let i=0;i<6;i++)if(n.bindFramebuffer(e.FRAMEBUFFER,s.__webglFramebuffer[i]),void 0===s.__webglDepthbuffer[i])s.__webglDepthbuffer[i]=e.createRenderbuffer(),L(s.__webglDepthbuffer[i],t,!1);else{const n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,r=s.__webglDepthbuffer[i];e.bindRenderbuffer(e.RENDERBUFFER,r),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,r)}}else if(n.bindFramebuffer(e.FRAMEBUFFER,s.__webglFramebuffer),void 0===s.__webglDepthbuffer)s.__webglDepthbuffer=e.createRenderbuffer(),L(s.__webglDepthbuffer,t,!1);else{const n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,i=s.__webglDepthbuffer;e.bindRenderbuffer(e.RENDERBUFFER,i),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,i)}n.bindFramebuffer(e.FRAMEBUFFER,null)}const F=[],k=[];function N(e){return Math.min(s.maxSamples,e.samples)}function O(e){const n=i.get(e);return e.samples>0&&!0===t.has("WEBGL_multisampled_render_to_texture")&&!1!==n.__useRenderToTexture}function z(e,t){const n=e.colorSpace,i=e.format,s=e.type;return!0===e.isCompressedTexture||!0===e.isVideoTexture||n!==on&&n!==rn&&(qn.getTransfer(n)===cn?i===ht&&s===Je||console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",n)),t}function H(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>=s.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+e+" texture units while this GPU supports only "+s.maxTextures),w+=1,e},this.resetTextureUnits=function(){w=0},this.setTexture2D=T,this.setTexture2DArray=function(t,s){const r=i.get(t);t.version>0&&r.__version!==t.version?P(r,t,s):n.bindTexture(e.TEXTURE_2D_ARRAY,r.__webglTexture,e.TEXTURE0+s)},this.setTexture3D=function(t,s){const r=i.get(t);t.version>0&&r.__version!==t.version?P(r,t,s):n.bindTexture(e.TEXTURE_3D,r.__webglTexture,e.TEXTURE0+s)},this.setTextureCube=function(t,a){const o=i.get(t);t.version>0&&o.__version!==t.version?function(t,a,o){if(6!==a.image.length)return;const l=D(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=qn.getPrimaries(qn.workingColorSpace),i=a.colorSpace===rn?null:qn.getPrimaries(a.colorSpace),u=a.colorSpace===rn||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,s.maxCubemapSize),f[e]=z(a,f[e]);const _=f[0],y=r.convert(a.format,a.colorSpace),S=r.convert(a.type),b=x(a.internalFormat,y,S,a.colorSpace),M=!0!==a.isVideoTexture,w=void 0===h.__version||!0===l,T=c.dataReady;let E,C=A(a,_);if(I(e.TEXTURE_CUBE_MAP,a),d){M&&w&&n.texStorage2D(e.TEXTURE_CUBE_MAP,C,b,_.width,_.height);for(let t=0;t<6;t++){E=f[t].mipmaps;for(let i=0;i<E.length;i++){const s=E[i];a.format!==ht?null!==y?M?T&&n.compressedTexSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,i,0,0,s.width,s.height,y,s.data):n.compressedTexImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,i,b,s.width,s.height,0,s.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):M?T&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,i,0,0,s.width,s.height,y,S,s.data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,i,b,s.width,s.height,0,y,S,s.data)}}}else{if(E=a.mipmaps,M&&w){E.length>0&&C++;const t=H(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,S,f[t].data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,b,f[t].width,f[t].height,0,y,S,f[t].data);for(let i=0;i<E.length;i++){const s=E[i].image[t].image;M?T&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,i+1,0,0,s.width,s.height,y,S,s.data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,i+1,b,s.width,s.height,0,y,S,s.data)}}else{M?T&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,y,S,f[t]):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,b,y,S,f[t]);for(let i=0;i<E.length;i++){const s=E[i];M?T&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,i+1,0,0,y,S,s.image[t]):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,i+1,b,y,S,s.image[t])}}}g(a)&&v(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,s){const r=i.get(t);void 0!==n&&B(r.__webglFramebuffer,t,t.texture,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,0),void 0!==s&&U(t)},this.setupRenderTarget=function(t){const s=t.texture,o=i.get(t),l=i.get(s);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=s.version,a.memory.textures++),h){o.__webglFramebuffer=[];for(let t=0;t<6;t++)if(s.mipmaps&&s.mipmaps.length>0){o.__webglFramebuffer[t]=[];for(let n=0;n<s.mipmaps.length;n++)o.__webglFramebuffer[t][n]=e.createFramebuffer()}else o.__webglFramebuffer[t]=e.createFramebuffer()}else{if(s.mipmaps&&s.mipmaps.length>0){o.__webglFramebuffer=[];for(let t=0;t<s.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===O(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 s=r.convert(i.format,i.colorSpace),a=r.convert(i.type),l=x(i.internalFormat,s,a,i.colorSpace,!0===t.isXRRenderTarget),h=N(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(),L(o.__webglDepthRenderbuffer,t,!0)),n.bindFramebuffer(e.FRAMEBUFFER,null)}}if(h){n.bindTexture(e.TEXTURE_CUBE_MAP,l.__webglTexture),I(e.TEXTURE_CUBE_MAP,s);for(let n=0;n<6;n++)if(s.mipmaps&&s.mipmaps.length>0)for(let i=0;i<s.mipmaps.length;i++)B(o.__webglFramebuffer[n][i],t,s,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+n,i);else B(o.__webglFramebuffer[n],t,s,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+n,0);g(s)&&v(e.TEXTURE_CUBE_MAP),n.unbindTexture()}else if(u){for(let s=0,r=c.length;s<r;s++){const r=c[s],a=i.get(r);n.bindTexture(e.TEXTURE_2D,a.__webglTexture),I(e.TEXTURE_2D,r),B(o.__webglFramebuffer,t,r,e.COLOR_ATTACHMENT0+s,e.TEXTURE_2D,0),g(r)&&v(e.TEXTURE_2D)}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,s),s.mipmaps&&s.mipmaps.length>0)for(let n=0;n<s.mipmaps.length;n++)B(o.__webglFramebuffer[n],t,s,e.COLOR_ATTACHMENT0,i,n);else B(o.__webglFramebuffer,t,s,e.COLOR_ATTACHMENT0,i,0);g(s)&&v(i),n.unbindTexture()}t.depthBuffer&&U(t)},this.updateRenderTargetMipmap=function(e){const t=e.textures;for(let s=0,r=t.length;s<r;s++){const r=t[s];if(g(r)){const t=_(e),s=i.get(r).__webglTexture;n.bindTexture(t,s),v(t),n.unbindTexture()}}},this.updateMultisampleRenderTarget=function(t){if(t.samples>0)if(!1===O(t)){const s=t.textures,r=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=s.length>1;if(u)for(let t=0;t<s.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),n.bindFramebuffer(e.DRAW_FRAMEBUFFER,h.__webglFramebuffer);for(let n=0;n<s.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(s[n]).__webglTexture;e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)}e.blitFramebuffer(0,0,r,a,0,0,r,a,o,e.NEAREST),!0===l&&(F.length=0,k.length=0,F.push(e.COLOR_ATTACHMENT0+n),t.depthBuffer&&!1===t.resolveDepthBuffer&&(F.push(c),k.push(c),e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,k)),e.invalidateFramebuffer(e.READ_FRAMEBUFFER,F))}if(n.bindFramebuffer(e.READ_FRAMEBUFFER,null),n.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),u)for(let t=0;t<s.length;t++){n.bindFramebuffer(e.FRAMEBUFFER,h.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.RENDERBUFFER,h.__webglColorRenderbuffer[t]);const r=i.get(s[t]).__webglTexture;n.bindFramebuffer(e.FRAMEBUFFER,h.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.TEXTURE_2D,r,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=U,this.setupFrameBufferTexture=B,this.useMultisampledRTT=O}function Sh(e,t){return{convert:function(n,i=""){let s;const r=qn.getTransfer(i);if(n===Je)return e.UNSIGNED_BYTE;if(n===at)return e.UNSIGNED_SHORT_4_4_4_4;if(n===ot)return e.UNSIGNED_SHORT_5_5_5_1;if(n===ct)return e.UNSIGNED_INT_5_9_9_9_REV;if(n===$e)return e.BYTE;if(n===et)return e.SHORT;if(n===tt)return e.UNSIGNED_SHORT;if(n===nt)return e.INT;if(n===it)return e.UNSIGNED_INT;if(n===st)return e.FLOAT;if(n===rt)return e.HALF_FLOAT;if(1021===n)return e.ALPHA;if(1022===n)return e.RGB;if(n===ht)return e.RGBA;if(1024===n)return e.LUMINANCE;if(1025===n)return e.LUMINANCE_ALPHA;if(n===ut)return e.DEPTH_COMPONENT;if(n===dt)return e.DEPTH_STENCIL;if(n===pt)return e.RED;if(n===ft)return e.RED_INTEGER;if(n===mt)return e.RG;if(n===gt)return e.RG_INTEGER;if(n===vt)return e.RGBA_INTEGER;if(n===_t||n===xt||n===yt||n===At)if(r===cn){if(s=t.get("WEBGL_compressed_texture_s3tc_srgb"),null===s)return null;if(n===_t)return s.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===xt)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===yt)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===At)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(s=t.get("WEBGL_compressed_texture_s3tc"),null===s)return null;if(n===_t)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===xt)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===yt)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===At)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(n===St||n===bt||n===Mt||n===wt){if(s=t.get("WEBGL_compressed_texture_pvrtc"),null===s)return null;if(n===St)return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===bt)return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===Mt)return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===wt)return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(n===Tt||n===Et||n===Ct){if(s=t.get("WEBGL_compressed_texture_etc"),null===s)return null;if(n===Tt||n===Et)return r===cn?s.COMPRESSED_SRGB8_ETC2:s.COMPRESSED_RGB8_ETC2;if(n===Ct)return r===cn?s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:s.COMPRESSED_RGBA8_ETC2_EAC}if(n===Rt||n===It||n===Dt||n===Pt||n===Bt||n===Lt||n===Ut||n===Ft||n===kt||n===Nt||n===Ot||n===zt||n===Ht||n===Vt){if(s=t.get("WEBGL_compressed_texture_astc"),null===s)return null;if(n===Rt)return r===cn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:s.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===It)return r===cn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:s.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===Dt)return r===cn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:s.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===Pt)return r===cn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:s.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===Bt)return r===cn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:s.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===Lt)return r===cn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:s.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===Ut)return r===cn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:s.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===Ft)return r===cn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:s.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===kt)return r===cn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:s.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===Nt)return r===cn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:s.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===Ot)return r===cn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:s.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===zt)return r===cn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:s.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===Ht)return r===cn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:s.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===Vt)return r===cn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:s.COMPRESSED_RGBA_ASTC_12x12_KHR}if(n===Gt||n===Wt||n===jt){if(s=t.get("EXT_texture_compression_bptc"),null===s)return null;if(n===Gt)return r===cn?s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:s.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===Wt)return s.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===jt)return s.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}if(36283===n||n===Xt||n===qt||n===Qt){if(s=t.get("EXT_texture_compression_rgtc"),null===s)return null;if(n===Gt)return s.COMPRESSED_RED_RGTC1_EXT;if(n===Xt)return s.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===qt)return s.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===Qt)return s.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}return n===lt?e.UNSIGNED_INT_24_8:void 0!==e[n]?e[n]:null}}}class bh{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t,n){if(null===this.texture){const i=new ni;e.properties.get(i).__webglTexture=t.texture,t.depthNear===n.depthNear&&t.depthFar===n.depthFar||(this.depthNear=t.depthNear,this.depthFar=t.depthFar),this.texture=i}}getMesh(e){if(null!==this.texture&&null===this.mesh){const t=e.cameras[0].viewport,n=new _r({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 ur(new La(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class Mh extends Mn{constructor(e,t){super();const n=this;let i=null,s=1,r=null,a="local-floor",o=1,l=null,c=null,h=null,u=null,d=null,p=null;const f=new bh,m=t.getContextAttributes();let g=null,v=null;const _=[],x=[],y=new Fn;let A=null;const S=new br;S.viewport=new ii;const b=new br;b.viewport=new ii;const M=[S,b],w=new Do;let T=null,E=null;function C(e){const t=x.indexOf(e.inputSource);if(-1===t)return;const n=_[t];void 0!==n&&(n.update(e.inputSource,e.frame,l||r),n.dispatchEvent({type:e.type,data:e.inputSource}))}function R(){i.removeEventListener("select",C),i.removeEventListener("selectstart",C),i.removeEventListener("selectend",C),i.removeEventListener("squeeze",C),i.removeEventListener("squeezestart",C),i.removeEventListener("squeezeend",C),i.removeEventListener("end",R),i.removeEventListener("inputsourceschange",I);for(let e=0;e<_.length;e++){const t=x[e];null!==t&&(x[e]=null,_[e].disconnect(t))}T=null,E=null,f.reset(),e.setRenderTarget(g),d=null,u=null,h=null,i=null,v=null,U.stop(),n.isPresenting=!1,e.setPixelRatio(A),e.setSize(y.width,y.height,!1),n.dispatchEvent({type:"sessionend"})}function I(e){for(let t=0;t<e.removed.length;t++){const n=e.removed[t],i=x.indexOf(n);i>=0&&(x[i]=null,_[i].disconnect(n))}for(let t=0;t<e.added.length;t++){const n=e.added[t];let i=x.indexOf(n);if(-1===i){for(let e=0;e<_.length;e++){if(e>=x.length){x.push(n),i=e;break}if(null===x[e]){x[e]=n,i=e;break}}if(-1===i)break}const s=_[i];s&&s.connect(n)}}this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(e){let t=_[e];return void 0===t&&(t=new Ir,_[e]=t),t.getTargetRaySpace()},this.getControllerGrip=function(e){let t=_[e];return void 0===t&&(t=new Ir,_[e]=t),t.getGripSpace()},this.getHand=function(e){let t=_[e];return void 0===t&&(t=new Ir,_[e]=t),t.getHandSpace()},this.setFramebufferScaleFactor=function(e){s=e,!0===n.isPresenting&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(e){a=e,!0===n.isPresenting&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return l||r},this.setReferenceSpace=function(e){l=e},this.getBaseLayer=function(){return null!==u?u:d},this.getBinding=function(){return h},this.getFrame=function(){return p},this.getSession=function(){return i},this.setSession=async function(c){if(i=c,null!==i){g=e.getRenderTarget(),i.addEventListener("select",C),i.addEventListener("selectstart",C),i.addEventListener("selectend",C),i.addEventListener("squeeze",C),i.addEventListener("squeezestart",C),i.addEventListener("squeezeend",C),i.addEventListener("end",R),i.addEventListener("inputsourceschange",I),!0!==m.xrCompatible&&await t.makeXRCompatible(),A=e.getPixelRatio(),e.getSize(y);if("undefined"!=typeof XRWebGLBinding&&"createProjectionLayer"in XRWebGLBinding.prototype){let n=null,r=null,a=null;m.depth&&(a=m.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,n=m.stencil?dt:ut,r=m.stencil?lt:it);const o={colorFormat:t.RGBA8,depthFormat:a,scaleFactor:s};h=new XRWebGLBinding(i,t),u=h.createProjectionLayer(o),i.updateRenderState({layers:[u]}),e.setPixelRatio(1),e.setSize(u.textureWidth,u.textureHeight,!1),v=new ri(u.textureWidth,u.textureHeight,{format:ht,type:Je,depthTexture:new Ba(u.textureWidth,u.textureHeight,r,void 0,void 0,void 0,void 0,void 0,void 0,n),stencilBuffer:m.stencil,colorSpace:e.outputColorSpace,samples:m.antialias?4:0,resolveDepthBuffer:!1===u.ignoreDepthValues})}else{const n={antialias:m.antialias,alpha:!0,depth:m.depth,stencil:m.stencil,framebufferScaleFactor:s};d=new XRWebGLLayer(i,t,n),i.updateRenderState({baseLayer:d}),e.setPixelRatio(1),e.setSize(d.framebufferWidth,d.framebufferHeight,!1),v=new ri(d.framebufferWidth,d.framebufferHeight,{format:ht,type:Je,colorSpace:e.outputColorSpace,stencilBuffer:m.stencil})}v.isXRRenderTarget=!0,this.setFoveation(o),l=null,r=await i.requestReferenceSpace(a),U.setContext(i),U.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(null!==i)return i.environmentBlendMode},this.getDepthTexture=function(){return f.getDepthTexture()};const D=new ci,P=new ci;function B(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!==f.texture&&(f.depthNear>0&&(t=f.depthNear),f.depthFar>0&&(n=f.depthFar)),w.near=b.near=S.near=t,w.far=b.far=S.far=n,T===w.near&&E===w.far||(i.updateRenderState({depthNear:w.near,depthFar:w.far}),T=w.near,E=w.far),S.layers.mask=2|e.layers.mask,b.layers.mask=4|e.layers.mask,w.layers.mask=S.layers.mask|b.layers.mask;const s=e.parent,r=w.cameras;B(w,s);for(let i=0;i<r.length;i++)B(r[i],s);2===r.length?function(e,t,n){D.setFromMatrixPosition(t.matrixWorld),P.setFromMatrixPosition(n.matrixWorld);const i=D.distanceTo(P),s=t.projectionMatrix.elements,r=n.projectionMatrix.elements,a=s[14]/(s[10]-1),o=s[14]/(s[10]+1),l=(s[9]+1)/s[5],c=(s[9]-1)/s[5],h=(s[8]-1)/s[0],u=(r[8]+1)/r[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===s[10])e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse);else{const t=a+f,n=o+f,s=d-m,r=p+(i-m),h=l*o/n*t,u=c*o/n*t;e.projectionMatrix.makePerspective(s,r,h,u,t,n),e.projectionMatrixInverse.copy(e.projectionMatrix).invert()}}(w,S,b):w.projectionMatrix.copy(S.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*Cn*Math.atan(1/e.projectionMatrix.elements[5]),e.zoom=1)}(e,w,s)},this.getCamera=function(){return w},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!==f.texture},this.getDepthSensingMesh=function(){return f.getMesh(w)};let L=null;const U=new Qo;U.setAnimationLoop(function(t,s){if(c=s.getViewerPose(l||r),p=s,null!==c){const t=c.views;null!==d&&(e.setRenderTargetFramebuffer(v,d.framebuffer),e.setRenderTarget(v));let n=!1;t.length!==w.cameras.length&&(w.cameras.length=0,n=!0);for(let i=0;i<t.length;i++){const s=t[i];let r=null;if(null!==d)r=d.getViewport(s);else{const t=h.getViewSubImage(u,s);r=t.viewport,0===i&&(e.setRenderTargetTextures(v,t.colorTexture,u.ignoreDepthValues?void 0:t.depthStencilTexture),e.setRenderTarget(v))}let a=M[i];void 0===a&&(a=new br,a.layers.enable(i),a.viewport=new ii,M[i]=a),a.matrix.fromArray(s.transform.matrix),a.matrix.decompose(a.position,a.quaternion,a.scale),a.projectionMatrix.fromArray(s.projectionMatrix),a.projectionMatrixInverse.copy(a.projectionMatrix).invert(),a.viewport.set(r.x,r.y,r.width,r.height),0===i&&(w.matrix.copy(a.matrix),w.matrix.decompose(w.position,w.quaternion,w.scale)),!0===n&&w.cameras.push(a)}const s=i.enabledFeatures;if(s&&s.includes("depth-sensing")&&"gpu-optimized"==i.depthUsage&&h){const n=h.getDepthInformation(t[0]);n&&n.isValid&&n.texture&&f.init(e,n,i.renderState)}}for(let e=0;e<_.length;e++){const t=x[e],n=_[e];null!==t&&void 0!==n&&n.update(t,s,l||r)}L&&L(t,s),s.detectedPlanes&&n.dispatchEvent({type:"planesdetected",data:s}),p=null}),this.setAnimationLoop=function(e){L=e},this.dispose=function(){}}}const wh=new Ki,Th=new Oi;function Eh(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 s=t.get(i),r=s.envMap,a=s.envMapRotation;r&&(e.envMap.value=r,wh.copy(a),wh.x*=-1,wh.y*=-1,wh.z*=-1,r.isCubeTexture&&!1===r.isRenderTargetTexture&&(wh.y*=-1,wh.z*=-1),e.envMapRotation.value.setFromMatrix4(Th.makeRotationFromEuler(wh)),e.flipEnvMap.value=r.isCubeTexture&&!1===r.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,gr(e)),n.isFog?(t.fogNear.value=n.near,t.fogFar.value=n.far):n.isFogExp2&&(t.fogDensity.value=n.density)},refreshMaterialUniforms:function(e,s,r,a,o){s.isMeshBasicMaterial||s.isMeshLambertMaterial?i(e,s):s.isMeshToonMaterial?(i(e,s),function(e,t){t.gradientMap&&(e.gradientMap.value=t.gradientMap)}(e,s)):s.isMeshPhongMaterial?(i(e,s),function(e,t){e.specular.value.copy(t.specular),e.shininess.value=Math.max(t.shininess,1e-4)}(e,s)):s.isMeshStandardMaterial?(i(e,s),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,s),s.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,s,o)):s.isMeshMatcapMaterial?(i(e,s),function(e,t){t.matcap&&(e.matcap.value=t.matcap)}(e,s)):s.isMeshDepthMaterial?i(e,s):s.isMeshDistanceMaterial?(i(e,s),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,s)):s.isMeshNormalMaterial?i(e,s):s.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,s),s.isLineDashedMaterial&&function(e,t){e.dashSize.value=t.dashSize,e.totalSize.value=t.dashSize+t.gapSize,e.scale.value=t.scale}(e,s)):s.isPointsMaterial?function(e,t,i,s){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.size.value=t.size*i,e.scale.value=.5*s,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,s,r,a):s.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,s):s.isShadowMaterial?(e.color.value.copy(s.color),e.opacity.value=s.opacity):s.isShaderMaterial&&(s.uniformsNeedUpdate=!1)}}}function Ch(e,t,n,i){let s={},r={},a=[];const o=e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS);function l(e,t,n,i){const s=e.value,r=t+"_"+n;if(void 0===i[r])return i[r]="number"==typeof s||"boolean"==typeof s?s:s.clone(),!0;{const e=i[r];if("number"==typeof s||"boolean"==typeof s){if(e!==s)return i[r]=s,!0}else if(!1===e.equals(s))return e.copy(s),!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?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.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(s[n.id]),delete s[n.id],delete r[n.id]}return{bind:function(e,t){const n=t.program;i.uniformBlockBinding(e,n)},update:function(n,u){let d=s[n.id];void 0===d&&(!function(e){const t=e.uniforms;let n=0;const i=16;for(let r=0,a=t.length;r<a;r++){const e=Array.isArray(t[r])?t[r]:[t[r]];for(let t=0,s=e.length;t<s;t++){const s=e[t],r=Array.isArray(s.value)?s.value:[s.value];for(let e=0,t=r.length;e<t;e++){const t=c(r[e]),a=n%i,o=a%t.boundary,l=a+o;n+=o,0!==l&&i-l<t.storage&&(n+=i-l),s.__data=new Float32Array(t.storage/Float32Array.BYTES_PER_ELEMENT),s.__offset=n,n+=t.storage}}}const s=n%i;s>0&&(n+=i-s);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 console.error("THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}();t.__bindingPointIndex=n;const i=e.createBuffer(),s=t.__size,r=t.usage;return e.bindBuffer(e.UNIFORM_BUFFER,i),e.bufferData(e.UNIFORM_BUFFER,s,r),e.bindBuffer(e.UNIFORM_BUFFER,null),e.bindBufferBase(e.UNIFORM_BUFFER,n,i),i}(n),s[n.id]=d,n.addEventListener("dispose",h));const p=u.program;i.updateUBOMapping(n,p);const f=t.render.frame;r[n.id]!==f&&(!function(t){const n=s[t.id],i=t.uniforms,r=t.__cache;e.bindBuffer(e.UNIFORM_BUFFER,n);for(let s=0,a=i.length;s<a;s++){const t=Array.isArray(i[s])?i[s]:[i[s]];for(let n=0,i=t.length;n<i;n++){const i=t[n];if(!0===l(i,s,n,r)){const t=i.__offset,n=Array.isArray(i.value)?i.value:[i.value];let s=0;for(let r=0;r<n.length;r++){const a=n[r],o=c(a);"number"==typeof a||"boolean"==typeof a?(i.__data[0]=a,e.bufferSubData(e.UNIFORM_BUFFER,t+s,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,s),s+=o.storage/Float32Array.BYTES_PER_ELEMENT)}e.bufferSubData(e.UNIFORM_BUFFER,t,i.__data)}}}e.bindBuffer(e.UNIFORM_BUFFER,null)}(n),r[n.id]=f)},dispose:function(){for(const t in s)e.deleteBuffer(s[t]);a=[],s={},r={}}}}class Rh{constructor(e={}){const{canvas:t=Hn(),context:n=null,depth:i=!0,stencil:s=!1,alpha:r=!1,antialias:a=!1,premultipliedAlpha:o=!0,preserveDrawingBuffer:l=!1,powerPreference:c="default",failIfMajorPerformanceCaveat:h=!1,reverseDepthBuffer:u=!1}=e;let d;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.");d=n.getContextAttributes().alpha}else d=r;const p=new Uint32Array(4),f=new Int32Array(4);let m=null,g=null;const v=[],_=[];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._outputColorSpace=an,this.toneMapping=0,this.toneMappingExposure=1;const x=this;let y=!1,A=0,S=0,b=null,M=-1,w=null;const T=new ii,E=new ii;let C=null;const R=new Ds(0);let I=0,D=t.width,P=t.height,B=1,L=null,U=null;const F=new ii(0,0,D,P),k=new ii(0,0,D,P);let N=!1;const O=new ua;let z=!1,H=!1;this.transmissionResolutionScale=1;const V=new Oi,G=new Oi,W=new ci,j=new ii,X={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let q=!1;function Q(){return null===b?B:1}let K,Y,Z,J,$,ee,te,ie,se,re,ae,oe,le,ce,he,ue,de,pe,fe,me,ge,ve,_e,xe,ye=n;function Ae(e,n){return t.getContext(e,n)}try{const e={alpha:!0,depth:i,stencil:s,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",Me,!1),t.addEventListener("webglcontextrestored",we,!1),t.addEventListener("webglcontextcreationerror",Te,!1),null===ye){const t="webgl2";if(ye=Ae(t,e),null===ye)throw Ae(t)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(We){throw console.error("THREE.WebGLRenderer: "+We.message),We}function Se(){K=new Tl(ye),K.init(),ve=new Sh(ye,K),Y=new rl(ye,K,e,ve),Z=new yh(ye,K),Y.reverseDepthBuffer&&u&&Z.buffers.depth.setReversed(!0),J=new Rl(ye),$=new oh,ee=new Ah(ye,K,Z,$,Y,ve,J),te=new ol(x),ie=new wl(x),se=new Ko(ye),_e=new il(ye,se),re=new El(ye,se,J,_e),ae=new Dl(ye,re,se,J),fe=new Il(ye,Y,ee),ue=new al($),oe=new ah(x,te,ie,K,Y,_e,ue),le=new Eh(x,$),ce=new uh,he=new vh(K),pe=new nl(x,te,ie,Z,ae,d,o),de=new _h(x,ae,Y),xe=new Ch(ye,J,Y,Z),me=new sl(ye,K,J),ge=new Cl(ye,K,J),J.programs=oe.programs,x.capabilities=Y,x.extensions=K,x.properties=$,x.renderLists=ce,x.shadowMap=de,x.state=Z,x.info=J}Se();const be=new Mh(x,ye);function Me(e){e.preventDefault(),y=!0}function we(){y=!1;const e=J.autoReset,t=de.enabled,n=de.autoUpdate,i=de.needsUpdate,s=de.type;Se(),J.autoReset=e,de.enabled=t,de.autoUpdate=n,de.needsUpdate=i,de.type=s}function Te(e){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",e.statusMessage)}function Ee(e){const t=e.target;t.removeEventListener("dispose",Ee),function(e){(function(e){const t=$.get(e).programs;void 0!==t&&(t.forEach(function(e){oe.releaseProgram(e)}),e.isShaderMaterial&&oe.releaseShaderCache(e))})(e),$.remove(e)}(t)}function Ce(e,t,n){!0===e.transparent&&2===e.side&&!1===e.forceSinglePass?(e.side=1,e.needsUpdate=!0,Ne(e,t,n),e.side=0,e.needsUpdate=!0,Ne(e,t,n),e.side=2):Ne(e,t,n)}this.xr=be,this.getContext=function(){return ye},this.getContextAttributes=function(){return ye.getContextAttributes()},this.forceContextLoss=function(){const e=K.get("WEBGL_lose_context");e&&e.loseContext()},this.forceContextRestore=function(){const e=K.get("WEBGL_lose_context");e&&e.restoreContext()},this.getPixelRatio=function(){return B},this.setPixelRatio=function(e){void 0!==e&&(B=e,this.setSize(D,P,!1))},this.getSize=function(e){return e.set(D,P)},this.setSize=function(e,n,i=!0){be.isPresenting?console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting."):(D=e,P=n,t.width=Math.floor(e*B),t.height=Math.floor(n*B),!0===i&&(t.style.width=e+"px",t.style.height=n+"px"),this.setViewport(0,0,e,n))},this.getDrawingBufferSize=function(e){return e.set(D*B,P*B).floor()},this.setDrawingBufferSize=function(e,n,i){D=e,P=n,B=i,t.width=Math.floor(e*i),t.height=Math.floor(n*i),this.setViewport(0,0,e,n)},this.getCurrentViewport=function(e){return e.copy(T)},this.getViewport=function(e){return e.copy(F)},this.setViewport=function(e,t,n,i){e.isVector4?F.set(e.x,e.y,e.z,e.w):F.set(e,t,n,i),Z.viewport(T.copy(F).multiplyScalar(B).round())},this.getScissor=function(e){return e.copy(k)},this.setScissor=function(e,t,n,i){e.isVector4?k.set(e.x,e.y,e.z,e.w):k.set(e,t,n,i),Z.scissor(E.copy(k).multiplyScalar(B).round())},this.getScissorTest=function(){return N},this.setScissorTest=function(e){Z.setScissorTest(N=e)},this.setOpaqueSort=function(e){L=e},this.setTransparentSort=function(e){U=e},this.getClearColor=function(e){return e.copy(pe.getClearColor())},this.setClearColor=function(){pe.setClearColor.apply(pe,arguments)},this.getClearAlpha=function(){return pe.getClearAlpha()},this.setClearAlpha=function(){pe.setClearAlpha.apply(pe,arguments)},this.clear=function(e=!0,t=!0,n=!0){let i=0;if(e){let e=!1;if(null!==b){const t=b.texture.format;e=t===vt||t===gt||t===ft}if(e){const e=b.texture.type,t=e===Je||e===it||e===tt||e===lt||e===at||e===ot,n=pe.getClearColor(),i=pe.getClearAlpha(),s=n.r,r=n.g,a=n.b;t?(p[0]=s,p[1]=r,p[2]=a,p[3]=i,ye.clearBufferuiv(ye.COLOR,0,p)):(f[0]=s,f[1]=r,f[2]=a,f[3]=i,ye.clearBufferiv(ye.COLOR,0,f))}else i|=ye.COLOR_BUFFER_BIT}t&&(i|=ye.DEPTH_BUFFER_BIT),n&&(i|=ye.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),ye.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",Me,!1),t.removeEventListener("webglcontextrestored",we,!1),t.removeEventListener("webglcontextcreationerror",Te,!1),pe.dispose(),ce.dispose(),he.dispose(),$.dispose(),te.dispose(),ie.dispose(),ae.dispose(),_e.dispose(),xe.dispose(),oe.dispose(),be.dispose(),be.removeEventListener("sessionstart",Ie),be.removeEventListener("sessionend",De),Pe.stop()},this.renderBufferDirect=function(e,t,n,i,s,r){null===t&&(t=X);const a=s.isMesh&&s.matrixWorld.determinant()<0,o=function(e,t,n,i,s){!0!==t.isScene&&(t=X);ee.resetTextureUnits();const r=t.fog,a=i.isMeshStandardMaterial?t.environment:null,o=null===b?x.outputColorSpace:!0===b.isXRRenderTarget?b.texture.colorSpace:on,l=(i.isMeshStandardMaterial?ie:te).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!==b&&!0!==b.isXRRenderTarget||(f=x.toneMapping));const m=n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color,v=void 0!==m?m.length:0,_=$.get(i),y=g.state.lights;if(!0===z&&(!0===H||e!==w)){const t=e===w&&i.id===M;ue.setState(i,e,t)}let A=!1;i.version===_.__version?_.needsLights&&_.lightsStateVersion!==y.state.version||_.outputColorSpace!==o||s.isBatchedMesh&&!1===_.batching?A=!0:s.isBatchedMesh||!0!==_.batching?s.isBatchedMesh&&!0===_.batchingColor&&null===s.colorTexture||s.isBatchedMesh&&!1===_.batchingColor&&null!==s.colorTexture||s.isInstancedMesh&&!1===_.instancing?A=!0:s.isInstancedMesh||!0!==_.instancing?s.isSkinnedMesh&&!1===_.skinning?A=!0:s.isSkinnedMesh||!0!==_.skinning?s.isInstancedMesh&&!0===_.instancingColor&&null===s.instanceColor||s.isInstancedMesh&&!1===_.instancingColor&&null!==s.instanceColor||s.isInstancedMesh&&!0===_.instancingMorph&&null===s.morphTexture||s.isInstancedMesh&&!1===_.instancingMorph&&null!==s.morphTexture||_.envMap!==l||!0===i.fog&&_.fog!==r?A=!0:void 0===_.numClippingPlanes||_.numClippingPlanes===ue.numPlanes&&_.numIntersection===ue.numIntersection?(_.vertexAlphas!==c||_.vertexTangents!==h||_.morphTargets!==u||_.morphNormals!==d||_.morphColors!==p||_.toneMapping!==f||_.morphTargetsCount!==v)&&(A=!0):A=!0:A=!0:A=!0:A=!0:(A=!0,_.__version=i.version);let S=_.currentProgram;!0===A&&(S=Ne(i,t,s));let T=!1,E=!1,C=!1;const R=S.getUniforms(),I=_.uniforms;Z.useProgram(S.program)&&(T=!0,E=!0,C=!0);i.id!==M&&(M=i.id,E=!0);if(T||w!==e){Z.buffers.depth.getReversed()?(V.copy(e.projectionMatrix),function(e){const t=e.elements;t[2]=.5*t[2]+.5*t[3],t[6]=.5*t[6]+.5*t[7],t[10]=.5*t[10]+.5*t[11],t[14]=.5*t[14]+.5*t[15]}(V),function(e){const t=e.elements;-1===t[11]?(t[10]=-t[10]-1,t[14]=-t[14]):(t[10]=-t[10],t[14]=1-t[14])}(V),R.setValue(ye,"projectionMatrix",V)):R.setValue(ye,"projectionMatrix",e.projectionMatrix),R.setValue(ye,"viewMatrix",e.matrixWorldInverse);const t=R.map.cameraPosition;void 0!==t&&t.setValue(ye,W.setFromMatrixPosition(e.matrixWorld)),Y.logarithmicDepthBuffer&&R.setValue(ye,"logDepthBufFC",2/(Math.log(e.far+1)/Math.LN2)),(i.isMeshPhongMaterial||i.isMeshToonMaterial||i.isMeshLambertMaterial||i.isMeshBasicMaterial||i.isMeshStandardMaterial||i.isShaderMaterial)&&R.setValue(ye,"isOrthographic",!0===e.isOrthographicCamera),w!==e&&(w=e,E=!0,C=!0)}if(s.isSkinnedMesh){R.setOptional(ye,s,"bindMatrix"),R.setOptional(ye,s,"bindMatrixInverse");const e=s.skeleton;e&&(null===e.boneTexture&&e.computeBoneTexture(),R.setValue(ye,"boneTexture",e.boneTexture,ee))}s.isBatchedMesh&&(R.setOptional(ye,s,"batchingTexture"),R.setValue(ye,"batchingTexture",s._matricesTexture,ee),R.setOptional(ye,s,"batchingIdTexture"),R.setValue(ye,"batchingIdTexture",s._indirectTexture,ee),R.setOptional(ye,s,"batchingColorTexture"),null!==s._colorsTexture&&R.setValue(ye,"batchingColorTexture",s._colorsTexture,ee));const D=n.morphAttributes;void 0===D.position&&void 0===D.normal&&void 0===D.color||fe.update(s,n,S);(E||_.receiveShadow!==s.receiveShadow)&&(_.receiveShadow=s.receiveShadow,R.setValue(ye,"receiveShadow",s.receiveShadow));i.isMeshGouraudMaterial&&null!==i.envMap&&(I.envMap.value=l,I.flipEnvMap.value=l.isCubeTexture&&!1===l.isRenderTargetTexture?-1:1);i.isMeshStandardMaterial&&null===i.envMap&&null!==t.environment&&(I.envMapIntensity.value=t.environmentIntensity);E&&(R.setValue(ye,"toneMappingExposure",x.toneMappingExposure),_.needsLights&&(U=C,(L=I).ambientLightColor.needsUpdate=U,L.lightProbe.needsUpdate=U,L.directionalLights.needsUpdate=U,L.directionalLightShadows.needsUpdate=U,L.pointLights.needsUpdate=U,L.pointLightShadows.needsUpdate=U,L.spotLights.needsUpdate=U,L.spotLightShadows.needsUpdate=U,L.rectAreaLights.needsUpdate=U,L.hemisphereLights.needsUpdate=U),r&&!0===i.fog&&le.refreshFogUniforms(I,r),le.refreshMaterialUniforms(I,i,B,P,g.state.transmissionRenderTarget[e.id]),Fc.upload(ye,Oe(_),I,ee));var L,U;i.isShaderMaterial&&!0===i.uniformsNeedUpdate&&(Fc.upload(ye,Oe(_),I,ee),i.uniformsNeedUpdate=!1);i.isSpriteMaterial&&R.setValue(ye,"center",s.center);if(R.setValue(ye,"modelViewMatrix",s.modelViewMatrix),R.setValue(ye,"normalMatrix",s.normalMatrix),R.setValue(ye,"modelMatrix",s.matrixWorld),i.isShaderMaterial||i.isRawShaderMaterial){const e=i.uniformsGroups;for(let t=0,n=e.length;t<n;t++){const n=e[t];xe.update(n,S),xe.bind(n,S)}}return S}(e,t,n,i,s);Z.setMaterial(i,a);let l=n.index,c=1;if(!0===i.wireframe){if(l=re.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!==r&&(d=Math.max(d,r.start*c),p=Math.min(p,(r.start+r.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;_e.setup(s,i,o,n,l);let v=me;if(null!==l&&(m=se.get(l),v=ge,v.setIndex(m)),s.isMesh)!0===i.wireframe?(Z.setLineWidth(i.wireframeLinewidth*Q()),v.setMode(ye.LINES)):v.setMode(ye.TRIANGLES);else if(s.isLine){let e=i.linewidth;void 0===e&&(e=1),Z.setLineWidth(e*Q()),s.isLineSegments?v.setMode(ye.LINES):s.isLineLoop?v.setMode(ye.LINE_LOOP):v.setMode(ye.LINE_STRIP)}else s.isPoints?v.setMode(ye.POINTS):s.isSprite&&v.setMode(ye.TRIANGLES);if(s.isBatchedMesh)if(null!==s._multiDrawInstances)v.renderMultiDrawInstances(s._multiDrawStarts,s._multiDrawCounts,s._multiDrawCount,s._multiDrawInstances);else if(K.get("WEBGL_multi_draw"))v.renderMultiDraw(s._multiDrawStarts,s._multiDrawCounts,s._multiDrawCount);else{const e=s._multiDrawStarts,t=s._multiDrawCounts,n=s._multiDrawCount,r=l?se.get(l).bytesPerElement:1,a=$.get(i).currentProgram.getUniforms();for(let i=0;i<n;i++)a.setValue(ye,"_gl_DrawID",i),v.render(e[i]/r,t[i])}else if(s.isInstancedMesh)v.renderInstances(d,f,s.count);else if(n.isInstancedBufferGeometry){const e=void 0!==n._maxInstanceCount?n._maxInstanceCount:1/0,t=Math.min(n.instanceCount,e);v.renderInstances(d,f,t)}else v.render(d,f)},this.compile=function(e,t,n=null){null===n&&(n=e),g=he.get(n),g.init(t),_.push(g),n.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(g.pushLight(e),e.castShadow&&g.pushShadow(e))}),e!==n&&e.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(g.pushLight(e),e.castShadow&&g.pushShadow(e))}),g.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 s=0;s<t.length;s++){const r=t[s];Ce(r,n,e),i.add(r)}else Ce(t,n,e),i.add(t)}),_.pop(),g=null,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){$.get(e).currentProgram.isReady()&&i.delete(e)}),0!==i.size?setTimeout(n,10):t(e)}null!==K.get("KHR_parallel_shader_compile")?n():setTimeout(n,10)})};let Re=null;function Ie(){Pe.stop()}function De(){Pe.start()}const Pe=new Qo;function Be(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)g.pushLight(e),e.castShadow&&g.pushShadow(e);else if(e.isSprite){if(!e.frustumCulled||O.intersectsSprite(e)){i&&j.setFromMatrixPosition(e.matrixWorld).applyMatrix4(G);const t=ae.update(e),s=e.material;s.visible&&m.push(e,t,s,n,j.z,null)}}else if((e.isMesh||e.isLine||e.isPoints)&&(!e.frustumCulled||O.intersectsObject(e))){const t=ae.update(e),s=e.material;if(i&&(void 0!==e.boundingSphere?(null===e.boundingSphere&&e.computeBoundingSphere(),j.copy(e.boundingSphere.center)):(null===t.boundingSphere&&t.computeBoundingSphere(),j.copy(t.boundingSphere.center)),j.applyMatrix4(e.matrixWorld).applyMatrix4(G)),Array.isArray(s)){const i=t.groups;for(let r=0,a=i.length;r<a;r++){const a=i[r],o=s[a.materialIndex];o&&o.visible&&m.push(e,t,o,n,j.z,a)}}else s.visible&&m.push(e,t,s,n,j.z,null)}const s=e.children;for(let r=0,a=s.length;r<a;r++)Be(s[r],t,n,i)}function Le(e,t,n,i){const s=e.opaque,r=e.transmissive,a=e.transparent;g.setupLightsView(n),!0===z&&ue.setGlobalState(x.clippingPlanes,n),i&&Z.viewport(T.copy(i)),s.length>0&&Fe(s,t,n),r.length>0&&Fe(r,t,n),a.length>0&&Fe(a,t,n),Z.buffers.depth.setTest(!0),Z.buffers.depth.setMask(!0),Z.buffers.color.setMask(!0),Z.setPolygonOffset(!1)}function Ue(e,t,n,i){if(null!==(!0===n.isScene?n.overrideMaterial:null))return;void 0===g.state.transmissionRenderTarget[i.id]&&(g.state.transmissionRenderTarget[i.id]=new ri(1,1,{generateMipmaps:!0,type:K.has("EXT_color_buffer_half_float")||K.has("EXT_color_buffer_float")?rt:Je,minFilter:Ze,samples:4,stencilBuffer:s,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:qn.workingColorSpace}));const r=g.state.transmissionRenderTarget[i.id],a=i.viewport||T;r.setSize(a.z*x.transmissionResolutionScale,a.w*x.transmissionResolutionScale);const o=x.getRenderTarget();x.setRenderTarget(r),x.getClearColor(R),I=x.getClearAlpha(),I<1&&x.setClearColor(16777215,.5),x.clear(),q&&pe.render(n);const l=x.toneMapping;x.toneMapping=0;const c=i.viewport;if(void 0!==i.viewport&&(i.viewport=void 0),g.setupLightsView(i),!0===z&&ue.setGlobalState(x.clippingPlanes,i),Fe(e,n,i),ee.updateMultisampleRenderTarget(r),ee.updateRenderTargetMipmap(r),!1===K.has("WEBGL_multisampled_render_to_texture")){let e=!1;for(let s=0,r=t.length;s<r;s++){const r=t[s],a=r.object,o=r.geometry,l=r.material,c=r.group;if(2===l.side&&a.layers.test(i.layers)){const t=l.side;l.side=1,l.needsUpdate=!0,ke(a,n,i,o,l,c),l.side=t,l.needsUpdate=!0,e=!0}}!0===e&&(ee.updateMultisampleRenderTarget(r),ee.updateRenderTargetMipmap(r))}x.setRenderTarget(o),x.setClearColor(R,I),void 0!==c&&(i.viewport=c),x.toneMapping=l}function Fe(e,t,n){const i=!0===t.isScene?t.overrideMaterial:null;for(let s=0,r=e.length;s<r;s++){const r=e[s],a=r.object,o=r.geometry,l=null===i?r.material:i,c=r.group;a.layers.test(n.layers)&&ke(a,t,n,o,l,c)}}function ke(e,t,n,i,s,r){e.onBeforeRender(x,t,n,i,s,r),e.modelViewMatrix.multiplyMatrices(n.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix),s.onBeforeRender(x,t,n,i,e,r),!0===s.transparent&&2===s.side&&!1===s.forceSinglePass?(s.side=1,s.needsUpdate=!0,x.renderBufferDirect(n,t,i,s,e,r),s.side=0,s.needsUpdate=!0,x.renderBufferDirect(n,t,i,s,e,r),s.side=2):x.renderBufferDirect(n,t,i,s,e,r),e.onAfterRender(x,t,n,i,s,r)}function Ne(e,t,n){!0!==t.isScene&&(t=X);const i=$.get(e),s=g.state.lights,r=g.state.shadowsArray,a=s.state.version,o=oe.getParameters(e,s.state,r,t,n),l=oe.getProgramCacheKey(o);let c=i.programs;i.environment=e.isMeshStandardMaterial?t.environment:null,i.fog=t.fog,i.envMap=(e.isMeshStandardMaterial?ie:te).get(e.envMap||i.environment),i.envMapRotation=null!==i.environment&&null===e.envMap?t.environmentRotation:e.envMapRotation,void 0===c&&(e.addEventListener("dispose",Ee),c=new Map,i.programs=c);let h=c.get(l);if(void 0!==h){if(i.currentProgram===h&&i.lightsStateVersion===a)return ze(e,o),h}else o.uniforms=oe.getUniforms(e),e.onBeforeCompile(o,x),h=oe.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=ue.uniform),ze(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=s.state.ambient,u.lightProbe.value=s.state.probe,u.directionalLights.value=s.state.directional,u.directionalLightShadows.value=s.state.directionalShadow,u.spotLights.value=s.state.spot,u.spotLightShadows.value=s.state.spotShadow,u.rectAreaLights.value=s.state.rectArea,u.ltc_1.value=s.state.rectAreaLTC1,u.ltc_2.value=s.state.rectAreaLTC2,u.pointLights.value=s.state.point,u.pointLightShadows.value=s.state.pointShadow,u.hemisphereLights.value=s.state.hemi,u.directionalShadowMap.value=s.state.directionalShadowMap,u.directionalShadowMatrix.value=s.state.directionalShadowMatrix,u.spotShadowMap.value=s.state.spotShadowMap,u.spotLightMatrix.value=s.state.spotLightMatrix,u.spotLightMap.value=s.state.spotLightMap,u.pointShadowMap.value=s.state.pointShadowMap,u.pointShadowMatrix.value=s.state.pointShadowMatrix),i.currentProgram=h,i.uniformsList=null,h}function Oe(e){if(null===e.uniformsList){const t=e.currentProgram.getUniforms();e.uniformsList=Fc.seqWithValue(t.seq,e.uniforms)}return e.uniformsList}function ze(e,t){const n=$.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}Pe.setAnimationLoop(function(e){Re&&Re(e)}),"undefined"!=typeof self&&Pe.setContext(self),this.setAnimationLoop=function(e){Re=e,be.setAnimationLoop(e),null===e?Pe.stop():Pe.start()},be.addEventListener("sessionstart",Ie),be.addEventListener("sessionend",De),this.render=function(e,t){if(void 0!==t&&!0!==t.isCamera)return void console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");if(!0===y)return;if(!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&!0===t.matrixWorldAutoUpdate&&t.updateMatrixWorld(),!0===be.enabled&&!0===be.isPresenting&&(!0===be.cameraAutoUpdate&&be.updateCamera(t),t=be.getCamera()),!0===e.isScene&&e.onBeforeRender(x,e,t,b),g=he.get(e,_.length),g.init(t),_.push(g),G.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),O.setFromProjectionMatrix(G),H=this.localClippingEnabled,z=ue.init(this.clippingPlanes,H),m=ce.get(e,v.length),m.init(),v.push(m),!0===be.enabled&&!0===be.isPresenting){const e=x.xr.getDepthSensingMesh();null!==e&&Be(e,t,-1/0,x.sortObjects)}Be(e,t,0,x.sortObjects),m.finish(),!0===x.sortObjects&&m.sort(L,U),q=!1===be.enabled||!1===be.isPresenting||!1===be.hasDepthSensing(),q&&pe.addToRenderList(m,e),this.info.render.frame++,!0===z&&ue.beginShadows();const n=g.state.shadowsArray;de.render(n,e,t),!0===z&&ue.endShadows(),!0===this.info.autoReset&&this.info.reset();const i=m.opaque,s=m.transmissive;if(g.setupLights(),t.isArrayCamera){const n=t.cameras;if(s.length>0)for(let t=0,r=n.length;t<r;t++){Ue(i,s,e,n[t])}q&&pe.render(e);for(let t=0,i=n.length;t<i;t++){const i=n[t];Le(m,e,i,i.viewport)}}else s.length>0&&Ue(i,s,e,t),q&&pe.render(e),Le(m,e,t);null!==b&&0===S&&(ee.updateMultisampleRenderTarget(b),ee.updateRenderTargetMipmap(b)),!0===e.isScene&&e.onAfterRender(x,e,t),_e.resetDefaultState(),M=-1,w=null,_.pop(),_.length>0?(g=_[_.length-1],!0===z&&ue.setGlobalState(x.clippingPlanes,g.state.camera)):g=null,v.pop(),m=v.length>0?v[v.length-1]:null},this.getActiveCubeFace=function(){return A},this.getActiveMipmapLevel=function(){return S},this.getRenderTarget=function(){return b},this.setRenderTargetTextures=function(e,t,n){$.get(e.texture).__webglTexture=t,$.get(e.depthTexture).__webglTexture=n;const i=$.get(e);i.__hasExternalTextures=!0,i.__autoAllocateDepthBuffer=void 0===n,i.__autoAllocateDepthBuffer||!0===K.has("WEBGL_multisampled_render_to_texture")&&(console.warn("THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided"),i.__useRenderToTexture=!1)},this.setRenderTargetFramebuffer=function(e,t){const n=$.get(e);n.__webglFramebuffer=t,n.__useDefaultFramebuffer=void 0===t};const He=ye.createFramebuffer();this.setRenderTarget=function(e,t=0,n=0){b=e,A=t,S=n;let i=!0,s=null,r=!1,a=!1;if(e){const o=$.get(e);if(void 0!==o.__useDefaultFramebuffer)Z.bindFramebuffer(ye.FRAMEBUFFER,null),i=!1;else if(void 0===o.__webglFramebuffer)ee.setupRenderTarget(e);else if(o.__hasExternalTextures)ee.rebindTextures(e,$.get(e.texture).__webglTexture,$.get(e.depthTexture).__webglTexture);else if(e.depthBuffer){const t=e.depthTexture;if(o.__boundDepthTexture!==t){if(null!==t&&$.has(t)&&(e.width!==t.image.width||e.height!==t.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");ee.setupDepthRenderbuffer(e)}}const l=e.texture;(l.isData3DTexture||l.isDataArrayTexture||l.isCompressedArrayTexture)&&(a=!0);const c=$.get(e).__webglFramebuffer;e.isWebGLCubeRenderTarget?(s=Array.isArray(c[t])?c[t][n]:c[t],r=!0):s=e.samples>0&&!1===ee.useMultisampledRTT(e)?$.get(e).__webglMultisampledFramebuffer:Array.isArray(c)?c[n]:c,T.copy(e.viewport),E.copy(e.scissor),C=e.scissorTest}else T.copy(F).multiplyScalar(B).floor(),E.copy(k).multiplyScalar(B).floor(),C=N;0!==n&&(s=He);if(Z.bindFramebuffer(ye.FRAMEBUFFER,s)&&i&&Z.drawBuffers(e,s),Z.viewport(T),Z.scissor(E),Z.setScissorTest(C),r){const i=$.get(e.texture);ye.framebufferTexture2D(ye.FRAMEBUFFER,ye.COLOR_ATTACHMENT0,ye.TEXTURE_CUBE_MAP_POSITIVE_X+t,i.__webglTexture,n)}else if(a){const i=$.get(e.texture),s=t;ye.framebufferTextureLayer(ye.FRAMEBUFFER,ye.COLOR_ATTACHMENT0,i.__webglTexture,n,s)}else if(null!==e&&0!==n){const t=$.get(e.texture);ye.framebufferTexture2D(ye.FRAMEBUFFER,ye.COLOR_ATTACHMENT0,ye.TEXTURE_2D,t.__webglTexture,n)}M=-1},this.readRenderTargetPixels=function(e,t,n,i,s,r,a){if(!e||!e.isWebGLRenderTarget)return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let o=$.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&void 0!==a&&(o=o[a]),o){Z.bindFramebuffer(ye.FRAMEBUFFER,o);try{const a=e.texture,o=a.format,l=a.type;if(!Y.textureFormatReadable(o))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");if(!Y.textureTypeReadable(l))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");t>=0&&t<=e.width-i&&n>=0&&n<=e.height-s&&ye.readPixels(t,n,i,s,ve.convert(o),ve.convert(l),r)}finally{const e=null!==b?$.get(b).__webglFramebuffer:null;Z.bindFramebuffer(ye.FRAMEBUFFER,e)}}},this.readRenderTargetPixelsAsync=async function(e,t,n,i,s,r,a){if(!e||!e.isWebGLRenderTarget)throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let o=$.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&void 0!==a&&(o=o[a]),o){const a=e.texture,l=a.format,c=a.type;if(!Y.textureFormatReadable(l))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!Y.textureTypeReadable(c))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");if(t>=0&&t<=e.width-i&&n>=0&&n<=e.height-s){Z.bindFramebuffer(ye.FRAMEBUFFER,o);const e=ye.createBuffer();ye.bindBuffer(ye.PIXEL_PACK_BUFFER,e),ye.bufferData(ye.PIXEL_PACK_BUFFER,r.byteLength,ye.STREAM_READ),ye.readPixels(t,n,i,s,ve.convert(l),ve.convert(c),0);const a=null!==b?$.get(b).__webglFramebuffer:null;Z.bindFramebuffer(ye.FRAMEBUFFER,a);const h=ye.fenceSync(ye.SYNC_GPU_COMMANDS_COMPLETE,0);return ye.flush(),await function(e,t,n){return new Promise(function(i,s){setTimeout(function r(){switch(e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0)){case e.WAIT_FAILED:s();break;case e.TIMEOUT_EXPIRED:setTimeout(r,n);break;default:i()}},n)})}(ye,h,4),ye.bindBuffer(ye.PIXEL_PACK_BUFFER,e),ye.getBufferSubData(ye.PIXEL_PACK_BUFFER,0,r),ye.deleteBuffer(e),ye.deleteSync(h),r}throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")}},this.copyFramebufferToTexture=function(e,t=null,n=0){!0!==e.isTexture&&(Gn("WebGLRenderer: copyFramebufferToTexture function signature has changed."),t=arguments[0]||null,e=arguments[1]);const i=Math.pow(2,-n),s=Math.floor(e.image.width*i),r=Math.floor(e.image.height*i),a=null!==t?t.x:0,o=null!==t?t.y:0;ee.setTexture2D(e,0),ye.copyTexSubImage2D(ye.TEXTURE_2D,n,0,0,a,o,s,r),Z.unbindTexture()};const Ve=ye.createFramebuffer(),Ge=ye.createFramebuffer();this.copyTextureToTexture=function(e,t,n=null,i=null,s=0,r=null){let a,o,l,c,h,u,d,p,f;!0!==e.isTexture&&(Gn("WebGLRenderer: copyTextureToTexture function signature has changed."),i=arguments[0]||null,e=arguments[1],t=arguments[2],r=arguments[3]||0,n=null),null===r&&(0!==s?(Gn("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),r=s,s=0):r=0);const m=e.isCompressedTexture?e.mipmaps[r]: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,-s);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=ve.convert(t.format),v=ve.convert(t.type);let _;t.isData3DTexture?(ee.setTexture3D(t,0),_=ye.TEXTURE_3D):t.isDataArrayTexture||t.isCompressedArrayTexture?(ee.setTexture2DArray(t,0),_=ye.TEXTURE_2D_ARRAY):(ee.setTexture2D(t,0),_=ye.TEXTURE_2D),ye.pixelStorei(ye.UNPACK_FLIP_Y_WEBGL,t.flipY),ye.pixelStorei(ye.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),ye.pixelStorei(ye.UNPACK_ALIGNMENT,t.unpackAlignment);const x=ye.getParameter(ye.UNPACK_ROW_LENGTH),y=ye.getParameter(ye.UNPACK_IMAGE_HEIGHT),A=ye.getParameter(ye.UNPACK_SKIP_PIXELS),S=ye.getParameter(ye.UNPACK_SKIP_ROWS),b=ye.getParameter(ye.UNPACK_SKIP_IMAGES);ye.pixelStorei(ye.UNPACK_ROW_LENGTH,m.width),ye.pixelStorei(ye.UNPACK_IMAGE_HEIGHT,m.height),ye.pixelStorei(ye.UNPACK_SKIP_PIXELS,c),ye.pixelStorei(ye.UNPACK_SKIP_ROWS,h),ye.pixelStorei(ye.UNPACK_SKIP_IMAGES,u);const M=e.isDataArrayTexture||e.isData3DTexture,w=t.isDataArrayTexture||t.isData3DTexture;if(e.isDepthTexture){const n=$.get(e),i=$.get(t),m=$.get(n.__renderTarget),g=$.get(i.__renderTarget);Z.bindFramebuffer(ye.READ_FRAMEBUFFER,m.__webglFramebuffer),Z.bindFramebuffer(ye.DRAW_FRAMEBUFFER,g.__webglFramebuffer);for(let v=0;v<l;v++)M&&(ye.framebufferTextureLayer(ye.READ_FRAMEBUFFER,ye.COLOR_ATTACHMENT0,$.get(e).__webglTexture,s,u+v),ye.framebufferTextureLayer(ye.DRAW_FRAMEBUFFER,ye.COLOR_ATTACHMENT0,$.get(t).__webglTexture,r,f+v)),ye.blitFramebuffer(c,h,a,o,d,p,a,o,ye.DEPTH_BUFFER_BIT,ye.NEAREST);Z.bindFramebuffer(ye.READ_FRAMEBUFFER,null),Z.bindFramebuffer(ye.DRAW_FRAMEBUFFER,null)}else if(0!==s||e.isRenderTargetTexture||$.has(e)){const n=$.get(e),i=$.get(t);Z.bindFramebuffer(ye.READ_FRAMEBUFFER,Ve),Z.bindFramebuffer(ye.DRAW_FRAMEBUFFER,Ge);for(let e=0;e<l;e++)M?ye.framebufferTextureLayer(ye.READ_FRAMEBUFFER,ye.COLOR_ATTACHMENT0,n.__webglTexture,s,u+e):ye.framebufferTexture2D(ye.READ_FRAMEBUFFER,ye.COLOR_ATTACHMENT0,ye.TEXTURE_2D,n.__webglTexture,s),w?ye.framebufferTextureLayer(ye.DRAW_FRAMEBUFFER,ye.COLOR_ATTACHMENT0,i.__webglTexture,r,f+e):ye.framebufferTexture2D(ye.DRAW_FRAMEBUFFER,ye.COLOR_ATTACHMENT0,ye.TEXTURE_2D,i.__webglTexture,r),0!==s?ye.blitFramebuffer(c,h,a,o,d,p,a,o,ye.COLOR_BUFFER_BIT,ye.NEAREST):w?ye.copyTexSubImage3D(_,r,d,p,f+e,c,h,a,o):ye.copyTexSubImage2D(_,r,d,p,c,h,a,o);Z.bindFramebuffer(ye.READ_FRAMEBUFFER,null),Z.bindFramebuffer(ye.DRAW_FRAMEBUFFER,null)}else w?e.isDataTexture||e.isData3DTexture?ye.texSubImage3D(_,r,d,p,f,a,o,l,g,v,m.data):t.isCompressedArrayTexture?ye.compressedTexSubImage3D(_,r,d,p,f,a,o,l,g,m.data):ye.texSubImage3D(_,r,d,p,f,a,o,l,g,v,m):e.isDataTexture?ye.texSubImage2D(ye.TEXTURE_2D,r,d,p,a,o,g,v,m.data):e.isCompressedTexture?ye.compressedTexSubImage2D(ye.TEXTURE_2D,r,d,p,m.width,m.height,g,m.data):ye.texSubImage2D(ye.TEXTURE_2D,r,d,p,a,o,g,v,m);ye.pixelStorei(ye.UNPACK_ROW_LENGTH,x),ye.pixelStorei(ye.UNPACK_IMAGE_HEIGHT,y),ye.pixelStorei(ye.UNPACK_SKIP_PIXELS,A),ye.pixelStorei(ye.UNPACK_SKIP_ROWS,S),ye.pixelStorei(ye.UNPACK_SKIP_IMAGES,b),0===r&&t.generateMipmaps&&ye.generateMipmap(_),Z.unbindTexture()},this.copyTextureToTexture3D=function(e,t,n=null,i=null,s=0){return!0!==e.isTexture&&(Gn("WebGLRenderer: copyTextureToTexture3D function signature has changed."),n=arguments[0]||null,i=arguments[1]||null,e=arguments[2],t=arguments[3],s=arguments[4]||0),Gn('WebGLRenderer: copyTextureToTexture3D function has been deprecated. Use "copyTextureToTexture" instead.'),this.copyTextureToTexture(e,t,n,i,s)},this.initRenderTarget=function(e){void 0===$.get(e).__webglFramebuffer&&ee.setupRenderTarget(e)},this.initTexture=function(e){e.isCubeTexture?ee.setTextureCube(e,0):e.isData3DTexture?ee.setTexture3D(e,0):e.isDataArrayTexture||e.isCompressedArrayTexture?ee.setTexture2DArray(e,0):ee.setTexture2D(e,0),Z.unbindTexture()},this.resetState=function(){A=0,S=0,b=null,Z.reset(),_e.reset()},"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return Sn}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const t=this.getContext();t.drawingBufferColorspace=qn._getDrawingBufferColorSpace(e),t.unpackColorSpace=qn._getUnpackColorSpace()}}function Ih(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,s=[];if(2===t)for(let e=1;e<=i;e++)s.push(n.getX(0)),s.push(n.getX(e)),s.push(n.getX(e+1));else for(let e=0;e<i;e++)e%2==0?(s.push(n.getX(e)),s.push(n.getX(e+1)),s.push(n.getX(e+2))):(s.push(n.getX(e+2)),s.push(n.getX(e+1)),s.push(n.getX(e)));s.length/3!==i&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const r=e.clone();return r.setIndex(s),r.clearGroups(),r}return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",t),e}class Dh extends ao{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(e){return new kh(e)}),this.register(function(e){return new Nh(e)}),this.register(function(e){return new qh(e)}),this.register(function(e){return new Qh(e)}),this.register(function(e){return new Kh(e)}),this.register(function(e){return new zh(e)}),this.register(function(e){return new Hh(e)}),this.register(function(e){return new Vh(e)}),this.register(function(e){return new Gh(e)}),this.register(function(e){return new Fh(e)}),this.register(function(e){return new Wh(e)}),this.register(function(e){return new Oh(e)}),this.register(function(e){return new Xh(e)}),this.register(function(e){return new jh(e)}),this.register(function(e){return new Lh(e)}),this.register(function(e){return new Yh(e)}),this.register(function(e){return new Zh(e)})}load(e,t,n,i){const s=this;let r;if(""!==this.resourcePath)r=this.resourcePath;else if(""!==this.path){const t=Co.extractUrlBase(e);r=Co.resolveURL(t,this.path)}else r=Co.extractUrlBase(e);this.manager.itemStart(e);const a=function(t){i?i(t):console.error(t),s.manager.itemError(e),s.manager.itemEnd(e)},o=new co(this.manager);o.setPath(this.path),o.setResponseType("arraybuffer"),o.setRequestHeader(this.requestHeader),o.setWithCredentials(this.withCredentials),o.load(e,function(n){try{s.parse(n,r,function(n){t(n),s.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 s;const r={},a={},o=new TextDecoder;if("string"==typeof e)s=JSON.parse(e);else if(e instanceof ArrayBuffer){if(o.decode(new Uint8Array(e,0,4))===Jh){try{r[Bh.KHR_BINARY_GLTF]=new tu(e)}catch(c){return void(i&&i(c))}s=JSON.parse(r[Bh.KHR_BINARY_GLTF].content)}else s=JSON.parse(o.decode(e))}else s=e;if(void 0===s.asset||s.asset.version[0]<2)return void(i&&i(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.")));const l=new Eu(s,{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,r[e.name]=!0}if(s.extensionsUsed)for(let h=0;h<s.extensionsUsed.length;++h){const e=s.extensionsUsed[h],t=s.extensionsRequired||[];switch(e){case Bh.KHR_MATERIALS_UNLIT:r[e]=new Uh;break;case Bh.KHR_DRACO_MESH_COMPRESSION:r[e]=new nu(s,this.dracoLoader);break;case Bh.KHR_TEXTURE_TRANSFORM:r[e]=new iu;break;case Bh.KHR_MESH_QUANTIZATION:r[e]=new su;break;default:t.indexOf(e)>=0&&void 0===a[e]&&console.warn('THREE.GLTFLoader: Unknown extension "'+e+'".')}}l.setExtensions(r),l.setPlugins(a),l.parse(n,i)}parseAsync(e,t){const n=this;return new Promise(function(i,s){n.parse(e,t,i,s)})}}function Ph(){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 Bh={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 Lh{constructor(e){this.parser=e,this.name=Bh.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 s=t.json,r=((s.extensions&&s.extensions[this.name]||{}).lights||[])[e];let a;const o=new Ds(16777215);void 0!==r.color&&o.setRGB(r.color[0],r.color[1],r.color[2],on);const l=void 0!==r.range?r.range:0;switch(r.type){case"directional":a=new Eo(o),a.target.position.set(0,0,-1),a.add(a.target);break;case"point":a=new Mo(o),a.distance=l;break;case"spot":a=new xo(o),a.distance=l,r.spot=r.spot||{},r.spot.innerConeAngle=void 0!==r.spot.innerConeAngle?r.spot.innerConeAngle:0,r.spot.outerConeAngle=void 0!==r.spot.outerConeAngle?r.spot.outerConeAngle:Math.PI/4,a.angle=r.spot.outerConeAngle,a.penumbra=1-r.spot.innerConeAngle/r.spot.outerConeAngle,a.target.position.set(0,0,-1),a.add(a.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+r.type)}return a.position.set(0,0,0),Au(a,r),void 0!==r.intensity&&(a.intensity=r.intensity),a.name=t.createUniqueName(r.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],s=(i.extensions&&i.extensions[this.name]||{}).light;return void 0===s?null:this._loadLight(s).then(function(e){return n._getNodeRef(t.cache,s,e)})}}class Uh{constructor(){this.name=Bh.KHR_MATERIALS_UNLIT}getMaterialType(){return Us}extendParams(e,t,n){const i=[];e.color=new Ds(1,1,1),e.opacity=1;const s=t.pbrMetallicRoughness;if(s){if(Array.isArray(s.baseColorFactor)){const t=s.baseColorFactor;e.color.setRGB(t[0],t[1],t[2],on),e.opacity=t[3]}void 0!==s.baseColorTexture&&i.push(n.assignTexture(e,"map",s.baseColorTexture,an))}return Promise.all(i)}}class Fh{constructor(e){this.parser=e,this.name=Bh.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 kh{constructor(e){this.parser=e,this.name=Bh.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?Fa:null}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[],r=i.extensions[this.name];if(void 0!==r.clearcoatFactor&&(t.clearcoat=r.clearcoatFactor),void 0!==r.clearcoatTexture&&s.push(n.assignTexture(t,"clearcoatMap",r.clearcoatTexture)),void 0!==r.clearcoatRoughnessFactor&&(t.clearcoatRoughness=r.clearcoatRoughnessFactor),void 0!==r.clearcoatRoughnessTexture&&s.push(n.assignTexture(t,"clearcoatRoughnessMap",r.clearcoatRoughnessTexture)),void 0!==r.clearcoatNormalTexture&&(s.push(n.assignTexture(t,"clearcoatNormalMap",r.clearcoatNormalTexture)),void 0!==r.clearcoatNormalTexture.scale)){const e=r.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new Fn(e,e)}return Promise.all(s)}}class Nh{constructor(e){this.parser=e,this.name=Bh.KHR_MATERIALS_DISPERSION}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?Fa: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 Oh{constructor(e){this.parser=e,this.name=Bh.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?Fa:null}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[],r=i.extensions[this.name];return void 0!==r.iridescenceFactor&&(t.iridescence=r.iridescenceFactor),void 0!==r.iridescenceTexture&&s.push(n.assignTexture(t,"iridescenceMap",r.iridescenceTexture)),void 0!==r.iridescenceIor&&(t.iridescenceIOR=r.iridescenceIor),void 0===t.iridescenceThicknessRange&&(t.iridescenceThicknessRange=[100,400]),void 0!==r.iridescenceThicknessMinimum&&(t.iridescenceThicknessRange[0]=r.iridescenceThicknessMinimum),void 0!==r.iridescenceThicknessMaximum&&(t.iridescenceThicknessRange[1]=r.iridescenceThicknessMaximum),void 0!==r.iridescenceThicknessTexture&&s.push(n.assignTexture(t,"iridescenceThicknessMap",r.iridescenceThicknessTexture)),Promise.all(s)}}class zh{constructor(e){this.parser=e,this.name=Bh.KHR_MATERIALS_SHEEN}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?Fa:null}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[];t.sheenColor=new Ds(0,0,0),t.sheenRoughness=0,t.sheen=1;const r=i.extensions[this.name];if(void 0!==r.sheenColorFactor){const e=r.sheenColorFactor;t.sheenColor.setRGB(e[0],e[1],e[2],on)}return void 0!==r.sheenRoughnessFactor&&(t.sheenRoughness=r.sheenRoughnessFactor),void 0!==r.sheenColorTexture&&s.push(n.assignTexture(t,"sheenColorMap",r.sheenColorTexture,an)),void 0!==r.sheenRoughnessTexture&&s.push(n.assignTexture(t,"sheenRoughnessMap",r.sheenRoughnessTexture)),Promise.all(s)}}class Hh{constructor(e){this.parser=e,this.name=Bh.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?Fa:null}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[],r=i.extensions[this.name];return void 0!==r.transmissionFactor&&(t.transmission=r.transmissionFactor),void 0!==r.transmissionTexture&&s.push(n.assignTexture(t,"transmissionMap",r.transmissionTexture)),Promise.all(s)}}class Vh{constructor(e){this.parser=e,this.name=Bh.KHR_MATERIALS_VOLUME}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?Fa:null}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[],r=i.extensions[this.name];t.thickness=void 0!==r.thicknessFactor?r.thicknessFactor:0,void 0!==r.thicknessTexture&&s.push(n.assignTexture(t,"thicknessMap",r.thicknessTexture)),t.attenuationDistance=r.attenuationDistance||1/0;const a=r.attenuationColor||[1,1,1];return t.attenuationColor=(new Ds).setRGB(a[0],a[1],a[2],on),Promise.all(s)}}class Gh{constructor(e){this.parser=e,this.name=Bh.KHR_MATERIALS_IOR}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?Fa: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 Wh{constructor(e){this.parser=e,this.name=Bh.KHR_MATERIALS_SPECULAR}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?Fa:null}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[],r=i.extensions[this.name];t.specularIntensity=void 0!==r.specularFactor?r.specularFactor:1,void 0!==r.specularTexture&&s.push(n.assignTexture(t,"specularIntensityMap",r.specularTexture));const a=r.specularColorFactor||[1,1,1];return t.specularColor=(new Ds).setRGB(a[0],a[1],a[2],on),void 0!==r.specularColorTexture&&s.push(n.assignTexture(t,"specularColorMap",r.specularColorTexture,an)),Promise.all(s)}}class jh{constructor(e){this.parser=e,this.name=Bh.EXT_MATERIALS_BUMP}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?Fa:null}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[],r=i.extensions[this.name];return t.bumpScale=void 0!==r.bumpFactor?r.bumpFactor:1,void 0!==r.bumpTexture&&s.push(n.assignTexture(t,"bumpMap",r.bumpTexture)),Promise.all(s)}}class Xh{constructor(e){this.parser=e,this.name=Bh.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?Fa:null}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[],r=i.extensions[this.name];return void 0!==r.anisotropyStrength&&(t.anisotropy=r.anisotropyStrength),void 0!==r.anisotropyRotation&&(t.anisotropyRotation=r.anisotropyRotation),void 0!==r.anisotropyTexture&&s.push(n.assignTexture(t,"anisotropyMap",r.anisotropyTexture)),Promise.all(s)}}class qh{constructor(e){this.parser=e,this.name=Bh.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 s=i.extensions[this.name],r=t.options.ktx2Loader;if(!r){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,s.source,r)}}class Qh{constructor(e){this.parser=e,this.name=Bh.EXT_TEXTURE_WEBP,this.isSupported=null}loadTexture(e){const t=this.name,n=this.parser,i=n.json,s=i.textures[e];if(!s.extensions||!s.extensions[t])return null;const r=s.extensions[t],a=i.images[r.source];let o=n.textureLoader;if(a.uri){const e=n.options.manager.getHandler(a.uri);null!==e&&(o=e)}return this.detectSupport().then(function(s){if(s)return n.loadTextureImage(e,r.source,o);if(i.extensionsRequired&&i.extensionsRequired.indexOf(t)>=0)throw new Error("THREE.GLTFLoader: WebP required by asset but unsupported.");return n.loadTexture(e)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(e){const t=new Image;t.src="data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA",t.onload=t.onerror=function(){e(1===t.height)}})),this.isSupported}}class Kh{constructor(e){this.parser=e,this.name=Bh.EXT_TEXTURE_AVIF,this.isSupported=null}loadTexture(e){const t=this.name,n=this.parser,i=n.json,s=i.textures[e];if(!s.extensions||!s.extensions[t])return null;const r=s.extensions[t],a=i.images[r.source];let o=n.textureLoader;if(a.uri){const e=n.options.manager.getHandler(a.uri);null!==e&&(o=e)}return this.detectSupport().then(function(s){if(s)return n.loadTextureImage(e,r.source,o);if(i.extensionsRequired&&i.extensionsRequired.indexOf(t)>=0)throw new Error("THREE.GLTFLoader: AVIF required by asset but unsupported.");return n.loadTexture(e)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(e){const t=new Image;t.src="data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAABcAAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAEAAAABAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQAMAAAAABNjb2xybmNseAACAAIABoAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAAB9tZGF0EgAKCBgABogQEDQgMgkQAAAAB8dSLfI=",t.onload=t.onerror=function(){e(1===t.height)}})),this.isSupported}}class Yh{constructor(e){this.name=Bh.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),s=this.parser.options.meshoptDecoder;if(!s||!s.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,r=e.count,a=e.byteStride,o=new Uint8Array(t,n,i);return s.decodeGltfBufferAsync?s.decodeGltfBufferAsync(r,a,o,e.mode,e.filter).then(function(e){return e.buffer}):s.ready.then(function(){const t=new ArrayBuffer(r*a);return s.decodeGltfBuffer(new Uint8Array(t),r,a,o,e.mode,e.filter),t})})}return null}}class Zh{constructor(e){this.name=Bh.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!==lu.TRIANGLES&&o.mode!==lu.TRIANGLE_STRIP&&o.mode!==lu.TRIANGLE_FAN&&void 0!==o.mode)return null;const s=n.extensions[this.name].attributes,r=[],a={};for(const o in s)r.push(this.parser.getDependency("accessor",s[o]).then(e=>(a[o]=e,a[o])));return r.length<1?null:(r.push(this.parser.createNodeMesh(e)),Promise.all(r).then(e=>{const t=e.pop(),n=t.isGroup?t.children:[t],i=e[0].count,s=[];for(const r of n){const e=new Oi,t=new ci,n=new li,o=new ci(1,1,1),l=new sa(r.geometry,r.material,i);for(let s=0;s<i;s++)a.TRANSLATION&&t.fromBufferAttribute(a.TRANSLATION,s),a.ROTATION&&n.fromBufferAttribute(a.ROTATION,s),a.SCALE&&o.fromBufferAttribute(a.SCALE,s),l.setMatrixAt(s,e.compose(t,n,o));for(const i in a)if("_COLOR_0"===i){const e=a[i];l.instanceColor=new Yr(e.array,e.itemSize,e.normalized)}else"TRANSLATION"!==i&&"ROTATION"!==i&&"SCALE"!==i&&r.geometry.setAttribute(i,a[i]);ds.prototype.copy.call(l,r),this.parser.assignFinalMaterial(l),s.push(l)}return t.isGroup?(t.clear(),t.add(...s),t):s[0]}))}}const Jh="glTF",$h=1313821514,eu=5130562;class tu{constructor(e){this.name=Bh.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!==Jh)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,s=new DataView(e,12);let r=0;for(;r<i;){const t=s.getUint32(r,!0);r+=4;const i=s.getUint32(r,!0);if(r+=4,i===$h){const i=new Uint8Array(e,12+r,t);this.content=n.decode(i)}else if(i===eu){const n=12+r;this.body=e.slice(n,n+t)}r+=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=Bh.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const n=this.json,i=this.dracoLoader,s=e.extensions[this.name].bufferView,r=e.extensions[this.name].attributes,a={},o={},l={};for(const c in r){const e=pu[c]||c.toLowerCase();a[e]=r[c]}for(const c in e.attributes){const t=pu[c]||c.toLowerCase();if(void 0!==r[c]){const i=n.accessors[e.attributes[c]],s=cu[i.componentType];l[t]=s.name,o[t]=!0===i.normalized}}return t.getDependency("bufferView",s).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,on,n)})})}}class iu{constructor(){this.name=Bh.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 su{constructor(){this.name=Bh.KHR_MESH_QUANTIZATION}}class ru extends Ga{constructor(e,t,n,i){super(e,t,n,i)}copySampleValue_(e){const t=this.resultBuffer,n=this.sampleValues,i=this.valueSize,s=e*i*3+i;for(let r=0;r!==i;r++)t[r]=n[s+r];return t}interpolate_(e,t,n,i){const s=this.resultBuffer,r=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,v=1-m,_=g-u+h;for(let x=0;x!==a;x++){const e=r[f+x+a],t=r[f+x+o]*c,n=r[p+x+a],i=r[p+x]*c;s[x]=v*e+_*t+m*n+g*i}return s}}const au=new li;class ou extends ru{interpolate_(e,t,n,i){const s=super.interpolate_(e,t,n,i);return au.fromArray(s).normalize().toArray(s),s}}const lu={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},cu={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},hu={9728:Xe,9729:Ke,9984:1004,9985:Ye,9986:Qe,9987:Ze},uu={33071:We,33648:je,10497:Ge},du={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},pu={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"},fu={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},mu={CUBICSPLINE:void 0,LINEAR:Jt,STEP:Zt},gu="OPAQUE",vu="MASK",_u="BLEND";function xu(e){return void 0===e.DefaultMaterial&&(e.DefaultMaterial=new Ua({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:0})),e.DefaultMaterial}function yu(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 Au(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 Su(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 bu(e){let t;const n=e.extensions&&e.extensions[Bh.KHR_DRACO_MESH_COMPRESSION];if(t=n?"draco:"+n.bufferView+":"+n.indices+":"+Mu(n.attributes):e.indices+":"+Mu(e.attributes)+":"+e.mode,void 0!==e.targets)for(let i=0,s=e.targets.length;i<s;i++)t+=":"+Mu(e.targets[i]);return t}function Mu(e){let t="";const n=Object.keys(e).sort();for(let i=0,s=n.length;i<s;i++)t+=n[i]+":"+e[n[i]]+";";return t}function wu(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 Tu=new Oi;class Eu{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new Ph,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,s=!1,r=-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,s=e.indexOf("Firefox")>-1,r=s?e.match(/Firefox\/([0-9]+)\./)[1]:-1}"undefined"==typeof createImageBitmap||n&&i<17||s&&r<98?this.textureLoader=new uo(this.options.manager):this.textureLoader=new Io(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new co(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,s=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 r={scene:t[0][i.scene||0],scenes:t[0],animations:t[1],cameras:t[2],asset:i.asset,parser:n,userData:{}};return yu(s,r,i),Au(r,i),Promise.all(n._invokeAll(function(e){return e.afterRoot&&e.afterRoot(r)})).then(function(){for(const e of r.scenes)e.updateMatrixWorld();e(r)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let i=0,s=t.length;i<s;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,s=e.length;i<s;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(),s=(e,t)=>{const n=this.associations.get(e);null!=n&&this.associations.set(t,n);for(const[i,r]of e.children.entries())s(r,t.children[i])};return s(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 s=e(t[i]);s&&n.push(s)}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[Bh.KHR_BINARY_GLTF].body);const i=this.options;return new Promise(function(e,s){n.load(Co.resolveURL(t.uri,i.path),e,void 0,function(){s(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=du[i.type],t=cu[i.componentType],n=!0===i.normalized,s=new t(i.count*e);return Promise.resolve(new Vs(s,e,n))}const s=[];return void 0!==i.bufferView?s.push(this.getDependency("bufferView",i.bufferView)):s.push(null),void 0!==i.sparse&&(s.push(this.getDependency("bufferView",i.sparse.indices.bufferView)),s.push(this.getDependency("bufferView",i.sparse.values.bufferView))),Promise.all(s).then(function(e){const s=e[0],r=du[i.type],a=cu[i.componentType],o=a.BYTES_PER_ELEMENT,l=o*r,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(s,e*h,i.count*h/o),l=new Pr(d,h/o),t.cache.add(n,l)),p=new Lr(l,r,c%h/o,u)}else d=null===s?new a(i.count*r):new a(s,c,i.count*r),p=new Vs(d,r,u);if(void 0!==i.sparse){const t=du.SCALAR,n=cu[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*r);null!==s&&(p=new Vs(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*r]),r>=2&&p.setY(t,h[e*r+1]),r>=3&&p.setZ(t,h[e*r+2]),r>=4&&p.setW(t,h[e*r+3]),r>=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,s=t.images[i];let r=this.textureLoader;if(s.uri){const e=n.manager.getHandler(s.uri);null!==e&&(r=e)}return this.loadTextureImage(e,i,r)}loadTextureImage(e,t,n){const i=this,s=this.json,r=s.textures[e],a=s.images[t],o=(a.uri||a.bufferView)+":"+r.sampler;if(this.textureCache[o])return this.textureCache[o];const l=this.loadImageSource(t,n).then(function(t){t.flipY=!1,t.name=r.name||a.name||"",""===t.name&&"string"==typeof a.uri&&!1===a.uri.startsWith("data:image/")&&(t.name=a.uri);const n=(s.samplers||{})[r.sampler]||{};return t.magFilter=hu[n.magFilter]||Ke,t.minFilter=hu[n.minFilter]||Ze,t.wrapS=uu[n.wrapS]||Ge,t.wrapT=uu[n.wrapT]||Ge,t.generateMipmaps=!t.isCompressedTexture&&t.minFilter!==Xe&&t.minFilter!==Ke,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,s=this.options;if(void 0!==this.sourceCache[e])return this.sourceCache[e].then(e=>e.clone());const r=i.images[e],a=self.URL||self.webkitURL;let o=r.uri||"",l=!1;if(void 0!==r.bufferView)o=n.getDependency("bufferView",r.bufferView).then(function(e){l=!0;const t=new Blob([e],{type:r.mimeType});return o=a.createObjectURL(t),o});else if(void 0===r.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 r=n;!0===t.isImageBitmapLoader&&(r=function(e){const t=new ni(e);t.needsUpdate=!0,n(t)}),t.load(Co.resolveURL(e,s.path),r,void 0,i)})}).then(function(e){var t;return!0===l&&a.revokeObjectURL(o),Au(e,r),e.userData.mimeType=r.mimeType||((t=r.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 s=this;return this.getDependency("texture",n.index).then(function(r){if(!r)return null;if(void 0!==n.texCoord&&n.texCoord>0&&((r=r.clone()).channel=n.texCoord),s.extensions[Bh.KHR_TEXTURE_TRANSFORM]){const e=void 0!==n.extensions?n.extensions[Bh.KHR_TEXTURE_TRANSFORM]:void 0;if(e){const t=s.associations.get(r);r=s.extensions[Bh.KHR_TEXTURE_TRANSFORM].extendTexture(r,e),s.associations.set(r,t)}}return void 0!==i&&(r.colorSpace=i),e[t]=r,r})}assignFinalMaterial(e){const t=e.geometry;let n=e.material;const i=void 0===t.attributes.tangent,s=void 0!==t.attributes.color,r=void 0===t.attributes.normal;if(e.isPoints){const e="PointsMaterial:"+n.uuid;let t=this.cache.get(e);t||(t=new Ta,Ls.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 da,Ls.prototype.copy.call(t,n),t.color.copy(n.color),t.map=n.map,this.cache.add(e,t)),n=t}if(i||s||r){let e="ClonedMaterial:"+n.uuid+":";i&&(e+="derivative-tangents:"),s&&(e+="vertex-colors:"),r&&(e+="flat-shading:");let t=this.cache.get(e);t||(t=n.clone(),s&&(t.vertexColors=!0),r&&(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 Ua}loadMaterial(e){const t=this,n=this.json,i=this.extensions,s=n.materials[e];let r;const a={},o=[];if((s.extensions||{})[Bh.KHR_MATERIALS_UNLIT]){const e=i[Bh.KHR_MATERIALS_UNLIT];r=e.getMaterialType(),o.push(e.extendParams(a,s,t))}else{const n=s.pbrMetallicRoughness||{};if(a.color=new Ds(1,1,1),a.opacity=1,Array.isArray(n.baseColorFactor)){const e=n.baseColorFactor;a.color.setRGB(e[0],e[1],e[2],on),a.opacity=e[3]}void 0!==n.baseColorTexture&&o.push(t.assignTexture(a,"map",n.baseColorTexture,an)),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))),r=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===s.doubleSided&&(a.side=2);const l=s.alphaMode||gu;if(l===_u?(a.transparent=!0,a.depthWrite=!1):(a.transparent=!1,l===vu&&(a.alphaTest=void 0!==s.alphaCutoff?s.alphaCutoff:.5)),void 0!==s.normalTexture&&r!==Us&&(o.push(t.assignTexture(a,"normalMap",s.normalTexture)),a.normalScale=new Fn(1,1),void 0!==s.normalTexture.scale)){const e=s.normalTexture.scale;a.normalScale.set(e,e)}if(void 0!==s.occlusionTexture&&r!==Us&&(o.push(t.assignTexture(a,"aoMap",s.occlusionTexture)),void 0!==s.occlusionTexture.strength&&(a.aoMapIntensity=s.occlusionTexture.strength)),void 0!==s.emissiveFactor&&r!==Us){const e=s.emissiveFactor;a.emissive=(new Ds).setRGB(e[0],e[1],e[2],on)}return void 0!==s.emissiveTexture&&r!==Us&&o.push(t.assignTexture(a,"emissiveMap",s.emissiveTexture,an)),Promise.all(o).then(function(){const n=new r(a);return s.name&&(n.name=s.name),Au(n,s),t.associations.set(n,{materials:e}),s.extensions&&yu(i,n,s),n})}createUniqueName(e){const t=Ho.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 s(e){return n[Bh.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(e,t).then(function(n){return Cu(n,e,t)})}const r=[];for(let a=0,o=e.length;a<o;a++){const n=e[a],o=bu(n),l=i[o];if(l)r.push(l.promise);else{let e;e=n.extensions&&n.extensions[Bh.KHR_DRACO_MESH_COMPRESSION]?s(n):Cu(new $s,n,t),i[o]={primitive:n,promise:e},r.push(e)}}return Promise.all(r)}loadMesh(e){const t=this,n=this.json,i=this.extensions,s=n.meshes[e],r=s.primitives,a=[];for(let o=0,l=r.length;o<l;o++){const e=void 0===r[o].material?xu(this.cache):this.getDependency("material",r[o].material);a.push(e)}return a.push(t.loadGeometries(r)),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=r[h];let u;const d=a[h];if(c.mode===lu.TRIANGLES||c.mode===lu.TRIANGLE_STRIP||c.mode===lu.TRIANGLE_FAN||void 0===c.mode)u=!0===s.isSkinnedMesh?new Wr(n,d):new ur(n,d),!0===u.isSkinnedMesh&&u.normalizeSkinWeights(),c.mode===lu.TRIANGLE_STRIP?u.geometry=Ih(u.geometry,1):c.mode===lu.TRIANGLE_FAN&&(u.geometry=Ih(u.geometry,2));else if(c.mode===lu.LINES)u=new Ma(n,d);else if(c.mode===lu.LINE_STRIP)u=new ya(n,d);else if(c.mode===lu.LINE_LOOP)u=new wa(n,d);else{if(c.mode!==lu.POINTS)throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+c.mode);u=new Da(n,d)}Object.keys(u.geometry.morphAttributes).length>0&&Su(u,s),u.name=t.createUniqueName(s.name||"mesh_"+e),Au(u,s),c.extensions&&yu(i,u,c),t.assignFinalMaterial(u),l.push(u)}for(let i=0,s=l.length;i<s;i++)t.associations.set(l[i],{meshes:e,primitives:i});if(1===l.length)return s.extensions&&yu(i,l[0],s),l[0];const c=new Cr;s.extensions&&yu(i,c,s),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 br(Un.radToDeg(i.yfov),i.aspectRatio||1,i.znear||1,i.zfar||2e6):"orthographic"===n.type&&(t=new wo(-i.xmag,i.xmag,i.ymag,-i.ymag,i.znear,i.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),Au(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,s=t.joints.length;i<s;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,s=[],r=[];for(let a=0,o=i.length;a<o;a++){const e=i[a];if(e){s.push(e);const t=new Oi;null!==n&&t.fromArray(n.array,16*a),r.push(t)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[a])}return new Kr(s,r)})}loadAnimation(e){const t=this.json,n=this,i=t.animations[e],s=i.name?i.name:"animation_"+e,r=[],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,s=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&&(r.push(this.getDependency("node",s)),a.push(this.getDependency("accessor",u)),o.push(this.getDependency("accessor",d)),l.push(t),c.push(n))}return Promise.all([Promise.all(r),Promise.all(a),Promise.all(o),Promise.all(l),Promise.all(c)]).then(function(e){const t=e[0],i=e[1],r=e[2],a=e[3],o=e[4],l=[];for(let s=0,c=t.length;s<c;s++){const e=t[s],c=i[s],h=r[s],u=a[s],d=o[s];if(void 0===e)continue;e.updateMatrix&&e.updateMatrix();const p=n._createAnimationTracks(e,c,h,u,d);if(p)for(let t=0;t<p.length;t++)l.push(p[t])}return new to(s,void 0,l)})}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),s=[],r=n.children||[];for(let o=0,l=r.length;o<l;o++)s.push(t.getDependency("node",r[o]));const a=void 0===n.skin?Promise.resolve(null):t.getDependency("skin",n.skin);return Promise.all([i,Promise.all(s),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,Tu)});for(let s=0,r=n.length;s<r;s++)t.add(n[s]);return t})}_loadNodeShallow(e){const t=this.json,n=this.extensions,i=this;if(void 0!==this.nodeCache[e])return this.nodeCache[e];const s=t.nodes[e],r=s.name?i.createUniqueName(s.name):"",a=[],o=i._invokeOne(function(t){return t.createNodeMesh&&t.createNodeMesh(e)});return o&&a.push(o),void 0!==s.camera&&a.push(i.getDependency("camera",s.camera).then(function(e){return i._getNodeRef(i.cameraCache,s.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===s.isBone?new jr:t.length>1?new Cr:1===t.length?t[0]:new ds,a!==t[0])for(let e=0,n=t.length;e<n;e++)a.add(t[e]);if(s.name&&(a.userData.name=s.name,a.name=r),Au(a,s),s.extensions&&yu(n,a,s),void 0!==s.matrix){const e=new Oi;e.fromArray(s.matrix),a.applyMatrix4(e)}else void 0!==s.translation&&a.position.fromArray(s.translation),void 0!==s.rotation&&a.quaternion.fromArray(s.rotation),void 0!==s.scale&&a.scale.fromArray(s.scale);return i.associations.has(a)||i.associations.set(a,{}),i.associations.get(a).nodes=e,a}),this.nodeCache[e]}loadScene(e){const t=this.extensions,n=this.json.scenes[e],i=this,s=new Cr;n.name&&(s.name=i.createUniqueName(n.name)),Au(s,n),n.extensions&&yu(t,s,n);const r=n.nodes||[],a=[];for(let o=0,l=r.length;o<l;o++)a.push(i.getDependency("node",r[o]));return Promise.all(a).then(function(e){for(let t=0,n=e.length;t<n;t++)s.add(e[t]);return i.associations=(e=>{const t=new Map;for(const[n,s]of i.associations)(n instanceof Ls||n instanceof ni)&&t.set(n,s);return e.traverse(e=>{const n=i.associations.get(e);null!=n&&t.set(e,n)}),t})(s),s})}_createAnimationTracks(e,t,n,i,s){const r=[],a=e.name?e.name:e.uuid,o=[];let l;switch(fu[s.path]===fu.weights?e.traverse(function(e){e.morphTargetInfluences&&o.push(e.name?e.name:e.uuid)}):o.push(a),fu[s.path]){case fu.weights:l=Ya;break;case fu.rotation:l=Ja;break;case fu.position:case fu.scale:l=eo;break;default:if(1===n.itemSize)l=Ya;else l=eo}const c=void 0!==i.interpolation?mu[i.interpolation]:Jt,h=this._getArrayFromAccessor(n);for(let u=0,d=o.length;u<d;u++){const e=new l(o[u]+"."+fu[s.path],t.array,h,c);"CUBICSPLINE"===i.interpolation&&this._createCubicSplineTrackInterpolant(e),r.push(e)}return r}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const e=wu(t.constructor),n=new Float32Array(t.length);for(let i=0,s=t.length;i<s;i++)n[i]=t[i]*e;t=n}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(e){return new(this instanceof Ja?ou:ru)(this.times,this.values,this.getValueSize()/3,e)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function Cu(e,t,n){const i=t.attributes,s=[];function r(t,i){return n.getDependency("accessor",t).then(function(t){e.setAttribute(i,t)})}for(const a in i){const t=pu[a]||a.toLowerCase();t in e.attributes||s.push(r(i[a],t))}if(void 0!==t.indices&&!e.index){const i=n.getDependency("accessor",t.indices).then(function(t){e.setIndex(t)});s.push(i)}return qn.workingColorSpace!==on&&"COLOR_0"in i&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${qn.workingColorSpace}" not supported.`),Au(e,t),function(e,t,n){const i=t.attributes,s=new di;if(void 0===i.POSITION)return;{const e=n.json.accessors[i.POSITION],t=e.min,r=e.max;if(void 0===t||void 0===r)return void console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");if(s.set(new ci(t[0],t[1],t[2]),new ci(r[0],r[1],r[2])),e.normalized){const t=wu(cu[e.componentType]);s.min.multiplyScalar(t),s.max.multiplyScalar(t)}}const r=t.targets;if(void 0!==r){const e=new ci,t=new ci;for(let i=0,s=r.length;i<s;i++){const s=r[i];if(void 0!==s.POSITION){const i=n.json.accessors[s.POSITION],r=i.min,a=i.max;if(void 0!==r&&void 0!==a){if(t.setX(Math.max(Math.abs(r[0]),Math.abs(a[0]))),t.setY(Math.max(Math.abs(r[1]),Math.abs(a[1]))),t.setZ(Math.max(Math.abs(r[2]),Math.abs(a[2]))),i.normalized){const e=wu(cu[i.componentType]);t.multiplyScalar(e)}e.max(t)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}s.expandByVector(e)}e.boundingBox=s;const a=new Ii;s.getCenter(a.center),a.radius=s.min.distanceTo(s.max)/2,e.boundingSphere=a}(e,t,n),Promise.all(s).then(function(){return void 0!==t.targets?function(e,t,n){let i=!1,s=!1,r=!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&&(s=!0),void 0!==e.COLOR_0&&(r=!0),i&&s&&r)break}if(!i&&!s&&!r)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(s){const t=void 0!==h.NORMAL?n.getDependency("accessor",h.NORMAL):e.attributes.normal;o.push(t)}if(r){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),s&&(e.morphAttributes.normal=a),r&&(e.morphAttributes.color=o),e.morphTargetsRelative=!0,e})}(e,t.targets,n):e})}var Ru="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Iu(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Du(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 Pu={exports:{}};Pu.exports=function e(t,n,i){function s(a,o){if(!n[a]){if(!t[a]){if(!o&&Du)return Du(a);if(r)return r(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 s(t[a][1][e]||e)},c,c.exports,e,t,n,i)}return n[a].exports}for(var r=Du,a=0;a<i.length;a++)s(i[a]);return s}({1:[function(e,t,n){var i=e("./utils"),s=e("./support"),r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";n.encode=function(e){for(var t,n,s,a,o,l,c,h=[],u=0,d=e.length,p=d,f="string"!==i.getTypeOf(e);u<e.length;)p=d-u,s=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|s>>6:64,c=2<p?63&s:64,h.push(r.charAt(a)+r.charAt(o)+r.charAt(l)+r.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)===r.charAt(64)&&p--,e.charAt(e.length-2)===r.charAt(64)&&p--,p%1!=0)throw new Error("Invalid base64 input, bad content length.");for(d=s.uint8array?new Uint8Array(0|p):new Array(0|p);c<e.length;)t=r.indexOf(e.charAt(c++))<<2|(a=r.indexOf(e.charAt(c++)))>>4,n=(15&a)<<4|(o=r.indexOf(e.charAt(c++)))>>2,i=(3&o)<<6|(l=r.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"),s=e("./stream/DataWorker"),r=e("./stream/Crc32Probe"),a=e("./stream/DataLengthProbe");function o(e,t,n,i,s){this.compressedSize=e,this.uncompressedSize=t,this.crc32=n,this.compression=i,this.compressedContent=s}o.prototype={getContentWorker:function(){var e=new s(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 s(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 r).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"),s=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 r=s,a=i+n;e^=-1;for(var o=i;o<a;o++)e=e>>>8^r[255&(e^t[o])];return-1^e}(0|t,e,e.length,0):function(e,t,n,i){var r=s,a=i+n;e^=-1;for(var o=i;o<a;o++)e=e>>>8^r[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,s=e("pako"),r=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",r.inherits(l,a),l.prototype.processChunk=function(e){this.meta=e.meta,null===this._pako&&this._createPako(),this._pako.push(r.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 s[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var e=this;this._pako.onData=function(t){e.push({data:t,meta:e.meta})}},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 s(e,t,n,s,a,h){var u,d,p=e.file,f=e.compression,m=h!==o.utf8encode,g=r.transformTo("string",h(p.name)),v=r.transformTo("string",o.utf8encode(p.name)),_=p.comment,x=r.transformTo("string",h(_)),y=r.transformTo("string",o.utf8encode(_)),A=v.length!==p.name.length,S=y.length!==_.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||!A&&!S||(R|=2048);var I,D,P,B=0,L=0;T&&(B|=16),"UNIX"===a?(L=798,B|=(I=p.unixPermissions,D=T,P=I,I||(P=D?16893:33204),(65535&P)<<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(),A&&(M=i(1,1)+i(l(g),4)+v,b+="up"+i(M.length,2)+M),S&&(w=i(1,1)+i(l(x),4)+y,b+="uc"+i(w.length,2)+w);var U="";return U+="\n\0",U+=i(R,2),U+=f.magic,U+=i(u,2),U+=i(d,2),U+=i(C.crc32,4),U+=i(C.compressedSize,4),U+=i(C.uncompressedSize,4),U+=i(g.length,2),U+=i(b.length,2),{fileRecord:c.LOCAL_FILE_HEADER+U+g+b,dirRecord:c.CENTRAL_FILE_HEADER+i(L,2)+U+i(x.length,2)+"\0\0\0\0"+i(B,4)+i(s,4)+g+b+x}}var r=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=[]}r.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=s(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,r=s(e,n,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(r.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:r.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},h.prototype.flush=function(){for(var e=this.bytesWritten,t=0;t<this.dirRecords.length;t++)this.push({data:this.dirRecords[t],meta:{percent:100}});var n,s,a,o,l,h,u=this.bytesWritten-e,d=(n=this.dirRecords.length,s=u,a=e,o=this.zipComment,l=this.encodeFileName,h=r.transformTo("string",l(o)),c.CENTRAL_DIRECTORY_END+"\0\0\0\0"+i(n,2)+i(n,2)+i(s,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"),s=e("./ZipFileWorker");n.generateWorker=function(e,t,n){var r=new s(t.streamFiles,n,t.platform,t.encodeFileName),a=0;try{e.forEach(function(e,n){a++;var s=function(e,t){var n=e||t,s=i[n];if(!s)throw new Error(n+" is not a valid compression method !");return s}(n.options.compression,t.compression),o=n.options.compressionOptions||t.compressionOptions||{},l=n.dir,c=n.date;n._compressWorker(s,o).withStreamInfo("file",{name:e,dir:l,date:c,comment:n.comment||"",unixPermissions:n.unixPermissions,dosPermissions:n.dosPermissions}).pipe(r)}),r.entriesCount=a}catch(o){r.error(o)}return r}},{"../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"),s=e("./external"),r=e("./utf8"),a=e("./zipEntries"),o=e("./stream/Crc32Probe"),l=e("./nodejsUtils");function c(e){return new s.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:r.utf8decode}),l.isNode&&l.isStream(e)?s.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=[s.Promise.resolve(e)],i=e.files;if(t.checkCRC32)for(var r=0;r<i.length;r++)n.push(c(i[r]));return s.Promise.all(n)}).then(function(e){for(var s=e.shift(),r=s.files,a=0;a<r.length;a++){var o=r[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 s.zipComment.length&&(n.comment=s.zipComment),n})}},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(e,t,n){var i=e("../utils"),s=e("../stream/GenericWorker");function r(e,t){s.call(this,"Nodejs stream input adapter for "+e),this._upstreamEnded=!1,this._bindStream(t)}i.inherits(r,s),r.prototype._bindStream=function(e){var t=this;(this._stream=e).pause(),e.on("data",function(e){t.push({data:e,meta:{percent:0}})}).on("error",function(e){t.isPaused?this.generatedError=e:t.error(e)}).on("end",function(){t.isPaused?t._upstreamEnded=!0:t.end()})},r.prototype.pause=function(){return!!s.prototype.pause.call(this)&&(this._stream.pause(),!0)},r.prototype.resume=function(){return!!s.prototype.resume.call(this)&&(this._upstreamEnded?this.end():this._stream.resume(),!0)},t.exports=r},{"../stream/GenericWorker":28,"../utils":32}],13:[function(e,t,n){var i=e("readable-stream").Readable;function s(e,t,n){i.call(this,t),this._helper=e;var s=this;e.on("data",function(e,t){s.push(e)||s._helper.pause(),n&&n(t)}).on("error",function(e){s.emit("error",e)}).on("end",function(){s.push(null)})}e("../utils").inherits(s,i),s.prototype._read=function(){this._helper.resume()},t.exports=s},{"../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,s=r.getTypeOf(t),o=r.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"===s&&!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",s="string");var v=null;v=t instanceof c||t instanceof a?t:d.isNode&&d.isStream(t)?new p(e,t):r.prepareContent(e,t,o.binary,o.optimizedBinaryString,o.base64);var _=new h(e,v,o);this.files[e]=_}var s=e("./utf8"),r=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 v(e){return"[object RegExp]"===Object.prototype.toString.call(e)}var _={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(v(e)){var s=e;return this.filter(function(e,t){return!t.dir&&s.test(e)})}var r=this.files[this.root+e];return r&&!r.dir?r:null},folder:function(e){if(!e)return this;if(v(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=r.extend(e||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:s.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.");r.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=_},{"./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 s(e){i.call(this,e);for(var t=0;t<this.data.length;t++)e[t]=255&e[t]}e("../utils").inherits(s,i),s.prototype.byteAt=function(e){return this.data[this.zero+e]},s.prototype.lastIndexOfSignature=function(e){for(var t=e.charCodeAt(0),n=e.charCodeAt(1),i=e.charCodeAt(2),s=e.charCodeAt(3),r=this.length-4;0<=r;--r)if(this.data[r]===t&&this.data[r+1]===n&&this.data[r+2]===i&&this.data[r+3]===s)return r-this.zero;return-1},s.prototype.readAndCheckSignature=function(e){var t=e.charCodeAt(0),n=e.charCodeAt(1),i=e.charCodeAt(2),s=e.charCodeAt(3),r=this.readData(4);return t===r[0]&&n===r[1]&&i===r[2]&&s===r[3]},s.prototype.readData=function(e){if(this.checkOffset(e),0===e)return[];var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=s},{"../utils":32,"./DataReader":18}],18:[function(e,t,n){var i=e("../utils");function s(e){this.data=e,this.length=e.length,this.index=0,this.zero=0}s.prototype={checkOffset:function(e){this.checkIndex(this.index+e)},checkIndex:function(e){if(this.length<this.zero+e||e<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+e+"). Corrupted zip ?")},setIndex:function(e){this.checkIndex(e),this.index=e},skip:function(e){this.setIndex(this.index+e)},byteAt:function(){},readInt:function(e){var t,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=s},{"../utils":32}],19:[function(e,t,n){var i=e("./Uint8ArrayReader");function s(e){i.call(this,e)}e("../utils").inherits(s,i),s.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=s},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(e,t,n){var i=e("./DataReader");function s(e){i.call(this,e)}e("../utils").inherits(s,i),s.prototype.byteAt=function(e){return this.data.charCodeAt(this.zero+e)},s.prototype.lastIndexOfSignature=function(e){return this.data.lastIndexOf(e)-this.zero},s.prototype.readAndCheckSignature=function(e){return e===this.readData(4)},s.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=s},{"../utils":32,"./DataReader":18}],21:[function(e,t,n){var i=e("./ArrayReader");function s(e){i.call(this,e)}e("../utils").inherits(s,i),s.prototype.readData=function(e){if(this.checkOffset(e),0===e)return new Uint8Array(0);var t=this.data.subarray(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=s},{"../utils":32,"./ArrayReader":17}],22:[function(e,t,n){var i=e("../utils"),s=e("../support"),r=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||s.uint8array?"nodebuffer"===t?new o(e):s.uint8array?new l(i.transformTo("uint8array",e)):new r(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"),s=e("../utils");function r(e){i.call(this,"ConvertWorker to "+e),this.destType=e}s.inherits(r,i),r.prototype.processChunk=function(e){this.push({data:s.transformTo(this.destType,e.data),meta:e.meta})},t.exports=r},{"../utils":32,"./GenericWorker":28}],25:[function(e,t,n){var i=e("./GenericWorker"),s=e("../crc32");function r(){i.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}e("../utils").inherits(r,i),r.prototype.processChunk=function(e){this.streamInfo.crc32=s(e.data,this.streamInfo.crc32||0),this.push(e)},t.exports=r},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(e,t,n){var i=e("../utils"),s=e("./GenericWorker");function r(e){s.call(this,"DataLengthProbe for "+e),this.propName=e,this.withStreamInfo(e,0)}i.inherits(r,s),r.prototype.processChunk=function(e){if(e){var t=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=t+e.data.length}s.prototype.processChunk.call(this,e)},t.exports=r},{"../utils":32,"./GenericWorker":28}],27:[function(e,t,n){var i=e("../utils"),s=e("./GenericWorker");function r(e){s.call(this,"DataWorker");var t=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,e.then(function(e){t.dataIsReady=!0,t.data=e,t.max=e&&e.length||0,t.type=i.getTypeOf(e),t.isPaused||t._tickAndRepeat()},function(e){t.error(e)})}i.inherits(r,s),r.prototype.cleanUp=function(){s.prototype.cleanUp.call(this),this.data=null},r.prototype.resume=function(){return!!s.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,i.delay(this._tickAndRepeat,[],this)),!0)},r.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(i.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},r.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var e=null,t=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":e=this.data.substring(this.index,t);break;case"uint8array":e=this.data.subarray(this.index,t);break;case"array":case"nodebuffer":e=this.data.slice(this.index,t)}return this.index=t,this.push({data:e,meta:{percent:this.max?this.index/this.max*100:0}})},t.exports=r},{"../utils":32,"./GenericWorker":28}],28:[function(e,t,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"),s=e("./ConvertWorker"),r=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,s){var r=[],o=e._internalType,l=e._outputType,c=e._mimeType;e.on("data",function(e,n){r.push(e),t&&t(n)}).on("error",function(e){r=[],s(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,s=null,r=0;for(n=0;n<t.length;n++)r+=t[n].length;switch(e){case"string":return t.join("");case"array":return Array.prototype.concat.apply([],t);case"uint8array":for(s=new Uint8Array(r),n=0;n<t.length;n++)s.set(t[n],i),i+=t[n].length;return s;case"nodebuffer":return Buffer.concat(t);default:throw new Error("concat : unsupported type '"+e+"'")}}(o,r),c);n(e)}catch(t){s(t)}r=[]}).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 s(a)),e.lock()}catch(o){this._worker=new r("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(r){try{var s=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);s.append(i),n.blob=0===s.getBlob("application/zip").size}catch(a){n.blob=!1}}}try{n.nodestream=!!e("readable-stream").Readable}catch(r){n.nodestream=!1}},{"readable-stream":16}],31:[function(e,t,n){for(var i=e("./utils"),s=e("./support"),r=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 s.nodebuffer?r.newBufferFrom(e,"utf-8"):function(e){var t,n,i,r,a,o=e.length,l=0;for(r=0;r<o;r++)55296==(64512&(n=e.charCodeAt(r)))&&r+1<o&&56320==(64512&(i=e.charCodeAt(r+1)))&&(n=65536+(n-55296<<10)+(i-56320),r++),l+=n<128?1:n<2048?2:n<65536?3:4;for(t=s.uint8array?new Uint8Array(l):new Array(l),r=a=0;a<l;r++)55296==(64512&(n=e.charCodeAt(r)))&&r+1<o&&56320==(64512&(i=e.charCodeAt(r+1)))&&(n=65536+(n-55296<<10)+(i-56320),r++),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 s.nodebuffer?i.transformTo("nodebuffer",e).toString("utf-8"):function(e){var t,n,s,r,a=e.length,l=new Array(2*a);for(t=n=0;t<a;)if((s=e[t++])<128)l[n++]=s;else if(4<(r=o[s]))l[n++]=65533,t+=r-1;else{for(s&=2===r?31:3===r?15:7;1<r&&t<a;)s=s<<6|63&e[t++],r--;1<r?l[n++]=65533:s<65536?l[n++]=s:(s-=65536,l[n++]=55296|s>>10&1023,l[n++]=56320|1023&s)}return l.length!==n&&(l.subarray?l=l.subarray(0,n):l.length=n),i.applyFromCharCode(l)}(e=i.transformTo(s.uint8array?"uint8array":"array",e))},i.inherits(c,a),c.prototype.processChunk=function(e){var t=i.transformTo(s.uint8array?"uint8array":"array",e.data);if(this.leftOver&&this.leftOver.length){if(s.uint8array){var r=t;(t=new Uint8Array(r.length+this.leftOver.length)).set(this.leftOver,0),t.set(r,this.leftOver.length)}else t=this.leftOver.concat(t);this.leftOver=null}var 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&&(s.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"),s=e("./base64"),r=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(s){try{var i=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return i.append(e),i.getBlob(t)}catch(r){throw new Error("Bug : can't construct the Blob.")}}};var c={stringifyByChunk:function(e,t,n){var i=[],s=0,r=e.length;if(r<=n)return String.fromCharCode.apply(null,e);for(;s<r;)"array"===t||"nodebuffer"===t?i.push(String.fromCharCode.apply(null,e.slice(s,Math.min(s+n,r)))):i.push(String.fromCharCode.apply(null,e.subarray(s,Math.min(s+n,r)))),s+=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,r.allocBuffer(1)).length}catch(e){return!1}}()}};function h(e){var t=65536,i=n.getTypeOf(e),s=!0;if("uint8array"===i?s=c.applyCanBeUsed.uint8array:"nodebuffer"===i&&(s=c.applyCanBeUsed.nodebuffer),s)for(;1<t;)try{return c.stringifyByChunk(e,i,t)}catch(r){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,r.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 r.newBufferFrom(e)}},d.arraybuffer={string:function(e){return h(new Uint8Array(e))},array:function(e){return u(new Uint8Array(e),new Array(e.byteLength))},arraybuffer:o,uint8array:function(e){return new Uint8Array(e)},nodebuffer:function(e){return r.newBufferFrom(new Uint8Array(e))}},d.uint8array={string:h,array:function(e){return u(e,new Array(e.length))},arraybuffer:function(e){return e.buffer},uint8array:o,nodebuffer:function(e){return r.newBufferFrom(e)}},d.nodebuffer={string:h,array:function(e){return u(e,new Array(e.length))},arraybuffer:function(e){return d.nodebuffer.uint8array(e).buffer},uint8array:function(e){return u(e,new Uint8Array(e.length))},nodebuffer: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 s=t[i];"."===s||""===s&&0!==i&&i!==t.length-1||(".."===s?n.pop():n.push(s))}return n.join("/")},n.getTypeOf=function(e){return"string"==typeof e?"string":"[object Array]"===Object.prototype.toString.call(e)?"array":i.nodebuffer&&r.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,r,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=s.decode(t):r&&!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"),s=e("./utils"),r=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 ("+s.pretty(t)+", expected "+s.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=s.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(r.LOCAL_FILE_HEADER),t.readLocalPart(this.reader),t.handleUTF8(),t.processAttributes()},readCentralDir:function(){var e;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(r.CENTRAL_FILE_HEADER);)(e=new 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(r.CENTRAL_DIRECTORY_END);if(e<0)throw this.isSignature(0,r.LOCAL_FILE_HEADER)?new Error("Corrupted zip: can't find end of central directory"):new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html");this.reader.setIndex(e);var t=e;if(this.checkSignature(r.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===s.MAX_VALUE_16BITS||this.diskWithCentralDirStart===s.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===s.MAX_VALUE_16BITS||this.centralDirRecords===s.MAX_VALUE_16BITS||this.centralDirSize===s.MAX_VALUE_32BITS||this.centralDirOffset===s.MAX_VALUE_32BITS){if(this.zip64=!0,(e=this.reader.lastIndexOfSignature(r.ZIP64_CENTRAL_DIRECTORY_LOCATOR))<0)throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");if(this.reader.setIndex(e),this.checkSignature(r.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),!this.isSignature(this.relativeOffsetEndOfZip64CentralDir,r.ZIP64_CENTRAL_DIRECTORY_END)&&(this.relativeOffsetEndOfZip64CentralDir=this.reader.lastIndexOfSignature(r.ZIP64_CENTRAL_DIRECTORY_END),this.relativeOffsetEndOfZip64CentralDir<0))throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir),this.checkSignature(r.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral()}var n=this.centralDirOffset+this.centralDirSize;this.zip64&&(n+=20,n+=12+this.zip64EndOfCentralSize);var i=t-n;if(0<i)this.isSignature(t,r.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"),s=e("./utils"),r=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 "+s.pretty(this.compressionMethod)+" unknown (inner file : "+s.transformTo("string",this.fileName)+")");this.decompressed=new r(this.compressedSize,this.uncompressedSize,this.crc32,t,e.readData(this.compressedSize))},readCentralPart:function(e){this.versionMadeBy=e.readInt(2),e.skip(2),this.bitFlag=e.readInt(2),this.compressionMethod=e.readString(2),this.date=e.readDate(),this.crc32=e.readInt(4),this.compressedSize=e.readInt(4),this.uncompressedSize=e.readInt(4);var t=e.readInt(2);if(this.extraFieldsLength=e.readInt(2),this.fileCommentLength=e.readInt(2),this.diskNumberStart=e.readInt(2),this.internalFileAttributes=e.readInt(2),this.externalFileAttributes=e.readInt(4),this.localHeaderOffset=e.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");e.skip(t),this.readExtraFields(e),this.parseZIP64ExtraField(e),this.fileComment=e.readData(this.fileCommentLength)},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var e=this.versionMadeBy>>8;this.dir=!!(16&this.externalFileAttributes),0==e&&(this.dosPermissions=63&this.externalFileAttributes),3==e&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||"/"!==this.fileNameStr.slice(-1)||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var e=i(this.extraFields[1].value);this.uncompressedSize===s.MAX_VALUE_32BITS&&(this.uncompressedSize=e.readInt(8)),this.compressedSize===s.MAX_VALUE_32BITS&&(this.compressedSize=e.readInt(8)),this.localHeaderOffset===s.MAX_VALUE_32BITS&&(this.localHeaderOffset=e.readInt(8)),this.diskNumberStart===s.MAX_VALUE_32BITS&&(this.diskNumberStart=e.readInt(4))}},readExtraFields:function(e){var t,n,i,s=e.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});e.index+4<s;)t=e.readInt(2),n=e.readInt(2),i=e.readData(n),this.extraFields[t]={id:t,length:n,value:i};e.setIndex(s)},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=s.transformTo(e,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(n)}var i=this.findExtraFieldUnicodeComment();if(null!==i)this.fileCommentStr=i;else{var r=s.transformTo(e,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(r)}}},findExtraFieldUnicodePath:function(){var e=this.extraFields[28789];if(e){var t=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 s=e("./stream/StreamHelper"),r=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 r=!this._dataBinary;r&&!i&&(t=t.pipe(new a.Utf8EncodeWorker)),!r&&i&&(t=t.pipe(new a.Utf8DecodeWorker))}catch(o){(t=new l("error")).error(o)}return new s(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 r(this._data)}};for(var c=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],h=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},u=0;u<c.length;u++)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,s=e.MutationObserver||e.WebKitMutationObserver;if(s){var r=0,a=new s(h),o=e.document.createTextNode("");a.observe(o,{characterData:!0}),n=function(){o.data=r=++r%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!==Ru?Ru:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],37:[function(e,t,n){var i=e("immediate");function s(){}var r={},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!==s&&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(s){return r.reject(e,s)}i===e?r.reject(e,new TypeError("Cannot resolve promise with itself")):r.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,r.reject(e,t))}function s(t){n||(n=!0,r.resolve(e,t))}var a=f(function(){t(s,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(s);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){r.resolve(this.promise,e)},h.prototype.otherCallFulfilled=function(e){u(this.promise,this.onFulfilled,e)},h.prototype.callRejected=function(e){r.reject(this.promise,e)},h.prototype.otherCallRejected=function(e){u(this.promise,this.onRejected,e)},r.resolve=function(e,t){var n=f(d,t);if("error"===n.status)return r.reject(e,n.value);var i=n.value;if(i)p(e,i);else{e.state=o,e.outcome=t;for(var s=-1,a=e.queue.length;++s<a;)e.queue[s].callFulfilled(t)}return e},r.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:r.resolve(new this(s),e)},c.reject=function(e){var t=new this(s);return r.reject(t,e)},c.all=function(e){var t=this;if("[object Array]"!==Object.prototype.toString.call(e))return this.reject(new TypeError("must be an array"));var n=e.length,i=!1;if(!n)return this.resolve([]);for(var a=new Array(n),o=0,l=-1,c=new this(s);++l<n;)h(e[l],l);return c;function h(e,s){t.resolve(e).then(function(e){a[s]=e,++o!==n||i||(i=!0,r.resolve(c,a))},function(e){i||(i=!0,r.reject(c,e))})}},c.race=function(e){var t=this;if("[object Array]"!==Object.prototype.toString.call(e))return this.reject(new TypeError("must be an array"));var n=e.length,i=!1;if(!n)return this.resolve([]);for(var a,o=-1,l=new this(s);++o<n;)a=e[o],t.resolve(a).then(function(e){i||(i=!0,r.resolve(l,e))},function(e){i||(i=!0,r.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"),s=e("./utils/common"),r=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=s.assign({level:h,method:d,chunkSize:16384,windowBits:15,memLevel:8,strategy:u,to:""},e||{});var t=this.options;t.raw&&0<t.windowBits?t.windowBits=-t.windowBits:t.gzip&&0<t.windowBits&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new 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?r.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=r.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 s.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(r.buf2binstring(s.shrinkBuf(o.output,o.next_out))):this.onData(s.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=s.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"),s=e("./utils/common"),r=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=s.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&0<=t.windowBits&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(0<=t.windowBits&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),15<t.windowBits&&t.windowBits<48&&!(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var 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=r.binstring2buf(e):"[object ArrayBuffer]"===h.call(e)?p.input=new Uint8Array(e):p.input=e,p.next_in=0,p.avail_in=p.input.length;do{if(0===p.avail_out&&(p.output=new s.Buf8(f),p.next_out=0,p.avail_out=f),(n=i.inflate(p,a.Z_NO_FLUSH))===a.Z_NEED_DICT&&m&&(d="string"==typeof m?r.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=r.utf8border(p.output,p.next_out),c=p.next_out-l,u=r.buf2string(p.output,l),p.next_out=c,p.avail_out=f-c,c&&s.arraySet(p.output,p.output,l,c,0),this.onData(u)):this.onData(s.shrinkBuf(p.output,p.next_out)))),0===p.avail_in&&0===p.avail_out&&(g=!0)}while((0<p.avail_in||0===p.avail_out)&&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=s.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 s={arraySet:function(e,t,n,i,s){if(t.subarray&&e.subarray)e.set(t.subarray(n,n+i),s);else for(var r=0;r<i;r++)e[s+r]=t[n+r]},flattenChunks:function(e){var t,n,i,s,r,a;for(t=i=0,n=e.length;t<n;t++)i+=e[t].length;for(a=new Uint8Array(i),t=s=0,n=e.length;t<n;t++)r=e[t],a.set(r,s),s+=r.length;return a}},r={arraySet:function(e,t,n,i,s){for(var r=0;r<i;r++)e[s+r]=t[n+r]},flattenChunks:function(e){return[].concat.apply([],e)}};n.setTyped=function(e){e?(n.Buf8=Uint8Array,n.Buf16=Uint16Array,n.Buf32=Int32Array,n.assign(n,s)):(n.Buf8=Array,n.Buf16=Array,n.Buf32=Array,n.assign(n,r))},n.setTyped(i)},{}],42:[function(e,t,n){var i=e("./common"),s=!0,r=!0;try{String.fromCharCode.apply(null,[0])}catch(c){s=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(c){r=!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&&r||!e.subarray&&s))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,s,r,a,o=e.length,l=0;for(r=0;r<o;r++)55296==(64512&(n=e.charCodeAt(r)))&&r+1<o&&56320==(64512&(s=e.charCodeAt(r+1)))&&(n=65536+(n-55296<<10)+(s-56320),r++),l+=n<128?1:n<2048?2:n<65536?3:4;for(t=new i.Buf8(l),r=a=0;a<l;r++)55296==(64512&(n=e.charCodeAt(r)))&&r+1<o&&56320==(64512&(s=e.charCodeAt(r+1)))&&(n=65536+(n-55296<<10)+(s-56320),r++),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,s=t.length;n<s;n++)t[n]=e.charCodeAt(n);return t},n.buf2string=function(e,t){var n,i,s,r,o=t||e.length,c=new Array(2*o);for(n=i=0;n<o;)if((s=e[n++])<128)c[i++]=s;else if(4<(r=a[s]))c[i++]=65533,n+=r-1;else{for(s&=2===r?31:3===r?15:7;1<r&&n<o;)s=s<<6|63&e[n++],r--;1<r?c[i++]=65533:s<65536?c[i++]=s:(s-=65536,c[i++]=55296|s>>10&1023,c[i++]=56320|1023&s)}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 s=65535&e,r=e>>>16&65535,a=0;0!==n;){for(n-=a=2e3<n?2e3:n;r=r+(s=s+t[i++]|0)|0,--a;);s%=65521,r%=65521}return s|r<<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,s){var r=i,a=s+n;e^=-1;for(var o=s;o<a;o++)e=e>>>8^r[255&(e^t[o])];return-1^e}},{}],46:[function(e,t,n){var i,s=e("../utils/common"),r=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,v=9,_=286,x=30,y=19,A=2*_+1,S=15,b=3,M=258,w=M+b+1,T=42,E=113,C=1,R=2,I=3,D=4;function P(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 U(e){var t=e.state,n=t.pending;n>e.avail_out&&(n=e.avail_out),0!==n&&(s.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 F(e,t){r._tr_flush_block(e,0<=e.block_start?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,U(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,s=e.max_chain_length,r=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[r+a-1],f=c[r+a];e.prev_length>=e.good_match&&(s>>=2),o>e.lookahead&&(o=e.lookahead);do{if(c[(n=t)+a]===f&&c[n+a-1]===p&&c[n]===c[r]&&c[++n]===c[r+1]){r+=2,n++;do{}while(c[++r]===c[++n]&&c[++r]===c[++n]&&c[++r]===c[++n]&&c[++r]===c[++n]&&c[++r]===c[++n]&&c[++r]===c[++n]&&c[++r]===c[++n]&&c[++r]===c[++n]&&r<d);if(i=M-(d-r),r=d-M,a<i){if(e.match_start=t,o<=(a=i))break;p=c[r+a-1],f=c[r+a]}}}while((t=u[t&h])>l&&0!=--s);return a<=e.lookahead?a:e.lookahead}function z(e){var t,n,i,r,l,c,h,u,d,p,f=e.w_size;do{if(r=e.window_size-e.lookahead-e.strstart,e.strstart>=f+(f-w)){for(s.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;);r+=f}if(0===e.strm.avail_in)break;if(c=e.strm,h=e.window,u=e.strstart+e.lookahead,p=void 0,(d=r)<(p=c.avail_in)&&(p=d),n=0===p?0:(c.avail_in-=p,s.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=r._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=r._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(i&&(F(e,!1),0===e.strm.avail_out))return C}return e.insert=e.strstart<b-1?e.strstart:b-1,t===h?(F(e,!0),0===e.strm.avail_out?I:D):e.last_lit&&(F(e,!1),0===e.strm.avail_out)?C:R}function V(e,t){for(var n,i,s;;){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(s=e.strstart+e.lookahead-b,i=r._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<=s&&(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&&(F(e,!1),0===e.strm.avail_out))return C}else if(e.match_available){if((i=r._tr_tally(e,0,e.window[e.strstart-1]))&&F(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=r._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?(F(e,!0),0===e.strm.avail_out?I:D):e.last_lit&&(F(e,!1),0===e.strm.avail_out)?C:R}function G(e,t,n,i,s){this.good_length=e,this.max_lazy=t,this.nice_length=n,this.max_chain=i,this.func=s}function W(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=g,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new s.Buf16(2*A),this.dyn_dtree=new s.Buf16(2*(2*x+1)),this.bl_tree=new s.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 s.Buf16(S+1),this.heap=new s.Buf16(2*_+1),L(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new s.Buf16(2*_+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,r._tr_init(t),u):P(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,r,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),r<1||v<r||n!==g||i<8||15<i||t<0||9<t||a<0||f<a)return P(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=r+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 s.Buf8(2*l.w_size),l.head=new s.Buf16(l.hash_size),l.prev=new s.Buf16(l.w_size),l.lit_bufsize=1<<r+6,l.pending_buf_size=4*l.lit_bufsize,l.pending_buf=new s.Buf8(l.pending_buf_size),l.d_buf=1*l.lit_bufsize,l.l_buf=3*l.lit_bufsize,l.level=t,l.strategy=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,F(e,!1),0===e.strm.avail_out))return C;if(e.strstart-e.block_start>=e.w_size-w&&(F(e,!1),0===e.strm.avail_out))return C}return e.insert=0,t===h?(F(e,!0),0===e.strm.avail_out?I:D):(e.strstart>e.block_start&&(F(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,s,a,l;if(!e||!e.state||5<t||t<0)return e?P(e,d):d;if(s=e.state,!e.output||!e.input&&0!==e.avail_in||666===s.status&&t!==h)return P(e,0===e.avail_out?-5:d);if(s.strm=e,n=s.last_flush,s.last_flush=t,s.status===T)if(2===s.wrap)e.adler=0,k(s,31),k(s,139),k(s,8),s.gzhead?(k(s,(s.gzhead.text?1:0)+(s.gzhead.hcrc?2:0)+(s.gzhead.extra?4:0)+(s.gzhead.name?8:0)+(s.gzhead.comment?16:0)),k(s,255&s.gzhead.time),k(s,s.gzhead.time>>8&255),k(s,s.gzhead.time>>16&255),k(s,s.gzhead.time>>24&255),k(s,9===s.level?2:2<=s.strategy||s.level<2?4:0),k(s,255&s.gzhead.os),s.gzhead.extra&&s.gzhead.extra.length&&(k(s,255&s.gzhead.extra.length),k(s,s.gzhead.extra.length>>8&255)),s.gzhead.hcrc&&(e.adler=o(e.adler,s.pending_buf,s.pending,0)),s.gzindex=0,s.status=69):(k(s,0),k(s,0),k(s,0),k(s,0),k(s,0),k(s,9===s.level?2:2<=s.strategy||s.level<2?4:0),k(s,3),s.status=E);else{var p=g+(s.w_bits-8<<4)<<8;p|=(2<=s.strategy||s.level<2?0:s.level<6?1:6===s.level?2:3)<<6,0!==s.strstart&&(p|=32),p+=31-p%31,s.status=E,N(s,p),0!==s.strstart&&(N(s,e.adler>>>16),N(s,65535&e.adler)),e.adler=1}if(69===s.status)if(s.gzhead.extra){for(a=s.pending;s.gzindex<(65535&s.gzhead.extra.length)&&(s.pending!==s.pending_buf_size||(s.gzhead.hcrc&&s.pending>a&&(e.adler=o(e.adler,s.pending_buf,s.pending-a,a)),U(e),a=s.pending,s.pending!==s.pending_buf_size));)k(s,255&s.gzhead.extra[s.gzindex]),s.gzindex++;s.gzhead.hcrc&&s.pending>a&&(e.adler=o(e.adler,s.pending_buf,s.pending-a,a)),s.gzindex===s.gzhead.extra.length&&(s.gzindex=0,s.status=73)}else s.status=73;if(73===s.status)if(s.gzhead.name){a=s.pending;do{if(s.pending===s.pending_buf_size&&(s.gzhead.hcrc&&s.pending>a&&(e.adler=o(e.adler,s.pending_buf,s.pending-a,a)),U(e),a=s.pending,s.pending===s.pending_buf_size)){l=1;break}l=s.gzindex<s.gzhead.name.length?255&s.gzhead.name.charCodeAt(s.gzindex++):0,k(s,l)}while(0!==l);s.gzhead.hcrc&&s.pending>a&&(e.adler=o(e.adler,s.pending_buf,s.pending-a,a)),0===l&&(s.gzindex=0,s.status=91)}else s.status=91;if(91===s.status)if(s.gzhead.comment){a=s.pending;do{if(s.pending===s.pending_buf_size&&(s.gzhead.hcrc&&s.pending>a&&(e.adler=o(e.adler,s.pending_buf,s.pending-a,a)),U(e),a=s.pending,s.pending===s.pending_buf_size)){l=1;break}l=s.gzindex<s.gzhead.comment.length?255&s.gzhead.comment.charCodeAt(s.gzindex++):0,k(s,l)}while(0!==l);s.gzhead.hcrc&&s.pending>a&&(e.adler=o(e.adler,s.pending_buf,s.pending-a,a)),0===l&&(s.status=103)}else s.status=103;if(103===s.status&&(s.gzhead.hcrc?(s.pending+2>s.pending_buf_size&&U(e),s.pending+2<=s.pending_buf_size&&(k(s,255&e.adler),k(s,e.adler>>8&255),e.adler=0,s.status=E)):s.status=E),0!==s.pending){if(U(e),0===e.avail_out)return s.last_flush=-1,u}else if(0===e.avail_in&&B(t)<=B(n)&&t!==h)return P(e,-5);if(666===s.status&&0!==e.avail_in)return P(e,-5);if(0!==e.avail_in||0!==s.lookahead||t!==c&&666!==s.status){var f=2===s.strategy?function(e,t){for(var n;;){if(0===e.lookahead&&(z(e),0===e.lookahead)){if(t===c)return C;break}if(e.match_length=0,n=r._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,n&&(F(e,!1),0===e.strm.avail_out))return C}return e.insert=0,t===h?(F(e,!0),0===e.strm.avail_out?I:D):e.last_lit&&(F(e,!1),0===e.strm.avail_out)?C:R}(s,t):3===s.strategy?function(e,t){for(var n,i,s,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[s=e.strstart-1])===o[++s]&&i===o[++s]&&i===o[++s]){a=e.strstart+M;do{}while(i===o[++s]&&i===o[++s]&&i===o[++s]&&i===o[++s]&&i===o[++s]&&i===o[++s]&&i===o[++s]&&i===o[++s]&&s<a);e.match_length=M-(a-s),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=b?(n=r._tr_tally(e,1,e.match_length-b),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(n=r._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),n&&(F(e,!1),0===e.strm.avail_out))return C}return e.insert=0,t===h?(F(e,!0),0===e.strm.avail_out?I:D):e.last_lit&&(F(e,!1),0===e.strm.avail_out)?C:R}(s,t):i[s.level].func(s,t);if(f!==I&&f!==D||(s.status=666),f===C||f===I)return 0===e.avail_out&&(s.last_flush=-1),u;if(f===R&&(1===t?r._tr_align(s):5!==t&&(r._tr_stored_block(s,0,0,!1),3===t&&(L(s.head),0===s.lookahead&&(s.strstart=0,s.block_start=0,s.insert=0))),U(e),0===e.avail_out))return s.last_flush=-1,u}return t!==h?u:s.wrap<=0?1:(2===s.wrap?(k(s,255&e.adler),k(s,e.adler>>8&255),k(s,e.adler>>16&255),k(s,e.adler>>24&255),k(s,255&e.total_in),k(s,e.total_in>>8&255),k(s,e.total_in>>16&255),k(s,e.total_in>>24&255)):(N(s,e.adler>>>16),N(s,65535&e.adler)),U(e),0<s.wrap&&(s.wrap=-s.wrap),0!==s.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?P(e,d):(e.state=null,t===E?P(e,-3):u):d},n.deflateSetDictionary=function(e,t){var n,i,r,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 s.Buf8(n.w_size),s.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,r=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++,--r;);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,s,r,a,o,l,c,h,u,d,p,f,m,g,v,_,x,y,A,S,b,M,w,T;n=e.state,i=e.next_in,w=e.input,s=i+(e.avail_in-5),r=e.next_out,T=e.output,a=r-(t-e.avail_out),o=r+(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,v=(1<<n.lenbits)-1,_=(1<<n.distbits)-1;e:do{f<15&&(p+=w[i++]<<f,f+=8,p+=w[i++]<<f,f+=8),x=m[p&v];t:for(;;){if(p>>>=y=x>>>24,f-=y,0==(y=x>>>16&255))T[r++]=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}A=65535&x,(y&=15)&&(f<y&&(p+=w[i++]<<f,f+=8),A+=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&_];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(S=65535&x,f<(y&=15)&&(p+=w[i++]<<f,(f+=8)<y&&(p+=w[i++]<<f,f+=8)),l<(S+=p&(1<<y)-1)){e.msg="invalid distance too far back",n.mode=30;break e}if(p>>>=y,f-=y,(y=r-a)<S){if(h<(y=S-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<A){for(A-=y;T[r++]=d[b++],--y;);b=r-S,M=T}}else if(u<y){if(b+=c+u-y,(y-=u)<A){for(A-=y;T[r++]=d[b++],--y;);if(b=0,u<A){for(A-=y=u;T[r++]=d[b++],--y;);b=r-S,M=T}}}else if(b+=u-y,y<A){for(A-=y;T[r++]=d[b++],--y;);b=r-S,M=T}for(;2<A;)T[r++]=M[b++],T[r++]=M[b++],T[r++]=M[b++],A-=3;A&&(T[r++]=M[b++],1<A&&(T[r++]=M[b++]))}else{for(b=r-S;T[r++]=T[b++],T[r++]=T[b++],T[r++]=T[b++],2<(A-=3););A&&(T[r++]=T[b++],1<A&&(T[r++]=T[b++]))}break}}break}}while(i<s&&r<o);i-=A=f>>3,p&=(1<<(f-=A<<3))-1,e.next_in=i,e.next_out=r,e.avail_in=i<s?s-i+5:5-(i-s),e.avail_out=r<o?o-r+257:257-(r-o),n.hold=p,n.bits=f}},{}],49:[function(e,t,n){var i=e("../utils/common"),s=e("./adler32"),r=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 v(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 _(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,v(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,_(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 A,S,b=!0;function M(e){if(b){var t;for(A=new i.Buf32(512),S=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,A,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;o(c,e.lens,0,32,S,0,e.work,{bits:5}),b=!1}e.lencode=A,e.lenbits=9,e.distcode=S,e.distbits=5}function w(e,t,n,s){var r,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)),s>=a.wsize?(i.arraySet(a.window,t,n-a.wsize,a.wsize,0),a.wnext=0,a.whave=a.wsize):(s<(r=a.wsize-a.wnext)&&(r=s),i.arraySet(a.window,t,n-s,r,a.wnext),(s-=r)?(i.arraySet(a.window,t,n-s,s,0),a.wnext=s,a.whave=a.wsize):(a.wnext+=r,a.wnext===a.wsize&&(a.wnext=0),a.whave<a.wsize&&(a.whave+=r))),0}n.inflateReset=_,n.inflateReset2=x,n.inflateResetKeep=v,n.inflateInit=function(e){return y(e,15)},n.inflateInit2=y,n.inflate=function(e,t){var n,p,f,g,v,_,x,y,A,S,b,T,E,C,R,I,D,P,B,L,U,F,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),v=e.next_out,f=e.output,x=e.avail_out,g=e.next_in,p=e.input,_=e.avail_in,y=n.hold,A=n.bits,S=_,b=x,F=h;e:for(;;)switch(n.mode){case d:if(0===n.wrap){n.mode=13;break}for(;A<16;){if(0===_)break e;_--,y+=p[g++]<<A,A+=8}if(2&n.wrap&&35615===y){z[n.check=0]=255&y,z[1]=y>>>8&255,n.check=r(n.check,z,2,0),A=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(A-=4,U=8+(15&(y>>>=4)),0===n.wbits)n.wbits=U;else if(U>n.wbits){e.msg="invalid window size",n.mode=30;break}n.dmax=1<<U,e.adler=n.check=1,n.mode=512&y?10:12,A=y=0;break;case 2:for(;A<16;){if(0===_)break e;_--,y+=p[g++]<<A,A+=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=r(n.check,z,2,0)),A=y=0,n.mode=3;case 3:for(;A<32;){if(0===_)break e;_--,y+=p[g++]<<A,A+=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=r(n.check,z,4,0)),A=y=0,n.mode=4;case 4:for(;A<16;){if(0===_)break e;_--,y+=p[g++]<<A,A+=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=r(n.check,z,2,0)),A=y=0,n.mode=5;case 5:if(1024&n.flags){for(;A<16;){if(0===_)break e;_--,y+=p[g++]<<A,A+=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=r(n.check,z,2,0)),A=y=0}else n.head&&(n.head.extra=null);n.mode=6;case 6:if(1024&n.flags&&(_<(T=n.length)&&(T=_),T&&(n.head&&(U=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,U)),512&n.flags&&(n.check=r(n.check,p,T,g)),_-=T,g+=T,n.length-=T),n.length))break e;n.length=0,n.mode=7;case 7:if(2048&n.flags){if(0===_)break e;for(T=0;U=p[g+T++],n.head&&U&&n.length<65536&&(n.head.name+=String.fromCharCode(U)),U&&T<_;);if(512&n.flags&&(n.check=r(n.check,p,T,g)),_-=T,g+=T,U)break e}else n.head&&(n.head.name=null);n.length=0,n.mode=8;case 8:if(4096&n.flags){if(0===_)break e;for(T=0;U=p[g+T++],n.head&&U&&n.length<65536&&(n.head.comment+=String.fromCharCode(U)),U&&T<_;);if(512&n.flags&&(n.check=r(n.check,p,T,g)),_-=T,g+=T,U)break e}else n.head&&(n.head.comment=null);n.mode=9;case 9:if(512&n.flags){for(;A<16;){if(0===_)break e;_--,y+=p[g++]<<A,A+=8}if(y!==(65535&n.check)){e.msg="header crc mismatch",n.mode=30;break}A=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(;A<32;){if(0===_)break e;_--,y+=p[g++]<<A,A+=8}e.adler=n.check=m(y),A=y=0,n.mode=11;case 11:if(0===n.havedict)return e.next_out=v,e.avail_out=x,e.next_in=g,e.avail_in=_,n.hold=y,n.bits=A,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&A,A-=7&A,n.mode=27;break}for(;A<3;){if(0===_)break e;_--,y+=p[g++]<<A,A+=8}switch(n.last=1&y,A-=1,3&(y>>>=1)){case 0:n.mode=14;break;case 1:if(M(n),n.mode=20,6!==t)break;y>>>=2,A-=2;break e;case 2:n.mode=17;break;case 3:e.msg="invalid block type",n.mode=30}y>>>=2,A-=2;break;case 14:for(y>>>=7&A,A-=7&A;A<32;){if(0===_)break e;_--,y+=p[g++]<<A,A+=8}if((65535&y)!=(y>>>16^65535)){e.msg="invalid stored block lengths",n.mode=30;break}if(n.length=65535&y,A=y=0,n.mode=15,6===t)break e;case 15:n.mode=16;case 16:if(T=n.length){if(_<T&&(T=_),x<T&&(T=x),0===T)break e;i.arraySet(f,p,g,T,v),_-=T,g+=T,x-=T,v+=T,n.length-=T;break}n.mode=12;break;case 17:for(;A<14;){if(0===_)break e;_--,y+=p[g++]<<A,A+=8}if(n.nlen=257+(31&y),y>>>=5,A-=5,n.ndist=1+(31&y),y>>>=5,A-=5,n.ncode=4+(15&y),y>>>=4,A-=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(;A<3;){if(0===_)break e;_--,y+=p[g++]<<A,A+=8}n.lens[H[n.have++]]=7&y,y>>>=3,A-=3}for(;n.have<19;)n.lens[H[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,k={bits:n.lenbits},F=o(0,n.lens,0,19,n.lencode,0,n.work,k),n.lenbits=k.bits,F){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,D=65535&O,!((R=O>>>24)<=A);){if(0===_)break e;_--,y+=p[g++]<<A,A+=8}if(D<16)y>>>=R,A-=R,n.lens[n.have++]=D;else{if(16===D){for(N=R+2;A<N;){if(0===_)break e;_--,y+=p[g++]<<A,A+=8}if(y>>>=R,A-=R,0===n.have){e.msg="invalid bit length repeat",n.mode=30;break}U=n.lens[n.have-1],T=3+(3&y),y>>>=2,A-=2}else if(17===D){for(N=R+3;A<N;){if(0===_)break e;_--,y+=p[g++]<<A,A+=8}A-=R,U=0,T=3+(7&(y>>>=R)),y>>>=3,A-=3}else{for(N=R+7;A<N;){if(0===_)break e;_--,y+=p[g++]<<A,A+=8}A-=R,U=0,T=11+(127&(y>>>=R)),y>>>=7,A-=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++]=U}}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},F=o(l,n.lens,0,n.nlen,n.lencode,0,n.work,k),n.lenbits=k.bits,F){e.msg="invalid literal/lengths set",n.mode=30;break}if(n.distbits=6,n.distcode=n.distdyn,k={bits:n.distbits},F=o(c,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,k),n.distbits=k.bits,F){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<=_&&258<=x){e.next_out=v,e.avail_out=x,e.next_in=g,e.avail_in=_,n.hold=y,n.bits=A,a(e,b),v=e.next_out,f=e.output,x=e.avail_out,g=e.next_in,p=e.input,_=e.avail_in,y=n.hold,A=n.bits,12===n.mode&&(n.back=-1);break}for(n.back=0;I=(O=n.lencode[y&(1<<n.lenbits)-1])>>>16&255,D=65535&O,!((R=O>>>24)<=A);){if(0===_)break e;_--,y+=p[g++]<<A,A+=8}if(I&&!(240&I)){for(P=R,B=I,L=D;I=(O=n.lencode[L+((y&(1<<P+B)-1)>>P)])>>>16&255,D=65535&O,!(P+(R=O>>>24)<=A);){if(0===_)break e;_--,y+=p[g++]<<A,A+=8}y>>>=P,A-=P,n.back+=P}if(y>>>=R,A-=R,n.back+=R,n.length=D,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;A<N;){if(0===_)break e;_--,y+=p[g++]<<A,A+=8}n.length+=y&(1<<n.extra)-1,y>>>=n.extra,A-=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,D=65535&O,!((R=O>>>24)<=A);){if(0===_)break e;_--,y+=p[g++]<<A,A+=8}if(!(240&I)){for(P=R,B=I,L=D;I=(O=n.distcode[L+((y&(1<<P+B)-1)>>P)])>>>16&255,D=65535&O,!(P+(R=O>>>24)<=A);){if(0===_)break e;_--,y+=p[g++]<<A,A+=8}y>>>=P,A-=P,n.back+=P}if(y>>>=R,A-=R,n.back+=R,64&I){e.msg="invalid distance code",n.mode=30;break}n.offset=D,n.extra=15&I,n.mode=24;case 24:if(n.extra){for(N=n.extra;A<N;){if(0===_)break e;_--,y+=p[g++]<<A,A+=8}n.offset+=y&(1<<n.extra)-1,y>>>=n.extra,A-=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=v-n.offset,T=n.length;for(x<T&&(T=x),x-=T,n.length-=T;f[v++]=C[E++],--T;);0===n.length&&(n.mode=21);break;case 26:if(0===x)break e;f[v++]=n.length,x--,n.mode=21;break;case 27:if(n.wrap){for(;A<32;){if(0===_)break e;_--,y|=p[g++]<<A,A+=8}if(b-=x,e.total_out+=b,n.total+=b,b&&(e.adler=n.check=n.flags?r(n.check,f,b,v-b):s(n.check,f,b,v-b)),b=x,(n.flags?y:m(y))!==n.check){e.msg="incorrect data check",n.mode=30;break}A=y=0}n.mode=28;case 28:if(n.wrap&&n.flags){for(;A<32;){if(0===_)break e;_--,y+=p[g++]<<A,A+=8}if(y!==(4294967295&n.total)){e.msg="incorrect length check",n.mode=30;break}A=y=0}n.mode=29;case 29:F=1;break e;case 30:F=-3;break e;case 31:return-4;default:return u}return e.next_out=v,e.avail_out=x,e.next_in=g,e.avail_in=_,n.hold=y,n.bits=A,(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):(S-=e.avail_in,b-=e.avail_out,e.total_in+=S,e.total_out+=b,n.total+=b,n.wrap&&b&&(e.adler=n.check=n.flags?r(n.check,f,b,e.next_out-b):s(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==S&&0===b||4===t)&&F===h&&(F=-5),F)},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&&s(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"),s=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],r=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],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,A,S=d.bits,b=0,M=0,w=0,T=0,E=0,C=0,R=0,I=0,D=0,P=0,B=null,L=0,U=new i.Buf16(16),F=new i.Buf16(16),k=null,N=0;for(b=0;b<=15;b++)U[b]=0;for(M=0;M<l;M++)U[t[n+M]]++;for(E=S,T=15;1<=T&&0===U[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===U[w];w++);for(E<w&&(E=w),b=I=1;b<=15;b++)if(I<<=1,(I-=U[b])<0)return-1;if(0<I&&(0===e||1!==T))return-1;for(F[1]=0,b=1;b<15;b++)F[b+1]=F[b]+U[b];for(M=0;M<l;M++)0!==t[n+M]&&(u[F[t[n+M]]++]=M);if(_=0===e?(B=k=u,19):1===e?(B=s,L-=257,k=r,N-=257,256):(B=a,k=o,-1),b=w,v=h,R=M=P=0,m=-1,g=(D=1<<(C=E))-1,1===e&&852<D||2===e&&592<D)return 1;for(;;){for(x=b-R,A=u[M]<_?(y=0,u[M]):u[M]>_?(y=k[N+u[M]],B[L+u[M]]):(y=96,0),p=1<<b-R,w=f=1<<C;c[v+(P>>R)+(f-=p)]=x<<24|y<<16|A,0!==f;);for(p=1<<b-1;P&p;)p>>=1;if(0!==p?(P&=p-1,P+=p):P=0,M++,0==--U[b]){if(b===T)break;b=t[n+u[M]]}if(E<b&&(P&g)!==m){for(0===R&&(R=E),v+=w,I=1<<(C=b-R);C+R<T&&!((I-=U[C+R])<=0);)C++,I<<=1;if(D+=1<<C,1===e&&852<D||2===e&&592<D)return 1;c[m=P&g]=E<<24|C<<16|v-h}}return 0!==P&&(c[v+P]=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"),s=0,r=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,v=256,_=16,x=17,y=18,A=[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],S=[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,D,P,B=new Array(u);function L(e,t,n,i,s){this.static_tree=e,this.extra_bits=t,this.extra_base=n,this.elems=i,this.max_length=s,this.has_stree=e&&e.length}function U(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function F(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,s,r=new Array(f+1),a=0;for(i=1;i<=f;i++)r[i]=a=a+n[i-1]<<1;for(s=0;s<=t;s++){var o=e[2*s+1];0!==o&&(e[2*s]=z(r[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*v]=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 s=2*t,r=2*n;return e[s]<e[r]||e[s]===e[r]&&i[t]<=i[n]}function j(e,t,n){for(var i=e.heap[n],s=n<<1;s<=e.heap_len&&(s<e.heap_len&&W(t,e.heap[s+1],e.heap[s],e.depth)&&s++,!W(t,i,e.heap[s],e.depth));)e.heap[n]=e.heap[s],n=s,s<<=1;e.heap[n]=i}function X(e,t,n){var i,s,r,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],s=e.pending_buf[e.l_buf+o],o++,0===i?O(e,s,t):(O(e,(r=C[s])+c+1,t),0!==(a=A[r])&&N(e,s-=R[r],a),O(e,r=F(--i),n),0!==(a=S[r])&&N(e,i-=B[r],a)),o<e.last_lit;);O(e,v,t)}function q(e,t){var n,i,s,r=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!==r[2*n]?(e.heap[++e.heap_len]=c=n,e.depth[n]=0):r[2*n+1]=0;for(;e.heap_len<2;)r[2*(s=e.heap[++e.heap_len]=c<2?++c:0)]=1,e.depth[s]=0,e.opt_len--,o&&(e.static_len-=a[2*s+1]);for(t.max_code=c,n=e.heap_len>>1;1<=n;n--)j(e,r,n);for(s=l;n=e.heap[1],e.heap[1]=e.heap[e.heap_len--],j(e,r,1),i=e.heap[1],e.heap[--e.heap_max]=n,e.heap[--e.heap_max]=i,r[2*s]=r[2*n]+r[2*i],e.depth[s]=(e.depth[n]>=e.depth[i]?e.depth[n]:e.depth[i])+1,r[2*n+1]=r[2*i+1]=s,e.heap[1]=s++,j(e,r,1),2<=e.heap_len;);e.heap[--e.heap_max]=e.heap[1],function(e,t){var n,i,s,r,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,v=0;for(r=0;r<=f;r++)e.bl_count[r]=0;for(l[2*e.heap[e.heap_max]+1]=0,n=e.heap_max+1;n<p;n++)g<(r=l[2*l[2*(i=e.heap[n])+1]+1]+1)&&(r=g,v++),l[2*i+1]=r,c<i||(e.bl_count[r]++,a=0,m<=i&&(a=d[i-m]),o=l[2*i],e.opt_len+=o*(r+a),u&&(e.static_len+=o*(h[2*i+1]+a)));if(0!==v){do{for(r=g-1;0===e.bl_count[r];)r--;e.bl_count[r]--,e.bl_count[r+1]+=2,e.bl_count[g]--,v-=2}while(0<v);for(r=g;0!==r;r--)for(i=e.bl_count[r];0!==i;)c<(s=e.heap[--n])||(l[2*s+1]!==r&&(e.opt_len+=(r-l[2*s+1])*l[2*s],l[2*s+1]=r),i--)}}(e,t),H(r,c,e.bl_count)}function Q(e,t,n){var i,s,r=-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++)s=a,a=t[2*(i+1)+1],++o<l&&s===a||(o<c?e.bl_tree[2*s]+=o:0!==s?(s!==r&&e.bl_tree[2*s]++,e.bl_tree[2*_]++):o<=10?e.bl_tree[2*x]++:e.bl_tree[2*y]++,r=s,c=(o=0)===a?(l=138,3):s===a?(l=6,3):(l=7,4))}function K(e,t,n){var i,s,r=-1,a=t[1],o=0,l=7,c=4;for(0===a&&(l=138,c=3),i=0;i<=n;i++)if(s=a,a=t[2*(i+1)+1],!(++o<l&&s===a)){if(o<c)for(;O(e,s,e.bl_tree),0!=--o;);else 0!==s?(s!==r&&(O(e,s,e.bl_tree),o--),O(e,_,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));r=s,c=(o=0)===a?(l=138,3):s===a?(l=6,3):(l=7,4)}}a(B);var Y=!1;function Z(e,t,n,s){var r,a,l;N(e,(o<<1)+(s?1:0),3),a=t,l=n,G(r=e),k(r,l),k(r,~l),i.arraySet(r.pending_buf,r.window,a,l,r.pending),r.pending+=l}n._tr_init=function(e){Y||(function(){var e,t,n,i,s,r=new Array(f+1);for(i=n=0;i<l-1;i++)for(R[i]=n,e=0;e<1<<A[i];e++)C[n++]=i;for(C[n-1]=i,i=s=0;i<16;i++)for(B[i]=s,e=0;e<1<<S[i];e++)E[s++]=i;for(s>>=7;i<u;i++)for(B[i]=s<<7,e=0;e<1<<S[i]-7;e++)E[256+s++]=i;for(t=0;t<=f;t++)r[t]=0;for(e=0;e<=143;)w[2*e+1]=8,e++,r[8]++;for(;e<=255;)w[2*e+1]=9,e++,r[9]++;for(;e<=279;)w[2*e+1]=7,e++,r[7]++;for(;e<=287;)w[2*e+1]=8,e++,r[8]++;for(H(w,h+1,r),e=0;e<u;e++)T[2*e+1]=5,T[2*e]=z(e,5);I=new L(w,A,c+1,h,f),D=new L(T,S,0,u,f),P=new L(new Array(0),b,0,d,g)}(),Y=!0),e.l_desc=new U(e.dyn_ltree,I),e.d_desc=new U(e.dyn_dtree,D),e.bl_desc=new U(e.bl_tree,P),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 s;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return r;for(t=32;t<c;t++)if(0!==e.dyn_ltree[2*t])return r;return s}(e)),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 s;for(N(e,t-257,5),N(e,n-1,5),N(e,i-4,4),s=0;s<i;s++)N(e,e.bl_tree[2*M[s]+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*F(t)]++),e.last_lit===e.lit_bufsize-1},n._tr_align=function(e){var t;N(e,2,3),O(e,v,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,s,r,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}}()?(r="setImmediate$"+Math.random()+"$",e.addEventListener?e.addEventListener("message",p,!1):e.attachEvent("onmessage",p),function(t){e.postMessage(r+t,"*")}):e.MessageChannel?((s=new MessageChannel).port1.onmessage=function(e){d(e.data)},function(e){s.port2.postMessage(e)}):c&&"onreadystatechange"in c.createElement("script")?(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 s={callback:e,args:t};return o[a]=s,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(r)&&d(+t.data.slice(r.length))}}("undefined"==typeof self?void 0===e?this:e:self)}).call(this,void 0!==Ru?Ru:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}]},{},[10])(10);const Bu=Iu(Pu.exports),Lu={type:"change"},Uu={type:"start"},Fu={type:"end"},ku=new Ni,Nu=new la,Ou=Math.cos(70*Un.DEG2RAD),zu=new ci,Hu=2*Math.PI,Vu=-1,Gu=0,Wu=1,ju=2,Xu=3,qu=4,Qu=5,Ku=6,Yu=1e-6;class Zu extends Xo{constructor(e,t=null){super(e,t),this.state=Vu,this.enabled=!0,this.target=new ci,this.cursor=new ci,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:se,RIGHT:re},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 ci,this._lastQuaternion=new li,this._lastTargetPosition=new ci,this._quat=(new li).setFromUnitVectors(e.up,new ci(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new jo,this._sphericalDelta=new jo,this._scale=1,this._panOffset=new ci,this._rotateStart=new Fn,this._rotateEnd=new Fn,this._rotateDelta=new Fn,this._panStart=new Fn,this._panEnd=new Fn,this._panDelta=new Fn,this._dollyStart=new Fn,this._dollyEnd=new Fn,this._dollyDelta=new Fn,this._dollyDirection=new ci,this._mouse=new Fn,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=$u.bind(this),this._onPointerDown=Ju.bind(this),this._onPointerUp=ed.bind(this),this._onContextMenu=od.bind(this),this._onMouseWheel=id.bind(this),this._onKeyDown=sd.bind(this),this._onTouchStart=rd.bind(this),this._onTouchMove=ad.bind(this),this._onMouseDown=td.bind(this),this._onMouseMove=nd.bind(this),this._interceptControlDown=ld.bind(this),this._interceptControlUp=cd.bind(this),null!==this.domElement&&this.connect(),this.update()}connect(){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.removeEventListener("pointermove",this._onPointerMove),this.domElement.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(Lu),this.update(),this.state=Vu}update(e=null){const t=this.object.position;zu.copy(t).sub(this.target),zu.applyQuaternion(this._quat),this._spherical.setFromVector3(zu),this.autoRotate&&this.state===Vu&&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+=Hu:n>Math.PI&&(n-=Hu),i<-Math.PI?i+=Hu:i>Math.PI&&(i-=Hu),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 s=!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),s=e!=this._spherical.radius}if(zu.setFromSpherical(this._spherical),zu.applyQuaternion(this._quatInverse),t.copy(this.target).add(zu),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=zu.length();e=this._clampDistance(t*this._scale);const n=t-e;this.object.position.addScaledVector(this._dollyDirection,n),this.object.updateMatrixWorld(),s=!!n}else if(this.object.isOrthographicCamera){const t=new ci(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(),s=n!==this.object.zoom;const i=new ci(this._mouse.x,this._mouse.y,0);i.unproject(this.object),this.object.position.sub(i).add(t),this.object.updateMatrixWorld(),e=zu.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):(ku.origin.copy(this.object.position),ku.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(ku.direction))<Ou?this.object.lookAt(this.target):(Nu.setFromNormalAndCoplanarPoint(this.object.up,this.target),ku.intersectPlane(Nu,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(),s=!0)}return this._scale=1,this._performCursorZoom=!1,!!(s||this._lastPosition.distanceToSquared(this.object.position)>Yu||8*(1-this._lastQuaternion.dot(this.object.quaternion))>Yu||this._lastTargetPosition.distanceToSquared(this.target)>Yu)&&(this.dispatchEvent(Lu),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0)}_getAutoRotationAngle(e){return null!==e?Hu/60*this.autoRotateSpeed*e:Hu/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){zu.setFromMatrixColumn(t,0),zu.multiplyScalar(-e),this._panOffset.add(zu)}_panUp(e,t){!0===this.screenSpacePanning?zu.setFromMatrixColumn(t,1):(zu.setFromMatrixColumn(t,0),zu.crossVectors(this.object.up,zu)),zu.multiplyScalar(e),this._panOffset.add(zu)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const i=this.object.position;zu.copy(i).sub(this.target);let s=zu.length();s*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*s/n.clientHeight,this.object.matrix),this._panUp(2*t*s/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,s=t-n.top,r=n.width,a=n.height;this._mouse.x=i/r*2-1,this._mouse.y=-s/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(Hu*this._rotateDelta.x/t.clientHeight),this._rotateUp(Hu*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(Hu*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(-Hu*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(Hu*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(-Hu*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,s=Math.sqrt(n*n+i*i);this._dollyStart.set(0,s)}_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(Hu*this._rotateDelta.x/t.clientHeight),this._rotateUp(Hu*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,s=Math.sqrt(n*n+i*i);this._dollyEnd.set(0,s),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 r=.5*(e.pageX+t.x),a=.5*(e.pageY+t.y);this._updateZoomParameters(r,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 Fn,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 Ju(e){!1!==this.enabled&&(0===this._pointers.length&&(this.domElement.setPointerCapture(e.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerup",this._onPointerUp)),this._isTrackingPointer(e)||(this._addPointer(e),"touch"===e.pointerType?this._onTouchStart(e):this._onMouseDown(e)))}function $u(e){!1!==this.enabled&&("touch"===e.pointerType?this._onTouchMove(e):this._onMouseMove(e))}function ed(e){switch(this._removePointer(e),this._pointers.length){case 0:this.domElement.releasePointerCapture(e.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(Fu),this.state=Vu;break;case 1:const t=this._pointers[0],n=this._pointerPositions[t];this._onTouchStart({pointerId:t,pageX:n.x,pageY:n.y})}}function td(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 se:if(!1===this.enableZoom)return;this._handleMouseDownDolly(e),this.state=Wu;break;case ie:if(e.ctrlKey||e.metaKey||e.shiftKey){if(!1===this.enablePan)return;this._handleMouseDownPan(e),this.state=ju}else{if(!1===this.enableRotate)return;this._handleMouseDownRotate(e),this.state=Gu}break;case re:if(e.ctrlKey||e.metaKey||e.shiftKey){if(!1===this.enableRotate)return;this._handleMouseDownRotate(e),this.state=Gu}else{if(!1===this.enablePan)return;this._handleMouseDownPan(e),this.state=ju}break;default:this.state=Vu}this.state!==Vu&&this.dispatchEvent(Uu)}function nd(e){switch(this.state){case Gu:if(!1===this.enableRotate)return;this._handleMouseMoveRotate(e);break;case Wu:if(!1===this.enableZoom)return;this._handleMouseMoveDolly(e);break;case ju:if(!1===this.enablePan)return;this._handleMouseMovePan(e)}}function id(e){!1!==this.enabled&&!1!==this.enableZoom&&this.state===Vu&&(e.preventDefault(),this.dispatchEvent(Uu),this._handleMouseWheel(this._customWheelEvent(e)),this.dispatchEvent(Fu))}function sd(e){!1!==this.enabled&&this._handleKeyDown(e)}function rd(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=Xu;break;case oe:if(!1===this.enablePan)return;this._handleTouchStartPan(e),this.state=qu;break;default:this.state=Vu}break;case 2:switch(this.touches.TWO){case le:if(!1===this.enableZoom&&!1===this.enablePan)return;this._handleTouchStartDollyPan(e),this.state=Qu;break;case ce:if(!1===this.enableZoom&&!1===this.enableRotate)return;this._handleTouchStartDollyRotate(e),this.state=Ku;break;default:this.state=Vu}break;default:this.state=Vu}this.state!==Vu&&this.dispatchEvent(Uu)}function ad(e){switch(this._trackPointer(e),this.state){case Xu:if(!1===this.enableRotate)return;this._handleTouchMoveRotate(e),this.update();break;case qu:if(!1===this.enablePan)return;this._handleTouchMovePan(e),this.update();break;case Qu:if(!1===this.enableZoom&&!1===this.enablePan)return;this._handleTouchMoveDollyPan(e),this.update();break;case Ku:if(!1===this.enableZoom&&!1===this.enableRotate)return;this._handleTouchMoveDollyRotate(e),this.update();break;default:this.state=Vu}}function od(e){!1!==this.enabled&&e.preventDefault()}function ld(e){if("Control"===e.key){this._controlActive=!0;this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}}function cd(e){if("Control"===e.key){this._controlActive=!1;this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}}const hd=0,ud=3,dd=0,pd=2,fd=0,md=e=>e.endsWith(".ply")?fd:null,gd=0,vd=2,_d=0,xd=1;let yd=(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 Ad=yd.SphericalHarmonics8BitCompressionRange,Sd=0,bd=1,Md=2,wd=0,Td=1,Ed=2;class Cd extends Error{constructor(e){super(e),this.name="AbortedPromiseError"}}const Rd=function(e,t,n){return Math.max(Math.min(e,n),t)},Id=function(){return performance.now()/1e3},Dd=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)Dd(t)},Pd=(e,t)=>new Promise(n=>{window.setTimeout(()=>{n(e())},t?1:50)}),Bd=(e=0)=>{switch(e){case 1:return 9;case 2:return 24}return 0},Ld=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 Ud{constructor(e,t,n){this.major=e,this.minor=t,this.patch=n}toString(){return`${this.major}_${this.minor}_${this.patch}`}}function Fd(){const e=navigator.userAgent;return e.indexOf("iPhone")>0||e.indexOf("iPad")>0}function kd(){if(Fd()){const e=navigator.userAgent.match(/OS (\d+)_(\d+)_?(\d+)?/);return new Ud(parseInt(e[1]||0,10),parseInt(e[2]||0,10),parseInt(e[3]||0,10))}return null}const Nd=Ns.toHalfFloat.bind(Ns),Od=Ns.fromHalfFloat.bind(Ns),zd=Ad/2,Hd=(e,t,n)=>{e=Rd(e,t,n);const i=n-t;return Rd(Math.floor((e-t)/i*255),0,255)},Vd=(e,t,n)=>e/255*(n-t)+t,Gd=(e,t,n)=>Hd(Od(e),t,n),Wd=(e,t,n)=>Nd(Vd(e,t,n)),jd=function(){const e=e=>e;return function(t,n,i,s=!1){if(n===i)return t;let r=e;return 2===n&&s?1===i?r=Wd:0===i&&(r=Vd):2===n||1===n?0===i?r=Od:2===i&&(r=s?Gd:e):0===n&&(1===i?r=Nd:2===i&&(r=s?Hd:Nd)),r(t)}}();!function(){const e=new Float32Array(1),t=new Int32Array(e.buffer)}();const Xd=function(){const e=new Float32Array(1),t=new Int32Array(e.buffer);return function(n){return e[0]=n,t[0]}}(),qd=function(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24)},Qd="Idle",Kd="Listening",Yd="Responding",Zd="Thinking";class Jd{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 $d extends Jd{constructor(e,t){super(e,t)}update(e){if(this.actions&&0!==this.actions.length&&(void 0===rp.CurPlaying&&e===Qd&&!1===this.isPlaying&&(this.stage=0,this.actions[this.stage].time=0,rp.SetWeight(this.actions[this.stage],1),this.actions[this.stage].loop=Yt,this.actions[this.stage].clampWhenFinished=!1,this.actions[this.stage].paused=!1,this.actions[this.stage].play(),void 0!==rp.LastAction&&rp.PrepareCrossFade(rp.LastAction,this.actions[this.stage],this.blendingTime),this.isPlaying=!0),rp.CurPlaying===Qd&&e===Qd&&!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,rp.SetWeight(this.actions[e],1),this.actions[e].loop=Yt,this.actions[e].play(),rp.PrepareCrossFade(this.actions[this.stage],this.actions[e],this.blendingTime),this.stage=e}}}class ep extends Jd{constructor(e,t){super(e,t)}update(e){this.actions&&0!==this.actions.length&&(void 0===rp.CurPlaying&&e===Qd&&!1===this.isPlaying&&(this.stage=0,this.actions[this.stage].time=0,rp.SetWeight(this.actions[this.stage],1),this.actions[this.stage].loop=Yt,this.actions[this.stage].clampWhenFinished=!1,this.actions[this.stage].paused=!1,this.actions[this.stage].play(),void 0!==rp.LastAction&&rp.PrepareCrossFade(rp.LastAction,this.actions[this.stage],this.blendingTime),this.isPlaying=!0),rp.CurPlaying===Qd&&e!==Qd&&!0===this.isPlaying&&0===this.stage&&(this.actions[this.stage].loop=Kt,this.actions[this.stage].clampWhenFinished=!0,this.isPlaying=!1,rp.LastAction=this.actions[this.stage]))}}class tp extends Jd{constructor(e,t){super(e,t)}update(e){this.actions&&0!==this.actions.length&&(void 0===rp.CurPlaying&&e===Kd&&!1===this.isPlaying&&(this.stage=0,this.actions[this.stage].time=0,this.actions[this.stage].play(),rp.SetWeight(this.actions[this.stage],1),this.actions[this.stage].loop=this.isGroup?Kt:Yt,this.actions[this.stage].clampWhenFinished=!!this.isGroup,void 0!==rp.LastAction&&rp.PrepareCrossFade(rp.LastAction,this.actions[this.stage],this.blendingTime),this.isPlaying=!0),this.isGroup&&(rp.CurPlaying===Kd&&e===Kd&&!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,rp.SetWeight(this.actions[this.stage+1],1),this.actions[this.stage+1].loop=Yt,this.actions[this.stage+1].play(),rp.PrepareCrossFade(this.actions[this.stage],this.actions[this.stage+1],this.blendingTime),this.stage=1),rp.CurPlaying!==Kd||e===Kd||!0!==this.isPlaying||0!==this.stage&&1!==this.stage||(this.actions[2].time=0,this.actions[2].play(),rp.SetWeight(this.actions[2],1),this.actions[2].loop=Kt,rp.PrepareCrossFade(this.actions[this.stage],this.actions[2],this.blendingTime),this.stage=2)),rp.CurPlaying===Kd&&e!==Kd&&!0===this.isPlaying&&this.stage===(this.isGroup?this.actions.length-1:0)&&(this.actions[this.stage].loop=Kt,this.actions[this.stage].clampWhenFinished=!0,this.isPlaying=!1,rp.LastAction=this.actions[this.stage]))}}class np extends Jd{constructor(e,t){super(e,t)}update(e){this.actions&&0!==this.actions.length&&(void 0===rp.CurPlaying&&e===Zd&&!1===this.isPlaying&&(this.stage=0,this.actions[this.stage].time=0,this.actions[this.stage].play(),rp.SetWeight(this.actions[this.stage],1),this.actions[this.stage].loop=Kt,void 0!==rp.LastAction&&rp.PrepareCrossFade(rp.LastAction,this.actions[this.stage],this.blendingTime),this.isPlaying=!0),this.isGroup&&(rp.CurPlaying===Zd&&e===Zd&&!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,rp.SetWeight(this.actions[this.stage+1],1),this.actions[this.stage+1].loop=Yt,this.actions[this.stage+1].play(),rp.PrepareCrossFade(this.actions[this.stage],this.actions[this.stage+1],this.blendingTime),this.stage=1),rp.CurPlaying!==Zd||e===Zd||!0!==this.isPlaying||0!==this.stage&&1!==this.stage||(this.actions[2].time=0,this.actions[2].play(),rp.SetWeight(this.actions[2],1),this.actions[2].loop=Kt,rp.PrepareCrossFade(this.actions[this.stage],this.actions[2],this.blendingTime),this.stage=2)),rp.CurPlaying===Zd&&e!==Zd&&!0===this.isPlaying&&this.stage===(this.isGroup?this.actions.length-1:0)&&(this.actions[this.stage].loop=Kt,this.actions[this.stage].clampWhenFinished=!0,this.isPlaying=!1,rp.LastAction=this.actions[this.stage]))}}class ip extends Jd{constructor(e,t){super(e,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===rp.CurPlaying&&e===Yd&&!1===this.isPlaying&&(this.stage=Math.ceil(this.getRandomNumber(0,this.actions.length-1)),this.stage,this.actions.length,this.actions[this.stage].time=0,this.actions[this.stage].play(),rp.SetWeight(this.actions[this.stage],1),this.actions[this.stage].loop=Kt,this.actions[this.stage].clampWhenFinished=!0,void 0!==rp.LastAction&&rp.PrepareCrossFade(rp.LastAction,this.actions[this.stage],this.blendingTime),this.isPlaying=!0),rp.CurPlaying===Yd&&e===Yd&&!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,this.stage,this.actions[this.stage].time=0,this.actions[this.stage].play(),rp.SetWeight(this.actions[this.stage],1),this.actions[this.stage].loop=Kt,this.actions[this.stage].clampWhenFinished=!0,rp.PrepareCrossFade(e,this.actions[this.stage],this.blendingTime)}rp.CurPlaying===Yd&&e!==Yd&&!0===this.isPlaying&&(this.actions[this.stage].loop=Kt,this.actions[this.stage].clampWhenFinished=!0,this.isPlaying=!1,rp.LastAction=this.actions[this.stage])}else this._warnedNoActions||(console.warn("[SPEAK] No actions available!"),this._warnedNoActions=!0)}}const sp=class e{static SetWeight(e,t){e.enabled=!0,e.setEffectiveTimeScale(1),e.setEffectiveWeight(t)}static PrepareCrossFade(t,n,i){const s=i;e.UnPauseAllActions(),e.ExecuteCrossFade(t,n,s),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 s=[],r=[],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?s.push(m):f<h?(r.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 $d(s,i?.hello?.isGroup||!1),this.idle=new ep(r,i?.idle?.isGroup||!1),this.listen=new tp(a,i?.listen?.isGroup||!1),this.think=new np(l,i?.think?.isGroup||!1),this.speak=new ip(o,i?.speak?.isGroup||!1)}curPlaying(){return this.hello.isPlaying||this.idle.isPlaying?Qd:this.listen.isPlaying?Kd:this.think.isPlaying?Zd:this.speak.isPlaying?Yd: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 Qd:e.LastAction=this.hello.actions[this.hello.stage];break;case Kd:e.LastAction=this.listen.actions[this.listen.stage];break;case Zd:e.LastAction=this.think.actions[this.think.stage];break;case Yd:e.LastAction=this.speak.actions[this.speak.stage];break;default:e.LastAction=void 0}e.LastAction&&(e.LastAction.loop=Kt,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 Qd:this.idle.update(t);break;case Kd:this.listen.update(t);break;case Zd:this.think.update(t);break;case Yd:this.speak.update(t);break;default:this.idle.update(t)}else switch(e.CurPlaying){case Qd:this.idle.update(t);break;case Kd:this.listen.update(t);break;case Zd:this.think.update(t);break;case Yd:this.speak.update(t);break;default:this.idle.update(t)}}};i(sp,"IsBlending",!1),i(sp,"actions",[]),i(sp,"NeedReset",!1),i(sp,"NeedFullReset",!1),i(sp,"LastAction"),i(sp,"CurPlaying");let rp=sp;class ap extends ds{constructor(e,t=new ci,n=new li,i=new ci(1,1,1),s=1,r=1,a=!0){super(),this.splatBuffer=e,this.position.copy(t),this.quaternion.copy(n),this.scale.copy(i),this.transform=new Oi,this.minimumAlpha=s,this.opacity=r,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 op{static build(e){const t=new $s;t.setIndex([0,1,2,0,2,3]);const n=new Float32Array(12),i=new Vs(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 s=(new Ro).copy(t),r=new Uint32Array(e),a=new Yr(r,1,!1);return a.setUsage(yn),s.setAttribute("splatIndex",a),s.instanceCount=0,s}}class lp{constructor(){this.rootNode=null,this.splatMesh=null}static convertWorkerSubTree(e,t){const n=new lp;return n.rootNode=e.rootNode,n.splatMesh=t,n}}class cp{constructor(e,t){i(this,"processSplatMesh",(e,t=()=>!0,n,i)=>{this.splatTreeWorker||(this.splatTreeWorker=null),this.splatMesh=e,this.subTrees=[];const s=new ci,r=(n,i)=>{const r=new Float32Array(4*i);let a=0;for(let o=0;o<i;o++){const i=o+n;if(t(i)){e.getSplatCenter(i,s);const t=4*a;r[t]=s.x,r[t+1]=s.y,r[t+2]=s.z,r[t+3]=i,a++}}return r};return new Promise(t=>{const s=()=>!!this.disposed&&(this.diposeSplatTreeWorker(),t(),!0);n&&n(!1),Pd(()=>{if(s())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(),s=r(t,i);a.push(s),t+=i}}else{const t=r(0,e.getSplatCount());a.push(t)}this.splatTreeWorker.onmessage=n=>{s()||n.data.subTrees&&(i&&i(!1),Pd(()=>{if(!s()){for(let t of n.data.subTrees){const n=lp.convertWorkerSubTree(t,e);this.subTrees.push(n)}this.diposeSplatTreeWorker(),i&&i(!0),Pd(()=>{t()})}}))},Pd(()=>{if(s())return;n&&n(!0);const e=a.map(e=>e.buffer);((e,t,n,i,s)=>{e&&e.postMessage({process:{centers:t,maxDepth:i,maxCentersPerNode:s}},n)})(this.splatTreeWorker,a,e,this.maxDepth,this.maxCentersPerNode)})})})}),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 hp{static buildVertexShaderBase(e=!1,t=!1,n=0,i="",s=!0){let r="";return r+=1==s?"#define USE_FLAME":"#define USE_SKINNING",r+="\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 ",t&&(r+=`\n uniform float sceneOpacity[${yd.MaxScenes}];\n uniform int sceneVisibility[${yd.MaxScenes}];\n `),e&&(r+=`\n uniform highp mat4 transforms[${yd.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[${yd.MaxScenes}];\n uniform float sphericalHarmonics8BitCompressionRangeMax[${yd.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,s=!1){const r={sceneCenter:{type:"v3",value:new ci},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 Oi},bindMatrixInverse:{type:"m4",value:new Oi},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 Fn},orthoZoom:{type:"f",value:1},inverseFocalAdjustment:{type:"f",value:1},viewport:{type:"v2",value:new Fn},basisViewport:{type:"v2",value:new Fn},debugColor:{type:"v3",value:new Ds},centersColorsTextureSize:{type:"v2",value:new Fn(1024,1024)},flameModelTextureSize:{type:"v2",value:new Fn(4096,2048)},boneTextureSize:{type:"v2",value:new Fn(4,32)},boneWeightTextureSize:{type:"v2",value:new Fn(512,512)},sphericalHarmonicsDegree:{type:"i",value:n},sphericalHarmonicsTextureSize:{type:"v2",value:new Fn(1024,1024)},sphericalHarmonics8BitMode:{type:"i",value:0},sphericalHarmonicsMultiTextureMode:{type:"i",value:0},splatScale:{type:"f",value:i},pointCloudModeEnabled:{type:"i",value:s?1:0},sceneIndexesTexture:{type:"t",value:null},sceneIndexesTextureSize:{type:"v2",value:new Fn(1024,1024)},sceneCount:{type:"i",value:1},gaussianSplatCount:{type:"i",value:1},bsCount:{type:"i",value:1},headBoneIndex:{type:"f",value:-1}};for(let a=0;a<yd.MaxScenes;a++)r.sphericalHarmonics8BitCompressionRangeMin.value.push(-1.5),r.sphericalHarmonics8BitCompressionRangeMax.value.push(yd.SphericalHarmonics8BitCompressionRange/2);if(t){const e=[];for(let n=0;n<yd.MaxScenes;n++)e.push(1);r.sceneOpacity={type:"f",value:e};const t=[];for(let n=0;n<yd.MaxScenes;n++)t.push(1);r.sceneVisibility={type:"i",value:t}}if(e){const e=[];for(let t=0;t<yd.MaxScenes;t++)e.push(new Oi);r.transforms={type:"mat4",value:e}}return r}}class up{static build(e=!1,t=!1,n=!1,i=2048,s=1,r=!1,a=0,o=.3,l=!0){let c=hp.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 ",l);c+=up.buildVertexShaderProjection(n,t,i,o);const h=up.buildFragmentShader(),u=hp.getUniforms(e,t,a,s,r);u.covariancesTextureSize={type:"v2",value:new Fn(1024,1024)},u.covariancesTexture={type:"t",value:null},u.covariancesTextureHalfFloat={type:"t",value:null},u.covariancesAreHalfFloat={type:"i",value:0};return new _r({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 s="\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 s+=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 `,s+=`\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&&(s+="\n vColor.a *= splatOpacityFromScene;\n "),s+="\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 ",s+=hp.getVertexShaderFadeIn(),s+="}",s}static buildFragmentShader(){let e="\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 vec2 vSplatIndex;\n\n ";return e+="\n void main () {\n // Compute the positional squared distance from the center of the splat to the current fragment.\n float A = dot(vPosition, vPosition);\n // Since the positional data in vPosition has been scaled by sqrt(8), the squared result will be\n // scaled by a factor of 8. If the squared result is larger than 8, it means it is outside the ellipse\n // defined by the rectangle formed by vPosition. It also means it's farther\n // away than sqrt(8) standard deviations from the mean.\n\n // if(vSplatIndex.x > 20000.0) discard;\n // if (A > 8.0) discard;\n vec3 color = vColor.rgb;\n\n // Since the rendered splat is scaled by sqrt(8), the inverse covariance matrix that is part of\n // the gaussian formula becomes the identity matrix. We're then left with (X - mean) * (X - mean),\n // and since 'mean' is zero, we have X * X, which is the same as A:\n float opacity = exp( -0.5*A) * vColor.a;\n if(opacity < 1.0 / 255.0)\n discard;\n\n // uint a = uint(255);\n // vec3 c = vec3(vSplatIndex.x / 256.0 / 256.0, float(uint(vSplatIndex.x / 256.0 )% a) / 256.0, float(uint(vSplatIndex.x)% a) / 256.0);\n // gl_FragColor = vec4(c, 1.0);\n gl_FragColor = vec4(color, opacity);\n\n\n }\n ","\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 vec2 vSplatIndex;\n\n \n void main () {\n // Compute the positional squared distance from the center of the splat to the current fragment.\n float A = dot(vPosition, vPosition);\n // Since the positional data in vPosition has been scaled by sqrt(8), the squared result will be\n // scaled by a factor of 8. If the squared result is larger than 8, it means it is outside the ellipse\n // defined by the rectangle formed by vPosition. It also means it's farther\n // away than sqrt(8) standard deviations from the mean.\n\n // if(vSplatIndex.x > 20000.0) discard;\n // if (A > 8.0) discard;\n vec3 color = vColor.rgb;\n\n // Since the rendered splat is scaled by sqrt(8), the inverse covariance matrix that is part of\n // the gaussian formula becomes the identity matrix. We're then left with (X - mean) * (X - mean),\n // and since 'mean' is zero, we have X * X, which is the same as A:\n float opacity = exp( -0.5*A) * vColor.a;\n if(opacity < 1.0 / 255.0)\n discard;\n\n // uint a = uint(255);\n // vec3 c = vec3(vSplatIndex.x / 256.0 / 256.0, float(uint(vSplatIndex.x / 256.0 )% a) / 256.0, float(uint(vSplatIndex.x)% a) / 256.0);\n // gl_FragColor = vec4(c, 1.0);\n gl_FragColor = vec4(color, opacity);\n\n\n }\n "}}class dp{static build(e=!1,t=!1,n=1,i=!1,s=0){let r=hp.buildVertexShaderBase(e,t,s,"\n uniform vec2 scaleRotationsTextureSize;\n uniform highp sampler2D scaleRotationsTexture;\n varying mat3 vT;\n varying vec2 vQuadCenter;\n varying vec2 vFragCoord;\n ");r+=dp.buildVertexShaderProjection();const a=dp.buildFragmentShader(),o=hp.getUniforms(e,t,s,n,i);o.scaleRotationsTexture={type:"t",value:null},o.scaleRotationsTextureSize={type:"v2",value:new Fn(1024,1024)};return new _r({uniforms:o,vertexShader:r,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+=hp.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 pp=new $s,fp=new Us;function mp(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&&console.warn("THREE.WebGLRenderer: "+e+" extension not supported."),t}}}function gp(e,t,n){let i;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"}const r="undefined"!=typeof WebGL2RenderingContext&&"WebGL2RenderingContext"===e.constructor.name;let a=void 0!==n.precision?n.precision:"highp";const o=s(a);o!==a&&(console.warn("THREE.WebGLRenderer:",a,"not supported, using",o,"instead."),a=o);const l=r||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),v=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),_=u>0,x=r||t.has("OES_texture_float");return{isWebGL2:r,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:s,precision:a,logarithmicDepthBuffer:c,maxTextures:h,maxVertexTextures:u,maxTextureSize:d,maxCubemapSize:p,maxAttributes:f,maxVertexUniforms:m,maxVaryings:g,maxFragmentUniforms:v,vertexTextures:_,floatFragmentTextures:x,floatVertexTextures:_&&x,maxSamples:r?e.getParameter(e.MAX_SAMPLES):0}}function vp(e,t,n){const i=n.isWebGL2;return{convert:function(n,s){let r;if(n===Je)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===st)return e.FLOAT;if(n===rt)return i?e.HALF_FLOAT:(r=t.get("OES_texture_half_float"),null!==r?r.HALF_FLOAT_OES:null);if(1021===n)return e.ALPHA;if(1022===n)return e.RGB;if(n===ht)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===pt)return e.RED;if(n===ft)return e.RED_INTEGER;if(n===mt)return e.RG;if(n===gt)return e.RG_INTEGER;if(1032===n)return e.RGB_INTEGER;if(n===vt)return e.RGBA_INTEGER;if(33776===n||33777===n||33778===n||33779===n){if(r=t.get("WEBGL_compressed_texture_s3tc"),null===r)return null;if(33776===n)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(33777===n)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(33778===n)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(33779===n)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(35840===n||35841===n||35842===n||35843===n){if(r=t.get("WEBGL_compressed_texture_pvrtc"),null===r)return null;if(35840===n)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(35841===n)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(35842===n)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(35843===n)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(36196===n)return r=t.get("WEBGL_compressed_texture_etc1"),null!==r?r.COMPRESSED_RGB_ETC1_WEBGL:null;if(n>=37808&&n<=37814||n>=37840&&n<=37846)return r=t.get("WEBGL_compressed_texture_astc"),null!==r?n:null;if(36492===n||36494===n||36495===n)return r=t.get("EXT_texture_compression_bptc"),null!==r?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 _p=16777216;class xp extends ur{constructor(e=_d,t=!1,n=!1,s=!1,r=1,a=!0,o=!1,l=!1,c=1024,h=hd,u=0,d=1,p=.3){super(pp,fp),i(this,"buildSplatTree",(e=[],t,n)=>new Promise(i=>{this.disposeSplatTree(),this.baseSplatTree=new cp(8,1e3);performance.now();const s=new ii;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(()=>{performance.now();if(this.logLevel,this.disposed)i();else{this.splatTree=this.baseSplatTree,this.baseSplatTree=null;let e=0,t=0,n=0;this.splatTree.visitLeaves(i=>{const s=i.data.indexes.length;s>0&&(t+=s,n++,e++)}),this.logLevel>=ud&&(this.splatTree.countLeaves(),t/=n,this.getSplatCount()),i()}})})),i(this,"updateUniforms",function(){const e=new Fn;return function(t,n,i,s,r,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=s?1:0,this.material.uniforms.orthoZoom.value=r,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]=Rd(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 s=this.renderer.getContext(),r=(e,t,n)=>{const i=e.createShader(t);if(!i)return console.error("Fatal error: gl could not create a shader object."),null;e.shaderSource(i,n),e.compileShader(i);if(!e.getShaderParameter(i,e.COMPILE_STATUS)){let n="unknown";t===e.VERTEX_SHADER?n="vertex shader":t===e.FRAGMENT_SHADER&&(n="fragement shader");const s=e.getShaderInfoLog(i);return console.error("Failed to compile "+n+" with these errors:"+s),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[${yd.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[${yd.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=s.getParameter(s.VERTEX_ARRAY_BINDING),l=s.getParameter(s.CURRENT_PROGRAM),c=!!l&&s.getProgramParameter(l,s.DELETE_STATUS);if(n&&(this.distancesTransformFeedback.vao=s.createVertexArray()),s.bindVertexArray(this.distancesTransformFeedback.vao),n){const e=s.createProgram(),t=r(s,s.VERTEX_SHADER,a),n=r(s,s.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.");s.attachShader(e,t),s.attachShader(e,n),s.transformFeedbackVaryings(e,["distance"],s.SEPARATE_ATTRIBS),s.linkProgram(e);if(!s.getProgramParameter(e,s.LINK_STATUS)){const i=s.getProgramInfoLog(e);throw console.error("Fatal error: Failed to link program: "+i),s.deleteProgram(e),s.deleteShader(n),s.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(s.useProgram(this.distancesTransformFeedback.program),this.distancesTransformFeedback.centersLoc=s.getAttribLocation(this.distancesTransformFeedback.program,"center"),this.dynamicMode){this.distancesTransformFeedback.sceneIndexesLoc=s.getAttribLocation(this.distancesTransformFeedback.program,"sceneIndex");for(let e=0;e<this.scenes.length;e++)this.distancesTransformFeedback.transformsLocs[e]=s.getUniformLocation(this.distancesTransformFeedback.program,`transforms[${e}]`)}else this.distancesTransformFeedback.modelViewProjLoc=s.getUniformLocation(this.distancesTransformFeedback.program,"modelViewProj");(n||i)&&(this.distancesTransformFeedback.centersBuffer=s.createBuffer(),s.bindBuffer(s.ARRAY_BUFFER,this.distancesTransformFeedback.centersBuffer),s.enableVertexAttribArray(this.distancesTransformFeedback.centersLoc),this.integerBasedDistancesComputation?s.vertexAttribIPointer(this.distancesTransformFeedback.centersLoc,4,s.INT,0,0):s.vertexAttribPointer(this.distancesTransformFeedback.centersLoc,4,s.FLOAT,!1,0,0),this.dynamicMode&&(this.distancesTransformFeedback.sceneIndexesBuffer=s.createBuffer(),s.bindBuffer(s.ARRAY_BUFFER,this.distancesTransformFeedback.sceneIndexesBuffer),s.enableVertexAttribArray(this.distancesTransformFeedback.sceneIndexesLoc),s.vertexAttribIPointer(this.distancesTransformFeedback.sceneIndexesLoc,1,s.UNSIGNED_INT,0,0))),(n||i)&&(this.distancesTransformFeedback.outDistancesBuffer=s.createBuffer()),s.bindBuffer(s.ARRAY_BUFFER,this.distancesTransformFeedback.outDistancesBuffer),s.bufferData(s.ARRAY_BUFFER,4*t,s.STATIC_READ),n&&(this.distancesTransformFeedback.id=s.createTransformFeedback()),s.bindTransformFeedback(s.TRANSFORM_FEEDBACK,this.distancesTransformFeedback.id),s.bindBufferBase(s.TRANSFORM_FEEDBACK_BUFFER,0,this.distancesTransformFeedback.outDistancesBuffer),l&&!0!==c&&s.useProgram(l),o&&s.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 Oi;return(t,n)=>{if(!this.renderer)return;const i=this.renderer.getContext(),s=i.getParameter(i.VERTEX_ARRAY_BINDING),r=i.getParameter(i.CURRENT_PROGRAM),a=!!r&&i.getProgramParameter(r,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=xp.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=xp.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 s=0,r=0;switch(i.clientWaitSync(o,r,s)){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 r&&!0!==a&&i.useProgram(r),s&&i.bindVertexArray(s),l}}()),i(this,"morphedMesh"),i(this,"getSplatCenter",function(){const e={};return function(t,n,i,s){this.getLocalSplatParameters(n,e,s),e.splatBuffer.getSplatCenter(t,e.localIndex,i,e.sceneTransform)}}()),i(this,"getSplatScaleAndRotation",function(){const e={},t=new ci;return function(n,i,s,r){this.getLocalSplatParameters(n,e,r),t.x=void 0,t.y=void 0,t.z=void 0,this.splatRenderMode===xd&&(t.z=0),e.splatBuffer.getSplatScaleAndRotation(e.localIndex,i,s,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=s,this.devicePixelRatio=r,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.useFlameModel=!0,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.lastBuildSplatCount=0,this.lastBuildScenes=[],this.lastBuildMaxSplatCount=0,this.lastBuildSceneCount=0,this.firstRenderTime=-1,this.finalBuild=!1,this.webGLUtils=null,this.boundingBox=new di,this.calculatedSceneCenter=new ci,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 s=0;s<t.length;s++){const r=t[s],a=n[s]||{};let o=a.position||[0,0,0],l=a.rotation||[0,0,0,1],c=a.scale||[1,1,1];const h=(new ci).fromArray(o),u=(new li).fromArray(l),d=(new ci).fromArray(c),p=xp.createScene(r,h,u,d,a.splatAlphaRemovalThreshold||1,a.opacity,a.visible);e.add(p),i[s]=p}return i}static createScene(e,t,n,i,s,r=1,a=!0){return new ap(e,t,n,i,s,r,a)}static buildSplatIndexMaps(e){const t=[],n=[];let i=0;for(let s=0;s<e.length;s++){const r=e[s].getMaxSplatCount();for(let e=0;e<r;e++)t[i]=e,n[i]=s,i++}return{localSplatIndexMap:t,sceneIndexMap:n}}build(e,t,n=!0,i=!1,s,r,a=!0){this.sceneOptions=t,this.finalBuild=i;const o=xp.getTotalMaxSplatCountForSplatBuffers(e),l=xp.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 di,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=op.build(o),this.splatRenderMode===_d?this.material=up.build(this.dynamicMode,this.enableOptionalEffects,this.antialiased,this.maxScreenSpaceSplatSize,this.splatScale,this.pointCloudModeEnabled,this.minSphericalHarmonicsDegree,this.kernel2DSize,this.useFlameModel):this.material=dp.build(this.dynamicMode,this.enableOptionalEffects,this.splatScale,this.pointCloudModeEnabled,this.minSphericalHarmonicsDegree);const t=xp.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 di,this.calculatedSceneCenter=new ci,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!==pp&&(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:s}=this.getDataForDistancesComputation(n,t-1);return this.enableDistancesComputationOnGPU&&this.refreshGPUBuffersForDistancesComputation(i,s,e),{from:n,to:t-1,count:t-n,centers:i,sceneIndexes:s}}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 Fn(4096,1024);for(;i.x*i.y*t<e*n;)i.y*=2;return i},i=e=>{const t=(e=>e>=1?6:4)(e);return{elementsPerTexelStored:t,texSize:n(t,6)}};let s=this.getTargetCovarianceCompressionLevel();const r=this.getTargetSphericalHarmonicsCompressionLevel();let a,o,l;if(this.splatRenderMode===_d){const t=i(s);t.texSize.x*t.texSize.y>_p&&0===s&&(s=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===r?u=Uint16Array:2===r&&(u=Uint8Array);const d=Bd(this.minSphericalHarmonicsDegree),p=this.minSphericalHarmonicsDegree?new u(e*d):void 0,f=n(4,4),m=new Uint32Array(f.x*f.y*4);xp.updateCenterColorsPaddedData(0,t-1,c,h,m);const g=new Xr(m,f.x,f.y,vt,it);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===_d){const e=i(s),t=e.elementsPerTexelStored,n=e.texSize;const r=s>=1?8:4,o=new(s>=1?Uint32Array:Float32Array)(n.x*n.y*r);let l;if(0===s?o.set(a):xp.updatePaddedCompressedCovariancesTextureData(a,o,0,0,a.length),s>=1)l=new Xr(o,n.x,n.y,vt,it),l.internalFormat="RGBA32UI",this.material.uniforms.covariancesTextureHalfFloat.value=l;else{l=new Xr(o,n.x,n.y,ht,st),this.material.uniforms.covariancesTexture.value=l;const e=new Xr(new Uint32Array(32),2,2,vt,it);e.internalFormat="RGBA32UI",this.material.uniforms.covariancesTextureHalfFloat.value=e,e.needsUpdate=!0}l.needsUpdate=!0,this.material.uniforms.covariancesAreHalfFloat.value=s>=1?1:0,this.material.uniforms.covariancesTextureSize.value.copy(n),this.splatDataTextures.covariances={data:o,texture:l,size:n,compressionLevel:s,elementsPerTexelStored:t,elementsPerTexelAllocated:r}}else{const e=n(4,6);let i=Float32Array,s=st;const r=new i(e.x*e.y*4);xp.updateScaleRotationsPaddedData(0,t-1,o,l,r);const a=new Xr(r,e.x,e.y,ht,s);a.needsUpdate=!0,this.material.uniforms.scaleRotationsTexture.value=a,this.material.uniforms.scaleRotationsTextureSize.value.copy(e),this.splatDataTextures.scaleRotations={data:r,texture:a,size:e,compressionLevel:0}}if(p){const e=2===r?Je:rt;let i=d;i%2!=0&&i++;const s=2===this.minSphericalHarmonicsDegree?4:2,a=4===s?ht:mt;let o=n(s,i);if(o.x*o.y<=_p){const n=new u(o.x*o.y*s);for(let e=0;e<t;e++){const t=d*e,s=i*e;for(let e=0;e<d;e++)n[s+e]=p[t+e]}const l=new Xr(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:r,elementsPerTexel:s}}else{const l=d/3;i=l,i%2!=0&&i++,o=n(s,i);const c=o.x*o.y*s,h=[this.material.uniforms.sphericalHarmonicsTextureR,this.material.uniforms.sphericalHarmonicsTextureG,this.material.uniforms.sphericalHarmonicsTextureB],f=[],m=[];for(let n=0;n<3;n++){const s=new u(c);f.push(s);for(let e=0;e<t;e++){const t=d*e,r=i*e;if(l>=3){for(let e=0;e<3;e++)s[r+e]=p[t+3*n+e];if(l>=8)for(let e=0;e<5;e++)s[r+3+e]=p[t+9+5*n+e]}}const r=new Xr(s,o.x,o.y,a,e);m.push(r),r.needsUpdate=!0,h[n].value=r}this.material.uniforms.sphericalHarmonicsMultiTextureMode.value=1,this.splatDataTextures.sphericalHarmonics={componentCount:d,componentCountPerChannel:l,paddedComponentCount:i,data:f,textureCount:3,textures:m,size:o,compressionLevel:r,elementsPerTexel:s}}this.material.uniforms.sphericalHarmonicsTextureSize.value.copy(o),this.material.uniforms.sphericalHarmonics8BitMode.value=2===r?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 v=n(1,4),_=new Uint32Array(v.x*v.y*1);for(let y=0;y<t;y++)_[y]=this.globalSplatIndexToSceneIndexMap[y];const x=new Xr(_,v.x,v.y,ft,it);x.internalFormat="R32UI",x.needsUpdate=!0,this.material.uniforms.sceneIndexesTexture.value=x,this.material.uniforms.sceneIndexesTextureSize.value.copy(v),this.material.uniformsNeedUpdate=!0,this.splatDataTextures.sceneIndexes={data:_,texture:x,size:v},this.material.uniforms.sceneCount.value=this.scenes.length,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.useFlameModel&&this.buildBoneWeightTexture(this.flameModel)}buildBoneMatrixTexture(){if(!this.bsWeight)return;const e=new Fn(4,32);let t=new Float32Array(this.bonesMatrix),n=new Uint32Array(e.x*e.y*4);if(this.morphTargetDictionary=this.flameModel.morphTargetDictionary,this.useFlameModel){for(let e=0;e<16*this.bonesNum;e++)n[e]=Xd(t[e]);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 s in this.bsWeight)if(Object.hasOwn(this.bsWeight,s)){const e=this.bsWeight[s];n[this.morphTargetDictionary[s]+16*this.bonesNum]=Xd(e)}const i=new Xr(n,e.x,e.y,vt,it);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(e=!1){if(this.bsWeight&&this.morphTargetDictionary){if(1==e){let e=new Float32Array(this.bonesMatrix);for(let t=0;t<16*this.bonesNum;t++)this.splatDataTextures.baseData.boneMatrix[t]=Xd(e[t])}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]=Xd(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){let t=e.geometry.attributes.position.array.length/3;const n=new Fn(512,512);let i=new Float32Array(n.x*n.y*4),s=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],s[8*a+0]=Xd(this.bonesWeight[a][0]),s[8*a+1]=Xd(this.bonesWeight[a][1]),s[8*a+2]=Xd(this.bonesWeight[a][2]),s[8*a+3]=Xd(this.bonesWeight[a][3]),s[8*a+4]=Xd(this.bonesWeight[a][4]);const r=new Xr(s,n.x,n.y,vt,it);r.internalFormat="RGBA32UI",r.needsUpdate=!0,this.material.uniforms.boneWeightTexture.value=r,this.material.uniforms.boneWeightTextureSize.value.copy(n),this.material.uniformsNeedUpdate=!0,this.splatDataTextures.boneWeight={data:s,texture:r,size:n},this.splatDataTextures.baseData.boneWeight=s}buildModelTexture(e){const t=new Fn(4096,2048);var n=e.geometry.attributes.position.array,i=[];let s=n.length/3,r=e.geometry.morphAttributes.position.length;Object.keys(e.morphTargetDictionary).forEach((t,n)=>{const s=e.morphTargetDictionary[t];var r=e.geometry.morphAttributes.position[s];i=i.concat(Array.from(r.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<s*(r+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]=Xd(a[4*c+0]),o[4*c+1]=Xd(a[4*c+1]),o[4*c+2]=Xd(a[4*c+2]);const l=new Xr(o,t.x,t.y,vt,it);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,n=!0){const i=new Oi;this.getSceneTransform(0,i),this.getScene(0).splatBuffer.fillSplatCenterArray(this.morphedMesh,this.splatDataTextures.baseData.centers,i,e,t,0);const s=this.splatDataTextures.centerColors,r=s.data,a=s.texture;xp.updateCenterColorsPaddedData(e,t,this.splatDataTextures.baseData.centers,this.splatDataTextures.baseData.colors,r);const o=this.renderer?this.renderer.properties.get(a):null;o&&o.__webglTexture?this.updateDataTexture(r,s.texture,s.size,o,4,4,4,e,t):a.needsUpdate=!0,this.updateBoneMatrixTexture(n)}updateBaseDataFromSplatBuffers(e,t){const n=this.splatDataTextures.covariances,i=n?n.compressionLevel:void 0,s=this.splatDataTextures.scaleRotations,r=s?s.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,r,o,e,t,e)}updateDataTexturesFromBaseData(e,t){const n=this.splatDataTextures.covariances,i=n?n.compressionLevel:void 0,s=this.splatDataTextures.scaleRotations,r=s?s.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;xp.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 s=n.texture,r=6*e,a=6*t;if(0===i)for(let e=r;e<=a;e++){const t=this.splatDataTextures.baseData.covariances[e];n.data[e]=t}else xp.updatePaddedCompressedCovariancesTextureData(this.splatDataTextures.baseData.covariances,n.data,e*n.elementsPerTexelAllocated,r,a);const o=this.renderer?this.renderer.properties.get(s):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):s.needsUpdate=!0}if(s){const n=s.data,i=s.texture,a=6,o=0===r?4:2;xp.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,s.texture,s.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,s,r,a,o)=>{const l=this.renderer?this.renderer.properties.get(i):null;l&&l.__webglTexture?this.updateDataTexture(a,i,s,l,r,o,n,e,t):i.needsUpdate=!0},s=a.componentCount,r=a.paddedComponentCount;if(1===a.textureCount){const n=a.data;for(let i=e;i<=t;i++){const e=s*i,t=r*i;for(let i=0;i<s;i++)n[t+i]=g[e+i]}i(a.texture,a.size,a.elementsPerTexel,n,r)}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=s*i,t=r*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,r)}}}const v=this.splatDataTextures.sceneIndexes,_=v.data;for(let A=this.lastBuildSplatCount;A<=t;A++)_[A]=this.globalSplatIndexToSceneIndexMap[A];const x=v.texture,y=this.renderer?this.renderer.properties.get(x):null;y&&y.__webglTexture?this.updateDataTexture(_,v.texture,v.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,s){const r=s/i,a=e*r,o=Math.floor(a/n),l=o*n*i,c=t*r,h=Math.floor(c/n);return{dataStart:l,dataEnd:h*n*i+n*i,startRow:o,endRow:h}}updateDataTexture(e,t,n,i,s,r,a,o,l){const c=this.renderer.getContext(),h=xp.computeTextureUpdateRegion(o,l,n.x,s,r),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,s){let r=new DataView(t.buffer),a=n,o=0;for(let l=i;l<=s;l+=2)r.setUint16(2*a,e[l],!0),r.setUint16(2*a+2,e[l+1],!0),a+=2,o++,o>=3&&(a+=2,o=0)}static updateCenterColorsPaddedData(e,t,n,i,s){for(let r=e;r<=t;r++){const e=4*r,t=3*r,a=4*r;s[a]=qd(i,e),s[a+1]=Xd(n[t]),s[a+2]=Xd(n[t+1]),s[a+3]=Xd(n[t+2])}}static updateScaleRotationsPaddedData(e,t,n,i,s){for(let r=e;r<=t;r++){const e=3*r,t=4*r,a=6*r;s[a]=n[e],s[a+1]=n[e+1],s[a+2]=n[e+2],s[a+3]=i[t],s[a+4]=i[t+1],s[a+5]=i[t+2]}}updateVisibleRegion(e){const t=this.getSplatCount(!0),n=new ci;if(!e){const e=new ci;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=gd){const t=.012*this.sceneFadeInRateMultiplier,n=.003*this.sceneFadeInRateMultiplier,i=this.finalBuild?t:n,s=e===gd?i:n;this.visibleRegionFadeStartRadius=(this.visibleRegionRadius-this.visibleRegionFadeStartRadius)*s+this.visibleRegionFadeStartRadius;const r=(this.visibleRegionBufferRadius>0?this.visibleRegionFadeStartRadius/this.visibleRegionBufferRadius:0)>.99,a=r||e===vd?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=!r}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?xp.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 xp.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 mp(t),i=new gp(t,n,{});if(n.init(i),this.webGLUtils=new vp(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(),s=i.getParameter(i.VERTEX_ARRAY_BINDING);i.bindVertexArray(this.distancesTransformFeedback.vao);const r=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 r(16*this.getMaxSplatCount());e.set(t),i.bufferData(i.ARRAY_BUFFER,e,i.STATIC_DRAW)}i.bindBuffer(i.ARRAY_BUFFER,null),s&&i.bindVertexArray(s)}updateGPUTransformIndexesBufferForDistancesComputation(e,t,n){if(!this.renderer||!this.dynamicMode)return;const i=this.renderer.getContext(),s=i.getParameter(i.VERTEX_ARRAY_BINDING);i.bindVertexArray(this.distancesTransformFeedback.vao);const r=4*n;if(i.bindBuffer(i.ARRAY_BUFFER,this.distancesTransformFeedback.sceneIndexesBuffer),e)i.bufferSubData(i.ARRAY_BUFFER,r,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),s&&i.bindVertexArray(s)}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,s,r,a,o,l=0,c=0,h=1,u,d,p=0,f){const m=new ci;m.x=void 0,m.y=void 0,this.splatRenderMode===_d?m.z=void 0:m.z=1;const g=new Oi;let v=0,_=this.scenes.length-1;null!=f&&f>=0&&f<=this.scenes.length&&(v=f,_=f);for(let x=v;x<=_;x++){null==o&&(o=!this.dynamicMode);const a=this.getScene(x),f=a.splatBuffer;let v;if(o&&(this.getSceneTransform(x,g),v=g),e&&f.fillSplatCovarianceArray(e,v,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,v,u,d,p,c,m)}i&&f.fillSplatCenterArray(this.morphedMesh,i,v,u,d,p),s&&f.fillSplatColorArray(s,a.minimumAlpha,u,d,p),r&&f.fillSphericalHarmonicsArray(r,this.minSphericalHarmonicsDegree,v,u,d,p,h),p+=f.getSplatCount()}}getIntegerCenters(e,t,n=!1){const i=t-e+1,s=new Float32Array(3*i);let r;this.fillSplatDataArrays(null,null,null,s,null,null,void 0,void 0,void 0,void 0,e);let a=n?4:3;r=new Int32Array(i*a);for(let o=0;o<i;o++){for(let e=0;e<3;e++)r[o*a+e]=Math.round(1e3*s[3*o+e]);n&&(r[o*a+3]=1e3)}return r}getFloatCenters(e,t,n=!1){const i=t-e+1,s=new Float32Array(3*i);if(this.fillSplatDataArrays(null,null,null,s,null,null,void 0,void 0,void 0,void 0,e),!n)return s;let r=new Float32Array(4*i);for(let a=0;a<i;a++){for(let e=0;e<3;e++)r[4*a+e]=s[3*a+e];r[4*a+3]=1}return r}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 s=new ci,r=new ci;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<s.x)&&(s.x=t),(0===a||n<s.y)&&(s.y=n),(0===a||o<s.z)&&(s.z=o),(0===a||t>r.x)&&(r.x=t),(0===a||n>r.y)&&(r.y=n),(0===a||o>r.z)&&(r.z=o)}return new di(s,r)}}class yp extends Error{constructor(e){super(e),this.name="DirectLoadError"}}const Ap=class e{constructor(e=0){this.sphericalHarmonicsDegree=e,this.sphericalHarmonicsCount=Bd(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=Bd(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,s,r,a,o,l,c,h,u,d,p,...f){const m=[e,t,n,i,s,r,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],s=e.createSplat(this.sphericalHarmonicsDegree);for(let e=0;e<this.componentCount&&e<i.length;e++)s[e]=i[e];this.addSplat(s)}};i(Ap,"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 Sp=Ap;const bp=(e,t,n,i,s=0)=>{const r=new Uint8Array(e,t),a=new Uint8Array(n,i);for(let o=0;o<s;o++)a[o]=r[o]},Mp=Ns.toHalfFloat.bind(Ns),wp=Ns.fromHalfFloat.bind(Ns),Tp=(e,t,n=!1,i,s)=>0===t?e:1===t||2===t&&!n?Ns.fromHalfFloat(e):2===t?Cp(e,i,s):void 0,Ep=(e,t,n)=>{e=Rd(e,t,n);const i=n-t;return Rd(Math.floor((e-t)/i*255),0,255)},Cp=(e,t,n)=>e/255*(n-t)+t,Rp=(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),Ip=class e{constructor(t,n=!0){i(this,"getSplatScaleAndRotation",function(){const t=new Oi,n=new Oi,i=new Oi,s=new ci,r=new ci,a=new li;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);r.set(Tp(Rp(g,0,this.compressionLevel),this.compressionLevel),Tp(Rp(g,1,this.compressionLevel),this.compressionLevel),Tp(Rp(g,2,this.compressionLevel),this.compressionLevel)),u&&(void 0!==u.x&&(r.x=u.x),void 0!==u.y&&(r.y=u.y),void 0!==u.z&&(r.z=u.z)),a.set(Tp(Rp(g,4,this.compressionLevel),this.compressionLevel),Tp(Rp(g,5,this.compressionLevel),this.compressionLevel),Tp(Rp(g,6,this.compressionLevel),this.compressionLevel),Tp(Rp(g,3,this.compressionLevel),this.compressionLevel)),h?(t.makeScale(r.x,r.y,r.z),n.makeRotationFromQuaternion(a),i.copy(t).multiply(n).multiply(h),i.decompose(s,c,l)):(l.copy(r),c.copy(a))}}()),i(this,"fillSplatScaleRotationArray",function(){const t=new Oi,n=new Oi,i=new Oi,s=new ci,r=new li,a=new ci,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 v=(e,t)=>jd(e,t,f);for(let _=u;_<=d;_++){const d=this.globalSplatIndexToSectionMap[_],f=this.sections[d],g=_-f.splatCountOffset,x=f.bytesPerSplat*g+e.CompressionLevels[this.compressionLevel].ScaleOffsetBytes,y=(_-u+p)*e.ScaleComponentCount,A=(_-u+p)*e.RotationComponentCount,S=new DataView(this.bufferData,f.dataBase+x),b=m&&void 0!==m.x?m.x:Rp(S,0,this.compressionLevel),M=m&&void 0!==m.y?m.y:Rp(S,1,this.compressionLevel),w=m&&void 0!==m.z?m.z:Rp(S,2,this.compressionLevel),T=Rp(S,3,this.compressionLevel),E=Rp(S,4,this.compressionLevel),C=Rp(S,5,this.compressionLevel),R=Rp(S,6,this.compressionLevel);s.set(Tp(b,this.compressionLevel),Tp(M,this.compressionLevel),Tp(w,this.compressionLevel)),r.set(Tp(E,this.compressionLevel),Tp(C,this.compressionLevel),Tp(R,this.compressionLevel),Tp(T,this.compressionLevel)).normalize(),h&&(a.set(0,0,0),t.makeScale(s.x,s.y,s.z),n.makeRotationFromQuaternion(r),i.identity().premultiply(t).premultiply(n),i.premultiply(h),i.decompose(a,r,s),r.normalize()),o(r),l&&(l[y]=v(s.x,0),l[y+1]=v(s.y,0),l[y+2]=v(s.z,0)),c&&(c[A]=v(r.x,0),c[A+1]=v(r.y,0),c[A+2]=v(r.z,0),c[A+3]=v(r.w,0))}}}()),i(this,"fillSphericalHarmonicsArray",function(){for(let e=0;e<15;e++)new ci;const t=new kn,n=new Oi,i=new ci,s=new ci,r=new li,a=[],o=[],l=[],c=[],h=[],u=[],d=[],p=[],f=[],m=[],g=[],v=[],_=[],x=[],y=[],A=[],S=[],b=[],M=e=>e,w=(e,t,n,i)=>{e[0]=t,e[1]=n,e[2]=i},T=(e,t,n,i,s)=>{e[0]=Rp(t,i,s,!0),e[1]=Rp(t,i+n,s,!0),e[2]=Rp(t,i+n+n,s,!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,s)=>(t[0]=Tp(e[0],n,!0,i,s),t[1]=Tp(e[1],n,!0,i,s),t[2]=Tp(e[2],n,!0,i,s),t);return function(I,D,P,B,L,U,F){const k=this.splatCount;B=B||0,L=L||k-1,void 0===U&&(U=B),P&&D>=1&&(n.copy(P),n.decompose(i,r,s),r.normalize(),n.makeRotationFromQuaternion(r),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=>((e,t,n)=>Ep(wp(e),t,n))(e,this.minSphericalHarmonicsCoeff,this.maxSphericalHarmonicsCoeff),O=e=>Ep(e,this.minSphericalHarmonicsCoeff,this.maxSphericalHarmonicsCoeff);for(let t=B;t<=L;t++){const n=this.globalSplatIndexToSectionMap[t],i=this.sections[n];D=Math.min(D,i.sphericalHarmonicsDegree);const s=Bd(D),r=t-i.splatCountOffset,w=i.bytesPerSplat*r+e.CompressionLevels[this.compressionLevel].SphericalHarmonicsOffsetBytes,L=new DataView(this.bufferData,i.dataBase+w),k=(t-B+U)*s;let z=P?0:this.compressionLevel,H=M;z!==F&&(1===z?0===F?H=wp:2==F&&(H=N):0===z&&(1===F?H=Mp:2==F&&(H=O)));const V=this.minSphericalHarmonicsCoeff,G=this.maxSphericalHarmonicsCoeff;D>=1&&(T(f,L,3,0,this.compressionLevel),T(m,L,3,1,this.compressionLevel),T(g,L,3,2,this.compressionLevel),P?(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,A)):(E(f,x),E(m,y),E(g,A)),C(x,I,k,H),C(y,I,k+3,H),C(A,I,k+6,H),D>=2&&(T(f,L,5,9,this.compressionLevel),T(m,L,5,10,this.compressionLevel),T(g,L,5,11,this.compressionLevel),T(v,L,5,12,this.compressionLevel),T(_,L,5,13,this.compressionLevel),P?(R(f,f,this.compressionLevel,V,G),R(m,m,this.compressionLevel,V,G),R(g,g,this.compressionLevel,V,G),R(v,v,this.compressionLevel,V,G),R(_,_,this.compressionLevel,V,G),e.rotateSphericalHarmonics5(f,m,g,v,_,a,o,l,c,h,u,d,p,x,y,A,S,b)):(E(f,x),E(m,y),E(g,A),E(v,S),E(_,b)),C(x,I,k+9,H),C(y,I,k+12,H),C(A,I,k+15,H),C(S,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 s=i;n=e.fullBucketCount;let r=0;for(;s<e.splatCount;){let i=e.partiallyFilledBucketLengths[r];if(t>=s&&t<s+i)break;s+=i,n++,r++}}return n}getSplatCenter(t,n,i,s){const r=this.globalSplatIndexToSectionMap[n],a=this.sections[r],o=n-a.splatCountOffset,l=a.bytesPerSplat*o,c=new DataView(this.bufferData,a.dataBase+l),h=Rp(c,0,this.compressionLevel),u=Rp(c,1,this.compressionLevel),d=Rp(c,2,this.compressionLevel);if(this.compressionLevel>=1){const t=this.getBucketIndex(a,o)*e.BucketStorageSizeFloats,n=a.compressionScaleFactor,s=a.compressionScaleRange;i.x=(h-s)*n+a.bucketArray[t],i.y=(u-s)*n+a.bucketArray[t+1],i.z=(d-s)*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],s&&i.applyMatrix4(s)}getSplatColor(t,n){const i=this.globalSplatIndexToSectionMap[t],s=this.sections[i],r=t-s.splatCountOffset,a=s.bytesPerSplat*r+e.CompressionLevels[this.compressionLevel].ColorOffsetBytes,o=new Uint8Array(this.bufferData,s.dataBase+a,4);n.set(o[0],o[1],o[2],o[3])}fillSplatCenterArray(t,n,i,s,r,a){const o=this.splatCount;s=s||0,r=r||o-1,void 0===a&&(a=s);const l=new ci;for(let c=s;c<=r;c++){const r=this.globalSplatIndexToSectionMap[c],o=this.sections[r],h=c-o.splatCountOffset,u=(c-s+a)*e.CenterComponentCount,d=o.bytesPerSplat*h,p=new DataView(this.bufferData,o.dataBase+d),f=Rp(p,0,this.compressionLevel),m=Rp(p,1,this.compressionLevel),g=Rp(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,s,r,a){const o=this.splatCount,l=new ci,c=new li;i=i||0,s=s||o-1,void 0===r&&(r=i);for(let h=i;h<=s;h++){const s=this.globalSplatIndexToSectionMap[h],o=this.sections[s],u=h-o.splatCountOffset,d=(h-i+r)*e.CovarianceComponentCount,p=o.bytesPerSplat*u+e.CompressionLevels[this.compressionLevel].ScaleOffsetBytes,f=new DataView(this.bufferData,o.dataBase+p);l.set(Tp(Rp(f,0,this.compressionLevel),this.compressionLevel),Tp(Rp(f,1,this.compressionLevel),this.compressionLevel),Tp(Rp(f,2,this.compressionLevel),this.compressionLevel)),c.set(Tp(Rp(f,4,this.compressionLevel),this.compressionLevel),Tp(Rp(f,5,this.compressionLevel),this.compressionLevel),Tp(Rp(f,6,this.compressionLevel),this.compressionLevel),Tp(Rp(f,3,this.compressionLevel),this.compressionLevel)),e.computeCovariance(l,c,n,t,d,a)}}fillSplatColorArray(t,n,i,s,r){const a=this.splatCount;i=i||0,s=s||a-1,void 0===r&&(r=i);for(let o=i;o<=s;o++){const s=this.globalSplatIndexToSectionMap[o],a=this.sections[s],l=o-a.splatCountOffset,c=(o-i+r)*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),s=new Uint32Array(t,0,e.HeaderSizeBytes/4),r=new Float32Array(t,0,e.HeaderSizeBytes/4);return{versionMajor:n[0],versionMinor:n[1],maxSectionCount:s[1],sectionCount:s[2],maxSplatCount:s[3],splatCount:s[4],compressionLevel:i[10],sceneCenter:new ci(r[6],r[7],r[8]),minSphericalHarmonicsCoeff:r[9]||-zd,maxSphericalHarmonicsCoeff:r[10]||zd}}static writeHeaderCountsToBuffer(t,n,i){const s=new Uint32Array(i,0,e.HeaderSizeBytes/4);s[2]=t,s[4]=n}static writeHeaderToBuffer(t,n){const i=new Uint8Array(n,0,e.HeaderSizeBytes),s=new Uint16Array(n,0,e.HeaderSizeBytes/2),r=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,r[1]=t.maxSectionCount,r[2]=t.sectionCount,r[3]=t.maxSplatCount,r[4]=t.splatCount,s[10]=t.compressionLevel,a[6]=t.sceneCenter.x,a[7]=t.sceneCenter.y,a[8]=t.sceneCenter.z,a[9]=t.minSphericalHarmonicsCoeff||-zd,a[10]=t.maxSphericalHarmonicsCoeff||zd}static parseSectionHeaders(t,n,i=0,s){const r=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],v=a/2,_=o[d+10],x=l[p+6]||e.CompressionLevels[r].ScaleRange,y=l[p+8],A=l[p+9],S=4*A,b=_*i+S,M=o[d+20],{bytesPerSplat:w}=e.calculateComponentStorage(r,M),T=w*t,E=T+b,C={bytesPerSplat:w,splatCountOffset:m,splatCount:s?t:0,maxSplatCount:t,bucketSize:n,bucketCount:i,bucketBlockSize:a,halfBucketBlockSize:v,bucketStorageSizeBytes:_,bucketsStorageSizeBytes:b,splatDataStorageSizeBytes:T,storageSizeBytes:E,compressionScaleRange:x,compressionScaleFactor:v/x,base:f,bucketsBase:f+S,dataBase:f+b,fullBucketCount:y,partiallyFilledBucketCount:A,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,s=0){const r=new Uint16Array(i,s,e.SectionHeaderSizeBytes/2),a=new Uint32Array(i,s,e.SectionHeaderSizeBytes/4),o=new Float32Array(i,s,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,r[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,r[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 ci).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,s=e.CompressionLevels[t].BytesPerScale,r=e.CompressionLevels[t].BytesPerRotation,a=e.CompressionLevels[t].BytesPerColor,o=Bd(n),l=e.CompressionLevels[t].BytesPerSphericalHarmonicsComponent*o;return{bytesPerCenter:i,bytesPerScale:s,bytesPerRotation:r,bytesPerColor:a,sphericalHarmonicsComponentsPerSplat:o,sphericalHarmonicsBytesPerSplat:l,bytesPerSplat:i+s+r+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,s,r,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=Sp.OFFSET.FRC0;e<Sp.OFFSET.FRC23&&e<t.length;e++)(!l||t[e]<l)&&(l=t[e]),(!c||t[e]>c)&&(c=t[e])}}l=l||-zd,c=c||zd;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 s=t[y],g=new Sp(h);for(let e=0;e<s.splatCount;e++){const t=s.splats[e];(t[Sp.OFFSET.OPACITY]||0)>=n&&g.addSplat(t)}const v=o[y]||{},_=(v.blockSizeFactor||1)*(r||e.BucketBlockSize),x=Math.ceil((v.bucketSizeFactor||1)*(a||e.BucketSize)),A=e.computeBucketsForUncompressedSplatArray(g,_,x),S=A.fullBuckets.length,b=A.partiallyFullBuckets.map(e=>e.splats.length),M=b.length,w=[...A.fullBuckets,...A.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),D=d/(.5*_),P=new ci;let B=0;for(let t=0;t<w.length;t++){const n=w[t];P.fromArray(n.center);for(let t=0;t<n.splats.length;t++){let s=n.splats[t];const r=g.splats[s],a=C+B*u;e.writeSplatDataToSectionBuffer(r,I,a,i,h,P,D,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:_,compressionScaleRange:d,storageSizeBytes:R,fullBucketCount:S,partiallyFilledBucketCount:M,sphericalHarmonicsDegree:h},i,L,0),f.push(L)}let g=0;for(let e of p)g+=e.byteLength;const v=e.HeaderSizeBytes+e.SectionHeaderSizeBytes*p.length+g,_=new ArrayBuffer(v);e.writeHeaderToBuffer({versionMajor:0,versionMinor:1,maxSectionCount:p.length,sectionCount:p.length,maxSplatCount:m,splatCount:m,compressionLevel:i,sceneCenter:s,minSphericalHarmonicsCoeff:l,maxSphericalHarmonicsCoeff:c},_);let x=e.HeaderSizeBytes;for(let y of f)new Uint8Array(_,x,e.SectionHeaderSizeBytes).set(new Uint8Array(y)),x+=e.SectionHeaderSizeBytes;for(let e of p)new Uint8Array(_,x,e.byteLength).set(new Uint8Array(e)),x+=e.byteLength;return new e(_)}static computeBucketsForUncompressedSplatArray(e,t,n){let i=e.splatCount;const s=t/2,r=new ci,a=new ci;for(let f=0;f<i;f++){const t=e.splats[f],n=[t[Sp.OFFSET.X],t[Sp.OFFSET.Y],t[Sp.OFFSET.Z]];(0===f||n[0]<r.x)&&(r.x=n[0]),(0===f||n[0]>a.x)&&(a.x=n[0]),(0===f||n[1]<r.y)&&(r.y=n[1]),(0===f||n[1]>a.y)&&(a.y=n[1]),(0===f||n[2]<r.z)&&(r.z=n[2]),(0===f||n[2]>a.z)&&(a.z=n[2])}const o=(new ci).copy(a).sub(r),l=Math.ceil(o.y/t),c=Math.ceil(o.z/t),h=new ci,u=[],d={};for(let f=0;f<i;f++){const i=e.splats[f],a=[i[Sp.OFFSET.X],i[Sp.OFFSET.Y],i[Sp.OFFSET.Z]],o=Math.floor((a[0]-r.x)/t),p=Math.floor((a[1]-r.y)/t),m=Math.floor((a[2]-r.z)/t);h.x=o*t+r.x+s,h.y=p*t+r.y+s,h.z=m*t+r.z+s;const g=o*(l*c)+p*c+m;let v=d[g];v||(d[g]=v={splats:[],center:h.toArray()}),v.splats.push(f),v.splats.length>=n&&(u.push(v),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(Ip,"CurrentMajorVersion",0),i(Ip,"CurrentMinorVersion",1),i(Ip,"CenterComponentCount",3),i(Ip,"ScaleComponentCount",3),i(Ip,"RotationComponentCount",4),i(Ip,"ColorComponentCount",4),i(Ip,"CovarianceComponentCount",6),i(Ip,"SplatScaleOffsetFloat",3),i(Ip,"SplatRotationOffsetFloat",6),i(Ip,"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(Ip,"CovarianceSizeFloats",6),i(Ip,"HeaderSizeBytes",4096),i(Ip,"SectionHeaderSizeBytes",1024),i(Ip,"BucketStorageSizeBytes",12),i(Ip,"BucketStorageSizeFloats",3),i(Ip,"BucketBlockSize",5),i(Ip,"BucketSize",256),i(Ip,"computeCovariance",function(){const e=new Oi,t=new kn,n=new kn,i=new kn,s=new kn,r=new kn,a=new kn;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),s.copy(i).transpose().premultiply(i),c&&(r.setFromMatrix4(c),a.copy(r).transpose(),s.multiply(a),s.premultiply(r)),d>=1?(h[u]=Mp(s.elements[0]),h[u+1]=Mp(s.elements[3]),h[u+2]=Mp(s.elements[6]),h[u+3]=Mp(s.elements[4]),h[u+4]=Mp(s.elements[7]),h[u+5]=Mp(s.elements[8])):(h[u]=s.elements[0],h[u+1]=s.elements[3],h[u+2]=s.elements[6],h[u+3]=s.elements[4],h[u+4]=s.elements[7],h[u+5]=s.elements[8])}}()),i(Ip,"dot3",(e,t,n,i,s)=>{s[0]=s[1]=s[2]=0;const r=i[0],a=i[1],o=i[2];Ip.addInto3(e[0]*r,e[1]*r,e[2]*r,s),Ip.addInto3(t[0]*a,t[1]*a,t[2]*a,s),Ip.addInto3(n[0]*o,n[1]*o,n[2]*o,s)}),i(Ip,"addInto3",(e,t,n,i)=>{i[0]=i[0]+e,i[1]=i[1]+t,i[2]=i[2]+n}),i(Ip,"dot5",(e,t,n,i,s,r,a)=>{a[0]=a[1]=a[2]=0;const o=r[0],l=r[1],c=r[2],h=r[3],u=r[4];Ip.addInto3(e[0]*o,e[1]*o,e[2]*o,a),Ip.addInto3(t[0]*l,t[1]*l,t[2]*l,a),Ip.addInto3(n[0]*c,n[1]*c,n[2]*c,a),Ip.addInto3(i[0]*h,i[1]*h,i[2]*h,a),Ip.addInto3(s[0]*u,s[1]*u,s[2]*u,a)}),i(Ip,"rotateSphericalHarmonics3",(e,t,n,i,s,r,a,o,l)=>{Ip.dot3(e,t,n,i,a),Ip.dot3(e,t,n,s,o),Ip.dot3(e,t,n,r,l)}),i(Ip,"rotateSphericalHarmonics5",(e,t,n,i,s,r,a,o,l,c,h,u,d,p,f,m,g,v)=>{const _=Math.sqrt(1/4),x=Math.sqrt(3/4),y=Math.sqrt(1/3),A=Math.sqrt(4/3),S=Math.sqrt(1/12);l[0]=_*(o[2]*r[0]+o[0]*r[2]+(r[2]*o[0]+r[0]*o[2])),l[1]=o[1]*r[0]+r[1]*o[0],l[2]=x*(o[1]*r[1]+r[1]*o[1]),l[3]=o[1]*r[2]+r[1]*o[2],l[4]=_*(o[2]*r[2]-o[0]*r[0]+(r[2]*o[2]-r[0]*o[0])),Ip.dot5(e,t,n,i,s,l,p),c[0]=_*(a[2]*r[0]+a[0]*r[2]+(r[2]*a[0]+r[0]*a[2])),c[1]=a[1]*r[0]+r[1]*a[0],c[2]=x*(a[1]*r[1]+r[1]*a[1]),c[3]=a[1]*r[2]+r[1]*a[2],c[4]=_*(a[2]*r[2]-a[0]*r[0]+(r[2]*a[2]-r[0]*a[0])),Ip.dot5(e,t,n,i,s,c,f),h[0]=y*(a[2]*a[0]+a[0]*a[2])+-S*(o[2]*o[0]+o[0]*o[2]+(r[2]*r[0]+r[0]*r[2])),h[1]=A*a[1]*a[0]+-y*(o[1]*o[0]+r[1]*r[0]),h[2]=a[1]*a[1]+-_*(o[1]*o[1]+r[1]*r[1]),h[3]=A*a[1]*a[2]+-y*(o[1]*o[2]+r[1]*r[2]),h[4]=y*(a[2]*a[2]-a[0]*a[0])+-S*(o[2]*o[2]-o[0]*o[0]+(r[2]*r[2]-r[0]*r[0])),Ip.dot5(e,t,n,i,s,h,m),u[0]=_*(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]=_*(a[2]*o[2]-a[0]*o[0]+(o[2]*a[2]-o[0]*a[0])),Ip.dot5(e,t,n,i,s,u,g),d[0]=_*(o[2]*o[0]+o[0]*o[2]-(r[2]*r[0]+r[0]*r[2])),d[1]=o[1]*o[0]-r[1]*r[0],d[2]=x*(o[1]*o[1]-r[1]*r[1]),d[3]=o[1]*o[2]-r[1]*r[2],d[4]=_*(o[2]*o[2]-o[0]*o[0]-(r[2]*r[2]-r[0]*r[0])),Ip.dot5(e,t,n,i,s,d,v)}),i(Ip,"writeSplatDataToSectionBuffer",function(){const e=new ArrayBuffer(12),t=new ArrayBuffer(12),n=new ArrayBuffer(16),i=new ArrayBuffer(4),s=new ArrayBuffer(256),r=new li,a=new ci,o=new ci,{X:l,Y:c,Z:h,SCALE0:u,SCALE1:d,SCALE2:p,ROTATION0:f,ROTATION1:m,ROTATION2:g,ROTATION3:v,FDC0:_,FDC1:x,FDC2:y,OPACITY:A,FRC0:S,FRC9:b}=Sp.OFFSET,M=(e,t,n)=>{const i=2*n+1;return e=Math.round(e*t)+n,Rd(e,0,i)};return function(w,T,E,C,R,I,D,P,B=-zd,L=zd){const U=Bd(R),F=E,k=F+Ip.CompressionLevels[C].BytesPerCenter,N=k+Ip.CompressionLevels[C].BytesPerScale,O=N+Ip.CompressionLevels[C].BytesPerRotation,z=O+Ip.CompressionLevels[C].BytesPerColor;if(void 0!==w[f]?(r.set(w[f],w[m],w[g],w[v]),r.normalize()):r.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,F,Ip.CenterComponentCount),t=new Float32Array(T,N,Ip.RotationComponentCount),n=new Float32Array(T,k,Ip.ScaleComponentCount);if(t.set([r.x,r.y,r.z,r.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,U);if(R>=1){for(let t=0;t<9;t++)e[t]=w[S+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,Ip.CenterComponentCount),u=new Uint16Array(n,0,Ip.RotationComponentCount),d=new Uint16Array(t,0,Ip.ScaleComponentCount);if(u.set([Mp(r.x),Mp(r.y),Mp(r.z),Mp(r.w)]),d.set([Mp(a.x),Mp(a.y),Mp(a.z)]),o.set(w[l],w[c],w[h]).sub(I),o.x=M(o.x,D,P),o.y=M(o.y,D,P),o.z=M(o.z,D,P),i.set([o.x,o.y,o.z]),R>0){const e=1===C?2:1,t=new(1===C?Uint16Array:Uint8Array)(s,0,U);if(R>=1){for(let e=0;e<9;e++){const n=w[S+e]||0;t[e]=1===C?Mp(n):Ep(n,B,L)}const n=9*e;if(bp(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?Mp(n):Ep(n,B,L)}bp(t.buffer,n,T,z+n,15*e)}}}bp(i.buffer,0,T,F,6),bp(d.buffer,0,T,k,6),bp(u.buffer,0,T,N,8)}const H=new Uint8ClampedArray(i,0,4);H.set([w[_]||0,w[x]||0,w[y]||0]),H[3]=w[A]||0,bp(H.buffer,0,T,O,4)}}());let Dp=Ip;class Pp{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 s=this.partitionGenerator(e);t=s.groupingParameters,n=s.sectionCount,i=s.sectionFilters}else t=this.groupingParameters,n=this.sectionCount,i=this.sectionFilters;const s=[];for(let r=0;r<n;r++){const t=new Sp(e.sphericalHarmonicsDegree),n=i[r];for(let i=0;i<e.splatCount;i++)n(i)&&t.addSplat(e.splats[i]);s.push(t)}return{splatArrays:s,parameters:t}}static getStandardPartitioner(e=0,t=new ci,n=Dp.BucketBlockSize,i=Dp.BucketSize){return new Pp(void 0,void 0,void 0,s=>{const r=Sp.OFFSET.X,a=Sp.OFFSET.Y,o=Sp.OFFSET.Z;e<=0&&(e=s.splatCount);const l=new ci,c=.5;s.splats.forEach(e=>{var n;l.set(e[r],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()}),s.splats.sort((e,t)=>e.centerDist>t.centerDist?1:-1);const h=[],u=[];e=Math.min(s.splatCount,e);const d=Math.ceil(s.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 Bp{constructor(e,t,n,i,s,r,a){this.splatPartitioner=e,this.alphaRemovalThreshold=t,this.compressionLevel=n,this.sectionSize=i,this.sceneCenter=s?(new ci).copy(s):void 0,this.blockSize=r,this.bucketSize=a}generateFromUncompressedSplatArray(e){const t=this.splatPartitioner.partitionUncompressedSplatArray(e);return Dp.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 ci,s=Dp.BucketBlockSize,r=Dp.BucketSize){const a=Pp.getStandardPartitioner(n,i,s,r);return new Bp(a,e,t,n,i,s,r)}}const Lp=0,Up=0,Fp=1,kp=2,Np=3,Op=4,zp=5,Hp=6,Vp={double:0,int:1,uint:2,float:3,short:4,ushort:5,uchar:6},Gp={[Up]:8,[Fp]:4,[kp]:4,[Np]:4,[Op]:2,[zp]:2,[Hp]:1},Wp=class e{constructor(){}decodeSectionHeader(t,n,i=0){const s=[];let r=!1,a=-1,o=0,l=!1,c=null;const h=[],u=[],d=[],p={};for(let v=i;v<t.length;v++){const f=t[v].trim();if(f.startsWith("element")){if(r){a--;break}{r=!0,i=v,a=v;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 s=n[i];p[i]=t;const r=Vp[t];void 0!==s&&(h.push(s),u[s]=r)}}if(f===e.HeaderEndToken){l=!0;break}r&&(s.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+=Gp[Vp[t]]}const g=this.decodeSphericalHarmonicsFromSectionHeader(d,n);return{headerLines:s,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 s=0;i>=3&&(s=1),i>=8&&(s=2);let r=[],a=[];for(let o=0;o<3;o++){if(s>=1)for(let e=0;e<3;e++)r.push(t["f_rest_"+(e+i*o)]);if(s>=2)for(let e=0;e<5;e++)a.push(t["f_rest_"+(e+i*o+3)])}return{degree:s,coefficientsPerChannel:i,degree1Fields:r,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,s){const r=new Uint8Array(t,Math.max(0,n-i),i),a=s.decode(r);return e.checkTextForEndHeader(a)}static extractHeaderFromBufferToText(t){const n=new TextDecoder;let i=0,s="";const r=100;for(;;){if(i+r>=t.byteLength)throw new Error("End of file reached while searching for end of header");const a=new Uint8Array(t,i,r);if(s+=n.decode(a),i+=r,e.checkBufferForEndHeader(t,i,200,n))break}return s}readHeaderFromBuffer(t){const n=new TextDecoder;let i=0,s="";const r=100;for(;;){if(i+r>=t.byteLength)throw new Error("End of file reached while searching for end of header");const a=new Uint8Array(t,i,r);if(s+=n.decode(a),i+=r,e.checkBufferForEndHeader(t,i,200,n))break}return s}static convertHeaderTextToLines(t){const n=t.split("\n"),i=[];for(let s=0;s<n.length;s++){const t=n[s].trim();if(i.push(t),t===e.HeaderEndToken)break}return i}static determineHeaderFormatFromHeaderText(e){return Lp}static determineHeaderFormatFromPlyBuffer(t){const n=e.extractHeaderFromBufferToText(t);return e.determineHeaderFormatFromHeaderText(n)}static readVertex(e,t,n,i,s,r,a=!0){const o=n*t.bytesPerVertex+i,l=t.fieldOffsets,c=t.fieldTypes;for(let h of s){const t=c[h];3===t?r[h]=e.getFloat32(o+l[h],!0):4===t?r[h]=e.getInt16(o+l[h],!0):5===t?r[h]=e.getUint16(o+l[h],!0):1===t?r[h]=e.getInt32(o+l[h],!0):2===t?r[h]=e.getUint32(o+l[h],!0):6===t&&(r[h]=a?e.getUint8(o+l[h])/255:e.getUint8(o+l[h]))}}};i(Wp,"HeaderEndToken","end_header");let jp=Wp;const Xp=["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"],qp=Xp.map((e,t)=>t),[Qp,Kp,Yp,Zp,Jp,$p,ef,tf,nf,sf,rf,af,of,lf,cf,hf,uf,df]=qp,pf=class e{constructor(){this.plyParserutils=new jp}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 s=[...Xp,...i],r=s.map((e,t)=>t),a=r.reduce((e,t)=>(e[s[t]]=t,e),{}),o=this.plyParserutils.decodeSectionHeader(e,a,0);return o.splatCount=o.vertexCount,o.bytesPerSplat=o.bytesPerVertex,o.fieldsToReadIndexes=r,o}decodeHeaderText(e){const t=jp.convertHeaderTextToLines(e),n=this.decodeHeaderLines(t);return n.headerText=e,n.headerSizeBytes=e.indexOf(jp.HeaderEndToken)+jp.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,s,r,a,o,l=0){l=Math.min(l,t.sphericalHarmonicsDegree);const c=Dp.CompressionLevels[0].SphericalHarmonicsDegrees[l].BytesPerSplat;for(let h=n;h<=i;h++){const n=e.parseToUncompressedSplat(s,h,t,r,l),i=h*c+o;Dp.writeSplatDataToSectionBuffer(n,a,i,0,l)}}parseToUncompressedSplatArraySection(t,n,i,s,r,a,o=0){o=Math.min(o,t.sphericalHarmonicsDegree);for(let l=n;l<=i;l++){const n=e.parseToUncompressedSplat(s,l,t,r,o);a.addSplat(n)}}decodeSectionSplatData(t,n,i,s){s=Math.min(s,i.sphericalHarmonicsDegree);const r=new Sp(s);for(let a=0;a<n;a++){const n=e.parseToUncompressedSplat(t,a,i,0,s);r.addSplat(n)}return r}static readSplat(e,t,n,i,s){return jp.readVertex(e,t,n,i,t.fieldsToReadIndexes,s,!0)}parseToUncompressedSplatArray(e,t=0){const n=this.decodeHeaderFromBuffer(e),i=n.splatCount,s=this.findSplatData(e,n);return this.decodeSectionSplatData(s,i,n,t)}};i(pf,"parseToUncompressedSplat",function(){let e=[];const t=new li,n=Sp.OFFSET.X,i=Sp.OFFSET.Y,s=Sp.OFFSET.Z,r=Sp.OFFSET.SCALE0,a=Sp.OFFSET.SCALE1,o=Sp.OFFSET.SCALE2,l=Sp.OFFSET.ROTATION0,c=Sp.OFFSET.ROTATION1,h=Sp.OFFSET.ROTATION2,u=Sp.OFFSET.ROTATION3,d=Sp.OFFSET.FDC0,p=Sp.OFFSET.FDC1,f=Sp.OFFSET.FDC2,m=Sp.OFFSET.OPACITY,g=[];for(let v=0;v<45;v++)g[v]=Sp.OFFSET.FRC0+v;return function(v,_,x,y=0,A=0){A=Math.min(A,x.sphericalHarmonicsDegree),pf.readSplat(v,x,_,y,e);const S=Sp.createSplat(A);if(void 0!==e[Qp]?(S[r]=Math.exp(e[Qp]),S[a]=Math.exp(e[Kp]),S[o]=Math.exp(e[Yp])):(S[r]=.01,S[a]=.01,S[o]=.01),void 0!==e[rf]?(S[d]=255*e[rf],S[p]=255*e[af],S[f]=255*e[of]):void 0!==e[cf]?(S[d]=255*e[cf],S[p]=255*e[hf],S[f]=255*e[uf]):(S[d]=0,S[p]=0,S[f]=0),void 0!==e[lf]&&(S[m]=1/(1+Math.exp(-e[lf]))*255),S[d]=Rd(Math.floor(S[d]),0,255),S[p]=Rd(Math.floor(S[p]),0,255),S[f]=Rd(Math.floor(S[f]),0,255),S[m]=Rd(Math.floor(S[m]),0,255),A>=1&&void 0!==e[df]){for(let t=0;t<9;t++)S[g[t]]=e[x.sphericalHarmonicsDegree1Fields[t]];if(A>=2)for(let t=0;t<15;t++)S[g[9+t]]=e[x.sphericalHarmonicsDegree2Fields[t]]}return t.set(e[Zp],e[Jp],e[$p],e[ef]),t.normalize(),S[l]=t.x,S[c]=t.y,S[h]=t.z,S[u]=t.w,S[n]=e[tf],S[i]=e[nf],S[s]=e[sf],S}}());let ff=pf;class mf{static parseToUncompressedSplatArray(e,t=0){return(new ff).parseToUncompressedSplatArray(e,t)}}function gf(e,t,n,i,s,r,a,o){if(t){return Bp.getStandardGenerator(n,i,s,r,a,o).generateFromUncompressedSplatArray(e)}return Dp.generateFromUncompressedSplatArrays([e],n,0,new ci)}class vf{static loadFromURL(e,t,n,i,s,r,a=!0,o=0,l,c,h,u,d){let p=n?Sd:bd;a&&(p=bd);const f=yd.ProgressiveLoadSectionSize,m=Dp.HeaderSizeBytes+Dp.SectionHeaderSizeBytes;let g,v,_,x=0,y=0,A=!1,S=!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 D=new TextDecoder,P=new ff;return t&&t(0,"0%",wd),function(e,t,n=!0,i){const s=new AbortController,r=s.signal;let a=!1,o=!1;const l=(e,n,i,s)=>{t&&!o&&(t(e,n,i,s),100===e&&(o=!0))},c=new Promise((t,s)=>{const o={signal:r};i&&(o.headers=i),fetch(e,o).then(async e=>{if(!e.ok){const t=await e.text();return void s(new Error(`Fetch failed: ${e.status} ${e.statusText} ${t}`))}const i=e.body.getReader();let r=0,o=e.headers.get("Content-Length"),c=o?parseInt(o):void 0;const h=[];for(;!a;)try{const{value:e,done:s}=await i.read();if(s){if(l(100,"100%",e,c),n){const e=new Blob(h).arrayBuffer();t(e)}else t();break}let a,o;r+=e.length,void 0!==c&&(a=r/c*100,o=`${a.toFixed(2)}%`),n&&h.push(e),l(a,o,e,c)}catch(u){return void s(u)}}).catch(e=>{"AbortError"===e.name?s(new Cd("Fetch aborted")):s(new Cd(e.message||e))})});return c.abort=e=>{a=!0,s.abort(e)},c.abortController=s,c}(e,(e,n,s)=>{const r=e>=100;if(s&&(I.push({data:s,sizeBytes:s.byteLength,startBytes:E,endBytes:E+s.byteLength}),E+=s.byteLength),p===Md)r&&b.resolve(I);else{if(!A&&(C+=D.decode(s),jp.checkTextForEndHeader(C))){R=P.decodeHeaderText(C),x=R.splatCount,S=!0,o=Math.min(o,R.sphericalHarmonicsDegree);const e=Dp.CompressionLevels[0].SphericalHarmonicsDegrees[o],t=m+e.BytesPerSplat*x;p===Sd?(v=new ArrayBuffer(t),Dp.writeHeaderToBuffer({versionMajor:Dp.CurrentMajorVersion,versionMinor:Dp.CurrentMinorVersion,maxSectionCount:1,sectionCount:1,maxSplatCount:x,splatCount:y,compressionLevel:0,sceneCenter:new ci},v)):M=new Sp(o),w=R.headerSizeBytes,T=R.headerSizeBytes,A=!0}if(A&&S){if(I.length>0){g=function(e,t){let n=0;for(let s of e)n+=s.sizeBytes;(!t||t.byteLength<n)&&(t=new ArrayBuffer(n));let i=0;for(let s of e)new Uint8Array(t,i,s.sizeBytes).set(s.data),i+=s.sizeBytes;return t}(I,g);if(E-w>f||r){const e=E-T,t=Math.floor(e/R.bytesPerSplat),n=t*R.bytesPerSplat,s=e-n,a=y+t,l=T-I[0].startBytes,c=new DataView(g,l,n),h=Dp.CompressionLevels[0].SphericalHarmonicsDegrees[o],u=y*h.BytesPerSplat+m;if(p===Sd?P.parseToUncompressedSplatBufferSection(R,0,t-1,c,0,v,u,o):P.parseToUncompressedSplatArraySection(R,0,t-1,c,0,M,o),y=a,p===Sd&&(_||(Dp.writeSectionHeaderToBuffer({maxSplatCount:x,splatCount:y,bucketSize:0,bucketCount:0,bucketBlockSize:0,compressionScaleRange:0,storageSizeBytes:0,fullBucketCount:0,partiallyFilledBucketCount:0,sphericalHarmonicsDegree:o},0,v,Dp.HeaderSizeBytes),_=new Dp(v,!1)),_.updateLoadedCounts(1,y),i&&i(_,r)),w+=f,T+=n,0===s)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>=s)break}I=e}}}r&&(p===Sd?b.resolve(_):b.resolve(M))}}t&&t(e,n,wd)},!1,l).then(()=>(t&&t(0,"0%",Td),b.promise.then(e=>{if(t&&t(100,"100%",Ed),p===Md){const e=I.map(e=>e.data);return new Blob(e).arrayBuffer().then(e=>vf.loadFromFileData(e,s,r,a,o,c,h,u,d))}return p===Sd?e:Pd(()=>gf(e,a,s,r,c,h,u,d))})))}static loadFromFileData(e,t,n,i,s=0,r,a,o,l){return Pd(()=>mf.parseToUncompressedSplatArray(e,s)).then(e=>gf(e,i,t,n,r,a,o,l))}}const _f=new ci(1,0,0),xf=new ci(0,1,0),yf=new ci(0,0,1);class Af{constructor(e=new ci,t=new ci){i(this,"intersectBox",function(){const e=new ci,t=[],n=[],i=[];return function(s,r){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(s,this.origin,1e-4))return r&&(r.origin.copy(this.origin),r.normal.set(0,0,0),r.distance=-1),!0;for(let a=0;a<3;a++){if(0==i[a])continue;const o=0==a?_f:1==a?xf:yf,l=i[a]<0?s.max:s.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(s,e,1e-4))return r&&(r.origin.copy(e),r.normal.copy(o).multiplyScalar(c),r.distance=e.sub(this.origin).length()),!0}}return!1}}()),i(this,"intersectSphere",function(){const e=new ci;return function(t,n,i){e.copy(t).sub(this.origin);const s=e.dot(this.direction),r=s*s,a=e.dot(e)-r,o=n*n;if(a>o)return!1;const l=Math.sqrt(o-a),c=s-l,h=s+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 ci,this.direction=new ci,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 Sf{constructor(){this.origin=new ci,this.normal=new ci,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 Sf;return e.origin.copy(this.origin),e.normal.copy(this.normal),e.distance=this.distance,e.splatIndex=this.splatIndex,e}}class bf{constructor(e,t,n=!1){i(this,"setFromCameraAndScreenPosition",function(){const e=new Fn;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 Oi,t=new Oi,n=new Oi,i=new Af,s=new ci;return function(r,a=[]){const o=r.getSplatTree();if(o){for(let l=0;l<o.subTrees.length;l++){const c=o.subTrees[l];t.copy(r.matrixWorld),r.dynamicMode&&(r.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=s.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 ii,t=new ci,n=new ci,i=new li,s=new Sf,r=1e-7,a=new ci(0,0,0),o=new Oi,l=new Oi,c=new Oi,h=new Oi,u=new Oi,d=new Af;return function(p,f,m,g=[]){if(p.intersectBox(m.boundingBox)){if(m.data&&m.data.indexes&&m.data.indexes.length>0)for(let v=0;v<m.data.indexes.length;v++){const _=m.data.indexes[v],x=f.splatMesh.getSceneIndexForSplat(_);if(f.splatMesh.getScene(x).visible&&(f.splatMesh.getSplatColor(_,e),f.splatMesh.getSplatCenter(_,t),f.splatMesh.getSplatScaleAndRotation(_,n,i),!(n.x<=r||n.y<=r||f.splatMesh.splatRenderMode===_d&&n.z<=r)))if(this.raycastAgainstTrueSplatEllipsoid){l.makeScale(n.x,n.y,n.z),c.makeRotationFromQuaternion(i);const r=2*Math.log10(e.w);if(o.makeScale(r,r,r),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,s)){const e=s.clone();e.splatIndex=_,e.origin.applyMatrix4(u).add(t),g.push(e)}}else{let e=n.x+n.y,i=2;if(f.splatMesh.splatRenderMode===_d&&(e+=n.z,i=3),e/=i,p.intersectSphere(t,e,s)){const e=s.clone();e.splatIndex=_,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 Af(e,t),this.raycastAgainstTrueSplatEllipsoid=n}}const Mf="AGFzbQEAAAAADwhkeWxpbmsuMAEEAAAAAAEXAmAAAGAQf39/f39/f39/f39/f39/fwACEgEDZW52Bm1lbW9yeQIDAICABAMDAgABBz4DEV9fd2FzbV9jYWxsX2N0b3JzAAAYX193YXNtX2FwcGx5X2RhdGFfcmVsb2NzAAALc29ydEluZGV4ZXMAAQqiDwICAAucDwMBfAd9Bn8gCyAKayEMAkACQCAOBEAgDQRAQfj///8HIQpBiICAgHghDSALIAxNDQMgDCEFA0AgAyAFQQJ0IgFqIAIgACABaigCAEECdGooAgAiATYCACABIAogASAKSBshCiABIA0gASANShshDSAFQQFqIgUgC0cNAAsMAwsgDwRAIAsgDE0NAkF/IQ9B+P///wchCkGIgICAeCENIAwhAgNAIA8gByAAIAJBAnQiGmooAgBBAnQiG2ooAgAiDkcEQAJ/IAUqAjgiESAIIA5BBnRqIg8qAjyUIAUqAigiEiAPKgI4lCAFKgIIIhMgDyoCMJQgBSoCGCIUIA8qAjSUkpKSu0QAAAAAAECPQKIiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLIRgCfyARIA8qAiyUIBIgDyoCKJQgEyAPKgIglCAUIA8qAiSUkpKSu0QAAAAAAECPQKIiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLIRkCfyARIA8qAhyUIBIgDyoCGJQgEyAPKgIQlCAUIA8qAhSUkpKSu0QAAAAAAECPQKIiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLIRwCfyARIA8qAgyUIBIgDyoCCJQgEyAPKgIAlCAUIA8qAgSUkpKSu0QAAAAAAECPQKIiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLIR0gDiEPCyADIBpqIAEgG0ECdGoiDigCBCAcbCAOKAIAIB1saiAOKAIIIBlsaiAOKAIMIBhsaiIONgIAIA4gCiAKIA5KGyEKIA4gDSANIA5IGyENIAJBAWoiAiALRw0ACwwDCwJ/IAUqAii7RAAAAAAAQI9AoiIQmUQAAAAAAADgQWMEQCAQqgwBC0GAgICAeAshAgJ/IAUqAhi7RAAAAAAAQI9AoiIQmUQAAAAAAADgQWMEQCAQqgwBC0GAgICAeAshByALIAxNAn8gBSoCCLtEAAAAAABAj0CiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyEPQfj///8HIQpBiICAgHghDQ0CIAwhBQNAIAMgBUECdCIIaiABIAAgCGooAgBBBHRqIggoAgQgB2wgCCgCACAPbGogCCgCCCACbGoiCDYCACAIIAogCCAKSBshCiAIIA0gCCANShshDSAFQQFqIgUgC0cNAAsMAgsgDQRAQfj///8HIQpBiICAgHghDSALIAxNDQIgDCEFA0AgAyAFQQJ0IgFqAn8gAiAAIAFqKAIAQQJ0aioCALtEAAAAAAAAsECiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyIONgIAIAogDiAKIA5IGyEKIA0gDiANIA5KGyENIAVBAWoiBSALRw0ACwwCCyAPRQRAIAsgDE0NASAFKgIoIREgBSoCGCESIAUqAgghE0H4////ByEKQYiAgIB4IQ0gDCEFA0ACfyARIAEgACAFQQJ0IgdqKAIAQQR0aiICKgIIlCATIAIqAgCUIBIgAioCBJSSkrtEAAAAAAAAsECiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyEOIAMgB2ogDjYCACAKIA4gCiAOSBshCiANIA4gDSAOShshDSAFQQFqIgUgC0cNAAsMAgsgCyAMTQ0AQX8hD0H4////ByEKQYiAgIB4IQ0gDCECA0AgDyAHIAAgAkECdCIYaigCAEECdCIZaigCACIORwRAIAUqAjgiESAIIA5BBnRqIg8qAjyUIAUqAigiEiAPKgI4lCAFKgIIIhMgDyoCMJQgBSoCGCIUIA8qAjSUkpKSIRUgESAPKgIslCASIA8qAiiUIBMgDyoCIJQgFCAPKgIklJKSkiEWIBEgDyoCHJQgEiAPKgIYlCATIA8qAhCUIBQgDyoCFJSSkpIhFyARIA8qAgyUIBIgDyoCCJQgEyAPKgIAlCAUIA8qAgSUkpKSIREgDiEPCyADIBhqAn8gFSABIBlBAnRqIg4qAgyUIBYgDioCCJQgESAOKgIAlCAXIA4qAgSUkpKSu0QAAAAAAACwQKIiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLIg42AgAgCiAOIAogDkgbIQogDSAOIA0gDkobIQ0gAkEBaiICIAtHDQALDAELQYiAgIB4IQ1B+P///wchCgsgCyAMSwRAIAlBAWuzIA2yIAqyk5UhESAMIQ0DQAJ/IBEgAyANQQJ0aiIBKAIAIAprspQiEotDAAAAT10EQCASqAwBC0GAgICAeAshDiABIA42AgAgBCAOQQJ0aiIBIAEoAgBBAWo2AgAgDUEBaiINIAtHDQALCyAJQQJPBEAgBCgCACENQQEhCgNAIAQgCkECdGoiASABKAIAIA1qIg02AgAgCkEBaiIKIAlHDQALCyAMQQBKBEAgDCEKA0AgBiAKQQFrIgFBAnQiAmogACACaigCADYCACAKQQFLIAEhCg0ACwsgCyAMSgRAIAshCgNAIAYgCyAEIAMgCkEBayIKQQJ0IgFqKAIAQQJ0aiICKAIAIgVrQQJ0aiAAIAFqKAIANgIAIAIgBUEBazYCACAKIAxKDQALCws=";function wf(e){let t,n,i,s,r,a,o,l,c,h,u,d,p,f,m,g,v,_,x,y;e.onmessage=A=>{if(A.data.centers){let e=A.data.centers,t=A.data.sceneIndexes;s?new Int32Array(n,f+A.data.range.from*y.BytesPerInt*4,4*A.data.range.count).set(new Int32Array(e)):new Float32Array(n,f+A.data.range.from*y.BytesPerFloat*4,4*A.data.range.count).set(new Float32Array(e)),r&&new Uint32Array(n,c+4*A.data.range.from,A.data.range.count).set(new Uint32Array(t)),x=A.data.range.from+A.data.range.count}else if(A.data.sort){const S=Math.min(A.data.sort.splatRenderCount||0,x),b=Math.min(A.data.sort.splatSortCount||0,x),M=A.data.sort.usePrecomputedDistances;let w,T,E;i||(w=A.data.sort.indexesToSort,E=A.data.sort.transforms,M&&(T=A.data.sort.precomputedDistances)),function(x,A,S,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=s?new Int32Array(n,u,w.byteLength/y.BytesPerInt):new Float32Array(n,u,w.byteLength/y.BytesPerFloat),e.set(w)}g||(g=new Uint32Array(_)),new Float32Array(n,m,16).set(S),new Uint32Array(n,p,_).set(g),t.exports.sortIndexes(o,f,u,d,p,m,l,c,h,_,x,A,a,b,s,r);const C={sortDone:!0,splatSortCount:x,splatRenderCount:A,sortTime:0};if(!i){const e=new Uint32Array(n,l,A);(!v||v.length<A)&&(v=new Uint32Array(A)),v.set(e),C.sortedIndexes=v}const R=performance.now();C.sortTime=R-E,e.postMessage(C)}(b,S,A.data.sort.modelViewProj,M,w,T,E)}else if(A.data.init){y=A.data.init.Constants,a=A.data.init.splatCount,i=A.data.init.useSharedMemory,s=A.data.init.integerBasedSort,r=A.data.init.dynamicMode,_=A.data.init.distanceMapRange,x=0;const g=s?4*y.BytesPerInt:4*y.BytesPerFloat,v=new Uint8Array(A.data.init.sorterWasmBytes),S=16*y.BytesPerFloat,b=a*y.BytesPerInt,M=a*g,w=S,T=s?a*y.BytesPerInt:a*y.BytesPerFloat,E=a*y.BytesPerInt,C=a*y.BytesPerInt,R=s?_*y.BytesPerInt*2:_*y.BytesPerFloat*2,I=r?a*y.BytesPerInt:0,D=r?y.MaxScenes*S:0,P=32*y.MemoryPageSize,B=b+M+w+T+E+R+C+I+D+P,L=Math.floor(B/y.MemoryPageSize)+1,U={module:{},env:{memory:new WebAssembly.Memory({initial:L,maximum:L,shared:!0})}};WebAssembly.compile(v).then(e=>WebAssembly.instantiate(e,U)).then(s=>{t=s,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=U.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})})}}}class Tf{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 Ef{constructor(e){}show(){}hide(){}setContainer(e){}setProgress(e){}}class Cf{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 Rf=class e{constructor(e={}){if(i(this,"tempForward",new ci),i(this,"tempMatrixLeft",new Oi),i(this,"tempMatrixRight",new Oi),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 Fn;return function(t){e.copy(this.mousePosition).sub(this.mouseDownPosition);Id()-this.mouseDownTime<.5&&e.length()<2&&this.onMouseClick(t)}}()),i(this,"checkPointRenderDimensions",new Fn),i(this,"checkPointToNewFocalPoint",new ci),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=Id())}}),i(this,"updateSplatMesh",function(){const e=new Fn;return function(){if(!this.splatMesh)return;if(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,s=this.focalAdjustment*i,r=1/s;this.adjustForWebXRStereo(e),this.splatMesh.updateUniforms(e,t*s,n*s,this.camera.isOrthographicCamera,this.camera.zoom||1,r)}}}()),i(this,"addSplatBuffers",(e,t=[],n=!0,i=!0,s=!0,r=!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...")),Pd(()=>{if(this.isDisposingOrDisposed())h();else{const i=this.addSplatBuffersToMesh(e,t,n,s,r,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,s=!1,r=!1,a=!0){if(this.isDisposingOrDisposed())return;let o=[],l=[];r||(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();s&&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 ci,n=new li,i=1e-4;return function(){if(!this.initialized||!this.splatRenderReady||this.isDisposingOrDisposed())return!1;let s=!1,r=!1;if(this.camera){const e=this.camera.position,s=this.camera.quaternion;r=Math.abs(e.x-t.x)>i||Math.abs(e.y-t.y)>i||Math.abs(e.z-t.z)>i||Math.abs(s.x-n.x)>i||Math.abs(s.y-n.y)>i||Math.abs(s.z-n.z)>i||Math.abs(s.w-n.w)>i}return s=this.renderMode!==pd&&(0===e||this.splatMesh.visibleRegionChanging||r||this.renderMode===dd||!0===this.dynamicMode||this.renderNextFrame),this.camera&&(t.copy(this.camera.position),n.copy(this.camera.quaternion)),e++,s}}()),i(this,"render",function(){return 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",Id()),i(this,"fpsFrameCount",0),i(this,"updateFPS",()=>{if(this.consecutiveRenderFrames>60){const e=Id();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 Fn,t=new Fn;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=Id();e||(e=t);const n=t-e;this.updateCameraTransition(t),this.updateFocusMarker(n),e=t}}()),i(this,"tempCameraTarget",new ci),i(this,"toPreviousTarget",new ci),i(this,"toNextTarget",new ci),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 Fn;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 s=Math.min(i+.4*n,1);this.sceneHelper.setFocusMarkerOpacity(s),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 Fn;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 Fn;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 Oi),i(this,"cameraPositionArray",[]),i(this,"lastSortViewDir",new ci(0,0,-1)),i(this,"sortViewDir",new ci(0,0,-1)),i(this,"lastSortViewPos",new ci),i(this,"sortViewOffset",new ci),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,s=!1,r=!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&&(s=!0),i>=1&&(r=!0),s||r)))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 ci,i=new ci,s=new ci,r=new Oi,a=new Oi,o=new Oi,l=new ci,c=new ci(0,0,-1),h=new ci,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*Un.DEG2RAD),p=Math.atan(l.x/2/d),f=Math.atan(l.y/2/d),m=Math.cos(p),g=Math.cos(f),v=this.splatMesh.getSplatTree();if(v){a.copy(this.camera.matrixWorld).invert(),this.splatMesh.dynamicMode||a.multiply(this.splatMesh.matrixWorld);let t=0,l=0;for(let p=0;p<v.subTrees.length;p++){const d=v.subTrees[p];r.copy(a),this.splatMesh.dynamicMode&&(this.splatMesh.getSceneTransform(p,o),r.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;s.copy(o.center).applyMatrix4(r);const p=s.length();s.normalize(),n.copy(s).setX(0).normalize(),i.copy(s).setY(0).normalize();const f=c.dot(i),v=c.dot(n),_=u(o);!h&&(f<m-.6||v<g-.6)&&p>_||(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*yd.BytesPerInt;for(let n=0;n<t;n++){const t=e[n],i=t.data.indexes.length,s=i*yd.BytesPerInt;new Uint32Array(this.sortWorkerIndexesToSort.buffer,d-s,i).set(t.data.indexes),d-=s}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 ci).fromArray(e.cameraUp),e.initialCameraPosition||(e.initialCameraPosition=[0,10,15]),this.initialCameraPosition=(new ci).fromArray(e.initialCameraPosition),e.initialCameraRotation||(e.initialCameraRotation=[0,0,0]),this.initialCameraRotation=(new ci).fromArray(e.initialCameraRotation),this.backgroundColor=e.backgroundColor,e.initialCameraLookAt||(e.initialCameraLookAt=[0,0,0]),this.initialCameraLookAt=(new ci).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||dd,this.sceneRevealMode=e.sceneRevealMode||gd,this.focalAdjustment=e.focalAdjustment||1,this.maxScreenSpaceSplatSize=e.maxScreenSpaceSplatSize||1024,this.logLevel=e.logLevel||hd,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,Fd()){const e=kd();e.major<17&&(this.enableSIMDInSort=!1),e.major<16&&(this.sharedMemoryForWorkers=!1)}void 0!==e.splatRenderMode&&null!==e.splatRenderMode||(e.splatRenderMode=_d),this.splatRenderMode=e.splatRenderMode,this.sceneFadeInRateMultiplier=e.sceneFadeInRateMultiplier||1,this.splatSortDistanceMapPrecision=e.splatSortDistanceMapPrecision||yd.DefaultSplatSortDistanceMapPrecision;const t=this.integerBasedSort?20:24;this.splatSortDistanceMapPrecision=Rd(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 bf,this.infoPanel=null,this.startInOrthographicMode=!1,this.currentFPS=0,this.lastSortTime=0,this.consecutiveRenderFrames=0,this.previousCameraTarget=new ci,this.nextCameraTarget=new ci,this.mousePosition=new Fn,this.mouseDownPosition=new Fn,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 Tf(null,this.rootElement||document.body),this.loadingSpinner.hide(),this.loadingProgressBar=new Ef(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.flame_params=null,this.bone_tree=null,this.lbs_weight_80k=null,this.frame=0,this.useFlame=!0,this.bones=null,this.skeleton=null,this.avatarMesh=null,this.skinModel=null,this.boneRoot=null,this.baseMesh=null,this.setSkinAttibutes=!1,this.dropInMode||this.init()}createSplatMesh(){this.splatMesh=new xp(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.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 Dr,this.sceneHelper=new Cf(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 Fn;this.getRenderDimensions(e),this.perspectiveCamera=new br(50,e.x/e.y,.1,1e3),this.orthographicCamera=new wo(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(Un.degToRad(this.initialCameraRotation.x)),this.camera.rotateY(Un.degToRad(this.initialCameraRotation.y)),this.camera.rotateZ(Un.degToRad(this.initialCameraRotation.z))}}setupRenderer(){if(!this.usingExternalRenderer){const e=new Fn;this.getRenderDimensions(e),this.renderer=new Rh({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 Zu(this.camera,this.renderer.domElement):this.perspectiveControls=new Zu(this.camera,this.renderer.domElement):(this.perspectiveControls=new Zu(this.perspectiveCamera,this.renderer.domElement),this.orthographicControls=new Zu(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=Id()}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 s=e=>{e.saveState(),e.reset()},r=this.controls,a=t?this.orthographicControls:this.perspectiveControls;s(a),s(r),a.target.copy(r.target),t?e.setCameraZoomFromPosition(i,n,r):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&&(n.progressiveLoad=!1);const i=void 0!==n.format&&null!==n.format?n.format:md(t),s=e.isProgressivelyLoadable(i)&&n.progressiveLoad,r=void 0===n.showLoadingUI||null===n.showLoadingUI||n.showLoadingUI;let a=null;r&&(this.loadingSpinner.removeAllTasks(),a=this.loadingSpinner.addTask("Downloading..."));const o=(e,t,n)=>{if(r)if(n===wd)if(100==e)this.loadingSpinner.setMessageForTask(a,"Download complete!");else if(s)this.loadingSpinner.setMessageForTask(a,"Downloading splats...");else{const e=t?`: ${t}`:"...";this.loadingSpinner.setMessageForTask(a,`Downloading${e}`)}else n===Td&&this.loadingSpinner.setMessageForTask(a,"Processing splats...")};let l=!1,c=0;const h=(e,t)=>{r&&((e&&s||t&&!s)&&(this.loadingSpinner.removeTask(a),t||l||this.loadingProgressBar.show()),s&&(t?(l=!0,this.loadingProgressBar.hide()):this.loadingProgressBar.setProgress(c)))};return(s?this.downloadAndBuildSingleSplatSceneProgressiveLoad.bind(this):this.downloadAndBuildSingleSplatSceneStandardLoad.bind(this))(t,i,n.splatAlphaRemovalThreshold,((e,t,i)=>{!s&&n.onProgress&&n.onProgress(0,"0%",Td);const a={rotation:n.rotation||n.orientation,position:n.position,scale:n.scale,splatAlphaRemovalThreshold:n.splatAlphaRemovalThreshold};return this.addSplatBuffers([e],[a],i,t&&r,r,s,s).then(()=>{!s&&n.onProgress&&n.onProgress(100,"100%",Td),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,s,r,a){const o=this.downloadSplatSceneToSplatBuffer(e,n,s,!1,void 0,t,a),l=Ld(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=>{r&&r(),this.clearSplatSceneDownloadAndBuildPromise(),this.removeSplatSceneDownloadPromise(o);const n=t instanceof Cd||"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,s,r,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&&Pd(()=>h())})}},u=this.downloadSplatSceneToSplatBuffer(e,n,s,!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=Ld(d),f=Ld(d);return this.addSplatSceneDownloadPromise(u),this.setSplatSceneDownloadAndBuildPromise(f.promise),u.then(()=>{this.removeSplatSceneDownloadPromise(u)}).catch(e=>{console.error("Viewer::addSplatScene actual error:",e),this.clearSplatSceneDownloadAndBuildPromise(),this.removeSplatSceneDownloadPromise(u);const t=e instanceof Cd||"AbortError"===e.name?e:new Error(`Viewer::addSplatScene -> Could not load one or more scenes: ${e.message}`);p.reject(t),r&&r(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,s=[];let r;t&&(this.loadingSpinner.removeAllTasks(),r=this.loadingSpinner.addTask("Downloading..."));const a=(e,a,o,l)=>{s[e]=a;let c=0;for(let t=0;t<i;t++)c+=s[t]||0;c/=i,o=`${c.toFixed(2)}%`,t&&l===wd&&this.loadingSpinner.setMessageForTask(r,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:md(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(r),n&&n(0,"0%",Td),this.addSplatBuffers(i,e,!0,t,t,!1,!1).then(()=>{n&&n(100,"100%",Td),this.clearSplatSceneDownloadAndBuildPromise()}))).catch(e=>{t&&this.loadingSpinner.removeTask(r),this.clearSplatSceneDownloadAndBuildPromise();throw"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,s=void 0,r,a){const o=!i&&this.optimizeSplatData;try{if(r===fd)return vf.loadFromURL(e,n,i,s,t,this.inMemoryCompressionLevel,o,this.sphericalHarmonicsDegree,a)}catch(l){throw l instanceof yp?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===fd}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,s,r=yd.DefaultSplatSortDistanceMapPrecision){const a=new Worker(URL.createObjectURL(new Blob(["(",wf.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=Fd()?kd():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=Mf:(o=Mf,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:s,distanceMapRange:1<<r,Constants:{BytesPerFloat:yd.BytesPerFloat,BytesPerInt:yd.BytesPerInt,MemoryPageSize:yd.MemoryPageSize,MaxScenes:yd.MaxScenes}}}),a}(i,this.sharedMemoryForWorkers,this.enableSIMDInSort,this.integerBasedSort,this.splatMesh.dynamicMode,this.splatSortDistanceMapPrecision),new Promise(e=>{this.sortWorker.onmessage=s=>{if(s.data.sortDone){if(this.sortRunning=!1,Array.from({length:this.gaussianSplatCount},(e,t)=>t),this.sharedMemoryForWorkers)this.splatMesh.updateRenderIndexes(this.sortWorkerSortedIndexes,s.data.splatRenderCount);else{const e=new Uint32Array(s.data.sortedIndexes.buffer,0,s.data.splatRenderCount);this.splatMesh.updateRenderIndexes(e,s.data.splatRenderCount)}this.lastSplatSortCount=this.splatSortCount,this.lastSortTime=s.data.sortTime,this.sortPromiseResolver(),this.sortPromiseResolver=null,this.forceRenderNextFrame(),this.runAfterNextSort.length>0&&(this.runAfterNextSort.forEach(e=>{e()}),this.runAfterNextSort.length=0)}else if(s.data.sortCanceled)this.sortRunning=!1;else if(s.data.sortSetupPhase1Complete){this.logLevel,this.sharedMemoryForWorkers?(this.sortWorkerSortedIndexes=new Uint32Array(s.data.sortedIndexesBuffer,s.data.sortedIndexesOffset,i),this.sortWorkerIndexesToSort=new Uint32Array(s.data.indexesToSortBuffer,s.data.indexesToSortOffset,i),this.sortWorkerPrecomputedDistances=new t(s.data.precomputedDistancesBuffer,s.data.precomputedDistancesOffset,i),this.sortWorkerTransforms=new Float32Array(s.data.transformsBuffer,s.data.transformsOffset,16*yd.MaxScenes)):(this.sortWorkerIndexesToSort=new Uint32Array(i),this.sortWorkerPrecomputedDistances=new t(i),this.sortWorkerTransforms=new Float32Array(16*yd.MaxScenes));for(let e=0;e<n;e++)this.sortWorkerIndexesToSort[e]=e;if(this.sortWorker.maxSplatCount=i,this.logLevel>=ud){const e=this.splatMesh.getSplatDataTextures(),t=e.covariances.size,n=e.centerColors.size;t.x,t.y,n.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,s)=>{let r;t&&(this.loadingSpinner.removeAllTasks(),this.loadingSpinner.show(),r=this.loadingSpinner.addTask("Removing splat scene..."));const a=()=>{t&&(this.loadingSpinner.hide(),this.loadingSpinner.removeTask(r))},o=e=>{a(),this.splatSceneRemovalPromise=null,e?s(e):i()},l=()=>!!this.isDisposingOrDisposed()&&(o(),!0);n=this.sortPromise||Promise.resolve(),n.then(()=>{if(l())return;const t=[],i=[],s=[];for(let n=0;n<this.splatMesh.scenes.length;n++){let r=!1;for(let t of e)if(t===n){r=!0;break}if(!r){const e=this.splatMesh.scenes[n];t.push(e.splatBuffer),i.push(this.splatMesh.sceneOptions[n]),s.push({position:e.position.clone(),quaternion:e.quaternion.clone(),scale:e.scale.clone()})}}this.disposeSortWorker(),this.splatMesh.dispose(),this.sceneRevealMode=vd,this.createSplatMesh(),this.addSplatBuffers(t,i,!0,!1,!0).then(()=>{l()||(a(),this.splatMesh.scenes.forEach((e,t)=>{e.position.copy(s[t].position),e.quaternion.copy(s[t].quaternion),e.scale.copy(s[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&&(Dd(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")}createBonesFromJson(e){const t=[];function n(e,i=null){const s=new jr;return s.name=e.name,i&&i.add(s),s.position.set(...e.position),t.push(s),e.children&&e.children.forEach(e=>n(e,s)),s}return e.forEach(e=>n(e)),t}updateMorphTarget(e){if(this.avatarMesh=e,this.splatMesh.flameModel=e,this.splatMesh.useFlameModel=this.useFlame,1==this.useFlame){this.bones=this.createBonesFromJson(this.bone_tree.bones);const e=[new ci(this.bones[0].position.x,this.bones[0].position.y,this.bones[0].position.z),new ci(this.bones[1].position.x,this.bones[1].position.y,this.bones[1].position.z),new ci(this.bones[2].position.x,this.bones[2].position.y,this.bones[2].position.z),new ci(this.bones[3].position.x,this.bones[3].position.y,this.bones[3].position.z),new ci(this.bones[4].position.x,this.bones[4].position.y,this.bones[4].position.z)];this.bones[1].position.copy(new ci(e[1].x-e[0].x,e[1].y-e[0].y,e[1].z-e[0].z)),this.bones[2].position.copy(new ci(e[2].x-e[1].x,e[2].y-e[1].y,e[2].z-e[1].z)),this.bones[3].position.copy(new ci(e[3].x-e[1].x,e[3].y-e[1].y,e[3].z-e[1].z)),this.bones[4].position.copy(new ci(e[4].x-e[1].x,e[4].y-e[1].y,e[4].z-e[1].z)),this.bones[0].updateMatrixWorld(!0);const t=[this.bones[0].matrixWorld.clone().invert(),this.bones[1].matrixWorld.clone().invert(),this.bones[2].matrixWorld.clone().invert(),this.bones[3].matrixWorld.clone().invert(),this.bones[4].matrixWorld.clone().invert()];this.skeleton=new Kr(this.bones,t)}this.runMorphUpdate(),this.splatMesh.gaussianSplatCount=this.gaussianSplatCount}updatedBoneMatrices(e){let t=[];for(let n=0;n<e;n++){let e,i=function(e,t){let n=e.elements;for(let i=0;i<n.length;i++)t.push(n[i])};e=this.skeleton.bones[n].matrixWorld.clone().multiply(this.skeleton.boneInverses[n].clone()),i(e,t)}return new Float32Array(t)}runMorphUpdate(){this.gaussianSplatCount=this.avatarMesh.geometry.attributes.position.count;var e=new Float32Array(this.avatarMesh.geometry.attributes.position.array);if(this.splatMesh.bonesNum=5,0==this.useFlame){if(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 Yr(new t.array.constructor(t.array),4,t.normalized,1),s=new Yr(new n.array.constructor(n.array),4,n.normalized,1);i.setUsage(yn),s.setUsage(yn),e.setAttribute("skinIndex",i),e.setAttribute("skinWeight",s)}}else this.updateFlameBones();this.splatMesh.morphedMesh=e;let t=this.splatMesh.morphedMesh.length/3;null!=this.splatMesh.splatDataTextures.flameModel&&this.splatMesh.updateTetureAfterBSAndSkeleton(0,t-1,this.useFlame)}updateFlameBones(){function e(e,t,n=!1){let i;if(1==n)i=new li(t[0],t[1],t[2],t[3]);else{const e=new ci(t[0],t[1],t[2]),n=e.length(),s=e.normalize();i=(new li).setFromAxisAngle(s,n)}e.quaternion.copy(i),e.updateMatrixWorld(!0)}this.splatMesh.bsWeight=this.flame_params.expr[this.frame];let t=this.flame_params.rotation[this.frame];e(this.skeleton.bones[0],t),t=this.flame_params.neck_pose[this.frame],e(this.skeleton.bones[1],t),t=this.flame_params.jaw_pose[this.frame],e(this.skeleton.bones[2],t),t=this.flame_params.eyes_pose[this.frame],e(this.skeleton.bones[3],t),e(this.skeleton.bones[4],[t[3],t[4],t[5]]),this.skeleton.update();const n=this.updatedBoneMatrices(5);this.splatMesh.bonesMatrix=n,this.splatMesh.bonesNum=5,this.splatMesh.bonesWeight=this.lbs_weight_80k}};i(Rf,"setCameraPositionFromZoom",function(){const e=new ci;return function(t,n,i){const s=1/(.001*n.zoom);e.copy(i.target).sub(t.position).normalize().multiplyScalar(s).negate(),t.position.copy(i.target).add(e)}}()),i(Rf,"setCameraZoomFromPosition",function(){const e=new ci;return function(t,n,i){const s=e.copy(i.target).sub(n.position).length();t.zoom=1/(.001*s)}}());let If=Rf;const Df={x:0,y:1.8,z:1},Pf={x:-10,y:0,z:0},Bf="ffffff",Lf="false",Uf={offset:{},scale:{}},Ff={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:[]},kf=class e{static async getInstance(t,n,i={}){if(void 0!==this.instance)return this.instance;try{const s=n,r=new URL(s,window.location.href),a=r.pathname.match(/\/([^/]+?)\.zip/);if(!(a&&a[1]))throw new Error("character model is not found");"undefined"!=typeof NProgress&&NProgress.start();const o=await fetch(s);if(!o.ok)throw new Error(`Failed to download: ${o.statusText}`);i.downloadProgress&&i.downloadProgress(1),i.loadProgress&&i.loadProgress(.1),"undefined"!=typeof NProgress&&NProgress.done();const l=await o.arrayBuffer(),c=await Bu.loadAsync(l);let h="";if(Object.values(c.files).forEach(e=>{e.dir&&(h=e.name?.slice(0,e.name?.length-1))}),!h)throw new Error("file folder is not found");const u=new e(t,c),d=new ci;d.x=Df?.x||0,d.y=Df?.y||0,d.z=Df?.z||1;const p=new ci;p.x=Pf?.x||0,p.y=Pf?.y||0,p.z=Pf?.z||0;let f=16777215;Bf&&(f=parseInt(Bf,16)),i?.backgroundColor&&u.isHexColorStrict(i.backgroundColor)&&(f=parseInt(i.backgroundColor,16)),u.getChatState=i?.getChatState,u.getExpressionData=i?.getExpressionData,Lf&&(u.useFlame="false"!==Lf),u.viewer=new If({rootElement:t,threejsCanvas:e._canvas,cameraUp:[0,1,0],initialCameraPosition:[d.x,d.y,d.z],initialCameraRotation:[p.x,p.y,p.z],sphericalHarmonicsDegree:0,backgroundColor:f}),u.viewer.useFlame=u.useFlame,!0===u.viewer.useFlame?await u.loadFlameModel(h,Uf):await u.loadModel(h,Ff,Uf),i.loadProgress&&i.loadProgress(.2);const m=await u.unpackFileAsBlob(h+"/offset.ply");return i.loadProgress&&i.loadProgress(.3),await u.viewer.addSplatScene(m,{progressiveLoad:!0,sharedMemoryForWorkers:!1,showLoadingUI:!1,format:fd}),u.render(),i.loadProgress&&i.loadProgress(1),this.instance=u,u}catch(s){throw console.error("GaussianSplatRenderer.getInstance error:",s),s}}constructor(t,n){if(this.zipUrls={urls:new Map,zip:n},this.useFlame=!1,this.lastTime=0,this.startTime=0,this.expressionData={},this.chatState=Qd,e._canvas&&t){const{width:n,height:i}=t.getBoundingClientRect();e._canvas.style.visibility="visible",e._canvas.width=n,e._canvas.height=i,t.appendChild(e._canvas)}this.clock=new Po,this.startTime=performance.now()/1e3,this.viewer=null,this.mixer=null,this.animManager=null,this.model=null,this.motioncfg=null,this.getChatState=null,this.getExpressionData=null}dispose(){e._canvas&&(e._canvas.style.visibility="hidden"),this.disposeModel(),this.zipUrls.urls.forEach(e=>{URL.revokeObjectURL(e)}),e.instance=void 0}disposeModel(){this.mixer&&(this.mixer.stopAllAction(),this.viewer?.avatarMesh&&this.mixer.uncacheRoot(this.viewer.avatarMesh),this.mixer=void 0,this.animManager?.dispose()),this.viewer?.dispose()}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),s=Math.floor(i/e);if(this.viewer.frame=s,this.getChatState&&(this.chatState=this.getChatState(),this._lastLoggedState&&this._lastLoggedState===this.chatState||(this.chatState,this.animManager,this._lastLoggedState=this.chatState),this.animManager?.update(this.chatState)),this.getExpressionData&&(this.expressionData=this.updateBS(this.getExpressionData())),!1===this.viewer.useFlame)if(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||(console.warn("render: mixer or animManager not initialized, skipping animation update"),this.viewer.useFlame,this.mixer,this.animManager,this._warnedOnce=!0);this.viewer.update(this.viewer.renderer,this.viewer.camera);const r=this.viewer.shouldRender();this._renderLogCount,r?(this.viewer.render(),this.viewer.consecutiveRenderFrames++):this.viewer.consecutiveRenderFrames=0,this.viewer.renderNextFrame=!1,this.viewer.selfDrivenModeRunning=!0}}isHexColorStrict(e){if("string"!=typeof e)return!1;return/^(#|0x)[0-9A-Fa-f]{6}$/i.test(e)}setExpression(){this.viewer?.splatMesh&&(this.viewer.splatMesh.bsWeight=this.expressionData),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],s=this.expressionData[n];void 0!==s&&(e.morphTargetInfluences[i]=Math.max(0,Math.min(1,s)))}}}})}async loadFlameModel(e,t){const[n,i,s,r,a]=await Promise.all([this.unpackAndLoadGlb(e+"/skin.glb"),this.unpackAndLoadJson(e+"/lbs_weight_20k.json"),this.unpackAndLoadJson(e+"/flame_params.json"),this.unpackAndLoadJson(e+"/vertex_order.json"),this.unpackAndLoadJson(e+"/bone_tree.json")]);if(!this.viewer)throw new Error("render viewer is not initialized");let o,l;n.traverse(e=>{e.isSkinnedMesh&&(o=e),e instanceof jr&&"hip"===e.name&&(l=e)}),this.viewer.sortedIndexes=r,this.viewer.flame_params=s,this.viewer.lbs_weight_80k=i,this.viewer.bone_tree=a,this.viewer.totalFrames=s.expr?.length||1,o&&(this.viewer.gaussianSplatCount=o.geometry.attributes.position.count),this.viewer.avatarMesh=n,this.viewer.skinModel=o,this.viewer.boneRoot=l,this.motioncfg=t,o&&this.viewer.updateMorphTarget(o),this.viewer.threeScene.add(n),n.visible=!1,o&&o.skeleton.computeBoneTexture()}async loadModel(e,t,n){const[i,s,r]=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 jr&&"hip"===e.name&&(o=e)}),this.viewer.sortedIndexes=r,a&&(this.viewer.gaussianSplatCount=a.geometry.attributes.position.count),this.viewer.avatarMesh=i,this.viewer.skinModel=a,this.viewer.boneRoot=o,this.mixer=new Wo(i),this.animManager=new rp(this.mixer,s,t),this.motioncfg=n,Array.isArray(s)&&s.length>0&&s[0].duration?this.viewer.totalFrames=Math.floor(30*s[0].duration):this.viewer.totalFrames=1,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.zipUrls.urls.has(e)){const t=await(this.zipUrls.zip?.file(e)?.async("blob"));if(t){const n=URL.createObjectURL(t);this.zipUrls.urls.set(e,n)}}return this.zipUrls.urls.get(e)}async unpackAndLoadGlb(e){if(!this.zipUrls.urls.has(e)){const t=await(this.zipUrls.zip?.file(e)?.async("arraybuffer"));if(t){const n=new Blob([t],{type:"model/gltf-binary"}),i=URL.createObjectURL(n);this.zipUrls.urls.set(e,i)}}return this.LoadGLTF(this.zipUrls.urls.get(e))}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 Dh).load(e,e=>{e.animations.length>0?t(e.animations):t(e.scene)},void 0,e=>{n(e)})})}};i(kf,"_canvas","undefined"!=typeof document?document.createElement("canvas"):null),i(kf,"instance");let Nf=kf;!function(){const e=new Float32Array(1),t=new Int32Array(e.buffer)}();const Of=v.scope("GaussianAvatar"),zf=[[.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]],Hf={Idle:[2e3,4e3],Hello:[1800,3500],Responding:[1300,3300]};const Vf=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=zf[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 Nf.getInstance(this._avatarDivEle,this._assetsPath,{getChatState:this.getChatState.bind(this),getExpressionData:this.getArkitFaceFrame.bind(this),backgroundColor:"0xffffff"}),this.startTime=performance.now()/1e3,Of.info("Avatar ready, initial state:",this.curState)}pause(){this.isPaused=!0,Of.debug("Avatar paused")}resume(){this.isPaused=!1,Of.debug("Avatar resumed")}getChatState(){return this.curState}setChatState(e){if(this.curState!==e){const t=(new Date).toLocaleTimeString();Of.info(`[${t}] Avatar state: ${this.curState} → ${e}`),this.curState=e}}enableLiveBlendshapes(){Of.debug("Live blendshapes mode active")}disableLiveBlendshapes(){this.liveBlendshapeData=null,Of.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]=Hf[this.curState]||Hf.Idle;if(-1===this.blinkFrame&&t-this.lastBlinkTime>=this.nextBlinkInterval&&(this.blinkFrame=0,this.lastBlinkFrameTime=t,this.currentBlinkPattern=zf[Math.floor(Math.random()*zf.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,Of.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.cjs.map