@myned-ai/gsplat-flame-avatar-renderer 1.0.5 → 1.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +130 -32
- package/dist/gsplat-flame-avatar-renderer.cjs.js +3478 -722
- package/dist/gsplat-flame-avatar-renderer.cjs.min.js +2 -0
- package/dist/gsplat-flame-avatar-renderer.cjs.min.js.map +1 -0
- package/dist/gsplat-flame-avatar-renderer.esm.js +3439 -724
- package/dist/gsplat-flame-avatar-renderer.esm.min.js +2 -0
- package/dist/gsplat-flame-avatar-renderer.esm.min.js.map +1 -0
- package/package.json +10 -6
- package/src/core/SplatMesh.js +53 -46
- package/src/core/Viewer.js +47 -196
- package/src/errors/ApplicationError.js +185 -0
- package/src/errors/index.js +17 -0
- package/src/flame/FlameAnimator.js +282 -57
- package/src/loaders/PlyLoader.js +302 -44
- package/src/materials/SplatMaterial.js +13 -10
- package/src/materials/SplatMaterial3D.js +72 -27
- package/src/renderer/AnimationManager.js +8 -5
- package/src/renderer/GaussianSplatRenderer.js +668 -217
- package/src/utils/BlobUrlManager.js +294 -0
- package/src/utils/EventEmitter.js +349 -0
- package/src/utils/LoaderUtils.js +2 -1
- package/src/utils/Logger.js +171 -0
- package/src/utils/ObjectPool.js +248 -0
- package/src/utils/RenderLoop.js +306 -0
- package/src/utils/Util.js +59 -18
- package/src/utils/ValidationUtils.js +331 -0
- package/src/utils/index.js +10 -1
- package/dist/gsplat-flame-avatar-renderer.cjs.js.map +0 -1
- package/dist/gsplat-flame-avatar-renderer.esm.js.map +0 -1
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var e=require("three"),t=require("three/examples/jsm/loaders/GLTFLoader.js"),s=require("jszip"),i=require("three/examples/jsm/controls/OrbitControls.js");function n(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(s){if("default"!==s){var i=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,i.get?i:{enumerable:!0,get:function(){return e[s]}})}}),t.default=e,Object.freeze(t)}var r=n(e);const a={None:0,Error:1,Warning:2,Info:3,Debug:4},o={Always:0,OnChange:1,Never:2},l={Ply:0},c=e=>e.endsWith(".ply")?l.Ply:null,h={Default:0,Gradual:1,Instant:2},d={ThreeD:0,TwoD:1};let u=class{static DefaultSplatSortDistanceMapPrecision=16;static MemoryPageSize=65536;static BytesPerFloat=4;static BytesPerInt=4;static MaxScenes=32;static ProgressiveLoadSectionSize=262144;static ProgressiveLoadSectionDelayDuration=15;static SphericalHarmonics8BitCompressionRange=3};const p=u.SphericalHarmonics8BitCompressionRange,m=15e5,g={DirectToSplatBuffer:0,DirectToSplatArray:1,DownloadBeforeProcessing:2},A={Downloading:0,Processing:1,Done:2};class f extends Error{constructor(e,t,s=null){super(e),this.name=this.constructor.name,this.code=t,this.cause=s,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,message:this.message,code:this.code,stack:this.stack,cause:this.cause?{name:this.cause.name,message:this.cause.message}:null}}}class S extends f{constructor(e,t,s=null){super(e,"VALIDATION_ERROR",s),this.field=t}}class C extends f{constructor(e,t=0,s=null){super(e,"NETWORK_ERROR",s),this.statusCode=t}}class x extends f{constructor(e,t,s=null){super(e,"ASSET_LOAD_ERROR",s),this.assetPath=t}}class y extends f{constructor(e){super(`Cannot use ${e}: resource has been disposed`,"RESOURCE_DISPOSED_ERROR"),this.resourceName=e}}class v extends f{constructor(e,t,s=null){super(e,"INITIALIZATION_ERROR",s),this.component=t}}let I=class extends f{constructor(e,t,s=null){super(e,"PARSE_ERROR",s),this.dataType=t}};const b=Object.freeze({DEBUG:0,INFO:1,WARN:2,ERROR:3,NONE:4});class w{constructor(e,t=b.INFO){this.namespace=e,this.minLevel=t}setLevel(e){this.minLevel=e}_format(e,t){return[`[${(new Date).toISOString()}] [${e}] [${this.namespace}]`,...t]}debug(...e){this.minLevel<=b.DEBUG&&this._format("DEBUG",e)}info(...e){this.minLevel<=b.INFO&&console.info(...this._format("INFO",e))}warn(...e){this.minLevel<=b.WARN&&console.warn(...this._format("WARN",e))}error(...e){this.minLevel<=b.ERROR&&console.error(...this._format("ERROR",e))}errorWithTrace(e,t=""){if(this.minLevel<=b.ERROR){const s=t?` Context: ${t}`:"";console.error(...this._format("ERROR",[`${e.message}${s}`,"\nStack:",e.stack]))}}child(e){return new w(`${this.namespace}:${e}`,this.minLevel)}}const B=new Map;let T=b.INFO;function D(e){T=e;for(const t of B.values())t.setLevel(e)}function E(e){return B.has(e)||B.set(e,new w(e,T)),B.get(e)}E("App");const M=E("Util");class R extends Error{constructor(e){super(e),this.name="AbortedPromiseError",this.code="ABORTED"}}const F=function(e,t,s=!0,i){const n=new AbortController,r=n.signal;let a=!1,o=!1;const l=(e,s,i,n)=>{if(t&&!o)try{t(e,s,i,n),100===e&&(o=!0)}catch(e){M.error("Error in progress callback:",e)}},c=new Promise((t,n)=>{const o={signal:r};i&&(o.headers=i),fetch(e,o).then(async e=>{if(!e.ok){let t="";try{t=await e.text()}catch{}return void n(new C(`Fetch failed: ${e.statusText}${t?" - "+t:""}`,e.status))}const i=e.body?.getReader();if(!i)return void n(new C("Response body is not readable",0));let r=0;const o=e.headers.get("Content-Length"),c=o?parseInt(o,10):void 0,h=[];for(;!a;)try{const{value:e,done:n}=await i.read();if(n){if(l(100,"100%",e,c),s){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)}%`),s&&h.push(e),l(a,o,e,c)}catch(e){return void n(new C(`Error reading response stream: ${e.message}`,0,e))}}).catch(e=>{e instanceof C?n(e):"AbortError"===e.name?n(new C("Fetch aborted by user",0,e)):n(new C(`Fetch failed: ${e.message||"Unknown error"}`,0,e))})});return c.abort=e=>{a=!0,n.abort(e)},c.abortController=n,c},P=function(e,t,s){return Math.max(Math.min(e,s),t)},k=function(){return performance.now()/1e3},_=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)_(t)},L=(e,t)=>new Promise(s=>{window.setTimeout(()=>{s(e())},t?1:50)}),U=(e=0)=>{switch(e){case 1:return 9;case 2:return 24}return 0},O=()=>{let e,t;return{promise:new Promise((s,i)=>{e=s,t=i}),resolve:e,reject:t}},H=e=>{let t,s;const i=new Promise((e,i)=>{t=e,s=i});return i.abort=e||(()=>{}),{promise:i,resolve:t,reject:s}};class z{constructor(e,t,s){this.major=e,this.minor=t,this.patch=s}toString(){return`${this.major}_${this.minor}_${this.patch}`}}function Q(){const e=navigator.userAgent;return e.indexOf("iPhone")>0||e.indexOf("iPad")>0}function V(){if(Q()){const e=navigator.userAgent.match(/OS (\d+)_(\d+)_?(\d+)?/);return new z(parseInt(e[1]||0,10),parseInt(e[2]||0,10),parseInt(e[3]||0,10))}return null}const N=e.DataUtils.toHalfFloat.bind(e.DataUtils),G=e.DataUtils.fromHalfFloat.bind(e.DataUtils),W=p/2,q=(e,t,s)=>{e=P(e,t,s);const i=s-t;return P(Math.floor((e-t)/i*255),0,255)},K=(e,t,s)=>e/255*(s-t)+t,j=(e,t,s)=>q(G(e),t,s),Y=(e,t,s)=>N(K(e,t,s)),J=function(){const e=e=>e;return function(t,s,i,n=!1){if(s===i)return t;let r=e;return 2===s&&n?1===i?r=Y:0===i&&(r=K):2===s||1===s?0===i?r=G:2===i&&(r=n?j:e):0===s&&(1===i?r=N:2===i&&(r=n?q:N)),r(t)}}(),X=function(){const e=new Float32Array(1),t=new Int32Array(e.buffer);return function(s){e[0]=s;const i=t[0];let n=i>>16&32768,r=i>>12&2047;const a=i>>23&255;return a<103?n:a>142?(n|=31744,n|=(255==a?0:1)&&8388607&i,n):a<113?(r|=2048,n|=(r>>114-a)+(r>>113-a&1),n):(n|=a-112<<10|r>>1,n+=1&r,n)}}(),$=function(){const e=new Float32Array(1),t=new Int32Array(e.buffer);return function(s){return e[0]=s,t[0]}}(),Z=function(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24)},ee=Object.freeze(["https:","http:","blob:","data:"]);function te(e,t){if("string"!=typeof e||0===e.length)throw new S("URL must be a non-empty string","url");let s;try{const i=t||("undefined"!=typeof window?window.location.href:void 0);s=new URL(e,i)}catch(t){throw new S(`Invalid URL format: ${e}`,"url",t)}if(!ee.includes(s.protocol))throw new S(`Disallowed protocol: ${s.protocol}. Allowed protocols: ${ee.join(", ")}`,"url.protocol");return s.href}function se(e,t){if("number"!=typeof e||!Number.isInteger(e))throw new S(`${t} must be an integer`,t);return e}function ie(e,t,s){if(null===e||"object"!=typeof e)throw new S(`${s} must be an object`,s);for(const i of t)if(!(i in e)||void 0===e[i])throw new S(`${s} missing required property: ${i}`,`${s}.${i}`);return e}function ne(e,t,s=0){if(!(e instanceof ArrayBuffer))throw new S(`${t} must be an ArrayBuffer`,t);if(e.byteLength<s)throw new S(`${t} must be at least ${s} bytes, got ${e.byteLength}`,t);return e}function re(e,t,s=!0){if(null==e){if(s)throw new S(`${t} is required`,t);return null}if("function"!=typeof e)throw new S(`${t} must be a function`,t);return e}function ae(e,t){if("string"!=typeof e)throw new S(`${t} must be a string`,t);if(!/^(#|0x)[0-9A-Fa-f]{6}$/i.test(e))throw new S(`${t} must be a valid hex color (e.g., #FFFFFF or 0xFFFFFF)`,t);return e}function oe(e,t){if("undefined"!=typeof HTMLElement&&!(e instanceof HTMLElement))throw new S(`${t} must be a valid HTML element`,t);return e}class le{constructor(e,t,s=10){this._factory=e,this._reset=t,this._pool=[],this._allocated=0,this._maxSize=10*s;for(let t=0;t<s;t++)this._pool.push(e())}acquire(){return this._allocated++,this._pool.length>0?this._pool.pop():this._factory()}release(e){this._allocated--,this._pool.length<this._maxSize&&(this._reset(e),this._pool.push(e))}releaseAll(e){for(const t of e)this.release(t)}getStats(){return{available:this._pool.length,allocated:this._allocated,maxSize:this._maxSize}}dispose(){this._pool.length=0,this._allocated=0}}const ce=new le(()=>new e.Vector3,e=>e.set(0,0,0),50),he=new le(()=>new e.Matrix4,e=>e.identity(),20),de=new le(()=>new e.Quaternion,e=>e.set(0,0,0,1),30),ue=new le(()=>new e.Euler,e=>e.set(0,0,0),30),pe=new e.Vector3,me=new e.Vector3,ge=new e.Vector3,Ae=new e.Matrix4,fe=new e.Matrix4,Se=new e.Quaternion,Ce=new e.Quaternion,xe=E("BlobUrlManager");class ye{constructor(){this._urls=new Map,this._disposed=!1}_assertNotDisposed(){if(this._disposed)throw new Error("BlobUrlManager has been disposed")}createBlobUrl(e,t,s=""){if(this._assertNotDisposed(),"string"!=typeof t||0===t.length)throw new S("mimeType must be a non-empty string","mimeType");let i;if(e instanceof Blob)i=e;else{if(!(e instanceof ArrayBuffer||e instanceof Uint8Array))throw new S("data must be Blob, ArrayBuffer, or Uint8Array","data");i=new Blob([e],{type:t})}const n=URL.createObjectURL(i);return this._urls.set(n,{createdAt:Date.now(),mimeType:t,label:s||"unlabeled",size:i.size}),xe.debug(`Created blob URL: ${s||n.substring(0,50)}, size: ${i.size} bytes`),n}registerBlobUrl(e,t=""){if(this._assertNotDisposed(),"string"!=typeof e||!e.startsWith("blob:"))throw new S("url must be a valid blob URL","url");this._urls.has(e)||(this._urls.set(e,{createdAt:Date.now(),mimeType:"unknown",label:t||"registered-external",size:0}),xe.debug(`Registered external blob URL: ${t||e.substring(0,50)}`))}revokeBlobUrl(e){if(this._assertNotDisposed(),this._urls.has(e)){const t=this._urls.get(e);return URL.revokeObjectURL(e),this._urls.delete(e),xe.debug(`Revoked blob URL: ${t.label}, age: ${Date.now()-t.createdAt}ms`),!0}return!1}revokeAll(){this._assertNotDisposed(),xe.debug(`Revoking ${this._urls.size} blob URLs`);for(const e of this._urls.keys())URL.revokeObjectURL(e);this._urls.clear()}getMetadata(e){return this._urls.get(e)||null}getAllTrackedUrls(){const e=[];for(const[t,s]of this._urls.entries())e.push({url:t,metadata:s});return e}getStats(){let e=0,t=0;const s=Date.now();for(const i of this._urls.values()){e+=i.size;const n=s-i.createdAt;n>t&&(t=n)}return{count:this._urls.size,totalSize:e,oldestAge:t}}revokeOlderThan(e){this._assertNotDisposed();const t=Date.now(),s=[];for(const[i,n]of this._urls.entries())t-n.createdAt>e&&s.push(i);for(const e of s)this.revokeBlobUrl(e);return s.length>0&&xe.info(`Revoked ${s.length} blob URLs older than ${e}ms`),s.length}isTracked(e){return this._urls.has(e)}dispose(){this._disposed||(xe.debug("Disposing BlobUrlManager"),this.revokeAll(),this._disposed=!0)}}const ve=new ye,Ie=E("RenderLoop"),be=E("EventEmitter");class we{constructor(){this._listeners=new Map,this._disposed=!1,this._eventHistory=[],this._maxHistorySize=50}_assertNotDisposed(){if(this._disposed)throw new Error("EventEmitter has been disposed")}on(e,t,s={}){if(this._assertNotDisposed(),"string"!=typeof e||0===e.length)throw new S("event must be a non-empty string","event");if("function"!=typeof t)throw new S("callback must be a function","callback");const i=s.once?(...s)=>{this.off(e,i),t(...s)}:t;return s.once&&(i._originalCallback=t),this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(i),be.debug(`Subscribed to event: ${e}`),()=>this.off(e,i)}once(e,t){return this.on(e,t,{once:!0})}off(e,t){this._assertNotDisposed();const s=this._listeners.get(e);if(!s)return!1;if(s.delete(t))return be.debug(`Unsubscribed from event: ${e}`),!0;for(const i of s)if(i._originalCallback===t)return s.delete(i),be.debug(`Unsubscribed from event: ${e} (once listener)`),!0;return!1}removeAllListeners(e=null){if(this._assertNotDisposed(),e){const t=this._listeners.get(e)?.size||0;this._listeners.delete(e),be.debug(`Removed ${t} listeners for event: ${e}`)}else{const e=Array.from(this._listeners.values()).reduce((e,t)=>e+t.size,0);this._listeners.clear(),be.debug(`Removed all ${e} listeners`)}}emit(e,...t){this._assertNotDisposed();const s=this._listeners.get(e);if(!s||0===s.size)return!1;this._recordEvent(e,t);let i=0;for(const n of s)try{n(...t),i++}catch(t){be.error(`Error in event listener for '${e}':`,t)}return be.debug(`Emitted event: ${e} to ${i} listeners`),!0}_recordEvent(e,t){this._eventHistory.push({event:e,timestamp:Date.now(),argCount:t.length}),this._eventHistory.length>this._maxHistorySize&&this._eventHistory.shift()}getEventHistory(){return[...this._eventHistory]}hasListeners(e){const t=this._listeners.get(e);return!!t&&t.size>0}listenerCount(e){const t=this._listeners.get(e);return t?t.size:0}eventNames(){return Array.from(this._listeners.keys())}getStats(){const e={totalEvents:this._listeners.size,totalListeners:0,eventBreakdown:{}};for(const[t,s]of this._listeners.entries()){const i=s.size;e.totalListeners+=i,e.eventBreakdown[t]=i}return e}dispose(){this._disposed||(be.debug("Disposing EventEmitter"),this.removeAllListeners(),this._eventHistory.length=0,this._disposed=!0)}}const Be={Idle:"Idle",Listening:"Listening",Responding:"Responding",Thinking:"Thinking"},Te=["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"],De=["root","neck","jaw","leftEye","rightEye"],Ee=Te.length,Me=De.length,Re=E("AnimationManager");class Fe{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 Pe extends Fe{constructor(e,t){super(e,t)}update(t){if(this.actions&&0!==this.actions.length&&(void 0===Oe.CurPlaying&&t===Be.Idle&&!1===this.isPlaying&&(this.stage=0,this.actions[this.stage].time=0,Oe.SetWeight(this.actions[this.stage],1),this.actions[this.stage].loop=e.LoopRepeat,this.actions[this.stage].clampWhenFinished=!1,this.actions[this.stage].paused=!1,this.actions[this.stage].play(),void 0!==Oe.LastAction&&Oe.PrepareCrossFade(Oe.LastAction,this.actions[this.stage],this.blendingTime),this.isPlaying=!0),Oe.CurPlaying===Be.Idle&&t===Be.Idle&&!0===this.isPlaying&&this.actions[this.stage].time>this.actions[this.stage].getClip().duration-this.blendingTime)){let t=this.stage+1;t>=this.actions.length&&(t=0),this.actions[t].time=0,Oe.SetWeight(this.actions[t],1),this.actions[t].loop=e.LoopRepeat,this.actions[t].play(),Oe.PrepareCrossFade(this.actions[this.stage],this.actions[t],this.blendingTime),this.stage=t}}}class ke extends Fe{constructor(e,t){super(e,t)}update(t){this.actions&&0!==this.actions.length&&(void 0===Oe.CurPlaying&&t===Be.Idle&&!1===this.isPlaying&&(this.stage=0,this.actions[this.stage].time=0,Oe.SetWeight(this.actions[this.stage],1),this.actions[this.stage].loop=e.LoopRepeat,this.actions[this.stage].clampWhenFinished=!1,this.actions[this.stage].paused=!1,this.actions[this.stage].play(),void 0!==Oe.LastAction&&Oe.PrepareCrossFade(Oe.LastAction,this.actions[this.stage],this.blendingTime),this.isPlaying=!0),Oe.CurPlaying===Be.Idle&&t!==Be.Idle&&!0===this.isPlaying&&0===this.stage&&(this.actions[this.stage].loop=e.LoopOnce,this.actions[this.stage].clampWhenFinished=!0,this.isPlaying=!1,Oe.LastAction=this.actions[this.stage]))}}class _e extends Fe{constructor(e,t){super(e,t)}update(t){this.actions&&0!==this.actions.length&&(void 0===Oe.CurPlaying&&t===Be.Listening&&!1===this.isPlaying&&(this.stage=0,this.actions[this.stage].time=0,this.actions[this.stage].play(),Oe.SetWeight(this.actions[this.stage],1),this.actions[this.stage].loop=this.isGroup?e.LoopOnce:e.LoopRepeat,this.actions[this.stage].clampWhenFinished=!!this.isGroup,void 0!==Oe.LastAction&&Oe.PrepareCrossFade(Oe.LastAction,this.actions[this.stage],this.blendingTime),this.isPlaying=!0),this.isGroup&&(Oe.CurPlaying===Be.Listening&&t===Be.Listening&&!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,Oe.SetWeight(this.actions[this.stage+1],1),this.actions[this.stage+1].loop=e.LoopRepeat,this.actions[this.stage+1].play(),Oe.PrepareCrossFade(this.actions[this.stage],this.actions[this.stage+1],this.blendingTime),this.stage=1),Oe.CurPlaying!==Be.Listening||t===Be.Listening||!0!==this.isPlaying||0!==this.stage&&1!==this.stage||(this.actions[2].time=0,this.actions[2].play(),Oe.SetWeight(this.actions[2],1),this.actions[2].loop=e.LoopOnce,Oe.PrepareCrossFade(this.actions[this.stage],this.actions[2],this.blendingTime),this.stage=2)),Oe.CurPlaying===Be.Listening&&t!==Be.Listening&&!0===this.isPlaying&&this.stage===(this.isGroup?this.actions.length-1:0)&&(this.actions[this.stage].loop=e.LoopOnce,this.actions[this.stage].clampWhenFinished=!0,this.isPlaying=!1,Oe.LastAction=this.actions[this.stage]))}}class Le extends Fe{constructor(e,t){super(e,t)}update(t){this.actions&&0!==this.actions.length&&(void 0===Oe.CurPlaying&&t===Be.Thinking&&!1===this.isPlaying&&(this.stage=0,this.actions[this.stage].time=0,this.actions[this.stage].play(),Oe.SetWeight(this.actions[this.stage],1),this.actions[this.stage].loop=e.LoopOnce,void 0!==Oe.LastAction&&Oe.PrepareCrossFade(Oe.LastAction,this.actions[this.stage],this.blendingTime),this.isPlaying=!0),this.isGroup&&(Oe.CurPlaying===Be.Thinking&&t===Be.Thinking&&!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,Oe.SetWeight(this.actions[this.stage+1],1),this.actions[this.stage+1].loop=e.LoopRepeat,this.actions[this.stage+1].play(),Oe.PrepareCrossFade(this.actions[this.stage],this.actions[this.stage+1],this.blendingTime),this.stage=1),Oe.CurPlaying!==Be.Thinking||t===Be.Thinking||!0!==this.isPlaying||0!==this.stage&&1!==this.stage||(this.actions[2].time=0,this.actions[2].play(),Oe.SetWeight(this.actions[2],1),this.actions[2].loop=e.LoopOnce,Oe.PrepareCrossFade(this.actions[this.stage],this.actions[2],this.blendingTime),this.stage=2)),Oe.CurPlaying===Be.Thinking&&t!==Be.Thinking&&!0===this.isPlaying&&this.stage===(this.isGroup?this.actions.length-1:0)&&(this.actions[this.stage].loop=e.LoopOnce,this.actions[this.stage].clampWhenFinished=!0,this.isPlaying=!1,Oe.LastAction=this.actions[this.stage]))}}class Ue extends Fe{constructor(e,t){super(e,t),Re.debug("[SPEAK] Initialized with",e?.length||0,"actions, isGroup:",t)}getRandomNumber(e,t){const s=e-t;return t+Math.round(Math.random()*s)}update(t){if(this.actions&&0!==this.actions.length){if(void 0===Oe.CurPlaying&&t===Be.Responding&&!1===this.isPlaying&&(this.stage=Math.ceil(this.getRandomNumber(0,this.actions.length-1)),Re.debug("[SPEAK] Starting animation, stage:",this.stage,"of",this.actions.length),this.actions[this.stage].time=0,this.actions[this.stage].play(),Oe.SetWeight(this.actions[this.stage],1),this.actions[this.stage].loop=e.LoopOnce,this.actions[this.stage].clampWhenFinished=!0,void 0!==Oe.LastAction&&Oe.PrepareCrossFade(Oe.LastAction,this.actions[this.stage],this.blendingTime),this.isPlaying=!0),Oe.CurPlaying===Be.Responding&&t===Be.Responding&&!0===this.isPlaying&&this.actions[this.stage].time>=this.actions[this.stage].getClip().duration-this.blendingTime){const t=this.actions[this.stage];this.stage=(this.stage+Math.ceil(this.getRandomNumber(1,this.actions.length-1)))%this.actions.length,Re.debug("[SPEAK] Cycling to next animation, stage:",this.stage),this.actions[this.stage].time=0,this.actions[this.stage].play(),Oe.SetWeight(this.actions[this.stage],1),this.actions[this.stage].loop=e.LoopOnce,this.actions[this.stage].clampWhenFinished=!0,Oe.PrepareCrossFade(t,this.actions[this.stage],this.blendingTime)}Oe.CurPlaying===Be.Responding&&t!==Be.Responding&&!0===this.isPlaying&&(this.actions[this.stage].loop=e.LoopOnce,this.actions[this.stage].clampWhenFinished=!0,this.isPlaying=!1,Oe.LastAction=this.actions[this.stage])}else this._warnedNoActions||(Re.warn("[SPEAK] No actions available!"),this._warnedNoActions=!0)}}class Oe{static IsBlending=!1;static actions=[];static NeedReset=!1;static NeedFullReset=!1;static LastAction=void 0;static CurPlaying=void 0;static SetWeight(e,t){e.enabled=!0,e.setEffectiveTimeScale(1),e.setEffectiveWeight(t)}static PrepareCrossFade(e,t,s){const i=s;Oe.UnPauseAllActions(),Oe.ExecuteCrossFade(e,t,i),Oe.IsBlending=!0,setTimeout(()=>{Oe.IsBlending=!1},s+.1)}static PauseAllActions(){Oe.actions.forEach(function(e){e.paused=!0})}static UnPauseAllActions(){Oe.actions.forEach(function(e){e.paused=!1})}static ExecuteCrossFade(e,t,s){Oe.SetWeight(t,1),t.time=0,e.crossFadeTo(t,s,!0)}constructor(e,t,s){const i=[],n=[],r=[],a=[],o=[];this.mixer=e;const l=s?.hello?.size||0,c=(s?.idle?.size||0)+l,h=(s?.listen?.size||0)+c,d=(s?.speak?.size||0)+h,u=(s?.think?.size||0)+d;if(t&&t.length>0)for(let s=0;s<t.length;s++){const p=t[s],m=e.clipAction(p);s<l?i.push(m):s<c?(n.push(m),h===c&&r.push(e.clipAction(p.clone())),d===h&&a.push(e.clipAction(p.clone())),u===d&&o.push(e.clipAction(p.clone()))):s<h?r.push(m):s<d?a.push(m):s<u&&o.push(m),Oe.actions.push(m),Oe.SetWeight(m,0)}this.hello=new Pe(i,s?.hello?.isGroup||!1),this.idle=new ke(n,s?.idle?.isGroup||!1),this.listen=new _e(r,s?.listen?.isGroup||!1),this.think=new Le(o,s?.think?.isGroup||!1),this.speak=new Ue(a,s?.speak?.isGroup||!1)}curPlaying(){return this.hello.isPlaying||this.idle.isPlaying?Be.Idle:this.listen.isPlaying?Be.Listening:this.think.isPlaying?Be.Thinking:this.speak.isPlaying?Be.Responding:void 0}dispose(){this.hello.dispose(),this.idle.dispose(),this.listen.dispose(),this.think.dispose(),this.speak.dispose(),Oe.actions=[]}resetAllActions(t=!1){switch(this.curPlaying()){case Be.Idle:Oe.LastAction=this.hello.actions[this.hello.stage];break;case Be.Listening:Oe.LastAction=this.listen.actions[this.listen.stage];break;case Be.Thinking:Oe.LastAction=this.think.actions[this.think.stage];break;case Be.Responding:Oe.LastAction=this.speak.actions[this.speak.stage];break;default:Oe.LastAction=void 0}Oe.LastAction&&(Oe.LastAction.loop=e.LoopOnce,Oe.LastAction.clampWhenFinished=!0,Oe.SetWeight(Oe.LastAction,1)),t&&(Oe.PauseAllActions(),Oe.actions.forEach(function(e){e.time=0,Oe.SetWeight(e,0)}),Oe.LastAction=void 0),this.hello.isPlaying=!1,this.idle.isPlaying=!1,this.listen.isPlaying=!1,this.think.isPlaying=!1,this.speak.isPlaying=!1}update(e){if(!Oe.IsBlending)if(Oe.CurPlaying=this.curPlaying(),void 0===Oe.CurPlaying)switch(e){case Be.Idle:this.idle.update(e);break;case Be.Listening:this.listen.update(e);break;case Be.Thinking:this.think.update(e);break;case Be.Responding:this.speak.update(e);break;default:this.idle.update(e)}else switch(Oe.CurPlaying){case Be.Idle:this.idle.update(e);break;case Be.Listening:this.listen.update(e);break;case Be.Thinking:this.think.update(e);break;case Be.Responding:this.speak.update(e);break;default:this.idle.update(e)}}}class He extends e.Object3D{constructor(t,s=new e.Vector3,i=new e.Quaternion,n=new e.Vector3(1,1,1),r=1,a=1,o=!0){super(),this.splatBuffer=t,this.position.copy(s),this.quaternion.copy(i),this.scale.copy(n),this.transform=new e.Matrix4,this.minimumAlpha=r,this.opacity=a,this.visible=o}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 ze{static build(t){const s=new e.BufferGeometry;s.setIndex([0,1,2,0,2,3]);const i=new Float32Array(12),n=new e.BufferAttribute(i,3);s.setAttribute("position",n),n.setXYZ(0,-1,-1,0),n.setXYZ(1,-1,1,0),n.setXYZ(2,1,1,0),n.setXYZ(3,1,-1,0),n.needsUpdate=!0;const r=(new e.InstancedBufferGeometry).copy(s),a=new Uint32Array(t),o=new e.InstancedBufferAttribute(a,1,!1);return o.setUsage(e.DynamicDrawUsage),r.setAttribute("splatIndex",o),r.instanceCount=0,r}}class Qe{constructor(){this.rootNode=null,this.splatMesh=null}static convertWorkerSubTree(e,t){const s=new Qe;return s.rootNode=e.rootNode,s.splatMesh=t,s}}class Ve{constructor(e,t){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}processSplatMesh=(t,s=()=>!0,i,n)=>{this.splatTreeWorker||(this.splatTreeWorker=null),this.splatMesh=t,this.subTrees=[];const r=new e.Vector3,a=(e,i)=>{const n=new Float32Array(4*i);let a=0;for(let o=0;o<i;o++){const i=o+e;if(s(i)){t.getSplatCenter(i,r);const e=4*a;n[e]=r.x,n[e+1]=r.y,n[e+2]=r.z,n[e+3]=i,a++}}return n};return new Promise(e=>{const s=()=>!!this.disposed&&(this.diposeSplatTreeWorker(),e(),!0);i&&i(!1),L(()=>{if(s())return;const r=[];if(t.dynamicMode){let e=0;for(let s=0;s<t.scenes.length;s++){const i=t.getScene(s).splatBuffer.getSplatCount(),n=a(e,i);r.push(n),e+=i}}else{const e=a(0,t.getSplatCount());r.push(e)}this.splatTreeWorker.onmessage=i=>{s()||i.data.subTrees&&(n&&n(!1),L(()=>{if(!s()){for(let e of i.data.subTrees){const s=Qe.convertWorkerSubTree(e,t);this.subTrees.push(s)}this.diposeSplatTreeWorker(),n&&n(!0),L(()=>{e()})}}))},L(()=>{if(s())return;i&&i(!0);const e=r.map(e=>e.buffer);var t,n,a,o,l;t=this.splatTreeWorker,n=r,a=e,o=this.maxDepth,l=this.maxCentersPerNode,t&&t.postMessage({process:{centers:n,maxDepth:o,maxCentersPerNode:l}},a)})})})};countLeaves(){let e=0;return this.visitLeaves(()=>{e++}),e}visitLeaves(e){const t=(e,s)=>{0===e.children.length&&s(e);for(let i of e.children)t(i,s)};for(let s of this.subTrees)t(s.rootNode,e)}}class Ne{static buildVertexShaderBase(e=!1,t=!1,s=0,i=""){let n="#define USE_SKINNING\n\n precision highp float;\n #include <common>\n\n attribute uint splatIndex;\n uniform highp usampler2D flameModelTexture;\n uniform highp usampler2D boneTexture;\n uniform highp usampler2D boneWeightTexture;\n\n\n uniform highp usampler2D centersColorsTexture;\n uniform highp sampler2D sphericalHarmonicsTexture;\n uniform highp sampler2D sphericalHarmonicsTextureR;\n uniform highp sampler2D sphericalHarmonicsTextureG;\n uniform highp sampler2D sphericalHarmonicsTextureB;\n\n uniform highp usampler2D sceneIndexesTexture;\n uniform vec2 sceneIndexesTextureSize;\n uniform int sceneCount;\n uniform int gaussianSplatCount;\n uniform int bsCount;\n uniform float headBoneIndex;\n #ifdef USE_SKINNING\n attribute vec4 skinIndex;\n attribute vec4 skinWeight;\n #endif\n ";return t&&(n+=`\n uniform float sceneOpacity[${u.MaxScenes}];\n uniform int sceneVisibility[${u.MaxScenes}];\n `),e&&(n+=`\n uniform highp mat4 transforms[${u.MaxScenes}];\n `),n+=`\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[${u.MaxScenes}];\n uniform float sphericalHarmonics8BitCompressionRangeMax[${u.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&&(n+="\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 "),n+=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;",n+="\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 ",s>=1&&(n+=" \n if (sphericalHarmonicsDegree >= 1) {\n ",n+=e?"\n vec3 worldViewDir = normalize(splatCenter - vec3(inverse(transform) * vec4(cameraPosition, 1.0)));\n ":"\n vec3 worldViewDir = normalize(splatCenter - cameraPosition);\n ",n+="\n vec3 sh1;\n vec3 sh2;\n vec3 sh3;\n ",s>=2&&(n+="\n vec3 sh4;\n vec3 sh5;\n vec3 sh6;\n vec3 sh7;\n vec3 sh8;\n "),1===s?n+="\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===s&&(n+="\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 "),n+="\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 ",s>=2&&(n+="\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===s&&(n+="\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 "),n+="\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 "),n+="\n\n vColor.rgb = clamp(vColor.rgb, vec3(0.), vec3(1.));\n\n }\n\n "),n}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(t=!1,s=!1,i=0,n=1,r=!1){const a={sceneCenter:{type:"v3",value:new e.Vector3},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 e.Matrix4},bindMatrixInverse:{type:"m4",value:new e.Matrix4},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 e.Vector2},orthoZoom:{type:"f",value:1},inverseFocalAdjustment:{type:"f",value:1},viewport:{type:"v2",value:new e.Vector2},basisViewport:{type:"v2",value:new e.Vector2},debugColor:{type:"v3",value:new e.Color},centersColorsTextureSize:{type:"v2",value:new e.Vector2(1024,1024)},flameModelTextureSize:{type:"v2",value:new e.Vector2(4096,2048)},boneTextureSize:{type:"v2",value:new e.Vector2(4,32)},boneWeightTextureSize:{type:"v2",value:new e.Vector2(512,512)},sphericalHarmonicsDegree:{type:"i",value:i},sphericalHarmonicsTextureSize:{type:"v2",value:new e.Vector2(1024,1024)},sphericalHarmonics8BitMode:{type:"i",value:0},sphericalHarmonicsMultiTextureMode:{type:"i",value:0},splatScale:{type:"f",value:n},pointCloudModeEnabled:{type:"i",value:r?1:0},sceneIndexesTexture:{type:"t",value:null},sceneIndexesTextureSize:{type:"v2",value:new e.Vector2(1024,1024)},sceneCount:{type:"i",value:1},gaussianSplatCount:{type:"i",value:1},bsCount:{type:"i",value:1},headBoneIndex:{type:"f",value:-1},eyeBlinkLeft:{type:"f",value:0},eyeBlinkRight:{type:"f",value:0}};for(let e=0;e<u.MaxScenes;e++)a.sphericalHarmonics8BitCompressionRangeMin.value.push(-u.SphericalHarmonics8BitCompressionRange/2),a.sphericalHarmonics8BitCompressionRangeMax.value.push(u.SphericalHarmonics8BitCompressionRange/2);if(s){const e=[];for(let t=0;t<u.MaxScenes;t++)e.push(1);a.sceneOpacity={type:"f",value:e};const t=[];for(let e=0;e<u.MaxScenes;e++)t.push(1);a.sceneVisibility={type:"i",value:t}}if(t){const t=[];for(let s=0;s<u.MaxScenes;s++)t.push(new e.Matrix4);a.transforms={type:"mat4",value:t}}return a}}class Ge{static build(t=!1,s=!1,i=!1,n=2048,r=1,a=!1,o=0,l=.3,c=null){let h=Ne.buildVertexShaderBase(t,s,o,"\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 ");h+=Ge.buildVertexShaderProjection(i,s,n,l);const d=Ge.buildFragmentShader(c),u=Ne.getUniforms(t,s,o,r,a);return u.covariancesTextureSize={type:"v2",value:new e.Vector2(1024,1024)},u.covariancesTexture={type:"t",value:null},u.covariancesTextureHalfFloat={type:"t",value:null},u.covariancesAreHalfFloat={type:"i",value:0},new e.ShaderMaterial({uniforms:u,vertexShader:h,fragmentShader:d,transparent:!0,alphaTest:1,blending:e.NormalBlending,depthTest:!0,depthWrite:!1,side:e.DoubleSide})}static buildVertexShaderProjection(e,t,s,i){let n="\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 n+=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 `,n+=`\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(s)}.0);\n vec2 basisVector2 = eigenVector2 * splatScale * min(sqrt8 * sqrt(eigenValue2), ${parseInt(s)}.0);\n `,t&&(n+="\n vColor.a *= splatOpacityFromScene;\n "),n+="\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 ",n+=Ne.getVertexShaderFadeIn(),n+="}",n}static buildFragmentShader(e=null){let t="\n precision highp float;\n #include <common>\n\n uniform float eyeBlinkLeft;\n uniform float eyeBlinkRight;\n\n varying vec4 vColor;\n varying vec2 vUv;\n varying vec2 vPosition;\n varying vec2 vSplatIndex;\n ";return t+="\n void main () {\n float A = dot(vPosition, vPosition);\n float opacity = exp(-0.5 * A) * vColor.a;\n if (opacity < 1.0 / 255.0)\n discard;\n ",e&&(e.right_iris||e.left_iris)?(t+="\n float idx = vSplatIndex.x;\n ",e.right_iris&&e.right_iris.length>0?t+=`\n // Check if this splat is part of right iris\n bool isRightIris = ${e.right_iris.map(([e,t])=>`(idx >= ${e}.0 && idx <= ${t}.0)`).join(" ||\n ")};\n `:t+="\n bool isRightIris = false;\n ",e.left_iris&&e.left_iris.length>0?t+=`\n // Check if this splat is part of left iris\n bool isLeftIris = ${e.left_iris.map(([e,t])=>`(idx >= ${e}.0 && idx <= ${t}.0)`).join(" ||\n ")};\n `:t+="\n bool isLeftIris = false;\n ",t+="\n float finalOpacity = opacity;\n\n // Smooth fade: iris fades out as eye closes (blink increases)\n // smoothstep(0.1, 0.5, blink) = 0 when blink<0.1, 1 when blink>0.5\n if (isRightIris) {\n float fadeFactor = 1.0 - smoothstep(0.1, 0.5, eyeBlinkRight);\n finalOpacity = opacity * fadeFactor;\n } else if (isLeftIris) {\n float fadeFactor = 1.0 - smoothstep(0.1, 0.5, eyeBlinkLeft);\n finalOpacity = opacity * fadeFactor;\n }\n\n if (finalOpacity < 1.0 / 255.0)\n discard;\n\n gl_FragColor = vec4(vColor.rgb, finalOpacity);\n }\n "):t+="\n gl_FragColor = vec4(vColor.rgb, opacity);\n }\n ",t}}class We{static build(t=!1,s=!1,i=1,n=!1,r=0){let a=Ne.buildVertexShaderBase(t,s,r,"\n uniform vec2 scaleRotationsTextureSize;\n uniform highp sampler2D scaleRotationsTexture;\n varying mat3 vT;\n varying vec2 vQuadCenter;\n varying vec2 vFragCoord;\n ");a+=We.buildVertexShaderProjection();const o=We.buildFragmentShader(),l=Ne.getUniforms(t,s,r,i,n);return l.scaleRotationsTexture={type:"t",value:null},l.scaleRotationsTextureSize={type:"v2",value:new e.Vector2(1024,1024)},new e.ShaderMaterial({uniforms:l,vertexShader:a,fragmentShader:o,transparent:!0,alphaTest:1,blending:e.NormalBlending,depthTest:!0,depthWrite:!1,side:e.DoubleSide})}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+=Ne.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 qe=E("SplatMesh"),Ke=new e.BufferGeometry,je=new e.MeshBasicMaterial;function Ye(e){const t={};function s(s){if(void 0!==t[s])return t[s];let i;switch(s){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(s)}return t[s]=i,i}return{has:function(e){return null!==s(e)},init:function(e){e.isWebGL2?(s("EXT_color_buffer_float"),s("WEBGL_clip_cull_distance")):(s("WEBGL_depth_texture"),s("OES_texture_float"),s("OES_texture_half_float"),s("OES_texture_half_float_linear"),s("OES_standard_derivatives"),s("OES_element_index_uint"),s("OES_vertex_array_object"),s("ANGLE_instanced_arrays")),s("OES_texture_float_linear"),s("EXT_color_buffer_half_float"),s("WEBGL_multisampled_render_to_texture")},get:function(e){const t=s(e);return null===t&&qe.warn("THREE.WebGLRenderer: "+e+" extension not supported."),t}}}function Je(e,t,s){let i;function n(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!==s.precision?s.precision:"highp";const o=n(a);o!==a&&(qe.warn("THREE.WebGLRenderer:",a,"not supported, using",o,"instead."),a=o);const l=r||t.has("WEBGL_draw_buffers"),c=!0===s.logarithmicDepthBuffer,h=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),d=e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS),u=e.getParameter(e.MAX_TEXTURE_SIZE),p=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),m=e.getParameter(e.MAX_VERTEX_ATTRIBS),g=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),A=e.getParameter(e.MAX_VARYING_VECTORS),f=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),S=d>0,C=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 s=t.get("EXT_texture_filter_anisotropic");i=e.getParameter(s.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else i=0;return i},getMaxPrecision:n,precision:a,logarithmicDepthBuffer:c,maxTextures:h,maxVertexTextures:d,maxTextureSize:u,maxCubemapSize:p,maxAttributes:m,maxVertexUniforms:g,maxVaryings:A,maxFragmentUniforms:f,vertexTextures:S,floatFragmentTextures:C,floatVertexTextures:S&&C,maxSamples:r?e.getParameter(e.MAX_SAMPLES):0}}function Xe(t,s,i){const n=i.isWebGL2;return{convert:function(i,r){let a;if(i===e.UnsignedByteType)return t.UNSIGNED_BYTE;if(1017===i)return t.UNSIGNED_SHORT_4_4_4_4;if(1018===i)return t.UNSIGNED_SHORT_5_5_5_1;if(1010===i)return t.BYTE;if(1011===i)return t.SHORT;if(1012===i)return t.UNSIGNED_SHORT;if(1013===i)return t.INT;if(1014===i)return t.UNSIGNED_INT;if(i===e.FloatType)return t.FLOAT;if(i===e.HalfFloatType)return n?t.HALF_FLOAT:(a=s.get("OES_texture_half_float"),null!==a?a.HALF_FLOAT_OES:null);if(1021===i)return t.ALPHA;if(1022===i)return t.RGB;if(i===e.RGBAFormat)return t.RGBA;if(1024===i)return t.LUMINANCE;if(1025===i)return t.LUMINANCE_ALPHA;if(1026===i)return t.DEPTH_COMPONENT;if(1027===i)return t.DEPTH_STENCIL;if(i===e.RedFormat)return t.RED;if(i===e.RedIntegerFormat)return t.RED_INTEGER;if(i===e.RGFormat)return t.RG;if(i===e.RGIntegerFormat)return t.RG_INTEGER;if(i===e.RGBIntegerFormat)return t.RGB_INTEGER;if(i===e.RGBAIntegerFormat)return t.RGBA_INTEGER;if(33776===i||33777===i||33778===i||33779===i){if(a=s.get("WEBGL_compressed_texture_s3tc"),null===a)return null;if(33776===i)return a.COMPRESSED_RGB_S3TC_DXT1_EXT;if(33777===i)return a.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(33778===i)return a.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(33779===i)return a.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(35840===i||35841===i||35842===i||35843===i){if(a=s.get("WEBGL_compressed_texture_pvrtc"),null===a)return null;if(35840===i)return a.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(35841===i)return a.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(35842===i)return a.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(35843===i)return a.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(36196===i)return a=s.get("WEBGL_compressed_texture_etc1"),null!==a?a.COMPRESSED_RGB_ETC1_WEBGL:null;if(i>=37808&&i<=37814||i>=37840&&i<=37846)return a=s.get("WEBGL_compressed_texture_astc"),null!==a?i:null;if(36492===i||36494===i||36495===i)return a=s.get("EXT_texture_compression_bptc"),null!==a?i:null;if(34042===i)return t.UNSIGNED_INT_24_8;if(n){if(6407===i)return t.RGB;if(6408===i)return t.RGBA}return void 0!==t[i]?t[i]:null}}}const $e=16777216;class Ze extends e.Mesh{constructor(t=d.ThreeD,s=!1,i=!1,n=!1,r=1,o=!0,l=!1,c=!1,h=1024,u=a.None,p=0,m=1,g=.3){super(Ke,je),this.renderer=void 0,this.splatRenderMode=t,this.dynamicMode=s,this.enableOptionalEffects=i,this.halfPrecisionCovariancesOnGPU=n,this.devicePixelRatio=r,this.enableDistancesComputationOnGPU=o,this.integerBasedDistancesComputation=l,this.antialiased=c,this.kernel2DSize=g,this.maxScreenSpaceSplatSize=h,this.logLevel=u,this.sphericalHarmonicsDegree=p,this.minSphericalHarmonicsDegree=0,this.sceneFadeInRateMultiplier=m,this.scenes=[],this.splatTree=null,this.baseSplatTree=null,this.splatDataTextures={},this.flameModel=null,this.expressionBSNum=0,this.bsWeight=[],this.bonesMatrix=null,this.bonesNum=null,this.bonesWeight=null,this.gaussianSplatCount=null,this.morphTargetDictionary=null,this.distancesTransformFeedback={id:null,vertexShader:null,fragmentShader:null,program:null,centersBuffer:null,sceneIndexesBuffer:null,outDistancesBuffer:null,centersLoc:-1,modelViewProjLoc:-1,sceneIndexesLoc:-1,transformsLocs:[]},this.globalSplatIndexToLocalSplatIndexMap=[],this.globalSplatIndexToSceneIndexMap=[],this.irisOcclusionConfig=null,this.lastBuildSplatCount=0,this.lastBuildScenes=[],this.lastBuildMaxSplatCount=0,this.lastBuildSceneCount=0,this.firstRenderTime=-1,this.finalBuild=!1,this.webGLUtils=null,this.boundingBox=new e.Box3,this.calculatedSceneCenter=new e.Vector3,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(t,s,i){const n=[];n.length=s.length;for(let r=0;r<s.length;r++){const a=s[r],o=i[r]||{};let l=o.position||[0,0,0],c=o.rotation||[0,0,0,1],h=o.scale||[1,1,1];const d=(new e.Vector3).fromArray(l),u=(new e.Quaternion).fromArray(c),p=(new e.Vector3).fromArray(h),m=Ze.createScene(a,d,u,p,o.splatAlphaRemovalThreshold||1,o.opacity,o.visible);t.add(m),n[r]=m}return n}static createScene(e,t,s,i,n,r=1,a=!0){return new He(e,t,s,i,n,r,a)}static buildSplatIndexMaps(e){const t=[],s=[];let i=0;for(let n=0;n<e.length;n++){const r=e[n].getMaxSplatCount();for(let e=0;e<r;e++)t[i]=e,s[i]=n,i++}return{localSplatIndexMap:t,sceneIndexMap:s}}buildSplatTree=(t=[],s,i)=>new Promise(n=>{this.disposeSplatTree(),this.baseSplatTree=new Ve(8,1e3);const r=performance.now(),o=new e.Vector4;this.baseSplatTree.processSplatMesh(this,e=>{this.getSplatColor(e,o);const s=this.getSceneIndexForSplat(e),i=t[s]||1;return o.w>=i},s,i).then(()=>{const e=performance.now()-r;if(this.logLevel>=a.Info&&qe.info("SplatTree build: "+e+" ms"),this.disposed)n();else{this.splatTree=this.baseSplatTree,this.baseSplatTree=null;let e=0,t=0,s=0;this.splatTree.visitLeaves(i=>{const n=i.data.indexes.length;n>0&&(t+=n,s++,e++)}),this.logLevel>=a.Info&&(qe.info(`SplatTree leaves: ${this.splatTree.countLeaves()}`),qe.info(`SplatTree leaves with splats:${e}`),t/=s,qe.info(`Avg splat count per node: ${t}`),qe.info(`Total splat count: ${this.getSplatCount()}`)),n()}})});build(t,s,i=!0,n=!1,r,a,o=!0){this.sceneOptions=s,this.finalBuild=n;const l=Ze.getTotalMaxSplatCountForSplatBuffers(t),c=Ze.buildScenes(this,t,s);if(i)for(let e=0;e<this.scenes.length&&e<c.length;e++){const t=c[e],s=this.getScene(e);t.copyTransformData(s)}this.scenes=c;let h=3;for(let e of t){const t=e.getMinSphericalHarmonicsDegree();t<h&&(h=t)}this.minSphericalHarmonicsDegree=Math.min(h,this.sphericalHarmonicsDegree);let u=!1;if(t.length!==this.lastBuildScenes.length)u=!0;else for(let e=0;e<t.length;e++)if(t[e]!==this.lastBuildScenes[e].splatBuffer){u=!0;break}let p=!0;if((1!==this.scenes.length||this.lastBuildSceneCount!==this.scenes.length||this.lastBuildMaxSplatCount!==l||u)&&(p=!1),!p){this.boundingBox=new e.Box3,o||(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=ze.build(l),this.splatRenderMode===d.ThreeD?this.material=Ge.build(this.dynamicMode,this.enableOptionalEffects,this.antialiased,this.maxScreenSpaceSplatSize,this.splatScale,this.pointCloudModeEnabled,this.minSphericalHarmonicsDegree,this.kernel2DSize,this.irisOcclusionConfig):this.material=We.build(this.dynamicMode,this.enableOptionalEffects,this.splatScale,this.pointCloudModeEnabled,this.minSphericalHarmonicsDegree);const s=Ze.buildSplatIndexMaps(t);this.globalSplatIndexToLocalSplatIndexMap=s.localSplatIndexMap,this.globalSplatIndexToSceneIndexMap=s.sceneIndexMap}const m=this.getSplatCount(!0);this.enableDistancesComputationOnGPU&&this.setupDistancesComputationTransformFeedback();const g=this.refreshGPUDataFromSplatBuffers(p);for(let e=0;e<this.scenes.length;e++)this.lastBuildScenes[e]=this.scenes[e];return this.lastBuildSplatCount=m,this.lastBuildMaxSplatCount=this.getMaxSplatCount(),this.lastBuildSceneCount=this.scenes.length,this.visible=this.scenes.length>0,g}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 e.Box3,this.calculatedSceneCenter=new e.Vector3,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!==Ke&&(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 s=e?this.lastBuildSplatCount:0,{centers:i,sceneIndexes:n}=this.getDataForDistancesComputation(s,t-1);return this.enableDistancesComputationOnGPU&&this.refreshGPUBuffersForDistancesComputation(i,n,e),{from:s,to:t-1,count:t-s,centers:i,sceneIndexes:n}}refreshGPUBuffersForDistancesComputation(e,t,s=!1){const i=s?this.lastBuildSplatCount:0;this.updateGPUCentersBufferForDistancesComputation(s,e,i),this.updateGPUTransformIndexesBufferForDistancesComputation(s,t,i)}refreshDataTexturesFromSplatBuffers(e){const t=this.getSplatCount(!0),s=this.lastBuildSplatCount,i=t-1;e?this.updateBaseDataFromSplatBuffers(s,i):(this.setupDataTextures(),this.updateBaseDataFromSplatBuffers()),this.updateDataTexturesFromBaseData(s,i),this.updateVisibleRegion(e)}setupDataTextures(){const t=this.getMaxSplatCount(),s=this.getSplatCount(!0);this.disposeTextures();const i=(s,i)=>{const n=new e.Vector2(4096,1024);for(;n.x*n.y*s<t*i;)n.y*=2;return n},n=e=>{const t=(e=>e>=1?6:4)(e);return{elementsPerTexelStored:t,texSize:i(t,6)}};let r=this.getTargetCovarianceCompressionLevel();const a=this.getTargetSphericalHarmonicsCompressionLevel();let o,l,c;if(this.splatRenderMode===d.ThreeD){const e=n(r);e.texSize.x*e.texSize.y>$e&&0===r&&(r=1),o=new Float32Array(6*t)}else l=new Float32Array(3*t),c=new Float32Array(4*t);const h=new Float32Array(3*t),u=new Uint8Array(4*t);let p=Float32Array;1===a?p=Uint16Array:2===a&&(p=Uint8Array);const m=U(this.minSphericalHarmonicsDegree),g=this.minSphericalHarmonicsDegree?new p(t*m):void 0,A=i(4,4),f=new Uint32Array(A.x*A.y*4);Ze.updateCenterColorsPaddedData(0,s-1,h,u,f);const S=new e.DataTexture(f,A.x,A.y,e.RGBAIntegerFormat,e.UnsignedIntType);if(S.internalFormat="RGBA32UI",S.needsUpdate=!0,this.material.uniforms.centersColorsTexture.value=S,this.material.uniforms.centersColorsTextureSize.value.copy(A),this.material.uniformsNeedUpdate=!0,this.splatDataTextures={baseData:{covariances:o,scales:l,rotations:c,centers:h,colors:u,sphericalHarmonics:g},centerColors:{data:f,texture:S,size:A}},this.splatRenderMode===d.ThreeD){const t=n(r),s=t.elementsPerTexelStored,i=t.texSize,a=r>=1?8:4,l=new(r>=1?Uint32Array:Float32Array)(i.x*i.y*a);let c;if(0===r?l.set(o):Ze.updatePaddedCompressedCovariancesTextureData(o,l,0,0,o.length),r>=1)c=new e.DataTexture(l,i.x,i.y,e.RGBAIntegerFormat,e.UnsignedIntType),c.internalFormat="RGBA32UI",this.material.uniforms.covariancesTextureHalfFloat.value=c;else{c=new e.DataTexture(l,i.x,i.y,e.RGBAFormat,e.FloatType),this.material.uniforms.covariancesTexture.value=c;const t=new e.DataTexture(new Uint32Array(32),2,2,e.RGBAIntegerFormat,e.UnsignedIntType);t.internalFormat="RGBA32UI",this.material.uniforms.covariancesTextureHalfFloat.value=t,t.needsUpdate=!0}c.needsUpdate=!0,this.material.uniforms.covariancesAreHalfFloat.value=r>=1?1:0,this.material.uniforms.covariancesTextureSize.value.copy(i),this.splatDataTextures.covariances={data:l,texture:c,size:i,compressionLevel:r,elementsPerTexelStored:s,elementsPerTexelAllocated:a}}else{const t=i(4,6);let n=Float32Array,r=e.FloatType;const a=new n(t.x*t.y*4);Ze.updateScaleRotationsPaddedData(0,s-1,l,c,a);const o=new e.DataTexture(a,t.x,t.y,e.RGBAFormat,r);o.needsUpdate=!0,this.material.uniforms.scaleRotationsTexture.value=o,this.material.uniforms.scaleRotationsTextureSize.value.copy(t),this.splatDataTextures.scaleRotations={data:a,texture:o,size:t,compressionLevel:0}}if(g){const t=2===a?e.UnsignedByteType:e.HalfFloatType;let n=m;n%2!=0&&n++;const r=2===this.minSphericalHarmonicsDegree?4:2,o=4===r?e.RGBAFormat:e.RGFormat;let l=i(r,n);if(l.x*l.y<=$e){const i=new p(l.x*l.y*r);for(let e=0;e<s;e++){const t=m*e,s=n*e;for(let e=0;e<m;e++)i[s+e]=g[t+e]}const c=new e.DataTexture(i,l.x,l.y,o,t);c.needsUpdate=!0,this.material.uniforms.sphericalHarmonicsTexture.value=c,this.splatDataTextures.sphericalHarmonics={componentCount:m,paddedComponentCount:n,data:i,textureCount:1,texture:c,size:l,compressionLevel:a,elementsPerTexel:r}}else{const c=m/3;n=c,n%2!=0&&n++,l=i(r,n);const h=l.x*l.y*r,d=[this.material.uniforms.sphericalHarmonicsTextureR,this.material.uniforms.sphericalHarmonicsTextureG,this.material.uniforms.sphericalHarmonicsTextureB],u=[],A=[];for(let i=0;i<3;i++){const r=new p(h);u.push(r);for(let e=0;e<s;e++){const t=m*e,s=n*e;if(c>=3){for(let e=0;e<3;e++)r[s+e]=g[t+3*i+e];if(c>=8)for(let e=0;e<5;e++)r[s+3+e]=g[t+9+5*i+e]}}const a=new e.DataTexture(r,l.x,l.y,o,t);A.push(a),a.needsUpdate=!0,d[i].value=a}this.material.uniforms.sphericalHarmonicsMultiTextureMode.value=1,this.splatDataTextures.sphericalHarmonics={componentCount:m,componentCountPerChannel:c,paddedComponentCount:n,data:u,textureCount:3,textures:A,size:l,compressionLevel:a,elementsPerTexel:r}}this.material.uniforms.sphericalHarmonicsTextureSize.value.copy(l),this.material.uniforms.sphericalHarmonics8BitMode.value=2===a?1:0;for(let e=0;e<this.scenes.length;e++){const t=this.scenes[e].splatBuffer;this.material.uniforms.sphericalHarmonics8BitCompressionRangeMin.value[e]=t.minSphericalHarmonicsCoeff,this.material.uniforms.sphericalHarmonics8BitCompressionRangeMax.value[e]=t.maxSphericalHarmonicsCoeff}this.material.uniformsNeedUpdate=!0}const C=i(1,4),x=new Uint32Array(C.x*C.y*1);for(let e=0;e<s;e++)x[e]=this.globalSplatIndexToSceneIndexMap[e];const y=new e.DataTexture(x,C.x,C.y,e.RedIntegerFormat,e.UnsignedIntType);y.internalFormat="R32UI",y.needsUpdate=!0,this.material.uniforms.sceneIndexesTexture.value=y,this.material.uniforms.sceneIndexesTextureSize.value.copy(C),this.material.uniformsNeedUpdate=!0,this.splatDataTextures.sceneIndexes={data:x,texture:y,size:C},this.material.uniforms.sceneCount.value=this.scenes.length,this.flameModel&&this.flameModel.geometry&&this.flameModel.geometry.morphAttributes&&this.flameModel.skeleton&&(this.expressionBSNum=this.flameModel.geometry.morphAttributes.position.length,this.material.uniforms.bsCount.value=this.expressionBSNum,this.flameModel.skeleton.bones.forEach((e,t)=>{"head"==e.name&&(this.material.uniforms.headBoneIndex.value=t)}),this.buildModelTexture(this.flameModel),this.buildBoneMatrixTexture(),this.buildBoneWeightTexture(this.flameModel))}buildBoneMatrixTexture(){if(!this.bsWeight)return;if(!this.flameModel||!this.flameModel.morphTargetDictionary)return;const t=new e.Vector2(4,32);let s=new Float32Array(this.bonesMatrix),i=new Uint32Array(t.x*t.y*4);this.morphTargetDictionary=this.flameModel.morphTargetDictionary;for(let e=0;e<16*this.bonesNum;e++)i[e]=$(s[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 e in this.bsWeight)if(Object.hasOwn(this.bsWeight,e)){const t=this.bsWeight[e];i[this.morphTargetDictionary[e]+16*this.bonesNum]=$(t)}const n=new e.DataTexture(i,t.x,t.y,e.RGBAIntegerFormat,e.UnsignedIntType);n.internalFormat="RGBA32UI",n.needsUpdate=!0,this.material.uniforms.boneTexture.value=n,this.material.uniforms.boneTextureSize.value.copy(t),this.material.uniformsNeedUpdate=!0,this.splatDataTextures.boneMatrix={data:i,texture:n,size:t},this.splatDataTextures.baseData.boneMatrix=i}updateBoneMatrixTexture(){if(this.bsWeight&&this.morphTargetDictionary){for(const e in this.bsWeight)if(Object.hasOwn(this.bsWeight,e)){const t=this.bsWeight[e],s=this.morphTargetDictionary[e];this.splatDataTextures.baseData.boneMatrix[s+16*this.bonesNum]=$(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(t){if(!this.bonesWeight)return;let s=t.geometry.attributes.position.array.length/3;const i=new e.Vector2(512,512);let n=new Float32Array(i.x*i.y*4),r=new Uint32Array(i.x*i.y*4);for(let e=0;e<s;e++)n[8*e+0]=this.bonesWeight[e][0],n[8*e+1]=this.bonesWeight[e][1],n[8*e+2]=this.bonesWeight[e][2],n[8*e+3]=this.bonesWeight[e][3],n[8*e+4]=this.bonesWeight[e][4],r[8*e+0]=$(this.bonesWeight[e][0]),r[8*e+1]=$(this.bonesWeight[e][1]),r[8*e+2]=$(this.bonesWeight[e][2]),r[8*e+3]=$(this.bonesWeight[e][3]),r[8*e+4]=$(this.bonesWeight[e][4]);const a=new e.DataTexture(r,i.x,i.y,e.RGBAIntegerFormat,e.UnsignedIntType);a.internalFormat="RGBA32UI",a.needsUpdate=!0,this.material.uniforms.boneWeightTexture.value=a,this.material.uniforms.boneWeightTextureSize.value.copy(i),this.material.uniformsNeedUpdate=!0,this.splatDataTextures.boneWeight={data:r,texture:a,size:i},this.splatDataTextures.baseData.boneWeight=r}buildModelTexture(t){if(!(t&&t.geometry&&t.geometry.morphAttributes&&t.morphTargetDictionary))return;const s=new e.Vector2(4096,2048);var i=t.geometry.attributes.position.array,n=[];let r=i.length/3,a=t.geometry.morphAttributes.position.length;Object.keys(t.morphTargetDictionary).forEach((e,s)=>{const i=t.morphTargetDictionary[e];var r=t.geometry.morphAttributes.position[i];n=n.concat(Array.from(r.array))}),n=n.concat(Array.from(i));let o=new Float32Array(s.x*s.y*4),l=new Uint32Array(s.x*s.y*4);for(let e=0;e<r*(a+1);e++)o[4*e+0]=n[3*e+0],o[4*e+1]=n[3*e+1],o[4*e+2]=n[3*e+2],l[4*e+0]=$(o[4*e+0]),l[4*e+1]=$(o[4*e+1]),l[4*e+2]=$(o[4*e+2]);const c=new e.DataTexture(l,s.x,s.y,e.RGBAIntegerFormat,e.UnsignedIntType);c.internalFormat="RGBA32UI",c.needsUpdate=!0,this.material.uniforms.flameModelTexture.value=c,this.material.uniforms.flameModelTextureSize.value.copy(s),this.material.uniformsNeedUpdate=!0,this.material.uniforms.gaussianSplatCount.value=this.gaussianSplatCount,this.splatDataTextures.flameModel={data:l,texture:c,size:s},this.splatDataTextures.baseData.flameModelPos=o}updateTetureAfterBSAndSkeleton(t,s){const i=new e.Matrix4;this.getSceneTransform(0,i),this.getScene(0).splatBuffer.fillSplatCenterArray(this.morphedMesh,this.splatDataTextures.baseData.centers,i,t,s,0);const n=this.splatDataTextures.centerColors,r=n.data,a=n.texture;Ze.updateCenterColorsPaddedData(t,s,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,n.texture,n.size,o,4,4,4,t,s):a.needsUpdate=!0,this.updateBoneMatrixTexture()}updateBaseDataFromSplatBuffers(e,t){const s=this.splatDataTextures.covariances,i=s?s.compressionLevel:void 0,n=this.splatDataTextures.scaleRotations,r=n?n.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 s=this.splatDataTextures.covariances,i=s?s.compressionLevel:void 0,n=this.splatDataTextures.scaleRotations,r=n?n.compressionLevel:void 0,a=this.splatDataTextures.sphericalHarmonics,o=a?a.compressionLevel:0,l=this.splatDataTextures.flameModel,c=l.data,h=l.texture,d=this.renderer?this.renderer.properties.get(h):null;d&&d.__webglTexture?this.updateDataTexture(c,l.texture,l.size,d,4,4,3,e,t):h.needsUpdate=!0;const u=this.splatDataTextures.centerColors,p=u.data,m=u.texture;Ze.updateCenterColorsPaddedData(e,t,this.splatDataTextures.baseData.centers,this.splatDataTextures.baseData.colors,p);const g=this.renderer?this.renderer.properties.get(m):null;if(g&&g.__webglTexture?this.updateDataTexture(p,u.texture,u.size,g,4,4,4,e,t):m.needsUpdate=!0,s){const n=s.texture,r=6*e,a=6*t;if(0===i)for(let e=r;e<=a;e++){const t=this.splatDataTextures.baseData.covariances[e];s.data[e]=t}else Ze.updatePaddedCompressedCovariancesTextureData(this.splatDataTextures.baseData.covariances,s.data,e*s.elementsPerTexelAllocated,r,a);const o=this.renderer?this.renderer.properties.get(n):null;o&&o.__webglTexture?0===i?this.updateDataTexture(s.data,s.texture,s.size,o,s.elementsPerTexelStored,6,4,e,t):this.updateDataTexture(s.data,s.texture,s.size,o,s.elementsPerTexelAllocated,s.elementsPerTexelAllocated,2,e,t):n.needsUpdate=!0}if(n){const s=n.data,i=n.texture,a=6,o=0===r?4:2;Ze.updateScaleRotationsPaddedData(e,t,this.splatDataTextures.baseData.scales,this.splatDataTextures.baseData.rotations,s);const l=this.renderer?this.renderer.properties.get(i):null;l&&l.__webglTexture?this.updateDataTexture(s,n.texture,n.size,l,4,a,o,e,t):i.needsUpdate=!0}const A=this.splatDataTextures.baseData.sphericalHarmonics;if(A){let s=4;1===o?s=2:2===o&&(s=1);const i=(i,n,r,a,o)=>{const l=this.renderer?this.renderer.properties.get(i):null;l&&l.__webglTexture?this.updateDataTexture(a,i,n,l,r,o,s,e,t):i.needsUpdate=!0},n=a.componentCount,r=a.paddedComponentCount;if(1===a.textureCount){const s=a.data;for(let i=e;i<=t;i++){const e=n*i,t=r*i;for(let i=0;i<n;i++)s[t+i]=A[e+i]}i(a.texture,a.size,a.elementsPerTexel,s,r)}else{const s=a.componentCountPerChannel;for(let o=0;o<3;o++){const l=a.data[o];for(let i=e;i<=t;i++){const e=n*i,t=r*i;if(s>=3){for(let s=0;s<3;s++)l[t+s]=A[e+3*o+s];if(s>=8)for(let s=0;s<5;s++)l[t+3+s]=A[e+9+5*o+s]}}i(a.textures[o],a.size,a.elementsPerTexel,l,r)}}}const f=this.splatDataTextures.sceneIndexes,S=f.data;for(let e=this.lastBuildSplatCount;e<=t;e++)S[e]=this.globalSplatIndexToSceneIndexMap[e];const C=f.texture,x=this.renderer?this.renderer.properties.get(C):null;x&&x.__webglTexture?this.updateDataTexture(S,f.texture,f.size,x,1,1,1,this.lastBuildSplatCount,t):C.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 s=this.getScene(t).splatBuffer;(0===t||s.compressionLevel>e)&&(e=s.compressionLevel)}return e}getMinimumSplatBufferCompressionLevel(){let e;for(let t=0;t<this.scenes.length;t++){const s=this.getScene(t).splatBuffer;(0===t||s.compressionLevel<e)&&(e=s.compressionLevel)}return e}static computeTextureUpdateRegion(e,t,s,i,n){const r=n/i,a=e*r,o=Math.floor(a/s),l=o*s*i,c=t*r,h=Math.floor(c/s);return{dataStart:l,dataEnd:h*s*i+s*i,startRow:o,endRow:h}}updateDataTexture(e,t,s,i,n,r,a,o,l){const c=this.renderer.getContext(),h=Ze.computeTextureUpdateRegion(o,l,s.x,n,r),d=h.dataEnd-h.dataStart,u=new e.constructor(e.buffer,h.dataStart*a,d),p=h.endRow-h.startRow+1,m=this.webGLUtils.convert(t.type),g=this.webGLUtils.convert(t.format,t.colorSpace),A=c.getParameter(c.TEXTURE_BINDING_2D);c.bindTexture(c.TEXTURE_2D,i.__webglTexture),c.texSubImage2D(c.TEXTURE_2D,0,0,h.startRow,s.x,p,g,m,u),c.bindTexture(c.TEXTURE_2D,A)}static updatePaddedCompressedCovariancesTextureData(e,t,s,i,n){let r=new DataView(t.buffer),a=s,o=0;for(let t=i;t<=n;t+=2)r.setUint16(2*a,e[t],!0),r.setUint16(2*a+2,e[t+1],!0),a+=2,o++,o>=3&&(a+=2,o=0)}static updateCenterColorsPaddedData(e,t,s,i,n){for(let r=e;r<=t;r++){const e=4*r,t=3*r,a=4*r;n[a]=Z(i,e),n[a+1]=$(s[t]),n[a+2]=$(s[t+1]),n[a+3]=$(s[t+2])}}static updateScaleRotationsPaddedData(e,t,s,i,n){for(let r=e;r<=t;r++){const e=3*r,t=4*r,a=6*r;n[a]=s[e],n[a+1]=s[e+1],n[a+2]=s[e+2],n[a+3]=i[t],n[a+4]=i[t+1],n[a+5]=i[t+2]}}updateVisibleRegion(t){const s=this.getSplatCount(!0),i=new e.Vector3;if(!t){const t=new e.Vector3;this.scenes.forEach(e=>{t.add(e.splatBuffer.sceneCenter)}),t.multiplyScalar(1/this.scenes.length),this.calculatedSceneCenter.copy(t),this.material.uniforms.sceneCenter.value.copy(this.calculatedSceneCenter),this.material.uniformsNeedUpdate=!0}for(let e=t?this.lastBuildSplatCount:0;e<s;e++){this.getSplatCenter(this.morphedMesh,e,i,!0);const t=i.sub(this.calculatedSceneCenter).length();t>this.maxSplatDistanceFromSceneCenter&&(this.maxSplatDistanceFromSceneCenter=t)}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=h.Default){const t=.012*this.sceneFadeInRateMultiplier,s=.003*this.sceneFadeInRateMultiplier,i=this.finalBuild?t:s,n=e===h.Default?i:s;this.visibleRegionFadeStartRadius=(this.visibleRegionRadius-this.visibleRegionFadeStartRadius)*n+this.visibleRegionFadeStartRadius;const r=(this.visibleRegionBufferRadius>0?this.visibleRegionFadeStartRadius/this.visibleRegionBufferRadius:0)>.99,a=r||e===h.Instant?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 s=this.geometry;s.attributes.splatIndex.set(e),s.attributes.splatIndex.needsUpdate=!0,t>0&&-1===this.firstRenderTime&&(this.firstRenderTime=performance.now()),s.instanceCount=t,s.setDrawRange(0,t)}updateTransforms(){for(let e=0;e<this.scenes.length;e++)this.getScene(e).updateTransform(this.dynamicMode)}updateUniforms=function(){const t=new e.Vector2;return function(e,s,i,n,r,a){if(this.getSplatCount()>0){if(t.set(e.x*this.devicePixelRatio,e.y*this.devicePixelRatio),this.material.uniforms.viewport.value.copy(t),this.material.uniforms.basisViewport.value.set(1/t.x,1/t.y),this.material.uniforms.focal.value.set(s,i),this.material.uniforms.orthographicMode.value=n?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]=P(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}}}();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?Ze.getTotalSplatCountForScenes(this.scenes):this.lastBuildSplatCount}static getTotalSplatCountForScenes(e){let t=0;for(let s of e)s&&s.splatBuffer&&(t+=s.splatBuffer.getSplatCount());return t}static getTotalSplatCountForSplatBuffers(e){let t=0;for(let s of e)t+=s.getSplatCount();return t}getMaxSplatCount(){return Ze.getTotalMaxSplatCountForScenes(this.scenes)}static getTotalMaxSplatCountForScenes(e){let t=0;for(let s of e)s&&s.splatBuffer&&(t+=s.splatBuffer.getMaxSplatCount());return t}static getTotalMaxSplatCountForSplatBuffers(e){let t=0;for(let s of e)t+=s.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(),s=new Ye(t),i=new Je(t,s,{});if(s.init(i),this.webGLUtils=new Xe(t,s,i),this.enableDistancesComputationOnGPU&&this.getSplatCount()>0){this.setupDistancesComputationTransformFeedback();const{centers:e,sceneIndexes:t}=this.getDataForDistancesComputation(0,this.getSplatCount()-1);this.refreshGPUBuffersForDistancesComputation(e,t)}}}setupDistancesComputationTransformFeedback=function(){let e;return()=>{const t=this.getMaxSplatCount();if(!this.renderer)return;const s=this.lastRenderer!==this.renderer,i=e!==t;if(!s&&!i)return;s?this.disposeDistancesComputationGPUResources():i&&this.disposeDistancesComputationGPUBufferResources();const n=this.renderer.getContext(),r=(e,t,s)=>{const i=e.createShader(t);if(!i)return qe.error("Fatal error: gl could not create a shader object."),null;if(e.shaderSource(i,s),e.compileShader(i),!e.getShaderParameter(i,e.COMPILE_STATUS)){let s="unknown";t===e.VERTEX_SHADER?s="vertex shader":t===e.FRAGMENT_SHADER&&(s="fragement shader");const n=e.getShaderInfoLog(i);return qe.error("Failed to compile "+s+" with these errors:"+n),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[${u.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[${u.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=n.getParameter(n.VERTEX_ARRAY_BINDING),l=n.getParameter(n.CURRENT_PROGRAM),c=!!l&&n.getProgramParameter(l,n.DELETE_STATUS);if(s&&(this.distancesTransformFeedback.vao=n.createVertexArray()),n.bindVertexArray(this.distancesTransformFeedback.vao),s){const e=n.createProgram(),t=r(n,n.VERTEX_SHADER,a),s=r(n,n.FRAGMENT_SHADER,"#version 300 es\n precision lowp float;\n out vec4 fragColor;\n void main(){}\n ");if(!t||!s)throw new Error("Could not compile shaders for distances computation on GPU.");if(n.attachShader(e,t),n.attachShader(e,s),n.transformFeedbackVaryings(e,["distance"],n.SEPARATE_ATTRIBS),n.linkProgram(e),!n.getProgramParameter(e,n.LINK_STATUS)){const i=n.getProgramInfoLog(e);throw qe.error("Fatal error: Failed to link program: "+i),n.deleteProgram(e),n.deleteShader(s),n.deleteShader(t),new Error("Could not link shaders for distances computation on GPU.")}this.distancesTransformFeedback.program=e,this.distancesTransformFeedback.vertexShader=t,this.distancesTransformFeedback.vertexShader=s}if(n.useProgram(this.distancesTransformFeedback.program),this.distancesTransformFeedback.centersLoc=n.getAttribLocation(this.distancesTransformFeedback.program,"center"),this.dynamicMode){this.distancesTransformFeedback.sceneIndexesLoc=n.getAttribLocation(this.distancesTransformFeedback.program,"sceneIndex");for(let e=0;e<this.scenes.length;e++)this.distancesTransformFeedback.transformsLocs[e]=n.getUniformLocation(this.distancesTransformFeedback.program,`transforms[${e}]`)}else this.distancesTransformFeedback.modelViewProjLoc=n.getUniformLocation(this.distancesTransformFeedback.program,"modelViewProj");(s||i)&&(this.distancesTransformFeedback.centersBuffer=n.createBuffer(),n.bindBuffer(n.ARRAY_BUFFER,this.distancesTransformFeedback.centersBuffer),n.enableVertexAttribArray(this.distancesTransformFeedback.centersLoc),this.integerBasedDistancesComputation?n.vertexAttribIPointer(this.distancesTransformFeedback.centersLoc,4,n.INT,0,0):n.vertexAttribPointer(this.distancesTransformFeedback.centersLoc,4,n.FLOAT,!1,0,0),this.dynamicMode&&(this.distancesTransformFeedback.sceneIndexesBuffer=n.createBuffer(),n.bindBuffer(n.ARRAY_BUFFER,this.distancesTransformFeedback.sceneIndexesBuffer),n.enableVertexAttribArray(this.distancesTransformFeedback.sceneIndexesLoc),n.vertexAttribIPointer(this.distancesTransformFeedback.sceneIndexesLoc,1,n.UNSIGNED_INT,0,0))),(s||i)&&(this.distancesTransformFeedback.outDistancesBuffer=n.createBuffer()),n.bindBuffer(n.ARRAY_BUFFER,this.distancesTransformFeedback.outDistancesBuffer),n.bufferData(n.ARRAY_BUFFER,4*t,n.STATIC_READ),s&&(this.distancesTransformFeedback.id=n.createTransformFeedback()),n.bindTransformFeedback(n.TRANSFORM_FEEDBACK,this.distancesTransformFeedback.id),n.bindBufferBase(n.TRANSFORM_FEEDBACK_BUFFER,0,this.distancesTransformFeedback.outDistancesBuffer),l&&!0!==c&&n.useProgram(l),o&&n.bindVertexArray(o),this.lastRenderer=this.renderer,e=t}}();updateGPUCentersBufferForDistancesComputation(e,t,s){if(!this.renderer)return;const i=this.renderer.getContext(),n=i.getParameter(i.VERTEX_ARRAY_BINDING);i.bindVertexArray(this.distancesTransformFeedback.vao);const r=this.integerBasedDistancesComputation?Uint32Array:Float32Array,a=16*s;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),n&&i.bindVertexArray(n)}updateGPUTransformIndexesBufferForDistancesComputation(e,t,s){if(!this.renderer||!this.dynamicMode)return;const i=this.renderer.getContext(),n=i.getParameter(i.VERTEX_ARRAY_BINDING);i.bindVertexArray(this.distancesTransformFeedback.vao);const r=4*s;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),n&&i.bindVertexArray(n)}getSceneIndexes(e,t){let s;s=new Uint32Array(t-e+1);for(let i=e;i<=t;i++)s[i]=this.globalSplatIndexToSceneIndexMap[i];return s}fillTransformsArray=function(){const e=[];return function(t){e.length!==t.length&&(e.length=t.length);for(let t=0;t<this.scenes.length;t++){const s=this.getScene(t).transform.elements;for(let i=0;i<16;i++)e[16*t+i]=s[i]}t.set(e)}}();computeDistancesOnGPU=function(){const t=new e.Matrix4;return(e,s)=>{if(!this.renderer)return;const i=this.renderer.getContext(),n=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 s=0;s<this.scenes.length;s++)if(t.copy(this.getScene(s).transform),t.premultiply(e),this.integerBasedDistancesComputation){const e=Ze.getIntegerMatrixArray(t),n=[e[2],e[6],e[10],e[14]];i.uniform4i(this.distancesTransformFeedback.transformsLocs[s],n[0],n[1],n[2],n[3])}else i.uniformMatrix4fv(this.distancesTransformFeedback.transformsLocs[s],!1,t.elements);else if(this.integerBasedDistancesComputation){const t=Ze.getIntegerMatrixArray(e),s=[t[2],t[6],t[10]];i.uniform3i(this.distancesTransformFeedback.modelViewProjLoc,s[0],s[1],s[2])}else{const t=[e.elements[2],e.elements[6],e.elements[10]];i.uniform3f(this.distancesTransformFeedback.modelViewProjLoc,t[0],t[1],t[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 n=0,r=0;switch(i.clientWaitSync(o,r,n)){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,s),i.bindBuffer(i.ARRAY_BUFFER,null),t&&i.bindVertexArray(t),e()}}}};this.computeDistancesOnGPUSyncTimeout=setTimeout(t)});return r&&!0!==a&&i.useProgram(r),n&&i.bindVertexArray(n),l}}();getLocalSplatParameters(e,t,s){null==s&&(s=!this.dynamicMode),t.splatBuffer=this.getSplatBufferForSplat(e),t.localIndex=this.getSplatLocalIndex(e),t.sceneTransform=s?this.getSceneTransformForSplat(e):null}fillSplatDataArrays(t,s,i,n,r,a,o,l,c=0,h=0,u=1,p,m,g=0,A){const f=new e.Vector3;f.x=void 0,f.y=void 0,this.splatRenderMode===d.ThreeD?f.z=void 0:f.z=1;const S=new e.Matrix4;let C=0,x=this.scenes.length-1;null!=A&&A>=0&&A<=this.scenes.length&&(C=A,x=A);for(let e=C;e<=x;e++){null==l&&(l=!this.dynamicMode);const o=this.getScene(e),d=o.splatBuffer;let A;if(l&&(this.getSceneTransform(e,S),A=S),t&&d.fillSplatCovarianceArray(t,A,p,m,g,c),s||i){if(!s||!i)throw new Error('SplatMesh::fillSplatDataArrays() -> "scales" and "rotations" must both be valid.');d.fillSplatScaleRotationArray(s,i,A,p,m,g,h,f)}n&&d.fillSplatCenterArray(this.morphedMesh,n,A,p,m,g),r&&d.fillSplatColorArray(r,o.minimumAlpha,p,m,g),a&&d.fillSphericalHarmonicsArray(a,this.minSphericalHarmonicsDegree,A,p,m,g,u),g+=d.getSplatCount()}}morphedMesh;getIntegerCenters(e,t,s=!1){const i=t-e+1,n=new Float32Array(3*i);let r;this.fillSplatDataArrays(null,null,null,n,null,null,void 0,void 0,void 0,void 0,e);let a=s?4:3;r=new Int32Array(i*a);for(let e=0;e<i;e++){for(let t=0;t<3;t++)r[e*a+t]=Math.round(1e3*n[3*e+t]);s&&(r[e*a+3]=1e3)}return r}getFloatCenters(e,t,s=!1){const i=t-e+1,n=new Float32Array(3*i);if(this.fillSplatDataArrays(null,null,null,n,null,null,void 0,void 0,void 0,void 0,e),!s)return n;let r=new Float32Array(4*i);for(let e=0;e<i;e++){for(let t=0;t<3;t++)r[4*e+t]=n[3*e+t];r[4*e+3]=1}return r}getSplatCenter=function(){const e={};return function(t,s,i,n){this.getLocalSplatParameters(s,e,n),e.splatBuffer.getSplatCenter(t,e.localIndex,i,e.sceneTransform)}}();getSplatScaleAndRotation=function(){const t={},s=new e.Vector3;return function(e,i,n,r){this.getLocalSplatParameters(e,t,r),s.x=void 0,s.y=void 0,s.z=void 0,this.splatRenderMode===d.TwoD&&(s.z=0),t.splatBuffer.getSplatScaleAndRotation(t.localIndex,i,n,t.sceneTransform,s)}}();getSplatColor=function(){const e={};return function(t,s){this.getLocalSplatParameters(t,e),e.splatBuffer.getSplatColor(e.localIndex,s)}}();getSceneTransform(e,t){const s=this.getScene(e);s.updateTransform(this.dynamicMode),t.copy(s.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,s=[];for(let e=0;e<16;e++)s[e]=Math.round(1e3*t[e]);return s}computeBoundingBox(t=!1,s){let i=this.getSplatCount();if(null!=s){if(s<0||s>=this.scenes.length)throw new Error("SplatMesh::computeBoundingBox() -> Invalid scene index.");i=this.scenes[s].splatBuffer.getSplatCount()}const n=new Float32Array(3*i);this.fillSplatDataArrays(null,null,null,n,null,null,t,void 0,void 0,void 0,void 0,s);const r=new e.Vector3,a=new e.Vector3;for(let e=0;e<i;e++){const t=3*e,s=n[t],i=n[t+1],o=n[t+2];(0===e||s<r.x)&&(r.x=s),(0===e||i<r.y)&&(r.y=i),(0===e||o<r.z)&&(r.z=o),(0===e||s>a.x)&&(a.x=s),(0===e||i>a.y)&&(a.y=i),(0===e||o>a.z)&&(a.z=o)}return new e.Box3(r,a)}}class et extends Error{constructor(e){super(e),this.name="DirectLoadError"}}class tt{static 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};constructor(e=0){this.sphericalHarmonicsDegree=e,this.sphericalHarmonicsCount=U(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 s=U(e);for(let e=0;e<s;e++)t.push(0);return t}addSplat(e){this.splats.push(e),this.splatCount++}getSplat(e){return this.splats[e]}addDefaultSplat(){const e=tt.createSplat(this.sphericalHarmonicsDegree);return this.addSplat(e),e}addSplatFromComonents(e,t,s,i,n,r,a,o,l,c,h,d,u,p,...m){const g=[e,t,s,i,n,r,a,o,l,c,h,d,u,p,...this.defaultSphericalHarmonics];for(let e=0;e<m.length&&e<this.sphericalHarmonicsCount;e++)g[e]=m[e];return this.addSplat(g),g}addSplatFromArray(e,t){const s=e.splats[t],i=tt.createSplat(this.sphericalHarmonicsDegree);for(let e=0;e<this.componentCount&&e<s.length;e++)i[e]=s[e];this.addSplat(i)}}const st=(e,t,s,i,n=0)=>{const r=new Uint8Array(e,t),a=new Uint8Array(s,i);for(let e=0;e<n;e++)a[e]=r[e]},it=e.DataUtils.toHalfFloat.bind(e.DataUtils),nt=e.DataUtils.fromHalfFloat.bind(e.DataUtils),rt=(t,s,i=!1,n,r)=>0===s?t:1===s||2===s&&!i?e.DataUtils.fromHalfFloat(t):2===s?ot(t,n,r):void 0,at=(e,t,s)=>{e=P(e,t,s);const i=s-t;return P(Math.floor((e-t)/i*255),0,255)},ot=(e,t,s)=>e/255*(s-t)+t,lt=(e,t,s,i=!1)=>0===s?e.getFloat32(4*t,!0):1===s||2===s&&!i?e.getUint16(2*t,!0):e.getUint8(t,!0);class ct{static CurrentMajorVersion=0;static CurrentMinorVersion=1;static CenterComponentCount=3;static ScaleComponentCount=3;static RotationComponentCount=4;static ColorComponentCount=4;static CovarianceComponentCount=6;static SplatScaleOffsetFloat=3;static SplatRotationOffsetFloat=6;static 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}}}};static CovarianceSizeFloats=6;static HeaderSizeBytes=4096;static SectionHeaderSizeBytes=1024;static BucketStorageSizeBytes=12;static BucketStorageSizeFloats=3;static BucketBlockSize=5;static BucketSize=256;constructor(e,t=!0){this.constructFromBuffer(e,t)}getSplatCount(){return this.splatCount}getMaxSplatCount(){return this.maxSplatCount}getMinSphericalHarmonicsDegree(){let e=0;for(let t=0;t<this.sections.length;t++){const s=this.sections[t];(0===t||s.sphericalHarmonicsDegree<e)&&(e=s.sphericalHarmonicsDegree)}return e}getBucketIndex(e,t){let s;const i=e.fullBucketCount*e.bucketSize;if(t<i)s=Math.floor(t/e.bucketSize);else{let n=i;s=e.fullBucketCount;let r=0;for(;n<e.splatCount;){let i=e.partiallyFilledBucketLengths[r];if(t>=n&&t<n+i)break;n+=i,s++,r++}}return s}getSplatCenter(e,t,s,i){const n=this.globalSplatIndexToSectionMap[t],r=this.sections[n],a=t-r.splatCountOffset,o=r.bytesPerSplat*a,l=new DataView(this.bufferData,r.dataBase+o),c=lt(l,0,this.compressionLevel),h=lt(l,1,this.compressionLevel),d=lt(l,2,this.compressionLevel);if(this.compressionLevel>=1){const e=this.getBucketIndex(r,a)*ct.BucketStorageSizeFloats,t=r.compressionScaleFactor,i=r.compressionScaleRange;s.x=(c-i)*t+r.bucketArray[e],s.y=(h-i)*t+r.bucketArray[e+1],s.z=(d-i)*t+r.bucketArray[e+2]}else s.x=c,s.y=h,s.z=d;s.x+=e[3*t+0],s.y+=e[3*t+1],s.z+=e[3*t+2],i&&s.applyMatrix4(i)}getSplatScaleAndRotation=function(){const t=new e.Matrix4,s=new e.Matrix4,i=new e.Matrix4,n=new e.Vector3,r=new e.Vector3,a=new e.Quaternion;return function(e,o,l,c,h){const d=this.globalSplatIndexToSectionMap[e],u=this.sections[d],p=e-u.splatCountOffset,m=u.bytesPerSplat*p+ct.CompressionLevels[this.compressionLevel].ScaleOffsetBytes,g=new DataView(this.bufferData,u.dataBase+m);r.set(rt(lt(g,0,this.compressionLevel),this.compressionLevel),rt(lt(g,1,this.compressionLevel),this.compressionLevel),rt(lt(g,2,this.compressionLevel),this.compressionLevel)),h&&(void 0!==h.x&&(r.x=h.x),void 0!==h.y&&(r.y=h.y),void 0!==h.z&&(r.z=h.z)),a.set(rt(lt(g,4,this.compressionLevel),this.compressionLevel),rt(lt(g,5,this.compressionLevel),this.compressionLevel),rt(lt(g,6,this.compressionLevel),this.compressionLevel),rt(lt(g,3,this.compressionLevel),this.compressionLevel)),c?(t.makeScale(r.x,r.y,r.z),s.makeRotationFromQuaternion(a),i.copy(t).multiply(s).multiply(c),i.decompose(n,l,o)):(o.copy(r),l.copy(a))}}();getSplatColor(e,t){const s=this.globalSplatIndexToSectionMap[e],i=this.sections[s],n=e-i.splatCountOffset,r=i.bytesPerSplat*n+ct.CompressionLevels[this.compressionLevel].ColorOffsetBytes,a=new Uint8Array(this.bufferData,i.dataBase+r,4);t.set(a[0],a[1],a[2],a[3])}fillSplatCenterArray(t,s,i,n,r,a){const o=this.splatCount;n=n||0,r=r||o-1,void 0===a&&(a=n);const l=new e.Vector3;for(let e=n;e<=r;e++){const r=this.globalSplatIndexToSectionMap[e],o=this.sections[r],c=e-o.splatCountOffset,h=(e-n+a)*ct.CenterComponentCount,d=o.bytesPerSplat*c,u=new DataView(this.bufferData,o.dataBase+d),p=lt(u,0,this.compressionLevel),m=lt(u,1,this.compressionLevel),g=lt(u,2,this.compressionLevel);if(this.compressionLevel>=1){const e=this.getBucketIndex(o,c)*ct.BucketStorageSizeFloats,t=o.compressionScaleFactor,s=o.compressionScaleRange;l.x=(p-s)*t+o.bucketArray[e],l.y=(m-s)*t+o.bucketArray[e+1],l.z=(g-s)*t+o.bucketArray[e+2]}else l.x=p,l.y=m,l.z=g;i&&l.applyMatrix4(i),s[h]=l.x+t[3*e+0],s[h+1]=l.y+t[3*e+1],s[h+2]=l.z+t[3*e+2]}}fillSplatScaleRotationArray=function(){const t=new e.Matrix4,s=new e.Matrix4,i=new e.Matrix4,n=new e.Vector3,r=new e.Quaternion,a=new e.Vector3,o=e=>{const t=e.w<0?-1:1;e.x*=t,e.y*=t,e.z*=t,e.w*=t};return function(e,l,c,h,d,u,p,m){const g=this.splatCount;h=h||0,d=d||g-1,void 0===u&&(u=h);const A=(e,t)=>J(e,t,p);for(let p=h;p<=d;p++){const d=this.globalSplatIndexToSectionMap[p],g=this.sections[d],f=p-g.splatCountOffset,S=g.bytesPerSplat*f+ct.CompressionLevels[this.compressionLevel].ScaleOffsetBytes,C=(p-h+u)*ct.ScaleComponentCount,x=(p-h+u)*ct.RotationComponentCount,y=new DataView(this.bufferData,g.dataBase+S),v=m&&void 0!==m.x?m.x:lt(y,0,this.compressionLevel),I=m&&void 0!==m.y?m.y:lt(y,1,this.compressionLevel),b=m&&void 0!==m.z?m.z:lt(y,2,this.compressionLevel),w=lt(y,3,this.compressionLevel),B=lt(y,4,this.compressionLevel),T=lt(y,5,this.compressionLevel),D=lt(y,6,this.compressionLevel);n.set(rt(v,this.compressionLevel),rt(I,this.compressionLevel),rt(b,this.compressionLevel)),r.set(rt(B,this.compressionLevel),rt(T,this.compressionLevel),rt(D,this.compressionLevel),rt(w,this.compressionLevel)).normalize(),c&&(a.set(0,0,0),t.makeScale(n.x,n.y,n.z),s.makeRotationFromQuaternion(r),i.identity().premultiply(t).premultiply(s),i.premultiply(c),i.decompose(a,r,n),r.normalize()),o(r),e&&(e[C]=A(n.x,0),e[C+1]=A(n.y,0),e[C+2]=A(n.z,0)),l&&(l[x]=A(r.x,0),l[x+1]=A(r.y,0),l[x+2]=A(r.z,0),l[x+3]=A(r.w,0))}}}();static computeCovariance=function(){const t=new e.Matrix4,s=new e.Matrix3,i=new e.Matrix3,n=new e.Matrix3,r=new e.Matrix3,a=new e.Matrix3,o=new e.Matrix3;return function(e,l,c,h,d=0,u){t.makeScale(e.x,e.y,e.z),s.setFromMatrix4(t),t.makeRotationFromQuaternion(l),i.setFromMatrix4(t),n.copy(i).multiply(s),r.copy(n).transpose().premultiply(n),c&&(a.setFromMatrix4(c),o.copy(a).transpose(),r.multiply(o),r.premultiply(a)),u>=1?(h[d]=it(r.elements[0]),h[d+1]=it(r.elements[3]),h[d+2]=it(r.elements[6]),h[d+3]=it(r.elements[4]),h[d+4]=it(r.elements[7]),h[d+5]=it(r.elements[8])):(h[d]=r.elements[0],h[d+1]=r.elements[3],h[d+2]=r.elements[6],h[d+3]=r.elements[4],h[d+4]=r.elements[7],h[d+5]=r.elements[8])}}();fillSplatCovarianceArray(t,s,i,n,r,a){const o=this.splatCount,l=new e.Vector3,c=new e.Quaternion;i=i||0,n=n||o-1,void 0===r&&(r=i);for(let e=i;e<=n;e++){const n=this.globalSplatIndexToSectionMap[e],o=this.sections[n],h=e-o.splatCountOffset,d=(e-i+r)*ct.CovarianceComponentCount,u=o.bytesPerSplat*h+ct.CompressionLevels[this.compressionLevel].ScaleOffsetBytes,p=new DataView(this.bufferData,o.dataBase+u);l.set(rt(lt(p,0,this.compressionLevel),this.compressionLevel),rt(lt(p,1,this.compressionLevel),this.compressionLevel),rt(lt(p,2,this.compressionLevel),this.compressionLevel)),c.set(rt(lt(p,4,this.compressionLevel),this.compressionLevel),rt(lt(p,5,this.compressionLevel),this.compressionLevel),rt(lt(p,6,this.compressionLevel),this.compressionLevel),rt(lt(p,3,this.compressionLevel),this.compressionLevel)),ct.computeCovariance(l,c,s,t,d,a)}}fillSplatColorArray(e,t,s,i,n){const r=this.splatCount;s=s||0,i=i||r-1,void 0===n&&(n=s);for(let r=s;r<=i;r++){const i=this.globalSplatIndexToSectionMap[r],a=this.sections[i],o=r-a.splatCountOffset,l=(r-s+n)*ct.ColorComponentCount,c=a.bytesPerSplat*o+ct.CompressionLevels[this.compressionLevel].ColorOffsetBytes,h=new Uint8Array(this.bufferData,a.dataBase+c);let d=h[3];d=d>=t?d:0,e[l]=h[0],e[l+1]=h[1],e[l+2]=h[2],e[l+3]=d}}fillSphericalHarmonicsArray=function(){for(let t=0;t<15;t++)new e.Vector3;const t=new e.Matrix3,s=new e.Matrix4,i=new e.Vector3,n=new e.Vector3,r=new e.Quaternion,a=[],o=[],l=[],c=[],h=[],d=[],u=[],p=[],m=[],g=[],A=[],f=[],S=[],C=[],x=[],y=[],v=[],I=[],b=e=>e,w=(e,t,s,i)=>{e[0]=t,e[1]=s,e[2]=i},B=(e,t,s,i,n)=>{e[0]=lt(t,i,n,!0),e[1]=lt(t,i+s,n,!0),e[2]=lt(t,i+s+s,n,!0)},T=(e,t)=>{t[0]=e[0],t[1]=e[1],t[2]=e[2]},D=(e,t,s,i)=>{t[s]=i(e[0]),t[s+1]=i(e[1]),t[s+2]=i(e[2])},E=(e,t,s,i,n)=>(t[0]=rt(e[0],s,!0,i,n),t[1]=rt(e[1],s,!0,i,n),t[2]=rt(e[2],s,!0,i,n),t);return function(e,M,R,F,P,k,_){const L=this.splatCount;F=F||0,P=P||L-1,void 0===k&&(k=F),R&&M>=1&&(s.copy(R),s.decompose(i,r,n),r.normalize(),s.makeRotationFromQuaternion(r),t.setFromMatrix4(s),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 O=e=>((e,t,s)=>at(nt(e),t,s))(e,this.minSphericalHarmonicsCoeff,this.maxSphericalHarmonicsCoeff),H=e=>at(e,this.minSphericalHarmonicsCoeff,this.maxSphericalHarmonicsCoeff);for(let t=F;t<=P;t++){const s=this.globalSplatIndexToSectionMap[t],i=this.sections[s];M=Math.min(M,i.sphericalHarmonicsDegree);const n=U(M),r=t-i.splatCountOffset,w=i.bytesPerSplat*r+ct.CompressionLevels[this.compressionLevel].SphericalHarmonicsOffsetBytes,P=new DataView(this.bufferData,i.dataBase+w),L=(t-F+k)*n;let z=R?0:this.compressionLevel,Q=b;z!==_&&(1===z?0===_?Q=nt:2==_&&(Q=O):0===z&&(1===_?Q=it:2==_&&(Q=H)));const V=this.minSphericalHarmonicsCoeff,N=this.maxSphericalHarmonicsCoeff;M>=1&&(B(m,P,3,0,this.compressionLevel),B(g,P,3,1,this.compressionLevel),B(A,P,3,2,this.compressionLevel),R?(E(m,m,this.compressionLevel,V,N),E(g,g,this.compressionLevel,V,N),E(A,A,this.compressionLevel,V,N),ct.rotateSphericalHarmonics3(m,g,A,a,o,l,C,x,y)):(T(m,C),T(g,x),T(A,y)),D(C,e,L,Q),D(x,e,L+3,Q),D(y,e,L+6,Q),M>=2&&(B(m,P,5,9,this.compressionLevel),B(g,P,5,10,this.compressionLevel),B(A,P,5,11,this.compressionLevel),B(f,P,5,12,this.compressionLevel),B(S,P,5,13,this.compressionLevel),R?(E(m,m,this.compressionLevel,V,N),E(g,g,this.compressionLevel,V,N),E(A,A,this.compressionLevel,V,N),E(f,f,this.compressionLevel,V,N),E(S,S,this.compressionLevel,V,N),ct.rotateSphericalHarmonics5(m,g,A,f,S,a,o,l,c,h,d,u,p,C,x,y,v,I)):(T(m,C),T(g,x),T(A,y),T(f,v),T(S,I)),D(C,e,L+9,Q),D(x,e,L+12,Q),D(y,e,L+15,Q),D(v,e,L+18,Q),D(I,e,L+21,Q)))}}}();static dot3=(e,t,s,i,n)=>{n[0]=n[1]=n[2]=0;const r=i[0],a=i[1],o=i[2];ct.addInto3(e[0]*r,e[1]*r,e[2]*r,n),ct.addInto3(t[0]*a,t[1]*a,t[2]*a,n),ct.addInto3(s[0]*o,s[1]*o,s[2]*o,n)};static addInto3=(e,t,s,i)=>{i[0]=i[0]+e,i[1]=i[1]+t,i[2]=i[2]+s};static dot5=(e,t,s,i,n,r,a)=>{a[0]=a[1]=a[2]=0;const o=r[0],l=r[1],c=r[2],h=r[3],d=r[4];ct.addInto3(e[0]*o,e[1]*o,e[2]*o,a),ct.addInto3(t[0]*l,t[1]*l,t[2]*l,a),ct.addInto3(s[0]*c,s[1]*c,s[2]*c,a),ct.addInto3(i[0]*h,i[1]*h,i[2]*h,a),ct.addInto3(n[0]*d,n[1]*d,n[2]*d,a)};static rotateSphericalHarmonics3=(e,t,s,i,n,r,a,o,l)=>{ct.dot3(e,t,s,i,a),ct.dot3(e,t,s,n,o),ct.dot3(e,t,s,r,l)};static rotateSphericalHarmonics5=(e,t,s,i,n,r,a,o,l,c,h,d,u,p,m,g,A,f)=>{const S=Math.sqrt(1/4),C=Math.sqrt(3/4),x=Math.sqrt(1/3),y=Math.sqrt(4/3),v=Math.sqrt(1/12);l[0]=S*(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]=C*(o[1]*r[1]+r[1]*o[1]),l[3]=o[1]*r[2]+r[1]*o[2],l[4]=S*(o[2]*r[2]-o[0]*r[0]+(r[2]*o[2]-r[0]*o[0])),ct.dot5(e,t,s,i,n,l,p),c[0]=S*(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]=C*(a[1]*r[1]+r[1]*a[1]),c[3]=a[1]*r[2]+r[1]*a[2],c[4]=S*(a[2]*r[2]-a[0]*r[0]+(r[2]*a[2]-r[0]*a[0])),ct.dot5(e,t,s,i,n,c,m),h[0]=x*(a[2]*a[0]+a[0]*a[2])+-v*(o[2]*o[0]+o[0]*o[2]+(r[2]*r[0]+r[0]*r[2])),h[1]=y*a[1]*a[0]+-x*(o[1]*o[0]+r[1]*r[0]),h[2]=a[1]*a[1]+-S*(o[1]*o[1]+r[1]*r[1]),h[3]=y*a[1]*a[2]+-x*(o[1]*o[2]+r[1]*r[2]),h[4]=x*(a[2]*a[2]-a[0]*a[0])+-v*(o[2]*o[2]-o[0]*o[0]+(r[2]*r[2]-r[0]*r[0])),ct.dot5(e,t,s,i,n,h,g),d[0]=S*(a[2]*o[0]+a[0]*o[2]+(o[2]*a[0]+o[0]*a[2])),d[1]=a[1]*o[0]+o[1]*a[0],d[2]=C*(a[1]*o[1]+o[1]*a[1]),d[3]=a[1]*o[2]+o[1]*a[2],d[4]=S*(a[2]*o[2]-a[0]*o[0]+(o[2]*a[2]-o[0]*a[0])),ct.dot5(e,t,s,i,n,d,A),u[0]=S*(o[2]*o[0]+o[0]*o[2]-(r[2]*r[0]+r[0]*r[2])),u[1]=o[1]*o[0]-r[1]*r[0],u[2]=C*(o[1]*o[1]-r[1]*r[1]),u[3]=o[1]*o[2]-r[1]*r[2],u[4]=S*(o[2]*o[2]-o[0]*o[0]-(r[2]*r[2]-r[0]*r[0])),ct.dot5(e,t,s,i,n,u,f)};static parseHeader(t){const s=new Uint8Array(t,0,ct.HeaderSizeBytes),i=new Uint16Array(t,0,ct.HeaderSizeBytes/2),n=new Uint32Array(t,0,ct.HeaderSizeBytes/4),r=new Float32Array(t,0,ct.HeaderSizeBytes/4);return{versionMajor:s[0],versionMinor:s[1],maxSectionCount:n[1],sectionCount:n[2],maxSplatCount:n[3],splatCount:n[4],compressionLevel:i[10],sceneCenter:new e.Vector3(r[6],r[7],r[8]),minSphericalHarmonicsCoeff:r[9]||-W,maxSphericalHarmonicsCoeff:r[10]||W}}static writeHeaderCountsToBuffer(e,t,s){const i=new Uint32Array(s,0,ct.HeaderSizeBytes/4);i[2]=e,i[4]=t}static writeHeaderToBuffer(e,t){const s=new Uint8Array(t,0,ct.HeaderSizeBytes),i=new Uint16Array(t,0,ct.HeaderSizeBytes/2),n=new Uint32Array(t,0,ct.HeaderSizeBytes/4),r=new Float32Array(t,0,ct.HeaderSizeBytes/4);s[0]=e.versionMajor,s[1]=e.versionMinor,s[2]=0,s[3]=0,n[1]=e.maxSectionCount,n[2]=e.sectionCount,n[3]=e.maxSplatCount,n[4]=e.splatCount,i[10]=e.compressionLevel,r[6]=e.sceneCenter.x,r[7]=e.sceneCenter.y,r[8]=e.sceneCenter.z,r[9]=e.minSphericalHarmonicsCoeff||-W,r[10]=e.maxSphericalHarmonicsCoeff||W}static parseSectionHeaders(e,t,s=0,i){const n=e.compressionLevel,r=e.maxSectionCount,a=new Uint16Array(t,s,r*ct.SectionHeaderSizeBytes/2),o=new Uint32Array(t,s,r*ct.SectionHeaderSizeBytes/4),l=new Float32Array(t,s,r*ct.SectionHeaderSizeBytes/4),c=[];let h=0,d=h/2,u=h/4,p=ct.HeaderSizeBytes+e.maxSectionCount*ct.SectionHeaderSizeBytes,m=0;for(let e=0;e<r;e++){const t=o[u+1],s=o[u+2],r=o[u+3],g=l[u+4],A=g/2,f=a[d+10],S=o[u+6]||ct.CompressionLevels[n].ScaleRange,C=o[u+8],x=o[u+9],y=4*x,v=f*r+y,I=a[d+20],{bytesPerSplat:b}=ct.calculateComponentStorage(n,I),w=b*t,B=w+v,T={bytesPerSplat:b,splatCountOffset:m,splatCount:i?t:0,maxSplatCount:t,bucketSize:s,bucketCount:r,bucketBlockSize:g,halfBucketBlockSize:A,bucketStorageSizeBytes:f,bucketsStorageSizeBytes:v,splatDataStorageSizeBytes:w,storageSizeBytes:B,compressionScaleRange:S,compressionScaleFactor:A/S,base:p,bucketsBase:p+y,dataBase:p+v,fullBucketCount:C,partiallyFilledBucketCount:x,sphericalHarmonicsDegree:I};c[e]=T,p+=B,h+=ct.SectionHeaderSizeBytes,d=h/2,u=h/4,m+=t}return c}static writeSectionHeaderToBuffer(e,t,s,i=0){const n=new Uint16Array(s,i,ct.SectionHeaderSizeBytes/2),r=new Uint32Array(s,i,ct.SectionHeaderSizeBytes/4),a=new Float32Array(s,i,ct.SectionHeaderSizeBytes/4);r[0]=e.splatCount,r[1]=e.maxSplatCount,r[2]=t>=1?e.bucketSize:0,r[3]=t>=1?e.bucketCount:0,a[4]=t>=1?e.bucketBlockSize:0,n[10]=t>=1?ct.BucketStorageSizeBytes:0,r[6]=t>=1?e.compressionScaleRange:0,r[7]=e.storageSizeBytes,r[8]=t>=1?e.fullBucketCount:0,r[9]=t>=1?e.partiallyFilledBucketCount:0,n[20]=e.sphericalHarmonicsDegree}static writeSectionHeaderSplatCountToBuffer(e,t,s=0){new Uint32Array(t,s,ct.SectionHeaderSizeBytes/4)[0]=e}constructFromBuffer(t,s){this.bufferData=t,this.globalSplatIndexToLocalSplatIndexMap=[],this.globalSplatIndexToSectionMap=[];const i=ct.parseHeader(this.bufferData);this.versionMajor=i.versionMajor,this.versionMinor=i.versionMinor,this.maxSectionCount=i.maxSectionCount,this.sectionCount=s?i.maxSectionCount:0,this.maxSplatCount=i.maxSplatCount,this.splatCount=s?i.maxSplatCount:0,this.compressionLevel=i.compressionLevel,this.sceneCenter=(new e.Vector3).copy(i.sceneCenter),this.minSphericalHarmonicsCoeff=i.minSphericalHarmonicsCoeff,this.maxSphericalHarmonicsCoeff=i.maxSphericalHarmonicsCoeff,this.sections=ct.parseSectionHeaders(i,this.bufferData,ct.HeaderSizeBytes,s),this.linkBufferArrays(),this.buildMaps()}static calculateComponentStorage(e,t){const s=ct.CompressionLevels[e].BytesPerCenter,i=ct.CompressionLevels[e].BytesPerScale,n=ct.CompressionLevels[e].BytesPerRotation,r=ct.CompressionLevels[e].BytesPerColor,a=U(t),o=ct.CompressionLevels[e].BytesPerSphericalHarmonicsComponent*a;return{bytesPerCenter:s,bytesPerScale:i,bytesPerRotation:n,bytesPerColor:r,sphericalHarmonicsComponentsPerSplat:a,sphericalHarmonicsBytesPerSplat:o,bytesPerSplat:s+i+n+r+o}}linkBufferArrays(){for(let e=0;e<this.maxSectionCount;e++){const t=this.sections[e];t.bucketArray=new Float32Array(this.bufferData,t.bucketsBase,t.bucketCount*ct.BucketStorageSizeFloats),t.partiallyFilledBucketCount>0&&(t.partiallyFilledBucketLengths=new Uint32Array(this.bufferData,t.base,t.partiallyFilledBucketCount))}}buildMaps(){let e=0;for(let t=0;t<this.maxSectionCount;t++){const s=this.sections[t];for(let i=0;i<s.maxSplatCount;i++){const s=e+i;this.globalSplatIndexToLocalSplatIndexMap[s]=i,this.globalSplatIndexToSectionMap[s]=t}e+=s.maxSplatCount}}updateLoadedCounts(e,t){ct.writeHeaderCountsToBuffer(e,t,this.bufferData),this.sectionCount=e,this.splatCount=t}updateSectionLoadedCounts(e,t){const s=ct.HeaderSizeBytes+ct.SectionHeaderSizeBytes*e;ct.writeSectionHeaderSplatCountToBuffer(t,this.bufferData,s),this.sections[e].splatCount=t}static writeSplatDataToSectionBuffer=function(){const t=new ArrayBuffer(12),s=new ArrayBuffer(12),i=new ArrayBuffer(16),n=new ArrayBuffer(4),r=new ArrayBuffer(256),a=new e.Quaternion,o=new e.Vector3,l=new e.Vector3,{X:c,Y:h,Z:d,SCALE0:u,SCALE1:p,SCALE2:m,ROTATION0:g,ROTATION1:A,ROTATION2:f,ROTATION3:S,FDC0:C,FDC1:x,FDC2:y,OPACITY:v,FRC0:I,FRC9:b}=tt.OFFSET,w=(e,t,s)=>{const i=2*s+1;return e=Math.round(e*t)+s,P(e,0,i)};return function(e,B,T,D,E,M,R,F,P=-W,k=W){const _=U(E),L=T,O=L+ct.CompressionLevels[D].BytesPerCenter,H=O+ct.CompressionLevels[D].BytesPerScale,z=H+ct.CompressionLevels[D].BytesPerRotation,Q=z+ct.CompressionLevels[D].BytesPerColor;if(void 0!==e[g]?(a.set(e[g],e[A],e[f],e[S]),a.normalize()):a.set(1,0,0,0),void 0!==e[u]?o.set(e[u]||0,e[p]||0,e[m]||0):o.set(0,0,0),0===D){const t=new Float32Array(B,L,ct.CenterComponentCount),s=new Float32Array(B,H,ct.RotationComponentCount),i=new Float32Array(B,O,ct.ScaleComponentCount);if(s.set([a.x,a.y,a.z,a.w]),i.set([o.x,o.y,o.z]),t.set([e[c],e[h],e[d]]),E>0){const t=new Float32Array(B,Q,_);if(E>=1){for(let s=0;s<9;s++)t[s]=e[I+s]||0;if(E>=2)for(let s=0;s<15;s++)t[s+9]=e[b+s]||0}}}else{const n=new Uint16Array(t,0,ct.CenterComponentCount),u=new Uint16Array(i,0,ct.RotationComponentCount),p=new Uint16Array(s,0,ct.ScaleComponentCount);if(u.set([it(a.x),it(a.y),it(a.z),it(a.w)]),p.set([it(o.x),it(o.y),it(o.z)]),l.set(e[c],e[h],e[d]).sub(M),l.x=w(l.x,R,F),l.y=w(l.y,R,F),l.z=w(l.z,R,F),n.set([l.x,l.y,l.z]),E>0){const t=1===D?2:1,s=new(1===D?Uint16Array:Uint8Array)(r,0,_);if(E>=1){for(let t=0;t<9;t++){const i=e[I+t]||0;s[t]=1===D?it(i):at(i,P,k)}const i=9*t;if(st(s.buffer,0,B,Q,i),E>=2){for(let t=0;t<15;t++){const i=e[b+t]||0;s[t+9]=1===D?it(i):at(i,P,k)}st(s.buffer,i,B,Q+i,15*t)}}}st(n.buffer,0,B,L,6),st(p.buffer,0,B,O,6),st(u.buffer,0,B,H,8)}const V=new Uint8ClampedArray(n,0,4);V.set([e[C]||0,e[x]||0,e[y]||0]),V[3]=e[v]||0,st(V.buffer,0,B,z,4)}}();static generateFromUncompressedSplatArrays(t,s,i,n,r,a,o=[]){let l,c,h=0;for(let e=0;e<t.length;e++){const s=t[e];h=Math.max(s.sphericalHarmonicsDegree,h)}for(let e=0;e<t.length;e++){const s=t[e];for(let e=0;e<s.splats.length;e++){const t=s.splats[e];for(let e=tt.OFFSET.FRC0;e<tt.OFFSET.FRC23&&e<t.length;e++)(!l||t[e]<l)&&(l=t[e]),(!c||t[e]>c)&&(c=t[e])}}l=l||-W,c=c||W;const{bytesPerSplat:d}=ct.calculateComponentStorage(i,h),u=ct.CompressionLevels[i].ScaleRange,p=[],m=[];let g=0;for(let n=0;n<t.length;n++){const A=t[n],f=new tt(h);for(let e=0;e<A.splatCount;e++){const t=A.splats[e];(t[tt.OFFSET.OPACITY]||0)>=s&&f.addSplat(t)}const S=o[n]||{},C=(S.blockSizeFactor||1)*(r||ct.BucketBlockSize),x=Math.ceil((S.bucketSizeFactor||1)*(a||ct.BucketSize)),y=ct.computeBucketsForUncompressedSplatArray(f,C,x),v=y.fullBuckets.length,I=y.partiallyFullBuckets.map(e=>e.splats.length),b=I.length,w=[...y.fullBuckets,...y.partiallyFullBuckets],B=f.splats.length*d,T=4*b,D=i>=1?w.length*ct.BucketStorageSizeBytes+T:0,E=B+D,M=new ArrayBuffer(E),R=u/(.5*C),F=new e.Vector3;let P=0;for(let e=0;e<w.length;e++){const t=w[e];F.fromArray(t.center);for(let e=0;e<t.splats.length;e++){let s=t.splats[e];const n=f.splats[s],r=D+P*d;ct.writeSplatDataToSectionBuffer(n,M,r,i,h,F,R,u,l,c),P++}}if(g+=P,i>=1){const e=new Uint32Array(M,0,4*I.length);for(let t=0;t<I.length;t++)e[t]=I[t];const t=new Float32Array(M,T,w.length*ct.BucketStorageSizeFloats);for(let e=0;e<w.length;e++){const s=w[e],i=3*e;t[i]=s.center[0],t[i+1]=s.center[1],t[i+2]=s.center[2]}}p.push(M);const k=new ArrayBuffer(ct.SectionHeaderSizeBytes);ct.writeSectionHeaderToBuffer({maxSplatCount:P,splatCount:P,bucketSize:x,bucketCount:w.length,bucketBlockSize:C,compressionScaleRange:u,storageSizeBytes:E,fullBucketCount:v,partiallyFilledBucketCount:b,sphericalHarmonicsDegree:h},i,k,0),m.push(k)}let A=0;for(let e of p)A+=e.byteLength;const f=ct.HeaderSizeBytes+ct.SectionHeaderSizeBytes*p.length+A,S=new ArrayBuffer(f);ct.writeHeaderToBuffer({versionMajor:0,versionMinor:1,maxSectionCount:p.length,sectionCount:p.length,maxSplatCount:g,splatCount:g,compressionLevel:i,sceneCenter:n,minSphericalHarmonicsCoeff:l,maxSphericalHarmonicsCoeff:c},S);let C=ct.HeaderSizeBytes;for(let e of m)new Uint8Array(S,C,ct.SectionHeaderSizeBytes).set(new Uint8Array(e)),C+=ct.SectionHeaderSizeBytes;for(let e of p)new Uint8Array(S,C,e.byteLength).set(new Uint8Array(e)),C+=e.byteLength;return new ct(S)}static computeBucketsForUncompressedSplatArray(t,s,i){let n=t.splatCount;const r=s/2,a=new e.Vector3,o=new e.Vector3;for(let e=0;e<n;e++){const s=t.splats[e],i=[s[tt.OFFSET.X],s[tt.OFFSET.Y],s[tt.OFFSET.Z]];(0===e||i[0]<a.x)&&(a.x=i[0]),(0===e||i[0]>o.x)&&(o.x=i[0]),(0===e||i[1]<a.y)&&(a.y=i[1]),(0===e||i[1]>o.y)&&(o.y=i[1]),(0===e||i[2]<a.z)&&(a.z=i[2]),(0===e||i[2]>o.z)&&(o.z=i[2])}const l=(new e.Vector3).copy(o).sub(a),c=Math.ceil(l.y/s),h=Math.ceil(l.z/s),d=new e.Vector3,u=[],p={};for(let e=0;e<n;e++){const n=t.splats[e],o=[n[tt.OFFSET.X],n[tt.OFFSET.Y],n[tt.OFFSET.Z]],l=Math.floor((o[0]-a.x)/s),m=Math.floor((o[1]-a.y)/s),g=Math.floor((o[2]-a.z)/s);d.x=l*s+a.x+r,d.y=m*s+a.y+r,d.z=g*s+a.z+r;const A=l*(c*h)+m*h+g;let f=p[A];f||(p[A]=f={splats:[],center:d.toArray()}),f.splats.push(e),f.splats.length>=i&&(u.push(f),p[A]=null)}const m=[];for(let e in p)if(Object.hasOwn(p,e)){const t=p[e];t&&m.push(t)}return{fullBuckets:u,partiallyFullBuckets:m}}}class ht{constructor(e,t,s,i){this.sectionCount=e,this.sectionFilters=t,this.groupingParameters=s,this.partitionGenerator=i}partitionUncompressedSplatArray(e){let t,s,i;if(this.partitionGenerator){const n=this.partitionGenerator(e);t=n.groupingParameters,s=n.sectionCount,i=n.sectionFilters}else t=this.groupingParameters,s=this.sectionCount,i=this.sectionFilters;const n=[];for(let t=0;t<s;t++){const s=new tt(e.sphericalHarmonicsDegree),r=i[t];for(let t=0;t<e.splatCount;t++)r(t)&&s.addSplat(e.splats[t]);n.push(s)}return{splatArrays:n,parameters:t}}static getStandardPartitioner(t=0,s=new e.Vector3,i=ct.BucketBlockSize,n=ct.BucketSize){return new ht(void 0,void 0,void 0,r=>{const a=tt.OFFSET.X,o=tt.OFFSET.Y,l=tt.OFFSET.Z;t<=0&&(t=r.splatCount);const c=new e.Vector3,h=.5;r.splats.forEach(e=>{var t;c.set(e[a],e[o],e[l]).sub(s),(t=c).x=Math.floor(t.x/h)*h,t.y=Math.floor(t.y/h)*h,t.z=Math.floor(t.z/h)*h,e.centerDist=c.lengthSq()}),r.splats.sort((e,t)=>e.centerDist>t.centerDist?1:-1);const d=[],u=[];t=Math.min(r.splatCount,t);const p=Math.ceil(r.splatCount/t);let m=0;for(let e=0;e<p;e++){let e=m;d.push(s=>s>=e&&s<e+t),u.push({blocksSize:i,bucketSize:n}),m+=t}return{sectionCount:d.length,sectionFilters:d,groupingParameters:u}})}}class dt{constructor(t,s,i,n,r,a,o){this.splatPartitioner=t,this.alphaRemovalThreshold=s,this.compressionLevel=i,this.sectionSize=n,this.sceneCenter=r?(new e.Vector3).copy(r):void 0,this.blockSize=a,this.bucketSize=o}generateFromUncompressedSplatArray(e){const t=this.splatPartitioner.partitionUncompressedSplatArray(e);return ct.generateFromUncompressedSplatArrays(t.splatArrays,this.alphaRemovalThreshold,this.compressionLevel,this.sceneCenter,this.blockSize,this.bucketSize,t.parameters)}static getStandardGenerator(t=1,s=1,i=0,n=new e.Vector3,r=ct.BucketBlockSize,a=ct.BucketSize){const o=ht.getStandardPartitioner(i,n,r,a);return new dt(o,t,s,i,n,r,a)}}const ut={INRIAV1:0},pt=0,mt=1,gt=2,At=3,ft=4,St=5,Ct=6,xt={double:0,int:1,uint:2,float:3,short:4,ushort:5,uchar:6},yt={[pt]:8,[mt]:4,[gt]:4,[At]:4,[ft]:2,[St]:2,[Ct]:1};class vt{static HeaderEndToken="end_header";constructor(){}decodeSectionHeader(e,t,s=0){const i=[];let n=!1,r=-1,a=0,o=!1,l=null;const c=[],h=[],d=[],u={};for(let p=s;p<e.length;p++){const m=e[p].trim();if(m.startsWith("element")){if(n){r--;break}{n=!0,s=p,r=p;const e=m.split(" ");let t=0;for(let s of e){const e=s.trim();e.length>0&&(t++,2===t?l=e:3===t&&(a=parseInt(e)))}}}else if(m.startsWith("property")){const e=m.match(/(\w+)\s+(\w+)\s+(\w+)/);if(e){const s=e[2],i=e[3];d.push(i);const n=t[i];u[i]=s;const r=xt[s];void 0!==n&&(c.push(n),h[n]=r)}}if(m===vt.HeaderEndToken){o=!0;break}n&&(i.push(m),r++)}const p=[];let m=0;for(let e of d){const s=u[e];if(Object.hasOwn(u,e)){const s=t[e];void 0!==s&&(p[s]=m)}m+=yt[xt[s]]}const g=this.decodeSphericalHarmonicsFromSectionHeader(d,t);return{headerLines:i,headerStartLine:s,headerEndLine:r,fieldTypes:h,fieldIds:c,fieldOffsets:p,bytesPerVertex:m,vertexCount:a,dataSizeBytes:m*a,endOfHeader:o,sectionName:l,sphericalHarmonicsDegree:g.degree,sphericalHarmonicsCoefficientsPerChannel:g.coefficientsPerChannel,sphericalHarmonicsDegree1Fields:g.degree1Fields,sphericalHarmonicsDegree2Fields:g.degree2Fields}}decodeSphericalHarmonicsFromSectionHeader(e,t){let s=0,i=0;for(let t of e)t.startsWith("f_rest")&&s++;i=s/3;let n=0;i>=3&&(n=1),i>=8&&(n=2);let r=[],a=[];for(let e=0;e<3;e++){if(n>=1)for(let s=0;s<3;s++)r.push(t["f_rest_"+(s+i*e)]);if(n>=2)for(let s=0;s<5;s++)a.push(t["f_rest_"+(s+i*e+3)])}return{degree:n,coefficientsPerChannel:i,degree1Fields:r,degree2Fields:a}}static getHeaderSectionNames(e){const t=[];for(let s of e)if(s.startsWith("element")){const e=s.split(" ");let i=0;for(let s of e){const e=s.trim();e.length>0&&(i++,2===i&&t.push(e))}}return t}static checkTextForEndHeader(e){return!!e.includes(vt.HeaderEndToken)}static checkBufferForEndHeader(e,t,s,i){const n=new Uint8Array(e,Math.max(0,t-s),s),r=i.decode(n);return vt.checkTextForEndHeader(r)}static extractHeaderFromBufferToText(e){const t=new TextDecoder;let s=0,i="";for(;;){if(s+100>=e.byteLength)throw new Error("End of file reached while searching for end of header");const n=new Uint8Array(e,s,100);if(i+=t.decode(n),s+=100,vt.checkBufferForEndHeader(e,s,200,t))break}return i}readHeaderFromBuffer(e){const t=new TextDecoder;let s=0,i="";for(;;){if(s+100>=e.byteLength)throw new Error("End of file reached while searching for end of header");const n=new Uint8Array(e,s,100);if(i+=t.decode(n),s+=100,vt.checkBufferForEndHeader(e,s,200,t))break}return i}static convertHeaderTextToLines(e){const t=e.split("\n"),s=[];for(let e=0;e<t.length;e++){const i=t[e].trim();if(s.push(i),i===vt.HeaderEndToken)break}return s}static determineHeaderFormatFromHeaderText(e){return ut.INRIAV1}static determineHeaderFormatFromPlyBuffer(e){const t=vt.extractHeaderFromBufferToText(e);return vt.determineHeaderFormatFromHeaderText(t)}static readVertex(e,t,s,i,n,r,a=!0){const o=s*t.bytesPerVertex+i,l=t.fieldOffsets,c=t.fieldTypes;for(let t of n){const s=c[t];3===s?r[t]=e.getFloat32(o+l[t],!0):4===s?r[t]=e.getInt16(o+l[t],!0):5===s?r[t]=e.getUint16(o+l[t],!0):1===s?r[t]=e.getInt32(o+l[t],!0):2===s?r[t]=e.getUint32(o+l[t],!0):6===s&&(r[t]=a?e.getUint8(o+l[t])/255:e.getUint8(o+l[t]))}}}const It=["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"],bt=It.map((e,t)=>t),[wt,Bt,Tt,Dt,Et,Mt,Rt,Ft,Pt,kt,_t,Lt,Ut,Ot,Ht,zt,Qt,Vt]=bt;class Nt{constructor(){this.plyParserutils=new vt}decodeHeaderLines(e){let t=0;e.forEach(e=>{e.includes("f_rest_")&&t++});let s=0;t>=45?s=45:t>=24?s=24:t>=9&&(s=9);let i=Array.from(Array(Math.max(s-1,0))).map((e,t)=>`f_rest_${t+1}`);const n=[...It,...i],r=n.map((e,t)=>t),a=r.reduce((e,t)=>(e[n[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=vt.convertHeaderTextToLines(e),s=this.decodeHeaderLines(t);return s.headerText=e,s.headerSizeBytes=e.indexOf(vt.HeaderEndToken)+vt.HeaderEndToken.length+1,s}decodeHeaderFromBuffer(e){const t=this.plyParserutils.readHeaderFromBuffer(e);return this.decodeHeaderText(t)}findSplatData(e,t){return new DataView(e,t.headerSizeBytes)}parseToUncompressedSplatBufferSection(e,t,s,i,n,r,a,o=0){o=Math.min(o,e.sphericalHarmonicsDegree);const l=ct.CompressionLevels[0].SphericalHarmonicsDegrees[o].BytesPerSplat;for(let c=t;c<=s;c++){const t=Nt.parseToUncompressedSplat(i,c,e,n,o),s=c*l+a;ct.writeSplatDataToSectionBuffer(t,r,s,0,o)}}parseToUncompressedSplatArraySection(e,t,s,i,n,r,a=0){a=Math.min(a,e.sphericalHarmonicsDegree);for(let o=t;o<=s;o++){const t=Nt.parseToUncompressedSplat(i,o,e,n,a);r.addSplat(t)}}decodeSectionSplatData(e,t,s,i){i=Math.min(i,s.sphericalHarmonicsDegree);const n=new tt(i);for(let r=0;r<t;r++){const t=Nt.parseToUncompressedSplat(e,r,s,0,i);n.addSplat(t)}return n}static parseToUncompressedSplat=function(){let t=[];const s=new e.Quaternion,i=tt.OFFSET.X,n=tt.OFFSET.Y,r=tt.OFFSET.Z,a=tt.OFFSET.SCALE0,o=tt.OFFSET.SCALE1,l=tt.OFFSET.SCALE2,c=tt.OFFSET.ROTATION0,h=tt.OFFSET.ROTATION1,d=tt.OFFSET.ROTATION2,u=tt.OFFSET.ROTATION3,p=tt.OFFSET.FDC0,m=tt.OFFSET.FDC1,g=tt.OFFSET.FDC2,A=tt.OFFSET.OPACITY,f=[];for(let e=0;e<45;e++)f[e]=tt.OFFSET.FRC0+e;return function(e,S,C,x=0,y=0){y=Math.min(y,C.sphericalHarmonicsDegree),Nt.readSplat(e,C,S,x,t);const v=tt.createSplat(y);if(void 0!==t[wt]?(v[a]=Math.exp(t[wt]),v[o]=Math.exp(t[Bt]),v[l]=Math.exp(t[Tt])):(v[a]=.01,v[o]=.01,v[l]=.01),void 0!==t[_t]?(v[p]=255*t[_t],v[m]=255*t[Lt],v[g]=255*t[Ut]):void 0!==t[Ht]?(v[p]=255*t[Ht],v[m]=255*t[zt],v[g]=255*t[Qt]):(v[p]=0,v[m]=0,v[g]=0),void 0!==t[Ot]&&(v[A]=1/(1+Math.exp(-t[Ot]))*255),v[p]=P(Math.floor(v[p]),0,255),v[m]=P(Math.floor(v[m]),0,255),v[g]=P(Math.floor(v[g]),0,255),v[A]=P(Math.floor(v[A]),0,255),y>=1&&void 0!==t[Vt]){for(let e=0;e<9;e++)v[f[e]]=t[C.sphericalHarmonicsDegree1Fields[e]];if(y>=2)for(let e=0;e<15;e++)v[f[9+e]]=t[C.sphericalHarmonicsDegree2Fields[e]]}return s.set(t[Dt],t[Et],t[Mt],t[Rt]),s.normalize(),v[c]=s.x,v[h]=s.y,v[d]=s.z,v[u]=s.w,v[i]=t[Ft],v[n]=t[Pt],v[r]=t[kt],v}}();static readSplat(e,t,s,i,n){return vt.readVertex(e,t,s,i,t.fieldsToReadIndexes,n,!0)}parseToUncompressedSplatArray(e,t=0){const s=this.decodeHeaderFromBuffer(e),i=s.splatCount,n=this.findSplatData(e,s);return this.decodeSectionSplatData(n,i,s,t)}}class Gt{static parseToUncompressedSplatArray(e,t=0){return(new Nt).parseToUncompressedSplatArray(e,t)}}const Wt=E("PlyLoader");function qt(t,s,i,n,r,a,o,l){try{return s?dt.getStandardGenerator(i,n,r,a,o,l).generateFromUncompressedSplatArray(t):ct.generateFromUncompressedSplatArrays([t],i,0,new e.Vector3)}catch(e){throw new I(`Failed to finalize splat data: ${e.message}`,"splatData",e)}}class Kt{static loadFromURL(t,s,i,n,r,a,o=!0,l=0,c,h,d,p,m){try{te(t)}catch(e){throw Wt.error("Invalid URL provided to loadFromURL",{fileName:t,error:e}),e}s&&re(s,"onProgress",!1),n&&re(n,"onProgressiveLoadSectionProgress",!1),Wt.info("Loading PLY from URL",{fileName:t,optimizeSplatData:o,outSphericalHarmonicsDegree:l});let f=i?g.DirectToSplatBuffer:g.DirectToSplatArray;o&&(f=g.DirectToSplatArray);const y=u.ProgressiveLoadSectionSize,v=ct.HeaderSizeBytes+ct.SectionHeaderSizeBytes;let b,w,B,T=0,D=0,E=!1,M=!1;const R=O();let P,k=0,_=0,U=0,H="",z=null,Q=[];const V=new TextDecoder,N=new Nt;if(s)try{s(0,"0%",A.Downloading)}catch(e){Wt.warn("Error in onProgress callback",e)}return F(t,(t,i,r)=>{const a=t>=100;if(r&&(Q.push({data:r,sizeBytes:r.byteLength,startBytes:U,endBytes:U+r.byteLength}),U+=r.byteLength),f===g.DownloadBeforeProcessing)a&&R.resolve(Q);else{if(!E&&(H+=V.decode(r),vt.checkTextForEndHeader(H))){try{z=N.decodeHeaderText(H),T=z.splatCount,M=!0,Wt.debug("PLY header decoded",{splatCount:T,sphericalHarmonicsDegree:z.sphericalHarmonicsDegree}),l=Math.min(l,z.sphericalHarmonicsDegree)}catch(e){const t=new I(`Failed to decode PLY header: ${e.message}`,"headerText",e);return Wt.error("Header parsing failed",t),void R.reject(t)}const t=ct.CompressionLevels[0].SphericalHarmonicsDegrees[l],s=v+t.BytesPerSplat*T;f===g.DirectToSplatBuffer?(w=new ArrayBuffer(s),ct.writeHeaderToBuffer({versionMajor:ct.CurrentMajorVersion,versionMinor:ct.CurrentMinorVersion,maxSectionCount:1,sectionCount:1,maxSplatCount:T,splatCount:D,compressionLevel:0,sceneCenter:new e.Vector3},w)):P=new tt(l),k=z.headerSizeBytes,_=z.headerSizeBytes,E=!0}if(E&&M){if(Q.length>0&&(b=function(e,t){let s=0;for(let t of e)s+=t.sizeBytes;(!t||t.byteLength<s)&&(t=new ArrayBuffer(s));let i=0;for(let s of e)new Uint8Array(t,i,s.sizeBytes).set(s.data),i+=s.sizeBytes;return t}(Q,b),U-k>y||a)){const e=U-_,t=Math.floor(e/z.bytesPerSplat),s=t*z.bytesPerSplat,i=e-s,r=D+t,o=_-Q[0].startBytes,c=new DataView(b,o,s),h=ct.CompressionLevels[0].SphericalHarmonicsDegrees[l],d=D*h.BytesPerSplat+v;try{f===g.DirectToSplatBuffer?N.parseToUncompressedSplatBufferSection(z,0,t-1,c,0,w,d,l):N.parseToUncompressedSplatArraySection(z,0,t-1,c,0,P,l)}catch(e){const s=new I(`Failed to parse splat data section: ${e.message}`,"splatData",e);return Wt.error("Splat data parsing failed",{splatCount:D,addedSplatCount:t,error:e}),void R.reject(s)}if(D=r,f===g.DirectToSplatBuffer&&(B||(ct.writeSectionHeaderToBuffer({maxSplatCount:T,splatCount:D,bucketSize:0,bucketCount:0,bucketBlockSize:0,compressionScaleRange:0,storageSizeBytes:0,fullBucketCount:0,partiallyFilledBucketCount:0,sphericalHarmonicsDegree:l},0,w,ct.HeaderSizeBytes),B=new ct(w,!1)),B.updateLoadedCounts(1,D),n&&n(B,a)),k+=y,_+=s,0===i)Q=[];else{let e=[],t=0;for(let s=Q.length-1;s>=0;s--){const n=Q[s];if(t+=n.sizeBytes,e.unshift(n),t>=i)break}Q=e}}a&&(f===g.DirectToSplatBuffer?R.resolve(B):R.resolve(P))}}if(s)try{s(t,i,A.Downloading)}catch(e){Wt.warn("Error in onProgress callback",e)}},!1,c).then(()=>{if(s)try{s(0,"0%",A.Processing)}catch(e){Wt.warn("Error in onProgress callback",e)}return R.promise}).then(e=>{if(s)try{s(100,"100%",A.Done)}catch(e){Wt.warn("Error in onProgress callback",e)}if(Wt.debug("PLY data loaded successfully",{internalLoadType:f,splatCount:e?.splatCount||"unknown"}),f===g.DownloadBeforeProcessing){const e=Q.map(e=>e.data);return new Blob(e).arrayBuffer().then(e=>Kt.loadFromFileData(e,r,a,o,l,h,d,p,m)).catch(e=>{throw new x(`Failed to process downloaded PLY data: ${e.message}`,t,e)})}return f===g.DirectToSplatBuffer?e:L(()=>qt(e,o,r,a,h,d,p,m))}).catch(e=>{if(e instanceof S||e instanceof C||e instanceof I||e instanceof x)throw Wt.error("PLY loading failed",{fileName:t,errorCode:e.code}),e;throw Wt.error("Unexpected error loading PLY",{fileName:t,error:e}),new x(`Unexpected error loading PLY file: ${e.message}`,t,e)})}static loadFromFileData(e,t,s,i,n=0,r,a,o,l){try{ne(e,"plyFileData")}catch(e){return Wt.error("Invalid PLY file data",e),Promise.reject(e)}return Wt.info("Loading PLY from file data",{sizeBytes:e.byteLength,optimizeSplatData:i,outSphericalHarmonicsDegree:n}),L(()=>{try{return Gt.parseToUncompressedSplatArray(e,n)}catch(e){throw new I(`Failed to parse PLY file data: ${e.message}`,"plyFileData",e)}}).then(e=>(Wt.debug("PLY parsed successfully",{splatCount:e?.splatCount||"unknown"}),qt(e,i,t,s,r,a,o,l))).catch(e=>{if(e instanceof S||e instanceof I)throw Wt.error("PLY file data loading failed",{errorCode:e.code}),e;throw Wt.error("Unexpected error loading PLY from file data",e),new I(`Unexpected error parsing PLY data: ${e.message}`,"plyFileData",e)})}}const jt=new r.Vector3(1,0,0),Yt=new r.Vector3(0,1,0),Jt=new r.Vector3(0,0,1);class Xt{constructor(e=new r.Vector3,t=new r.Vector3){this.origin=new r.Vector3,this.direction=new r.Vector3,this.setParameters(e,t)}setParameters(e,t){this.origin.copy(e),this.direction.copy(t).normalize()}boxContainsPoint(e,t,s){return!(t.x<e.min.x-s||t.x>e.max.x+s||t.y<e.min.y-s||t.y>e.max.y+s||t.z<e.min.z-s||t.z>e.max.z+s)}intersectBox=function(){const e=new r.Vector3,t=[],s=[],i=[];return function(n,r){if(s[0]=this.origin.x,s[1]=this.origin.y,s[2]=this.origin.z,i[0]=this.direction.x,i[1]=this.direction.y,i[2]=this.direction.z,this.boxContainsPoint(n,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?jt:1==a?Yt:Jt,l=i[a]<0?n.max:n.min;let c=-Math.sign(i[a]);t[0]=0==a?l.x:1==a?l.y:l.z;let h=t[0]-s[a];if(h*c<0){const l=(a+1)%3,d=(a+2)%3;if(t[2]=i[l]/i[a]*h+s[l],t[1]=i[d]/i[a]*h+s[d],e.set(t[a],t[d],t[l]),this.boxContainsPoint(n,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}}();intersectSphere=function(){const e=new r.Vector3;return function(t,s,i){e.copy(t).sub(this.origin);const n=e.dot(this.direction),r=n*n,a=e.dot(e)-r,o=s*s;if(a>o)return!1;const l=Math.sqrt(o-a),c=n-l,h=n+l;if(h<0)return!1;let d=c<0?h:c;return i&&(i.origin.copy(this.origin).addScaledVector(this.direction,d),i.normal.copy(i.origin).sub(t).normalize(),i.distance=d),!0}}()}class $t{constructor(){this.origin=new r.Vector3,this.normal=new r.Vector3,this.distance=0,this.splatIndex=0}set(e,t,s,i){this.origin.copy(e),this.normal.copy(t),this.distance=s,this.splatIndex=i}clone(){const e=new $t;return e.origin.copy(this.origin),e.normal.copy(this.normal),e.distance=this.distance,e.splatIndex=this.splatIndex,e}}class Zt{constructor(e,t,s=!1){this.ray=new Xt(e,t),this.raycastAgainstTrueSplatEllipsoid=s}setFromCameraAndScreenPosition=function(){const e=new r.Vector2;return function(t,s,i){if(e.x=s.x/i.x*2-1,e.y=(i.y-s.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}}}();intersectSplatMesh=function(){const e=new r.Matrix4,t=new r.Matrix4,s=new r.Matrix4,i=new Xt,n=new r.Vector3;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,s),t.multiply(s)),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=n.copy(e.origin).sub(this.ray.origin).length()}),a.push(...h)}return a.sort((e,t)=>e.distance>t.distance?1:-1),a}}}();castRayAtSplatTreeNode=function(){const e=new r.Vector4,t=new r.Vector3,s=new r.Vector3,i=new r.Quaternion,n=new $t,a=1e-7,o=new r.Vector3(0,0,0),l=new r.Matrix4,c=new r.Matrix4,h=new r.Matrix4,u=new r.Matrix4,p=new r.Matrix4,m=new Xt;return function(r,g,A,f=[]){if(r.intersectBox(A.boundingBox)){if(A.data&&A.data.indexes&&A.data.indexes.length>0)for(let S=0;S<A.data.indexes.length;S++){const C=A.data.indexes[S],x=g.splatMesh.getSceneIndexForSplat(C);if(g.splatMesh.getScene(x).visible&&(g.splatMesh.getSplatColor(C,e),g.splatMesh.getSplatCenter(C,t),g.splatMesh.getSplatScaleAndRotation(C,s,i),!(s.x<=a||s.y<=a||g.splatMesh.splatRenderMode===d.ThreeD&&s.z<=a)))if(this.raycastAgainstTrueSplatEllipsoid){c.makeScale(s.x,s.y,s.z),h.makeRotationFromQuaternion(i);const a=2*Math.log10(e.w);if(l.makeScale(a,a,a),p.copy(l).multiply(h).multiply(c),u.copy(p).invert(),m.origin.copy(r.origin).sub(t).applyMatrix4(u),m.direction.copy(r.origin).add(r.direction).sub(t),m.direction.applyMatrix4(u).sub(m.origin).normalize(),m.intersectSphere(o,1,n)){const e=n.clone();e.splatIndex=C,e.origin.applyMatrix4(p).add(t),f.push(e)}}else{let e=s.x+s.y,i=2;if(g.splatMesh.splatRenderMode===d.ThreeD&&(e+=s.z,i=3),e/=i,r.intersectSphere(t,e,n)){const e=n.clone();e.splatIndex=C,f.push(e)}}}if(A.children&&A.children.length>0)for(let e of A.children)this.castRayAtSplatTreeNode(r,g,e,f);return f}}}()}const es="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";function ts(e){let t,s,i,n,r,a,o,l,c,h,d,u,p,m,g,A,f,S,C,x;e.onmessage=y=>{if(y.data.centers){let e=y.data.centers,t=y.data.sceneIndexes;n?new Int32Array(s,m+y.data.range.from*x.BytesPerInt*4,4*y.data.range.count).set(new Int32Array(e)):new Float32Array(s,m+y.data.range.from*x.BytesPerFloat*4,4*y.data.range.count).set(new Float32Array(e)),r&&new Uint32Array(s,c+4*y.data.range.from,y.data.range.count).set(new Uint32Array(t)),C=y.data.range.from+y.data.range.count}else if(y.data.sort){const v=Math.min(y.data.sort.splatRenderCount||0,C),I=Math.min(y.data.sort.splatSortCount||0,C),b=y.data.sort.usePrecomputedDistances;let w,B,T;i||(w=y.data.sort.indexesToSort,T=y.data.sort.transforms,b&&(B=y.data.sort.precomputedDistances)),function(C,y,v,I,b,w,B){const T=performance.now();if(!i&&(new Uint32Array(s,o,b.byteLength/x.BytesPerInt).set(b),new Float32Array(s,h,B.byteLength/x.BytesPerFloat).set(B),I)){let e;e=n?new Int32Array(s,d,w.byteLength/x.BytesPerInt):new Float32Array(s,d,w.byteLength/x.BytesPerFloat),e.set(w)}A||(A=new Uint32Array(S)),new Float32Array(s,g,16).set(v),new Uint32Array(s,p,S).set(A),t.exports.sortIndexes(o,m,d,u,p,g,l,c,h,S,C,y,a,I,n,r);const D={sortDone:!0,splatSortCount:C,splatRenderCount:y,sortTime:0};if(!i){const e=new Uint32Array(s,l,y);(!f||f.length<y)&&(f=new Uint32Array(y)),f.set(e),D.sortedIndexes=f}const E=performance.now();D.sortTime=E-T,e.postMessage(D)}(I,v,y.data.sort.modelViewProj,b,w,B,T)}else if(y.data.init){x=y.data.init.Constants,a=y.data.init.splatCount,i=y.data.init.useSharedMemory,n=y.data.init.integerBasedSort,r=y.data.init.dynamicMode,S=y.data.init.distanceMapRange,C=0;const A=n?4*x.BytesPerInt:4*x.BytesPerFloat,f=new Uint8Array(y.data.init.sorterWasmBytes),v=16*x.BytesPerFloat,I=a*x.BytesPerInt,b=a*A,w=v,B=n?a*x.BytesPerInt:a*x.BytesPerFloat,T=a*x.BytesPerInt,D=a*x.BytesPerInt,E=n?S*x.BytesPerInt*2:S*x.BytesPerFloat*2,M=r?a*x.BytesPerInt:0,R=r?x.MaxScenes*v:0,F=32*x.MemoryPageSize,P=I+b+w+B+T+E+D+M+R+F,k=Math.floor(P/x.MemoryPageSize)+1,_={module:{},env:{memory:new WebAssembly.Memory({initial:k,maximum:k,shared:!0})}};WebAssembly.compile(f).then(e=>WebAssembly.instantiate(e,_)).then(n=>{t=n,o=0,m=o+I,g=m+b,d=g+w,u=d+B,p=u+T,l=p+E,c=l+D,h=c+M,s=_.env.memory.buffer,i?e.postMessage({sortSetupPhase1Complete:!0,indexesToSortBuffer:s,indexesToSortOffset:o,sortedIndexesBuffer:s,sortedIndexesOffset:l,precomputedDistancesBuffer:s,precomputedDistancesOffset:d,transformsBuffer:s,transformsOffset:h}):e.postMessage({sortSetupPhase1Complete:!0})})}}}const ss=E("Viewer");class is{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 ns{constructor(e){}show(){}hide(){}setContainer(e){}setProgress(e){}}class rs{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,s){}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,s){}updateForRenderMode(e,t){}dispose(){}}class Viewer{constructor(t={}){if(t.cameraUp||(t.cameraUp=[0,1,0]),this.cameraUp=(new e.Vector3).fromArray(t.cameraUp),t.initialCameraPosition||(t.initialCameraPosition=[0,10,15]),this.initialCameraPosition=(new e.Vector3).fromArray(t.initialCameraPosition),t.initialCameraRotation||(t.initialCameraRotation=[0,0,0]),this.initialCameraRotation=(new e.Vector3).fromArray(t.initialCameraRotation),this.backgroundColor=t.backgroundColor,t.initialCameraLookAt||(t.initialCameraLookAt=[0,0,0]),this.initialCameraLookAt=(new e.Vector3).fromArray(t.initialCameraLookAt),this.dropInMode=t.dropInMode||!1,void 0!==t.selfDrivenMode&&null!==t.selfDrivenMode||(t.selfDrivenMode=!0),this.selfDrivenMode=t.selfDrivenMode&&!this.dropInMode,this.selfDrivenUpdateFunc=this.selfDrivenUpdate.bind(this),void 0===t.useBuiltInControls&&(t.useBuiltInControls=!0),this.useBuiltInControls=t.useBuiltInControls,this.rootElement=t.rootElement,this.canvas=t.threejsCanvas,this.ignoreDevicePixelRatio=t.ignoreDevicePixelRatio||!1,this.devicePixelRatio=this.ignoreDevicePixelRatio?1:window.devicePixelRatio||1,this.halfPrecisionCovariancesOnGPU=t.halfPrecisionCovariancesOnGPU||!1,this.threeScene=t.threeScene,this.renderer=t.renderer,this.camera=t.camera,this.gpuAcceleratedSort=t.gpuAcceleratedSort||!1,void 0!==t.integerBasedSort&&null!==t.integerBasedSort||(t.integerBasedSort=!0),this.integerBasedSort=t.integerBasedSort,void 0!==t.sharedMemoryForWorkers&&null!==t.sharedMemoryForWorkers||(t.sharedMemoryForWorkers=!0),this.sharedMemoryForWorkers=!1,this.dynamicScene=!!t.dynamicScene,this.antialiased=t.antialiased||!1,this.kernel2DSize=void 0===t.kernel2DSize?.3:t.kernel2DSize,this.renderMode=t.renderMode||o.Always,this.sceneRevealMode=t.sceneRevealMode||h.Default,this.focalAdjustment=t.focalAdjustment||1,this.maxScreenSpaceSplatSize=t.maxScreenSpaceSplatSize||1024,this.logLevel=t.logLevel||a.None,this.sphericalHarmonicsDegree=t.sphericalHarmonicsDegree||0,this.enableOptionalEffects=t.enableOptionalEffects||!1,void 0!==t.enableSIMDInSort&&null!==t.enableSIMDInSort||(t.enableSIMDInSort=!0),this.enableSIMDInSort=t.enableSIMDInSort,void 0!==t.inMemoryCompressionLevel&&null!==t.inMemoryCompressionLevel||(t.inMemoryCompressionLevel=0),this.inMemoryCompressionLevel=t.inMemoryCompressionLevel,void 0!==t.optimizeSplatData&&null!==t.optimizeSplatData||(t.optimizeSplatData=!0),this.optimizeSplatData=t.optimizeSplatData,void 0!==t.freeIntermediateSplatData&&null!==t.freeIntermediateSplatData||(t.freeIntermediateSplatData=!1),this.freeIntermediateSplatData=t.freeIntermediateSplatData,Q()){const e=V();e.major<17&&(this.enableSIMDInSort=!1),e.major<16&&(this.sharedMemoryForWorkers=!1)}void 0!==t.splatRenderMode&&null!==t.splatRenderMode||(t.splatRenderMode=d.ThreeD),this.splatRenderMode=t.splatRenderMode,this.sceneFadeInRateMultiplier=t.sceneFadeInRateMultiplier||1,this.splatSortDistanceMapPrecision=t.splatSortDistanceMapPrecision||u.DefaultSplatSortDistanceMapPrecision;const s=this.integerBasedSort?20:24;this.splatSortDistanceMapPrecision=P(this.splatSortDistanceMapPrecision,10,s),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 Zt,this.infoPanel=null,this.startInOrthographicMode=!1,this.currentFPS=0,this.lastSortTime=0,this.consecutiveRenderFrames=0,this.previousCameraTarget=new e.Vector3,this.nextCameraTarget=new e.Vector3,this.mousePosition=new e.Vector2,this.mouseDownPosition=new e.Vector2,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 is(null,this.rootElement||document.body),this.loadingSpinner.hide(),this.loadingProgressBar=new ns(this.rootElement||document.body),this.loadingProgressBar.hide(),this.usingExternalCamera=!(!this.dropInMode&&!this.camera),this.usingExternalRenderer=!(!this.dropInMode&&!this.renderer),this.initialized=!1,this.disposing=!1,this.disposed=!1,this.disposePromise=null,this.lastTime=0,this.gaussianSplatCount=0,this.totalFrames=0,this.frame=0,this.avatarMesh=null,this.skinModel=null,this.boneRoot=null,this.baseMesh=null,this.setSkinAttibutes=!1,this.dropInMode||this.init()}createSplatMesh(){this.splatMesh=new Ze(this.splatRenderMode,this.dynamicScene,this.enableOptionalEffects,this.halfPrecisionCovariancesOnGPU,this.devicePixelRatio,this.gpuAcceleratedSort,this.integerBasedSort,this.antialiased,this.maxScreenSpaceSplatSize,this.logLevel,this.sphericalHarmonicsDegree,this.sceneFadeInRateMultiplier,this.kernel2DSize),this.splatMesh.irisOcclusionConfig=this.irisOcclusionConfig,this.splatMesh.frustumCulled=!1,this.onSplatMeshChangedCallback&&this.onSplatMeshChangedCallback()}init(){this.initialized||(this.rootElement||(this.usingExternalRenderer?this.rootElement=this.renderer.domElement||document.body:(this.rootElement=document.createElement("div"),this.rootElement.style.width="100%",this.rootElement.style.height="100%",this.rootElement.style.position="absolute",document.body.appendChild(this.rootElement))),this.setupCamera(),this.setupRenderer(),this.setupEventHandlers(),this.threeScene=this.threeScene||new e.Scene,this.sceneHelper=new rs(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 t=new e.Vector2;this.getRenderDimensions(t),this.perspectiveCamera=new e.PerspectiveCamera(50,t.x/t.y,.1,1e3),this.orthographicCamera=new e.OrthographicCamera(t.x/-2,t.x/2,t.y/2,t.y/-2,.1,1e3),this.camera=this.startInOrthographicMode?this.orthographicCamera:this.perspectiveCamera,this.camera.position.copy(this.initialCameraPosition),this.camera.rotateX(e.MathUtils.degToRad(this.initialCameraRotation.x)),this.camera.rotateY(e.MathUtils.degToRad(this.initialCameraRotation.y)),this.camera.rotateZ(e.MathUtils.degToRad(this.initialCameraRotation.z))}}setupRenderer(){if(!this.usingExternalRenderer){const t=new e.Vector2;this.getRenderDimensions(t),this.renderer=new e.WebGLRenderer({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(t.x,t.y),this.resizeObserver=new ResizeObserver(()=>{this.getRenderDimensions(t),this.renderer.setSize(t.x,t.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 i.OrbitControls(this.camera,this.renderer.domElement):this.perspectiveControls=new i.OrbitControls(this.camera,this.renderer.domElement):(this.perspectiveControls=new i.OrbitControls(this.perspectiveCamera,this.renderer.domElement),this.orthographicControls=new i.OrbitControls(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}tempForward=new e.Vector3;tempMatrixLeft=new e.Matrix4;tempMatrixRight=new e.Matrix4;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))}};onMouseMove(e){this.mousePosition.set(e.offsetX,e.offsetY)}onMouseDown(){this.mouseDownPosition.copy(this.mousePosition),this.mouseDownTime=k()}onMouseUp=function(){const t=new e.Vector2;return function(e){t.copy(this.mousePosition).sub(this.mouseDownPosition),k()-this.mouseDownTime<.5&&t.length()<2&&this.onMouseClick(e)}}();onMouseClick(e){this.mousePosition.set(e.offsetX,e.offsetY),this.checkForFocalPointChange()}checkPointRenderDimensions=new e.Vector2;checkPointToNewFocalPoint=new e.Vector3;checkPointOutHits=[];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=k())}};getRenderDimensions(e){this.rootElement?(e.x=this.rootElement.offsetWidth,e.y=this.rootElement.offsetHeight):this.renderer.getSize(e)}setOrthographicMode(e){if(e===this.camera.isOrthographicCamera)return;const t=this.camera,s=e?this.orthographicCamera:this.perspectiveCamera;if(s.position.copy(t.position),s.up.copy(t.up),s.rotation.copy(t.rotation),s.quaternion.copy(t.quaternion),s.matrix.copy(t.matrix),this.camera=s,this.controls){const i=e=>{e.saveState(),e.reset()},n=this.controls,r=e?this.orthographicControls:this.perspectiveControls;i(r),i(n),r.target.copy(n.target),e?Viewer.setCameraZoomFromPosition(s,t,n):Viewer.setCameraPositionFromZoom(s,t,r),this.controls=r,this.camera.lookAt(this.controls.target)}}static setCameraPositionFromZoom=function(){const t=new e.Vector3;return function(e,s,i){const n=1/(.001*s.zoom);t.copy(i.target).sub(e.position).normalize().multiplyScalar(n).negate(),e.position.copy(i.target).add(t)}}();static setCameraZoomFromPosition=function(){const t=new e.Vector3;return function(e,s,i){const n=t.copy(i.target).sub(s.position).length();e.zoom=1/(.001*n)}}();updateSplatMesh=function(){const t=new e.Vector2;return function(){if(this.splatMesh&&this.splatMesh.getSplatCount()>0){this.splatMesh.updateVisibleRegionFadeDistance(this.sceneRevealMode),this.splatMesh.updateTransforms(),this.getRenderDimensions(t);const e=.5*this.camera.projectionMatrix.elements[0]*this.devicePixelRatio*t.x,s=.5*this.camera.projectionMatrix.elements[5]*this.devicePixelRatio*t.y,i=this.camera.isOrthographicCamera?1/this.devicePixelRatio:1,n=this.focalAdjustment*i,r=1/n;this.adjustForWebXRStereo(t),this.splatMesh.updateUniforms(t,e*n,s*n,this.camera.isOrthographicCamera,this.camera.zoom||1,r)}}}();adjustForWebXRStereo(e){if(this.camera&&this.webXRActive){const t=this.renderer.xr.getCamera().projectionMatrix.elements[0],s=this.camera.projectionMatrix.elements[0];e.x*=s/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(e,t={}){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.");t.progressiveLoad&&this.splatMesh.scenes&&this.splatMesh.scenes.length>0&&(ss.warn('addSplatScene(): "progressiveLoad" option ignore because there are multiple splat scenes'),t.progressiveLoad=!1);const s=void 0!==t.format&&null!==t.format?t.format:c(e),i=Viewer.isProgressivelyLoadable(s)&&t.progressiveLoad,n=void 0===t.showLoadingUI||null===t.showLoadingUI||t.showLoadingUI;let r=null;n&&(this.loadingSpinner.removeAllTasks(),r=this.loadingSpinner.addTask("Downloading..."));const a=(e,t,s)=>{if(n)if(s===A.Downloading)if(100==e)this.loadingSpinner.setMessageForTask(r,"Download complete!");else if(i)this.loadingSpinner.setMessageForTask(r,"Downloading splats...");else{const e=t?`: ${t}`:"...";this.loadingSpinner.setMessageForTask(r,`Downloading${e}`)}else s===A.Processing&&(ss.debug("loaderStatus === LoaderStatus.Processing"),this.loadingSpinner.setMessageForTask(r,"Processing splats..."))};let o=!1,l=0;const h=(e,t)=>{n&&((e&&i||t&&!i)&&(this.loadingSpinner.removeTask(r),t||o||this.loadingProgressBar.show()),i&&(t?(o=!0,this.loadingProgressBar.hide()):this.loadingProgressBar.setProgress(l)))};return(i?this.downloadAndBuildSingleSplatSceneProgressiveLoad.bind(this):this.downloadAndBuildSingleSplatSceneStandardLoad.bind(this))(e,s,t.splatAlphaRemovalThreshold,((e,s,r)=>{!i&&t.onProgress&&t.onProgress(0,"0%",A.Processing);const a={rotation:t.rotation||t.orientation,position:t.position,scale:t.scale,splatAlphaRemovalThreshold:t.splatAlphaRemovalThreshold};return this.addSplatBuffers([e],[a],r,s&&n,n,i,i).then(()=>{!i&&t.onProgress&&t.onProgress(100,"100%",A.Processing),h(s,r)})}).bind(this),(e,s,i)=>{l=e,a(e,s,i),t.onProgress&&t.onProgress(e,s,i)},(()=>{this.loadingProgressBar.hide(),this.loadingSpinner.removeAllTasks()}).bind(this),t.headers)}downloadAndBuildSingleSplatSceneStandardLoad(e,t,s,i,n,r,a){const o=this.downloadSplatSceneToSplatBuffer(e,s,n,!1,void 0,t,a),l=H(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 s=t instanceof R||"AbortError"===t.name?t:new Error(`Viewer::addSplatScene -> Could not load file ${e}`);l.reject(s)}),this.addSplatSceneDownloadPromise(o),this.setSplatSceneDownloadAndBuildPromise(l.promise),l.promise}downloadAndBuildSingleSplatSceneProgressiveLoad(e,t,s,i,n,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&&(m.resolve(),this.clearSplatSceneDownloadAndBuildPromise()),c.length>0&&L(()=>h())})}},d=this.downloadSplatSceneToSplatBuffer(e,s,n,!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),u=d.abort?d.abort.bind(d):void 0,p=H(u),m=H(u);return this.addSplatSceneDownloadPromise(d),this.setSplatSceneDownloadAndBuildPromise(m.promise),d.then(()=>{this.removeSplatSceneDownloadPromise(d)}).catch(e=>{ss.error("Viewer::addSplatScene actual error:",e),this.clearSplatSceneDownloadAndBuildPromise(),this.removeSplatSceneDownloadPromise(d);const t=e instanceof R||"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,s=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,n=[];let r;t&&(this.loadingSpinner.removeAllTasks(),r=this.loadingSpinner.addTask("Downloading..."));const a=(e,a,o,l)=>{n[e]=a;let c=0;for(let e=0;e<i;e++)c+=n[e]||0;c/=i,o=`${c.toFixed(2)}%`,t&&l===A.Downloading&&this.loadingSpinner.setMessageForTask(r,100==c?"Download complete!":`Downloading: ${o}`),s&&s(c,o,l)},o=new AbortController,l=o.signal;this.addSplatSceneDownloadController(o);const h=[];for(let t=0;t<e.length;t++){const s=e[t],i=void 0!==s.format&&null!==s.format?s.format:c(s.path),n=this.downloadSplatSceneToSplatBuffer(s.path,s.splatAlphaRemovalThreshold,a.bind(this,t),!1,void 0,i,s.headers,l);h.push(n)}const d=Promise.all(h).then(i=>(t&&this.loadingSpinner.removeTask(r),s&&s(0,"0%",A.Processing),this.addSplatBuffers(i,e,!0,t,t,!1,!1).then(()=>{s&&s(100,"100%",A.Processing),this.clearSplatSceneDownloadAndBuildPromise()}))).catch(e=>{throw t&&this.loadingSpinner.removeTask(r),this.clearSplatSceneDownloadAndBuildPromise(),"AbortError"===e.name?e:new Error("Viewer::addSplatScenes -> Could not load one or more splat scenes.")}).finally(()=>{this.removeSplatSceneDownloadController(o)});return this.setSplatSceneDownloadAndBuildPromise(d),d}downloadSplatSceneToSplatBuffer(e,t=1,s=void 0,i=!1,n=void 0,r,a){const o=!i&&this.optimizeSplatData;try{if(r===l.Ply)return Kt.loadFromURL(e,s,i,n,t,this.inMemoryCompressionLevel,o,this.sphericalHarmonicsDegree,a)}catch(e){throw e instanceof et?new Error("File type or server does not support progressive loading."):e}throw new Error(`Viewer::downloadSplatSceneToSplatBuffer -> File format not supported: ${e}`)}static isProgressivelyLoadable(e){return e===l.Ply}addSplatBuffers=(e,t=[],s=!0,i=!0,n=!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...")),L(()=>{if(this.isDisposingOrDisposed())h();else{const i=this.addSplatBuffersToMesh(e,t,s,n,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)})};addSplatBuffersToMesh=function(){let e;return function(t,s,i=!0,n=!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(...s),this.renderer&&this.splatMesh.setRenderer(this.renderer);const c=this.splatMesh.build(o,l,!0,i,t=>{if(this.isDisposingOrDisposed())return;const s=this.splatMesh.getSplatCount();n&&s>=m&&(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}}();async setupSortWorker(e){if(this.isDisposingOrDisposed())return;const t=this.integerBasedSort?Int32Array:Float32Array,s=e.getSplatCount(),i=e.getMaxSplatCount();return this.sortWorker=await function(e,t,s,i,n,r=u.DefaultSplatSortDistanceMapPrecision){const a=new Worker(URL.createObjectURL(new Blob(["(",ts.toString(),")(self)"],{type:"application/javascript"})));let o="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";const l=Q()?V():null;s||t?s?t||l&&l.major<=16&&l.minor<4&&(o="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"):o=es:(o=es,l&&l.major<=16&&l.minor<4&&(o="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"));const c=atob(o),h=new Uint8Array(c.length);for(let e=0;e<c.length;e++)h[e]=c.charCodeAt(e);return a.postMessage({init:{sorterWasmBytes:h.buffer,splatCount:e,useSharedMemory:t,integerBasedSort:i,dynamicMode:n,distanceMapRange:1<<r,Constants:{BytesPerFloat:u.BytesPerFloat,BytesPerInt:u.BytesPerInt,MemoryPageSize:u.MemoryPageSize,MaxScenes:u.MaxScenes}}}),a}(i,this.sharedMemoryForWorkers,this.enableSIMDInSort,this.integerBasedSort,this.splatMesh.dynamicMode,this.splatSortDistanceMapPrecision),new Promise(e=>{this.sortWorker.onmessage=n=>{if(n.data.sortDone){if(this.sortRunning=!1,Array.from({length:this.gaussianSplatCount},(e,t)=>t),this.sharedMemoryForWorkers)this.splatMesh.updateRenderIndexes(this.sortWorkerSortedIndexes,n.data.splatRenderCount);else{const e=new Uint32Array(n.data.sortedIndexes.buffer,0,n.data.splatRenderCount);this.splatMesh.updateRenderIndexes(e,n.data.splatRenderCount)}this.lastSplatSortCount=this.splatSortCount,this.lastSortTime=n.data.sortTime,this.sortPromiseResolver(),this.sortPromiseResolver=null,this.forceRenderNextFrame(),this.runAfterNextSort.length>0&&(this.runAfterNextSort.forEach(e=>{e()}),this.runAfterNextSort.length=0)}else if(n.data.sortCanceled)this.sortRunning=!1;else if(n.data.sortSetupPhase1Complete){this.logLevel>=a.Info&&ss.info("Sorting web worker WASM setup complete."),this.sharedMemoryForWorkers?(this.sortWorkerSortedIndexes=new Uint32Array(n.data.sortedIndexesBuffer,n.data.sortedIndexesOffset,i),this.sortWorkerIndexesToSort=new Uint32Array(n.data.indexesToSortBuffer,n.data.indexesToSortOffset,i),this.sortWorkerPrecomputedDistances=new t(n.data.precomputedDistancesBuffer,n.data.precomputedDistancesOffset,i),this.sortWorkerTransforms=new Float32Array(n.data.transformsBuffer,n.data.transformsOffset,16*u.MaxScenes)):(this.sortWorkerIndexesToSort=new Uint32Array(i),this.sortWorkerPrecomputedDistances=new t(i),this.sortWorkerTransforms=new Float32Array(16*u.MaxScenes));for(let e=0;e<s;e++)this.sortWorkerIndexesToSort[e]=e;if(this.sortWorker.maxSplatCount=i,this.logLevel>=a.Info){ss.info("Sorting web worker ready.");const e=this.splatMesh.getSplatDataTextures(),t=e.covariances.size,s=e.centerColors.size;ss.info("Covariances texture size: "+t.x+" x "+t.y),ss.info("Centers/colors texture size: "+s.x+" x "+s.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 s;return this.splatSceneRemovalPromise=new Promise((i,n)=>{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?n(e):i()},l=()=>!!this.isDisposingOrDisposed()&&(o(),!0);s=this.sortPromise||Promise.resolve(),s.then(()=>{if(l())return;const t=[],i=[],n=[];for(let s=0;s<this.splatMesh.scenes.length;s++){let r=!1;for(let t of e)if(t===s){r=!0;break}if(!r){const e=this.splatMesh.scenes[s];t.push(e.splatBuffer),i.push(this.splatMesh.sceneOptions[s]),n.push({position:e.position.clone(),quaternion:e.quaternion.clone(),scale:e.scale.clone()})}}this.disposeSortWorker(),this.splatMesh.dispose(),this.sceneRevealMode=h.Instant,this.createSplatMesh(),this.addSplatBuffers(t,i,!0,!1,!0).then(()=>{l()||(a(),this.splatMesh.scenes.forEach((e,t)=>{e.position.copy(n[t].position),e.quaternion.copy(n[t].quaternion),e.scale.copy(n[t].scale)}),this.splatMesh.updateTransforms(),this.splatRenderReady=!1,this.runSplatSort(!0).then(()=>{l()?this.splatRenderReady=!0:(s=this.sortPromise||Promise.resolve(),s.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 e of this.splatSceneDownloadControllers)e.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&&(_(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}vsyncNum=4;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}shouldRender=function(){let t=0;const s=new e.Vector3,i=new e.Quaternion,n=1e-4;return function(){if(!this.initialized||!this.splatRenderReady||this.isDisposingOrDisposed())return!1;let e=!1,r=!1;if(this.camera){const e=this.camera.position,t=this.camera.quaternion;r=Math.abs(e.x-s.x)>n||Math.abs(e.y-s.y)>n||Math.abs(e.z-s.z)>n||Math.abs(t.x-i.x)>n||Math.abs(t.y-i.y)>n||Math.abs(t.z-i.z)>n||Math.abs(t.w-i.w)>n}return e=this.renderMode!==o.Never&&(0===t||this.splatMesh.visibleRegionChanging||r||this.renderMode===o.Always||!0===this.dynamicMode||this.renderNextFrame),this.camera&&(s.copy(this.camera.position),i.copy(this.camera.quaternion)),t++,e}}();render=function(){if(!this.initialized||!this.splatRenderReady||this.isDisposingOrDisposed())return;const e=this.renderer.autoClear;(e=>{for(let t of e.children)if(t.visible)return!0;return!1})(this.threeScene)&&(this.renderer.render(this.threeScene,this.camera),this.renderer.autoClear=!1),this.renderer.render(this.splatMesh,this.camera),this.renderer.autoClear=!1,this.sceneHelper.getFocusMarkerOpacity()>0&&this.renderer.render(this.sceneHelper.focusMarker,this.camera),this.showControlPlane&&this.renderer.render(this.sceneHelper.controlPlane,this.camera),this.renderer.autoClear=e};update(e,t){const s=document.getElementById("fps");s&&(s.textContent=`FPS: ${this.currentFPS}`),this.frame>=this.totalFrames&&(this.frame=0),this.dropInMode&&this.updateForDropInMode(e,t),this.initialized&&this.splatRenderReady&&!this.isDisposingOrDisposed()&&(this.controls&&(this.controls.update(),this.camera.isOrthographicCamera&&!this.usingExternalCamera&&Viewer.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())}sortedIndexes;updateForDropInMode(e,t){this.renderer=e,this.splatMesh&&this.splatMesh.setRenderer(this.renderer),this.camera=t,this.controls&&(this.controls.object=t),this.init()}lastCalcTime=k();fpsFrameCount=0;updateFPS=()=>{if(this.consecutiveRenderFrames>60){const e=k();e-this.lastCalcTime>=1?(this.currentFPS=this.fpsFrameCount,this.fpsFrameCount=0,this.lastCalcTime=e):this.fpsFrameCount++}else this.currentFPS=null};updateForRendererSizeChanges=function(){const t=new e.Vector2,s=new e.Vector2;let i;return function(){this.usingExternalCamera||(this.renderer.getSize(s),void 0!==i&&i===this.camera.isOrthographicCamera&&s.x===t.x&&s.y===t.y||(this.camera.isOrthographicCamera?(this.camera.left=-s.x/2,this.camera.right=s.x/2,this.camera.top=s.y/2,this.camera.bottom=-s.y/2):this.camera.aspect=s.x/s.y,this.camera.updateProjectionMatrix(),t.copy(s),i=this.camera.isOrthographicCamera))}}();timingSensitiveUpdates=function(){let e;return function(){const t=k();e||(e=t);const s=t-e;this.updateCameraTransition(t),this.updateFocusMarker(s),e=t}}();tempCameraTarget=new e.Vector3;toPreviousTarget=new e.Vector3;toNextTarget=new e.Vector3;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)),s=(t/(Math.PI/3)*.65+.3)/t*(e-this.transitioningCameraTargetStartTime);this.tempCameraTarget.copy(this.previousCameraTarget).lerp(this.nextCameraTarget,s),this.camera.lookAt(this.tempCameraTarget),this.controls.target.copy(this.tempCameraTarget),s>=1&&(this.transitioningCameraTarget=!1)}};updateFocusMarker=function(){const t=new e.Vector2;let s=!1;return function(e){if(this.getRenderDimensions(t),this.transitioningCameraTarget){this.sceneHelper.setFocusMarkerVisibility(!0);const i=Math.max(this.sceneHelper.getFocusMarkerOpacity(),0);let n=Math.min(i+.4*e,1);this.sceneHelper.setFocusMarkerOpacity(n),this.sceneHelper.updateFocusMarker(this.nextCameraTarget,this.camera,t),s=!0,this.forceRenderNextFrame()}else{let i;if(i=s?1:Math.min(this.sceneHelper.getFocusMarkerOpacity(),1),i>0){this.sceneHelper.updateFocusMarker(this.nextCameraTarget,this.camera,t);let s=Math.max(i-.12*e,0);this.sceneHelper.setFocusMarkerOpacity(s),0===s&&this.sceneHelper.setFocusMarkerVisibility(!1)}i>0&&this.forceRenderNextFrame(),s=!1}}}();updateMeshCursor=function(){const t=[],s=new e.Vector2;return function(){this.showMeshCursor?(this.forceRenderNextFrame(),this.getRenderDimensions(s),t.length=0,this.raycaster.setFromCameraAndScreenPosition(this.camera,this.mousePosition,s),this.raycaster.intersectSplatMesh(this.splatMesh,t),t.length>0?(this.sceneHelper.setMeshCursorVisibility(!0),this.sceneHelper.positionAndOrientMeshCursor(t[0].origin,this.camera)):this.sceneHelper.setMeshCursorVisibility(!1)):(this.sceneHelper.getMeschCursorVisibility()&&this.forceRenderNextFrame(),this.sceneHelper.setMeshCursorVisibility(!1))}}();updateInfoPanel=function(){const t=new e.Vector2;return function(){if(!this.showInfo)return;const e=this.splatMesh.getSplatCount();this.getRenderDimensions(t),this.controls&&this.controls.target,this.showMeshCursor&&this.sceneHelper.meshCursor.position,e>0&&this.splatRenderCount}}();updateControlPlane(){this.showControlPlane?(this.sceneHelper.setControlPlaneVisibility(!0),this.sceneHelper.positionAndOrientControlPlane(this.controls.target,this.camera.up)):this.sceneHelper.setControlPlaneVisibility(!1)}mvpMatrix=new e.Matrix4;cameraPositionArray=[];lastSortViewDir=new e.Vector3(0,0,-1);sortViewDir=new e.Vector3(0,0,-1);lastSortViewPos=new e.Vector3;sortViewOffset=new e.Vector3;queuedSorts=[];partialSorts=[{angleThreshold:.55,sortFractions:[.125,.33333,.75]},{angleThreshold:.65,sortFractions:[.33333,.66667]},{angleThreshold:.8,sortFractions:[.5]}];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 s=0,i=0,n=!1,r=!1;if(this.sortViewDir.set(0,0,-1).applyQuaternion(this.camera.quaternion),s=this.sortViewDir.dot(this.lastSortViewDir),i=this.sortViewOffset.copy(this.camera.position).sub(this.lastSortViewPos).length(),!(e||this.splatMesh.dynamicMode||0!==this.queuedSorts.length||(s<=.99&&(n=!0),i>=1&&(r=!0),n||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(s<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};gatherSceneNodesForSort=function(){const t=[];let s=null;const i=new e.Vector3,n=new e.Vector3,r=new e.Vector3,a=new e.Matrix4,o=new e.Matrix4,l=new e.Matrix4,c=new e.Vector3,h=new e.Vector3(0,0,-1),d=new e.Vector3,p=e=>d.copy(e.max).sub(e.min).length();return function(d=!1){this.getRenderDimensions(c);const m=c.y/2/Math.tan(this.camera.fov/2*e.MathUtils.DEG2RAD),g=Math.atan(c.x/2/m),A=Math.atan(c.y/2/m),f=Math.cos(g),S=Math.cos(A),C=this.splatMesh.getSplatTree();if(C){o.copy(this.camera.matrixWorld).invert(),this.splatMesh.dynamicMode||o.multiply(this.splatMesh.matrixWorld);let e=0,s=0;for(let c=0;c<C.subTrees.length;c++){const u=C.subTrees[c];a.copy(o),this.splatMesh.dynamicMode&&(this.splatMesh.getSceneTransform(c,l),a.multiply(l));const m=u.nodesWithIndexes.length;for(let o=0;o<m;o++){const l=u.nodesWithIndexes[o];if(!l.data||!l.data.indexes||0===l.data.indexes.length)continue;r.copy(l.center).applyMatrix4(a);const c=r.length();r.normalize(),i.copy(r).setX(0).normalize(),n.copy(r).setY(0).normalize();const m=h.dot(n),g=h.dot(i),A=p(l);!d&&(m<f-.6||g<S-.6)&&c>A||(s+=l.data.indexes.length,t[e]=l,l.data.distanceToNode=c,e++)}}t.length=e,t.sort((e,t)=>e.data.distanceToNode<t.data.distanceToNode?-1:1);let c=s*u.BytesPerInt;for(let s=0;s<e;s++){const e=t[s],i=e.data.indexes.length,n=i*u.BytesPerInt;new Uint32Array(this.sortWorkerIndexesToSort.buffer,c-n,i).set(e.data.indexes),c-=n}return{splatRenderCount:s,shouldSortAll:!1}}{const e=this.splatMesh.getSplatCount();if(!s||s.length!==e){s=new Uint32Array(e);for(let t=0;t<e;t++)s[t]=t}return this.sortWorkerIndexesToSort.set(s),{splatRenderCount:e,shouldSortAll:!0}}}}();getSplatMesh(){return this.splatMesh}getSplatScene(e){return this.splatMesh.getScene(e)}getSceneCount(){return this.splatMesh.getSceneCount()}isMobile(){return navigator.userAgent.includes("Mobi")}updateMorphTarget(e){this.avatarMesh=e,this.splatMesh.flameModel=e,this.runMorphUpdate(),this.splatMesh.gaussianSplatCount=this.gaussianSplatCount}runMorphUpdate(){this.gaussianSplatCount=this.avatarMesh.geometry.attributes.position.count;var t=new Float32Array(this.avatarMesh.geometry.attributes.position.array);if(this.splatMesh.bonesNum=5,this.skinModel.skeleton.update(),this.boneRoot.updateMatrixWorld(!0),this.splatMesh.geometry.getAttribute("splatIndex")&&!1===this.setSkinAttibutes){this.setSkinAttibutes=!0;const t=this.splatMesh.geometry,s=this.skinModel.geometry.attributes.skinIndex,i=this.skinModel.geometry.attributes.skinWeight,n=new e.InstancedBufferAttribute(new s.array.constructor(s.array),4,s.normalized,1),r=new e.InstancedBufferAttribute(new i.array.constructor(i.array),4,i.normalized,1);n.setUsage(e.DynamicDrawUsage),r.setUsage(e.DynamicDrawUsage),t.setAttribute("skinIndex",n),t.setAttribute("skinWeight",r)}this.splatMesh.morphedMesh=t;let s=this.splatMesh.morphedMesh.length/3;null!=this.splatMesh.splatDataTextures.flameModel&&this.splatMesh.updateTetureAfterBSAndSkeleton(0,s-1,!1)}}const as=E("GaussianSplatRenderer"),os=0,ls=1.8,cs=1,hs=-10,ds=0,us=0,ps="ffffff",ms={offset:{},scale:{}},gs={hello:{size:2,isGroup:!1},idle:{size:1,isGroup:!1},listen:{size:0,isGroup:!1},speak:{size:6,isGroup:!1},think:{size:3,isGroup:!0},other:[]};class GaussianSplatRenderer{static async create(t,i,n={}){try{oe(t,"container"),te(i),n.downloadProgress&&re(n.downloadProgress,"options.downloadProgress",!1),n.loadProgress&&re(n.loadProgress,"options.loadProgress",!1),n.getChatState&&re(n.getChatState,"options.getChatState",!1),n.getExpressionData&&re(n.getExpressionData,"options.getExpressionData",!1),n.backgroundColor&&ae(n.backgroundColor,"options.backgroundColor"),as.info("Initializing GaussianSplatRenderer",{assetPath:i});const r=i;let a,o,c,h;try{const e=new URL(r,"undefined"!=typeof window?window.location.href:void 0).pathname.match(/\/([^/]+?)\.zip/);if(a=e?.[1],!a)throw new S("Character model name could not be extracted from path. Expected format: /path/name.zip","assetPath")}catch(e){if(e instanceof S)throw e;throw new S(`Invalid asset path format: ${e.message}`,"assetPath",e)}"undefined"!=typeof NProgress&&NProgress.start(),as.info("Downloading asset ZIP",{path:r});try{if(o=await fetch(r),!o.ok)throw new C(`Failed to download asset: ${o.statusText}`,o.status)}catch(e){if(e instanceof C)throw e;throw new C(`Network error downloading asset: ${e.message}`,0,e)}if(n.downloadProgress)try{n.downloadProgress(1)}catch(e){as.warn("Error in downloadProgress callback",e)}if(n.loadProgress)try{n.loadProgress(.1)}catch(e){as.warn("Error in loadProgress callback",e)}"undefined"!=typeof NProgress&&NProgress.done();try{c=await o.arrayBuffer()}catch(e){throw new C(`Failed to read response data: ${e.message}`,0,e)}as.debug("Unpacking ZIP archive");try{h=await s.loadAsync(c)}catch(e){throw new x(`Failed to unpack ZIP archive: ${e.message}`,r,e)}let d="";if(Object.values(h.files).forEach(e=>{e.dir&&(d=e.name?.slice(0,e.name?.length-1))}),!d)throw new x("No folder found in ZIP archive. Expected ZIP to contain a folder with model files.",r);as.debug("Found model folder in ZIP",{fileName:d}),as.debug("Creating GaussianSplatRenderer instance");const u=new GaussianSplatRenderer(t,h),p=pe.set(os??0,ls??0,cs??1),m=new e.Vector3(hs??0,ds??0,us??0);as.debug("Camera setup",{position:{x:p.x,y:p.y,z:p.z},rotation:{x:m.x,y:m.y,z:m.z}});let g,A=16777215;try{if(ps){const e=parseInt(ps,16);isNaN(e)?as.warn("Invalid backgroundColor in config, using default",{value:ps}):A=e}n?.backgroundColor&&(u.isHexColorStrict(n.backgroundColor)?A=parseInt(n.backgroundColor,16):as.warn("Invalid backgroundColor option, using config value",{value:n.backgroundColor}))}catch(e){as.warn("Error parsing backgroundColor, using default",e)}as.debug("Background color set",{backgroundColor:A.toString(16)}),u.getChatState=n?.getChatState,u.getExpressionData=n?.getExpressionData,as.debug("Creating Viewer instance");try{u.viewer=new Viewer({rootElement:t,threejsCanvas:u._canvas,cameraUp:[0,1,0],initialCameraPosition:[p.x,p.y,p.z],initialCameraRotation:[m.x,m.y,m.z],sphericalHarmonicsDegree:0,backgroundColor:A})}catch(e){throw new v(`Failed to create Viewer instance: ${e.message}`,e)}as.info("Loading model",{fileName:d});try{await u.loadModel(d,gs,ms)}catch(e){throw new x(`Failed to load model: ${e.message}`,d,e)}if(n.loadProgress)try{n.loadProgress(.2)}catch(e){as.warn("Error in loadProgress callback",e)}as.debug("Loading offset PLY file");try{g=await u.unpackFileAsBlob(d+"/offset.ply")}catch(e){throw new x(`Failed to load offset.ply: ${e.message}`,d+"/offset.ply",e)}as.debug("Checking for iris_occlusion.json");let f=null;try{f=await u._loadJsonFromZip(d+"/iris_occlusion.json"),f?(as.info("Iris occlusion configuration loaded",{rightIrisRanges:f.right_iris?.length??0,leftIrisRanges:f.left_iris?.length??0}),u.irisOcclusionConfig=f,u.viewer.irisOcclusionConfig=f):as.debug("No iris_occlusion.json found, iris occlusion will be disabled")}catch(e){as.warn("Failed to load iris_occlusion.json, continuing without it",{error:e.message}),u.irisOcclusionConfig=null}if(n.loadProgress)try{n.loadProgress(.3)}catch(e){as.warn("Error in loadProgress callback",e)}as.debug("Adding splat scene");try{await u.viewer.addSplatScene(g,{progressiveLoad:!0,sharedMemoryForWorkers:!1,showLoadingUI:!1,format:l.Ply})}catch(e){throw new v(`Failed to add splat scene: ${e.message}`,e)}try{u.render()}catch(e){as.error("Error in initial render",e)}if(n.loadProgress)try{n.loadProgress(1)}catch(e){as.warn("Error in loadProgress callback",e)}return as.info("GaussianSplatRenderer initialized successfully"),u}catch(e){if(e instanceof S||e instanceof C||e instanceof x||e instanceof v)throw as.error("Initialization failed",{errorCode:e.code,message:e.message}),e;throw as.error("Unexpected error during initialization",e),new v(`Unexpected error initializing GaussianSplatRenderer: ${e.message}`,e)}}static async getInstance(e,t,s={}){return as.warn("getInstance() is deprecated. Use create() instead. Each call creates a new instance."),this.create(e,t,s)}constructor(t,s){if(as.debug("GaussianSplatRenderer constructor called"),this._disposed=!1,this._blobUrlManager=new ye,this.zipUrls={urls:new Map,zip:s},this.lastTime=0,this.startTime=0,this.expressionData={},this.chatState=Be.Idle,this._canvas=null,"undefined"!=typeof document&&t){this._canvas=document.createElement("canvas");const{width:e,height:s}=t.getBoundingClientRect();this._canvas.style.visibility="visible",this._canvas.width=e,this._canvas.height=s,t.appendChild(this._canvas),as.debug("Canvas setup",{width:e,height:s})}this.clock=new e.Clock,this.startTime=performance.now()/1e3,this.viewer=null,this.mixer=null,this.animManager=null,this.model=null,this.irisOcclusionConfig=null,this.motioncfg=null,this.getChatState=null,this.getExpressionData=null,as.debug("GaussianSplatRenderer instance created")}_assertNotDisposed(){if(this._disposed)throw new y("GaussianSplatRenderer has been disposed")}dispose(){if(this._disposed)as.warn("GaussianSplatRenderer.dispose() called on already disposed instance");else{as.info("Disposing GaussianSplatRenderer"),this._canvas&&(this._canvas.style.visibility="hidden",this._canvas.parentNode&&this._canvas.parentNode.removeChild(this._canvas),this._canvas=null),this.disposeModel();try{this._blobUrlManager?.dispose()}catch(e){as.error("Error disposing BlobUrlManager",e)}this.zipUrls?.urls&&(this.zipUrls.urls.forEach(e=>{try{URL.revokeObjectURL(e)}catch(t){as.warn("Error revoking blob URL",{url:e,error:t})}}),this.zipUrls.urls.clear()),this.viewer=null,this.mixer=null,this.animManager=null,this.model=null,this.motioncfg=null,this.getChatState=null,this.getExpressionData=null,this.zipUrls=null,this._disposed=!0,GaussianSplatRenderer.instance=void 0,as.debug("GaussianSplatRenderer disposed successfully")}}disposeModel(){if(as.debug("Disposing model resources"),this.mixer){try{this.mixer.stopAllAction(),this.viewer?.avatarMesh&&this.mixer.uncacheRoot(this.viewer.avatarMesh)}catch(e){as.error("Error disposing animation mixer",e)}this.mixer=null}if(this.animManager){try{this.animManager.dispose()}catch(e){as.error("Error disposing animation manager",e)}this.animManager=null}if(this.viewer){try{this.viewer.dispose()}catch(e){as.error("Error disposing viewer",e)}this.viewer=null}as.debug("Model resources disposed")}getCamera(){return this.viewer?.camera}updateBS(e){let t={browDownLeft:0,browDownRight:0,browInnerUp:0,browOuterUpLeft:0,browOuterUpRight:0,mouthCheekPuff:0,cheekSquintLeft:0,cheekSquintRight:0,eyeBlinkLeft:0,eyeBlinkRight:0,eyeLookDownLeft:0,eyeLookDownRight:0,eyeLookInLeft:0,eyeLookInRight:0,eyeLookOutLeft:0,eyeLookOutRight:0,eyeLookUpLeft:0,eyeLookUpRight:0,eyeSquintLeft:0,eyeSquintRight:0,eyeWideLeft:0,eyeWideRight:0,jawForward:0,jawLeft:0,jawOpen:0,jawRight:0,mouthClose:0,mouthDimpleLeft:0,mouthDimpleRight:0,mouthFrownLeft:0,mouthFrownRight:0,mouthFunnel:0,mouthLeft:0,mouthLowerDownLeft:0,mouthLowerDownRight:0,mouthPressLeft:0,mouthPressRight:0,mouthPucker:0,mouthRight:0,mouthRollLower:0,mouthRollUpper:0,mouthShrugLower:0,mouthShrugUpper:0,mouthSmileLeft:0,mouthSmileRight:0,mouthStretchLeft:0,mouthStretchRight:0,mouthUpperUpLeft:0,mouthUpperUpRight:0,noseSneerLeft:0,noseSneerRight:0,tongueOut:0};return null!=e&&(t=e),t}render(){if(!this.viewer||!this.viewer.selfDrivenMode)throw new Error("Cannot start viewer unless it is in self driven mode.");{this.viewer.requestFrameId=requestAnimationFrame(()=>this.render());const e=1/30,t=performance.now()/1e3,s=this.viewer.totalFrames||1,i=(t-this.startTime)%(s*e),n=Math.floor(i/e);if(this.viewer.frame=n,this.getChatState&&(this.chatState=this.getChatState(),this._lastLoggedState&&this._lastLoggedState===this.chatState||(as.debug("Chat state changed",{newState:this.chatState,hasAnimManager:!!this.animManager}),this._lastLoggedState=this.chatState),this.animManager?.update(this.chatState)),this.getExpressionData&&(this.expressionData=this.updateBS(this.getExpressionData())),this.mixer&&this.animManager){const e=this.clock.getDelta();if(this.mixer.update(e),this.motioncfg)for(const e in this.expressionData){const t=this.motioncfg.offset?.[e],s=this.motioncfg.scale?.[e];void 0!==t&&void 0!==s&&(this.expressionData[e]=this.expressionData[e]*s+t)}this.setExpression()}else this._warnedOnce||(as.warn("Mixer or animManager not initialized, skipping animation update",{hasMixer:!!this.mixer,hasAnimManager:!!this.animManager}),this._warnedOnce=!0),this.setExpression();this.viewer.update(this.viewer.renderer,this.viewer.camera);const r=this.viewer.shouldRender();this._renderLogCount<=3&&as.debug("shouldRender check",{shouldRender:r}),r?(this.viewer.render(),this.viewer.consecutiveRenderFrames++):this.viewer.consecutiveRenderFrames=0,this.viewer.renderNextFrame=!1,this.viewer.selfDrivenModeRunning=!0}}isHexColorStrict(e){return"string"==typeof e&&/^(#|0x)[0-9A-Fa-f]{6}$/i.test(e)}setExpression(){if(this.viewer?.splatMesh){this.viewer.splatMesh.bsWeight=this.expressionData;const e=this.viewer.splatMesh.material;if(e?.uniforms){const t=this.expressionData.eyeBlinkLeft||0,s=this.expressionData.eyeBlinkRight||0;e.uniforms.eyeBlinkLeft&&(e.uniforms.eyeBlinkLeft.value=t),e.uniforms.eyeBlinkRight&&(e.uniforms.eyeBlinkRight.value=s)}}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 s in t){const i=t[s],n=this.expressionData[s];void 0!==n&&(e.morphTargetInfluences[i]=Math.max(0,Math.min(1,n)))}}}})}async loadModel(t,s,i){const[n,r,a]=await Promise.all([this.unpackAndLoadGlb(t+"/skin.glb"),this.unpackAndLoadGlb(t+"/animation.glb"),this.unpackAndLoadJson(t+"/vertex_order.json")]);if(!this.viewer)throw new Error("render viewer is not initialized");let o,l;n.traverse(t=>{t.isSkinnedMesh&&(o=t),t instanceof e.Bone&&"hip"===t.name&&(l=t)}),this.viewer.sortedIndexes=a,o&&(this.viewer.gaussianSplatCount=o.geometry.attributes.position.count),this.viewer.avatarMesh=n,this.viewer.skinModel=o,this.viewer.boneRoot=l,this.mixer=new e.AnimationMixer(n),this.animManager=new Oe(this.mixer,r,s),this.motioncfg=i,Array.isArray(r)&&r.length>0&&r[0].duration?this.viewer.totalFrames=Math.floor(30*r[0].duration):this.viewer.totalFrames=1,as.debug("Total frames calculated",{totalFrames:this.viewer.totalFrames}),o&&this.viewer.updateMorphTarget(o),this.viewer.threeScene.add(n),n.visible=!1,o&&o.skeleton.computeBoneTexture()}async unpackFileAsBlob(e){if(this._assertNotDisposed(),this.zipUrls.urls.has(e))return as.debug("Returning cached blob URL",{path:e}),this.zipUrls.urls.get(e);as.debug("Unpacking file from ZIP",{path:e});const t=this.zipUrls.zip?.file(e);if(!t)throw new x(`File not found in ZIP archive: ${e}`,e);let s;try{s=await t.async("blob")}catch(t){throw new x(`Failed to extract file from ZIP: ${t.message}`,e,t)}if(!s)throw new x(`File extracted but blob is empty: ${e}`,e);const i=this._getMimeType(e),n=this._blobUrlManager.createBlobUrl(s,i,`zip:${e}`);return this.zipUrls.urls.set(e,n),as.debug("Blob URL created and cached",{path:e,url:n.substring(0,50)}),n}async _loadJsonFromZip(e){this._assertNotDisposed(),as.debug("Attempting to load JSON from ZIP",{path:e});const t=this.zipUrls.zip?.file(e);if(!t)return as.debug("JSON file not found in ZIP, returning null",{path:e}),null;let s;try{s=await t.async("text")}catch(t){throw new ParseError(`Failed to extract JSON file from ZIP: ${t.message}`,e,t)}try{const t=JSON.parse(s);return as.debug("JSON file loaded successfully",{path:e}),t}catch(t){throw new ParseError(`Failed to parse JSON file: ${t.message}`,e,t)}}async unpackAndLoadGlb(e){if(this._assertNotDisposed(),this.zipUrls.urls.has(e))return as.debug("Using cached GLB URL",{path:e}),this.LoadGLTF(this.zipUrls.urls.get(e));as.debug("Unpacking GLB from ZIP",{path:e});const t=this.zipUrls.zip?.file(e);if(!t)throw new x(`GLB file not found in ZIP archive: ${e}`,e);let s;try{s=await t.async("arraybuffer")}catch(t){throw new x(`Failed to extract GLB from ZIP: ${t.message}`,e,t)}if(!s)throw new x(`GLB extracted but ArrayBuffer is empty: ${e}`,e);const i=new Blob([s],{type:"model/gltf-binary"}),n=this._blobUrlManager.createBlobUrl(i,"model/gltf-binary",`zip:${e}`);return this.zipUrls.urls.set(e,n),as.debug("GLB blob URL created and cached",{path:e}),this.LoadGLTF(n)}_getMimeType(e){const t=e.split(".").pop()?.toLowerCase();return{ply:"model/ply",glb:"model/gltf-binary",gltf:"model/gltf+json",json:"application/json",bin:"application/octet-stream",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg"}[t]||"application/octet-stream"}async unpackAndLoadJson(e){const t=this.zipUrls.zip?.file(e);if(!t)throw new Error(`File not found in ZIP: ${e}`);const s=await t.async("string");if(!s)throw new Error(`Failed to read file from ZIP: ${e}`);return JSON.parse(s)}async LoadGLTF(e){return new Promise((s,i)=>{(new t.GLTFLoader).load(e,e=>{e.animations.length>0?s(e.animations):s(e.scene)},void 0,e=>{i(e)})})}}const As=function(){const e=new Float32Array(1),t=new Int32Array(e.buffer);return function(s){return e[0]=s,t[0]}}();function fs(t,s,i){const n=new e.Vector2(4096,2048),r=t.geometry.attributes.position.array;let a=[];const o=r.length/3,l=t.geometry.morphAttributes.position.length;Object.keys(t.morphTargetDictionary).forEach(e=>{const s=t.morphTargetDictionary[e],i=t.geometry.morphAttributes.position[s];a=a.concat(Array.from(i.array))}),a=a.concat(Array.from(r));const c=new Float32Array(n.x*n.y*4),h=new Uint32Array(n.x*n.y*4);for(let e=0;e<o*(l+1);e++)c[4*e+0]=a[3*e+0],c[4*e+1]=a[3*e+1],c[4*e+2]=a[3*e+2],h[4*e+0]=As(c[4*e+0]),h[4*e+1]=As(c[4*e+1]),h[4*e+2]=As(c[4*e+2]);const d=new e.DataTexture(h,n.x,n.y,e.RGBAIntegerFormat,e.UnsignedIntType);return d.internalFormat="RGBA32UI",d.needsUpdate=!0,s.uniforms.flameModelTexture.value=d,s.uniforms.flameModelTextureSize.value.copy(n),s.uniforms.gaussianSplatCount.value=i,s.uniformsNeedUpdate=!0,{data:h,texture:d,size:n,baseData:{flameModelPos:c}}}function Ss(t,s,i,n,r,a,o){if(!i)return null;const l=new e.Vector2(4,32),c=new Float32Array(t),h=new Uint32Array(l.x*l.y*4);if(o){for(let e=0;e<16*s;e++)h[e]=As(c[e]);r&&r.skeleton&&(a.uniforms.boneTexture0.value=r.skeleton.boneTexture,a.uniforms.bindMatrix.value=r.bindMatrix,a.uniforms.bindMatrixInverse.value=r.bindMatrixInverse)}for(const e in i)if(Object.hasOwn(i,e)){const t=i[e];h[n[e]+16*s]=As(t)}const d=new e.DataTexture(h,l.x,l.y,e.RGBAIntegerFormat,e.UnsignedIntType);return d.internalFormat="RGBA32UI",d.needsUpdate=!0,a.uniforms.boneTexture.value=d,a.uniforms.boneTextureSize.value.copy(l),a.uniformsNeedUpdate=!0,{data:h,texture:d,size:l,baseData:{boneMatrix:h}}}function Cs(e,t,s,i,n,r,a,o=!1){if(i&&n){if(o){const i=new Float32Array(t);for(let t=0;t<16*s;t++)e.baseData.boneMatrix[t]=As(i[t])}for(const t in i)if(Object.hasOwn(i,t)){const r=i[t],a=n[t];e.baseData.boneMatrix[a+16*s]=As(r)}e.boneMatrix.texture.data=e.baseData.boneMatrix,e.boneMatrix.texture.needsUpdate=!0,a.uniforms.boneTexture.value=e.boneMatrix.texture,r.skeleton&&(a.uniforms.boneTexture0.value=r.skeleton.boneTexture,a.uniforms.bindMatrix.value=r.bindMatrix,a.uniforms.bindMatrixInverse.value=r.bindMatrixInverse),a.uniformsNeedUpdate=!0}}function xs(t,s,i){const n=t.geometry.attributes.position.array.length/3,r=new e.Vector2(512,512),a=new Float32Array(r.x*r.y*4),o=new Uint32Array(r.x*r.y*4);for(let e=0;e<n;e++)a[8*e+0]=s[e][0],a[8*e+1]=s[e][1],a[8*e+2]=s[e][2],a[8*e+3]=s[e][3],a[8*e+4]=s[e][4],o[8*e+0]=As(s[e][0]),o[8*e+1]=As(s[e][1]),o[8*e+2]=As(s[e][2]),o[8*e+3]=As(s[e][3]),o[8*e+4]=As(s[e][4]);const l=new e.DataTexture(o,r.x,r.y,e.RGBAIntegerFormat,e.UnsignedIntType);return l.internalFormat="RGBA32UI",l.needsUpdate=!0,i.uniforms.boneWeightTexture.value=l,i.uniforms.boneWeightTextureSize.value.copy(r),i.uniformsNeedUpdate=!0,{data:o,texture:l,size:r,baseData:{boneWeight:o}}}function ys(e,t){const s=[];for(let i=0;i<t;i++){const t=e.bones[i].matrixWorld.clone().multiply(e.boneInverses[i].clone()).elements;for(let e=0;e<t.length;e++)s.push(t[e])}return new Float32Array(s)}const vs={buildModelTexture:fs,buildBoneMatrixTexture:Ss,updateBoneMatrixTexture:Cs,buildBoneWeightTexture:xs,getUpdatedBoneMatrices:ys},Is=E("FlameAnimator");exports.ARKIT_BLENDSHAPES_COUNT=Ee,exports.ARKitBlendshapes=Te,exports.AbortedPromiseError=R,exports.AnimationManager=Oe,exports.BASE_COMPONENT_COUNT=14,exports.BlobUrlManager=ye,exports.CENTER_COLORS_ELEMENTS_PER_SPLAT=4,exports.CENTER_COLORS_ELEMENTS_PER_TEXEL=4,exports.CONSECUTIVE_RENDERED_FRAMES_FOR_FPS_CALCULATION=60,exports.COVARIANCES_ELEMENTS_PER_SPLAT=6,exports.COVARIANCES_ELEMENTS_PER_TEXEL_ALLOCATED=4,exports.COVARIANCES_ELEMENTS_PER_TEXEL_COMPRESSED_ALLOCATED=8,exports.COVARIANCES_ELEMENTS_PER_TEXEL_COMPRESSED_STORED=6,exports.COVARIANCES_ELEMENTS_PER_TEXEL_STORED=4,exports.Constants=u,exports.DefaultSphericalHarmonics8BitCompressionHalfRange=W,exports.DefaultSphericalHarmonics8BitCompressionRange=p,exports.DirectLoadError=et,exports.EventEmitter=we,exports.FLAME_BONES_COUNT=Me,exports.FOCUS_MARKER_FADE_IN_SPEED=.4,exports.FOCUS_MARKER_FADE_OUT_SPEED=.12,exports.FieldSize=yt,exports.FieldSizeStringMap=xt,exports.FlameAnimator=class{constructor(){this.skeleton=null,this.bones=null,this.flameParams=null,this.lbsWeight=null,this.frame=0,this.totalFrames=0,this.useFlame=!0,this.avatarMesh=null,this.gaussianSplatCount=0,this._disposed=!1,Is.debug("FlameAnimator instance created")}_assertNotDisposed(){if(this._disposed)throw new y("FlameAnimator has been disposed")}initialize(e,t,s,i){this._assertNotDisposed();try{ie(e,["rotation","expr","neck_pose","jaw_pose","eyes_pose"],"flameParams")}catch(e){throw Is.error("Invalid flameParams",e),e}if(!(i&&i.geometry&&i.geometry.attributes&&i.geometry.attributes.position)){const e=new S("avatarMesh must have geometry with position attribute","avatarMesh");throw Is.error("Invalid avatarMesh",e),e}Is.info("Initializing FlameAnimator",{frameCount:e.rotation?.length,splatCount:i.geometry.attributes.position.count}),this.flameParams=e,this.lbsWeight=s,this.avatarMesh=i,e.rotation&&Array.isArray(e.rotation)?(this.totalFrames=e.rotation.length,Is.debug("Animation has frames",{totalFrames:this.totalFrames})):(Is.warn("No rotation data found, totalFrames set to 0"),this.totalFrames=0),this.gaussianSplatCount=i.geometry.attributes.position.count;try{this.buildSkeleton(t),Is.debug("Skeleton built successfully",{boneCount:this.bones?.length})}catch(e){throw Is.error("Failed to build skeleton",e),new S(`Failed to build skeleton: ${e.message}`,"boneTree",e)}}buildSkeleton(t){if(!t)return;this.bones=[];const s=[],i=(t,n=null)=>{const r=new e.Bone;r.name=t.name||`bone_${this.bones.length}`,t.position&&r.position.fromArray(t.position),t.rotation&&r.rotation.fromArray(t.rotation),t.scale&&r.scale.fromArray(t.scale),n&&n.add(r),this.bones.push(r);const a=new e.Matrix4;t.inverseBindMatrix?a.fromArray(t.inverseBindMatrix):(r.updateMatrixWorld(!0),a.copy(r.matrixWorld).invert()),s.push(a),t.children&&t.children.forEach(e=>i(e,r))};Array.isArray(t)?(t.forEach((t,i)=>{const n=new e.Bone;n.name=t.name||`bone_${i}`,t.position&&n.position.fromArray(t.position),this.bones.push(n);const r=new e.Matrix4;t.inverseBindMatrix&&r.fromArray(t.inverseBindMatrix),s.push(r)}),this.bones.length>=5&&(this.bones[0].add(this.bones[1]),this.bones[1].add(this.bones[2]),this.bones[1].add(this.bones[3]),this.bones[1].add(this.bones[4]))):t.root&&i(t.root),this.skeleton=new e.Skeleton(this.bones,s)}setBoneRotation(e,t,s=!1){if(this._assertNotDisposed(),!e||!t||!Array.isArray(t))throw new S("bone and angles array are required","bone/angles");const i=de.acquire();try{if(s){if(t.length<4)throw new S("Quaternion requires 4 values","angles");i.set(t[0],t[1],t[2],t[3])}else{if(t.length<3)throw new S("Axis-angle requires 3 values","angles");const e=ce.acquire();try{e.set(t[0],t[1],t[2]);const s=e.length();e.normalize(),i.setFromAxisAngle(e,s)}finally{ce.release(e)}}e.quaternion.copy(i),e.updateMatrixWorld(!0)}finally{de.release(i)}}updateFlameBones(){if(this._assertNotDisposed(),!this.flameParams||!this.skeleton)return Is.warn("Cannot update bones: flameParams or skeleton not initialized"),{};const e=this.frame,t=this.flameParams.expr[e];try{const t=this.flameParams.rotation[e];this.setBoneRotation(this.skeleton.bones[0],t);const s=this.flameParams.neck_pose[e];this.setBoneRotation(this.skeleton.bones[1],s);const i=this.flameParams.jaw_pose[e];this.setBoneRotation(this.skeleton.bones[2],i);const n=this.flameParams.eyes_pose[e];this.setBoneRotation(this.skeleton.bones[3],n.slice(0,3)),this.setBoneRotation(this.skeleton.bones[4],n.slice(3,6))}catch(t){throw Is.error("Error setting bone rotations",{frame:e,error:t}),t}return this.skeleton.update(),{bsWeight:t,bonesMatrix:vs.getUpdatedBoneMatrices(this.skeleton,5),bonesNum:5,bonesWeight:this.lbsWeight}}runMorphUpdate(e){const t=new Float32Array(this.avatarMesh.geometry.attributes.position.array);if(e.gaussianSplatCount=this.gaussianSplatCount,e.bonesNum=5,this.useFlame){const t=this.updateFlameBones();e.bsWeight=t.bsWeight,e.bonesMatrix=t.bonesMatrix,e.bonesNum=t.bonesNum,e.bonesWeight=t.bonesWeight}e.morphedMesh=t;const s=e.morphedMesh.length/3;e.splatDataTextures&&e.splatDataTextures.flameModel&&e.updateTextureAfterBSAndSkeleton(0,s-1,this.useFlame)}setFrame(e){if(this._assertNotDisposed(),"number"!=typeof e||isNaN(e))throw new S("frame must be a valid number","frame");this.totalFrames>0?this.frame=(e%this.totalFrames+this.totalFrames)%this.totalFrames:this.frame=0}nextFrame(){this._assertNotDisposed(),this.totalFrames>0&&(this.frame=(this.frame+1)%this.totalFrames)}getSkeleton(){return this._assertNotDisposed(),this.skeleton}getFrame(){return this._assertNotDisposed(),this.frame}getTotalFrames(){return this._assertNotDisposed(),this.totalFrames}dispose(){this._disposed?Is.warn("FlameAnimator.dispose() called on already disposed instance"):(Is.info("Disposing FlameAnimator"),this.skeleton&&(this.skeleton.dispose(),this.skeleton=null),this.bones=null,this.flameParams=null,this.lbsWeight=null,this.avatarMesh=null,this.frame=0,this.totalFrames=0,this.gaussianSplatCount=0,this._disposed=!0,Is.debug("FlameAnimator disposed successfully"))}},exports.FlameBoneNames=De,exports.FlameConstants={FlameBonesCount:5,DefaultBlendshapeCount:52,FlameModelTextureSize:{width:4096,height:2048},BoneTextureSize:{width:4,height:32},BoneWeightTextureSize:{width:512,height:512}},exports.FlameTextureManager=vs,exports.FrameBudgetMonitor=class{constructor(e=60,t=null){this._targetFps=e,this._frameBudget=1e3/e,this._onViolation=t,this._violations=0,this._frameStart=0}startFrame(){this._frameStart=performance.now()}checkBudget(e=""){const t=performance.now()-this._frameStart,s=t<this._frameBudget;return s||(this._violations++,this._onViolation&&this._onViolation({location:e,elapsed:t,budget:this._frameBudget,overrun:t-this._frameBudget}),Ie.warn(`Frame budget violation at ${e}: ${t.toFixed(2)}ms / ${this._frameBudget.toFixed(2)}ms`)),s}getViolationCount(){return this._violations}resetViolations(){this._violations=0}},exports.GaussianSplatRenderer=GaussianSplatRenderer,exports.Hello=Pe,exports.Hit=$t,exports.INRIAV1PlyParser=Nt,exports.Idle=ke,exports.InternalLoadType=g,exports.Listen=_e,exports.LoaderStatus=A,exports.LoaderUtils=class{static decodeText(e){if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let s=0,i=e.length;s<i;s++)t+=String.fromCharCode(e[s]);try{return decodeURIComponent(escape(t))}catch{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)}},exports.LogLevel=a,exports.Logger=w,exports.LoggerLevel=b,exports.MINIMUM_DISTANCE_TO_NEW_FOCAL_POINT=.5,exports.MIN_SPLAT_COUNT_TO_SHOW_SPLAT_TREE_LOADING_SPINNER=m,exports.ObjectPool=le,exports.PlyFormat=ut,exports.PlyLoader=Kt,exports.PlyParser=Gt,exports.PlyParserUtils=vt,exports.PoolScope=class{constructor(){this._allocated=[]}vector3(){const e=ce.acquire();return this._allocated.push({pool:ce,obj:e}),e}matrix4(){const e=he.acquire();return this._allocated.push({pool:he,obj:e}),e}quaternion(){const e=de.acquire();return this._allocated.push({pool:de,obj:e}),e}euler(){const e=ue.acquire();return this._allocated.push({pool:ue,obj:e}),e}releaseAll(){for(const{pool:e,obj:t}of this._allocated)e.release(t);this._allocated.length=0}getAllocatedCount(){return this._allocated.length}},exports.Ray=Xt,exports.Raycaster=Zt,exports.RenderLoop=class{constructor(e,t,s={}){this._update=e,this._render=t,this._targetFps=s.targetFps||60,this._maxDeltaTime=s.maxDeltaTime||.1,this._frameBudget=1e3/this._targetFps,this._running=!1,this._rafId=null,this._lastTime=0,this._frameCount=0,this._deferredTasks=[],this._fpsHistory=[],this._fpsHistorySize=60,this._lastFpsUpdate=0,this._currentFps=0}start(){this._running?Ie.warn("RenderLoop already running"):(this._running=!0,this._lastTime=performance.now(),this._frameCount=0,Ie.info("RenderLoop started"),this._tick())}stop(){this._running&&(this._running=!1,null!==this._rafId&&(cancelAnimationFrame(this._rafId),this._rafId=null),Ie.info(`RenderLoop stopped after ${this._frameCount} frames`))}_tick=()=>{if(!this._running)return;const e=performance.now(),t=(e-this._lastTime)/1e3,s=Math.min(t,this._maxDeltaTime);this._lastTime=e,this._frameCount++;try{this._update(s),this._render();const t=performance.now()-e,i=this._frameBudget-t;i>1&&this._deferredTasks.length>0&&this._processDeferredTasks(i-1),this._updateFpsTracking(performance.now()-e)}catch(e){Ie.error("Error in render loop:",e)}this._rafId=requestAnimationFrame(this._tick)};_updateFpsTracking(e){this._fpsHistory.push(1e3/e),this._fpsHistory.length>this._fpsHistorySize&&this._fpsHistory.shift();const t=performance.now();t-this._lastFpsUpdate>1e3&&(this._currentFps=this._fpsHistory.reduce((e,t)=>e+t,0)/this._fpsHistory.length,this._lastFpsUpdate=t)}_processDeferredTasks(e){const t=performance.now();for(;this._deferredTasks.length>0&&!(performance.now()-t>=e);){const e=this._deferredTasks.shift();try{e.fn()}catch(t){Ie.error(`Error in deferred task: ${e.label}`,t)}}}executeOrDefer(e,t=0,s=""){performance.now()-this._lastTime<.8*this._frameBudget?e():(this._deferredTasks.push({fn:e,priority:t,label:s}),this._deferredTasks.sort((e,t)=>t.priority-e.priority))}getFps(){return Math.round(this._currentFps)}getStats(){return{fps:this.getFps(),frameCount:this._frameCount,deferredTaskCount:this._deferredTasks.length,running:this._running}}isRunning(){return this._running}getFrameCount(){return this._frameCount}clearDeferredTasks(){this._deferredTasks.length=0,Ie.debug("Cleared all deferred tasks")}},exports.RenderMode=o,exports.SCALES_ROTATIONS_ELEMENTS_PER_TEXEL=4,exports.SCENE_FADEIN_RATE_FAST=.012,exports.SCENE_FADEIN_RATE_GRADUAL=.003,exports.SCENE_INDEXES_ELEMENTS_PER_TEXEL=1,exports.SceneFormat=l,exports.SceneRevealMode=h,exports.Semver=z,exports.Speak=Ue,exports.SplatBuffer=ct,exports.SplatBufferGenerator=dt,exports.SplatGeometry=ze,exports.SplatMaterial=Ne,exports.SplatMaterial2D=We,exports.SplatMaterial3D=Ge,exports.SplatMesh=Ze,exports.SplatPartitioner=ht,exports.SplatRenderMode=d,exports.SplatScene=He,exports.SplatTree=Ve,exports.State=Fe,exports.THREE_CAMERA_FOV=50,exports.TYVoiceChatState=Be,exports.TextureConstants={CENTER_COLORS_ELEMENTS_PER_TEXEL:4,CENTER_COLORS_ELEMENTS_PER_SPLAT:4,COVARIANCES_ELEMENTS_PER_TEXEL_STORED:2,COVARIANCES_ELEMENTS_PER_TEXEL_ALLOCATED:4,COVARIANCES_ELEMENTS_PER_TEXEL_COMPRESSED_STORED:2,COVARIANCES_ELEMENTS_PER_TEXEL_COMPRESSED_ALLOCATED:4,COVARIANCES_ELEMENTS_PER_SPLAT:6,SCALES_ROTATIONS_ELEMENTS_PER_TEXEL:4,SCENE_INDEXES_ELEMENTS_PER_TEXEL:1,MAX_TEXTURE_TEXELS:16777216},exports.Think=Le,exports.TypedEventEmitter=class extends we{constructor(e){super(),this._allowedEvents=new Set(e)}_validateEvent(e){if(!this._allowedEvents.has(e))throw new S(`Event '${e}' is not registered. Allowed events: ${Array.from(this._allowedEvents).join(", ")}`,"event")}on(e,t,s){return this._validateEvent(e),super.on(e,t,s)}emit(e,...t){return this._validateEvent(e),super.emit(e,...t)}},exports.UncompressedSplatArray=tt,exports.Viewer=Viewer,exports.abortablePromiseWithExtractedComponents=H,exports.buildBoneMatrixTexture=Ss,exports.buildBoneWeightTexture=xs,exports.buildModelTexture=fs,exports.clamp=P,exports.configureForDevelopment=function(){D(b.DEBUG)},exports.configureForProduction=function(){D(b.NONE)},exports.convertBetweenCompressionLevels=J,exports.copyBetweenBuffers=(e,t,s,i,n=0)=>{const r=new Uint8Array(e,t),a=new Uint8Array(s,i);for(let e=0;e<n;e++)a[e]=r[e]},exports.createTrackedBlobUrl=function(e,t,s){return ve.createBlobUrl(e,t,s)},exports.dataViewFloatForCompressionLevel=(e,t,s,i=!1)=>0===s?e.getFloat32(4*t,!0):1===s||2===s&&!i?e.getUint16(2*t,!0):e.getUint8(t,!0),exports.delayedExecute=L,exports.disposeAllMeshes=_,exports.disposeAllPools=function(){ce.dispose(),he.dispose(),de.dispose(),ue.dispose()},exports.eulerPool=ue,exports.fetchWithProgress=F,exports.floatToHalf=X,exports.fromHalfFloat=G,exports.fromHalfFloatToUint8=j,exports.fromUint8=K,exports.fromUint8ToHalfFloat=Y,exports.getCurrentTime=k,exports.getGlobalBlobUrlManager=function(){return ve},exports.getIOSSemever=V,exports.getLogger=E,exports.getPoolStats=function(){return{vector3:ce.getStats(),matrix4:he.getStats(),quaternion:de.getStats(),euler:ue.getStats()}},exports.getSphericalHarmonicsComponentCountForDegree=U,exports.getUpdatedBoneMatrices=ys,exports.isIOS=Q,exports.matrix4Pool=he,exports.nativePromiseWithExtractedComponents=O,exports.quaternionPool=de,exports.revokeTrackedBlobUrl=function(e){return ve.revokeBlobUrl(e)},exports.rgbaArrayToInteger=Z,exports.rgbaToInteger=function(e,t,s,i){return e+(t<<8)+(s<<16)+(i<<24)},exports.sceneFormatFromPath=c,exports.setGlobalLogLevel=D,exports.tempMatrix4A=Ae,exports.tempMatrix4B=fe,exports.tempQuaternionA=Se,exports.tempQuaternionB=Ce,exports.tempVector3A=pe,exports.tempVector3B=me,exports.tempVector3C=ge,exports.toHalfFloat=N,exports.toUint8=q,exports.toUncompressedFloat=(t,s,i=!1,n,r)=>0===s?t:1===s||2===s&&!i?e.DataUtils.fromHalfFloat(t):2===s?K(t,n,r):void 0,exports.uintEncodedFloat=$,exports.updateBoneMatrixTexture=Cs,exports.validateArrayBuffer=ne,exports.validateAssetPath=function(e){if("string"!=typeof e||0===e.length)throw new S("Asset path must be a non-empty string","path");const t=["../","..\\","%2e%2e/","%2e%2e\\"],s=e.toLowerCase();for(const i of t)if(s.includes(i))throw new S(`Path traversal detected in asset path: ${e}`,"path");return e},exports.validateCallback=re,exports.validateDOMElement=oe,exports.validateEnum=function(e,t,s){if(!t.includes(e))throw new S(`${s} must be one of: ${t.join(", ")}. Got: ${e}`,s);return e},exports.validateFileExtension=function(e,t){if("string"!=typeof e||0===e.length)throw new S("Filename must be a non-empty string","filename");if(!Array.isArray(t)||0===t.length)throw new S("allowedExtensions must be a non-empty array","allowedExtensions");const s=e.slice(e.lastIndexOf(".")).toLowerCase();if(!t.map(e=>e.toLowerCase()).includes(s))throw new S(`File extension ${s} not allowed. Allowed: ${t.join(", ")}`,"filename");return e},exports.validateHexColor=ae,exports.validateInteger=se,exports.validateNumberInRange=function(e,t,s,i){if("number"!=typeof e||isNaN(e))throw new S(`${i} must be a valid number`,i);if(e<t||e>s)throw new S(`${i} must be between ${t} and ${s}, got ${e}`,i);return e},exports.validatePositiveInteger=function(e,t){if(se(e,t),e<=0)throw new S(`${t} must be positive, got ${e}`,t);return e},exports.validateRequiredProperties=ie,exports.validateUrl=te,exports.vector3Pool=ce;
|
|
2
|
+
//# sourceMappingURL=gsplat-flame-avatar-renderer.cjs.min.js.map
|