@naruya/gaussian-vrm 1.0.1 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1065 @@
1
+ // @naruya/gaussian-vrm - https://github.com/naruya/gaussian-vrm
2
+ // Includes gaussian-splats-3d (MIT License)
3
+ var Tn=Object.defineProperty;var Rn=(l,e)=>{for(var s in e)Tn(l,s,{get:e[s],enumerable:!0})};import*as Q from"three";var Dt={};Rn(Dt,{BONE_CONFIG:()=>bs,addChannels:()=>Ne,addPMC:()=>bt,applyBoneOperations:()=>Ms,colors:()=>ws,createDataTexture:()=>Oe,getPointsMeshCapsules:()=>Ft,removePMC:()=>Mt,resetPose:()=>In,setPose:()=>dt,simpleAnim:()=>vn,visualizeBoneAxes:()=>Bn,visualizePMC:()=>wt,visualizeVRM:()=>vt});import*as W from"three";var ws=[[255,222,62],[138,119,199],[243,82,82],[16,157,123],[43,247,242],[120,84,254],[157,238,149],[80,105,17],[39,121,232],[88,149,76],[22,60,188],[243,67,171],[94,62,2],[162,192,4]];function Ms(l,e){for(let s of e){let t=s.boneName,n=l.humanoid.getRawBoneNode(t),r=l.humanoid.getNormalizedBoneNode(t);s.position&&(n.position.x+=s.position.x,n.position.y+=s.position.y,n.position.z+=s.position.z),s.rotation&&(r.rotation.x=s.rotation.x*Math.PI/180,r.rotation.y=s.rotation.y*Math.PI/180,r.rotation.z=s.rotation.z*Math.PI/180),s.scale&&n.scale.set(s.scale.x,s.scale.y,s.scale.z)}}function dt(l,e){Ms(l.currentVrm,e),l.currentVrm.humanoid.update()}function In(l,e){l.currentVrm.humanoid.resetRawPose(),l.currentVrm.humanoid.resetNormalizedPose(),dt(l,e)}function vt(l,e){let s=l.currentVrm.scene.children[l.skinnedMeshIndex],t=l.faceIndex?l.currentVrm.scene.children[l.faceIndex]:null;e===null?(s.material.forEach(n=>{n.colorWrite=!n.colorWrite,n.depthWrite=!n.depthWrite}),t&&(t.visible=!t.visible)):(s.material.forEach(n=>{n.colorWrite=e,n.depthWrite=e}),t&&(t.visible=e))}function wt(l,e){let{points:s,mesh:t,capsules:n}=l;e===null?(s.visible=!s.visible,t.visible=!t.visible,n.children.forEach(r=>{r.visible=!r.visible})):(s.visible=e,t.visible=e,n.children.forEach(r=>{r.visible=e}))}function Bn(l,e){if(!l||!l.debugAxes||l.debugAxes.size===0)return;let s=l.debugAxes.values().next().value.visible;l.debugAxes.forEach(t=>{t.visible=!s})}function Mt(l,e){let{points:s,mesh:t,capsules:n}=e;s&&(l.remove(s),s.geometry.dispose(),s.material.dispose()),t&&(l.remove(t),t.geometry.dispose(),t.material.dispose()),n&&(l.remove(n),n.children.forEach(r=>{r.geometry.dispose(),r.material.dispose()}))}function bt(l,e){let{points:s,mesh:t,capsules:n}=e;s&&l.add(s),t&&l.add(t),n&&l.add(n)}function Ne(l,e,s,t=1){for(let n=0;n<s;n++)e[n*4+0]=t>3?1:l[n*(4-t)+0],e[n*4+1]=t>2?1:l[n*(4-t)+1],e[n*4+2]=t>1?1:l[n*(4-t)+2],e[n*4+3]=t>0?1:l[n*(4-t)+3]}function Oe(...l){let e=new W.DataTexture(...l);return e.needsUpdate=!0,e}function vn(l,e){let s=Math.PI*65/180*Math.sin(Math.PI*(e/60+.5)),t=.4*Math.PI*Math.sin(Math.PI*(e/60));l.currentVrm.humanoid.getNormalizedBoneNode("leftUpperArm").rotation.z=s,l.currentVrm.humanoid.getNormalizedBoneNode("leftUpperLeg").rotation.x=t,l.currentVrm.humanoid.getNormalizedBoneNode("leftLowerLeg").rotation.x=-Math.max(t,0),l.currentVrm.humanoid.getNormalizedBoneNode("rightLowerLeg").rotation.y=t}var bs={arm:{names:["J_Bip_L_Hand","J_Bip_L_LowerArm","J_Bip_R_Hand","J_Bip_R_LowerArm"],radius:.06,scale:{x:1,z:1}},leg:{names:["J_Bip_L_LowerLeg","J_Bip_L_Foot","J_Bip_R_LowerLeg","J_Bip_R_Foot"],radius:.08,scale:{x:1,z:1}},torso:{names:["J_Bip_C_Neck","J_Bip_C_Spine","J_Bip_C_Chest","J_Bip_C_UpperChest"],radius:.03,scale:{x:6,z:4}},headTop:{names:["J_Bip_C_HeadTop_End"],radius:.06,scale:{x:1.5,z:2}},head:{names:["J_Bip_C_Head"],radius:.03,scale:{x:2,z:2}}};function Ft(l){let e=l.currentVrm.scene.children[l.skinnedMeshIndex],s=new W.PointsMaterial({color:16711680,size:.02,opacity:.3,transparent:!0}),t=new W.MeshBasicMaterial({color:65280,wireframe:!0,opacity:.2,transparent:!0}),n=new W.MeshBasicMaterial({wireframe:!0,opacity:.5,transparent:!0}),r=new W.BufferGeometry,i=[],a=e.geometry.getAttribute("position"),c=new W.Vector3,d=new W.Vector3;for(let R=0;R<a.count;R++)c.fromBufferAttribute(a,R),d=e.applyBoneTransform(R,c),d.applyMatrix4(l.currentVrm.scene.matrixWorld),i.push(d.x,d.y,d.z);r.setAttribute("position",new W.Float32BufferAttribute(i,3));let u=new W.Points(r,s),p=new W.BufferGeometry;p.setAttribute("position",new W.Float32BufferAttribute(i,3));let h=e.geometry.getIndex();p.setIndex(h);let A=new W.Mesh(p,t),m=new W.Group,S=[],C=0;function E(R,y=0){C++;let g=new W.Vector3().setFromMatrixPosition(R.matrixWorld);R.children.forEach(function(I){if(I.isBone){let w=new W.Vector3().setFromMatrixPosition(I.matrixWorld),v=g.distanceTo(w),M=new W.Vector3().addVectors(g,w).multiplyScalar(.5),b=null;for(let D of Object.values(bs))if(D.names.includes(I.name)){b=D;break}if(b){let[D,L,F]=ws[m.children.length],P=D<<16|L<<8|F,z=new W.CapsuleGeometry(b.radius,v-b.radius*2,1,6),O=new W.Mesh(z,n.clone());O.material.color.setHex(P),O.scale.set(b.scale.x,1,b.scale.z),O.position.copy(M);let k=new W.Vector3().subVectors(w,g).normalize(),V=new W.Quaternion().setFromUnitVectors(new W.Vector3(0,1,0),k);O.setRotationFromQuaternion(V),O.updateMatrixWorld();let q=e.skeleton.bones.indexOf(I);m.add(O),S.push(q)}E(I,y+1)}})}let x=l.currentVrm.scene.children[0].children[0];return E(x,1),{pmc:{points:u,mesh:A,capsules:m},capsuleBoneIndex:S}}import*as J from"three";import{GLTFLoader as wn}from"three/addons/loaders/GLTFLoader.js";import{VRMLoaderPlugin as Mn,VRMUtils as ut}from"@pixiv/three-vrm";import{FBXLoader as bn}from"three/addons/loaders/FBXLoader.js";var ht=class{constructor(e,s=null,t=null,n=1,r=!1){this.modelUrl=s,this.animationUrl=t,this.currentVrm=void 0,this.currentMixer=void 0,this.currentAction=void 0,this.previousAction=null,this.transitionDuration=.5,this.scene=e,this.scale=n,this.center=r,this._isLoading=!0,this.clock=new J.Clock,this.loadVRM(this.modelUrl,this.animationUrl),this.place()}loadVRM(e=null,s=null,t=null){this._isLoading=!0,e&&(this.modelUrl=e),s&&(this.animationUrl=s),t&&(this.scale=t);let n=new wn;n.crossOrigin="anonymous";let r=new J.Group;r.renderOrder=1e4,r.clear(),n.register(i=>new Mn(i,{helperRoot:r,autoUpdateHumanBones:!0})),this.loadingPromise=new Promise((i,o)=>{n.load(this.modelUrl,async a=>{let c=a.userData.vrm;ut.removeUnnecessaryVertices(a.scene),ut.removeUnnecessaryJoints(a.scene),this.currentVrm=c,c.scene.traverse(p=>{p.frustumCulled=!1});let d=new J.Vector3;new J.Box3().setFromObject(c.scene).getSize(d),this.ground=-d.y*.5*this.scale,this.animationUrl&&this.animationUrl!==""&&await this.loadFBX(this.animationUrl),c.scene.position.y+=this.ground,c.scene.scale.setScalar(this.scale);for(let p of c.springBoneManager.joints)p.settings.stiffness*=this.scale,p.settings.hitRadius*=this.scale;for(let p of c.springBoneManager.colliders){let h=p.shape;h.radius*=this.scale,h.tail&&h.tail.multiplyScalar(this.scale)}ut.rotateVRM0(c),c.scene.updateMatrix(),c.scene.position0=c.scene.position.clone(),c.scene.rotation0=c.scene.rotation.clone(),c.scene.quaternion0=c.scene.quaternion.clone(),c.scene.matrix0=c.scene.matrix.clone(),c.hipPos0=c.humanoid.getNormalizedBoneNode("hips").position.clone(),this._isLoading=!1,i(a)},a=>{let c=parseFloat((100*(a.loaded/a.total)).toPrecision(3)),d=document.getElementById("loaddisplay");d&&(d.innerHTML=c+"%")},a=>o(a))})}async loadFBX(e=null){this._isLoading=!0,e&&(this.animationUrl=e),this.currentMixer||(this.currentMixer=new J.AnimationMixer(this.currentVrm.scene));let s=await Fn(this.animationUrl,this.currentVrm,this.scale);this.previousAction=this.action,this.action=this.currentMixer.clipAction(s),this.currentAction=this.action,this.previousAction?(this.previousAction.fadeOut(this.transitionDuration),this.action.reset().setEffectiveTimeScale(1).setEffectiveWeight(1).fadeIn(this.transitionDuration).play()):(this.action.play(),this.currentMixer.update(0),this.currentVrm.update(0)),this._isLoading=!1}async place(){await this.loadingPromise,this.scene.add(this.currentVrm.scene),this.center||this.currentVrm.scene.position.set(0,0,0)}async leave(e){e.remove(this.currentVrm.scene),ut.deepDispose(this.currentVrm.scene),this.currentVrm=void 0,this.currentMixer=void 0}async changeVRM(e,s,t=null){let n=this.currentVrm.scene.position.clone(),r=this.currentVrm.scene.rotation.clone(),i=this.currentVrm.scene.rotation0.clone();n.y=0,await this.leave(e),await this.loadVRM(s,null,t),await this.place();let o=this.currentVrm.scene.rotation0.clone(),a=c=>new J.Quaternion().setFromEuler(c);r=a(r).multiply(a(i).clone().invert()),r=a(o).multiply(r),r=new J.Euler().setFromQuaternion(r,"YZX"),this.currentVrm.scene.position.copy(n),this.currentVrm.scene.rotation.copy(r),this.center&&(this.currentVrm.scene.position.y+=this.ground)}async changeFBX(e){await this.loadFBX(e)}isLoading(){return this._isLoading}update(){if(this._isLoading)return;let e=this.clock.getDelta();this.currentVrm&&this.currentVrm.update(e),this.currentMixer&&this.currentMixer.update(e)}};function Fn(l,e,s){return new bn().loadAsync(l).then(n=>{let r=J.AnimationClip.findByName(n.animations,"mixamo.com"),i=[],o=new J.Quaternion,a=new J.Quaternion,c=new J.Quaternion,d=new J.Vector3,u=n.getObjectByName("mixamorigHips").position.y,h=Math.abs(e.hipPos0.y)*s/u;return r.tracks.forEach(A=>{let m=A.name.split("."),S=m[0],C=Dn[S],E=e.humanoid?.getNormalizedBoneNode(C)?.name,x=n.getObjectByName(S);if(E!=null){let T=m[1];if(x.getWorldQuaternion(o).invert(),x.parent.getWorldQuaternion(a),A instanceof J.QuaternionKeyframeTrack){for(let R=0;R<A.values.length;R+=4){let y=A.values.slice(R,R+4);c.fromArray(y),c.premultiply(a).multiply(o),c.toArray(y),y.forEach((g,I)=>{A.values[I+R]=g})}i.push(new J.QuaternionKeyframeTrack(`${E}.${T}`,A.times,A.values.map((R,y)=>e.meta?.metaVersion==="0"&&y%2===0?-R:R)))}else if(A instanceof J.VectorKeyframeTrack){let R=A.values.map((y,g)=>(e.meta?.metaVersion==="0"&&g%3!==1?-y:y)*h);i.push(new J.VectorKeyframeTrack(`${E}.${T}`,A.times,R))}}}),new J.AnimationClip("vrmAnimation",r.duration,i)})}var Dn={mixamorigHips:"hips",mixamorigSpine:"spine",mixamorigSpine1:"chest",mixamorigSpine2:"upperChest",mixamorigNeck:"neck",mixamorigHead:"head",mixamorigLeftShoulder:"leftShoulder",mixamorigLeftArm:"leftUpperArm",mixamorigLeftForeArm:"leftLowerArm",mixamorigLeftHand:"leftHand",mixamorigLeftHandThumb1:"leftThumbMetacarpal",mixamorigLeftHandThumb2:"leftThumbProximal",mixamorigLeftHandThumb3:"leftThumbDistal",mixamorigLeftHandIndex1:"leftIndexProximal",mixamorigLeftHandIndex2:"leftIndexIntermediate",mixamorigLeftHandIndex3:"leftIndexDistal",mixamorigLeftHandMiddle1:"leftMiddleProximal",mixamorigLeftHandMiddle2:"leftMiddleIntermediate",mixamorigLeftHandMiddle3:"leftMiddleDistal",mixamorigLeftHandRing1:"leftRingProximal",mixamorigLeftHandRing2:"leftRingIntermediate",mixamorigLeftHandRing3:"leftRingDistal",mixamorigLeftHandPinky1:"leftLittleProximal",mixamorigLeftHandPinky2:"leftLittleIntermediate",mixamorigLeftHandPinky3:"leftLittleDistal",mixamorigRightShoulder:"rightShoulder",mixamorigRightArm:"rightUpperArm",mixamorigRightForeArm:"rightLowerArm",mixamorigRightHand:"rightHand",mixamorigRightHandPinky1:"rightLittleProximal",mixamorigRightHandPinky2:"rightLittleIntermediate",mixamorigRightHandPinky3:"rightLittleDistal",mixamorigRightHandRing1:"rightRingProximal",mixamorigRightHandRing2:"rightRingIntermediate",mixamorigRightHandRing3:"rightRingDistal",mixamorigRightHandMiddle1:"rightMiddleProximal",mixamorigRightHandMiddle2:"rightMiddleIntermediate",mixamorigRightHandMiddle3:"rightMiddleDistal",mixamorigRightHandIndex1:"rightIndexProximal",mixamorigRightHandIndex2:"rightIndexIntermediate",mixamorigRightHandIndex3:"rightIndexDistal",mixamorigRightHandThumb1:"rightThumbMetacarpal",mixamorigRightHandThumb2:"rightThumbProximal",mixamorigRightHandThumb3:"rightThumbDistal",mixamorigLeftUpLeg:"leftUpperLeg",mixamorigLeftLeg:"leftLowerLeg",mixamorigLeftFoot:"leftFoot",mixamorigLeftToeBase:"leftToes",mixamorigRightUpLeg:"rightUpperLeg",mixamorigRightLeg:"rightLowerLeg",mixamorigRightFoot:"rightFoot",mixamorigRightToeBase:"rightToes"};import*as Be from"three";import*as f from"three";import{Ray as Pn,Plane as Hn,MathUtils as kn,EventDispatcher as Ln,Vector3 as Te,MOUSE as Ge,TOUCH as We,Quaternion as Fs,Spherical as Ds,Vector2 as Ie}from"three";var ot=class l{static idGen=0;constructor(e,s){let t,n;this.promise=new Promise((c,d)=>{t=c,n=d});let r=t.bind(this),i=n.bind(this),o=(...c)=>{r(...c)},a=c=>{i(c)};e(o.bind(this),a.bind(this)),this.abortHandler=s,this.id=l.idGen++}then(e){return new l((s,t)=>{this.promise=this.promise.then((...n)=>{let r=e(...n);r instanceof Promise||r instanceof l?r.then((...i)=>{s(...i)}):s(r)}).catch(n=>{t(n)})},this.abortHandler)}catch(e){return new l(s=>{this.promise=this.promise.then((...t)=>{s(...t)}).catch(e)},this.abortHandler)}abort(e){this.abortHandler&&this.abortHandler(e)}},Ct=class extends Error{constructor(e){super(e)}},Co=function(){let l=new Float32Array(1),e=new Int32Array(l.buffer);return function(s){l[0]=s;let t=e[0],n=t>>16&32768,r=t>>12&2047,i=t>>23&255;return i<103?n:i>142?(n|=31744,n|=(i==255?0:1)&&t&8388607,n):i<113?(r|=2048,n|=(r>>114-i)+(r>>113-i&1),n):(n|=i-112<<10|r>>1,n+=r&1,n)}}(),Pt=function(){let l=new Float32Array(1),e=new Int32Array(l.buffer);return function(s){return l[0]=s,e[0]}}();var On=function(l,e){return l[e]+(l[e+1]<<8)+(l[e+2]<<16)+(l[e+3]<<24)},Et=function(l,e,s=!0,t){let n=new AbortController,r=n.signal,i=!1,o=d=>{n.abort(d),i=!0},a=!1,c=(d,u,p,h)=>{e&&!a&&(e(d,u,p,h),d===100&&(a=!0))};return new ot((d,u)=>{let p={signal:r};t&&(p.headers=t),fetch(l,p).then(async h=>{if(!h.ok){let x=await h.text();u(new Error(`Fetch failed: ${h.status} ${h.statusText} ${x}`));return}let A=h.body.getReader(),m=0,S=h.headers.get("Content-Length"),C=S?parseInt(S):void 0,E=[];for(;!i;)try{let{value:x,done:T}=await A.read();if(T){if(c(100,"100%",x,C),s){let g=new Blob(E).arrayBuffer();d(g)}else d();break}m+=x.length;let R,y;C!==void 0&&(R=m/C*100,y=`${R.toFixed(2)}%`),s&&E.push(x),c(R,y,x,C)}catch(x){u(x);return}}).catch(h=>{u(new Ct(h))})},o)},se=function(l,e,s){return Math.max(Math.min(l,s),e)},qe=function(){return performance.now()/1e3},Ye=l=>{if(l.geometry&&(l.geometry.dispose(),l.geometry=null),l.material&&(l.material.dispose(),l.material=null),l.children)for(let e of l.children)Ye(e)},Re=(l,e)=>new Promise(s=>{window.setTimeout(()=>{s(l?l():void 0)},e?1:50)}),Je=(l=0)=>{let e=0;if(l===1)e=9;else if(l===2)e=24;else if(l===3)e=45;else if(l>3)throw new Error("getSphericalHarmonicsComponentCountForDegree() -> Invalid spherical harmonics degree");return e},fs=()=>{let l,e;return{promise:new Promise((t,n)=>{l=t,e=n}),resolve:l,reject:e}},Ht=l=>{let e,s;return l||(l=()=>{}),{promise:new ot((n,r)=>{e=n,s=r},l),resolve:e,reject:s}},Qt=class{constructor(e,s,t){this.major=e,this.minor=s,this.patch=t}toString(){return`${this.major}_${this.minor}_${this.patch}`}};function ms(){let l=navigator.userAgent;return l.indexOf("iPhone")>0||l.indexOf("iPad")>0}function an(){if(ms()){let l=navigator.userAgent.match(/OS (\d+)_(\d+)_?(\d+)?/);return new Qt(parseInt(l[1]||0,10),parseInt(l[2]||0,10),parseInt(l[3]||0,10))}else return null}var Un=14,H=class l{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=Je(this.sphericalHarmonicsDegree),this.componentCount=this.sphericalHarmonicsCount+Un,this.defaultSphericalHarmonics=new Array(this.sphericalHarmonicsCount).fill(0),this.splats=[],this.splatCount=0}static createSplat(e=0){let s=[0,0,0,1,1,1,1,0,0,0,0,0,0,0],t=Je(e);for(let n=0;n<t;n++)s.push(0);return s}addSplat(e){e.originalIndex=this.splatCount,this.splats.push(e),this.splatCount++}getSplat(e){return this.splats[e]}addDefaultSplat(){let e=l.createSplat(this.sphericalHarmonicsDegree);return this.addSplat(e),e}addSplatFromComonents(e,s,t,n,r,i,o,a,c,d,u,p,h,A,...m){let S=[e,s,t,n,r,i,o,a,c,d,u,p,h,A,...this.defaultSphericalHarmonics];for(let C=0;C<m.length&&C<this.sphericalHarmonicsCount;C++)S[C]=m[C];return this.addSplat(S),S}addSplatFromArray(e,s){let t=e.splats[s],n=l.createSplat(this.sphericalHarmonicsDegree);for(let r=0;r<this.componentCount&&r<t.length;r++)n[r]=t[r];this.addSplat(n)}},j=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},zn=j.SphericalHarmonics8BitCompressionRange,Ue=zn/2,pe=f.DataUtils.toHalfFloat.bind(f.DataUtils),As=f.DataUtils.fromHalfFloat.bind(f.DataUtils),te=(l,e,s=!1,t,n)=>{if(e===0)return l;if(e===1||e===2&&!s)return f.DataUtils.fromHalfFloat(l);if(e===2)return gs(l,t,n)},st=(l,e,s)=>{l=se(l,e,s);let t=s-e;return se(Math.floor((l-e)/t*255),0,255)},gs=(l,e,s)=>{let t=s-e;return l/255*t+e},ln=(l,e,s)=>st(As(l,e,s)),_n=(l,e,s)=>pe(gs(l,e,s)),X=(l,e,s,t=!1)=>s===0?l.getFloat32(e*4,!0):s===1||s===2&&!t?l.getUint16(e*2,!0):l.getUint8(e,!0),Vn=function(){let l=e=>e;return function(e,s,t,n=!1){if(s===t)return e;let r=l;return s===2&&n?t===1?r=_n:t==0&&(r=gs):s===2||s===1?t===0?r=As:t==2&&(n?r=ln:r=l):s===0&&(t===1?r=pe:t==2&&(n?r=st:r=pe)),r(e)}}(),Ke=(l,e,s,t,n=0)=>{let r=new Uint8Array(l,e),i=new Uint8Array(s,t);for(let o=0;o<n;o++)i[o]=r[o]},U=class l{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,s=!0){this.constructFromBuffer(e,s)}getSplatCount(){return this.splatCount}getMaxSplatCount(){return this.maxSplatCount}getMinSphericalHarmonicsDegree(){let e=0;for(let s=0;s<this.sections.length;s++){let t=this.sections[s];(s===0||t.sphericalHarmonicsDegree<e)&&(e=t.sphericalHarmonicsDegree)}return e}getBucketIndex(e,s){let t,n=e.fullBucketCount*e.bucketSize;if(s<n)t=Math.floor(s/e.bucketSize);else{let r=n;t=e.fullBucketCount;let i=0;for(;r<e.splatCount;){let o=e.partiallyFilledBucketLengths[i];if(s>=r&&s<r+o)break;r+=o,t++,i++}}return t}getSplatCenter(e,s,t){let n=this.globalSplatIndexToSectionMap[e],r=this.sections[n],i=e-r.splatCountOffset,o=r.bytesPerSplat*i,a=new DataView(this.bufferData,r.dataBase+o),c=X(a,0,this.compressionLevel),d=X(a,1,this.compressionLevel),u=X(a,2,this.compressionLevel);if(this.compressionLevel>=1){let h=this.getBucketIndex(r,i)*l.BucketStorageSizeFloats,A=r.compressionScaleFactor,m=r.compressionScaleRange;s.x=(c-m)*A+r.bucketArray[h],s.y=(d-m)*A+r.bucketArray[h+1],s.z=(u-m)*A+r.bucketArray[h+2]}else s.x=c,s.y=d,s.z=u;t&&s.applyMatrix4(t)}getSplatScaleAndRotation=function(){let e=new f.Matrix4,s=new f.Matrix4,t=new f.Matrix4,n=new f.Vector3,r=new f.Vector3,i=new f.Quaternion;return function(o,a,c,d,u){let p=this.globalSplatIndexToSectionMap[o],h=this.sections[p],A=o-h.splatCountOffset,m=h.bytesPerSplat*A+l.CompressionLevels[this.compressionLevel].ScaleOffsetBytes,S=new DataView(this.bufferData,h.dataBase+m);r.set(te(X(S,0,this.compressionLevel),this.compressionLevel),te(X(S,1,this.compressionLevel),this.compressionLevel),te(X(S,2,this.compressionLevel),this.compressionLevel)),u&&(u.x!==void 0&&(r.x=u.x),u.y!==void 0&&(r.y=u.y),u.z!==void 0&&(r.z=u.z)),i.set(te(X(S,4,this.compressionLevel),this.compressionLevel),te(X(S,5,this.compressionLevel),this.compressionLevel),te(X(S,6,this.compressionLevel),this.compressionLevel),te(X(S,3,this.compressionLevel),this.compressionLevel)),d?(e.makeScale(r.x,r.y,r.z),s.makeRotationFromQuaternion(i),t.copy(e).multiply(s).multiply(d),t.decompose(n,c,a)):(a.copy(r),c.copy(i))}}();getSplatColor(e,s){let t=this.globalSplatIndexToSectionMap[e],n=this.sections[t],r=e-n.splatCountOffset,i=n.bytesPerSplat*r+l.CompressionLevels[this.compressionLevel].ColorOffsetBytes,o=new Uint8Array(this.bufferData,n.dataBase+i,4);s.set(o[0],o[1],o[2],o[3])}fillSplatCenterArray(e,s,t,n,r){let i=this.splatCount;t=t||0,n=n||i-1,r===void 0&&(r=t);let o=new f.Vector3;for(let a=t;a<=n;a++){let c=this.globalSplatIndexToSectionMap[a],d=this.sections[c],u=a-d.splatCountOffset,p=(a-t+r)*l.CenterComponentCount,h=d.bytesPerSplat*u,A=new DataView(this.bufferData,d.dataBase+h),m=X(A,0,this.compressionLevel),S=X(A,1,this.compressionLevel),C=X(A,2,this.compressionLevel);if(this.compressionLevel>=1){let x=this.getBucketIndex(d,u)*l.BucketStorageSizeFloats,T=d.compressionScaleFactor,R=d.compressionScaleRange;o.x=(m-R)*T+d.bucketArray[x],o.y=(S-R)*T+d.bucketArray[x+1],o.z=(C-R)*T+d.bucketArray[x+2]}else o.x=m,o.y=S,o.z=C;s&&o.applyMatrix4(s),e[p]=o.x,e[p+1]=o.y,e[p+2]=o.z}}fillSplatScaleRotationArray=function(){let e=new f.Matrix4,s=new f.Matrix4,t=new f.Matrix4,n=new f.Vector3,r=new f.Quaternion,i=new f.Vector3,o=a=>{let c=a.w<0?-1:1;a.x*=c,a.y*=c,a.z*=c,a.w*=c};return function(a,c,d,u,p,h,A,m){let S=this.splatCount;u=u||0,p=p||S-1,h===void 0&&(h=u);let C=(E,x)=>(x===void 0&&(x=this.compressionLevel),Vn(E,x,A));for(let E=u;E<=p;E++){let x=this.globalSplatIndexToSectionMap[E],T=this.sections[x],R=E-T.splatCountOffset,y=T.bytesPerSplat*R+l.CompressionLevels[this.compressionLevel].ScaleOffsetBytes,g=(E-u+h)*l.ScaleComponentCount,I=(E-u+h)*l.RotationComponentCount,w=new DataView(this.bufferData,T.dataBase+y),v=m&&m.x!==void 0?m.x:X(w,0,this.compressionLevel),M=m&&m.y!==void 0?m.y:X(w,1,this.compressionLevel),b=m&&m.z!==void 0?m.z:X(w,2,this.compressionLevel),D=X(w,3,this.compressionLevel),L=X(w,4,this.compressionLevel),F=X(w,5,this.compressionLevel),P=X(w,6,this.compressionLevel);n.set(te(v,this.compressionLevel),te(M,this.compressionLevel),te(b,this.compressionLevel)),r.set(te(L,this.compressionLevel),te(F,this.compressionLevel),te(P,this.compressionLevel),te(D,this.compressionLevel)).normalize(),d&&(i.set(0,0,0),e.makeScale(n.x,n.y,n.z),s.makeRotationFromQuaternion(r),t.identity().premultiply(e).premultiply(s),t.premultiply(d),t.decompose(i,r,n),r.normalize()),o(r),a&&(a[g]=C(n.x,0),a[g+1]=C(n.y,0),a[g+2]=C(n.z,0)),c&&(c[I]=C(r.x,0),c[I+1]=C(r.y,0),c[I+2]=C(r.z,0),c[I+3]=C(r.w,0))}}}();static computeCovariance=function(){let e=new f.Matrix4,s=new f.Matrix3,t=new f.Matrix3,n=new f.Matrix3,r=new f.Matrix3,i=new f.Matrix3,o=new f.Matrix3;return function(a,c,d,u,p=0,h){e.makeScale(a.x,a.y,a.z),s.setFromMatrix4(e),e.makeRotationFromQuaternion(c),t.setFromMatrix4(e),n.copy(t).multiply(s),r.copy(n).transpose().premultiply(n),d&&(i.setFromMatrix4(d),o.copy(i).transpose(),r.multiply(o),r.premultiply(i)),h>=1?(u[p]=pe(r.elements[0]),u[p+1]=pe(r.elements[3]),u[p+2]=pe(r.elements[6]),u[p+3]=pe(r.elements[4]),u[p+4]=pe(r.elements[7]),u[p+5]=pe(r.elements[8])):(u[p]=r.elements[0],u[p+1]=r.elements[3],u[p+2]=r.elements[6],u[p+3]=r.elements[4],u[p+4]=r.elements[7],u[p+5]=r.elements[8])}}();fillSplatCovarianceArray(e,s,t,n,r,i){let o=this.splatCount,a=new f.Vector3,c=new f.Quaternion;t=t||0,n=n||o-1,r===void 0&&(r=t);for(let d=t;d<=n;d++){let u=this.globalSplatIndexToSectionMap[d],p=this.sections[u],h=d-p.splatCountOffset,A=(d-t+r)*l.CovarianceComponentCount,m=p.bytesPerSplat*h+l.CompressionLevels[this.compressionLevel].ScaleOffsetBytes,S=new DataView(this.bufferData,p.dataBase+m);a.set(te(X(S,0,this.compressionLevel),this.compressionLevel),te(X(S,1,this.compressionLevel),this.compressionLevel),te(X(S,2,this.compressionLevel),this.compressionLevel)),c.set(te(X(S,4,this.compressionLevel),this.compressionLevel),te(X(S,5,this.compressionLevel),this.compressionLevel),te(X(S,6,this.compressionLevel),this.compressionLevel),te(X(S,3,this.compressionLevel),this.compressionLevel)),l.computeCovariance(a,c,s,e,A,i)}}fillSplatColorArray(e,s,t,n,r){let i=this.splatCount;t=t||0,n=n||i-1,r===void 0&&(r=t);for(let o=t;o<=n;o++){let a=this.globalSplatIndexToSectionMap[o],c=this.sections[a],d=o-c.splatCountOffset,u=(o-t+r)*l.ColorComponentCount,p=c.bytesPerSplat*d+l.CompressionLevels[this.compressionLevel].ColorOffsetBytes,h=new Uint8Array(this.bufferData,c.dataBase+p),A=h[3];A=A>=s?A:0,e[u]=h[0],e[u+1]=h[1],e[u+2]=h[2],e[u+3]=A}}fillSphericalHarmonicsArray=function(){let e=[];for(let F=0;F<15;F++)e[F]=new f.Vector3;let s=new f.Matrix3,t=new f.Matrix4,n=new f.Vector3,r=new f.Vector3,i=new f.Quaternion,o=[],a=[],c=[],d=[],u=[],p=[],h=[],A=[],m=[],S=[],C=[],E=[],x=[],T=[],R=[],y=[],g=[],I=[],w=F=>F,v=(F,P,z,O)=>{F[0]=P,F[1]=z,F[2]=O},M=(F,P,z,O,k)=>{F[0]=X(P,O,k,!0),F[1]=X(P,O+z,k,!0),F[2]=X(P,O+z+z,k,!0)},b=(F,P)=>{P[0]=F[0],P[1]=F[1],P[2]=F[2]},D=(F,P,z,O)=>{P[z]=O(F[0]),P[z+1]=O(F[1]),P[z+2]=O(F[2])},L=(F,P,z,O,k)=>(P[0]=te(F[0],z,!0,O,k),P[1]=te(F[1],z,!0,O,k),P[2]=te(F[2],z,!0,O,k),P);return function(F,P,z,O,k,V,q){let oe=this.splatCount;O=O||0,k=k||oe-1,V===void 0&&(V=O),z&&P>=1&&(t.copy(z),t.decompose(n,i,r),i.normalize(),t.makeRotationFromQuaternion(i),s.setFromMatrix4(t),v(o,s.elements[4],-s.elements[7],s.elements[1]),v(a,-s.elements[5],s.elements[8],-s.elements[2]),v(c,s.elements[3],-s.elements[6],s.elements[0]));let N=G=>ln(G,this.minSphericalHarmonicsCoeff,this.maxSphericalHarmonicsCoeff),Ae=G=>st(G,this.minSphericalHarmonicsCoeff,this.maxSphericalHarmonicsCoeff);for(let G=O;G<=k;G++){let K=this.globalSplatIndexToSectionMap[G],Y=this.sections[K];P=Math.min(P,Y.sphericalHarmonicsDegree);let ie=Je(P),ae=G-Y.splatCountOffset,ge=Y.bytesPerSplat*ae+l.CompressionLevels[this.compressionLevel].SphericalHarmonicsOffsetBytes,me=new DataView(this.bufferData,Y.dataBase+ge),ee=(G-O+V)*ie,Se=z?0:this.compressionLevel,ne=w;Se!==q&&(Se===1?q===0?ne=As:q==2&&(ne=N):Se===0&&(q===1?ne=pe:q==2&&(ne=Ae)));let Z=this.minSphericalHarmonicsCoeff,le=this.maxSphericalHarmonicsCoeff;P>=1&&(M(m,me,3,0,this.compressionLevel),M(S,me,3,1,this.compressionLevel),M(C,me,3,2,this.compressionLevel),z?(L(m,m,this.compressionLevel,Z,le),L(S,S,this.compressionLevel,Z,le),L(C,C,this.compressionLevel,Z,le),l.rotateSphericalHarmonics3(m,S,C,o,a,c,T,R,y)):(b(m,T),b(S,R),b(C,y)),D(T,F,ee,ne),D(R,F,ee+3,ne),D(y,F,ee+6,ne),P>=2&&(M(m,me,5,9,this.compressionLevel),M(S,me,5,10,this.compressionLevel),M(C,me,5,11,this.compressionLevel),M(E,me,5,12,this.compressionLevel),M(x,me,5,13,this.compressionLevel),z?(L(m,m,this.compressionLevel,Z,le),L(S,S,this.compressionLevel,Z,le),L(C,C,this.compressionLevel,Z,le),L(E,E,this.compressionLevel,Z,le),L(x,x,this.compressionLevel,Z,le),l.rotateSphericalHarmonics5(m,S,C,E,x,o,a,c,d,u,p,h,A,T,R,y,g,I)):(b(m,T),b(S,R),b(C,y),b(E,g),b(x,I)),D(T,F,ee+9,ne),D(R,F,ee+12,ne),D(y,F,ee+15,ne),D(g,F,ee+18,ne),D(I,F,ee+21,ne)))}}}();static dot3=(e,s,t,n,r)=>{r[0]=r[1]=r[2]=0;let i=n[0],o=n[1],a=n[2];l.addInto3(e[0]*i,e[1]*i,e[2]*i,r),l.addInto3(s[0]*o,s[1]*o,s[2]*o,r),l.addInto3(t[0]*a,t[1]*a,t[2]*a,r)};static addInto3=(e,s,t,n)=>{n[0]=n[0]+e,n[1]=n[1]+s,n[2]=n[2]+t};static dot5=(e,s,t,n,r,i,o)=>{o[0]=o[1]=o[2]=0;let a=i[0],c=i[1],d=i[2],u=i[3],p=i[4];l.addInto3(e[0]*a,e[1]*a,e[2]*a,o),l.addInto3(s[0]*c,s[1]*c,s[2]*c,o),l.addInto3(t[0]*d,t[1]*d,t[2]*d,o),l.addInto3(n[0]*u,n[1]*u,n[2]*u,o),l.addInto3(r[0]*p,r[1]*p,r[2]*p,o)};static rotateSphericalHarmonics3=(e,s,t,n,r,i,o,a,c)=>{l.dot3(e,s,t,n,o),l.dot3(e,s,t,r,a),l.dot3(e,s,t,i,c)};static rotateSphericalHarmonics5=(e,s,t,n,r,i,o,a,c,d,u,p,h,A,m,S,C,E)=>{let x=Math.sqrt(.25),T=Math.sqrt(3/4),R=Math.sqrt(1/3),y=Math.sqrt(4/3),g=Math.sqrt(1/12);c[0]=x*(a[2]*i[0]+a[0]*i[2]+(i[2]*a[0]+i[0]*a[2])),c[1]=a[1]*i[0]+i[1]*a[0],c[2]=T*(a[1]*i[1]+i[1]*a[1]),c[3]=a[1]*i[2]+i[1]*a[2],c[4]=x*(a[2]*i[2]-a[0]*i[0]+(i[2]*a[2]-i[0]*a[0])),l.dot5(e,s,t,n,r,c,A),d[0]=x*(o[2]*i[0]+o[0]*i[2]+(i[2]*o[0]+i[0]*o[2])),d[1]=o[1]*i[0]+i[1]*o[0],d[2]=T*(o[1]*i[1]+i[1]*o[1]),d[3]=o[1]*i[2]+i[1]*o[2],d[4]=x*(o[2]*i[2]-o[0]*i[0]+(i[2]*o[2]-i[0]*o[0])),l.dot5(e,s,t,n,r,d,m),u[0]=R*(o[2]*o[0]+o[0]*o[2])+-g*(a[2]*a[0]+a[0]*a[2]+(i[2]*i[0]+i[0]*i[2])),u[1]=y*o[1]*o[0]+-R*(a[1]*a[0]+i[1]*i[0]),u[2]=o[1]*o[1]+-x*(a[1]*a[1]+i[1]*i[1]),u[3]=y*o[1]*o[2]+-R*(a[1]*a[2]+i[1]*i[2]),u[4]=R*(o[2]*o[2]-o[0]*o[0])+-g*(a[2]*a[2]-a[0]*a[0]+(i[2]*i[2]-i[0]*i[0])),l.dot5(e,s,t,n,r,u,S),p[0]=x*(o[2]*a[0]+o[0]*a[2]+(a[2]*o[0]+a[0]*o[2])),p[1]=o[1]*a[0]+a[1]*o[0],p[2]=T*(o[1]*a[1]+a[1]*o[1]),p[3]=o[1]*a[2]+a[1]*o[2],p[4]=x*(o[2]*a[2]-o[0]*a[0]+(a[2]*o[2]-a[0]*o[0])),l.dot5(e,s,t,n,r,p,C),h[0]=x*(a[2]*a[0]+a[0]*a[2]-(i[2]*i[0]+i[0]*i[2])),h[1]=a[1]*a[0]-i[1]*i[0],h[2]=T*(a[1]*a[1]-i[1]*i[1]),h[3]=a[1]*a[2]-i[1]*i[2],h[4]=x*(a[2]*a[2]-a[0]*a[0]-(i[2]*i[2]-i[0]*i[0])),l.dot5(e,s,t,n,r,h,E)};static parseHeader(e){let s=new Uint8Array(e,0,l.HeaderSizeBytes),t=new Uint16Array(e,0,l.HeaderSizeBytes/2),n=new Uint32Array(e,0,l.HeaderSizeBytes/4),r=new Float32Array(e,0,l.HeaderSizeBytes/4),i=s[0],o=s[1],a=n[1],c=n[2],d=n[3],u=n[4],p=t[10],h=new f.Vector3(r[6],r[7],r[8]),A=r[9]||-Ue,m=r[10]||Ue;return{versionMajor:i,versionMinor:o,maxSectionCount:a,sectionCount:c,maxSplatCount:d,splatCount:u,compressionLevel:p,sceneCenter:h,minSphericalHarmonicsCoeff:A,maxSphericalHarmonicsCoeff:m}}static writeHeaderCountsToBuffer(e,s,t){let n=new Uint32Array(t,0,l.HeaderSizeBytes/4);n[2]=e,n[4]=s}static writeHeaderToBuffer(e,s){let t=new Uint8Array(s,0,l.HeaderSizeBytes),n=new Uint16Array(s,0,l.HeaderSizeBytes/2),r=new Uint32Array(s,0,l.HeaderSizeBytes/4),i=new Float32Array(s,0,l.HeaderSizeBytes/4);t[0]=e.versionMajor,t[1]=e.versionMinor,t[2]=0,t[3]=0,r[1]=e.maxSectionCount,r[2]=e.sectionCount,r[3]=e.maxSplatCount,r[4]=e.splatCount,n[10]=e.compressionLevel,i[6]=e.sceneCenter.x,i[7]=e.sceneCenter.y,i[8]=e.sceneCenter.z,i[9]=e.minSphericalHarmonicsCoeff||-Ue,i[10]=e.maxSphericalHarmonicsCoeff||Ue}static parseSectionHeaders(e,s,t=0,n){let r=e.compressionLevel,i=e.maxSectionCount,o=new Uint16Array(s,t,i*l.SectionHeaderSizeBytes/2),a=new Uint32Array(s,t,i*l.SectionHeaderSizeBytes/4),c=new Float32Array(s,t,i*l.SectionHeaderSizeBytes/4),d=[],u=0,p=u/2,h=u/4,A=l.HeaderSizeBytes+e.maxSectionCount*l.SectionHeaderSizeBytes,m=0;for(let S=0;S<i;S++){let C=a[h+1],E=a[h+2],x=a[h+3],T=c[h+4],R=T/2,y=o[p+10],g=a[h+6]||l.CompressionLevels[r].ScaleRange,I=a[h+8],w=a[h+9],v=w*4,M=y*x+v,b=o[p+20],{bytesPerSplat:D}=l.calculateComponentStorage(r,b),L=D*C,F=L+M,P={bytesPerSplat:D,splatCountOffset:m,splatCount:n?C:0,maxSplatCount:C,bucketSize:E,bucketCount:x,bucketBlockSize:T,halfBucketBlockSize:R,bucketStorageSizeBytes:y,bucketsStorageSizeBytes:M,splatDataStorageSizeBytes:L,storageSizeBytes:F,compressionScaleRange:g,compressionScaleFactor:R/g,base:A,bucketsBase:A+v,dataBase:A+M,fullBucketCount:I,partiallyFilledBucketCount:w,sphericalHarmonicsDegree:b};d[S]=P,A+=F,u+=l.SectionHeaderSizeBytes,p=u/2,h=u/4,m+=C}return d}static writeSectionHeaderToBuffer(e,s,t,n=0){let r=new Uint16Array(t,n,l.SectionHeaderSizeBytes/2),i=new Uint32Array(t,n,l.SectionHeaderSizeBytes/4),o=new Float32Array(t,n,l.SectionHeaderSizeBytes/4);i[0]=e.splatCount,i[1]=e.maxSplatCount,i[2]=s>=1?e.bucketSize:0,i[3]=s>=1?e.bucketCount:0,o[4]=s>=1?e.bucketBlockSize:0,r[10]=s>=1?l.BucketStorageSizeBytes:0,i[6]=s>=1?e.compressionScaleRange:0,i[7]=e.storageSizeBytes,i[8]=s>=1?e.fullBucketCount:0,i[9]=s>=1?e.partiallyFilledBucketCount:0,r[20]=e.sphericalHarmonicsDegree}static writeSectionHeaderSplatCountToBuffer(e,s,t=0){let n=new Uint32Array(s,t,l.SectionHeaderSizeBytes/4);n[0]=e}constructFromBuffer(e,s){this.bufferData=e,this.globalSplatIndexToLocalSplatIndexMap=[],this.globalSplatIndexToSectionMap=[];let t=l.parseHeader(this.bufferData);this.versionMajor=t.versionMajor,this.versionMinor=t.versionMinor,this.maxSectionCount=t.maxSectionCount,this.sectionCount=s?t.maxSectionCount:0,this.maxSplatCount=t.maxSplatCount,this.splatCount=s?t.maxSplatCount:0,this.compressionLevel=t.compressionLevel,this.sceneCenter=new f.Vector3().copy(t.sceneCenter),this.minSphericalHarmonicsCoeff=t.minSphericalHarmonicsCoeff,this.maxSphericalHarmonicsCoeff=t.maxSphericalHarmonicsCoeff,this.sections=l.parseSectionHeaders(t,this.bufferData,l.HeaderSizeBytes,s),this.linkBufferArrays(),this.buildMaps()}static calculateComponentStorage(e,s){let t=l.CompressionLevels[e].BytesPerCenter,n=l.CompressionLevels[e].BytesPerScale,r=l.CompressionLevels[e].BytesPerRotation,i=l.CompressionLevels[e].BytesPerColor,o=Je(s),a=l.CompressionLevels[e].BytesPerSphericalHarmonicsComponent*o,c=t+n+r+i+a;return{bytesPerCenter:t,bytesPerScale:n,bytesPerRotation:r,bytesPerColor:i,sphericalHarmonicsComponentsPerSplat:o,sphericalHarmonicsBytesPerSplat:a,bytesPerSplat:c}}linkBufferArrays(){for(let e=0;e<this.maxSectionCount;e++){let s=this.sections[e];s.bucketArray=new Float32Array(this.bufferData,s.bucketsBase,s.bucketCount*l.BucketStorageSizeFloats),s.partiallyFilledBucketCount>0&&(s.partiallyFilledBucketLengths=new Uint32Array(this.bufferData,s.base,s.partiallyFilledBucketCount))}}buildMaps(){let e=0;for(let s=0;s<this.maxSectionCount;s++){let t=this.sections[s];for(let n=0;n<t.maxSplatCount;n++){let r=e+n;this.globalSplatIndexToLocalSplatIndexMap[r]=n,this.globalSplatIndexToSectionMap[r]=s}e+=t.maxSplatCount}}updateLoadedCounts(e,s){l.writeHeaderCountsToBuffer(e,s,this.bufferData),this.sectionCount=e,this.splatCount=s}updateSectionLoadedCounts(e,s){let t=l.HeaderSizeBytes+l.SectionHeaderSizeBytes*e;l.writeSectionHeaderSplatCountToBuffer(s,this.bufferData,t),this.sections[e].splatCount=s}static writeSplatDataToSectionBuffer=function(){let e=new ArrayBuffer(12),s=new ArrayBuffer(12),t=new ArrayBuffer(16),n=new ArrayBuffer(4),r=new ArrayBuffer(256),i=new f.Quaternion,o=new f.Vector3,a=new f.Vector3,{X:c,Y:d,Z:u,SCALE0:p,SCALE1:h,SCALE2:A,ROTATION0:m,ROTATION1:S,ROTATION2:C,ROTATION3:E,FDC0:x,FDC1:T,FDC2:R,OPACITY:y,FRC0:g,FRC9:I}=H.OFFSET,w=(v,M,b)=>{let D=b*2+1;return v=Math.round(v*M)+b,se(v,0,D)};return function(v,M,b,D,L,F,P,z,O=-Ue,k=Ue){let V=Je(L),q=l.CompressionLevels[D].BytesPerCenter,oe=l.CompressionLevels[D].BytesPerScale,N=l.CompressionLevels[D].BytesPerRotation,Ae=l.CompressionLevels[D].BytesPerColor,G=b,K=G+q,Y=K+oe,ie=Y+N,ae=ie+Ae;if(v[m]!==void 0?(i.set(v[m],v[S],v[C],v[E]),i.normalize()):i.set(1,0,0,0),v[p]!==void 0?o.set(v[p]||0,v[h]||0,v[A]||0):o.set(0,0,0),D===0){let me=new Float32Array(M,G,l.CenterComponentCount),ee=new Float32Array(M,Y,l.RotationComponentCount),Se=new Float32Array(M,K,l.ScaleComponentCount);if(ee.set([i.x,i.y,i.z,i.w]),Se.set([o.x,o.y,o.z]),me.set([v[c],v[d],v[u]]),L>0){let ne=new Float32Array(M,ae,V);if(L>=1){for(let Z=0;Z<9;Z++)ne[Z]=v[g+Z]||0;if(L>=2)for(let Z=0;Z<15;Z++)ne[Z+9]=v[I+Z]||0}}}else{let me=new Uint16Array(e,0,l.CenterComponentCount),ee=new Uint16Array(t,0,l.RotationComponentCount),Se=new Uint16Array(s,0,l.ScaleComponentCount);if(ee.set([pe(i.x),pe(i.y),pe(i.z),pe(i.w)]),Se.set([pe(o.x),pe(o.y),pe(o.z)]),a.set(v[c],v[d],v[u]).sub(F),a.x=w(a.x,P,z),a.y=w(a.y,P,z),a.z=w(a.z,P,z),me.set([a.x,a.y,a.z]),L>0){let ne=D===1?Uint16Array:Uint8Array,Z=D===1?2:1,le=new ne(r,0,V);if(L>=1){for(let fe=0;fe<9;fe++){let xe=v[g+fe]||0;le[fe]=D===1?pe(xe):st(xe,O,k)}let ve=9*Z;if(Ke(le.buffer,0,M,ae,ve),L>=2){for(let fe=0;fe<15;fe++){let xe=v[I+fe]||0;le[fe+9]=D===1?pe(xe):st(xe,O,k)}Ke(le.buffer,ve,M,ae+ve,15*Z)}}}Ke(me.buffer,0,M,G,6),Ke(Se.buffer,0,M,K,6),Ke(ee.buffer,0,M,Y,8)}let ge=new Uint8ClampedArray(n,0,4);ge.set([v[x]||0,v[T]||0,v[R]||0]),ge[3]=v[y]||0,Ke(ge.buffer,0,M,ie,4)}}();static generateFromUncompressedSplatArrays(e,s,t,n,r,i,o=[]){let a=0;for(let R=0;R<e.length;R++){let y=e[R];a=Math.max(y.sphericalHarmonicsDegree,a)}let c,d;for(let R=0;R<e.length;R++){let y=e[R];for(let g=0;g<y.splats.length;g++){let I=y.splats[g];for(let w=H.OFFSET.FRC0;w<H.OFFSET.FRC23&&w<I.length;w++)(!c||I[w]<c)&&(c=I[w]),(!d||I[w]>d)&&(d=I[w])}}c=c||-Ue,d=d||Ue;let{bytesPerSplat:u}=l.calculateComponentStorage(t,a),p=l.CompressionLevels[t].ScaleRange,h=[],A=[],m=0;for(let R=0;R<e.length;R++){let y=e[R],g=new H(a);for(let G=0;G<y.splatCount;G++){let K=y.splats[G];(K[H.OFFSET.OPACITY]||0)>=s&&g.addSplat(K)}let I=o[R]||{},w=(I.blockSizeFactor||1)*(r||l.BucketBlockSize),v=Math.ceil((I.bucketSizeFactor||1)*(i||l.BucketSize)),M=l.computeBucketsForUncompressedSplatArray(g,w,v),b=M.fullBuckets.length,D=M.partiallyFullBuckets.map(G=>G.splats.length),L=D.length,F=[...M.fullBuckets,...M.partiallyFullBuckets],P=g.splats.length*u,z=L*4,O=t>=1?F.length*l.BucketStorageSizeBytes+z:0,k=P+O,V=new ArrayBuffer(k),q=p/(w*.5),oe=new f.Vector3,N=0;for(let G=0;G<F.length;G++){let K=F[G];oe.fromArray(K.center);for(let Y=0;Y<K.splats.length;Y++){let ie=K.splats[Y],ae=g.splats[ie],ge=O+N*u;l.writeSplatDataToSectionBuffer(ae,V,ge,t,a,oe,q,p,c,d),N++}}if(m+=N,t>=1){let G=new Uint32Array(V,0,D.length*4);for(let Y=0;Y<D.length;Y++)G[Y]=D[Y];let K=new Float32Array(V,z,F.length*l.BucketStorageSizeFloats);for(let Y=0;Y<F.length;Y++){let ie=F[Y],ae=Y*3;K[ae]=ie.center[0],K[ae+1]=ie.center[1],K[ae+2]=ie.center[2]}}h.push(V);let Ae=new ArrayBuffer(l.SectionHeaderSizeBytes);l.writeSectionHeaderToBuffer({maxSplatCount:N,splatCount:N,bucketSize:v,bucketCount:F.length,bucketBlockSize:w,compressionScaleRange:p,storageSizeBytes:k,fullBucketCount:b,partiallyFilledBucketCount:L,sphericalHarmonicsDegree:a},t,Ae,0),A.push(Ae)}let S=0;for(let R of h)S+=R.byteLength;let C=l.HeaderSizeBytes+l.SectionHeaderSizeBytes*h.length+S,E=new ArrayBuffer(C);l.writeHeaderToBuffer({versionMajor:0,versionMinor:1,maxSectionCount:h.length,sectionCount:h.length,maxSplatCount:m,splatCount:m,compressionLevel:t,sceneCenter:n,minSphericalHarmonicsCoeff:c,maxSphericalHarmonicsCoeff:d},E);let x=l.HeaderSizeBytes;for(let R of A)new Uint8Array(E,x,l.SectionHeaderSizeBytes).set(new Uint8Array(R)),x+=l.SectionHeaderSizeBytes;for(let R of h)new Uint8Array(E,x,R.byteLength).set(new Uint8Array(R)),x+=R.byteLength;return new l(E)}static computeBucketsForUncompressedSplatArray(e,s,t){let n=e.splatCount,r=s/2,i=new f.Vector3,o=new f.Vector3;for(let m=0;m<n;m++){let S=e.splats[m],C=[S[H.OFFSET.X],S[H.OFFSET.Y],S[H.OFFSET.Z]];(m===0||C[0]<i.x)&&(i.x=C[0]),(m===0||C[0]>o.x)&&(o.x=C[0]),(m===0||C[1]<i.y)&&(i.y=C[1]),(m===0||C[1]>o.y)&&(o.y=C[1]),(m===0||C[2]<i.z)&&(i.z=C[2]),(m===0||C[2]>o.z)&&(o.z=C[2])}let a=new f.Vector3().copy(o).sub(i),c=Math.ceil(a.y/s),d=Math.ceil(a.z/s),u=new f.Vector3,p=[],h={};for(let m=0;m<n;m++){let S=e.splats[m],C=[S[H.OFFSET.X],S[H.OFFSET.Y],S[H.OFFSET.Z]],E=Math.floor((C[0]-i.x)/s),x=Math.floor((C[1]-i.y)/s),T=Math.floor((C[2]-i.z)/s);u.x=E*s+i.x+r,u.y=x*s+i.y+r,u.z=T*s+i.z+r;let R=E*(c*d)+x*d+T,y=h[R];y||(h[R]=y={splats:[],center:u.toArray()}),y.splats.push(m),y.splats.length>=t&&(p.push(y),h[R]=null)}let A=[];for(let m in h)if(h.hasOwnProperty(m)){let S=h[m];S&&A.push(S)}return{fullBuckets:p,partiallyFullBuckets:A}}static preallocateUncompressed(e,s){let t=l.CompressionLevels[0].SphericalHarmonicsDegrees[s],n=l.HeaderSizeBytes+l.SectionHeaderSizeBytes,r=n+t.BytesPerSplat*e,i=new ArrayBuffer(r);return l.writeHeaderToBuffer({versionMajor:l.CurrentMajorVersion,versionMinor:l.CurrentMinorVersion,maxSectionCount:1,sectionCount:1,maxSplatCount:e,splatCount:e,compressionLevel:0,sceneCenter:new f.Vector3},i),l.writeSectionHeaderToBuffer({maxSplatCount:e,splatCount:e,bucketSize:0,bucketCount:0,bucketBlockSize:0,compressionScaleRange:0,storageSizeBytes:0,fullBucketCount:0,partiallyFilledBucketCount:0,sphericalHarmonicsDegree:s},0,i,l.HeaderSizeBytes),{splatBuffer:new l(i,!0),splatBufferDataOffsetBytes:n}}},Ps=new Uint8Array([112,108,121,10]),Hs=new Uint8Array([10,101,110,100,95,104,101,97,100,101,114,10]),kt="end_header",Lt=new Map([["char",Int8Array],["uchar",Uint8Array],["short",Int16Array],["ushort",Uint16Array],["int",Int32Array],["uint",Uint32Array],["float",Float32Array],["double",Float64Array]]),we=(l,e)=>{let s=(1<<e)-1;return(l&s)/s},ks=(l,e)=>{l.x=we(e>>>21,11),l.y=we(e>>>11,10),l.z=we(e,11)},Qn=(l,e)=>{l.x=we(e>>>24,8),l.y=we(e>>>16,8),l.z=we(e>>>8,8),l.w=we(e,8)},Nn=(l,e)=>{let s=1/(Math.sqrt(2)*.5),t=(we(e>>>20,10)-.5)*s,n=(we(e>>>10,10)-.5)*s,r=(we(e,10)-.5)*s,i=Math.sqrt(1-(t*t+n*n+r*r));switch(e>>>30){case 0:l.set(i,t,n,r);break;case 1:l.set(t,i,n,r);break;case 2:l.set(t,n,i,r);break;case 3:l.set(t,n,r,i);break}},Fe=(l,e,s)=>l*(1-s)+e*s,re=(l,e)=>l.properties.find(s=>s.name===e&&s.storage)?.storage,Pe=class l{static decodeHeaderText(e){let s,t,n,r,i=e.split(`
4
+ `).filter(u=>!u.startsWith("comment ")),o=0,a=!1;for(let u=1;u<i.length;++u){let p=i[u].split(" ");switch(p[0]){case"format":if(p[1]!=="binary_little_endian")throw new Error("Unsupported ply format");break;case"element":s={name:p[1],count:parseInt(p[2],10),properties:[],storageSizeBytes:0},s.name==="chunk"?t=s:s.name==="vertex"?n=s:s.name==="sh"&&(r=s);break;case"property":{if(!Lt.has(p[1]))throw new Error(`Unrecognized property data type '${p[1]}' in ply header`);let h=Lt.get(p[1]),A=h.BYTES_PER_ELEMENT*s.count;s.name==="vertex"&&(o+=h.BYTES_PER_ELEMENT),s.properties.push({type:p[1],name:p[2],storage:null,byteSize:h.BYTES_PER_ELEMENT,storageSizeByes:A}),s.storageSizeBytes+=A;break}case kt:a=!0;break;default:throw new Error(`Unrecognized header value '${p[0]}' in ply header`)}if(a)break}let c=0,d=0;return r&&(d=r.properties.length,r.properties.length>=45?c=3:r.properties.length>=24?c=2:r.properties.length>=9&&(c=1)),{chunkElement:t,vertexElement:n,shElement:r,bytesPerSplat:o,headerSizeBytes:e.indexOf(kt)+kt.length+1,sphericalHarmonicsDegree:c,sphericalHarmonicsPerSplat:d}}static decodeHeader(e){let s=(h,A)=>{let m=h.length-A.length,S,C;for(S=0;S<=m;++S){for(C=0;C<A.length&&h[S+C]===A[C];++C);if(C===A.length)return S}return-1},t=(h,A)=>{if(h.length<A.length)return!1;for(let m=0;m<A.length;++m)if(h[m]!==A[m])return!1;return!0},n=new Uint8Array(e),r;if(n.length>=Ps.length&&!t(n,Ps))throw new Error("Invalid PLY header");if(r=s(n,Hs),r===-1)throw new Error("End of PLY header not found");let i=new TextDecoder("ascii").decode(n.slice(0,r)),{chunkElement:o,vertexElement:a,shElement:c,sphericalHarmonicsDegree:d,sphericalHarmonicsPerSplat:u,bytesPerSplat:p}=l.decodeHeaderText(i);return{headerSizeBytes:r+Hs.length,bytesPerSplat:p,chunkElement:o,vertexElement:a,shElement:c,sphericalHarmonicsDegree:d,sphericalHarmonicsPerSplat:u}}static readElementData(e,s,t,n,r,i=null){let o=s instanceof DataView?s:new DataView(s);n=n||0,r=r||e.count-1;for(let a=n;a<=r;++a)for(let c=0;c<e.properties.length;++c){let d=e.properties[c],u=Lt.get(d.type),p=u.BYTES_PER_ELEMENT*e.count;if((!d.storage||d.storage.byteLength<p)&&(!i||i(d.name))&&(d.storage=new u(e.count)),d.storage)switch(d.type){case"char":d.storage[a]=o.getInt8(t);break;case"uchar":d.storage[a]=o.getUint8(t);break;case"short":d.storage[a]=o.getInt16(t,!0);break;case"ushort":d.storage[a]=o.getUint16(t,!0);break;case"int":d.storage[a]=o.getInt32(t,!0);break;case"uint":d.storage[a]=o.getUint32(t,!0);break;case"float":d.storage[a]=o.getFloat32(t,!0);break;case"double":d.storage[a]=o.getFloat64(t,!0);break}t+=d.byteSize}return t}static readPly(e,s=null){let t=l.decodeHeader(e),n=l.readElementData(t.chunkElement,e,t.headerSizeBytes,null,null,s);return n=l.readElementData(t.vertexElement,e,n,null,null,s),l.readElementData(t.shElement,e,n,null,null,s),{chunkElement:t.chunkElement,vertexElement:t.vertexElement,shElement:t.shElement,sphericalHarmonicsDegree:t.sphericalHarmonicsDegree,sphericalHarmonicsPerSplat:t.sphericalHarmonicsPerSplat}}static getElementStorageArrays(e,s,t){let n={};if(s){let r=re(e,"min_r"),i=re(e,"min_g"),o=re(e,"min_b"),a=re(e,"max_r"),c=re(e,"max_g"),d=re(e,"max_b"),u=re(e,"min_x"),p=re(e,"min_y"),h=re(e,"min_z"),A=re(e,"max_x"),m=re(e,"max_y"),S=re(e,"max_z"),C=re(e,"min_scale_x"),E=re(e,"min_scale_y"),x=re(e,"min_scale_z"),T=re(e,"max_scale_x"),R=re(e,"max_scale_y"),y=re(e,"max_scale_z"),g=re(s,"packed_position"),I=re(s,"packed_rotation"),w=re(s,"packed_scale"),v=re(s,"packed_color");n.colorExtremes={minR:r,maxR:a,minG:i,maxG:c,minB:o,maxB:d},n.positionExtremes={minX:u,maxX:A,minY:p,maxY:m,minZ:h,maxZ:S},n.scaleExtremes={minScaleX:C,maxScaleX:T,minScaleY:E,maxScaleY:R,minScaleZ:x,maxScaleZ:y},n.position=g,n.rotation=I,n.scale=w,n.color=v}if(t){let r={};for(let i=0;i<45;i++){let o=`f_rest_${i}`,a=re(t,o);if(a)r[o]=a;else break}n.sh=r}return n}static decompressBaseSplat=function(){let e=new f.Vector3,s=new f.Quaternion,t=new f.Vector3,n=new f.Vector4,r=H.OFFSET;return function(i,o,a,c,d,u,p,h,A,m){m=m||H.createSplat();let S=Math.floor((o+i)/256);return ks(e,a[i]),Nn(s,p[i]),ks(t,d[i]),Qn(n,A[i]),m[r.X]=Fe(c.minX[S],c.maxX[S],e.x),m[r.Y]=Fe(c.minY[S],c.maxY[S],e.y),m[r.Z]=Fe(c.minZ[S],c.maxZ[S],e.z),m[r.ROTATION0]=s.x,m[r.ROTATION1]=s.y,m[r.ROTATION2]=s.z,m[r.ROTATION3]=s.w,m[r.SCALE0]=Math.exp(Fe(u.minScaleX[S],u.maxScaleX[S],t.x)),m[r.SCALE1]=Math.exp(Fe(u.minScaleY[S],u.maxScaleY[S],t.y)),m[r.SCALE2]=Math.exp(Fe(u.minScaleZ[S],u.maxScaleZ[S],t.z)),h.minR&&h.maxR?m[r.FDC0]=se(Math.round(Fe(h.minR[S],h.maxR[S],n.x)*255),0,255):m[r.FDC0]=se(Math.floor(n.x*255),0,255),h.minG&&h.maxG?m[r.FDC1]=se(Math.round(Fe(h.minG[S],h.maxG[S],n.y)*255),0,255):m[r.FDC1]=se(Math.floor(n.y*255),0,255),h.minB&&h.maxB?m[r.FDC2]=se(Math.round(Fe(h.minB[S],h.maxB[S],n.z)*255),0,255):m[r.FDC2]=se(Math.floor(n.z*255),0,255),m[r.OPACITY]=se(Math.floor(n.w*255),0,255),m}}();static decompressSphericalHarmonics=function(){let e=[0,3,8,15],s=[0,1,2,9,10,11,12,13,24,25,26,27,28,29,30,3,4,5,14,15,16,17,18,31,32,33,34,35,36,37,6,7,8,19,20,21,22,23,38,39,40,41,42,43,44];return function(t,n,r,i,o){o=o||H.createSplat();let a=e[r],c=e[i];for(let d=0;d<3;++d)for(let u=0;u<15;++u){let p=s[d*15+u];u<a&&u<c&&(o[H.OFFSET.FRC0+p]=n[d*c+u][t]*(8/255)-4)}return o}}();static parseToUncompressedSplatBufferSection(e,s,t,n,r,i,o,a,c=null){l.readElementData(s,i,0,t,n,c);let d=U.CompressionLevels[0].SphericalHarmonicsDegrees[0].BytesPerSplat,{positionExtremes:u,scaleExtremes:p,colorExtremes:h,position:A,rotation:m,scale:S,color:C}=l.getElementStorageArrays(e,s),E=H.createSplat();for(let x=t;x<=n;++x){l.decompressBaseSplat(x,r,A,u,S,p,m,h,C,E);let T=x*d+a;U.writeSplatDataToSectionBuffer(E,o,T,0,0)}}static parseToUncompressedSplatArraySection(e,s,t,n,r,i,o,a=null){l.readElementData(s,i,0,t,n,a);let{positionExtremes:c,scaleExtremes:d,colorExtremes:u,position:p,rotation:h,scale:A,color:m}=l.getElementStorageArrays(e,s);for(let S=t;S<=n;++S){let C=H.createSplat();l.decompressBaseSplat(S,r,p,c,A,d,h,u,m,C),o.addSplat(C)}}static parseSphericalHarmonicsToUncompressedSplatArraySection(e,s,t,n,r,i,o,a,c,d=null){l.readElementData(s,r,i,t,n,d);let{sh:u}=l.getElementStorageArrays(e,void 0,s),p=Object.values(u);for(let h=t;h<=n;++h)l.decompressSphericalHarmonics(h,p,o,a,c.splats[h])}static parseToUncompressedSplatArray(e,s){let{chunkElement:t,vertexElement:n,shElement:r,sphericalHarmonicsDegree:i}=l.readPly(e);s=Math.min(s,i);let o=new H(s),{positionExtremes:a,scaleExtremes:c,colorExtremes:d,position:u,rotation:p,scale:h,color:A}=l.getElementStorageArrays(t,n),m;if(s>0){let{sh:S}=l.getElementStorageArrays(t,void 0,r);m=Object.values(S)}for(let S=0;S<n.count;++S){o.addDefaultSplat();let C=o.getSplat(o.splatCount-1);l.decompressBaseSplat(S,0,u,a,h,c,p,d,A,C),s>0&&l.decompressSphericalHarmonics(S,m,s,i,C)}return o}static parseToUncompressedSplatBuffer(e,s){let{chunkElement:t,vertexElement:n,shElement:r,sphericalHarmonicsDegree:i}=l.readPly(e);s=Math.min(s,i);let{splatBuffer:o,splatBufferDataOffsetBytes:a}=U.preallocateUncompressed(n.count,s),{positionExtremes:c,scaleExtremes:d,colorExtremes:u,position:p,rotation:h,scale:A,color:m}=l.getElementStorageArrays(t,n),S;if(s>0){let{sh:x}=l.getElementStorageArrays(t,void 0,r);S=Object.values(x)}let C=U.CompressionLevels[0].SphericalHarmonicsDegrees[s].BytesPerSplat,E=H.createSplat(s);for(let x=0;x<n.count;++x){l.decompressBaseSplat(x,0,p,c,A,d,h,u,m,E),s>0&&l.decompressSphericalHarmonics(x,S,s,i,E);let T=x*C+a;U.writeSplatDataToSectionBuffer(E,o.bufferData,T,0,s)}return o}},ye={INRIAV1:0,INRIAV2:1,PlayCanvasCompressed:2},[cn,Ss,Cs,ys,xs,Es,Ts]=[0,1,2,3,4,5,6],Ls={double:cn,int:Ss,uint:Cs,float:ys,short:xs,ushort:Es,uchar:Ts},Gn={[cn]:8,[Ss]:4,[Cs]:4,[ys]:4,[xs]:2,[Es]:2,[Ts]:1},de=class l{static HeaderEndToken="end_header";static decodeSectionHeader(e,s,t=0){let n=[],r=!1,i=-1,o=0,a=!1,c=null,d=[],u=[],p=[],h=[],A={};for(let E=t;E<e.length;E++){let x=e[E].trim();if(x.startsWith("element"))if(r){i--;break}else{r=!0,t=E,i=E;let T=x.split(" "),R=0;for(let y of T){let g=y.trim();g.length>0&&(R++,R===2?c=g:R===3&&(o=parseInt(g)))}}else if(x.startsWith("property")){let T=x.match(/(\w+)\s+(\w+)\s+(\w+)/);if(T){let R=T[2],y=T[3];p.push(y);let g=s[y];A[y]=R;let I=Ls[R];g!==void 0&&(h.push(y),d.push(g),u[g]=I)}}if(x===l.HeaderEndToken){a=!0;break}r&&(n.push(x),i++)}let m=[],S=0;for(let E of p){let x=A[E];if(A.hasOwnProperty(E)){let T=s[E];T!==void 0&&(m[T]=S)}S+=Gn[Ls[x]]}let C=l.decodeSphericalHarmonicsFromSectionHeader(p,s);return{headerLines:n,headerStartLine:t,headerEndLine:i,fieldTypes:u,fieldIds:d,fieldOffsets:m,bytesPerVertex:S,vertexCount:o,dataSizeBytes:S*o,endOfHeader:a,sectionName:c,sphericalHarmonicsDegree:C.degree,sphericalHarmonicsCoefficientsPerChannel:C.coefficientsPerChannel,sphericalHarmonicsDegree1Fields:C.degree1Fields,sphericalHarmonicsDegree2Fields:C.degree2Fields}}static decodeSphericalHarmonicsFromSectionHeader(e,s){let t=0,n=0;for(let a of e)a.startsWith("f_rest")&&t++;n=t/3;let r=0;n>=3&&(r=1),n>=8&&(r=2);let i=[],o=[];for(let a=0;a<3;a++){if(r>=1)for(let c=0;c<3;c++)i.push(s["f_rest_"+(c+n*a)]);if(r>=2)for(let c=0;c<5;c++)o.push(s["f_rest_"+(c+n*a+3)])}return{degree:r,coefficientsPerChannel:n,degree1Fields:i,degree2Fields:o}}static getHeaderSectionNames(e){let s=[];for(let t of e)if(t.startsWith("element")){let n=t.split(" "),r=0;for(let i of n){let o=i.trim();o.length>0&&(r++,r===2&&s.push(o))}}return s}static checkTextForEndHeader(e){return!!e.includes(l.HeaderEndToken)}static checkBufferForEndHeader(e,s,t,n){let r=new Uint8Array(e,Math.max(0,s-t),t),i=n.decode(r);return l.checkTextForEndHeader(i)}static extractHeaderFromBufferToText(e){let s=new TextDecoder,t=0,n="",r=100;for(;;){if(t+r>=e.byteLength)throw new Error("End of file reached while searching for end of header");let i=new Uint8Array(e,t,r);if(n+=s.decode(i),t+=r,l.checkBufferForEndHeader(e,t,r*2,s))break}return n}static readHeaderFromBuffer(e){let s=new TextDecoder,t=0,n="",r=100;for(;;){if(t+r>=e.byteLength)throw new Error("End of file reached while searching for end of header");let i=new Uint8Array(e,t,r);if(n+=s.decode(i),t+=r,l.checkBufferForEndHeader(e,t,r*2,s))break}return n}static convertHeaderTextToLines(e){let s=e.split(`
5
+ `),t=[];for(let n=0;n<s.length;n++){let r=s[n].trim();if(t.push(r),r===l.HeaderEndToken)break}return t}static determineHeaderFormatFromHeaderText(e){let s=l.convertHeaderTextToLines(e),t=ye.INRIAV1;for(let n=0;n<s.length;n++){let r=s[n].trim();if(r.startsWith("element chunk")||r.match(/[A-Za-z]*packed_[A-Za-z]*/))t=ye.PlayCanvasCompressed;else if(r.startsWith("element codebook_centers"))t=ye.INRIAV2;else if(r===l.HeaderEndToken)break}return t}static determineHeaderFormatFromPlyBuffer(e){let s=l.extractHeaderFromBufferToText(e);return l.determineHeaderFormatFromHeaderText(s)}static readVertex(e,s,t,n,r,i,o=!0){let a=t*s.bytesPerVertex+n,c=s.fieldOffsets,d=s.fieldTypes;for(let u of r){let p=d[u];p===ys?i[u]=e.getFloat32(a+c[u],!0):p===xs?i[u]=e.getInt16(a+c[u],!0):p===Es?i[u]=e.getUint16(a+c[u],!0):p===Ss?i[u]=e.getInt32(a+c[u],!0):p===Cs?i[u]=e.getUint32(a+c[u],!0):p===Ts&&(o?i[u]=e.getUint8(a+c[u])/255:i[u]=e.getUint8(a+c[u]))}}},dn=["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"],Wn=dn.map((l,e)=>e),[Os,qn,Kn,jn,Yn,Xn,Jn,Zn,$n,er,Us,tr,sr,zs,_s,nr,rr,or]=Wn,He=class l{static decodeHeaderLines(e){let s=0;e.forEach(d=>{d.includes("f_rest_")&&s++});let t=0;s>=45?t=45:s>=24?t=24:s>=9&&(t=9);let r=Array.from(Array(Math.max(t-1,0))).map((d,u)=>`f_rest_${u+1}`),i=[...dn,...r],o=i.map((d,u)=>u),a=o.reduce((d,u)=>(d[i[u]]=u,d),{}),c=de.decodeSectionHeader(e,a,0);return c.splatCount=c.vertexCount,c.bytesPerSplat=c.bytesPerVertex,c.fieldsToReadIndexes=o,c}static decodeHeaderText(e){let s=de.convertHeaderTextToLines(e),t=l.decodeHeaderLines(s);return t.headerText=e,t.headerSizeBytes=e.indexOf(de.HeaderEndToken)+de.HeaderEndToken.length+1,t}static decodeHeaderFromBuffer(e){let s=de.readHeaderFromBuffer(e);return l.decodeHeaderText(s)}static findSplatData(e,s){return new DataView(e,s.headerSizeBytes)}static parseToUncompressedSplatBufferSection(e,s,t,n,r,i,o,a=0){a=Math.min(a,e.sphericalHarmonicsDegree);let c=U.CompressionLevels[0].SphericalHarmonicsDegrees[a].BytesPerSplat;for(let d=s;d<=t;d++){let u=l.parseToUncompressedSplat(n,d,e,r,a),p=d*c+o;U.writeSplatDataToSectionBuffer(u,i,p,0,a)}}static parseToUncompressedSplatArraySection(e,s,t,n,r,i,o=0){o=Math.min(o,e.sphericalHarmonicsDegree);for(let a=s;a<=t;a++){let c=l.parseToUncompressedSplat(n,a,e,r,o);i.addSplat(c)}}static decodeSectionSplatData(e,s,t,n,r=!0){if(n=Math.min(n,t.sphericalHarmonicsDegree),r){let i=new H(n);for(let o=0;o<s;o++){let a=l.parseToUncompressedSplat(e,o,t,0,n);i.addSplat(a)}return i}else{let{splatBuffer:i,splatBufferDataOffsetBytes:o}=U.preallocateUncompressed(s,n);return l.parseToUncompressedSplatBufferSection(t,0,s-1,e,0,i.bufferData,o,n),i}}static parseToUncompressedSplat=function(){let e=[],s=new f.Quaternion,t=H.OFFSET.X,n=H.OFFSET.Y,r=H.OFFSET.Z,i=H.OFFSET.SCALE0,o=H.OFFSET.SCALE1,a=H.OFFSET.SCALE2,c=H.OFFSET.ROTATION0,d=H.OFFSET.ROTATION1,u=H.OFFSET.ROTATION2,p=H.OFFSET.ROTATION3,h=H.OFFSET.FDC0,A=H.OFFSET.FDC1,m=H.OFFSET.FDC2,S=H.OFFSET.OPACITY,C=[];for(let E=0;E<45;E++)C[E]=H.OFFSET.FRC0+E;return function(E,x,T,R=0,y=0){y=Math.min(y,T.sphericalHarmonicsDegree),l.readSplat(E,T,x,R,e);let g=H.createSplat(y);if(e[Os]!==void 0?(g[i]=Math.exp(e[Os]),g[o]=Math.exp(e[qn]),g[a]=Math.exp(e[Kn])):(g[i]=.01,g[o]=.01,g[a]=.01),e[Us]!==void 0){let I=.28209479177387814;g[h]=(.5+I*e[Us])*255,g[A]=(.5+I*e[tr])*255,g[m]=(.5+I*e[sr])*255}else e[_s]!==void 0?(g[h]=e[_s]*255,g[A]=e[nr]*255,g[m]=e[rr]*255):(g[h]=0,g[A]=0,g[m]=0);if(e[zs]!==void 0&&(g[S]=1/(1+Math.exp(-e[zs]))*255),g[h]=se(Math.floor(g[h]),0,255),g[A]=se(Math.floor(g[A]),0,255),g[m]=se(Math.floor(g[m]),0,255),g[S]=se(Math.floor(g[S]),0,255),y>=1&&e[or]!==void 0){for(let I=0;I<9;I++)g[C[I]]=e[T.sphericalHarmonicsDegree1Fields[I]];if(y>=2)for(let I=0;I<15;I++)g[C[9+I]]=e[T.sphericalHarmonicsDegree2Fields[I]]}return s.set(e[jn],e[Yn],e[Xn],e[Jn]),s.normalize(),g[c]=s.x,g[d]=s.y,g[u]=s.z,g[p]=s.w,g[t]=e[Zn],g[n]=e[$n],g[r]=e[er],g}}();static readSplat(e,s,t,n,r){return de.readVertex(e,s,t,n,s.fieldsToReadIndexes,r,!0)}static parseToUncompressedSplatArray(e,s=0){let{header:t,splatCount:n,splatData:r}=Vs(e);return l.decodeSectionSplatData(r,n,t,s,!0)}static parseToUncompressedSplatBuffer(e,s=0){let{header:t,splatCount:n,splatData:r}=Vs(e);return l.decodeSectionSplatData(r,n,t,s,!1)}};function Vs(l){let e=He.decodeHeaderFromBuffer(l),s=e.splatCount,t=He.findSplatData(l,e);return{header:e,splatCount:s,splatData:t}}var un=["features_dc","features_rest_0","features_rest_1","features_rest_2","features_rest_3","features_rest_4","features_rest_5","features_rest_6","features_rest_7","features_rest_8","features_rest_9","features_rest_10","features_rest_11","features_rest_12","features_rest_13","features_rest_14","opacity","scaling","rotation_re","rotation_im"],pt=un.map((l,e)=>e),[ft,ir,ar,Qs,mt,lr,Ot]=[0,1,4,16,17,18,19],hn=["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","f_rest_1","f_rest_2","f_rest_3","f_rest_4","f_rest_5","f_rest_6","f_rest_7","f_rest_8","f_rest_9","f_rest_10","f_rest_11","f_rest_12","f_rest_13","f_rest_14","f_rest_15","f_rest_16","f_rest_17","f_rest_18","f_rest_19","f_rest_20","f_rest_21","f_rest_22","f_rest_23","f_rest_24","f_rest_25","f_rest_26","f_rest_27","f_rest_28","f_rest_29","f_rest_30","f_rest_31","f_rest_32","f_rest_33","f_rest_34","f_rest_35","f_rest_36","f_rest_37","f_rest_38","f_rest_39","f_rest_40","f_rest_41","f_rest_42","f_rest_43","f_rest_44","f_rest_45"],Nt=hn.map((l,e)=>e),[Ns,cr,dr,ur,hr,pr,fr,mr,Ar,gr,Gt,pn,fn,Gs]=Nt,Ws=Gt,Sr=pn,Cr=fn,At=l=>{let e=(31744&l)>>10,s=1023&l;return(l>>15?-1:1)*(e?e===31?s?NaN:1/0:Math.pow(2,e-15)*(1+s/1024):s/1024*6103515625e-14)},Wt=class l{static decodeSectionHeadersFromHeaderLines(e){let s=Nt.reduce((d,u)=>(d[hn[u]]=u,d),{}),t=pt.reduce((d,u)=>(d[un[u]]=u,d),{}),n=de.getHeaderSectionNames(e),r;for(let d=0;d<n.length;d++)n[d]==="codebook_centers"&&(r=d);let i=0,o=!1,a=[],c=0;for(;!o;){let d;c===r?d=de.decodeSectionHeader(e,t,i):d=de.decodeSectionHeader(e,s,i),o=d.endOfHeader,i=d.headerEndLine+1,o||(d.splatCount=d.vertexCount,d.bytesPerSplat=d.bytesPerVertex),a.push(d),c++}return a}static decodeSectionHeadersFromHeaderText(e){let s=de.convertHeaderTextToLines(e);return l.decodeSectionHeadersFromHeaderLines(s)}static getSplatCountFromSectionHeaders(e){let s=0;for(let t of e)t.sectionName!=="codebook_centers"&&(s+=t.vertexCount);return s}static decodeHeaderFromHeaderText(e){let s=e.indexOf(de.HeaderEndToken)+de.HeaderEndToken.length+1,t=l.decodeSectionHeadersFromHeaderText(e),n=l.getSplatCountFromSectionHeaders(t);return{headerSizeBytes:s,sectionHeaders:t,splatCount:n}}static decodeHeaderFromBuffer(e){let s=de.readHeaderFromBuffer(e);return l.decodeHeaderFromHeaderText(s)}static findVertexData(e,s,t){let n=s.headerSizeBytes;for(let r=0;r<t&&r<s.sectionHeaders.length;r++){let i=s.sectionHeaders[r];n+=i.dataSizeBytes}return new DataView(e,n,s.sectionHeaders[t].dataSizeBytes)}static decodeCodeBook(e,s){let t=[],n=[];for(let r=0;r<s.vertexCount;r++){de.readVertex(e,s,r,0,pt,t);for(let i of pt){let o=pt[i],a=n[o];a||(n[o]=a=[]),a.push(t[i])}}for(let r=0;r<n.length;r++){let i=n[r],o=.28209479177387814;for(let a=0;a<i.length;a++){let c=At(i[a]);r===Qs?i[a]=Math.round(1/(1+Math.exp(-c))*255):r===ft?i[a]=Math.round((.5+o*c)*255):r===mt?i[a]=Math.exp(c):i[a]=c}}return n}static decodeSectionSplatData(e,s,t,n,r){r=Math.min(r,t.sphericalHarmonicsDegree);let i=new H(r);for(let o=0;o<s;o++){let a=l.parseToUncompressedSplat(e,o,t,n,0,r);i.addSplat(a)}return i}static parseToUncompressedSplat=function(){let e=[],s=new f.Quaternion,t=H.OFFSET.X,n=H.OFFSET.Y,r=H.OFFSET.Z,i=H.OFFSET.SCALE0,o=H.OFFSET.SCALE1,a=H.OFFSET.SCALE2,c=H.OFFSET.ROTATION0,d=H.OFFSET.ROTATION1,u=H.OFFSET.ROTATION2,p=H.OFFSET.ROTATION3,h=H.OFFSET.FDC0,A=H.OFFSET.FDC1,m=H.OFFSET.FDC2,S=H.OFFSET.OPACITY,C=[];for(let E=0;E<45;E++)C[E]=H.OFFSET.FRC0+E;return function(E,x,T,R,y=0,g=0){g=Math.min(g,T.sphericalHarmonicsDegree),l.readSplat(E,T,x,y,e);let I=H.createSplat(g);if(e[Ns]!==void 0?(I[i]=R[mt][e[Ns]],I[o]=R[mt][e[cr]],I[a]=R[mt][e[dr]]):(I[i]=.01,I[o]=.01,I[a]=.01),e[Gt]!==void 0?(I[h]=R[ft][e[Gt]],I[A]=R[ft][e[pn]],I[m]=R[ft][e[fn]]):e[Ws]!==void 0?(I[h]=e[Ws]*255,I[A]=e[Sr]*255,I[m]=e[Cr]*255):(I[h]=0,I[A]=0,I[m]=0),e[Gs]!==void 0&&(I[S]=R[Qs][e[Gs]]),I[h]=se(Math.floor(I[h]),0,255),I[A]=se(Math.floor(I[A]),0,255),I[m]=se(Math.floor(I[m]),0,255),I[S]=se(Math.floor(I[S]),0,255),g>=1&&T.sphericalHarmonicsDegree>=1){for(let D=0;D<9;D++){let L=R[ir+D%3];I[C[D]]=L[e[T.sphericalHarmonicsDegree1Fields[D]]]}if(g>=2&&T.sphericalHarmonicsDegree>=2)for(let D=0;D<15;D++){let L=R[ar+D%5];I[C[9+D]]=L[e[T.sphericalHarmonicsDegree2Fields[D]]]}}let w=R[lr][e[ur]],v=R[Ot][e[hr]],M=R[Ot][e[pr]],b=R[Ot][e[fr]];return s.set(w,v,M,b),s.normalize(),I[c]=s.x,I[d]=s.y,I[u]=s.z,I[p]=s.w,I[t]=At(e[mr]),I[n]=At(e[Ar]),I[r]=At(e[gr]),I}}();static readSplat(e,s,t,n,r){return de.readVertex(e,s,t,n,Nt,r,!1)}static parseToUncompressedSplatArray(e,s=0){let t=[],n=l.decodeHeaderFromBuffer(e,s),r;for(let o=0;o<n.sectionHeaders.length;o++){let a=n.sectionHeaders[o];if(a.sectionName==="codebook_centers"){let c=l.findVertexData(e,n,o);r=l.decodeCodeBook(c,a)}}for(let o=0;o<n.sectionHeaders.length;o++){let a=n.sectionHeaders[o];if(a.sectionName!=="codebook_centers"){let c=a.vertexCount,d=l.findVertexData(e,n,o),u=l.decodeSectionSplatData(d,c,a,r,s);t.push(u)}}let i=new H(s);for(let o of t)for(let a of o.splats)i.addSplat(a);return i}},yt=class{static parseToUncompressedSplatArray(e,s=0){let t=de.determineHeaderFormatFromPlyBuffer(e);if(t===ye.PlayCanvasCompressed)return Pe.parseToUncompressedSplatArray(e,s);if(t===ye.INRIAV1)return He.parseToUncompressedSplatArray(e,s);if(t===ye.INRIAV2)return Wt.parseToUncompressedSplatArray(e,s)}static parseToUncompressedSplatBuffer(e,s=0){let t=de.determineHeaderFormatFromPlyBuffer(e);if(t===ye.PlayCanvasCompressed)return Pe.parseToUncompressedSplatBuffer(e,s);if(t===ye.INRIAV1)return He.parseToUncompressedSplatBuffer(e,s);if(t===ye.INRIAV2)throw new Error("parseToUncompressedSplatBuffer() is not implemented for INRIA V2 PLY files")}},qt=class l{constructor(e,s,t,n){this.sectionCount=e,this.sectionFilters=s,this.groupingParameters=t,this.partitionGenerator=n}partitionUncompressedSplatArray(e){let s,t,n;if(this.partitionGenerator){let i=this.partitionGenerator(e);s=i.groupingParameters,t=i.sectionCount,n=i.sectionFilters}else s=this.groupingParameters,t=this.sectionCount,n=this.sectionFilters;let r=[];for(let i=0;i<t;i++){let o=new H(e.sphericalHarmonicsDegree),a=n[i];for(let c=0;c<e.splatCount;c++)a(c)&&o.addSplat(e.splats[c]);r.push(o)}return{splatArrays:r,parameters:s}}static getStandardPartitioner(e=0,s=new f.Vector3,t=U.BucketBlockSize,n=U.BucketSize){let r=i=>{let o=H.OFFSET.X,a=H.OFFSET.Y,c=H.OFFSET.Z;e<=0&&(e=i.splatCount);let d=new f.Vector3,u=.5,p=C=>{C.x=Math.floor(C.x/u)*u,C.y=Math.floor(C.y/u)*u,C.z=Math.floor(C.z/u)*u};i.splats.forEach(C=>{d.set(C[o],C[a],C[c]).sub(s),p(d),C.centerDist=d.lengthSq()});let h=[],A=[];e=Math.min(i.splatCount,e);let m=Math.ceil(i.splatCount/e),S=0;for(let C=0;C<m;C++){let E=S;h.push(x=>x>=E&&x<E+e),A.push({blocksSize:t,bucketSize:n}),S+=e}return{sectionCount:h.length,sectionFilters:h,groupingParameters:A}};return new l(void 0,void 0,void 0,r)}},it=class l{constructor(e,s,t,n,r,i,o){this.splatPartitioner=e,this.alphaRemovalThreshold=s,this.compressionLevel=t,this.sectionSize=n,this.sceneCenter=r?new f.Vector3().copy(r):void 0,this.blockSize=i,this.bucketSize=o}generateFromUncompressedSplatArray(e){let s=this.splatPartitioner.partitionUncompressedSplatArray(e);return U.generateFromUncompressedSplatArrays(s.splatArrays,this.alphaRemovalThreshold,this.compressionLevel,this.sceneCenter,this.blockSize,this.bucketSize,s.parameters)}static getStandardGenerator(e=1,s=1,t=0,n=new f.Vector3,r=U.BucketBlockSize,i=U.BucketSize){let o=qt.getStandardPartitioner(t,n,r,i);return new l(o,e,s,t,n,r,i)}},ue={Downloading:0,Processing:1,Done:2},$e=class extends Error{constructor(e){super(e)}},$={ProgressiveToSplatBuffer:0,ProgressiveToSplatArray:1,DownloadBeforeProcessing:2};function qs(l,e){let s=0;for(let n of l)s+=n.sizeBytes;(!e||e.byteLength<s)&&(e=new ArrayBuffer(s));let t=0;for(let n of l)new Uint8Array(e,t,n.sizeBytes).set(n.data),t+=n.sizeBytes;return e}function Ks(l,e,s,t,n,r,i,o){return e?it.getStandardGenerator(s,t,n,r,i,o).generateFromUncompressedSplatArray(l):U.generateFromUncompressedSplatArrays([l],s,0,new f.Vector3)}var Kt=class l{static loadFromURL(e,s,t,n,r,i,o=!0,a=0,c,d,u,p,h){let A;!t&&!o?A=$.DownloadBeforeProcessing:o?A=$.ProgressiveToSplatArray:A=$.ProgressiveToSplatBuffer;let m=j.ProgressiveLoadSectionSize,S=U.HeaderSizeBytes+U.SectionHeaderSizeBytes,C=1,E,x,T,R,y,g=0,I=0,w=0,v=!1,M=!1,b=!1,D=fs(),L=0,F=0,P=0,z=0,O="",k=null,V=[],q,oe=new TextDecoder,N=(Ae,G,K)=>{let Y=Ae>=100;if(K&&(V.push({data:K,sizeBytes:K.byteLength,startBytes:P,endBytes:P+K.byteLength}),P+=K.byteLength),A===$.DownloadBeforeProcessing)Y&&D.resolve(V);else{if(v){if(E===ye.PlayCanvasCompressed&&!M){let ie=k.headerSizeBytes+k.chunkElement.storageSizeBytes;y=qs(V,y),y.byteLength>=ie&&(Pe.readElementData(k.chunkElement,y,k.headerSizeBytes),L=ie,F=ie,M=!0)}}else if(O+=oe.decode(K),de.checkTextForEndHeader(O)){if(E=de.determineHeaderFormatFromHeaderText(O),E===ye.INRIAV1)k=He.decodeHeaderText(O),a=Math.min(a,k.sphericalHarmonicsDegree),g=k.splatCount,M=!0,z=k.headerSizeBytes+k.bytesPerSplat*g;else if(E===ye.PlayCanvasCompressed){if(k=Pe.decodeHeaderText(O),a=Math.min(a,k.sphericalHarmonicsDegree),A===$.ProgressiveToSplatBuffer&&a>0)throw new $e("PlyLoader.loadFromURL() -> Selected PLY format has spherical harmonics data that cannot be progressively loaded.");g=k.vertexElement.count,z=k.headerSizeBytes+k.bytesPerSplat*g+k.chunkElement.storageSizeBytes}else{if(A===$.ProgressiveToSplatBuffer)throw new $e("PlyLoader.loadFromURL() -> Selected PLY format cannot be progressively loaded.");A=$.DownloadBeforeProcessing;return}if(A===$.ProgressiveToSplatBuffer){let ie=U.CompressionLevels[0].SphericalHarmonicsDegrees[a],ae=S+ie.BytesPerSplat*g;T=new ArrayBuffer(ae),U.writeHeaderToBuffer({versionMajor:U.CurrentMajorVersion,versionMinor:U.CurrentMinorVersion,maxSectionCount:C,sectionCount:C,maxSplatCount:g,splatCount:0,compressionLevel:0,sceneCenter:new f.Vector3},T)}else q=new H(a);L=k.headerSizeBytes,F=k.headerSizeBytes,v=!0}if(v&&M&&V.length>0&&(x=qs(V,x),P-L>m||P>=z&&!b||Y)){let ae=b?k.sphericalHarmonicsPerSplat:k.bytesPerSplat,me=(b?P:Math.min(z,P))-F,ee=Math.floor(me/ae),Se=ee*ae,ne=P-F-Se,Z=F-V[0].startBytes,le=new DataView(x,Z,Se);if(b)E===ye.PlayCanvasCompressed&&A===$.ProgressiveToSplatArray&&(Pe.parseSphericalHarmonicsToUncompressedSplatArraySection(k.chunkElement,k.shElement,w,w+ee-1,le,0,a,k.sphericalHarmonicsDegree,q),w+=ee);else{if(A===$.ProgressiveToSplatBuffer){let ve=U.CompressionLevels[0].SphericalHarmonicsDegrees[a],fe=I*ve.BytesPerSplat+S;E===ye.PlayCanvasCompressed?Pe.parseToUncompressedSplatBufferSection(k.chunkElement,k.vertexElement,0,ee-1,I,le,T,fe):He.parseToUncompressedSplatBufferSection(k,0,ee-1,le,0,T,fe,a)}else E===ye.PlayCanvasCompressed?Pe.parseToUncompressedSplatArraySection(k.chunkElement,k.vertexElement,0,ee-1,I,le,q):He.parseToUncompressedSplatArraySection(k,0,ee-1,le,0,q,a);I+=ee,A===$.ProgressiveToSplatBuffer&&(R||(U.writeSectionHeaderToBuffer({maxSplatCount:g,splatCount:I,bucketSize:0,bucketCount:0,bucketBlockSize:0,compressionScaleRange:0,storageSizeBytes:0,fullBucketCount:0,partiallyFilledBucketCount:0,sphericalHarmonicsDegree:a},0,T,U.HeaderSizeBytes),R=new U(T,!1)),R.updateLoadedCounts(1,I)),P>=z&&(b=!0)}if(ne===0)V=[];else{let ve=[],fe=0;for(let xe=V.length-1;xe>=0;xe--){let ke=V[xe];if(fe+=ke.sizeBytes,ve.unshift(ke),fe>=ne)break}V=ve}L+=m,F+=Se}n&&R&&n(R,Y),Y&&(A===$.ProgressiveToSplatBuffer?D.resolve(R):D.resolve(q))}s&&s(Ae,G,ue.Downloading)};return s&&s(0,"0%",ue.Downloading),Et(e,N,!1,c).then(()=>(s&&s(0,"0%",ue.Processing),D.promise.then(Ae=>{if(s&&s(100,"100%",ue.Done),A===$.DownloadBeforeProcessing){let G=V.map(K=>K.data);return new Blob(G).arrayBuffer().then(K=>l.loadFromFileData(K,r,i,o,a,d,u,p,h))}else return A===$.ProgressiveToSplatBuffer?Ae:Re(()=>Ks(Ae,o,r,i,d,u,p,h))})))}static loadFromFileData(e,s,t,n,r=0,i,o,a,c){return n?Re(()=>yt.parseToUncompressedSplatArray(e,r)).then(d=>Ks(d,n,s,t,i,o,a,c)):Re(()=>yt.parseToUncompressedSplatBuffer(e,r))}},yr=l=>new ReadableStream({async start(e){e.enqueue(l),e.close()}});async function xr(l){try{let e=yr(l);if(!e)throw new Error("Failed to create stream from data");return await Er(e)}catch(e){throw console.error("Error decompressing gzipped data:",e),e}}async function Er(l){let e=l.pipeThrough(new DecompressionStream("gzip")),t=await new Response(e).arrayBuffer();return new Uint8Array(t)}var Tr=1347635022,Rr=1,Ir=.15;function Br(l){let e=l>>15&1,s=l>>10&31,t=l&1023,n=e===1?-1:1;return s===0?n*Math.pow(2,-14)*t/1024:s===31?t!==0?NaN:n*(1/0):n*Math.pow(2,s-15)*(1+t/1024)}function vr(l){return(l-128)/128}function Ve(l){switch(l){case 0:return 0;case 1:return 3;case 2:return 8;case 3:return 15;default:return console.error(`[SPZ: ERROR] Unsupported SH degree: ${l}`),0}}var wr=function(){let l=[],e=new f.Quaternion,s=H.OFFSET.X,t=H.OFFSET.Y,n=H.OFFSET.Z,r=H.OFFSET.SCALE0,i=H.OFFSET.SCALE1,o=H.OFFSET.SCALE2,a=H.OFFSET.ROTATION0,c=H.OFFSET.ROTATION1,d=H.OFFSET.ROTATION2,u=H.OFFSET.ROTATION3,p=H.OFFSET.FDC0,h=H.OFFSET.FDC1,A=H.OFFSET.FDC2,m=H.OFFSET.OPACITY,S=[];for(let x=0;x<45;x++)S[x]=H.OFFSET.FRC0+x;let C=[Ve(0),Ve(1),Ve(2),Ve(3)],E=[0,1,2,9,10,11,12,13,24,25,26,27,28,29,30,3,4,5,14,15,16,17,18,31,32,33,34,35,36,37,6,7,8,19,20,21,22,23,38,39,40,41,42,43,44];return function(x,T,R){R=Math.min(T,R);let y=H.createSplat(R);x.scale[0]!==void 0?(y[r]=x.scale[0],y[i]=x.scale[1],y[o]=x.scale[2]):(y[r]=.01,y[i]=.01,y[o]=.01),x.color[0]!==void 0?(y[p]=x.color[0],y[h]=x.color[1],y[A]=x.color[2]):l[RED]!==void 0?(y[p]=l[RED]*255,y[h]=l[GREEN]*255,y[A]=l[BLUE]*255):(y[p]=0,y[h]=0,y[A]=0),x.alpha!==void 0&&(y[m]=x.alpha),y[p]=se(Math.floor(y[p]),0,255),y[h]=se(Math.floor(y[h]),0,255),y[A]=se(Math.floor(y[A]),0,255),y[m]=se(Math.floor(y[m]),0,255);let g=C[R],I=C[T];for(let w=0;w<3;++w)for(let v=0;v<15;++v){let M=E[w*15+v];v<g&&v<I&&(y[H.OFFSET.FRC0+M]=x.sh[w*I+v])}return e.set(x.rotation[3],x.rotation[0],x.rotation[1],x.rotation[2]),e.normalize(),y[a]=e.x,y[c]=e.y,y[d]=e.z,y[u]=e.w,y[s]=x.position[0],y[t]=x.position[1],y[n]=x.position[2],y}}();function Mr(l,e,s,t){return!(l.positions.length!==e*3*(t?2:3)||l.scales.length!==e*3||l.rotations.length!==e*3||l.alphas.length!==e||l.colors.length!==e*3||l.sh.length!==e*s*3)}function js(l,e,s,t,n){e=Math.min(e,l.shDegree);let r=l.numPoints,i=Ve(l.shDegree),o=l.positions.length===r*3*2;if(!Mr(l,r,i,o))return null;let a={position:[],scale:[],rotation:[],alpha:void 0,color:[],sh:[]},c;o&&(c=new Uint16Array(l.positions.buffer,l.positions.byteOffset,r*3));let d=1/(1<<l.fractionalBits),u=Ve(l.shDegree),p=.28209479177387814;for(let h=0;h<r;h++){if(o)for(let E=0;E<3;E++)a.position[E]=Br(c[h*3+E]);else for(let E=0;E<3;E++){let x=h*9+E*3,T=l.positions[x];T|=l.positions[x+1]<<8,T|=l.positions[x+2]<<16,T|=T&8388608?4278190080:0,a.position[E]=T*d}for(let E=0;E<3;E++)a.scale[E]=Math.exp(l.scales[h*3+E]/16-10);let A=l.rotations.subarray(h*3,h*3+3),m=[A[0]/127.5-1,A[1]/127.5-1,A[2]/127.5-1];a.rotation[0]=m[0],a.rotation[1]=m[1],a.rotation[2]=m[2];let S=m[0]*m[0]+m[1]*m[1]+m[2]*m[2];a.rotation[3]=Math.sqrt(Math.max(0,1-S)),a.alpha=Math.floor(l.alphas[h]);for(let E=0;E<3;E++)a.color[E]=Math.floor(((l.colors[h*3+E]/255-.5)/Ir*p+.5)*255);for(let E=0;E<3;E++)for(let x=0;x<u;x++)a.sh[E*u+x]=vr(l.sh[u*3*h+x*3+E]);let C=wr(a,l.shDegree,e);if(s){let E=U.CompressionLevels[0].SphericalHarmonicsDegrees[e].BytesPerSplat,x=h*E+n;U.writeSplatDataToSectionBuffer(C,t,x,0,e)}else t.addSplat(C)}}var br=16,Fr=1e7;function Dr(l){let e=new DataView(l),s=0,t={magic:e.getUint32(s,!0),version:e.getUint32(s+4,!0),numPoints:e.getUint32(s+8,!0),shDegree:e.getUint8(s+12),fractionalBits:e.getUint8(s+13),flags:e.getUint8(s+14),reserved:e.getUint8(s+15)};if(s+=br,t.magic!==Tr)return console.error("[SPZ ERROR] deserializePackedGaussians: header not found"),null;if(t.version<1||t.version>2)return console.error(`[SPZ ERROR] deserializePackedGaussians: version not supported: ${t.version}`),null;if(t.numPoints>Fr)return console.error(`[SPZ ERROR] deserializePackedGaussians: Too many points: ${t.numPoints}`),null;if(t.shDegree>3)return console.error(`[SPZ ERROR] deserializePackedGaussians: Unsupported SH degree: ${t.shDegree}`),null;let n=t.numPoints,r=Ve(t.shDegree),i=t.version===1,o={numPoints:n,shDegree:t.shDegree,fractionalBits:t.fractionalBits,antialiased:(t.flags&Rr)!==0,positions:new Uint8Array(n*3*(i?2:3)),scales:new Uint8Array(n*3),rotations:new Uint8Array(n*3),alphas:new Uint8Array(n),colors:new Uint8Array(n*3),sh:new Uint8Array(n*r*3)};try{let a=new Uint8Array(l),c=o.positions.length,d=s;if(o.positions.set(a.slice(d,d+c)),d+=c,o.alphas.set(a.slice(d,d+o.alphas.length)),d+=o.alphas.length,o.colors.set(a.slice(d,d+o.colors.length)),d+=o.colors.length,o.scales.set(a.slice(d,d+o.scales.length)),d+=o.scales.length,o.rotations.set(a.slice(d,d+o.rotations.length)),d+=o.rotations.length,o.sh.set(a.slice(d,d+o.sh.length)),d+o.sh.length!==l.byteLength)return console.error("[SPZ ERROR] deserializePackedGaussians: incorrect buffer size"),null}catch(a){return console.error("[SPZ ERROR] deserializePackedGaussians: read error",a),null}return o}async function Pr(l){try{let e=await xr(l);return Dr(e.buffer)}catch(e){return console.error("[SPZ ERROR] loadSpzPacked: decompression error",e),null}}var jt=class l{static loadFromURL(e,s,t,n,r=!0,i=0,o,a,c,d,u){return s&&s(0,"0%",ue.Downloading),Et(e,s,!0,o).then(p=>(s&&s(0,"0%",ue.Processing),l.loadFromFileData(p,t,n,r,i,a,c,d,u)))}static async loadFromFileData(e,s,t,n,r=0,i,o,a,c){await Re();let d=await Pr(e);r=Math.min(d.shDegree,r);let u=new H(r);if(n)return js(d,r,!1,u,0),it.getStandardGenerator(s,t,i,o,a,c).generateFromUncompressedSplatArray(u);{let{splatBuffer:p,splatBufferDataOffsetBytes:h}=U.preallocateUncompressed(d.numPoints,r);return js(d,r,!0,p.bufferData,h),p}}},_e=class l{static RowSizeBytes=32;static CenterSizeBytes=12;static ScaleSizeBytes=12;static RotationSizeBytes=4;static ColorSizeBytes=4;static parseToUncompressedSplatBufferSection(e,s,t,n,r,i){let o=U.CompressionLevels[0].BytesPerCenter,a=U.CompressionLevels[0].BytesPerScale,c=U.CompressionLevels[0].BytesPerRotation,d=U.CompressionLevels[0].SphericalHarmonicsDegrees[0].BytesPerSplat;for(let u=e;u<=s;u++){let p=u*l.RowSizeBytes+n,h=new Float32Array(t,p,3),A=new Float32Array(t,p+l.CenterSizeBytes,3),m=new Uint8Array(t,p+l.CenterSizeBytes+l.ScaleSizeBytes,4),S=new Uint8Array(t,p+l.CenterSizeBytes+l.ScaleSizeBytes+l.RotationSizeBytes,4),C=new f.Quaternion((S[1]-128)/128,(S[2]-128)/128,(S[3]-128)/128,(S[0]-128)/128);C.normalize();let E=u*d+i,x=new Float32Array(r,E,3),T=new Float32Array(r,E+o,3),R=new Float32Array(r,E+o+a,4),y=new Uint8Array(r,E+o+a+c,4);x[0]=h[0],x[1]=h[1],x[2]=h[2],T[0]=A[0],T[1]=A[1],T[2]=A[2],R[0]=C.w,R[1]=C.x,R[2]=C.y,R[3]=C.z,y[0]=m[0],y[1]=m[1],y[2]=m[2],y[3]=m[3]}}static parseToUncompressedSplatArraySection(e,s,t,n,r){for(let i=e;i<=s;i++){let o=i*l.RowSizeBytes+n,a=new Float32Array(t,o,3),c=new Float32Array(t,o+l.CenterSizeBytes,3),d=new Uint8Array(t,o+l.CenterSizeBytes+l.ScaleSizeBytes,4),u=new Uint8Array(t,o+l.CenterSizeBytes+l.ScaleSizeBytes+l.RotationSizeBytes,4),p=new f.Quaternion((u[1]-128)/128,(u[2]-128)/128,(u[3]-128)/128,(u[0]-128)/128);p.normalize(),r.addSplatFromComonents(a[0],a[1],a[2],c[0],c[1],c[2],p.w,p.x,p.y,p.z,d[0],d[1],d[2],d[3])}}static parseStandardSplatToUncompressedSplatArray(e){let s=e.byteLength/l.RowSizeBytes,t=new H;for(let n=0;n<s;n++){let r=n*l.RowSizeBytes,i=new Float32Array(e,r,3),o=new Float32Array(e,r+l.CenterSizeBytes,3),a=new Uint8Array(e,r+l.CenterSizeBytes+l.ScaleSizeBytes,4),c=new Uint8Array(e,r+l.CenterSizeBytes+l.ScaleSizeBytes+l.ColorSizeBytes,4),d=new f.Quaternion((c[1]-128)/128,(c[2]-128)/128,(c[3]-128)/128,(c[0]-128)/128);d.normalize(),t.addSplatFromComonents(i[0],i[1],i[2],o[0],o[1],o[2],d.w,d.x,d.y,d.z,a[0],a[1],a[2],a[3])}return t}};function Ys(l,e,s,t,n,r,i,o){return e?it.getStandardGenerator(s,t,n,r,i,o).generateFromUncompressedSplatArray(l):U.generateFromUncompressedSplatArrays([l],s,0,new f.Vector3)}var Yt=class l{static loadFromURL(e,s,t,n,r,i,o=!0,a,c,d,u,p){let h=t?$.ProgressiveToSplatBuffer:$.ProgressiveToSplatArray;o&&(h=$.ProgressiveToSplatArray);let A=U.HeaderSizeBytes+U.SectionHeaderSizeBytes,m=j.ProgressiveLoadSectionSize,S=1,C,E,x,T=0,R=0,y,g=fs(),I=0,w=0,v=[],M=(b,D,L,F)=>{let P=b>=100;if(L&&v.push(L),h===$.DownloadBeforeProcessing){P&&g.resolve(v);return}if(!F){if(t)throw new $e("Cannon directly load .splat because no file size info is available.");h=$.DownloadBeforeProcessing;return}if(!C){T=F/_e.RowSizeBytes,C=new ArrayBuffer(F);let z=U.CompressionLevels[0].SphericalHarmonicsDegrees[0].BytesPerSplat,O=A+z*T;h===$.ProgressiveToSplatBuffer?(E=new ArrayBuffer(O),U.writeHeaderToBuffer({versionMajor:U.CurrentMajorVersion,versionMinor:U.CurrentMinorVersion,maxSectionCount:S,sectionCount:S,maxSplatCount:T,splatCount:R,compressionLevel:0,sceneCenter:new f.Vector3},E)):y=new H(0)}if(L){new Uint8Array(C,w,L.byteLength).set(new Uint8Array(L)),w+=L.byteLength;let z=w-I;if(z>m||P){let k=(P?z:m)/_e.RowSizeBytes,V=R+k;h===$.ProgressiveToSplatBuffer?_e.parseToUncompressedSplatBufferSection(R,V-1,C,0,E,A):_e.parseToUncompressedSplatArraySection(R,V-1,C,0,y),R=V,h===$.ProgressiveToSplatBuffer&&(x||(U.writeSectionHeaderToBuffer({maxSplatCount:T,splatCount:R,bucketSize:0,bucketCount:0,bucketBlockSize:0,compressionScaleRange:0,storageSizeBytes:0,fullBucketCount:0,partiallyFilledBucketCount:0},0,E,U.HeaderSizeBytes),x=new U(E,!1)),x.updateLoadedCounts(1,R),n&&n(x,P)),I+=m}}P&&(h===$.ProgressiveToSplatBuffer?g.resolve(x):g.resolve(y)),s&&s(b,D,ue.Downloading)};return s&&s(0,"0%",ue.Downloading),Et(e,M,!1,a).then(()=>(s&&s(0,"0%",ue.Processing),g.promise.then(b=>(s&&s(100,"100%",ue.Done),h===$.DownloadBeforeProcessing?new Blob(v).arrayBuffer().then(D=>l.loadFromFileData(D,r,i,o,c,d,u,p)):h===$.ProgressiveToSplatBuffer?b:Re(()=>Ys(b,o,r,i,c,d,u,p))))))}static loadFromFileData(e,s,t,n,r,i,o,a){return Re(()=>{let c=_e.parseStandardSplatToUncompressedSplatArray(e);return Ys(c,n,s,t,r,i,o,a)})}},Xt=class l{static checkVersion(e){let s=U.CurrentMajorVersion,t=U.CurrentMinorVersion,n=U.parseHeader(e);if(n.versionMajor===s&&n.versionMinor>=t||n.versionMajor>s)return!0;throw new Error(`KSplat version not supported: v${n.versionMajor}.${n.versionMinor}. Minimum required: v${s}.${t}`)}static loadFromURL(e,s,t,n,r){let i,o,a,c,d=!1,u=!1,p,h=[],A=!1,m=!1,S=0,C=0,E=0,x=!1,T=!1,R=!1,y=[],g=fs(),I=()=>{!d&&!u&&S>=U.HeaderSizeBytes&&(u=!0,new Blob(y).arrayBuffer().then(F=>{a=new ArrayBuffer(U.HeaderSizeBytes),new Uint8Array(a).set(new Uint8Array(F,0,U.HeaderSizeBytes)),l.checkVersion(a),u=!1,d=!0,c=U.parseHeader(a),window.setTimeout(()=>{M()},1)}))},w=0,v=()=>{w===0&&(w++,window.setTimeout(()=>{w--,b()},1))},M=()=>{let L=()=>{m=!0,new Blob(y).arrayBuffer().then(P=>{m=!1,A=!0,p=new ArrayBuffer(c.maxSectionCount*U.SectionHeaderSizeBytes),new Uint8Array(p).set(new Uint8Array(P,U.HeaderSizeBytes,c.maxSectionCount*U.SectionHeaderSizeBytes)),h=U.parseSectionHeaders(c,p,0,!1);let z=0;for(let k=0;k<c.maxSectionCount;k++)z+=h[k].storageSizeBytes;let O=U.HeaderSizeBytes+c.maxSectionCount*U.SectionHeaderSizeBytes+z;if(!i){i=new ArrayBuffer(O);let k=0;for(let V=0;V<y.length;V++){let q=y[V];new Uint8Array(i,k,q.byteLength).set(new Uint8Array(q)),k+=q.byteLength}}E=U.HeaderSizeBytes+U.SectionHeaderSizeBytes*c.maxSectionCount;for(let k=0;k<=h.length&&k<c.maxSectionCount;k++)E+=h[k].storageSizeBytes;v()})};!m&&!A&&d&&S>=U.HeaderSizeBytes+U.SectionHeaderSizeBytes*c.maxSectionCount&&L()},b=()=>{if(R)return;R=!0;let L=()=>{if(R=!1,A){if(T)return;if(x=S>=E,S-C>j.ProgressiveLoadSectionSize||x){C+=j.ProgressiveLoadSectionSize,T=C>=E,o||(o=new U(i,!1));let P=U.HeaderSizeBytes+U.SectionHeaderSizeBytes*c.maxSectionCount,z=0,O=0,k=0;for(let oe=0;oe<c.maxSectionCount;oe++){let N=h[oe],Ae=z+N.partiallyFilledBucketCount*4+N.bucketStorageSizeBytes*N.bucketCount,G=P+Ae;if(C>=G){O++;let K=C-G,ae=U.CompressionLevels[c.compressionLevel].SphericalHarmonicsDegrees[N.sphericalHarmonicsDegree].BytesPerSplat,ge=Math.floor(K/ae);ge=Math.min(ge,N.maxSplatCount),k+=ge,o.updateLoadedCounts(O,k),o.updateSectionLoadedCounts(oe,ge)}else break;z+=N.storageSizeBytes}n(o,T);let V=C/E*100,q=V.toFixed(2)+"%";s&&s(V,q,ue.Downloading),T?g.resolve(o):b()}}};window.setTimeout(L,j.ProgressiveLoadSectionDelayDuration)};return Et(e,(L,F,P)=>{P&&(y.push(P),i&&new Uint8Array(i,S,P.byteLength).set(new Uint8Array(P)),S+=P.byteLength),t?(I(),M(),b()):s&&s(L,F,ue.Downloading)},!t,r).then(L=>(s&&s(0,"0%",ue.Processing),(t?g.promise:l.loadFromFileData(L)).then(P=>(s&&s(100,"100%",ue.Done),P))))}static loadFromFileData(e){return Re(()=>(l.checkVersion(e),new U(e)))}static downloadFile=function(){let e;return function(s,t){let n=new Blob([s.bufferData],{type:"application/octet-stream"});e||(e=document.createElement("a"),document.body.appendChild(e)),e.download=t,e.href=URL.createObjectURL(n),e.click()}}()},Ce={Splat:0,KSplat:1,Ply:2,Spz:3},Xs=l=>l.endsWith(".ply")?Ce.Ply:l.endsWith(".splat")?Ce.Splat:l.endsWith(".ksplat")?Ce.KSplat:l.endsWith(".spz")?Ce.Spz:Ce.Ply;var Js={type:"change"},Ut={type:"start"},Zs={type:"end"},gt=new Pn,$s=new Hn,Hr=Math.cos(70*kn.DEG2RAD),Xe=class extends Ln{constructor(e,s){super(),this.object=e,this.domElement=s,this.domElement.style.touchAction="none",this.enabled=!0,this.target=new Te,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"KeyA",UP:"KeyW",RIGHT:"KeyD",BOTTOM:"KeyS"},this.mouseButtons={LEFT:Ge.ROTATE,MIDDLE:Ge.DOLLY,RIGHT:Ge.PAN},this.touches={ONE:We.ROTATE,TWO:We.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this.getPolarAngle=function(){return o.phi},this.getAzimuthalAngle=function(){return o.theta},this.getDistance=function(){return this.object.position.distanceTo(this.target)},this.listenToKeyEvents=function(B){B.addEventListener("keydown",It),this._domElementKeyEvents=B},this.stopListenToKeyEvents=function(){this._domElementKeyEvents.removeEventListener("keydown",It),this._domElementKeyEvents=null},this.saveState=function(){t.target0.copy(t.target),t.position0.copy(t.object.position),t.zoom0=t.object.zoom},this.reset=function(){t.target.copy(t.target0),t.object.position.copy(t.position0),t.object.zoom=t.zoom0,this.clearDampedRotation(),this.clearDampedPan(),t.object.updateProjectionMatrix(),t.dispatchEvent(Js),t.update(),r=n.NONE},this.clearDampedRotation=function(){a.theta=0,a.phi=0},this.clearDampedPan=function(){d.set(0,0,0)},this.update=function(){let B=new Te,_=new Fs().setFromUnitVectors(e.up,new Te(0,1,0)),ce=_.clone().invert(),he=new Te,Ee=new Fs,Qe=new Te,Le=2*Math.PI;return function(){_.setFromUnitVectors(e.up,new Te(0,1,0)),ce.copy(_).invert();let vs=t.object.position;B.copy(vs).sub(t.target),B.applyQuaternion(_),o.setFromVector3(B),t.autoRotate&&r===n.NONE&&M(w()),t.enableDamping?(o.theta+=a.theta*t.dampingFactor,o.phi+=a.phi*t.dampingFactor):(o.theta+=a.theta,o.phi+=a.phi);let Me=t.minAzimuthAngle,be=t.maxAzimuthAngle;isFinite(Me)&&isFinite(be)&&(Me<-Math.PI?Me+=Le:Me>Math.PI&&(Me-=Le),be<-Math.PI?be+=Le:be>Math.PI&&(be-=Le),Me<=be?o.theta=Math.max(Me,Math.min(be,o.theta)):o.theta=o.theta>(Me+be)/2?Math.max(Me,o.theta):Math.min(be,o.theta)),o.phi=Math.max(t.minPolarAngle,Math.min(t.maxPolarAngle,o.phi)),o.makeSafe(),t.enableDamping===!0?t.target.addScaledVector(d,t.dampingFactor):t.target.add(d),t.zoomToCursor&&y||t.object.isOrthographicCamera?o.radius=k(o.radius):o.radius=k(o.radius*c),B.setFromSpherical(o),B.applyQuaternion(ce),vs.copy(t.target).add(B),t.object.lookAt(t.target),t.enableDamping===!0?(a.theta*=1-t.dampingFactor,a.phi*=1-t.dampingFactor,d.multiplyScalar(1-t.dampingFactor)):(a.set(0,0,0),d.set(0,0,0));let lt=!1;if(t.zoomToCursor&&y){let et=null;if(t.object.isPerspectiveCamera){let tt=B.length();et=k(tt*c);let ct=tt-et;t.object.position.addScaledVector(T,ct),t.object.updateMatrixWorld()}else if(t.object.isOrthographicCamera){let tt=new Te(R.x,R.y,0);tt.unproject(t.object),t.object.zoom=Math.max(t.minZoom,Math.min(t.maxZoom,t.object.zoom/c)),t.object.updateProjectionMatrix(),lt=!0;let ct=new Te(R.x,R.y,0);ct.unproject(t.object),t.object.position.sub(ct).add(tt),t.object.updateMatrixWorld(),et=B.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),t.zoomToCursor=!1;et!==null&&(this.screenSpacePanning?t.target.set(0,0,-1).transformDirection(t.object.matrix).multiplyScalar(et).add(t.object.position):(gt.origin.copy(t.object.position),gt.direction.set(0,0,-1).transformDirection(t.object.matrix),Math.abs(t.object.up.dot(gt.direction))<Hr?e.lookAt(t.target):($s.setFromNormalAndCoplanarPoint(t.object.up,t.target),gt.intersectPlane($s,t.target))))}else t.object.isOrthographicCamera&&(t.object.zoom=Math.max(t.minZoom,Math.min(t.maxZoom,t.object.zoom/c)),t.object.updateProjectionMatrix(),lt=!0);return c=1,y=!1,lt||he.distanceToSquared(t.object.position)>i||8*(1-Ee.dot(t.object.quaternion))>i||Qe.distanceToSquared(t.target)>0?(t.dispatchEvent(Js),he.copy(t.object.position),Ee.copy(t.object.quaternion),Qe.copy(t.target),lt=!1,!0):!1}}(),this.dispose=function(){t.domElement.removeEventListener("contextmenu",Is),t.domElement.removeEventListener("pointerdown",fe),t.domElement.removeEventListener("pointercancel",ke),t.domElement.removeEventListener("wheel",Rs),t.domElement.removeEventListener("pointermove",xe),t.domElement.removeEventListener("pointerup",ke),t._domElementKeyEvents!==null&&(t._domElementKeyEvents.removeEventListener("keydown",It),t._domElementKeyEvents=null)};let t=this,n={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},r=n.NONE,i=1e-6,o=new Ds,a=new Ds,c=1,d=new Te,u=new Ie,p=new Ie,h=new Ie,A=new Ie,m=new Ie,S=new Ie,C=new Ie,E=new Ie,x=new Ie,T=new Te,R=new Ie,y=!1,g=[],I={};function w(){return 2*Math.PI/60/60*t.autoRotateSpeed}function v(){return Math.pow(.95,t.zoomSpeed)}function M(B){a.theta-=B}function b(B){a.phi-=B}let D=function(){let B=new Te;return function(ce,he){B.setFromMatrixColumn(he,0),B.multiplyScalar(-ce),d.add(B)}}(),L=function(){let B=new Te;return function(ce,he){t.screenSpacePanning===!0?B.setFromMatrixColumn(he,1):(B.setFromMatrixColumn(he,0),B.crossVectors(t.object.up,B)),B.multiplyScalar(ce),d.add(B)}}(),F=function(){let B=new Te;return function(ce,he){let Ee=t.domElement;if(t.object.isPerspectiveCamera){let Qe=t.object.position;B.copy(Qe).sub(t.target);let Le=B.length();Le*=Math.tan(t.object.fov/2*Math.PI/180),D(2*ce*Le/Ee.clientHeight,t.object.matrix),L(2*he*Le/Ee.clientHeight,t.object.matrix)}else t.object.isOrthographicCamera?(D(ce*(t.object.right-t.object.left)/t.object.zoom/Ee.clientWidth,t.object.matrix),L(he*(t.object.top-t.object.bottom)/t.object.zoom/Ee.clientHeight,t.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),t.enablePan=!1)}}();function P(B){t.object.isPerspectiveCamera||t.object.isOrthographicCamera?c/=B:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),t.enableZoom=!1)}function z(B){t.object.isPerspectiveCamera||t.object.isOrthographicCamera?c*=B:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),t.enableZoom=!1)}function O(B){if(!t.zoomToCursor)return;y=!0;let _=t.domElement.getBoundingClientRect(),ce=B.clientX-_.left,he=B.clientY-_.top,Ee=_.width,Qe=_.height;R.x=ce/Ee*2-1,R.y=-(he/Qe)*2+1,T.set(R.x,R.y,1).unproject(e).sub(e.position).normalize()}function k(B){return Math.max(t.minDistance,Math.min(t.maxDistance,B))}function V(B){u.set(B.clientX,B.clientY)}function q(B){O(B),C.set(B.clientX,B.clientY)}function oe(B){A.set(B.clientX,B.clientY)}function N(B){p.set(B.clientX,B.clientY),h.subVectors(p,u).multiplyScalar(t.rotateSpeed);let _=t.domElement;M(2*Math.PI*h.x/_.clientHeight),b(2*Math.PI*h.y/_.clientHeight),u.copy(p),t.update()}function Ae(B){E.set(B.clientX,B.clientY),x.subVectors(E,C),x.y>0?P(v()):x.y<0&&z(v()),C.copy(E),t.update()}function G(B){m.set(B.clientX,B.clientY),S.subVectors(m,A).multiplyScalar(t.panSpeed),F(S.x,S.y),A.copy(m),t.update()}function K(B){O(B),B.deltaY<0?z(v()):B.deltaY>0&&P(v()),t.update()}function Y(B){let _=!1;switch(B.code){case t.keys.UP:B.ctrlKey||B.metaKey||B.shiftKey?b(2*Math.PI*t.rotateSpeed/t.domElement.clientHeight):F(0,t.keyPanSpeed),_=!0;break;case t.keys.BOTTOM:B.ctrlKey||B.metaKey||B.shiftKey?b(-2*Math.PI*t.rotateSpeed/t.domElement.clientHeight):F(0,-t.keyPanSpeed),_=!0;break;case t.keys.LEFT:B.ctrlKey||B.metaKey||B.shiftKey?M(2*Math.PI*t.rotateSpeed/t.domElement.clientHeight):F(t.keyPanSpeed,0),_=!0;break;case t.keys.RIGHT:B.ctrlKey||B.metaKey||B.shiftKey?M(-2*Math.PI*t.rotateSpeed/t.domElement.clientHeight):F(-t.keyPanSpeed,0),_=!0;break}_&&(B.preventDefault(),t.update())}function ie(){if(g.length===1)u.set(g[0].pageX,g[0].pageY);else{let B=.5*(g[0].pageX+g[1].pageX),_=.5*(g[0].pageY+g[1].pageY);u.set(B,_)}}function ae(){if(g.length===1)A.set(g[0].pageX,g[0].pageY);else{let B=.5*(g[0].pageX+g[1].pageX),_=.5*(g[0].pageY+g[1].pageY);A.set(B,_)}}function ge(){let B=g[0].pageX-g[1].pageX,_=g[0].pageY-g[1].pageY,ce=Math.sqrt(B*B+_*_);C.set(0,ce)}function me(){t.enableZoom&&ge(),t.enablePan&&ae()}function ee(){t.enableZoom&&ge(),t.enableRotate&&ie()}function Se(B){if(g.length==1)p.set(B.pageX,B.pageY);else{let ce=Bt(B),he=.5*(B.pageX+ce.x),Ee=.5*(B.pageY+ce.y);p.set(he,Ee)}h.subVectors(p,u).multiplyScalar(t.rotateSpeed);let _=t.domElement;M(2*Math.PI*h.x/_.clientHeight),b(2*Math.PI*h.y/_.clientHeight),u.copy(p)}function ne(B){if(g.length===1)m.set(B.pageX,B.pageY);else{let _=Bt(B),ce=.5*(B.pageX+_.x),he=.5*(B.pageY+_.y);m.set(ce,he)}S.subVectors(m,A).multiplyScalar(t.panSpeed),F(S.x,S.y),A.copy(m)}function Z(B){let _=Bt(B),ce=B.pageX-_.x,he=B.pageY-_.y,Ee=Math.sqrt(ce*ce+he*he);E.set(0,Ee),x.set(0,Math.pow(E.y/C.y,t.zoomSpeed)),P(x.y),C.copy(E)}function le(B){t.enableZoom&&Z(B),t.enablePan&&ne(B)}function ve(B){t.enableZoom&&Z(B),t.enableRotate&&Se(B)}function fe(B){t.enabled!==!1&&(g.length===0&&(t.domElement.setPointerCapture(B.pointerId),t.domElement.addEventListener("pointermove",xe),t.domElement.addEventListener("pointerup",ke)),xn(B),B.pointerType==="touch"?Cn(B):gn(B))}function xe(B){t.enabled!==!1&&(B.pointerType==="touch"?yn(B):Sn(B))}function ke(B){En(B),g.length===0&&(t.domElement.releasePointerCapture(B.pointerId),t.domElement.removeEventListener("pointermove",xe),t.domElement.removeEventListener("pointerup",ke)),t.dispatchEvent(Zs),r=n.NONE}function gn(B){let _;switch(B.button){case 0:_=t.mouseButtons.LEFT;break;case 1:_=t.mouseButtons.MIDDLE;break;case 2:_=t.mouseButtons.RIGHT;break;default:_=-1}switch(_){case Ge.DOLLY:if(t.enableZoom===!1)return;q(B),r=n.DOLLY;break;case Ge.ROTATE:if(B.ctrlKey||B.metaKey||B.shiftKey){if(t.enablePan===!1)return;oe(B),r=n.PAN}else{if(t.enableRotate===!1)return;V(B),r=n.ROTATE}break;case Ge.PAN:if(B.ctrlKey||B.metaKey||B.shiftKey){if(t.enableRotate===!1)return;V(B),r=n.ROTATE}else{if(t.enablePan===!1)return;oe(B),r=n.PAN}break;default:r=n.NONE}r!==n.NONE&&t.dispatchEvent(Ut)}function Sn(B){switch(r){case n.ROTATE:if(t.enableRotate===!1)return;N(B);break;case n.DOLLY:if(t.enableZoom===!1)return;Ae(B);break;case n.PAN:if(t.enablePan===!1)return;G(B);break}}function Rs(B){t.enabled===!1||t.enableZoom===!1||r!==n.NONE||(B.preventDefault(),t.dispatchEvent(Ut),K(B),t.dispatchEvent(Zs))}function It(B){t.enabled===!1||t.enablePan===!1||Y(B)}function Cn(B){switch(Bs(B),g.length){case 1:switch(t.touches.ONE){case We.ROTATE:if(t.enableRotate===!1)return;ie(),r=n.TOUCH_ROTATE;break;case We.PAN:if(t.enablePan===!1)return;ae(),r=n.TOUCH_PAN;break;default:r=n.NONE}break;case 2:switch(t.touches.TWO){case We.DOLLY_PAN:if(t.enableZoom===!1&&t.enablePan===!1)return;me(),r=n.TOUCH_DOLLY_PAN;break;case We.DOLLY_ROTATE:if(t.enableZoom===!1&&t.enableRotate===!1)return;ee(),r=n.TOUCH_DOLLY_ROTATE;break;default:r=n.NONE}break;default:r=n.NONE}r!==n.NONE&&t.dispatchEvent(Ut)}function yn(B){switch(Bs(B),r){case n.TOUCH_ROTATE:if(t.enableRotate===!1)return;Se(B),t.update();break;case n.TOUCH_PAN:if(t.enablePan===!1)return;ne(B),t.update();break;case n.TOUCH_DOLLY_PAN:if(t.enableZoom===!1&&t.enablePan===!1)return;le(B),t.update();break;case n.TOUCH_DOLLY_ROTATE:if(t.enableZoom===!1&&t.enableRotate===!1)return;ve(B),t.update();break;default:r=n.NONE}}function Is(B){t.enabled!==!1&&B.preventDefault()}function xn(B){g.push(B)}function En(B){delete I[B.pointerId];for(let _=0;_<g.length;_++)if(g[_].pointerId==B.pointerId){g.splice(_,1);return}}function Bs(B){let _=I[B.pointerId];_===void 0&&(_=new Ie,I[B.pointerId]=_),_.set(B.pageX,B.pageY)}function Bt(B){let _=B.pointerId===g[0].pointerId?g[1]:g[0];return I[_.pointerId]}t.domElement.addEventListener("contextmenu",Is),t.domElement.addEventListener("pointerdown",fe),t.domElement.addEventListener("pointercancel",ke),t.domElement.addEventListener("wheel",Rs,{passive:!1}),this.update()}},kr=(l,e,s,t,n)=>{let r=performance.now(),i=l.style.display==="none"?0:parseFloat(l.style.opacity);isNaN(i)&&(i=1);let o=window.setInterval(()=>{let c=performance.now()-r,d=Math.min(c/t,1);d>.999&&(d=1);let u;e?(u=(1-d)*i,u<1e-4&&(u=0)):u=(1-i)*d+i,u>0?(l.style.display=s,l.style.opacity=u):l.style.display="none",d>=1&&(n&&n(),window.clearInterval(o))},16);return o};var Lr=500,Jt=class l{static elementIDGen=0;constructor(e,s){this.taskIDGen=0,this.elementID=l.elementIDGen++,this.tasks=[],this.message=e||"Loading...",this.container=s||document.body,this.spinnerContainerOuter=document.createElement("div"),this.spinnerContainerOuter.className=`spinnerOuterContainer${this.elementID}`,this.spinnerContainerOuter.style.display="none",this.spinnerContainerPrimary=document.createElement("div"),this.spinnerContainerPrimary.className=`spinnerContainerPrimary${this.elementID}`,this.spinnerPrimary=document.createElement("div"),this.spinnerPrimary.classList.add(`spinner${this.elementID}`,`spinnerPrimary${this.elementID}`),this.messageContainerPrimary=document.createElement("div"),this.messageContainerPrimary.classList.add(`messageContainer${this.elementID}`,`messageContainerPrimary${this.elementID}`),this.messageContainerPrimary.innerHTML=this.message,this.spinnerContainerMin=document.createElement("div"),this.spinnerContainerMin.className=`spinnerContainerMin${this.elementID}`,this.spinnerMin=document.createElement("div"),this.spinnerMin.classList.add(`spinner${this.elementID}`,`spinnerMin${this.elementID}`),this.messageContainerMin=document.createElement("div"),this.messageContainerMin.classList.add(`messageContainer${this.elementID}`,`messageContainerMin${this.elementID}`),this.messageContainerMin.innerHTML=this.message,this.spinnerContainerPrimary.appendChild(this.spinnerPrimary),this.spinnerContainerPrimary.appendChild(this.messageContainerPrimary),this.spinnerContainerOuter.appendChild(this.spinnerContainerPrimary),this.spinnerContainerMin.appendChild(this.spinnerMin),this.spinnerContainerMin.appendChild(this.messageContainerMin),this.spinnerContainerOuter.appendChild(this.spinnerContainerMin);let t=document.createElement("style");t.innerHTML=`
6
+
7
+ .spinnerOuterContainer${this.elementID} {
8
+ width: 100%;
9
+ height: 100%;
10
+ margin: 0;
11
+ top: 0;
12
+ left: 0;
13
+ position: absolute;
14
+ pointer-events: none;
15
+ }
16
+
17
+ .messageContainer${this.elementID} {
18
+ height: 20px;
19
+ font-family: arial;
20
+ font-size: 12pt;
21
+ color: #ffffff;
22
+ text-align: center;
23
+ vertical-align: middle;
24
+ }
25
+
26
+ .spinner${this.elementID} {
27
+ padding: 15px;
28
+ background: #07e8d6;
29
+ z-index:99999;
30
+
31
+ aspect-ratio: 1;
32
+ border-radius: 50%;
33
+ --_m:
34
+ conic-gradient(#0000,#000),
35
+ linear-gradient(#000 0 0) content-box;
36
+ -webkit-mask: var(--_m);
37
+ mask: var(--_m);
38
+ -webkit-mask-composite: source-out;
39
+ mask-composite: subtract;
40
+ box-sizing: border-box;
41
+ animation: load 1s linear infinite;
42
+ }
43
+
44
+ .spinnerContainerPrimary${this.elementID} {
45
+ z-index:99999;
46
+ background-color: rgba(128, 128, 128, 0.75);
47
+ border: #666666 1px solid;
48
+ border-radius: 5px;
49
+ padding-top: 20px;
50
+ padding-bottom: 10px;
51
+ margin: 0;
52
+ position: absolute;
53
+ top: 50%;
54
+ left: 50%;
55
+ transform: translate(-80px, -80px);
56
+ width: 180px;
57
+ pointer-events: auto;
58
+ }
59
+
60
+ .spinnerPrimary${this.elementID} {
61
+ width: 120px;
62
+ margin-left: 30px;
63
+ }
64
+
65
+ .messageContainerPrimary${this.elementID} {
66
+ padding-top: 15px;
67
+ }
68
+
69
+ .spinnerContainerMin${this.elementID} {
70
+ z-index:99999;
71
+ background-color: rgba(128, 128, 128, 0.75);
72
+ border: #666666 1px solid;
73
+ border-radius: 5px;
74
+ padding-top: 20px;
75
+ padding-bottom: 15px;
76
+ margin: 0;
77
+ position: absolute;
78
+ bottom: 50px;
79
+ left: 50%;
80
+ transform: translate(-50%, 0);
81
+ display: flex;
82
+ flex-direction: left;
83
+ pointer-events: auto;
84
+ min-width: 250px;
85
+ }
86
+
87
+ .messageContainerMin${this.elementID} {
88
+ margin-right: 15px;
89
+ }
90
+
91
+ .spinnerMin${this.elementID} {
92
+ width: 50px;
93
+ height: 50px;
94
+ margin-left: 15px;
95
+ margin-right: 25px;
96
+ }
97
+
98
+ .messageContainerMin${this.elementID} {
99
+ padding-top: 15px;
100
+ }
101
+
102
+ @keyframes load {
103
+ to{transform: rotate(1turn)}
104
+ }
105
+
106
+ `,this.spinnerContainerOuter.appendChild(t),this.container.appendChild(this.spinnerContainerOuter),this.setMinimized(!1,!0),this.fadeTransitions=[]}addTask(e){let s={message:e,id:this.taskIDGen++};return this.tasks.push(s),this.update(),s.id}removeTask(e){let s=0;for(let t of this.tasks){if(t.id===e){this.tasks.splice(s,1);break}s++}this.update()}removeAllTasks(){this.tasks=[],this.update()}setMessageForTask(e,s){for(let t of this.tasks)if(t.id===e){t.message=s;break}this.update()}update(){this.tasks.length>0?(this.show(),this.setMessage(this.tasks[this.tasks.length-1].message)):this.hide()}show(){this.spinnerContainerOuter.style.display="block",this.visible=!0}hide(){this.spinnerContainerOuter.style.display="none",this.visible=!1}setContainer(e){this.container&&this.spinnerContainerOuter.parentElement===this.container&&this.container.removeChild(this.spinnerContainerOuter),e&&(this.container=e,this.container.appendChild(this.spinnerContainerOuter),this.spinnerContainerOuter.style.zIndex=this.container.style.zIndex+1)}setMinimized(e,s){let t=(n,r,i,o,a)=>{i?n.style.display=r?o:"none":this.fadeTransitions[a]=kr(n,!r,o,Lr,()=>{this.fadeTransitions[a]=null})};t(this.spinnerContainerPrimary,!e,s,"block",0),t(this.spinnerContainerMin,e,s,"flex",1),this.minimized=e}setMessage(e){this.messageContainerPrimary.innerHTML=e,this.messageContainerMin.innerHTML=e}},Zt=class{constructor(e){this.idGen=0,this.tasks=[],this.container=e||document.body,this.progressBarContainerOuter=document.createElement("div"),this.progressBarContainerOuter.className="progressBarOuterContainer",this.progressBarContainerOuter.style.display="none",this.progressBarBox=document.createElement("div"),this.progressBarBox.className="progressBarBox",this.progressBarBackground=document.createElement("div"),this.progressBarBackground.className="progressBarBackground",this.progressBar=document.createElement("div"),this.progressBar.className="progressBar",this.progressBarBackground.appendChild(this.progressBar),this.progressBarBox.appendChild(this.progressBarBackground),this.progressBarContainerOuter.appendChild(this.progressBarBox);let s=document.createElement("style");s.innerHTML=`
107
+
108
+ .progressBarOuterContainer {
109
+ width: 100%;
110
+ height: 100%;
111
+ margin: 0;
112
+ top: 0;
113
+ left: 0;
114
+ position: absolute;
115
+ pointer-events: none;
116
+ }
117
+
118
+ .progressBarBox {
119
+ z-index:99999;
120
+ padding: 7px 9px 5px 7px;
121
+ background-color: rgba(190, 190, 190, 0.75);
122
+ border: #555555 1px solid;
123
+ border-radius: 15px;
124
+ margin: 0;
125
+ position: absolute;
126
+ bottom: 50px;
127
+ left: 50%;
128
+ transform: translate(-50%, 0);
129
+ width: 180px;
130
+ height: 30px;
131
+ pointer-events: auto;
132
+ }
133
+
134
+ .progressBarBackground {
135
+ width: 100%;
136
+ height: 25px;
137
+ border-radius:10px;
138
+ background-color: rgba(128, 128, 128, 0.75);
139
+ border: #444444 1px solid;
140
+ box-shadow: inset 0 0 10px #333333;
141
+ }
142
+
143
+ .progressBar {
144
+ height: 25px;
145
+ width: 0px;
146
+ border-radius:10px;
147
+ background-color: rgba(0, 200, 0, 0.75);
148
+ box-shadow: inset 0 0 10px #003300;
149
+ }
150
+
151
+ `,this.progressBarContainerOuter.appendChild(s),this.container.appendChild(this.progressBarContainerOuter)}show(){this.progressBarContainerOuter.style.display="block"}hide(){this.progressBarContainerOuter.style.display="none"}setProgress(e){this.progressBar.style.width=e+"%"}setContainer(e){this.container&&this.progressBarContainerOuter.parentElement===this.container&&this.container.removeChild(this.progressBarContainerOuter),e&&(this.container=e,this.container.appendChild(this.progressBarContainerOuter),this.progressBarContainerOuter.style.zIndex=this.container.style.zIndex+1)}},$t=class{constructor(e){this.container=e||document.body,this.infoCells={};let s=[["Camera position","cameraPosition"],["Camera look-at","cameraLookAt"],["Camera up","cameraUp"],["Camera mode","orthographicCamera"],["Cursor position","cursorPosition"],["FPS","fps"],["Rendering:","renderSplatCount"],["Sort time","sortTime"],["Render window","renderWindow"],["Focal adjustment","focalAdjustment"],["Splat scale","splatScale"],["Point cloud mode","pointCloudMode"]];this.infoPanelContainer=document.createElement("div");let t=document.createElement("style");t.innerHTML=`
152
+
153
+ .infoPanel {
154
+ width: 430px;
155
+ padding: 10px;
156
+ background-color: rgba(50, 50, 50, 0.85);
157
+ border: #555555 2px solid;
158
+ color: #dddddd;
159
+ border-radius: 10px;
160
+ z-index: 9999;
161
+ font-family: arial;
162
+ font-size: 11pt;
163
+ text-align: left;
164
+ margin: 0;
165
+ top: 10px;
166
+ left:10px;
167
+ position: absolute;
168
+ pointer-events: auto;
169
+ }
170
+
171
+ .info-panel-cell {
172
+ margin-bottom: 5px;
173
+ padding-bottom: 2px;
174
+ }
175
+
176
+ .label-cell {
177
+ font-weight: bold;
178
+ font-size: 12pt;
179
+ width: 140px;
180
+ }
181
+
182
+ `,this.infoPanelContainer.append(t),this.infoPanel=document.createElement("div"),this.infoPanel.className="infoPanel";let n=document.createElement("div");n.style.display="table";for(let r of s){let i=document.createElement("div");i.style.display="table-row",i.className="info-panel-row";let o=document.createElement("div");o.style.display="table-cell",o.innerHTML=`${r[0]}: `,o.classList.add("info-panel-cell","label-cell");let a=document.createElement("div");a.style.display="table-cell",a.style.width="10px",a.innerHTML=" ",a.className="info-panel-cell";let c=document.createElement("div");c.style.display="table-cell",c.innerHTML="",c.className="info-panel-cell",this.infoCells[r[1]]=c,i.appendChild(o),i.appendChild(a),i.appendChild(c),n.appendChild(i)}this.infoPanel.appendChild(n),this.infoPanelContainer.append(this.infoPanel),this.infoPanelContainer.style.display="none",this.container.appendChild(this.infoPanelContainer),this.visible=!1}update=function(e,s,t,n,r,i,o,a,c,d,u,p,h,A){let m=`${s.x.toFixed(5)}, ${s.y.toFixed(5)}, ${s.z.toFixed(5)}`;if(this.infoCells.cameraPosition.innerHTML!==m&&(this.infoCells.cameraPosition.innerHTML=m),t){let C=t,E=`${C.x.toFixed(5)}, ${C.y.toFixed(5)}, ${C.z.toFixed(5)}`;this.infoCells.cameraLookAt.innerHTML!==E&&(this.infoCells.cameraLookAt.innerHTML=E)}let S=`${n.x.toFixed(5)}, ${n.y.toFixed(5)}, ${n.z.toFixed(5)}`;if(this.infoCells.cameraUp.innerHTML!==S&&(this.infoCells.cameraUp.innerHTML=S),this.infoCells.orthographicCamera.innerHTML=r?"Orthographic":"Perspective",i){let C=i,E=`${C.x.toFixed(5)}, ${C.y.toFixed(5)}, ${C.z.toFixed(5)}`;this.infoCells.cursorPosition.innerHTML=E}else this.infoCells.cursorPosition.innerHTML="N/A";this.infoCells.fps.innerHTML=o,this.infoCells.renderWindow.innerHTML=`${e.x} x ${e.y}`,this.infoCells.renderSplatCount.innerHTML=`${c} splats out of ${a} (${d.toFixed(2)}%)`,this.infoCells.sortTime.innerHTML=`${u.toFixed(3)} ms`,this.infoCells.focalAdjustment.innerHTML=`${p.toFixed(3)}`,this.infoCells.splatScale.innerHTML=`${h.toFixed(3)}`,this.infoCells.pointCloudMode.innerHTML=`${A}`};setContainer(e){this.container&&this.infoPanelContainer.parentElement===this.container&&this.container.removeChild(this.infoPanelContainer),e&&(this.container=e,this.container.appendChild(this.infoPanelContainer),this.infoPanelContainer.style.zIndex=this.container.style.zIndex+1)}show(){this.infoPanelContainer.style.display="block",this.visible=!0}hide(){this.infoPanelContainer.style.display="none",this.visible=!1}},en=new f.Vector3,es=class extends f.Object3D{constructor(e=new f.Vector3(0,0,1),s=new f.Vector3(0,0,0),t=1,n=.1,r=16776960,i=t*.2,o=i*.2){super(),this.type="ArrowHelper";let a=new f.CylinderGeometry(n,n,t,32);a.translate(0,t/2,0);let c=new f.CylinderGeometry(0,o,i,32);c.translate(0,t,0),this.position.copy(s),this.line=new f.Mesh(a,new f.MeshBasicMaterial({color:r,toneMapped:!1})),this.line.matrixAutoUpdate=!1,this.add(this.line),this.cone=new f.Mesh(c,new f.MeshBasicMaterial({color:r,toneMapped:!1})),this.cone.matrixAutoUpdate=!1,this.add(this.cone),this.setDirection(e)}setDirection(e){if(e.y>.99999)this.quaternion.set(0,0,0,1);else if(e.y<-.99999)this.quaternion.set(1,0,0,0);else{en.set(e.z,0,-e.x).normalize();let s=Math.acos(e.y);this.quaternion.setFromAxisAngle(en,s)}}setColor(e){this.line.material.color.set(e),this.cone.material.color.set(e)}copy(e){return super.copy(e,!1),this.line.copy(e.line),this.cone.copy(e.cone),this}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}},ts=class l{constructor(e){this.threeScene=e,this.splatRenderTarget=null,this.renderTargetCopyQuad=null,this.renderTargetCopyCamera=null,this.meshCursor=null,this.focusMarker=null,this.controlPlane=null,this.debugRoot=null,this.secondaryDebugRoot=null}updateSplatRenderTargetForRenderDimensions(e,s){this.destroySplatRendertarget(),this.splatRenderTarget=new f.WebGLRenderTarget(e,s,{format:f.RGBAFormat,stencilBuffer:!1,depthBuffer:!0}),this.splatRenderTarget.depthTexture=new f.DepthTexture(e,s),this.splatRenderTarget.depthTexture.format=f.DepthFormat,this.splatRenderTarget.depthTexture.type=f.UnsignedIntType}destroySplatRendertarget(){this.splatRenderTarget&&(this.splatRenderTarget=null)}setupRenderTargetCopyObjects(){let e={sourceColorTexture:{type:"t",value:null},sourceDepthTexture:{type:"t",value:null}},s=new f.ShaderMaterial({vertexShader:`
183
+ varying vec2 vUv;
184
+ void main() {
185
+ vUv = uv;
186
+ gl_Position = vec4( position.xy, 0.0, 1.0 );
187
+ }
188
+ `,fragmentShader:`
189
+ #include <common>
190
+ #include <packing>
191
+ varying vec2 vUv;
192
+ uniform sampler2D sourceColorTexture;
193
+ uniform sampler2D sourceDepthTexture;
194
+ void main() {
195
+ vec4 color = texture2D(sourceColorTexture, vUv);
196
+ float fragDepth = texture2D(sourceDepthTexture, vUv).x;
197
+ gl_FragDepth = fragDepth;
198
+ gl_FragColor = vec4(color.rgb, color.a * 2.0);
199
+ }
200
+ `,uniforms:e,depthWrite:!1,depthTest:!1,transparent:!0,blending:f.CustomBlending,blendSrc:f.SrcAlphaFactor,blendSrcAlpha:f.SrcAlphaFactor,blendDst:f.OneMinusSrcAlphaFactor,blendDstAlpha:f.OneMinusSrcAlphaFactor});s.extensions.fragDepth=!0,this.renderTargetCopyQuad=new f.Mesh(new f.PlaneGeometry(2,2),s),this.renderTargetCopyCamera=new f.OrthographicCamera(-1,1,1,-1,0,1)}destroyRenderTargetCopyObjects(){this.renderTargetCopyQuad&&(Ye(this.renderTargetCopyQuad),this.renderTargetCopyQuad=null)}setupMeshCursor(){if(!this.meshCursor){let e=new f.ConeGeometry(.5,1.5,32),s=new f.MeshBasicMaterial({color:16777215}),t=new f.Mesh(e,s);t.rotation.set(0,0,Math.PI),t.position.set(0,1,0);let n=new f.Mesh(e,s);n.position.set(0,-1,0);let r=new f.Mesh(e,s);r.rotation.set(0,0,Math.PI/2),r.position.set(1,0,0);let i=new f.Mesh(e,s);i.rotation.set(0,0,-Math.PI/2),i.position.set(-1,0,0),this.meshCursor=new f.Object3D,this.meshCursor.add(t),this.meshCursor.add(n),this.meshCursor.add(r),this.meshCursor.add(i),this.meshCursor.scale.set(.1,.1,.1),this.threeScene.add(this.meshCursor),this.meshCursor.visible=!1}}destroyMeshCursor(){this.meshCursor&&(Ye(this.meshCursor),this.threeScene.remove(this.meshCursor),this.meshCursor=null)}setMeshCursorVisibility(e){this.meshCursor.visible=e}getMeschCursorVisibility(){return this.meshCursor.visible}setMeshCursorPosition(e){this.meshCursor.position.copy(e)}positionAndOrientMeshCursor(e,s){this.meshCursor.position.copy(e),this.meshCursor.up.copy(s.up),this.meshCursor.lookAt(s.position)}setupFocusMarker(){if(!this.focusMarker){let e=new f.SphereGeometry(.5,32,32),s=l.buildFocusMarkerMaterial();s.depthTest=!1,s.depthWrite=!1,s.transparent=!0,this.focusMarker=new f.Mesh(e,s)}}destroyFocusMarker(){this.focusMarker&&(Ye(this.focusMarker),this.focusMarker=null)}updateFocusMarker=function(){let e=new f.Vector3,s=new f.Matrix4,t=new f.Vector3;return function(n,r,i){s.copy(r.matrixWorld).invert(),e.copy(n).applyMatrix4(s),e.normalize().multiplyScalar(10),e.applyMatrix4(r.matrixWorld),t.copy(r.position).sub(n);let o=t.length();this.focusMarker.position.copy(n),this.focusMarker.scale.set(o,o,o),this.focusMarker.material.uniforms.realFocusPosition.value.copy(n),this.focusMarker.material.uniforms.viewport.value.copy(i),this.focusMarker.material.uniformsNeedUpdate=!0}}();setFocusMarkerVisibility(e){this.focusMarker.visible=e}setFocusMarkerOpacity(e){this.focusMarker.material.uniforms.opacity.value=e,this.focusMarker.material.uniformsNeedUpdate=!0}getFocusMarkerOpacity(){return this.focusMarker.material.uniforms.opacity.value}setupControlPlane(){if(!this.controlPlane){let e=new f.PlaneGeometry(1,1);e.rotateX(-Math.PI/2);let s=new f.MeshBasicMaterial({color:16777215});s.transparent=!0,s.opacity=.6,s.depthTest=!1,s.depthWrite=!1,s.side=f.DoubleSide;let t=new f.Mesh(e,s),n=new f.Vector3(0,1,0);n.normalize();let r=new f.Vector3(0,0,0),i=.5,o=.01,a=56576,c=new es(n,r,i,o,a,.1,.03);this.controlPlane=new f.Object3D,this.controlPlane.add(t),this.controlPlane.add(c)}}destroyControlPlane(){this.controlPlane&&(Ye(this.controlPlane),this.controlPlane=null)}setControlPlaneVisibility(e){this.controlPlane.visible=e}positionAndOrientControlPlane=function(){let e=new f.Quaternion,s=new f.Vector3(0,1,0);return function(t,n){e.setFromUnitVectors(s,n),this.controlPlane.position.copy(t),this.controlPlane.quaternion.copy(e)}}();addDebugMeshes(){this.debugRoot=this.createDebugMeshes(),this.secondaryDebugRoot=this.createSecondaryDebugMeshes(),this.threeScene.add(this.debugRoot),this.threeScene.add(this.secondaryDebugRoot)}destroyDebugMeshes(){for(let e of[this.debugRoot,this.secondaryDebugRoot])e&&(Ye(e),this.threeScene.remove(e));this.debugRoot=null,this.secondaryDebugRoot=null}createDebugMeshes(e){let s=new f.SphereGeometry(1,32,32),t=new f.Object3D,n=(r,i)=>{let o=new f.Mesh(s,l.buildDebugMaterial(r));o.renderOrder=e,t.add(o),o.position.fromArray(i)};return n(16711680,[-50,0,0]),n(16711680,[50,0,0]),n(65280,[0,0,-50]),n(65280,[0,0,50]),n(16755200,[5,0,5]),t}createSecondaryDebugMeshes(e){let s=new f.BoxGeometry(3,3,3),t=new f.Object3D,n=12303291,r=o=>{let a=new f.Mesh(s,l.buildDebugMaterial(n));a.renderOrder=e,t.add(a),a.position.fromArray(o)},i=10;return r([-i,0,-i]),r([-i,0,i]),r([i,0,-i]),r([i,0,i]),t}static buildDebugMaterial(e){let s=`
201
+ #include <common>
202
+ varying float ndcDepth;
203
+
204
+ void main() {
205
+ gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(position.xyz, 1.0);
206
+ ndcDepth = gl_Position.z / gl_Position.w;
207
+ gl_Position.x = gl_Position.x / gl_Position.w;
208
+ gl_Position.y = gl_Position.y / gl_Position.w;
209
+ gl_Position.z = 0.0;
210
+ gl_Position.w = 1.0;
211
+
212
+ }
213
+ `,t=`
214
+ #include <common>
215
+ uniform vec3 color;
216
+ varying float ndcDepth;
217
+ void main() {
218
+ gl_FragDepth = (ndcDepth + 1.0) / 2.0;
219
+ gl_FragColor = vec4(color.rgb, 0.0);
220
+ }
221
+ `,n={color:{type:"v3",value:new f.Color(e)}},r=new f.ShaderMaterial({uniforms:n,vertexShader:s,fragmentShader:t,transparent:!1,depthTest:!0,depthWrite:!0,side:f.FrontSide});return r.extensions.fragDepth=!0,r}static buildFocusMarkerMaterial(e){let s=`
222
+ #include <common>
223
+
224
+ uniform vec2 viewport;
225
+ uniform vec3 realFocusPosition;
226
+
227
+ varying vec4 ndcPosition;
228
+ varying vec4 ndcCenter;
229
+ varying vec4 ndcFocusPosition;
230
+
231
+ void main() {
232
+ float radius = 0.01;
233
+
234
+ vec4 viewPosition = modelViewMatrix * vec4(position.xyz, 1.0);
235
+ vec4 viewCenter = modelViewMatrix * vec4(0.0, 0.0, 0.0, 1.0);
236
+
237
+ vec4 viewFocusPosition = modelViewMatrix * vec4(realFocusPosition, 1.0);
238
+
239
+ ndcPosition = projectionMatrix * viewPosition;
240
+ ndcPosition = ndcPosition * vec4(1.0 / ndcPosition.w);
241
+ ndcCenter = projectionMatrix * viewCenter;
242
+ ndcCenter = ndcCenter * vec4(1.0 / ndcCenter.w);
243
+
244
+ ndcFocusPosition = projectionMatrix * viewFocusPosition;
245
+ ndcFocusPosition = ndcFocusPosition * vec4(1.0 / ndcFocusPosition.w);
246
+
247
+ gl_Position = projectionMatrix * viewPosition;
248
+
249
+ }
250
+ `,t=`
251
+ #include <common>
252
+ uniform vec3 color;
253
+ uniform vec2 viewport;
254
+ uniform float opacity;
255
+
256
+ varying vec4 ndcPosition;
257
+ varying vec4 ndcCenter;
258
+ varying vec4 ndcFocusPosition;
259
+
260
+ void main() {
261
+ vec2 screenPosition = vec2(ndcPosition) * viewport;
262
+ vec2 screenCenter = vec2(ndcCenter) * viewport;
263
+
264
+ vec2 screenVec = screenPosition - screenCenter;
265
+
266
+ float projectedRadius = length(screenVec);
267
+
268
+ float lineWidth = 0.0005 * viewport.y;
269
+ float aaRange = 0.0025 * viewport.y;
270
+ float radius = 0.06 * viewport.y;
271
+ float radDiff = abs(projectedRadius - radius) - lineWidth;
272
+ float alpha = 1.0 - clamp(radDiff / 5.0, 0.0, 1.0);
273
+
274
+ gl_FragColor = vec4(color.rgb, alpha * opacity);
275
+ }
276
+ `,n={color:{type:"v3",value:new f.Color(e)},realFocusPosition:{type:"v3",value:new f.Vector3},viewport:{type:"v2",value:new f.Vector2},opacity:{value:0}};return new f.ShaderMaterial({uniforms:n,vertexShader:s,fragmentShader:t,transparent:!0,depthTest:!1,depthWrite:!1,side:f.FrontSide})}dispose(){this.destroyMeshCursor(),this.destroyFocusMarker(),this.destroyDebugMeshes(),this.destroyControlPlane(),this.destroyRenderTargetCopyObjects(),this.destroySplatRendertarget()}},Or=new f.Vector3(1,0,0),Ur=new f.Vector3(0,1,0),zr=new f.Vector3(0,0,1),nt=class{constructor(e=new f.Vector3,s=new f.Vector3){this.origin=new f.Vector3,this.direction=new f.Vector3,this.setParameters(e,s)}setParameters(e,s){this.origin.copy(e),this.direction.copy(s).normalize()}boxContainsPoint(e,s,t){return!(s.x<e.min.x-t||s.x>e.max.x+t||s.y<e.min.y-t||s.y>e.max.y+t||s.z<e.min.z-t||s.z>e.max.z+t)}intersectBox=function(){let e=new f.Vector3,s=[],t=[],n=[];return function(r,i){if(t[0]=this.origin.x,t[1]=this.origin.y,t[2]=this.origin.z,n[0]=this.direction.x,n[1]=this.direction.y,n[2]=this.direction.z,this.boxContainsPoint(r,this.origin,1e-4))return i&&(i.origin.copy(this.origin),i.normal.set(0,0,0),i.distance=-1),!0;for(let o=0;o<3;o++){if(n[o]==0)continue;let a=o==0?Or:o==1?Ur:zr,c=n[o]<0?r.max:r.min,d=-Math.sign(n[o]);s[0]=o==0?c.x:o==1?c.y:c.z;let u=s[0]-t[o];if(u*d<0){let p=(o+1)%3,h=(o+2)%3;if(s[2]=n[p]/n[o]*u+t[p],s[1]=n[h]/n[o]*u+t[h],e.set(s[o],s[h],s[p]),this.boxContainsPoint(r,e,1e-4))return i&&(i.origin.copy(e),i.normal.copy(a).multiplyScalar(d),i.distance=e.sub(this.origin).length()),!0}}return!1}}();intersectSphere=function(){let e=new f.Vector3;return function(s,t,n){e.copy(s).sub(this.origin);let r=e.dot(this.direction),i=r*r,a=e.dot(e)-i,c=t*t;if(a>c)return!1;let d=Math.sqrt(c-a),u=r-d,p=r+d;if(p<0)return!1;let h=u<0?p:u;return n&&(n.origin.copy(this.origin).addScaledVector(this.direction,h),n.normal.copy(n.origin).sub(s).normalize(),n.distance=h),!0}}()},ss=class l{constructor(){this.origin=new f.Vector3,this.normal=new f.Vector3,this.distance=0,this.splatIndex=0}set(e,s,t,n){this.origin.copy(e),this.normal.copy(s),this.distance=t,this.splatIndex=n}clone(){let e=new l;return e.origin.copy(this.origin),e.normal.copy(this.normal),e.distance=this.distance,e.splatIndex=this.splatIndex,e}},De={ThreeD:0,TwoD:1},ns=class{constructor(e,s,t=!1){this.ray=new nt(e,s),this.raycastAgainstTrueSplatEllipsoid=t}setFromCameraAndScreenPosition=function(){let e=new f.Vector2;return function(s,t,n){if(e.x=t.x/n.x*2-1,e.y=(n.y-t.y)/n.y*2-1,s.isPerspectiveCamera)this.ray.origin.setFromMatrixPosition(s.matrixWorld),this.ray.direction.set(e.x,e.y,.5).unproject(s).sub(this.ray.origin).normalize(),this.camera=s;else if(s.isOrthographicCamera)this.ray.origin.set(e.x,e.y,(s.near+s.far)/(s.near-s.far)).unproject(s),this.ray.direction.set(0,0,-1).transformDirection(s.matrixWorld),this.camera=s;else throw new Error("Raycaster::setFromCameraAndScreenPosition() -> Unsupported camera type")}}();intersectSplatMesh=function(){let e=new f.Matrix4,s=new f.Matrix4,t=new f.Matrix4,n=new nt,r=new f.Vector3;return function(i,o=[]){let a=i.getSplatTree();if(a){for(let c=0;c<a.subTrees.length;c++){let d=a.subTrees[c];s.copy(i.matrixWorld),i.dynamicMode&&(i.getSceneTransform(c,t),s.multiply(t)),e.copy(s).invert(),n.origin.copy(this.ray.origin).applyMatrix4(e),n.direction.copy(this.ray.origin).add(this.ray.direction),n.direction.applyMatrix4(e).sub(n.origin).normalize();let u=[];d.rootNode&&this.castRayAtSplatTreeNode(n,a,d.rootNode,u),u.forEach(p=>{p.origin.applyMatrix4(s),p.normal.applyMatrix4(s).normalize(),p.distance=r.copy(p.origin).sub(this.ray.origin).length()}),o.push(...u)}return o.sort((c,d)=>c.distance>d.distance?1:-1),o}}}();castRayAtSplatTreeNode=function(){let e=new f.Vector4,s=new f.Vector3,t=new f.Vector3,n=new f.Quaternion,r=new ss,i=1e-7,o=new f.Vector3(0,0,0),a=new f.Matrix4,c=new f.Matrix4,d=new f.Matrix4,u=new f.Matrix4,p=new f.Matrix4,h=new nt;return function(A,m,S,C=[]){if(A.intersectBox(S.boundingBox)){if(S.data&&S.data.indexes&&S.data.indexes.length>0)for(let E=0;E<S.data.indexes.length;E++){let x=S.data.indexes[E],T=m.splatMesh.getSceneIndexForSplat(x);if(m.splatMesh.getScene(T).visible&&(m.splatMesh.getSplatColor(x,e),m.splatMesh.getSplatCenter(x,s),m.splatMesh.getSplatScaleAndRotation(x,t,n),!(t.x<=i||t.y<=i||m.splatMesh.splatRenderMode===De.ThreeD&&t.z<=i)))if(this.raycastAgainstTrueSplatEllipsoid){c.makeScale(t.x,t.y,t.z),d.makeRotationFromQuaternion(n);let y=Math.log10(e.w)*2;if(a.makeScale(y,y,y),p.copy(a).multiply(d).multiply(c),u.copy(p).invert(),h.origin.copy(A.origin).sub(s).applyMatrix4(u),h.direction.copy(A.origin).add(A.direction).sub(s),h.direction.applyMatrix4(u).sub(h.origin).normalize(),h.intersectSphere(o,1,r)){let g=r.clone();g.splatIndex=x,g.origin.applyMatrix4(p).add(s),C.push(g)}}else{let y=t.x+t.y,g=2;if(m.splatMesh.splatRenderMode===De.ThreeD&&(y+=t.z,g=3),y=y/g,A.intersectSphere(s,y,r)){let I=r.clone();I.splatIndex=x,C.push(I)}}}if(S.children&&S.children.length>0)for(let E of S.children)this.castRayAtSplatTreeNode(A,m,E,C);return C}}}()},ze=class{static buildVertexShaderBase(e=!1,s=!1,t=0,n=""){let r=`
277
+ precision highp float;
278
+ #include <common>
279
+
280
+ attribute uint splatIndex;
281
+ uniform highp usampler2D centersColorsTexture;
282
+ uniform highp sampler2D sphericalHarmonicsTexture;
283
+ uniform highp sampler2D sphericalHarmonicsTextureR;
284
+ uniform highp sampler2D sphericalHarmonicsTextureG;
285
+ uniform highp sampler2D sphericalHarmonicsTextureB;
286
+
287
+ uniform highp usampler2D sceneIndexesTexture;
288
+ uniform vec2 sceneIndexesTextureSize;
289
+ uniform int sceneCount;
290
+ `;return s&&(r+=`
291
+ uniform float sceneOpacity[${j.MaxScenes}];
292
+ uniform int sceneVisibility[${j.MaxScenes}];
293
+ `),e&&(r+=`
294
+ uniform highp mat4 transforms[${j.MaxScenes}];
295
+ `),r+=`
296
+ ${n}
297
+ uniform vec2 focal;
298
+ uniform float orthoZoom;
299
+ uniform int orthographicMode;
300
+ uniform int pointCloudModeEnabled;
301
+ uniform float inverseFocalAdjustment;
302
+ uniform vec2 viewport;
303
+ uniform vec2 basisViewport;
304
+ uniform vec2 centersColorsTextureSize;
305
+ uniform int sphericalHarmonicsDegree;
306
+ uniform vec2 sphericalHarmonicsTextureSize;
307
+ uniform int sphericalHarmonics8BitMode;
308
+ uniform int sphericalHarmonicsMultiTextureMode;
309
+ uniform float visibleRegionRadius;
310
+ uniform float visibleRegionFadeStartRadius;
311
+ uniform float firstRenderTime;
312
+ uniform float currentTime;
313
+ uniform int fadeInComplete;
314
+ uniform vec3 sceneCenter;
315
+ uniform float splatScale;
316
+ uniform float sphericalHarmonics8BitCompressionRangeMin[${j.MaxScenes}];
317
+ uniform float sphericalHarmonics8BitCompressionRangeMax[${j.MaxScenes}];
318
+
319
+ varying vec4 vColor;
320
+ varying vec2 vUv;
321
+ varying vec2 vPosition;
322
+
323
+ mat3 quaternionToRotationMatrix(float x, float y, float z, float w) {
324
+ float s = 1.0 / sqrt(w * w + x * x + y * y + z * z);
325
+
326
+ return mat3(
327
+ 1. - 2. * (y * y + z * z),
328
+ 2. * (x * y + w * z),
329
+ 2. * (x * z - w * y),
330
+ 2. * (x * y - w * z),
331
+ 1. - 2. * (x * x + z * z),
332
+ 2. * (y * z + w * x),
333
+ 2. * (x * z + w * y),
334
+ 2. * (y * z - w * x),
335
+ 1. - 2. * (x * x + y * y)
336
+ );
337
+ }
338
+
339
+ const float sqrt8 = sqrt(8.0);
340
+ const float minAlpha = 1.0 / 255.0;
341
+
342
+ const vec4 encodeNorm4 = vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);
343
+ const uvec4 mask4 = uvec4(uint(0x000000FF), uint(0x0000FF00), uint(0x00FF0000), uint(0xFF000000));
344
+ const uvec4 shift4 = uvec4(0, 8, 16, 24);
345
+ vec4 uintToRGBAVec (uint u) {
346
+ uvec4 urgba = mask4 & u;
347
+ urgba = urgba >> shift4;
348
+ vec4 rgba = vec4(urgba) * encodeNorm4;
349
+ return rgba;
350
+ }
351
+
352
+ vec2 getDataUV(in int stride, in int offset, in vec2 dimensions) {
353
+ vec2 samplerUV = vec2(0.0, 0.0);
354
+ float d = float(splatIndex * uint(stride) + uint(offset)) / dimensions.x;
355
+ samplerUV.y = float(floor(d)) / dimensions.y;
356
+ samplerUV.x = fract(d);
357
+ return samplerUV;
358
+ }
359
+
360
+ vec2 getDataUVF(in uint sIndex, in float stride, in uint offset, in vec2 dimensions) {
361
+ vec2 samplerUV = vec2(0.0, 0.0);
362
+ float d = float(uint(float(sIndex) * stride) + offset) / dimensions.x;
363
+ samplerUV.y = float(floor(d)) / dimensions.y;
364
+ samplerUV.x = fract(d);
365
+ return samplerUV;
366
+ }
367
+
368
+ const float SH_C1 = 0.4886025119029199f;
369
+ const float[5] SH_C2 = float[](1.0925484, -1.0925484, 0.3153916, -1.0925484, 0.5462742);
370
+
371
+ void main () {
372
+
373
+ uint oddOffset = splatIndex & uint(0x00000001);
374
+ uint doubleOddOffset = oddOffset * uint(2);
375
+ bool isEven = oddOffset == uint(0);
376
+ uint nearestEvenIndex = splatIndex - oddOffset;
377
+ float fOddOffset = float(oddOffset);
378
+
379
+ uvec4 sampledCenterColor = texture(centersColorsTexture, getDataUV(1, 0, centersColorsTextureSize));
380
+ vec3 splatCenter = uintBitsToFloat(uvec3(sampledCenterColor.gba));
381
+
382
+ uint sceneIndex = uint(0);
383
+ if (sceneCount > 1) {
384
+ sceneIndex = texture(sceneIndexesTexture, getDataUV(1, 0, sceneIndexesTextureSize)).r;
385
+ }
386
+ `,s&&(r+=`
387
+ float splatOpacityFromScene = sceneOpacity[sceneIndex];
388
+ int sceneVisible = sceneVisibility[sceneIndex];
389
+ if (splatOpacityFromScene <= 0.01 || sceneVisible == 0) {
390
+ gl_Position = vec4(0.0, 0.0, 2.0, 1.0);
391
+ return;
392
+ }
393
+ `),e?r+=`
394
+ mat4 transform = transforms[sceneIndex];
395
+ mat4 transformModelViewMatrix = viewMatrix * transform;
396
+ `:r+="mat4 transformModelViewMatrix = modelViewMatrix;",r+=`
397
+ float sh8BitCompressionRangeMinForScene = sphericalHarmonics8BitCompressionRangeMin[sceneIndex];
398
+ float sh8BitCompressionRangeMaxForScene = sphericalHarmonics8BitCompressionRangeMax[sceneIndex];
399
+ float sh8BitCompressionRangeForScene = sh8BitCompressionRangeMaxForScene - sh8BitCompressionRangeMinForScene;
400
+ float sh8BitCompressionHalfRangeForScene = sh8BitCompressionRangeForScene / 2.0;
401
+ vec3 vec8BitSHShift = vec3(sh8BitCompressionRangeMinForScene);
402
+
403
+ vec4 viewCenter = transformModelViewMatrix * vec4(splatCenter, 1.0);
404
+
405
+ vec4 clipCenter = projectionMatrix * viewCenter;
406
+
407
+ float clip = 1.2 * clipCenter.w;
408
+ if (clipCenter.z < -clip || clipCenter.x < -clip || clipCenter.x > clip || clipCenter.y < -clip || clipCenter.y > clip) {
409
+ gl_Position = vec4(0.0, 0.0, 2.0, 1.0);
410
+ return;
411
+ }
412
+
413
+ vec3 ndcCenter = clipCenter.xyz / clipCenter.w;
414
+
415
+ vPosition = position.xy;
416
+ vColor = uintToRGBAVec(sampledCenterColor.r);
417
+ `,t>=1&&(r+=`
418
+ if (sphericalHarmonicsDegree >= 1) {
419
+ `,e?r+=`
420
+ vec3 worldViewDir = normalize(splatCenter - vec3(inverse(transform) * vec4(cameraPosition, 1.0)));
421
+ `:r+=`
422
+ vec3 worldViewDir = normalize(splatCenter - cameraPosition);
423
+ `,r+=`
424
+ vec3 sh1;
425
+ vec3 sh2;
426
+ vec3 sh3;
427
+ `,t>=2&&(r+=`
428
+ vec3 sh4;
429
+ vec3 sh5;
430
+ vec3 sh6;
431
+ vec3 sh7;
432
+ vec3 sh8;
433
+ `),t===1?r+=`
434
+ if (sphericalHarmonicsMultiTextureMode == 0) {
435
+ vec2 shUV = getDataUVF(nearestEvenIndex, 2.5, doubleOddOffset, sphericalHarmonicsTextureSize);
436
+ vec4 sampledSH0123 = texture(sphericalHarmonicsTexture, shUV);
437
+ shUV = getDataUVF(nearestEvenIndex, 2.5, doubleOddOffset + uint(1), sphericalHarmonicsTextureSize);
438
+ vec4 sampledSH4567 = texture(sphericalHarmonicsTexture, shUV);
439
+ shUV = getDataUVF(nearestEvenIndex, 2.5, doubleOddOffset + uint(2), sphericalHarmonicsTextureSize);
440
+ vec4 sampledSH891011 = texture(sphericalHarmonicsTexture, shUV);
441
+ sh1 = vec3(sampledSH0123.rgb) * (1.0 - fOddOffset) + vec3(sampledSH0123.ba, sampledSH4567.r) * fOddOffset;
442
+ sh2 = vec3(sampledSH0123.a, sampledSH4567.rg) * (1.0 - fOddOffset) + vec3(sampledSH4567.gba) * fOddOffset;
443
+ sh3 = vec3(sampledSH4567.ba, sampledSH891011.r) * (1.0 - fOddOffset) + vec3(sampledSH891011.rgb) * fOddOffset;
444
+ } else {
445
+ vec2 sampledSH01R = texture(sphericalHarmonicsTextureR, getDataUV(2, 0, sphericalHarmonicsTextureSize)).rg;
446
+ vec2 sampledSH23R = texture(sphericalHarmonicsTextureR, getDataUV(2, 1, sphericalHarmonicsTextureSize)).rg;
447
+ vec2 sampledSH01G = texture(sphericalHarmonicsTextureG, getDataUV(2, 0, sphericalHarmonicsTextureSize)).rg;
448
+ vec2 sampledSH23G = texture(sphericalHarmonicsTextureG, getDataUV(2, 1, sphericalHarmonicsTextureSize)).rg;
449
+ vec2 sampledSH01B = texture(sphericalHarmonicsTextureB, getDataUV(2, 0, sphericalHarmonicsTextureSize)).rg;
450
+ vec2 sampledSH23B = texture(sphericalHarmonicsTextureB, getDataUV(2, 1, sphericalHarmonicsTextureSize)).rg;
451
+ sh1 = vec3(sampledSH01R.rg, sampledSH23R.r);
452
+ sh2 = vec3(sampledSH01G.rg, sampledSH23G.r);
453
+ sh3 = vec3(sampledSH01B.rg, sampledSH23B.r);
454
+ }
455
+ `:t===2&&(r+=`
456
+ vec4 sampledSH0123;
457
+ vec4 sampledSH4567;
458
+ vec4 sampledSH891011;
459
+
460
+ vec4 sampledSH0123R;
461
+ vec4 sampledSH0123G;
462
+ vec4 sampledSH0123B;
463
+
464
+ if (sphericalHarmonicsMultiTextureMode == 0) {
465
+ sampledSH0123 = texture(sphericalHarmonicsTexture, getDataUV(6, 0, sphericalHarmonicsTextureSize));
466
+ sampledSH4567 = texture(sphericalHarmonicsTexture, getDataUV(6, 1, sphericalHarmonicsTextureSize));
467
+ sampledSH891011 = texture(sphericalHarmonicsTexture, getDataUV(6, 2, sphericalHarmonicsTextureSize));
468
+ sh1 = sampledSH0123.rgb;
469
+ sh2 = vec3(sampledSH0123.a, sampledSH4567.rg);
470
+ sh3 = vec3(sampledSH4567.ba, sampledSH891011.r);
471
+ } else {
472
+ sampledSH0123R = texture(sphericalHarmonicsTextureR, getDataUV(2, 0, sphericalHarmonicsTextureSize));
473
+ sampledSH0123G = texture(sphericalHarmonicsTextureG, getDataUV(2, 0, sphericalHarmonicsTextureSize));
474
+ sampledSH0123B = texture(sphericalHarmonicsTextureB, getDataUV(2, 0, sphericalHarmonicsTextureSize));
475
+ sh1 = vec3(sampledSH0123R.rgb);
476
+ sh2 = vec3(sampledSH0123G.rgb);
477
+ sh3 = vec3(sampledSH0123B.rgb);
478
+ }
479
+ `),r+=`
480
+ if (sphericalHarmonics8BitMode == 1) {
481
+ sh1 = sh1 * sh8BitCompressionRangeForScene + vec8BitSHShift;
482
+ sh2 = sh2 * sh8BitCompressionRangeForScene + vec8BitSHShift;
483
+ sh3 = sh3 * sh8BitCompressionRangeForScene + vec8BitSHShift;
484
+ }
485
+ float x = worldViewDir.x;
486
+ float y = worldViewDir.y;
487
+ float z = worldViewDir.z;
488
+ vColor.rgb += SH_C1 * (-sh1 * y + sh2 * z - sh3 * x);
489
+ `,t>=2&&(r+=`
490
+ if (sphericalHarmonicsDegree >= 2) {
491
+ float xx = x * x;
492
+ float yy = y * y;
493
+ float zz = z * z;
494
+ float xy = x * y;
495
+ float yz = y * z;
496
+ float xz = x * z;
497
+ `,t===2&&(r+=`
498
+ if (sphericalHarmonicsMultiTextureMode == 0) {
499
+ vec4 sampledSH12131415 = texture(sphericalHarmonicsTexture, getDataUV(6, 3, sphericalHarmonicsTextureSize));
500
+ vec4 sampledSH16171819 = texture(sphericalHarmonicsTexture, getDataUV(6, 4, sphericalHarmonicsTextureSize));
501
+ vec4 sampledSH20212223 = texture(sphericalHarmonicsTexture, getDataUV(6, 5, sphericalHarmonicsTextureSize));
502
+ sh4 = sampledSH891011.gba;
503
+ sh5 = sampledSH12131415.rgb;
504
+ sh6 = vec3(sampledSH12131415.a, sampledSH16171819.rg);
505
+ sh7 = vec3(sampledSH16171819.ba, sampledSH20212223.r);
506
+ sh8 = sampledSH20212223.gba;
507
+ } else {
508
+ vec4 sampledSH4567R = texture(sphericalHarmonicsTextureR, getDataUV(2, 1, sphericalHarmonicsTextureSize));
509
+ vec4 sampledSH4567G = texture(sphericalHarmonicsTextureG, getDataUV(2, 1, sphericalHarmonicsTextureSize));
510
+ vec4 sampledSH4567B = texture(sphericalHarmonicsTextureB, getDataUV(2, 1, sphericalHarmonicsTextureSize));
511
+ sh4 = vec3(sampledSH0123R.a, sampledSH4567R.rg);
512
+ sh5 = vec3(sampledSH4567R.ba, sampledSH0123G.a);
513
+ sh6 = vec3(sampledSH4567G.rgb);
514
+ sh7 = vec3(sampledSH4567G.a, sampledSH0123B.a, sampledSH4567B.r);
515
+ sh8 = vec3(sampledSH4567B.gba);
516
+ }
517
+ `),r+=`
518
+ if (sphericalHarmonics8BitMode == 1) {
519
+ sh4 = sh4 * sh8BitCompressionRangeForScene + vec8BitSHShift;
520
+ sh5 = sh5 * sh8BitCompressionRangeForScene + vec8BitSHShift;
521
+ sh6 = sh6 * sh8BitCompressionRangeForScene + vec8BitSHShift;
522
+ sh7 = sh7 * sh8BitCompressionRangeForScene + vec8BitSHShift;
523
+ sh8 = sh8 * sh8BitCompressionRangeForScene + vec8BitSHShift;
524
+ }
525
+
526
+ vColor.rgb +=
527
+ (SH_C2[0] * xy) * sh4 +
528
+ (SH_C2[1] * yz) * sh5 +
529
+ (SH_C2[2] * (2.0 * zz - xx - yy)) * sh6 +
530
+ (SH_C2[3] * xz) * sh7 +
531
+ (SH_C2[4] * (xx - yy)) * sh8;
532
+ }
533
+ `),r+=`
534
+
535
+ vColor.rgb = clamp(vColor.rgb, vec3(0.), vec3(1.));
536
+
537
+ }
538
+
539
+ `),r}static getVertexShaderFadeIn(){return`
540
+ if (fadeInComplete == 0) {
541
+ float opacityAdjust = 1.0;
542
+ float centerDist = length(splatCenter - sceneCenter);
543
+ float renderTime = max(currentTime - firstRenderTime, 0.0);
544
+
545
+ float fadeDistance = 0.75;
546
+ float distanceLoadFadeInFactor = step(visibleRegionFadeStartRadius, centerDist);
547
+ distanceLoadFadeInFactor = (1.0 - distanceLoadFadeInFactor) +
548
+ (1.0 - clamp((centerDist - visibleRegionFadeStartRadius) / fadeDistance, 0.0, 1.0)) *
549
+ distanceLoadFadeInFactor;
550
+ opacityAdjust *= distanceLoadFadeInFactor;
551
+ vColor.a *= opacityAdjust;
552
+ }
553
+ `}static getUniforms(e=!1,s=!1,t=0,n=1,r=!1){let i={sceneCenter:{type:"v3",value:new f.Vector3},fadeInComplete:{type:"i",value:0},orthographicMode:{type:"i",value:0},visibleRegionFadeStartRadius:{type:"f",value:0},visibleRegionRadius:{type:"f",value:0},currentTime:{type:"f",value:0},firstRenderTime:{type:"f",value:0},centersColorsTexture:{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 f.Vector2},orthoZoom:{type:"f",value:1},inverseFocalAdjustment:{type:"f",value:1},viewport:{type:"v2",value:new f.Vector2},basisViewport:{type:"v2",value:new f.Vector2},debugColor:{type:"v3",value:new f.Color},centersColorsTextureSize:{type:"v2",value:new f.Vector2(1024,1024)},sphericalHarmonicsDegree:{type:"i",value:t},sphericalHarmonicsTextureSize:{type:"v2",value:new f.Vector2(1024,1024)},sphericalHarmonics8BitMode:{type:"i",value:0},sphericalHarmonicsMultiTextureMode:{type:"i",value:0},splatScale:{type:"f",value:n},pointCloudModeEnabled:{type:"i",value:r?1:0},sceneIndexesTexture:{type:"t",value:null},sceneIndexesTextureSize:{type:"v2",value:new f.Vector2(1024,1024)},sceneCount:{type:"i",value:1}};for(let o=0;o<j.MaxScenes;o++)i.sphericalHarmonics8BitCompressionRangeMin.value.push(-j.SphericalHarmonics8BitCompressionRange/2),i.sphericalHarmonics8BitCompressionRangeMax.value.push(j.SphericalHarmonics8BitCompressionRange/2);if(s){let o=[];for(let c=0;c<j.MaxScenes;c++)o.push(1);i.sceneOpacity={type:"f",value:o};let a=[];for(let c=0;c<j.MaxScenes;c++)a.push(1);i.sceneVisibility={type:"i",value:a}}if(e){let o=[];for(let a=0;a<j.MaxScenes;a++)o.push(new f.Matrix4);i.transforms={type:"mat4",value:o}}return i}},rs=class l{static build(e=!1,s=!1,t=!1,n=2048,r=1,i=!1,o=0,a=.3){let d=ze.buildVertexShaderBase(e,s,o,`
554
+ uniform vec2 covariancesTextureSize;
555
+ uniform highp sampler2D covariancesTexture;
556
+ uniform highp usampler2D covariancesTextureHalfFloat;
557
+ uniform int covariancesAreHalfFloat;
558
+
559
+ void fromCovarianceHalfFloatV4(uvec4 val, out vec4 first, out vec4 second) {
560
+ vec2 r = unpackHalf2x16(val.r);
561
+ vec2 g = unpackHalf2x16(val.g);
562
+ vec2 b = unpackHalf2x16(val.b);
563
+
564
+ first = vec4(r.x, r.y, g.x, g.y);
565
+ second = vec4(b.x, b.y, 0.0, 0.0);
566
+ }
567
+ `);d+=l.buildVertexShaderProjection(t,s,n,a);let u=l.buildFragmentShader(),p=ze.getUniforms(e,s,o,r,i);return p.covariancesTextureSize={type:"v2",value:new f.Vector2(1024,1024)},p.covariancesTexture={type:"t",value:null},p.covariancesTextureHalfFloat={type:"t",value:null},p.covariancesAreHalfFloat={type:"i",value:0},new f.ShaderMaterial({uniforms:p,vertexShader:d,fragmentShader:u,transparent:!0,alphaTest:1,blending:f.NormalBlending,depthTest:!0,depthWrite:!1,side:f.DoubleSide})}static buildVertexShaderProjection(e,s,t,n){let r=`
568
+
569
+ vec4 sampledCovarianceA;
570
+ vec4 sampledCovarianceB;
571
+ vec3 cov3D_M11_M12_M13;
572
+ vec3 cov3D_M22_M23_M33;
573
+ if (covariancesAreHalfFloat == 0) {
574
+ sampledCovarianceA = texture(covariancesTexture, getDataUVF(nearestEvenIndex, 1.5, oddOffset,
575
+ covariancesTextureSize));
576
+ sampledCovarianceB = texture(covariancesTexture, getDataUVF(nearestEvenIndex, 1.5, oddOffset + uint(1),
577
+ covariancesTextureSize));
578
+
579
+ cov3D_M11_M12_M13 = vec3(sampledCovarianceA.rgb) * (1.0 - fOddOffset) +
580
+ vec3(sampledCovarianceA.ba, sampledCovarianceB.r) * fOddOffset;
581
+ cov3D_M22_M23_M33 = vec3(sampledCovarianceA.a, sampledCovarianceB.rg) * (1.0 - fOddOffset) +
582
+ vec3(sampledCovarianceB.gba) * fOddOffset;
583
+ } else {
584
+ uvec4 sampledCovarianceU = texture(covariancesTextureHalfFloat, getDataUV(1, 0, covariancesTextureSize));
585
+ fromCovarianceHalfFloatV4(sampledCovarianceU, sampledCovarianceA, sampledCovarianceB);
586
+ cov3D_M11_M12_M13 = sampledCovarianceA.rgb;
587
+ cov3D_M22_M23_M33 = vec3(sampledCovarianceA.a, sampledCovarianceB.rg);
588
+ }
589
+
590
+ // Construct the 3D covariance matrix
591
+ mat3 Vrk = mat3(
592
+ cov3D_M11_M12_M13.x, cov3D_M11_M12_M13.y, cov3D_M11_M12_M13.z,
593
+ cov3D_M11_M12_M13.y, cov3D_M22_M23_M33.x, cov3D_M22_M23_M33.y,
594
+ cov3D_M11_M12_M13.z, cov3D_M22_M23_M33.y, cov3D_M22_M23_M33.z
595
+ );
596
+
597
+ mat3 J;
598
+ if (orthographicMode == 1) {
599
+ // Since the projection is linear, we don't need an approximation
600
+ J = transpose(mat3(orthoZoom, 0.0, 0.0,
601
+ 0.0, orthoZoom, 0.0,
602
+ 0.0, 0.0, 0.0));
603
+ } else {
604
+ // Construct the Jacobian of the affine approximation of the projection matrix. It will be used to transform the
605
+ // 3D covariance matrix instead of using the actual projection matrix because that transformation would
606
+ // require a non-linear component (perspective division) which would yield a non-gaussian result.
607
+ float s = 1.0 / (viewCenter.z * viewCenter.z);
608
+ J = mat3(
609
+ focal.x / viewCenter.z, 0., -(focal.x * viewCenter.x) * s,
610
+ 0., focal.y / viewCenter.z, -(focal.y * viewCenter.y) * s,
611
+ 0., 0., 0.
612
+ );
613
+ }
614
+
615
+ // Concatenate the projection approximation with the model-view transformation
616
+ mat3 W = transpose(mat3(transformModelViewMatrix));
617
+ mat3 T = W * J;
618
+
619
+ // Transform the 3D covariance matrix (Vrk) to compute the 2D covariance matrix
620
+ mat3 cov2Dm = transpose(T) * Vrk * T;
621
+ `;return e?r+=`
622
+ float detOrig = cov2Dm[0][0] * cov2Dm[1][1] - cov2Dm[0][1] * cov2Dm[0][1];
623
+ cov2Dm[0][0] += ${n};
624
+ cov2Dm[1][1] += ${n};
625
+ float detBlur = cov2Dm[0][0] * cov2Dm[1][1] - cov2Dm[0][1] * cov2Dm[0][1];
626
+ vColor.a *= sqrt(max(detOrig / detBlur, 0.0));
627
+ if (vColor.a < minAlpha) return;
628
+ `:r+=`
629
+ cov2Dm[0][0] += ${n};
630
+ cov2Dm[1][1] += ${n};
631
+ `,r+=`
632
+
633
+ // We are interested in the upper-left 2x2 portion of the projected 3D covariance matrix because
634
+ // we only care about the X and Y values. We want the X-diagonal, cov2Dm[0][0],
635
+ // the Y-diagonal, cov2Dm[1][1], and the correlation between the two cov2Dm[0][1]. We don't
636
+ // need cov2Dm[1][0] because it is a symetric matrix.
637
+ vec3 cov2Dv = vec3(cov2Dm[0][0], cov2Dm[0][1], cov2Dm[1][1]);
638
+
639
+ // We now need to solve for the eigen-values and eigen vectors of the 2D covariance matrix
640
+ // so that we can determine the 2D basis for the splat. This is done using the method described
641
+ // here: https://people.math.harvard.edu/~knill/teaching/math21b2004/exhibits/2dmatrices/index.html
642
+ // After calculating the eigen-values and eigen-vectors, we calculate the basis for rendering the splat
643
+ // by normalizing the eigen-vectors and then multiplying them by (sqrt(8) * sqrt(eigen-value)), which is
644
+ // equal to scaling them by sqrt(8) standard deviations.
645
+ //
646
+ // This is a different approach than in the original work at INRIA. In that work they compute the
647
+ // max extents of the projected splat in screen space to form a screen-space aligned bounding rectangle
648
+ // which forms the geometry that is actually rasterized. The dimensions of that bounding box are 3.0
649
+ // times the square root of the maximum eigen-value, or 3 standard deviations. They then use the inverse
650
+ // 2D covariance matrix (called 'conic') in the CUDA rendering thread to determine fragment opacity by
651
+ // calculating the full gaussian: exp(-0.5 * (X - mean) * conic * (X - mean)) * splat opacity
652
+ float a = cov2Dv.x;
653
+ float d = cov2Dv.z;
654
+ float b = cov2Dv.y;
655
+ float D = a * d - b * b;
656
+ float trace = a + d;
657
+ float traceOver2 = 0.5 * trace;
658
+ float term2 = sqrt(max(0.1f, traceOver2 * traceOver2 - D));
659
+ float eigenValue1 = traceOver2 + term2;
660
+ float eigenValue2 = traceOver2 - term2;
661
+
662
+ if (pointCloudModeEnabled == 1) {
663
+ eigenValue1 = eigenValue2 = 0.2;
664
+ }
665
+
666
+ if (eigenValue2 <= 0.0) return;
667
+
668
+ vec2 eigenVector1 = normalize(vec2(b, eigenValue1 - a));
669
+ // since the eigen vectors are orthogonal, we derive the second one from the first
670
+ vec2 eigenVector2 = vec2(eigenVector1.y, -eigenVector1.x);
671
+
672
+ // We use sqrt(8) standard deviations instead of 3 to eliminate more of the splat with a very low opacity.
673
+ vec2 basisVector1 = eigenVector1 * splatScale * min(sqrt8 * sqrt(eigenValue1), ${parseInt(t)}.0);
674
+ vec2 basisVector2 = eigenVector2 * splatScale * min(sqrt8 * sqrt(eigenValue2), ${parseInt(t)}.0);
675
+ `,s&&(r+=`
676
+ vColor.a *= splatOpacityFromScene;
677
+ `),r+=`
678
+ vec2 ndcOffset = vec2(vPosition.x * basisVector1 + vPosition.y * basisVector2) *
679
+ basisViewport * 2.0 * inverseFocalAdjustment;
680
+
681
+ vec4 quadPos = vec4(ndcCenter.xy + ndcOffset, ndcCenter.z, 1.0);
682
+ gl_Position = quadPos;
683
+
684
+ // Scale the position data we send to the fragment shader
685
+ vPosition *= sqrt8;
686
+ `,r+=ze.getVertexShaderFadeIn(),r+="}",r}static buildFragmentShader(){let e=`
687
+ precision highp float;
688
+ #include <common>
689
+
690
+ uniform vec3 debugColor;
691
+
692
+ varying vec4 vColor;
693
+ varying vec2 vUv;
694
+ varying vec2 vPosition;
695
+ `;return e+=`
696
+ void main () {
697
+ // Compute the positional squared distance from the center of the splat to the current fragment.
698
+ float A = dot(vPosition, vPosition);
699
+ // Since the positional data in vPosition has been scaled by sqrt(8), the squared result will be
700
+ // scaled by a factor of 8. If the squared result is larger than 8, it means it is outside the ellipse
701
+ // defined by the rectangle formed by vPosition. It also means it's farther
702
+ // away than sqrt(8) standard deviations from the mean.
703
+ if (A > 8.0) discard;
704
+ vec3 color = vColor.rgb;
705
+
706
+ // Since the rendered splat is scaled by sqrt(8), the inverse covariance matrix that is part of
707
+ // the gaussian formula becomes the identity matrix. We're then left with (X - mean) * (X - mean),
708
+ // and since 'mean' is zero, we have X * X, which is the same as A:
709
+ float opacity = exp(-0.5 * A) * vColor.a;
710
+
711
+ gl_FragColor = vec4(color.rgb, opacity);
712
+ }
713
+ `,e}},os=class l{static build(e=!1,s=!1,t=1,n=!1,r=0){let o=ze.buildVertexShaderBase(e,s,r,`
714
+ uniform vec2 scaleRotationsTextureSize;
715
+ uniform highp sampler2D scaleRotationsTexture;
716
+ varying mat3 vT;
717
+ varying vec2 vQuadCenter;
718
+ varying vec2 vFragCoord;
719
+ `);o+=l.buildVertexShaderProjection();let a=l.buildFragmentShader(),c=ze.getUniforms(e,s,r,t,n);return c.scaleRotationsTexture={type:"t",value:null},c.scaleRotationsTextureSize={type:"v2",value:new f.Vector2(1024,1024)},new f.ShaderMaterial({uniforms:c,vertexShader:o,fragmentShader:a,transparent:!0,alphaTest:1,blending:f.NormalBlending,depthTest:!0,depthWrite:!1,side:f.DoubleSide})}static buildVertexShaderProjection(){let e=`
720
+
721
+ vec4 scaleRotationA = texture(scaleRotationsTexture, getDataUVF(nearestEvenIndex, 1.5,
722
+ oddOffset, scaleRotationsTextureSize));
723
+ vec4 scaleRotationB = texture(scaleRotationsTexture, getDataUVF(nearestEvenIndex, 1.5,
724
+ oddOffset + uint(1), scaleRotationsTextureSize));
725
+
726
+ vec3 scaleRotation123 = vec3(scaleRotationA.rgb) * (1.0 - fOddOffset) +
727
+ vec3(scaleRotationA.ba, scaleRotationB.r) * fOddOffset;
728
+ vec3 scaleRotation456 = vec3(scaleRotationA.a, scaleRotationB.rg) * (1.0 - fOddOffset) +
729
+ vec3(scaleRotationB.gba) * fOddOffset;
730
+
731
+ float missingW = sqrt(1.0 - scaleRotation456.x * scaleRotation456.x - scaleRotation456.y *
732
+ scaleRotation456.y - scaleRotation456.z * scaleRotation456.z);
733
+ mat3 R = quaternionToRotationMatrix(scaleRotation456.r, scaleRotation456.g, scaleRotation456.b, missingW);
734
+ mat3 S = mat3(scaleRotation123.r, 0.0, 0.0,
735
+ 0.0, scaleRotation123.g, 0.0,
736
+ 0.0, 0.0, scaleRotation123.b);
737
+
738
+ mat3 L = R * S;
739
+
740
+ mat3x4 splat2World = mat3x4(vec4(L[0], 0.0),
741
+ vec4(L[1], 0.0),
742
+ vec4(splatCenter.x, splatCenter.y, splatCenter.z, 1.0));
743
+
744
+ mat4 world2ndc = transpose(projectionMatrix * transformModelViewMatrix);
745
+
746
+ mat3x4 ndc2pix = mat3x4(vec4(viewport.x / 2.0, 0.0, 0.0, (viewport.x - 1.0) / 2.0),
747
+ vec4(0.0, viewport.y / 2.0, 0.0, (viewport.y - 1.0) / 2.0),
748
+ vec4(0.0, 0.0, 0.0, 1.0));
749
+
750
+ mat3 T = transpose(splat2World) * world2ndc * ndc2pix;
751
+ vec3 normal = vec3(viewMatrix * vec4(L[0][2], L[1][2], L[2][2], 0.0));
752
+ `;return e+=`
753
+
754
+ mat4 splat2World4 = mat4(vec4(L[0], 0.0),
755
+ vec4(L[1], 0.0),
756
+ vec4(L[2], 0.0),
757
+ vec4(splatCenter.x, splatCenter.y, splatCenter.z, 1.0));
758
+
759
+ mat4 Tt = transpose(transpose(splat2World4) * world2ndc);
760
+
761
+ vec4 tempPoint1 = Tt * vec4(1.0, 0.0, 0.0, 1.0);
762
+ tempPoint1 /= tempPoint1.w;
763
+
764
+ vec4 tempPoint2 = Tt * vec4(0.0, 1.0, 0.0, 1.0);
765
+ tempPoint2 /= tempPoint2.w;
766
+
767
+ vec4 center = Tt * vec4(0.0, 0.0, 0.0, 1.0);
768
+ center /= center.w;
769
+
770
+ vec2 basisVector1 = tempPoint1.xy - center.xy;
771
+ vec2 basisVector2 = tempPoint2.xy - center.xy;
772
+
773
+ vec2 basisVector1Screen = basisVector1 * 0.5 * viewport;
774
+ vec2 basisVector2Screen = basisVector2 * 0.5 * viewport;
775
+
776
+ const float minPix = 1.;
777
+ if (length(basisVector1Screen) < minPix || length(basisVector2Screen) < minPix) {
778
+
779
+ vec3 T0 = vec3(T[0][0], T[0][1], T[0][2]);
780
+ vec3 T1 = vec3(T[1][0], T[1][1], T[1][2]);
781
+ vec3 T3 = vec3(T[2][0], T[2][1], T[2][2]);
782
+
783
+ vec3 tempPoint = vec3(1.0, 1.0, -1.0);
784
+ float distance = (T3.x * T3.x * tempPoint.x) + (T3.y * T3.y * tempPoint.y) + (T3.z * T3.z * tempPoint.z);
785
+ vec3 f = (1.0 / distance) * tempPoint;
786
+ if (abs(distance) < 0.00001) return;
787
+
788
+ float pointImageX = (T0.x * T3.x * f.x) + (T0.y * T3.y * f.y) + (T0.z * T3.z * f.z);
789
+ float pointImageY = (T1.x * T3.x * f.x) + (T1.y * T3.y * f.y) + (T1.z * T3.z * f.z);
790
+ vec2 pointImage = vec2(pointImageX, pointImageY);
791
+
792
+ float tempX = (T0.x * T0.x * f.x) + (T0.y * T0.y * f.y) + (T0.z * T0.z * f.z);
793
+ float tempY = (T1.x * T1.x * f.x) + (T1.y * T1.y * f.y) + (T1.z * T1.z * f.z);
794
+ vec2 temp = vec2(tempX, tempY);
795
+
796
+ vec2 halfExtend = pointImage * pointImage - temp;
797
+ vec2 extent = sqrt(max(vec2(0.0001), halfExtend));
798
+ float radius = max(extent.x, extent.y);
799
+
800
+ vec2 ndcOffset = ((position.xy * radius * 3.0) * basisViewport * 2.0);
801
+
802
+ vec4 quadPos = vec4(ndcCenter.xy + ndcOffset, ndcCenter.z, 1.0);
803
+ gl_Position = quadPos;
804
+
805
+ vT = T;
806
+ vQuadCenter = pointImage;
807
+ vFragCoord = (quadPos.xy * 0.5 + 0.5) * viewport;
808
+
809
+ } else {
810
+ vec2 ndcOffset = vec2(position.x * basisVector1 + position.y * basisVector2) * 3.0 * inverseFocalAdjustment;
811
+ vec4 quadPos = vec4(ndcCenter.xy + ndcOffset, ndcCenter.z, 1.0);
812
+ gl_Position = quadPos;
813
+
814
+ vT = T;
815
+ vQuadCenter = center.xy;
816
+ vFragCoord = (quadPos.xy * 0.5 + 0.5) * viewport;
817
+ }
818
+ `,e+=ze.getVertexShaderFadeIn(),e+="}",e}static buildFragmentShader(){return`
819
+ precision highp float;
820
+ #include <common>
821
+
822
+ uniform vec3 debugColor;
823
+
824
+ varying vec4 vColor;
825
+ varying vec2 vUv;
826
+ varying vec2 vPosition;
827
+ varying mat3 vT;
828
+ varying vec2 vQuadCenter;
829
+ varying vec2 vFragCoord;
830
+
831
+ void main () {
832
+
833
+ const float FilterInvSquare = 2.0;
834
+ const float near_n = 0.2;
835
+ const float T = 1.0;
836
+
837
+ vec2 xy = vQuadCenter;
838
+ vec3 Tu = vT[0];
839
+ vec3 Tv = vT[1];
840
+ vec3 Tw = vT[2];
841
+ vec3 k = vFragCoord.x * Tw - Tu;
842
+ vec3 l = vFragCoord.y * Tw - Tv;
843
+ vec3 p = cross(k, l);
844
+ if (p.z == 0.0) discard;
845
+ vec2 s = vec2(p.x / p.z, p.y / p.z);
846
+ float rho3d = (s.x * s.x + s.y * s.y);
847
+ vec2 d = vec2(xy.x - vFragCoord.x, xy.y - vFragCoord.y);
848
+ float rho2d = FilterInvSquare * (d.x * d.x + d.y * d.y);
849
+
850
+ // compute intersection and depth
851
+ float rho = min(rho3d, rho2d);
852
+ float depth = (rho3d <= rho2d) ? (s.x * Tw.x + s.y * Tw.y) + Tw.z : Tw.z;
853
+ if (depth < near_n) discard;
854
+ // vec4 nor_o = collected_normal_opacity[j];
855
+ // float normal[3] = {nor_o.x, nor_o.y, nor_o.z};
856
+ float opa = vColor.a;
857
+
858
+ float power = -0.5f * rho;
859
+ if (power > 0.0f) discard;
860
+
861
+ // Eq. (2) from 3D Gaussian splatting paper.
862
+ // Obtain alpha by multiplying with Gaussian opacity
863
+ // and its exponential falloff from mean.
864
+ // Avoid numerical instabilities (see paper appendix).
865
+ float alpha = min(0.99f, opa * exp(power));
866
+ if (alpha < 1.0f / 255.0f) discard;
867
+ float test_T = T * (1.0 - alpha);
868
+ if (test_T < 0.0001)discard;
869
+
870
+ float w = alpha * T;
871
+ gl_FragColor = vec4(vColor.rgb, w);
872
+ }
873
+ `}},is=class{static build(e){let s=new f.BufferGeometry;s.setIndex([0,1,2,0,2,3]);let t=new Float32Array(4*3),n=new f.BufferAttribute(t,3);s.setAttribute("position",n),n.setXYZ(0,-1,-1,0),n.setXYZ(1,-1,1,0),n.setXYZ(2,1,1,0),n.setXYZ(3,1,-1,0),n.needsUpdate=!0;let r=new f.InstancedBufferGeometry().copy(s),i=new Uint32Array(e),o=new f.InstancedBufferAttribute(i,1,!1);return o.setUsage(f.DynamicDrawUsage),r.setAttribute("splatIndex",o),r.instanceCount=0,r}},as=class extends f.Object3D{constructor(e,s=new f.Vector3,t=new f.Quaternion,n=new f.Vector3(1,1,1),r=1,i=1,o=!0){super(),this.splatBuffer=e,this.position.copy(s),this.quaternion.copy(t),this.scale.copy(n),this.transform=new f.Matrix4,this.minimumAlpha=r,this.opacity=i,this.visible=o}copyTransformData(e){this.position.copy(e.position),this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.transform.copy(e.transform)}updateTransform(e){e?(this.matrixWorldAutoUpdate&&this.updateWorldMatrix(!0,!1),this.transform.copy(this.matrixWorld)):(this.matrixAutoUpdate&&this.updateMatrix(),this.transform.copy(this.matrix))}},ls=class l{static idGen=0;constructor(e,s,t,n){this.min=new f.Vector3().copy(e),this.max=new f.Vector3().copy(s),this.boundingBox=new f.Box3(this.min,this.max),this.center=new f.Vector3().copy(this.max).sub(this.min).multiplyScalar(.5).add(this.min),this.depth=t,this.children=[],this.data=null,this.id=n||l.idGen++}},cs=class l{constructor(e,s){this.maxDepth=e,this.maxCentersPerNode=s,this.sceneDimensions=new f.Vector3,this.sceneMin=new f.Vector3,this.sceneMax=new f.Vector3,this.rootNode=null,this.nodesWithIndexes=[],this.splatMesh=null}static convertWorkerSubTreeNode(e){let s=new f.Vector3().fromArray(e.min),t=new f.Vector3().fromArray(e.max),n=new ls(s,t,e.depth,e.id);if(e.data.indexes){n.data={indexes:[]};for(let r of e.data.indexes)n.data.indexes.push(r)}if(e.children)for(let r of e.children)n.children.push(l.convertWorkerSubTreeNode(r));return n}static convertWorkerSubTree(e,s){let t=new l(e.maxDepth,e.maxCentersPerNode);t.sceneMin=new f.Vector3().fromArray(e.sceneMin),t.sceneMax=new f.Vector3().fromArray(e.sceneMax),t.splatMesh=s,t.rootNode=l.convertWorkerSubTreeNode(e.rootNode);let n=(r,i)=>{r.children.length===0&&i(r);for(let o of r.children)n(o,i)};return t.nodesWithIndexes=[],n(t.rootNode,r=>{r.data&&r.data.indexes&&r.data.indexes.length>0&&t.nodesWithIndexes.push(r)}),t}};function _r(l){let e=0;class s{constructor(a,c){this.min=[a[0],a[1],a[2]],this.max=[c[0],c[1],c[2]]}containsPoint(a){return a[0]>=this.min[0]&&a[0]<=this.max[0]&&a[1]>=this.min[1]&&a[1]<=this.max[1]&&a[2]>=this.min[2]&&a[2]<=this.max[2]}}class t{constructor(a,c){this.maxDepth=a,this.maxCentersPerNode=c,this.sceneDimensions=[],this.sceneMin=[],this.sceneMax=[],this.rootNode=null,this.addedIndexes={},this.nodesWithIndexes=[],this.splatMesh=null,this.disposed=!1}}class n{constructor(a,c,d,u){this.min=[a[0],a[1],a[2]],this.max=[c[0],c[1],c[2]],this.center=[(c[0]-a[0])*.5+a[0],(c[1]-a[1])*.5+a[1],(c[2]-a[2])*.5+a[2]],this.depth=d,this.children=[],this.data=null,this.id=u||e++}}processSplatTreeNode=function(o,a,c,d){let u=a.data.indexes.length;if(u<o.maxCentersPerNode||a.depth>o.maxDepth){let x=[];for(let T=0;T<a.data.indexes.length;T++)o.addedIndexes[a.data.indexes[T]]||(x.push(a.data.indexes[T]),o.addedIndexes[a.data.indexes[T]]=!0);a.data.indexes=x,a.data.indexes.sort((T,R)=>T>R?1:-1),o.nodesWithIndexes.push(a);return}let p=[a.max[0]-a.min[0],a.max[1]-a.min[1],a.max[2]-a.min[2]],h=[p[0]*.5,p[1]*.5,p[2]*.5],A=[a.min[0]+h[0],a.min[1]+h[1],a.min[2]+h[2]],m=[new s([A[0]-h[0],A[1],A[2]-h[2]],[A[0],A[1]+h[1],A[2]]),new s([A[0],A[1],A[2]-h[2]],[A[0]+h[0],A[1]+h[1],A[2]]),new s([A[0],A[1],A[2]],[A[0]+h[0],A[1]+h[1],A[2]+h[2]]),new s([A[0]-h[0],A[1],A[2]],[A[0],A[1]+h[1],A[2]+h[2]]),new s([A[0]-h[0],A[1]-h[1],A[2]-h[2]],[A[0],A[1],A[2]]),new s([A[0],A[1]-h[1],A[2]-h[2]],[A[0]+h[0],A[1],A[2]]),new s([A[0],A[1]-h[1],A[2]],[A[0]+h[0],A[1],A[2]+h[2]]),new s([A[0]-h[0],A[1]-h[1],A[2]],[A[0],A[1],A[2]+h[2]])],S=[],C=[];for(let x=0;x<m.length;x++)S[x]=0,C[x]=[];let E=[0,0,0];for(let x=0;x<u;x++){let T=a.data.indexes[x],R=c[T];E[0]=d[R],E[1]=d[R+1],E[2]=d[R+2];for(let y=0;y<m.length;y++)m[y].containsPoint(E)&&(S[y]++,C[y].push(T))}for(let x=0;x<m.length;x++){let T=new n(m[x].min,m[x].max,a.depth+1);T.data={indexes:C[x]},a.children.push(T)}a.data={};for(let x of a.children)processSplatTreeNode(o,x,c,d)};let r=(o,a,c)=>{let d=[0,0,0],u=[0,0,0],p=[],h=Math.floor(o.length/4);for(let m=0;m<h;m++){let S=m*4,C=o[S],E=o[S+1],x=o[S+2],T=Math.round(o[S+3]);(m===0||C<d[0])&&(d[0]=C),(m===0||C>u[0])&&(u[0]=C),(m===0||E<d[1])&&(d[1]=E),(m===0||E>u[1])&&(u[1]=E),(m===0||x<d[2])&&(d[2]=x),(m===0||x>u[2])&&(u[2]=x),p.push(T)}let A=new t(a,c);return A.sceneMin=d,A.sceneMax=u,A.rootNode=new n(A.sceneMin,A.sceneMax,0),A.rootNode.data={indexes:p},A};function i(o,a,c){let d=[];for(let p of o){let h=Math.floor(p.length/4);for(let A=0;A<h;A++){let m=A*4,S=Math.round(p[m+3]);d[S]=m}}let u=[];for(let p of o){let h=r(p,a,c);u.push(h),processSplatTreeNode(h,h.rootNode,d,p)}l.postMessage({subTrees:u})}l.onmessage=o=>{o.data.process&&i(o.data.process.centers,o.data.process.maxDepth,o.data.process.maxCentersPerNode)}}function Vr(l,e,s,t,n){l.postMessage({process:{centers:e,maxDepth:t,maxCentersPerNode:n}},s)}function Qr(){return new Worker(URL.createObjectURL(new Blob(["(",_r.toString(),")(self)"],{type:"application/javascript"})))}var ds=class{constructor(e,s){this.maxDepth=e,this.maxCentersPerNode=s,this.subTrees=[],this.splatMesh=null}dispose(){this.diposeSplatTreeWorker(),this.disposed=!0}diposeSplatTreeWorker(){this.splatTreeWorker&&this.splatTreeWorker.terminate(),this.splatTreeWorker=null}processSplatMesh=function(e,s=()=>!0,t,n){this.splatTreeWorker||(this.splatTreeWorker=Qr()),this.splatMesh=e,this.subTrees=[];let r=new f.Vector3,i=(o,a)=>{let c=new Float32Array(a*4),d=0;for(let u=0;u<a;u++){let p=u+o;if(s(p)){e.getSplatCenter(p,r);let h=d*4;c[h]=r.x,c[h+1]=r.y,c[h+2]=r.z,c[h+3]=p,d++}}return c};return new Promise(o=>{let a=()=>this.disposed?(this.diposeSplatTreeWorker(),o(),!0):!1;t&&t(!1),Re(()=>{if(a())return;let c=[];if(e.dynamicMode){let d=0;for(let u=0;u<e.scenes.length;u++){let h=e.getScene(u).splatBuffer.getSplatCount(),A=i(d,h);c.push(A),d+=h}}else{let d=i(0,e.getSplatCount());c.push(d)}this.splatTreeWorker.onmessage=d=>{a()||d.data.subTrees&&(n&&n(!1),Re(()=>{if(!a()){for(let u of d.data.subTrees){let p=cs.convertWorkerSubTree(u,e);this.subTrees.push(p)}this.diposeSplatTreeWorker(),n&&n(!0),Re(()=>{o()})}}))},Re(()=>{if(a())return;t&&t(!0);let d=c.map(u=>u.buffer);Vr(this.splatTreeWorker,c,d,this.maxDepth,this.maxCentersPerNode)})})})};countLeaves(){let e=0;return this.visitLeaves(()=>{e++}),e}visitLeaves(e){let s=(t,n)=>{t.children.length===0&&n(t);for(let r of t.children)s(r,n)};for(let t of this.subTrees)s(t.rootNode,e)}};function Nr(l){let e={};function s(t){if(e[t]!==void 0)return e[t];let n;switch(t){case"WEBGL_depth_texture":n=l.getExtension("WEBGL_depth_texture")||l.getExtension("MOZ_WEBGL_depth_texture")||l.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":n=l.getExtension("EXT_texture_filter_anisotropic")||l.getExtension("MOZ_EXT_texture_filter_anisotropic")||l.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":n=l.getExtension("WEBGL_compressed_texture_s3tc")||l.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||l.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":n=l.getExtension("WEBGL_compressed_texture_pvrtc")||l.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:n=l.getExtension(t)}return e[t]=n,n}return{has:function(t){return s(t)!==null},init:function(t){t.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(t){let n=s(t);return n===null&&console.warn("THREE.WebGLRenderer: "+t+" extension not supported."),n}}}function Gr(l,e,s){let t;function n(){if(t!==void 0)return t;if(e.has("EXT_texture_filter_anisotropic")===!0){let g=e.get("EXT_texture_filter_anisotropic");t=l.getParameter(g.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else t=0;return t}function r(g){if(g==="highp"){if(l.getShaderPrecisionFormat(l.VERTEX_SHADER,l.HIGH_FLOAT).precision>0&&l.getShaderPrecisionFormat(l.FRAGMENT_SHADER,l.HIGH_FLOAT).precision>0)return"highp";g="mediump"}return g==="mediump"&&l.getShaderPrecisionFormat(l.VERTEX_SHADER,l.MEDIUM_FLOAT).precision>0&&l.getShaderPrecisionFormat(l.FRAGMENT_SHADER,l.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let i=typeof WebGL2RenderingContext<"u"&&l.constructor.name==="WebGL2RenderingContext",o=s.precision!==void 0?s.precision:"highp",a=r(o);a!==o&&(console.warn("THREE.WebGLRenderer:",o,"not supported, using",a,"instead."),o=a);let c=i||e.has("WEBGL_draw_buffers"),d=s.logarithmicDepthBuffer===!0,u=l.getParameter(l.MAX_TEXTURE_IMAGE_UNITS),p=l.getParameter(l.MAX_VERTEX_TEXTURE_IMAGE_UNITS),h=l.getParameter(l.MAX_TEXTURE_SIZE),A=l.getParameter(l.MAX_CUBE_MAP_TEXTURE_SIZE),m=l.getParameter(l.MAX_VERTEX_ATTRIBS),S=l.getParameter(l.MAX_VERTEX_UNIFORM_VECTORS),C=l.getParameter(l.MAX_VARYING_VECTORS),E=l.getParameter(l.MAX_FRAGMENT_UNIFORM_VECTORS),x=p>0,T=i||e.has("OES_texture_float"),R=x&&T,y=i?l.getParameter(l.MAX_SAMPLES):0;return{isWebGL2:i,drawBuffers:c,getMaxAnisotropy:n,getMaxPrecision:r,precision:o,logarithmicDepthBuffer:d,maxTextures:u,maxVertexTextures:p,maxTextureSize:h,maxCubemapSize:A,maxAttributes:m,maxVertexUniforms:S,maxVaryings:C,maxFragmentUniforms:E,vertexTextures:x,floatFragmentTextures:T,floatVertexTextures:R,maxSamples:y}}var rt={Default:0,Gradual:1,Instant:2},Ze={None:0,Error:1,Warning:2,Info:3,Debug:4},tn=new f.BufferGeometry,Wr=new f.MeshBasicMaterial,St=6,qr=4,Kr=4,jr=4,Yr=6,Xr=8,zt=4,_t=4,sn=1,Jr=.012,Zr=.003,nn=1,rn=16777216,us=class l extends f.Mesh{constructor(e=De.ThreeD,s=!1,t=!1,n=!1,r=1,i=!0,o=!1,a=!1,c=1024,d=Ze.None,u=0,p=1,h=.3){super(tn,Wr),this.renderer=void 0,this.splatRenderMode=e,this.dynamicMode=s,this.enableOptionalEffects=t,this.halfPrecisionCovariancesOnGPU=n,this.devicePixelRatio=r,this.enableDistancesComputationOnGPU=i,this.integerBasedDistancesComputation=o,this.antialiased=a,this.kernel2DSize=h,this.maxScreenSpaceSplatSize=c,this.logLevel=d,this.sphericalHarmonicsDegree=u,this.minSphericalHarmonicsDegree=0,this.sceneFadeInRateMultiplier=p,this.scenes=[],this.splatTree=null,this.baseSplatTree=null,this.splatDataTextures={},this.distancesTransformFeedback={id:null,vertexShader:null,fragmentShader:null,program:null,centersBuffer:null,sceneIndexesBuffer:null,outDistancesBuffer:null,centersLoc:-1,modelViewProjLoc:-1,sceneIndexesLoc:-1,transformsLocs:[]},this.globalSplatIndexToLocalSplatIndexMap=[],this.globalSplatIndexToSceneIndexMap=[],this.lastBuildSplatCount=0,this.lastBuildScenes=[],this.lastBuildMaxSplatCount=0,this.lastBuildSceneCount=0,this.firstRenderTime=-1,this.finalBuild=!1,this.webGLUtils=null,this.boundingBox=new f.Box3,this.calculatedSceneCenter=new f.Vector3,this.maxSplatDistanceFromSceneCenter=0,this.visibleRegionBufferRadius=0,this.visibleRegionRadius=0,this.visibleRegionFadeStartRadius=0,this.visibleRegionChanging=!1,this.splatScale=1,this.pointCloudModeEnabled=!1,this.disposed=!1,this.lastRenderer=null,this.visible=!1}static buildScenes(e,s,t){let n=[];n.length=s.length;for(let r=0;r<s.length;r++){let i=s[r],o=t[r]||{},a=o.position||[0,0,0],c=o.rotation||[0,0,0,1],d=o.scale||[1,1,1],u=new f.Vector3().fromArray(a),p=new f.Quaternion().fromArray(c),h=new f.Vector3().fromArray(d),A=l.createScene(i,u,p,h,o.splatAlphaRemovalThreshold||1,o.opacity,o.visible);e.add(A),n[r]=A}return n}static createScene(e,s,t,n,r,i=1,o=!0){return new as(e,s,t,n,r,i,o)}static buildSplatIndexMaps(e){let s=[],t=[],n=0;for(let r=0;r<e.length;r++){let o=e[r].getMaxSplatCount();for(let a=0;a<o;a++)s[n]=a,t[n]=r,n++}return{localSplatIndexMap:s,sceneIndexMap:t}}buildSplatTree=function(e=[],s,t){return new Promise(n=>{this.disposeSplatTree(),this.baseSplatTree=new ds(8,1e3);let r=performance.now(),i=new f.Vector4;this.baseSplatTree.processSplatMesh(this,o=>{this.getSplatColor(o,i);let a=this.getSceneIndexForSplat(o),c=e[a]||1;return i.w>=c},s,t).then(()=>{let o=performance.now()-r;if(this.logLevel>=Ze.Info&&console.log("SplatTree build: "+o+" ms"),this.disposed)n();else{this.splatTree=this.baseSplatTree,this.baseSplatTree=null;let a=0,c=0,d=0,u=0;this.splatTree.visitLeaves(p=>{let h=p.data.indexes.length;h>0&&(c+=h,d=Math.max(d,h),u++,a++)}),this.logLevel>=Ze.Info&&(console.log(`SplatTree leaves: ${this.splatTree.countLeaves()}`),console.log(`SplatTree leaves with splats:${a}`),c=c/u,console.log(`Avg splat count per node: ${c}`),console.log(`Total splat count: ${this.getSplatCount()}`)),n()}})})};build(e,s,t=!0,n=!1,r,i,o=!0){this.sceneOptions=s,this.finalBuild=n;let a=l.getTotalMaxSplatCountForSplatBuffers(e),c=l.buildScenes(this,e,s);if(t)for(let m=0;m<this.scenes.length&&m<c.length;m++){let S=c[m],C=this.getScene(m);S.copyTransformData(C)}this.scenes=c;let d=3;for(let m of e){let S=m.getMinSphericalHarmonicsDegree();S<d&&(d=S)}this.minSphericalHarmonicsDegree=Math.min(d,this.sphericalHarmonicsDegree);let u=!1;if(e.length!==this.lastBuildScenes.length)u=!0;else for(let m=0;m<e.length;m++)if(e[m]!==this.lastBuildScenes[m].splatBuffer){u=!0;break}let p=!0;if((this.scenes.length!==1||this.lastBuildSceneCount!==this.scenes.length||this.lastBuildMaxSplatCount!==a||u)&&(p=!1),!p){this.boundingBox=new f.Box3,o||(this.maxSplatDistanceFromSceneCenter=0,this.visibleRegionBufferRadius=0,this.visibleRegionRadius=0,this.visibleRegionFadeStartRadius=0,this.firstRenderTime=-1),this.lastBuildScenes=[],this.lastBuildSplatCount=0,this.lastBuildMaxSplatCount=0,this.disposeMeshData(),this.geometry=is.build(a),this.splatRenderMode===De.ThreeD?this.material=rs.build(this.dynamicMode,this.enableOptionalEffects,this.antialiased,this.maxScreenSpaceSplatSize,this.splatScale,this.pointCloudModeEnabled,this.minSphericalHarmonicsDegree,this.kernel2DSize):this.material=os.build(this.dynamicMode,this.enableOptionalEffects,this.splatScale,this.pointCloudModeEnabled,this.minSphericalHarmonicsDegree);let m=l.buildSplatIndexMaps(e);this.globalSplatIndexToLocalSplatIndexMap=m.localSplatIndexMap,this.globalSplatIndexToSceneIndexMap=m.sceneIndexMap}let h=this.getSplatCount(!0);this.enableDistancesComputationOnGPU&&this.setupDistancesComputationTransformFeedback();let A=this.refreshGPUDataFromSplatBuffers(p);for(let m=0;m<this.scenes.length;m++)this.lastBuildScenes[m]=this.scenes[m];return this.lastBuildSplatCount=h,this.lastBuildMaxSplatCount=this.getMaxSplatCount(),this.lastBuildSceneCount=this.scenes.length,n&&this.scenes.length>0&&this.buildSplatTree(s.map(m=>m.splatAlphaRemovalThreshold||1),r,i).then(()=>{this.onSplatTreeReadyCallback&&this.onSplatTreeReadyCallback(this.splatTree),this.onSplatTreeReadyCallback=null}),this.visible=this.scenes.length>0,A}freeIntermediateSplatData(){let e=s=>{delete s.source.data,delete s.image,s.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.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(s=>{s.needsUpdate=!0,s.onUpdate=()=>{e(s)}})),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 f.Box3,this.calculatedSceneCenter=new f.Vector3,this.maxSplatDistanceFromSceneCenter=0,this.visibleRegionBufferRadius=0,this.visibleRegionRadius=0,this.visibleRegionFadeStartRadius=0,this.visibleRegionChanging=!1,this.splatScale=1,this.pointCloudModeEnabled=!1,this.disposed=!0,this.lastRenderer=null,this.visible=!1}disposeMeshData(){this.geometry&&this.geometry!==tn&&(this.geometry.dispose(),this.geometry=null),this.material&&(this.material.dispose(),this.material=null)}disposeTextures(){for(let e in this.splatDataTextures)if(this.splatDataTextures.hasOwnProperty(e)){let s=this.splatDataTextures[e];s.texture&&(s.texture.dispose(),s.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,s){let t=this.integerBasedDistancesComputation?this.getIntegerCenters(e,s,!0):this.getFloatCenters(e,s,!0),n=this.getSceneIndexes(e,s);return{centers:t,sceneIndexes:n}}refreshGPUDataFromSplatBuffers(e){let s=this.getSplatCount(!0);this.refreshDataTexturesFromSplatBuffers(e);let t=e?this.lastBuildSplatCount:0,{centers:n,sceneIndexes:r}=this.getDataForDistancesComputation(t,s-1);return this.enableDistancesComputationOnGPU&&this.refreshGPUBuffersForDistancesComputation(n,r,e),{from:t,to:s-1,count:s-t,centers:n,sceneIndexes:r}}refreshGPUBuffersForDistancesComputation(e,s,t=!1){let n=t?this.lastBuildSplatCount:0;this.updateGPUCentersBufferForDistancesComputation(t,e,n),this.updateGPUTransformIndexesBufferForDistancesComputation(t,s,n)}refreshDataTexturesFromSplatBuffers(e){let s=this.getSplatCount(!0),t=this.lastBuildSplatCount,n=s-1;e?this.updateBaseDataFromSplatBuffers(t,n):(this.setupDataTextures(),this.updateBaseDataFromSplatBuffers()),this.updateDataTexturesFromBaseData(t,n),this.updateVisibleRegion(e)}setupDataTextures(){let e=this.getMaxSplatCount(),s=this.getSplatCount(!0);this.disposeTextures();let t=(g,I)=>{let w=new f.Vector2(4096,1024);for(;w.x*w.y*g<e*I;)w.y*=2;return w},n=g=>g>=1?Yr:Kr,r=g=>{let I=n(g),w=t(I,6);return{elementsPerTexelStored:I,texSize:w}},i=this.getTargetCovarianceCompressionLevel(),o=0,a=this.getTargetSphericalHarmonicsCompressionLevel(),c,d,u;if(this.splatRenderMode===De.ThreeD){let g=r(i);g.texSize.x*g.texSize.y>rn&&i===0&&(i=1),c=new Float32Array(e*St)}else d=new Float32Array(e*3),u=new Float32Array(e*4);let p=new Float32Array(e*3),h=new Uint8Array(e*4),A=Float32Array;a===1?A=Uint16Array:a===2&&(A=Uint8Array);let m=Je(this.minSphericalHarmonicsDegree),S=this.minSphericalHarmonicsDegree?new A(e*m):void 0,C=t(_t,4),E=new Uint32Array(C.x*C.y*_t);l.updateCenterColorsPaddedData(0,s-1,p,h,E);let x=new f.DataTexture(E,C.x,C.y,f.RGBAIntegerFormat,f.UnsignedIntType);if(x.internalFormat="RGBA32UI",x.needsUpdate=!0,this.material.uniforms.centersColorsTexture.value=x,this.material.uniforms.centersColorsTextureSize.value.copy(C),this.material.uniformsNeedUpdate=!0,this.splatDataTextures={baseData:{covariances:c,scales:d,rotations:u,centers:p,colors:h,sphericalHarmonics:S},centerColors:{data:E,texture:x,size:C}},this.splatRenderMode===De.ThreeD){let g=r(i),I=g.elementsPerTexelStored,w=g.texSize,v=i>=1?Uint32Array:Float32Array,M=i>=1?Xr:jr,b=new v(w.x*w.y*M);i===0?b.set(c):l.updatePaddedCompressedCovariancesTextureData(c,b,0,0,c.length);let D;if(i>=1)D=new f.DataTexture(b,w.x,w.y,f.RGBAIntegerFormat,f.UnsignedIntType),D.internalFormat="RGBA32UI",this.material.uniforms.covariancesTextureHalfFloat.value=D;else{D=new f.DataTexture(b,w.x,w.y,f.RGBAFormat,f.FloatType),this.material.uniforms.covariancesTexture.value=D;let L=new f.DataTexture(new Uint32Array(32),2,2,f.RGBAIntegerFormat,f.UnsignedIntType);L.internalFormat="RGBA32UI",this.material.uniforms.covariancesTextureHalfFloat.value=L,L.needsUpdate=!0}D.needsUpdate=!0,this.material.uniforms.covariancesAreHalfFloat.value=i>=1?1:0,this.material.uniforms.covariancesTextureSize.value.copy(w),this.splatDataTextures.covariances={data:b,texture:D,size:w,compressionLevel:i,elementsPerTexelStored:I,elementsPerTexelAllocated:M}}else{let I=t(zt,6),w=o>=1?Uint16Array:Float32Array,v=o>=1?f.HalfFloatType:f.FloatType,M=new w(I.x*I.y*zt);l.updateScaleRotationsPaddedData(0,s-1,d,u,M);let b=new f.DataTexture(M,I.x,I.y,f.RGBAFormat,v);b.needsUpdate=!0,this.material.uniforms.scaleRotationsTexture.value=b,this.material.uniforms.scaleRotationsTextureSize.value.copy(I),this.splatDataTextures.scaleRotations={data:M,texture:b,size:I,compressionLevel:o}}if(S){let g=a===2?f.UnsignedByteType:f.HalfFloatType,I=m;I%2!==0&&I++;let w=4,v=w===4?f.RGBAFormat:f.RGFormat,M=t(w,I);if(M.x*M.y<=rn){let b=M.x*M.y*w,D=new A(b);for(let F=0;F<s;F++){let P=m*F,z=I*F;for(let O=0;O<m;O++)D[z+O]=S[P+O]}let L=new f.DataTexture(D,M.x,M.y,v,g);L.needsUpdate=!0,this.material.uniforms.sphericalHarmonicsTexture.value=L,this.splatDataTextures.sphericalHarmonics={componentCount:m,paddedComponentCount:I,data:D,textureCount:1,texture:L,size:M,compressionLevel:a,elementsPerTexel:w}}else{let b=m/3;I=b,I%2!==0&&I++,M=t(w,I);let D=M.x*M.y*w,L=[this.material.uniforms.sphericalHarmonicsTextureR,this.material.uniforms.sphericalHarmonicsTextureG,this.material.uniforms.sphericalHarmonicsTextureB],F=[],P=[];for(let z=0;z<3;z++){let O=new A(D);F.push(O);for(let V=0;V<s;V++){let q=m*V,oe=I*V;if(b>=3){for(let N=0;N<3;N++)O[oe+N]=S[q+z*3+N];if(b>=8)for(let N=0;N<5;N++)O[oe+3+N]=S[q+9+z*5+N]}}let k=new f.DataTexture(O,M.x,M.y,v,g);P.push(k),k.needsUpdate=!0,L[z].value=k}this.material.uniforms.sphericalHarmonicsMultiTextureMode.value=1,this.splatDataTextures.sphericalHarmonics={componentCount:m,componentCountPerChannel:b,paddedComponentCount:I,data:F,textureCount:3,textures:P,size:M,compressionLevel:a,elementsPerTexel:w}}this.material.uniforms.sphericalHarmonicsTextureSize.value.copy(M),this.material.uniforms.sphericalHarmonics8BitMode.value=a===2?1:0;for(let b=0;b<this.scenes.length;b++){let D=this.scenes[b].splatBuffer;this.material.uniforms.sphericalHarmonics8BitCompressionRangeMin.value[b]=D.minSphericalHarmonicsCoeff,this.material.uniforms.sphericalHarmonics8BitCompressionRangeMax.value[b]=D.maxSphericalHarmonicsCoeff}this.material.uniformsNeedUpdate=!0}let T=t(sn,4),R=new Uint32Array(T.x*T.y*sn);for(let g=0;g<s;g++)R[g]=this.globalSplatIndexToSceneIndexMap[g];let y=new f.DataTexture(R,T.x,T.y,f.RedIntegerFormat,f.UnsignedIntType);y.internalFormat="R32UI",y.needsUpdate=!0,this.material.uniforms.sceneIndexesTexture.value=y,this.material.uniforms.sceneIndexesTextureSize.value.copy(T),this.material.uniformsNeedUpdate=!0,this.splatDataTextures.sceneIndexes={data:R,texture:y,size:T},this.material.uniforms.sceneCount.value=this.scenes.length}updateBaseDataFromSplatBuffers(e,s){let t=this.splatDataTextures.covariances,n=t?t.compressionLevel:void 0,r=this.splatDataTextures.scaleRotations,i=r?r.compressionLevel:void 0,o=this.splatDataTextures.sphericalHarmonics,a=o?o.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,void 0,n,i,a,e,s,e)}updateDataTexturesFromBaseData(e,s){let t=this.splatDataTextures.covariances,n=t?t.compressionLevel:void 0,r=this.splatDataTextures.scaleRotations,i=r?r.compressionLevel:void 0,o=this.splatDataTextures.sphericalHarmonics,a=o?o.compressionLevel:0,c=this.splatDataTextures.centerColors,d=c.data,u=c.texture;l.updateCenterColorsPaddedData(e,s,this.splatDataTextures.baseData.centers,this.splatDataTextures.baseData.colors,d);let p=this.renderer?this.renderer.properties.get(u):null;if(!p||!p.__webglTexture?u.needsUpdate=!0:this.updateDataTexture(d,c.texture,c.size,p,_t,qr,4,e,s),t){let E=t.texture,x=e*St,T=s*St;if(n===0)for(let y=x;y<=T;y++){let g=this.splatDataTextures.baseData.covariances[y];t.data[y]=g}else l.updatePaddedCompressedCovariancesTextureData(this.splatDataTextures.baseData.covariances,t.data,e*t.elementsPerTexelAllocated,x,T);let R=this.renderer?this.renderer.properties.get(E):null;!R||!R.__webglTexture?E.needsUpdate=!0:n===0?this.updateDataTexture(t.data,t.texture,t.size,R,t.elementsPerTexelStored,St,4,e,s):this.updateDataTexture(t.data,t.texture,t.size,R,t.elementsPerTexelAllocated,t.elementsPerTexelAllocated,2,e,s)}if(r){let E=r.data,x=r.texture,T=6,R=i===0?4:2;l.updateScaleRotationsPaddedData(e,s,this.splatDataTextures.baseData.scales,this.splatDataTextures.baseData.rotations,E);let y=this.renderer?this.renderer.properties.get(x):null;!y||!y.__webglTexture?x.needsUpdate=!0:this.updateDataTexture(E,r.texture,r.size,y,zt,T,R,e,s)}let h=this.splatDataTextures.baseData.sphericalHarmonics;if(h){let E=4;a===1?E=2:a===2&&(E=1);let x=(y,g,I,w,v)=>{let M=this.renderer?this.renderer.properties.get(y):null;!M||!M.__webglTexture?y.needsUpdate=!0:this.updateDataTexture(w,y,g,M,I,v,E,e,s)},T=o.componentCount,R=o.paddedComponentCount;if(o.textureCount===1){let y=o.data;for(let g=e;g<=s;g++){let I=T*g,w=R*g;for(let v=0;v<T;v++)y[w+v]=h[I+v]}x(o.texture,o.size,o.elementsPerTexel,y,R)}else{let y=o.componentCountPerChannel;for(let g=0;g<3;g++){let I=o.data[g];for(let w=e;w<=s;w++){let v=T*w,M=R*w;if(y>=3){for(let b=0;b<3;b++)I[M+b]=h[v+g*3+b];if(y>=8)for(let b=0;b<5;b++)I[M+3+b]=h[v+9+g*5+b]}}x(o.textures[g],o.size,o.elementsPerTexel,I,R)}}}let A=this.splatDataTextures.sceneIndexes,m=A.data;for(let E=this.lastBuildSplatCount;E<=s;E++)m[E]=this.globalSplatIndexToSceneIndexMap[E];let S=A.texture,C=this.renderer?this.renderer.properties.get(S):null;!C||!C.__webglTexture?S.needsUpdate=!0:this.updateDataTexture(m,A.texture,A.size,C,1,1,1,this.lastBuildSplatCount,s)}getTargetCovarianceCompressionLevel(){return this.halfPrecisionCovariancesOnGPU?1:0}getTargetSphericalHarmonicsCompressionLevel(){return Math.max(1,this.getMaximumSplatBufferCompressionLevel())}getMaximumSplatBufferCompressionLevel(){let e;for(let s=0;s<this.scenes.length;s++){let n=this.getScene(s).splatBuffer;(s===0||n.compressionLevel>e)&&(e=n.compressionLevel)}return e}getMinimumSplatBufferCompressionLevel(){let e;for(let s=0;s<this.scenes.length;s++){let n=this.getScene(s).splatBuffer;(s===0||n.compressionLevel<e)&&(e=n.compressionLevel)}return e}static computeTextureUpdateRegion(e,s,t,n,r){let i=r/n,o=e*i,a=Math.floor(o/t),c=a*t*n,d=s*i,u=Math.floor(d/t),p=u*t*n+t*n;return{dataStart:c,dataEnd:p,startRow:a,endRow:u}}updateDataTexture(e,s,t,n,r,i,o,a,c){let d=this.renderer.getContext(),u=l.computeTextureUpdateRegion(a,c,t.x,r,i),p=u.dataEnd-u.dataStart,h=new e.constructor(e.buffer,u.dataStart*o,p),A=u.endRow-u.startRow+1,m=this.webGLUtils.convert(s.type),S=this.webGLUtils.convert(s.format,s.colorSpace),C=d.getParameter(d.TEXTURE_BINDING_2D);d.bindTexture(d.TEXTURE_2D,n.__webglTexture),d.texSubImage2D(d.TEXTURE_2D,0,0,u.startRow,t.x,A,S,m,h),d.bindTexture(d.TEXTURE_2D,C)}static updatePaddedCompressedCovariancesTextureData(e,s,t,n,r){let i=new DataView(s.buffer),o=t,a=0;for(let c=n;c<=r;c+=2)i.setUint16(o*2,e[c],!0),i.setUint16(o*2+2,e[c+1],!0),o+=2,a++,a>=3&&(o+=2,a=0)}static updateCenterColorsPaddedData(e,s,t,n,r){for(let i=e;i<=s;i++){let o=i*4,a=i*3,c=i*4;r[c]=On(n,o),r[c+1]=Pt(t[a]),r[c+2]=Pt(t[a+1]),r[c+3]=Pt(t[a+2])}}static updateScaleRotationsPaddedData(e,s,t,n,r){for(let o=e;o<=s;o++){let a=o*3,c=o*4,d=o*6;r[d]=t[a],r[d+1]=t[a+1],r[d+2]=t[a+2],r[d+3]=n[c],r[d+4]=n[c+1],r[d+5]=n[c+2]}}updateVisibleRegion(e){let s=this.getSplatCount(!0),t=new f.Vector3;if(!e){let r=new f.Vector3;this.scenes.forEach(i=>{r.add(i.splatBuffer.sceneCenter)}),r.multiplyScalar(1/this.scenes.length),this.calculatedSceneCenter.copy(r),this.material.uniforms.sceneCenter.value.copy(this.calculatedSceneCenter),this.material.uniformsNeedUpdate=!0}let n=e?this.lastBuildSplatCount:0;for(let r=n;r<s;r++){this.getSplatCenter(r,t,!0);let i=t.sub(this.calculatedSceneCenter).length();i>this.maxSplatDistanceFromSceneCenter&&(this.maxSplatDistanceFromSceneCenter=i)}this.maxSplatDistanceFromSceneCenter-this.visibleRegionBufferRadius>nn&&(this.visibleRegionBufferRadius=this.maxSplatDistanceFromSceneCenter,this.visibleRegionRadius=Math.max(this.visibleRegionBufferRadius-nn,0)),this.finalBuild&&(this.visibleRegionRadius=this.visibleRegionBufferRadius=this.maxSplatDistanceFromSceneCenter),this.updateVisibleRegionFadeDistance()}updateVisibleRegionFadeDistance(e=rt.Default){let s=Jr*this.sceneFadeInRateMultiplier,t=Zr*this.sceneFadeInRateMultiplier,n=this.finalBuild?s:t,r=e===rt.Default?n:t;this.visibleRegionFadeStartRadius=(this.visibleRegionRadius-this.visibleRegionFadeStartRadius)*r+this.visibleRegionFadeStartRadius;let o=(this.visibleRegionBufferRadius>0?this.visibleRegionFadeStartRadius/this.visibleRegionBufferRadius:0)>.99,a=o||e===rt.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=!o}updateRenderIndexes(e,s){let t=this.geometry;t.attributes.splatIndex.set(e),t.attributes.splatIndex.needsUpdate=!0,s>0&&this.firstRenderTime===-1&&(this.firstRenderTime=performance.now()),t.instanceCount=s,t.setDrawRange(0,s)}updateTransforms(){for(let e=0;e<this.scenes.length;e++)this.getScene(e).updateTransform(this.dynamicMode)}updateUniforms=function(){let e=new f.Vector2;return function(s,t,n,r,i,o){if(this.getSplatCount()>0){if(e.set(s.x*this.devicePixelRatio,s.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(t,n),this.material.uniforms.orthographicMode.value=r?1:0,this.material.uniforms.orthoZoom.value=i,this.material.uniforms.inverseFocalAdjustment.value=o,this.dynamicMode)for(let c=0;c<this.scenes.length;c++)this.material.uniforms.transforms.value[c].copy(this.getScene(c).transform);if(this.enableOptionalEffects)for(let c=0;c<this.scenes.length;c++)this.material.uniforms.sceneOpacity.value[c]=se(this.getScene(c).opacity,0,1),this.material.uniforms.sceneVisibility.value[c]=this.getScene(c).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?l.getTotalSplatCountForScenes(this.scenes):this.lastBuildSplatCount}static getTotalSplatCountForScenes(e){let s=0;for(let t of e)t&&t.splatBuffer&&(s+=t.splatBuffer.getSplatCount());return s}static getTotalSplatCountForSplatBuffers(e){let s=0;for(let t of e)s+=t.getSplatCount();return s}getMaxSplatCount(){return l.getTotalMaxSplatCountForScenes(this.scenes)}static getTotalMaxSplatCountForScenes(e){let s=0;for(let t of e)t&&t.splatBuffer&&(s+=t.splatBuffer.getMaxSplatCount());return s}static getTotalMaxSplatCountForSplatBuffers(e){let s=0;for(let t of e)s+=t.getMaxSplatCount();return s}disposeDistancesComputationGPUResources(){if(!this.renderer)return;let 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;let 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;let s=this.renderer.getContext(),t=new Nr(s),n=new Gr(s,t,{});if(t.init(n),this.webGLUtils=new f.WebGLUtils(s,t,n),this.enableDistancesComputationOnGPU&&this.getSplatCount()>0){this.setupDistancesComputationTransformFeedback();let{centers:r,sceneIndexes:i}=this.getDataForDistancesComputation(0,this.getSplatCount()-1);this.refreshGPUBuffersForDistancesComputation(r,i)}}}setupDistancesComputationTransformFeedback=function(){let e;return function(){let s=this.getMaxSplatCount();if(!this.renderer)return;let t=this.lastRenderer!==this.renderer,n=e!==s;if(!t&&!n)return;t?this.disposeDistancesComputationGPUResources():n&&this.disposeDistancesComputationGPUBufferResources();let r=this.renderer.getContext(),i=(p,h,A)=>{let m=p.createShader(h);if(!m)return console.error("Fatal error: gl could not create a shader object."),null;if(p.shaderSource(m,A),p.compileShader(m),!p.getShaderParameter(m,p.COMPILE_STATUS)){let C="unknown";h===p.VERTEX_SHADER?C="vertex shader":h===p.FRAGMENT_SHADER&&(C="fragement shader");let E=p.getShaderInfoLog(m);return console.error("Failed to compile "+C+" with these errors:"+E),p.deleteShader(m),null}return m},o;this.integerBasedDistancesComputation?(o=`#version 300 es
874
+ in ivec4 center;
875
+ flat out int distance;`,this.dynamicMode?o+=`
876
+ in uint sceneIndex;
877
+ uniform ivec4 transforms[${j.MaxScenes}];
878
+ void main(void) {
879
+ ivec4 transform = transforms[sceneIndex];
880
+ distance = center.x * transform.x + center.y * transform.y + center.z * transform.z + transform.w * center.w;
881
+ }
882
+ `:o+=`
883
+ uniform ivec3 modelViewProj;
884
+ void main(void) {
885
+ distance = center.x * modelViewProj.x + center.y * modelViewProj.y + center.z * modelViewProj.z;
886
+ }
887
+ `):(o=`#version 300 es
888
+ in vec4 center;
889
+ flat out float distance;`,this.dynamicMode?o+=`
890
+ in uint sceneIndex;
891
+ uniform mat4 transforms[${j.MaxScenes}];
892
+ void main(void) {
893
+ vec4 transformedCenter = transforms[sceneIndex] * vec4(center.xyz, 1.0);
894
+ distance = transformedCenter.z;
895
+ }
896
+ `:o+=`
897
+ uniform vec3 modelViewProj;
898
+ void main(void) {
899
+ distance = center.x * modelViewProj.x + center.y * modelViewProj.y + center.z * modelViewProj.z;
900
+ }
901
+ `);let a=`#version 300 es
902
+ precision lowp float;
903
+ out vec4 fragColor;
904
+ void main(){}
905
+ `,c=r.getParameter(r.VERTEX_ARRAY_BINDING),d=r.getParameter(r.CURRENT_PROGRAM),u=d?r.getProgramParameter(d,r.DELETE_STATUS):!1;if(t&&(this.distancesTransformFeedback.vao=r.createVertexArray()),r.bindVertexArray(this.distancesTransformFeedback.vao),t){let p=r.createProgram(),h=i(r,r.VERTEX_SHADER,o),A=i(r,r.FRAGMENT_SHADER,a);if(!h||!A)throw new Error("Could not compile shaders for distances computation on GPU.");if(r.attachShader(p,h),r.attachShader(p,A),r.transformFeedbackVaryings(p,["distance"],r.SEPARATE_ATTRIBS),r.linkProgram(p),!r.getProgramParameter(p,r.LINK_STATUS)){let S=r.getProgramInfoLog(p);throw console.error("Fatal error: Failed to link program: "+S),r.deleteProgram(p),r.deleteShader(A),r.deleteShader(h),new Error("Could not link shaders for distances computation on GPU.")}this.distancesTransformFeedback.program=p,this.distancesTransformFeedback.vertexShader=h,this.distancesTransformFeedback.vertexShader=A}if(r.useProgram(this.distancesTransformFeedback.program),this.distancesTransformFeedback.centersLoc=r.getAttribLocation(this.distancesTransformFeedback.program,"center"),this.dynamicMode){this.distancesTransformFeedback.sceneIndexesLoc=r.getAttribLocation(this.distancesTransformFeedback.program,"sceneIndex");for(let p=0;p<this.scenes.length;p++)this.distancesTransformFeedback.transformsLocs[p]=r.getUniformLocation(this.distancesTransformFeedback.program,`transforms[${p}]`)}else this.distancesTransformFeedback.modelViewProjLoc=r.getUniformLocation(this.distancesTransformFeedback.program,"modelViewProj");(t||n)&&(this.distancesTransformFeedback.centersBuffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,this.distancesTransformFeedback.centersBuffer),r.enableVertexAttribArray(this.distancesTransformFeedback.centersLoc),this.integerBasedDistancesComputation?r.vertexAttribIPointer(this.distancesTransformFeedback.centersLoc,4,r.INT,0,0):r.vertexAttribPointer(this.distancesTransformFeedback.centersLoc,4,r.FLOAT,!1,0,0),this.dynamicMode&&(this.distancesTransformFeedback.sceneIndexesBuffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,this.distancesTransformFeedback.sceneIndexesBuffer),r.enableVertexAttribArray(this.distancesTransformFeedback.sceneIndexesLoc),r.vertexAttribIPointer(this.distancesTransformFeedback.sceneIndexesLoc,1,r.UNSIGNED_INT,0,0))),(t||n)&&(this.distancesTransformFeedback.outDistancesBuffer=r.createBuffer()),r.bindBuffer(r.ARRAY_BUFFER,this.distancesTransformFeedback.outDistancesBuffer),r.bufferData(r.ARRAY_BUFFER,s*4,r.STATIC_READ),t&&(this.distancesTransformFeedback.id=r.createTransformFeedback()),r.bindTransformFeedback(r.TRANSFORM_FEEDBACK,this.distancesTransformFeedback.id),r.bindBufferBase(r.TRANSFORM_FEEDBACK_BUFFER,0,this.distancesTransformFeedback.outDistancesBuffer),d&&u!==!0&&r.useProgram(d),c&&r.bindVertexArray(c),this.lastRenderer=this.renderer,e=s}}();updateGPUCentersBufferForDistancesComputation(e,s,t){if(!this.renderer)return;let n=this.renderer.getContext(),r=n.getParameter(n.VERTEX_ARRAY_BINDING);n.bindVertexArray(this.distancesTransformFeedback.vao);let i=this.integerBasedDistancesComputation?Uint32Array:Float32Array,o=16,a=t*o;if(n.bindBuffer(n.ARRAY_BUFFER,this.distancesTransformFeedback.centersBuffer),e)n.bufferSubData(n.ARRAY_BUFFER,a,s);else{let c=new i(this.getMaxSplatCount()*o);c.set(s),n.bufferData(n.ARRAY_BUFFER,c,n.STATIC_DRAW)}n.bindBuffer(n.ARRAY_BUFFER,null),r&&n.bindVertexArray(r)}updateGPUTransformIndexesBufferForDistancesComputation(e,s,t){if(!this.renderer||!this.dynamicMode)return;let n=this.renderer.getContext(),r=n.getParameter(n.VERTEX_ARRAY_BINDING);n.bindVertexArray(this.distancesTransformFeedback.vao);let i=t*4;if(n.bindBuffer(n.ARRAY_BUFFER,this.distancesTransformFeedback.sceneIndexesBuffer),e)n.bufferSubData(n.ARRAY_BUFFER,i,s);else{let o=new Uint32Array(this.getMaxSplatCount()*4);o.set(s),n.bufferData(n.ARRAY_BUFFER,o,n.STATIC_DRAW)}n.bindBuffer(n.ARRAY_BUFFER,null),r&&n.bindVertexArray(r)}getSceneIndexes(e,s){let t,n=s-e+1;t=new Uint32Array(n);for(let r=e;r<=s;r++)t[r]=this.globalSplatIndexToSceneIndexMap[r];return t}fillTransformsArray=function(){let e=[];return function(s){e.length!==s.length&&(e.length=s.length);for(let t=0;t<this.scenes.length;t++){let r=this.getScene(t).transform.elements;for(let i=0;i<16;i++)e[t*16+i]=r[i]}s.set(e)}}();computeDistancesOnGPU=function(){let e=new f.Matrix4;return function(s,t){if(!this.renderer)return;let n=this.renderer.getContext(),r=n.getParameter(n.VERTEX_ARRAY_BINDING),i=n.getParameter(n.CURRENT_PROGRAM),o=i?n.getProgramParameter(i,n.DELETE_STATUS):!1;if(n.bindVertexArray(this.distancesTransformFeedback.vao),n.useProgram(this.distancesTransformFeedback.program),n.enable(n.RASTERIZER_DISCARD),this.dynamicMode)for(let d=0;d<this.scenes.length;d++)if(e.copy(this.getScene(d).transform),e.premultiply(s),this.integerBasedDistancesComputation){let u=l.getIntegerMatrixArray(e),p=[u[2],u[6],u[10],u[14]];n.uniform4i(this.distancesTransformFeedback.transformsLocs[d],p[0],p[1],p[2],p[3])}else n.uniformMatrix4fv(this.distancesTransformFeedback.transformsLocs[d],!1,e.elements);else if(this.integerBasedDistancesComputation){let d=l.getIntegerMatrixArray(s),u=[d[2],d[6],d[10]];n.uniform3i(this.distancesTransformFeedback.modelViewProjLoc,u[0],u[1],u[2])}else{let d=[s.elements[2],s.elements[6],s.elements[10]];n.uniform3f(this.distancesTransformFeedback.modelViewProjLoc,d[0],d[1],d[2])}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&&(n.bindBuffer(n.ARRAY_BUFFER,this.distancesTransformFeedback.sceneIndexesBuffer),n.enableVertexAttribArray(this.distancesTransformFeedback.sceneIndexesLoc),n.vertexAttribIPointer(this.distancesTransformFeedback.sceneIndexesLoc,1,n.UNSIGNED_INT,0,0)),n.bindTransformFeedback(n.TRANSFORM_FEEDBACK,this.distancesTransformFeedback.id),n.bindBufferBase(n.TRANSFORM_FEEDBACK_BUFFER,0,this.distancesTransformFeedback.outDistancesBuffer),n.beginTransformFeedback(n.POINTS),n.drawArrays(n.POINTS,0,this.getSplatCount()),n.endTransformFeedback(),n.bindBufferBase(n.TRANSFORM_FEEDBACK_BUFFER,0,null),n.bindTransformFeedback(n.TRANSFORM_FEEDBACK,null),n.disable(n.RASTERIZER_DISCARD);let a=n.fenceSync(n.SYNC_GPU_COMMANDS_COMPLETE,0);n.flush();let c=new Promise(d=>{let u=()=>{if(this.disposed)d();else switch(n.clientWaitSync(a,0,0)){case n.TIMEOUT_EXPIRED:return this.computeDistancesOnGPUSyncTimeout=setTimeout(u),this.computeDistancesOnGPUSyncTimeout;case n.WAIT_FAILED:throw new Error("should never get here");default:this.computeDistancesOnGPUSyncTimeout=null,n.deleteSync(a);let m=n.getParameter(n.VERTEX_ARRAY_BINDING);n.bindVertexArray(this.distancesTransformFeedback.vao),n.bindBuffer(n.ARRAY_BUFFER,this.distancesTransformFeedback.outDistancesBuffer),n.getBufferSubData(n.ARRAY_BUFFER,0,t),n.bindBuffer(n.ARRAY_BUFFER,null),m&&n.bindVertexArray(m),d()}};this.computeDistancesOnGPUSyncTimeout=setTimeout(u)});return i&&o!==!0&&n.useProgram(i),r&&n.bindVertexArray(r),c}}();getLocalSplatParameters(e,s,t){t==null&&(t=!this.dynamicMode),s.splatBuffer=this.getSplatBufferForSplat(e),s.localIndex=this.getSplatLocalIndex(e),s.sceneTransform=t?this.getSceneTransformForSplat(e):null}fillSplatDataArrays(e,s,t,n,r,i,o,a=0,c=0,d=1,u,p,h=0,A){let m=new f.Vector3;m.x=void 0,m.y=void 0,this.splatRenderMode===De.ThreeD?m.z=void 0:m.z=1;let S=new f.Matrix4,C=0,E=this.scenes.length-1;A!=null&&A>=0&&A<=this.scenes.length&&(C=A,E=A);for(let x=C;x<=E;x++){o==null&&(o=!this.dynamicMode);let T=this.getScene(x),R=T.splatBuffer,y;if(o&&(this.getSceneTransform(x,S),y=S),e&&R.fillSplatCovarianceArray(e,y,u,p,h,a),s||t){if(!s||!t)throw new Error('SplatMesh::fillSplatDataArrays() -> "scales" and "rotations" must both be valid.');R.fillSplatScaleRotationArray(s,t,y,u,p,h,c,m)}n&&R.fillSplatCenterArray(n,y,u,p,h),r&&R.fillSplatColorArray(r,T.minimumAlpha,u,p,h),i&&R.fillSphericalHarmonicsArray(i,this.minSphericalHarmonicsDegree,y,u,p,h,d),h+=R.getSplatCount()}}getIntegerCenters(e,s,t=!1){let n=s-e+1,r=new Float32Array(n*3);this.fillSplatDataArrays(null,null,null,r,null,null,void 0,void 0,void 0,void 0,e);let i,o=t?4:3;i=new Int32Array(n*o);for(let a=0;a<n;a++){for(let c=0;c<3;c++)i[a*o+c]=Math.round(r[a*3+c]*1e3);t&&(i[a*o+3]=1e3)}return i}getFloatCenters(e,s,t=!1){let n=s-e+1,r=new Float32Array(n*3);if(this.fillSplatDataArrays(null,null,null,r,null,null,void 0,void 0,void 0,void 0,e),!t)return r;let i=new Float32Array(n*4);for(let o=0;o<n;o++){for(let a=0;a<3;a++)i[o*4+a]=r[o*3+a];i[o*4+3]=1}return i}getSplatCenter=function(){let e={};return function(s,t,n){this.getLocalSplatParameters(s,e,n),e.splatBuffer.getSplatCenter(e.localIndex,t,e.sceneTransform)}}();getSplatScaleAndRotation=function(){let e={},s=new f.Vector3;return function(t,n,r,i){this.getLocalSplatParameters(t,e,i),s.x=void 0,s.y=void 0,s.z=void 0,this.splatRenderMode===De.TwoD&&(s.z=0),e.splatBuffer.getSplatScaleAndRotation(e.localIndex,n,r,e.sceneTransform,s)}}();getSplatColor=function(){let e={};return function(s,t){this.getLocalSplatParameters(s,e),e.splatBuffer.getSplatColor(e.localIndex,t)}}();getSceneTransform(e,s){let t=this.getScene(e);t.updateTransform(this.dynamicMode),s.copy(t.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){let s=e.elements,t=[];for(let n=0;n<16;n++)t[n]=Math.round(s[n]*1e3);return t}computeBoundingBox(e=!1,s){let t=this.getSplatCount();if(s!=null){if(s<0||s>=this.scenes.length)throw new Error("SplatMesh::computeBoundingBox() -> Invalid scene index.");t=this.scenes[s].splatBuffer.getSplatCount()}let n=new Float32Array(t*3);this.fillSplatDataArrays(null,null,null,n,null,null,e,void 0,void 0,void 0,void 0,s);let r=new f.Vector3,i=new f.Vector3;for(let o=0;o<t;o++){let a=o*3,c=n[a],d=n[a+1],u=n[a+2];(o===0||c<r.x)&&(r.x=c),(o===0||d<r.y)&&(r.y=d),(o===0||u<r.z)&&(r.z=u),(o===0||c>i.x)&&(i.x=c),(o===0||d>i.y)&&(i.y=d),(o===0||u>i.z)&&(i.z=u)}return new f.Box3(r,i)}},$r="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",on="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",eo="AGFzbQEAAAAADwhkeWxpbmsuMAEEAAAAAAEXAmAAAGAQf39/f39/f39/f39/f39/fwACDwEDZW52Bm1lbW9yeQIAAAMDAgABBz4DEV9fd2FzbV9jYWxsX2N0b3JzAAAYX193YXNtX2FwcGx5X2RhdGFfcmVsb2NzAAALc29ydEluZGV4ZXMAAQrrDwICAAvlDwQBfAN7B30DfyALIAprIQwCQAJAIA4EQCANBEBB+P///wchCkGIgICAeCENIAsgDE0NAyAMIQUDQCADIAVBAnQiAWogAiAAIAFqKAIAQQJ0aigCACIBNgIAIAEgCiABIApIGyEKIAEgDSABIA1KGyENIAVBAWoiBSALRw0ACwwDCyAPBEAgCyAMTQ0CQX8hD0H4////ByEKQYiAgIB4IQ0gDCECA0AgDyAHIAAgAkECdCIcaigCACIdQQJ0aigCACIbRwRAAn8gBf0JAjggCCAbQQZ0aiIO/QkCDCAOKgIc/SABIA4qAiz9IAIgDioCPP0gA/3mASAF/QkCKCAO/QkCCCAOKgIY/SABIA4qAij9IAIgDioCOP0gA/3mASAF/QkCCCAO/QkCACAOKgIQ/SABIA4qAiD9IAIgDioCMP0gA/3mASAF/QkCGCAO/QkCBCAOKgIU/SABIA4qAiT9IAIgDioCNP0gA/3mAf3kAf3kAf3kASIR/V/9DAAAAAAAQI9AAAAAAABAj0AiEv3yASIT/SEBIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyEOAn8gE/0hACIQmUQAAAAAAADgQWMEQCAQqgwBC0GAgICAeAv9ESAO/RwBAn8gESAR/Q0ICQoLDA0ODwABAgMAAQID/V8gEv3yASIR/SEAIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4C/0cAgJ/IBH9IQEiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgL/RwDIRIgGyEPCyADIBxqIAEgHUEEdGr9AAAAIBL9tQEiEf0bACAR/RsBaiAR/RsCaiAR/RsDaiIONgIAIA4gCiAKIA5KGyEKIA4gDSANIA5IGyENIAJBAWoiAiALRw0ACwwDCwJ/IAUqAgi7/RQgBSoCGLv9IgH9DAAAAAAAQI9AAAAAAABAj0D98gEiEf0hASIQmUQAAAAAAADgQWMEQCAQqgwBC0GAgICAeAshDgJ/IBH9IQAiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLAn8gBSoCKLtEAAAAAABAj0CiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyEFQfj///8HIQpBiICAgHghDSALIAxNDQL9ESAO/RwBIAX9HAIhEiAMIQUDQCADIAVBAnQiAmogASAAIAJqKAIAQQR0av0AAAAgEv21ASIR/RsAIBH9GwFqIBH9GwJqIgI2AgAgAiAKIAIgCkgbIQogAiANIAIgDUobIQ0gBUEBaiIFIAtHDQALDAILIA0EQEH4////ByEKQYiAgIB4IQ0gCyAMTQ0CIAwhBQNAIAMgBUECdCIBagJ/IAIgACABaigCAEECdGoqAgC7RAAAAAAAALBAoiIQmUQAAAAAAADgQWMEQCAQqgwBC0GAgICAeAsiDjYCACAKIA4gCiAOSBshCiANIA4gDSAOShshDSAFQQFqIgUgC0cNAAsMAgsgD0UEQCALIAxNDQEgBSoCKCEUIAUqAhghFSAFKgIIIRZB+P///wchCkGIgICAeCENIAwhBQNAAn8gFCABIAAgBUECdCIHaigCAEEEdGoiAioCCJQgFiACKgIAlCAVIAIqAgSUkpK7RAAAAAAAALBAoiIQmUQAAAAAAADgQWMEQCAQqgwBC0GAgICAeAshDiADIAdqIA42AgAgCiAOIAogDkgbIQogDSAOIA0gDkobIQ0gBUEBaiIFIAtHDQALDAILIAsgDE0NAEF/IQ9B+P///wchCkGIgICAeCENIAwhAgNAIA8gByAAIAJBAnQiG2ooAgBBAnQiHGooAgAiDkcEQCAFKgI4IhQgCCAOQQZ0aiIPKgI8lCAFKgIoIhUgDyoCOJQgBSoCCCIWIA8qAjCUIAUqAhgiFyAPKgI0lJKSkiEYIBQgDyoCLJQgFSAPKgIolCAWIA8qAiCUIBcgDyoCJJSSkpIhGSAUIA8qAhyUIBUgDyoCGJQgFiAPKgIQlCAXIA8qAhSUkpKSIRogFCAPKgIMlCAVIA8qAgiUIBYgDyoCAJQgFyAPKgIElJKSkiEUIA4hDwsgAyAbagJ/IBggASAcQQJ0aiIOKgIMlCAZIA4qAgiUIBQgDioCAJQgGiAOKgIElJKSkrtEAAAAAAAAsECiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyIONgIAIAogDiAKIA5IGyEKIA0gDiANIA5KGyENIAJBAWoiAiALRw0ACwwBC0GIgICAeCENQfj///8HIQoLIAsgDEsEQCAJQQFrsyANsiAKspOVIRQgDCENA0ACfyAUIAMgDUECdGoiASgCACAKa7KUIhWLQwAAAE9dBEAgFagMAQtBgICAgHgLIQ4gASAONgIAIAQgDkECdGoiASABKAIAQQFqNgIAIA1BAWoiDSALRw0ACwsgCUECTwRAIAQoAgAhDUEBIQoDQCAEIApBAnRqIgEgASgCACANaiINNgIAIApBAWoiCiAJRw0ACwsgDEEASgRAIAwhCgNAIAYgCkEBayIBQQJ0IgJqIAAgAmooAgA2AgAgCkEBSyABIQoNAAsLIAsgDEoEQCALIQoDQCAGIAsgBCADIApBAWsiCkECdCIBaigCAEECdGoiAigCACIFa0ECdGogACABaigCADYCACACIAVBAWs2AgAgCiAMSg0ACwsL",to="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";function so(l){let e,s,t,n,r,i,o,a,c,d,u,p,h,A,m,S,C,E,x,T;function R(y,g,I,w,v,M,b){let D=performance.now();if(!t&&(new Uint32Array(s,o,v.byteLength/T.BytesPerInt).set(v),new Float32Array(s,d,b.byteLength/T.BytesPerFloat).set(b),w)){let O;n?O=new Int32Array(s,u,M.byteLength/T.BytesPerInt):O=new Float32Array(s,u,M.byteLength/T.BytesPerFloat),O.set(M)}S||(S=new Uint32Array(E)),new Float32Array(s,m,16).set(I),new Uint32Array(s,h,E).set(S),e.exports.sortIndexes(o,A,u,p,h,m,a,c,d,E,y,g,i,w,n,r);let L={sortDone:!0,splatSortCount:y,splatRenderCount:g,sortTime:0};if(!t){let P=new Uint32Array(s,a,g);(!C||C.length<g)&&(C=new Uint32Array(g)),C.set(P),L.sortedIndexes=C}let F=performance.now();L.sortTime=F-D,l.postMessage(L)}l.onmessage=y=>{if(y.data.centers)centers=y.data.centers,sceneIndexes=y.data.sceneIndexes,n?new Int32Array(s,A+y.data.range.from*T.BytesPerInt*4,y.data.range.count*4).set(new Int32Array(centers)):new Float32Array(s,A+y.data.range.from*T.BytesPerFloat*4,y.data.range.count*4).set(new Float32Array(centers)),r&&new Uint32Array(s,c+y.data.range.from*4,y.data.range.count).set(new Uint32Array(sceneIndexes)),x=y.data.range.from+y.data.range.count;else if(y.data.sort){let g=Math.min(y.data.sort.splatRenderCount||0,x),I=Math.min(y.data.sort.splatSortCount||0,x),w=y.data.sort.usePrecomputedDistances,v,M,b;t||(v=y.data.sort.indexesToSort,b=y.data.sort.transforms,w&&(M=y.data.sort.precomputedDistances)),R(I,g,y.data.sort.modelViewProj,w,v,M,b)}else if(y.data.init){T=y.data.init.Constants,i=y.data.init.splatCount,t=y.data.init.useSharedMemory,n=y.data.init.integerBasedSort,r=y.data.init.dynamicMode,E=y.data.init.distanceMapRange,x=0;let g=n?T.BytesPerInt*4:T.BytesPerFloat*4,I=new Uint8Array(y.data.init.sorterWasmBytes),w=16*T.BytesPerFloat,v=i*T.BytesPerInt,M=i*g,b=w,D=n?i*T.BytesPerInt:i*T.BytesPerFloat,L=i*T.BytesPerInt,F=i*T.BytesPerInt,P=n?E*T.BytesPerInt*2:E*T.BytesPerFloat*2,z=r?i*T.BytesPerInt:0,O=r?T.MaxScenes*w:0,k=T.MemoryPageSize*32,V=v+M+b+D+L+P+F+z+O+k,q=Math.floor(V/T.MemoryPageSize)+1,oe={module:{},env:{memory:new WebAssembly.Memory({initial:q,maximum:q,shared:!0})}};WebAssembly.compile(I).then(N=>WebAssembly.instantiate(N,oe)).then(N=>{e=N,o=0,A=o+v,m=A+M,u=m+b,p=u+D,h=p+L,a=h+P,c=a+F,d=c+z,s=oe.env.memory.buffer,t?l.postMessage({sortSetupPhase1Complete:!0,indexesToSortBuffer:s,indexesToSortOffset:o,sortedIndexesBuffer:s,sortedIndexesOffset:a,precomputedDistancesBuffer:s,precomputedDistancesOffset:u,transformsBuffer:s,transformsOffset:d}):l.postMessage({sortSetupPhase1Complete:!0})})}}}function no(l,e,s,t,n,r=j.DefaultSplatSortDistanceMapPrecision){let i=new Worker(URL.createObjectURL(new Blob(["(",so.toString(),")(self)"],{type:"application/javascript"}))),o=$r,a=ms()?an():null;!s&&!e?(o=on,a&&a.major<=16&&a.minor<4&&(o=to)):s?e||a&&a.major<=16&&a.minor<4&&(o=eo):o=on;let c=atob(o),d=new Uint8Array(c.length);for(let u=0;u<c.length;u++)d[u]=c.charCodeAt(u);return i.postMessage({init:{sorterWasmBytes:d.buffer,splatCount:l,useSharedMemory:e,integerBasedSort:t,dynamicMode:n,distanceMapRange:1<<r,Constants:{BytesPerFloat:j.BytesPerFloat,BytesPerInt:j.BytesPerInt,MemoryPageSize:j.MemoryPageSize,MaxScenes:j.MaxScenes}}}),i}var je={None:0,VR:1,AR:2},at=class l{static createButton(e,s={}){let t=document.createElement("button");function n(){let c=null;async function d(h){h.addEventListener("end",u),await e.xr.setSession(h),t.textContent="EXIT VR",c=h}function u(){c.removeEventListener("end",u),t.textContent="ENTER VR",c=null}t.style.display="",t.style.cursor="pointer",t.style.left="calc(50% - 50px)",t.style.width="100px",t.textContent="ENTER VR";let p={...s,optionalFeatures:["local-floor","bounded-floor","layers",...s.optionalFeatures||[]]};t.onmouseenter=function(){t.style.opacity="1.0"},t.onmouseleave=function(){t.style.opacity="0.5"},t.onclick=function(){c===null?navigator.xr.requestSession("immersive-vr",p).then(d):(c.end(),navigator.xr.offerSession!==void 0&&navigator.xr.offerSession("immersive-vr",p).then(d).catch(h=>{console.warn(h)}))},navigator.xr.offerSession!==void 0&&navigator.xr.offerSession("immersive-vr",p).then(d).catch(h=>{console.warn(h)})}function r(){t.style.display="",t.style.cursor="auto",t.style.left="calc(50% - 75px)",t.style.width="150px",t.onmouseenter=null,t.onmouseleave=null,t.onclick=null}function i(){r(),t.textContent="VR NOT SUPPORTED"}function o(c){r(),console.warn("Exception when trying to call xr.isSessionSupported",c),t.textContent="VR NOT ALLOWED"}function a(c){c.style.position="absolute",c.style.bottom="20px",c.style.padding="12px 6px",c.style.border="1px solid #fff",c.style.borderRadius="4px",c.style.background="rgba(0,0,0,0.1)",c.style.color="#fff",c.style.font="normal 13px sans-serif",c.style.textAlign="center",c.style.opacity="0.5",c.style.outline="none",c.style.zIndex="999"}if("xr"in navigator)return t.id="VRButton",t.style.display="none",a(t),navigator.xr.isSessionSupported("immersive-vr").then(function(c){c?n():i(),c&&l.xrSessionIsGranted&&t.click()}).catch(o),t;{let c=document.createElement("a");return window.isSecureContext===!1?(c.href=document.location.href.replace(/^http:/,"https:"),c.innerHTML="WEBXR NEEDS HTTPS"):(c.href="https://immersiveweb.dev/",c.innerHTML="WEBXR NOT AVAILABLE"),c.style.left="calc(50% - 90px)",c.style.width="180px",c.style.textDecoration="none",a(c),c}}static registerSessionGrantedListener(){if(typeof navigator<"u"&&"xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent))return;navigator.xr.addEventListener("sessiongranted",()=>{l.xrSessionIsGranted=!0})}}};at.xrSessionIsGranted=!1;at.registerSessionGrantedListener();var hs=class{static createButton(e,s={}){let t=document.createElement("button");function n(){if(s.domOverlay===void 0){let p=document.createElement("div");p.style.display="none",document.body.appendChild(p);let h=document.createElementNS("http://www.w3.org/2000/svg","svg");h.setAttribute("width",38),h.setAttribute("height",38),h.style.position="absolute",h.style.right="20px",h.style.top="20px",h.addEventListener("click",function(){c.end()}),p.appendChild(h);let A=document.createElementNS("http://www.w3.org/2000/svg","path");A.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),A.setAttribute("stroke","#fff"),A.setAttribute("stroke-width",2),h.appendChild(A),s.optionalFeatures===void 0&&(s.optionalFeatures=[]),s.optionalFeatures.push("dom-overlay"),s.domOverlay={root:p}}let c=null;async function d(p){p.addEventListener("end",u),e.xr.setReferenceSpaceType("local"),await e.xr.setSession(p),t.textContent="STOP AR",s.domOverlay.root.style.display="",c=p}function u(){c.removeEventListener("end",u),t.textContent="START AR",s.domOverlay.root.style.display="none",c=null}t.style.display="",t.style.cursor="pointer",t.style.left="calc(50% - 50px)",t.style.width="100px",t.textContent="START AR",t.onmouseenter=function(){t.style.opacity="1.0"},t.onmouseleave=function(){t.style.opacity="0.5"},t.onclick=function(){c===null?navigator.xr.requestSession("immersive-ar",s).then(d):(c.end(),navigator.xr.offerSession!==void 0&&navigator.xr.offerSession("immersive-ar",s).then(d).catch(p=>{console.warn(p)}))},navigator.xr.offerSession!==void 0&&navigator.xr.offerSession("immersive-ar",s).then(d).catch(p=>{console.warn(p)})}function r(){t.style.display="",t.style.cursor="auto",t.style.left="calc(50% - 75px)",t.style.width="150px",t.onmouseenter=null,t.onmouseleave=null,t.onclick=null}function i(){r(),t.textContent="AR NOT SUPPORTED"}function o(c){r(),console.warn("Exception when trying to call xr.isSessionSupported",c),t.textContent="AR NOT ALLOWED"}function a(c){c.style.position="absolute",c.style.bottom="20px",c.style.padding="12px 6px",c.style.border="1px solid #fff",c.style.borderRadius="4px",c.style.background="rgba(0,0,0,0.1)",c.style.color="#fff",c.style.font="normal 13px sans-serif",c.style.textAlign="center",c.style.opacity="0.5",c.style.outline="none",c.style.zIndex="999"}if("xr"in navigator)return t.id="ARButton",t.style.display="none",a(t),navigator.xr.isSessionSupported("immersive-ar").then(function(c){c?n():i()}).catch(o),t;{let c=document.createElement("a");return window.isSecureContext===!1?(c.href=document.location.href.replace(/^http:/,"https:"),c.innerHTML="WEBXR NEEDS HTTPS"):(c.href="https://immersiveweb.dev/",c.innerHTML="WEBXR NOT AVAILABLE"),c.style.left="calc(50% - 90px)",c.style.width="180px",c.style.textDecoration="none",a(c),c}}},Vt={Always:0,OnChange:1,Never:2},ro=50,oo=.75,io=15e5,ao=10,lo=2.5,co=60,ps=class l{constructor(e={}){if(e.cameraUp||(e.cameraUp=[0,1,0]),this.cameraUp=new f.Vector3().fromArray(e.cameraUp),e.initialCameraPosition||(e.initialCameraPosition=[0,10,15]),this.initialCameraPosition=new f.Vector3().fromArray(e.initialCameraPosition),e.initialCameraLookAt||(e.initialCameraLookAt=[0,0,0]),this.initialCameraLookAt=new f.Vector3().fromArray(e.initialCameraLookAt),this.dropInMode=e.dropInMode||!1,(e.selfDrivenMode===void 0||e.selfDrivenMode===null)&&(e.selfDrivenMode=!0),this.selfDrivenMode=e.selfDrivenMode&&!this.dropInMode,this.selfDrivenUpdateFunc=this.selfDrivenUpdate.bind(this),e.useBuiltInControls===void 0&&(e.useBuiltInControls=!0),this.useBuiltInControls=e.useBuiltInControls,this.rootElement=e.rootElement,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,(e.integerBasedSort===void 0||e.integerBasedSort===null)&&(e.integerBasedSort=!0),this.integerBasedSort=e.integerBasedSort,(e.sharedMemoryForWorkers===void 0||e.sharedMemoryForWorkers===null)&&(e.sharedMemoryForWorkers=!0),this.sharedMemoryForWorkers=e.sharedMemoryForWorkers,this.dynamicScene=!!e.dynamicScene,this.antialiased=e.antialiased||!1,this.kernel2DSize=e.kernel2DSize===void 0?.3:e.kernel2DSize,this.webXRMode=e.webXRMode||je.None,this.webXRMode!==je.None&&(this.gpuAcceleratedSort=!1),this.webXRActive=!1,this.webXRSessionInit=e.webXRSessionInit||{},this.renderMode=e.renderMode||Vt.Always,this.sceneRevealMode=e.sceneRevealMode||rt.Default,this.focalAdjustment=e.focalAdjustment||1,this.maxScreenSpaceSplatSize=e.maxScreenSpaceSplatSize||1024,this.logLevel=e.logLevel||Ze.None,this.sphericalHarmonicsDegree=e.sphericalHarmonicsDegree||0,this.enableOptionalEffects=e.enableOptionalEffects||!1,(e.enableSIMDInSort===void 0||e.enableSIMDInSort===null)&&(e.enableSIMDInSort=!0),this.enableSIMDInSort=e.enableSIMDInSort,(e.inMemoryCompressionLevel===void 0||e.inMemoryCompressionLevel===null)&&(e.inMemoryCompressionLevel=0),this.inMemoryCompressionLevel=e.inMemoryCompressionLevel,(e.optimizeSplatData===void 0||e.optimizeSplatData===null)&&(e.optimizeSplatData=!0),this.optimizeSplatData=e.optimizeSplatData,(e.freeIntermediateSplatData===void 0||e.freeIntermediateSplatData===null)&&(e.freeIntermediateSplatData=!1),this.freeIntermediateSplatData=e.freeIntermediateSplatData,ms()){let t=an();t.major<17&&(this.enableSIMDInSort=!1),t.major<16&&(this.sharedMemoryForWorkers=!1)}(e.splatRenderMode===void 0||e.splatRenderMode===null)&&(e.splatRenderMode=De.ThreeD),this.splatRenderMode=e.splatRenderMode,this.sceneFadeInRateMultiplier=e.sceneFadeInRateMultiplier||1,this.splatSortDistanceMapPrecision=e.splatSortDistanceMapPrecision||j.DefaultSplatSortDistanceMapPrecision;let s=this.integerBasedSort?20:24;this.splatSortDistanceMapPrecision=se(this.splatSortDistanceMapPrecision,10,s),this.onSplatMeshChangedCallback=null,this.createSplatMesh(),this.controls=null,this.perspectiveControls=null,this.orthographicControls=null,this.orthographicCamera=null,this.perspectiveCamera=null,this.showMeshCursor=!1,this.showControlPlane=!1,this.showInfo=!1,this.sceneHelper=null,this.sortWorker=null,this.sortRunning=!1,this.splatRenderCount=0,this.splatSortCount=0,this.lastSplatSortCount=0,this.sortWorkerIndexesToSort=null,this.sortWorkerSortedIndexes=null,this.sortWorkerPrecomputedDistances=null,this.sortWorkerTransforms=null,this.preSortMessages=[],this.runAfterNextSort=[],this.selfDrivenModeRunning=!1,this.splatRenderReady=!1,this.raycaster=new ns,this.infoPanel=null,this.startInOrthographicMode=!1,this.currentFPS=0,this.lastSortTime=0,this.consecutiveRenderFrames=0,this.previousCameraTarget=new f.Vector3,this.nextCameraTarget=new f.Vector3,this.mousePosition=new f.Vector2,this.mouseDownPosition=new f.Vector2,this.mouseDownTime=null,this.resizeObserver=null,this.mouseMoveListener=null,this.mouseDownListener=null,this.mouseUpListener=null,this.keyDownListener=null,this.sortPromise=null,this.sortPromiseResolver=null,this.splatSceneDownloadPromises={},this.splatSceneDownloadAndBuildPromise=null,this.splatSceneRemovalPromise=null,this.loadingSpinner=new Jt(null,this.rootElement||document.body),this.loadingSpinner.hide(),this.loadingProgressBar=new Zt(this.rootElement||document.body),this.loadingProgressBar.hide(),this.infoPanel=new $t(this.rootElement||document.body),this.infoPanel.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.dropInMode||this.init()}createSplatMesh(){this.splatMesh=new us(this.splatRenderMode,this.dynamicScene,this.enableOptionalEffects,this.halfPrecisionCovariancesOnGPU,this.devicePixelRatio,this.gpuAcceleratedSort,this.integerBasedSort,this.antialiased,this.maxScreenSpaceSplatSize,this.logLevel,this.sphericalHarmonicsDegree,this.sceneFadeInRateMultiplier,this.kernel2DSize),this.splatMesh.frustumCulled=!1,this.onSplatMeshChangedCallback&&this.onSplatMeshChangedCallback()}init(){this.initialized||(this.rootElement||(this.usingExternalRenderer?this.rootElement=this.renderer.domElement||document.body:(this.rootElement=document.createElement("div"),this.rootElement.style.width="100%",this.rootElement.style.height="100%",this.rootElement.style.position="absolute",document.body.appendChild(this.rootElement))),this.setupCamera(),this.setupRenderer(),this.setupWebXR(this.webXRSessionInit),this.setupControls(),this.setupEventHandlers(),this.threeScene=this.threeScene||new f.Scene,this.sceneHelper=new ts(this.threeScene),this.sceneHelper.setupMeshCursor(),this.sceneHelper.setupFocusMarker(),this.sceneHelper.setupControlPlane(),this.loadingProgressBar.setContainer(this.rootElement),this.loadingSpinner.setContainer(this.rootElement),this.infoPanel.setContainer(this.rootElement),this.initialized=!0)}setupCamera(){if(!this.usingExternalCamera){let e=new f.Vector2;this.getRenderDimensions(e),this.perspectiveCamera=new f.PerspectiveCamera(ro,e.x/e.y,.1,1e3),this.orthographicCamera=new f.OrthographicCamera(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.up.copy(this.cameraUp).normalize(),this.camera.lookAt(this.initialCameraLookAt)}}setupRenderer(){if(!this.usingExternalRenderer){let e=new f.Vector2;this.getRenderDimensions(e),this.renderer=new f.WebGLRenderer({antialias:!1,precision:"highp"}),this.renderer.setPixelRatio(this.devicePixelRatio),this.renderer.autoClear=!0,this.renderer.setClearColor(new f.Color(0),0),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)}}setupWebXR(e){this.webXRMode&&(this.webXRMode===je.VR?this.rootElement.appendChild(at.createButton(this.renderer,e)):this.webXRMode===je.AR&&this.rootElement.appendChild(hs.createButton(this.renderer,e)),this.renderer.xr.addEventListener("sessionstart",s=>{this.webXRActive=!0}),this.renderer.xr.addEventListener("sessionend",s=>{this.webXRActive=!1}),this.renderer.xr.enabled=!0,this.camera.position.copy(this.initialCameraPosition),this.camera.up.copy(this.cameraUp).normalize(),this.camera.lookAt(this.initialCameraLookAt))}setupControls(){if(this.useBuiltInControls&&this.webXRMode===je.None){this.usingExternalCamera?this.camera.isOrthographicCamera?this.orthographicControls=new Xe(this.camera,this.renderer.domElement):this.perspectiveControls=new Xe(this.camera,this.renderer.domElement):(this.perspectiveControls=new Xe(this.perspectiveCamera,this.renderer.domElement),this.orthographicControls=new Xe(this.orthographicCamera,this.renderer.domElement));for(let e of[this.orthographicControls,this.perspectiveControls])e&&(e.listenToKeyEvents(window),e.rotateSpeed=.5,e.maxPolarAngle=Math.PI*.75,e.minPolarAngle=.1,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.webXRMode===je.None&&(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),window.addEventListener("keydown",this.keyDownListener,!1))}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}onKeyDown=function(){let e=new f.Vector3,s=new f.Matrix4,t=new f.Matrix4;return function(n){switch(e.set(0,0,-1),e.transformDirection(this.camera.matrixWorld),s.makeRotationAxis(e,Math.PI/128),t.makeRotationAxis(e,-Math.PI/128),n.code){case"KeyG":this.focalAdjustment+=.02,this.forceRenderNextFrame();break;case"KeyF":this.focalAdjustment-=.02,this.forceRenderNextFrame();break;case"ArrowLeft":this.camera.up.transformDirection(s);break;case"ArrowRight":this.camera.up.transformDirection(t);break;case"KeyC":this.showMeshCursor=!this.showMeshCursor;break;case"KeyU":this.showControlPlane=!this.showControlPlane;break;case"KeyI":this.showInfo=!this.showInfo,this.showInfo?this.infoPanel.show():this.infoPanel.hide();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));break}}}();onMouseMove(e){this.mousePosition.set(e.offsetX,e.offsetY)}onMouseDown(){this.mouseDownPosition.copy(this.mousePosition),this.mouseDownTime=qe()}onMouseUp=function(){let e=new f.Vector2;return function(s){e.copy(this.mousePosition).sub(this.mouseDownPosition),qe()-this.mouseDownTime<.5&&e.length()<2&&this.onMouseClick(s)}}();onMouseClick(e){this.mousePosition.set(e.offsetX,e.offsetY),this.checkForFocalPointChange()}checkForFocalPointChange=function(){let e=new f.Vector2,s=new f.Vector3,t=[];return function(){if(!this.transitioningCameraTarget&&(this.getRenderDimensions(e),t.length=0,this.raycaster.setFromCameraAndScreenPosition(this.camera,this.mousePosition,e),this.raycaster.intersectSplatMesh(this.splatMesh,t),t.length>0)){let r=t[0].origin;s.copy(r).sub(this.camera.position),s.length()>oo&&(this.previousCameraTarget.copy(this.controls.target),this.nextCameraTarget.copy(r),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;let s=this.camera,t=e?this.orthographicCamera:this.perspectiveCamera;if(t.position.copy(s.position),t.up.copy(s.up),t.rotation.copy(s.rotation),t.quaternion.copy(s.quaternion),t.matrix.copy(s.matrix),this.camera=t,this.controls){let n=o=>{o.saveState(),o.reset()},r=this.controls,i=e?this.orthographicControls:this.perspectiveControls;n(i),n(r),i.target.copy(r.target),e?l.setCameraZoomFromPosition(t,s,r):l.setCameraPositionFromZoom(t,s,i),this.controls=i,this.camera.lookAt(this.controls.target)}}static setCameraPositionFromZoom=function(){let e=new f.Vector3;return function(s,t,n){let r=1/(t.zoom*.001);e.copy(n.target).sub(s.position).normalize().multiplyScalar(r).negate(),s.position.copy(n.target).add(e)}}();static setCameraZoomFromPosition=function(){let e=new f.Vector3;return function(s,t,n){let r=e.copy(n.target).sub(t.position).length();s.zoom=1/(r*.001)}}();updateSplatMesh=function(){let e=new f.Vector2;return function(){if(!this.splatMesh)return;if(this.splatMesh.getSplatCount()>0){this.splatMesh.updateVisibleRegionFadeDistance(this.sceneRevealMode),this.splatMesh.updateTransforms(),this.getRenderDimensions(e);let t=this.camera.projectionMatrix.elements[0]*.5*this.devicePixelRatio*e.x,n=this.camera.projectionMatrix.elements[5]*.5*this.devicePixelRatio*e.y,r=this.camera.isOrthographicCamera?1/this.devicePixelRatio:1,i=this.focalAdjustment*r,o=1/i;this.adjustForWebXRStereo(e),this.splatMesh.updateUniforms(e,t*i,n*i,this.camera.isOrthographicCamera,this.camera.zoom||1,o)}}}();adjustForWebXRStereo(e){if(this.camera&&this.webXRActive){let t=this.renderer.xr.getCamera().projectionMatrix.elements[0],n=this.camera.projectionMatrix.elements[0];e.x*=n/t}}isLoadingOrUnloading(){return Object.keys(this.splatSceneDownloadPromises).length>0||this.splatSceneDownloadAndBuildPromise!==null||this.splatSceneRemovalPromise!==null}isDisposingOrDisposed(){return this.disposing||this.disposed}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,s={}){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.");s.progressiveLoad&&this.splatMesh.scenes&&this.splatMesh.scenes.length>0&&(console.log('addSplatScene(): "progressiveLoad" option ignore because there are multiple splat scenes'),s.progressiveLoad=!1);let t=s.format!==void 0&&s.format!==null?s.format:Xs(e),n=l.isProgressivelyLoadable(t)&&s.progressiveLoad,r=s.showLoadingUI!==void 0&&s.showLoadingUI!==null?s.showLoadingUI:!0,i=null;r&&(this.loadingSpinner.removeAllTasks(),i=this.loadingSpinner.addTask("Downloading..."));let o=()=>{this.loadingProgressBar.hide(),this.loadingSpinner.removeAllTasks()},a=(m,S,C)=>{if(r)if(C===ue.Downloading)if(m==100)this.loadingSpinner.setMessageForTask(i,"Download complete!");else if(n)this.loadingSpinner.setMessageForTask(i,"Downloading splats...");else{let E=S?`: ${S}`:"...";this.loadingSpinner.setMessageForTask(i,`Downloading${E}`)}else C===ue.Processing&&this.loadingSpinner.setMessageForTask(i,"Processing splats...")},c=!1,d=0,u=(m,S)=>{r&&((m&&n||S&&!n)&&(this.loadingSpinner.removeTask(i),!S&&!c&&this.loadingProgressBar.show()),n&&(S?(c=!0,this.loadingProgressBar.hide()):this.loadingProgressBar.setProgress(d)))},p=(m,S,C)=>{d=m,a(m,S,C),s.onProgress&&s.onProgress(m,S,C)},h=(m,S,C)=>{!n&&s.onProgress&&s.onProgress(0,"0%",ue.Processing);let E={rotation:s.rotation||s.orientation,position:s.position,scale:s.scale,splatAlphaRemovalThreshold:s.splatAlphaRemovalThreshold};return this.addSplatBuffers([m],[E],C,S&&r,r,n,n).then(()=>{!n&&s.onProgress&&s.onProgress(100,"100%",ue.Processing),u(S,C)})};return(n?this.downloadAndBuildSingleSplatSceneProgressiveLoad.bind(this):this.downloadAndBuildSingleSplatSceneStandardLoad.bind(this))(e,t,s.splatAlphaRemovalThreshold,h.bind(this),p,o.bind(this),s.headers)}downloadAndBuildSingleSplatSceneStandardLoad(e,s,t,n,r,i,o){let a=this.downloadSplatSceneToSplatBuffer(e,t,r,!1,void 0,s,o),c=Ht(a.abortHandler);return a.then(d=>(this.removeSplatSceneDownloadPromise(a),n(d,!0,!0).then(()=>{c.resolve(),this.clearSplatSceneDownloadAndBuildPromise()}))).catch(d=>{i&&i(),this.clearSplatSceneDownloadAndBuildPromise(),this.removeSplatSceneDownloadPromise(a),c.reject(this.updateError(d,`Viewer::addSplatScene -> Could not load file ${e}`))}),this.addSplatSceneDownloadPromise(a),this.setSplatSceneDownloadAndBuildPromise(c.promise),c.promise}downloadAndBuildSingleSplatSceneProgressiveLoad(e,s,t,n,r,i,o){let a=0,c=!1,d=[],u=()=>{if(d.length>0&&!c&&!this.isDisposingOrDisposed()){c=!0;let S=d.shift();n(S.splatBuffer,S.firstBuild,S.finalBuild).then(()=>{c=!1,S.firstBuild?A.resolve():S.finalBuild&&(m.resolve(),this.clearSplatSceneDownloadAndBuildPromise()),d.length>0&&Re(()=>u())})}},p=(S,C)=>{this.isDisposingOrDisposed()||(C||d.length===0||S.getSplatCount()>d[0].splatBuffer.getSplatCount())&&(d.push({splatBuffer:S,firstBuild:a===0,finalBuild:C}),a++,u())},h=this.downloadSplatSceneToSplatBuffer(e,t,r,!0,p,s,o),A=Ht(h.abortHandler),m=Ht();return this.addSplatSceneDownloadPromise(h),this.setSplatSceneDownloadAndBuildPromise(m.promise),h.then(()=>{this.removeSplatSceneDownloadPromise(h)}).catch(S=>{this.clearSplatSceneDownloadAndBuildPromise(),this.removeSplatSceneDownloadPromise(h);let C=this.updateError(S,"Viewer::addSplatScene -> Could not load one or more scenes");A.reject(C),i&&i(C)}),A.promise}addSplatScenes(e,s=!0,t=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.");let n=e.length,r=[],i;s&&(this.loadingSpinner.removeAllTasks(),i=this.loadingSpinner.addTask("Downloading..."));let o=(u,p,h,A)=>{r[u]=p;let m=0;for(let S=0;S<n;S++)m+=r[S]||0;m=m/n,h=`${m.toFixed(2)}%`,s&&A===ue.Downloading&&this.loadingSpinner.setMessageForTask(i,m==100?"Download complete!":`Downloading: ${h}`),t&&t(m,h,A)},a=[],c=[];for(let u=0;u<e.length;u++){let p=e[u],h=p.format!==void 0&&p.format!==null?p.format:Xs(p.path),A=this.downloadSplatSceneToSplatBuffer(p.path,p.splatAlphaRemovalThreshold,o.bind(this,u),!1,void 0,h,p.headers);a.push(A),c.push(A.promise)}let d=new ot((u,p)=>{Promise.all(c).then(h=>{s&&this.loadingSpinner.removeTask(i),t&&t(0,"0%",ue.Processing),this.addSplatBuffers(h,e,!0,s,s,!1,!1).then(()=>{t&&t(100,"100%",ue.Processing),this.clearSplatSceneDownloadAndBuildPromise(),u()})}).catch(h=>{s&&this.loadingSpinner.removeTask(i),this.clearSplatSceneDownloadAndBuildPromise(),p(this.updateError(h,"Viewer::addSplatScenes -> Could not load one or more splat scenes."))}).finally(()=>{this.removeSplatSceneDownloadPromise(d)})},u=>{for(let p of a)p.abort(u)});return this.addSplatSceneDownloadPromise(d),this.setSplatSceneDownloadAndBuildPromise(d),d}downloadSplatSceneToSplatBuffer(e,s=1,t=void 0,n=!1,r=void 0,i,o){try{if(i===Ce.Splat||i===Ce.KSplat||i===Ce.Ply){let a=n?!1:this.optimizeSplatData;if(i===Ce.Splat)return Yt.loadFromURL(e,t,n,r,s,this.inMemoryCompressionLevel,a,o);if(i===Ce.KSplat)return Xt.loadFromURL(e,t,n,r,o);if(i===Ce.Ply)return Kt.loadFromURL(e,t,n,r,s,this.inMemoryCompressionLevel,a,this.sphericalHarmonicsDegree,o)}else if(i===Ce.Spz)return jt.loadFromURL(e,t,s,this.inMemoryCompressionLevel,this.optimizeSplatData,this.sphericalHarmonicsDegree,o)}catch(a){throw this.updateError(a,null)}throw new Error(`Viewer::downloadSplatSceneToSplatBuffer -> File format not supported: ${e}`)}static isProgressivelyLoadable(e){return e===Ce.Splat||e===Ce.KSplat||e===Ce.Ply}addSplatBuffers=function(){return function(e,s=[],t=!0,n=!0,r=!0,i=!1,o=!1,a=!0){if(this.isDisposingOrDisposed())return Promise.resolve();let c=null,d=()=>{c!==null&&(this.loadingSpinner.removeTask(c),c=null)};return this.splatRenderReady=!1,new Promise(u=>{n&&(c=this.loadingSpinner.addTask("Processing splats...")),Re(()=>{if(this.isDisposingOrDisposed())u();else{let p=this.addSplatBuffersToMesh(e,s,t,r,i,a),h=this.splatMesh.getMaxSplatCount();this.sortWorker&&this.sortWorker.maxSplatCount!==h&&this.disposeSortWorker(),this.gpuAcceleratedSort||this.preSortMessages.push({centers:p.centers.buffer,sceneIndexes:p.sceneIndexes.buffer,range:{from:p.from,to:p.to,count:p.count}}),(!this.sortWorker&&h>0?this.setupSortWorker(this.splatMesh):Promise.resolve()).then(()=>{this.isDisposingOrDisposed()||this.runSplatSort(!0,!0).then(m=>{!this.sortWorker||!m?(this.splatRenderReady=!0,d(),u()):(o?this.splatRenderReady=!0:this.runAfterNextSort.push(()=>{this.splatRenderReady=!0}),this.runAfterNextSort.push(()=>{d(),u()}))})})}},!0)})}}();addSplatBuffersToMesh=function(){let e;return function(s,t,n=!0,r=!1,i=!1,o=!0){if(this.isDisposingOrDisposed())return;let a=[],c=[];i||(a=this.splatMesh.scenes.map(h=>h.splatBuffer)||[],c=this.splatMesh.sceneOptions?this.splatMesh.sceneOptions.map(h=>h):[]),a.push(...s),c.push(...t),this.renderer&&this.splatMesh.setRenderer(this.renderer);let d=h=>{if(this.isDisposingOrDisposed())return;let A=this.splatMesh.getSplatCount();r&&A>=io&&!h&&!e&&(this.loadingSpinner.setMinimized(!0,!0),e=this.loadingSpinner.addTask("Optimizing data structures..."))},u=h=>{this.isDisposingOrDisposed()||h&&e&&(this.loadingSpinner.removeTask(e),e=null)},p=this.splatMesh.build(a,c,!0,n,d,u,o);return n&&this.freeIntermediateSplatData&&this.splatMesh.freeIntermediateSplatData(),p}}();setupSortWorker(e){if(!this.isDisposingOrDisposed())return new Promise(s=>{let t=this.integerBasedSort?Int32Array:Float32Array,n=e.getSplatCount(),r=e.getMaxSplatCount();this.sortWorker=no(r,this.sharedMemoryForWorkers,this.enableSIMDInSort,this.integerBasedSort,this.splatMesh.dynamicMode,this.splatSortDistanceMapPrecision),this.sortWorker.onmessage=i=>{if(i.data.sortDone){if(this.sortRunning=!1,this.sharedMemoryForWorkers)this.splatMesh.updateRenderIndexes(this.sortWorkerSortedIndexes,i.data.splatRenderCount);else{let o=new Uint32Array(i.data.sortedIndexes.buffer,0,i.data.splatRenderCount);this.splatMesh.updateRenderIndexes(o,i.data.splatRenderCount)}this.lastSplatSortCount=this.splatSortCount,this.lastSortTime=i.data.sortTime,this.sortPromiseResolver(),this.sortPromiseResolver=null,this.forceRenderNextFrame(),this.runAfterNextSort.length>0&&(this.runAfterNextSort.forEach(o=>{o()}),this.runAfterNextSort.length=0)}else if(i.data.sortCanceled)this.sortRunning=!1;else if(i.data.sortSetupPhase1Complete){this.logLevel>=Ze.Info&&console.log("Sorting web worker WASM setup complete."),this.sharedMemoryForWorkers?(this.sortWorkerSortedIndexes=new Uint32Array(i.data.sortedIndexesBuffer,i.data.sortedIndexesOffset,r),this.sortWorkerIndexesToSort=new Uint32Array(i.data.indexesToSortBuffer,i.data.indexesToSortOffset,r),this.sortWorkerPrecomputedDistances=new t(i.data.precomputedDistancesBuffer,i.data.precomputedDistancesOffset,r),this.sortWorkerTransforms=new Float32Array(i.data.transformsBuffer,i.data.transformsOffset,j.MaxScenes*16)):(this.sortWorkerIndexesToSort=new Uint32Array(r),this.sortWorkerPrecomputedDistances=new t(r),this.sortWorkerTransforms=new Float32Array(j.MaxScenes*16));for(let o=0;o<n;o++)this.sortWorkerIndexesToSort[o]=o;if(this.sortWorker.maxSplatCount=r,this.logLevel>=Ze.Info){console.log("Sorting web worker ready.");let o=this.splatMesh.getSplatDataTextures(),a=o.covariances.size,c=o.centerColors.size;console.log("Covariances texture size: "+a.x+" x "+a.y),console.log("Centers/colors texture size: "+c.x+" x "+c.y)}s()}}})}updateError(e,s){return e instanceof Ct?e:e instanceof $e?new Error("File type or server does not support progressive loading."):s?new Error(s):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,s=!0){return this.removeSplatScenes([e],s)}removeSplatScenes(e,s=!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 t;return this.splatSceneRemovalPromise=new Promise((n,r)=>{let i;s&&(this.loadingSpinner.removeAllTasks(),this.loadingSpinner.show(),i=this.loadingSpinner.addTask("Removing splat scene..."));let o=()=>{s&&(this.loadingSpinner.hide(),this.loadingSpinner.removeTask(i))},a=d=>{o(),this.splatSceneRemovalPromise=null,d?r(d):n()},c=()=>this.isDisposingOrDisposed()?(a(),!0):!1;t=this.sortPromise||Promise.resolve(),t.then(()=>{if(c())return;let d=[],u=[],p=[];for(let h=0;h<this.splatMesh.scenes.length;h++){let A=!1;for(let m of e)if(m===h){A=!0;break}if(!A){let m=this.splatMesh.scenes[h];d.push(m.splatBuffer),u.push(this.splatMesh.sceneOptions[h]),p.push({position:m.position.clone(),quaternion:m.quaternion.clone(),scale:m.scale.clone()})}}this.disposeSortWorker(),this.splatMesh.dispose(),this.sceneRevealMode=rt.Instant,this.createSplatMesh(),this.addSplatBuffers(d,u,!0,!1,!0).then(()=>{c()||(o(),this.splatMesh.scenes.forEach((h,A)=>{h.position.copy(p[A].position),h.quaternion.copy(p[A].quaternion),h.scale.copy(p[A].scale)}),this.splatMesh.updateTransforms(),this.splatRenderReady=!1,this.runSplatSort(!0).then(()=>{if(c()){this.splatRenderReady=!0;return}t=this.sortPromise||Promise.resolve(),t.then(()=>{this.splatRenderReady=!0,a()})}))}).catch(h=>{a(h)})})}),this.splatSceneRemovalPromise}start(){if(this.selfDrivenMode)this.webXRMode?this.renderer.setAnimationLoop(this.selfDrivenUpdateFunc):this.requestFrameId=requestAnimationFrame(this.selfDrivenUpdateFunc),this.selfDrivenModeRunning=!0;else throw new Error("Cannot start viewer unless it is in self driven mode.")}stop(){this.selfDrivenMode&&this.selfDrivenModeRunning&&(this.webXRMode?this.renderer.setAnimationLoop(null):cancelAnimationFrame(this.requestFrameId),this.selfDrivenModeRunning=!1)}async dispose(){if(this.isDisposingOrDisposed())return this.disposePromise;let e=[],s=[];for(let t in this.splatSceneDownloadPromises)if(this.splatSceneDownloadPromises.hasOwnProperty(t)){let n=this.splatSceneDownloadPromises[t];s.push(n),e.push(n.promise)}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.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.infoPanel.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||document.body.removeChild(this.rootElement),this.sortWorkerSortedIndexes=null,this.sortWorkerIndexesToSort=null,this.sortWorkerPrecomputedDistances=null,this.sortWorkerTransforms=null,this.disposed=!0,this.disposing=!1,this.disposePromise=null}),s.forEach(t=>{t.abort("Scene disposed")}),this.disposePromise}selfDrivenUpdate(){this.selfDrivenMode&&!this.webXRMode&&(this.requestFrameId=requestAnimationFrame(this.selfDrivenUpdateFunc)),this.update(),this.shouldRender()?(this.render(),this.consecutiveRenderFrames++):this.consecutiveRenderFrames=0,this.renderNextFrame=!1}forceRenderNextFrame(){this.renderNextFrame=!0}shouldRender=function(){let e=0,s=new f.Vector3,t=new f.Quaternion,n=1e-4;return function(){if(!this.initialized||!this.splatRenderReady||this.isDisposingOrDisposed())return!1;let r=!1,i=!1;if(this.camera){let o=this.camera.position,a=this.camera.quaternion;i=Math.abs(o.x-s.x)>n||Math.abs(o.y-s.y)>n||Math.abs(o.z-s.z)>n||Math.abs(a.x-t.x)>n||Math.abs(a.y-t.y)>n||Math.abs(a.z-t.z)>n||Math.abs(a.w-t.w)>n}return r=this.renderMode!==Vt.Never&&(e===0||this.splatMesh.visibleRegionChanging||i||this.renderMode===Vt.Always||this.dynamicMode===!0||this.renderNextFrame),this.camera&&(s.copy(this.camera.position),t.copy(this.camera.quaternion)),e++,r}}();render=function(){return function(){if(!this.initialized||!this.splatRenderReady||this.isDisposingOrDisposed())return;let e=t=>{for(let n of t.children)if(n.visible)return!0;return!1},s=this.renderer.autoClear;e(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=s}}();update(e,s){this.dropInMode&&this.updateForDropInMode(e,s),!(!this.initialized||!this.splatRenderReady||this.isDisposingOrDisposed())&&(this.controls&&(this.controls.update(),this.camera.isOrthographicCamera&&!this.usingExternalCamera&&l.setCameraPositionFromZoom(this.camera,this.camera,this.controls)),this.runSplatSort(),this.updateForRendererSizeChanges(),this.updateSplatMesh(),this.updateMeshCursor(),this.updateFPS(),this.timingSensitiveUpdates(),this.updateInfoPanel(),this.updateControlPlane())}updateForDropInMode(e,s){this.renderer=e,this.splatMesh&&this.splatMesh.setRenderer(this.renderer),this.camera=s,this.controls&&(this.controls.object=s),this.init()}updateFPS=function(){let e=qe(),s=0;return function(){if(this.consecutiveRenderFrames>co){let t=qe();t-e>=1?(this.currentFPS=s,s=0,e=t):s++}else this.currentFPS=null}}();updateForRendererSizeChanges=function(){let e=new f.Vector2,s=new f.Vector2,t;return function(){this.usingExternalCamera||(this.renderer.getSize(s),(t===void 0||t!==this.camera.isOrthographicCamera||s.x!==e.x||s.y!==e.y)&&(this.camera.isOrthographicCamera?(this.camera.left=-s.x/2,this.camera.right=s.x/2,this.camera.top=s.y/2,this.camera.bottom=-s.y/2):this.camera.aspect=s.x/s.y,this.camera.updateProjectionMatrix(),e.copy(s),t=this.camera.isOrthographicCamera))}}();timingSensitiveUpdates=function(){let e;return function(){let s=qe();e||(e=s);let t=s-e;this.updateCameraTransition(s),this.updateFocusMarker(t),e=s}}();updateCameraTransition=function(){let e=new f.Vector3,s=new f.Vector3,t=new f.Vector3;return function(n){if(this.transitioningCameraTarget){s.copy(this.previousCameraTarget).sub(this.camera.position).normalize(),t.copy(this.nextCameraTarget).sub(this.camera.position).normalize();let r=Math.acos(s.dot(t)),o=(r/(Math.PI/3)*.65+.3)/r*(n-this.transitioningCameraTargetStartTime);e.copy(this.previousCameraTarget).lerp(this.nextCameraTarget,o),this.camera.lookAt(e),this.controls.target.copy(e),o>=1&&(this.transitioningCameraTarget=!1)}}}();updateFocusMarker=function(){let e=new f.Vector2,s=!1;return function(t){if(this.getRenderDimensions(e),this.transitioningCameraTarget){this.sceneHelper.setFocusMarkerVisibility(!0);let n=Math.max(this.sceneHelper.getFocusMarkerOpacity(),0),r=Math.min(n+ao*t,1);this.sceneHelper.setFocusMarkerOpacity(r),this.sceneHelper.updateFocusMarker(this.nextCameraTarget,this.camera,e),s=!0,this.forceRenderNextFrame()}else{let n;if(s?n=1:n=Math.min(this.sceneHelper.getFocusMarkerOpacity(),1),n>0){this.sceneHelper.updateFocusMarker(this.nextCameraTarget,this.camera,e);let r=Math.max(n-lo*t,0);this.sceneHelper.setFocusMarkerOpacity(r),r===0&&this.sceneHelper.setFocusMarkerVisibility(!1)}n>0&&this.forceRenderNextFrame(),s=!1}}}();updateMeshCursor=function(){let e=[],s=new f.Vector2;return function(){this.showMeshCursor?(this.forceRenderNextFrame(),this.getRenderDimensions(s),e.length=0,this.raycaster.setFromCameraAndScreenPosition(this.camera,this.mousePosition,s),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(){let e=new f.Vector2;return function(){if(!this.showInfo)return;let s=this.splatMesh.getSplatCount();this.getRenderDimensions(e);let t=this.controls?this.controls.target:null,n=this.showMeshCursor?this.sceneHelper.meshCursor.position:null,r=s>0?this.splatRenderCount/s*100:0;this.infoPanel.update(e,this.camera.position,t,this.camera.up,this.camera.isOrthographicCamera,n,this.currentFPS||"N/A",s,this.splatRenderCount,r,this.lastSortTime,this.focalAdjustment,this.splatMesh.getSplatScale(),this.splatMesh.getPointCloudModeEnabled())}}();updateControlPlane(){this.showControlPlane?(this.sceneHelper.setControlPlaneVisibility(!0),this.sceneHelper.positionAndOrientControlPlane(this.controls.target,this.camera.up)):this.sceneHelper.setControlPlaneVisibility(!1)}runSplatSort=function(){let e=new f.Matrix4,s=[],t=new f.Vector3(0,0,-1),n=new f.Vector3(0,0,-1),r=new f.Vector3,i=new f.Vector3,o=[],a=[{angleThreshold:.55,sortFractions:[.125,.33333,.75]},{angleThreshold:.65,sortFractions:[.33333,.66667]},{angleThreshold:.8,sortFractions:[.5]}];return function(c=!1,d=!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 u=0,p=0,h=!1,A=!1;if(n.set(0,0,-1).applyQuaternion(this.camera.quaternion),u=n.dot(t),p=i.copy(this.camera.position).sub(r).length(),!c&&!this.splatMesh.dynamicMode&&o.length===0&&(u<=.99&&(h=!0),p>=1&&(A=!0),!h&&!A))return Promise.resolve(!1);this.sortRunning=!0;let{splatRenderCount:m,shouldSortAll:S}=this.gatherSceneNodesForSort();S=S||d,this.splatRenderCount=m,e.copy(this.camera.matrixWorld).invert();let C=this.perspectiveCamera||this.camera;e.premultiply(C.projectionMatrix),this.splatMesh.dynamicMode||e.multiply(this.splatMesh.matrixWorld);let E=Promise.resolve(!0);return this.gpuAcceleratedSort&&(o.length<=1||o.length%2===0)&&(E=this.splatMesh.computeDistancesOnGPU(e,this.sortWorkerPrecomputedDistances)),E.then(()=>{if(o.length===0)if(this.splatMesh.dynamicMode||S)o.push(this.splatRenderCount);else{for(let R of a)if(u<R.angleThreshold){for(let y of R.sortFractions)o.push(Math.floor(this.splatRenderCount*y));break}o.push(this.splatRenderCount)}let x=Math.min(o.shift(),this.splatRenderCount);this.splatSortCount=x,s[0]=this.camera.position.x,s[1]=this.camera.position.y,s[2]=this.camera.position.z;let T={modelViewProj:e.elements,cameraPosition:s,splatRenderCount:this.splatRenderCount,splatSortCount:x,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(R=>{this.sortPromiseResolver=R}),this.preSortMessages.length>0&&(this.preSortMessages.forEach(R=>{this.sortWorker.postMessage(R)}),this.preSortMessages=[]),this.sortWorker.postMessage({sort:T}),o.length===0&&(r.copy(this.camera.position),t.copy(n)),!0}),E}}();gatherSceneNodesForSort=function(){let e=[],s=null,t=new f.Vector3,n=new f.Vector3,r=new f.Vector3,i=new f.Matrix4,o=new f.Matrix4,a=new f.Matrix4,c=new f.Vector3,d=new f.Vector3(0,0,-1),u=new f.Vector3,p=h=>u.copy(h.max).sub(h.min).length();return function(h=!1){this.getRenderDimensions(c);let A=c.y/2/Math.tan(this.camera.fov/2*f.MathUtils.DEG2RAD),m=Math.atan(c.x/2/A),S=Math.atan(c.y/2/A),C=Math.cos(m),E=Math.cos(S),x=this.splatMesh.getSplatTree();if(x){o.copy(this.camera.matrixWorld).invert(),this.splatMesh.dynamicMode||o.multiply(this.splatMesh.matrixWorld);let T=0,R=0;for(let g=0;g<x.subTrees.length;g++){let I=x.subTrees[g];i.copy(o),this.splatMesh.dynamicMode&&(this.splatMesh.getSceneTransform(g,a),i.multiply(a));let w=I.nodesWithIndexes.length;for(let v=0;v<w;v++){let M=I.nodesWithIndexes[v];if(!M.data||!M.data.indexes||M.data.indexes.length===0)continue;r.copy(M.center).applyMatrix4(i);let b=r.length();r.normalize(),t.copy(r).setX(0).normalize(),n.copy(r).setY(0).normalize();let D=d.dot(n),L=d.dot(t),F=p(M),P=L<E-.6,z=D<C-.6;!h&&(z||P)&&b>F||(R+=M.data.indexes.length,e[T]=M,M.data.distanceToNode=b,T++)}}e.length=T,e.sort((g,I)=>g.data.distanceToNode<I.data.distanceToNode?-1:1);let y=R*j.BytesPerInt;for(let g=0;g<T;g++){let I=e[g],w=I.data.indexes.length,v=w*j.BytesPerInt;new Uint32Array(this.sortWorkerIndexesToSort.buffer,y-v,w).set(I.data.indexes),y-=v}return{splatRenderCount:R,shouldSortAll:!1}}else{let T=this.splatMesh.getSplatCount();if(!s||s.length!==T){s=new Uint32Array(T);for(let R=0;R<T;R++)s[R]=R}return this.sortWorkerIndexesToSort.set(s),{splatRenderCount:T,shouldSortAll:!0}}}}();getSplatMesh(){return this.splatMesh}getSplatScene(e){return this.splatMesh.getScene(e)}getSceneCount(){return this.splatMesh.getSceneCount()}isMobile(){return navigator.userAgent.includes("Mobi")}},xt=class l extends f.Group{constructor(e={}){super(),e.selfDrivenMode=!1,e.useBuiltInControls=!1,e.rootElement=null,e.dropInMode=!0,e.camera=void 0,e.renderer=void 0,this.viewer=new ps(e),this.splatMesh=null,this.updateSplatMesh(),this.callbackMesh=l.createCallbackMesh(),this.add(this.callbackMesh),this.callbackMesh.onBeforeRender=l.onBeforeRender.bind(this,this.viewer),this.viewer.onSplatMeshChanged(()=>{this.updateSplatMesh()})}updateSplatMesh(){this.splatMesh!==this.viewer.splatMesh&&(this.splatMesh&&this.remove(this.splatMesh),this.splatMesh=this.viewer.splatMesh,this.add(this.viewer.splatMesh))}addSplatScene(e,s={}){return s.showLoadingUI!==!1&&(s.showLoadingUI=!0),this.viewer.addSplatScene(e,s)}addSplatScenes(e,s){return s!==!1&&(s=!0),this.viewer.addSplatScenes(e,s)}getSplatScene(e){return this.viewer.getSplatScene(e)}removeSplatScene(e,s=!0){return this.viewer.removeSplatScene(e,s)}removeSplatScenes(e,s=!0){return this.viewer.removeSplatScenes(e,s)}getSceneCount(){return this.viewer.getSceneCount()}setActiveSphericalHarmonicsDegrees(e){this.viewer.setActiveSphericalHarmonicsDegrees(e)}async dispose(){return await this.viewer.dispose()}static onBeforeRender(e,s,t,n){e.update(s,n)}static createCallbackMesh(){let e=new f.SphereGeometry(1,8,8),s=new f.MeshBasicMaterial;s.colorWrite=!1,s.depthWrite=!1;let t=new f.Mesh(e,s);return t.frustumCulled=!1,t}};var Tt=class extends Be.Group{constructor(e,s,t,n){super(),this.loadGS(e,s,t,n)}loadGS(e,s,t=[0,0,0],n=[0,0,1,0]){Array.isArray(e)||(e=[e]),this.loadingPromise=new Promise(async(r,i)=>{let o=new xt({sharedMemoryForWorkers:!1,dynamicScene:!0,sceneRevealMode:2,sphericalHarmonicsDegree:2}),a=e.map(c=>({path:c,scale:[s,s,s],position:t,rotation:n,splatAlphaRemovalThreshold:0}));await o.addSplatScenes(a,!1),this.add(o),this.viewer=o,this.position0=new Be.Vector3(...t),this.quaternion0=new Be.Quaternion(...n),this.rotation0=new Be.Euler().setFromQuaternion(this.quaternion0),this.matrix0=new Be.Matrix4().compose(this.position0,this.quaternion0,new Be.Vector3(1,1,1)),r(this)},void 0,function(r){console.error(r)})}};var Rt=class{constructor(){this.header=null,this.vertexCount=0,this.properties=[],this.propertyTypes=new Map([["char",1],["uchar",1],["short",2],["ushort",2],["int",4],["uint",4],["float",4],["double",8]])}async parsePLY(e,s){let t;if(e.endsWith(".ply")||(s=!1),s)try{let T=await fetch(e,{method:"HEAD"});t=Number(T.headers.get("content-length"))}catch{let R=await fetch(e);t=Number(R.headers.get("content-length"))}else{let T=await fetch(e);t=Number(T.headers.get("content-length"))}let r=(await fetch(e)).body.getReader(),i=[],o=0;for(;;){let{done:T,value:R}=await r.read();if(T)break;i.push(R),o+=R.length;let y=document.getElementById("loaddisplay");if(y)if(t){let g=o/t*100;y.innerHTML=`${g.toFixed(1)}% (1/2)`}else y.innerHTML=`${o} bytes loaded (1/2)`}let a=document.getElementById("loaddisplay");a&&(a.innerHTML=`${100 .toFixed(1)}% (1/2)`);let c=new ArrayBuffer(o),d=new Uint8Array(c),u=0;for(let T of i)d.set(T,u),u+=T.length;let p=new DataView(c);u=0;let h="";for(;;){let T=p.getUint8(u++);if(h+=String.fromCharCode(T),h.includes(`end_header
906
+ `))break}let A=h.split(`
907
+ `);this.header=A.filter(T=>T.trim()!=="");let m="binary_little_endian";for(let T of this.header)if(T.startsWith("format"))m=T.split(" ")[1];else if(T.startsWith("element vertex"))this.vertexCount=parseInt(T.split(" ")[2]);else if(T.startsWith("property")){let R=T.split(" ");this.properties.push({type:R[1],name:R[2]})}let S=this.properties.reduce((T,R)=>T+this.propertyTypes.get(R.type),0),C=[],E=new Uint8Array(c.slice(u));for(let T=0;T<this.vertexCount;T++){let R={rawData:E.slice(T*S,(T+1)*S)},y=0;for(let g of this.properties){let I=this.propertyTypes.get(g.type),w;switch(g.type){case"float":w=p.getFloat32(u+y,!0);break}R[g.name]=w,y+=I}if(C.push(R),u+=S,T%1e4===0){let g=T/this.vertexCount*100,I=document.getElementById("loaddisplay");I&&await new Promise(w=>{requestAnimationFrame(()=>{I.innerHTML=`${g.toFixed(1)}% (2/2)`,w()})})}}let x=document.getElementById("loaddisplay");return x&&(x.innerHTML=`${100 .toFixed(1)}% (2/2)`),{header:this.header,vertices:C,vertexCount:this.vertexCount,vertexSize:S}}createPLYFile(e,s,t){let n=e.join(`
908
+ `)+`
909
+ `,i=new TextEncoder().encode(n),o=new Uint8Array(s.length*t);s.forEach((c,d)=>{o.set(c.rawData,d*t)});let a=new Uint8Array(i.length+o.length);return a.set(i,0),a.set(o,i.length),a}async splitPLY(e,s){let t=await this.parsePLY(e,!1),n=i=>t.header.map(o=>o.startsWith("element vertex")?`element vertex ${i}`:o),r=[];for(let[i,o]of Object.entries(s)){let a=o.map(u=>t.vertices[u]),c=this.createPLYFile(n(a.length),a,t.vertexSize),d=new Blob([c],{type:"application/octet-stream"});r.push(URL.createObjectURL(d))}return r}};import mn from"jszip";var An=class l extends Q.Group{constructor(e,s){super(),this.character=e,this.gs=s,this.debugAxes=new Map,this.isReady=!1,this.t=0}static async initVRM(e,s,t,n,r,i){i||(i=(await(await fetch("./assets/default.json")).json()).boneOperations),r||(r=1);let o=new ht(s,e,"",r,!0);await o.loadingPromise,o.skinnedMeshIndex=1,o.faceIndex=void 0,o.currentVrm.scene.children.length>4&&(o.skinnedMeshIndex=2,o.faceIndex=1);let a=o.currentVrm.scene.children[o.skinnedMeshIndex];if(vt(o,!1),dt(o,i),a.skeleton.update(),a.skeleton.computeBoneTexture(),a.geometry.computeVertexNormals(),o.skinnedMeshIndex===2){let A=o.currentVrm.humanoid.getRawBoneNode("head"),m=new Q.Bone;m.name="J_Bip_C_HeadTop_End",m.position.set(0,.2,-.05),m.updateMatrixWorld(!0),A.add(m),a.skeleton.bones.push(m),a.bind(new Q.Skeleton(a.skeleton.bones),a.matrixWorld)}n.render(s,t),a.bindMatrix0=a.bindMatrix.clone(),a.bindMatrixInverse0=a.bindMatrixInverse.clone();let c=a.skeleton.boneTexture.image.width,d=a.skeleton.boneTexture.image.height,u=a.skeleton.boneTexture.format,p=a.skeleton.boneTexture.type,h=a.skeleton.boneTexture.image.data.slice();return a.boneTexture0=new Q.DataTexture(h,c,d,u,p),a.boneTexture0.needsUpdate=!0,o}static async initGS(e,s,t,n){let r=await new Tt(e,1,s,t);return await r.loadingPromise,n.add(r),r.splatMesh=r.viewer.splatMesh,r.centers=r.splatMesh.splatDataTextures.baseData.centers,r.colors=r.splatMesh.splatDataTextures.baseData.colors,r.covariances=r.splatMesh.splatDataTextures.baseData.covariances,r.splatCount=r.splatMesh.geometry.attributes.splatIndex.array.length,r.centers0=new Float32Array(r.centers),r.colors0=new Float32Array(r.colors),r.covariances0=new Float32Array(r.covariances),r.splatMesh.updateDataTexturesFromBaseData(0,r.splatCount-1),r}static async load(e,s,t,n,r){console.log("Loading GVRM:",e);let i=await fetch(e),o=await mn.loadAsync(i.arrayBuffer()),a=await o.file("model.vrm").async("arraybuffer"),c=await o.file("model.ply").async("arraybuffer"),d=JSON.parse(await o.file("data.json").async("text")),u=new Blob([a],{type:"application/octet-stream"}),p=URL.createObjectURL(u),h=new Blob([c],{type:"application/octet-stream"}),A=URL.createObjectURL(h),m=d.modelScale,S=d.boneOperations;d.splatRelativePoses===void 0&&(d.splatRelativePoses=d.relativePoses);let C=await l.initVRM(p,s,t,n,m,S),{sceneSplatIndices:E,boneSceneMap:x}=l.sortSplatsByBones(d),R=await new Rt().splitPLY(A,E),y=await l.initGS(R,d.gsPosition,d.gsQuaternion,s),g=new l(C,y);g.modelScale=m,g.boneOperations=S,g.boneSceneMap=x,g.fileName=r,g.updatePMC(),bt(s,g.pmc),wt(g.pmc,!1),n.render(s,t),g.gs.splatVertexIndices=d.splatVertexIndices,g.gs.splatBoneIndices=d.splatBoneIndices,g.gs.splatRelativePoses=d.splatRelativePoses,l.gsCustomizeMaterial(C,y);for(let v=0;v<g.gs.splatCount;v++){let M=Math.sqrt(g.gs.splatRelativePoses[v*3+0]**2+g.gs.splatRelativePoses[v*3+1]**2+g.gs.splatRelativePoses[v*3+2]**2);(g.gs.splatBoneIndices[v]!==57&&M>.2||g.gs.splatBoneIndices[v]==21&&M>.1||g.gs.splatBoneIndices[v]==19&&M>.1||g.gs.splatBoneIndices[v]===57&&M>.3)&&(g.gs.colors[v*4+3]=0)}g.gs.splatMesh.updateDataTexturesFromBaseData(0,g.gs.splatCount-1);function I(v,M=0){v.children.forEach(function(b){b.isBone&&(["J_Bip_L_Hand","J_Bip_L_LowerArm","J_Bip_R_Hand","J_Bip_R_LowerArm","J_Bip_L_LowerLeg","J_Bip_L_Foot","J_Bip_R_LowerLeg","J_Bip_R_Foot","J_Bip_C_Neck","J_Bip_C_Spine","J_Bip_C_Chest","J_Bip_C_UpperChest","J_Bip_C_HeadTop_End","J_Bip_C_Head"].includes(b.name)&&(b.updateMatrix(),b.matrixWorld0=b.matrixWorld.clone()),I(b,M+1))})}let w=C.currentVrm.scene.children[0].children[0];return I(w,1),g.vrmWorldPosition0=new Q.Vector3,g.vrmWorldQuaternion0=new Q.Quaternion,C.currentVrm.scene.getWorldPosition(g.vrmWorldPosition0),C.currentVrm.scene.getWorldQuaternion(g.vrmWorldQuaternion0),g.isReady=!0,g}static async save(e,s,t,n,r,i,o=!1){let a=await fetch(s).then(A=>A.arrayBuffer()),c=await fetch(t).then(A=>A.arrayBuffer()),d={modelScale:r,boneOperations:n,gsQuaternion:e.gs.viewer.splatMesh.scenes[0].quaternion.toArray(),gsPosition:e.gs.viewer.splatMesh.scenes[0].position.toArray(),splatVertexIndices:e.gs.splatVertexIndices,splatBoneIndices:e.gs.splatBoneIndices,splatRelativePoses:e.gs.splatRelativePoses},u=new mn;u.file("model.vrm",a),u.file("model.ply",c),u.file("data.json",JSON.stringify(d,null,2));let p=await u.generateAsync({type:"blob"});if(!i&&t.endsWith(".ply")?i=t.split("/").pop().replace(".ply",".gvrm"):i||(i=t.split("/").pop()+".gvrm"),h(p,i),o){console.log("savePly!");let A=new Blob([c],{type:"application/octet-stream"}),m=i.replace(".gvrm","_processed.ply");h(A,m)}function h(A,m){let S=URL.createObjectURL(A),C=document.createElement("a");C.href=S,C.download=m,C.click(),A===p&&e.url&&URL.revokeObjectURL(e.url),A===p?e.url=S:URL.revokeObjectURL(S)}}static async remove(e,s){e.character&&(await e.character.leave(s),e.character=null),e.gs&&(await e.gs.viewer.dispose(),e.gs=null),e.pmc&&Mt(s,e.pmc)}async load(e,s,t,n,r=null){let i=await l.load(e,s,t,n,r);this.character=i.character,this.gs=i.gs,this.modelScale=i.modelScale,this.boneOperations=i.boneOperations,this.boneSceneMap=i.boneSceneMap,this.vertexSceneMap=i.vertexSceneMap,this.fileName=i.fileName,this.vrmWorldPosition0=i.vrmWorldPosition0,this.vrmWorldQuaternion0=i.vrmWorldQuaternion0,this.isReady=!0}async save(e,s,t,n,r,i=!1){await l.save(this,e,s,t,n,r,i)}async remove(e){this.isReady=!1,await l.remove(this,e)}async changeFBX(e){await this.character.changeFBX(e)}updatePMC(){let{pmc:e}=Ft(this.character);this.pmc=e}updateByBones(){let e=new Q.Vector3,s=new Q.Vector3,t=new Q.Vector3,n=new Q.Matrix4,r=new Q.Quaternion,i=new Q.Matrix4,o=new Q.Quaternion,a=new Q.Quaternion,c=["J_Bip_C_Neck","J_Bip_C_Spine","J_Bip_C_Chest","J_Bip_C_UpperChest","J_Bip_C_HeadTop_End","J_Bip_C_Head"],d=this.character.currentVrm.scene.children[2].skeleton;this.gs.viewer.updateMatrixWorld(),i.copy(this.gs.viewer.matrixWorld).invert(),this.gs.viewer.getWorldQuaternion(o),a.copy(o).invert(),d.bones.forEach(u=>{let p=u.children;p.length!==0&&p.forEach(h=>{let A=d.bones.indexOf(h),m=this.boneSceneMap[A];if(m===void 0)return;u.updateMatrixWorld(!0),h.updateMatrixWorld(!0),e.setFromMatrixPosition(u.matrixWorld),s.setFromMatrixPosition(h.matrixWorld),t.addVectors(e,s).multiplyScalar(.5),t.applyMatrix4(i),n.extractRotation(h.matrixWorld.multiply(h.matrixWorld0.clone().invert())),r.setFromRotationMatrix(n),r.premultiply(a),r.multiply(this.gs.quaternion0);let S=this.gs.viewer.getSplatScene(m);if(S){c.includes(h.name)||(S.position.copy(t),S.quaternion.copy(r));let C=this.debugAxes.get(m);C||(C=this.createDebugAxes(m)),C.position.copy(t),C.quaternion.copy(r)}})})}createDebugAxes(e){let s=new Q.AxesHelper(.3);return s.visible=!1,this.gs.add(s),this.debugAxes.set(e,s),s}update(){if(!this.isReady)return;let e=this.character.currentVrm.scene.quaternion.clone(),s=this.character.currentVrm.scene.quaternion0.clone(),t=this.character.currentVrm.scene.position.clone(),n=this.character.currentVrm.scene.position0.clone();this.gs.viewer.quaternion.copy(e.multiply(s.invert())),this.gs.viewer.position.copy(t.sub(n)),this.updateByBones(),this.character.update()}static sortSplatsByBones(e){let s={},t=0,n={};for(let r=0;r<e.splatBoneIndices.length;r++){let i=e.splatBoneIndices[r];n[i]===void 0&&(n[i]=t,t++,s[n[i]]=[]),s[n[i]].push(r)}return l.updateExtraData(e,s),{sceneSplatIndices:s,boneSceneMap:n}}static updateExtraData(e,s){let t=[];for(let o=0;o<Object.keys(s).length;o++)t=t.concat(s[o]);let n=[],r=[],i=[];for(let o of Object.keys(s))for(let a of s[o])n.push(e.splatVertexIndices[a]),r.push(e.splatBoneIndices[a]),i.push(e.splatRelativePoses[a*3],e.splatRelativePoses[a*3+1],e.splatRelativePoses[a*3+2]);e.splatVertexIndices=n,e.splatBoneIndices=r,e.splatRelativePoses=i}static gsCustomizeMaterial(e,s){s.splatMesh.material=s.splatMesh.material.clone(),s.splatMesh.material.needsUpdate=!0;let t=e.currentVrm.scene.children[e.skinnedMeshIndex],n=t.geometry.attributes.position.count,r=t.geometry.attributes.position.array,i=t.geometry.attributes.normal.array,o=t.geometry.attributes.skinIndex.array,a=t.geometry.attributes.skinWeight.array,c=s.splatVertexIndices,d=s.splatRelativePoses,u=new Float32Array(4096*1024*4),p=new Float32Array(4096*1024*4),h=new Float32Array(4096*1024*4),A=new Float32Array(4096*1024*4),m=new Float32Array(4096*1024*4),S=new Float32Array(4096*1024*4);Ne(r,u,n,1),Ne(i,p,n,1),h.set(o),A.set(a),Ne(c,m,s.splatCount,3),Ne(d,S,s.splatCount,1);let C=Oe(u,4096,1024,Q.RGBAFormat,Q.FloatType),E=Oe(p,4096,1024,Q.RGBAFormat,Q.FloatType),x=Oe(h,4096,1024,Q.RGBAFormat,Q.FloatType),T=Oe(A,4096,1024,Q.RGBAFormat,Q.FloatType),R=Oe(m,4096,1024,Q.RGBAFormat,Q.FloatType),y=Oe(S,4096,1024,Q.RGBAFormat,Q.FloatType);s.splatMesh.material.onBeforeCompile=function(g){g.uniforms.meshPositionTexture={value:C},g.uniforms.meshNormalTexture={value:E},g.uniforms.meshSkinIndexTexture={value:x},g.uniforms.meshSkinWeightTexture={value:T},g.uniforms.gsMeshVertexIndexTexture={value:R},g.uniforms.gsMeshRelativePosTexture={value:y},g.uniforms.bindMatrix0={value:t.bindMatrix0},g.uniforms.bindMatrix={value:t.bindMatrix},g.uniforms.bindMatrixInverse0={value:t.bindMatrixInverse0},g.uniforms.bindMatrixInverse={value:t.bindMatrixInverse},g.uniforms.boneTexture0={value:t.boneTexture0},g.uniforms.boneTexture={value:t.skeleton.boneTexture},g.uniforms.meshMatrixWorld={value:e.currentVrm.scene.matrixWorld},g.uniforms.gsMatrix0={value:s.matrix0},g.uniforms.gsMatrix={value:s.viewer.matrixWorld},g.vertexShader=g.vertexShader.replace("#include <common>",`
910
+ #define USE_SKINNING
911
+
912
+ #include <common>
913
+ #include <skinning_pars_vertex> // boneTexture
914
+
915
+ uniform sampler2D meshPositionTexture;
916
+ uniform sampler2D meshNormalTexture;
917
+ uniform sampler2D meshSkinIndexTexture;
918
+ uniform sampler2D meshSkinWeightTexture;
919
+ uniform sampler2D gsMeshVertexIndexTexture;
920
+ uniform sampler2D gsMeshRelativePosTexture;
921
+ uniform mat4 meshMatrixWorld;
922
+ uniform mat4 gsMatrix0;
923
+ uniform mat4 gsMatrix;
924
+
925
+ uniform mat4 bindMatrix0;
926
+ uniform mat4 bindMatrixInverse0;
927
+ uniform highp sampler2D boneTexture0;
928
+
929
+ mat4 getBoneMatrix0( const in float i ) {
930
+ int size = textureSize( boneTexture0, 0 ).x;
931
+ int j = int( i ) * 4;
932
+ int x = j % size;
933
+ int y = j / size;
934
+ vec4 v1 = texelFetch( boneTexture0, ivec2( x, y ), 0 );
935
+ vec4 v2 = texelFetch( boneTexture0, ivec2( x + 1, y ), 0 );
936
+ vec4 v3 = texelFetch( boneTexture0, ivec2( x + 2, y ), 0 );
937
+ vec4 v4 = texelFetch( boneTexture0, ivec2( x + 3, y ), 0 );
938
+ return mat4( v1, v2, v3, v4 );
939
+ }
940
+
941
+ // TODO: check this
942
+ vec4 quatFromMat3(mat3 m) {
943
+ float trace = m[0][0] + m[1][1] + m[2][2];
944
+ vec4 q;
945
+
946
+ if (trace > 0.0) {
947
+ float s = 0.5 / sqrt(trace + 1.0);
948
+ q.w = 0.25 / s;
949
+ q.x = (m[2][1] - m[1][2]) * s;
950
+ q.y = (m[0][2] - m[2][0]) * s;
951
+ q.z = (m[1][0] - m[0][1]) * s;
952
+ } else if (m[0][0] > m[1][1] && m[0][0] > m[2][2]) {
953
+ float s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);
954
+ q.w = (m[2][1] - m[1][2]) / s;
955
+ q.x = 0.25 * s;
956
+ q.y = (m[0][1] + m[1][0]) / s;
957
+ q.z = (m[0][2] + m[2][0]) / s;
958
+ } else if (m[1][1] > m[2][2]) {
959
+ float s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);
960
+ q.w = (m[0][2] - m[2][0]) / s;
961
+ q.x = (m[0][1] + m[1][0]) / s;
962
+ q.y = 0.25 * s;
963
+ q.z = (m[1][2] + m[2][1]) / s;
964
+ } else {
965
+ float s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);
966
+ q.w = (m[1][0] - m[0][1]) / s;
967
+ q.x = (m[0][2] + m[2][0]) / s;
968
+ q.y = (m[1][2] + m[2][1]) / s;
969
+ q.z = 0.25 * s;
970
+ }
971
+ return q;
972
+ }
973
+
974
+ vec4 quatInverse(vec4 q) {
975
+ return vec4(-q.x, -q.y, -q.z, q.w) / dot(q, q);
976
+ }
977
+
978
+ vec4 quatMultiply(vec4 a, vec4 b) {
979
+ return vec4(
980
+ a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y,
981
+ a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x,
982
+ a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w,
983
+ a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z
984
+ );
985
+ }
986
+
987
+ mat3 mat3FromQuat(vec4 q) {
988
+ float x = q.x, y = q.y, z = q.z, w = q.w;
989
+ float x2 = x + x, y2 = y + y, z2 = z + z;
990
+ float xx = x * x2, xy = x * y2, xz = x * z2;
991
+ float yy = y * y2, yz = y * z2, zz = z * z2;
992
+ float wx = w * x2, wy = w * y2, wz = w * z2;
993
+
994
+ return mat3(
995
+ 1.0 - (yy + zz), xy - wz, xz + wy,
996
+ xy + wz, 1.0 - (xx + zz), yz - wx,
997
+ xz - wy, yz + wx, 1.0 - (xx + yy)
998
+ );
999
+ }
1000
+ `),g.vertexShader=g.vertexShader.replace("mat4 transform = transforms[sceneIndex]","mat4 transform = gsMatrix * gsMatrix0;"),g.vertexShader=g.vertexShader.replace("vec3 splatCenter = uintBitsToFloat(uvec3(sampledCenterColor.gba));",`
1001
+ vec2 samplerUV2 = vec2(0.0, 0.0);
1002
+ float d2 = float(splatIndex) / 4096.0;
1003
+ samplerUV2.y = float(floor(d2)) / 1024.0;
1004
+ samplerUV2.x = fract(d2);
1005
+ float meshVertexIndex = texture2D(gsMeshVertexIndexTexture, samplerUV2).r;
1006
+ vec3 relativePos = texture2D(gsMeshRelativePosTexture, samplerUV2).rgb;
1007
+
1008
+ vec2 samplerUV3 = vec2(0.0, 0.0);
1009
+ float d3 = float(meshVertexIndex) / 4096.0;
1010
+ samplerUV3.y = float(floor(d3)) / 1024.0;
1011
+ samplerUV3.x = fract(d3);
1012
+ vec3 transformed = texture2D(meshPositionTexture, samplerUV3).rgb;
1013
+ vec3 objectNormal = texture2D(meshNormalTexture, samplerUV3).rgb;
1014
+ vec4 skinIndex = texture2D(meshSkinIndexTexture, samplerUV3);
1015
+ vec4 skinWeight = texture2D(meshSkinWeightTexture, samplerUV3);
1016
+
1017
+ mat4 boneMatX0 = getBoneMatrix0( skinIndex.x );
1018
+ mat4 boneMatY0 = getBoneMatrix0( skinIndex.y );
1019
+ mat4 boneMatZ0 = getBoneMatrix0( skinIndex.z );
1020
+ mat4 boneMatW0 = getBoneMatrix0( skinIndex.w );
1021
+ mat4 skinMatrix0 = mat4( 0.0 );
1022
+ skinMatrix0 += skinWeight.x * boneMatX0;
1023
+ skinMatrix0 += skinWeight.y * boneMatY0;
1024
+ skinMatrix0 += skinWeight.z * boneMatZ0;
1025
+ skinMatrix0 += skinWeight.w * boneMatW0;
1026
+ skinMatrix0 = bindMatrixInverse0 * skinMatrix0 * bindMatrix0;
1027
+
1028
+ #include <skinbase_vertex> // boneMat
1029
+ #include <skinnormal_vertex> // skinMatrix, using normal
1030
+ #include <defaultnormal_vertex> // ?
1031
+ #include <skinning_vertex>
1032
+
1033
+ // vec3 splatCenter = ( vec4(transformed, 1.0) ).xyz;
1034
+ // vec3 splatCenter = ( meshMatrixWorld * vec4(transformed, 1.0) ).xyz;
1035
+ // vec3 splatCenter = ( meshMatrixWorld * vec4(transformed + relativePos, 1.0) ).xyz; // GOOD
1036
+
1037
+ vec3 skinnedRelativePos = vec4( skinMatrix * inverse(skinMatrix0) * vec4( relativePos, 0.0 ) ).xyz;
1038
+ vec3 splatCenter = ( meshMatrixWorld * vec4(transformed + skinnedRelativePos, 1.0) ).xyz;
1039
+ `),g.vertexShader=g.vertexShader.replace("vec4 viewCenter = transformModelViewMatrix * vec4(splatCenter, 1.0);",`
1040
+ // The splatCenter is the coordinate system for inverse(transform).
1041
+ splatCenter = (inverse(transform) * vec4(splatCenter, 1.0)).xyz;
1042
+ vec4 viewCenter = transformModelViewMatrix * vec4(splatCenter, 1.0);
1043
+ `),g.vertexShader=g.vertexShader.replace("mat3 cov2Dm = transpose(T) * Vrk * T;",`
1044
+ // for debug
1045
+ // Vrk[0][0] *= 25.0; Vrk[1][1] *= 0.1; Vrk[2][2] *= 0.1;
1046
+ // Vrk[1][1] *= 25.0; Vrk[0][0] *= 0.1; Vrk[2][2] *= 0.1;
1047
+ // Vrk[2][2] *= 25.0; Vrk[0][0] *= 0.1; Vrk[1][1] *= 0.1;
1048
+
1049
+ // via quat
1050
+ mat3 gsRotation0 = mat3(gsMatrix0);
1051
+ mat3 skinRotationMatrix = mat3(skinMatrix * inverse(skinMatrix0));
1052
+ mat3 relativeRotation = transpose(gsRotation0) * skinRotationMatrix * gsRotation0;
1053
+ vec4 tempQuat = quatFromMat3(relativeRotation);
1054
+ tempQuat.y = -tempQuat.y; // Hardcode, maybe bug in quatFromMat3?
1055
+ relativeRotation = mat3FromQuat(tempQuat);
1056
+ mat3 rotatedVrk = transpose(relativeRotation) * Vrk * relativeRotation;
1057
+ mat3 cov2Dm = transpose(T) * rotatedVrk * T;
1058
+
1059
+ // TODO: via mat
1060
+ // mat3 gsRotation0 = mat3(gsMatrix0);
1061
+ // mat3 skinRotationMatrix = mat3(skinMatrix * inverse(skinMatrix0));
1062
+ // mat3 relativeRotation = transpose(gsRotation0) * skinRotationMatrix * gsRotation0;
1063
+ // mat3 rotatedVrk = transpose(relativeRotation) * Vrk * relativeRotation;
1064
+ // mat3 cov2Dm = transpose(T) * rotatedVrk * T;
1065
+ `)},s.splatMesh.material.needsUpdate=!0}};export{An as GVRM,Dt as GVRMUtils};