@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
|
+
import*as e from"three";import{DataUtils as t,Vector3 as s,Matrix4 as i,Quaternion as n,Euler as r,LoopOnce as a,LoopRepeat as o,Object3D as l,BufferGeometry as c,BufferAttribute as h,InstancedBufferGeometry as d,InstancedBufferAttribute as u,DynamicDrawUsage as p,Vector2 as m,Color as g,ShaderMaterial as A,DoubleSide as f,NormalBlending as S,MeshBasicMaterial as C,Mesh as y,Box3 as x,Vector4 as v,DataTexture as I,RGBAIntegerFormat as b,UnsignedIntType as w,RGBAFormat as B,FloatType as T,RGFormat as D,UnsignedByteType as E,HalfFloatType as M,RedIntegerFormat as R,RedFormat as F,RGIntegerFormat as P,RGBIntegerFormat as k,Matrix3 as _,Scene as L,PerspectiveCamera as U,OrthographicCamera as H,MathUtils as O,WebGLRenderer as z,Clock as Q,Bone as N,AnimationMixer as V,Skeleton as G}from"three";import{GLTFLoader as W}from"three/examples/jsm/loaders/GLTFLoader.js";import q from"jszip";import{OrbitControls as K}from"three/examples/jsm/controls/OrbitControls.js";const j={None:0,Error:1,Warning:2,Info:3,Debug:4},Y={Always:0,OnChange:1,Never:2},J={Ply:0},X=e=>e.endsWith(".ply")?J.Ply:null,$={Default:0,Gradual:1,Instant:2},Z={ThreeD:0,TwoD:1};let ee=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 te=ee.SphericalHarmonics8BitCompressionRange,se=6,ie=4,ne=4,re=4,ae=6,oe=8,le=4,ce=4,he=1,de=.012,ue=.003,pe=50,me=.5,ge=60,Ae=15e5,fe=.4,Se=.12,Ce={DirectToSplatBuffer:0,DirectToSplatArray:1,DownloadBeforeProcessing:2},ye={Downloading:0,Processing:1,Done:2};class xe{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)}}class ve 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 Ie extends ve{constructor(e,t,s=null){super(e,"VALIDATION_ERROR",s),this.field=t}}class be extends ve{constructor(e,t=0,s=null){super(e,"NETWORK_ERROR",s),this.statusCode=t}}class we extends ve{constructor(e,t,s=null){super(e,"ASSET_LOAD_ERROR",s),this.assetPath=t}}class Be extends ve{constructor(e){super(`Cannot use ${e}: resource has been disposed`,"RESOURCE_DISPOSED_ERROR"),this.resourceName=e}}class Te extends ve{constructor(e,t,s=null){super(e,"INITIALIZATION_ERROR",s),this.component=t}}let De=class extends ve{constructor(e,t,s=null){super(e,"PARSE_ERROR",s),this.dataType=t}};const Ee=Object.freeze({DEBUG:0,INFO:1,WARN:2,ERROR:3,NONE:4});class Me{constructor(e,t=Ee.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<=Ee.DEBUG&&this._format("DEBUG",e)}info(...e){this.minLevel<=Ee.INFO&&console.info(...this._format("INFO",e))}warn(...e){this.minLevel<=Ee.WARN&&console.warn(...this._format("WARN",e))}error(...e){this.minLevel<=Ee.ERROR&&console.error(...this._format("ERROR",e))}errorWithTrace(e,t=""){if(this.minLevel<=Ee.ERROR){const s=t?` Context: ${t}`:"";console.error(...this._format("ERROR",[`${e.message}${s}`,"\nStack:",e.stack]))}}child(e){return new Me(`${this.namespace}:${e}`,this.minLevel)}}const Re=new Map;let Fe=Ee.INFO;function Pe(e){Fe=e;for(const t of Re.values())t.setLevel(e)}function ke(e){return Re.has(e)||Re.set(e,new Me(e,Fe)),Re.get(e)}function _e(){Pe(Ee.NONE)}function Le(){Pe(Ee.DEBUG)}ke("App");const Ue=ke("Util");class He extends Error{constructor(e){super(e),this.name="AbortedPromiseError",this.code="ABORTED"}}const Oe=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){Ue.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 be(`Fetch failed: ${e.statusText}${t?" - "+t:""}`,e.status))}const i=e.body?.getReader();if(!i)return void n(new be("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 be(`Error reading response stream: ${e.message}`,0,e))}}).catch(e=>{e instanceof be?n(e):"AbortError"===e.name?n(new be("Fetch aborted by user",0,e)):n(new be(`Fetch failed: ${e.message||"Unknown error"}`,0,e))})});return c.abort=e=>{a=!0,n.abort(e)},c.abortController=n,c},ze=function(e,t,s){return Math.max(Math.min(e,s),t)},Qe=function(){return performance.now()/1e3},Ne=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)Ne(t)},Ve=(e,t)=>new Promise(s=>{window.setTimeout(()=>{s(e())},t?1:50)}),Ge=(e=0)=>{switch(e){case 1:return 9;case 2:return 24}return 0},We=()=>{let e,t;return{promise:new Promise((s,i)=>{e=s,t=i}),resolve:e,reject:t}},qe=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 Ke{constructor(e,t,s){this.major=e,this.minor=t,this.patch=s}toString(){return`${this.major}_${this.minor}_${this.patch}`}}function je(){const e=navigator.userAgent;return e.indexOf("iPhone")>0||e.indexOf("iPad")>0}function Ye(){if(je()){const e=navigator.userAgent.match(/OS (\d+)_(\d+)_?(\d+)?/);return new Ke(parseInt(e[1]||0,10),parseInt(e[2]||0,10),parseInt(e[3]||0,10))}return null}const Je=t.toHalfFloat.bind(t),Xe=t.fromHalfFloat.bind(t),$e=te/2,Ze=(e,s,i=!1,n,r)=>0===s?e:1===s||2===s&&!i?t.fromHalfFloat(e):2===s?tt(e,n,r):void 0,et=(e,t,s)=>{e=ze(e,t,s);const i=s-t;return ze(Math.floor((e-t)/i*255),0,255)},tt=(e,t,s)=>e/255*(s-t)+t,st=(e,t,s)=>et(Xe(e),t,s),it=(e,t,s)=>Je(tt(e,t,s)),nt=(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),rt=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=it:0===i&&(r=tt):2===s||1===s?0===i?r=Xe:2===i&&(r=n?st:e):0===s&&(1===i?r=Je:2===i&&(r=n?et:Je)),r(t)}}(),at=(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]},ot=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)}}(),lt=function(){const e=new Float32Array(1),t=new Int32Array(e.buffer);return function(s){return e[0]=s,t[0]}}(),ct=function(e,t,s,i){return e+(t<<8)+(s<<16)+(i<<24)},ht=function(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24)},dt=14,ut=Object.freeze(["https:","http:","blob:","data:"]);function pt(e,t){if("string"!=typeof e||0===e.length)throw new Ie("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 Ie(`Invalid URL format: ${e}`,"url",t)}if(!ut.includes(s.protocol))throw new Ie(`Disallowed protocol: ${s.protocol}. Allowed protocols: ${ut.join(", ")}`,"url.protocol");return s.href}function mt(e){if("string"!=typeof e||0===e.length)throw new Ie("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 Ie(`Path traversal detected in asset path: ${e}`,"path");return e}function gt(e,t){if("string"!=typeof e||0===e.length)throw new Ie("Filename must be a non-empty string","filename");if(!Array.isArray(t)||0===t.length)throw new Ie("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 Ie(`File extension ${s} not allowed. Allowed: ${t.join(", ")}`,"filename");return e}function At(e,t,s,i){if("number"!=typeof e||isNaN(e))throw new Ie(`${i} must be a valid number`,i);if(e<t||e>s)throw new Ie(`${i} must be between ${t} and ${s}, got ${e}`,i);return e}function ft(e,t){if("number"!=typeof e||!Number.isInteger(e))throw new Ie(`${t} must be an integer`,t);return e}function St(e,t){if(ft(e,t),e<=0)throw new Ie(`${t} must be positive, got ${e}`,t);return e}function Ct(e,t,s){if(null===e||"object"!=typeof e)throw new Ie(`${s} must be an object`,s);for(const i of t)if(!(i in e)||void 0===e[i])throw new Ie(`${s} missing required property: ${i}`,`${s}.${i}`);return e}function yt(e,t,s=0){if(!(e instanceof ArrayBuffer))throw new Ie(`${t} must be an ArrayBuffer`,t);if(e.byteLength<s)throw new Ie(`${t} must be at least ${s} bytes, got ${e.byteLength}`,t);return e}function xt(e,t,s){if(!t.includes(e))throw new Ie(`${s} must be one of: ${t.join(", ")}. Got: ${e}`,s);return e}function vt(e,t,s=!0){if(null==e){if(s)throw new Ie(`${t} is required`,t);return null}if("function"!=typeof e)throw new Ie(`${t} must be a function`,t);return e}function It(e,t){if("string"!=typeof e)throw new Ie(`${t} must be a string`,t);if(!/^(#|0x)[0-9A-Fa-f]{6}$/i.test(e))throw new Ie(`${t} must be a valid hex color (e.g., #FFFFFF or 0xFFFFFF)`,t);return e}function bt(e,t){if("undefined"!=typeof HTMLElement&&!(e instanceof HTMLElement))throw new Ie(`${t} must be a valid HTML element`,t);return e}class wt{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 Bt=new wt(()=>new s,e=>e.set(0,0,0),50),Tt=new wt(()=>new i,e=>e.identity(),20),Dt=new wt(()=>new n,e=>e.set(0,0,0,1),30),Et=new wt(()=>new r,e=>e.set(0,0,0),30);class Mt{constructor(){this._allocated=[]}vector3(){const e=Bt.acquire();return this._allocated.push({pool:Bt,obj:e}),e}matrix4(){const e=Tt.acquire();return this._allocated.push({pool:Tt,obj:e}),e}quaternion(){const e=Dt.acquire();return this._allocated.push({pool:Dt,obj:e}),e}euler(){const e=Et.acquire();return this._allocated.push({pool:Et,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}}const Rt=new s,Ft=new s,Pt=new s,kt=new i,_t=new i,Lt=new n,Ut=new n;function Ht(){return{vector3:Bt.getStats(),matrix4:Tt.getStats(),quaternion:Dt.getStats(),euler:Et.getStats()}}function Ot(){Bt.dispose(),Tt.dispose(),Dt.dispose(),Et.dispose()}const zt=ke("BlobUrlManager");class Qt{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 Ie("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 Ie("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}),zt.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 Ie("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}),zt.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),zt.debug(`Revoked blob URL: ${t.label}, age: ${Date.now()-t.createdAt}ms`),!0}return!1}revokeAll(){this._assertNotDisposed(),zt.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&&zt.info(`Revoked ${s.length} blob URLs older than ${e}ms`),s.length}isTracked(e){return this._urls.has(e)}dispose(){this._disposed||(zt.debug("Disposing BlobUrlManager"),this.revokeAll(),this._disposed=!0)}}const Nt=new Qt;function Vt(){return Nt}function Gt(e,t,s){return Nt.createBlobUrl(e,t,s)}function Wt(e){return Nt.revokeBlobUrl(e)}const qt=ke("RenderLoop");class Kt{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?qt.warn("RenderLoop already running"):(this._running=!0,this._lastTime=performance.now(),this._frameCount=0,qt.info("RenderLoop started"),this._tick())}stop(){this._running&&(this._running=!1,null!==this._rafId&&(cancelAnimationFrame(this._rafId),this._rafId=null),qt.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){qt.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){qt.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,qt.debug("Cleared all deferred tasks")}}class jt{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}),qt.warn(`Frame budget violation at ${e}: ${t.toFixed(2)}ms / ${this._frameBudget.toFixed(2)}ms`)),s}getViolationCount(){return this._violations}resetViolations(){this._violations=0}}const Yt=ke("EventEmitter");class Jt{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 Ie("event must be a non-empty string","event");if("function"!=typeof t)throw new Ie("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),Yt.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 Yt.debug(`Unsubscribed from event: ${e}`),!0;for(const i of s)if(i._originalCallback===t)return s.delete(i),Yt.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),Yt.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(),Yt.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){Yt.error(`Error in event listener for '${e}':`,t)}return Yt.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||(Yt.debug("Disposing EventEmitter"),this.removeAllListeners(),this._eventHistory.length=0,this._disposed=!0)}}class Xt extends Jt{constructor(e){super(),this._allowedEvents=new Set(e)}_validateEvent(e){if(!this._allowedEvents.has(e))throw new Ie(`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)}}const $t={Idle:"Idle",Listening:"Listening",Responding:"Responding",Thinking:"Thinking"},Zt=["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"],es=["root","neck","jaw","leftEye","rightEye"],ts=Zt.length,ss=es.length,is=ke("AnimationManager");class ns{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 rs extends ns{constructor(e,t){super(e,t)}update(e){if(this.actions&&0!==this.actions.length&&(void 0===hs.CurPlaying&&e===$t.Idle&&!1===this.isPlaying&&(this.stage=0,this.actions[this.stage].time=0,hs.SetWeight(this.actions[this.stage],1),this.actions[this.stage].loop=o,this.actions[this.stage].clampWhenFinished=!1,this.actions[this.stage].paused=!1,this.actions[this.stage].play(),void 0!==hs.LastAction&&hs.PrepareCrossFade(hs.LastAction,this.actions[this.stage],this.blendingTime),this.isPlaying=!0),hs.CurPlaying===$t.Idle&&e===$t.Idle&&!0===this.isPlaying&&this.actions[this.stage].time>this.actions[this.stage].getClip().duration-this.blendingTime)){let e=this.stage+1;e>=this.actions.length&&(e=0),this.actions[e].time=0,hs.SetWeight(this.actions[e],1),this.actions[e].loop=o,this.actions[e].play(),hs.PrepareCrossFade(this.actions[this.stage],this.actions[e],this.blendingTime),this.stage=e}}}class as extends ns{constructor(e,t){super(e,t)}update(e){this.actions&&0!==this.actions.length&&(void 0===hs.CurPlaying&&e===$t.Idle&&!1===this.isPlaying&&(this.stage=0,this.actions[this.stage].time=0,hs.SetWeight(this.actions[this.stage],1),this.actions[this.stage].loop=o,this.actions[this.stage].clampWhenFinished=!1,this.actions[this.stage].paused=!1,this.actions[this.stage].play(),void 0!==hs.LastAction&&hs.PrepareCrossFade(hs.LastAction,this.actions[this.stage],this.blendingTime),this.isPlaying=!0),hs.CurPlaying===$t.Idle&&e!==$t.Idle&&!0===this.isPlaying&&0===this.stage&&(this.actions[this.stage].loop=a,this.actions[this.stage].clampWhenFinished=!0,this.isPlaying=!1,hs.LastAction=this.actions[this.stage]))}}class os extends ns{constructor(e,t){super(e,t)}update(e){this.actions&&0!==this.actions.length&&(void 0===hs.CurPlaying&&e===$t.Listening&&!1===this.isPlaying&&(this.stage=0,this.actions[this.stage].time=0,this.actions[this.stage].play(),hs.SetWeight(this.actions[this.stage],1),this.actions[this.stage].loop=this.isGroup?a:o,this.actions[this.stage].clampWhenFinished=!!this.isGroup,void 0!==hs.LastAction&&hs.PrepareCrossFade(hs.LastAction,this.actions[this.stage],this.blendingTime),this.isPlaying=!0),this.isGroup&&(hs.CurPlaying===$t.Listening&&e===$t.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,hs.SetWeight(this.actions[this.stage+1],1),this.actions[this.stage+1].loop=o,this.actions[this.stage+1].play(),hs.PrepareCrossFade(this.actions[this.stage],this.actions[this.stage+1],this.blendingTime),this.stage=1),hs.CurPlaying!==$t.Listening||e===$t.Listening||!0!==this.isPlaying||0!==this.stage&&1!==this.stage||(this.actions[2].time=0,this.actions[2].play(),hs.SetWeight(this.actions[2],1),this.actions[2].loop=a,hs.PrepareCrossFade(this.actions[this.stage],this.actions[2],this.blendingTime),this.stage=2)),hs.CurPlaying===$t.Listening&&e!==$t.Listening&&!0===this.isPlaying&&this.stage===(this.isGroup?this.actions.length-1:0)&&(this.actions[this.stage].loop=a,this.actions[this.stage].clampWhenFinished=!0,this.isPlaying=!1,hs.LastAction=this.actions[this.stage]))}}class ls extends ns{constructor(e,t){super(e,t)}update(e){this.actions&&0!==this.actions.length&&(void 0===hs.CurPlaying&&e===$t.Thinking&&!1===this.isPlaying&&(this.stage=0,this.actions[this.stage].time=0,this.actions[this.stage].play(),hs.SetWeight(this.actions[this.stage],1),this.actions[this.stage].loop=a,void 0!==hs.LastAction&&hs.PrepareCrossFade(hs.LastAction,this.actions[this.stage],this.blendingTime),this.isPlaying=!0),this.isGroup&&(hs.CurPlaying===$t.Thinking&&e===$t.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,hs.SetWeight(this.actions[this.stage+1],1),this.actions[this.stage+1].loop=o,this.actions[this.stage+1].play(),hs.PrepareCrossFade(this.actions[this.stage],this.actions[this.stage+1],this.blendingTime),this.stage=1),hs.CurPlaying!==$t.Thinking||e===$t.Thinking||!0!==this.isPlaying||0!==this.stage&&1!==this.stage||(this.actions[2].time=0,this.actions[2].play(),hs.SetWeight(this.actions[2],1),this.actions[2].loop=a,hs.PrepareCrossFade(this.actions[this.stage],this.actions[2],this.blendingTime),this.stage=2)),hs.CurPlaying===$t.Thinking&&e!==$t.Thinking&&!0===this.isPlaying&&this.stage===(this.isGroup?this.actions.length-1:0)&&(this.actions[this.stage].loop=a,this.actions[this.stage].clampWhenFinished=!0,this.isPlaying=!1,hs.LastAction=this.actions[this.stage]))}}class cs extends ns{constructor(e,t){super(e,t),is.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(e){if(this.actions&&0!==this.actions.length){if(void 0===hs.CurPlaying&&e===$t.Responding&&!1===this.isPlaying&&(this.stage=Math.ceil(this.getRandomNumber(0,this.actions.length-1)),is.debug("[SPEAK] Starting animation, stage:",this.stage,"of",this.actions.length),this.actions[this.stage].time=0,this.actions[this.stage].play(),hs.SetWeight(this.actions[this.stage],1),this.actions[this.stage].loop=a,this.actions[this.stage].clampWhenFinished=!0,void 0!==hs.LastAction&&hs.PrepareCrossFade(hs.LastAction,this.actions[this.stage],this.blendingTime),this.isPlaying=!0),hs.CurPlaying===$t.Responding&&e===$t.Responding&&!0===this.isPlaying&&this.actions[this.stage].time>=this.actions[this.stage].getClip().duration-this.blendingTime){const e=this.actions[this.stage];this.stage=(this.stage+Math.ceil(this.getRandomNumber(1,this.actions.length-1)))%this.actions.length,is.debug("[SPEAK] Cycling to next animation, stage:",this.stage),this.actions[this.stage].time=0,this.actions[this.stage].play(),hs.SetWeight(this.actions[this.stage],1),this.actions[this.stage].loop=a,this.actions[this.stage].clampWhenFinished=!0,hs.PrepareCrossFade(e,this.actions[this.stage],this.blendingTime)}hs.CurPlaying===$t.Responding&&e!==$t.Responding&&!0===this.isPlaying&&(this.actions[this.stage].loop=a,this.actions[this.stage].clampWhenFinished=!0,this.isPlaying=!1,hs.LastAction=this.actions[this.stage])}else this._warnedNoActions||(is.warn("[SPEAK] No actions available!"),this._warnedNoActions=!0)}}class hs{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;hs.UnPauseAllActions(),hs.ExecuteCrossFade(e,t,i),hs.IsBlending=!0,setTimeout(()=>{hs.IsBlending=!1},s+.1)}static PauseAllActions(){hs.actions.forEach(function(e){e.paused=!0})}static UnPauseAllActions(){hs.actions.forEach(function(e){e.paused=!1})}static ExecuteCrossFade(e,t,s){hs.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),hs.actions.push(m),hs.SetWeight(m,0)}this.hello=new rs(i,s?.hello?.isGroup||!1),this.idle=new as(n,s?.idle?.isGroup||!1),this.listen=new os(r,s?.listen?.isGroup||!1),this.think=new ls(o,s?.think?.isGroup||!1),this.speak=new cs(a,s?.speak?.isGroup||!1)}curPlaying(){return this.hello.isPlaying||this.idle.isPlaying?$t.Idle:this.listen.isPlaying?$t.Listening:this.think.isPlaying?$t.Thinking:this.speak.isPlaying?$t.Responding:void 0}dispose(){this.hello.dispose(),this.idle.dispose(),this.listen.dispose(),this.think.dispose(),this.speak.dispose(),hs.actions=[]}resetAllActions(e=!1){switch(this.curPlaying()){case $t.Idle:hs.LastAction=this.hello.actions[this.hello.stage];break;case $t.Listening:hs.LastAction=this.listen.actions[this.listen.stage];break;case $t.Thinking:hs.LastAction=this.think.actions[this.think.stage];break;case $t.Responding:hs.LastAction=this.speak.actions[this.speak.stage];break;default:hs.LastAction=void 0}hs.LastAction&&(hs.LastAction.loop=a,hs.LastAction.clampWhenFinished=!0,hs.SetWeight(hs.LastAction,1)),e&&(hs.PauseAllActions(),hs.actions.forEach(function(e){e.time=0,hs.SetWeight(e,0)}),hs.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(!hs.IsBlending)if(hs.CurPlaying=this.curPlaying(),void 0===hs.CurPlaying)switch(e){case $t.Idle:this.idle.update(e);break;case $t.Listening:this.listen.update(e);break;case $t.Thinking:this.think.update(e);break;case $t.Responding:this.speak.update(e);break;default:this.idle.update(e)}else switch(hs.CurPlaying){case $t.Idle:this.idle.update(e);break;case $t.Listening:this.listen.update(e);break;case $t.Thinking:this.think.update(e);break;case $t.Responding:this.speak.update(e);break;default:this.idle.update(e)}}}class ds extends l{constructor(e,t=new s,r=new n,a=new s(1,1,1),o=1,l=1,c=!0){super(),this.splatBuffer=e,this.position.copy(t),this.quaternion.copy(r),this.scale.copy(a),this.transform=new i,this.minimumAlpha=o,this.opacity=l,this.visible=c}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 us{static build(e){const t=new c;t.setIndex([0,1,2,0,2,3]);const s=new Float32Array(12),i=new h(s,3);t.setAttribute("position",i),i.setXYZ(0,-1,-1,0),i.setXYZ(1,-1,1,0),i.setXYZ(2,1,1,0),i.setXYZ(3,1,-1,0),i.needsUpdate=!0;const n=(new d).copy(t),r=new Uint32Array(e),a=new u(r,1,!1);return a.setUsage(p),n.setAttribute("splatIndex",a),n.instanceCount=0,n}}class ps{constructor(){this.rootNode=null,this.splatMesh=null}static convertWorkerSubTree(e,t){const s=new ps;return s.rootNode=e.rootNode,s.splatMesh=t,s}}class ms{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=(e,t=()=>!0,i,n)=>{this.splatTreeWorker||(this.splatTreeWorker=null),this.splatMesh=e,this.subTrees=[];const r=new s,a=(s,i)=>{const n=new Float32Array(4*i);let a=0;for(let o=0;o<i;o++){const i=o+s;if(t(i)){e.getSplatCenter(i,r);const t=4*a;n[t]=r.x,n[t+1]=r.y,n[t+2]=r.z,n[t+3]=i,a++}}return n};return new Promise(t=>{const s=()=>!!this.disposed&&(this.diposeSplatTreeWorker(),t(),!0);i&&i(!1),Ve(()=>{if(s())return;const r=[];if(e.dynamicMode){let t=0;for(let s=0;s<e.scenes.length;s++){const i=e.getScene(s).splatBuffer.getSplatCount(),n=a(t,i);r.push(n),t+=i}}else{const t=a(0,e.getSplatCount());r.push(t)}this.splatTreeWorker.onmessage=i=>{s()||i.data.subTrees&&(n&&n(!1),Ve(()=>{if(!s()){for(let t of i.data.subTrees){const s=ps.convertWorkerSubTree(t,e);this.subTrees.push(s)}this.diposeSplatTreeWorker(),n&&n(!0),Ve(()=>{t()})}}))},Ve(()=>{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 gs{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[${ee.MaxScenes}];\n uniform int sceneVisibility[${ee.MaxScenes}];\n `),e&&(n+=`\n uniform highp mat4 transforms[${ee.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[${ee.MaxScenes}];\n uniform float sphericalHarmonics8BitCompressionRangeMax[${ee.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(e=!1,t=!1,n=0,r=1,a=!1){const o={sceneCenter:{type:"v3",value:new s},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 i},bindMatrixInverse:{type:"m4",value:new i},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 m},orthoZoom:{type:"f",value:1},inverseFocalAdjustment:{type:"f",value:1},viewport:{type:"v2",value:new m},basisViewport:{type:"v2",value:new m},debugColor:{type:"v3",value:new g},centersColorsTextureSize:{type:"v2",value:new m(1024,1024)},flameModelTextureSize:{type:"v2",value:new m(4096,2048)},boneTextureSize:{type:"v2",value:new m(4,32)},boneWeightTextureSize:{type:"v2",value:new m(512,512)},sphericalHarmonicsDegree:{type:"i",value:n},sphericalHarmonicsTextureSize:{type:"v2",value:new m(1024,1024)},sphericalHarmonics8BitMode:{type:"i",value:0},sphericalHarmonicsMultiTextureMode:{type:"i",value:0},splatScale:{type:"f",value:r},pointCloudModeEnabled:{type:"i",value:a?1:0},sceneIndexesTexture:{type:"t",value:null},sceneIndexesTextureSize:{type:"v2",value:new m(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<ee.MaxScenes;e++)o.sphericalHarmonics8BitCompressionRangeMin.value.push(-ee.SphericalHarmonics8BitCompressionRange/2),o.sphericalHarmonics8BitCompressionRangeMax.value.push(ee.SphericalHarmonics8BitCompressionRange/2);if(t){const e=[];for(let t=0;t<ee.MaxScenes;t++)e.push(1);o.sceneOpacity={type:"f",value:e};const t=[];for(let e=0;e<ee.MaxScenes;e++)t.push(1);o.sceneVisibility={type:"i",value:t}}if(e){const e=[];for(let t=0;t<ee.MaxScenes;t++)e.push(new i);o.transforms={type:"mat4",value:e}}return o}}class As{static build(e=!1,t=!1,s=!1,i=2048,n=1,r=!1,a=0,o=.3,l=null){let c=gs.buildVertexShaderBase(e,t,a,"\n uniform vec2 covariancesTextureSize;\n uniform highp sampler2D covariancesTexture;\n uniform highp usampler2D covariancesTextureHalfFloat;\n uniform int covariancesAreHalfFloat;\n\n void fromCovarianceHalfFloatV4(uvec4 val, out vec4 first, out vec4 second) {\n vec2 r = unpackHalf2x16(val.r);\n vec2 g = unpackHalf2x16(val.g);\n vec2 b = unpackHalf2x16(val.b);\n\n first = vec4(r.x, r.y, g.x, g.y);\n second = vec4(b.x, b.y, 0.0, 0.0);\n }\n ");c+=As.buildVertexShaderProjection(s,t,i,o);const h=As.buildFragmentShader(l),d=gs.getUniforms(e,t,a,n,r);return d.covariancesTextureSize={type:"v2",value:new m(1024,1024)},d.covariancesTexture={type:"t",value:null},d.covariancesTextureHalfFloat={type:"t",value:null},d.covariancesAreHalfFloat={type:"i",value:0},new A({uniforms:d,vertexShader:c,fragmentShader:h,transparent:!0,alphaTest:1,blending:S,depthTest:!0,depthWrite:!1,side:f})}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+=gs.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 fs{static build(e=!1,t=!1,s=1,i=!1,n=0){let r=gs.buildVertexShaderBase(e,t,n,"\n uniform vec2 scaleRotationsTextureSize;\n uniform highp sampler2D scaleRotationsTexture;\n varying mat3 vT;\n varying vec2 vQuadCenter;\n varying vec2 vFragCoord;\n ");r+=fs.buildVertexShaderProjection();const a=fs.buildFragmentShader(),o=gs.getUniforms(e,t,n,s,i);return o.scaleRotationsTexture={type:"t",value:null},o.scaleRotationsTextureSize={type:"v2",value:new m(1024,1024)},new A({uniforms:o,vertexShader:r,fragmentShader:a,transparent:!0,alphaTest:1,blending:S,depthTest:!0,depthWrite:!1,side:f})}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+=gs.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 Ss=ke("SplatMesh"),Cs=new c,ys=new C;function xs(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&&Ss.warn("THREE.WebGLRenderer: "+e+" extension not supported."),t}}}function vs(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&&(Ss.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 Is(e,t,s){const i=s.isWebGL2;return{convert:function(s,n){let r;if(s===E)return e.UNSIGNED_BYTE;if(1017===s)return e.UNSIGNED_SHORT_4_4_4_4;if(1018===s)return e.UNSIGNED_SHORT_5_5_5_1;if(1010===s)return e.BYTE;if(1011===s)return e.SHORT;if(1012===s)return e.UNSIGNED_SHORT;if(1013===s)return e.INT;if(1014===s)return e.UNSIGNED_INT;if(s===T)return e.FLOAT;if(s===M)return i?e.HALF_FLOAT:(r=t.get("OES_texture_half_float"),null!==r?r.HALF_FLOAT_OES:null);if(1021===s)return e.ALPHA;if(1022===s)return e.RGB;if(s===B)return e.RGBA;if(1024===s)return e.LUMINANCE;if(1025===s)return e.LUMINANCE_ALPHA;if(1026===s)return e.DEPTH_COMPONENT;if(1027===s)return e.DEPTH_STENCIL;if(s===F)return e.RED;if(s===R)return e.RED_INTEGER;if(s===D)return e.RG;if(s===P)return e.RG_INTEGER;if(s===k)return e.RGB_INTEGER;if(s===b)return e.RGBA_INTEGER;if(33776===s||33777===s||33778===s||33779===s){if(r=t.get("WEBGL_compressed_texture_s3tc"),null===r)return null;if(33776===s)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(33777===s)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(33778===s)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(33779===s)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(35840===s||35841===s||35842===s||35843===s){if(r=t.get("WEBGL_compressed_texture_pvrtc"),null===r)return null;if(35840===s)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(35841===s)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(35842===s)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(35843===s)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(36196===s)return r=t.get("WEBGL_compressed_texture_etc1"),null!==r?r.COMPRESSED_RGB_ETC1_WEBGL:null;if(s>=37808&&s<=37814||s>=37840&&s<=37846)return r=t.get("WEBGL_compressed_texture_astc"),null!==r?s:null;if(36492===s||36494===s||36495===s)return r=t.get("EXT_texture_compression_bptc"),null!==r?s:null;if(34042===s)return e.UNSIGNED_INT_24_8;if(i){if(6407===s)return e.RGB;if(6408===s)return e.RGBA}return void 0!==e[s]?e[s]:null}}}const bs=16777216;class ws extends y{constructor(e=Z.ThreeD,t=!1,i=!1,n=!1,r=1,a=!0,o=!1,l=!1,c=1024,h=j.None,d=0,u=1,p=.3){super(Cs,ys),this.renderer=void 0,this.splatRenderMode=e,this.dynamicMode=t,this.enableOptionalEffects=i,this.halfPrecisionCovariancesOnGPU=n,this.devicePixelRatio=r,this.enableDistancesComputationOnGPU=a,this.integerBasedDistancesComputation=o,this.antialiased=l,this.kernel2DSize=p,this.maxScreenSpaceSplatSize=c,this.logLevel=h,this.sphericalHarmonicsDegree=d,this.minSphericalHarmonicsDegree=0,this.sceneFadeInRateMultiplier=u,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 x,this.calculatedSceneCenter=new s,this.maxSplatDistanceFromSceneCenter=0,this.visibleRegionBufferRadius=0,this.visibleRegionRadius=0,this.visibleRegionFadeStartRadius=0,this.visibleRegionChanging=!1,this.splatScale=1,this.pointCloudModeEnabled=!1,this.disposed=!1,this.lastRenderer=null,this.visible=!1}static buildScenes(e,t,i){const r=[];r.length=t.length;for(let a=0;a<t.length;a++){const o=t[a],l=i[a]||{};let c=l.position||[0,0,0],h=l.rotation||[0,0,0,1],d=l.scale||[1,1,1];const u=(new s).fromArray(c),p=(new n).fromArray(h),m=(new s).fromArray(d),g=ws.createScene(o,u,p,m,l.splatAlphaRemovalThreshold||1,l.opacity,l.visible);e.add(g),r[a]=g}return r}static createScene(e,t,s,i,n,r=1,a=!0){return new ds(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=(e=[],t,s)=>new Promise(i=>{this.disposeSplatTree(),this.baseSplatTree=new ms(8,1e3);const n=performance.now(),r=new v;this.baseSplatTree.processSplatMesh(this,t=>{this.getSplatColor(t,r);const s=this.getSceneIndexForSplat(t),i=e[s]||1;return r.w>=i},t,s).then(()=>{const e=performance.now()-n;if(this.logLevel>=j.Info&&Ss.info("SplatTree build: "+e+" ms"),this.disposed)i();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>=j.Info&&(Ss.info(`SplatTree leaves: ${this.splatTree.countLeaves()}`),Ss.info(`SplatTree leaves with splats:${e}`),t/=s,Ss.info(`Avg splat count per node: ${t}`),Ss.info(`Total splat count: ${this.getSplatCount()}`)),i()}})});build(e,t,s=!0,i=!1,n,r,a=!0){this.sceneOptions=t,this.finalBuild=i;const o=ws.getTotalMaxSplatCountForSplatBuffers(e),l=ws.buildScenes(this,e,t);if(s)for(let e=0;e<this.scenes.length&&e<l.length;e++){const t=l[e],s=this.getScene(e);t.copyTransformData(s)}this.scenes=l;let c=3;for(let t of e){const e=t.getMinSphericalHarmonicsDegree();e<c&&(c=e)}this.minSphericalHarmonicsDegree=Math.min(c,this.sphericalHarmonicsDegree);let h=!1;if(e.length!==this.lastBuildScenes.length)h=!0;else for(let t=0;t<e.length;t++)if(e[t]!==this.lastBuildScenes[t].splatBuffer){h=!0;break}let d=!0;if((1!==this.scenes.length||this.lastBuildSceneCount!==this.scenes.length||this.lastBuildMaxSplatCount!==o||h)&&(d=!1),!d){this.boundingBox=new x,a||(this.maxSplatDistanceFromSceneCenter=0,this.visibleRegionBufferRadius=0,this.visibleRegionRadius=0,this.visibleRegionFadeStartRadius=0,this.firstRenderTime=-1),this.lastBuildScenes=[],this.lastBuildSplatCount=0,this.lastBuildMaxSplatCount=0,this.disposeMeshData(),this.geometry=us.build(o),this.splatRenderMode===Z.ThreeD?this.material=As.build(this.dynamicMode,this.enableOptionalEffects,this.antialiased,this.maxScreenSpaceSplatSize,this.splatScale,this.pointCloudModeEnabled,this.minSphericalHarmonicsDegree,this.kernel2DSize,this.irisOcclusionConfig):this.material=fs.build(this.dynamicMode,this.enableOptionalEffects,this.splatScale,this.pointCloudModeEnabled,this.minSphericalHarmonicsDegree);const t=ws.buildSplatIndexMaps(e);this.globalSplatIndexToLocalSplatIndexMap=t.localSplatIndexMap,this.globalSplatIndexToSceneIndexMap=t.sceneIndexMap}const u=this.getSplatCount(!0);this.enableDistancesComputationOnGPU&&this.setupDistancesComputationTransformFeedback();const p=this.refreshGPUDataFromSplatBuffers(d);for(let e=0;e<this.scenes.length;e++)this.lastBuildScenes[e]=this.scenes[e];return this.lastBuildSplatCount=u,this.lastBuildMaxSplatCount=this.getMaxSplatCount(),this.lastBuildSceneCount=this.scenes.length,this.visible=this.scenes.length>0,p}freeIntermediateSplatData(){const e=e=>{delete e.source.data,delete e.image,e.onUpdate=null};delete this.splatDataTextures.baseData.covariances,delete this.splatDataTextures.baseData.centers,delete this.splatDataTextures.baseData.colors,delete this.splatDataTextures.baseData.sphericalHarmonics,delete this.splatDataTextures.centerColors.data,delete this.splatDataTextures.covariances.data,this.splatDataTextures.sphericalHarmonics&&delete this.splatDataTextures.sphericalHarmonics.data,this.splatDataTextures.sceneIndexes&&delete this.splatDataTextures.sceneIndexes.data,this.splatDataTextures.centerColors.texture.needsUpdate=!0,this.splatDataTextures.centerColors.texture.onUpdate=()=>{e(this.splatDataTextures.centerColors.texture)},this.splatDataTextures.flameModelPosTexture.texture.needsUpdate=!0,this.splatDataTextures.flameModelPosTexture.texture.onUpdate=()=>{e(this.splatDataTextures.flameModelPosTexture.texture)},this.splatDataTextures.covariances.texture.needsUpdate=!0,this.splatDataTextures.covariances.texture.onUpdate=()=>{e(this.splatDataTextures.covariances.texture)},this.splatDataTextures.sphericalHarmonics&&(this.splatDataTextures.sphericalHarmonics.texture?(this.splatDataTextures.sphericalHarmonics.texture.needsUpdate=!0,this.splatDataTextures.sphericalHarmonics.texture.onUpdate=()=>{e(this.splatDataTextures.sphericalHarmonics.texture)}):this.splatDataTextures.sphericalHarmonics.textures.forEach(t=>{t.needsUpdate=!0,t.onUpdate=()=>{e(t)}})),this.splatDataTextures.sceneIndexes&&(this.splatDataTextures.sceneIndexes.texture.needsUpdate=!0,this.splatDataTextures.sceneIndexes.texture.onUpdate=()=>{e(this.splatDataTextures.sceneIndexes.texture)})}dispose(){this.disposeMeshData(),this.disposeTextures(),this.disposeSplatTree(),this.enableDistancesComputationOnGPU&&(this.computeDistancesOnGPUSyncTimeout&&(clearTimeout(this.computeDistancesOnGPUSyncTimeout),this.computeDistancesOnGPUSyncTimeout=null),this.disposeDistancesComputationGPUResources()),this.scenes=[],this.distancesTransformFeedback={id:null,vertexShader:null,fragmentShader:null,program:null,centersBuffer:null,sceneIndexesBuffer:null,outDistancesBuffer:null,centersLoc:-1,modelViewProjLoc:-1,sceneIndexesLoc:-1,transformsLocs:[]},this.renderer=null,this.globalSplatIndexToLocalSplatIndexMap=[],this.globalSplatIndexToSceneIndexMap=[],this.lastBuildSplatCount=0,this.lastBuildScenes=[],this.lastBuildMaxSplatCount=0,this.lastBuildSceneCount=0,this.firstRenderTime=-1,this.finalBuild=!1,this.webGLUtils=null,this.boundingBox=new x,this.calculatedSceneCenter=new s,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!==Cs&&(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 e=this.getMaxSplatCount(),t=this.getSplatCount(!0);this.disposeTextures();const s=(t,s)=>{const i=new m(4096,1024);for(;i.x*i.y*t<e*s;)i.y*=2;return i},i=e=>{const t=(e=>e>=1?6:4)(e);return{elementsPerTexelStored:t,texSize:s(t,6)}};let n=this.getTargetCovarianceCompressionLevel();const r=this.getTargetSphericalHarmonicsCompressionLevel();let a,o,l;if(this.splatRenderMode===Z.ThreeD){const t=i(n);t.texSize.x*t.texSize.y>bs&&0===n&&(n=1),a=new Float32Array(6*e)}else o=new Float32Array(3*e),l=new Float32Array(4*e);const c=new Float32Array(3*e),h=new Uint8Array(4*e);let d=Float32Array;1===r?d=Uint16Array:2===r&&(d=Uint8Array);const u=Ge(this.minSphericalHarmonicsDegree),p=this.minSphericalHarmonicsDegree?new d(e*u):void 0,g=s(4,4),A=new Uint32Array(g.x*g.y*4);ws.updateCenterColorsPaddedData(0,t-1,c,h,A);const f=new I(A,g.x,g.y,b,w);if(f.internalFormat="RGBA32UI",f.needsUpdate=!0,this.material.uniforms.centersColorsTexture.value=f,this.material.uniforms.centersColorsTextureSize.value.copy(g),this.material.uniformsNeedUpdate=!0,this.splatDataTextures={baseData:{covariances:a,scales:o,rotations:l,centers:c,colors:h,sphericalHarmonics:p},centerColors:{data:A,texture:f,size:g}},this.splatRenderMode===Z.ThreeD){const e=i(n),t=e.elementsPerTexelStored,s=e.texSize,r=n>=1?8:4,o=new(n>=1?Uint32Array:Float32Array)(s.x*s.y*r);let l;if(0===n?o.set(a):ws.updatePaddedCompressedCovariancesTextureData(a,o,0,0,a.length),n>=1)l=new I(o,s.x,s.y,b,w),l.internalFormat="RGBA32UI",this.material.uniforms.covariancesTextureHalfFloat.value=l;else{l=new I(o,s.x,s.y,B,T),this.material.uniforms.covariancesTexture.value=l;const e=new I(new Uint32Array(32),2,2,b,w);e.internalFormat="RGBA32UI",this.material.uniforms.covariancesTextureHalfFloat.value=e,e.needsUpdate=!0}l.needsUpdate=!0,this.material.uniforms.covariancesAreHalfFloat.value=n>=1?1:0,this.material.uniforms.covariancesTextureSize.value.copy(s),this.splatDataTextures.covariances={data:o,texture:l,size:s,compressionLevel:n,elementsPerTexelStored:t,elementsPerTexelAllocated:r}}else{const e=s(4,6);let i=Float32Array,n=T;const r=new i(e.x*e.y*4);ws.updateScaleRotationsPaddedData(0,t-1,o,l,r);const a=new I(r,e.x,e.y,B,n);a.needsUpdate=!0,this.material.uniforms.scaleRotationsTexture.value=a,this.material.uniforms.scaleRotationsTextureSize.value.copy(e),this.splatDataTextures.scaleRotations={data:r,texture:a,size:e,compressionLevel:0}}if(p){const e=2===r?E:M;let i=u;i%2!=0&&i++;const n=2===this.minSphericalHarmonicsDegree?4:2,a=4===n?B:D;let o=s(n,i);if(o.x*o.y<=bs){const s=new d(o.x*o.y*n);for(let e=0;e<t;e++){const t=u*e,n=i*e;for(let e=0;e<u;e++)s[n+e]=p[t+e]}const l=new I(s,o.x,o.y,a,e);l.needsUpdate=!0,this.material.uniforms.sphericalHarmonicsTexture.value=l,this.splatDataTextures.sphericalHarmonics={componentCount:u,paddedComponentCount:i,data:s,textureCount:1,texture:l,size:o,compressionLevel:r,elementsPerTexel:n}}else{const l=u/3;i=l,i%2!=0&&i++,o=s(n,i);const c=o.x*o.y*n,h=[this.material.uniforms.sphericalHarmonicsTextureR,this.material.uniforms.sphericalHarmonicsTextureG,this.material.uniforms.sphericalHarmonicsTextureB],m=[],g=[];for(let s=0;s<3;s++){const n=new d(c);m.push(n);for(let e=0;e<t;e++){const t=u*e,r=i*e;if(l>=3){for(let e=0;e<3;e++)n[r+e]=p[t+3*s+e];if(l>=8)for(let e=0;e<5;e++)n[r+3+e]=p[t+9+5*s+e]}}const r=new I(n,o.x,o.y,a,e);g.push(r),r.needsUpdate=!0,h[s].value=r}this.material.uniforms.sphericalHarmonicsMultiTextureMode.value=1,this.splatDataTextures.sphericalHarmonics={componentCount:u,componentCountPerChannel:l,paddedComponentCount:i,data:m,textureCount:3,textures:g,size:o,compressionLevel:r,elementsPerTexel:n}}this.material.uniforms.sphericalHarmonicsTextureSize.value.copy(o),this.material.uniforms.sphericalHarmonics8BitMode.value=2===r?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 S=s(1,4),C=new Uint32Array(S.x*S.y*1);for(let e=0;e<t;e++)C[e]=this.globalSplatIndexToSceneIndexMap[e];const y=new I(C,S.x,S.y,R,w);y.internalFormat="R32UI",y.needsUpdate=!0,this.material.uniforms.sceneIndexesTexture.value=y,this.material.uniforms.sceneIndexesTextureSize.value.copy(S),this.material.uniformsNeedUpdate=!0,this.splatDataTextures.sceneIndexes={data:C,texture:y,size:S},this.material.uniforms.sceneCount.value=this.scenes.length,this.flameModel&&this.flameModel.geometry&&this.flameModel.geometry.morphAttributes&&this.flameModel.skeleton&&(this.expressionBSNum=this.flameModel.geometry.morphAttributes.position.length,this.material.uniforms.bsCount.value=this.expressionBSNum,this.flameModel.skeleton.bones.forEach((e,t)=>{"head"==e.name&&(this.material.uniforms.headBoneIndex.value=t)}),this.buildModelTexture(this.flameModel),this.buildBoneMatrixTexture(),this.buildBoneWeightTexture(this.flameModel))}buildBoneMatrixTexture(){if(!this.bsWeight)return;if(!this.flameModel||!this.flameModel.morphTargetDictionary)return;const e=new m(4,32);let t=new Float32Array(this.bonesMatrix),s=new Uint32Array(e.x*e.y*4);this.morphTargetDictionary=this.flameModel.morphTargetDictionary;for(let e=0;e<16*this.bonesNum;e++)s[e]=lt(t[e]);this.flameModel&&this.flameModel.skeleton&&(this.material.uniforms.boneTexture0.value=this.flameModel.skeleton.boneTexture,this.material.uniforms.bindMatrix.value=this.flameModel.bindMatrix,this.material.uniforms.bindMatrixInverse.value=this.flameModel.bindMatrixInverse);for(const e in this.bsWeight)if(Object.hasOwn(this.bsWeight,e)){const t=this.bsWeight[e];s[this.morphTargetDictionary[e]+16*this.bonesNum]=lt(t)}const i=new I(s,e.x,e.y,b,w);i.internalFormat="RGBA32UI",i.needsUpdate=!0,this.material.uniforms.boneTexture.value=i,this.material.uniforms.boneTextureSize.value.copy(e),this.material.uniformsNeedUpdate=!0,this.splatDataTextures.boneMatrix={data:s,texture:i,size:e},this.splatDataTextures.baseData.boneMatrix=s}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]=lt(t)}this.splatDataTextures.boneMatrix.texture.data=this.splatDataTextures.baseData.boneMatrix,this.splatDataTextures.boneMatrix.texture.needsUpdate=!0,this.material.uniforms.boneTexture.value=this.splatDataTextures.boneMatrix.texture,this.flameModel.skeleton&&(this.material.uniforms.boneTexture0.value=this.flameModel.skeleton.boneTexture,this.material.uniforms.bindMatrix.value=this.flameModel.bindMatrix,this.material.uniforms.bindMatrixInverse.value=this.flameModel.bindMatrixInverse),this.material.uniformsNeedUpdate=!0}}buildBoneWeightTexture(e){if(!this.bonesWeight)return;let t=e.geometry.attributes.position.array.length/3;const s=new m(512,512);let i=new Float32Array(s.x*s.y*4),n=new Uint32Array(s.x*s.y*4);for(let e=0;e<t;e++)i[8*e+0]=this.bonesWeight[e][0],i[8*e+1]=this.bonesWeight[e][1],i[8*e+2]=this.bonesWeight[e][2],i[8*e+3]=this.bonesWeight[e][3],i[8*e+4]=this.bonesWeight[e][4],n[8*e+0]=lt(this.bonesWeight[e][0]),n[8*e+1]=lt(this.bonesWeight[e][1]),n[8*e+2]=lt(this.bonesWeight[e][2]),n[8*e+3]=lt(this.bonesWeight[e][3]),n[8*e+4]=lt(this.bonesWeight[e][4]);const r=new I(n,s.x,s.y,b,w);r.internalFormat="RGBA32UI",r.needsUpdate=!0,this.material.uniforms.boneWeightTexture.value=r,this.material.uniforms.boneWeightTextureSize.value.copy(s),this.material.uniformsNeedUpdate=!0,this.splatDataTextures.boneWeight={data:n,texture:r,size:s},this.splatDataTextures.baseData.boneWeight=n}buildModelTexture(e){if(!(e&&e.geometry&&e.geometry.morphAttributes&&e.morphTargetDictionary))return;const t=new m(4096,2048);var s=e.geometry.attributes.position.array,i=[];let n=s.length/3,r=e.geometry.morphAttributes.position.length;Object.keys(e.morphTargetDictionary).forEach((t,s)=>{const n=e.morphTargetDictionary[t];var r=e.geometry.morphAttributes.position[n];i=i.concat(Array.from(r.array))}),i=i.concat(Array.from(s));let a=new Float32Array(t.x*t.y*4),o=new Uint32Array(t.x*t.y*4);for(let e=0;e<n*(r+1);e++)a[4*e+0]=i[3*e+0],a[4*e+1]=i[3*e+1],a[4*e+2]=i[3*e+2],o[4*e+0]=lt(a[4*e+0]),o[4*e+1]=lt(a[4*e+1]),o[4*e+2]=lt(a[4*e+2]);const l=new I(o,t.x,t.y,b,w);l.internalFormat="RGBA32UI",l.needsUpdate=!0,this.material.uniforms.flameModelTexture.value=l,this.material.uniforms.flameModelTextureSize.value.copy(t),this.material.uniformsNeedUpdate=!0,this.material.uniforms.gaussianSplatCount.value=this.gaussianSplatCount,this.splatDataTextures.flameModel={data:o,texture:l,size:t},this.splatDataTextures.baseData.flameModelPos=a}updateTetureAfterBSAndSkeleton(e,t){const s=new i;this.getSceneTransform(0,s),this.getScene(0).splatBuffer.fillSplatCenterArray(this.morphedMesh,this.splatDataTextures.baseData.centers,s,e,t,0);const n=this.splatDataTextures.centerColors,r=n.data,a=n.texture;ws.updateCenterColorsPaddedData(e,t,this.splatDataTextures.baseData.centers,this.splatDataTextures.baseData.colors,r);const o=this.renderer?this.renderer.properties.get(a):null;o&&o.__webglTexture?this.updateDataTexture(r,n.texture,n.size,o,4,4,4,e,t):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;ws.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 ws.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;ws.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,y=this.renderer?this.renderer.properties.get(C):null;y&&y.__webglTexture?this.updateDataTexture(S,f.texture,f.size,y,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=ws.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]=ht(i,e),n[a+1]=lt(s[t]),n[a+2]=lt(s[t+1]),n[a+3]=lt(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(e){const t=this.getSplatCount(!0),i=new s;if(!e){const e=new s;this.scenes.forEach(t=>{e.add(t.splatBuffer.sceneCenter)}),e.multiplyScalar(1/this.scenes.length),this.calculatedSceneCenter.copy(e),this.material.uniforms.sceneCenter.value.copy(this.calculatedSceneCenter),this.material.uniformsNeedUpdate=!0}for(let s=e?this.lastBuildSplatCount:0;s<t;s++){this.getSplatCenter(this.morphedMesh,s,i,!0);const e=i.sub(this.calculatedSceneCenter).length();e>this.maxSplatDistanceFromSceneCenter&&(this.maxSplatDistanceFromSceneCenter=e)}this.maxSplatDistanceFromSceneCenter-this.visibleRegionBufferRadius>1&&(this.visibleRegionBufferRadius=this.maxSplatDistanceFromSceneCenter,this.visibleRegionRadius=Math.max(this.visibleRegionBufferRadius-1,0)),this.finalBuild&&(this.visibleRegionRadius=this.visibleRegionBufferRadius=this.maxSplatDistanceFromSceneCenter),this.updateVisibleRegionFadeDistance()}updateVisibleRegionFadeDistance(e=$.Default){const t=.012*this.sceneFadeInRateMultiplier,s=.003*this.sceneFadeInRateMultiplier,i=this.finalBuild?t:s,n=e===$.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===$.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 e=new m;return function(t,s,i,n,r,a){if(this.getSplatCount()>0){if(e.set(t.x*this.devicePixelRatio,t.y*this.devicePixelRatio),this.material.uniforms.viewport.value.copy(e),this.material.uniforms.basisViewport.value.set(1/e.x,1/e.y),this.material.uniforms.focal.value.set(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]=ze(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?ws.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 ws.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 xs(t),i=new vs(t,s,{});if(s.init(i),this.webGLUtils=new Is(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 Ss.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 Ss.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[${ee.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[${ee.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 Ss.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 e=new i;return(t,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(e.copy(this.getScene(s).transform),e.premultiply(t),this.integerBasedDistancesComputation){const t=ws.getIntegerMatrixArray(e),n=[t[2],t[6],t[10],t[14]];i.uniform4i(this.distancesTransformFeedback.transformsLocs[s],n[0],n[1],n[2],n[3])}else i.uniformMatrix4fv(this.distancesTransformFeedback.transformsLocs[s],!1,e.elements);else if(this.integerBasedDistancesComputation){const e=ws.getIntegerMatrixArray(t),s=[e[2],e[6],e[10]];i.uniform3i(this.distancesTransformFeedback.modelViewProjLoc,s[0],s[1],s[2])}else{const e=[t.elements[2],t.elements[6],t.elements[10]];i.uniform3f(this.distancesTransformFeedback.modelViewProjLoc,e[0],e[1],e[2])}i.bindBuffer(i.ARRAY_BUFFER,this.distancesTransformFeedback.centersBuffer),i.enableVertexAttribArray(this.distancesTransformFeedback.centersLoc),this.integerBasedDistancesComputation?i.vertexAttribIPointer(this.distancesTransformFeedback.centersLoc,4,i.INT,0,0):i.vertexAttribPointer(this.distancesTransformFeedback.centersLoc,4,i.FLOAT,!1,0,0),this.dynamicMode&&(i.bindBuffer(i.ARRAY_BUFFER,this.distancesTransformFeedback.sceneIndexesBuffer),i.enableVertexAttribArray(this.distancesTransformFeedback.sceneIndexesLoc),i.vertexAttribIPointer(this.distancesTransformFeedback.sceneIndexesLoc,1,i.UNSIGNED_INT,0,0)),i.bindTransformFeedback(i.TRANSFORM_FEEDBACK,this.distancesTransformFeedback.id),i.bindBufferBase(i.TRANSFORM_FEEDBACK_BUFFER,0,this.distancesTransformFeedback.outDistancesBuffer),i.beginTransformFeedback(i.POINTS),i.drawArrays(i.POINTS,0,this.getSplatCount()),i.endTransformFeedback(),i.bindBufferBase(i.TRANSFORM_FEEDBACK_BUFFER,0,null),i.bindTransformFeedback(i.TRANSFORM_FEEDBACK,null),i.disable(i.RASTERIZER_DISCARD);const o=i.fenceSync(i.SYNC_GPU_COMMANDS_COMPLETE,0);i.flush();const l=new Promise(e=>{const t=()=>{if(this.disposed)e();else{const 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(e,t,n,r,a,o,l,c,h=0,d=0,u=1,p,m,g=0,A){const f=new s;f.x=void 0,f.y=void 0,this.splatRenderMode===Z.ThreeD?f.z=void 0:f.z=1;const S=new i;let C=0,y=this.scenes.length-1;null!=A&&A>=0&&A<=this.scenes.length&&(C=A,y=A);for(let s=C;s<=y;s++){null==c&&(c=!this.dynamicMode);const i=this.getScene(s),l=i.splatBuffer;let A;if(c&&(this.getSceneTransform(s,S),A=S),e&&l.fillSplatCovarianceArray(e,A,p,m,g,h),t||n){if(!t||!n)throw new Error('SplatMesh::fillSplatDataArrays() -> "scales" and "rotations" must both be valid.');l.fillSplatScaleRotationArray(t,n,A,p,m,g,d,f)}r&&l.fillSplatCenterArray(this.morphedMesh,r,A,p,m,g),a&&l.fillSplatColorArray(a,i.minimumAlpha,p,m,g),o&&l.fillSphericalHarmonicsArray(o,this.minSphericalHarmonicsDegree,A,p,m,g,u),g+=l.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 e={},t=new s;return function(s,i,n,r){this.getLocalSplatParameters(s,e,r),t.x=void 0,t.y=void 0,t.z=void 0,this.splatRenderMode===Z.TwoD&&(t.z=0),e.splatBuffer.getSplatScaleAndRotation(e.localIndex,i,n,e.sceneTransform,t)}}();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(e=!1,t){let i=this.getSplatCount();if(null!=t){if(t<0||t>=this.scenes.length)throw new Error("SplatMesh::computeBoundingBox() -> Invalid scene index.");i=this.scenes[t].splatBuffer.getSplatCount()}const n=new Float32Array(3*i);this.fillSplatDataArrays(null,null,null,n,null,null,e,void 0,void 0,void 0,void 0,t);const r=new s,a=new s;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 x(r,a)}}class Bs extends Error{constructor(e){super(e),this.name="DirectLoadError"}}class Ts{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=Ge(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=Ge(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=Ts.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=Ts.createSplat(this.sphericalHarmonicsDegree);for(let e=0;e<this.componentCount&&e<s.length;e++)i[e]=s[e];this.addSplat(i)}}const Ds=(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]},Es=t.toHalfFloat.bind(t),Ms=t.fromHalfFloat.bind(t),Rs=(e,s,i=!1,n,r)=>0===s?e:1===s||2===s&&!i?t.fromHalfFloat(e):2===s?Ps(e,n,r):void 0,Fs=(e,t,s)=>{e=ze(e,t,s);const i=s-t;return ze(Math.floor((e-t)/i*255),0,255)},Ps=(e,t,s)=>e/255*(s-t)+t,ks=(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 _s{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=ks(l,0,this.compressionLevel),h=ks(l,1,this.compressionLevel),d=ks(l,2,this.compressionLevel);if(this.compressionLevel>=1){const e=this.getBucketIndex(r,a)*_s.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 e=new i,t=new i,r=new i,a=new s,o=new s,l=new n;return function(s,i,n,c,h){const d=this.globalSplatIndexToSectionMap[s],u=this.sections[d],p=s-u.splatCountOffset,m=u.bytesPerSplat*p+_s.CompressionLevels[this.compressionLevel].ScaleOffsetBytes,g=new DataView(this.bufferData,u.dataBase+m);o.set(Rs(ks(g,0,this.compressionLevel),this.compressionLevel),Rs(ks(g,1,this.compressionLevel),this.compressionLevel),Rs(ks(g,2,this.compressionLevel),this.compressionLevel)),h&&(void 0!==h.x&&(o.x=h.x),void 0!==h.y&&(o.y=h.y),void 0!==h.z&&(o.z=h.z)),l.set(Rs(ks(g,4,this.compressionLevel),this.compressionLevel),Rs(ks(g,5,this.compressionLevel),this.compressionLevel),Rs(ks(g,6,this.compressionLevel),this.compressionLevel),Rs(ks(g,3,this.compressionLevel),this.compressionLevel)),c?(e.makeScale(o.x,o.y,o.z),t.makeRotationFromQuaternion(l),r.copy(e).multiply(t).multiply(c),r.decompose(a,n,i)):(i.copy(o),n.copy(l))}}();getSplatColor(e,t){const s=this.globalSplatIndexToSectionMap[e],i=this.sections[s],n=e-i.splatCountOffset,r=i.bytesPerSplat*n+_s.CompressionLevels[this.compressionLevel].ColorOffsetBytes,a=new Uint8Array(this.bufferData,i.dataBase+r,4);t.set(a[0],a[1],a[2],a[3])}fillSplatCenterArray(e,t,i,n,r,a){const o=this.splatCount;n=n||0,r=r||o-1,void 0===a&&(a=n);const l=new s;for(let s=n;s<=r;s++){const r=this.globalSplatIndexToSectionMap[s],o=this.sections[r],c=s-o.splatCountOffset,h=(s-n+a)*_s.CenterComponentCount,d=o.bytesPerSplat*c,u=new DataView(this.bufferData,o.dataBase+d),p=ks(u,0,this.compressionLevel),m=ks(u,1,this.compressionLevel),g=ks(u,2,this.compressionLevel);if(this.compressionLevel>=1){const e=this.getBucketIndex(o,c)*_s.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),t[h]=l.x+e[3*s+0],t[h+1]=l.y+e[3*s+1],t[h+2]=l.z+e[3*s+2]}}fillSplatScaleRotationArray=function(){const e=new i,t=new i,r=new i,a=new s,o=new n,l=new s,c=e=>{const t=e.w<0?-1:1;e.x*=t,e.y*=t,e.z*=t,e.w*=t};return function(s,i,n,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)=>rt(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+_s.CompressionLevels[this.compressionLevel].ScaleOffsetBytes,C=(p-h+u)*_s.ScaleComponentCount,y=(p-h+u)*_s.RotationComponentCount,x=new DataView(this.bufferData,g.dataBase+S),v=m&&void 0!==m.x?m.x:ks(x,0,this.compressionLevel),I=m&&void 0!==m.y?m.y:ks(x,1,this.compressionLevel),b=m&&void 0!==m.z?m.z:ks(x,2,this.compressionLevel),w=ks(x,3,this.compressionLevel),B=ks(x,4,this.compressionLevel),T=ks(x,5,this.compressionLevel),D=ks(x,6,this.compressionLevel);a.set(Rs(v,this.compressionLevel),Rs(I,this.compressionLevel),Rs(b,this.compressionLevel)),o.set(Rs(B,this.compressionLevel),Rs(T,this.compressionLevel),Rs(D,this.compressionLevel),Rs(w,this.compressionLevel)).normalize(),n&&(l.set(0,0,0),e.makeScale(a.x,a.y,a.z),t.makeRotationFromQuaternion(o),r.identity().premultiply(e).premultiply(t),r.premultiply(n),r.decompose(l,o,a),o.normalize()),c(o),s&&(s[C]=A(a.x,0),s[C+1]=A(a.y,0),s[C+2]=A(a.z,0)),i&&(i[y]=A(o.x,0),i[y+1]=A(o.y,0),i[y+2]=A(o.z,0),i[y+3]=A(o.w,0))}}}();static computeCovariance=function(){const e=new i,t=new _,s=new _,n=new _,r=new _,a=new _,o=new _;return function(i,l,c,h,d=0,u){e.makeScale(i.x,i.y,i.z),t.setFromMatrix4(e),e.makeRotationFromQuaternion(l),s.setFromMatrix4(e),n.copy(s).multiply(t),r.copy(n).transpose().premultiply(n),c&&(a.setFromMatrix4(c),o.copy(a).transpose(),r.multiply(o),r.premultiply(a)),u>=1?(h[d]=Es(r.elements[0]),h[d+1]=Es(r.elements[3]),h[d+2]=Es(r.elements[6]),h[d+3]=Es(r.elements[4]),h[d+4]=Es(r.elements[7]),h[d+5]=Es(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(e,t,i,r,a,o){const l=this.splatCount,c=new s,h=new n;i=i||0,r=r||l-1,void 0===a&&(a=i);for(let s=i;s<=r;s++){const n=this.globalSplatIndexToSectionMap[s],r=this.sections[n],l=s-r.splatCountOffset,d=(s-i+a)*_s.CovarianceComponentCount,u=r.bytesPerSplat*l+_s.CompressionLevels[this.compressionLevel].ScaleOffsetBytes,p=new DataView(this.bufferData,r.dataBase+u);c.set(Rs(ks(p,0,this.compressionLevel),this.compressionLevel),Rs(ks(p,1,this.compressionLevel),this.compressionLevel),Rs(ks(p,2,this.compressionLevel),this.compressionLevel)),h.set(Rs(ks(p,4,this.compressionLevel),this.compressionLevel),Rs(ks(p,5,this.compressionLevel),this.compressionLevel),Rs(ks(p,6,this.compressionLevel),this.compressionLevel),Rs(ks(p,3,this.compressionLevel),this.compressionLevel)),_s.computeCovariance(c,h,t,e,d,o)}}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)*_s.ColorComponentCount,c=a.bytesPerSplat*o+_s.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 e=0;e<15;e++)new s;const e=new _,t=new i,r=new s,a=new s,o=new n,l=[],c=[],h=[],d=[],u=[],p=[],m=[],g=[],A=[],f=[],S=[],C=[],y=[],x=[],v=[],I=[],b=[],w=[],B=e=>e,T=(e,t,s,i)=>{e[0]=t,e[1]=s,e[2]=i},D=(e,t,s,i,n)=>{e[0]=ks(t,i,n,!0),e[1]=ks(t,i+s,n,!0),e[2]=ks(t,i+s+s,n,!0)},E=(e,t)=>{t[0]=e[0],t[1]=e[1],t[2]=e[2]},M=(e,t,s,i)=>{t[s]=i(e[0]),t[s+1]=i(e[1]),t[s+2]=i(e[2])},R=(e,t,s,i,n)=>(t[0]=Rs(e[0],s,!0,i,n),t[1]=Rs(e[1],s,!0,i,n),t[2]=Rs(e[2],s,!0,i,n),t);return function(s,i,n,F,P,k,_){const L=this.splatCount;F=F||0,P=P||L-1,void 0===k&&(k=F),n&&i>=1&&(t.copy(n),t.decompose(r,o,a),o.normalize(),t.makeRotationFromQuaternion(o),e.setFromMatrix4(t),T(l,e.elements[4],-e.elements[7],e.elements[1]),T(c,-e.elements[5],e.elements[8],-e.elements[2]),T(h,e.elements[3],-e.elements[6],e.elements[0]));const U=e=>((e,t,s)=>Fs(Ms(e),t,s))(e,this.minSphericalHarmonicsCoeff,this.maxSphericalHarmonicsCoeff),H=e=>Fs(e,this.minSphericalHarmonicsCoeff,this.maxSphericalHarmonicsCoeff);for(let e=F;e<=P;e++){const t=this.globalSplatIndexToSectionMap[e],r=this.sections[t];i=Math.min(i,r.sphericalHarmonicsDegree);const a=Ge(i),o=e-r.splatCountOffset,T=r.bytesPerSplat*o+_s.CompressionLevels[this.compressionLevel].SphericalHarmonicsOffsetBytes,P=new DataView(this.bufferData,r.dataBase+T),L=(e-F+k)*a;let O=n?0:this.compressionLevel,z=B;O!==_&&(1===O?0===_?z=Ms:2==_&&(z=U):0===O&&(1===_?z=Es:2==_&&(z=H)));const Q=this.minSphericalHarmonicsCoeff,N=this.maxSphericalHarmonicsCoeff;i>=1&&(D(A,P,3,0,this.compressionLevel),D(f,P,3,1,this.compressionLevel),D(S,P,3,2,this.compressionLevel),n?(R(A,A,this.compressionLevel,Q,N),R(f,f,this.compressionLevel,Q,N),R(S,S,this.compressionLevel,Q,N),_s.rotateSphericalHarmonics3(A,f,S,l,c,h,x,v,I)):(E(A,x),E(f,v),E(S,I)),M(x,s,L,z),M(v,s,L+3,z),M(I,s,L+6,z),i>=2&&(D(A,P,5,9,this.compressionLevel),D(f,P,5,10,this.compressionLevel),D(S,P,5,11,this.compressionLevel),D(C,P,5,12,this.compressionLevel),D(y,P,5,13,this.compressionLevel),n?(R(A,A,this.compressionLevel,Q,N),R(f,f,this.compressionLevel,Q,N),R(S,S,this.compressionLevel,Q,N),R(C,C,this.compressionLevel,Q,N),R(y,y,this.compressionLevel,Q,N),_s.rotateSphericalHarmonics5(A,f,S,C,y,l,c,h,d,u,p,m,g,x,v,I,b,w)):(E(A,x),E(f,v),E(S,I),E(C,b),E(y,w)),M(x,s,L+9,z),M(v,s,L+12,z),M(I,s,L+15,z),M(b,s,L+18,z),M(w,s,L+21,z)))}}}();static dot3=(e,t,s,i,n)=>{n[0]=n[1]=n[2]=0;const r=i[0],a=i[1],o=i[2];_s.addInto3(e[0]*r,e[1]*r,e[2]*r,n),_s.addInto3(t[0]*a,t[1]*a,t[2]*a,n),_s.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];_s.addInto3(e[0]*o,e[1]*o,e[2]*o,a),_s.addInto3(t[0]*l,t[1]*l,t[2]*l,a),_s.addInto3(s[0]*c,s[1]*c,s[2]*c,a),_s.addInto3(i[0]*h,i[1]*h,i[2]*h,a),_s.addInto3(n[0]*d,n[1]*d,n[2]*d,a)};static rotateSphericalHarmonics3=(e,t,s,i,n,r,a,o,l)=>{_s.dot3(e,t,s,i,a),_s.dot3(e,t,s,n,o),_s.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),y=Math.sqrt(1/3),x=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])),_s.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])),_s.dot5(e,t,s,i,n,c,m),h[0]=y*(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]=x*a[1]*a[0]+-y*(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]=x*a[1]*a[2]+-y*(o[1]*o[2]+r[1]*r[2]),h[4]=y*(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])),_s.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])),_s.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])),_s.dot5(e,t,s,i,n,u,f)};static parseHeader(e){const t=new Uint8Array(e,0,_s.HeaderSizeBytes),i=new Uint16Array(e,0,_s.HeaderSizeBytes/2),n=new Uint32Array(e,0,_s.HeaderSizeBytes/4),r=new Float32Array(e,0,_s.HeaderSizeBytes/4);return{versionMajor:t[0],versionMinor:t[1],maxSectionCount:n[1],sectionCount:n[2],maxSplatCount:n[3],splatCount:n[4],compressionLevel:i[10],sceneCenter:new s(r[6],r[7],r[8]),minSphericalHarmonicsCoeff:r[9]||-$e,maxSphericalHarmonicsCoeff:r[10]||$e}}static writeHeaderCountsToBuffer(e,t,s){const i=new Uint32Array(s,0,_s.HeaderSizeBytes/4);i[2]=e,i[4]=t}static writeHeaderToBuffer(e,t){const s=new Uint8Array(t,0,_s.HeaderSizeBytes),i=new Uint16Array(t,0,_s.HeaderSizeBytes/2),n=new Uint32Array(t,0,_s.HeaderSizeBytes/4),r=new Float32Array(t,0,_s.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||-$e,r[10]=e.maxSphericalHarmonicsCoeff||$e}static parseSectionHeaders(e,t,s=0,i){const n=e.compressionLevel,r=e.maxSectionCount,a=new Uint16Array(t,s,r*_s.SectionHeaderSizeBytes/2),o=new Uint32Array(t,s,r*_s.SectionHeaderSizeBytes/4),l=new Float32Array(t,s,r*_s.SectionHeaderSizeBytes/4),c=[];let h=0,d=h/2,u=h/4,p=_s.HeaderSizeBytes+e.maxSectionCount*_s.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]||_s.CompressionLevels[n].ScaleRange,C=o[u+8],y=o[u+9],x=4*y,v=f*r+x,I=a[d+20],{bytesPerSplat:b}=_s.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+x,dataBase:p+v,fullBucketCount:C,partiallyFilledBucketCount:y,sphericalHarmonicsDegree:I};c[e]=T,p+=B,h+=_s.SectionHeaderSizeBytes,d=h/2,u=h/4,m+=t}return c}static writeSectionHeaderToBuffer(e,t,s,i=0){const n=new Uint16Array(s,i,_s.SectionHeaderSizeBytes/2),r=new Uint32Array(s,i,_s.SectionHeaderSizeBytes/4),a=new Float32Array(s,i,_s.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?_s.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,_s.SectionHeaderSizeBytes/4)[0]=e}constructFromBuffer(e,t){this.bufferData=e,this.globalSplatIndexToLocalSplatIndexMap=[],this.globalSplatIndexToSectionMap=[];const i=_s.parseHeader(this.bufferData);this.versionMajor=i.versionMajor,this.versionMinor=i.versionMinor,this.maxSectionCount=i.maxSectionCount,this.sectionCount=t?i.maxSectionCount:0,this.maxSplatCount=i.maxSplatCount,this.splatCount=t?i.maxSplatCount:0,this.compressionLevel=i.compressionLevel,this.sceneCenter=(new s).copy(i.sceneCenter),this.minSphericalHarmonicsCoeff=i.minSphericalHarmonicsCoeff,this.maxSphericalHarmonicsCoeff=i.maxSphericalHarmonicsCoeff,this.sections=_s.parseSectionHeaders(i,this.bufferData,_s.HeaderSizeBytes,t),this.linkBufferArrays(),this.buildMaps()}static calculateComponentStorage(e,t){const s=_s.CompressionLevels[e].BytesPerCenter,i=_s.CompressionLevels[e].BytesPerScale,n=_s.CompressionLevels[e].BytesPerRotation,r=_s.CompressionLevels[e].BytesPerColor,a=Ge(t),o=_s.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*_s.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){_s.writeHeaderCountsToBuffer(e,t,this.bufferData),this.sectionCount=e,this.splatCount=t}updateSectionLoadedCounts(e,t){const s=_s.HeaderSizeBytes+_s.SectionHeaderSizeBytes*e;_s.writeSectionHeaderSplatCountToBuffer(t,this.bufferData,s),this.sections[e].splatCount=t}static writeSplatDataToSectionBuffer=function(){const e=new ArrayBuffer(12),t=new ArrayBuffer(12),i=new ArrayBuffer(16),r=new ArrayBuffer(4),a=new ArrayBuffer(256),o=new n,l=new s,c=new s,{X:h,Y:d,Z:u,SCALE0:p,SCALE1:m,SCALE2:g,ROTATION0:A,ROTATION1:f,ROTATION2:S,ROTATION3:C,FDC0:y,FDC1:x,FDC2:v,OPACITY:I,FRC0:b,FRC9:w}=Ts.OFFSET,B=(e,t,s)=>{const i=2*s+1;return e=Math.round(e*t)+s,ze(e,0,i)};return function(s,n,T,D,E,M,R,F,P=-$e,k=$e){const _=Ge(E),L=T,U=L+_s.CompressionLevels[D].BytesPerCenter,H=U+_s.CompressionLevels[D].BytesPerScale,O=H+_s.CompressionLevels[D].BytesPerRotation,z=O+_s.CompressionLevels[D].BytesPerColor;if(void 0!==s[A]?(o.set(s[A],s[f],s[S],s[C]),o.normalize()):o.set(1,0,0,0),void 0!==s[p]?l.set(s[p]||0,s[m]||0,s[g]||0):l.set(0,0,0),0===D){const e=new Float32Array(n,L,_s.CenterComponentCount),t=new Float32Array(n,H,_s.RotationComponentCount),i=new Float32Array(n,U,_s.ScaleComponentCount);if(t.set([o.x,o.y,o.z,o.w]),i.set([l.x,l.y,l.z]),e.set([s[h],s[d],s[u]]),E>0){const e=new Float32Array(n,z,_);if(E>=1){for(let t=0;t<9;t++)e[t]=s[b+t]||0;if(E>=2)for(let t=0;t<15;t++)e[t+9]=s[w+t]||0}}}else{const r=new Uint16Array(e,0,_s.CenterComponentCount),p=new Uint16Array(i,0,_s.RotationComponentCount),m=new Uint16Array(t,0,_s.ScaleComponentCount);if(p.set([Es(o.x),Es(o.y),Es(o.z),Es(o.w)]),m.set([Es(l.x),Es(l.y),Es(l.z)]),c.set(s[h],s[d],s[u]).sub(M),c.x=B(c.x,R,F),c.y=B(c.y,R,F),c.z=B(c.z,R,F),r.set([c.x,c.y,c.z]),E>0){const e=1===D?2:1,t=new(1===D?Uint16Array:Uint8Array)(a,0,_);if(E>=1){for(let e=0;e<9;e++){const i=s[b+e]||0;t[e]=1===D?Es(i):Fs(i,P,k)}const i=9*e;if(Ds(t.buffer,0,n,z,i),E>=2){for(let e=0;e<15;e++){const i=s[w+e]||0;t[e+9]=1===D?Es(i):Fs(i,P,k)}Ds(t.buffer,i,n,z+i,15*e)}}}Ds(r.buffer,0,n,L,6),Ds(m.buffer,0,n,U,6),Ds(p.buffer,0,n,H,8)}const Q=new Uint8ClampedArray(r,0,4);Q.set([s[y]||0,s[x]||0,s[v]||0]),Q[3]=s[I]||0,Ds(Q.buffer,0,n,O,4)}}();static generateFromUncompressedSplatArrays(e,t,i,n,r,a,o=[]){let l,c,h=0;for(let t=0;t<e.length;t++){const s=e[t];h=Math.max(s.sphericalHarmonicsDegree,h)}for(let t=0;t<e.length;t++){const s=e[t];for(let e=0;e<s.splats.length;e++){const t=s.splats[e];for(let e=Ts.OFFSET.FRC0;e<Ts.OFFSET.FRC23&&e<t.length;e++)(!l||t[e]<l)&&(l=t[e]),(!c||t[e]>c)&&(c=t[e])}}l=l||-$e,c=c||$e;const{bytesPerSplat:d}=_s.calculateComponentStorage(i,h),u=_s.CompressionLevels[i].ScaleRange,p=[],m=[];let g=0;for(let n=0;n<e.length;n++){const A=e[n],f=new Ts(h);for(let e=0;e<A.splatCount;e++){const s=A.splats[e];(s[Ts.OFFSET.OPACITY]||0)>=t&&f.addSplat(s)}const S=o[n]||{},C=(S.blockSizeFactor||1)*(r||_s.BucketBlockSize),y=Math.ceil((S.bucketSizeFactor||1)*(a||_s.BucketSize)),x=_s.computeBucketsForUncompressedSplatArray(f,C,y),v=x.fullBuckets.length,I=x.partiallyFullBuckets.map(e=>e.splats.length),b=I.length,w=[...x.fullBuckets,...x.partiallyFullBuckets],B=f.splats.length*d,T=4*b,D=i>=1?w.length*_s.BucketStorageSizeBytes+T:0,E=B+D,M=new ArrayBuffer(E),R=u/(.5*C),F=new s;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;_s.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*_s.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(_s.SectionHeaderSizeBytes);_s.writeSectionHeaderToBuffer({maxSplatCount:P,splatCount:P,bucketSize:y,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=_s.HeaderSizeBytes+_s.SectionHeaderSizeBytes*p.length+A,S=new ArrayBuffer(f);_s.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=_s.HeaderSizeBytes;for(let e of m)new Uint8Array(S,C,_s.SectionHeaderSizeBytes).set(new Uint8Array(e)),C+=_s.SectionHeaderSizeBytes;for(let e of p)new Uint8Array(S,C,e.byteLength).set(new Uint8Array(e)),C+=e.byteLength;return new _s(S)}static computeBucketsForUncompressedSplatArray(e,t,i){let n=e.splatCount;const r=t/2,a=new s,o=new s;for(let t=0;t<n;t++){const s=e.splats[t],i=[s[Ts.OFFSET.X],s[Ts.OFFSET.Y],s[Ts.OFFSET.Z]];(0===t||i[0]<a.x)&&(a.x=i[0]),(0===t||i[0]>o.x)&&(o.x=i[0]),(0===t||i[1]<a.y)&&(a.y=i[1]),(0===t||i[1]>o.y)&&(o.y=i[1]),(0===t||i[2]<a.z)&&(a.z=i[2]),(0===t||i[2]>o.z)&&(o.z=i[2])}const l=(new s).copy(o).sub(a),c=Math.ceil(l.y/t),h=Math.ceil(l.z/t),d=new s,u=[],p={};for(let s=0;s<n;s++){const n=e.splats[s],o=[n[Ts.OFFSET.X],n[Ts.OFFSET.Y],n[Ts.OFFSET.Z]],l=Math.floor((o[0]-a.x)/t),m=Math.floor((o[1]-a.y)/t),g=Math.floor((o[2]-a.z)/t);d.x=l*t+a.x+r,d.y=m*t+a.y+r,d.z=g*t+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(s),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 Ls{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 Ts(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(e=0,t=new s,i=_s.BucketBlockSize,n=_s.BucketSize){return new Ls(void 0,void 0,void 0,r=>{const a=Ts.OFFSET.X,o=Ts.OFFSET.Y,l=Ts.OFFSET.Z;e<=0&&(e=r.splatCount);const c=new s,h=.5;r.splats.forEach(e=>{var s;c.set(e[a],e[o],e[l]).sub(t),(s=c).x=Math.floor(s.x/h)*h,s.y=Math.floor(s.y/h)*h,s.z=Math.floor(s.z/h)*h,e.centerDist=c.lengthSq()}),r.splats.sort((e,t)=>e.centerDist>t.centerDist?1:-1);const d=[],u=[];e=Math.min(r.splatCount,e);const p=Math.ceil(r.splatCount/e);let m=0;for(let t=0;t<p;t++){let t=m;d.push(s=>s>=t&&s<t+e),u.push({blocksSize:i,bucketSize:n}),m+=e}return{sectionCount:d.length,sectionFilters:d,groupingParameters:u}})}}class Us{constructor(e,t,i,n,r,a,o){this.splatPartitioner=e,this.alphaRemovalThreshold=t,this.compressionLevel=i,this.sectionSize=n,this.sceneCenter=r?(new s).copy(r):void 0,this.blockSize=a,this.bucketSize=o}generateFromUncompressedSplatArray(e){const t=this.splatPartitioner.partitionUncompressedSplatArray(e);return _s.generateFromUncompressedSplatArrays(t.splatArrays,this.alphaRemovalThreshold,this.compressionLevel,this.sceneCenter,this.blockSize,this.bucketSize,t.parameters)}static getStandardGenerator(e=1,t=1,i=0,n=new s,r=_s.BucketBlockSize,a=_s.BucketSize){const o=Ls.getStandardPartitioner(i,n,r,a);return new Us(o,e,t,i,n,r,a)}}const Hs={INRIAV1:0},Os=0,zs=1,Qs=2,Ns=3,Vs=4,Gs=5,Ws=6,qs={double:0,int:1,uint:2,float:3,short:4,ushort:5,uchar:6},Ks={[Os]:8,[zs]:4,[Qs]:4,[Ns]:4,[Vs]:2,[Gs]:2,[Ws]:1};class js{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=qs[s];void 0!==n&&(c.push(n),h[n]=r)}}if(m===js.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+=Ks[qs[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(js.HeaderEndToken)}static checkBufferForEndHeader(e,t,s,i){const n=new Uint8Array(e,Math.max(0,t-s),s),r=i.decode(n);return js.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,js.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,js.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===js.HeaderEndToken)break}return s}static determineHeaderFormatFromHeaderText(e){return Hs.INRIAV1}static determineHeaderFormatFromPlyBuffer(e){const t=js.extractHeaderFromBufferToText(e);return js.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 Ys=["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"],Js=Ys.map((e,t)=>t),[Xs,$s,Zs,ei,ti,si,ii,ni,ri,ai,oi,li,ci,hi,di,ui,pi,mi]=Js;class gi{constructor(){this.plyParserutils=new js}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=[...Ys,...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=js.convertHeaderTextToLines(e),s=this.decodeHeaderLines(t);return s.headerText=e,s.headerSizeBytes=e.indexOf(js.HeaderEndToken)+js.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=_s.CompressionLevels[0].SphericalHarmonicsDegrees[o].BytesPerSplat;for(let c=t;c<=s;c++){const t=gi.parseToUncompressedSplat(i,c,e,n,o),s=c*l+a;_s.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=gi.parseToUncompressedSplat(i,o,e,n,a);r.addSplat(t)}}decodeSectionSplatData(e,t,s,i){i=Math.min(i,s.sphericalHarmonicsDegree);const n=new Ts(i);for(let r=0;r<t;r++){const t=gi.parseToUncompressedSplat(e,r,s,0,i);n.addSplat(t)}return n}static parseToUncompressedSplat=function(){let e=[];const t=new n,s=Ts.OFFSET.X,i=Ts.OFFSET.Y,r=Ts.OFFSET.Z,a=Ts.OFFSET.SCALE0,o=Ts.OFFSET.SCALE1,l=Ts.OFFSET.SCALE2,c=Ts.OFFSET.ROTATION0,h=Ts.OFFSET.ROTATION1,d=Ts.OFFSET.ROTATION2,u=Ts.OFFSET.ROTATION3,p=Ts.OFFSET.FDC0,m=Ts.OFFSET.FDC1,g=Ts.OFFSET.FDC2,A=Ts.OFFSET.OPACITY,f=[];for(let e=0;e<45;e++)f[e]=Ts.OFFSET.FRC0+e;return function(n,S,C,y=0,x=0){x=Math.min(x,C.sphericalHarmonicsDegree),gi.readSplat(n,C,S,y,e);const v=Ts.createSplat(x);if(void 0!==e[Xs]?(v[a]=Math.exp(e[Xs]),v[o]=Math.exp(e[$s]),v[l]=Math.exp(e[Zs])):(v[a]=.01,v[o]=.01,v[l]=.01),void 0!==e[oi]?(v[p]=255*e[oi],v[m]=255*e[li],v[g]=255*e[ci]):void 0!==e[di]?(v[p]=255*e[di],v[m]=255*e[ui],v[g]=255*e[pi]):(v[p]=0,v[m]=0,v[g]=0),void 0!==e[hi]&&(v[A]=1/(1+Math.exp(-e[hi]))*255),v[p]=ze(Math.floor(v[p]),0,255),v[m]=ze(Math.floor(v[m]),0,255),v[g]=ze(Math.floor(v[g]),0,255),v[A]=ze(Math.floor(v[A]),0,255),x>=1&&void 0!==e[mi]){for(let t=0;t<9;t++)v[f[t]]=e[C.sphericalHarmonicsDegree1Fields[t]];if(x>=2)for(let t=0;t<15;t++)v[f[9+t]]=e[C.sphericalHarmonicsDegree2Fields[t]]}return t.set(e[ei],e[ti],e[si],e[ii]),t.normalize(),v[c]=t.x,v[h]=t.y,v[d]=t.z,v[u]=t.w,v[s]=e[ni],v[i]=e[ri],v[r]=e[ai],v}}();static readSplat(e,t,s,i,n){return js.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 Ai{static parseToUncompressedSplatArray(e,t=0){return(new gi).parseToUncompressedSplatArray(e,t)}}const fi=ke("PlyLoader");function Si(e,t,i,n,r,a,o,l){try{return t?Us.getStandardGenerator(i,n,r,a,o,l).generateFromUncompressedSplatArray(e):_s.generateFromUncompressedSplatArrays([e],i,0,new s)}catch(e){throw new De(`Failed to finalize splat data: ${e.message}`,"splatData",e)}}class Ci{static loadFromURL(e,t,i,n,r,a,o=!0,l=0,c,h,d,u,p){try{pt(e)}catch(t){throw fi.error("Invalid URL provided to loadFromURL",{fileName:e,error:t}),t}t&&vt(t,"onProgress",!1),n&&vt(n,"onProgressiveLoadSectionProgress",!1),fi.info("Loading PLY from URL",{fileName:e,optimizeSplatData:o,outSphericalHarmonicsDegree:l});let m=i?Ce.DirectToSplatBuffer:Ce.DirectToSplatArray;o&&(m=Ce.DirectToSplatArray);const g=ee.ProgressiveLoadSectionSize,A=_s.HeaderSizeBytes+_s.SectionHeaderSizeBytes;let f,S,C,y=0,x=0,v=!1,I=!1;const b=We();let w,B=0,T=0,D=0,E="",M=null,R=[];const F=new TextDecoder,P=new gi;if(t)try{t(0,"0%",ye.Downloading)}catch(e){fi.warn("Error in onProgress callback",e)}return Oe(e,(e,i,r)=>{const a=e>=100;if(r&&(R.push({data:r,sizeBytes:r.byteLength,startBytes:D,endBytes:D+r.byteLength}),D+=r.byteLength),m===Ce.DownloadBeforeProcessing)a&&b.resolve(R);else{if(!v&&(E+=F.decode(r),js.checkTextForEndHeader(E))){try{M=P.decodeHeaderText(E),y=M.splatCount,I=!0,fi.debug("PLY header decoded",{splatCount:y,sphericalHarmonicsDegree:M.sphericalHarmonicsDegree}),l=Math.min(l,M.sphericalHarmonicsDegree)}catch(e){const t=new De(`Failed to decode PLY header: ${e.message}`,"headerText",e);return fi.error("Header parsing failed",t),void b.reject(t)}const e=_s.CompressionLevels[0].SphericalHarmonicsDegrees[l],t=A+e.BytesPerSplat*y;m===Ce.DirectToSplatBuffer?(S=new ArrayBuffer(t),_s.writeHeaderToBuffer({versionMajor:_s.CurrentMajorVersion,versionMinor:_s.CurrentMinorVersion,maxSectionCount:1,sectionCount:1,maxSplatCount:y,splatCount:x,compressionLevel:0,sceneCenter:new s},S)):w=new Ts(l),B=M.headerSizeBytes,T=M.headerSizeBytes,v=!0}if(v&&I){if(R.length>0&&(f=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}(R,f),D-B>g||a)){const e=D-T,t=Math.floor(e/M.bytesPerSplat),s=t*M.bytesPerSplat,i=e-s,r=x+t,o=T-R[0].startBytes,c=new DataView(f,o,s),h=_s.CompressionLevels[0].SphericalHarmonicsDegrees[l],d=x*h.BytesPerSplat+A;try{m===Ce.DirectToSplatBuffer?P.parseToUncompressedSplatBufferSection(M,0,t-1,c,0,S,d,l):P.parseToUncompressedSplatArraySection(M,0,t-1,c,0,w,l)}catch(e){const s=new De(`Failed to parse splat data section: ${e.message}`,"splatData",e);return fi.error("Splat data parsing failed",{splatCount:x,addedSplatCount:t,error:e}),void b.reject(s)}if(x=r,m===Ce.DirectToSplatBuffer&&(C||(_s.writeSectionHeaderToBuffer({maxSplatCount:y,splatCount:x,bucketSize:0,bucketCount:0,bucketBlockSize:0,compressionScaleRange:0,storageSizeBytes:0,fullBucketCount:0,partiallyFilledBucketCount:0,sphericalHarmonicsDegree:l},0,S,_s.HeaderSizeBytes),C=new _s(S,!1)),C.updateLoadedCounts(1,x),n&&n(C,a)),B+=g,T+=s,0===i)R=[];else{let e=[],t=0;for(let s=R.length-1;s>=0;s--){const n=R[s];if(t+=n.sizeBytes,e.unshift(n),t>=i)break}R=e}}a&&(m===Ce.DirectToSplatBuffer?b.resolve(C):b.resolve(w))}}if(t)try{t(e,i,ye.Downloading)}catch(e){fi.warn("Error in onProgress callback",e)}},!1,c).then(()=>{if(t)try{t(0,"0%",ye.Processing)}catch(e){fi.warn("Error in onProgress callback",e)}return b.promise}).then(s=>{if(t)try{t(100,"100%",ye.Done)}catch(e){fi.warn("Error in onProgress callback",e)}if(fi.debug("PLY data loaded successfully",{internalLoadType:m,splatCount:s?.splatCount||"unknown"}),m===Ce.DownloadBeforeProcessing){const t=R.map(e=>e.data);return new Blob(t).arrayBuffer().then(e=>Ci.loadFromFileData(e,r,a,o,l,h,d,u,p)).catch(t=>{throw new we(`Failed to process downloaded PLY data: ${t.message}`,e,t)})}return m===Ce.DirectToSplatBuffer?s:Ve(()=>Si(s,o,r,a,h,d,u,p))}).catch(t=>{if(t instanceof Ie||t instanceof be||t instanceof De||t instanceof we)throw fi.error("PLY loading failed",{fileName:e,errorCode:t.code}),t;throw fi.error("Unexpected error loading PLY",{fileName:e,error:t}),new we(`Unexpected error loading PLY file: ${t.message}`,e,t)})}static loadFromFileData(e,t,s,i,n=0,r,a,o,l){try{yt(e,"plyFileData")}catch(e){return fi.error("Invalid PLY file data",e),Promise.reject(e)}return fi.info("Loading PLY from file data",{sizeBytes:e.byteLength,optimizeSplatData:i,outSphericalHarmonicsDegree:n}),Ve(()=>{try{return Ai.parseToUncompressedSplatArray(e,n)}catch(e){throw new De(`Failed to parse PLY file data: ${e.message}`,"plyFileData",e)}}).then(e=>(fi.debug("PLY parsed successfully",{splatCount:e?.splatCount||"unknown"}),Si(e,i,t,s,r,a,o,l))).catch(e=>{if(e instanceof Ie||e instanceof De)throw fi.error("PLY file data loading failed",{errorCode:e.code}),e;throw fi.error("Unexpected error loading PLY from file data",e),new De(`Unexpected error parsing PLY data: ${e.message}`,"plyFileData",e)})}}const yi=new e.Vector3(1,0,0),xi=new e.Vector3(0,1,0),vi=new e.Vector3(0,0,1);class Ii{constructor(t=new e.Vector3,s=new e.Vector3){this.origin=new e.Vector3,this.direction=new e.Vector3,this.setParameters(t,s)}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 t=new e.Vector3,s=[],i=[],n=[];return function(e,r){if(i[0]=this.origin.x,i[1]=this.origin.y,i[2]=this.origin.z,n[0]=this.direction.x,n[1]=this.direction.y,n[2]=this.direction.z,this.boxContainsPoint(e,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==n[a])continue;const o=0==a?yi:1==a?xi:vi,l=n[a]<0?e.max:e.min;let c=-Math.sign(n[a]);s[0]=0==a?l.x:1==a?l.y:l.z;let h=s[0]-i[a];if(h*c<0){const l=(a+1)%3,d=(a+2)%3;if(s[2]=n[l]/n[a]*h+i[l],s[1]=n[d]/n[a]*h+i[d],t.set(s[a],s[d],s[l]),this.boxContainsPoint(e,t,1e-4))return r&&(r.origin.copy(t),r.normal.copy(o).multiplyScalar(c),r.distance=t.sub(this.origin).length()),!0}}return!1}}();intersectSphere=function(){const t=new e.Vector3;return function(e,s,i){t.copy(e).sub(this.origin);const n=t.dot(this.direction),r=n*n,a=t.dot(t)-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(e).normalize(),i.distance=d),!0}}()}class bi{constructor(){this.origin=new e.Vector3,this.normal=new e.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 bi;return e.origin.copy(this.origin),e.normal.copy(this.normal),e.distance=this.distance,e.splatIndex=this.splatIndex,e}}class wi{constructor(e,t,s=!1){this.ray=new Ii(e,t),this.raycastAgainstTrueSplatEllipsoid=s}setFromCameraAndScreenPosition=function(){const t=new e.Vector2;return function(e,s,i){if(t.x=s.x/i.x*2-1,t.y=(i.y-s.y)/i.y*2-1,e.isPerspectiveCamera)this.ray.origin.setFromMatrixPosition(e.matrixWorld),this.ray.direction.set(t.x,t.y,.5).unproject(e).sub(this.ray.origin).normalize(),this.camera=e;else{if(!e.isOrthographicCamera)throw new Error("Raycaster::setFromCameraAndScreenPosition() -> Unsupported camera type");this.ray.origin.set(t.x,t.y,(e.near+e.far)/(e.near-e.far)).unproject(e),this.ray.direction.set(0,0,-1).transformDirection(e.matrixWorld),this.camera=e}}}();intersectSplatMesh=function(){const t=new e.Matrix4,s=new e.Matrix4,i=new e.Matrix4,n=new Ii,r=new e.Vector3;return function(e,a=[]){const o=e.getSplatTree();if(o){for(let l=0;l<o.subTrees.length;l++){const c=o.subTrees[l];s.copy(e.matrixWorld),e.dynamicMode&&(e.getSceneTransform(l,i),s.multiply(i)),t.copy(s).invert(),n.origin.copy(this.ray.origin).applyMatrix4(t),n.direction.copy(this.ray.origin).add(this.ray.direction),n.direction.applyMatrix4(t).sub(n.origin).normalize();const h=[];c.rootNode&&this.castRayAtSplatTreeNode(n,o,c.rootNode,h),h.forEach(e=>{e.origin.applyMatrix4(s),e.normal.applyMatrix4(s).normalize(),e.distance=r.copy(e.origin).sub(this.ray.origin).length()}),a.push(...h)}return a.sort((e,t)=>e.distance>t.distance?1:-1),a}}}();castRayAtSplatTreeNode=function(){const t=new e.Vector4,s=new e.Vector3,i=new e.Vector3,n=new e.Quaternion,r=new bi,a=1e-7,o=new e.Vector3(0,0,0),l=new e.Matrix4,c=new e.Matrix4,h=new e.Matrix4,d=new e.Matrix4,u=new e.Matrix4,p=new Ii;return function(e,m,g,A=[]){if(e.intersectBox(g.boundingBox)){if(g.data&&g.data.indexes&&g.data.indexes.length>0)for(let f=0;f<g.data.indexes.length;f++){const S=g.data.indexes[f],C=m.splatMesh.getSceneIndexForSplat(S);if(m.splatMesh.getScene(C).visible&&(m.splatMesh.getSplatColor(S,t),m.splatMesh.getSplatCenter(S,s),m.splatMesh.getSplatScaleAndRotation(S,i,n),!(i.x<=a||i.y<=a||m.splatMesh.splatRenderMode===Z.ThreeD&&i.z<=a)))if(this.raycastAgainstTrueSplatEllipsoid){c.makeScale(i.x,i.y,i.z),h.makeRotationFromQuaternion(n);const a=2*Math.log10(t.w);if(l.makeScale(a,a,a),u.copy(l).multiply(h).multiply(c),d.copy(u).invert(),p.origin.copy(e.origin).sub(s).applyMatrix4(d),p.direction.copy(e.origin).add(e.direction).sub(s),p.direction.applyMatrix4(d).sub(p.origin).normalize(),p.intersectSphere(o,1,r)){const e=r.clone();e.splatIndex=S,e.origin.applyMatrix4(u).add(s),A.push(e)}}else{let t=i.x+i.y,n=2;if(m.splatMesh.splatRenderMode===Z.ThreeD&&(t+=i.z,n=3),t/=n,e.intersectSphere(s,t,r)){const e=r.clone();e.splatIndex=S,A.push(e)}}}if(g.children&&g.children.length>0)for(let t of g.children)this.castRayAtSplatTreeNode(e,m,t,A);return A}}}()}const Bi="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";function Ti(e){let t,s,i,n,r,a,o,l,c,h,d,u,p,m,g,A,f,S,C,y;e.onmessage=x=>{if(x.data.centers){let e=x.data.centers,t=x.data.sceneIndexes;n?new Int32Array(s,m+x.data.range.from*y.BytesPerInt*4,4*x.data.range.count).set(new Int32Array(e)):new Float32Array(s,m+x.data.range.from*y.BytesPerFloat*4,4*x.data.range.count).set(new Float32Array(e)),r&&new Uint32Array(s,c+4*x.data.range.from,x.data.range.count).set(new Uint32Array(t)),C=x.data.range.from+x.data.range.count}else if(x.data.sort){const v=Math.min(x.data.sort.splatRenderCount||0,C),I=Math.min(x.data.sort.splatSortCount||0,C),b=x.data.sort.usePrecomputedDistances;let w,B,T;i||(w=x.data.sort.indexesToSort,T=x.data.sort.transforms,b&&(B=x.data.sort.precomputedDistances)),function(C,x,v,I,b,w,B){const T=performance.now();if(!i&&(new Uint32Array(s,o,b.byteLength/y.BytesPerInt).set(b),new Float32Array(s,h,B.byteLength/y.BytesPerFloat).set(B),I)){let e;e=n?new Int32Array(s,d,w.byteLength/y.BytesPerInt):new Float32Array(s,d,w.byteLength/y.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,x,a,I,n,r);const D={sortDone:!0,splatSortCount:C,splatRenderCount:x,sortTime:0};if(!i){const e=new Uint32Array(s,l,x);(!f||f.length<x)&&(f=new Uint32Array(x)),f.set(e),D.sortedIndexes=f}const E=performance.now();D.sortTime=E-T,e.postMessage(D)}(I,v,x.data.sort.modelViewProj,b,w,B,T)}else if(x.data.init){y=x.data.init.Constants,a=x.data.init.splatCount,i=x.data.init.useSharedMemory,n=x.data.init.integerBasedSort,r=x.data.init.dynamicMode,S=x.data.init.distanceMapRange,C=0;const A=n?4*y.BytesPerInt:4*y.BytesPerFloat,f=new Uint8Array(x.data.init.sorterWasmBytes),v=16*y.BytesPerFloat,I=a*y.BytesPerInt,b=a*A,w=v,B=n?a*y.BytesPerInt:a*y.BytesPerFloat,T=a*y.BytesPerInt,D=a*y.BytesPerInt,E=n?S*y.BytesPerInt*2:S*y.BytesPerFloat*2,M=r?a*y.BytesPerInt:0,R=r?y.MaxScenes*v:0,F=32*y.MemoryPageSize,P=I+b+w+B+T+E+D+M+R+F,k=Math.floor(P/y.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 Di=ke("Viewer");class Ei{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 Mi{constructor(e){}show(){}hide(){}setContainer(e){}setProgress(e){}}class Ri{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(e={}){if(e.cameraUp||(e.cameraUp=[0,1,0]),this.cameraUp=(new s).fromArray(e.cameraUp),e.initialCameraPosition||(e.initialCameraPosition=[0,10,15]),this.initialCameraPosition=(new s).fromArray(e.initialCameraPosition),e.initialCameraRotation||(e.initialCameraRotation=[0,0,0]),this.initialCameraRotation=(new s).fromArray(e.initialCameraRotation),this.backgroundColor=e.backgroundColor,e.initialCameraLookAt||(e.initialCameraLookAt=[0,0,0]),this.initialCameraLookAt=(new s).fromArray(e.initialCameraLookAt),this.dropInMode=e.dropInMode||!1,void 0!==e.selfDrivenMode&&null!==e.selfDrivenMode||(e.selfDrivenMode=!0),this.selfDrivenMode=e.selfDrivenMode&&!this.dropInMode,this.selfDrivenUpdateFunc=this.selfDrivenUpdate.bind(this),void 0===e.useBuiltInControls&&(e.useBuiltInControls=!0),this.useBuiltInControls=e.useBuiltInControls,this.rootElement=e.rootElement,this.canvas=e.threejsCanvas,this.ignoreDevicePixelRatio=e.ignoreDevicePixelRatio||!1,this.devicePixelRatio=this.ignoreDevicePixelRatio?1:window.devicePixelRatio||1,this.halfPrecisionCovariancesOnGPU=e.halfPrecisionCovariancesOnGPU||!1,this.threeScene=e.threeScene,this.renderer=e.renderer,this.camera=e.camera,this.gpuAcceleratedSort=e.gpuAcceleratedSort||!1,void 0!==e.integerBasedSort&&null!==e.integerBasedSort||(e.integerBasedSort=!0),this.integerBasedSort=e.integerBasedSort,void 0!==e.sharedMemoryForWorkers&&null!==e.sharedMemoryForWorkers||(e.sharedMemoryForWorkers=!0),this.sharedMemoryForWorkers=!1,this.dynamicScene=!!e.dynamicScene,this.antialiased=e.antialiased||!1,this.kernel2DSize=void 0===e.kernel2DSize?.3:e.kernel2DSize,this.renderMode=e.renderMode||Y.Always,this.sceneRevealMode=e.sceneRevealMode||$.Default,this.focalAdjustment=e.focalAdjustment||1,this.maxScreenSpaceSplatSize=e.maxScreenSpaceSplatSize||1024,this.logLevel=e.logLevel||j.None,this.sphericalHarmonicsDegree=e.sphericalHarmonicsDegree||0,this.enableOptionalEffects=e.enableOptionalEffects||!1,void 0!==e.enableSIMDInSort&&null!==e.enableSIMDInSort||(e.enableSIMDInSort=!0),this.enableSIMDInSort=e.enableSIMDInSort,void 0!==e.inMemoryCompressionLevel&&null!==e.inMemoryCompressionLevel||(e.inMemoryCompressionLevel=0),this.inMemoryCompressionLevel=e.inMemoryCompressionLevel,void 0!==e.optimizeSplatData&&null!==e.optimizeSplatData||(e.optimizeSplatData=!0),this.optimizeSplatData=e.optimizeSplatData,void 0!==e.freeIntermediateSplatData&&null!==e.freeIntermediateSplatData||(e.freeIntermediateSplatData=!1),this.freeIntermediateSplatData=e.freeIntermediateSplatData,je()){const e=Ye();e.major<17&&(this.enableSIMDInSort=!1),e.major<16&&(this.sharedMemoryForWorkers=!1)}void 0!==e.splatRenderMode&&null!==e.splatRenderMode||(e.splatRenderMode=Z.ThreeD),this.splatRenderMode=e.splatRenderMode,this.sceneFadeInRateMultiplier=e.sceneFadeInRateMultiplier||1,this.splatSortDistanceMapPrecision=e.splatSortDistanceMapPrecision||ee.DefaultSplatSortDistanceMapPrecision;const t=this.integerBasedSort?20:24;this.splatSortDistanceMapPrecision=ze(this.splatSortDistanceMapPrecision,10,t),this.onSplatMeshChangedCallback=null,this.createSplatMesh(),this.controls=null,this.perspectiveControls=null,this.orthographicControls=null,this.orthographicCamera=null,this.perspectiveCamera=null,this.showMeshCursor=!1,this.showControlPlane=!1,this.showInfo=!1,this.sceneHelper=null,this.sortWorker=null,this.sortRunning=!1,this.splatRenderCount=0,this.splatSortCount=0,this.lastSplatSortCount=0,this.sortWorkerIndexesToSort=null,this.sortWorkerSortedIndexes=null,this.sortWorkerPrecomputedDistances=null,this.sortWorkerTransforms=null,this.preSortMessages=[],this.runAfterNextSort=[],this.selfDrivenModeRunning=!1,this.splatRenderReady=!1,this.raycaster=new wi,this.infoPanel=null,this.startInOrthographicMode=!1,this.currentFPS=0,this.lastSortTime=0,this.consecutiveRenderFrames=0,this.previousCameraTarget=new s,this.nextCameraTarget=new s,this.mousePosition=new m,this.mouseDownPosition=new m,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 Ei(null,this.rootElement||document.body),this.loadingSpinner.hide(),this.loadingProgressBar=new Mi(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 ws(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 L,this.sceneHelper=new Ri(this.threeScene),this.sceneHelper.setupMeshCursor(),this.sceneHelper.setupFocusMarker(),this.sceneHelper.setupControlPlane(),this.loadingProgressBar.setContainer(this.rootElement),this.loadingSpinner.setContainer(this.rootElement),this.initialized=!0)}setupCamera(){if(!this.usingExternalCamera){const e=new m;this.getRenderDimensions(e),this.perspectiveCamera=new U(50,e.x/e.y,.1,1e3),this.orthographicCamera=new H(e.x/-2,e.x/2,e.y/2,e.y/-2,.1,1e3),this.camera=this.startInOrthographicMode?this.orthographicCamera:this.perspectiveCamera,this.camera.position.copy(this.initialCameraPosition),this.camera.rotateX(O.degToRad(this.initialCameraRotation.x)),this.camera.rotateY(O.degToRad(this.initialCameraRotation.y)),this.camera.rotateZ(O.degToRad(this.initialCameraRotation.z))}}setupRenderer(){if(!this.usingExternalRenderer){const e=new m;this.getRenderDimensions(e),this.renderer=new z({antialias:!1,precision:"highp",canvas:this.canvas}),this.renderer.setPixelRatio(this.devicePixelRatio),this.renderer.autoClear=!0,this.renderer.setClearColor(this.backgroundColor,1),this.renderer.setSize(e.x,e.y),this.resizeObserver=new ResizeObserver(()=>{this.getRenderDimensions(e),this.renderer.setSize(e.x,e.y),this.forceRenderNextFrame()}),this.resizeObserver.observe(this.rootElement),this.rootElement.appendChild(this.renderer.domElement)}}setupControls(){if(this.useBuiltInControls){this.usingExternalCamera?this.camera.isOrthographicCamera?this.orthographicControls=new K(this.camera,this.renderer.domElement):this.perspectiveControls=new K(this.camera,this.renderer.domElement):(this.perspectiveControls=new K(this.perspectiveCamera,this.renderer.domElement),this.orthographicControls=new K(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 s;tempMatrixLeft=new i;tempMatrixRight=new i;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=Qe()}onMouseUp=function(){const e=new m;return function(t){e.copy(this.mousePosition).sub(this.mouseDownPosition),Qe()-this.mouseDownTime<.5&&e.length()<2&&this.onMouseClick(t)}}();onMouseClick(e){this.mousePosition.set(e.offsetX,e.offsetY),this.checkForFocalPointChange()}checkPointRenderDimensions=new m;checkPointToNewFocalPoint=new s;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=Qe())}};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 e=new s;return function(t,s,i){const n=1/(.001*s.zoom);e.copy(i.target).sub(t.position).normalize().multiplyScalar(n).negate(),t.position.copy(i.target).add(e)}}();static setCameraZoomFromPosition=function(){const e=new s;return function(t,s,i){const n=e.copy(i.target).sub(s.position).length();t.zoom=1/(.001*n)}}();updateSplatMesh=function(){const e=new m;return function(){if(this.splatMesh&&this.splatMesh.getSplatCount()>0){this.splatMesh.updateVisibleRegionFadeDistance(this.sceneRevealMode),this.splatMesh.updateTransforms(),this.getRenderDimensions(e);const t=.5*this.camera.projectionMatrix.elements[0]*this.devicePixelRatio*e.x,s=.5*this.camera.projectionMatrix.elements[5]*this.devicePixelRatio*e.y,i=this.camera.isOrthographicCamera?1/this.devicePixelRatio:1,n=this.focalAdjustment*i,r=1/n;this.adjustForWebXRStereo(e),this.splatMesh.updateUniforms(e,t*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&&(Di.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:X(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===ye.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===ye.Processing&&(Di.debug("loaderStatus === LoaderStatus.Processing"),this.loadingSpinner.setMessageForTask(r,"Processing splats..."))};let o=!1,l=0;const c=(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%",ye.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%",ye.Processing),c(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=qe(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 He||"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&&Ve(()=>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=qe(u),m=qe(u);return this.addSplatSceneDownloadPromise(d),this.setSplatSceneDownloadAndBuildPromise(m.promise),d.then(()=>{this.removeSplatSceneDownloadPromise(d)}).catch(e=>{Di.error("Viewer::addSplatScene actual error:",e),this.clearSplatSceneDownloadAndBuildPromise(),this.removeSplatSceneDownloadPromise(d);const t=e instanceof He||"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===ye.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 c=[];for(let t=0;t<e.length;t++){const s=e[t],i=void 0!==s.format&&null!==s.format?s.format:X(s.path),n=this.downloadSplatSceneToSplatBuffer(s.path,s.splatAlphaRemovalThreshold,a.bind(this,t),!1,void 0,i,s.headers,l);c.push(n)}const h=Promise.all(c).then(i=>(t&&this.loadingSpinner.removeTask(r),s&&s(0,"0%",ye.Processing),this.addSplatBuffers(i,e,!0,t,t,!1,!1).then(()=>{s&&s(100,"100%",ye.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(h),h}downloadSplatSceneToSplatBuffer(e,t=1,s=void 0,i=!1,n=void 0,r,a){const o=!i&&this.optimizeSplatData;try{if(r===J.Ply)return Ci.loadFromURL(e,s,i,n,t,this.inMemoryCompressionLevel,o,this.sphericalHarmonicsDegree,a)}catch(e){throw e instanceof Bs?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===J.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...")),Ve(()=>{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>=Ae&&(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=ee.DefaultSplatSortDistanceMapPrecision){const a=new Worker(URL.createObjectURL(new Blob(["(",Ti.toString(),")(self)"],{type:"application/javascript"})));let o="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";const l=je()?Ye():null;s||t?s?t||l&&l.major<=16&&l.minor<4&&(o="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"):o=Bi:(o=Bi,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:ee.BytesPerFloat,BytesPerInt:ee.BytesPerInt,MemoryPageSize:ee.MemoryPageSize,MaxScenes:ee.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>=j.Info&&Di.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*ee.MaxScenes)):(this.sortWorkerIndexesToSort=new Uint32Array(i),this.sortWorkerPrecomputedDistances=new t(i),this.sortWorkerTransforms=new Float32Array(16*ee.MaxScenes));for(let e=0;e<s;e++)this.sortWorkerIndexesToSort[e]=e;if(this.sortWorker.maxSplatCount=i,this.logLevel>=j.Info){Di.info("Sorting web worker ready.");const e=this.splatMesh.getSplatDataTextures(),t=e.covariances.size,s=e.centerColors.size;Di.info("Covariances texture size: "+t.x+" x "+t.y),Di.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=$.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&&(Ne(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 e=0;const t=new s,i=new n,r=1e-4;return function(){if(!this.initialized||!this.splatRenderReady||this.isDisposingOrDisposed())return!1;let s=!1,n=!1;if(this.camera){const e=this.camera.position,s=this.camera.quaternion;n=Math.abs(e.x-t.x)>r||Math.abs(e.y-t.y)>r||Math.abs(e.z-t.z)>r||Math.abs(s.x-i.x)>r||Math.abs(s.y-i.y)>r||Math.abs(s.z-i.z)>r||Math.abs(s.w-i.w)>r}return s=this.renderMode!==Y.Never&&(0===e||this.splatMesh.visibleRegionChanging||n||this.renderMode===Y.Always||!0===this.dynamicMode||this.renderNextFrame),this.camera&&(t.copy(this.camera.position),i.copy(this.camera.quaternion)),e++,s}}();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=Qe();fpsFrameCount=0;updateFPS=()=>{if(this.consecutiveRenderFrames>60){const e=Qe();e-this.lastCalcTime>=1?(this.currentFPS=this.fpsFrameCount,this.fpsFrameCount=0,this.lastCalcTime=e):this.fpsFrameCount++}else this.currentFPS=null};updateForRendererSizeChanges=function(){const e=new m,t=new m;let s;return function(){this.usingExternalCamera||(this.renderer.getSize(t),void 0!==s&&s===this.camera.isOrthographicCamera&&t.x===e.x&&t.y===e.y||(this.camera.isOrthographicCamera?(this.camera.left=-t.x/2,this.camera.right=t.x/2,this.camera.top=t.y/2,this.camera.bottom=-t.y/2):this.camera.aspect=t.x/t.y,this.camera.updateProjectionMatrix(),e.copy(t),s=this.camera.isOrthographicCamera))}}();timingSensitiveUpdates=function(){let e;return function(){const t=Qe();e||(e=t);const s=t-e;this.updateCameraTransition(t),this.updateFocusMarker(s),e=t}}();tempCameraTarget=new s;toPreviousTarget=new s;toNextTarget=new s;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 e=new m;let t=!1;return function(s){if(this.getRenderDimensions(e),this.transitioningCameraTarget){this.sceneHelper.setFocusMarkerVisibility(!0);const i=Math.max(this.sceneHelper.getFocusMarkerOpacity(),0);let n=Math.min(i+.4*s,1);this.sceneHelper.setFocusMarkerOpacity(n),this.sceneHelper.updateFocusMarker(this.nextCameraTarget,this.camera,e),t=!0,this.forceRenderNextFrame()}else{let i;if(i=t?1:Math.min(this.sceneHelper.getFocusMarkerOpacity(),1),i>0){this.sceneHelper.updateFocusMarker(this.nextCameraTarget,this.camera,e);let t=Math.max(i-.12*s,0);this.sceneHelper.setFocusMarkerOpacity(t),0===t&&this.sceneHelper.setFocusMarkerVisibility(!1)}i>0&&this.forceRenderNextFrame(),t=!1}}}();updateMeshCursor=function(){const e=[],t=new m;return function(){this.showMeshCursor?(this.forceRenderNextFrame(),this.getRenderDimensions(t),e.length=0,this.raycaster.setFromCameraAndScreenPosition(this.camera,this.mousePosition,t),this.raycaster.intersectSplatMesh(this.splatMesh,e),e.length>0?(this.sceneHelper.setMeshCursorVisibility(!0),this.sceneHelper.positionAndOrientMeshCursor(e[0].origin,this.camera)):this.sceneHelper.setMeshCursorVisibility(!1)):(this.sceneHelper.getMeschCursorVisibility()&&this.forceRenderNextFrame(),this.sceneHelper.setMeshCursorVisibility(!1))}}();updateInfoPanel=function(){const e=new m;return function(){if(!this.showInfo)return;const t=this.splatMesh.getSplatCount();this.getRenderDimensions(e),this.controls&&this.controls.target,this.showMeshCursor&&this.sceneHelper.meshCursor.position,t>0&&this.splatRenderCount}}();updateControlPlane(){this.showControlPlane?(this.sceneHelper.setControlPlaneVisibility(!0),this.sceneHelper.positionAndOrientControlPlane(this.controls.target,this.camera.up)):this.sceneHelper.setControlPlaneVisibility(!1)}mvpMatrix=new i;cameraPositionArray=[];lastSortViewDir=new s(0,0,-1);sortViewDir=new s(0,0,-1);lastSortViewPos=new s;sortViewOffset=new s;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 e=[];let t=null;const n=new s,r=new s,a=new s,o=new i,l=new i,c=new i,h=new s,d=new s(0,0,-1),u=new s,p=e=>u.copy(e.max).sub(e.min).length();return function(s=!1){this.getRenderDimensions(h);const i=h.y/2/Math.tan(this.camera.fov/2*O.DEG2RAD),u=Math.atan(h.x/2/i),m=Math.atan(h.y/2/i),g=Math.cos(u),A=Math.cos(m),f=this.splatMesh.getSplatTree();if(f){l.copy(this.camera.matrixWorld).invert(),this.splatMesh.dynamicMode||l.multiply(this.splatMesh.matrixWorld);let t=0,i=0;for(let h=0;h<f.subTrees.length;h++){const u=f.subTrees[h];o.copy(l),this.splatMesh.dynamicMode&&(this.splatMesh.getSceneTransform(h,c),o.multiply(c));const m=u.nodesWithIndexes.length;for(let l=0;l<m;l++){const c=u.nodesWithIndexes[l];if(!c.data||!c.data.indexes||0===c.data.indexes.length)continue;a.copy(c.center).applyMatrix4(o);const h=a.length();a.normalize(),n.copy(a).setX(0).normalize(),r.copy(a).setY(0).normalize();const m=d.dot(r),f=d.dot(n),S=p(c);!s&&(m<g-.6||f<A-.6)&&h>S||(i+=c.data.indexes.length,e[t]=c,c.data.distanceToNode=h,t++)}}e.length=t,e.sort((e,t)=>e.data.distanceToNode<t.data.distanceToNode?-1:1);let h=i*ee.BytesPerInt;for(let s=0;s<t;s++){const t=e[s],i=t.data.indexes.length,n=i*ee.BytesPerInt;new Uint32Array(this.sortWorkerIndexesToSort.buffer,h-n,i).set(t.data.indexes),h-=n}return{splatRenderCount:i,shouldSortAll:!1}}{const e=this.splatMesh.getSplatCount();if(!t||t.length!==e){t=new Uint32Array(e);for(let s=0;s<e;s++)t[s]=s}return this.sortWorkerIndexesToSort.set(t),{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 e=new Float32Array(this.avatarMesh.geometry.attributes.position.array);if(this.splatMesh.bonesNum=5,this.skinModel.skeleton.update(),this.boneRoot.updateMatrixWorld(!0),this.splatMesh.geometry.getAttribute("splatIndex")&&!1===this.setSkinAttibutes){this.setSkinAttibutes=!0;const e=this.splatMesh.geometry,t=this.skinModel.geometry.attributes.skinIndex,s=this.skinModel.geometry.attributes.skinWeight,i=new u(new t.array.constructor(t.array),4,t.normalized,1),n=new u(new s.array.constructor(s.array),4,s.normalized,1);i.setUsage(p),n.setUsage(p),e.setAttribute("skinIndex",i),e.setAttribute("skinWeight",n)}this.splatMesh.morphedMesh=e;let t=this.splatMesh.morphedMesh.length/3;null!=this.splatMesh.splatDataTextures.flameModel&&this.splatMesh.updateTetureAfterBSAndSkeleton(0,t-1,!1)}}const Fi=ke("GaussianSplatRenderer"),Pi=0,ki=1.8,_i=1,Li=-10,Ui=0,Hi=0,Oi="ffffff",zi={offset:{},scale:{}},Qi={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(e,t,i={}){try{bt(e,"container"),pt(t),i.downloadProgress&&vt(i.downloadProgress,"options.downloadProgress",!1),i.loadProgress&&vt(i.loadProgress,"options.loadProgress",!1),i.getChatState&&vt(i.getChatState,"options.getChatState",!1),i.getExpressionData&&vt(i.getExpressionData,"options.getExpressionData",!1),i.backgroundColor&&It(i.backgroundColor,"options.backgroundColor"),Fi.info("Initializing GaussianSplatRenderer",{assetPath:t});const n=t;let r,a,o,l;try{const e=new URL(n,"undefined"!=typeof window?window.location.href:void 0).pathname.match(/\/([^/]+?)\.zip/);if(r=e?.[1],!r)throw new Ie("Character model name could not be extracted from path. Expected format: /path/name.zip","assetPath")}catch(e){if(e instanceof Ie)throw e;throw new Ie(`Invalid asset path format: ${e.message}`,"assetPath",e)}"undefined"!=typeof NProgress&&NProgress.start(),Fi.info("Downloading asset ZIP",{path:n});try{if(a=await fetch(n),!a.ok)throw new be(`Failed to download asset: ${a.statusText}`,a.status)}catch(e){if(e instanceof be)throw e;throw new be(`Network error downloading asset: ${e.message}`,0,e)}if(i.downloadProgress)try{i.downloadProgress(1)}catch(e){Fi.warn("Error in downloadProgress callback",e)}if(i.loadProgress)try{i.loadProgress(.1)}catch(e){Fi.warn("Error in loadProgress callback",e)}"undefined"!=typeof NProgress&&NProgress.done();try{o=await a.arrayBuffer()}catch(e){throw new be(`Failed to read response data: ${e.message}`,0,e)}Fi.debug("Unpacking ZIP archive");try{l=await q.loadAsync(o)}catch(e){throw new we(`Failed to unpack ZIP archive: ${e.message}`,n,e)}let c="";if(Object.values(l.files).forEach(e=>{e.dir&&(c=e.name?.slice(0,e.name?.length-1))}),!c)throw new we("No folder found in ZIP archive. Expected ZIP to contain a folder with model files.",n);Fi.debug("Found model folder in ZIP",{fileName:c}),Fi.debug("Creating GaussianSplatRenderer instance");const h=new GaussianSplatRenderer(e,l),d=Rt.set(Pi??0,ki??0,_i??1),u=new s(Li??0,Ui??0,Hi??0);Fi.debug("Camera setup",{position:{x:d.x,y:d.y,z:d.z},rotation:{x:u.x,y:u.y,z:u.z}});let p,m=16777215;try{if(Oi){const e=parseInt(Oi,16);isNaN(e)?Fi.warn("Invalid backgroundColor in config, using default",{value:Oi}):m=e}i?.backgroundColor&&(h.isHexColorStrict(i.backgroundColor)?m=parseInt(i.backgroundColor,16):Fi.warn("Invalid backgroundColor option, using config value",{value:i.backgroundColor}))}catch(e){Fi.warn("Error parsing backgroundColor, using default",e)}Fi.debug("Background color set",{backgroundColor:m.toString(16)}),h.getChatState=i?.getChatState,h.getExpressionData=i?.getExpressionData,Fi.debug("Creating Viewer instance");try{h.viewer=new Viewer({rootElement:e,threejsCanvas:h._canvas,cameraUp:[0,1,0],initialCameraPosition:[d.x,d.y,d.z],initialCameraRotation:[u.x,u.y,u.z],sphericalHarmonicsDegree:0,backgroundColor:m})}catch(e){throw new Te(`Failed to create Viewer instance: ${e.message}`,e)}Fi.info("Loading model",{fileName:c});try{await h.loadModel(c,Qi,zi)}catch(e){throw new we(`Failed to load model: ${e.message}`,c,e)}if(i.loadProgress)try{i.loadProgress(.2)}catch(e){Fi.warn("Error in loadProgress callback",e)}Fi.debug("Loading offset PLY file");try{p=await h.unpackFileAsBlob(c+"/offset.ply")}catch(e){throw new we(`Failed to load offset.ply: ${e.message}`,c+"/offset.ply",e)}Fi.debug("Checking for iris_occlusion.json");let g=null;try{g=await h._loadJsonFromZip(c+"/iris_occlusion.json"),g?(Fi.info("Iris occlusion configuration loaded",{rightIrisRanges:g.right_iris?.length??0,leftIrisRanges:g.left_iris?.length??0}),h.irisOcclusionConfig=g,h.viewer.irisOcclusionConfig=g):Fi.debug("No iris_occlusion.json found, iris occlusion will be disabled")}catch(e){Fi.warn("Failed to load iris_occlusion.json, continuing without it",{error:e.message}),h.irisOcclusionConfig=null}if(i.loadProgress)try{i.loadProgress(.3)}catch(e){Fi.warn("Error in loadProgress callback",e)}Fi.debug("Adding splat scene");try{await h.viewer.addSplatScene(p,{progressiveLoad:!0,sharedMemoryForWorkers:!1,showLoadingUI:!1,format:J.Ply})}catch(e){throw new Te(`Failed to add splat scene: ${e.message}`,e)}try{h.render()}catch(e){Fi.error("Error in initial render",e)}if(i.loadProgress)try{i.loadProgress(1)}catch(e){Fi.warn("Error in loadProgress callback",e)}return Fi.info("GaussianSplatRenderer initialized successfully"),h}catch(e){if(e instanceof Ie||e instanceof be||e instanceof we||e instanceof Te)throw Fi.error("Initialization failed",{errorCode:e.code,message:e.message}),e;throw Fi.error("Unexpected error during initialization",e),new Te(`Unexpected error initializing GaussianSplatRenderer: ${e.message}`,e)}}static async getInstance(e,t,s={}){return Fi.warn("getInstance() is deprecated. Use create() instead. Each call creates a new instance."),this.create(e,t,s)}constructor(e,t){if(Fi.debug("GaussianSplatRenderer constructor called"),this._disposed=!1,this._blobUrlManager=new Qt,this.zipUrls={urls:new Map,zip:t},this.lastTime=0,this.startTime=0,this.expressionData={},this.chatState=$t.Idle,this._canvas=null,"undefined"!=typeof document&&e){this._canvas=document.createElement("canvas");const{width:t,height:s}=e.getBoundingClientRect();this._canvas.style.visibility="visible",this._canvas.width=t,this._canvas.height=s,e.appendChild(this._canvas),Fi.debug("Canvas setup",{width:t,height:s})}this.clock=new Q,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,Fi.debug("GaussianSplatRenderer instance created")}_assertNotDisposed(){if(this._disposed)throw new Be("GaussianSplatRenderer has been disposed")}dispose(){if(this._disposed)Fi.warn("GaussianSplatRenderer.dispose() called on already disposed instance");else{Fi.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){Fi.error("Error disposing BlobUrlManager",e)}this.zipUrls?.urls&&(this.zipUrls.urls.forEach(e=>{try{URL.revokeObjectURL(e)}catch(t){Fi.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,Fi.debug("GaussianSplatRenderer disposed successfully")}}disposeModel(){if(Fi.debug("Disposing model resources"),this.mixer){try{this.mixer.stopAllAction(),this.viewer?.avatarMesh&&this.mixer.uncacheRoot(this.viewer.avatarMesh)}catch(e){Fi.error("Error disposing animation mixer",e)}this.mixer=null}if(this.animManager){try{this.animManager.dispose()}catch(e){Fi.error("Error disposing animation manager",e)}this.animManager=null}if(this.viewer){try{this.viewer.dispose()}catch(e){Fi.error("Error disposing viewer",e)}this.viewer=null}Fi.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||(Fi.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||(Fi.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&&Fi.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(e,t,s){const[i,n,r]=await Promise.all([this.unpackAndLoadGlb(e+"/skin.glb"),this.unpackAndLoadGlb(e+"/animation.glb"),this.unpackAndLoadJson(e+"/vertex_order.json")]);if(!this.viewer)throw new Error("render viewer is not initialized");let a,o;i.traverse(e=>{e.isSkinnedMesh&&(a=e),e instanceof N&&"hip"===e.name&&(o=e)}),this.viewer.sortedIndexes=r,a&&(this.viewer.gaussianSplatCount=a.geometry.attributes.position.count),this.viewer.avatarMesh=i,this.viewer.skinModel=a,this.viewer.boneRoot=o,this.mixer=new V(i),this.animManager=new hs(this.mixer,n,t),this.motioncfg=s,Array.isArray(n)&&n.length>0&&n[0].duration?this.viewer.totalFrames=Math.floor(30*n[0].duration):this.viewer.totalFrames=1,Fi.debug("Total frames calculated",{totalFrames:this.viewer.totalFrames}),a&&this.viewer.updateMorphTarget(a),this.viewer.threeScene.add(i),i.visible=!1,a&&a.skeleton.computeBoneTexture()}async unpackFileAsBlob(e){if(this._assertNotDisposed(),this.zipUrls.urls.has(e))return Fi.debug("Returning cached blob URL",{path:e}),this.zipUrls.urls.get(e);Fi.debug("Unpacking file from ZIP",{path:e});const t=this.zipUrls.zip?.file(e);if(!t)throw new we(`File not found in ZIP archive: ${e}`,e);let s;try{s=await t.async("blob")}catch(t){throw new we(`Failed to extract file from ZIP: ${t.message}`,e,t)}if(!s)throw new we(`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),Fi.debug("Blob URL created and cached",{path:e,url:n.substring(0,50)}),n}async _loadJsonFromZip(e){this._assertNotDisposed(),Fi.debug("Attempting to load JSON from ZIP",{path:e});const t=this.zipUrls.zip?.file(e);if(!t)return Fi.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 Fi.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 Fi.debug("Using cached GLB URL",{path:e}),this.LoadGLTF(this.zipUrls.urls.get(e));Fi.debug("Unpacking GLB from ZIP",{path:e});const t=this.zipUrls.zip?.file(e);if(!t)throw new we(`GLB file not found in ZIP archive: ${e}`,e);let s;try{s=await t.async("arraybuffer")}catch(t){throw new we(`Failed to extract GLB from ZIP: ${t.message}`,e,t)}if(!s)throw new we(`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),Fi.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((t,s)=>{(new W).load(e,e=>{e.animations.length>0?t(e.animations):t(e.scene)},void 0,e=>{s(e)})})}}const Ni={FlameBonesCount:5,DefaultBlendshapeCount:52,FlameModelTextureSize:{width:4096,height:2048},BoneTextureSize:{width:4,height:32},BoneWeightTextureSize:{width:512,height:512}},Vi=function(){const e=new Float32Array(1),t=new Int32Array(e.buffer);return function(s){return e[0]=s,t[0]}}(),Gi={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};function Wi(e,t,s){const i=new m(4096,2048),n=e.geometry.attributes.position.array;let r=[];const a=n.length/3,o=e.geometry.morphAttributes.position.length;Object.keys(e.morphTargetDictionary).forEach(t=>{const s=e.morphTargetDictionary[t],i=e.geometry.morphAttributes.position[s];r=r.concat(Array.from(i.array))}),r=r.concat(Array.from(n));const l=new Float32Array(i.x*i.y*4),c=new Uint32Array(i.x*i.y*4);for(let e=0;e<a*(o+1);e++)l[4*e+0]=r[3*e+0],l[4*e+1]=r[3*e+1],l[4*e+2]=r[3*e+2],c[4*e+0]=Vi(l[4*e+0]),c[4*e+1]=Vi(l[4*e+1]),c[4*e+2]=Vi(l[4*e+2]);const h=new I(c,i.x,i.y,b,w);return h.internalFormat="RGBA32UI",h.needsUpdate=!0,t.uniforms.flameModelTexture.value=h,t.uniforms.flameModelTextureSize.value.copy(i),t.uniforms.gaussianSplatCount.value=s,t.uniformsNeedUpdate=!0,{data:c,texture:h,size:i,baseData:{flameModelPos:l}}}function qi(e,t,s,i,n,r,a){if(!s)return null;const o=new m(4,32),l=new Float32Array(e),c=new Uint32Array(o.x*o.y*4);if(a){for(let e=0;e<16*t;e++)c[e]=Vi(l[e]);n&&n.skeleton&&(r.uniforms.boneTexture0.value=n.skeleton.boneTexture,r.uniforms.bindMatrix.value=n.bindMatrix,r.uniforms.bindMatrixInverse.value=n.bindMatrixInverse)}for(const e in s)if(Object.hasOwn(s,e)){const n=s[e];c[i[e]+16*t]=Vi(n)}const h=new I(c,o.x,o.y,b,w);return h.internalFormat="RGBA32UI",h.needsUpdate=!0,r.uniforms.boneTexture.value=h,r.uniforms.boneTextureSize.value.copy(o),r.uniformsNeedUpdate=!0,{data:c,texture:h,size:o,baseData:{boneMatrix:c}}}function Ki(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]=Vi(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]=Vi(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 ji(e,t,s){const i=e.geometry.attributes.position.array.length/3,n=new m(512,512),r=new Float32Array(n.x*n.y*4),a=new Uint32Array(n.x*n.y*4);for(let e=0;e<i;e++)r[8*e+0]=t[e][0],r[8*e+1]=t[e][1],r[8*e+2]=t[e][2],r[8*e+3]=t[e][3],r[8*e+4]=t[e][4],a[8*e+0]=Vi(t[e][0]),a[8*e+1]=Vi(t[e][1]),a[8*e+2]=Vi(t[e][2]),a[8*e+3]=Vi(t[e][3]),a[8*e+4]=Vi(t[e][4]);const o=new I(a,n.x,n.y,b,w);return o.internalFormat="RGBA32UI",o.needsUpdate=!0,s.uniforms.boneWeightTexture.value=o,s.uniforms.boneWeightTextureSize.value.copy(n),s.uniformsNeedUpdate=!0,{data:a,texture:o,size:n,baseData:{boneWeight:a}}}function Yi(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 Ji={buildModelTexture:Wi,buildBoneMatrixTexture:qi,updateBoneMatrixTexture:Ki,buildBoneWeightTexture:ji,getUpdatedBoneMatrices:Yi},Xi=ke("FlameAnimator");class FlameAnimator{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,Xi.debug("FlameAnimator instance created")}_assertNotDisposed(){if(this._disposed)throw new Be("FlameAnimator has been disposed")}initialize(e,t,s,i){this._assertNotDisposed();try{Ct(e,["rotation","expr","neck_pose","jaw_pose","eyes_pose"],"flameParams")}catch(e){throw Xi.error("Invalid flameParams",e),e}if(!(i&&i.geometry&&i.geometry.attributes&&i.geometry.attributes.position)){const e=new Ie("avatarMesh must have geometry with position attribute","avatarMesh");throw Xi.error("Invalid avatarMesh",e),e}Xi.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,Xi.debug("Animation has frames",{totalFrames:this.totalFrames})):(Xi.warn("No rotation data found, totalFrames set to 0"),this.totalFrames=0),this.gaussianSplatCount=i.geometry.attributes.position.count;try{this.buildSkeleton(t),Xi.debug("Skeleton built successfully",{boneCount:this.bones?.length})}catch(e){throw Xi.error("Failed to build skeleton",e),new Ie(`Failed to build skeleton: ${e.message}`,"boneTree",e)}}buildSkeleton(e){if(!e)return;this.bones=[];const t=[],s=(e,n=null)=>{const r=new N;r.name=e.name||`bone_${this.bones.length}`,e.position&&r.position.fromArray(e.position),e.rotation&&r.rotation.fromArray(e.rotation),e.scale&&r.scale.fromArray(e.scale),n&&n.add(r),this.bones.push(r);const a=new i;e.inverseBindMatrix?a.fromArray(e.inverseBindMatrix):(r.updateMatrixWorld(!0),a.copy(r.matrixWorld).invert()),t.push(a),e.children&&e.children.forEach(e=>s(e,r))};Array.isArray(e)?(e.forEach((e,s)=>{const n=new N;n.name=e.name||`bone_${s}`,e.position&&n.position.fromArray(e.position),this.bones.push(n);const r=new i;e.inverseBindMatrix&&r.fromArray(e.inverseBindMatrix),t.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]))):e.root&&s(e.root),this.skeleton=new G(this.bones,t)}setBoneRotation(e,t,s=!1){if(this._assertNotDisposed(),!e||!t||!Array.isArray(t))throw new Ie("bone and angles array are required","bone/angles");const i=Dt.acquire();try{if(s){if(t.length<4)throw new Ie("Quaternion requires 4 values","angles");i.set(t[0],t[1],t[2],t[3])}else{if(t.length<3)throw new Ie("Axis-angle requires 3 values","angles");const e=Bt.acquire();try{e.set(t[0],t[1],t[2]);const s=e.length();e.normalize(),i.setFromAxisAngle(e,s)}finally{Bt.release(e)}}e.quaternion.copy(i),e.updateMatrixWorld(!0)}finally{Dt.release(i)}}updateFlameBones(){if(this._assertNotDisposed(),!this.flameParams||!this.skeleton)return Xi.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 Xi.error("Error setting bone rotations",{frame:e,error:t}),t}return this.skeleton.update(),{bsWeight:t,bonesMatrix:Ji.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 Ie("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?Xi.warn("FlameAnimator.dispose() called on already disposed instance"):(Xi.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,Xi.debug("FlameAnimator disposed successfully"))}}export{ts as ARKIT_BLENDSHAPES_COUNT,Zt as ARKitBlendshapes,He as AbortedPromiseError,hs as AnimationManager,dt as BASE_COMPONENT_COUNT,Qt as BlobUrlManager,ie as CENTER_COLORS_ELEMENTS_PER_SPLAT,ce as CENTER_COLORS_ELEMENTS_PER_TEXEL,ge as CONSECUTIVE_RENDERED_FRAMES_FOR_FPS_CALCULATION,se as COVARIANCES_ELEMENTS_PER_SPLAT,re as COVARIANCES_ELEMENTS_PER_TEXEL_ALLOCATED,oe as COVARIANCES_ELEMENTS_PER_TEXEL_COMPRESSED_ALLOCATED,ae as COVARIANCES_ELEMENTS_PER_TEXEL_COMPRESSED_STORED,ne as COVARIANCES_ELEMENTS_PER_TEXEL_STORED,ee as Constants,$e as DefaultSphericalHarmonics8BitCompressionHalfRange,te as DefaultSphericalHarmonics8BitCompressionRange,Bs as DirectLoadError,Jt as EventEmitter,ss as FLAME_BONES_COUNT,fe as FOCUS_MARKER_FADE_IN_SPEED,Se as FOCUS_MARKER_FADE_OUT_SPEED,Ks as FieldSize,qs as FieldSizeStringMap,FlameAnimator,es as FlameBoneNames,Ni as FlameConstants,Ji as FlameTextureManager,jt as FrameBudgetMonitor,GaussianSplatRenderer,rs as Hello,bi as Hit,gi as INRIAV1PlyParser,as as Idle,Ce as InternalLoadType,os as Listen,ye as LoaderStatus,xe as LoaderUtils,j as LogLevel,Me as Logger,Ee as LoggerLevel,me as MINIMUM_DISTANCE_TO_NEW_FOCAL_POINT,Ae as MIN_SPLAT_COUNT_TO_SHOW_SPLAT_TREE_LOADING_SPINNER,wt as ObjectPool,Hs as PlyFormat,Ci as PlyLoader,Ai as PlyParser,js as PlyParserUtils,Mt as PoolScope,Ii as Ray,wi as Raycaster,Kt as RenderLoop,Y as RenderMode,le as SCALES_ROTATIONS_ELEMENTS_PER_TEXEL,de as SCENE_FADEIN_RATE_FAST,ue as SCENE_FADEIN_RATE_GRADUAL,he as SCENE_INDEXES_ELEMENTS_PER_TEXEL,J as SceneFormat,$ as SceneRevealMode,Ke as Semver,cs as Speak,_s as SplatBuffer,Us as SplatBufferGenerator,us as SplatGeometry,gs as SplatMaterial,fs as SplatMaterial2D,As as SplatMaterial3D,ws as SplatMesh,Ls as SplatPartitioner,Z as SplatRenderMode,ds as SplatScene,ms as SplatTree,ns as State,pe as THREE_CAMERA_FOV,$t as TYVoiceChatState,Gi as TextureConstants,ls as Think,Xt as TypedEventEmitter,Ts as UncompressedSplatArray,Viewer,qe as abortablePromiseWithExtractedComponents,qi as buildBoneMatrixTexture,ji as buildBoneWeightTexture,Wi as buildModelTexture,ze as clamp,Le as configureForDevelopment,_e as configureForProduction,rt as convertBetweenCompressionLevels,at as copyBetweenBuffers,Gt as createTrackedBlobUrl,nt as dataViewFloatForCompressionLevel,Ve as delayedExecute,Ne as disposeAllMeshes,Ot as disposeAllPools,Et as eulerPool,Oe as fetchWithProgress,ot as floatToHalf,Xe as fromHalfFloat,st as fromHalfFloatToUint8,tt as fromUint8,it as fromUint8ToHalfFloat,Qe as getCurrentTime,Vt as getGlobalBlobUrlManager,Ye as getIOSSemever,ke as getLogger,Ht as getPoolStats,Ge as getSphericalHarmonicsComponentCountForDegree,Yi as getUpdatedBoneMatrices,je as isIOS,Tt as matrix4Pool,We as nativePromiseWithExtractedComponents,Dt as quaternionPool,Wt as revokeTrackedBlobUrl,ht as rgbaArrayToInteger,ct as rgbaToInteger,X as sceneFormatFromPath,Pe as setGlobalLogLevel,kt as tempMatrix4A,_t as tempMatrix4B,Lt as tempQuaternionA,Ut as tempQuaternionB,Rt as tempVector3A,Ft as tempVector3B,Pt as tempVector3C,Je as toHalfFloat,et as toUint8,Ze as toUncompressedFloat,lt as uintEncodedFloat,Ki as updateBoneMatrixTexture,yt as validateArrayBuffer,mt as validateAssetPath,vt as validateCallback,bt as validateDOMElement,xt as validateEnum,gt as validateFileExtension,It as validateHexColor,ft as validateInteger,At as validateNumberInRange,St as validatePositiveInteger,Ct as validateRequiredProperties,pt as validateUrl,Bt as vector3Pool};
|
|
2
|
+
//# sourceMappingURL=gsplat-flame-avatar-renderer.esm.min.js.map
|