@needle-tools/engine 3.36.1-beta → 3.36.2-beta

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.
@@ -4341,7 +4341,7 @@ void main() {
4341
4341
  `;a+=r(o);const l=Object.keys(s);let c="";for(let u=0;u<l.length;u++){const d=l[u],p=s[d];if(ag.has(p)){c+="";continue}ag.set(p,!0),c+=d+":"+n(p,o+1),u<l.length-1&&(c+=", "),c.length>=60&&(c+=`
4342
4342
  `,c+=r(o),a+=c,c="")}return a+=c,a+=`
4343
4343
  }`,a}return s}function r(s){let o="";for(let a=0;a<s;a++)o+=" ";return o}}const dY=ee("nodevlogs");function $i(i,e=Ws.Log){Oa(e,i)}function Qi(i){$i(i,Ws.Warn)}function AE(i){$i(i,Ws.Error)}let yE;function pt(){return dY?!1:yE!==void 0?yE:Bs()}function pY(i){yE=i}const Eu=new Au,Hr=new S,Vc=new S,Hi=new Me,Fk={X:new S(1,0,0),Y:new S(0,1,0),Z:new S(0,0,1)},bE={type:"change"},Nk={type:"mouseDown"},zk={type:"mouseUp",mode:null},jk={type:"objectChange"};class fY extends ge{constructor(e,t){super(),t===void 0&&(console.warn('THREE.TransformControls: The second parameter "domElement" is now mandatory.'),t=document),this.isTransformControls=!0,this.visible=!1,this.domElement=t,this.domElement.style.touchAction="none";const n=new xE;this._gizmo=n,this.add(n);const r=new bY;this._plane=r,this.add(r);const s=this;function o(y,b){let _=b;Object.defineProperty(s,y,{get:function(){return _!==void 0?_:b},set:function(E){_!==E&&(_=E,r[y]=E,n[y]=E,s.dispatchEvent({type:y+"-changed",value:E}),s.dispatchEvent(bE))}}),s[y]=b,r[y]=b,n[y]=b}o("camera",e),o("object",void 0),o("enabled",!0),o("axis",null),o("mode","translate"),o("translationSnap",null),o("rotationSnap",null),o("scaleSnap",null),o("space","world"),o("size",1),o("dragging",!1),o("showX",!0),o("showY",!0),o("showZ",!0);const a=new S,l=new S,c=new Me,u=new Me,d=new S,p=new Me,f=new S,m=new S,A=new S,v=0,g=new S;o("worldPosition",a),o("worldPositionStart",l),o("worldQuaternion",c),o("worldQuaternionStart",u),o("cameraPosition",d),o("cameraQuaternion",p),o("pointStart",f),o("pointEnd",m),o("rotationAxis",A),o("rotationAngle",v),o("eye",g),this._offset=new S,this._startNorm=new S,this._endNorm=new S,this._cameraScale=new S,this._parentPosition=new S,this._parentQuaternion=new Me,this._parentQuaternionInv=new Me,this._parentScale=new S,this._worldScaleStart=new S,this._worldQuaternionInv=new Me,this._worldScale=new S,this._positionStart=new S,this._quaternionStart=new Me,this._scaleStart=new S,this._getPointer=mY.bind(this),this._onPointerDown=vY.bind(this),this._onPointerHover=gY.bind(this),this._onPointerMove=AY.bind(this),this._onPointerUp=yY.bind(this),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointermove",this._onPointerHover),this.domElement.addEventListener("pointerup",this._onPointerUp)}updateMatrixWorld(){this.object!==void 0&&(this.object.updateMatrixWorld(),this.object.parent===null?console.error("TransformControls: The attached 3D object must be a part of the scene graph."):this.object.parent.matrixWorld.decompose(this._parentPosition,this._parentQuaternion,this._parentScale),this.object.matrixWorld.decompose(this.worldPosition,this.worldQuaternion,this._worldScale),this._parentQuaternionInv.copy(this._parentQuaternion).invert(),this._worldQuaternionInv.copy(this.worldQuaternion).invert()),this.camera.updateMatrixWorld(),this.camera.matrixWorld.decompose(this.cameraPosition,this.cameraQuaternion,this._cameraScale),this.camera.isOrthographicCamera?this.camera.getWorldDirection(this.eye).negate():this.eye.copy(this.cameraPosition).sub(this.worldPosition).normalize(),super.updateMatrixWorld(this)}pointerHover(e){if(this.object===void 0||this.dragging===!0)return;e!==null&&Eu.setFromCamera(e,this.camera);const t=_E(this._gizmo.picker[this.mode],Eu);t?this.axis=t.object.name:this.axis=null}pointerDown(e){if(!(this.object===void 0||this.dragging===!0||e!=null&&e.button!==0)&&this.axis!==null){e!==null&&Eu.setFromCamera(e,this.camera);const t=_E(this._plane,Eu,!0);t&&(this.object.updateMatrixWorld(),this.object.parent.updateMatrixWorld(),this._positionStart.copy(this.object.position),this._quaternionStart.copy(this.object.quaternion),this._scaleStart.copy(this.object.scale),this.object.matrixWorld.decompose(this.worldPositionStart,this.worldQuaternionStart,this._worldScaleStart),this.pointStart.copy(t.point).sub(this.worldPositionStart)),this.dragging=!0,Nk.mode=this.mode,this.dispatchEvent(Nk)}}pointerMove(e){const t=this.axis,n=this.mode,r=this.object;let s=this.space;if(n==="scale"?s="local":(t==="E"||t==="XYZE"||t==="XYZ")&&(s="world"),r===void 0||t===null||this.dragging===!1||e!==null&&e.button!==-1)return;e!==null&&Eu.setFromCamera(e,this.camera);const o=_E(this._plane,Eu,!0);if(o){if(this.pointEnd.copy(o.point).sub(this.worldPositionStart),n==="translate")this._offset.copy(this.pointEnd).sub(this.pointStart),s==="local"&&t!=="XYZ"&&this._offset.applyQuaternion(this._worldQuaternionInv),t.indexOf("X")===-1&&(this._offset.x=0),t.indexOf("Y")===-1&&(this._offset.y=0),t.indexOf("Z")===-1&&(this._offset.z=0),s==="local"&&t!=="XYZ"?this._offset.applyQuaternion(this._quaternionStart).divide(this._parentScale):this._offset.applyQuaternion(this._parentQuaternionInv).divide(this._parentScale),r.position.copy(this._offset).add(this._positionStart),this.translationSnap&&(s==="local"&&(r.position.applyQuaternion(Hi.copy(this._quaternionStart).invert()),t.search("X")!==-1&&(r.position.x=Math.round(r.position.x/this.translationSnap)*this.translationSnap),t.search("Y")!==-1&&(r.position.y=Math.round(r.position.y/this.translationSnap)*this.translationSnap),t.search("Z")!==-1&&(r.position.z=Math.round(r.position.z/this.translationSnap)*this.translationSnap),r.position.applyQuaternion(this._quaternionStart)),s==="world"&&(r.parent&&r.position.add(Hr.setFromMatrixPosition(r.parent.matrixWorld)),t.search("X")!==-1&&(r.position.x=Math.round(r.position.x/this.translationSnap)*this.translationSnap),t.search("Y")!==-1&&(r.position.y=Math.round(r.position.y/this.translationSnap)*this.translationSnap),t.search("Z")!==-1&&(r.position.z=Math.round(r.position.z/this.translationSnap)*this.translationSnap),r.parent&&r.position.sub(Hr.setFromMatrixPosition(r.parent.matrixWorld))));else if(n==="scale"){if(t.search("XYZ")!==-1){let a=this.pointEnd.length()/this.pointStart.length();this.pointEnd.dot(this.pointStart)<0&&(a*=-1),Vc.set(a,a,a)}else Hr.copy(this.pointStart),Vc.copy(this.pointEnd),Hr.applyQuaternion(this._worldQuaternionInv),Vc.applyQuaternion(this._worldQuaternionInv),Vc.divide(Hr),t.search("X")===-1&&(Vc.x=1),t.search("Y")===-1&&(Vc.y=1),t.search("Z")===-1&&(Vc.z=1);r.scale.copy(this._scaleStart).multiply(Vc),this.scaleSnap&&(t.search("X")!==-1&&(r.scale.x=Math.round(r.scale.x/this.scaleSnap)*this.scaleSnap||this.scaleSnap),t.search("Y")!==-1&&(r.scale.y=Math.round(r.scale.y/this.scaleSnap)*this.scaleSnap||this.scaleSnap),t.search("Z")!==-1&&(r.scale.z=Math.round(r.scale.z/this.scaleSnap)*this.scaleSnap||this.scaleSnap))}else if(n==="rotate"){this._offset.copy(this.pointEnd).sub(this.pointStart);const a=20/this.worldPosition.distanceTo(Hr.setFromMatrixPosition(this.camera.matrixWorld));let l=!1;t==="XYZE"?(this.rotationAxis.copy(this._offset).cross(this.eye).normalize(),this.rotationAngle=this._offset.dot(Hr.copy(this.rotationAxis).cross(this.eye))*a):(t==="X"||t==="Y"||t==="Z")&&(this.rotationAxis.copy(Fk[t]),Hr.copy(Fk[t]),s==="local"&&Hr.applyQuaternion(this.worldQuaternion),Hr.cross(this.eye),Hr.length()===0?l=!0:this.rotationAngle=this._offset.dot(Hr.normalize())*a),(t==="E"||l)&&(this.rotationAxis.copy(this.eye),this.rotationAngle=this.pointEnd.angleTo(this.pointStart),this._startNorm.copy(this.pointStart).normalize(),this._endNorm.copy(this.pointEnd).normalize(),this.rotationAngle*=this._endNorm.cross(this._startNorm).dot(this.eye)<0?1:-1),this.rotationSnap&&(this.rotationAngle=Math.round(this.rotationAngle/this.rotationSnap)*this.rotationSnap),s==="local"&&t!=="E"&&t!=="XYZE"?(r.quaternion.copy(this._quaternionStart),r.quaternion.multiply(Hi.setFromAxisAngle(this.rotationAxis,this.rotationAngle)).normalize()):(this.rotationAxis.applyQuaternion(this._parentQuaternionInv),r.quaternion.copy(Hi.setFromAxisAngle(this.rotationAxis,this.rotationAngle)),r.quaternion.multiply(this._quaternionStart).normalize())}this.dispatchEvent(bE),this.dispatchEvent(jk)}}pointerUp(e){e!==null&&e.button!==0||(this.dragging&&this.axis!==null&&(zk.mode=this.mode,this.dispatchEvent(zk)),this.dragging=!1,this.axis=null)}dispose(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerHover),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.traverse(function(e){e.geometry&&e.geometry.dispose(),e.material&&e.material.dispose()})}attach(e){return this.object=e,this.visible=!0,this}detach(){return this.object=void 0,this.visible=!1,this.axis=null,this}reset(){this.enabled&&this.dragging&&(this.object.position.copy(this._positionStart),this.object.quaternion.copy(this._quaternionStart),this.object.scale.copy(this._scaleStart),this.dispatchEvent(bE),this.dispatchEvent(jk),this.pointStart.copy(this.pointEnd))}getRaycaster(){return Eu}getMode(){return this.mode}setMode(e){this.mode=e}setTranslationSnap(e){this.translationSnap=e}setRotationSnap(e){this.rotationSnap=e}setScaleSnap(e){this.scaleSnap=e}setSize(e){this.size=e}setSpace(e){this.space=e}}function mY(i){if(this.domElement.ownerDocument.pointerLockElement)return{x:0,y:0,button:i.button};{const e=this.domElement.getBoundingClientRect();return{x:(i.clientX-e.left)/e.width*2-1,y:-(i.clientY-e.top)/e.height*2+1,button:i.button}}}function gY(i){if(this.enabled)switch(i.pointerType){case"mouse":case"pen":this.pointerHover(this._getPointer(i));break}}function vY(i){this.enabled&&(document.pointerLockElement||this.domElement.setPointerCapture(i.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.pointerHover(this._getPointer(i)),this.pointerDown(this._getPointer(i)))}function AY(i){this.enabled&&this.pointerMove(this._getPointer(i))}function yY(i){this.enabled&&(this.domElement.releasePointerCapture(i.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.pointerUp(this._getPointer(i)))}function _E(i,e,t){const n=e.intersectObject(i,!0);for(let r=0;r<n.length;r++)if(n[r].object.visible||t)return n[r];return!1}const ub=new Fi,Mi=new S(0,1,0),Gk=new S(0,0,0),Qk=new Ce,db=new Me,pb=new Me,La=new S,Hk=new Ce,lg=new S(1,0,0),Mu=new S(0,1,0),cg=new S(0,0,1),fb=new S,hg=new S,ug=new S;class xE extends ge{constructor(){super(),this.isTransformControlsGizmo=!0,this.type="TransformControlsGizmo";const e=new oi({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),t=new vn({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),n=e.clone();n.opacity=.15;const r=t.clone();r.opacity=.5;const s=e.clone();s.color.setHex(16711680);const o=e.clone();o.color.setHex(65280);const a=e.clone();a.color.setHex(255);const l=e.clone();l.color.setHex(16711680),l.opacity=.5;const c=e.clone();c.color.setHex(65280),c.opacity=.5;const u=e.clone();u.color.setHex(255),u.opacity=.5;const d=e.clone();d.opacity=.25;const p=e.clone();p.color.setHex(16776960),p.opacity=.25,e.clone().color.setHex(16776960);const f=e.clone();f.color.setHex(7895160);const m=new Cn(0,.04,.1,12);m.translate(0,.05,0);const A=new Di(.08,.08,.08);A.translate(0,.04,0);const v=new ut;v.setAttribute("position",new ot([0,0,0,1,0,0],3));const g=new Cn(.0075,.0075,.5,3);g.translate(0,.25,0);function y(k,W){const U=new yc(k,.0075,3,64,W*Math.PI*2);return U.rotateY(Math.PI/2),U.rotateX(Math.PI/2),U}function b(){const k=new ut;return k.setAttribute("position",new ot([0,0,0,1,1,1],3)),k}const _={X:[[new ue(m,s),[.5,0,0],[0,0,-Math.PI/2]],[new ue(m,s),[-.5,0,0],[0,0,Math.PI/2]],[new ue(g,s),[0,0,0],[0,0,-Math.PI/2]]],Y:[[new ue(m,o),[0,.5,0]],[new ue(m,o),[0,-.5,0],[Math.PI,0,0]],[new ue(g,o)]],Z:[[new ue(m,a),[0,0,.5],[Math.PI/2,0,0]],[new ue(m,a),[0,0,-.5],[-Math.PI/2,0,0]],[new ue(g,a),null,[Math.PI/2,0,0]]],XYZ:[[new ue(new Ac(.1,0),d.clone()),[0,0,0]]],XY:[[new ue(new Di(.15,.15,.01),u.clone()),[.15,.15,0]]],YZ:[[new ue(new Di(.15,.15,.01),l.clone()),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new ue(new Di(.15,.15,.01),c.clone()),[.15,0,.15],[-Math.PI/2,0,0]]]},E={X:[[new ue(new Cn(.2,0,.6,4),n),[.3,0,0],[0,0,-Math.PI/2]],[new ue(new Cn(.2,0,.6,4),n),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new ue(new Cn(.2,0,.6,4),n),[0,.3,0]],[new ue(new Cn(.2,0,.6,4),n),[0,-.3,0],[0,0,Math.PI]]],Z:[[new ue(new Cn(.2,0,.6,4),n),[0,0,.3],[Math.PI/2,0,0]],[new ue(new Cn(.2,0,.6,4),n),[0,0,-.3],[-Math.PI/2,0,0]]],XYZ:[[new ue(new Ac(.2,0),n)]],XY:[[new ue(new Di(.2,.2,.01),n),[.15,.15,0]]],YZ:[[new ue(new Di(.2,.2,.01),n),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new ue(new Di(.2,.2,.01),n),[.15,0,.15],[-Math.PI/2,0,0]]]},I={START:[[new ue(new Ac(.01,2),r),null,null,null,"helper"]],END:[[new ue(new Ac(.01,2),r),null,null,null,"helper"]],DELTA:[[new An(b(),r),null,null,null,"helper"]],X:[[new An(v,r.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new An(v,r.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new An(v,r.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},T={XYZE:[[new ue(y(.5,1),f),null,[0,Math.PI/2,0]]],X:[[new ue(y(.5,.5),s)]],Y:[[new ue(y(.5,.5),o),null,[0,0,-Math.PI/2]]],Z:[[new ue(y(.5,.5),a),null,[0,Math.PI/2,0]]],E:[[new ue(y(.75,1),p),null,[0,Math.PI/2,0]]]},M={AXIS:[[new An(v,r.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]]},D={XYZE:[[new ue(new wa(.25,10,8),n)]],X:[[new ue(new yc(.5,.1,4,24),n),[0,0,0],[0,-Math.PI/2,-Math.PI/2]]],Y:[[new ue(new yc(.5,.1,4,24),n),[0,0,0],[Math.PI/2,0,0]]],Z:[[new ue(new yc(.5,.1,4,24),n),[0,0,0],[0,0,-Math.PI/2]]],E:[[new ue(new yc(.75,.1,2,24),n)]]},C={X:[[new ue(A,s),[.5,0,0],[0,0,-Math.PI/2]],[new ue(g,s),[0,0,0],[0,0,-Math.PI/2]],[new ue(A,s),[-.5,0,0],[0,0,Math.PI/2]]],Y:[[new ue(A,o),[0,.5,0]],[new ue(g,o)],[new ue(A,o),[0,-.5,0],[0,0,Math.PI]]],Z:[[new ue(A,a),[0,0,.5],[Math.PI/2,0,0]],[new ue(g,a),[0,0,0],[Math.PI/2,0,0]],[new ue(A,a),[0,0,-.5],[-Math.PI/2,0,0]]],XY:[[new ue(new Di(.15,.15,.01),u),[.15,.15,0]]],YZ:[[new ue(new Di(.15,.15,.01),l),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new ue(new Di(.15,.15,.01),c),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new ue(new Di(.1,.1,.1),d.clone())]]},P={X:[[new ue(new Cn(.2,0,.6,4),n),[.3,0,0],[0,0,-Math.PI/2]],[new ue(new Cn(.2,0,.6,4),n),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new ue(new Cn(.2,0,.6,4),n),[0,.3,0]],[new ue(new Cn(.2,0,.6,4),n),[0,-.3,0],[0,0,Math.PI]]],Z:[[new ue(new Cn(.2,0,.6,4),n),[0,0,.3],[Math.PI/2,0,0]],[new ue(new Cn(.2,0,.6,4),n),[0,0,-.3],[-Math.PI/2,0,0]]],XY:[[new ue(new Di(.2,.2,.01),n),[.15,.15,0]]],YZ:[[new ue(new Di(.2,.2,.01),n),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new ue(new Di(.2,.2,.01),n),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new ue(new Di(.2,.2,.2),n),[0,0,0]]]},G={X:[[new An(v,r.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new An(v,r.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new An(v,r.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]};function Q(k){const W=new ge;for(const U in k)for(let F=k[U].length;F--;){const z=k[U][F][0].clone(),Z=k[U][F][1],K=k[U][F][2],se=k[U][F][3],Ae=k[U][F][4];z.name=U,z.tag=Ae,Z&&z.position.set(Z[0],Z[1],Z[2]),K&&z.rotation.set(K[0],K[1],K[2]),se&&z.scale.set(se[0],se[1],se[2]),z.updateMatrix();const Re=z.geometry.clone();Re.applyMatrix4(z.matrix),z.geometry=Re,z.renderOrder=1/0,z.position.set(0,0,0),z.rotation.set(0,0,0),z.scale.set(1,1,1),W.add(z)}return W}this.gizmo={},this.picker={},this.helper={},this.add(this.gizmo.translate=Q(_)),this.add(this.gizmo.rotate=Q(T)),this.add(this.gizmo.scale=Q(C)),this.add(this.picker.translate=Q(E)),this.add(this.picker.rotate=Q(D)),this.add(this.picker.scale=Q(P)),this.add(this.helper.translate=Q(I)),this.add(this.helper.rotate=Q(M)),this.add(this.helper.scale=Q(G)),this.picker.translate.visible=!1,this.picker.rotate.visible=!1,this.picker.scale.visible=!1}updateMatrixWorld(e){const t=(this.mode==="scale"?"local":this.space)==="local"?this.worldQuaternion:pb;this.gizmo.translate.visible=this.mode==="translate",this.gizmo.rotate.visible=this.mode==="rotate",this.gizmo.scale.visible=this.mode==="scale",this.helper.translate.visible=this.mode==="translate",this.helper.rotate.visible=this.mode==="rotate",this.helper.scale.visible=this.mode==="scale";let n=[];n=n.concat(this.picker[this.mode].children),n=n.concat(this.gizmo[this.mode].children),n=n.concat(this.helper[this.mode].children);for(let r=0;r<n.length;r++){const s=n[r];s.visible=!0,s.rotation.set(0,0,0),s.position.copy(this.worldPosition);let o;if(this.camera.isOrthographicCamera?o=(this.camera.top-this.camera.bottom)/this.camera.zoom:o=this.worldPosition.distanceTo(this.cameraPosition)*Math.min(1.9*Math.tan(Math.PI*this.camera.fov/360)/this.camera.zoom,7),s.scale.set(1,1,1).multiplyScalar(o*this.size/4),s.tag==="helper"){s.visible=!1,s.name==="AXIS"?(s.visible=!!this.axis,this.axis==="X"&&(Hi.setFromEuler(ub.set(0,0,0)),s.quaternion.copy(t).multiply(Hi),Math.abs(Mi.copy(lg).applyQuaternion(t).dot(this.eye))>.9&&(s.visible=!1)),this.axis==="Y"&&(Hi.setFromEuler(ub.set(0,0,Math.PI/2)),s.quaternion.copy(t).multiply(Hi),Math.abs(Mi.copy(Mu).applyQuaternion(t).dot(this.eye))>.9&&(s.visible=!1)),this.axis==="Z"&&(Hi.setFromEuler(ub.set(0,Math.PI/2,0)),s.quaternion.copy(t).multiply(Hi),Math.abs(Mi.copy(cg).applyQuaternion(t).dot(this.eye))>.9&&(s.visible=!1)),this.axis==="XYZE"&&(Hi.setFromEuler(ub.set(0,Math.PI/2,0)),Mi.copy(this.rotationAxis),s.quaternion.setFromRotationMatrix(Qk.lookAt(Gk,Mi,Mu)),s.quaternion.multiply(Hi),s.visible=this.dragging),this.axis==="E"&&(s.visible=!1)):s.name==="START"?(s.position.copy(this.worldPositionStart),s.visible=this.dragging):s.name==="END"?(s.position.copy(this.worldPosition),s.visible=this.dragging):s.name==="DELTA"?(s.position.copy(this.worldPositionStart),s.quaternion.copy(this.worldQuaternionStart),Hr.set(1e-10,1e-10,1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1),Hr.applyQuaternion(this.worldQuaternionStart.clone().invert()),s.scale.copy(Hr),s.visible=this.dragging):(s.quaternion.copy(t),this.dragging?s.position.copy(this.worldPositionStart):s.position.copy(this.worldPosition),this.axis&&(s.visible=this.axis.search(s.name)!==-1));continue}s.quaternion.copy(t),this.mode==="translate"||this.mode==="scale"?(s.name==="X"&&Math.abs(Mi.copy(lg).applyQuaternion(t).dot(this.eye))>.99&&(s.scale.set(1e-10,1e-10,1e-10),s.visible=!1),s.name==="Y"&&Math.abs(Mi.copy(Mu).applyQuaternion(t).dot(this.eye))>.99&&(s.scale.set(1e-10,1e-10,1e-10),s.visible=!1),s.name==="Z"&&Math.abs(Mi.copy(cg).applyQuaternion(t).dot(this.eye))>.99&&(s.scale.set(1e-10,1e-10,1e-10),s.visible=!1),s.name==="XY"&&Math.abs(Mi.copy(cg).applyQuaternion(t).dot(this.eye))<.2&&(s.scale.set(1e-10,1e-10,1e-10),s.visible=!1),s.name==="YZ"&&Math.abs(Mi.copy(lg).applyQuaternion(t).dot(this.eye))<.2&&(s.scale.set(1e-10,1e-10,1e-10),s.visible=!1),s.name==="XZ"&&Math.abs(Mi.copy(Mu).applyQuaternion(t).dot(this.eye))<.2&&(s.scale.set(1e-10,1e-10,1e-10),s.visible=!1)):this.mode==="rotate"&&(db.copy(t),Mi.copy(this.eye).applyQuaternion(Hi.copy(t).invert()),s.name.search("E")!==-1&&s.quaternion.setFromRotationMatrix(Qk.lookAt(this.eye,Gk,Mu)),s.name==="X"&&(Hi.setFromAxisAngle(lg,Math.atan2(-Mi.y,Mi.z)),Hi.multiplyQuaternions(db,Hi),s.quaternion.copy(Hi)),s.name==="Y"&&(Hi.setFromAxisAngle(Mu,Math.atan2(Mi.x,Mi.z)),Hi.multiplyQuaternions(db,Hi),s.quaternion.copy(Hi)),s.name==="Z"&&(Hi.setFromAxisAngle(cg,Math.atan2(Mi.y,Mi.x)),Hi.multiplyQuaternions(db,Hi),s.quaternion.copy(Hi))),s.visible=s.visible&&(s.name.indexOf("X")===-1||this.showX),s.visible=s.visible&&(s.name.indexOf("Y")===-1||this.showY),s.visible=s.visible&&(s.name.indexOf("Z")===-1||this.showZ),s.visible=s.visible&&(s.name.indexOf("E")===-1||this.showX&&this.showY&&this.showZ),s.material._color=s.material._color||s.material.color.clone(),s.material._opacity=s.material._opacity||s.material.opacity,s.material.color.copy(s.material._color),s.material.opacity=s.material._opacity,this.enabled&&this.axis&&(s.name===this.axis||this.axis.split("").some(function(a){return s.name===a}))&&(s.material.color.setHex(16776960),s.material.opacity=1)}super.updateMatrixWorld(e)}}class bY extends ue{constructor(){super(new Un(1e5,1e5,2,2),new oi({visible:!1,wireframe:!0,side:hi,transparent:!0,opacity:.1,toneMapped:!1})),this.isTransformControlsPlane=!0,this.type="TransformControlsPlane"}updateMatrixWorld(e){let t=this.space;switch(this.position.copy(this.worldPosition),this.mode==="scale"&&(t="local"),fb.copy(lg).applyQuaternion(t==="local"?this.worldQuaternion:pb),hg.copy(Mu).applyQuaternion(t==="local"?this.worldQuaternion:pb),ug.copy(cg).applyQuaternion(t==="local"?this.worldQuaternion:pb),Mi.copy(hg),this.mode){case"translate":case"scale":switch(this.axis){case"X":Mi.copy(this.eye).cross(fb),La.copy(fb).cross(Mi);break;case"Y":Mi.copy(this.eye).cross(hg),La.copy(hg).cross(Mi);break;case"Z":Mi.copy(this.eye).cross(ug),La.copy(ug).cross(Mi);break;case"XY":La.copy(ug);break;case"YZ":La.copy(fb);break;case"XZ":Mi.copy(ug),La.copy(hg);break;case"XYZ":case"E":La.set(0,0,0);break}break;case"rotate":default:La.set(0,0,0)}La.length()===0?this.quaternion.copy(this.cameraQuaternion):(Hk.lookAt(Hr.set(0,0,0),La,Mi),this.quaternion.setFromRotationMatrix(Hk)),super.updateMatrixWorld(e)}}const _Y=ee("debugpatch");function mb(i,e,t,n){const r=_Y===e;if(!t&&!n)return;const s=e+"___needle";wY(i,e,t,n);const o=Object.getOwnPropertyDescriptor(i,e),a=i[e];r&&console.log("Patch",i.constructor.name,e,o,a),o?(r&&console.log("Apply patch with existing descriptor",i.constructor.name,e,o),typeof o.value=="function"&&(i[e]=Wk(o.value,i,e))):(r&&console.log("Create patch with new property",i.constructor.name,e,o),Object.defineProperty(i,e,{set:function(l){if(typeof l=="function")this[s]=Wk(l,i,e);else{const c=this[s];qk(i,e,this,c,l),this[s]=l,Xk(i,e,this,c,l)}},get:function(){const l=this[s];return typeof l=="function"&&l[s]?l[s]:l}}))}function xY(i,e,t){const n=SE(i,e);if(n)for(let r=n.length-1;r>=0;r--){const s=n[r];s.prefix===t&&(s.prefix=null),s.postfix===t&&(s.postfix=null),!s.prefix&&!s.postfix&&n.splice(r,1)}}const Vk=Symbol("Needle:Patches:WrappedFunction");function Wk(i,e,t){if(i[Vk])return i;const n=function(...r){qk(e,t,this,...r);const s=i.apply(this,r);return Xk(e,t,this,s,...r),s};return n[Vk]=!0,n}const gb="Needle:Patches";function wE(){return globalThis[gb]||(globalThis[gb]=new WeakMap),globalThis[gb]}function SE(i,e){const t=wE().get(i);return t?t.get(e):null}function wY(i,e,t,n){let r=wE().get(i);r||(r=new Map,wE().set(i,r));let s=r.get(e);s||(s=[],r.set(e,s)),s.push({prefix:t,postfix:n})}function qk(i,e,t,...n){var r;if(!t)return;const s=SE(i,e);if(s)for(const o of s)(r=o.prefix)==null||r.call(t,...n)}function Xk(i,e,t,n,...r){var s;if(!t)return;const o=SE(i,e);if(o)for(const a of o)(s=a.postfix)==null||s.call(t,n,...r)}const Yk=Symbol("gltf-loader-internal-usage-tracker"),SY=ee("debugusers"),vb=class{constructor(i){h(this,"parser"),h(this,"_getDependency"),h(this,"_loadingId"),h(this,"_loadedObjects",new Set),this.parser=i,this._getDependency=this.parser.getDependency,this._loadingId=Date.now().toString()}get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(i){return vb._loadingProcesses>0}beforeRoot(){vb._loadingProcesses++;const i=this,e=this._getDependency;return this.parser.getDependency=function(t,n){const r=e.call(this,t,n);return r.then(s=>(s&&(i._loadedObjects.add(s),s[Yk]=i._loadingId),s)),r},null}afterRoot(i){vb._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const e of this._loadedObjects)delete e[Yk],e instanceof ge&&(e.parent||e instanceof ue&&setTimeout(()=>{SY&&console.warn("> GLTF LOADER: Mesh not used in scene!",e),e.material=null,e.geometry=null},1e3));return null}};let CE=vb;h(CE,"_loadingProcesses",0);class Jk{constructor(){window.addEventListener("unhandledrejection",e=>{var t;if(e.defaultPrevented)return;const n=(t=e?.reason)==null?void 0:t.path;if(n){const r=n[0];r&&r.tagName==="IMG"&&(console.warn(`Could not load image:
4344
- `+r.src),e.preventDefault())}})}}const Ab=ee("trackresources");function Kk(){return Ab==="dispose"}let Tu=!0;Ab===0&&(Tu=!1);function CY(i){Tu=i}function Zk(){return Tu}const $k=Symbol("disposable");function EE(i,e){i&&(i[$k]=e,Iu&&console.warn("Set disposable",e,i))}const eL=Symbol("disposed");function EY(i){return i[eL]===!0}function Ii(i){var e;if(i){if(i[$k]===!1){Iu&&console.warn("Object is marked as not disposable",i);return}if(i[eL]=!0,i instanceof jr)Ii(i.environment),Ii(i.background),Ii(i.customDepthMaterial),Ii(i.customDistanceMaterial);else if(i instanceof Ao)Ii(i.geometry),Ii(i.material),Ii(i.skeleton),Ii(i.bindMatrix),Ii(i.bindMatrixInverse),Ii(i.customDepthMaterial),Ii(i.customDistanceMaterial),i.geometry=null,i.material=null;else if(i instanceof ue)Ii(i.geometry),Ii(i.material),Ii(i.customDepthMaterial),Ii(i.customDistanceMaterial),i.geometry=null,i.material=null;else if(i instanceof ut){Tp(i);for(const t of Object.keys(i.attributes)){const n=i.attributes[t];Ii(n)}}else if(i instanceof $e||i instanceof Cs)Iu&&console.warn("BufferAttribute dispose not supported",i.count);else if(i instanceof Array)for(const t of i)t instanceof It&&Ii(t);else if(i instanceof It){Tp(i);for(const n of Object.keys(i)){const r=i[n];r instanceof gt&&(Ii(r),i[n]=null)}const t=i.uniforms;if(t)for(const n of Object.keys(t)){const r=t[n];r instanceof gt?(Ii(r),t[n]=null):r instanceof be&&(Ii(r.value),r.value=null)}}else i instanceof gt?(Tp(i),Tp(i.source),((e=i.source)==null?void 0:e.data)instanceof ImageBitmap&&Tp(i.source.data)):i instanceof $f?(Tp(i.boneTexture),i.boneTexture=null):i instanceof Om||!(i instanceof ge)&&Iu&&console.warn("Unknown object type",i)}}function Tp(i){i&&((Iu||Kk()||Ab)&&console.warn("\u{1F9E8} FREE",i),i instanceof ImageBitmap?i.close():i instanceof wl?i.data=null:i.dispose())}function tL(i){(i instanceof ue||i instanceof Ao)&&(i.material=null,i.geometry=null)}const MY=new Set;function yb(i,e,t=null,n){if(n||(n=MY,n.clear()),!i)return n;const r=i[dg];if(r)for(const s of r)n.has(s)||t?.call(null,s)!==!1&&(n.add(s),e&&yb(s,!0,t,n));return n}function TY(i){return i[pg]}const Iu=ee("debugresourceusers")||ee("debugmemory"),dg=Symbol("needle-resource-users"),pg=Symbol("needle-resource-users-count");function hs(i,e){mb(i,e,function(t,n){Tu&&(bb(dg,this,t,!1),bb(dg,this,n,!0))})}Tu&&(hs(ue.prototype,"material"),hs(ue.prototype,"geometry"),hs(It.prototype,"map"),hs(It.prototype,"bumpMap"),hs(It.prototype,"alphaMap"),hs(It.prototype,"normalMap"),hs(It.prototype,"displacementMap"),hs(It.prototype,"roughnessMap"),hs(It.prototype,"metalnessMap"),hs(It.prototype,"emissiveMap"),hs(It.prototype,"specularMap"),hs(It.prototype,"envMap"),hs(It.prototype,"lightMap"),hs(It.prototype,"aoMap"),hs(It.prototype,"gradientMap"));function IY(i){if(Tu===!1)return;const e=i[dg];if(e)for(const t of e)bb(dg,t,i,!1)}Tu&&mb(It.prototype,"dispose",function(){IY(this)});let ME=0;function bb(i,e,t,n){if(ME>0)return;if(Array.isArray(t)){for(const s of t)bb(i,e,s,n);return}if(!t)return;let r=t[i];if(r||(r=new Set),n){if(e&&!r.has(e)){r.add(e);let s=t[pg]||0;s+=1,t[pg]=s,Iu&&console.warn(`\u{1F7E2} Added user of "${t.type}"`,e,t,s,"users:",r)}}else if(e&&r.has(e)){r.delete(e);let s=t[pg]||0;s>0&&(s-=1,t[pg]=s),Iu&&console.warn(`\u{1F534} Removed user of "${t.type}"`,e,t,s,"users:",r),s<=0&&(CE.isLoading(t)||(Ab&&console.warn(`\u{1F534} Removed all user of "${t.type}"`,t),Kk()&&Ii(t)))}t[i]=r}try{mb(Pl.prototype,"render",function(){ME++},function(){ME--})}catch(i){console.warn("Could not wrap WebGLRenderer.render",i)}var fg=(i=>(i.Added="component-added",i.Removing="removing-component",i))(fg||{});const iL=ee("debugcomponentevents");class mg{static addComponentLifecylceEventListener(e,t){this.eventListeners.has(e)&&this.eventListeners.set(e,[]);let n=this.eventListeners.get(e);n||(n=[]),n.push(t),this.eventListeners.set(e,n),iL&&console.log("Added event listener for "+e,this.eventListeners)}static removeComponentLifecylceEventListener(e,t){const n=this.eventListeners.get(e);if(!n)return;const r=n.indexOf(t);r<0||n.splice(r,1)}static dispatchComponentLifecycleEvent(e,t){const n=this.eventListeners.get(e);if(iL&&console.log("Dispatching event "+e,n),!!n)for(const r of n)r(t)}}h(mg,"eventListeners",new Map);const nL=ee("debugdefines");Ip('if(!globalThis[""3.36.1-beta""]) globalThis[""3.36.1-beta""] = "0.0.0";'),Ip('if(!globalThis[""undefined""]) globalThis[""undefined""] = "unknown";'),Ip('if(!globalThis[""Wed Apr 03 2024 09:14:19 GMT+0200 (Central European Summer Time)""]) globalThis[""Wed Apr 03 2024 09:14:19 GMT+0200 (Central European Summer Time)""] = "unknown";'),Ip('globalThis["__NEEDLE_ENGINE_VERSION__"] = "3.36.1-beta";'),Ip('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),Ip('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Wed Apr 03 2024 09:14:19 GMT+0200 (Central European Summer Time)";');const Fl="3.36.1-beta",_b="undefined",TE="Wed Apr 03 2024 09:14:19 GMT+0200 (Central European Summer Time)";nL&&console.log(`Engine version: ${Fl} (generator: ${_b})
4344
+ `+r.src),e.preventDefault())}})}}const Ab=ee("trackresources");function Kk(){return Ab==="dispose"}let Tu=!0;Ab===0&&(Tu=!1);function CY(i){Tu=i}function Zk(){return Tu}const $k=Symbol("disposable");function EE(i,e){i&&(i[$k]=e,Iu&&console.warn("Set disposable",e,i))}const eL=Symbol("disposed");function EY(i){return i[eL]===!0}function Ii(i){var e;if(i){if(i[$k]===!1){Iu&&console.warn("Object is marked as not disposable",i);return}if(i[eL]=!0,i instanceof jr)Ii(i.environment),Ii(i.background),Ii(i.customDepthMaterial),Ii(i.customDistanceMaterial);else if(i instanceof Ao)Ii(i.geometry),Ii(i.material),Ii(i.skeleton),Ii(i.bindMatrix),Ii(i.bindMatrixInverse),Ii(i.customDepthMaterial),Ii(i.customDistanceMaterial),i.geometry=null,i.material=null;else if(i instanceof ue)Ii(i.geometry),Ii(i.material),Ii(i.customDepthMaterial),Ii(i.customDistanceMaterial),i.geometry=null,i.material=null;else if(i instanceof ut){Tp(i);for(const t of Object.keys(i.attributes)){const n=i.attributes[t];Ii(n)}}else if(i instanceof $e||i instanceof Cs)Iu&&console.warn("BufferAttribute dispose not supported",i.count);else if(i instanceof Array)for(const t of i)t instanceof It&&Ii(t);else if(i instanceof It){Tp(i);for(const n of Object.keys(i)){const r=i[n];r instanceof gt&&(Ii(r),i[n]=null)}const t=i.uniforms;if(t)for(const n of Object.keys(t)){const r=t[n];r instanceof gt?(Ii(r),t[n]=null):r instanceof be&&(Ii(r.value),r.value=null)}}else i instanceof gt?(Tp(i),Tp(i.source),((e=i.source)==null?void 0:e.data)instanceof ImageBitmap&&Tp(i.source.data)):i instanceof $f?(Tp(i.boneTexture),i.boneTexture=null):i instanceof Om||!(i instanceof ge)&&Iu&&console.warn("Unknown object type",i)}}function Tp(i){i&&((Iu||Kk()||Ab)&&console.warn("\u{1F9E8} FREE",i),i instanceof ImageBitmap?i.close():i instanceof wl?i.data=null:i.dispose())}function tL(i){(i instanceof ue||i instanceof Ao)&&(i.material=null,i.geometry=null)}const MY=new Set;function yb(i,e,t=null,n){if(n||(n=MY,n.clear()),!i)return n;const r=i[dg];if(r)for(const s of r)n.has(s)||t?.call(null,s)!==!1&&(n.add(s),e&&yb(s,!0,t,n));return n}function TY(i){return i[pg]}const Iu=ee("debugresourceusers")||ee("debugmemory"),dg=Symbol("needle-resource-users"),pg=Symbol("needle-resource-users-count");function hs(i,e){mb(i,e,function(t,n){Tu&&(bb(dg,this,t,!1),bb(dg,this,n,!0))})}Tu&&(hs(ue.prototype,"material"),hs(ue.prototype,"geometry"),hs(It.prototype,"map"),hs(It.prototype,"bumpMap"),hs(It.prototype,"alphaMap"),hs(It.prototype,"normalMap"),hs(It.prototype,"displacementMap"),hs(It.prototype,"roughnessMap"),hs(It.prototype,"metalnessMap"),hs(It.prototype,"emissiveMap"),hs(It.prototype,"specularMap"),hs(It.prototype,"envMap"),hs(It.prototype,"lightMap"),hs(It.prototype,"aoMap"),hs(It.prototype,"gradientMap"));function IY(i){if(Tu===!1)return;const e=i[dg];if(e)for(const t of e)bb(dg,t,i,!1)}Tu&&mb(It.prototype,"dispose",function(){IY(this)});let ME=0;function bb(i,e,t,n){if(ME>0)return;if(Array.isArray(t)){for(const s of t)bb(i,e,s,n);return}if(!t)return;let r=t[i];if(r||(r=new Set),n){if(e&&!r.has(e)){r.add(e);let s=t[pg]||0;s+=1,t[pg]=s,Iu&&console.warn(`\u{1F7E2} Added user of "${t.type}"`,e,t,s,"users:",r)}}else if(e&&r.has(e)){r.delete(e);let s=t[pg]||0;s>0&&(s-=1,t[pg]=s),Iu&&console.warn(`\u{1F534} Removed user of "${t.type}"`,e,t,s,"users:",r),s<=0&&(CE.isLoading(t)||(Ab&&console.warn(`\u{1F534} Removed all user of "${t.type}"`,t),Kk()&&Ii(t)))}t[i]=r}try{mb(Pl.prototype,"render",function(){ME++},function(){ME--})}catch(i){console.warn("Could not wrap WebGLRenderer.render",i)}var fg=(i=>(i.Added="component-added",i.Removing="removing-component",i))(fg||{});const iL=ee("debugcomponentevents");class mg{static addComponentLifecylceEventListener(e,t){this.eventListeners.has(e)&&this.eventListeners.set(e,[]);let n=this.eventListeners.get(e);n||(n=[]),n.push(t),this.eventListeners.set(e,n),iL&&console.log("Added event listener for "+e,this.eventListeners)}static removeComponentLifecylceEventListener(e,t){const n=this.eventListeners.get(e);if(!n)return;const r=n.indexOf(t);r<0||n.splice(r,1)}static dispatchComponentLifecycleEvent(e,t){const n=this.eventListeners.get(e);if(iL&&console.log("Dispatching event "+e,n),!!n)for(const r of n)r(t)}}h(mg,"eventListeners",new Map);const nL=ee("debugdefines");Ip('if(!globalThis[""3.36.2-beta""]) globalThis[""3.36.2-beta""] = "0.0.0";'),Ip('if(!globalThis[""undefined""]) globalThis[""undefined""] = "unknown";'),Ip('if(!globalThis[""Wed Apr 03 2024 13:37:08 GMT+0200 (Central European Summer Time)""]) globalThis[""Wed Apr 03 2024 13:37:08 GMT+0200 (Central European Summer Time)""] = "unknown";'),Ip('globalThis["__NEEDLE_ENGINE_VERSION__"] = "3.36.2-beta";'),Ip('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),Ip('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Wed Apr 03 2024 13:37:08 GMT+0200 (Central European Summer Time)";');const Fl="3.36.2-beta",_b="undefined",TE="Wed Apr 03 2024 13:37:08 GMT+0200 (Central European Summer Time)";nL&&console.log(`Engine version: ${Fl} (generator: ${_b})
4345
4345
  Project built at ${TE}`);const Nl="needle_isActiveInHierarchy",Ru="builtin_components",gg="needle_editor_guid";function Ip(i){try{(0,eval)(i)}catch(e){nL&&console.error(e)}}const vg=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),rL=Symbol("isUsingInstancing"),sL=Symbol("instancingRenderer"),Ag=Symbol("instancingAutoUpdateBounds");class qo{static isUsingInstancing(e){return e[rL]===!0}static getRenderer(e){return e[sL]||null}setAutoUpdateBounds(e,t){const n=qo.getRenderer(e);n&&(n[Ag]=t)}static markDirty(e,t=!0){if(e&&(this.isUsingInstancing(e)&&(e[vg]=!0,e.matrixWorldNeedsUpdate=!0),t))for(const n of e.children)qo.markDirty(n,!0)}}function Pu(i,e){try{e?i(e):i()}catch(t){return console.error(t),!1}return!0}const IE=ee("debugnewscripts"),RY=ee("debughierarchy"),Vi=[];function PY(){return Vi.length>0}function xb(i){if(!(i.new_scripts.length<=0)){if(IE&&console.log("Register new components",i.new_scripts.length,[...i.new_scripts],i.alias?"element: "+i.alias:i.hash,i),i.new_scripts_pre_setup_callbacks.length>0){for(const e of i.new_scripts_pre_setup_callbacks)e&&e();i.new_scripts_pre_setup_callbacks.length=0}Vi.length=0,i.new_scripts.length>0&&Vi.push(...i.new_scripts),i.new_scripts.length=0;for(let e=0;e<Vi.length;e++)try{const t=Vi[e];if(t.isComponent!==!0){(pt()||IE)&&console.error(`Registered script is not a Needle Engine component.
4346
4346
  The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
4347
4347
  `,t),Vi.splice(e,1),e--;continue}if(t.destroyed)continue;if(!t.gameObject){console.error("MISSING GAMEOBJECT - will ignore",t),Vi.splice(e,1),e--;continue}t.context=i,yg(t.gameObject),RE(t,i)}catch(t){console.error(t),zl(Vi[e],i),Vi.splice(e,1),e--}for(let e=0;e<Vi.length;e++)try{const t=Vi[e];if(t.destroyed){zl(Vi[e],i),Vi.splice(e,1),e--;continue}if(t.registering)try{t.registering()}catch(n){console.error(n)}t.__internalAwake!==void 0&&(t.gameObject||console.error("MISSING GAMEOBJECT",t,t.gameObject),yg(t.gameObject),t.activeAndEnabled&&Pu(t.__internalAwake.bind(t)))}catch(t){console.error(t),zl(Vi[e],i),Vi.splice(e,1),e--}for(let e=0;e<Vi.length;e++)try{const t=Vi[e];if(t.destroyed||t.enabled===!1||(yg(t.gameObject),t.activeAndEnabled===!1))continue;t.__internalEnable!==void 0&&(t.enabled=!0,Pu(t.__internalEnable.bind(t)))}catch(t){console.error(t),zl(Vi[e],i),Vi.splice(e,1),e--}for(let e=0;e<Vi.length;e++)try{const t=Vi[e];if(t.destroyed||!t.gameObject)continue;i.new_script_start.push(t)}catch(t){console.error(t),zl(Vi[e],i),Vi.splice(e,1),e--}Vi.length=0;for(const e of i.new_scripts_post_setup_callbacks)e&&e();i.new_scripts_post_setup_callbacks.length=0}}function BY(i){i&&(i.__internalDisable(!0),zl(i,i.context))}function oL(i,e){for(let t=0;t<i.new_script_start.length;t++)try{const n=i.new_script_start[t];if(e!==void 0&&n.gameObject!==e||n.destroyed||n.activeAndEnabled===!1)continue;Pu(n.__internalAwake.bind(n)),n.enabled&&(Pu(n.__internalEnable.bind(n)),Pu(n.__internalStart.bind(n)),i.new_script_start.splice(t,1),t--)}catch(n){console.error(n),zl(i.new_script_start[t],i),i.new_script_start.splice(t,1),t--}}function RE(i,e){e.scripts.indexOf(i)===-1&&(e.scripts.push(i),i.earlyUpdate&&e.scripts_earlyUpdate.push(i),i.update&&e.scripts_update.push(i),i.lateUpdate&&e.scripts_lateUpdate.push(i),i.onBeforeRender&&e.scripts_onBeforeRender.push(i),i.onAfterRender&&e.scripts_onAfterRender.push(i),i.onPausedChanged&&e.scripts_pausedChanged.push(i),PE(i,null)&&e.new_scripts_xr.push(i),PE(i,"immersive-vr")&&e.scripts_immersive_vr.push(i),PE(i,"immersive-ar")&&e.scripts_immersive_ar.push(i))}function zl(i,e){Co(i,e.new_scripts),Co(i,e.new_script_start),Co(i,e.scripts),Co(i,e.scripts_earlyUpdate),Co(i,e.scripts_update),Co(i,e.scripts_lateUpdate),Co(i,e.scripts_onBeforeRender),Co(i,e.scripts_onAfterRender),Co(i,e.scripts_pausedChanged),Co(i,e.new_scripts_xr),Co(i,e.scripts_immersive_vr),Co(i,e.scripts_immersive_ar),e.stopAllCoroutinesFrom(i)}function Co(i,e){const t=e.indexOf(i);t>=0&&e.splice(t,1)}function PE(i,e){var t;if(i){const n=i;if(n.onBeforeXR||n.onEnterXR||n.onUpdateXR||n.onLeaveXR||n.onXRControllerAdded||n.onXRControllerRemoved)return!(e!=null&&((t=n.supportsXR)==null?void 0:t.call(n,e))===!1)}return!1}function wb(i){if(i||(i=ii.Current.scene),!i){console.trace("Invalid call - no current context.");return}const e=jp(i);aL(i,e,!0)||(IE||pt()?console.error(`Error updating hierarchy
@@ -4880,7 +4880,7 @@ in script ${s}.ts
4880
4880
  `);let r=`Controller[${this.index}] ${this.side}
4881
4881
  C:${this.connected?"yes":"no"} T:${this.isTracking?"yes":"no"} Hand:${this.inputSource.hand?"yes":"no"}`;this.inputSource.hand&&(r+=`
4882
4882
  Pinch: ${(e=this.getGesture("pinch"))==null?void 0:e.value.toFixed(3)}`),r+=`
4883
- `+n,Ct.DrawLabel(t,r,.01)}onUpdateFrame(e){var t,n,r;if(this._handJointPoses.clear(),!this.xr.referenceSpace){this._isTracking=!1;return}const s=e.getPose(this.inputSource.targetRaySpace,this.xr.referenceSpace);if(this._isTracking=s!=null,s){const c=s.transform;this._rayPosition.set(c.position.x,c.position.y,c.position.z),this._rayQuaternion.set(c.orientation.x,c.orientation.y,c.orientation.z,c.orientation.w)}if(this.inputSource.gripSpace){const c=e.getPose(this.inputSource.gripSpace,this.xr.referenceSpace);if(c){const u=c.transform;if(this._gripPosition.set(u.position.x,u.position.y,u.position.z),this._gripQuaternion.set(u.orientation.x,u.orientation.y,u.orientation.z,u.orientation.w),"linearVelocity"in c&&c.linearVelocity){const d=c.linearVelocity;this._linearVelocity.set(d.x,d.y,d.z)}}}(t=this.xr.context.mainCamera)!=null&&t.parent&&this._object.parent!==((n=this.xr.context.mainCamera)==null?void 0:n.parent)&&this.xr.context.mainCamera.parent.add(this._object);const o=this.hand;if(o){let c=!1;const u=o.get("wrist"),d=u&&this.getHandJointPose(u);if(d){c=!0;const m=d.transform.position,A=d.transform.orientation;this._object.position.set(m.x,m.y,m.z),this._object.quaternion.set(A.x,A.y,A.z,A.w).multiply(Mo)}c||(this._object.position.copy(this._rayPosition),this._object.quaternion.copy(this._rayQuaternion).multiply(Mo));const p=o.get("middle-finger-metacarpal"),f=p&&this.getHandJointPose(p);if(f){const m=f.transform.position,A=f.transform.orientation;this._gripPosition.set(m.x,m.y,m.z),this._gripQuaternion.set(A.x,A.y,A.z,A.w)}}else this.inputSource.gripSpace&&this.targetRayMode==="transient-pointer"?(this._object.position.copy(this._gripPosition),this._object.quaternion.copy(this._gripQuaternion).multiply(Mo)):(this._object.position.copy(this._rayPosition),this._object.quaternion.copy(this._rayQuaternion).multiply(Mo));const a=(r=this.xr.context.mainCamera)==null?void 0:r.parent,l=a?xi(a):void 0;this._gripWorldPosition.copy(this._gripPosition),a&&this._gripWorldPosition.applyMatrix4(a.matrixWorld),this._gripWorldQuaternion.copy(this._gripQuaternion),this._gripWorldQuaternion.multiply(Mo),l&&this._gripWorldQuaternion.premultiply(l),this.updateRayWorldPosition(),this.updateRayWorldQuaternion()}onDisconnected(){this._connected=!1,Yc&&console.warn("Controller disconnected",this.index);for(const e of this._object.children)this.xr.context.scene.attach(e);this._object.removeFromParent(),this._debugAxesHelper.removeFromParent(),this.unsubscribeEvents()}getButton(e){var t;if(!this._layout)return;switch(e){case"primary-button":if(this.isLeft)e="x-button";else if(this.isRight)e="a-button";else return;break;case"primary":return this.toNeedleGamepadButton(0)}if(this._buttonMap.has(e))return this.toNeedleGamepadButton(this._buttonMap.get(e));const n=(t=this._layout)==null?void 0:t.components[e];if(n!=null&&n.gamepadIndices)switch(n.type){case"button":case"squeeze":if(this.inputSource.gamepad){const r=n.gamepadIndices.button;return this._buttonMap.set(e,r),this.toNeedleGamepadButton(r)}break;default:console.warn("Unsupported component type",n.type);break}this._buttonMap.set(e,void 0)}getGesture(e){const t=this.states[e];if(!t)return null;this.states[e]=t;const n=this._needleGamepadButtons[e]||new ZL;return n.pressed=t.pressed,n.value=t.value,n.isDown=t.isDown,n.isUp=t.isUp,this._needleGamepadButtons[e]=n,n}toNeedleGamepadButton(e){var t,n;if(!((t=this.inputSource.gamepad)!=null&&t.buttons))return;const r=(n=this.inputSource.gamepad)==null?void 0:n.buttons[e],s=this.states[e],o=this._needleGamepadButtons[e]||new ZL;return r&&(o.pressed=r.pressed,o.value=r.value,o.touched=r.touched),s&&(o.isDown=s.isDown,o.isUp=s.isUp),this._needleGamepadButtons[e]=o,o}getStick(e){var t,n,r,s,o,a,l;if(!this._layout)return{x:0,y:0,z:0};if(e==="primary"){const u=((t=this.inputSource.gamepad)==null?void 0:t.axes[0])||0,d=((n=this.inputSource.gamepad)==null?void 0:n.axes[1])||0,p=((r=this.inputSource.gamepad)==null?void 0:r.buttons[3].value)||0;return{x:u,y:d,z:p}}const c=(s=this._layout)==null?void 0:s.components[e];if(c!=null&&c.gamepadIndices)switch(c.type){case"thumbstick":if(this.inputSource.gamepad){const u=c.gamepadIndices.xAxis,d=c.gamepadIndices.yAxis;let p=(o=this.inputSource.gamepad)==null?void 0:o.axes[u],f=(a=this.inputSource.gamepad)==null?void 0:a.axes[d];p*=-1,f*=-1;const m=c.gamepadIndices.button,A=(l=this.inputSource.gamepad)==null?void 0:l.buttons[m].value;return{x:p,y:f,z:A}}}return{x:0,y:0,z:0}}initialize(){if(this._hasSelectEvent=this.profiles.includes("generic-hand-select")||this.profiles.some(e=>e.startsWith("generic-trigger")),!this._layout){if(this.inputSource.targetRayMode==="transient-pointer")return;const e=fZ(this.inputSource,CZ,EZ);this.getMotionController=e.then(t=>{var n;if(!this.connected)return null;this._motioncontroller=new yZ(this.inputSource,t.profile,t.assetPath||"");const r=t.profile.layouts[this.inputSource.handedness];if(this._layout=r,this._layout&&!((n=this._layout.gamepad)!=null&&n.length)){this._layout.gamepad=[];for(const s in this._layout.components){const o=this._layout.components[s];this._layout.gamepad[o.gamepadIndices.button]=s}}return this._motioncontroller}).catch(t=>(this.inputSource&&console.warn("Couldn't initialize motion controller profile for ",this.inputSource,t),null))}}subscribeEvents(){this.xr.session.addEventListener("selectstart",this.onSelectStart),this.xr.session.addEventListener("selectend",this.onSelectEnd),this.xr.session.addEventListener("squeezestart",this.onSequeezeStart),this.xr.session.addEventListener("squeezeend",this.onSequeezeEnd)}unsubscribeEvents(){this.xr.session.removeEventListener("selectstart",this.onSelectStart),this.xr.session.removeEventListener("selectend",this.onSelectEnd),this.xr.session.removeEventListener("squeezestart",this.onSequeezeStart),this.xr.session.removeEventListener("squeezeend",this.onSequeezeEnd)}updateInputEvents(){var e,t;if((e=this.gamepad)!=null&&e.buttons)for(let n=0;n<this.gamepad.buttons.length;n++){const r=this.gamepad.buttons[n],s=this.states[n]||new KL;let o=null;r.pressed&&!s.pressed?(o="pointerdown",s.isDown=!0,s.isUp=!1):!r.pressed&&s.pressed?(o="pointerup",s.isDown=!1,s.isUp=!0):(s.isDown=!1,s.isUp=!1),s.value=r.value,s.pressed=r.pressed,this.states[n]=s;const a=n!==this._selectButtonIndex&&n!==this._squeezeButtonIndex;if(o!=null&&a){const l=(t=this._layout)==null?void 0:t.gamepad[n];(Yc||Nb)&&console.log("Emitting pointer event",o,n,l,r.value,this.gamepad,this._layout),this.emitPointerEvent(o,n,l??"none",!1,null,r.value)}}if(this.hand){const n=this.handObject;if(n){const r=n.joints["index-finger-tip"],s=n.joints["thumb-tip"];if(r&&s){const o=r.position.distanceTo(s.position),a=this.states.pinch||new KL;a.value=o;const l=o<.02-.01,c=o>.02+.01;l&&!a.pressed?(Nb&&console.log("pinch start",o),a.isDown=!0,a.isUp=!1,a.pressed=!0):c&&a.pressed?(a.isDown=!1,a.isUp=!0,a.pressed=!1):(a.isDown=!1,a.isUp=!1),this.states.pinch=a}}}}onUpdateMove(){var e,t;let n=!1;if(this._lastPointerMovePosition.distanceTo(this.gripWorldPosition)>.02&&(n=!0),n||this._lastPointerMoveQuaternion.angleTo(this.gripWorldQuaternion)>.02&&(n=!0),n){this._didMoveLastFrame=!0,this._lastPointerMovePosition.copy(this.gripWorldPosition),this._lastPointerMoveQuaternion.copy(this.gripWorldQuaternion),Yc&&Ct.DrawLabel(this.rayWorldPosition.add(this.object.worldForward.multiplyScalar(.1)),"move",.01);let r=this.xr.context.input.getFirstPressedButtonForPointer(this.index);r===void 0&&(r=0);const s=(t=(e=this.gamepad)==null?void 0:e.buttons[r])==null?void 0:t.value;this.emitPointerEvent("pointermove",r,"none",!1,null,s)}else this._didMoveLastFrame=!1}emitPointerEvent(e,t,n,r,s=null,o){if(!this.emitEvents){Yc&&e!==Wi.PointerMove&&console.warn("Pointer events are disabled for this controller",this.index,e,t);return}if(this.xr.mode==="immersive-vr"||this.xr.isPassThrough){this.pointerInit.origin=this,this.pointerInit.pointerId=this.index*10+t,this.pointerInit.pointerType=this.hand?"hand":"controller",this.pointerInit.button=t,this.pointerInit.buttonName=n,this.pointerInit.isPrimary=r,this.pointerInit.mode=this.inputSource.targetRayMode,this.pointerInit.ray=this.ray,this.pointerInit.device=this.object,this.pointerInit.pressure=o;const a=Lt.Current;Lt.Current=this.xr.context,Yc&&e!=="pointermove"&&console.warn("Pointer event",e,t,n,{...this.pointerInit}),this.xr.context.input.createInputEvent(new Hl(e,s,this.pointerInit)),Lt.Current=a}}}class KL{constructor(){h(this,"isDown",!1),h(this,"isUp",!1),h(this,"pressed",!1),h(this,"value",0)}}class ZL{constructor(){h(this,"touched",!1),h(this,"pressed",!1),h(this,"value",0),h(this,"isDown",!1),h(this,"isUp",!1)}}const Eg=new Map;function Mg(i,e){Eg.has(e)||Eg.set(e,new Array),Eg.get(e).push(i)}function MZ(i,e){const t=Eg.get(e);if(t){const n=t.indexOf(i);n>=0&&t.splice(n,1)}}function Ou(i,e){const t=Eg.get(e);if(t&&t.length>0){let n=t;e===Pn.Start&&(n=[...t],t.length=0),TZ(i,n)}}function TZ(i,e){for(let t=e.length-1;t>=0;t--){const n=e[t];Pu(n,i)}}const zb=[];function oM(i){zb.indexOf(i)===-1&&zb.push(i)}function IZ(i){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-start",{detail:i}));for(let e=0;e<zb.length;e++)zb[e](i)}const aM=2,ja=4,Vl=4,lM=4,Jc=new Int32Array(2),$L=new Float32Array(Jc.buffer),eU=new Float64Array(Jc.buffer),jb=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1;class _c{constructor(e,t){this.low=e|0,this.high=t|0}static create(e,t){return e==0&&t==0?_c.ZERO:new _c(e,t)}toFloat64(){return(this.low>>>0)+this.high*4294967296}equals(e){return this.low==e.low&&this.high==e.high}}_c.ZERO=new _c(0,0);var cM;(function(i){i[i.UTF8_BYTES=1]="UTF8_BYTES",i[i.UTF16_STRING=2]="UTF16_STRING"})(cM||(cM={}));class J0{constructor(e){this.bytes_=e,this.position_=0}static allocate(e){return new J0(new Uint8Array(e))}clear(){this.position_=0}bytes(){return this.bytes_}position(){return this.position_}setPosition(e){this.position_=e}capacity(){return this.bytes_.length}readInt8(e){return this.readUint8(e)<<24>>24}readUint8(e){return this.bytes_[e]}readInt16(e){return this.readUint16(e)<<16>>16}readUint16(e){return this.bytes_[e]|this.bytes_[e+1]<<8}readInt32(e){return this.bytes_[e]|this.bytes_[e+1]<<8|this.bytes_[e+2]<<16|this.bytes_[e+3]<<24}readUint32(e){return this.readInt32(e)>>>0}readInt64(e){return new _c(this.readInt32(e),this.readInt32(e+4))}readUint64(e){return new _c(this.readUint32(e),this.readUint32(e+4))}readFloat32(e){return Jc[0]=this.readInt32(e),$L[0]}readFloat64(e){return Jc[jb?0:1]=this.readInt32(e),Jc[jb?1:0]=this.readInt32(e+4),eU[0]}writeInt8(e,t){this.bytes_[e]=t}writeUint8(e,t){this.bytes_[e]=t}writeInt16(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8}writeUint16(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8}writeInt32(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24}writeUint32(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24}writeInt64(e,t){this.writeInt32(e,t.low),this.writeInt32(e+4,t.high)}writeUint64(e,t){this.writeUint32(e,t.low),this.writeUint32(e+4,t.high)}writeFloat32(e,t){$L[0]=t,this.writeInt32(e,Jc[0])}writeFloat64(e,t){eU[0]=t,this.writeInt32(e,Jc[jb?0:1]),this.writeInt32(e+4,Jc[jb?1:0])}getBufferIdentifier(){if(this.bytes_.length<this.position_+ja+Vl)throw new Error("FlatBuffers: ByteBuffer is too short to contain an identifier.");let e="";for(let t=0;t<Vl;t++)e+=String.fromCharCode(this.readInt8(this.position_+ja+t));return e}__offset(e,t){const n=e-this.readInt32(e);return t<this.readInt16(n)?this.readInt16(n+t):0}__union(e,t){return e.bb_pos=t+this.readInt32(t),e.bb=this,e}__string(e,t){e+=this.readInt32(e);const n=this.readInt32(e);let r="",s=0;if(e+=ja,t===cM.UTF8_BYTES)return this.bytes_.subarray(e,e+n);for(;s<n;){let o;const a=this.readUint8(e+s++);if(a<192)o=a;else{const l=this.readUint8(e+s++);if(a<224)o=(a&31)<<6|l&63;else{const c=this.readUint8(e+s++);if(a<240)o=(a&15)<<12|(l&63)<<6|c&63;else{const u=this.readUint8(e+s++);o=(a&7)<<18|(l&63)<<12|(c&63)<<6|u&63}}}o<65536?r+=String.fromCharCode(o):(o-=65536,r+=String.fromCharCode((o>>10)+55296,(o&1024-1)+56320))}return r}__union_with_string(e,t){return typeof e=="string"?this.__string(t):this.__union(e,t)}__indirect(e){return e+this.readInt32(e)}__vector(e){return e+this.readInt32(e)+ja}__vector_len(e){return this.readInt32(e+this.readInt32(e))}__has_identifier(e){if(e.length!=Vl)throw new Error("FlatBuffers: file identifier must be length "+Vl);for(let t=0;t<Vl;t++)if(e.charCodeAt(t)!=this.readInt8(this.position()+ja+t))return!1;return!0}createLong(e,t){return _c.create(e,t)}createScalarList(e,t){const n=[];for(let r=0;r<t;++r)e(r)!==null&&n.push(e(r));return n}createObjList(e,t){const n=[];for(let r=0;r<t;++r){const s=e(r);s!==null&&n.push(s.unpack())}return n}}class K0{constructor(e){this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null;let t;e?t=e:t=1024,this.bb=J0.allocate(t),this.space=t}clear(){this.bb.clear(),this.space=this.bb.capacity(),this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null}forceDefaults(e){this.force_defaults=e}dataBuffer(){return this.bb}asUint8Array(){return this.bb.bytes().subarray(this.bb.position(),this.bb.position()+this.offset())}prep(e,t){e>this.minalign&&(this.minalign=e);const n=~(this.bb.capacity()-this.space+t)+1&e-1;for(;this.space<n+e+t;){const r=this.bb.capacity();this.bb=K0.growByteBuffer(this.bb),this.space+=this.bb.capacity()-r}this.pad(n)}pad(e){for(let t=0;t<e;t++)this.bb.writeInt8(--this.space,0)}writeInt8(e){this.bb.writeInt8(this.space-=1,e)}writeInt16(e){this.bb.writeInt16(this.space-=2,e)}writeInt32(e){this.bb.writeInt32(this.space-=4,e)}writeInt64(e){this.bb.writeInt64(this.space-=8,e)}writeFloat32(e){this.bb.writeFloat32(this.space-=4,e)}writeFloat64(e){this.bb.writeFloat64(this.space-=8,e)}addInt8(e){this.prep(1,0),this.writeInt8(e)}addInt16(e){this.prep(2,0),this.writeInt16(e)}addInt32(e){this.prep(4,0),this.writeInt32(e)}addInt64(e){this.prep(8,0),this.writeInt64(e)}addFloat32(e){this.prep(4,0),this.writeFloat32(e)}addFloat64(e){this.prep(8,0),this.writeFloat64(e)}addFieldInt8(e,t,n){(this.force_defaults||t!=n)&&(this.addInt8(t),this.slot(e))}addFieldInt16(e,t,n){(this.force_defaults||t!=n)&&(this.addInt16(t),this.slot(e))}addFieldInt32(e,t,n){(this.force_defaults||t!=n)&&(this.addInt32(t),this.slot(e))}addFieldInt64(e,t,n){(this.force_defaults||!t.equals(n))&&(this.addInt64(t),this.slot(e))}addFieldFloat32(e,t,n){(this.force_defaults||t!=n)&&(this.addFloat32(t),this.slot(e))}addFieldFloat64(e,t,n){(this.force_defaults||t!=n)&&(this.addFloat64(t),this.slot(e))}addFieldOffset(e,t,n){(this.force_defaults||t!=n)&&(this.addOffset(t),this.slot(e))}addFieldStruct(e,t,n){t!=n&&(this.nested(t),this.slot(e))}nested(e){if(e!=this.offset())throw new Error("FlatBuffers: struct must be serialized inline.")}notNested(){if(this.isNested)throw new Error("FlatBuffers: object serialization must not be nested.")}slot(e){this.vtable!==null&&(this.vtable[e]=this.offset())}offset(){return this.bb.capacity()-this.space}static growByteBuffer(e){const t=e.capacity();if(t&3221225472)throw new Error("FlatBuffers: cannot grow buffer beyond 2 gigabytes.");const n=t<<1,r=J0.allocate(n);return r.setPosition(n-t),r.bytes().set(e.bytes(),n-t),r}addOffset(e){this.prep(ja,0),this.writeInt32(this.offset()-e+ja)}startObject(e){this.notNested(),this.vtable==null&&(this.vtable=[]),this.vtable_in_use=e;for(let t=0;t<e;t++)this.vtable[t]=0;this.isNested=!0,this.object_start=this.offset()}endObject(){if(this.vtable==null||!this.isNested)throw new Error("FlatBuffers: endObject called without startObject");this.addInt32(0);const e=this.offset();let t=this.vtable_in_use-1;for(;t>=0&&this.vtable[t]==0;t--);const n=t+1;for(;t>=0;t--)this.addInt16(this.vtable[t]!=0?e-this.vtable[t]:0);const r=2;this.addInt16(e-this.object_start);const s=(n+r)*aM;this.addInt16(s);let o=0;const a=this.space;e:for(t=0;t<this.vtables.length;t++){const l=this.bb.capacity()-this.vtables[t];if(s==this.bb.readInt16(l)){for(let c=aM;c<s;c+=aM)if(this.bb.readInt16(a+c)!=this.bb.readInt16(l+c))continue e;o=this.vtables[t];break}}return o?(this.space=this.bb.capacity()-e,this.bb.writeInt32(this.space,o-e)):(this.vtables.push(this.offset()),this.bb.writeInt32(this.bb.capacity()-e,this.offset()-e)),this.isNested=!1,e}finish(e,t,n){const r=n?lM:0;if(t){const s=t;if(this.prep(this.minalign,ja+Vl+r),s.length!=Vl)throw new Error("FlatBuffers: file identifier must be length "+Vl);for(let o=Vl-1;o>=0;o--)this.writeInt8(s.charCodeAt(o))}this.prep(this.minalign,ja+r),this.addOffset(e),r&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(e,t){this.finish(e,t,!0)}requiredField(e,t){const n=this.bb.capacity()-e,r=n-this.bb.readInt32(n);if(this.bb.readInt16(r+t)==0)throw new Error("FlatBuffers: field "+t+" must be set")}startVector(e,t,n){this.notNested(),this.vector_num_elems=t,this.prep(ja,e*t),this.prep(n,e*t)}endVector(){return this.writeInt32(this.vector_num_elems),this.offset()}createSharedString(e){if(!e)return 0;if(this.string_maps||(this.string_maps=new Map),this.string_maps.has(e))return this.string_maps.get(e);const t=this.createString(e);return this.string_maps.set(e,t),t}createString(e){if(!e)return 0;let t;if(e instanceof Uint8Array)t=e;else{t=[];let n=0;for(;n<e.length;){let r;const s=e.charCodeAt(n++);if(s<55296||s>=56320)r=s;else{const o=e.charCodeAt(n++);r=(s<<10)+o+(65536-56623104-56320)}r<128?t.push(r):(r<2048?t.push(r>>6&31|192):(r<65536?t.push(r>>12&15|224):t.push(r>>18&7|240,r>>12&63|128),t.push(r>>6&63|128)),t.push(r&63|128))}}this.addInt8(0),this.startVector(1,t.length,1),this.bb.setPosition(this.space-=t.length);for(let n=0,r=this.space,s=this.bb.bytes();n<t.length;n++)s[r++]=t[n];return this.endVector()}createLong(e,t){return _c.create(e,t)}createObjectOffset(e){return e===null?0:typeof e=="string"?this.createString(e):e.pack(this)}createObjectOffsetList(e){const t=[];for(let n=0;n<e.length;++n){const r=e[n];if(r!==null)t.push(this.createObjectOffset(r));else throw new Error("FlatBuffers: Argument for createObjectOffsetList cannot contain null.")}return t}createStructOffsetList(e,t){return t(this,e.length),this.createObjectOffsetList(e),this.endVector()}}const hM={};function uM(i,e){hM[i]=e}function tU(i){const e=i.getBufferIdentifier(),t=hM[e];return t(i)}function iU(i){return typeof i.guid=="function"?i.guid():null}var nU={exports:{}};(function(i){var e={};e.useBlobBuilder=function(){try{return new Blob([]),!1}catch{return!0}}(),e.useArrayBufferView=!e.useBlobBuilder&&function(){try{return new Blob([new Uint8Array([])]).size===0}catch{return!0}}(),i.exports.binaryFeatures=e;var t=i.exports.BlobBuilder;typeof window<"u"&&(t=i.exports.BlobBuilder=window.WebKitBlobBuilder||window.MozBlobBuilder||window.MSBlobBuilder||window.BlobBuilder);function n(){this._pieces=[],this._parts=[]}n.prototype.append=function(r){typeof r=="number"?this._pieces.push(r):(this.flush(),this._parts.push(r))},n.prototype.flush=function(){if(this._pieces.length>0){var r=new Uint8Array(this._pieces);e.useArrayBufferView||(r=r.buffer),this._parts.push(r),this._pieces=[]}},n.prototype.getBuffer=function(){if(this.flush(),e.useBlobBuilder){for(var r=new t,s=0,o=this._parts.length;s<o;s++)r.append(this._parts[s]);return r.getBlob()}else return new Blob(this._parts)},i.exports.BufferBuilder=n})(nU);var rU=nU.exports,RZ=rU.BufferBuilder,sU=rU.binaryFeatures,PZ={unpack:function(i){var e=new gr(i);return e.unpack()},pack:function(i){var e=new vr;e.pack(i);var t=e.getBuffer();return t}},BZ=PZ;function gr(i){this.index=0,this.dataBuffer=i,this.dataView=new Uint8Array(this.dataBuffer),this.length=this.dataBuffer.byteLength}gr.prototype.unpack=function(){var i=this.unpack_uint8();if(i<128)return i;if((i^224)<32)return(i^224)-32;var e;if((e=i^160)<=15)return this.unpack_raw(e);if((e=i^176)<=15)return this.unpack_string(e);if((e=i^144)<=15)return this.unpack_array(e);if((e=i^128)<=15)return this.unpack_map(e);switch(i){case 192:return null;case 193:return;case 194:return!1;case 195:return!0;case 202:return this.unpack_float();case 203:return this.unpack_double();case 204:return this.unpack_uint8();case 205:return this.unpack_uint16();case 206:return this.unpack_uint32();case 207:return this.unpack_uint64();case 208:return this.unpack_int8();case 209:return this.unpack_int16();case 210:return this.unpack_int32();case 211:return this.unpack_int64();case 212:return;case 213:return;case 214:return;case 215:return;case 216:return e=this.unpack_uint16(),this.unpack_string(e);case 217:return e=this.unpack_uint32(),this.unpack_string(e);case 218:return e=this.unpack_uint16(),this.unpack_raw(e);case 219:return e=this.unpack_uint32(),this.unpack_raw(e);case 220:return e=this.unpack_uint16(),this.unpack_array(e);case 221:return e=this.unpack_uint32(),this.unpack_array(e);case 222:return e=this.unpack_uint16(),this.unpack_map(e);case 223:return e=this.unpack_uint32(),this.unpack_map(e)}},gr.prototype.unpack_uint8=function(){var i=this.dataView[this.index]&255;return this.index++,i},gr.prototype.unpack_uint16=function(){var i=this.read(2),e=(i[0]&255)*256+(i[1]&255);return this.index+=2,e},gr.prototype.unpack_uint32=function(){var i=this.read(4),e=((i[0]*256+i[1])*256+i[2])*256+i[3];return this.index+=4,e},gr.prototype.unpack_uint64=function(){var i=this.read(8),e=((((((i[0]*256+i[1])*256+i[2])*256+i[3])*256+i[4])*256+i[5])*256+i[6])*256+i[7];return this.index+=8,e},gr.prototype.unpack_int8=function(){var i=this.unpack_uint8();return i<128?i:i-256},gr.prototype.unpack_int16=function(){var i=this.unpack_uint16();return i<32768?i:i-65536},gr.prototype.unpack_int32=function(){var i=this.unpack_uint32();return i<Math.pow(2,31)?i:i-Math.pow(2,32)},gr.prototype.unpack_int64=function(){var i=this.unpack_uint64();return i<Math.pow(2,63)?i:i-Math.pow(2,64)},gr.prototype.unpack_raw=function(i){if(this.length<this.index+i)throw new Error("BinaryPackFailure: index is out of range "+this.index+" "+i+" "+this.length);var e=this.dataBuffer.slice(this.index,this.index+i);return this.index+=i,e},gr.prototype.unpack_string=function(i){for(var e=this.read(i),t=0,n="",r,s;t<i;)r=e[t],r<128?(n+=String.fromCharCode(r),t++):(r^192)<32?(s=(r^192)<<6|e[t+1]&63,n+=String.fromCharCode(s),t+=2):(s=(r&15)<<12|(e[t+1]&63)<<6|e[t+2]&63,n+=String.fromCharCode(s),t+=3);return this.index+=i,n},gr.prototype.unpack_array=function(i){for(var e=new Array(i),t=0;t<i;t++)e[t]=this.unpack();return e},gr.prototype.unpack_map=function(i){for(var e={},t=0;t<i;t++){var n=this.unpack(),r=this.unpack();e[n]=r}return e},gr.prototype.unpack_float=function(){var i=this.unpack_uint32(),e=i>>31,t=(i>>23&255)-127,n=i&8388607|8388608;return(e===0?1:-1)*n*Math.pow(2,t-23)},gr.prototype.unpack_double=function(){var i=this.unpack_uint32(),e=this.unpack_uint32(),t=i>>31,n=(i>>20&2047)-1023,r=i&1048575|1048576,s=r*Math.pow(2,n-20)+e*Math.pow(2,n-52);return(t===0?1:-1)*s},gr.prototype.read=function(i){var e=this.index;if(e+i<=this.length)return this.dataView.subarray(e,e+i);throw new Error("BinaryPackFailure: read index out of range")};function vr(){this.bufferBuilder=new RZ}vr.prototype.getBuffer=function(){return this.bufferBuilder.getBuffer()},vr.prototype.pack=function(i){var e=typeof i;if(e==="string")this.pack_string(i);else if(e==="number")Math.floor(i)===i?this.pack_integer(i):this.pack_double(i);else if(e==="boolean")i===!0?this.bufferBuilder.append(195):i===!1&&this.bufferBuilder.append(194);else if(e==="undefined")this.bufferBuilder.append(192);else if(e==="object")if(i===null)this.bufferBuilder.append(192);else{var t=i.constructor;if(t==Array)this.pack_array(i);else if(t==Blob||t==File||i instanceof Blob||i instanceof File)this.pack_bin(i);else if(t==ArrayBuffer)sU.useArrayBufferView?this.pack_bin(new Uint8Array(i)):this.pack_bin(i);else if("BYTES_PER_ELEMENT"in i)sU.useArrayBufferView?this.pack_bin(new Uint8Array(i.buffer)):this.pack_bin(i.buffer);else if(t==Object||t.toString().startsWith("class"))this.pack_object(i);else if(t==Date)this.pack_string(i.toString());else if(typeof i.toBinaryPack=="function")this.bufferBuilder.append(i.toBinaryPack());else throw new Error('Type "'+t.toString()+'" not yet supported')}else throw new Error('Type "'+e+'" not yet supported');this.bufferBuilder.flush()},vr.prototype.pack_bin=function(i){var e=i.length||i.byteLength||i.size;if(e<=15)this.pack_uint8(160+e);else if(e<=65535)this.bufferBuilder.append(218),this.pack_uint16(e);else if(e<=4294967295)this.bufferBuilder.append(219),this.pack_uint32(e);else throw new Error("Invalid length");this.bufferBuilder.append(i)},vr.prototype.pack_string=function(i){var e=OZ(i);if(e<=15)this.pack_uint8(176+e);else if(e<=65535)this.bufferBuilder.append(216),this.pack_uint16(e);else if(e<=4294967295)this.bufferBuilder.append(217),this.pack_uint32(e);else throw new Error("Invalid length");this.bufferBuilder.append(i)},vr.prototype.pack_array=function(i){var e=i.length;if(e<=15)this.pack_uint8(144+e);else if(e<=65535)this.bufferBuilder.append(220),this.pack_uint16(e);else if(e<=4294967295)this.bufferBuilder.append(221),this.pack_uint32(e);else throw new Error("Invalid length");for(var t=0;t<e;t++)this.pack(i[t])},vr.prototype.pack_integer=function(i){if(i>=-32&&i<=127)this.bufferBuilder.append(i&255);else if(i>=0&&i<=255)this.bufferBuilder.append(204),this.pack_uint8(i);else if(i>=-128&&i<=127)this.bufferBuilder.append(208),this.pack_int8(i);else if(i>=0&&i<=65535)this.bufferBuilder.append(205),this.pack_uint16(i);else if(i>=-32768&&i<=32767)this.bufferBuilder.append(209),this.pack_int16(i);else if(i>=0&&i<=4294967295)this.bufferBuilder.append(206),this.pack_uint32(i);else if(i>=-2147483648&&i<=2147483647)this.bufferBuilder.append(210),this.pack_int32(i);else if(i>=-9223372036854776e3&&i<=9223372036854776e3)this.bufferBuilder.append(211),this.pack_int64(i);else if(i>=0&&i<=18446744073709552e3)this.bufferBuilder.append(207),this.pack_uint64(i);else throw new Error("Invalid integer")},vr.prototype.pack_double=function(i){var e=0;i<0&&(e=1,i=-i);var t=Math.floor(Math.log(i)/Math.LN2),n=i/Math.pow(2,t)-1,r=Math.floor(n*Math.pow(2,52)),s=Math.pow(2,32),o=e<<31|t+1023<<20|r/s&1048575,a=r%s;this.bufferBuilder.append(203),this.pack_int32(o),this.pack_int32(a)},vr.prototype.pack_object=function(i){var e=Object.keys(i),t=e.length;if(t<=15)this.pack_uint8(128+t);else if(t<=65535)this.bufferBuilder.append(222),this.pack_uint16(t);else if(t<=4294967295)this.bufferBuilder.append(223),this.pack_uint32(t);else throw new Error("Invalid length");for(var n in i)i.hasOwnProperty(n)&&(this.pack(n),this.pack(i[n]))},vr.prototype.pack_uint8=function(i){this.bufferBuilder.append(i)},vr.prototype.pack_uint16=function(i){this.bufferBuilder.append(i>>8),this.bufferBuilder.append(i&255)},vr.prototype.pack_uint32=function(i){var e=i&4294967295;this.bufferBuilder.append((e&4278190080)>>>24),this.bufferBuilder.append((e&16711680)>>>16),this.bufferBuilder.append((e&65280)>>>8),this.bufferBuilder.append(e&255)},vr.prototype.pack_uint64=function(i){var e=i/Math.pow(2,32),t=i%Math.pow(2,32);this.bufferBuilder.append((e&4278190080)>>>24),this.bufferBuilder.append((e&16711680)>>>16),this.bufferBuilder.append((e&65280)>>>8),this.bufferBuilder.append(e&255),this.bufferBuilder.append((t&4278190080)>>>24),this.bufferBuilder.append((t&16711680)>>>16),this.bufferBuilder.append((t&65280)>>>8),this.bufferBuilder.append(t&255)},vr.prototype.pack_int8=function(i){this.bufferBuilder.append(i&255)},vr.prototype.pack_int16=function(i){this.bufferBuilder.append((i&65280)>>8),this.bufferBuilder.append(i&255)},vr.prototype.pack_int32=function(i){this.bufferBuilder.append(i>>>24&255),this.bufferBuilder.append((i&16711680)>>>16),this.bufferBuilder.append((i&65280)>>>8),this.bufferBuilder.append(i&255)},vr.prototype.pack_int64=function(i){var e=Math.floor(i/Math.pow(2,32)),t=i%Math.pow(2,32);this.bufferBuilder.append((e&4278190080)>>>24),this.bufferBuilder.append((e&16711680)>>>16),this.bufferBuilder.append((e&65280)>>>8),this.bufferBuilder.append(e&255),this.bufferBuilder.append((t&4278190080)>>>24),this.bufferBuilder.append((t&16711680)>>>16),this.bufferBuilder.append((t&65280)>>>8),this.bufferBuilder.append(t&255)};function DZ(i){var e=i.charCodeAt(0);return e<=2047?"00":e<=65535?"000":e<=2097151?"0000":e<=67108863?"00000":"000000"}function OZ(i){return i.length>600?new Blob([i]).size:i.replace(/[^\u0000-\u007F]/g,DZ).length}const oU=Bb(BZ);let aU=!0,lU=!0;function Tg(i,e,t){const n=i.match(e);return n&&n.length>=t&&parseInt(n[t],10)}function Dp(i,e,t){if(!i.RTCPeerConnection)return;const n=i.RTCPeerConnection.prototype,r=n.addEventListener;n.addEventListener=function(o,a){if(o!==e)return r.apply(this,arguments);const l=c=>{const u=t(c);u&&(a.handleEvent?a.handleEvent(u):a(u))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(a,l),r.apply(this,[o,l])};const s=n.removeEventListener;n.removeEventListener=function(o,a){if(o!==e||!this._eventMap||!this._eventMap[e])return s.apply(this,arguments);if(!this._eventMap[e].has(a))return s.apply(this,arguments);const l=this._eventMap[e].get(a);return this._eventMap[e].delete(a),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,s.apply(this,[o,l])},Object.defineProperty(n,"on"+e,{get(){return this["_on"+e]},set(o){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),o&&this.addEventListener(e,this["_on"+e]=o)},enumerable:!0,configurable:!0})}function kZ(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(aU=i,i?"adapter.js logging disabled":"adapter.js logging enabled")}function LZ(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(lU=!i,"adapter.js deprecation warnings "+(i?"disabled":"enabled"))}function dM(){if(typeof window=="object"){if(aU)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function Gb(i,e){lU&&console.warn(i+" is deprecated, please use "+e+" instead.")}function UZ(i){const e={browser:null,version:null};if(typeof i>"u"||!i.navigator)return e.browser="Not a browser.",e;const{navigator:t}=i;if(t.mozGetUserMedia)e.browser="firefox",e.version=Tg(t.userAgent,/Firefox\/(\d+)\./,1);else if(t.webkitGetUserMedia||i.isSecureContext===!1&&i.webkitRTCPeerConnection&&!i.RTCIceGatherer)e.browser="chrome",e.version=Tg(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(t.mediaDevices&&t.userAgent.match(/Edge\/(\d+).(\d+)$/))e.browser="edge",e.version=Tg(t.userAgent,/Edge\/(\d+).(\d+)$/,2);else if(i.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=Tg(t.userAgent,/AppleWebKit\/(\d+)\./,1),e.supportsUnifiedPlan=i.RTCRtpTransceiver&&"currentDirection"in i.RTCRtpTransceiver.prototype;else return e.browser="Not a supported browser.",e;return e}function cU(i){return Object.prototype.toString.call(i)==="[object Object]"}function hU(i){return cU(i)?Object.keys(i).reduce(function(e,t){const n=cU(i[t]),r=n?hU(i[t]):i[t],s=n&&!Object.keys(r).length;return r===void 0||s?e:Object.assign(e,{[t]:r})},{}):i}function pM(i,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(n=>{n.endsWith("Id")?pM(i,i.get(e[n]),t):n.endsWith("Ids")&&e[n].forEach(r=>{pM(i,i.get(r),t)})}))}function uU(i,e,t){const n=t?"outbound-rtp":"inbound-rtp",r=new Map;if(e===null)return r;const s=[];return i.forEach(o=>{o.type==="track"&&o.trackIdentifier===e.id&&s.push(o)}),s.forEach(o=>{i.forEach(a=>{a.type===n&&a.trackId===o.id&&pM(i,a,r)})}),r}const dU=dM;function pU(i,e){const t=i&&i.navigator;if(!t.mediaDevices)return;const n=function(a){if(typeof a!="object"||a.mandatory||a.optional)return a;const l={};return Object.keys(a).forEach(c=>{if(c==="require"||c==="advanced"||c==="mediaSource")return;const u=typeof a[c]=="object"?a[c]:{ideal:a[c]};u.exact!==void 0&&typeof u.exact=="number"&&(u.min=u.max=u.exact);const d=function(p,f){return p?p+f.charAt(0).toUpperCase()+f.slice(1):f==="deviceId"?"sourceId":f};if(u.ideal!==void 0){l.optional=l.optional||[];let p={};typeof u.ideal=="number"?(p[d("min",c)]=u.ideal,l.optional.push(p),p={},p[d("max",c)]=u.ideal,l.optional.push(p)):(p[d("",c)]=u.ideal,l.optional.push(p))}u.exact!==void 0&&typeof u.exact!="number"?(l.mandatory=l.mandatory||{},l.mandatory[d("",c)]=u.exact):["min","max"].forEach(p=>{u[p]!==void 0&&(l.mandatory=l.mandatory||{},l.mandatory[d(p,c)]=u[p])})}),a.advanced&&(l.optional=(l.optional||[]).concat(a.advanced)),l},r=function(a,l){if(e.version>=61)return l(a);if(a=JSON.parse(JSON.stringify(a)),a&&typeof a.audio=="object"){const c=function(u,d,p){d in u&&!(p in u)&&(u[p]=u[d],delete u[d])};a=JSON.parse(JSON.stringify(a)),c(a.audio,"autoGainControl","googAutoGainControl"),c(a.audio,"noiseSuppression","googNoiseSuppression"),a.audio=n(a.audio)}if(a&&typeof a.video=="object"){let c=a.video.facingMode;c=c&&(typeof c=="object"?c:{ideal:c});const u=e.version<66;if(c&&(c.exact==="user"||c.exact==="environment"||c.ideal==="user"||c.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!u)){delete a.video.facingMode;let d;if(c.exact==="environment"||c.ideal==="environment"?d=["back","rear"]:(c.exact==="user"||c.ideal==="user")&&(d=["front"]),d)return t.mediaDevices.enumerateDevices().then(p=>{p=p.filter(m=>m.kind==="videoinput");let f=p.find(m=>d.some(A=>m.label.toLowerCase().includes(A)));return!f&&p.length&&d.includes("back")&&(f=p[p.length-1]),f&&(a.video.deviceId=c.exact?{exact:f.deviceId}:{ideal:f.deviceId}),a.video=n(a.video),dU("chrome: "+JSON.stringify(a)),l(a)})}a.video=n(a.video)}return dU("chrome: "+JSON.stringify(a)),l(a)},s=function(a){return e.version>=64?a:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[a.name]||a.name,message:a.message,constraint:a.constraint||a.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},o=function(a,l,c){r(a,u=>{t.webkitGetUserMedia(u,l,d=>{c&&c(s(d))})})};if(t.getUserMedia=o.bind(t),t.mediaDevices.getUserMedia){const a=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(l){return r(l,c=>a(c).then(u=>{if(c.audio&&!u.getAudioTracks().length||c.video&&!u.getVideoTracks().length)throw u.getTracks().forEach(d=>{d.stop()}),new DOMException("","NotFoundError");return u},u=>Promise.reject(s(u))))}}}function FZ(i,e){if(!(i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices)&&i.navigator.mediaDevices){if(typeof e!="function"){console.error("shimGetDisplayMedia: getSourceId argument is not a function");return}i.navigator.mediaDevices.getDisplayMedia=function(t){return e(t).then(n=>{const r=t.video&&t.video.width,s=t.video&&t.video.height,o=t.video&&t.video.frameRate;return t.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:n,maxFrameRate:o||3}},r&&(t.video.mandatory.maxWidth=r),s&&(t.video.mandatory.maxHeight=s),i.navigator.mediaDevices.getUserMedia(t)})}}}function fU(i){i.MediaStream=i.MediaStream||i.webkitMediaStream}function mU(i){if(typeof i=="object"&&i.RTCPeerConnection&&!("ontrack"in i.RTCPeerConnection.prototype)){Object.defineProperty(i.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(t){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=t)},enumerable:!0,configurable:!0});const e=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",n=>{let r;i.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(o=>o.track&&o.track.id===n.track.id):r={track:n.track};const s=new Event("track");s.track=n.track,s.receiver=r,s.transceiver={receiver:r},s.streams=[t.stream],this.dispatchEvent(s)}),t.stream.getTracks().forEach(n=>{let r;i.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(o=>o.track&&o.track.id===n.id):r={track:n};const s=new Event("track");s.track=n,s.receiver=r,s.transceiver={receiver:r},s.streams=[t.stream],this.dispatchEvent(s)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else Dp(i,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function gU(i){if(typeof i=="object"&&i.RTCPeerConnection&&!("getSenders"in i.RTCPeerConnection.prototype)&&"createDTMFSender"in i.RTCPeerConnection.prototype){const e=function(r,s){return{track:s,get dtmf(){return this._dtmf===void 0&&(s.kind==="audio"?this._dtmf=r.createDTMFSender(s):this._dtmf=null),this._dtmf},_pc:r}};if(!i.RTCPeerConnection.prototype.getSenders){i.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const r=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(o,a){let l=r.apply(this,arguments);return l||(l=e(this,o),this._senders.push(l)),l};const s=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(o){s.apply(this,arguments);const a=this._senders.indexOf(o);a!==-1&&this._senders.splice(a,1)}}const t=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(r){this._senders=this._senders||[],t.apply(this,[r]),r.getTracks().forEach(s=>{this._senders.push(e(this,s))})};const n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(r){this._senders=this._senders||[],n.apply(this,[r]),r.getTracks().forEach(s=>{const o=this._senders.find(a=>a.track===s);o&&this._senders.splice(this._senders.indexOf(o),1)})}}else if(typeof i=="object"&&i.RTCPeerConnection&&"getSenders"in i.RTCPeerConnection.prototype&&"createDTMFSender"in i.RTCPeerConnection.prototype&&i.RTCRtpSender&&!("dtmf"in i.RTCRtpSender.prototype)){const e=i.RTCPeerConnection.prototype.getSenders;i.RTCPeerConnection.prototype.getSenders=function(){const t=e.apply(this,[]);return t.forEach(n=>n._pc=this),t},Object.defineProperty(i.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function vU(i){if(!i.RTCPeerConnection)return;const e=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){const[t,n,r]=arguments;if(arguments.length>0&&typeof t=="function")return e.apply(this,arguments);if(e.length===0&&(arguments.length===0||typeof t!="function"))return e.apply(this,[]);const s=function(a){const l={};return a.result().forEach(c=>{const u={id:c.id,timestamp:c.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[c.type]||c.type};c.names().forEach(d=>{u[d]=c.stat(d)}),l[u.id]=u}),l},o=function(a){return new Map(Object.keys(a).map(l=>[l,a[l]]))};if(arguments.length>=2){const a=function(l){n(o(s(l)))};return e.apply(this,[a,t])}return new Promise((a,l)=>{e.apply(this,[function(c){a(o(s(c)))},l])}).then(n,r)}}function AU(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender&&i.RTCRtpReceiver))return;if(!("getStats"in i.RTCRtpSender.prototype)){const t=i.RTCPeerConnection.prototype.getSenders;t&&(i.RTCPeerConnection.prototype.getSenders=function(){const r=t.apply(this,[]);return r.forEach(s=>s._pc=this),r});const n=i.RTCPeerConnection.prototype.addTrack;n&&(i.RTCPeerConnection.prototype.addTrack=function(){const r=n.apply(this,arguments);return r._pc=this,r}),i.RTCRtpSender.prototype.getStats=function(){const r=this;return this._pc.getStats().then(s=>uU(s,r.track,!0))}}if(!("getStats"in i.RTCRtpReceiver.prototype)){const t=i.RTCPeerConnection.prototype.getReceivers;t&&(i.RTCPeerConnection.prototype.getReceivers=function(){const n=t.apply(this,[]);return n.forEach(r=>r._pc=this),n}),Dp(i,"track",n=>(n.receiver._pc=n.srcElement,n)),i.RTCRtpReceiver.prototype.getStats=function(){const n=this;return this._pc.getStats().then(r=>uU(r,n.track,!1))}}if(!("getStats"in i.RTCRtpSender.prototype&&"getStats"in i.RTCRtpReceiver.prototype))return;const e=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof i.MediaStreamTrack){const t=arguments[0];let n,r,s;return this.getSenders().forEach(o=>{o.track===t&&(n?s=!0:n=o)}),this.getReceivers().forEach(o=>(o.track===t&&(r?s=!0:r=o),o.track===t)),s||n&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):n?n.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function yU(i){i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(s=>this._shimmedLocalStreams[s][0])};const e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(s,o){if(!o)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const a=e.apply(this,arguments);return this._shimmedLocalStreams[o.id]?this._shimmedLocalStreams[o.id].indexOf(a)===-1&&this._shimmedLocalStreams[o.id].push(a):this._shimmedLocalStreams[o.id]=[o,a],a};const t=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(s){this._shimmedLocalStreams=this._shimmedLocalStreams||{},s.getTracks().forEach(l=>{if(this.getSenders().find(c=>c.track===l))throw new DOMException("Track already exists.","InvalidAccessError")});const o=this.getSenders();t.apply(this,arguments);const a=this.getSenders().filter(l=>o.indexOf(l)===-1);this._shimmedLocalStreams[s.id]=[s].concat(a)};const n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(s){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[s.id],n.apply(this,arguments)};const r=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(s){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},s&&Object.keys(this._shimmedLocalStreams).forEach(o=>{const a=this._shimmedLocalStreams[o].indexOf(s);a!==-1&&this._shimmedLocalStreams[o].splice(a,1),this._shimmedLocalStreams[o].length===1&&delete this._shimmedLocalStreams[o]}),r.apply(this,arguments)}}function bU(i,e){if(!i.RTCPeerConnection)return;if(i.RTCPeerConnection.prototype.addTrack&&e.version>=65)return yU(i);const t=i.RTCPeerConnection.prototype.getLocalStreams;i.RTCPeerConnection.prototype.getLocalStreams=function(){const c=t.apply(this);return this._reverseStreams=this._reverseStreams||{},c.map(u=>this._reverseStreams[u.id])};const n=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(c){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},c.getTracks().forEach(u=>{if(this.getSenders().find(d=>d.track===u))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[c.id]){const u=new i.MediaStream(c.getTracks());this._streams[c.id]=u,this._reverseStreams[u.id]=c,c=u}n.apply(this,[c])};const r=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(c){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[c.id]||c]),delete this._reverseStreams[this._streams[c.id]?this._streams[c.id].id:c.id],delete this._streams[c.id]},i.RTCPeerConnection.prototype.addTrack=function(c,u){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const d=[].slice.call(arguments,1);if(d.length!==1||!d[0].getTracks().find(f=>f===c))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(f=>f.track===c))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const p=this._streams[u.id];if(p)p.addTrack(c),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const f=new i.MediaStream([c]);this._streams[u.id]=f,this._reverseStreams[f.id]=u,this.addStream(f)}return this.getSenders().find(f=>f.track===c)};function s(c,u){let d=u.sdp;return Object.keys(c._reverseStreams||[]).forEach(p=>{const f=c._reverseStreams[p],m=c._streams[f.id];d=d.replace(new RegExp(m.id,"g"),f.id)}),new RTCSessionDescription({type:u.type,sdp:d})}function o(c,u){let d=u.sdp;return Object.keys(c._reverseStreams||[]).forEach(p=>{const f=c._reverseStreams[p],m=c._streams[f.id];d=d.replace(new RegExp(f.id,"g"),m.id)}),new RTCSessionDescription({type:u.type,sdp:d})}["createOffer","createAnswer"].forEach(function(c){const u=i.RTCPeerConnection.prototype[c],d={[c](){const p=arguments;return arguments.length&&typeof arguments[0]=="function"?u.apply(this,[f=>{const m=s(this,f);p[0].apply(null,[m])},f=>{p[1]&&p[1].apply(null,f)},arguments[2]]):u.apply(this,arguments).then(f=>s(this,f))}};i.RTCPeerConnection.prototype[c]=d[c]});const a=i.RTCPeerConnection.prototype.setLocalDescription;i.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?a.apply(this,arguments):(arguments[0]=o(this,arguments[0]),a.apply(this,arguments))};const l=Object.getOwnPropertyDescriptor(i.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(i.RTCPeerConnection.prototype,"localDescription",{get(){const c=l.get.apply(this);return c.type===""?c:s(this,c)}}),i.RTCPeerConnection.prototype.removeTrack=function(c){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!c._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(c._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let u;Object.keys(this._streams).forEach(d=>{this._streams[d].getTracks().find(p=>c.track===p)&&(u=this._streams[d])}),u&&(u.getTracks().length===1?this.removeStream(this._reverseStreams[u.id]):u.removeTrack(c.track),this.dispatchEvent(new Event("negotiationneeded")))}}function fM(i,e){!i.RTCPeerConnection&&i.webkitRTCPeerConnection&&(i.RTCPeerConnection=i.webkitRTCPeerConnection),i.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const n=i.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new(t==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};i.RTCPeerConnection.prototype[t]=r[t]})}function _U(i,e){Dp(i,"negotiationneeded",t=>{const n=t.target;if(!((e.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")&&n.signalingState!=="stable"))return t})}const xU=Object.freeze(Object.defineProperty({__proto__:null,fixNegotiationNeeded:_U,shimAddTrackRemoveTrack:bU,shimAddTrackRemoveTrackWithNative:yU,shimGetDisplayMedia:FZ,shimGetSendersWithDtmf:gU,shimGetStats:vU,shimGetUserMedia:pU,shimMediaStream:fU,shimOnTrack:mU,shimPeerConnection:fM,shimSenderReceiverGetStats:AU},Symbol.toStringTag,{value:"Module"}));function NZ(i,e){let t=!1;return i=JSON.parse(JSON.stringify(i)),i.filter(n=>{if(n&&(n.urls||n.url)){let r=n.urls||n.url;n.url&&!n.urls&&Gb("RTCIceServer.url","RTCIceServer.urls");const s=typeof r=="string";return s&&(r=[r]),r=r.filter(o=>{if(o.indexOf("stun:")===0)return!1;const a=o.startsWith("turn")&&!o.startsWith("turn:[")&&o.includes("transport=udp");return a&&!t?(t=!0,!0):a&&!t}),delete n.url,n.urls=s?r[0]:r,!!r.length}})}var wU={exports:{}};(function(i){var e={};e.generateIdentifier=function(){return Math.random().toString(36).substr(2,10)},e.localCName=e.generateIdentifier(),e.splitLines=function(t){return t.trim().split(`
4883
+ `+n,Ct.DrawLabel(t,r,.01)}onUpdateFrame(e){var t,n,r;if(this._handJointPoses.clear(),!this.xr.referenceSpace){this._isTracking=!1;return}const s=e.getPose(this.inputSource.targetRaySpace,this.xr.referenceSpace);if(this._isTracking=s!=null,s){const c=s.transform;this._rayPosition.set(c.position.x,c.position.y,c.position.z),this._rayQuaternion.set(c.orientation.x,c.orientation.y,c.orientation.z,c.orientation.w)}if(this.inputSource.gripSpace){const c=e.getPose(this.inputSource.gripSpace,this.xr.referenceSpace);if(c){const u=c.transform;if(this._gripPosition.set(u.position.x,u.position.y,u.position.z),this._gripQuaternion.set(u.orientation.x,u.orientation.y,u.orientation.z,u.orientation.w),"linearVelocity"in c&&c.linearVelocity){const d=c.linearVelocity;this._linearVelocity.set(d.x,d.y,d.z)}}}(t=this.xr.context.mainCamera)!=null&&t.parent&&this._object.parent!==((n=this.xr.context.mainCamera)==null?void 0:n.parent)&&this.xr.context.mainCamera.parent.add(this._object);const o=this.hand;if(o){let c=!1;const u=o.get("wrist"),d=u&&this.getHandJointPose(u);if(d){c=!0;const m=d.transform.position,A=d.transform.orientation;this._object.position.set(m.x,m.y,m.z),this._object.quaternion.set(A.x,A.y,A.z,A.w).multiply(Mo)}c||(this._object.position.copy(this._rayPosition),this._object.quaternion.copy(this._rayQuaternion).multiply(Mo));const p=o.get("middle-finger-metacarpal"),f=p&&this.getHandJointPose(p);if(f){const m=f.transform.position,A=f.transform.orientation;this._gripPosition.set(m.x,m.y,m.z),this._gripQuaternion.set(A.x,A.y,A.z,A.w)}}else this.inputSource.gripSpace&&this.targetRayMode==="transient-pointer"?(this._object.position.copy(this._gripPosition),this._object.quaternion.copy(this._gripQuaternion).multiply(Mo)):(this._object.position.copy(this._rayPosition),this._object.quaternion.copy(this._rayQuaternion).multiply(Mo));const a=(r=this.xr.context.mainCamera)==null?void 0:r.parent,l=a?xi(a):void 0;this._gripWorldPosition.copy(this._gripPosition),a&&this._gripWorldPosition.applyMatrix4(a.matrixWorld),this._gripWorldQuaternion.copy(this._gripQuaternion),this._gripWorldQuaternion.multiply(Mo),l&&this._gripWorldQuaternion.premultiply(l),this.updateRayWorldPosition(),this.updateRayWorldQuaternion()}onDisconnected(){this._connected=!1,Yc&&console.warn("Controller disconnected",this.index);for(const e of this._object.children)this.xr.context.scene.attach(e);this._object.removeFromParent(),this._debugAxesHelper.removeFromParent(),this.unsubscribeEvents()}getButton(e){var t;if(!this._layout)return;switch(e){case"primary-button":if(this.isLeft)e="x-button";else if(this.isRight)e="a-button";else return;break;case"primary":return this.toNeedleGamepadButton(0)}if(this._buttonMap.has(e))return this.toNeedleGamepadButton(this._buttonMap.get(e));const n=(t=this._layout)==null?void 0:t.components[e];if(n!=null&&n.gamepadIndices)switch(n.type){case"button":case"squeeze":if(this.inputSource.gamepad){const r=n.gamepadIndices.button;return this._buttonMap.set(e,r),this.toNeedleGamepadButton(r)}break;default:console.warn("Unsupported component type",n.type);break}this._buttonMap.set(e,void 0)}getGesture(e){const t=this.states[e];if(!t)return null;this.states[e]=t;const n=this._needleGamepadButtons[e]||new ZL;return n.pressed=t.pressed,n.value=t.value,n.isDown=t.isDown,n.isUp=t.isUp,this._needleGamepadButtons[e]=n,n}toNeedleGamepadButton(e){var t,n;if(!((t=this.inputSource.gamepad)!=null&&t.buttons))return;const r=(n=this.inputSource.gamepad)==null?void 0:n.buttons[e],s=this.states[e],o=this._needleGamepadButtons[e]||new ZL;return r&&(o.pressed=r.pressed,o.value=r.value,o.touched=r.touched),s&&(o.isDown=s.isDown,o.isUp=s.isUp),this._needleGamepadButtons[e]=o,o}getStick(e){var t,n,r,s,o,a,l;if(!this._layout)return{x:0,y:0,z:0};if(e==="primary"){const u=((t=this.inputSource.gamepad)==null?void 0:t.axes[0])||0,d=((n=this.inputSource.gamepad)==null?void 0:n.axes[1])||0,p=((r=this.inputSource.gamepad)==null?void 0:r.buttons[3].value)||0;return{x:u,y:d,z:p}}const c=(s=this._layout)==null?void 0:s.components[e];if(c!=null&&c.gamepadIndices)switch(c.type){case"thumbstick":if(this.inputSource.gamepad){const u=c.gamepadIndices.xAxis,d=c.gamepadIndices.yAxis;let p=(o=this.inputSource.gamepad)==null?void 0:o.axes[u],f=(a=this.inputSource.gamepad)==null?void 0:a.axes[d];p*=-1,f*=-1;const m=c.gamepadIndices.button,A=(l=this.inputSource.gamepad)==null?void 0:l.buttons[m].value;return{x:p,y:f,z:A}}}return{x:0,y:0,z:0}}initialize(){if(this._hasSelectEvent=this.profiles.includes("generic-hand-select")||this.profiles.some(e=>e.startsWith("generic-trigger")),!this._layout){if(this.inputSource.targetRayMode==="transient-pointer")return;const e=fZ(this.inputSource,CZ,EZ);this.getMotionController=e.then(t=>{var n;if(!this.connected)return null;this._motioncontroller=new yZ(this.inputSource,t.profile,t.assetPath||"");const r=t.profile.layouts[this.inputSource.handedness];if(this._layout=r,this._layout&&!((n=this._layout.gamepad)!=null&&n.length)){this._layout.gamepad=[];for(const s in this._layout.components){const o=this._layout.components[s];this._layout.gamepad[o.gamepadIndices.button]=s}}return this._motioncontroller}).catch(t=>(this.inputSource&&console.warn("Couldn't initialize motion controller profile for ",this.inputSource,t),null))}}subscribeEvents(){this.xr.session.addEventListener("selectstart",this.onSelectStart),this.xr.session.addEventListener("selectend",this.onSelectEnd),this.xr.session.addEventListener("squeezestart",this.onSequeezeStart),this.xr.session.addEventListener("squeezeend",this.onSequeezeEnd)}unsubscribeEvents(){this.xr.session.removeEventListener("selectstart",this.onSelectStart),this.xr.session.removeEventListener("selectend",this.onSelectEnd),this.xr.session.removeEventListener("squeezestart",this.onSequeezeStart),this.xr.session.removeEventListener("squeezeend",this.onSequeezeEnd)}updateInputEvents(){var e,t;if((e=this.gamepad)!=null&&e.buttons)for(let n=0;n<this.gamepad.buttons.length;n++){const r=this.gamepad.buttons[n],s=this.states[n]||new KL;let o=null;r.pressed&&!s.pressed?(o="pointerdown",s.isDown=!0,s.isUp=!1):!r.pressed&&s.pressed?(o="pointerup",s.isDown=!1,s.isUp=!0):(s.isDown=!1,s.isUp=!1),s.value=r.value,s.pressed=r.pressed,this.states[n]=s;const a=n!==this._selectButtonIndex&&n!==this._squeezeButtonIndex;if(o!=null&&a){const l=(t=this._layout)==null?void 0:t.gamepad[n];(Yc||Nb)&&console.log("Emitting pointer event",o,n,l,r.value,this.gamepad,this._layout),this.emitPointerEvent(o,n,l??"none",!1,null,r.value)}}if(this.hand){const n=this.handObject;if(n){const r=n.joints["index-finger-tip"],s=n.joints["thumb-tip"];if(r&&s){const o=r.position.distanceTo(s.position),a=this.states.pinch||new KL;a.value=o;const l=o<.02-.01,c=o>.02+.01;l&&!a.pressed?(Nb&&console.log("pinch start",o),a.isDown=!0,a.isUp=!1,a.pressed=!0):c&&a.pressed?(a.isDown=!1,a.isUp=!0,a.pressed=!1):(a.isDown=!1,a.isUp=!1),this.states.pinch=a}}}}onUpdateMove(){var e,t;let n=!1;if(this._lastPointerMovePosition.distanceTo(this.gripWorldPosition)>.02&&(n=!0),n||this._lastPointerMoveQuaternion.angleTo(this.gripWorldQuaternion)>.02&&(n=!0),n){this._didMoveLastFrame=!0,this._lastPointerMovePosition.copy(this.gripWorldPosition),this._lastPointerMoveQuaternion.copy(this.gripWorldQuaternion),Yc&&Ct.DrawLabel(this.rayWorldPosition.add(this.object.worldForward.multiplyScalar(.1)),"move",.01);let r=this.xr.context.input.getFirstPressedButtonForPointer(this.index);r===void 0&&(r=0);const s=(t=(e=this.gamepad)==null?void 0:e.buttons[r])==null?void 0:t.value;this.emitPointerEvent("pointermove",r,"none",!1,null,s)}else this._didMoveLastFrame=!1}emitPointerEvent(e,t,n,r,s=null,o){if(!this.emitEvents){Yc&&e!==Wi.PointerMove&&console.warn("Pointer events are disabled for this controller",this.index,e,t);return}if(this.xr.mode==="immersive-vr"||this.xr.isPassThrough){this.pointerInit.origin=this,this.pointerInit.pointerId=this.index*10+t,this.pointerInit.pointerType=this.hand?"hand":"controller",this.pointerInit.button=t,this.pointerInit.buttonName=n,this.pointerInit.isPrimary=r,this.pointerInit.mode=this.inputSource.targetRayMode,this.pointerInit.ray=this.ray,this.pointerInit.device=this.object,this.pointerInit.pressure=o;const a=Lt.Current;Lt.Current=this.xr.context,Yc&&e!=="pointermove"&&console.warn("Pointer event",e,t,n,{...this.pointerInit}),this.xr.context.input.createInputEvent(new Hl(e,s,this.pointerInit)),Lt.Current=a}}}class KL{constructor(){h(this,"isDown",!1),h(this,"isUp",!1),h(this,"pressed",!1),h(this,"value",0)}}class ZL{constructor(){h(this,"touched",!1),h(this,"pressed",!1),h(this,"value",0),h(this,"isDown",!1),h(this,"isUp",!1)}}const Eg=new Map;function Mg(i,e){Eg.has(e)||Eg.set(e,new Array),Eg.get(e).push(i)}function MZ(i,e){const t=Eg.get(e);if(t){const n=t.indexOf(i);n>=0&&t.splice(n,1)}}function Ou(i,e){const t=Eg.get(e);if(t&&t.length>0){let n=t;e===Pn.Start&&(n=[...t],t.length=0),TZ(i,n)}}function TZ(i,e){for(let t=e.length-1;t>=0;t--){const n=e[t];Pu(n,i)}}const zb=[];function oM(i){zb.indexOf(i)===-1&&zb.push(i)}function IZ(i){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-start",{detail:i}));for(let e=0;e<zb.length;e++)zb[e](i)}const aM=2,ja=4,Vl=4,lM=4,Jc=new Int32Array(2),$L=new Float32Array(Jc.buffer),e3=new Float64Array(Jc.buffer),jb=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1;class _c{constructor(e,t){this.low=e|0,this.high=t|0}static create(e,t){return e==0&&t==0?_c.ZERO:new _c(e,t)}toFloat64(){return(this.low>>>0)+this.high*4294967296}equals(e){return this.low==e.low&&this.high==e.high}}_c.ZERO=new _c(0,0);var cM;(function(i){i[i.UTF8_BYTES=1]="UTF8_BYTES",i[i.UTF16_STRING=2]="UTF16_STRING"})(cM||(cM={}));class J0{constructor(e){this.bytes_=e,this.position_=0}static allocate(e){return new J0(new Uint8Array(e))}clear(){this.position_=0}bytes(){return this.bytes_}position(){return this.position_}setPosition(e){this.position_=e}capacity(){return this.bytes_.length}readInt8(e){return this.readUint8(e)<<24>>24}readUint8(e){return this.bytes_[e]}readInt16(e){return this.readUint16(e)<<16>>16}readUint16(e){return this.bytes_[e]|this.bytes_[e+1]<<8}readInt32(e){return this.bytes_[e]|this.bytes_[e+1]<<8|this.bytes_[e+2]<<16|this.bytes_[e+3]<<24}readUint32(e){return this.readInt32(e)>>>0}readInt64(e){return new _c(this.readInt32(e),this.readInt32(e+4))}readUint64(e){return new _c(this.readUint32(e),this.readUint32(e+4))}readFloat32(e){return Jc[0]=this.readInt32(e),$L[0]}readFloat64(e){return Jc[jb?0:1]=this.readInt32(e),Jc[jb?1:0]=this.readInt32(e+4),e3[0]}writeInt8(e,t){this.bytes_[e]=t}writeUint8(e,t){this.bytes_[e]=t}writeInt16(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8}writeUint16(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8}writeInt32(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24}writeUint32(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24}writeInt64(e,t){this.writeInt32(e,t.low),this.writeInt32(e+4,t.high)}writeUint64(e,t){this.writeUint32(e,t.low),this.writeUint32(e+4,t.high)}writeFloat32(e,t){$L[0]=t,this.writeInt32(e,Jc[0])}writeFloat64(e,t){e3[0]=t,this.writeInt32(e,Jc[jb?0:1]),this.writeInt32(e+4,Jc[jb?1:0])}getBufferIdentifier(){if(this.bytes_.length<this.position_+ja+Vl)throw new Error("FlatBuffers: ByteBuffer is too short to contain an identifier.");let e="";for(let t=0;t<Vl;t++)e+=String.fromCharCode(this.readInt8(this.position_+ja+t));return e}__offset(e,t){const n=e-this.readInt32(e);return t<this.readInt16(n)?this.readInt16(n+t):0}__union(e,t){return e.bb_pos=t+this.readInt32(t),e.bb=this,e}__string(e,t){e+=this.readInt32(e);const n=this.readInt32(e);let r="",s=0;if(e+=ja,t===cM.UTF8_BYTES)return this.bytes_.subarray(e,e+n);for(;s<n;){let o;const a=this.readUint8(e+s++);if(a<192)o=a;else{const l=this.readUint8(e+s++);if(a<224)o=(a&31)<<6|l&63;else{const c=this.readUint8(e+s++);if(a<240)o=(a&15)<<12|(l&63)<<6|c&63;else{const u=this.readUint8(e+s++);o=(a&7)<<18|(l&63)<<12|(c&63)<<6|u&63}}}o<65536?r+=String.fromCharCode(o):(o-=65536,r+=String.fromCharCode((o>>10)+55296,(o&1024-1)+56320))}return r}__union_with_string(e,t){return typeof e=="string"?this.__string(t):this.__union(e,t)}__indirect(e){return e+this.readInt32(e)}__vector(e){return e+this.readInt32(e)+ja}__vector_len(e){return this.readInt32(e+this.readInt32(e))}__has_identifier(e){if(e.length!=Vl)throw new Error("FlatBuffers: file identifier must be length "+Vl);for(let t=0;t<Vl;t++)if(e.charCodeAt(t)!=this.readInt8(this.position()+ja+t))return!1;return!0}createLong(e,t){return _c.create(e,t)}createScalarList(e,t){const n=[];for(let r=0;r<t;++r)e(r)!==null&&n.push(e(r));return n}createObjList(e,t){const n=[];for(let r=0;r<t;++r){const s=e(r);s!==null&&n.push(s.unpack())}return n}}class K0{constructor(e){this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null;let t;e?t=e:t=1024,this.bb=J0.allocate(t),this.space=t}clear(){this.bb.clear(),this.space=this.bb.capacity(),this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null}forceDefaults(e){this.force_defaults=e}dataBuffer(){return this.bb}asUint8Array(){return this.bb.bytes().subarray(this.bb.position(),this.bb.position()+this.offset())}prep(e,t){e>this.minalign&&(this.minalign=e);const n=~(this.bb.capacity()-this.space+t)+1&e-1;for(;this.space<n+e+t;){const r=this.bb.capacity();this.bb=K0.growByteBuffer(this.bb),this.space+=this.bb.capacity()-r}this.pad(n)}pad(e){for(let t=0;t<e;t++)this.bb.writeInt8(--this.space,0)}writeInt8(e){this.bb.writeInt8(this.space-=1,e)}writeInt16(e){this.bb.writeInt16(this.space-=2,e)}writeInt32(e){this.bb.writeInt32(this.space-=4,e)}writeInt64(e){this.bb.writeInt64(this.space-=8,e)}writeFloat32(e){this.bb.writeFloat32(this.space-=4,e)}writeFloat64(e){this.bb.writeFloat64(this.space-=8,e)}addInt8(e){this.prep(1,0),this.writeInt8(e)}addInt16(e){this.prep(2,0),this.writeInt16(e)}addInt32(e){this.prep(4,0),this.writeInt32(e)}addInt64(e){this.prep(8,0),this.writeInt64(e)}addFloat32(e){this.prep(4,0),this.writeFloat32(e)}addFloat64(e){this.prep(8,0),this.writeFloat64(e)}addFieldInt8(e,t,n){(this.force_defaults||t!=n)&&(this.addInt8(t),this.slot(e))}addFieldInt16(e,t,n){(this.force_defaults||t!=n)&&(this.addInt16(t),this.slot(e))}addFieldInt32(e,t,n){(this.force_defaults||t!=n)&&(this.addInt32(t),this.slot(e))}addFieldInt64(e,t,n){(this.force_defaults||!t.equals(n))&&(this.addInt64(t),this.slot(e))}addFieldFloat32(e,t,n){(this.force_defaults||t!=n)&&(this.addFloat32(t),this.slot(e))}addFieldFloat64(e,t,n){(this.force_defaults||t!=n)&&(this.addFloat64(t),this.slot(e))}addFieldOffset(e,t,n){(this.force_defaults||t!=n)&&(this.addOffset(t),this.slot(e))}addFieldStruct(e,t,n){t!=n&&(this.nested(t),this.slot(e))}nested(e){if(e!=this.offset())throw new Error("FlatBuffers: struct must be serialized inline.")}notNested(){if(this.isNested)throw new Error("FlatBuffers: object serialization must not be nested.")}slot(e){this.vtable!==null&&(this.vtable[e]=this.offset())}offset(){return this.bb.capacity()-this.space}static growByteBuffer(e){const t=e.capacity();if(t&3221225472)throw new Error("FlatBuffers: cannot grow buffer beyond 2 gigabytes.");const n=t<<1,r=J0.allocate(n);return r.setPosition(n-t),r.bytes().set(e.bytes(),n-t),r}addOffset(e){this.prep(ja,0),this.writeInt32(this.offset()-e+ja)}startObject(e){this.notNested(),this.vtable==null&&(this.vtable=[]),this.vtable_in_use=e;for(let t=0;t<e;t++)this.vtable[t]=0;this.isNested=!0,this.object_start=this.offset()}endObject(){if(this.vtable==null||!this.isNested)throw new Error("FlatBuffers: endObject called without startObject");this.addInt32(0);const e=this.offset();let t=this.vtable_in_use-1;for(;t>=0&&this.vtable[t]==0;t--);const n=t+1;for(;t>=0;t--)this.addInt16(this.vtable[t]!=0?e-this.vtable[t]:0);const r=2;this.addInt16(e-this.object_start);const s=(n+r)*aM;this.addInt16(s);let o=0;const a=this.space;e:for(t=0;t<this.vtables.length;t++){const l=this.bb.capacity()-this.vtables[t];if(s==this.bb.readInt16(l)){for(let c=aM;c<s;c+=aM)if(this.bb.readInt16(a+c)!=this.bb.readInt16(l+c))continue e;o=this.vtables[t];break}}return o?(this.space=this.bb.capacity()-e,this.bb.writeInt32(this.space,o-e)):(this.vtables.push(this.offset()),this.bb.writeInt32(this.bb.capacity()-e,this.offset()-e)),this.isNested=!1,e}finish(e,t,n){const r=n?lM:0;if(t){const s=t;if(this.prep(this.minalign,ja+Vl+r),s.length!=Vl)throw new Error("FlatBuffers: file identifier must be length "+Vl);for(let o=Vl-1;o>=0;o--)this.writeInt8(s.charCodeAt(o))}this.prep(this.minalign,ja+r),this.addOffset(e),r&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(e,t){this.finish(e,t,!0)}requiredField(e,t){const n=this.bb.capacity()-e,r=n-this.bb.readInt32(n);if(this.bb.readInt16(r+t)==0)throw new Error("FlatBuffers: field "+t+" must be set")}startVector(e,t,n){this.notNested(),this.vector_num_elems=t,this.prep(ja,e*t),this.prep(n,e*t)}endVector(){return this.writeInt32(this.vector_num_elems),this.offset()}createSharedString(e){if(!e)return 0;if(this.string_maps||(this.string_maps=new Map),this.string_maps.has(e))return this.string_maps.get(e);const t=this.createString(e);return this.string_maps.set(e,t),t}createString(e){if(!e)return 0;let t;if(e instanceof Uint8Array)t=e;else{t=[];let n=0;for(;n<e.length;){let r;const s=e.charCodeAt(n++);if(s<55296||s>=56320)r=s;else{const o=e.charCodeAt(n++);r=(s<<10)+o+(65536-56623104-56320)}r<128?t.push(r):(r<2048?t.push(r>>6&31|192):(r<65536?t.push(r>>12&15|224):t.push(r>>18&7|240,r>>12&63|128),t.push(r>>6&63|128)),t.push(r&63|128))}}this.addInt8(0),this.startVector(1,t.length,1),this.bb.setPosition(this.space-=t.length);for(let n=0,r=this.space,s=this.bb.bytes();n<t.length;n++)s[r++]=t[n];return this.endVector()}createLong(e,t){return _c.create(e,t)}createObjectOffset(e){return e===null?0:typeof e=="string"?this.createString(e):e.pack(this)}createObjectOffsetList(e){const t=[];for(let n=0;n<e.length;++n){const r=e[n];if(r!==null)t.push(this.createObjectOffset(r));else throw new Error("FlatBuffers: Argument for createObjectOffsetList cannot contain null.")}return t}createStructOffsetList(e,t){return t(this,e.length),this.createObjectOffsetList(e),this.endVector()}}const hM={};function uM(i,e){hM[i]=e}function t3(i){const e=i.getBufferIdentifier(),t=hM[e];return t(i)}function i3(i){return typeof i.guid=="function"?i.guid():null}var n3={exports:{}};(function(i){var e={};e.useBlobBuilder=function(){try{return new Blob([]),!1}catch{return!0}}(),e.useArrayBufferView=!e.useBlobBuilder&&function(){try{return new Blob([new Uint8Array([])]).size===0}catch{return!0}}(),i.exports.binaryFeatures=e;var t=i.exports.BlobBuilder;typeof window<"u"&&(t=i.exports.BlobBuilder=window.WebKitBlobBuilder||window.MozBlobBuilder||window.MSBlobBuilder||window.BlobBuilder);function n(){this._pieces=[],this._parts=[]}n.prototype.append=function(r){typeof r=="number"?this._pieces.push(r):(this.flush(),this._parts.push(r))},n.prototype.flush=function(){if(this._pieces.length>0){var r=new Uint8Array(this._pieces);e.useArrayBufferView||(r=r.buffer),this._parts.push(r),this._pieces=[]}},n.prototype.getBuffer=function(){if(this.flush(),e.useBlobBuilder){for(var r=new t,s=0,o=this._parts.length;s<o;s++)r.append(this._parts[s]);return r.getBlob()}else return new Blob(this._parts)},i.exports.BufferBuilder=n})(n3);var r3=n3.exports,RZ=r3.BufferBuilder,s3=r3.binaryFeatures,PZ={unpack:function(i){var e=new gr(i);return e.unpack()},pack:function(i){var e=new vr;e.pack(i);var t=e.getBuffer();return t}},BZ=PZ;function gr(i){this.index=0,this.dataBuffer=i,this.dataView=new Uint8Array(this.dataBuffer),this.length=this.dataBuffer.byteLength}gr.prototype.unpack=function(){var i=this.unpack_uint8();if(i<128)return i;if((i^224)<32)return(i^224)-32;var e;if((e=i^160)<=15)return this.unpack_raw(e);if((e=i^176)<=15)return this.unpack_string(e);if((e=i^144)<=15)return this.unpack_array(e);if((e=i^128)<=15)return this.unpack_map(e);switch(i){case 192:return null;case 193:return;case 194:return!1;case 195:return!0;case 202:return this.unpack_float();case 203:return this.unpack_double();case 204:return this.unpack_uint8();case 205:return this.unpack_uint16();case 206:return this.unpack_uint32();case 207:return this.unpack_uint64();case 208:return this.unpack_int8();case 209:return this.unpack_int16();case 210:return this.unpack_int32();case 211:return this.unpack_int64();case 212:return;case 213:return;case 214:return;case 215:return;case 216:return e=this.unpack_uint16(),this.unpack_string(e);case 217:return e=this.unpack_uint32(),this.unpack_string(e);case 218:return e=this.unpack_uint16(),this.unpack_raw(e);case 219:return e=this.unpack_uint32(),this.unpack_raw(e);case 220:return e=this.unpack_uint16(),this.unpack_array(e);case 221:return e=this.unpack_uint32(),this.unpack_array(e);case 222:return e=this.unpack_uint16(),this.unpack_map(e);case 223:return e=this.unpack_uint32(),this.unpack_map(e)}},gr.prototype.unpack_uint8=function(){var i=this.dataView[this.index]&255;return this.index++,i},gr.prototype.unpack_uint16=function(){var i=this.read(2),e=(i[0]&255)*256+(i[1]&255);return this.index+=2,e},gr.prototype.unpack_uint32=function(){var i=this.read(4),e=((i[0]*256+i[1])*256+i[2])*256+i[3];return this.index+=4,e},gr.prototype.unpack_uint64=function(){var i=this.read(8),e=((((((i[0]*256+i[1])*256+i[2])*256+i[3])*256+i[4])*256+i[5])*256+i[6])*256+i[7];return this.index+=8,e},gr.prototype.unpack_int8=function(){var i=this.unpack_uint8();return i<128?i:i-256},gr.prototype.unpack_int16=function(){var i=this.unpack_uint16();return i<32768?i:i-65536},gr.prototype.unpack_int32=function(){var i=this.unpack_uint32();return i<Math.pow(2,31)?i:i-Math.pow(2,32)},gr.prototype.unpack_int64=function(){var i=this.unpack_uint64();return i<Math.pow(2,63)?i:i-Math.pow(2,64)},gr.prototype.unpack_raw=function(i){if(this.length<this.index+i)throw new Error("BinaryPackFailure: index is out of range "+this.index+" "+i+" "+this.length);var e=this.dataBuffer.slice(this.index,this.index+i);return this.index+=i,e},gr.prototype.unpack_string=function(i){for(var e=this.read(i),t=0,n="",r,s;t<i;)r=e[t],r<128?(n+=String.fromCharCode(r),t++):(r^192)<32?(s=(r^192)<<6|e[t+1]&63,n+=String.fromCharCode(s),t+=2):(s=(r&15)<<12|(e[t+1]&63)<<6|e[t+2]&63,n+=String.fromCharCode(s),t+=3);return this.index+=i,n},gr.prototype.unpack_array=function(i){for(var e=new Array(i),t=0;t<i;t++)e[t]=this.unpack();return e},gr.prototype.unpack_map=function(i){for(var e={},t=0;t<i;t++){var n=this.unpack(),r=this.unpack();e[n]=r}return e},gr.prototype.unpack_float=function(){var i=this.unpack_uint32(),e=i>>31,t=(i>>23&255)-127,n=i&8388607|8388608;return(e===0?1:-1)*n*Math.pow(2,t-23)},gr.prototype.unpack_double=function(){var i=this.unpack_uint32(),e=this.unpack_uint32(),t=i>>31,n=(i>>20&2047)-1023,r=i&1048575|1048576,s=r*Math.pow(2,n-20)+e*Math.pow(2,n-52);return(t===0?1:-1)*s},gr.prototype.read=function(i){var e=this.index;if(e+i<=this.length)return this.dataView.subarray(e,e+i);throw new Error("BinaryPackFailure: read index out of range")};function vr(){this.bufferBuilder=new RZ}vr.prototype.getBuffer=function(){return this.bufferBuilder.getBuffer()},vr.prototype.pack=function(i){var e=typeof i;if(e==="string")this.pack_string(i);else if(e==="number")Math.floor(i)===i?this.pack_integer(i):this.pack_double(i);else if(e==="boolean")i===!0?this.bufferBuilder.append(195):i===!1&&this.bufferBuilder.append(194);else if(e==="undefined")this.bufferBuilder.append(192);else if(e==="object")if(i===null)this.bufferBuilder.append(192);else{var t=i.constructor;if(t==Array)this.pack_array(i);else if(t==Blob||t==File||i instanceof Blob||i instanceof File)this.pack_bin(i);else if(t==ArrayBuffer)s3.useArrayBufferView?this.pack_bin(new Uint8Array(i)):this.pack_bin(i);else if("BYTES_PER_ELEMENT"in i)s3.useArrayBufferView?this.pack_bin(new Uint8Array(i.buffer)):this.pack_bin(i.buffer);else if(t==Object||t.toString().startsWith("class"))this.pack_object(i);else if(t==Date)this.pack_string(i.toString());else if(typeof i.toBinaryPack=="function")this.bufferBuilder.append(i.toBinaryPack());else throw new Error('Type "'+t.toString()+'" not yet supported')}else throw new Error('Type "'+e+'" not yet supported');this.bufferBuilder.flush()},vr.prototype.pack_bin=function(i){var e=i.length||i.byteLength||i.size;if(e<=15)this.pack_uint8(160+e);else if(e<=65535)this.bufferBuilder.append(218),this.pack_uint16(e);else if(e<=4294967295)this.bufferBuilder.append(219),this.pack_uint32(e);else throw new Error("Invalid length");this.bufferBuilder.append(i)},vr.prototype.pack_string=function(i){var e=OZ(i);if(e<=15)this.pack_uint8(176+e);else if(e<=65535)this.bufferBuilder.append(216),this.pack_uint16(e);else if(e<=4294967295)this.bufferBuilder.append(217),this.pack_uint32(e);else throw new Error("Invalid length");this.bufferBuilder.append(i)},vr.prototype.pack_array=function(i){var e=i.length;if(e<=15)this.pack_uint8(144+e);else if(e<=65535)this.bufferBuilder.append(220),this.pack_uint16(e);else if(e<=4294967295)this.bufferBuilder.append(221),this.pack_uint32(e);else throw new Error("Invalid length");for(var t=0;t<e;t++)this.pack(i[t])},vr.prototype.pack_integer=function(i){if(i>=-32&&i<=127)this.bufferBuilder.append(i&255);else if(i>=0&&i<=255)this.bufferBuilder.append(204),this.pack_uint8(i);else if(i>=-128&&i<=127)this.bufferBuilder.append(208),this.pack_int8(i);else if(i>=0&&i<=65535)this.bufferBuilder.append(205),this.pack_uint16(i);else if(i>=-32768&&i<=32767)this.bufferBuilder.append(209),this.pack_int16(i);else if(i>=0&&i<=4294967295)this.bufferBuilder.append(206),this.pack_uint32(i);else if(i>=-2147483648&&i<=2147483647)this.bufferBuilder.append(210),this.pack_int32(i);else if(i>=-9223372036854776e3&&i<=9223372036854776e3)this.bufferBuilder.append(211),this.pack_int64(i);else if(i>=0&&i<=18446744073709552e3)this.bufferBuilder.append(207),this.pack_uint64(i);else throw new Error("Invalid integer")},vr.prototype.pack_double=function(i){var e=0;i<0&&(e=1,i=-i);var t=Math.floor(Math.log(i)/Math.LN2),n=i/Math.pow(2,t)-1,r=Math.floor(n*Math.pow(2,52)),s=Math.pow(2,32),o=e<<31|t+1023<<20|r/s&1048575,a=r%s;this.bufferBuilder.append(203),this.pack_int32(o),this.pack_int32(a)},vr.prototype.pack_object=function(i){var e=Object.keys(i),t=e.length;if(t<=15)this.pack_uint8(128+t);else if(t<=65535)this.bufferBuilder.append(222),this.pack_uint16(t);else if(t<=4294967295)this.bufferBuilder.append(223),this.pack_uint32(t);else throw new Error("Invalid length");for(var n in i)i.hasOwnProperty(n)&&(this.pack(n),this.pack(i[n]))},vr.prototype.pack_uint8=function(i){this.bufferBuilder.append(i)},vr.prototype.pack_uint16=function(i){this.bufferBuilder.append(i>>8),this.bufferBuilder.append(i&255)},vr.prototype.pack_uint32=function(i){var e=i&4294967295;this.bufferBuilder.append((e&4278190080)>>>24),this.bufferBuilder.append((e&16711680)>>>16),this.bufferBuilder.append((e&65280)>>>8),this.bufferBuilder.append(e&255)},vr.prototype.pack_uint64=function(i){var e=i/Math.pow(2,32),t=i%Math.pow(2,32);this.bufferBuilder.append((e&4278190080)>>>24),this.bufferBuilder.append((e&16711680)>>>16),this.bufferBuilder.append((e&65280)>>>8),this.bufferBuilder.append(e&255),this.bufferBuilder.append((t&4278190080)>>>24),this.bufferBuilder.append((t&16711680)>>>16),this.bufferBuilder.append((t&65280)>>>8),this.bufferBuilder.append(t&255)},vr.prototype.pack_int8=function(i){this.bufferBuilder.append(i&255)},vr.prototype.pack_int16=function(i){this.bufferBuilder.append((i&65280)>>8),this.bufferBuilder.append(i&255)},vr.prototype.pack_int32=function(i){this.bufferBuilder.append(i>>>24&255),this.bufferBuilder.append((i&16711680)>>>16),this.bufferBuilder.append((i&65280)>>>8),this.bufferBuilder.append(i&255)},vr.prototype.pack_int64=function(i){var e=Math.floor(i/Math.pow(2,32)),t=i%Math.pow(2,32);this.bufferBuilder.append((e&4278190080)>>>24),this.bufferBuilder.append((e&16711680)>>>16),this.bufferBuilder.append((e&65280)>>>8),this.bufferBuilder.append(e&255),this.bufferBuilder.append((t&4278190080)>>>24),this.bufferBuilder.append((t&16711680)>>>16),this.bufferBuilder.append((t&65280)>>>8),this.bufferBuilder.append(t&255)};function DZ(i){var e=i.charCodeAt(0);return e<=2047?"00":e<=65535?"000":e<=2097151?"0000":e<=67108863?"00000":"000000"}function OZ(i){return i.length>600?new Blob([i]).size:i.replace(/[^\u0000-\u007F]/g,DZ).length}const o3=Bb(BZ);let a3=!0,l3=!0;function Tg(i,e,t){const n=i.match(e);return n&&n.length>=t&&parseInt(n[t],10)}function Dp(i,e,t){if(!i.RTCPeerConnection)return;const n=i.RTCPeerConnection.prototype,r=n.addEventListener;n.addEventListener=function(o,a){if(o!==e)return r.apply(this,arguments);const l=c=>{const u=t(c);u&&(a.handleEvent?a.handleEvent(u):a(u))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(a,l),r.apply(this,[o,l])};const s=n.removeEventListener;n.removeEventListener=function(o,a){if(o!==e||!this._eventMap||!this._eventMap[e])return s.apply(this,arguments);if(!this._eventMap[e].has(a))return s.apply(this,arguments);const l=this._eventMap[e].get(a);return this._eventMap[e].delete(a),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,s.apply(this,[o,l])},Object.defineProperty(n,"on"+e,{get(){return this["_on"+e]},set(o){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),o&&this.addEventListener(e,this["_on"+e]=o)},enumerable:!0,configurable:!0})}function kZ(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(a3=i,i?"adapter.js logging disabled":"adapter.js logging enabled")}function LZ(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(l3=!i,"adapter.js deprecation warnings "+(i?"disabled":"enabled"))}function dM(){if(typeof window=="object"){if(a3)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function Gb(i,e){l3&&console.warn(i+" is deprecated, please use "+e+" instead.")}function UZ(i){const e={browser:null,version:null};if(typeof i>"u"||!i.navigator)return e.browser="Not a browser.",e;const{navigator:t}=i;if(t.mozGetUserMedia)e.browser="firefox",e.version=Tg(t.userAgent,/Firefox\/(\d+)\./,1);else if(t.webkitGetUserMedia||i.isSecureContext===!1&&i.webkitRTCPeerConnection&&!i.RTCIceGatherer)e.browser="chrome",e.version=Tg(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(t.mediaDevices&&t.userAgent.match(/Edge\/(\d+).(\d+)$/))e.browser="edge",e.version=Tg(t.userAgent,/Edge\/(\d+).(\d+)$/,2);else if(i.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=Tg(t.userAgent,/AppleWebKit\/(\d+)\./,1),e.supportsUnifiedPlan=i.RTCRtpTransceiver&&"currentDirection"in i.RTCRtpTransceiver.prototype;else return e.browser="Not a supported browser.",e;return e}function c3(i){return Object.prototype.toString.call(i)==="[object Object]"}function h3(i){return c3(i)?Object.keys(i).reduce(function(e,t){const n=c3(i[t]),r=n?h3(i[t]):i[t],s=n&&!Object.keys(r).length;return r===void 0||s?e:Object.assign(e,{[t]:r})},{}):i}function pM(i,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(n=>{n.endsWith("Id")?pM(i,i.get(e[n]),t):n.endsWith("Ids")&&e[n].forEach(r=>{pM(i,i.get(r),t)})}))}function u3(i,e,t){const n=t?"outbound-rtp":"inbound-rtp",r=new Map;if(e===null)return r;const s=[];return i.forEach(o=>{o.type==="track"&&o.trackIdentifier===e.id&&s.push(o)}),s.forEach(o=>{i.forEach(a=>{a.type===n&&a.trackId===o.id&&pM(i,a,r)})}),r}const d3=dM;function p3(i,e){const t=i&&i.navigator;if(!t.mediaDevices)return;const n=function(a){if(typeof a!="object"||a.mandatory||a.optional)return a;const l={};return Object.keys(a).forEach(c=>{if(c==="require"||c==="advanced"||c==="mediaSource")return;const u=typeof a[c]=="object"?a[c]:{ideal:a[c]};u.exact!==void 0&&typeof u.exact=="number"&&(u.min=u.max=u.exact);const d=function(p,f){return p?p+f.charAt(0).toUpperCase()+f.slice(1):f==="deviceId"?"sourceId":f};if(u.ideal!==void 0){l.optional=l.optional||[];let p={};typeof u.ideal=="number"?(p[d("min",c)]=u.ideal,l.optional.push(p),p={},p[d("max",c)]=u.ideal,l.optional.push(p)):(p[d("",c)]=u.ideal,l.optional.push(p))}u.exact!==void 0&&typeof u.exact!="number"?(l.mandatory=l.mandatory||{},l.mandatory[d("",c)]=u.exact):["min","max"].forEach(p=>{u[p]!==void 0&&(l.mandatory=l.mandatory||{},l.mandatory[d(p,c)]=u[p])})}),a.advanced&&(l.optional=(l.optional||[]).concat(a.advanced)),l},r=function(a,l){if(e.version>=61)return l(a);if(a=JSON.parse(JSON.stringify(a)),a&&typeof a.audio=="object"){const c=function(u,d,p){d in u&&!(p in u)&&(u[p]=u[d],delete u[d])};a=JSON.parse(JSON.stringify(a)),c(a.audio,"autoGainControl","googAutoGainControl"),c(a.audio,"noiseSuppression","googNoiseSuppression"),a.audio=n(a.audio)}if(a&&typeof a.video=="object"){let c=a.video.facingMode;c=c&&(typeof c=="object"?c:{ideal:c});const u=e.version<66;if(c&&(c.exact==="user"||c.exact==="environment"||c.ideal==="user"||c.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!u)){delete a.video.facingMode;let d;if(c.exact==="environment"||c.ideal==="environment"?d=["back","rear"]:(c.exact==="user"||c.ideal==="user")&&(d=["front"]),d)return t.mediaDevices.enumerateDevices().then(p=>{p=p.filter(m=>m.kind==="videoinput");let f=p.find(m=>d.some(A=>m.label.toLowerCase().includes(A)));return!f&&p.length&&d.includes("back")&&(f=p[p.length-1]),f&&(a.video.deviceId=c.exact?{exact:f.deviceId}:{ideal:f.deviceId}),a.video=n(a.video),d3("chrome: "+JSON.stringify(a)),l(a)})}a.video=n(a.video)}return d3("chrome: "+JSON.stringify(a)),l(a)},s=function(a){return e.version>=64?a:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[a.name]||a.name,message:a.message,constraint:a.constraint||a.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},o=function(a,l,c){r(a,u=>{t.webkitGetUserMedia(u,l,d=>{c&&c(s(d))})})};if(t.getUserMedia=o.bind(t),t.mediaDevices.getUserMedia){const a=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(l){return r(l,c=>a(c).then(u=>{if(c.audio&&!u.getAudioTracks().length||c.video&&!u.getVideoTracks().length)throw u.getTracks().forEach(d=>{d.stop()}),new DOMException("","NotFoundError");return u},u=>Promise.reject(s(u))))}}}function FZ(i,e){if(!(i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices)&&i.navigator.mediaDevices){if(typeof e!="function"){console.error("shimGetDisplayMedia: getSourceId argument is not a function");return}i.navigator.mediaDevices.getDisplayMedia=function(t){return e(t).then(n=>{const r=t.video&&t.video.width,s=t.video&&t.video.height,o=t.video&&t.video.frameRate;return t.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:n,maxFrameRate:o||3}},r&&(t.video.mandatory.maxWidth=r),s&&(t.video.mandatory.maxHeight=s),i.navigator.mediaDevices.getUserMedia(t)})}}}function f3(i){i.MediaStream=i.MediaStream||i.webkitMediaStream}function m3(i){if(typeof i=="object"&&i.RTCPeerConnection&&!("ontrack"in i.RTCPeerConnection.prototype)){Object.defineProperty(i.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(t){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=t)},enumerable:!0,configurable:!0});const e=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",n=>{let r;i.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(o=>o.track&&o.track.id===n.track.id):r={track:n.track};const s=new Event("track");s.track=n.track,s.receiver=r,s.transceiver={receiver:r},s.streams=[t.stream],this.dispatchEvent(s)}),t.stream.getTracks().forEach(n=>{let r;i.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(o=>o.track&&o.track.id===n.id):r={track:n};const s=new Event("track");s.track=n,s.receiver=r,s.transceiver={receiver:r},s.streams=[t.stream],this.dispatchEvent(s)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else Dp(i,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function g3(i){if(typeof i=="object"&&i.RTCPeerConnection&&!("getSenders"in i.RTCPeerConnection.prototype)&&"createDTMFSender"in i.RTCPeerConnection.prototype){const e=function(r,s){return{track:s,get dtmf(){return this._dtmf===void 0&&(s.kind==="audio"?this._dtmf=r.createDTMFSender(s):this._dtmf=null),this._dtmf},_pc:r}};if(!i.RTCPeerConnection.prototype.getSenders){i.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const r=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(o,a){let l=r.apply(this,arguments);return l||(l=e(this,o),this._senders.push(l)),l};const s=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(o){s.apply(this,arguments);const a=this._senders.indexOf(o);a!==-1&&this._senders.splice(a,1)}}const t=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(r){this._senders=this._senders||[],t.apply(this,[r]),r.getTracks().forEach(s=>{this._senders.push(e(this,s))})};const n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(r){this._senders=this._senders||[],n.apply(this,[r]),r.getTracks().forEach(s=>{const o=this._senders.find(a=>a.track===s);o&&this._senders.splice(this._senders.indexOf(o),1)})}}else if(typeof i=="object"&&i.RTCPeerConnection&&"getSenders"in i.RTCPeerConnection.prototype&&"createDTMFSender"in i.RTCPeerConnection.prototype&&i.RTCRtpSender&&!("dtmf"in i.RTCRtpSender.prototype)){const e=i.RTCPeerConnection.prototype.getSenders;i.RTCPeerConnection.prototype.getSenders=function(){const t=e.apply(this,[]);return t.forEach(n=>n._pc=this),t},Object.defineProperty(i.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function v3(i){if(!i.RTCPeerConnection)return;const e=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){const[t,n,r]=arguments;if(arguments.length>0&&typeof t=="function")return e.apply(this,arguments);if(e.length===0&&(arguments.length===0||typeof t!="function"))return e.apply(this,[]);const s=function(a){const l={};return a.result().forEach(c=>{const u={id:c.id,timestamp:c.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[c.type]||c.type};c.names().forEach(d=>{u[d]=c.stat(d)}),l[u.id]=u}),l},o=function(a){return new Map(Object.keys(a).map(l=>[l,a[l]]))};if(arguments.length>=2){const a=function(l){n(o(s(l)))};return e.apply(this,[a,t])}return new Promise((a,l)=>{e.apply(this,[function(c){a(o(s(c)))},l])}).then(n,r)}}function A3(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender&&i.RTCRtpReceiver))return;if(!("getStats"in i.RTCRtpSender.prototype)){const t=i.RTCPeerConnection.prototype.getSenders;t&&(i.RTCPeerConnection.prototype.getSenders=function(){const r=t.apply(this,[]);return r.forEach(s=>s._pc=this),r});const n=i.RTCPeerConnection.prototype.addTrack;n&&(i.RTCPeerConnection.prototype.addTrack=function(){const r=n.apply(this,arguments);return r._pc=this,r}),i.RTCRtpSender.prototype.getStats=function(){const r=this;return this._pc.getStats().then(s=>u3(s,r.track,!0))}}if(!("getStats"in i.RTCRtpReceiver.prototype)){const t=i.RTCPeerConnection.prototype.getReceivers;t&&(i.RTCPeerConnection.prototype.getReceivers=function(){const n=t.apply(this,[]);return n.forEach(r=>r._pc=this),n}),Dp(i,"track",n=>(n.receiver._pc=n.srcElement,n)),i.RTCRtpReceiver.prototype.getStats=function(){const n=this;return this._pc.getStats().then(r=>u3(r,n.track,!1))}}if(!("getStats"in i.RTCRtpSender.prototype&&"getStats"in i.RTCRtpReceiver.prototype))return;const e=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof i.MediaStreamTrack){const t=arguments[0];let n,r,s;return this.getSenders().forEach(o=>{o.track===t&&(n?s=!0:n=o)}),this.getReceivers().forEach(o=>(o.track===t&&(r?s=!0:r=o),o.track===t)),s||n&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):n?n.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function y3(i){i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(s=>this._shimmedLocalStreams[s][0])};const e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(s,o){if(!o)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const a=e.apply(this,arguments);return this._shimmedLocalStreams[o.id]?this._shimmedLocalStreams[o.id].indexOf(a)===-1&&this._shimmedLocalStreams[o.id].push(a):this._shimmedLocalStreams[o.id]=[o,a],a};const t=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(s){this._shimmedLocalStreams=this._shimmedLocalStreams||{},s.getTracks().forEach(l=>{if(this.getSenders().find(c=>c.track===l))throw new DOMException("Track already exists.","InvalidAccessError")});const o=this.getSenders();t.apply(this,arguments);const a=this.getSenders().filter(l=>o.indexOf(l)===-1);this._shimmedLocalStreams[s.id]=[s].concat(a)};const n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(s){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[s.id],n.apply(this,arguments)};const r=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(s){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},s&&Object.keys(this._shimmedLocalStreams).forEach(o=>{const a=this._shimmedLocalStreams[o].indexOf(s);a!==-1&&this._shimmedLocalStreams[o].splice(a,1),this._shimmedLocalStreams[o].length===1&&delete this._shimmedLocalStreams[o]}),r.apply(this,arguments)}}function b3(i,e){if(!i.RTCPeerConnection)return;if(i.RTCPeerConnection.prototype.addTrack&&e.version>=65)return y3(i);const t=i.RTCPeerConnection.prototype.getLocalStreams;i.RTCPeerConnection.prototype.getLocalStreams=function(){const c=t.apply(this);return this._reverseStreams=this._reverseStreams||{},c.map(u=>this._reverseStreams[u.id])};const n=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(c){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},c.getTracks().forEach(u=>{if(this.getSenders().find(d=>d.track===u))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[c.id]){const u=new i.MediaStream(c.getTracks());this._streams[c.id]=u,this._reverseStreams[u.id]=c,c=u}n.apply(this,[c])};const r=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(c){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[c.id]||c]),delete this._reverseStreams[this._streams[c.id]?this._streams[c.id].id:c.id],delete this._streams[c.id]},i.RTCPeerConnection.prototype.addTrack=function(c,u){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const d=[].slice.call(arguments,1);if(d.length!==1||!d[0].getTracks().find(f=>f===c))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(f=>f.track===c))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const p=this._streams[u.id];if(p)p.addTrack(c),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const f=new i.MediaStream([c]);this._streams[u.id]=f,this._reverseStreams[f.id]=u,this.addStream(f)}return this.getSenders().find(f=>f.track===c)};function s(c,u){let d=u.sdp;return Object.keys(c._reverseStreams||[]).forEach(p=>{const f=c._reverseStreams[p],m=c._streams[f.id];d=d.replace(new RegExp(m.id,"g"),f.id)}),new RTCSessionDescription({type:u.type,sdp:d})}function o(c,u){let d=u.sdp;return Object.keys(c._reverseStreams||[]).forEach(p=>{const f=c._reverseStreams[p],m=c._streams[f.id];d=d.replace(new RegExp(f.id,"g"),m.id)}),new RTCSessionDescription({type:u.type,sdp:d})}["createOffer","createAnswer"].forEach(function(c){const u=i.RTCPeerConnection.prototype[c],d={[c](){const p=arguments;return arguments.length&&typeof arguments[0]=="function"?u.apply(this,[f=>{const m=s(this,f);p[0].apply(null,[m])},f=>{p[1]&&p[1].apply(null,f)},arguments[2]]):u.apply(this,arguments).then(f=>s(this,f))}};i.RTCPeerConnection.prototype[c]=d[c]});const a=i.RTCPeerConnection.prototype.setLocalDescription;i.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?a.apply(this,arguments):(arguments[0]=o(this,arguments[0]),a.apply(this,arguments))};const l=Object.getOwnPropertyDescriptor(i.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(i.RTCPeerConnection.prototype,"localDescription",{get(){const c=l.get.apply(this);return c.type===""?c:s(this,c)}}),i.RTCPeerConnection.prototype.removeTrack=function(c){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!c._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(c._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let u;Object.keys(this._streams).forEach(d=>{this._streams[d].getTracks().find(p=>c.track===p)&&(u=this._streams[d])}),u&&(u.getTracks().length===1?this.removeStream(this._reverseStreams[u.id]):u.removeTrack(c.track),this.dispatchEvent(new Event("negotiationneeded")))}}function fM(i,e){!i.RTCPeerConnection&&i.webkitRTCPeerConnection&&(i.RTCPeerConnection=i.webkitRTCPeerConnection),i.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const n=i.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new(t==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};i.RTCPeerConnection.prototype[t]=r[t]})}function _3(i,e){Dp(i,"negotiationneeded",t=>{const n=t.target;if(!((e.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")&&n.signalingState!=="stable"))return t})}const x3=Object.freeze(Object.defineProperty({__proto__:null,fixNegotiationNeeded:_3,shimAddTrackRemoveTrack:b3,shimAddTrackRemoveTrackWithNative:y3,shimGetDisplayMedia:FZ,shimGetSendersWithDtmf:g3,shimGetStats:v3,shimGetUserMedia:p3,shimMediaStream:f3,shimOnTrack:m3,shimPeerConnection:fM,shimSenderReceiverGetStats:A3},Symbol.toStringTag,{value:"Module"}));function NZ(i,e){let t=!1;return i=JSON.parse(JSON.stringify(i)),i.filter(n=>{if(n&&(n.urls||n.url)){let r=n.urls||n.url;n.url&&!n.urls&&Gb("RTCIceServer.url","RTCIceServer.urls");const s=typeof r=="string";return s&&(r=[r]),r=r.filter(o=>{if(o.indexOf("stun:")===0)return!1;const a=o.startsWith("turn")&&!o.startsWith("turn:[")&&o.includes("transport=udp");return a&&!t?(t=!0,!0):a&&!t}),delete n.url,n.urls=s?r[0]:r,!!r.length}})}var w3={exports:{}};(function(i){var e={};e.generateIdentifier=function(){return Math.random().toString(36).substr(2,10)},e.localCName=e.generateIdentifier(),e.splitLines=function(t){return t.trim().split(`
4884
4884
  `).map(function(n){return n.trim()})},e.splitSections=function(t){var n=t.split(`
4885
4885
  m=`);return n.map(function(r,s){return(s>0?"m="+r:r).trim()+`\r
4886
4886
  `})},e.getDescription=function(t){var n=e.splitSections(t);return n&&n[0]},e.getMediaSections=function(t){var n=e.splitSections(t);return n.shift(),n},e.matchPrefix=function(t,n){return e.splitLines(t).filter(function(r){return r.indexOf(n)===0})},e.parseCandidate=function(t){var n;t.indexOf("a=candidate:")===0?n=t.substring(12).split(" "):n=t.substring(10).split(" ");for(var r={foundation:n[0],component:parseInt(n[1],10),protocol:n[2].toLowerCase(),priority:parseInt(n[3],10),ip:n[4],address:n[4],port:parseInt(n[5],10),type:n[7]},s=8;s<n.length;s+=2)switch(n[s]){case"raddr":r.relatedAddress=n[s+1];break;case"rport":r.relatedPort=parseInt(n[s+1],10);break;case"tcptype":r.tcpType=n[s+1];break;case"ufrag":r.ufrag=n[s+1],r.usernameFragment=n[s+1];break;default:r[n[s]]=n[s+1];break}return r},e.writeCandidate=function(t){var n=[];n.push(t.foundation),n.push(t.component),n.push(t.protocol.toUpperCase()),n.push(t.priority),n.push(t.address||t.ip),n.push(t.port);var r=t.type;return n.push("typ"),n.push(r),r!=="host"&&t.relatedAddress&&t.relatedPort&&(n.push("raddr"),n.push(t.relatedAddress),n.push("rport"),n.push(t.relatedPort)),t.tcpType&&t.protocol.toLowerCase()==="tcp"&&(n.push("tcptype"),n.push(t.tcpType)),(t.usernameFragment||t.ufrag)&&(n.push("ufrag"),n.push(t.usernameFragment||t.ufrag)),"candidate:"+n.join(" ")},e.parseIceOptions=function(t){return t.substr(14).split(" ")},e.parseRtpMap=function(t){var n=t.substr(9).split(" "),r={payloadType:parseInt(n.shift(),10)};return n=n[0].split("/"),r.name=n[0],r.clockRate=parseInt(n[1],10),r.channels=n.length===3?parseInt(n[2],10):1,r.numChannels=r.channels,r},e.writeRtpMap=function(t){var n=t.payloadType;t.preferredPayloadType!==void 0&&(n=t.preferredPayloadType);var r=t.channels||t.numChannels||1;return"a=rtpmap:"+n+" "+t.name+"/"+t.clockRate+(r!==1?"/"+r:"")+`\r
@@ -4918,7 +4918,7 @@ t=0 0\r
4918
4918
  `;o+="a="+a,o+="a=ssrc:"+t.sendEncodingParameters[0].ssrc+" "+a,t.sendEncodingParameters[0].rtx&&(o+="a=ssrc:"+t.sendEncodingParameters[0].rtx.ssrc+" "+a,o+="a=ssrc-group:FID "+t.sendEncodingParameters[0].ssrc+" "+t.sendEncodingParameters[0].rtx.ssrc+`\r
4919
4919
  `)}return o+="a=ssrc:"+t.sendEncodingParameters[0].ssrc+" cname:"+e.localCName+`\r
4920
4920
  `,t.rtpSender&&t.sendEncodingParameters[0].rtx&&(o+="a=ssrc:"+t.sendEncodingParameters[0].rtx.ssrc+" cname:"+e.localCName+`\r
4921
- `),o},e.getDirection=function(t,n){for(var r=e.splitLines(t),s=0;s<r.length;s++)switch(r[s]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return r[s].substr(2)}return n?e.getDirection(n):"sendrecv"},e.getKind=function(t){var n=e.splitLines(t),r=n[0].split(" ");return r[0].substr(2)},e.isRejected=function(t){return t.split(" ",2)[1]==="0"},e.parseMLine=function(t){var n=e.splitLines(t),r=n[0].substr(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},e.parseOLine=function(t){var n=e.matchPrefix(t,"o=")[0],r=n.substr(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},e.isValidSDP=function(t){if(typeof t!="string"||t.length===0)return!1;for(var n=e.splitLines(t),r=0;r<n.length;r++)if(n[r].length<2||n[r].charAt(1)!=="=")return!1;return!0},i.exports=e})(wU);var SU=wU.exports;const Qb=Bb(SU);var Pt=SU;function zZ(i){return{inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[i.type]||i.type}function CU(i,e,t,n,r){var s=Pt.writeRtpDescription(i.kind,e);if(s+=Pt.writeIceParameters(i.iceGatherer.getLocalParameters()),s+=Pt.writeDtlsParameters(i.dtlsTransport.getLocalParameters(),t==="offer"?"actpass":r||"active"),s+="a=mid:"+i.mid+`\r
4921
+ `),o},e.getDirection=function(t,n){for(var r=e.splitLines(t),s=0;s<r.length;s++)switch(r[s]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return r[s].substr(2)}return n?e.getDirection(n):"sendrecv"},e.getKind=function(t){var n=e.splitLines(t),r=n[0].split(" ");return r[0].substr(2)},e.isRejected=function(t){return t.split(" ",2)[1]==="0"},e.parseMLine=function(t){var n=e.splitLines(t),r=n[0].substr(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},e.parseOLine=function(t){var n=e.matchPrefix(t,"o=")[0],r=n.substr(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},e.isValidSDP=function(t){if(typeof t!="string"||t.length===0)return!1;for(var n=e.splitLines(t),r=0;r<n.length;r++)if(n[r].length<2||n[r].charAt(1)!=="=")return!1;return!0},i.exports=e})(w3);var S3=w3.exports;const Qb=Bb(S3);var Pt=S3;function zZ(i){return{inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[i.type]||i.type}function C3(i,e,t,n,r){var s=Pt.writeRtpDescription(i.kind,e);if(s+=Pt.writeIceParameters(i.iceGatherer.getLocalParameters()),s+=Pt.writeDtlsParameters(i.dtlsTransport.getLocalParameters(),t==="offer"?"actpass":r||"active"),s+="a=mid:"+i.mid+`\r
4922
4922
  `,i.rtpSender&&i.rtpReceiver?s+=`a=sendrecv\r
4923
4923
  `:i.rtpSender?s+=`a=sendonly\r
4924
4924
  `:i.rtpReceiver?s+=`a=recvonly\r
@@ -4927,11 +4927,11 @@ t=0 0\r
4927
4927
  `;s+="a="+a,s+="a=ssrc:"+i.sendEncodingParameters[0].ssrc+" "+a,i.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+i.sendEncodingParameters[0].rtx.ssrc+" "+a,s+="a=ssrc-group:FID "+i.sendEncodingParameters[0].ssrc+" "+i.sendEncodingParameters[0].rtx.ssrc+`\r
4928
4928
  `)}return s+="a=ssrc:"+i.sendEncodingParameters[0].ssrc+" cname:"+Pt.localCName+`\r
4929
4929
  `,i.rtpSender&&i.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+i.sendEncodingParameters[0].rtx.ssrc+" cname:"+Pt.localCName+`\r
4930
- `),s}function jZ(i,e){var t=!1;return i=JSON.parse(JSON.stringify(i)),i.filter(function(n){if(n&&(n.urls||n.url)){var r=n.urls||n.url;n.url&&!n.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var s=typeof r=="string";return s&&(r=[r]),r=r.filter(function(o){var a=o.indexOf("turn:")===0&&o.indexOf("transport=udp")!==-1&&o.indexOf("turn:[")===-1&&!t;return a?(t=!0,!0):o.indexOf("stun:")===0&&e>=14393&&o.indexOf("?transport=udp")===-1}),delete n.url,n.urls=s?r[0]:r,!!r.length}})}function Hb(i,e){var t={codecs:[],headerExtensions:[],fecMechanisms:[]},n=function(s,o){s=parseInt(s,10);for(var a=0;a<o.length;a++)if(o[a].payloadType===s||o[a].preferredPayloadType===s)return o[a]},r=function(s,o,a,l){var c=n(s.parameters.apt,a),u=n(o.parameters.apt,l);return c&&u&&c.name.toLowerCase()===u.name.toLowerCase()};return i.codecs.forEach(function(s){for(var o=0;o<e.codecs.length;o++){var a=e.codecs[o];if(s.name.toLowerCase()===a.name.toLowerCase()&&s.clockRate===a.clockRate){if(s.name.toLowerCase()==="rtx"&&s.parameters&&a.parameters.apt&&!r(s,a,i.codecs,e.codecs))continue;a=JSON.parse(JSON.stringify(a)),a.numChannels=Math.min(s.numChannels,a.numChannels),t.codecs.push(a),a.rtcpFeedback=a.rtcpFeedback.filter(function(l){for(var c=0;c<s.rtcpFeedback.length;c++)if(s.rtcpFeedback[c].type===l.type&&s.rtcpFeedback[c].parameter===l.parameter)return!0;return!1});break}}}),i.headerExtensions.forEach(function(s){for(var o=0;o<e.headerExtensions.length;o++){var a=e.headerExtensions[o];if(s.uri===a.uri){t.headerExtensions.push(a);break}}}),t}function EU(i,e,t){return{offer:{setLocalDescription:["stable","have-local-offer"],setRemoteDescription:["stable","have-remote-offer"]},answer:{setLocalDescription:["have-remote-offer","have-local-pranswer"],setRemoteDescription:["have-local-offer","have-remote-pranswer"]}}[e][i].indexOf(t)!==-1}function mM(i,e){var t=i.getRemoteCandidates().find(function(n){return e.foundation===n.foundation&&e.ip===n.ip&&e.port===n.port&&e.priority===n.priority&&e.protocol===n.protocol&&e.type===n.type});return t||i.addRemoteCandidate(e),!t}function Vr(i,e){var t=new Error(e);return t.name=i,t.code={NotSupportedError:9,InvalidStateError:11,InvalidAccessError:15,TypeError:void 0,OperationError:void 0}[i],t}var GZ=function(i,e){function t(l,c){c.addTrack(l),c.dispatchEvent(new i.MediaStreamTrackEvent("addtrack",{track:l}))}function n(l,c){c.removeTrack(l),c.dispatchEvent(new i.MediaStreamTrackEvent("removetrack",{track:l}))}function r(l,c,u,d){var p=new Event("track");p.track=c,p.receiver=u,p.transceiver={receiver:u},p.streams=d,i.setTimeout(function(){l._dispatchEvent("track",p)})}var s=function(l){var c=this,u=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach(function(p){c[p]=u[p].bind(u)}),this.canTrickleIceCandidates=null,this.needNegotiation=!1,this.localStreams=[],this.remoteStreams=[],this._localDescription=null,this._remoteDescription=null,this.signalingState="stable",this.iceConnectionState="new",this.connectionState="new",this.iceGatheringState="new",l=JSON.parse(JSON.stringify(l||{})),this.usingBundle=l.bundlePolicy==="max-bundle",l.rtcpMuxPolicy==="negotiate")throw Vr("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(l.rtcpMuxPolicy||(l.rtcpMuxPolicy="require"),l.iceTransportPolicy){case"all":case"relay":break;default:l.iceTransportPolicy="all";break}switch(l.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:l.bundlePolicy="balanced";break}if(l.iceServers=jZ(l.iceServers||[],e),this._iceGatherers=[],l.iceCandidatePoolSize)for(var d=l.iceCandidatePoolSize;d>0;d--)this._iceGatherers.push(new i.RTCIceGatherer({iceServers:l.iceServers,gatherPolicy:l.iceTransportPolicy}));else l.iceCandidatePoolSize=0;this._config=l,this.transceivers=[],this._sdpSessionId=Pt.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(s.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(s.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),s.prototype.onicecandidate=null,s.prototype.onaddstream=null,s.prototype.ontrack=null,s.prototype.onremovestream=null,s.prototype.onsignalingstatechange=null,s.prototype.oniceconnectionstatechange=null,s.prototype.onconnectionstatechange=null,s.prototype.onicegatheringstatechange=null,s.prototype.onnegotiationneeded=null,s.prototype.ondatachannel=null,s.prototype._dispatchEvent=function(l,c){this._isClosed||(this.dispatchEvent(c),typeof this["on"+l]=="function"&&this["on"+l](c))},s.prototype._emitGatheringStateChange=function(){var l=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",l)},s.prototype.getConfiguration=function(){return this._config},s.prototype.getLocalStreams=function(){return this.localStreams},s.prototype.getRemoteStreams=function(){return this.remoteStreams},s.prototype._createTransceiver=function(l,c){var u=this.transceivers.length>0,d={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind:l,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,associatedRemoteMediaStreams:[],wantReceive:!0};if(this.usingBundle&&u)d.iceTransport=this.transceivers[0].iceTransport,d.dtlsTransport=this.transceivers[0].dtlsTransport;else{var p=this._createIceAndDtlsTransports();d.iceTransport=p.iceTransport,d.dtlsTransport=p.dtlsTransport}return c||this.transceivers.push(d),d},s.prototype.addTrack=function(l,c){if(this._isClosed)throw Vr("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var u=this.transceivers.find(function(f){return f.track===l});if(u)throw Vr("InvalidAccessError","Track already exists.");for(var d,p=0;p<this.transceivers.length;p++)!this.transceivers[p].track&&this.transceivers[p].kind===l.kind&&(d=this.transceivers[p]);return d||(d=this._createTransceiver(l.kind)),this._maybeFireNegotiationNeeded(),this.localStreams.indexOf(c)===-1&&this.localStreams.push(c),d.track=l,d.stream=c,d.rtpSender=new i.RTCRtpSender(l,d.dtlsTransport),d.rtpSender},s.prototype.addStream=function(l){var c=this;if(e>=15025)l.getTracks().forEach(function(d){c.addTrack(d,l)});else{var u=l.clone();l.getTracks().forEach(function(d,p){var f=u.getTracks()[p];d.addEventListener("enabled",function(m){f.enabled=m.enabled})}),u.getTracks().forEach(function(d){c.addTrack(d,u)})}},s.prototype.removeTrack=function(l){if(this._isClosed)throw Vr("InvalidStateError","Attempted to call removeTrack on a closed peerconnection.");if(!(l instanceof i.RTCRtpSender))throw new TypeError("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.");var c=this.transceivers.find(function(p){return p.rtpSender===l});if(!c)throw Vr("InvalidAccessError","Sender was not created by this connection.");var u=c.stream;c.rtpSender.stop(),c.rtpSender=null,c.track=null,c.stream=null;var d=this.transceivers.map(function(p){return p.stream});d.indexOf(u)===-1&&this.localStreams.indexOf(u)>-1&&this.localStreams.splice(this.localStreams.indexOf(u),1),this._maybeFireNegotiationNeeded()},s.prototype.removeStream=function(l){var c=this;l.getTracks().forEach(function(u){var d=c.getSenders().find(function(p){return p.track===u});d&&c.removeTrack(d)})},s.prototype.getSenders=function(){return this.transceivers.filter(function(l){return!!l.rtpSender}).map(function(l){return l.rtpSender})},s.prototype.getReceivers=function(){return this.transceivers.filter(function(l){return!!l.rtpReceiver}).map(function(l){return l.rtpReceiver})},s.prototype._createIceGatherer=function(l,c){var u=this;if(c&&l>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var d=new i.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(d,"state",{value:"new",writable:!0}),this.transceivers[l].bufferedCandidateEvents=[],this.transceivers[l].bufferCandidates=function(p){var f=!p.candidate||Object.keys(p.candidate).length===0;d.state=f?"completed":"gathering",u.transceivers[l].bufferedCandidateEvents!==null&&u.transceivers[l].bufferedCandidateEvents.push(p)},d.addEventListener("localcandidate",this.transceivers[l].bufferCandidates),d},s.prototype._gather=function(l,c){var u=this,d=this.transceivers[c].iceGatherer;if(!d.onlocalcandidate){var p=this.transceivers[c].bufferedCandidateEvents;this.transceivers[c].bufferedCandidateEvents=null,d.removeEventListener("localcandidate",this.transceivers[c].bufferCandidates),d.onlocalcandidate=function(f){if(!(u.usingBundle&&c>0)){var m=new Event("icecandidate");m.candidate={sdpMid:l,sdpMLineIndex:c};var A=f.candidate,v=!A||Object.keys(A).length===0;if(v)(d.state==="new"||d.state==="gathering")&&(d.state="completed");else{d.state==="new"&&(d.state="gathering"),A.component=1,A.ufrag=d.getLocalParameters().usernameFragment;var g=Pt.writeCandidate(A);m.candidate=Object.assign(m.candidate,Pt.parseCandidate(g)),m.candidate.candidate=g,m.candidate.toJSON=function(){return{candidate:m.candidate.candidate,sdpMid:m.candidate.sdpMid,sdpMLineIndex:m.candidate.sdpMLineIndex,usernameFragment:m.candidate.usernameFragment}}}var y=Pt.getMediaSections(u._localDescription.sdp);v?y[m.candidate.sdpMLineIndex]+=`a=end-of-candidates\r
4930
+ `),s}function jZ(i,e){var t=!1;return i=JSON.parse(JSON.stringify(i)),i.filter(function(n){if(n&&(n.urls||n.url)){var r=n.urls||n.url;n.url&&!n.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var s=typeof r=="string";return s&&(r=[r]),r=r.filter(function(o){var a=o.indexOf("turn:")===0&&o.indexOf("transport=udp")!==-1&&o.indexOf("turn:[")===-1&&!t;return a?(t=!0,!0):o.indexOf("stun:")===0&&e>=14393&&o.indexOf("?transport=udp")===-1}),delete n.url,n.urls=s?r[0]:r,!!r.length}})}function Hb(i,e){var t={codecs:[],headerExtensions:[],fecMechanisms:[]},n=function(s,o){s=parseInt(s,10);for(var a=0;a<o.length;a++)if(o[a].payloadType===s||o[a].preferredPayloadType===s)return o[a]},r=function(s,o,a,l){var c=n(s.parameters.apt,a),u=n(o.parameters.apt,l);return c&&u&&c.name.toLowerCase()===u.name.toLowerCase()};return i.codecs.forEach(function(s){for(var o=0;o<e.codecs.length;o++){var a=e.codecs[o];if(s.name.toLowerCase()===a.name.toLowerCase()&&s.clockRate===a.clockRate){if(s.name.toLowerCase()==="rtx"&&s.parameters&&a.parameters.apt&&!r(s,a,i.codecs,e.codecs))continue;a=JSON.parse(JSON.stringify(a)),a.numChannels=Math.min(s.numChannels,a.numChannels),t.codecs.push(a),a.rtcpFeedback=a.rtcpFeedback.filter(function(l){for(var c=0;c<s.rtcpFeedback.length;c++)if(s.rtcpFeedback[c].type===l.type&&s.rtcpFeedback[c].parameter===l.parameter)return!0;return!1});break}}}),i.headerExtensions.forEach(function(s){for(var o=0;o<e.headerExtensions.length;o++){var a=e.headerExtensions[o];if(s.uri===a.uri){t.headerExtensions.push(a);break}}}),t}function E3(i,e,t){return{offer:{setLocalDescription:["stable","have-local-offer"],setRemoteDescription:["stable","have-remote-offer"]},answer:{setLocalDescription:["have-remote-offer","have-local-pranswer"],setRemoteDescription:["have-local-offer","have-remote-pranswer"]}}[e][i].indexOf(t)!==-1}function mM(i,e){var t=i.getRemoteCandidates().find(function(n){return e.foundation===n.foundation&&e.ip===n.ip&&e.port===n.port&&e.priority===n.priority&&e.protocol===n.protocol&&e.type===n.type});return t||i.addRemoteCandidate(e),!t}function Vr(i,e){var t=new Error(e);return t.name=i,t.code={NotSupportedError:9,InvalidStateError:11,InvalidAccessError:15,TypeError:void 0,OperationError:void 0}[i],t}var GZ=function(i,e){function t(l,c){c.addTrack(l),c.dispatchEvent(new i.MediaStreamTrackEvent("addtrack",{track:l}))}function n(l,c){c.removeTrack(l),c.dispatchEvent(new i.MediaStreamTrackEvent("removetrack",{track:l}))}function r(l,c,u,d){var p=new Event("track");p.track=c,p.receiver=u,p.transceiver={receiver:u},p.streams=d,i.setTimeout(function(){l._dispatchEvent("track",p)})}var s=function(l){var c=this,u=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach(function(p){c[p]=u[p].bind(u)}),this.canTrickleIceCandidates=null,this.needNegotiation=!1,this.localStreams=[],this.remoteStreams=[],this._localDescription=null,this._remoteDescription=null,this.signalingState="stable",this.iceConnectionState="new",this.connectionState="new",this.iceGatheringState="new",l=JSON.parse(JSON.stringify(l||{})),this.usingBundle=l.bundlePolicy==="max-bundle",l.rtcpMuxPolicy==="negotiate")throw Vr("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(l.rtcpMuxPolicy||(l.rtcpMuxPolicy="require"),l.iceTransportPolicy){case"all":case"relay":break;default:l.iceTransportPolicy="all";break}switch(l.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:l.bundlePolicy="balanced";break}if(l.iceServers=jZ(l.iceServers||[],e),this._iceGatherers=[],l.iceCandidatePoolSize)for(var d=l.iceCandidatePoolSize;d>0;d--)this._iceGatherers.push(new i.RTCIceGatherer({iceServers:l.iceServers,gatherPolicy:l.iceTransportPolicy}));else l.iceCandidatePoolSize=0;this._config=l,this.transceivers=[],this._sdpSessionId=Pt.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(s.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(s.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),s.prototype.onicecandidate=null,s.prototype.onaddstream=null,s.prototype.ontrack=null,s.prototype.onremovestream=null,s.prototype.onsignalingstatechange=null,s.prototype.oniceconnectionstatechange=null,s.prototype.onconnectionstatechange=null,s.prototype.onicegatheringstatechange=null,s.prototype.onnegotiationneeded=null,s.prototype.ondatachannel=null,s.prototype._dispatchEvent=function(l,c){this._isClosed||(this.dispatchEvent(c),typeof this["on"+l]=="function"&&this["on"+l](c))},s.prototype._emitGatheringStateChange=function(){var l=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",l)},s.prototype.getConfiguration=function(){return this._config},s.prototype.getLocalStreams=function(){return this.localStreams},s.prototype.getRemoteStreams=function(){return this.remoteStreams},s.prototype._createTransceiver=function(l,c){var u=this.transceivers.length>0,d={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind:l,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,associatedRemoteMediaStreams:[],wantReceive:!0};if(this.usingBundle&&u)d.iceTransport=this.transceivers[0].iceTransport,d.dtlsTransport=this.transceivers[0].dtlsTransport;else{var p=this._createIceAndDtlsTransports();d.iceTransport=p.iceTransport,d.dtlsTransport=p.dtlsTransport}return c||this.transceivers.push(d),d},s.prototype.addTrack=function(l,c){if(this._isClosed)throw Vr("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var u=this.transceivers.find(function(f){return f.track===l});if(u)throw Vr("InvalidAccessError","Track already exists.");for(var d,p=0;p<this.transceivers.length;p++)!this.transceivers[p].track&&this.transceivers[p].kind===l.kind&&(d=this.transceivers[p]);return d||(d=this._createTransceiver(l.kind)),this._maybeFireNegotiationNeeded(),this.localStreams.indexOf(c)===-1&&this.localStreams.push(c),d.track=l,d.stream=c,d.rtpSender=new i.RTCRtpSender(l,d.dtlsTransport),d.rtpSender},s.prototype.addStream=function(l){var c=this;if(e>=15025)l.getTracks().forEach(function(d){c.addTrack(d,l)});else{var u=l.clone();l.getTracks().forEach(function(d,p){var f=u.getTracks()[p];d.addEventListener("enabled",function(m){f.enabled=m.enabled})}),u.getTracks().forEach(function(d){c.addTrack(d,u)})}},s.prototype.removeTrack=function(l){if(this._isClosed)throw Vr("InvalidStateError","Attempted to call removeTrack on a closed peerconnection.");if(!(l instanceof i.RTCRtpSender))throw new TypeError("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.");var c=this.transceivers.find(function(p){return p.rtpSender===l});if(!c)throw Vr("InvalidAccessError","Sender was not created by this connection.");var u=c.stream;c.rtpSender.stop(),c.rtpSender=null,c.track=null,c.stream=null;var d=this.transceivers.map(function(p){return p.stream});d.indexOf(u)===-1&&this.localStreams.indexOf(u)>-1&&this.localStreams.splice(this.localStreams.indexOf(u),1),this._maybeFireNegotiationNeeded()},s.prototype.removeStream=function(l){var c=this;l.getTracks().forEach(function(u){var d=c.getSenders().find(function(p){return p.track===u});d&&c.removeTrack(d)})},s.prototype.getSenders=function(){return this.transceivers.filter(function(l){return!!l.rtpSender}).map(function(l){return l.rtpSender})},s.prototype.getReceivers=function(){return this.transceivers.filter(function(l){return!!l.rtpReceiver}).map(function(l){return l.rtpReceiver})},s.prototype._createIceGatherer=function(l,c){var u=this;if(c&&l>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var d=new i.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(d,"state",{value:"new",writable:!0}),this.transceivers[l].bufferedCandidateEvents=[],this.transceivers[l].bufferCandidates=function(p){var f=!p.candidate||Object.keys(p.candidate).length===0;d.state=f?"completed":"gathering",u.transceivers[l].bufferedCandidateEvents!==null&&u.transceivers[l].bufferedCandidateEvents.push(p)},d.addEventListener("localcandidate",this.transceivers[l].bufferCandidates),d},s.prototype._gather=function(l,c){var u=this,d=this.transceivers[c].iceGatherer;if(!d.onlocalcandidate){var p=this.transceivers[c].bufferedCandidateEvents;this.transceivers[c].bufferedCandidateEvents=null,d.removeEventListener("localcandidate",this.transceivers[c].bufferCandidates),d.onlocalcandidate=function(f){if(!(u.usingBundle&&c>0)){var m=new Event("icecandidate");m.candidate={sdpMid:l,sdpMLineIndex:c};var A=f.candidate,v=!A||Object.keys(A).length===0;if(v)(d.state==="new"||d.state==="gathering")&&(d.state="completed");else{d.state==="new"&&(d.state="gathering"),A.component=1,A.ufrag=d.getLocalParameters().usernameFragment;var g=Pt.writeCandidate(A);m.candidate=Object.assign(m.candidate,Pt.parseCandidate(g)),m.candidate.candidate=g,m.candidate.toJSON=function(){return{candidate:m.candidate.candidate,sdpMid:m.candidate.sdpMid,sdpMLineIndex:m.candidate.sdpMLineIndex,usernameFragment:m.candidate.usernameFragment}}}var y=Pt.getMediaSections(u._localDescription.sdp);v?y[m.candidate.sdpMLineIndex]+=`a=end-of-candidates\r
4931
4931
  `:y[m.candidate.sdpMLineIndex]+="a="+m.candidate.candidate+`\r
4932
- `,u._localDescription.sdp=Pt.getDescription(u._localDescription.sdp)+y.join("");var b=u.transceivers.every(function(_){return _.iceGatherer&&_.iceGatherer.state==="completed"});u.iceGatheringState!=="gathering"&&(u.iceGatheringState="gathering",u._emitGatheringStateChange()),v||u._dispatchEvent("icecandidate",m),b&&(u._dispatchEvent("icecandidate",new Event("icecandidate")),u.iceGatheringState="complete",u._emitGatheringStateChange())}},i.setTimeout(function(){p.forEach(function(f){d.onlocalcandidate(f)})},0)}},s.prototype._createIceAndDtlsTransports=function(){var l=this,c=new i.RTCIceTransport(null);c.onicestatechange=function(){l._updateIceConnectionState(),l._updateConnectionState()};var u=new i.RTCDtlsTransport(c);return u.ondtlsstatechange=function(){l._updateConnectionState()},u.onerror=function(){Object.defineProperty(u,"state",{value:"failed",writable:!0}),l._updateConnectionState()},{iceTransport:c,dtlsTransport:u}},s.prototype._disposeIceAndDtlsTransports=function(l){var c=this.transceivers[l].iceGatherer;c&&(delete c.onlocalcandidate,delete this.transceivers[l].iceGatherer);var u=this.transceivers[l].iceTransport;u&&(delete u.onicestatechange,delete this.transceivers[l].iceTransport);var d=this.transceivers[l].dtlsTransport;d&&(delete d.ondtlsstatechange,delete d.onerror,delete this.transceivers[l].dtlsTransport)},s.prototype._transceive=function(l,c,u){var d=Hb(l.localCapabilities,l.remoteCapabilities);c&&l.rtpSender&&(d.encodings=l.sendEncodingParameters,d.rtcp={cname:Pt.localCName,compound:l.rtcpParameters.compound},l.recvEncodingParameters.length&&(d.rtcp.ssrc=l.recvEncodingParameters[0].ssrc),l.rtpSender.send(d)),u&&l.rtpReceiver&&d.codecs.length>0&&(l.kind==="video"&&l.recvEncodingParameters&&e<15019&&l.recvEncodingParameters.forEach(function(p){delete p.rtx}),l.recvEncodingParameters.length?d.encodings=l.recvEncodingParameters:d.encodings=[{}],d.rtcp={compound:l.rtcpParameters.compound},l.rtcpParameters.cname&&(d.rtcp.cname=l.rtcpParameters.cname),l.sendEncodingParameters.length&&(d.rtcp.ssrc=l.sendEncodingParameters[0].ssrc),l.rtpReceiver.receive(d))},s.prototype.setLocalDescription=function(l){var c=this;if(["offer","answer"].indexOf(l.type)===-1)return Promise.reject(Vr("TypeError",'Unsupported type "'+l.type+'"'));if(!EU("setLocalDescription",l.type,c.signalingState)||c._isClosed)return Promise.reject(Vr("InvalidStateError","Can not set local "+l.type+" in state "+c.signalingState));var u,d;if(l.type==="offer")u=Pt.splitSections(l.sdp),d=u.shift(),u.forEach(function(f,m){var A=Pt.parseRtpParameters(f);c.transceivers[m].localCapabilities=A}),c.transceivers.forEach(function(f,m){c._gather(f.mid,m)});else if(l.type==="answer"){u=Pt.splitSections(c._remoteDescription.sdp),d=u.shift();var p=Pt.matchPrefix(d,"a=ice-lite").length>0;u.forEach(function(f,m){var A=c.transceivers[m],v=A.iceGatherer,g=A.iceTransport,y=A.dtlsTransport,b=A.localCapabilities,_=A.remoteCapabilities,E=Pt.isRejected(f)&&Pt.matchPrefix(f,"a=bundle-only").length===0;if(!E&&!A.rejected){var I=Pt.getIceParameters(f,d),T=Pt.getDtlsParameters(f,d);p&&(T.role="server"),(!c.usingBundle||m===0)&&(c._gather(A.mid,m),g.state==="new"&&g.start(v,I,p?"controlling":"controlled"),y.state==="new"&&y.start(T));var M=Hb(b,_);c._transceive(A,M.codecs.length>0,!1)}})}return c._localDescription={type:l.type,sdp:l.sdp},l.type==="offer"?c._updateSignalingState("have-local-offer"):c._updateSignalingState("stable"),Promise.resolve()},s.prototype.setRemoteDescription=function(l){var c=this;if(["offer","answer"].indexOf(l.type)===-1)return Promise.reject(Vr("TypeError",'Unsupported type "'+l.type+'"'));if(!EU("setRemoteDescription",l.type,c.signalingState)||c._isClosed)return Promise.reject(Vr("InvalidStateError","Can not set remote "+l.type+" in state "+c.signalingState));var u={};c.remoteStreams.forEach(function(g){u[g.id]=g});var d=[],p=Pt.splitSections(l.sdp),f=p.shift(),m=Pt.matchPrefix(f,"a=ice-lite").length>0,A=Pt.matchPrefix(f,"a=group:BUNDLE ").length>0;c.usingBundle=A;var v=Pt.matchPrefix(f,"a=ice-options:")[0];return v?c.canTrickleIceCandidates=v.substr(14).split(" ").indexOf("trickle")>=0:c.canTrickleIceCandidates=!1,p.forEach(function(g,y){var b=Pt.splitLines(g),_=Pt.getKind(g),E=Pt.isRejected(g)&&Pt.matchPrefix(g,"a=bundle-only").length===0,I=b[0].substr(2).split(" ")[2],T=Pt.getDirection(g,f),M=Pt.parseMsid(g),D=Pt.getMid(g)||Pt.generateIdentifier();if(E||_==="application"&&(I==="DTLS/SCTP"||I==="UDP/DTLS/SCTP")){c.transceivers[y]={mid:D,kind:_,protocol:I,rejected:!0};return}!E&&c.transceivers[y]&&c.transceivers[y].rejected&&(c.transceivers[y]=c._createTransceiver(_,!0));var C,P,G,Q,k,W,U,F,z,Z=Pt.parseRtpParameters(g),K,se;E||(K=Pt.getIceParameters(g,f),se=Pt.getDtlsParameters(g,f),se.role="client"),U=Pt.parseRtpEncodingParameters(g);var Ae=Pt.parseRtcpParameters(g),Re=Pt.matchPrefix(g,"a=end-of-candidates",f).length>0,ne=Pt.matchPrefix(g,"a=candidate:").map(function(De){return Pt.parseCandidate(De)}).filter(function(De){return De.component===1});if((l.type==="offer"||l.type==="answer")&&!E&&A&&y>0&&c.transceivers[y]&&(c._disposeIceAndDtlsTransports(y),c.transceivers[y].iceGatherer=c.transceivers[0].iceGatherer,c.transceivers[y].iceTransport=c.transceivers[0].iceTransport,c.transceivers[y].dtlsTransport=c.transceivers[0].dtlsTransport,c.transceivers[y].rtpSender&&c.transceivers[y].rtpSender.setTransport(c.transceivers[0].dtlsTransport),c.transceivers[y].rtpReceiver&&c.transceivers[y].rtpReceiver.setTransport(c.transceivers[0].dtlsTransport)),l.type==="offer"&&!E){C=c.transceivers[y]||c._createTransceiver(_),C.mid=D,C.iceGatherer||(C.iceGatherer=c._createIceGatherer(y,A)),ne.length&&C.iceTransport.state==="new"&&(Re&&(!A||y===0)?C.iceTransport.setRemoteCandidates(ne):ne.forEach(function(De){mM(C.iceTransport,De)})),F=i.RTCRtpReceiver.getCapabilities(_),e<15019&&(F.codecs=F.codecs.filter(function(De){return De.name!=="rtx"})),W=C.sendEncodingParameters||[{ssrc:(2*y+2)*1001}];var ye=!1;if(T==="sendrecv"||T==="sendonly"){if(ye=!C.rtpReceiver,k=C.rtpReceiver||new i.RTCRtpReceiver(C.dtlsTransport,_),ye){var Be;z=k.track,M&&M.stream==="-"||(M?(u[M.stream]||(u[M.stream]=new i.MediaStream,Object.defineProperty(u[M.stream],"id",{get:function(){return M.stream}})),Object.defineProperty(z,"id",{get:function(){return M.track}}),Be=u[M.stream]):(u.default||(u.default=new i.MediaStream),Be=u.default)),Be&&(t(z,Be),C.associatedRemoteMediaStreams.push(Be)),d.push([z,k,Be])}}else C.rtpReceiver&&C.rtpReceiver.track&&(C.associatedRemoteMediaStreams.forEach(function(De){var it=De.getTracks().find(function(pe){return pe.id===C.rtpReceiver.track.id});it&&n(it,De)}),C.associatedRemoteMediaStreams=[]);C.localCapabilities=F,C.remoteCapabilities=Z,C.rtpReceiver=k,C.rtcpParameters=Ae,C.sendEncodingParameters=W,C.recvEncodingParameters=U,c._transceive(c.transceivers[y],!1,ye)}else if(l.type==="answer"&&!E){C=c.transceivers[y],P=C.iceGatherer,G=C.iceTransport,Q=C.dtlsTransport,k=C.rtpReceiver,W=C.sendEncodingParameters,F=C.localCapabilities,c.transceivers[y].recvEncodingParameters=U,c.transceivers[y].remoteCapabilities=Z,c.transceivers[y].rtcpParameters=Ae,ne.length&&G.state==="new"&&((m||Re)&&(!A||y===0)?G.setRemoteCandidates(ne):ne.forEach(function(De){mM(C.iceTransport,De)})),(!A||y===0)&&(G.state==="new"&&G.start(P,K,"controlling"),Q.state==="new"&&Q.start(se));var We=Hb(C.localCapabilities,C.remoteCapabilities),Je=We.codecs.filter(function(De){return De.name.toLowerCase()==="rtx"}).length;!Je&&C.sendEncodingParameters[0].rtx&&delete C.sendEncodingParameters[0].rtx,c._transceive(C,T==="sendrecv"||T==="recvonly",T==="sendrecv"||T==="sendonly"),k&&(T==="sendrecv"||T==="sendonly")?(z=k.track,M?(u[M.stream]||(u[M.stream]=new i.MediaStream),t(z,u[M.stream]),d.push([z,k,u[M.stream]])):(u.default||(u.default=new i.MediaStream),t(z,u.default),d.push([z,k,u.default]))):delete C.rtpReceiver}}),c._dtlsRole===void 0&&(c._dtlsRole=l.type==="offer"?"active":"passive"),c._remoteDescription={type:l.type,sdp:l.sdp},l.type==="offer"?c._updateSignalingState("have-remote-offer"):c._updateSignalingState("stable"),Object.keys(u).forEach(function(g){var y=u[g];if(y.getTracks().length){if(c.remoteStreams.indexOf(y)===-1){c.remoteStreams.push(y);var b=new Event("addstream");b.stream=y,i.setTimeout(function(){c._dispatchEvent("addstream",b)})}d.forEach(function(_){var E=_[0],I=_[1];y.id===_[2].id&&r(c,E,I,[y])})}}),d.forEach(function(g){g[2]||r(c,g[0],g[1],[])}),i.setTimeout(function(){c&&c.transceivers&&c.transceivers.forEach(function(g){g.iceTransport&&g.iceTransport.state==="new"&&g.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),g.iceTransport.addRemoteCandidate({}))})},4e3),Promise.resolve()},s.prototype.close=function(){this.transceivers.forEach(function(l){l.iceTransport&&l.iceTransport.stop(),l.dtlsTransport&&l.dtlsTransport.stop(),l.rtpSender&&l.rtpSender.stop(),l.rtpReceiver&&l.rtpReceiver.stop()}),this._isClosed=!0,this._updateSignalingState("closed")},s.prototype._updateSignalingState=function(l){this.signalingState=l;var c=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",c)},s.prototype._maybeFireNegotiationNeeded=function(){var l=this;this.signalingState!=="stable"||this.needNegotiation===!0||(this.needNegotiation=!0,i.setTimeout(function(){if(l.needNegotiation){l.needNegotiation=!1;var c=new Event("negotiationneeded");l._dispatchEvent("negotiationneeded",c)}},0))},s.prototype._updateIceConnectionState=function(){var l,c={new:0,closed:0,checking:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(d){d.iceTransport&&!d.rejected&&c[d.iceTransport.state]++}),l="new",c.failed>0?l="failed":c.checking>0?l="checking":c.disconnected>0?l="disconnected":c.new>0?l="new":c.connected>0?l="connected":c.completed>0&&(l="completed"),l!==this.iceConnectionState){this.iceConnectionState=l;var u=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",u)}},s.prototype._updateConnectionState=function(){var l,c={new:0,closed:0,connecting:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(d){d.iceTransport&&d.dtlsTransport&&!d.rejected&&(c[d.iceTransport.state]++,c[d.dtlsTransport.state]++)}),c.connected+=c.completed,l="new",c.failed>0?l="failed":c.connecting>0?l="connecting":c.disconnected>0?l="disconnected":c.new>0?l="new":c.connected>0&&(l="connected"),l!==this.connectionState){this.connectionState=l;var u=new Event("connectionstatechange");this._dispatchEvent("connectionstatechange",u)}},s.prototype.createOffer=function(){var l=this;if(l._isClosed)return Promise.reject(Vr("InvalidStateError","Can not call createOffer after close"));var c=l.transceivers.filter(function(m){return m.kind==="audio"}).length,u=l.transceivers.filter(function(m){return m.kind==="video"}).length,d=arguments[0];if(d){if(d.mandatory||d.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");d.offerToReceiveAudio!==void 0&&(d.offerToReceiveAudio===!0?c=1:d.offerToReceiveAudio===!1?c=0:c=d.offerToReceiveAudio),d.offerToReceiveVideo!==void 0&&(d.offerToReceiveVideo===!0?u=1:d.offerToReceiveVideo===!1?u=0:u=d.offerToReceiveVideo)}for(l.transceivers.forEach(function(m){m.kind==="audio"?(c--,c<0&&(m.wantReceive=!1)):m.kind==="video"&&(u--,u<0&&(m.wantReceive=!1))});c>0||u>0;)c>0&&(l._createTransceiver("audio"),c--),u>0&&(l._createTransceiver("video"),u--);var p=Pt.writeSessionBoilerplate(l._sdpSessionId,l._sdpSessionVersion++);l.transceivers.forEach(function(m,A){var v=m.track,g=m.kind,y=m.mid||Pt.generateIdentifier();m.mid=y,m.iceGatherer||(m.iceGatherer=l._createIceGatherer(A,l.usingBundle));var b=i.RTCRtpSender.getCapabilities(g);e<15019&&(b.codecs=b.codecs.filter(function(E){return E.name!=="rtx"})),b.codecs.forEach(function(E){E.name==="H264"&&E.parameters["level-asymmetry-allowed"]===void 0&&(E.parameters["level-asymmetry-allowed"]="1"),m.remoteCapabilities&&m.remoteCapabilities.codecs&&m.remoteCapabilities.codecs.forEach(function(I){E.name.toLowerCase()===I.name.toLowerCase()&&E.clockRate===I.clockRate&&(E.preferredPayloadType=I.payloadType)})}),b.headerExtensions.forEach(function(E){var I=m.remoteCapabilities&&m.remoteCapabilities.headerExtensions||[];I.forEach(function(T){E.uri===T.uri&&(E.id=T.id)})});var _=m.sendEncodingParameters||[{ssrc:(2*A+1)*1001}];v&&e>=15019&&g==="video"&&!_[0].rtx&&(_[0].rtx={ssrc:_[0].ssrc+1}),m.wantReceive&&(m.rtpReceiver=new i.RTCRtpReceiver(m.dtlsTransport,g)),m.localCapabilities=b,m.sendEncodingParameters=_}),l._config.bundlePolicy!=="max-compat"&&(p+="a=group:BUNDLE "+l.transceivers.map(function(m){return m.mid}).join(" ")+`\r
4932
+ `,u._localDescription.sdp=Pt.getDescription(u._localDescription.sdp)+y.join("");var b=u.transceivers.every(function(_){return _.iceGatherer&&_.iceGatherer.state==="completed"});u.iceGatheringState!=="gathering"&&(u.iceGatheringState="gathering",u._emitGatheringStateChange()),v||u._dispatchEvent("icecandidate",m),b&&(u._dispatchEvent("icecandidate",new Event("icecandidate")),u.iceGatheringState="complete",u._emitGatheringStateChange())}},i.setTimeout(function(){p.forEach(function(f){d.onlocalcandidate(f)})},0)}},s.prototype._createIceAndDtlsTransports=function(){var l=this,c=new i.RTCIceTransport(null);c.onicestatechange=function(){l._updateIceConnectionState(),l._updateConnectionState()};var u=new i.RTCDtlsTransport(c);return u.ondtlsstatechange=function(){l._updateConnectionState()},u.onerror=function(){Object.defineProperty(u,"state",{value:"failed",writable:!0}),l._updateConnectionState()},{iceTransport:c,dtlsTransport:u}},s.prototype._disposeIceAndDtlsTransports=function(l){var c=this.transceivers[l].iceGatherer;c&&(delete c.onlocalcandidate,delete this.transceivers[l].iceGatherer);var u=this.transceivers[l].iceTransport;u&&(delete u.onicestatechange,delete this.transceivers[l].iceTransport);var d=this.transceivers[l].dtlsTransport;d&&(delete d.ondtlsstatechange,delete d.onerror,delete this.transceivers[l].dtlsTransport)},s.prototype._transceive=function(l,c,u){var d=Hb(l.localCapabilities,l.remoteCapabilities);c&&l.rtpSender&&(d.encodings=l.sendEncodingParameters,d.rtcp={cname:Pt.localCName,compound:l.rtcpParameters.compound},l.recvEncodingParameters.length&&(d.rtcp.ssrc=l.recvEncodingParameters[0].ssrc),l.rtpSender.send(d)),u&&l.rtpReceiver&&d.codecs.length>0&&(l.kind==="video"&&l.recvEncodingParameters&&e<15019&&l.recvEncodingParameters.forEach(function(p){delete p.rtx}),l.recvEncodingParameters.length?d.encodings=l.recvEncodingParameters:d.encodings=[{}],d.rtcp={compound:l.rtcpParameters.compound},l.rtcpParameters.cname&&(d.rtcp.cname=l.rtcpParameters.cname),l.sendEncodingParameters.length&&(d.rtcp.ssrc=l.sendEncodingParameters[0].ssrc),l.rtpReceiver.receive(d))},s.prototype.setLocalDescription=function(l){var c=this;if(["offer","answer"].indexOf(l.type)===-1)return Promise.reject(Vr("TypeError",'Unsupported type "'+l.type+'"'));if(!E3("setLocalDescription",l.type,c.signalingState)||c._isClosed)return Promise.reject(Vr("InvalidStateError","Can not set local "+l.type+" in state "+c.signalingState));var u,d;if(l.type==="offer")u=Pt.splitSections(l.sdp),d=u.shift(),u.forEach(function(f,m){var A=Pt.parseRtpParameters(f);c.transceivers[m].localCapabilities=A}),c.transceivers.forEach(function(f,m){c._gather(f.mid,m)});else if(l.type==="answer"){u=Pt.splitSections(c._remoteDescription.sdp),d=u.shift();var p=Pt.matchPrefix(d,"a=ice-lite").length>0;u.forEach(function(f,m){var A=c.transceivers[m],v=A.iceGatherer,g=A.iceTransport,y=A.dtlsTransport,b=A.localCapabilities,_=A.remoteCapabilities,E=Pt.isRejected(f)&&Pt.matchPrefix(f,"a=bundle-only").length===0;if(!E&&!A.rejected){var I=Pt.getIceParameters(f,d),T=Pt.getDtlsParameters(f,d);p&&(T.role="server"),(!c.usingBundle||m===0)&&(c._gather(A.mid,m),g.state==="new"&&g.start(v,I,p?"controlling":"controlled"),y.state==="new"&&y.start(T));var M=Hb(b,_);c._transceive(A,M.codecs.length>0,!1)}})}return c._localDescription={type:l.type,sdp:l.sdp},l.type==="offer"?c._updateSignalingState("have-local-offer"):c._updateSignalingState("stable"),Promise.resolve()},s.prototype.setRemoteDescription=function(l){var c=this;if(["offer","answer"].indexOf(l.type)===-1)return Promise.reject(Vr("TypeError",'Unsupported type "'+l.type+'"'));if(!E3("setRemoteDescription",l.type,c.signalingState)||c._isClosed)return Promise.reject(Vr("InvalidStateError","Can not set remote "+l.type+" in state "+c.signalingState));var u={};c.remoteStreams.forEach(function(g){u[g.id]=g});var d=[],p=Pt.splitSections(l.sdp),f=p.shift(),m=Pt.matchPrefix(f,"a=ice-lite").length>0,A=Pt.matchPrefix(f,"a=group:BUNDLE ").length>0;c.usingBundle=A;var v=Pt.matchPrefix(f,"a=ice-options:")[0];return v?c.canTrickleIceCandidates=v.substr(14).split(" ").indexOf("trickle")>=0:c.canTrickleIceCandidates=!1,p.forEach(function(g,y){var b=Pt.splitLines(g),_=Pt.getKind(g),E=Pt.isRejected(g)&&Pt.matchPrefix(g,"a=bundle-only").length===0,I=b[0].substr(2).split(" ")[2],T=Pt.getDirection(g,f),M=Pt.parseMsid(g),D=Pt.getMid(g)||Pt.generateIdentifier();if(E||_==="application"&&(I==="DTLS/SCTP"||I==="UDP/DTLS/SCTP")){c.transceivers[y]={mid:D,kind:_,protocol:I,rejected:!0};return}!E&&c.transceivers[y]&&c.transceivers[y].rejected&&(c.transceivers[y]=c._createTransceiver(_,!0));var C,P,G,Q,k,W,U,F,z,Z=Pt.parseRtpParameters(g),K,se;E||(K=Pt.getIceParameters(g,f),se=Pt.getDtlsParameters(g,f),se.role="client"),U=Pt.parseRtpEncodingParameters(g);var Ae=Pt.parseRtcpParameters(g),Re=Pt.matchPrefix(g,"a=end-of-candidates",f).length>0,ne=Pt.matchPrefix(g,"a=candidate:").map(function(De){return Pt.parseCandidate(De)}).filter(function(De){return De.component===1});if((l.type==="offer"||l.type==="answer")&&!E&&A&&y>0&&c.transceivers[y]&&(c._disposeIceAndDtlsTransports(y),c.transceivers[y].iceGatherer=c.transceivers[0].iceGatherer,c.transceivers[y].iceTransport=c.transceivers[0].iceTransport,c.transceivers[y].dtlsTransport=c.transceivers[0].dtlsTransport,c.transceivers[y].rtpSender&&c.transceivers[y].rtpSender.setTransport(c.transceivers[0].dtlsTransport),c.transceivers[y].rtpReceiver&&c.transceivers[y].rtpReceiver.setTransport(c.transceivers[0].dtlsTransport)),l.type==="offer"&&!E){C=c.transceivers[y]||c._createTransceiver(_),C.mid=D,C.iceGatherer||(C.iceGatherer=c._createIceGatherer(y,A)),ne.length&&C.iceTransport.state==="new"&&(Re&&(!A||y===0)?C.iceTransport.setRemoteCandidates(ne):ne.forEach(function(De){mM(C.iceTransport,De)})),F=i.RTCRtpReceiver.getCapabilities(_),e<15019&&(F.codecs=F.codecs.filter(function(De){return De.name!=="rtx"})),W=C.sendEncodingParameters||[{ssrc:(2*y+2)*1001}];var ye=!1;if(T==="sendrecv"||T==="sendonly"){if(ye=!C.rtpReceiver,k=C.rtpReceiver||new i.RTCRtpReceiver(C.dtlsTransport,_),ye){var Be;z=k.track,M&&M.stream==="-"||(M?(u[M.stream]||(u[M.stream]=new i.MediaStream,Object.defineProperty(u[M.stream],"id",{get:function(){return M.stream}})),Object.defineProperty(z,"id",{get:function(){return M.track}}),Be=u[M.stream]):(u.default||(u.default=new i.MediaStream),Be=u.default)),Be&&(t(z,Be),C.associatedRemoteMediaStreams.push(Be)),d.push([z,k,Be])}}else C.rtpReceiver&&C.rtpReceiver.track&&(C.associatedRemoteMediaStreams.forEach(function(De){var it=De.getTracks().find(function(pe){return pe.id===C.rtpReceiver.track.id});it&&n(it,De)}),C.associatedRemoteMediaStreams=[]);C.localCapabilities=F,C.remoteCapabilities=Z,C.rtpReceiver=k,C.rtcpParameters=Ae,C.sendEncodingParameters=W,C.recvEncodingParameters=U,c._transceive(c.transceivers[y],!1,ye)}else if(l.type==="answer"&&!E){C=c.transceivers[y],P=C.iceGatherer,G=C.iceTransport,Q=C.dtlsTransport,k=C.rtpReceiver,W=C.sendEncodingParameters,F=C.localCapabilities,c.transceivers[y].recvEncodingParameters=U,c.transceivers[y].remoteCapabilities=Z,c.transceivers[y].rtcpParameters=Ae,ne.length&&G.state==="new"&&((m||Re)&&(!A||y===0)?G.setRemoteCandidates(ne):ne.forEach(function(De){mM(C.iceTransport,De)})),(!A||y===0)&&(G.state==="new"&&G.start(P,K,"controlling"),Q.state==="new"&&Q.start(se));var We=Hb(C.localCapabilities,C.remoteCapabilities),Je=We.codecs.filter(function(De){return De.name.toLowerCase()==="rtx"}).length;!Je&&C.sendEncodingParameters[0].rtx&&delete C.sendEncodingParameters[0].rtx,c._transceive(C,T==="sendrecv"||T==="recvonly",T==="sendrecv"||T==="sendonly"),k&&(T==="sendrecv"||T==="sendonly")?(z=k.track,M?(u[M.stream]||(u[M.stream]=new i.MediaStream),t(z,u[M.stream]),d.push([z,k,u[M.stream]])):(u.default||(u.default=new i.MediaStream),t(z,u.default),d.push([z,k,u.default]))):delete C.rtpReceiver}}),c._dtlsRole===void 0&&(c._dtlsRole=l.type==="offer"?"active":"passive"),c._remoteDescription={type:l.type,sdp:l.sdp},l.type==="offer"?c._updateSignalingState("have-remote-offer"):c._updateSignalingState("stable"),Object.keys(u).forEach(function(g){var y=u[g];if(y.getTracks().length){if(c.remoteStreams.indexOf(y)===-1){c.remoteStreams.push(y);var b=new Event("addstream");b.stream=y,i.setTimeout(function(){c._dispatchEvent("addstream",b)})}d.forEach(function(_){var E=_[0],I=_[1];y.id===_[2].id&&r(c,E,I,[y])})}}),d.forEach(function(g){g[2]||r(c,g[0],g[1],[])}),i.setTimeout(function(){c&&c.transceivers&&c.transceivers.forEach(function(g){g.iceTransport&&g.iceTransport.state==="new"&&g.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),g.iceTransport.addRemoteCandidate({}))})},4e3),Promise.resolve()},s.prototype.close=function(){this.transceivers.forEach(function(l){l.iceTransport&&l.iceTransport.stop(),l.dtlsTransport&&l.dtlsTransport.stop(),l.rtpSender&&l.rtpSender.stop(),l.rtpReceiver&&l.rtpReceiver.stop()}),this._isClosed=!0,this._updateSignalingState("closed")},s.prototype._updateSignalingState=function(l){this.signalingState=l;var c=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",c)},s.prototype._maybeFireNegotiationNeeded=function(){var l=this;this.signalingState!=="stable"||this.needNegotiation===!0||(this.needNegotiation=!0,i.setTimeout(function(){if(l.needNegotiation){l.needNegotiation=!1;var c=new Event("negotiationneeded");l._dispatchEvent("negotiationneeded",c)}},0))},s.prototype._updateIceConnectionState=function(){var l,c={new:0,closed:0,checking:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(d){d.iceTransport&&!d.rejected&&c[d.iceTransport.state]++}),l="new",c.failed>0?l="failed":c.checking>0?l="checking":c.disconnected>0?l="disconnected":c.new>0?l="new":c.connected>0?l="connected":c.completed>0&&(l="completed"),l!==this.iceConnectionState){this.iceConnectionState=l;var u=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",u)}},s.prototype._updateConnectionState=function(){var l,c={new:0,closed:0,connecting:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(d){d.iceTransport&&d.dtlsTransport&&!d.rejected&&(c[d.iceTransport.state]++,c[d.dtlsTransport.state]++)}),c.connected+=c.completed,l="new",c.failed>0?l="failed":c.connecting>0?l="connecting":c.disconnected>0?l="disconnected":c.new>0?l="new":c.connected>0&&(l="connected"),l!==this.connectionState){this.connectionState=l;var u=new Event("connectionstatechange");this._dispatchEvent("connectionstatechange",u)}},s.prototype.createOffer=function(){var l=this;if(l._isClosed)return Promise.reject(Vr("InvalidStateError","Can not call createOffer after close"));var c=l.transceivers.filter(function(m){return m.kind==="audio"}).length,u=l.transceivers.filter(function(m){return m.kind==="video"}).length,d=arguments[0];if(d){if(d.mandatory||d.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");d.offerToReceiveAudio!==void 0&&(d.offerToReceiveAudio===!0?c=1:d.offerToReceiveAudio===!1?c=0:c=d.offerToReceiveAudio),d.offerToReceiveVideo!==void 0&&(d.offerToReceiveVideo===!0?u=1:d.offerToReceiveVideo===!1?u=0:u=d.offerToReceiveVideo)}for(l.transceivers.forEach(function(m){m.kind==="audio"?(c--,c<0&&(m.wantReceive=!1)):m.kind==="video"&&(u--,u<0&&(m.wantReceive=!1))});c>0||u>0;)c>0&&(l._createTransceiver("audio"),c--),u>0&&(l._createTransceiver("video"),u--);var p=Pt.writeSessionBoilerplate(l._sdpSessionId,l._sdpSessionVersion++);l.transceivers.forEach(function(m,A){var v=m.track,g=m.kind,y=m.mid||Pt.generateIdentifier();m.mid=y,m.iceGatherer||(m.iceGatherer=l._createIceGatherer(A,l.usingBundle));var b=i.RTCRtpSender.getCapabilities(g);e<15019&&(b.codecs=b.codecs.filter(function(E){return E.name!=="rtx"})),b.codecs.forEach(function(E){E.name==="H264"&&E.parameters["level-asymmetry-allowed"]===void 0&&(E.parameters["level-asymmetry-allowed"]="1"),m.remoteCapabilities&&m.remoteCapabilities.codecs&&m.remoteCapabilities.codecs.forEach(function(I){E.name.toLowerCase()===I.name.toLowerCase()&&E.clockRate===I.clockRate&&(E.preferredPayloadType=I.payloadType)})}),b.headerExtensions.forEach(function(E){var I=m.remoteCapabilities&&m.remoteCapabilities.headerExtensions||[];I.forEach(function(T){E.uri===T.uri&&(E.id=T.id)})});var _=m.sendEncodingParameters||[{ssrc:(2*A+1)*1001}];v&&e>=15019&&g==="video"&&!_[0].rtx&&(_[0].rtx={ssrc:_[0].ssrc+1}),m.wantReceive&&(m.rtpReceiver=new i.RTCRtpReceiver(m.dtlsTransport,g)),m.localCapabilities=b,m.sendEncodingParameters=_}),l._config.bundlePolicy!=="max-compat"&&(p+="a=group:BUNDLE "+l.transceivers.map(function(m){return m.mid}).join(" ")+`\r
4933
4933
  `),p+=`a=ice-options:trickle\r
4934
- `,l.transceivers.forEach(function(m,A){p+=CU(m,m.localCapabilities,"offer",m.stream,l._dtlsRole),p+=`a=rtcp-rsize\r
4934
+ `,l.transceivers.forEach(function(m,A){p+=C3(m,m.localCapabilities,"offer",m.stream,l._dtlsRole),p+=`a=rtcp-rsize\r
4935
4935
  `,m.iceGatherer&&l.iceGatheringState!=="new"&&(A===0||!l.usingBundle)&&(m.iceGatherer.getLocalCandidates().forEach(function(v){v.component=1,p+="a="+Pt.writeCandidate(v)+`\r
4936
4936
  `}),m.iceGatherer.state==="completed"&&(p+=`a=end-of-candidates\r
4937
4937
  `))});var f=new i.RTCSessionDescription({type:"offer",sdp:p});return Promise.resolve(f)},s.prototype.createAnswer=function(){var l=this;if(l._isClosed)return Promise.reject(Vr("InvalidStateError","Can not call createAnswer after close"));if(!(l.signalingState==="have-remote-offer"||l.signalingState==="have-local-pranswer"))return Promise.reject(Vr("InvalidStateError","Can not call createAnswer in signalingState "+l.signalingState));var c=Pt.writeSessionBoilerplate(l._sdpSessionId,l._sdpSessionVersion++);l.usingBundle&&(c+="a=group:BUNDLE "+l.transceivers.map(function(p){return p.mid}).join(" ")+`\r
@@ -4945,32 +4945,32 @@ a=rtpmap:120 VP8/90000\r
4945
4945
  `),c+=`c=IN IP4 0.0.0.0\r
4946
4946
  a=inactive\r
4947
4947
  a=mid:`+p.mid+`\r
4948
- `;return}if(p.stream){var m;p.kind==="audio"?m=p.stream.getAudioTracks()[0]:p.kind==="video"&&(m=p.stream.getVideoTracks()[0]),m&&e>=15019&&p.kind==="video"&&!p.sendEncodingParameters[0].rtx&&(p.sendEncodingParameters[0].rtx={ssrc:p.sendEncodingParameters[0].ssrc+1})}var A=Hb(p.localCapabilities,p.remoteCapabilities),v=A.codecs.filter(function(g){return g.name.toLowerCase()==="rtx"}).length;!v&&p.sendEncodingParameters[0].rtx&&delete p.sendEncodingParameters[0].rtx,c+=CU(p,A,"answer",p.stream,l._dtlsRole),p.rtcpParameters&&p.rtcpParameters.reducedSize&&(c+=`a=rtcp-rsize\r
4948
+ `;return}if(p.stream){var m;p.kind==="audio"?m=p.stream.getAudioTracks()[0]:p.kind==="video"&&(m=p.stream.getVideoTracks()[0]),m&&e>=15019&&p.kind==="video"&&!p.sendEncodingParameters[0].rtx&&(p.sendEncodingParameters[0].rtx={ssrc:p.sendEncodingParameters[0].ssrc+1})}var A=Hb(p.localCapabilities,p.remoteCapabilities),v=A.codecs.filter(function(g){return g.name.toLowerCase()==="rtx"}).length;!v&&p.sendEncodingParameters[0].rtx&&delete p.sendEncodingParameters[0].rtx,c+=C3(p,A,"answer",p.stream,l._dtlsRole),p.rtcpParameters&&p.rtcpParameters.reducedSize&&(c+=`a=rtcp-rsize\r
4949
4949
  `)}});var d=new i.RTCSessionDescription({type:"answer",sdp:c});return Promise.resolve(d)},s.prototype.addIceCandidate=function(l){var c=this,u;return l&&!(l.sdpMLineIndex!==void 0||l.sdpMid)?Promise.reject(new TypeError("sdpMLineIndex or sdpMid required")):new Promise(function(d,p){if(c._remoteDescription)if(!l||l.candidate==="")for(var f=0;f<c.transceivers.length&&!(!c.transceivers[f].rejected&&(c.transceivers[f].iceTransport.addRemoteCandidate({}),u=Pt.getMediaSections(c._remoteDescription.sdp),u[f]+=`a=end-of-candidates\r
4950
4950
  `,c._remoteDescription.sdp=Pt.getDescription(c._remoteDescription.sdp)+u.join(""),c.usingBundle));f++);else{var m=l.sdpMLineIndex;if(l.sdpMid){for(var A=0;A<c.transceivers.length;A++)if(c.transceivers[A].mid===l.sdpMid){m=A;break}}var v=c.transceivers[m];if(v){if(v.rejected)return d();var g=Object.keys(l.candidate).length>0?Pt.parseCandidate(l.candidate):{};if(g.protocol==="tcp"&&(g.port===0||g.port===9)||g.component&&g.component!==1)return d();if((m===0||m>0&&v.iceTransport!==c.transceivers[0].iceTransport)&&!mM(v.iceTransport,g))return p(Vr("OperationError","Can not add ICE candidate"));var y=l.candidate.trim();y.indexOf("a=")===0&&(y=y.substr(2)),u=Pt.getMediaSections(c._remoteDescription.sdp),u[m]+="a="+(g.type?y:"end-of-candidates")+`\r
4951
- `,c._remoteDescription.sdp=Pt.getDescription(c._remoteDescription.sdp)+u.join("")}else return p(Vr("OperationError","Can not add ICE candidate"))}else return p(Vr("InvalidStateError","Can not add ICE candidate without a remote description"));d()})},s.prototype.getStats=function(l){if(l&&l instanceof i.MediaStreamTrack){var c=null;if(this.transceivers.forEach(function(d){d.rtpSender&&d.rtpSender.track===l?c=d.rtpSender:d.rtpReceiver&&d.rtpReceiver.track===l&&(c=d.rtpReceiver)}),!c)throw Vr("InvalidAccessError","Invalid selector.");return c.getStats()}var u=[];return this.transceivers.forEach(function(d){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach(function(p){d[p]&&u.push(d[p].getStats())})}),Promise.all(u).then(function(d){var p=new Map;return d.forEach(function(f){f.forEach(function(m){p.set(m.id,m)})}),p})};var o=["RTCRtpSender","RTCRtpReceiver","RTCIceGatherer","RTCIceTransport","RTCDtlsTransport"];o.forEach(function(l){var c=i[l];if(c&&c.prototype&&c.prototype.getStats){var u=c.prototype.getStats;c.prototype.getStats=function(){return u.apply(this).then(function(d){var p=new Map;return Object.keys(d).forEach(function(f){d[f].type=zZ(d[f]),p.set(f,d[f])}),p})}}});var a=["createOffer","createAnswer"];return a.forEach(function(l){var c=s.prototype[l];s.prototype[l]=function(){var u=arguments;return typeof u[0]=="function"||typeof u[1]=="function"?c.apply(this,[arguments[2]]).then(function(d){typeof u[0]=="function"&&u[0].apply(null,[d])},function(d){typeof u[1]=="function"&&u[1].apply(null,[d])}):c.apply(this,arguments)}}),a=["setLocalDescription","setRemoteDescription","addIceCandidate"],a.forEach(function(l){var c=s.prototype[l];s.prototype[l]=function(){var u=arguments;return typeof u[1]=="function"||typeof u[2]=="function"?c.apply(this,arguments).then(function(){typeof u[1]=="function"&&u[1].apply(null)},function(d){typeof u[2]=="function"&&u[2].apply(null,[d])}):c.apply(this,arguments)}}),["getStats"].forEach(function(l){var c=s.prototype[l];s.prototype[l]=function(){var u=arguments;return typeof u[1]=="function"?c.apply(this,arguments).then(function(){typeof u[1]=="function"&&u[1].apply(null)}):c.apply(this,arguments)}}),s};const QZ=Bb(GZ);function MU(i){const e=i&&i.navigator,t=function(r){return{name:{PermissionDeniedError:"NotAllowedError"}[r.name]||r.name,message:r.message,constraint:r.constraint,toString(){return this.name}}},n=e.mediaDevices.getUserMedia.bind(e.mediaDevices);e.mediaDevices.getUserMedia=function(r){return n(r).catch(s=>Promise.reject(t(s)))}}function TU(i){"getDisplayMedia"in i.navigator&&i.navigator.mediaDevices&&(i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices||(i.navigator.mediaDevices.getDisplayMedia=i.navigator.getDisplayMedia.bind(i.navigator)))}function gM(i,e){if(i.RTCIceGatherer&&(i.RTCIceCandidate||(i.RTCIceCandidate=function(n){return n}),i.RTCSessionDescription||(i.RTCSessionDescription=function(n){return n}),e.version<15025)){const n=Object.getOwnPropertyDescriptor(i.MediaStreamTrack.prototype,"enabled");Object.defineProperty(i.MediaStreamTrack.prototype,"enabled",{set(r){n.set.call(this,r);const s=new Event("enabled");s.enabled=r,this.dispatchEvent(s)}})}i.RTCRtpSender&&!("dtmf"in i.RTCRtpSender.prototype)&&Object.defineProperty(i.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=new i.RTCDtmfSender(this):this.track.kind==="video"&&(this._dtmf=null)),this._dtmf}}),i.RTCDtmfSender&&!i.RTCDTMFSender&&(i.RTCDTMFSender=i.RTCDtmfSender);const t=QZ(i,e.version);i.RTCPeerConnection=function(n){return n&&n.iceServers&&(n.iceServers=NZ(n.iceServers,e.version),dM("ICE servers after filtering:",n.iceServers)),new t(n)},i.RTCPeerConnection.prototype=t.prototype}function IU(i){i.RTCRtpSender&&!("replaceTrack"in i.RTCRtpSender.prototype)&&(i.RTCRtpSender.prototype.replaceTrack=i.RTCRtpSender.prototype.setTrack)}const RU=Object.freeze(Object.defineProperty({__proto__:null,shimGetDisplayMedia:TU,shimGetUserMedia:MU,shimPeerConnection:gM,shimReplaceTrack:IU},Symbol.toStringTag,{value:"Module"}));function PU(i,e){const t=i&&i.navigator,n=i&&i.MediaStreamTrack;if(t.getUserMedia=function(r,s,o){Gb("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(r).then(s,o)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const r=function(o,a,l){a in o&&!(l in o)&&(o[l]=o[a],delete o[a])},s=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(o){return typeof o=="object"&&typeof o.audio=="object"&&(o=JSON.parse(JSON.stringify(o)),r(o.audio,"autoGainControl","mozAutoGainControl"),r(o.audio,"noiseSuppression","mozNoiseSuppression")),s(o)},n&&n.prototype.getSettings){const o=n.prototype.getSettings;n.prototype.getSettings=function(){const a=o.apply(this,arguments);return r(a,"mozAutoGainControl","autoGainControl"),r(a,"mozNoiseSuppression","noiseSuppression"),a}}if(n&&n.prototype.applyConstraints){const o=n.prototype.applyConstraints;n.prototype.applyConstraints=function(a){return this.kind==="audio"&&typeof a=="object"&&(a=JSON.parse(JSON.stringify(a)),r(a,"autoGainControl","mozAutoGainControl"),r(a,"noiseSuppression","mozNoiseSuppression")),o.apply(this,[a])}}}}function HZ(i,e){i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices||i.navigator.mediaDevices&&(i.navigator.mediaDevices.getDisplayMedia=function(t){if(!(t&&t.video)){const n=new DOMException("getDisplayMedia without video constraints is undefined");return n.name="NotFoundError",n.code=8,Promise.reject(n)}return t.video===!0?t.video={mediaSource:e}:t.video.mediaSource=e,i.navigator.mediaDevices.getUserMedia(t)})}function BU(i){typeof i=="object"&&i.RTCTrackEvent&&"receiver"in i.RTCTrackEvent.prototype&&!("transceiver"in i.RTCTrackEvent.prototype)&&Object.defineProperty(i.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function vM(i,e){if(typeof i!="object"||!(i.RTCPeerConnection||i.mozRTCPeerConnection))return;!i.RTCPeerConnection&&i.mozRTCPeerConnection&&(i.RTCPeerConnection=i.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(r){const s=i.RTCPeerConnection.prototype[r],o={[r](){return arguments[0]=new(r==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),s.apply(this,arguments)}};i.RTCPeerConnection.prototype[r]=o[r]});const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){const[r,s,o]=arguments;return n.apply(this,[r||null]).then(a=>{if(e.version<53&&!s)try{a.forEach(l=>{l.type=t[l.type]||l.type})}catch(l){if(l.name!=="TypeError")throw l;a.forEach((c,u)=>{a.set(u,Object.assign({},c,{type:t[c.type]||c.type}))})}return a}).then(s,o)}}function DU(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender)||i.RTCRtpSender&&"getStats"in i.RTCRtpSender.prototype)return;const e=i.RTCPeerConnection.prototype.getSenders;e&&(i.RTCPeerConnection.prototype.getSenders=function(){const n=e.apply(this,[]);return n.forEach(r=>r._pc=this),n});const t=i.RTCPeerConnection.prototype.addTrack;t&&(i.RTCPeerConnection.prototype.addTrack=function(){const n=t.apply(this,arguments);return n._pc=this,n}),i.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function OU(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender)||i.RTCRtpSender&&"getStats"in i.RTCRtpReceiver.prototype)return;const e=i.RTCPeerConnection.prototype.getReceivers;e&&(i.RTCPeerConnection.prototype.getReceivers=function(){const t=e.apply(this,[]);return t.forEach(n=>n._pc=this),t}),Dp(i,"track",t=>(t.receiver._pc=t.srcElement,t)),i.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function kU(i){!i.RTCPeerConnection||"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(e){Gb("removeStream","removeTrack"),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function LU(i){i.DataChannel&&!i.RTCDataChannel&&(i.RTCDataChannel=i.DataChannel)}function UU(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.addTransceiver;e&&(i.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];const t=arguments[1],n=t&&"sendEncodings"in t;n&&t.sendEncodings.forEach(s=>{if("rid"in s&&!/^[a-z0-9]{0,16}$/i.test(s.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in s&&!(parseFloat(s.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in s&&!(parseFloat(s.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const r=e.apply(this,arguments);if(n){const{sender:s}=r,o=s.getParameters();(!("encodings"in o)||o.encodings.length===1&&Object.keys(o.encodings[0]).length===0)&&(o.encodings=t.sendEncodings,s.sendEncodings=t.sendEncodings,this.setParametersPromises.push(s.setParameters(o).then(()=>{delete s.sendEncodings}).catch(()=>{delete s.sendEncodings})))}return r})}function FU(i){if(!(typeof i=="object"&&i.RTCRtpSender))return;const e=i.RTCRtpSender.prototype.getParameters;e&&(i.RTCRtpSender.prototype.getParameters=function(){const t=e.apply(this,arguments);return"encodings"in t||(t.encodings=[].concat(this.sendEncodings||[{}])),t})}function NU(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.createOffer;i.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function zU(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.createAnswer;i.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}const jU=Object.freeze(Object.defineProperty({__proto__:null,shimAddTransceiver:UU,shimCreateAnswer:zU,shimCreateOffer:NU,shimGetDisplayMedia:HZ,shimGetParameters:FU,shimGetUserMedia:PU,shimOnTrack:BU,shimPeerConnection:vM,shimRTCDataChannel:LU,shimReceiverGetStats:OU,shimRemoveStream:kU,shimSenderGetStats:DU},Symbol.toStringTag,{value:"Module"}));function GU(i){if(!(typeof i!="object"||!i.RTCPeerConnection)){if("getLocalStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in i.RTCPeerConnection.prototype)){const e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addStream=function(t){this._localStreams||(this._localStreams=[]),this._localStreams.includes(t)||this._localStreams.push(t),t.getAudioTracks().forEach(n=>e.call(this,n,t)),t.getVideoTracks().forEach(n=>e.call(this,n,t))},i.RTCPeerConnection.prototype.addTrack=function(t,...n){return n&&n.forEach(r=>{this._localStreams?this._localStreams.includes(r)||this._localStreams.push(r):this._localStreams=[r]}),e.apply(this,arguments)}}"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(t===-1)return;this._localStreams.splice(t,1);const n=e.getTracks();this.getSenders().forEach(r=>{n.includes(r.track)&&this.removeTrack(r)})})}}function QU(i){if(!(typeof i!="object"||!i.RTCPeerConnection)&&("getRemoteStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in i.RTCPeerConnection.prototype))){Object.defineProperty(i.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=n=>{n.streams.forEach(r=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(r))return;this._remoteStreams.push(r);const s=new Event("addstream");s.stream=r,this.dispatchEvent(s)})})}});const e=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){const t=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(n){n.streams.forEach(r=>{if(t._remoteStreams||(t._remoteStreams=[]),t._remoteStreams.indexOf(r)>=0)return;t._remoteStreams.push(r);const s=new Event("addstream");s.stream=r,t.dispatchEvent(s)})}),e.apply(t,arguments)}}}function HU(i){if(typeof i!="object"||!i.RTCPeerConnection)return;const e=i.RTCPeerConnection.prototype,t=e.createOffer,n=e.createAnswer,r=e.setLocalDescription,s=e.setRemoteDescription,o=e.addIceCandidate;e.createOffer=function(l,c){const u=arguments.length>=2?arguments[2]:arguments[0],d=t.apply(this,[u]);return c?(d.then(l,c),Promise.resolve()):d},e.createAnswer=function(l,c){const u=arguments.length>=2?arguments[2]:arguments[0],d=n.apply(this,[u]);return c?(d.then(l,c),Promise.resolve()):d};let a=function(l,c,u){const d=r.apply(this,[l]);return u?(d.then(c,u),Promise.resolve()):d};e.setLocalDescription=a,a=function(l,c,u){const d=s.apply(this,[l]);return u?(d.then(c,u),Promise.resolve()):d},e.setRemoteDescription=a,a=function(l,c,u){const d=o.apply(this,[l]);return u?(d.then(c,u),Promise.resolve()):d},e.addIceCandidate=a}function VU(i){const e=i&&i.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,n=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=r=>n(WU(r))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=function(t,n,r){e.mediaDevices.getUserMedia(t).then(n,r)}.bind(e))}function WU(i){return i&&i.video!==void 0?Object.assign({},i,{video:hU(i.video)}):i}function qU(i){if(!i.RTCPeerConnection)return;const e=i.RTCPeerConnection;i.RTCPeerConnection=function(t,n){if(t&&t.iceServers){const r=[];for(let s=0;s<t.iceServers.length;s++){let o=t.iceServers[s];!o.hasOwnProperty("urls")&&o.hasOwnProperty("url")?(Gb("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,r.push(o)):r.push(t.iceServers[s])}t.iceServers=r}return new e(t,n)},i.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(i.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function XU(i){typeof i=="object"&&i.RTCTrackEvent&&"receiver"in i.RTCTrackEvent.prototype&&!("transceiver"in i.RTCTrackEvent.prototype)&&Object.defineProperty(i.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function YU(i){const e=i.RTCPeerConnection.prototype.createOffer;i.RTCPeerConnection.prototype.createOffer=function(t){if(t){typeof t.offerToReceiveAudio<"u"&&(t.offerToReceiveAudio=!!t.offerToReceiveAudio);const n=this.getTransceivers().find(s=>s.receiver.track.kind==="audio");t.offerToReceiveAudio===!1&&n?n.direction==="sendrecv"?n.setDirection?n.setDirection("sendonly"):n.direction="sendonly":n.direction==="recvonly"&&(n.setDirection?n.setDirection("inactive"):n.direction="inactive"):t.offerToReceiveAudio===!0&&!n&&this.addTransceiver("audio"),typeof t.offerToReceiveVideo<"u"&&(t.offerToReceiveVideo=!!t.offerToReceiveVideo);const r=this.getTransceivers().find(s=>s.receiver.track.kind==="video");t.offerToReceiveVideo===!1&&r?r.direction==="sendrecv"?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":r.direction==="recvonly"&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):t.offerToReceiveVideo===!0&&!r&&this.addTransceiver("video")}return e.apply(this,arguments)}}function JU(i){typeof i!="object"||i.AudioContext||(i.AudioContext=i.webkitAudioContext)}const KU=Object.freeze(Object.defineProperty({__proto__:null,shimAudioContext:JU,shimCallbacksAPI:HU,shimConstraints:WU,shimCreateOfferLegacy:YU,shimGetUserMedia:VU,shimLocalStreamsAPI:GU,shimRTCIceServerUrls:qU,shimRemoteStreamsAPI:QU,shimTrackEventTransceiver:XU},Symbol.toStringTag,{value:"Module"}));function Vb(i){if(!i.RTCIceCandidate||i.RTCIceCandidate&&"foundation"in i.RTCIceCandidate.prototype)return;const e=i.RTCIceCandidate;i.RTCIceCandidate=function(t){if(typeof t=="object"&&t.candidate&&t.candidate.indexOf("a=")===0&&(t=JSON.parse(JSON.stringify(t)),t.candidate=t.candidate.substr(2)),t.candidate&&t.candidate.length){const n=new e(t),r=Qb.parseCandidate(t.candidate),s=Object.assign(n,r);return s.toJSON=function(){return{candidate:s.candidate,sdpMid:s.sdpMid,sdpMLineIndex:s.sdpMLineIndex,usernameFragment:s.usernameFragment}},s}return new e(t)},i.RTCIceCandidate.prototype=e.prototype,Dp(i,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new i.RTCIceCandidate(t.candidate),writable:"false"}),t))}function Ig(i,e){if(!i.RTCPeerConnection)return;"sctp"in i.RTCPeerConnection.prototype||Object.defineProperty(i.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const t=function(a){if(!a||!a.sdp)return!1;const l=Qb.splitSections(a.sdp);return l.shift(),l.some(c=>{const u=Qb.parseMLine(c);return u&&u.kind==="application"&&u.protocol.indexOf("SCTP")!==-1})},n=function(a){const l=a.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(l===null||l.length<2)return-1;const c=parseInt(l[1],10);return c!==c?-1:c},r=function(a){let l=65536;return e.browser==="firefox"&&(e.version<57?a===-1?l=16384:l=2147483637:e.version<60?l=e.version===57?65535:65536:l=2147483637),l},s=function(a,l){let c=65536;e.browser==="firefox"&&e.version===57&&(c=65535);const u=Qb.matchPrefix(a.sdp,"a=max-message-size:");return u.length>0?c=parseInt(u[0].substr(19),10):e.browser==="firefox"&&l!==-1&&(c=2147483637),c},o=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76){const{sdpSemantics:a}=this.getConfiguration();a==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0})}if(t(arguments[0])){const a=n(arguments[0]),l=r(a),c=s(arguments[0],a);let u;l===0&&c===0?u=Number.POSITIVE_INFINITY:l===0||c===0?u=Math.max(l,c):u=Math.min(l,c);const d={};Object.defineProperty(d,"maxMessageSize",{get(){return u}}),this._sctp=d}return o.apply(this,arguments)}}function Rg(i){if(!(i.RTCPeerConnection&&"createDataChannel"in i.RTCPeerConnection.prototype))return;function e(n,r){const s=n.send;n.send=function(){const o=arguments[0],a=o.length||o.size||o.byteLength;if(n.readyState==="open"&&r.sctp&&a>r.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+r.sctp.maxMessageSize+" bytes)");return s.apply(n,arguments)}}const t=i.RTCPeerConnection.prototype.createDataChannel;i.RTCPeerConnection.prototype.createDataChannel=function(){const n=t.apply(this,arguments);return e(n,this),n},Dp(i,"datachannel",n=>(e(n.channel,n.target),n))}function AM(i){if(!i.RTCPeerConnection||"connectionState"in i.RTCPeerConnection.prototype)return;const e=i.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(t){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),t&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=t)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(t=>{const n=e[t];e[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=r=>{const s=r.target;if(s._lastConnectionState!==s.connectionState){s._lastConnectionState=s.connectionState;const o=new Event("connectionstatechange",r);s.dispatchEvent(o)}return r},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}})}function yM(i,e){if(!i.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e.version>=605)return;const t=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(n){if(n&&n.sdp&&n.sdp.indexOf(`
4951
+ `,c._remoteDescription.sdp=Pt.getDescription(c._remoteDescription.sdp)+u.join("")}else return p(Vr("OperationError","Can not add ICE candidate"))}else return p(Vr("InvalidStateError","Can not add ICE candidate without a remote description"));d()})},s.prototype.getStats=function(l){if(l&&l instanceof i.MediaStreamTrack){var c=null;if(this.transceivers.forEach(function(d){d.rtpSender&&d.rtpSender.track===l?c=d.rtpSender:d.rtpReceiver&&d.rtpReceiver.track===l&&(c=d.rtpReceiver)}),!c)throw Vr("InvalidAccessError","Invalid selector.");return c.getStats()}var u=[];return this.transceivers.forEach(function(d){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach(function(p){d[p]&&u.push(d[p].getStats())})}),Promise.all(u).then(function(d){var p=new Map;return d.forEach(function(f){f.forEach(function(m){p.set(m.id,m)})}),p})};var o=["RTCRtpSender","RTCRtpReceiver","RTCIceGatherer","RTCIceTransport","RTCDtlsTransport"];o.forEach(function(l){var c=i[l];if(c&&c.prototype&&c.prototype.getStats){var u=c.prototype.getStats;c.prototype.getStats=function(){return u.apply(this).then(function(d){var p=new Map;return Object.keys(d).forEach(function(f){d[f].type=zZ(d[f]),p.set(f,d[f])}),p})}}});var a=["createOffer","createAnswer"];return a.forEach(function(l){var c=s.prototype[l];s.prototype[l]=function(){var u=arguments;return typeof u[0]=="function"||typeof u[1]=="function"?c.apply(this,[arguments[2]]).then(function(d){typeof u[0]=="function"&&u[0].apply(null,[d])},function(d){typeof u[1]=="function"&&u[1].apply(null,[d])}):c.apply(this,arguments)}}),a=["setLocalDescription","setRemoteDescription","addIceCandidate"],a.forEach(function(l){var c=s.prototype[l];s.prototype[l]=function(){var u=arguments;return typeof u[1]=="function"||typeof u[2]=="function"?c.apply(this,arguments).then(function(){typeof u[1]=="function"&&u[1].apply(null)},function(d){typeof u[2]=="function"&&u[2].apply(null,[d])}):c.apply(this,arguments)}}),["getStats"].forEach(function(l){var c=s.prototype[l];s.prototype[l]=function(){var u=arguments;return typeof u[1]=="function"?c.apply(this,arguments).then(function(){typeof u[1]=="function"&&u[1].apply(null)}):c.apply(this,arguments)}}),s};const QZ=Bb(GZ);function M3(i){const e=i&&i.navigator,t=function(r){return{name:{PermissionDeniedError:"NotAllowedError"}[r.name]||r.name,message:r.message,constraint:r.constraint,toString(){return this.name}}},n=e.mediaDevices.getUserMedia.bind(e.mediaDevices);e.mediaDevices.getUserMedia=function(r){return n(r).catch(s=>Promise.reject(t(s)))}}function T3(i){"getDisplayMedia"in i.navigator&&i.navigator.mediaDevices&&(i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices||(i.navigator.mediaDevices.getDisplayMedia=i.navigator.getDisplayMedia.bind(i.navigator)))}function gM(i,e){if(i.RTCIceGatherer&&(i.RTCIceCandidate||(i.RTCIceCandidate=function(n){return n}),i.RTCSessionDescription||(i.RTCSessionDescription=function(n){return n}),e.version<15025)){const n=Object.getOwnPropertyDescriptor(i.MediaStreamTrack.prototype,"enabled");Object.defineProperty(i.MediaStreamTrack.prototype,"enabled",{set(r){n.set.call(this,r);const s=new Event("enabled");s.enabled=r,this.dispatchEvent(s)}})}i.RTCRtpSender&&!("dtmf"in i.RTCRtpSender.prototype)&&Object.defineProperty(i.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=new i.RTCDtmfSender(this):this.track.kind==="video"&&(this._dtmf=null)),this._dtmf}}),i.RTCDtmfSender&&!i.RTCDTMFSender&&(i.RTCDTMFSender=i.RTCDtmfSender);const t=QZ(i,e.version);i.RTCPeerConnection=function(n){return n&&n.iceServers&&(n.iceServers=NZ(n.iceServers,e.version),dM("ICE servers after filtering:",n.iceServers)),new t(n)},i.RTCPeerConnection.prototype=t.prototype}function I3(i){i.RTCRtpSender&&!("replaceTrack"in i.RTCRtpSender.prototype)&&(i.RTCRtpSender.prototype.replaceTrack=i.RTCRtpSender.prototype.setTrack)}const R3=Object.freeze(Object.defineProperty({__proto__:null,shimGetDisplayMedia:T3,shimGetUserMedia:M3,shimPeerConnection:gM,shimReplaceTrack:I3},Symbol.toStringTag,{value:"Module"}));function P3(i,e){const t=i&&i.navigator,n=i&&i.MediaStreamTrack;if(t.getUserMedia=function(r,s,o){Gb("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(r).then(s,o)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const r=function(o,a,l){a in o&&!(l in o)&&(o[l]=o[a],delete o[a])},s=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(o){return typeof o=="object"&&typeof o.audio=="object"&&(o=JSON.parse(JSON.stringify(o)),r(o.audio,"autoGainControl","mozAutoGainControl"),r(o.audio,"noiseSuppression","mozNoiseSuppression")),s(o)},n&&n.prototype.getSettings){const o=n.prototype.getSettings;n.prototype.getSettings=function(){const a=o.apply(this,arguments);return r(a,"mozAutoGainControl","autoGainControl"),r(a,"mozNoiseSuppression","noiseSuppression"),a}}if(n&&n.prototype.applyConstraints){const o=n.prototype.applyConstraints;n.prototype.applyConstraints=function(a){return this.kind==="audio"&&typeof a=="object"&&(a=JSON.parse(JSON.stringify(a)),r(a,"autoGainControl","mozAutoGainControl"),r(a,"noiseSuppression","mozNoiseSuppression")),o.apply(this,[a])}}}}function HZ(i,e){i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices||i.navigator.mediaDevices&&(i.navigator.mediaDevices.getDisplayMedia=function(t){if(!(t&&t.video)){const n=new DOMException("getDisplayMedia without video constraints is undefined");return n.name="NotFoundError",n.code=8,Promise.reject(n)}return t.video===!0?t.video={mediaSource:e}:t.video.mediaSource=e,i.navigator.mediaDevices.getUserMedia(t)})}function B3(i){typeof i=="object"&&i.RTCTrackEvent&&"receiver"in i.RTCTrackEvent.prototype&&!("transceiver"in i.RTCTrackEvent.prototype)&&Object.defineProperty(i.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function vM(i,e){if(typeof i!="object"||!(i.RTCPeerConnection||i.mozRTCPeerConnection))return;!i.RTCPeerConnection&&i.mozRTCPeerConnection&&(i.RTCPeerConnection=i.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(r){const s=i.RTCPeerConnection.prototype[r],o={[r](){return arguments[0]=new(r==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),s.apply(this,arguments)}};i.RTCPeerConnection.prototype[r]=o[r]});const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){const[r,s,o]=arguments;return n.apply(this,[r||null]).then(a=>{if(e.version<53&&!s)try{a.forEach(l=>{l.type=t[l.type]||l.type})}catch(l){if(l.name!=="TypeError")throw l;a.forEach((c,u)=>{a.set(u,Object.assign({},c,{type:t[c.type]||c.type}))})}return a}).then(s,o)}}function D3(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender)||i.RTCRtpSender&&"getStats"in i.RTCRtpSender.prototype)return;const e=i.RTCPeerConnection.prototype.getSenders;e&&(i.RTCPeerConnection.prototype.getSenders=function(){const n=e.apply(this,[]);return n.forEach(r=>r._pc=this),n});const t=i.RTCPeerConnection.prototype.addTrack;t&&(i.RTCPeerConnection.prototype.addTrack=function(){const n=t.apply(this,arguments);return n._pc=this,n}),i.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function O3(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender)||i.RTCRtpSender&&"getStats"in i.RTCRtpReceiver.prototype)return;const e=i.RTCPeerConnection.prototype.getReceivers;e&&(i.RTCPeerConnection.prototype.getReceivers=function(){const t=e.apply(this,[]);return t.forEach(n=>n._pc=this),t}),Dp(i,"track",t=>(t.receiver._pc=t.srcElement,t)),i.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function k3(i){!i.RTCPeerConnection||"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(e){Gb("removeStream","removeTrack"),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function L3(i){i.DataChannel&&!i.RTCDataChannel&&(i.RTCDataChannel=i.DataChannel)}function U3(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.addTransceiver;e&&(i.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];const t=arguments[1],n=t&&"sendEncodings"in t;n&&t.sendEncodings.forEach(s=>{if("rid"in s&&!/^[a-z0-9]{0,16}$/i.test(s.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in s&&!(parseFloat(s.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in s&&!(parseFloat(s.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const r=e.apply(this,arguments);if(n){const{sender:s}=r,o=s.getParameters();(!("encodings"in o)||o.encodings.length===1&&Object.keys(o.encodings[0]).length===0)&&(o.encodings=t.sendEncodings,s.sendEncodings=t.sendEncodings,this.setParametersPromises.push(s.setParameters(o).then(()=>{delete s.sendEncodings}).catch(()=>{delete s.sendEncodings})))}return r})}function F3(i){if(!(typeof i=="object"&&i.RTCRtpSender))return;const e=i.RTCRtpSender.prototype.getParameters;e&&(i.RTCRtpSender.prototype.getParameters=function(){const t=e.apply(this,arguments);return"encodings"in t||(t.encodings=[].concat(this.sendEncodings||[{}])),t})}function N3(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.createOffer;i.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function z3(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.createAnswer;i.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}const j3=Object.freeze(Object.defineProperty({__proto__:null,shimAddTransceiver:U3,shimCreateAnswer:z3,shimCreateOffer:N3,shimGetDisplayMedia:HZ,shimGetParameters:F3,shimGetUserMedia:P3,shimOnTrack:B3,shimPeerConnection:vM,shimRTCDataChannel:L3,shimReceiverGetStats:O3,shimRemoveStream:k3,shimSenderGetStats:D3},Symbol.toStringTag,{value:"Module"}));function G3(i){if(!(typeof i!="object"||!i.RTCPeerConnection)){if("getLocalStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in i.RTCPeerConnection.prototype)){const e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addStream=function(t){this._localStreams||(this._localStreams=[]),this._localStreams.includes(t)||this._localStreams.push(t),t.getAudioTracks().forEach(n=>e.call(this,n,t)),t.getVideoTracks().forEach(n=>e.call(this,n,t))},i.RTCPeerConnection.prototype.addTrack=function(t,...n){return n&&n.forEach(r=>{this._localStreams?this._localStreams.includes(r)||this._localStreams.push(r):this._localStreams=[r]}),e.apply(this,arguments)}}"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(t===-1)return;this._localStreams.splice(t,1);const n=e.getTracks();this.getSenders().forEach(r=>{n.includes(r.track)&&this.removeTrack(r)})})}}function Q3(i){if(!(typeof i!="object"||!i.RTCPeerConnection)&&("getRemoteStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in i.RTCPeerConnection.prototype))){Object.defineProperty(i.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=n=>{n.streams.forEach(r=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(r))return;this._remoteStreams.push(r);const s=new Event("addstream");s.stream=r,this.dispatchEvent(s)})})}});const e=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){const t=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(n){n.streams.forEach(r=>{if(t._remoteStreams||(t._remoteStreams=[]),t._remoteStreams.indexOf(r)>=0)return;t._remoteStreams.push(r);const s=new Event("addstream");s.stream=r,t.dispatchEvent(s)})}),e.apply(t,arguments)}}}function H3(i){if(typeof i!="object"||!i.RTCPeerConnection)return;const e=i.RTCPeerConnection.prototype,t=e.createOffer,n=e.createAnswer,r=e.setLocalDescription,s=e.setRemoteDescription,o=e.addIceCandidate;e.createOffer=function(l,c){const u=arguments.length>=2?arguments[2]:arguments[0],d=t.apply(this,[u]);return c?(d.then(l,c),Promise.resolve()):d},e.createAnswer=function(l,c){const u=arguments.length>=2?arguments[2]:arguments[0],d=n.apply(this,[u]);return c?(d.then(l,c),Promise.resolve()):d};let a=function(l,c,u){const d=r.apply(this,[l]);return u?(d.then(c,u),Promise.resolve()):d};e.setLocalDescription=a,a=function(l,c,u){const d=s.apply(this,[l]);return u?(d.then(c,u),Promise.resolve()):d},e.setRemoteDescription=a,a=function(l,c,u){const d=o.apply(this,[l]);return u?(d.then(c,u),Promise.resolve()):d},e.addIceCandidate=a}function V3(i){const e=i&&i.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,n=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=r=>n(W3(r))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=function(t,n,r){e.mediaDevices.getUserMedia(t).then(n,r)}.bind(e))}function W3(i){return i&&i.video!==void 0?Object.assign({},i,{video:h3(i.video)}):i}function q3(i){if(!i.RTCPeerConnection)return;const e=i.RTCPeerConnection;i.RTCPeerConnection=function(t,n){if(t&&t.iceServers){const r=[];for(let s=0;s<t.iceServers.length;s++){let o=t.iceServers[s];!o.hasOwnProperty("urls")&&o.hasOwnProperty("url")?(Gb("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,r.push(o)):r.push(t.iceServers[s])}t.iceServers=r}return new e(t,n)},i.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(i.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function X3(i){typeof i=="object"&&i.RTCTrackEvent&&"receiver"in i.RTCTrackEvent.prototype&&!("transceiver"in i.RTCTrackEvent.prototype)&&Object.defineProperty(i.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Y3(i){const e=i.RTCPeerConnection.prototype.createOffer;i.RTCPeerConnection.prototype.createOffer=function(t){if(t){typeof t.offerToReceiveAudio<"u"&&(t.offerToReceiveAudio=!!t.offerToReceiveAudio);const n=this.getTransceivers().find(s=>s.receiver.track.kind==="audio");t.offerToReceiveAudio===!1&&n?n.direction==="sendrecv"?n.setDirection?n.setDirection("sendonly"):n.direction="sendonly":n.direction==="recvonly"&&(n.setDirection?n.setDirection("inactive"):n.direction="inactive"):t.offerToReceiveAudio===!0&&!n&&this.addTransceiver("audio"),typeof t.offerToReceiveVideo<"u"&&(t.offerToReceiveVideo=!!t.offerToReceiveVideo);const r=this.getTransceivers().find(s=>s.receiver.track.kind==="video");t.offerToReceiveVideo===!1&&r?r.direction==="sendrecv"?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":r.direction==="recvonly"&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):t.offerToReceiveVideo===!0&&!r&&this.addTransceiver("video")}return e.apply(this,arguments)}}function J3(i){typeof i!="object"||i.AudioContext||(i.AudioContext=i.webkitAudioContext)}const K3=Object.freeze(Object.defineProperty({__proto__:null,shimAudioContext:J3,shimCallbacksAPI:H3,shimConstraints:W3,shimCreateOfferLegacy:Y3,shimGetUserMedia:V3,shimLocalStreamsAPI:G3,shimRTCIceServerUrls:q3,shimRemoteStreamsAPI:Q3,shimTrackEventTransceiver:X3},Symbol.toStringTag,{value:"Module"}));function Vb(i){if(!i.RTCIceCandidate||i.RTCIceCandidate&&"foundation"in i.RTCIceCandidate.prototype)return;const e=i.RTCIceCandidate;i.RTCIceCandidate=function(t){if(typeof t=="object"&&t.candidate&&t.candidate.indexOf("a=")===0&&(t=JSON.parse(JSON.stringify(t)),t.candidate=t.candidate.substr(2)),t.candidate&&t.candidate.length){const n=new e(t),r=Qb.parseCandidate(t.candidate),s=Object.assign(n,r);return s.toJSON=function(){return{candidate:s.candidate,sdpMid:s.sdpMid,sdpMLineIndex:s.sdpMLineIndex,usernameFragment:s.usernameFragment}},s}return new e(t)},i.RTCIceCandidate.prototype=e.prototype,Dp(i,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new i.RTCIceCandidate(t.candidate),writable:"false"}),t))}function Ig(i,e){if(!i.RTCPeerConnection)return;"sctp"in i.RTCPeerConnection.prototype||Object.defineProperty(i.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const t=function(a){if(!a||!a.sdp)return!1;const l=Qb.splitSections(a.sdp);return l.shift(),l.some(c=>{const u=Qb.parseMLine(c);return u&&u.kind==="application"&&u.protocol.indexOf("SCTP")!==-1})},n=function(a){const l=a.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(l===null||l.length<2)return-1;const c=parseInt(l[1],10);return c!==c?-1:c},r=function(a){let l=65536;return e.browser==="firefox"&&(e.version<57?a===-1?l=16384:l=2147483637:e.version<60?l=e.version===57?65535:65536:l=2147483637),l},s=function(a,l){let c=65536;e.browser==="firefox"&&e.version===57&&(c=65535);const u=Qb.matchPrefix(a.sdp,"a=max-message-size:");return u.length>0?c=parseInt(u[0].substr(19),10):e.browser==="firefox"&&l!==-1&&(c=2147483637),c},o=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76){const{sdpSemantics:a}=this.getConfiguration();a==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0})}if(t(arguments[0])){const a=n(arguments[0]),l=r(a),c=s(arguments[0],a);let u;l===0&&c===0?u=Number.POSITIVE_INFINITY:l===0||c===0?u=Math.max(l,c):u=Math.min(l,c);const d={};Object.defineProperty(d,"maxMessageSize",{get(){return u}}),this._sctp=d}return o.apply(this,arguments)}}function Rg(i){if(!(i.RTCPeerConnection&&"createDataChannel"in i.RTCPeerConnection.prototype))return;function e(n,r){const s=n.send;n.send=function(){const o=arguments[0],a=o.length||o.size||o.byteLength;if(n.readyState==="open"&&r.sctp&&a>r.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+r.sctp.maxMessageSize+" bytes)");return s.apply(n,arguments)}}const t=i.RTCPeerConnection.prototype.createDataChannel;i.RTCPeerConnection.prototype.createDataChannel=function(){const n=t.apply(this,arguments);return e(n,this),n},Dp(i,"datachannel",n=>(e(n.channel,n.target),n))}function AM(i){if(!i.RTCPeerConnection||"connectionState"in i.RTCPeerConnection.prototype)return;const e=i.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(t){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),t&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=t)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(t=>{const n=e[t];e[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=r=>{const s=r.target;if(s._lastConnectionState!==s.connectionState){s._lastConnectionState=s.connectionState;const o=new Event("connectionstatechange",r);s.dispatchEvent(o)}return r},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}})}function yM(i,e){if(!i.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e.version>=605)return;const t=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(n){if(n&&n.sdp&&n.sdp.indexOf(`
4952
4952
  a=extmap-allow-mixed`)!==-1){const r=n.sdp.split(`
4953
4953
  `).filter(s=>s.trim()!=="a=extmap-allow-mixed").join(`
4954
- `);i.RTCSessionDescription&&n instanceof i.RTCSessionDescription?arguments[0]=new i.RTCSessionDescription({type:n.type,sdp:r}):n.sdp=r}return t.apply(this,arguments)}}function Wb(i,e){if(!(i.RTCPeerConnection&&i.RTCPeerConnection.prototype))return;const t=i.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(i.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}const VZ=Object.freeze(Object.defineProperty({__proto__:null,removeExtmapAllowMixed:yM,shimAddIceCandidateNullOrEmpty:Wb,shimConnectionState:AM,shimMaxMessageSize:Ig,shimRTCIceCandidate:Vb,shimSendThrowTypeError:Rg},Symbol.toStringTag,{value:"Module"}));function WZ({window:i}={},e={shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0}){const t=dM,n=UZ(i),r={browserDetails:n,commonShim:VZ,extractVersion:Tg,disableLog:kZ,disableWarnings:LZ};switch(n.browser){case"chrome":if(!xU||!fM||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),r;if(n.version===null)return t("Chrome shim can not determine version, not shimming."),r;t("adapter.js shimming chrome."),r.browserShim=xU,Wb(i,n),pU(i,n),fU(i),fM(i,n),mU(i),bU(i,n),gU(i),vU(i),AU(i),_U(i,n),Vb(i),AM(i),Ig(i,n),Rg(i),yM(i,n);break;case"firefox":if(!jU||!vM||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),r;t("adapter.js shimming firefox."),r.browserShim=jU,Wb(i,n),PU(i,n),vM(i,n),BU(i),kU(i),DU(i),OU(i),LU(i),UU(i),FU(i),NU(i),zU(i),Vb(i),AM(i),Ig(i,n),Rg(i);break;case"edge":if(!RU||!gM||!e.shimEdge)return t("MS edge shim is not included in this adapter release."),r;t("adapter.js shimming edge."),r.browserShim=RU,MU(i),TU(i),gM(i,n),IU(i),Ig(i,n),Rg(i);break;case"safari":if(!KU||!e.shimSafari)return t("Safari shim is not included in this adapter release."),r;t("adapter.js shimming safari."),r.browserShim=KU,Wb(i,n),qU(i),YU(i),HU(i),GU(i),QU(i),XU(i),VU(i),JU(i),Vb(i),Ig(i,n),Rg(i),yM(i,n);break;default:t("Unsupported browser!");break}return r}const ZU=WZ({window:typeof window>"u"?void 0:window});function Ga(i,e,t,n){Object.defineProperty(i,e,{get:t,set:n,enumerable:!0,configurable:!0})}var bM=ZU.default||ZU,Pg=new(function(){function i(){this.isIOS=["iPad","iPhone","iPod"].includes(navigator.platform),this.supportedBrowsers=["firefox","chrome","safari"],this.minFirefoxVersion=59,this.minChromeVersion=72,this.minSafariVersion=605}return i.prototype.isWebRTCSupported=function(){return typeof RTCPeerConnection<"u"},i.prototype.isBrowserSupported=function(){var e=this.getBrowser(),t=this.getVersion(),n=this.supportedBrowsers.includes(e);return n?e==="chrome"?t>=this.minChromeVersion:e==="firefox"?t>=this.minFirefoxVersion:e==="safari"?!this.isIOS&&t>=this.minSafariVersion:!1:!1},i.prototype.getBrowser=function(){return bM.browserDetails.browser},i.prototype.getVersion=function(){return bM.browserDetails.version||0},i.prototype.isUnifiedPlanSupported=function(){var e=this.getBrowser(),t=bM.browserDetails.version||0;if(e==="chrome"&&t<this.minChromeVersion)return!1;if(e==="firefox"&&t>=this.minFirefoxVersion)return!0;if(!window.RTCRtpTransceiver||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;var n,r=!1;try{n=new RTCPeerConnection,n.addTransceiver("audio"),r=!0}catch{}finally{n&&n.close()}return r},i.prototype.toString=function(){return`Supports:
4954
+ `);i.RTCSessionDescription&&n instanceof i.RTCSessionDescription?arguments[0]=new i.RTCSessionDescription({type:n.type,sdp:r}):n.sdp=r}return t.apply(this,arguments)}}function Wb(i,e){if(!(i.RTCPeerConnection&&i.RTCPeerConnection.prototype))return;const t=i.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(i.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}const VZ=Object.freeze(Object.defineProperty({__proto__:null,removeExtmapAllowMixed:yM,shimAddIceCandidateNullOrEmpty:Wb,shimConnectionState:AM,shimMaxMessageSize:Ig,shimRTCIceCandidate:Vb,shimSendThrowTypeError:Rg},Symbol.toStringTag,{value:"Module"}));function WZ({window:i}={},e={shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0}){const t=dM,n=UZ(i),r={browserDetails:n,commonShim:VZ,extractVersion:Tg,disableLog:kZ,disableWarnings:LZ};switch(n.browser){case"chrome":if(!x3||!fM||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),r;if(n.version===null)return t("Chrome shim can not determine version, not shimming."),r;t("adapter.js shimming chrome."),r.browserShim=x3,Wb(i,n),p3(i,n),f3(i),fM(i,n),m3(i),b3(i,n),g3(i),v3(i),A3(i),_3(i,n),Vb(i),AM(i),Ig(i,n),Rg(i),yM(i,n);break;case"firefox":if(!j3||!vM||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),r;t("adapter.js shimming firefox."),r.browserShim=j3,Wb(i,n),P3(i,n),vM(i,n),B3(i),k3(i),D3(i),O3(i),L3(i),U3(i),F3(i),N3(i),z3(i),Vb(i),AM(i),Ig(i,n),Rg(i);break;case"edge":if(!R3||!gM||!e.shimEdge)return t("MS edge shim is not included in this adapter release."),r;t("adapter.js shimming edge."),r.browserShim=R3,M3(i),T3(i),gM(i,n),I3(i),Ig(i,n),Rg(i);break;case"safari":if(!K3||!e.shimSafari)return t("Safari shim is not included in this adapter release."),r;t("adapter.js shimming safari."),r.browserShim=K3,Wb(i,n),q3(i),Y3(i),H3(i),G3(i),Q3(i),X3(i),V3(i),J3(i),Vb(i),Ig(i,n),Rg(i),yM(i,n);break;default:t("Unsupported browser!");break}return r}const Z3=WZ({window:typeof window>"u"?void 0:window});function Ga(i,e,t,n){Object.defineProperty(i,e,{get:t,set:n,enumerable:!0,configurable:!0})}var bM=Z3.default||Z3,Pg=new(function(){function i(){this.isIOS=["iPad","iPhone","iPod"].includes(navigator.platform),this.supportedBrowsers=["firefox","chrome","safari"],this.minFirefoxVersion=59,this.minChromeVersion=72,this.minSafariVersion=605}return i.prototype.isWebRTCSupported=function(){return typeof RTCPeerConnection<"u"},i.prototype.isBrowserSupported=function(){var e=this.getBrowser(),t=this.getVersion(),n=this.supportedBrowsers.includes(e);return n?e==="chrome"?t>=this.minChromeVersion:e==="firefox"?t>=this.minFirefoxVersion:e==="safari"?!this.isIOS&&t>=this.minSafariVersion:!1:!1},i.prototype.getBrowser=function(){return bM.browserDetails.browser},i.prototype.getVersion=function(){return bM.browserDetails.version||0},i.prototype.isUnifiedPlanSupported=function(){var e=this.getBrowser(),t=bM.browserDetails.version||0;if(e==="chrome"&&t<this.minChromeVersion)return!1;if(e==="firefox"&&t>=this.minFirefoxVersion)return!0;if(!window.RTCRtpTransceiver||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;var n,r=!1;try{n=new RTCPeerConnection,n.addTransceiver("audio"),r=!0}catch{}finally{n&&n.close()}return r},i.prototype.toString=function(){return`Supports:
4955
4955
  browser:`.concat(this.getBrowser(),`
4956
4956
  version:`).concat(this.getVersion(),`
4957
4957
  isIOS:`).concat(this.isIOS,`
4958
4958
  isWebRTCSupported:`).concat(this.isWebRTCSupported(),`
4959
4959
  isBrowserSupported:`).concat(this.isBrowserSupported(),`
4960
- isUnifiedPlanSupported:`).concat(this.isUnifiedPlanSupported())},i}()),$U={iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:["turn:eu-0.turn.peerjs.com:3478","turn:us-0.turn.peerjs.com:3478"],username:"peerjs",credential:"peerjsp"}],sdpSemantics:"unified-plan"},qZ=function(){function i(){this.CLOUD_HOST="0.peerjs.com",this.CLOUD_PORT=443,this.chunkedBrowsers={Chrome:1,chrome:1},this.chunkedMTU=16300,this.defaultConfig=$U,this.browser=Pg.getBrowser(),this.browserVersion=Pg.getVersion(),this.supports=function(){var e={browser:Pg.isBrowserSupported(),webRTC:Pg.isWebRTCSupported(),audioVideo:!1,data:!1,binaryBlob:!1,reliable:!1};if(!e.webRTC)return e;var t;try{t=new RTCPeerConnection($U),e.audioVideo=!0;var n=void 0;try{n=t.createDataChannel("_PEERJSTEST",{ordered:!0}),e.data=!0,e.reliable=!!n.ordered;try{n.binaryType="blob",e.binaryBlob=!Pg.isIOS}catch{}}catch{}finally{n&&n.close()}}catch{}finally{t&&t.close()}return e}(),this.pack=oU.pack,this.unpack=oU.unpack,this._dataCount=1}return i.prototype.noop=function(){},i.prototype.validateId=function(e){return!e||/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.test(e)},i.prototype.chunk=function(e){for(var t=[],n=e.size,r=Math.ceil(n/mi.chunkedMTU),s=0,o=0;o<n;){var a=Math.min(n,o+mi.chunkedMTU),l=e.slice(o,a),c={__peerData:this._dataCount,n:s,data:l,total:r};t.push(c),o=a,s++}return this._dataCount++,t},i.prototype.blobToArrayBuffer=function(e,t){var n=new FileReader;return n.onload=function(r){r.target&&t(r.target.result)},n.readAsArrayBuffer(e),n},i.prototype.binaryStringToArrayBuffer=function(e){for(var t=new Uint8Array(e.length),n=0;n<e.length;n++)t[n]=e.charCodeAt(n)&255;return t.buffer},i.prototype.randomToken=function(){return Math.random().toString(36).slice(2)},i.prototype.isSecure=function(){return location.protocol==="https:"},i}(),mi=new qZ,e3={};Ga(e3,"Peer",()=>EM,i=>EM=i);var Bg={},XZ=Object.prototype.hasOwnProperty,ds="~";function Dg(){}Object.create&&(Dg.prototype=Object.create(null),new Dg().__proto__||(ds=!1));function YZ(i,e,t){this.fn=i,this.context=e,this.once=t||!1}function t3(i,e,t,n,r){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new YZ(t,n||i,r),o=ds?ds+e:e;return i._events[o]?i._events[o].fn?i._events[o]=[i._events[o],s]:i._events[o].push(s):(i._events[o]=s,i._eventsCount++),i}function qb(i,e){--i._eventsCount===0?i._events=new Dg:delete i._events[e]}function Wr(){this._events=new Dg,this._eventsCount=0}Wr.prototype.eventNames=function(){var i=[],e,t;if(this._eventsCount===0)return i;for(t in e=this._events)XZ.call(e,t)&&i.push(ds?t.slice(1):t);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i},Wr.prototype.listeners=function(i){var e=ds?ds+i:i,t=this._events[e];if(!t)return[];if(t.fn)return[t.fn];for(var n=0,r=t.length,s=new Array(r);n<r;n++)s[n]=t[n].fn;return s},Wr.prototype.listenerCount=function(i){var e=ds?ds+i:i,t=this._events[e];return t?t.fn?1:t.length:0},Wr.prototype.emit=function(i,e,t,n,r,s){var o=ds?ds+i:i;if(!this._events[o])return!1;var a=this._events[o],l=arguments.length,c,u;if(a.fn){switch(a.once&&this.removeListener(i,a.fn,void 0,!0),l){case 1:return a.fn.call(a.context),!0;case 2:return a.fn.call(a.context,e),!0;case 3:return a.fn.call(a.context,e,t),!0;case 4:return a.fn.call(a.context,e,t,n),!0;case 5:return a.fn.call(a.context,e,t,n,r),!0;case 6:return a.fn.call(a.context,e,t,n,r,s),!0}for(u=1,c=new Array(l-1);u<l;u++)c[u-1]=arguments[u];a.fn.apply(a.context,c)}else{var d=a.length,p;for(u=0;u<d;u++)switch(a[u].once&&this.removeListener(i,a[u].fn,void 0,!0),l){case 1:a[u].fn.call(a[u].context);break;case 2:a[u].fn.call(a[u].context,e);break;case 3:a[u].fn.call(a[u].context,e,t);break;case 4:a[u].fn.call(a[u].context,e,t,n);break;default:if(!c)for(p=1,c=new Array(l-1);p<l;p++)c[p-1]=arguments[p];a[u].fn.apply(a[u].context,c)}}return!0},Wr.prototype.on=function(i,e,t){return t3(this,i,e,t,!1)},Wr.prototype.once=function(i,e,t){return t3(this,i,e,t,!0)},Wr.prototype.removeListener=function(i,e,t,n){var r=ds?ds+i:i;if(!this._events[r])return this;if(!e)return qb(this,r),this;var s=this._events[r];if(s.fn)s.fn===e&&(!n||s.once)&&(!t||s.context===t)&&qb(this,r);else{for(var o=0,a=[],l=s.length;o<l;o++)(s[o].fn!==e||n&&!s[o].once||t&&s[o].context!==t)&&a.push(s[o]);a.length?this._events[r]=a.length===1?a[0]:a:qb(this,r)}return this},Wr.prototype.removeAllListeners=function(i){var e;return i?(e=ds?ds+i:i,this._events[e]&&qb(this,e)):(this._events=new Dg,this._eventsCount=0),this},Wr.prototype.off=Wr.prototype.removeListener,Wr.prototype.addListener=Wr.prototype.on,Wr.prefixed=ds,Wr.EventEmitter=Wr,Bg=Wr;var at={};Ga(at,"LogLevel",()=>Ds,i=>Ds=i),Ga(at,"default",()=>i3,i=>i3=i);var ku=function(i,e){var t=typeof Symbol=="function"&&i[Symbol.iterator];if(!t)return i;var n=t.call(i),r,s=[],o;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)s.push(r.value)}catch(a){o={error:a}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(o)throw o.error}}return s},Lu=function(i,e,t){if(t||arguments.length===2)for(var n=0,r=e.length,s;n<r;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return i.concat(s||Array.prototype.slice.call(e))},JZ="PeerJS: ",Ds;(function(i){i[i.Disabled=0]="Disabled",i[i.Errors=1]="Errors",i[i.Warnings=2]="Warnings",i[i.All=3]="All"})(Ds||(Ds={}));var KZ=function(){function i(){this._logLevel=Ds.Disabled}return Object.defineProperty(i.prototype,"logLevel",{get:function(){return this._logLevel},set:function(e){this._logLevel=e},enumerable:!1,configurable:!0}),i.prototype.log=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._logLevel>=Ds.All&&this._print.apply(this,Lu([Ds.All],ku(e),!1))},i.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._logLevel>=Ds.Warnings&&this._print.apply(this,Lu([Ds.Warnings],ku(e),!1))},i.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._logLevel>=Ds.Errors&&this._print.apply(this,Lu([Ds.Errors],ku(e),!1))},i.prototype.setLogFunction=function(e){this._print=e},i.prototype._print=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];var r=Lu([JZ],ku(t),!1);for(var s in r)r[s]instanceof Error&&(r[s]="("+r[s].name+") "+r[s].message);e>=Ds.All?console.log.apply(console,Lu([],ku(r),!1)):e>=Ds.Warnings?console.warn.apply(console,Lu(["WARNING"],ku(r),!1)):e>=Ds.Errors&&console.error.apply(console,Lu(["ERROR"],ku(r),!1))},i}(),i3=new KZ,n3={};Ga(n3,"Socket",()=>r3,i=>r3=i);var ca;(function(i){i.Data="data",i.Media="media"})(ca||(ca={}));var _n;(function(i){i.BrowserIncompatible="browser-incompatible",i.Disconnected="disconnected",i.InvalidID="invalid-id",i.InvalidKey="invalid-key",i.Network="network",i.PeerUnavailable="peer-unavailable",i.SslUnavailable="ssl-unavailable",i.ServerError="server-error",i.SocketError="socket-error",i.SocketClosed="socket-closed",i.UnavailableID="unavailable-id",i.WebRTC="webrtc"})(_n||(_n={}));var Wl;(function(i){i.Binary="binary",i.BinaryUTF8="binary-utf8",i.JSON="json"})(Wl||(Wl={}));var ql;(function(i){i.Message="message",i.Disconnected="disconnected",i.Error="error",i.Close="close"})(ql||(ql={}));var Ar;(function(i){i.Heartbeat="HEARTBEAT",i.Candidate="CANDIDATE",i.Offer="OFFER",i.Answer="ANSWER",i.Open="OPEN",i.Error="ERROR",i.IdTaken="ID-TAKEN",i.InvalidKey="INVALID-KEY",i.Leave="LEAVE",i.Expire="EXPIRE"})(Ar||(Ar={}));var _M={};_M=JSON.parse('{"name":"peerjs","version":"1.4.7","keywords":["peerjs","webrtc","p2p","rtc"],"description":"PeerJS client","homepage":"https://peerjs.com","bugs":{"url":"https://github.com/peers/peerjs/issues"},"repository":{"type":"git","url":"https://github.com/peers/peerjs"},"license":"MIT","contributors":["Michelle Bu <michelle@michellebu.com>","afrokick <devbyru@gmail.com>","ericz <really.ez@gmail.com>","Jairo <kidandcat@gmail.com>","Jonas Gloning <34194370+jonasgloning@users.noreply.github.com>","Jairo Caro-Accino Viciana <jairo@galax.be>","Carlos Caballero <carlos.caballero.gonzalez@gmail.com>","hc <hheennrryy@gmail.com>","Muhammad Asif <capripio@gmail.com>","PrashoonB <prashoonbhattacharjee@gmail.com>","Harsh Bardhan Mishra <47351025+HarshCasper@users.noreply.github.com>","akotynski <aleksanderkotbury@gmail.com>","lmb <i@lmb.io>","Jairooo <jairocaro@msn.com>","Moritz St\xFCckler <moritz.stueckler@gmail.com>","Simon <crydotsnakegithub@gmail.com>","Denis Lukov <denismassters@gmail.com>","Philipp Hancke <fippo@andyet.net>","Hans Oksendahl <hansoksendahl@gmail.com>","Jess <jessachandler@gmail.com>","khankuan <khankuan@gmail.com>","DUODVK <kurmanov.work@gmail.com>","XiZhao <kwang1imsa@gmail.com>","Matthias Lohr <matthias@lohr.me>","=frank tree <=frnktrb@googlemail.com>","Andre Eckardt <aeckardt@outlook.com>","Chris Cowan <agentme49@gmail.com>","Alex Chuev <alex@chuev.com>","alxnull <alxnull@e.mail.de>","Yemel Jardi <angel.jardi@gmail.com>","Ben Parnell <benjaminparnell.94@gmail.com>","Benny Lichtner <bennlich@gmail.com>","fresheneesz <bitetrudpublic@gmail.com>","bob.barstead@exaptive.com <bob.barstead@exaptive.com>","chandika <chandika@gmail.com>","emersion <contact@emersion.fr>","Christopher Van <cvan@users.noreply.github.com>","eddieherm <edhermoso@gmail.com>","Eduardo Pinho <enet4mikeenet@gmail.com>","Evandro Zanatta <ezanatta@tray.net.br>","Gardner Bickford <gardner@users.noreply.github.com>","Gian Luca <gianluca.cecchi@cynny.com>","PatrickJS <github@gdi2290.com>","jonnyf <github@jonathanfoss.co.uk>","Hizkia Felix <hizkifw@gmail.com>","Hristo Oskov <hristo.oskov@gmail.com>","Isaac Madwed <i.madwed@gmail.com>","Ilya Konanykhin <ilya.konanykhin@gmail.com>","jasonbarry <jasbarry@me.com>","Jonathan Burke <jonathan.burke.1311@googlemail.com>","Josh Hamit <josh.hamit@gmail.com>","Jordan Austin <jrax86@gmail.com>","Joel Wetzell <jwetzell@yahoo.com>","xizhao <kevin.wang@cloudera.com>","Alberto Torres <kungfoobar@gmail.com>","Jonathan Mayol <mayoljonathan@gmail.com>","Jefferson Felix <me@jsfelix.dev>","Rolf Erik Lekang <me@rolflekang.com>","Kevin Mai-Husan Chia <mhchia@users.noreply.github.com>","Pepijn de Vos <pepijndevos@gmail.com>","JooYoung <qkdlql@naver.com>","Tobias Speicher <rootcommander@gmail.com>","Steve Blaurock <sblaurock@gmail.com>","Kyrylo Shegeda <shegeda@ualberta.ca>","Diwank Singh Tomer <singh@diwank.name>","So\u0308ren Balko <Soeren.Balko@gmail.com>","Arpit Solanki <solankiarpit1997@gmail.com>","Yuki Ito <yuki@gnnk.net>","Artur Zayats <zag2art@gmail.com>"],"funding":{"type":"opencollective","url":"https://opencollective.com/peer"},"collective":{"type":"opencollective","url":"https://opencollective.com/peer"},"files":["dist/*"],"sideEffects":["lib/global.ts","lib/supports.ts"],"main":"dist/bundler.cjs","module":"dist/bundler.mjs","browser-minified":"dist/peerjs.min.js","browser-unminified":"dist/peerjs.js","types":"dist/types.d.ts","engines":{"node":">= 10"},"targets":{"types":{"source":"lib/exports.ts"},"main":{"source":"lib/exports.ts","sourceMap":{"inlineSources":true}},"module":{"source":"lib/exports.ts","includeNodeModules":["eventemitter3"],"sourceMap":{"inlineSources":true}},"browser-minified":{"context":"browser","outputFormat":"global","optimize":true,"engines":{"browsers":"cover 99%, not dead"},"source":"lib/global.ts"},"browser-unminified":{"context":"browser","outputFormat":"global","optimize":false,"engines":{"browsers":"cover 99%, not dead"},"source":"lib/global.ts"}},"scripts":{"contributors":"git-authors-cli --print=false && prettier --write package.json && git add package.json package-lock.json && git commit -m \\"chore(contributors): update and sort contributors list\\"","check":"tsc --noEmit","watch":"parcel watch","build":"rm -rf dist && parcel build","prepublishOnly":"npm run build","test":"mocha -r ts-node/register -r jsdom-global/register test/**/*.ts","format":"prettier --write .","semantic-release":"semantic-release"},"devDependencies":{"@parcel/config-default":"^2.5.0","@parcel/packager-ts":"^2.5.0","@parcel/transformer-typescript-tsc":"^2.5.0","@parcel/transformer-typescript-types":"^2.5.0","@semantic-release/changelog":"^6.0.1","@semantic-release/git":"^10.0.1","@types/chai":"^4.3.0","@types/mocha":"^9.1.0","@types/node":"^17.0.18","chai":"^4.3.6","git-authors-cli":"^1.0.40","jsdom":"^19.0.0","jsdom-global":"^3.0.2","mocha":"^9.2.0","mock-socket":"8.0.5","parcel":"^2.5.0","parcel-transformer-tsc-sourcemaps":"^1.0.2","prettier":"^2.6.2","semantic-release":"^19.0.2","standard":"^16.0.4","ts-node":"^10.5.0","typescript":"^4.5.5"},"dependencies":{"@swc/helpers":"^0.3.13","eventemitter3":"^4.0.7","peerjs-js-binarypack":"1.0.1","webrtc-adapter":"^7.7.1"}}');var ZZ=function(){var i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(n[s]=r[s])},i(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");i(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),$Z=function(i,e){var t=typeof Symbol=="function"&&i[Symbol.iterator];if(!t)return i;var n=t.call(i),r,s=[],o;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)s.push(r.value)}catch(a){o={error:a}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(o)throw o.error}}return s},e$=function(i,e,t){if(t||arguments.length===2)for(var n=0,r=e.length,s;n<r;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return i.concat(s||Array.prototype.slice.call(e))},t$=function(i){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&i[e],n=0;if(t)return t.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&n>=i.length&&(i=void 0),{value:i&&i[n++],done:!i}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},r3=function(i){ZZ(e,i);function e(t,n,r,s,o,a){a===void 0&&(a=5e3);var l=i.call(this)||this;l.pingInterval=a,l._disconnected=!0,l._messagesQueue=[];var c=t?"wss://":"ws://";return l._baseUrl=c+n+":"+r+s+"peerjs?key="+o,l}return e.prototype.start=function(t,n){var r=this;this._id=t;var s="".concat(this._baseUrl,"&id=").concat(t,"&token=").concat(n);this._socket||!this._disconnected||(this._socket=new WebSocket(s+"&version="+_M.version),this._disconnected=!1,this._socket.onmessage=function(o){var a;try{a=JSON.parse(o.data),at.default.log("Server message received:",a)}catch{at.default.log("Invalid server message",o.data);return}r.emit(ql.Message,a)},this._socket.onclose=function(o){r._disconnected||(at.default.log("Socket closed.",o),r._cleanup(),r._disconnected=!0,r.emit(ql.Disconnected))},this._socket.onopen=function(){r._disconnected||(r._sendQueuedMessages(),at.default.log("Socket open"),r._scheduleHeartbeat())})},e.prototype._scheduleHeartbeat=function(){var t=this;this._wsPingTimer=setTimeout(function(){t._sendHeartbeat()},this.pingInterval)},e.prototype._sendHeartbeat=function(){if(!this._wsOpen()){at.default.log("Cannot send heartbeat, because socket closed");return}var t=JSON.stringify({type:Ar.Heartbeat});this._socket.send(t),this._scheduleHeartbeat()},e.prototype._wsOpen=function(){return!!this._socket&&this._socket.readyState===1},e.prototype._sendQueuedMessages=function(){var t,n,r=e$([],$Z(this._messagesQueue),!1);this._messagesQueue=[];try{for(var s=t$(r),o=s.next();!o.done;o=s.next()){var a=o.value;this.send(a)}}catch(l){t={error:l}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}},e.prototype.send=function(t){if(!this._disconnected){if(!this._id){this._messagesQueue.push(t);return}if(!t.type){this.emit(ql.Error,"Invalid message");return}if(this._wsOpen()){var n=JSON.stringify(t);this._socket.send(n)}}},e.prototype.close=function(){this._disconnected||(this._cleanup(),this._disconnected=!0)},e.prototype._cleanup=function(){this._socket&&(this._socket.onopen=this._socket.onmessage=this._socket.onclose=null,this._socket.close(),this._socket=void 0),clearTimeout(this._wsPingTimer)},e}(Bg.EventEmitter),xM={};Ga(xM,"MediaConnection",()=>a3,i=>a3=i);var wM={};Ga(wM,"Negotiator",()=>s3,i=>s3=i);var Xb=function(){return Xb=Object.assign||function(i){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(i[r]=e[r])}return i},Xb.apply(this,arguments)},Yb=function(i,e,t,n){function r(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(u){try{c(n.next(u))}catch(d){o(d)}}function l(u){try{c(n.throw(u))}catch(d){o(d)}}function c(u){u.done?s(u.value):r(u.value).then(a,l)}c((n=n.apply(i,e||[])).next())})},Jb=function(i,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,r,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(c){return function(u){return l([c,u])}}function l(c){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,r&&(s=c[0]&2?r.return:c[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,c[1])).done)return s;switch(r=0,s&&(c=[c[0]&2,s.value]),c[0]){case 0:case 1:s=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,r=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!s||c[1]>s[0]&&c[1]<s[3])){t.label=c[1];break}if(c[0]===6&&t.label<s[1]){t.label=s[1],s=c;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(c);break}s[2]&&t.ops.pop(),t.trys.pop();continue}c=e.call(i,t)}catch(u){c=[6,u],r=0}finally{n=s=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}},s3=function(){function i(e){this.connection=e}return i.prototype.startConnection=function(e){var t=this._startPeerConnection();if(this.connection.peerConnection=t,this.connection.type===ca.Media&&e._stream&&this._addTracksToConnection(e._stream,t),e.originator){if(this.connection.type===ca.Data){var n=this.connection,r={ordered:!!e.reliable},s=t.createDataChannel(n.label,r);n.initialize(s)}this._makeOffer()}else this.handleSDP("OFFER",e.sdp)},i.prototype._startPeerConnection=function(){at.default.log("Creating RTCPeerConnection.");var e=new RTCPeerConnection(this.connection.provider.options.config);return this._setupListeners(e),e},i.prototype._setupListeners=function(e){var t=this,n=this.connection.peer,r=this.connection.connectionId,s=this.connection.type,o=this.connection.provider;at.default.log("Listening for ICE candidates."),e.onicecandidate=function(a){!a.candidate||!a.candidate.candidate||(at.default.log("Received ICE candidates for ".concat(n,":"),a.candidate),o.socket.send({type:Ar.Candidate,payload:{candidate:a.candidate,type:s,connectionId:r},dst:n}))},e.oniceconnectionstatechange=function(){switch(e.iceConnectionState){case"failed":at.default.log("iceConnectionState is failed, closing connections to "+n),t.connection.emit("error",new Error("Negotiation of connection to "+n+" failed.")),t.connection.close();break;case"closed":at.default.log("iceConnectionState is closed, closing connections to "+n),t.connection.emit("error",new Error("Connection to "+n+" closed.")),t.connection.close();break;case"disconnected":at.default.log("iceConnectionState changed to disconnected on the connection with "+n);break;case"completed":e.onicecandidate=mi.noop;break}t.connection.emit("iceStateChanged",e.iceConnectionState)},at.default.log("Listening for data channel"),e.ondatachannel=function(a){at.default.log("Received data channel");var l=a.channel,c=o.getConnection(n,r);c.initialize(l)},at.default.log("Listening for remote stream"),e.ontrack=function(a){at.default.log("Received remote stream");var l=a.streams[0],c=o.getConnection(n,r);if(c.type===ca.Media){var u=c;t._addStreamToMediaConnection(l,u)}}},i.prototype.cleanup=function(){at.default.log("Cleaning up PeerConnection to "+this.connection.peer);var e=this.connection.peerConnection;if(e){this.connection.peerConnection=null,e.onicecandidate=e.oniceconnectionstatechange=e.ondatachannel=e.ontrack=function(){};var t=e.signalingState!=="closed",n=!1;if(this.connection.type===ca.Data){var r=this.connection,s=r.dataChannel;s&&(n=!!s.readyState&&s.readyState!=="closed")}(t||n)&&e.close()}},i.prototype._makeOffer=function(){return Yb(this,void 0,Promise,function(){var e,t,n,r,s,o,a;return Jb(this,function(l){switch(l.label){case 0:e=this.connection.peerConnection,t=this.connection.provider,l.label=1;case 1:return l.trys.push([1,7,,8]),[4,e.createOffer(this.connection.options.constraints)];case 2:n=l.sent(),at.default.log("Created offer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(n.sdp=this.connection.options.sdpTransform(n.sdp)||n.sdp),l.label=3;case 3:return l.trys.push([3,5,,6]),[4,e.setLocalDescription(n)];case 4:return l.sent(),at.default.log("Set localDescription:",n,"for:".concat(this.connection.peer)),r={sdp:n,type:this.connection.type,connectionId:this.connection.connectionId,metadata:this.connection.metadata,browser:mi.browser},this.connection.type===ca.Data&&(s=this.connection,r=Xb(Xb({},r),{label:s.label,reliable:s.reliable,serialization:s.serialization})),t.socket.send({type:Ar.Offer,payload:r,dst:this.connection.peer}),[3,6];case 5:return o=l.sent(),o!="OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer"&&(t.emitError(_n.WebRTC,o),at.default.log("Failed to setLocalDescription, ",o)),[3,6];case 6:return[3,8];case 7:return a=l.sent(),t.emitError(_n.WebRTC,a),at.default.log("Failed to createOffer, ",a),[3,8];case 8:return[2]}})})},i.prototype._makeAnswer=function(){return Yb(this,void 0,Promise,function(){var e,t,n,r,s;return Jb(this,function(o){switch(o.label){case 0:e=this.connection.peerConnection,t=this.connection.provider,o.label=1;case 1:return o.trys.push([1,7,,8]),[4,e.createAnswer()];case 2:n=o.sent(),at.default.log("Created answer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(n.sdp=this.connection.options.sdpTransform(n.sdp)||n.sdp),o.label=3;case 3:return o.trys.push([3,5,,6]),[4,e.setLocalDescription(n)];case 4:return o.sent(),at.default.log("Set localDescription:",n,"for:".concat(this.connection.peer)),t.socket.send({type:Ar.Answer,payload:{sdp:n,type:this.connection.type,connectionId:this.connection.connectionId,browser:mi.browser},dst:this.connection.peer}),[3,6];case 5:return r=o.sent(),t.emitError(_n.WebRTC,r),at.default.log("Failed to setLocalDescription, ",r),[3,6];case 6:return[3,8];case 7:return s=o.sent(),t.emitError(_n.WebRTC,s),at.default.log("Failed to create answer, ",s),[3,8];case 8:return[2]}})})},i.prototype.handleSDP=function(e,t){return Yb(this,void 0,Promise,function(){var n,r,s,o;return Jb(this,function(a){switch(a.label){case 0:t=new RTCSessionDescription(t),n=this.connection.peerConnection,r=this.connection.provider,at.default.log("Setting remote description",t),s=this,a.label=1;case 1:return a.trys.push([1,5,,6]),[4,n.setRemoteDescription(t)];case 2:return a.sent(),at.default.log("Set remoteDescription:".concat(e," for:").concat(this.connection.peer)),e!=="OFFER"?[3,4]:[4,s._makeAnswer()];case 3:a.sent(),a.label=4;case 4:return[3,6];case 5:return o=a.sent(),r.emitError(_n.WebRTC,o),at.default.log("Failed to setRemoteDescription, ",o),[3,6];case 6:return[2]}})})},i.prototype.handleCandidate=function(e){return Yb(this,void 0,Promise,function(){var t,n,r,s,o,a;return Jb(this,function(l){switch(l.label){case 0:at.default.log("handleCandidate:",e),t=e.candidate,n=e.sdpMLineIndex,r=e.sdpMid,s=this.connection.peerConnection,o=this.connection.provider,l.label=1;case 1:return l.trys.push([1,3,,4]),[4,s.addIceCandidate(new RTCIceCandidate({sdpMid:r,sdpMLineIndex:n,candidate:t}))];case 2:return l.sent(),at.default.log("Added ICE candidate for:".concat(this.connection.peer)),[3,4];case 3:return a=l.sent(),o.emitError(_n.WebRTC,a),at.default.log("Failed to handleCandidate, ",a),[3,4];case 4:return[2]}})})},i.prototype._addTracksToConnection=function(e,t){if(at.default.log("add tracks from stream ".concat(e.id," to peer connection")),!t.addTrack)return at.default.error("Your browser does't support RTCPeerConnection#addTrack. Ignored.");e.getTracks().forEach(function(n){t.addTrack(n,e)})},i.prototype._addStreamToMediaConnection=function(e,t){at.default.log("add stream ".concat(e.id," to media connection ").concat(t.connectionId)),t.addStream(e)},i}(),SM={};Ga(SM,"BaseConnection",()=>o3,i=>o3=i);var i$=function(){var i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(n[s]=r[s])},i(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");i(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),o3=function(i){i$(e,i);function e(t,n,r){var s=i.call(this)||this;return s.peer=t,s.provider=n,s.options=r,s._open=!1,s.metadata=r.metadata,s}return Object.defineProperty(e.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),e}(Bg.EventEmitter),n$=function(){var i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(n[s]=r[s])},i(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");i(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Kb=function(){return Kb=Object.assign||function(i){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(i[r]=e[r])}return i},Kb.apply(this,arguments)},r$=function(i){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&i[e],n=0;if(t)return t.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&n>=i.length&&(i=void 0),{value:i&&i[n++],done:!i}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},a3=function(i){n$(e,i);function e(t,n,r){var s=i.call(this,t,n,r)||this;return s._localStream=s.options._stream,s.connectionId=s.options.connectionId||e.ID_PREFIX+mi.randomToken(),s._negotiator=new wM.Negotiator(s),s._localStream&&s._negotiator.startConnection({_stream:s._localStream,originator:!0}),s}return Object.defineProperty(e.prototype,"type",{get:function(){return ca.Media},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"localStream",{get:function(){return this._localStream},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteStream",{get:function(){return this._remoteStream},enumerable:!1,configurable:!0}),e.prototype.addStream=function(t){at.default.log("Receiving stream",t),this._remoteStream=t,i.prototype.emit.call(this,"stream",t)},e.prototype.handleMessage=function(t){var n=t.type,r=t.payload;switch(t.type){case Ar.Answer:this._negotiator.handleSDP(n,r.sdp),this._open=!0;break;case Ar.Candidate:this._negotiator.handleCandidate(r.candidate);break;default:at.default.warn("Unrecognized message type:".concat(n," from peer:").concat(this.peer));break}},e.prototype.answer=function(t,n){var r,s;if(n===void 0&&(n={}),this._localStream){at.default.warn("Local stream already exists on this MediaConnection. Are you answering a call twice?");return}this._localStream=t,n&&n.sdpTransform&&(this.options.sdpTransform=n.sdpTransform),this._negotiator.startConnection(Kb(Kb({},this.options._payload),{_stream:t}));var o=this.provider._getMessages(this.connectionId);try{for(var a=r$(o),l=a.next();!l.done;l=a.next()){var c=l.value;this.handleMessage(c)}}catch(u){r={error:u}}finally{try{l&&!l.done&&(s=a.return)&&s.call(a)}finally{if(r)throw r.error}}this._open=!0},e.prototype.close=function(){this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this._localStream=null,this._remoteStream=null,this.provider&&(this.provider._removeConnection(this),this.provider=null),this.options&&this.options._stream&&(this.options._stream=null),this.open&&(this._open=!1,i.prototype.emit.call(this,"close"))},e.ID_PREFIX="mc_",e}(SM.BaseConnection),CM={};Ga(CM,"DataConnection",()=>h3,i=>h3=i);var l3={};Ga(l3,"EncodingQueue",()=>c3,i=>c3=i);var s$=function(){var i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(n[s]=r[s])},i(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");i(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),c3=function(i){s$(e,i);function e(){var t=i.call(this)||this;return t.fileReader=new FileReader,t._queue=[],t._processing=!1,t.fileReader.onload=function(n){t._processing=!1,n.target&&t.emit("done",n.target.result),t.doNextTask()},t.fileReader.onerror=function(n){at.default.error("EncodingQueue error:",n),t._processing=!1,t.destroy(),t.emit("error",n)},t}return Object.defineProperty(e.prototype,"queue",{get:function(){return this._queue},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"size",{get:function(){return this.queue.length},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"processing",{get:function(){return this._processing},enumerable:!1,configurable:!0}),e.prototype.enque=function(t){this.queue.push(t),!this.processing&&this.doNextTask()},e.prototype.destroy=function(){this.fileReader.abort(),this._queue=[]},e.prototype.doNextTask=function(){this.size!==0&&(this.processing||(this._processing=!0,this.fileReader.readAsArrayBuffer(this.queue.shift())))},e}(Bg.EventEmitter),o$=function(){var i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(n[s]=r[s])},i(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");i(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),a$=function(i){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&i[e],n=0;if(t)return t.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&n>=i.length&&(i=void 0),{value:i&&i[n++],done:!i}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},h3=function(i){o$(e,i);function e(t,n,r){var s=i.call(this,t,n,r)||this;return s.stringify=JSON.stringify,s.parse=JSON.parse,s._buffer=[],s._bufferSize=0,s._buffering=!1,s._chunkedData={},s._encodingQueue=new l3.EncodingQueue,s.connectionId=s.options.connectionId||e.ID_PREFIX+mi.randomToken(),s.label=s.options.label||s.connectionId,s.serialization=s.options.serialization||Wl.Binary,s.reliable=!!s.options.reliable,s._encodingQueue.on("done",function(o){s._bufferedSend(o)}),s._encodingQueue.on("error",function(){at.default.error("DC#".concat(s.connectionId,": Error occured in encoding from blob to arraybuffer, close DC")),s.close()}),s._negotiator=new wM.Negotiator(s),s._negotiator.startConnection(s.options._payload||{originator:!0}),s}return Object.defineProperty(e.prototype,"type",{get:function(){return ca.Data},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"dataChannel",{get:function(){return this._dc},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"bufferSize",{get:function(){return this._bufferSize},enumerable:!1,configurable:!0}),e.prototype.initialize=function(t){this._dc=t,this._configureDataChannel()},e.prototype._configureDataChannel=function(){var t=this;(!mi.supports.binaryBlob||mi.supports.reliable)&&(this.dataChannel.binaryType="arraybuffer"),this.dataChannel.onopen=function(){at.default.log("DC#".concat(t.connectionId," dc connection success")),t._open=!0,t.emit("open")},this.dataChannel.onmessage=function(n){at.default.log("DC#".concat(t.connectionId," dc onmessage:"),n.data),t._handleDataMessage(n)},this.dataChannel.onclose=function(){at.default.log("DC#".concat(t.connectionId," dc closed for:"),t.peer),t.close()}},e.prototype._handleDataMessage=function(t){var n=this,r=t.data,s=r.constructor,o=this.serialization===Wl.Binary||this.serialization===Wl.BinaryUTF8,a=r;if(o){if(s===Blob){mi.blobToArrayBuffer(r,function(c){var u=mi.unpack(c);n.emit("data",u)});return}else if(s===ArrayBuffer)a=mi.unpack(r);else if(s===String){var l=mi.binaryStringToArrayBuffer(r);a=mi.unpack(l)}}else this.serialization===Wl.JSON&&(a=this.parse(r));if(a.__peerData){this._handleChunk(a);return}i.prototype.emit.call(this,"data",a)},e.prototype._handleChunk=function(t){var n=t.__peerData,r=this._chunkedData[n]||{data:[],count:0,total:t.total};if(r.data[t.n]=t.data,r.count++,this._chunkedData[n]=r,r.total===r.count){delete this._chunkedData[n];var s=new Blob(r.data);this._handleDataMessage({data:s})}},e.prototype.close=function(){this._buffer=[],this._bufferSize=0,this._chunkedData={},this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this.provider&&(this.provider._removeConnection(this),this.provider=null),this.dataChannel&&(this.dataChannel.onopen=null,this.dataChannel.onmessage=null,this.dataChannel.onclose=null,this._dc=null),this._encodingQueue&&(this._encodingQueue.destroy(),this._encodingQueue.removeAllListeners(),this._encodingQueue=null),this.open&&(this._open=!1,i.prototype.emit.call(this,"close"))},e.prototype.send=function(t,n){if(!this.open){i.prototype.emit.call(this,"error",new Error("Connection is not open. You should listen for the `open` event before sending messages."));return}if(this.serialization===Wl.JSON)this._bufferedSend(this.stringify(t));else if(this.serialization===Wl.Binary||this.serialization===Wl.BinaryUTF8){var r=mi.pack(t);if(!n&&r.size>mi.chunkedMTU){this._sendChunks(r);return}mi.supports.binaryBlob?this._bufferedSend(r):this._encodingQueue.enque(r)}else this._bufferedSend(t)},e.prototype._bufferedSend=function(t){(this._buffering||!this._trySend(t))&&(this._buffer.push(t),this._bufferSize=this._buffer.length)},e.prototype._trySend=function(t){var n=this;if(!this.open)return!1;if(this.dataChannel.bufferedAmount>e.MAX_BUFFERED_AMOUNT)return this._buffering=!0,setTimeout(function(){n._buffering=!1,n._tryBuffer()},50),!1;try{this.dataChannel.send(t)}catch(r){return at.default.error("DC#:".concat(this.connectionId," Error when sending:"),r),this._buffering=!0,this.close(),!1}return!0},e.prototype._tryBuffer=function(){if(this.open&&this._buffer.length!==0){var t=this._buffer[0];this._trySend(t)&&(this._buffer.shift(),this._bufferSize=this._buffer.length,this._tryBuffer())}},e.prototype._sendChunks=function(t){var n,r,s=mi.chunk(t);at.default.log("DC#".concat(this.connectionId," Try to send ").concat(s.length," chunks..."));try{for(var o=a$(s),a=o.next();!a.done;a=o.next()){var l=a.value;this.send(l,!0)}}catch(c){n={error:c}}finally{try{a&&!a.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}},e.prototype.handleMessage=function(t){var n=t.payload;switch(t.type){case Ar.Answer:this._negotiator.handleSDP(t.type,n.sdp);break;case Ar.Candidate:this._negotiator.handleCandidate(n.candidate);break;default:at.default.warn("Unrecognized message type:",t.type,"from peer:",this.peer);break}},e.ID_PREFIX="dc_",e.MAX_BUFFERED_AMOUNT=8388608,e}(SM.BaseConnection),u3={};Ga(u3,"API",()=>f3,i=>f3=i);var d3=function(i,e,t,n){function r(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(u){try{c(n.next(u))}catch(d){o(d)}}function l(u){try{c(n.throw(u))}catch(d){o(d)}}function c(u){u.done?s(u.value):r(u.value).then(a,l)}c((n=n.apply(i,e||[])).next())})},p3=function(i,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,r,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(c){return function(u){return l([c,u])}}function l(c){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,r&&(s=c[0]&2?r.return:c[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,c[1])).done)return s;switch(r=0,s&&(c=[c[0]&2,s.value]),c[0]){case 0:case 1:s=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,r=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!s||c[1]>s[0]&&c[1]<s[3])){t.label=c[1];break}if(c[0]===6&&t.label<s[1]){t.label=s[1],s=c;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(c);break}s[2]&&t.ops.pop(),t.trys.pop();continue}c=e.call(i,t)}catch(u){c=[6,u],r=0}finally{n=s=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}},f3=function(){function i(e){this._options=e}return i.prototype._buildRequest=function(e){var t=this._options.secure?"https":"http",n=this._options,r=n.host,s=n.port,o=n.path,a=n.key,l=new URL("".concat(t,"://").concat(r,":").concat(s).concat(o).concat(a,"/").concat(e));return l.searchParams.set("ts","".concat(Date.now()).concat(Math.random())),l.searchParams.set("version",_M.version),fetch(l.href,{referrerPolicy:this._options.referrerPolicy})},i.prototype.retrieveId=function(){return d3(this,void 0,Promise,function(){var e,t,n;return p3(this,function(r){switch(r.label){case 0:return r.trys.push([0,2,,3]),[4,this._buildRequest("id")];case 1:if(e=r.sent(),e.status!==200)throw new Error("Error. Status:".concat(e.status));return[2,e.text()];case 2:throw t=r.sent(),at.default.error("Error retrieving ID",t),n="",this._options.path==="/"&&this._options.host!==mi.CLOUD_HOST&&(n=" If you passed in a `path` to your self-hosted PeerServer, you'll also need to pass in that same path when creating a new Peer."),new Error("Could not get an ID from the server."+n);case 3:return[2]}})})},i.prototype.listAllPeers=function(){return d3(this,void 0,Promise,function(){var e,t,n;return p3(this,function(r){switch(r.label){case 0:return r.trys.push([0,2,,3]),[4,this._buildRequest("peers")];case 1:if(e=r.sent(),e.status!==200)throw e.status===401?(t="",this._options.host===mi.CLOUD_HOST?t="It looks like you're using the cloud server. You can email team@peerjs.com to enable peer listing for your API key.":t="You need to enable `allow_discovery` on your self-hosted PeerServer to use this feature.",new Error("It doesn't look like you have permission to list peers IDs. "+t)):new Error("Error. Status:".concat(e.status));return[2,e.json()];case 2:throw n=r.sent(),at.default.error("Error retrieving list peers",n),new Error("Could not get list peers from the server."+n);case 3:return[2]}})})},i}(),l$=function(){var i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(n[s]=r[s])},i(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");i(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Og=function(){return Og=Object.assign||function(i){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(i[r]=e[r])}return i},Og.apply(this,arguments)},kg=function(i){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&i[e],n=0;if(t)return t.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&n>=i.length&&(i=void 0),{value:i&&i[n++],done:!i}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},c$=function(i,e){var t=typeof Symbol=="function"&&i[Symbol.iterator];if(!t)return i;var n=t.call(i),r,s=[],o;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)s.push(r.value)}catch(a){o={error:a}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(o)throw o.error}}return s},EM=function(i){l$(e,i);function e(t,n){var r=i.call(this)||this;r._id=null,r._lastServerId=null,r._destroyed=!1,r._disconnected=!1,r._open=!1,r._connections=new Map,r._lostMessages=new Map;var s;return t&&t.constructor==Object?n=t:t&&(s=t.toString()),n=Og({debug:0,host:mi.CLOUD_HOST,port:mi.CLOUD_PORT,path:"/",key:e.DEFAULT_KEY,token:mi.randomToken(),config:mi.defaultConfig,referrerPolicy:"strict-origin-when-cross-origin"},n),r._options=n,r._options.host==="/"&&(r._options.host=window.location.hostname),r._options.path&&(r._options.path[0]!=="/"&&(r._options.path="/"+r._options.path),r._options.path[r._options.path.length-1]!=="/"&&(r._options.path+="/")),r._options.secure===void 0&&r._options.host!==mi.CLOUD_HOST?r._options.secure=mi.isSecure():r._options.host==mi.CLOUD_HOST&&(r._options.secure=!0),r._options.logFunction&&at.default.setLogFunction(r._options.logFunction),at.default.logLevel=r._options.debug||0,r._api=new u3.API(n),r._socket=r._createServerConnection(),!mi.supports.audioVideo&&!mi.supports.data?(r._delayedAbort(_n.BrowserIncompatible,"The current browser does not support WebRTC"),r):s&&!mi.validateId(s)?(r._delayedAbort(_n.InvalidID,'ID "'.concat(s,'" is invalid')),r):(s?r._initialize(s):r._api.retrieveId().then(function(o){return r._initialize(o)}).catch(function(o){return r._abort(_n.ServerError,o)}),r)}return Object.defineProperty(e.prototype,"id",{get:function(){return this._id},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"options",{get:function(){return this._options},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"socket",{get:function(){return this._socket},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"connections",{get:function(){var t,n,r=Object.create(null);try{for(var s=kg(this._connections),o=s.next();!o.done;o=s.next()){var a=c$(o.value,2),l=a[0],c=a[1];r[l]=c}}catch(u){t={error:u}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}return r},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"destroyed",{get:function(){return this._destroyed},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"disconnected",{get:function(){return this._disconnected},enumerable:!1,configurable:!0}),e.prototype._createServerConnection=function(){var t=this,n=new n3.Socket(this._options.secure,this._options.host,this._options.port,this._options.path,this._options.key,this._options.pingInterval);return n.on(ql.Message,function(r){t._handleMessage(r)}),n.on(ql.Error,function(r){t._abort(_n.SocketError,r)}),n.on(ql.Disconnected,function(){t.disconnected||(t.emitError(_n.Network,"Lost connection to server."),t.disconnect())}),n.on(ql.Close,function(){t.disconnected||t._abort(_n.SocketClosed,"Underlying socket is already closed.")}),n},e.prototype._initialize=function(t){this._id=t,this.socket.start(t,this._options.token)},e.prototype._handleMessage=function(t){var n,r,s=t.type,o=t.payload,a=t.src;switch(s){case Ar.Open:this._lastServerId=this.id,this._open=!0,this.emit("open",this.id);break;case Ar.Error:this._abort(_n.ServerError,o.msg);break;case Ar.IdTaken:this._abort(_n.UnavailableID,'ID "'.concat(this.id,'" is taken'));break;case Ar.InvalidKey:this._abort(_n.InvalidKey,'API KEY "'.concat(this._options.key,'" is invalid'));break;case Ar.Leave:at.default.log("Received leave message from ".concat(a)),this._cleanupPeer(a),this._connections.delete(a);break;case Ar.Expire:this.emitError(_n.PeerUnavailable,"Could not connect to peer ".concat(a));break;case Ar.Offer:var m=o.connectionId,A=this.getConnection(a,m);if(A&&(A.close(),at.default.warn("Offer received for existing Connection ID:".concat(m))),o.type===ca.Media){var l=new xM.MediaConnection(a,this,{connectionId:m,_payload:o,metadata:o.metadata});A=l,this._addConnection(a,A),this.emit("call",l)}else if(o.type===ca.Data){var c=new CM.DataConnection(a,this,{connectionId:m,_payload:o,metadata:o.metadata,label:o.label,serialization:o.serialization,reliable:o.reliable});A=c,this._addConnection(a,A),this.emit("connection",c)}else{at.default.warn("Received malformed connection type:".concat(o.type));return}var u=this._getMessages(m);try{for(var d=kg(u),p=d.next();!p.done;p=d.next()){var f=p.value;A.handleMessage(f)}}catch(v){n={error:v}}finally{try{p&&!p.done&&(r=d.return)&&r.call(d)}finally{if(n)throw n.error}}break;default:if(!o){at.default.warn("You received a malformed message from ".concat(a," of type ").concat(s));return}var m=o.connectionId,A=this.getConnection(a,m);A&&A.peerConnection?A.handleMessage(t):m?this._storeMessage(m,t):at.default.warn("You received an unrecognized message:",t);break}},e.prototype._storeMessage=function(t,n){this._lostMessages.has(t)||this._lostMessages.set(t,[]),this._lostMessages.get(t).push(n)},e.prototype._getMessages=function(t){var n=this._lostMessages.get(t);return n?(this._lostMessages.delete(t),n):[]},e.prototype.connect=function(t,n){if(n===void 0&&(n={}),this.disconnected){at.default.warn("You cannot connect to a new Peer because you called .disconnect() on this Peer and ended your connection with the server. You can create a new Peer to reconnect, or call reconnect on this peer if you believe its ID to still be available."),this.emitError(_n.Disconnected,"Cannot connect to new Peer after disconnecting from server.");return}var r=new CM.DataConnection(t,this,n);return this._addConnection(t,r),r},e.prototype.call=function(t,n,r){if(r===void 0&&(r={}),this.disconnected){at.default.warn("You cannot connect to a new Peer because you called .disconnect() on this Peer and ended your connection with the server. You can create a new Peer to reconnect."),this.emitError(_n.Disconnected,"Cannot connect to new Peer after disconnecting from server.");return}if(!n){at.default.error("To call a peer, you must provide a stream from your browser's `getUserMedia`.");return}var s=new xM.MediaConnection(t,this,Og(Og({},r),{_stream:n}));return this._addConnection(t,s),s},e.prototype._addConnection=function(t,n){at.default.log("add connection ".concat(n.type,":").concat(n.connectionId," to peerId:").concat(t)),this._connections.has(t)||this._connections.set(t,[]),this._connections.get(t).push(n)},e.prototype._removeConnection=function(t){var n=this._connections.get(t.peer);if(n){var r=n.indexOf(t);r!==-1&&n.splice(r,1)}this._lostMessages.delete(t.connectionId)},e.prototype.getConnection=function(t,n){var r,s,o=this._connections.get(t);if(!o)return null;try{for(var a=kg(o),l=a.next();!l.done;l=a.next()){var c=l.value;if(c.connectionId===n)return c}}catch(u){r={error:u}}finally{try{l&&!l.done&&(s=a.return)&&s.call(a)}finally{if(r)throw r.error}}return null},e.prototype._delayedAbort=function(t,n){var r=this;setTimeout(function(){r._abort(t,n)},0)},e.prototype._abort=function(t,n){at.default.error("Aborting!"),this.emitError(t,n),this._lastServerId?this.disconnect():this.destroy()},e.prototype.emitError=function(t,n){at.default.error("Error:",n);var r;typeof n=="string"?r=new Error(n):r=n,r.type=t,this.emit("error",r)},e.prototype.destroy=function(){this.destroyed||(at.default.log("Destroy peer with ID:".concat(this.id)),this.disconnect(),this._cleanup(),this._destroyed=!0,this.emit("close"))},e.prototype._cleanup=function(){var t,n;try{for(var r=kg(this._connections.keys()),s=r.next();!s.done;s=r.next()){var o=s.value;this._cleanupPeer(o),this._connections.delete(o)}}catch(a){t={error:a}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}finally{if(t)throw t.error}}this.socket.removeAllListeners()},e.prototype._cleanupPeer=function(t){var n,r,s=this._connections.get(t);if(s)try{for(var o=kg(s),a=o.next();!a.done;a=o.next()){var l=a.value;l.close()}}catch(c){n={error:c}}finally{try{a&&!a.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}},e.prototype.disconnect=function(){if(!this.disconnected){var t=this.id;at.default.log("Disconnect peer with ID:".concat(t)),this._disconnected=!0,this._open=!1,this.socket.close(),this._lastServerId=t,this._id=null,this.emit("disconnected",t)}},e.prototype.reconnect=function(){if(this.disconnected&&!this.destroyed)at.default.log("Attempting reconnection to server with ID ".concat(this._lastServerId)),this._disconnected=!1,this._initialize(this._lastServerId);else{if(this.destroyed)throw new Error("This peer cannot reconnect to the server. It has already been destroyed.");if(!this.disconnected&&!this.open)at.default.error("In a hurry? We're still trying to make the initial connection!");else throw new Error("Peer ".concat(this.id," cannot reconnect because it is not disconnected from the server!"))}},e.prototype.listAllPeers=function(t){var n=this;t===void 0&&(t=function(r){}),this._api.listAllPeers().then(function(r){return t(r)}).catch(function(r){return n._abort(_n.ServerError,r)})},e.DEFAULT_KEY="peerjs",e}(Bg.EventEmitter),MM=e3.Peer;const h$=Object.freeze(Object.defineProperty({__proto__:null,get Peer(){return EM},default:MM,util:mi},Symbol.toStringTag,{value:"Module"}));let TM;function u$(){return TM}function d$(i){TM=i}function m3(i,e){return e||(e={}),e={...TM,...e},i?new MM(i,e):new MM(e)}async function g3(){const i=await Promise.resolve().then(()=>h$);return console.log(i),i.default===void 0?i:i.default}class v3{constructor(){h(this,"_host"),h(this,"_client"),h(this,"_clientData"),this.onEnable()}get isHost(){return this._host!==void 0}onEnable(){const e="HOST-5980e65c-8438-453e-8b35-f13c736dcd81";this.trySetupHost(e)}async trySetupHost(e){const t=await g3(),n=new t(e);n.on("error",r=>{console.error(r),this._host=void 0,this.trySetupClient(e)}),n.on("open",r=>{this._host=new f$(n)})}async trySetupClient(e){const t=await g3();this._client=new t,this._client.on("error",n=>{console.error("Client error",n)}),this._client.on("open",n=>{console.log("client connected",n),this._clientData=this._client.connect(e,{metadata:{id:n}}),this._clientData.on("open",()=>{console.log("Connected to host")}),this._clientData.on("data",r=>{console.log("<<",r)})})}}class p${constructor(e){h(this,"_peer"),this._peer=e}}class f$ extends p${constructor(e){var t;super(e),h(this,"_connections",[]),console.log("I AM THE HOST"),(t=this._peer)==null||t.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("BYE")}),setInterval(()=>{this.broadcast("HELLO")},2e3)}get isHost(){return!0}onConnection(e){console.log("host connection",e),e.on("open",()=>{this._connections.push(e),this.broadcastConnection(e)})}broadcastConnection(e){const t=this._connections.map(n=>{var r;return(r=n.metadata)==null?void 0:r.id}).filter(n=>n!==void 0);this.broadcast({type:"connection-list",connections:t})}broadcast(e){if(e!=null){console.log(">>",e);for(const t in this._peer.connections){const n=this._peer.connections[t];if(n)if(Array.isArray(n))for(const r of n)r&&r.send(e);else console.warn(n)}}}}const A3="https://urls.needle.tools/default-networking-backend/index";let Kc="wss://needle-tiny-starter.glitch.me/socket";const ps=!!ee("debugnet"),Lg=!!(ps||ee("debugowner")),y3=ee("debugnetbin");var b3=(i=>(i.ConnectionInfo="connection-start-info",i))(b3||{}),Jt=(i=>(i.Join="join-room",i.Leave="leave-room",i.JoinedRoom="joined-room",i.LeftRoom="left-room",i.UserJoinedRoom="user-joined-room",i.UserLeftRoom="user-left-room",i.RoomStateSent="room-state-sent",i))(Jt||{});class m${constructor(){h(this,"room"),h(this,"viewId"),h(this,"allowEditing"),h(this,"inRoom")}}class g${constructor(){h(this,"room")}}class v${constructor(){h(this,"userId")}}var _3=(i=>(i.RequestHasOwner="request-has-owner",i.ResponseHasOwner="response-has-owner",i.RequestIsOwner="request-is-owner",i.ResponseIsOwner="response-is-owner",i.RequestOwnership="request-ownership",i.GainedOwnership="gained-ownership",i.RemoveOwnership="remove-ownership",i.LostOwnership="lost-ownership",i.GainedOwnershipBroadcast="gained-ownership-broadcast",i.LostOwnershipBroadcast="lost-ownership-broadcast",i))(_3||{});class IM{constructor(e,t){h(this,"guid"),h(this,"connection"),h(this,"_hasOwnership",!1),h(this,"_isOwned"),h(this,"_gainSubscription"),h(this,"_lostSubscription"),h(this,"_hasOwnerResponse"),h(this,"_isWaitingForOwnershipResponseCallback",null),this.connection=e,this.guid=t,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),e.beginListen("lost-ownership",this._lostSubscription),e.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),e.beginListen("response-has-owner",this._hasOwnerResponse)}get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}updateIsOwned(){this.connection.send("request-has-owner",{guid:this.guid})}onHasOwnerResponse(e){e.guid===this.guid&&(this._isOwned=e.value)}requestOwnershipIfNotOwned(){return this._isWaitingForOwnershipResponseCallback!==null?this:(this._isWaitingForOwnershipResponseCallback=this.waitForHasOwnershipRequestResponse.bind(this),this.connection.beginListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this.connection.send("request-has-owner",{guid:this.guid}),this)}waitForHasOwnershipRequestResponse(e){e.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=e.value,e.value||(Lg&&console.log("request ownership",this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((e,t)=>{this.requestOwnership();let n=0;const r=()=>{if(n++>10)return t("Timeout");setTimeout(()=>{this.hasOwnership?e(this):r()},100)};r()})}requestOwnership(){return Lg&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),this}freeOwnership(){return this.connection.send("remove-ownership",{guid:this.guid}),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this}destroy(){this.connection.stopListen("gained-ownership",this._gainSubscription),this.connection.stopListen("lost-ownership",this._lostSubscription),this.connection.stopListen("response-has-owner",this._hasOwnerResponse),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null)}onGainedOwnership(e){e.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===e.owner?(Lg&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(Lg&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}}class x3{constructor(e){h(this,"context"),h(this,"_peer",null),h(this,"_usersInRoomCopy",[]),h(this,"_defaultMessagesBuffer",[]),h(this,"_defaultMessagesBufferArray",[]),h(this,"netWebSocketUrlProvider"),h(this,"_listeners",{}),h(this,"_listenersBinary",{}),h(this,"connected",!1),h(this,"channelId"),h(this,"_connectionId",null),h(this,"_ws"),h(this,"_waitingForSocket",{}),h(this,"_isInRoom",!1),h(this,"_currentRoomName",null),h(this,"_currentRoomViewId",null),h(this,"_currentRoomAllowEditing",!0),h(this,"_currentInRoom",[]),h(this,"_state",{}),h(this,"_currentDelay",-1),h(this,"_connectingToWebsocketPromise",null),this.context=e}get peer(){return this._peer||(this._peer=new v3),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return ps}get isConnected(){return this.connected}get currentRoomName(){return this._currentRoomName}get allowEditing(){return this._currentRoomAllowEditing}get currentRoomViewId(){return this._currentRoomViewId}get isInRoom(){return this._isInRoom}get currentLatency(){return this._currentDelay}get currentServerUrl(){var e;return((e=this._ws)==null?void 0:e.url)??null}sendPing(){this.send("ping",{time:this.context.time.time})}userIsInRoom(e){return this._currentInRoom.indexOf(e)!==-1}usersInRoom(e=null){e||(e=this._usersInRoomCopy),e.length=0;for(const t of this._currentInRoom)e.push(t);return e}joinRoom(e,t=!1){return e?e.length>1024?(console.error('Room name too long, can not join: "'+e+'". Max length is 1024 characters.'),!1):(this.connect(),ps&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},la.OnConnection),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}leaveRoom(e=null){return e||(e=this.currentRoomName),e?(this.send("leave-room",{room:e}),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}send(e,t=null,n=la.Queued){if(t===null&&(t={}),n===la.Queued){this._defaultMessagesBuffer.push({key:e,value:t});return}return this.sendWithWebsocket(e,t,n)}sendDeleteRemoteState(e){this.send("delete-state",{guid:e,dontSave:!0}),delete this._state[e]}sendDeleteRemoteStateAll(){this.send("delete-all-state"),this._state={}}sendBinary(e){var t;y3&&console.log("<< send binary",this.context.time.frame,e.length/1024+" KB"),(t=this._ws)==null||t.send(e)}sendBufferedMessagesNow(){var e;if(!this._ws)return;this._defaultMessagesBufferArray.length=0;const t=Object.keys(this._defaultMessagesBuffer).length;for(const r in this._defaultMessagesBuffer){const s=this._defaultMessagesBuffer[r];if(t<=1){this.sendWithWebsocket(s.key,s.value,la.Immediate);break}const o=this.toMessage(s.key,s.value);this._defaultMessagesBufferArray.push(o)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&ps&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;const n=JSON.stringify(this._defaultMessagesBufferArray);(e=this._ws)==null||e.send(n)}beginListen(e,t){return this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t),t}stopListening(e,t){return this.stopListen(e,t)}stopListen(e,t){if(!t||!this._listeners[e])return;const n=this._listeners[e].indexOf(t);n>=0&&this._listeners[e].splice(n,1)}beginListenBinary(e,t){return this._listenersBinary[e]||(this._listenersBinary[e]=[]),this._listenersBinary[e].push(t),t}stopListenBinary(e,t){if(!this._listenersBinary[e])return;const n=this._listenersBinary[e].indexOf(t);n>=0&&this._listenersBinary[e].splice(n,1)}registerProvider(e){this.netWebSocketUrlProvider=e}async connect(){var e;if(this.connected)return Promise.resolve(!0);ps&&console.log("connecting");const t=(e=this.netWebSocketUrlProvider)==null?void 0:e.getWebsocketUrl();return t?Kc=t:hO()&&(Kc="wss://"+window.location.host+"/socket"),this.connectWebsocket()}disconnect(){var e;(e=this._ws)==null||e.close(),this._ws=void 0}connectWebsocket(){return this._connectingToWebsocketPromise?this._connectingToWebsocketPromise:this._connectingToWebsocketPromise=new Promise(async(e,t)=>{var n;let r=!1;const s=c=>{r||(r=!0,e(c))};if(Kc===void 0&&(console.log("Fetch default backend url: "+A3),Kc=await(await fetch(A3)).text()),Kc===void 0){s(!1);return}console.log(`\u22A1 Connecting to networking backend on
4960
+ isUnifiedPlanSupported:`).concat(this.isUnifiedPlanSupported())},i}()),$3={iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:["turn:eu-0.turn.peerjs.com:3478","turn:us-0.turn.peerjs.com:3478"],username:"peerjs",credential:"peerjsp"}],sdpSemantics:"unified-plan"},qZ=function(){function i(){this.CLOUD_HOST="0.peerjs.com",this.CLOUD_PORT=443,this.chunkedBrowsers={Chrome:1,chrome:1},this.chunkedMTU=16300,this.defaultConfig=$3,this.browser=Pg.getBrowser(),this.browserVersion=Pg.getVersion(),this.supports=function(){var e={browser:Pg.isBrowserSupported(),webRTC:Pg.isWebRTCSupported(),audioVideo:!1,data:!1,binaryBlob:!1,reliable:!1};if(!e.webRTC)return e;var t;try{t=new RTCPeerConnection($3),e.audioVideo=!0;var n=void 0;try{n=t.createDataChannel("_PEERJSTEST",{ordered:!0}),e.data=!0,e.reliable=!!n.ordered;try{n.binaryType="blob",e.binaryBlob=!Pg.isIOS}catch{}}catch{}finally{n&&n.close()}}catch{}finally{t&&t.close()}return e}(),this.pack=o3.pack,this.unpack=o3.unpack,this._dataCount=1}return i.prototype.noop=function(){},i.prototype.validateId=function(e){return!e||/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.test(e)},i.prototype.chunk=function(e){for(var t=[],n=e.size,r=Math.ceil(n/mi.chunkedMTU),s=0,o=0;o<n;){var a=Math.min(n,o+mi.chunkedMTU),l=e.slice(o,a),c={__peerData:this._dataCount,n:s,data:l,total:r};t.push(c),o=a,s++}return this._dataCount++,t},i.prototype.blobToArrayBuffer=function(e,t){var n=new FileReader;return n.onload=function(r){r.target&&t(r.target.result)},n.readAsArrayBuffer(e),n},i.prototype.binaryStringToArrayBuffer=function(e){for(var t=new Uint8Array(e.length),n=0;n<e.length;n++)t[n]=e.charCodeAt(n)&255;return t.buffer},i.prototype.randomToken=function(){return Math.random().toString(36).slice(2)},i.prototype.isSecure=function(){return location.protocol==="https:"},i}(),mi=new qZ,eU={};Ga(eU,"Peer",()=>EM,i=>EM=i);var Bg={},XZ=Object.prototype.hasOwnProperty,ds="~";function Dg(){}Object.create&&(Dg.prototype=Object.create(null),new Dg().__proto__||(ds=!1));function YZ(i,e,t){this.fn=i,this.context=e,this.once=t||!1}function tU(i,e,t,n,r){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new YZ(t,n||i,r),o=ds?ds+e:e;return i._events[o]?i._events[o].fn?i._events[o]=[i._events[o],s]:i._events[o].push(s):(i._events[o]=s,i._eventsCount++),i}function qb(i,e){--i._eventsCount===0?i._events=new Dg:delete i._events[e]}function Wr(){this._events=new Dg,this._eventsCount=0}Wr.prototype.eventNames=function(){var i=[],e,t;if(this._eventsCount===0)return i;for(t in e=this._events)XZ.call(e,t)&&i.push(ds?t.slice(1):t);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i},Wr.prototype.listeners=function(i){var e=ds?ds+i:i,t=this._events[e];if(!t)return[];if(t.fn)return[t.fn];for(var n=0,r=t.length,s=new Array(r);n<r;n++)s[n]=t[n].fn;return s},Wr.prototype.listenerCount=function(i){var e=ds?ds+i:i,t=this._events[e];return t?t.fn?1:t.length:0},Wr.prototype.emit=function(i,e,t,n,r,s){var o=ds?ds+i:i;if(!this._events[o])return!1;var a=this._events[o],l=arguments.length,c,u;if(a.fn){switch(a.once&&this.removeListener(i,a.fn,void 0,!0),l){case 1:return a.fn.call(a.context),!0;case 2:return a.fn.call(a.context,e),!0;case 3:return a.fn.call(a.context,e,t),!0;case 4:return a.fn.call(a.context,e,t,n),!0;case 5:return a.fn.call(a.context,e,t,n,r),!0;case 6:return a.fn.call(a.context,e,t,n,r,s),!0}for(u=1,c=new Array(l-1);u<l;u++)c[u-1]=arguments[u];a.fn.apply(a.context,c)}else{var d=a.length,p;for(u=0;u<d;u++)switch(a[u].once&&this.removeListener(i,a[u].fn,void 0,!0),l){case 1:a[u].fn.call(a[u].context);break;case 2:a[u].fn.call(a[u].context,e);break;case 3:a[u].fn.call(a[u].context,e,t);break;case 4:a[u].fn.call(a[u].context,e,t,n);break;default:if(!c)for(p=1,c=new Array(l-1);p<l;p++)c[p-1]=arguments[p];a[u].fn.apply(a[u].context,c)}}return!0},Wr.prototype.on=function(i,e,t){return tU(this,i,e,t,!1)},Wr.prototype.once=function(i,e,t){return tU(this,i,e,t,!0)},Wr.prototype.removeListener=function(i,e,t,n){var r=ds?ds+i:i;if(!this._events[r])return this;if(!e)return qb(this,r),this;var s=this._events[r];if(s.fn)s.fn===e&&(!n||s.once)&&(!t||s.context===t)&&qb(this,r);else{for(var o=0,a=[],l=s.length;o<l;o++)(s[o].fn!==e||n&&!s[o].once||t&&s[o].context!==t)&&a.push(s[o]);a.length?this._events[r]=a.length===1?a[0]:a:qb(this,r)}return this},Wr.prototype.removeAllListeners=function(i){var e;return i?(e=ds?ds+i:i,this._events[e]&&qb(this,e)):(this._events=new Dg,this._eventsCount=0),this},Wr.prototype.off=Wr.prototype.removeListener,Wr.prototype.addListener=Wr.prototype.on,Wr.prefixed=ds,Wr.EventEmitter=Wr,Bg=Wr;var at={};Ga(at,"LogLevel",()=>Ds,i=>Ds=i),Ga(at,"default",()=>iU,i=>iU=i);var ku=function(i,e){var t=typeof Symbol=="function"&&i[Symbol.iterator];if(!t)return i;var n=t.call(i),r,s=[],o;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)s.push(r.value)}catch(a){o={error:a}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(o)throw o.error}}return s},Lu=function(i,e,t){if(t||arguments.length===2)for(var n=0,r=e.length,s;n<r;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return i.concat(s||Array.prototype.slice.call(e))},JZ="PeerJS: ",Ds;(function(i){i[i.Disabled=0]="Disabled",i[i.Errors=1]="Errors",i[i.Warnings=2]="Warnings",i[i.All=3]="All"})(Ds||(Ds={}));var KZ=function(){function i(){this._logLevel=Ds.Disabled}return Object.defineProperty(i.prototype,"logLevel",{get:function(){return this._logLevel},set:function(e){this._logLevel=e},enumerable:!1,configurable:!0}),i.prototype.log=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._logLevel>=Ds.All&&this._print.apply(this,Lu([Ds.All],ku(e),!1))},i.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._logLevel>=Ds.Warnings&&this._print.apply(this,Lu([Ds.Warnings],ku(e),!1))},i.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._logLevel>=Ds.Errors&&this._print.apply(this,Lu([Ds.Errors],ku(e),!1))},i.prototype.setLogFunction=function(e){this._print=e},i.prototype._print=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];var r=Lu([JZ],ku(t),!1);for(var s in r)r[s]instanceof Error&&(r[s]="("+r[s].name+") "+r[s].message);e>=Ds.All?console.log.apply(console,Lu([],ku(r),!1)):e>=Ds.Warnings?console.warn.apply(console,Lu(["WARNING"],ku(r),!1)):e>=Ds.Errors&&console.error.apply(console,Lu(["ERROR"],ku(r),!1))},i}(),iU=new KZ,nU={};Ga(nU,"Socket",()=>rU,i=>rU=i);var ca;(function(i){i.Data="data",i.Media="media"})(ca||(ca={}));var _n;(function(i){i.BrowserIncompatible="browser-incompatible",i.Disconnected="disconnected",i.InvalidID="invalid-id",i.InvalidKey="invalid-key",i.Network="network",i.PeerUnavailable="peer-unavailable",i.SslUnavailable="ssl-unavailable",i.ServerError="server-error",i.SocketError="socket-error",i.SocketClosed="socket-closed",i.UnavailableID="unavailable-id",i.WebRTC="webrtc"})(_n||(_n={}));var Wl;(function(i){i.Binary="binary",i.BinaryUTF8="binary-utf8",i.JSON="json"})(Wl||(Wl={}));var ql;(function(i){i.Message="message",i.Disconnected="disconnected",i.Error="error",i.Close="close"})(ql||(ql={}));var Ar;(function(i){i.Heartbeat="HEARTBEAT",i.Candidate="CANDIDATE",i.Offer="OFFER",i.Answer="ANSWER",i.Open="OPEN",i.Error="ERROR",i.IdTaken="ID-TAKEN",i.InvalidKey="INVALID-KEY",i.Leave="LEAVE",i.Expire="EXPIRE"})(Ar||(Ar={}));var _M={};_M=JSON.parse('{"name":"peerjs","version":"1.4.7","keywords":["peerjs","webrtc","p2p","rtc"],"description":"PeerJS client","homepage":"https://peerjs.com","bugs":{"url":"https://github.com/peers/peerjs/issues"},"repository":{"type":"git","url":"https://github.com/peers/peerjs"},"license":"MIT","contributors":["Michelle Bu <michelle@michellebu.com>","afrokick <devbyru@gmail.com>","ericz <really.ez@gmail.com>","Jairo <kidandcat@gmail.com>","Jonas Gloning <34194370+jonasgloning@users.noreply.github.com>","Jairo Caro-Accino Viciana <jairo@galax.be>","Carlos Caballero <carlos.caballero.gonzalez@gmail.com>","hc <hheennrryy@gmail.com>","Muhammad Asif <capripio@gmail.com>","PrashoonB <prashoonbhattacharjee@gmail.com>","Harsh Bardhan Mishra <47351025+HarshCasper@users.noreply.github.com>","akotynski <aleksanderkotbury@gmail.com>","lmb <i@lmb.io>","Jairooo <jairocaro@msn.com>","Moritz St\xFCckler <moritz.stueckler@gmail.com>","Simon <crydotsnakegithub@gmail.com>","Denis Lukov <denismassters@gmail.com>","Philipp Hancke <fippo@andyet.net>","Hans Oksendahl <hansoksendahl@gmail.com>","Jess <jessachandler@gmail.com>","khankuan <khankuan@gmail.com>","DUODVK <kurmanov.work@gmail.com>","XiZhao <kwang1imsa@gmail.com>","Matthias Lohr <matthias@lohr.me>","=frank tree <=frnktrb@googlemail.com>","Andre Eckardt <aeckardt@outlook.com>","Chris Cowan <agentme49@gmail.com>","Alex Chuev <alex@chuev.com>","alxnull <alxnull@e.mail.de>","Yemel Jardi <angel.jardi@gmail.com>","Ben Parnell <benjaminparnell.94@gmail.com>","Benny Lichtner <bennlich@gmail.com>","fresheneesz <bitetrudpublic@gmail.com>","bob.barstead@exaptive.com <bob.barstead@exaptive.com>","chandika <chandika@gmail.com>","emersion <contact@emersion.fr>","Christopher Van <cvan@users.noreply.github.com>","eddieherm <edhermoso@gmail.com>","Eduardo Pinho <enet4mikeenet@gmail.com>","Evandro Zanatta <ezanatta@tray.net.br>","Gardner Bickford <gardner@users.noreply.github.com>","Gian Luca <gianluca.cecchi@cynny.com>","PatrickJS <github@gdi2290.com>","jonnyf <github@jonathanfoss.co.uk>","Hizkia Felix <hizkifw@gmail.com>","Hristo Oskov <hristo.oskov@gmail.com>","Isaac Madwed <i.madwed@gmail.com>","Ilya Konanykhin <ilya.konanykhin@gmail.com>","jasonbarry <jasbarry@me.com>","Jonathan Burke <jonathan.burke.1311@googlemail.com>","Josh Hamit <josh.hamit@gmail.com>","Jordan Austin <jrax86@gmail.com>","Joel Wetzell <jwetzell@yahoo.com>","xizhao <kevin.wang@cloudera.com>","Alberto Torres <kungfoobar@gmail.com>","Jonathan Mayol <mayoljonathan@gmail.com>","Jefferson Felix <me@jsfelix.dev>","Rolf Erik Lekang <me@rolflekang.com>","Kevin Mai-Husan Chia <mhchia@users.noreply.github.com>","Pepijn de Vos <pepijndevos@gmail.com>","JooYoung <qkdlql@naver.com>","Tobias Speicher <rootcommander@gmail.com>","Steve Blaurock <sblaurock@gmail.com>","Kyrylo Shegeda <shegeda@ualberta.ca>","Diwank Singh Tomer <singh@diwank.name>","So\u0308ren Balko <Soeren.Balko@gmail.com>","Arpit Solanki <solankiarpit1997@gmail.com>","Yuki Ito <yuki@gnnk.net>","Artur Zayats <zag2art@gmail.com>"],"funding":{"type":"opencollective","url":"https://opencollective.com/peer"},"collective":{"type":"opencollective","url":"https://opencollective.com/peer"},"files":["dist/*"],"sideEffects":["lib/global.ts","lib/supports.ts"],"main":"dist/bundler.cjs","module":"dist/bundler.mjs","browser-minified":"dist/peerjs.min.js","browser-unminified":"dist/peerjs.js","types":"dist/types.d.ts","engines":{"node":">= 10"},"targets":{"types":{"source":"lib/exports.ts"},"main":{"source":"lib/exports.ts","sourceMap":{"inlineSources":true}},"module":{"source":"lib/exports.ts","includeNodeModules":["eventemitter3"],"sourceMap":{"inlineSources":true}},"browser-minified":{"context":"browser","outputFormat":"global","optimize":true,"engines":{"browsers":"cover 99%, not dead"},"source":"lib/global.ts"},"browser-unminified":{"context":"browser","outputFormat":"global","optimize":false,"engines":{"browsers":"cover 99%, not dead"},"source":"lib/global.ts"}},"scripts":{"contributors":"git-authors-cli --print=false && prettier --write package.json && git add package.json package-lock.json && git commit -m \\"chore(contributors): update and sort contributors list\\"","check":"tsc --noEmit","watch":"parcel watch","build":"rm -rf dist && parcel build","prepublishOnly":"npm run build","test":"mocha -r ts-node/register -r jsdom-global/register test/**/*.ts","format":"prettier --write .","semantic-release":"semantic-release"},"devDependencies":{"@parcel/config-default":"^2.5.0","@parcel/packager-ts":"^2.5.0","@parcel/transformer-typescript-tsc":"^2.5.0","@parcel/transformer-typescript-types":"^2.5.0","@semantic-release/changelog":"^6.0.1","@semantic-release/git":"^10.0.1","@types/chai":"^4.3.0","@types/mocha":"^9.1.0","@types/node":"^17.0.18","chai":"^4.3.6","git-authors-cli":"^1.0.40","jsdom":"^19.0.0","jsdom-global":"^3.0.2","mocha":"^9.2.0","mock-socket":"8.0.5","parcel":"^2.5.0","parcel-transformer-tsc-sourcemaps":"^1.0.2","prettier":"^2.6.2","semantic-release":"^19.0.2","standard":"^16.0.4","ts-node":"^10.5.0","typescript":"^4.5.5"},"dependencies":{"@swc/helpers":"^0.3.13","eventemitter3":"^4.0.7","peerjs-js-binarypack":"1.0.1","webrtc-adapter":"^7.7.1"}}');var ZZ=function(){var i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(n[s]=r[s])},i(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");i(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),$Z=function(i,e){var t=typeof Symbol=="function"&&i[Symbol.iterator];if(!t)return i;var n=t.call(i),r,s=[],o;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)s.push(r.value)}catch(a){o={error:a}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(o)throw o.error}}return s},e$=function(i,e,t){if(t||arguments.length===2)for(var n=0,r=e.length,s;n<r;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return i.concat(s||Array.prototype.slice.call(e))},t$=function(i){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&i[e],n=0;if(t)return t.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&n>=i.length&&(i=void 0),{value:i&&i[n++],done:!i}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},rU=function(i){ZZ(e,i);function e(t,n,r,s,o,a){a===void 0&&(a=5e3);var l=i.call(this)||this;l.pingInterval=a,l._disconnected=!0,l._messagesQueue=[];var c=t?"wss://":"ws://";return l._baseUrl=c+n+":"+r+s+"peerjs?key="+o,l}return e.prototype.start=function(t,n){var r=this;this._id=t;var s="".concat(this._baseUrl,"&id=").concat(t,"&token=").concat(n);this._socket||!this._disconnected||(this._socket=new WebSocket(s+"&version="+_M.version),this._disconnected=!1,this._socket.onmessage=function(o){var a;try{a=JSON.parse(o.data),at.default.log("Server message received:",a)}catch{at.default.log("Invalid server message",o.data);return}r.emit(ql.Message,a)},this._socket.onclose=function(o){r._disconnected||(at.default.log("Socket closed.",o),r._cleanup(),r._disconnected=!0,r.emit(ql.Disconnected))},this._socket.onopen=function(){r._disconnected||(r._sendQueuedMessages(),at.default.log("Socket open"),r._scheduleHeartbeat())})},e.prototype._scheduleHeartbeat=function(){var t=this;this._wsPingTimer=setTimeout(function(){t._sendHeartbeat()},this.pingInterval)},e.prototype._sendHeartbeat=function(){if(!this._wsOpen()){at.default.log("Cannot send heartbeat, because socket closed");return}var t=JSON.stringify({type:Ar.Heartbeat});this._socket.send(t),this._scheduleHeartbeat()},e.prototype._wsOpen=function(){return!!this._socket&&this._socket.readyState===1},e.prototype._sendQueuedMessages=function(){var t,n,r=e$([],$Z(this._messagesQueue),!1);this._messagesQueue=[];try{for(var s=t$(r),o=s.next();!o.done;o=s.next()){var a=o.value;this.send(a)}}catch(l){t={error:l}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}},e.prototype.send=function(t){if(!this._disconnected){if(!this._id){this._messagesQueue.push(t);return}if(!t.type){this.emit(ql.Error,"Invalid message");return}if(this._wsOpen()){var n=JSON.stringify(t);this._socket.send(n)}}},e.prototype.close=function(){this._disconnected||(this._cleanup(),this._disconnected=!0)},e.prototype._cleanup=function(){this._socket&&(this._socket.onopen=this._socket.onmessage=this._socket.onclose=null,this._socket.close(),this._socket=void 0),clearTimeout(this._wsPingTimer)},e}(Bg.EventEmitter),xM={};Ga(xM,"MediaConnection",()=>aU,i=>aU=i);var wM={};Ga(wM,"Negotiator",()=>sU,i=>sU=i);var Xb=function(){return Xb=Object.assign||function(i){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(i[r]=e[r])}return i},Xb.apply(this,arguments)},Yb=function(i,e,t,n){function r(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(u){try{c(n.next(u))}catch(d){o(d)}}function l(u){try{c(n.throw(u))}catch(d){o(d)}}function c(u){u.done?s(u.value):r(u.value).then(a,l)}c((n=n.apply(i,e||[])).next())})},Jb=function(i,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,r,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(c){return function(u){return l([c,u])}}function l(c){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,r&&(s=c[0]&2?r.return:c[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,c[1])).done)return s;switch(r=0,s&&(c=[c[0]&2,s.value]),c[0]){case 0:case 1:s=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,r=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!s||c[1]>s[0]&&c[1]<s[3])){t.label=c[1];break}if(c[0]===6&&t.label<s[1]){t.label=s[1],s=c;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(c);break}s[2]&&t.ops.pop(),t.trys.pop();continue}c=e.call(i,t)}catch(u){c=[6,u],r=0}finally{n=s=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}},sU=function(){function i(e){this.connection=e}return i.prototype.startConnection=function(e){var t=this._startPeerConnection();if(this.connection.peerConnection=t,this.connection.type===ca.Media&&e._stream&&this._addTracksToConnection(e._stream,t),e.originator){if(this.connection.type===ca.Data){var n=this.connection,r={ordered:!!e.reliable},s=t.createDataChannel(n.label,r);n.initialize(s)}this._makeOffer()}else this.handleSDP("OFFER",e.sdp)},i.prototype._startPeerConnection=function(){at.default.log("Creating RTCPeerConnection.");var e=new RTCPeerConnection(this.connection.provider.options.config);return this._setupListeners(e),e},i.prototype._setupListeners=function(e){var t=this,n=this.connection.peer,r=this.connection.connectionId,s=this.connection.type,o=this.connection.provider;at.default.log("Listening for ICE candidates."),e.onicecandidate=function(a){!a.candidate||!a.candidate.candidate||(at.default.log("Received ICE candidates for ".concat(n,":"),a.candidate),o.socket.send({type:Ar.Candidate,payload:{candidate:a.candidate,type:s,connectionId:r},dst:n}))},e.oniceconnectionstatechange=function(){switch(e.iceConnectionState){case"failed":at.default.log("iceConnectionState is failed, closing connections to "+n),t.connection.emit("error",new Error("Negotiation of connection to "+n+" failed.")),t.connection.close();break;case"closed":at.default.log("iceConnectionState is closed, closing connections to "+n),t.connection.emit("error",new Error("Connection to "+n+" closed.")),t.connection.close();break;case"disconnected":at.default.log("iceConnectionState changed to disconnected on the connection with "+n);break;case"completed":e.onicecandidate=mi.noop;break}t.connection.emit("iceStateChanged",e.iceConnectionState)},at.default.log("Listening for data channel"),e.ondatachannel=function(a){at.default.log("Received data channel");var l=a.channel,c=o.getConnection(n,r);c.initialize(l)},at.default.log("Listening for remote stream"),e.ontrack=function(a){at.default.log("Received remote stream");var l=a.streams[0],c=o.getConnection(n,r);if(c.type===ca.Media){var u=c;t._addStreamToMediaConnection(l,u)}}},i.prototype.cleanup=function(){at.default.log("Cleaning up PeerConnection to "+this.connection.peer);var e=this.connection.peerConnection;if(e){this.connection.peerConnection=null,e.onicecandidate=e.oniceconnectionstatechange=e.ondatachannel=e.ontrack=function(){};var t=e.signalingState!=="closed",n=!1;if(this.connection.type===ca.Data){var r=this.connection,s=r.dataChannel;s&&(n=!!s.readyState&&s.readyState!=="closed")}(t||n)&&e.close()}},i.prototype._makeOffer=function(){return Yb(this,void 0,Promise,function(){var e,t,n,r,s,o,a;return Jb(this,function(l){switch(l.label){case 0:e=this.connection.peerConnection,t=this.connection.provider,l.label=1;case 1:return l.trys.push([1,7,,8]),[4,e.createOffer(this.connection.options.constraints)];case 2:n=l.sent(),at.default.log("Created offer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(n.sdp=this.connection.options.sdpTransform(n.sdp)||n.sdp),l.label=3;case 3:return l.trys.push([3,5,,6]),[4,e.setLocalDescription(n)];case 4:return l.sent(),at.default.log("Set localDescription:",n,"for:".concat(this.connection.peer)),r={sdp:n,type:this.connection.type,connectionId:this.connection.connectionId,metadata:this.connection.metadata,browser:mi.browser},this.connection.type===ca.Data&&(s=this.connection,r=Xb(Xb({},r),{label:s.label,reliable:s.reliable,serialization:s.serialization})),t.socket.send({type:Ar.Offer,payload:r,dst:this.connection.peer}),[3,6];case 5:return o=l.sent(),o!="OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer"&&(t.emitError(_n.WebRTC,o),at.default.log("Failed to setLocalDescription, ",o)),[3,6];case 6:return[3,8];case 7:return a=l.sent(),t.emitError(_n.WebRTC,a),at.default.log("Failed to createOffer, ",a),[3,8];case 8:return[2]}})})},i.prototype._makeAnswer=function(){return Yb(this,void 0,Promise,function(){var e,t,n,r,s;return Jb(this,function(o){switch(o.label){case 0:e=this.connection.peerConnection,t=this.connection.provider,o.label=1;case 1:return o.trys.push([1,7,,8]),[4,e.createAnswer()];case 2:n=o.sent(),at.default.log("Created answer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(n.sdp=this.connection.options.sdpTransform(n.sdp)||n.sdp),o.label=3;case 3:return o.trys.push([3,5,,6]),[4,e.setLocalDescription(n)];case 4:return o.sent(),at.default.log("Set localDescription:",n,"for:".concat(this.connection.peer)),t.socket.send({type:Ar.Answer,payload:{sdp:n,type:this.connection.type,connectionId:this.connection.connectionId,browser:mi.browser},dst:this.connection.peer}),[3,6];case 5:return r=o.sent(),t.emitError(_n.WebRTC,r),at.default.log("Failed to setLocalDescription, ",r),[3,6];case 6:return[3,8];case 7:return s=o.sent(),t.emitError(_n.WebRTC,s),at.default.log("Failed to create answer, ",s),[3,8];case 8:return[2]}})})},i.prototype.handleSDP=function(e,t){return Yb(this,void 0,Promise,function(){var n,r,s,o;return Jb(this,function(a){switch(a.label){case 0:t=new RTCSessionDescription(t),n=this.connection.peerConnection,r=this.connection.provider,at.default.log("Setting remote description",t),s=this,a.label=1;case 1:return a.trys.push([1,5,,6]),[4,n.setRemoteDescription(t)];case 2:return a.sent(),at.default.log("Set remoteDescription:".concat(e," for:").concat(this.connection.peer)),e!=="OFFER"?[3,4]:[4,s._makeAnswer()];case 3:a.sent(),a.label=4;case 4:return[3,6];case 5:return o=a.sent(),r.emitError(_n.WebRTC,o),at.default.log("Failed to setRemoteDescription, ",o),[3,6];case 6:return[2]}})})},i.prototype.handleCandidate=function(e){return Yb(this,void 0,Promise,function(){var t,n,r,s,o,a;return Jb(this,function(l){switch(l.label){case 0:at.default.log("handleCandidate:",e),t=e.candidate,n=e.sdpMLineIndex,r=e.sdpMid,s=this.connection.peerConnection,o=this.connection.provider,l.label=1;case 1:return l.trys.push([1,3,,4]),[4,s.addIceCandidate(new RTCIceCandidate({sdpMid:r,sdpMLineIndex:n,candidate:t}))];case 2:return l.sent(),at.default.log("Added ICE candidate for:".concat(this.connection.peer)),[3,4];case 3:return a=l.sent(),o.emitError(_n.WebRTC,a),at.default.log("Failed to handleCandidate, ",a),[3,4];case 4:return[2]}})})},i.prototype._addTracksToConnection=function(e,t){if(at.default.log("add tracks from stream ".concat(e.id," to peer connection")),!t.addTrack)return at.default.error("Your browser does't support RTCPeerConnection#addTrack. Ignored.");e.getTracks().forEach(function(n){t.addTrack(n,e)})},i.prototype._addStreamToMediaConnection=function(e,t){at.default.log("add stream ".concat(e.id," to media connection ").concat(t.connectionId)),t.addStream(e)},i}(),SM={};Ga(SM,"BaseConnection",()=>oU,i=>oU=i);var i$=function(){var i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(n[s]=r[s])},i(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");i(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),oU=function(i){i$(e,i);function e(t,n,r){var s=i.call(this)||this;return s.peer=t,s.provider=n,s.options=r,s._open=!1,s.metadata=r.metadata,s}return Object.defineProperty(e.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),e}(Bg.EventEmitter),n$=function(){var i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(n[s]=r[s])},i(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");i(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Kb=function(){return Kb=Object.assign||function(i){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(i[r]=e[r])}return i},Kb.apply(this,arguments)},r$=function(i){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&i[e],n=0;if(t)return t.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&n>=i.length&&(i=void 0),{value:i&&i[n++],done:!i}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},aU=function(i){n$(e,i);function e(t,n,r){var s=i.call(this,t,n,r)||this;return s._localStream=s.options._stream,s.connectionId=s.options.connectionId||e.ID_PREFIX+mi.randomToken(),s._negotiator=new wM.Negotiator(s),s._localStream&&s._negotiator.startConnection({_stream:s._localStream,originator:!0}),s}return Object.defineProperty(e.prototype,"type",{get:function(){return ca.Media},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"localStream",{get:function(){return this._localStream},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteStream",{get:function(){return this._remoteStream},enumerable:!1,configurable:!0}),e.prototype.addStream=function(t){at.default.log("Receiving stream",t),this._remoteStream=t,i.prototype.emit.call(this,"stream",t)},e.prototype.handleMessage=function(t){var n=t.type,r=t.payload;switch(t.type){case Ar.Answer:this._negotiator.handleSDP(n,r.sdp),this._open=!0;break;case Ar.Candidate:this._negotiator.handleCandidate(r.candidate);break;default:at.default.warn("Unrecognized message type:".concat(n," from peer:").concat(this.peer));break}},e.prototype.answer=function(t,n){var r,s;if(n===void 0&&(n={}),this._localStream){at.default.warn("Local stream already exists on this MediaConnection. Are you answering a call twice?");return}this._localStream=t,n&&n.sdpTransform&&(this.options.sdpTransform=n.sdpTransform),this._negotiator.startConnection(Kb(Kb({},this.options._payload),{_stream:t}));var o=this.provider._getMessages(this.connectionId);try{for(var a=r$(o),l=a.next();!l.done;l=a.next()){var c=l.value;this.handleMessage(c)}}catch(u){r={error:u}}finally{try{l&&!l.done&&(s=a.return)&&s.call(a)}finally{if(r)throw r.error}}this._open=!0},e.prototype.close=function(){this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this._localStream=null,this._remoteStream=null,this.provider&&(this.provider._removeConnection(this),this.provider=null),this.options&&this.options._stream&&(this.options._stream=null),this.open&&(this._open=!1,i.prototype.emit.call(this,"close"))},e.ID_PREFIX="mc_",e}(SM.BaseConnection),CM={};Ga(CM,"DataConnection",()=>hU,i=>hU=i);var lU={};Ga(lU,"EncodingQueue",()=>cU,i=>cU=i);var s$=function(){var i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(n[s]=r[s])},i(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");i(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),cU=function(i){s$(e,i);function e(){var t=i.call(this)||this;return t.fileReader=new FileReader,t._queue=[],t._processing=!1,t.fileReader.onload=function(n){t._processing=!1,n.target&&t.emit("done",n.target.result),t.doNextTask()},t.fileReader.onerror=function(n){at.default.error("EncodingQueue error:",n),t._processing=!1,t.destroy(),t.emit("error",n)},t}return Object.defineProperty(e.prototype,"queue",{get:function(){return this._queue},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"size",{get:function(){return this.queue.length},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"processing",{get:function(){return this._processing},enumerable:!1,configurable:!0}),e.prototype.enque=function(t){this.queue.push(t),!this.processing&&this.doNextTask()},e.prototype.destroy=function(){this.fileReader.abort(),this._queue=[]},e.prototype.doNextTask=function(){this.size!==0&&(this.processing||(this._processing=!0,this.fileReader.readAsArrayBuffer(this.queue.shift())))},e}(Bg.EventEmitter),o$=function(){var i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(n[s]=r[s])},i(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");i(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),a$=function(i){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&i[e],n=0;if(t)return t.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&n>=i.length&&(i=void 0),{value:i&&i[n++],done:!i}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},hU=function(i){o$(e,i);function e(t,n,r){var s=i.call(this,t,n,r)||this;return s.stringify=JSON.stringify,s.parse=JSON.parse,s._buffer=[],s._bufferSize=0,s._buffering=!1,s._chunkedData={},s._encodingQueue=new lU.EncodingQueue,s.connectionId=s.options.connectionId||e.ID_PREFIX+mi.randomToken(),s.label=s.options.label||s.connectionId,s.serialization=s.options.serialization||Wl.Binary,s.reliable=!!s.options.reliable,s._encodingQueue.on("done",function(o){s._bufferedSend(o)}),s._encodingQueue.on("error",function(){at.default.error("DC#".concat(s.connectionId,": Error occured in encoding from blob to arraybuffer, close DC")),s.close()}),s._negotiator=new wM.Negotiator(s),s._negotiator.startConnection(s.options._payload||{originator:!0}),s}return Object.defineProperty(e.prototype,"type",{get:function(){return ca.Data},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"dataChannel",{get:function(){return this._dc},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"bufferSize",{get:function(){return this._bufferSize},enumerable:!1,configurable:!0}),e.prototype.initialize=function(t){this._dc=t,this._configureDataChannel()},e.prototype._configureDataChannel=function(){var t=this;(!mi.supports.binaryBlob||mi.supports.reliable)&&(this.dataChannel.binaryType="arraybuffer"),this.dataChannel.onopen=function(){at.default.log("DC#".concat(t.connectionId," dc connection success")),t._open=!0,t.emit("open")},this.dataChannel.onmessage=function(n){at.default.log("DC#".concat(t.connectionId," dc onmessage:"),n.data),t._handleDataMessage(n)},this.dataChannel.onclose=function(){at.default.log("DC#".concat(t.connectionId," dc closed for:"),t.peer),t.close()}},e.prototype._handleDataMessage=function(t){var n=this,r=t.data,s=r.constructor,o=this.serialization===Wl.Binary||this.serialization===Wl.BinaryUTF8,a=r;if(o){if(s===Blob){mi.blobToArrayBuffer(r,function(c){var u=mi.unpack(c);n.emit("data",u)});return}else if(s===ArrayBuffer)a=mi.unpack(r);else if(s===String){var l=mi.binaryStringToArrayBuffer(r);a=mi.unpack(l)}}else this.serialization===Wl.JSON&&(a=this.parse(r));if(a.__peerData){this._handleChunk(a);return}i.prototype.emit.call(this,"data",a)},e.prototype._handleChunk=function(t){var n=t.__peerData,r=this._chunkedData[n]||{data:[],count:0,total:t.total};if(r.data[t.n]=t.data,r.count++,this._chunkedData[n]=r,r.total===r.count){delete this._chunkedData[n];var s=new Blob(r.data);this._handleDataMessage({data:s})}},e.prototype.close=function(){this._buffer=[],this._bufferSize=0,this._chunkedData={},this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this.provider&&(this.provider._removeConnection(this),this.provider=null),this.dataChannel&&(this.dataChannel.onopen=null,this.dataChannel.onmessage=null,this.dataChannel.onclose=null,this._dc=null),this._encodingQueue&&(this._encodingQueue.destroy(),this._encodingQueue.removeAllListeners(),this._encodingQueue=null),this.open&&(this._open=!1,i.prototype.emit.call(this,"close"))},e.prototype.send=function(t,n){if(!this.open){i.prototype.emit.call(this,"error",new Error("Connection is not open. You should listen for the `open` event before sending messages."));return}if(this.serialization===Wl.JSON)this._bufferedSend(this.stringify(t));else if(this.serialization===Wl.Binary||this.serialization===Wl.BinaryUTF8){var r=mi.pack(t);if(!n&&r.size>mi.chunkedMTU){this._sendChunks(r);return}mi.supports.binaryBlob?this._bufferedSend(r):this._encodingQueue.enque(r)}else this._bufferedSend(t)},e.prototype._bufferedSend=function(t){(this._buffering||!this._trySend(t))&&(this._buffer.push(t),this._bufferSize=this._buffer.length)},e.prototype._trySend=function(t){var n=this;if(!this.open)return!1;if(this.dataChannel.bufferedAmount>e.MAX_BUFFERED_AMOUNT)return this._buffering=!0,setTimeout(function(){n._buffering=!1,n._tryBuffer()},50),!1;try{this.dataChannel.send(t)}catch(r){return at.default.error("DC#:".concat(this.connectionId," Error when sending:"),r),this._buffering=!0,this.close(),!1}return!0},e.prototype._tryBuffer=function(){if(this.open&&this._buffer.length!==0){var t=this._buffer[0];this._trySend(t)&&(this._buffer.shift(),this._bufferSize=this._buffer.length,this._tryBuffer())}},e.prototype._sendChunks=function(t){var n,r,s=mi.chunk(t);at.default.log("DC#".concat(this.connectionId," Try to send ").concat(s.length," chunks..."));try{for(var o=a$(s),a=o.next();!a.done;a=o.next()){var l=a.value;this.send(l,!0)}}catch(c){n={error:c}}finally{try{a&&!a.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}},e.prototype.handleMessage=function(t){var n=t.payload;switch(t.type){case Ar.Answer:this._negotiator.handleSDP(t.type,n.sdp);break;case Ar.Candidate:this._negotiator.handleCandidate(n.candidate);break;default:at.default.warn("Unrecognized message type:",t.type,"from peer:",this.peer);break}},e.ID_PREFIX="dc_",e.MAX_BUFFERED_AMOUNT=8388608,e}(SM.BaseConnection),uU={};Ga(uU,"API",()=>fU,i=>fU=i);var dU=function(i,e,t,n){function r(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(u){try{c(n.next(u))}catch(d){o(d)}}function l(u){try{c(n.throw(u))}catch(d){o(d)}}function c(u){u.done?s(u.value):r(u.value).then(a,l)}c((n=n.apply(i,e||[])).next())})},pU=function(i,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,r,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(c){return function(u){return l([c,u])}}function l(c){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,r&&(s=c[0]&2?r.return:c[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,c[1])).done)return s;switch(r=0,s&&(c=[c[0]&2,s.value]),c[0]){case 0:case 1:s=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,r=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!s||c[1]>s[0]&&c[1]<s[3])){t.label=c[1];break}if(c[0]===6&&t.label<s[1]){t.label=s[1],s=c;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(c);break}s[2]&&t.ops.pop(),t.trys.pop();continue}c=e.call(i,t)}catch(u){c=[6,u],r=0}finally{n=s=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}},fU=function(){function i(e){this._options=e}return i.prototype._buildRequest=function(e){var t=this._options.secure?"https":"http",n=this._options,r=n.host,s=n.port,o=n.path,a=n.key,l=new URL("".concat(t,"://").concat(r,":").concat(s).concat(o).concat(a,"/").concat(e));return l.searchParams.set("ts","".concat(Date.now()).concat(Math.random())),l.searchParams.set("version",_M.version),fetch(l.href,{referrerPolicy:this._options.referrerPolicy})},i.prototype.retrieveId=function(){return dU(this,void 0,Promise,function(){var e,t,n;return pU(this,function(r){switch(r.label){case 0:return r.trys.push([0,2,,3]),[4,this._buildRequest("id")];case 1:if(e=r.sent(),e.status!==200)throw new Error("Error. Status:".concat(e.status));return[2,e.text()];case 2:throw t=r.sent(),at.default.error("Error retrieving ID",t),n="",this._options.path==="/"&&this._options.host!==mi.CLOUD_HOST&&(n=" If you passed in a `path` to your self-hosted PeerServer, you'll also need to pass in that same path when creating a new Peer."),new Error("Could not get an ID from the server."+n);case 3:return[2]}})})},i.prototype.listAllPeers=function(){return dU(this,void 0,Promise,function(){var e,t,n;return pU(this,function(r){switch(r.label){case 0:return r.trys.push([0,2,,3]),[4,this._buildRequest("peers")];case 1:if(e=r.sent(),e.status!==200)throw e.status===401?(t="",this._options.host===mi.CLOUD_HOST?t="It looks like you're using the cloud server. You can email team@peerjs.com to enable peer listing for your API key.":t="You need to enable `allow_discovery` on your self-hosted PeerServer to use this feature.",new Error("It doesn't look like you have permission to list peers IDs. "+t)):new Error("Error. Status:".concat(e.status));return[2,e.json()];case 2:throw n=r.sent(),at.default.error("Error retrieving list peers",n),new Error("Could not get list peers from the server."+n);case 3:return[2]}})})},i}(),l$=function(){var i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(n[s]=r[s])},i(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");i(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Og=function(){return Og=Object.assign||function(i){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(i[r]=e[r])}return i},Og.apply(this,arguments)},kg=function(i){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&i[e],n=0;if(t)return t.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&n>=i.length&&(i=void 0),{value:i&&i[n++],done:!i}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},c$=function(i,e){var t=typeof Symbol=="function"&&i[Symbol.iterator];if(!t)return i;var n=t.call(i),r,s=[],o;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)s.push(r.value)}catch(a){o={error:a}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(o)throw o.error}}return s},EM=function(i){l$(e,i);function e(t,n){var r=i.call(this)||this;r._id=null,r._lastServerId=null,r._destroyed=!1,r._disconnected=!1,r._open=!1,r._connections=new Map,r._lostMessages=new Map;var s;return t&&t.constructor==Object?n=t:t&&(s=t.toString()),n=Og({debug:0,host:mi.CLOUD_HOST,port:mi.CLOUD_PORT,path:"/",key:e.DEFAULT_KEY,token:mi.randomToken(),config:mi.defaultConfig,referrerPolicy:"strict-origin-when-cross-origin"},n),r._options=n,r._options.host==="/"&&(r._options.host=window.location.hostname),r._options.path&&(r._options.path[0]!=="/"&&(r._options.path="/"+r._options.path),r._options.path[r._options.path.length-1]!=="/"&&(r._options.path+="/")),r._options.secure===void 0&&r._options.host!==mi.CLOUD_HOST?r._options.secure=mi.isSecure():r._options.host==mi.CLOUD_HOST&&(r._options.secure=!0),r._options.logFunction&&at.default.setLogFunction(r._options.logFunction),at.default.logLevel=r._options.debug||0,r._api=new uU.API(n),r._socket=r._createServerConnection(),!mi.supports.audioVideo&&!mi.supports.data?(r._delayedAbort(_n.BrowserIncompatible,"The current browser does not support WebRTC"),r):s&&!mi.validateId(s)?(r._delayedAbort(_n.InvalidID,'ID "'.concat(s,'" is invalid')),r):(s?r._initialize(s):r._api.retrieveId().then(function(o){return r._initialize(o)}).catch(function(o){return r._abort(_n.ServerError,o)}),r)}return Object.defineProperty(e.prototype,"id",{get:function(){return this._id},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"options",{get:function(){return this._options},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"socket",{get:function(){return this._socket},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"connections",{get:function(){var t,n,r=Object.create(null);try{for(var s=kg(this._connections),o=s.next();!o.done;o=s.next()){var a=c$(o.value,2),l=a[0],c=a[1];r[l]=c}}catch(u){t={error:u}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}return r},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"destroyed",{get:function(){return this._destroyed},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"disconnected",{get:function(){return this._disconnected},enumerable:!1,configurable:!0}),e.prototype._createServerConnection=function(){var t=this,n=new nU.Socket(this._options.secure,this._options.host,this._options.port,this._options.path,this._options.key,this._options.pingInterval);return n.on(ql.Message,function(r){t._handleMessage(r)}),n.on(ql.Error,function(r){t._abort(_n.SocketError,r)}),n.on(ql.Disconnected,function(){t.disconnected||(t.emitError(_n.Network,"Lost connection to server."),t.disconnect())}),n.on(ql.Close,function(){t.disconnected||t._abort(_n.SocketClosed,"Underlying socket is already closed.")}),n},e.prototype._initialize=function(t){this._id=t,this.socket.start(t,this._options.token)},e.prototype._handleMessage=function(t){var n,r,s=t.type,o=t.payload,a=t.src;switch(s){case Ar.Open:this._lastServerId=this.id,this._open=!0,this.emit("open",this.id);break;case Ar.Error:this._abort(_n.ServerError,o.msg);break;case Ar.IdTaken:this._abort(_n.UnavailableID,'ID "'.concat(this.id,'" is taken'));break;case Ar.InvalidKey:this._abort(_n.InvalidKey,'API KEY "'.concat(this._options.key,'" is invalid'));break;case Ar.Leave:at.default.log("Received leave message from ".concat(a)),this._cleanupPeer(a),this._connections.delete(a);break;case Ar.Expire:this.emitError(_n.PeerUnavailable,"Could not connect to peer ".concat(a));break;case Ar.Offer:var m=o.connectionId,A=this.getConnection(a,m);if(A&&(A.close(),at.default.warn("Offer received for existing Connection ID:".concat(m))),o.type===ca.Media){var l=new xM.MediaConnection(a,this,{connectionId:m,_payload:o,metadata:o.metadata});A=l,this._addConnection(a,A),this.emit("call",l)}else if(o.type===ca.Data){var c=new CM.DataConnection(a,this,{connectionId:m,_payload:o,metadata:o.metadata,label:o.label,serialization:o.serialization,reliable:o.reliable});A=c,this._addConnection(a,A),this.emit("connection",c)}else{at.default.warn("Received malformed connection type:".concat(o.type));return}var u=this._getMessages(m);try{for(var d=kg(u),p=d.next();!p.done;p=d.next()){var f=p.value;A.handleMessage(f)}}catch(v){n={error:v}}finally{try{p&&!p.done&&(r=d.return)&&r.call(d)}finally{if(n)throw n.error}}break;default:if(!o){at.default.warn("You received a malformed message from ".concat(a," of type ").concat(s));return}var m=o.connectionId,A=this.getConnection(a,m);A&&A.peerConnection?A.handleMessage(t):m?this._storeMessage(m,t):at.default.warn("You received an unrecognized message:",t);break}},e.prototype._storeMessage=function(t,n){this._lostMessages.has(t)||this._lostMessages.set(t,[]),this._lostMessages.get(t).push(n)},e.prototype._getMessages=function(t){var n=this._lostMessages.get(t);return n?(this._lostMessages.delete(t),n):[]},e.prototype.connect=function(t,n){if(n===void 0&&(n={}),this.disconnected){at.default.warn("You cannot connect to a new Peer because you called .disconnect() on this Peer and ended your connection with the server. You can create a new Peer to reconnect, or call reconnect on this peer if you believe its ID to still be available."),this.emitError(_n.Disconnected,"Cannot connect to new Peer after disconnecting from server.");return}var r=new CM.DataConnection(t,this,n);return this._addConnection(t,r),r},e.prototype.call=function(t,n,r){if(r===void 0&&(r={}),this.disconnected){at.default.warn("You cannot connect to a new Peer because you called .disconnect() on this Peer and ended your connection with the server. You can create a new Peer to reconnect."),this.emitError(_n.Disconnected,"Cannot connect to new Peer after disconnecting from server.");return}if(!n){at.default.error("To call a peer, you must provide a stream from your browser's `getUserMedia`.");return}var s=new xM.MediaConnection(t,this,Og(Og({},r),{_stream:n}));return this._addConnection(t,s),s},e.prototype._addConnection=function(t,n){at.default.log("add connection ".concat(n.type,":").concat(n.connectionId," to peerId:").concat(t)),this._connections.has(t)||this._connections.set(t,[]),this._connections.get(t).push(n)},e.prototype._removeConnection=function(t){var n=this._connections.get(t.peer);if(n){var r=n.indexOf(t);r!==-1&&n.splice(r,1)}this._lostMessages.delete(t.connectionId)},e.prototype.getConnection=function(t,n){var r,s,o=this._connections.get(t);if(!o)return null;try{for(var a=kg(o),l=a.next();!l.done;l=a.next()){var c=l.value;if(c.connectionId===n)return c}}catch(u){r={error:u}}finally{try{l&&!l.done&&(s=a.return)&&s.call(a)}finally{if(r)throw r.error}}return null},e.prototype._delayedAbort=function(t,n){var r=this;setTimeout(function(){r._abort(t,n)},0)},e.prototype._abort=function(t,n){at.default.error("Aborting!"),this.emitError(t,n),this._lastServerId?this.disconnect():this.destroy()},e.prototype.emitError=function(t,n){at.default.error("Error:",n);var r;typeof n=="string"?r=new Error(n):r=n,r.type=t,this.emit("error",r)},e.prototype.destroy=function(){this.destroyed||(at.default.log("Destroy peer with ID:".concat(this.id)),this.disconnect(),this._cleanup(),this._destroyed=!0,this.emit("close"))},e.prototype._cleanup=function(){var t,n;try{for(var r=kg(this._connections.keys()),s=r.next();!s.done;s=r.next()){var o=s.value;this._cleanupPeer(o),this._connections.delete(o)}}catch(a){t={error:a}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}finally{if(t)throw t.error}}this.socket.removeAllListeners()},e.prototype._cleanupPeer=function(t){var n,r,s=this._connections.get(t);if(s)try{for(var o=kg(s),a=o.next();!a.done;a=o.next()){var l=a.value;l.close()}}catch(c){n={error:c}}finally{try{a&&!a.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}},e.prototype.disconnect=function(){if(!this.disconnected){var t=this.id;at.default.log("Disconnect peer with ID:".concat(t)),this._disconnected=!0,this._open=!1,this.socket.close(),this._lastServerId=t,this._id=null,this.emit("disconnected",t)}},e.prototype.reconnect=function(){if(this.disconnected&&!this.destroyed)at.default.log("Attempting reconnection to server with ID ".concat(this._lastServerId)),this._disconnected=!1,this._initialize(this._lastServerId);else{if(this.destroyed)throw new Error("This peer cannot reconnect to the server. It has already been destroyed.");if(!this.disconnected&&!this.open)at.default.error("In a hurry? We're still trying to make the initial connection!");else throw new Error("Peer ".concat(this.id," cannot reconnect because it is not disconnected from the server!"))}},e.prototype.listAllPeers=function(t){var n=this;t===void 0&&(t=function(r){}),this._api.listAllPeers().then(function(r){return t(r)}).catch(function(r){return n._abort(_n.ServerError,r)})},e.DEFAULT_KEY="peerjs",e}(Bg.EventEmitter),MM=eU.Peer;const h$=Object.freeze(Object.defineProperty({__proto__:null,get Peer(){return EM},default:MM,util:mi},Symbol.toStringTag,{value:"Module"}));let TM;function u$(){return TM}function d$(i){TM=i}function mU(i,e){return e||(e={}),e={...TM,...e},i?new MM(i,e):new MM(e)}async function gU(){const i=await Promise.resolve().then(()=>h$);return console.log(i),i.default===void 0?i:i.default}class vU{constructor(){h(this,"_host"),h(this,"_client"),h(this,"_clientData"),this.onEnable()}get isHost(){return this._host!==void 0}onEnable(){const e="HOST-5980e65c-8438-453e-8b35-f13c736dcd81";this.trySetupHost(e)}async trySetupHost(e){const t=await gU(),n=new t(e);n.on("error",r=>{console.error(r),this._host=void 0,this.trySetupClient(e)}),n.on("open",r=>{this._host=new f$(n)})}async trySetupClient(e){const t=await gU();this._client=new t,this._client.on("error",n=>{console.error("Client error",n)}),this._client.on("open",n=>{console.log("client connected",n),this._clientData=this._client.connect(e,{metadata:{id:n}}),this._clientData.on("open",()=>{console.log("Connected to host")}),this._clientData.on("data",r=>{console.log("<<",r)})})}}class p${constructor(e){h(this,"_peer"),this._peer=e}}class f$ extends p${constructor(e){var t;super(e),h(this,"_connections",[]),console.log("I AM THE HOST"),(t=this._peer)==null||t.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("BYE")}),setInterval(()=>{this.broadcast("HELLO")},2e3)}get isHost(){return!0}onConnection(e){console.log("host connection",e),e.on("open",()=>{this._connections.push(e),this.broadcastConnection(e)})}broadcastConnection(e){const t=this._connections.map(n=>{var r;return(r=n.metadata)==null?void 0:r.id}).filter(n=>n!==void 0);this.broadcast({type:"connection-list",connections:t})}broadcast(e){if(e!=null){console.log(">>",e);for(const t in this._peer.connections){const n=this._peer.connections[t];if(n)if(Array.isArray(n))for(const r of n)r&&r.send(e);else console.warn(n)}}}}const AU="https://urls.needle.tools/default-networking-backend/index";let Kc="wss://needle-tiny-starter.glitch.me/socket";const ps=!!ee("debugnet"),Lg=!!(ps||ee("debugowner")),yU=ee("debugnetbin");var bU=(i=>(i.ConnectionInfo="connection-start-info",i))(bU||{}),Jt=(i=>(i.Join="join-room",i.Leave="leave-room",i.JoinedRoom="joined-room",i.LeftRoom="left-room",i.UserJoinedRoom="user-joined-room",i.UserLeftRoom="user-left-room",i.RoomStateSent="room-state-sent",i))(Jt||{});class m${constructor(){h(this,"room"),h(this,"viewId"),h(this,"allowEditing"),h(this,"inRoom")}}class g${constructor(){h(this,"room")}}class v${constructor(){h(this,"userId")}}var _U=(i=>(i.RequestHasOwner="request-has-owner",i.ResponseHasOwner="response-has-owner",i.RequestIsOwner="request-is-owner",i.ResponseIsOwner="response-is-owner",i.RequestOwnership="request-ownership",i.GainedOwnership="gained-ownership",i.RemoveOwnership="remove-ownership",i.LostOwnership="lost-ownership",i.GainedOwnershipBroadcast="gained-ownership-broadcast",i.LostOwnershipBroadcast="lost-ownership-broadcast",i))(_U||{});class IM{constructor(e,t){h(this,"guid"),h(this,"connection"),h(this,"_hasOwnership",!1),h(this,"_isOwned"),h(this,"_gainSubscription"),h(this,"_lostSubscription"),h(this,"_hasOwnerResponse"),h(this,"_isWaitingForOwnershipResponseCallback",null),this.connection=e,this.guid=t,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),e.beginListen("lost-ownership",this._lostSubscription),e.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),e.beginListen("response-has-owner",this._hasOwnerResponse)}get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}updateIsOwned(){this.connection.send("request-has-owner",{guid:this.guid})}onHasOwnerResponse(e){e.guid===this.guid&&(this._isOwned=e.value)}requestOwnershipIfNotOwned(){return this._isWaitingForOwnershipResponseCallback!==null?this:(this._isWaitingForOwnershipResponseCallback=this.waitForHasOwnershipRequestResponse.bind(this),this.connection.beginListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this.connection.send("request-has-owner",{guid:this.guid}),this)}waitForHasOwnershipRequestResponse(e){e.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=e.value,e.value||(Lg&&console.log("request ownership",this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((e,t)=>{this.requestOwnership();let n=0;const r=()=>{if(n++>10)return t("Timeout");setTimeout(()=>{this.hasOwnership?e(this):r()},100)};r()})}requestOwnership(){return Lg&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),this}freeOwnership(){return this.connection.send("remove-ownership",{guid:this.guid}),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this}destroy(){this.connection.stopListen("gained-ownership",this._gainSubscription),this.connection.stopListen("lost-ownership",this._lostSubscription),this.connection.stopListen("response-has-owner",this._hasOwnerResponse),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null)}onGainedOwnership(e){e.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===e.owner?(Lg&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(Lg&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}}class xU{constructor(e){h(this,"context"),h(this,"_peer",null),h(this,"_usersInRoomCopy",[]),h(this,"_defaultMessagesBuffer",[]),h(this,"_defaultMessagesBufferArray",[]),h(this,"netWebSocketUrlProvider"),h(this,"_listeners",{}),h(this,"_listenersBinary",{}),h(this,"connected",!1),h(this,"channelId"),h(this,"_connectionId",null),h(this,"_ws"),h(this,"_waitingForSocket",{}),h(this,"_isInRoom",!1),h(this,"_currentRoomName",null),h(this,"_currentRoomViewId",null),h(this,"_currentRoomAllowEditing",!0),h(this,"_currentInRoom",[]),h(this,"_state",{}),h(this,"_currentDelay",-1),h(this,"_connectingToWebsocketPromise",null),this.context=e}get peer(){return this._peer||(this._peer=new vU),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return ps}get isConnected(){return this.connected}get currentRoomName(){return this._currentRoomName}get allowEditing(){return this._currentRoomAllowEditing}get currentRoomViewId(){return this._currentRoomViewId}get isInRoom(){return this._isInRoom}get currentLatency(){return this._currentDelay}get currentServerUrl(){var e;return((e=this._ws)==null?void 0:e.url)??null}sendPing(){this.send("ping",{time:this.context.time.time})}userIsInRoom(e){return this._currentInRoom.indexOf(e)!==-1}usersInRoom(e=null){e||(e=this._usersInRoomCopy),e.length=0;for(const t of this._currentInRoom)e.push(t);return e}joinRoom(e,t=!1){return e?e.length>1024?(console.error('Room name too long, can not join: "'+e+'". Max length is 1024 characters.'),!1):(this.connect(),ps&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},la.OnConnection),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}leaveRoom(e=null){return e||(e=this.currentRoomName),e?(this.send("leave-room",{room:e}),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}send(e,t=null,n=la.Queued){if(t===null&&(t={}),n===la.Queued){this._defaultMessagesBuffer.push({key:e,value:t});return}return this.sendWithWebsocket(e,t,n)}sendDeleteRemoteState(e){this.send("delete-state",{guid:e,dontSave:!0}),delete this._state[e]}sendDeleteRemoteStateAll(){this.send("delete-all-state"),this._state={}}sendBinary(e){var t;yU&&console.log("<< send binary",this.context.time.frame,e.length/1024+" KB"),(t=this._ws)==null||t.send(e)}sendBufferedMessagesNow(){var e;if(!this._ws)return;this._defaultMessagesBufferArray.length=0;const t=Object.keys(this._defaultMessagesBuffer).length;for(const r in this._defaultMessagesBuffer){const s=this._defaultMessagesBuffer[r];if(t<=1){this.sendWithWebsocket(s.key,s.value,la.Immediate);break}const o=this.toMessage(s.key,s.value);this._defaultMessagesBufferArray.push(o)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&ps&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;const n=JSON.stringify(this._defaultMessagesBufferArray);(e=this._ws)==null||e.send(n)}beginListen(e,t){return this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t),t}stopListening(e,t){return this.stopListen(e,t)}stopListen(e,t){if(!t||!this._listeners[e])return;const n=this._listeners[e].indexOf(t);n>=0&&this._listeners[e].splice(n,1)}beginListenBinary(e,t){return this._listenersBinary[e]||(this._listenersBinary[e]=[]),this._listenersBinary[e].push(t),t}stopListenBinary(e,t){if(!this._listenersBinary[e])return;const n=this._listenersBinary[e].indexOf(t);n>=0&&this._listenersBinary[e].splice(n,1)}registerProvider(e){this.netWebSocketUrlProvider=e}async connect(){var e;if(this.connected)return Promise.resolve(!0);ps&&console.log("connecting");const t=(e=this.netWebSocketUrlProvider)==null?void 0:e.getWebsocketUrl();return t?Kc=t:hO()&&(Kc="wss://"+window.location.host+"/socket"),this.connectWebsocket()}disconnect(){var e;(e=this._ws)==null||e.close(),this._ws=void 0}connectWebsocket(){return this._connectingToWebsocketPromise?this._connectingToWebsocketPromise:this._connectingToWebsocketPromise=new Promise(async(e,t)=>{var n;let r=!1;const s=c=>{r||(r=!0,e(c))};if(Kc===void 0&&(console.log("Fetch default backend url: "+AU),Kc=await(await fetch(AU)).text()),Kc===void 0){s(!1);return}console.log(`\u22A1 Connecting to networking backend on
4961
4961
  `+Kc);const o=await Promise.resolve().then(()=>Cue),a=((n=o.default)==null?void 0:n.WebsocketBuilder)??o.WebsocketBuilder,l=new a(Kc).onOpen(()=>{this._connectingToWebsocketPromise=null,this._ws=l,this.connected=!0,console.log(`\u229E Connected to networking backend
4962
- `+Kc),s(!0),this.onSendQueued(la.OnConnection)}).onClose(c=>{this._connectingToWebsocketPromise=null,this.connected=!1,this._isInRoom=!1,s(!1)}).onError((c,u)=>{console.error("\u22A0 Websocket error",c,u),s(!1)}).onRetry(()=>{console.log("Retry connecting to networking websocket")}).build();l.addEventListener(o.WebsocketEvent.message,(c,u)=>{this.onMessage(c,u)})})}onMessage(e,t){const n=t.data;try{if(typeof n!="string"){n.size&&this.handleIncomingBinaryMessage(n);return}const r=JSON.parse(n);if(Array.isArray(r))for(const s of r)this.handleIncomingStringMessage(s);else this.handleIncomingStringMessage(r);return}catch(r){ps&&n==="pong"?console.log("<<",n):pt()&&console.error("Failed to parse message",r)}}async handleIncomingBinaryMessage(e){y3&&console.log("<< bin",this.context.time.frame);const t=await e.arrayBuffer();var n=new Uint8Array(t);const r=new J0(n),s=r.getBufferIdentifier(),o=this._listenersBinary[s],a=tU(r),l=iU(a);if(l&&typeof l=="string"&&(this._state[l]=a),!o)return;const c=a??r;for(const u of o)u(c)}handleIncomingStringMessage(e){var t,n;if(ps&&console.log("<<",e.key??e),e.key)switch(e.key){case"connection-start-info":if(e.data){const a=e.data;a&&(console.assert(a.id!==void 0&&a.id!==null&&a.id.length>0,"server did not send connection id",a.id),console.log("Your id is: "+a.id,this.context.alias??""),this._connectionId=a.id)}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(ps&&console.log(e),e){this._isInRoom=!0;const a=e;this._currentRoomName=a.room,this._currentRoomViewId=a.viewId,this._currentRoomAllowEditing=a.allowEditing??!0,this._currentInRoom.length=0,this._currentInRoom.push(...a.inRoom),ps&&console.log("joined room with",this._currentInRoom,this.context.alias??"");const l=new URL(window.location.href);l.searchParams.has("room")&&l.searchParams.delete("room"),l.searchParams.set("view",this._currentRoomViewId),console.log("Room view id: "+this._currentRoomViewId+`
4963
- `+l.href)}this.onSendQueued(la.OnRoomJoin);break;case"left-room":e.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentInRoom.length=0);break;case"user-joined-room":if(e.data){const a=e.data;this._currentInRoom.push(a.userId),ps&&console.log(a.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){const a=e.data,l=this._currentInRoom.indexOf(a.userId);l>=0&&(ps&&console.log(a.userId+" left","now in room:",this._currentInRoom),this._currentInRoom.splice(l,1)),a.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":ps&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const o=(t=e.data)==null?void 0:t.time;o&&(this._currentDelay=this.context.time.time-o),ps&&console.log("Current latency: "+this._currentDelay.toFixed(1)+" sec","Clients in room: "+((n=this._currentInRoom)==null?void 0:n.length));break}let r=this._listeners[e.key];if(r){r=[...r];for(const o of r)try{o(e.data)}catch(a){console.error('Error invoking callback for "'+e.key+'"',a)}}const s=e.data;s&&(this._state[s.guid]=s)}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,n=la.OnRoomJoin){if(!this._ws){const s=this._waitingForSocket[n]||[];s.push(()=>this.sendWithWebsocket(e,t,n)),this._waitingForSocket[n]=s;return}const r=JSON.stringify(this.toMessage(e,t));ps&&console.log(">>",e),this._ws.send(r)}onSendQueued(e){const t=this._waitingForSocket[e];if(t){for(const n of t)n();t.length=0}}}const Ug=ee("debugwebxr");class RM{constructor(e,t){h(this,"controllerStates",[]),h(this,"userId"),h(this,"context"),h(this,"userStateEvtName"),h(this,"onReceivedControllerState",n=>{Ug&&console.log(`XRSync: Received change for ${this.userId}: ${n.type} ${n.handedness}; tracked=${n.isTracking}`);let r=!1;for(let s=0;s<this.controllerStates.length;s++)if(this.controllerStates[s].index===n.index){this.controllerStates[s]=n,r=!0;break}r||this.controllerStates.push(n)}),this.userId=e,this.context=t,this.userStateEvtName="xr-sync-user-state-"+e,this.context.connection.beginListen(this.userStateEvtName,this.onReceivedControllerState)}dispose(){this.context.connection.stopListen(this.userStateEvtName,this.onReceivedControllerState)}update(e){if(this.context.connection.isConnected!=!1){for(let t=this.controllerStates.length-1;t>=0;t--){const n=this.controllerStates[t];let r=!1;for(let s=0;s<e.controllers.length;s++)e.controllers[s].index===n.index&&(r=!0);r||(Ug&&console.log(`XRSync: ${n.type} ${n.handedness} removed`,n.index),this.controllerStates.splice(t,1),this.sendControllerRemoved(n))}for(const t of e.controllers)this.updateControllerStates(t)}}onExitXR(e){for(const t of this.controllerStates)this.sendControllerRemoved(t);this.controllerStates.length=0}sendControllerRemoved(e){e.isTracking=!1,e.guid="",this.context.connection.send(this.userStateEvtName,e),this.context.connection.sendDeleteRemoteState(e.guid)}updateControllerStates(e){const t=this.controllerStates.find(n=>n.index===e.index);if(t){let n=!1;n||(n=t.isTracking!=e.isTracking),n&&(t.isTracking=e.isTracking,this.context.connection.send(this.userStateEvtName,t))}else{const n={guid:this.userId+"-"+e.index,isTracking:e.isTracking,handedness:e.side,index:e.index,type:e.hand?"hand":"controller"};this.controllerStates.push(n),this.context.connection.send(this.userStateEvtName,n),Ug&&console.log(`XRSync: ${n.type} ${n.handedness} added`,n.index)}}}class w3{constructor(e){h(this,"context"),h(this,"onJoinedRoom",()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(Ug&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new RM(this.context.connection.connectionId,this.context)));for(const t of this.context.connection.usersInRoom())this._states.has(t)||this._states.set(t,new RM(t,this.context))}}),h(this,"onLeftRoom",()=>{if(this.context.connection.connectionId&&!this._states.has(this.context.connection.connectionId)){const t=this._states.get(this.context.connection.connectionId);t?.dispose(),this._states.delete(this.context.connection.connectionId)}}),h(this,"onOtherUserJoinedRoom",t=>{const n=t.userId;this._states.has(n)||(Ug&&console.log("XRSync: Remote user joined room",n),this._states.set(n,new RM(n,this.context)))}),h(this,"onOtherUserLeftRoom",t=>{const n=t.userId;if(!this._states.has(n)){const r=this._states.get(n);r?.dispose(),this._states.delete(n)}}),h(this,"_states",new Map),this.context=e,this.context.connection.beginListen(Jt.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Jt.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(Jt.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(Jt.UserLeftRoom,this.onOtherUserLeftRoom)}hasState(e){return e?this._states.has(e):!1}isTracking(e,t){if(!e)return;const n=this._states.get(e);if(!n)return;const r=n.controllerStates.find(s=>s.handedness===t);return r?.isTracking||!1}getDeviceType(e,t){if(!e)return;const n=this._states.get(e);if(!n)return;const r=n.controllerStates.find(s=>s.handedness===t);return r?.type||"unknown"}destroy(){this.context.connection.stopListen(Jt.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Jt.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(Jt.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(Jt.UserLeftRoom,this.onOtherUserLeftRoom)}onUpdate(e){if(this.context.connection.isConnected&&this.context.connection.connectionId){const t=this._states.get(this.context.connection.connectionId);t?.update(e)}}onExitXR(e){if(this.context.connection.isConnected&&this.context.connection.connectionId){const t=this._states.get(this.context.connection.connectionId);t?.onExitXR(e)}}}class S3{constructor(){h(this,"_fadeToColorQuad"),h(this,"_fadeToColorMaterial"),h(this,"_requestedFadeValue",0),h(this,"_transitionPromise",null),h(this,"_transitionResolve",null),this._fadeToColorMaterial=new oi({color:0,transparent:!0,depthTest:!1,fog:!1,side:hi}),this._fadeToColorQuad=new ue(new Un(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(e,t){const n=this._fadeToColorQuad,r=this._fadeToColorMaterial;n.parent!==e&&r.opacity>0?e.add(n):r.opacity===0&&n.removeFromParent(),n.layers.set(2),n.material=this._fadeToColorMaterial,n.position.z=-1,n.renderOrder=1/0;const s=this._requestedFadeValue;r.opacity=Ze.lerp(r.opacity,s,t/.03),Math.abs(r.opacity-s)<=.01&&this._transitionResolve&&(this._transitionResolve(),this._transitionResolve=null,this._transitionPromise=null,this._requestedFadeValue=0)}remove(){this._fadeToColorQuad.removeFromParent()}fadeTransition(){if(this._transitionPromise)return this._transitionPromise;this._requestedFadeValue=1;const e=new Promise(t=>{this._transitionResolve=t});return this._transitionPromise=e,e}}var Uu=(i=>(i[i.Quad=0]="Quad",i[i.Cube=1]="Cube",i[i.Sphere=2]="Sphere",i))(Uu||{});class Fg{static createPrimitive(e,t){let n;switch(e){case"Quad":case 0:const r=new Un(1,1,1,1),s=t?.material??new ls({color:16777215});n=new ue(r,s);break;case"Cube":case 1:const o=new Di(1,1,1),a=t?.material??new ls({color:16777215});n=new ue(o,a);break;case"Sphere":case 2:const l=new wa(.5,16,16),c=t?.material??new ls({color:16777215});n=new ue(l,c);break}return t!=null&&t.name&&(n.name=t.name),t!=null&&t.position&&n.position.set(t.position.x,t.position.y,t.position.z),t!=null&&t.rotation&&n.rotation.set(t.rotation.x,t.rotation.y,t.rotation.z),t!=null&&t.scale&&n.scale.set(t.scale.x,t.scale.y,t.scale.z),n}}const C3=class{constructor(i,e,t){h(this,"_session"),h(this,"_mode"),h(this,"_init"),h(this,"_renderer"),h(this,"_camera"),h(this,"_scene"),h(this,"onEnd",()=>{var n;(n=this._session)==null||n.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()}),h(this,"_lastTime",0),h(this,"onFrame",(n,r)=>{const s=n-this._lastTime;this.update(n,s),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera)}),h(this,"_objects",[]),this._mode=i,this._init=e,this._session=t,this._session.addEventListener("end",this.onEnd),this._renderer=new Pl({alpha:!0}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(t),this._renderer.xr.enabled=!0,this._camera=new kt,this._scene=new jr,this._scene.fog=new ny(4473924,10,250),this._scene.add(this._camera),this.setupScene()}static get active(){return this._active}static async start(i,e){if(this._active)return console.error("Cannot start a new XR session while one is already active"),null;if(this._requestInFlight)return console.error("Cannot start a new XR session while a request is already in flight"),null;if("xr"in navigator&&navigator.xr){if(!e)return console.error("XRSessionInit must be provided"),null;this._requestInFlight=!0;const t=await navigator.xr.requestSession(i,e);return t.addEventListener("end",()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new C3(i,e,t),this._active):(t.end(),null)}return null}static async handoff(){return this._active?this._active.handoff():null}static async stop(){this._requestInFlight=!1,this._active&&(await this._active.end(),await na(100)),this._active=null}get isAR(){return this._mode==="immersive-ar"}end(){return this._session?this._session.end():Promise.resolve()}async handoff(){if(!this._session)throw new Error("Cannot handoff a session that has already ended");const i={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,i}async onBeforeHandoff(){await na(1e3),this._scene.clear()}setupScene(){this._scene.background=new Se(0),this._scene.add(new Ny(5,10,1118481,1118481));const i=new _p(16777215,1);i.position.set(0,20,0),i.castShadow=!1,this._scene.add(i);const e=new _p(16777215,1);e.position.set(0,-1,0),e.castShadow=!1,this._scene.add(e);const t=new qm(16777215,1,100,1);t.position.set(0,2,0),t.castShadow=!1,t.distance=200,this._scene.add(t);const n=50;for(let r=0;r<100;r++){const s=new ls({color:2236962,metalness:1,roughness:.8});this.isAR&&(s.emissive=new Se(Math.random(),Math.random(),Math.random()),s.emissiveIntensity=Math.random());const o=Ze.random(0,1)>.5?Uu.Sphere:Uu.Cube,a=Fg.createPrimitive(o,{material:s});a.position.x=Ze.random(-n,n),a.position.y=Ze.random(-2,n),a.position.z=Ze.random(-n,n),a.rotation.x=Ze.random(0,Math.PI*2),a.rotation.y=Ze.random(0,Math.PI*2),a.rotation.z=Ze.random(0,Math.PI*2),a.scale.multiplyScalar(.5+Math.random()*10);const l=a.position.distanceTo(this._camera.position)-a.scale.x;l<1&&a.position.multiplyScalar(1+1/l),this._objects.push(a),this._scene.add(a)}}update(i,e){const t=i*4e-4;for(let n=0;n<this._objects.length;n++){const r=this._objects[n];r.position.y+=Math.sin(t+n*.5)*.005,r.rotateY(.002)}}};let Op=C3;h(Op,"_active",null),h(Op,"_requestInFlight",!1);const $n=ee("debugwebxr"),A$=ee("stats");function y$(i){let e=null;const t=i;return t.getAROverlayContainer?e=t.getAROverlayContainer():e=i,e}b$();async function b$(){var i;if(ee("debugasap")){let e=globalThis["needle:XRSession"];if(e instanceof Promise){delete globalThis["needle:XRSession"],ii.addContextCreatedCallback(async t=>{if(!e)return;Mp(!0);const n=await e;if(n){const r=mt.getDefaultSessionInit("immersive-vr");mt.setSession("immersive-vr",n,r,t.context)}else console.error("NeedleXRSession: ASAP session was rejected");e=void 0});return}}if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent)){console.warn("WebXRViewer does not support addEventListener");return}(i=navigator.xr)==null||i.addEventListener("sessiongranted",async()=>{Mp(!0),console.log("Received Session Granted..."),await na(100);const e=sessionStorage.getItem("needle_xr_session_mode"),t=sessionStorage.getItem("needle_xr_session_init")??null,n=t?JSON.parse(t):null;let r=null;if(E3()&&(await Op.start(e||"immersive-vr",n||mt.getDefaultSessionInit("immersive-vr")),await w$(),r=await Op.handoff()),r)mt.setSession(r.mode,r.session,r.init,Lt.Current);else if(e&&t){console.log("Session Granted: Restore last session");const s=JSON.parse(t);mt.start(e,s).catch(o=>console.warn(o))}else mt.start("immersive-vr").catch(s=>console.warn("Session Granted failed:",s))},{once:!0})}}function _$(i,e){sessionStorage.setItem("needle_xr_session_mode",i),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(e))}function x$(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const PM=new Set;ii.registerCallback(bn.ContextCreationStart,async i=>{PM.add(i.context)}),ii.registerCallback(bn.ContextCreated,async i=>{PM.delete(i.context)});function E3(){return PM.size>0}function w$(){return new Promise(i=>{const e=Date.now(),t=setInterval(()=>{(!E3()||Date.now()-e>6e4)&&(clearInterval(t),i())},100)})}yu()&&pt()&&window.addEventListener("keydown",i=>{(i.key==="x"||i.key==="Escape")&&mt.active&&mt.stop()});const Zc=class{constructor(i,e,t,n){h(this,"context"),h(this,"session"),h(this,"mode"),h(this,"controllers",[]),h(this,"_rigScale",1),h(this,"_lastRigScaleUpdate",-1),h(this,"_rigs",[]),h(this,"_viewerHitTestSource",null),h(this,"_defaultRig"),h(this,"_xr_scripts"),h(this,"_xr_update_scripts",[]),h(this,"_inactive_scripts",[]),h(this,"_controllerAdded"),h(this,"_controllerRemoved"),h(this,"_originalCameraWorldPosition"),h(this,"_originalCameraWorldRotation"),h(this,"_originalCameraWorldScale"),h(this,"_originalCameraParent"),h(this,"_mainCamera",null),h(this,"onRendererSessionSet",()=>{var o;this.running&&(this.context.renderer.xr.enabled=!0,this.context.renderer.xr.updateCamera(this.context.mainCamera),(o=this.context.mainCameraComponent)==null||o.applyClearFlags())}),h(this,"onInputSourceAdded",o=>{if(o.targetRayMode==="screen")return;let a=0;for(let c=0;c<this.session.inputSources.length;c++)if(this.session.inputSources[c]===o){a=c;break}if(this.controllers.find(c=>c.inputSource===o)){console.warn("Controller already exists for input source",a);return}$n&&console.log("Adding controller",a);const l=new sM(this,o,a);this._newControllers.push(l)}),h(this,"_ended",!1),h(this,"_newControllers",[]),h(this,"onEnd",o=>{var a,l,c;if(this._ended)return;this._ended=!0,$n&&console.log("XR Session ended"),x$(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,MZ(this.onBefore,Pn.LateUpdate);const u=this.context.pre_render_callbacks.indexOf(this.onBeforeRender);u>=0&&this.context.pre_render_callbacks.splice(u,1);const d=this.context.post_render_callbacks.indexOf(this.onAfterRender);d>=0&&this.context.post_render_callbacks.splice(d,1),this.context.xr=null,this.context.renderer.xr.enabled=!1,this.context.pre_update_oneshot_callbacks.push(()=>{var p;(p=this.context.mainCameraComponent)==null||p.applyClearFlags()});for(const p of Zc._xrEndListeners)p({xr:this});for(let p=0;p<this.controllers.length;p++)this.disconnectInputSource(this.controllers[p].inputSource);for(const p of this._xr_scripts)(a=p?.onLeaveXR)==null||a.call(p,{xr:this});(l=this.sync)==null||l.onExitXR(this),this.context.mainCamera&&((c=this._originalCameraParent)==null||c.add(this.context.mainCamera),this._originalCameraWorldPosition&&Qr(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&So(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&ng(this.context.mainCamera,this._originalCameraWorldScale)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),Mp(!1)}),h(this,"_didStart",!1),h(this,"onBefore",o=>{var a,l,c,u,d,p,f,m;const A=o.xrFrame;if(!A)return;this.context.xr=this,this.context.mainCameraComponent&&this.context.mainCameraComponent!==this._mainCamera&&(this._mainCamera=this.context.mainCameraComponent),((a=this.rig)==null?void 0:a.isActive)==!1&&($n&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig&&(l=this._mainCamera)!=null&&l.gameObject&&((u=(c=this._mainCamera)==null?void 0:c.gameObject)==null?void 0:u.parent)!==this.rig.gameObject&&this.rig.gameObject.add((d=this._mainCamera)==null?void 0:d.gameObject),this.internalUpdateState(),this.applyCustomForward();const v={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const g=[...this.context.new_scripts_xr];for(let y=0;y<g.length;y++){const b=this.context.new_scripts_xr[y];if(!b||b.destroyed||((p=b.supportsXR)==null?void 0:p.call(b,this.mode))==!1){this.context.new_scripts_xr.splice(y,1);continue}if(!b.activeAndEnabled){this.context.new_scripts_xr.splice(y,1),this.markInactive(b);continue}if(this.addScript(b)){this.invokeCallback_EnterXR(b);for(const _ of this.controllers)this.invokeCallback_ControllerAdded(b,_)}}}}else{this._didStart=!0,IZ({session:this});for(const y of Zc._xrStartListeners)y(v);const g=[...this._xr_scripts];$n&&console.log("NeedleXRSession start, handle scripts:",g);for(const y of g){if(y.destroyed){this._script_to_remove.push(y);continue}if(!y.activeAndEnabled){this.markInactive(y);continue}this.invokeCallback_EnterXR(y);for(const b of this.controllers)this.invokeCallback_ControllerAdded(y,b)}}this.syncCameraCullingMask();for(const g of this.controllers)g.onUpdate(A);if(this._newControllers.length>0){const g=[...this._newControllers];this._newControllers.length=0;for(const y of g)if(y.connected){this.controllers.push(y);for(const b of this._xr_scripts){if(b.destroyed){this._script_to_remove.push(b);continue}b.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(b,y)}}this.controllers.sort((y,b)=>y.index-b.index)}for(const g of this._xr_update_scripts){if(g.destroyed===!0){this._script_to_remove.push(g);continue}if(g.activeAndEnabled===!1){this.markInactive(g);continue}g.onUpdateXR&&g.onUpdateXR(v)}if(this.handleInactiveScripts(),this._script_to_remove.length>0){const g=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const y of g)!y.destroyed&&this.running&&((f=y.onLeaveXR)==null||f.call(y,v)),this.removeScript(y)}(m=this.sync)==null||m.onUpdate(this),this.onRenderDebug()}),h(this,"onBeforeRender",()=>{this.context.mainCamera&&this.updateFade(this.context.mainCamera)}),h(this,"onAfterRender",()=>{if(this.onUpdateFade_PostRender(),yu()){const o=this.context.renderer;if(o.xr.isPresenting&&this.context.mainCamera){const a=o.xr.enabled,l=o.getRenderTarget();o.xr.enabled=!1,o.setRenderTarget(null),o.render(this.context.scene,this.context.mainCamera),o.xr.enabled=a,o.setRenderTarget(l)}}}),h(this,"_script_to_remove",[]),h(this,"_camera"),h(this,"_cameraRenderParent",new ge().rotateY(Math.PI)),h(this,"_previousCameraParent"),h(this,"_customforward",!0),h(this,"originalCameraNearPlane"),h(this,"_viewerPose"),h(this,"_transformOrientation",new Me),h(this,"_transformPosition",new S),h(this,"_transition");var r,s;_$(i,n.init),this.session=e,this.mode=i,this.context=t,($n||ee("console"))&&Mp(!0),this._xr_scripts=[...n.scripts],this._xr_update_scripts=this._xr_scripts.filter(o=>typeof o.onUpdateXR=="function"),this._controllerAdded=n.controller_added,this._controllerRemoved=n.controller_removed,Mg(this.onBefore,Pn.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),((r=n.init.optionalFeatures)!=null&&r.includes("hit-test")||(s=n.init.requiredFeatures)!=null&&s.includes("hit-test"))&&e.requestReferenceSpace("viewer").then(o=>{var a,l;return(l=(a=e.requestHitTestSource)==null?void 0:a.call(e,{space:o}))==null?void 0:l.then(c=>this._viewerHitTestSource=c)}).catch(o=>console.warn(o)),this.context.mainCamera&&(this._originalCameraWorldPosition=Rt(this.context.mainCamera,new S),this._originalCameraWorldRotation=xi(this.context.mainCamera,new Me),this._originalCameraWorldScale=ki(this.context.mainCamera,new S),this._originalCameraParent=this.context.mainCamera.parent),this._defaultRig=new SZ,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let o=0;o<e.inputSources.length;o++){const a=e.inputSources[o];if(!a.handedness){console.warn("Input source in xr session has no handedness - ignoring",o);continue}this.onInputSourceAdded(a)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",o=>{for(const a of o.removed)this.disconnectInputSource(a);for(const a of o.added)this.onInputSourceAdded(a)}),this.context.xr=this,this.context.renderer.xr.setSession(this.session).then(this.onRendererSessionSet)}static getXRSync(i){return this._sync||(this._sync=new w3(i)),this._sync}static get currentSessionRequest(){return this._currentSessionRequestMode}static get active(){return this._activeSession}static get activeMode(){var i;return((i=this._activeSession)==null?void 0:i.mode)??null}static get xrSystem(){return"xr"in navigator?navigator.xr:void 0}static isXRSupported(){return Promise.all([this.isVRSupported(),this.isARSupported()]).then(i=>i.some(e=>e)).catch(()=>!1)}static isVRSupported(){return this.isSessionSupported("immersive-vr")}static isARSupported(){return this.isSessionSupported("immersive-ar")}static isSessionSupported(i){var e;return((e=this.xrSystem)==null?void 0:e.isSessionSupported(i).catch(t=>($n&&console.error(t),!1)))??Promise.resolve(!1)}static onSessionRequestStart(i){this._sessionRequestStartListeners.push(i)}static offSessionRequestStart(i){const e=this._sessionRequestStartListeners.indexOf(i);e>=0&&this._sessionRequestStartListeners.splice(e,1)}static onSessionRequestEnd(i){this._sessionRequestEndListeners.push(i)}static offSessionRequestEnd(i){const e=this._sessionRequestEndListeners.indexOf(i);e>=0&&this._sessionRequestEndListeners.splice(e,1)}static onXRSessionStart(i){this._xrStartListeners.push(i)}static offXRSessionStart(i){const e=this._xrStartListeners.indexOf(i);e>=0&&this._xrStartListeners.splice(e,1)}static onXRSessionEnd(i){this._xrEndListeners.push(i)}static offXRSessionEnd(i){const e=this._xrEndListeners.indexOf(i);e>=0&&this._xrEndListeners.splice(e,1)}static onControllerAdded(i){this._controllerAddedListeners.push(i)}static offControllerAdded(i){const e=this._controllerAddedListeners.indexOf(i);e>=0&&this._controllerAddedListeners.splice(e,1)}static onControllerRemoved(i){this._controllerRemovedListeners.push(i)}static offControllerRemoved(i){const e=this._controllerRemovedListeners.indexOf(i);e>=0&&this._controllerRemovedListeners.splice(e,1)}static offerSession(i,e,t){return"xr"in navigator&&navigator.xr&&"offerSession"in navigator.xr?(typeof navigator.xr.offerSession=="function"&&(console.log("WebXR offerSession is available - requesting mode: "+i),e=="default"&&(e=this.getDefaultSessionInit(i)),navigator.xr.offerSession(i,{...e}).then(n=>Zc.setSession(i,n,e,t)).catch(n=>{console.log("XRSession offer rejected (perhaps because another call to offerSession was made or a call to requestSession was made)")})),!0):!1}static getDefaultSessionInit(i){switch(i){case"immersive-ar":return{optionalFeatures:["anchors","local-floor","hand-tracking","layers","dom-overlay","hit-test"]};case"immersive-vr":return{optionalFeatures:["local-floor","bounded-floor","hand-tracking","high-fixed-foveation-level","layers"]};default:return console.warn("No default session init for mode",i),{}}}static async start(i,e,t){var n,r,s,o;if(pt()&&ee("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await Op.start(i,e||Zc.getDefaultSessionInit(i)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),($n||pt())&&Qi("A XRSession is already being requested"),this._currentSessionRequest.then(()=>this._activeSession);if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;if(t||(t=Lt.Current),t||(t=ii.All[0]),!t)throw new Error("No Needle Engine Context found");switch(e||(e={}),i){case"immersive-ar":{if(await((n=this.xrSystem)==null?void 0:n.isSessionSupported("immersive-ar"))!==!0)return console.error(i+" is not supported by this browser."),null;const c=this.getDefaultSessionInit(i),u=y$(t.domElement);u&&!qy()&&(c.domOverlay={root:u},c.optionalFeatures.push("dom-overlay")),e={...c,...e}}break;case"immersive-vr":{if(await((r=this.xrSystem)==null?void 0:r.isSessionSupported("immersive-vr"))!==!0)return console.error(i+" is not supported by this browser."),null;e={...this.getDefaultSessionInit(i),...e}}break;default:console.warn("No default session init for mode",i);break}await Op.stop();const a=i=="immersive-ar"?t.scripts_immersive_ar:t.scripts_immersive_vr;$n?console.log(`%cRequesting ${i} session`,"font-weight:bold;",e,a):console.log(`%cRequesting ${i} session`,"font-weight:bold;");for(const c of a)c.onBeforeXR&&c.onBeforeXR(i,e);for(const c of this._sessionRequestStartListeners)c({mode:i,init:e});$n&&$i("Requesting "+i+" session ("+Date.now()+")"),this._currentSessionRequest=(s=navigator.xr)==null?void 0:s.requestSession(i,e),this._currentSessionRequestMode=i;const l=await((o=this._currentSessionRequest)==null?void 0:o.catch(c=>{console.error(c,"Code: "+c.code),c.code===9&&Qi("Make sure your device has the required permissions (e.g. camera access)"),console.log("If the specified XR configuration is not supported (e.g. entering AR doesnt work) - make sure you access the website on a secure connection (HTTPS) and your device has the required permissions (e.g. camera access)"),location.protocol==="http:"&&Qi("XR requires a secure connection (HTTPS)")}));this._currentSessionRequest=void 0,this._currentSessionRequestMode=null;for(const c of this._sessionRequestEndListeners)c({mode:i,init:e,newSession:l||null});return l?this.setSession(i,l,e,t):(console.warn("XR Session request was rejected"),null)}static setSession(i,e,t,n){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const r=i=="immersive-ar"?n.scripts_immersive_ar:n.scripts_immersive_vr;return this._activeSession=new Zc(i,e,n,{scripts:r,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:t}),e.addEventListener("end",this.onEnd),$n?console.log(`%cStarted ${i} session`,"font-weight:bold;",r):console.log(`%cStarted ${i} session`,"font-weight:bold;"),this._activeSession}static stop(){var i;(i=this._activeSession)==null||i.end()}get sync(){return Zc._sync}get running(){return!this._ended&&this.session!=null}get interactionMode(){return this.session.interactionMode}get visibilityState(){return this.session.visibilityState}get environmentBlendMode(){return this.session.environmentBlendMode}get frame(){return this.context.xrFrame}get leftController(){return this.controllers.find(i=>i.isLeft)}get rightController(){return this.controllers.find(i=>i.isRight)}getController(i){return typeof i=="number"?this.controllers[i]||null:this.controllers.find(e=>e.side===i)||null}get isPassThrough(){return!!(this.environmentBlendMode!=="opaque"&&this.interactionMode==="world-space"||this.mode==="immersive-ar"&&this.environmentBlendMode!=="opaque"&&this.controllers.some(i=>i.inputSource.targetRayMode==="tracked-pointer")||pt()&&yu()&&this.mode==="immersive-ar")}get isAR(){return this.mode==="immersive-ar"}get isVR(){return this.mode==="immersive-vr"}get isScreenBasedAR(){return this.isAR&&!this.isPassThrough}get posePosition(){return this._transformPosition}get poseOrientation(){return this._transformOrientation}get referenceSpace(){return this.context.renderer.xr.getReferenceSpace()}get viewerPose(){return this._viewerPose}get isTrackingImages(){if(this.frame&&"getImageTrackingResults"in this.frame&&typeof this.frame.getImageTrackingResults=="function")try{const i=this.frame.getImageTrackingResults();for(const e of i)if(e.trackingState==="tracked")return!0}catch{return!1}return!1}get rig(){const i=this._rigs[0]??null;return i!=null&&i.gameObject&&zu(i.gameObject)||i?.isActive===!1?(this.updateActiveXRRig(),this._rigs[0]??null):i}get rigScale(){return this._rigs[0]?(this._lastRigScaleUpdate!==this.context.time.frame&&(this._lastRigScaleUpdate=this.context.time.frame,this._rigScale=this._rigs[0].gameObject.worldScale.x),this._rigScale):1}addRig(i){this._rigs.indexOf(i)>=0||(i.priority===void 0&&(i.priority=0),this._rigs.push(i),this.updateActiveXRRig())}removeRig(i){const e=this._rigs.indexOf(i);e!==-1&&(this._rigs.splice(e,1),this.updateActiveXRRig())}setRigActive(i){const e=this._rigs.indexOf(i);this._rigs.splice(e,1),this._rigs.unshift(i),this.updateActiveXRRig()}updateActiveXRRig(){const i=this._rigs[0]??null;this._defaultRig.gameObject.parent!==this.context.scene&&this.context.scene.add(this._defaultRig.gameObject),this._defaultRig.gameObject.visible=!0,this._rigs.includes(this._defaultRig)||this._rigs.push(this._defaultRig);let e=this._rigs[0];e&&e.priority===void 0&&(e.priority=0);for(let t=1;t<this._rigs.length;t++){const n=this._rigs[t];if(n.isActive){if(zu(n.gameObject)){this._rigs.splice(t,1),t--;continue}(!e||e.isActive===!1||n.priority!==void 0&&n.priority>e.priority)&&(e=n)}}if(i!==e){const t=this._rigs.indexOf(e);t>=0&&this._rigs.splice(t,1),this._rigs.unshift(e)}$n&&(i===e?console.log("Updated Active XR Rig:",e,"prev:",i):console.log("Updated Active XRRig:",e," (the same as before)"))}getHitTest(i){if(i)return this.getControllerHitTest(i);if(!this._viewerHitTestSource)return null;const e=this._viewerHitTestSource,t=this.frame.getHitTestResults(e);if(t.length>0){const n=t[0];return this.convertHitTestResult(n)}return null}getControllerHitTest(i){const e=i.hitTestSource;if(!e)return null;const t=this.frame.getHitTestResultsForTransientInput(e);for(const n of t)if(n.inputSource===i.inputSource)for(const r of n.results)return this.convertHitTestResult(r);return null}convertHitTestResult(i){const e=this.context.renderer.xr.getReferenceSpace(),t=e&&i.getPose(e);if(t){const n=Zi(t.transform.position),r=wu(t.transform.orientation),s=this.context.mainCamera;if(s?.parent!==this._cameraRenderParent&&n.applyMatrix4(Fb),s!=null&&s.parent){n.applyMatrix4(s.parent.matrixWorld),r.multiply(Mo);const o=xi(s.parent);o.premultiply(Mo),r.premultiply(o)}return{hit:i,position:n,quaternion:r}}return null}convertSpace(i){const e=Zi(i.position);e.applyMatrix4(Fb);const t=wu(i.orientation);return t.premultiply(Mo),{position:e,quaternion:t}}disconnectInputSource(i){const e=(t,n,r)=>{if(t.inputSource===i){$n&&console.log("Disconnecting controller",t.index),this.controllers.splice(r,1),this.invokeControllerEvent(t,this._controllerRemoved,"removed");const s={xr:this,controller:t,change:"removed"};for(const o of this._xr_scripts)o.onXRControllerRemoved&&o.onXRControllerRemoved(s);t.onDisconnected()}};for(let t=this.controllers.length-1;t>=0;t--){const n=this.controllers[t];e(n,this.controllers,t)}for(let t=this._newControllers.length-1;t>=0;t--){const n=this._newControllers[t];e(n,this._newControllers,t)}}end(){this._ended||this.session.end().catch(i=>console.warn(i))}onRenderDebug(){if($n)for(const i of this.controllers)i.onRenderDebug();if(($n||A$)&&this.rig){const i=this.rig.gameObject.worldPosition,e=this.rig.gameObject.worldForward;i.add(e.multiplyScalar(1.5));const t=this.rig.gameObject.worldUp;i.add(t.multiplyScalar(2.5));let n="";if(n+=this.context.time.smoothedFps.toFixed(1),$n)for(const r of this.controllers)n+=`
4964
- ${r.hand?"hand":"ctrl"} ${r.inputSource.handedness}[${r.index}] con:${r.connected} tr:${r.isTracking}`;Ct.DrawLabel(i,n)}}addScript(i){return this._xr_scripts.includes(i)?!1:($n&&console.log("Register new XRScript",i),this._xr_scripts.push(i),typeof i.onUpdateXR=="function"&&this._xr_update_scripts.push(i),!0)}markInactive(i){if(!(this._inactive_scripts.indexOf(i)>=0)){this.removeScript(i,!1),this._inactive_scripts.push(i);for(const e of this.controllers)this.invokeCallback_ControllerRemoved(i,e);this.invokeCallback_LeaveXR(i)}}handleInactiveScripts(){if(this._inactive_scripts.length>0)for(let i=this._inactive_scripts.length-1;i>=0;i--){const e=this._inactive_scripts[i];if(e.activeAndEnabled){this._inactive_scripts.splice(i,1),this.addScript(e),this.invokeCallback_EnterXR(e);for(const t of this.controllers)this.invokeCallback_ControllerAdded(e,t)}}}removeScript(i,e=!0){$n&&console.log("Remove XRScript",i);const t=this._xr_scripts.indexOf(i);t>=0&&this._xr_scripts.splice(t,1);const n=this._xr_update_scripts.indexOf(i);if(n>=0&&this._xr_update_scripts.splice(n,1),e){const r=this._inactive_scripts.indexOf(i);r>=0&&this._inactive_scripts.splice(r,1)}}invokeCallback_EnterXR(i){i.onEnterXR&&i.onEnterXR({xr:this})}invokeCallback_ControllerAdded(i,e){i.onXRControllerAdded&&i.onXRControllerAdded({xr:this,controller:e,change:"added"})}invokeCallback_ControllerRemoved(i,e){i.onXRControllerRemoved&&i.onXRControllerRemoved({xr:this,controller:e,change:"removed"})}invokeCallback_LeaveXR(i){i.onLeaveXR&&!i.destroyed&&i.onLeaveXR({xr:this})}syncCameraCullingMask(){var i;const e=this.context.xrCamera,t=(i=this.context.mainCameraComponent)==null?void 0:i.cullingMask;if(e&&t!==void 0){for(const n of e.cameras)n.layers.mask=t;e.layers.mask=t}else if(e){for(const n of e.cameras)n.layers.enableAll();e.layers.enableAll()}}invokeControllerEvent(i,e,t){for(let n=e.length-1;n>=0;n--){const r=e[n];if(r)try{r({xr:this,controller:i,change:t})}catch(s){console.error(s)}}}applyCustomForward(){var i;if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,(i=this._previousCameraParent)==null||i.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);let e=.02;if(this.rig){const t=ki(this.rig.gameObject);e*=t.x}this._camera instanceof kt&&this._camera.near>e&&(this.originalCameraNearPlane=this._camera.near,this._camera.near=e)}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof kt&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane)}internalUpdateState(){const i=this.context.renderer.xr.getReferenceSpace();if(!i){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(i),this._viewerPose){const e=this._viewerPose.transform;this._transformPosition.set(e.position.x,e.position.y,e.position.z),this._transformOrientation.set(e.orientation.x,e.orientation.y,e.orientation.z,e.orientation.w)}}get transition(){return this._transition||(this._transition=new S3),this._transition}fadeTransition(){return this._transition||(this._transition=new S3),this._transition.fadeTransition()}updateFade(i){this._transition&&i instanceof kt&&this._transition.update(i,this.context.time.deltaTime)}onUpdateFade_PostRender(){var i;(i=this._transition)==null||i.remove()}};let mt=Zc;h(mt,"_sync",null),h(mt,"_currentSessionRequestMode",null),h(mt,"_currentSessionRequest"),h(mt,"_activeSession"),h(mt,"_sessionRequestStartListeners",[]),h(mt,"_sessionRequestEndListeners",[]),h(mt,"_xrStartListeners",[]),h(mt,"_xrEndListeners",[]),h(mt,"_controllerAddedListeners",[]),h(mt,"_controllerRemovedListeners",[]),h(mt,"onEnd",()=>{$n&&console.log("XR Session ended"),Zc._activeSession=null});const BM=ee("debugwebxr");class M3{static tryFindAvatarObjects(e,t,n){if(n.head&&n.leftHand&&n.rightHand)return;const r=e.name.toLocaleLowerCase();!n.head&&r.includes("head")&&(BM&&console.log("FOUND AVATAR HEAD",e.name),n.head=new ni("",t,e)),r.includes("hand")&&(!n.leftHand&&r.includes("left")&&(BM&&console.log("FOUND AVATAR LEFT HAND",e.name),n.leftHand=new ni("",t,e)),!n.rightHand&&r.includes("right")&&(BM&&console.log("FOUND AVATAR RIGHT HAND",e.name),n.rightHand=new ni("",t,e)));for(let s=0;s<e.children.length;s++){if(n.head&&n.leftHand&&n.rightHand)return;const o=e.children[s];this.tryFindAvatarObjects(o,t,n)}}}var Zb=(i=>(i.Visible="application-visible",i.Hidden="application-hidden",i.MuteChanged="application-mutechanged",i))(Zb||{});let $b=!1;const e_=[];function kp(){if($b)return;pt()&&console.log("User interaction registered: audio can now be played"),$b=!0;const i=[...e_];e_.length=0,i.forEach(e=>e())}document.addEventListener("pointerdown",kp),document.addEventListener("click",kp),document.addEventListener("dragstart",kp),document.addEventListener("touchstart",kp),document.addEventListener("keydown",kp),mt.onXRSessionStart(()=>{kp()});class Ng extends EventTarget{constructor(e){super(),h(this,"_mute",!1),h(this,"context"),h(this,"_isVisible",!0),this.context=e,window.addEventListener("visibilitychange",this.onVisiblityChanged.bind(this),!1)}static get userInteractionRegistered(){return $b}static registerWaitForAllowAudio(e){if(e!==null){if($b){e();return}e_.indexOf(e)===-1&&e_.push(e)}}get muted(){return this._mute}set muted(e){e!==this._mute&&(this._mute=e,this.dispatchEvent(new Event("application-mutechanged")))}get hasFocus(){return document.hasFocus()}get isVisible(){return this._isVisible}onVisiblityChanged(e){switch(e.target.visibilityState){case"hidden":this._isVisible=!1,this.dispatchEvent(new Event("application-hidden"));break;case"visible":this._isVisible=!0,this.dispatchEvent(new Event("application-visible"));break}}}function*T3(i,e=null){const t=e?e.time:Lt.Current.time,n=t.time;for(;t.time-n<i;)yield}function*S$(i){for(let e=0;e<i;e++)yield}function*I3(i){let e=!0;for(i.then(()=>e=!1),i.catch(()=>e=!1);e;)yield}/*!
4962
+ `+Kc),s(!0),this.onSendQueued(la.OnConnection)}).onClose(c=>{this._connectingToWebsocketPromise=null,this.connected=!1,this._isInRoom=!1,s(!1)}).onError((c,u)=>{console.error("\u22A0 Websocket error",c,u),s(!1)}).onRetry(()=>{console.log("Retry connecting to networking websocket")}).build();l.addEventListener(o.WebsocketEvent.message,(c,u)=>{this.onMessage(c,u)})})}onMessage(e,t){const n=t.data;try{if(typeof n!="string"){n.size&&this.handleIncomingBinaryMessage(n);return}const r=JSON.parse(n);if(Array.isArray(r))for(const s of r)this.handleIncomingStringMessage(s);else this.handleIncomingStringMessage(r);return}catch(r){ps&&n==="pong"?console.log("<<",n):pt()&&console.error("Failed to parse message",r)}}async handleIncomingBinaryMessage(e){yU&&console.log("<< bin",this.context.time.frame);const t=await e.arrayBuffer();var n=new Uint8Array(t);const r=new J0(n),s=r.getBufferIdentifier(),o=this._listenersBinary[s],a=t3(r),l=i3(a);if(l&&typeof l=="string"&&(this._state[l]=a),!o)return;const c=a??r;for(const u of o)u(c)}handleIncomingStringMessage(e){var t,n;if(ps&&console.log("<<",e.key??e),e.key)switch(e.key){case"connection-start-info":if(e.data){const a=e.data;a&&(console.assert(a.id!==void 0&&a.id!==null&&a.id.length>0,"server did not send connection id",a.id),console.log("Your id is: "+a.id,this.context.alias??""),this._connectionId=a.id)}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(ps&&console.log(e),e){this._isInRoom=!0;const a=e;this._currentRoomName=a.room,this._currentRoomViewId=a.viewId,this._currentRoomAllowEditing=a.allowEditing??!0,this._currentInRoom.length=0,this._currentInRoom.push(...a.inRoom),ps&&console.log("joined room with",this._currentInRoom,this.context.alias??"");const l=new URL(window.location.href);l.searchParams.has("room")&&l.searchParams.delete("room"),l.searchParams.set("view",this._currentRoomViewId),console.log("Room view id: "+this._currentRoomViewId+`
4963
+ `+l.href)}this.onSendQueued(la.OnRoomJoin);break;case"left-room":e.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentInRoom.length=0);break;case"user-joined-room":if(e.data){const a=e.data;this._currentInRoom.push(a.userId),ps&&console.log(a.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){const a=e.data,l=this._currentInRoom.indexOf(a.userId);l>=0&&(ps&&console.log(a.userId+" left","now in room:",this._currentInRoom),this._currentInRoom.splice(l,1)),a.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":ps&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const o=(t=e.data)==null?void 0:t.time;o&&(this._currentDelay=this.context.time.time-o),ps&&console.log("Current latency: "+this._currentDelay.toFixed(1)+" sec","Clients in room: "+((n=this._currentInRoom)==null?void 0:n.length));break}let r=this._listeners[e.key];if(r){r=[...r];for(const o of r)try{o(e.data)}catch(a){console.error('Error invoking callback for "'+e.key+'"',a)}}const s=e.data;s&&(this._state[s.guid]=s)}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,n=la.OnRoomJoin){if(!this._ws){const s=this._waitingForSocket[n]||[];s.push(()=>this.sendWithWebsocket(e,t,n)),this._waitingForSocket[n]=s;return}const r=JSON.stringify(this.toMessage(e,t));ps&&console.log(">>",e),this._ws.send(r)}onSendQueued(e){const t=this._waitingForSocket[e];if(t){for(const n of t)n();t.length=0}}}const Ug=ee("debugwebxr");class RM{constructor(e,t){h(this,"controllerStates",[]),h(this,"userId"),h(this,"context"),h(this,"userStateEvtName"),h(this,"onReceivedControllerState",n=>{Ug&&console.log(`XRSync: Received change for ${this.userId}: ${n.type} ${n.handedness}; tracked=${n.isTracking}`);let r=!1;for(let s=0;s<this.controllerStates.length;s++)if(this.controllerStates[s].index===n.index){this.controllerStates[s]=n,r=!0;break}r||this.controllerStates.push(n)}),this.userId=e,this.context=t,this.userStateEvtName="xr-sync-user-state-"+e,this.context.connection.beginListen(this.userStateEvtName,this.onReceivedControllerState)}dispose(){this.context.connection.stopListen(this.userStateEvtName,this.onReceivedControllerState)}update(e){if(this.context.connection.isConnected!=!1){for(let t=this.controllerStates.length-1;t>=0;t--){const n=this.controllerStates[t];let r=!1;for(let s=0;s<e.controllers.length;s++)e.controllers[s].index===n.index&&(r=!0);r||(Ug&&console.log(`XRSync: ${n.type} ${n.handedness} removed`,n.index),this.controllerStates.splice(t,1),this.sendControllerRemoved(n))}for(const t of e.controllers)this.updateControllerStates(t)}}onExitXR(e){for(const t of this.controllerStates)this.sendControllerRemoved(t);this.controllerStates.length=0}sendControllerRemoved(e){e.isTracking=!1,e.guid="",this.context.connection.send(this.userStateEvtName,e),this.context.connection.sendDeleteRemoteState(e.guid)}updateControllerStates(e){const t=this.controllerStates.find(n=>n.index===e.index);if(t){let n=!1;n||(n=t.isTracking!=e.isTracking),n&&(t.isTracking=e.isTracking,this.context.connection.send(this.userStateEvtName,t))}else{const n={guid:this.userId+"-"+e.index,isTracking:e.isTracking,handedness:e.side,index:e.index,type:e.hand?"hand":"controller"};this.controllerStates.push(n),this.context.connection.send(this.userStateEvtName,n),Ug&&console.log(`XRSync: ${n.type} ${n.handedness} added`,n.index)}}}class wU{constructor(e){h(this,"context"),h(this,"onJoinedRoom",()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(Ug&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new RM(this.context.connection.connectionId,this.context)));for(const t of this.context.connection.usersInRoom())this._states.has(t)||this._states.set(t,new RM(t,this.context))}}),h(this,"onLeftRoom",()=>{if(this.context.connection.connectionId&&!this._states.has(this.context.connection.connectionId)){const t=this._states.get(this.context.connection.connectionId);t?.dispose(),this._states.delete(this.context.connection.connectionId)}}),h(this,"onOtherUserJoinedRoom",t=>{const n=t.userId;this._states.has(n)||(Ug&&console.log("XRSync: Remote user joined room",n),this._states.set(n,new RM(n,this.context)))}),h(this,"onOtherUserLeftRoom",t=>{const n=t.userId;if(!this._states.has(n)){const r=this._states.get(n);r?.dispose(),this._states.delete(n)}}),h(this,"_states",new Map),this.context=e,this.context.connection.beginListen(Jt.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Jt.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(Jt.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(Jt.UserLeftRoom,this.onOtherUserLeftRoom)}hasState(e){return e?this._states.has(e):!1}isTracking(e,t){if(!e)return;const n=this._states.get(e);if(!n)return;const r=n.controllerStates.find(s=>s.handedness===t);return r?.isTracking||!1}getDeviceType(e,t){if(!e)return;const n=this._states.get(e);if(!n)return;const r=n.controllerStates.find(s=>s.handedness===t);return r?.type||"unknown"}destroy(){this.context.connection.stopListen(Jt.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Jt.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(Jt.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(Jt.UserLeftRoom,this.onOtherUserLeftRoom)}onUpdate(e){if(this.context.connection.isConnected&&this.context.connection.connectionId){const t=this._states.get(this.context.connection.connectionId);t?.update(e)}}onExitXR(e){if(this.context.connection.isConnected&&this.context.connection.connectionId){const t=this._states.get(this.context.connection.connectionId);t?.onExitXR(e)}}}class SU{constructor(){h(this,"_fadeToColorQuad"),h(this,"_fadeToColorMaterial"),h(this,"_requestedFadeValue",0),h(this,"_transitionPromise",null),h(this,"_transitionResolve",null),this._fadeToColorMaterial=new oi({color:0,transparent:!0,depthTest:!1,fog:!1,side:hi}),this._fadeToColorQuad=new ue(new Un(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(e,t){const n=this._fadeToColorQuad,r=this._fadeToColorMaterial;n.parent!==e&&r.opacity>0?e.add(n):r.opacity===0&&n.removeFromParent(),n.layers.set(2),n.material=this._fadeToColorMaterial,n.position.z=-1,n.renderOrder=1/0;const s=this._requestedFadeValue;r.opacity=Ze.lerp(r.opacity,s,t/.03),Math.abs(r.opacity-s)<=.01&&this._transitionResolve&&(this._transitionResolve(),this._transitionResolve=null,this._transitionPromise=null,this._requestedFadeValue=0)}remove(){this._fadeToColorQuad.removeFromParent()}fadeTransition(){if(this._transitionPromise)return this._transitionPromise;this._requestedFadeValue=1;const e=new Promise(t=>{this._transitionResolve=t});return this._transitionPromise=e,e}}var Uu=(i=>(i[i.Quad=0]="Quad",i[i.Cube=1]="Cube",i[i.Sphere=2]="Sphere",i))(Uu||{});class Fg{static createPrimitive(e,t){let n;switch(e){case"Quad":case 0:const r=new Un(1,1,1,1),s=t?.material??new ls({color:16777215});n=new ue(r,s);break;case"Cube":case 1:const o=new Di(1,1,1),a=t?.material??new ls({color:16777215});n=new ue(o,a);break;case"Sphere":case 2:const l=new wa(.5,16,16),c=t?.material??new ls({color:16777215});n=new ue(l,c);break}return t!=null&&t.name&&(n.name=t.name),t!=null&&t.position&&n.position.set(t.position.x,t.position.y,t.position.z),t!=null&&t.rotation&&n.rotation.set(t.rotation.x,t.rotation.y,t.rotation.z),t!=null&&t.scale&&n.scale.set(t.scale.x,t.scale.y,t.scale.z),n}}const CU=class{constructor(i,e,t){h(this,"_session"),h(this,"_mode"),h(this,"_init"),h(this,"_renderer"),h(this,"_camera"),h(this,"_scene"),h(this,"onEnd",()=>{var n;(n=this._session)==null||n.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()}),h(this,"_lastTime",0),h(this,"onFrame",(n,r)=>{const s=n-this._lastTime;this.update(n,s),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera)}),h(this,"_objects",[]),this._mode=i,this._init=e,this._session=t,this._session.addEventListener("end",this.onEnd),this._renderer=new Pl({alpha:!0}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(t),this._renderer.xr.enabled=!0,this._camera=new kt,this._scene=new jr,this._scene.fog=new ny(4473924,10,250),this._scene.add(this._camera),this.setupScene()}static get active(){return this._active}static async start(i,e){if(this._active)return console.error("Cannot start a new XR session while one is already active"),null;if(this._requestInFlight)return console.error("Cannot start a new XR session while a request is already in flight"),null;if("xr"in navigator&&navigator.xr){if(!e)return console.error("XRSessionInit must be provided"),null;this._requestInFlight=!0;const t=await navigator.xr.requestSession(i,e);return t.addEventListener("end",()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new CU(i,e,t),this._active):(t.end(),null)}return null}static async handoff(){return this._active?this._active.handoff():null}static async stop(){this._requestInFlight=!1,this._active&&(await this._active.end(),await na(100)),this._active=null}get isAR(){return this._mode==="immersive-ar"}end(){return this._session?this._session.end():Promise.resolve()}async handoff(){if(!this._session)throw new Error("Cannot handoff a session that has already ended");const i={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,i}async onBeforeHandoff(){await na(1e3),this._scene.clear()}setupScene(){this._scene.background=new Se(0),this._scene.add(new Ny(5,10,1118481,1118481));const i=new _p(16777215,1);i.position.set(0,20,0),i.castShadow=!1,this._scene.add(i);const e=new _p(16777215,1);e.position.set(0,-1,0),e.castShadow=!1,this._scene.add(e);const t=new qm(16777215,1,100,1);t.position.set(0,2,0),t.castShadow=!1,t.distance=200,this._scene.add(t);const n=50;for(let r=0;r<100;r++){const s=new ls({color:2236962,metalness:1,roughness:.8});this.isAR&&(s.emissive=new Se(Math.random(),Math.random(),Math.random()),s.emissiveIntensity=Math.random());const o=Ze.random(0,1)>.5?Uu.Sphere:Uu.Cube,a=Fg.createPrimitive(o,{material:s});a.position.x=Ze.random(-n,n),a.position.y=Ze.random(-2,n),a.position.z=Ze.random(-n,n),a.rotation.x=Ze.random(0,Math.PI*2),a.rotation.y=Ze.random(0,Math.PI*2),a.rotation.z=Ze.random(0,Math.PI*2),a.scale.multiplyScalar(.5+Math.random()*10);const l=a.position.distanceTo(this._camera.position)-a.scale.x;l<1&&a.position.multiplyScalar(1+1/l),this._objects.push(a),this._scene.add(a)}}update(i,e){const t=i*4e-4;for(let n=0;n<this._objects.length;n++){const r=this._objects[n];r.position.y+=Math.sin(t+n*.5)*.005,r.rotateY(.002)}}};let Op=CU;h(Op,"_active",null),h(Op,"_requestInFlight",!1);const $n=ee("debugwebxr"),A$=ee("stats");function y$(i){let e=null;const t=i;return t.getAROverlayContainer?e=t.getAROverlayContainer():e=i,e}b$();async function b$(){var i;if(ee("debugasap")){let e=globalThis["needle:XRSession"];if(e instanceof Promise){delete globalThis["needle:XRSession"],ii.addContextCreatedCallback(async t=>{if(!e)return;Mp(!0);const n=await e;if(n){const r=mt.getDefaultSessionInit("immersive-vr");mt.setSession("immersive-vr",n,r,t.context)}else console.error("NeedleXRSession: ASAP session was rejected");e=void 0});return}}if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent)){console.warn("WebXRViewer does not support addEventListener");return}(i=navigator.xr)==null||i.addEventListener("sessiongranted",async()=>{Mp(!0),console.log("Received Session Granted..."),await na(100);const e=sessionStorage.getItem("needle_xr_session_mode"),t=sessionStorage.getItem("needle_xr_session_init")??null,n=t?JSON.parse(t):null;let r=null;if(EU()&&(await Op.start(e||"immersive-vr",n||mt.getDefaultSessionInit("immersive-vr")),await w$(),r=await Op.handoff()),r)mt.setSession(r.mode,r.session,r.init,Lt.Current);else if(e&&t){console.log("Session Granted: Restore last session");const s=JSON.parse(t);mt.start(e,s).catch(o=>console.warn(o))}else mt.start("immersive-vr").catch(s=>console.warn("Session Granted failed:",s))},{once:!0})}}function _$(i,e){sessionStorage.setItem("needle_xr_session_mode",i),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(e))}function x$(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const PM=new Set;ii.registerCallback(bn.ContextCreationStart,async i=>{PM.add(i.context)}),ii.registerCallback(bn.ContextCreated,async i=>{PM.delete(i.context)});function EU(){return PM.size>0}function w$(){return new Promise(i=>{const e=Date.now(),t=setInterval(()=>{(!EU()||Date.now()-e>6e4)&&(clearInterval(t),i())},100)})}yu()&&pt()&&window.addEventListener("keydown",i=>{(i.key==="x"||i.key==="Escape")&&mt.active&&mt.stop()});const Zc=class{constructor(i,e,t,n){h(this,"context"),h(this,"session"),h(this,"mode"),h(this,"controllers",[]),h(this,"_rigScale",1),h(this,"_lastRigScaleUpdate",-1),h(this,"_rigs",[]),h(this,"_viewerHitTestSource",null),h(this,"_defaultRig"),h(this,"_xr_scripts"),h(this,"_xr_update_scripts",[]),h(this,"_inactive_scripts",[]),h(this,"_controllerAdded"),h(this,"_controllerRemoved"),h(this,"_originalCameraWorldPosition"),h(this,"_originalCameraWorldRotation"),h(this,"_originalCameraWorldScale"),h(this,"_originalCameraParent"),h(this,"_mainCamera",null),h(this,"onRendererSessionSet",()=>{var o;this.running&&(this.context.renderer.xr.enabled=!0,this.context.renderer.xr.updateCamera(this.context.mainCamera),(o=this.context.mainCameraComponent)==null||o.applyClearFlags())}),h(this,"onInputSourceAdded",o=>{if(o.targetRayMode==="screen")return;let a=0;for(let c=0;c<this.session.inputSources.length;c++)if(this.session.inputSources[c]===o){a=c;break}if(this.controllers.find(c=>c.inputSource===o)){console.warn("Controller already exists for input source",a);return}$n&&console.log("Adding controller",a);const l=new sM(this,o,a);this._newControllers.push(l)}),h(this,"_ended",!1),h(this,"_newControllers",[]),h(this,"onEnd",o=>{var a,l,c;if(this._ended)return;this._ended=!0,$n&&console.log("XR Session ended"),x$(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,MZ(this.onBefore,Pn.LateUpdate);const u=this.context.pre_render_callbacks.indexOf(this.onBeforeRender);u>=0&&this.context.pre_render_callbacks.splice(u,1);const d=this.context.post_render_callbacks.indexOf(this.onAfterRender);d>=0&&this.context.post_render_callbacks.splice(d,1),this.context.xr=null,this.context.renderer.xr.enabled=!1,this.context.pre_update_oneshot_callbacks.push(()=>{var p;(p=this.context.mainCameraComponent)==null||p.applyClearFlags()});for(const p of Zc._xrEndListeners)p({xr:this});for(let p=0;p<this.controllers.length;p++)this.disconnectInputSource(this.controllers[p].inputSource);for(const p of this._xr_scripts)(a=p?.onLeaveXR)==null||a.call(p,{xr:this});(l=this.sync)==null||l.onExitXR(this),this.context.mainCamera&&((c=this._originalCameraParent)==null||c.add(this.context.mainCamera),this._originalCameraWorldPosition&&Qr(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&So(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&ng(this.context.mainCamera,this._originalCameraWorldScale)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),Mp(!1)}),h(this,"_didStart",!1),h(this,"onBefore",o=>{var a,l,c,u,d,p,f,m;const A=o.xrFrame;if(!A)return;this.context.xr=this,this.context.mainCameraComponent&&this.context.mainCameraComponent!==this._mainCamera&&(this._mainCamera=this.context.mainCameraComponent),((a=this.rig)==null?void 0:a.isActive)==!1&&($n&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig&&(l=this._mainCamera)!=null&&l.gameObject&&((u=(c=this._mainCamera)==null?void 0:c.gameObject)==null?void 0:u.parent)!==this.rig.gameObject&&this.rig.gameObject.add((d=this._mainCamera)==null?void 0:d.gameObject),this.internalUpdateState(),this.applyCustomForward();const v={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const g=[...this.context.new_scripts_xr];for(let y=0;y<g.length;y++){const b=this.context.new_scripts_xr[y];if(!b||b.destroyed||((p=b.supportsXR)==null?void 0:p.call(b,this.mode))==!1){this.context.new_scripts_xr.splice(y,1);continue}if(!b.activeAndEnabled){this.context.new_scripts_xr.splice(y,1),this.markInactive(b);continue}if(this.addScript(b)){this.invokeCallback_EnterXR(b);for(const _ of this.controllers)this.invokeCallback_ControllerAdded(b,_)}}}}else{this._didStart=!0,IZ({session:this});for(const y of Zc._xrStartListeners)y(v);const g=[...this._xr_scripts];$n&&console.log("NeedleXRSession start, handle scripts:",g);for(const y of g){if(y.destroyed){this._script_to_remove.push(y);continue}if(!y.activeAndEnabled){this.markInactive(y);continue}this.invokeCallback_EnterXR(y);for(const b of this.controllers)this.invokeCallback_ControllerAdded(y,b)}}this.syncCameraCullingMask();for(const g of this.controllers)g.onUpdate(A);if(this._newControllers.length>0){const g=[...this._newControllers];this._newControllers.length=0;for(const y of g)if(y.connected){this.controllers.push(y);for(const b of this._xr_scripts){if(b.destroyed){this._script_to_remove.push(b);continue}b.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(b,y)}}this.controllers.sort((y,b)=>y.index-b.index)}for(const g of this._xr_update_scripts){if(g.destroyed===!0){this._script_to_remove.push(g);continue}if(g.activeAndEnabled===!1){this.markInactive(g);continue}g.onUpdateXR&&g.onUpdateXR(v)}if(this.handleInactiveScripts(),this._script_to_remove.length>0){const g=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const y of g)!y.destroyed&&this.running&&((f=y.onLeaveXR)==null||f.call(y,v)),this.removeScript(y)}(m=this.sync)==null||m.onUpdate(this),this.onRenderDebug()}),h(this,"onBeforeRender",()=>{this.context.mainCamera&&this.updateFade(this.context.mainCamera)}),h(this,"onAfterRender",()=>{if(this.onUpdateFade_PostRender(),yu()){const o=this.context.renderer;if(o.xr.isPresenting&&this.context.mainCamera){const a=o.xr.enabled,l=o.getRenderTarget();o.xr.enabled=!1,o.setRenderTarget(null),o.render(this.context.scene,this.context.mainCamera),o.xr.enabled=a,o.setRenderTarget(l)}}}),h(this,"_script_to_remove",[]),h(this,"_camera"),h(this,"_cameraRenderParent",new ge().rotateY(Math.PI)),h(this,"_previousCameraParent"),h(this,"_customforward",!0),h(this,"originalCameraNearPlane"),h(this,"_viewerPose"),h(this,"_transformOrientation",new Me),h(this,"_transformPosition",new S),h(this,"_transition");var r,s;_$(i,n.init),this.session=e,this.mode=i,this.context=t,($n||ee("console"))&&Mp(!0),this._xr_scripts=[...n.scripts],this._xr_update_scripts=this._xr_scripts.filter(o=>typeof o.onUpdateXR=="function"),this._controllerAdded=n.controller_added,this._controllerRemoved=n.controller_removed,Mg(this.onBefore,Pn.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),((r=n.init.optionalFeatures)!=null&&r.includes("hit-test")||(s=n.init.requiredFeatures)!=null&&s.includes("hit-test"))&&e.requestReferenceSpace("viewer").then(o=>{var a,l;return(l=(a=e.requestHitTestSource)==null?void 0:a.call(e,{space:o}))==null?void 0:l.then(c=>this._viewerHitTestSource=c)}).catch(o=>console.warn(o)),this.context.mainCamera&&(this._originalCameraWorldPosition=Rt(this.context.mainCamera,new S),this._originalCameraWorldRotation=xi(this.context.mainCamera,new Me),this._originalCameraWorldScale=ki(this.context.mainCamera,new S),this._originalCameraParent=this.context.mainCamera.parent),this._defaultRig=new SZ,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let o=0;o<e.inputSources.length;o++){const a=e.inputSources[o];if(!a.handedness){console.warn("Input source in xr session has no handedness - ignoring",o);continue}this.onInputSourceAdded(a)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",o=>{for(const a of o.removed)this.disconnectInputSource(a);for(const a of o.added)this.onInputSourceAdded(a)}),this.context.xr=this,this.context.renderer.xr.setSession(this.session).then(this.onRendererSessionSet)}static getXRSync(i){return this._sync||(this._sync=new wU(i)),this._sync}static get currentSessionRequest(){return this._currentSessionRequestMode}static get active(){return this._activeSession}static get activeMode(){var i;return((i=this._activeSession)==null?void 0:i.mode)??null}static get xrSystem(){return"xr"in navigator?navigator.xr:void 0}static isXRSupported(){return Promise.all([this.isVRSupported(),this.isARSupported()]).then(i=>i.some(e=>e)).catch(()=>!1)}static isVRSupported(){return this.isSessionSupported("immersive-vr")}static isARSupported(){return this.isSessionSupported("immersive-ar")}static isSessionSupported(i){var e;return((e=this.xrSystem)==null?void 0:e.isSessionSupported(i).catch(t=>($n&&console.error(t),!1)))??Promise.resolve(!1)}static onSessionRequestStart(i){this._sessionRequestStartListeners.push(i)}static offSessionRequestStart(i){const e=this._sessionRequestStartListeners.indexOf(i);e>=0&&this._sessionRequestStartListeners.splice(e,1)}static onSessionRequestEnd(i){this._sessionRequestEndListeners.push(i)}static offSessionRequestEnd(i){const e=this._sessionRequestEndListeners.indexOf(i);e>=0&&this._sessionRequestEndListeners.splice(e,1)}static onXRSessionStart(i){this._xrStartListeners.push(i)}static offXRSessionStart(i){const e=this._xrStartListeners.indexOf(i);e>=0&&this._xrStartListeners.splice(e,1)}static onXRSessionEnd(i){this._xrEndListeners.push(i)}static offXRSessionEnd(i){const e=this._xrEndListeners.indexOf(i);e>=0&&this._xrEndListeners.splice(e,1)}static onControllerAdded(i){this._controllerAddedListeners.push(i)}static offControllerAdded(i){const e=this._controllerAddedListeners.indexOf(i);e>=0&&this._controllerAddedListeners.splice(e,1)}static onControllerRemoved(i){this._controllerRemovedListeners.push(i)}static offControllerRemoved(i){const e=this._controllerRemovedListeners.indexOf(i);e>=0&&this._controllerRemovedListeners.splice(e,1)}static offerSession(i,e,t){return"xr"in navigator&&navigator.xr&&"offerSession"in navigator.xr?(typeof navigator.xr.offerSession=="function"&&(console.log("WebXR offerSession is available - requesting mode: "+i),e=="default"&&(e=this.getDefaultSessionInit(i)),navigator.xr.offerSession(i,{...e}).then(n=>Zc.setSession(i,n,e,t)).catch(n=>{console.log("XRSession offer rejected (perhaps because another call to offerSession was made or a call to requestSession was made)")})),!0):!1}static getDefaultSessionInit(i){switch(i){case"immersive-ar":return{optionalFeatures:["anchors","local-floor","hand-tracking","layers","dom-overlay","hit-test"]};case"immersive-vr":return{optionalFeatures:["local-floor","bounded-floor","hand-tracking","high-fixed-foveation-level","layers"]};default:return console.warn("No default session init for mode",i),{}}}static async start(i,e,t){var n,r,s,o;if(pt()&&ee("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await Op.start(i,e||Zc.getDefaultSessionInit(i)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),($n||pt())&&Qi("A XRSession is already being requested"),this._currentSessionRequest.then(()=>this._activeSession);if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;if(t||(t=Lt.Current),t||(t=ii.All[0]),!t)throw new Error("No Needle Engine Context found");switch(e||(e={}),i){case"immersive-ar":{if(await((n=this.xrSystem)==null?void 0:n.isSessionSupported("immersive-ar"))!==!0)return console.error(i+" is not supported by this browser."),null;const c=this.getDefaultSessionInit(i),u=y$(t.domElement);u&&!qy()&&(c.domOverlay={root:u},c.optionalFeatures.push("dom-overlay")),e={...c,...e}}break;case"immersive-vr":{if(await((r=this.xrSystem)==null?void 0:r.isSessionSupported("immersive-vr"))!==!0)return console.error(i+" is not supported by this browser."),null;e={...this.getDefaultSessionInit(i),...e}}break;default:console.warn("No default session init for mode",i);break}await Op.stop();const a=i=="immersive-ar"?t.scripts_immersive_ar:t.scripts_immersive_vr;$n?console.log(`%cRequesting ${i} session`,"font-weight:bold;",e,a):console.log(`%cRequesting ${i} session`,"font-weight:bold;");for(const c of a)c.onBeforeXR&&c.onBeforeXR(i,e);for(const c of this._sessionRequestStartListeners)c({mode:i,init:e});$n&&$i("Requesting "+i+" session ("+Date.now()+")"),this._currentSessionRequest=(s=navigator.xr)==null?void 0:s.requestSession(i,e),this._currentSessionRequestMode=i;const l=await((o=this._currentSessionRequest)==null?void 0:o.catch(c=>{console.error(c,"Code: "+c.code),c.code===9&&Qi("Make sure your device has the required permissions (e.g. camera access)"),console.log("If the specified XR configuration is not supported (e.g. entering AR doesnt work) - make sure you access the website on a secure connection (HTTPS) and your device has the required permissions (e.g. camera access)"),location.protocol==="http:"&&Qi("XR requires a secure connection (HTTPS)")}));this._currentSessionRequest=void 0,this._currentSessionRequestMode=null;for(const c of this._sessionRequestEndListeners)c({mode:i,init:e,newSession:l||null});return l?this.setSession(i,l,e,t):(console.warn("XR Session request was rejected"),null)}static setSession(i,e,t,n){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const r=i=="immersive-ar"?n.scripts_immersive_ar:n.scripts_immersive_vr;return this._activeSession=new Zc(i,e,n,{scripts:r,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:t}),e.addEventListener("end",this.onEnd),$n?console.log(`%cStarted ${i} session`,"font-weight:bold;",r):console.log(`%cStarted ${i} session`,"font-weight:bold;"),this._activeSession}static stop(){var i;(i=this._activeSession)==null||i.end()}get sync(){return Zc._sync}get running(){return!this._ended&&this.session!=null}get interactionMode(){return this.session.interactionMode}get visibilityState(){return this.session.visibilityState}get environmentBlendMode(){return this.session.environmentBlendMode}get frame(){return this.context.xrFrame}get leftController(){return this.controllers.find(i=>i.isLeft)}get rightController(){return this.controllers.find(i=>i.isRight)}getController(i){return typeof i=="number"?this.controllers[i]||null:this.controllers.find(e=>e.side===i)||null}get isPassThrough(){return!!(this.environmentBlendMode!=="opaque"&&this.interactionMode==="world-space"||this.mode==="immersive-ar"&&this.environmentBlendMode!=="opaque"&&this.controllers.some(i=>i.inputSource.targetRayMode==="tracked-pointer")||pt()&&yu()&&this.mode==="immersive-ar")}get isAR(){return this.mode==="immersive-ar"}get isVR(){return this.mode==="immersive-vr"}get isScreenBasedAR(){return this.isAR&&!this.isPassThrough}get posePosition(){return this._transformPosition}get poseOrientation(){return this._transformOrientation}get referenceSpace(){return this.context.renderer.xr.getReferenceSpace()}get viewerPose(){return this._viewerPose}get isTrackingImages(){if(this.frame&&"getImageTrackingResults"in this.frame&&typeof this.frame.getImageTrackingResults=="function")try{const i=this.frame.getImageTrackingResults();for(const e of i)if(e.trackingState==="tracked")return!0}catch{return!1}return!1}get rig(){const i=this._rigs[0]??null;return i!=null&&i.gameObject&&zu(i.gameObject)||i?.isActive===!1?(this.updateActiveXRRig(),this._rigs[0]??null):i}get rigScale(){return this._rigs[0]?(this._lastRigScaleUpdate!==this.context.time.frame&&(this._lastRigScaleUpdate=this.context.time.frame,this._rigScale=this._rigs[0].gameObject.worldScale.x),this._rigScale):1}addRig(i){this._rigs.indexOf(i)>=0||(i.priority===void 0&&(i.priority=0),this._rigs.push(i),this.updateActiveXRRig())}removeRig(i){const e=this._rigs.indexOf(i);e!==-1&&(this._rigs.splice(e,1),this.updateActiveXRRig())}setRigActive(i){const e=this._rigs.indexOf(i);this._rigs.splice(e,1),this._rigs.unshift(i),this.updateActiveXRRig()}updateActiveXRRig(){const i=this._rigs[0]??null;this._defaultRig.gameObject.parent!==this.context.scene&&this.context.scene.add(this._defaultRig.gameObject),this._defaultRig.gameObject.visible=!0,this._rigs.includes(this._defaultRig)||this._rigs.push(this._defaultRig);let e=this._rigs[0];e&&e.priority===void 0&&(e.priority=0);for(let t=1;t<this._rigs.length;t++){const n=this._rigs[t];if(n.isActive){if(zu(n.gameObject)){this._rigs.splice(t,1),t--;continue}(!e||e.isActive===!1||n.priority!==void 0&&n.priority>e.priority)&&(e=n)}}if(i!==e){const t=this._rigs.indexOf(e);t>=0&&this._rigs.splice(t,1),this._rigs.unshift(e)}$n&&(i===e?console.log("Updated Active XR Rig:",e,"prev:",i):console.log("Updated Active XRRig:",e," (the same as before)"))}getHitTest(i){if(i)return this.getControllerHitTest(i);if(!this._viewerHitTestSource)return null;const e=this._viewerHitTestSource,t=this.frame.getHitTestResults(e);if(t.length>0){const n=t[0];return this.convertHitTestResult(n)}return null}getControllerHitTest(i){const e=i.hitTestSource;if(!e)return null;const t=this.frame.getHitTestResultsForTransientInput(e);for(const n of t)if(n.inputSource===i.inputSource)for(const r of n.results)return this.convertHitTestResult(r);return null}convertHitTestResult(i){const e=this.context.renderer.xr.getReferenceSpace(),t=e&&i.getPose(e);if(t){const n=Zi(t.transform.position),r=wu(t.transform.orientation),s=this.context.mainCamera;if(s?.parent!==this._cameraRenderParent&&n.applyMatrix4(Fb),s!=null&&s.parent){n.applyMatrix4(s.parent.matrixWorld),r.multiply(Mo);const o=xi(s.parent);o.premultiply(Mo),r.premultiply(o)}return{hit:i,position:n,quaternion:r}}return null}convertSpace(i){const e=Zi(i.position);e.applyMatrix4(Fb);const t=wu(i.orientation);return t.premultiply(Mo),{position:e,quaternion:t}}disconnectInputSource(i){const e=(t,n,r)=>{if(t.inputSource===i){$n&&console.log("Disconnecting controller",t.index),this.controllers.splice(r,1),this.invokeControllerEvent(t,this._controllerRemoved,"removed");const s={xr:this,controller:t,change:"removed"};for(const o of this._xr_scripts)o.onXRControllerRemoved&&o.onXRControllerRemoved(s);t.onDisconnected()}};for(let t=this.controllers.length-1;t>=0;t--){const n=this.controllers[t];e(n,this.controllers,t)}for(let t=this._newControllers.length-1;t>=0;t--){const n=this._newControllers[t];e(n,this._newControllers,t)}}end(){this._ended||this.session.end().catch(i=>console.warn(i))}onRenderDebug(){if($n)for(const i of this.controllers)i.onRenderDebug();if(($n||A$)&&this.rig){const i=this.rig.gameObject.worldPosition,e=this.rig.gameObject.worldForward;i.add(e.multiplyScalar(1.5));const t=this.rig.gameObject.worldUp;i.add(t.multiplyScalar(2.5));let n="";if(n+=this.context.time.smoothedFps.toFixed(1),$n)for(const r of this.controllers)n+=`
4964
+ ${r.hand?"hand":"ctrl"} ${r.inputSource.handedness}[${r.index}] con:${r.connected} tr:${r.isTracking}`;Ct.DrawLabel(i,n)}}addScript(i){return this._xr_scripts.includes(i)?!1:($n&&console.log("Register new XRScript",i),this._xr_scripts.push(i),typeof i.onUpdateXR=="function"&&this._xr_update_scripts.push(i),!0)}markInactive(i){if(!(this._inactive_scripts.indexOf(i)>=0)){this.removeScript(i,!1),this._inactive_scripts.push(i);for(const e of this.controllers)this.invokeCallback_ControllerRemoved(i,e);this.invokeCallback_LeaveXR(i)}}handleInactiveScripts(){if(this._inactive_scripts.length>0)for(let i=this._inactive_scripts.length-1;i>=0;i--){const e=this._inactive_scripts[i];if(e.activeAndEnabled){this._inactive_scripts.splice(i,1),this.addScript(e),this.invokeCallback_EnterXR(e);for(const t of this.controllers)this.invokeCallback_ControllerAdded(e,t)}}}removeScript(i,e=!0){$n&&console.log("Remove XRScript",i);const t=this._xr_scripts.indexOf(i);t>=0&&this._xr_scripts.splice(t,1);const n=this._xr_update_scripts.indexOf(i);if(n>=0&&this._xr_update_scripts.splice(n,1),e){const r=this._inactive_scripts.indexOf(i);r>=0&&this._inactive_scripts.splice(r,1)}}invokeCallback_EnterXR(i){i.onEnterXR&&i.onEnterXR({xr:this})}invokeCallback_ControllerAdded(i,e){i.onXRControllerAdded&&i.onXRControllerAdded({xr:this,controller:e,change:"added"})}invokeCallback_ControllerRemoved(i,e){i.onXRControllerRemoved&&i.onXRControllerRemoved({xr:this,controller:e,change:"removed"})}invokeCallback_LeaveXR(i){i.onLeaveXR&&!i.destroyed&&i.onLeaveXR({xr:this})}syncCameraCullingMask(){var i;const e=this.context.xrCamera,t=(i=this.context.mainCameraComponent)==null?void 0:i.cullingMask;if(e&&t!==void 0){for(const n of e.cameras)n.layers.mask=t;e.layers.mask=t}else if(e){for(const n of e.cameras)n.layers.enableAll();e.layers.enableAll()}}invokeControllerEvent(i,e,t){for(let n=e.length-1;n>=0;n--){const r=e[n];if(r)try{r({xr:this,controller:i,change:t})}catch(s){console.error(s)}}}applyCustomForward(){var i;if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,(i=this._previousCameraParent)==null||i.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);let e=.02;if(this.rig){const t=ki(this.rig.gameObject);e*=t.x}this._camera instanceof kt&&this._camera.near>e&&(this.originalCameraNearPlane=this._camera.near,this._camera.near=e)}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof kt&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane)}internalUpdateState(){const i=this.context.renderer.xr.getReferenceSpace();if(!i){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(i),this._viewerPose){const e=this._viewerPose.transform;this._transformPosition.set(e.position.x,e.position.y,e.position.z),this._transformOrientation.set(e.orientation.x,e.orientation.y,e.orientation.z,e.orientation.w)}}get transition(){return this._transition||(this._transition=new SU),this._transition}fadeTransition(){return this._transition||(this._transition=new SU),this._transition.fadeTransition()}updateFade(i){this._transition&&i instanceof kt&&this._transition.update(i,this.context.time.deltaTime)}onUpdateFade_PostRender(){var i;(i=this._transition)==null||i.remove()}};let mt=Zc;h(mt,"_sync",null),h(mt,"_currentSessionRequestMode",null),h(mt,"_currentSessionRequest"),h(mt,"_activeSession"),h(mt,"_sessionRequestStartListeners",[]),h(mt,"_sessionRequestEndListeners",[]),h(mt,"_xrStartListeners",[]),h(mt,"_xrEndListeners",[]),h(mt,"_controllerAddedListeners",[]),h(mt,"_controllerRemovedListeners",[]),h(mt,"onEnd",()=>{$n&&console.log("XR Session ended"),Zc._activeSession=null});const BM=ee("debugwebxr");class MU{static tryFindAvatarObjects(e,t,n){if(n.head&&n.leftHand&&n.rightHand)return;const r=e.name.toLocaleLowerCase();!n.head&&r.includes("head")&&(BM&&console.log("FOUND AVATAR HEAD",e.name),n.head=new ni("",t,e)),r.includes("hand")&&(!n.leftHand&&r.includes("left")&&(BM&&console.log("FOUND AVATAR LEFT HAND",e.name),n.leftHand=new ni("",t,e)),!n.rightHand&&r.includes("right")&&(BM&&console.log("FOUND AVATAR RIGHT HAND",e.name),n.rightHand=new ni("",t,e)));for(let s=0;s<e.children.length;s++){if(n.head&&n.leftHand&&n.rightHand)return;const o=e.children[s];this.tryFindAvatarObjects(o,t,n)}}}var Zb=(i=>(i.Visible="application-visible",i.Hidden="application-hidden",i.MuteChanged="application-mutechanged",i))(Zb||{});let $b=!1;const e_=[];function kp(){if($b)return;pt()&&console.log("User interaction registered: audio can now be played"),$b=!0;const i=[...e_];e_.length=0,i.forEach(e=>e())}document.addEventListener("pointerdown",kp),document.addEventListener("click",kp),document.addEventListener("dragstart",kp),document.addEventListener("touchstart",kp),document.addEventListener("keydown",kp),mt.onXRSessionStart(()=>{kp()});class Ng extends EventTarget{constructor(e){super(),h(this,"_mute",!1),h(this,"context"),h(this,"_isVisible",!0),this.context=e,window.addEventListener("visibilitychange",this.onVisiblityChanged.bind(this),!1)}static get userInteractionRegistered(){return $b}static registerWaitForAllowAudio(e){if(e!==null){if($b){e();return}e_.indexOf(e)===-1&&e_.push(e)}}get muted(){return this._mute}set muted(e){e!==this._mute&&(this._mute=e,this.dispatchEvent(new Event("application-mutechanged")))}get hasFocus(){return document.hasFocus()}get isVisible(){return this._isVisible}onVisiblityChanged(e){switch(e.target.visibilityState){case"hidden":this._isVisible=!1,this.dispatchEvent(new Event("application-hidden"));break;case"visible":this._isVisible=!0,this.dispatchEvent(new Event("application-visible"));break}}}function*TU(i,e=null){const t=e?e.time:Lt.Current.time,n=t.time;for(;t.time-n<i;)yield}function*S$(i){for(let e=0;e<i;e++)yield}function*IU(i){let e=!0;for(i.then(()=>e=!1),i.catch(()=>e=!1);e;)yield}/*!
4965
4965
  fflate - fast JavaScript compression/decompression
4966
4966
  <https://101arrowz.github.io/fflate>
4967
4967
  Licensed under MIT. https://github.com/101arrowz/fflate/blob/master/LICENSE
4968
4968
  version 0.6.9
4969
- */var R3=function(i){return URL.createObjectURL(new Blob([i],{type:"text/javascript"}))};try{URL.revokeObjectURL(R3(""))}catch{R3=function(i){return"data:application/javascript;charset=UTF-8,"+encodeURI(i)}}var Rn=Uint8Array,fs=Uint16Array,Lp=Uint32Array,t_=new Rn([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),i_=new Rn([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),DM=new Rn([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),P3=function(i,e){for(var t=new fs(31),n=0;n<31;++n)t[n]=e+=1<<i[n-1];for(var r=new Lp(t[30]),n=1;n<30;++n)for(var s=t[n];s<t[n+1];++s)r[s]=s-t[n]<<5|n;return[t,r]},B3=P3(t_,2),D3=B3[0],OM=B3[1];D3[28]=258,OM[258]=28;for(var O3=P3(i_,0),C$=O3[0],k3=O3[1],kM=new fs(32768),Ni=0;Ni<32768;++Ni){var $c=(Ni&43690)>>>1|(Ni&21845)<<1;$c=($c&52428)>>>2|($c&13107)<<2,$c=($c&61680)>>>4|($c&3855)<<4,kM[Ni]=(($c&65280)>>>8|($c&255)<<8)>>>1}for(var Qa=function(i,e,t){for(var n=i.length,r=0,s=new fs(e);r<n;++r)++s[i[r]-1];var o=new fs(e);for(r=0;r<e;++r)o[r]=o[r-1]+s[r-1]<<1;var a;if(t){a=new fs(1<<e);var l=15-e;for(r=0;r<n;++r)if(i[r])for(var c=r<<4|i[r],u=e-i[r],d=o[i[r]-1]++<<u,p=d|(1<<u)-1;d<=p;++d)a[kM[d]>>>l]=c}else for(a=new fs(n),r=0;r<n;++r)i[r]&&(a[r]=kM[o[i[r]-1]++]>>>15-i[r]);return a},eh=new Rn(288),Ni=0;Ni<144;++Ni)eh[Ni]=8;for(var Ni=144;Ni<256;++Ni)eh[Ni]=9;for(var Ni=256;Ni<280;++Ni)eh[Ni]=7;for(var Ni=280;Ni<288;++Ni)eh[Ni]=8;for(var zg=new Rn(32),Ni=0;Ni<32;++Ni)zg[Ni]=5;var E$=Qa(eh,9,0),M$=Qa(eh,9,1),T$=Qa(zg,5,0),I$=Qa(zg,5,1),LM=function(i){for(var e=i[0],t=1;t<i.length;++t)i[t]>e&&(e=i[t]);return e},ha=function(i,e,t){var n=e/8|0;return(i[n]|i[n+1]<<8)>>(e&7)&t},UM=function(i,e){var t=e/8|0;return(i[t]|i[t+1]<<8|i[t+2]<<16)>>(e&7)},FM=function(i){return(i/8|0)+(i&7&&1)},NM=function(i,e,t){(e==null||e<0)&&(e=0),(t==null||t>i.length)&&(t=i.length);var n=new(i instanceof fs?fs:i instanceof Lp?Lp:Rn)(t-e);return n.set(i.subarray(e,t)),n},R$=function(i,e,t){var n=i.length;if(!n||t&&!t.l&&n<5)return e||new Rn(0);var r=!e||t,s=!t||t.i;t||(t={}),e||(e=new Rn(n*3));var o=function(Be){var We=e.length;if(Be>We){var Je=new Rn(Math.max(We*2,Be));Je.set(e),e=Je}},a=t.f||0,l=t.p||0,c=t.b||0,u=t.l,d=t.d,p=t.m,f=t.n,m=n*8;do{if(!u){t.f=a=ha(i,l,1);var A=ha(i,l+1,3);if(l+=3,A)if(A==1)u=M$,d=I$,p=9,f=5;else if(A==2){var v=ha(i,l,31)+257,g=ha(i,l+10,15)+4,y=v+ha(i,l+5,31)+1;l+=14;for(var b=new Rn(y),_=new Rn(19),E=0;E<g;++E)_[DM[E]]=ha(i,l+E*3,7);l+=g*3;for(var I=LM(_),T=(1<<I)-1,M=Qa(_,I,1),E=0;E<y;){var D=M[ha(i,l,T)];l+=D&15;var C=D>>>4;if(C<16)b[E++]=C;else{var P=0,G=0;for(C==16?(G=3+ha(i,l,3),l+=2,P=b[E-1]):C==17?(G=3+ha(i,l,7),l+=3):C==18&&(G=11+ha(i,l,127),l+=7);G--;)b[E++]=P}}var Q=b.subarray(0,v),k=b.subarray(v);p=LM(Q),f=LM(k),u=Qa(Q,p,1),d=Qa(k,f,1)}else throw"invalid block type";else{var C=FM(l)+4,W=i[C-4]|i[C-3]<<8,U=C+W;if(U>n){if(s)throw"unexpected EOF";break}r&&o(c+W),e.set(i.subarray(C,U),c),t.b=c+=W,t.p=l=U*8;continue}if(l>m){if(s)throw"unexpected EOF";break}}r&&o(c+131072);for(var F=(1<<p)-1,z=(1<<f)-1,Z=l;;Z=l){var P=u[UM(i,l)&F],K=P>>>4;if(l+=P&15,l>m){if(s)throw"unexpected EOF";break}if(!P)throw"invalid length/literal";if(K<256)e[c++]=K;else if(K==256){Z=l,u=null;break}else{var se=K-254;if(K>264){var E=K-257,Ae=t_[E];se=ha(i,l,(1<<Ae)-1)+D3[E],l+=Ae}var Re=d[UM(i,l)&z],ne=Re>>>4;if(!Re)throw"invalid distance";l+=Re&15;var k=C$[ne];if(ne>3){var Ae=i_[ne];k+=UM(i,l)&(1<<Ae)-1,l+=Ae}if(l>m){if(s)throw"unexpected EOF";break}r&&o(c+131072);for(var ye=c+se;c<ye;c+=4)e[c]=e[c-k],e[c+1]=e[c+1-k],e[c+2]=e[c+2-k],e[c+3]=e[c+3-k];c=ye}}t.l=u,t.p=Z,t.b=c,u&&(a=1,t.m=p,t.d=d,t.n=f)}while(!a);return c==e.length?e:NM(e,0,c)},Xl=function(i,e,t){t<<=e&7;var n=e/8|0;i[n]|=t,i[n+1]|=t>>>8},jg=function(i,e,t){t<<=e&7;var n=e/8|0;i[n]|=t,i[n+1]|=t>>>8,i[n+2]|=t>>>16},zM=function(i,e){for(var t=[],n=0;n<i.length;++n)i[n]&&t.push({s:n,f:i[n]});var r=t.length,s=t.slice();if(!r)return[GM,0];if(r==1){var o=new Rn(t[0].s+1);return o[t[0].s]=1,[o,1]}t.sort(function(E,I){return E.f-I.f}),t.push({s:-1,f:25001});var a=t[0],l=t[1],c=0,u=1,d=2;for(t[0]={s:-1,f:a.f+l.f,l:a,r:l};u!=r-1;)a=t[t[c].f<t[d].f?c++:d++],l=t[c!=u&&t[c].f<t[d].f?c++:d++],t[u++]={s:-1,f:a.f+l.f,l:a,r:l};for(var p=s[0].s,n=1;n<r;++n)s[n].s>p&&(p=s[n].s);var f=new fs(p+1),m=jM(t[u-1],f,0);if(m>e){var n=0,A=0,v=m-e,g=1<<v;for(s.sort(function(I,T){return f[T.s]-f[I.s]||I.f-T.f});n<r;++n){var y=s[n].s;if(f[y]>e)A+=g-(1<<m-f[y]),f[y]=e;else break}for(A>>>=v;A>0;){var b=s[n].s;f[b]<e?A-=1<<e-f[b]++-1:++n}for(;n>=0&&A;--n){var _=s[n].s;f[_]==e&&(--f[_],++A)}m=e}return[new Rn(f),m]},jM=function(i,e,t){return i.s==-1?Math.max(jM(i.l,e,t+1),jM(i.r,e,t+1)):e[i.s]=t},L3=function(i){for(var e=i.length;e&&!i[--e];);for(var t=new fs(++e),n=0,r=i[0],s=1,o=function(l){t[n++]=l},a=1;a<=e;++a)if(i[a]==r&&a!=e)++s;else{if(!r&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(r),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(r);s=1,r=i[a]}return[t.subarray(0,n),e]},Gg=function(i,e){for(var t=0,n=0;n<e.length;++n)t+=i[n]*e[n];return t},n_=function(i,e,t){var n=t.length,r=FM(e+2);i[r]=n&255,i[r+1]=n>>>8,i[r+2]=i[r]^255,i[r+3]=i[r+1]^255;for(var s=0;s<n;++s)i[r+s+4]=t[s];return(r+4+n)*8},U3=function(i,e,t,n,r,s,o,a,l,c,u){Xl(e,u++,t),++r[256];for(var d=zM(r,15),p=d[0],f=d[1],m=zM(s,15),A=m[0],v=m[1],g=L3(p),y=g[0],b=g[1],_=L3(A),E=_[0],I=_[1],T=new fs(19),M=0;M<y.length;++M)T[y[M]&31]++;for(var M=0;M<E.length;++M)T[E[M]&31]++;for(var D=zM(T,7),C=D[0],P=D[1],G=19;G>4&&!C[DM[G-1]];--G);var Q=c+5<<3,k=Gg(r,eh)+Gg(s,zg)+o,W=Gg(r,p)+Gg(s,A)+o+14+3*G+Gg(T,C)+(2*T[16]+3*T[17]+7*T[18]);if(Q<=k&&Q<=W)return n_(e,u,i.subarray(l,l+c));var U,F,z,Z;if(Xl(e,u,1+(W<k)),u+=2,W<k){U=Qa(p,f,0),F=p,z=Qa(A,v,0),Z=A;var K=Qa(C,P,0);Xl(e,u,b-257),Xl(e,u+5,I-1),Xl(e,u+10,G-4),u+=14;for(var M=0;M<G;++M)Xl(e,u+3*M,C[DM[M]]);u+=3*G;for(var se=[y,E],Ae=0;Ae<2;++Ae)for(var Re=se[Ae],M=0;M<Re.length;++M){var ne=Re[M]&31;Xl(e,u,K[ne]),u+=C[ne],ne>15&&(Xl(e,u,Re[M]>>>5&127),u+=Re[M]>>>12)}}else U=E$,F=eh,z=T$,Z=zg;for(var M=0;M<a;++M)if(n[M]>255){var ne=n[M]>>>18&31;jg(e,u,U[ne+257]),u+=F[ne+257],ne>7&&(Xl(e,u,n[M]>>>23&31),u+=t_[ne]);var ye=n[M]&31;jg(e,u,z[ye]),u+=Z[ye],ye>3&&(jg(e,u,n[M]>>>5&8191),u+=i_[ye])}else jg(e,u,U[n[M]]),u+=F[n[M]];return jg(e,u,U[256]),u+F[256]},P$=new Lp([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),GM=new Rn(0),B$=function(i,e,t,n,r,s){var o=i.length,a=new Rn(n+o+5*(1+Math.ceil(o/7e3))+r),l=a.subarray(n,a.length-r),c=0;if(!e||o<8)for(var u=0;u<=o;u+=65535){var d=u+65535;d<o?c=n_(l,c,i.subarray(u,d)):(l[u]=s,c=n_(l,c,i.subarray(u,o)))}else{for(var p=P$[e-1],f=p>>>13,m=p&8191,A=(1<<t)-1,v=new fs(32768),g=new fs(A+1),y=Math.ceil(t/3),b=2*y,_=function(we){return(i[we]^i[we+1]<<y^i[we+2]<<b)&A},E=new Lp(25e3),I=new fs(288),T=new fs(32),M=0,D=0,u=0,C=0,P=0,G=0;u<o;++u){var Q=_(u),k=u&32767,W=g[Q];if(v[k]=W,g[Q]=k,P<=u){var U=o-u;if((M>7e3||C>24576)&&U>423){c=U3(i,l,0,E,I,T,D,C,G,u-G,c),C=M=D=0,G=u;for(var F=0;F<286;++F)I[F]=0;for(var F=0;F<30;++F)T[F]=0}var z=2,Z=0,K=m,se=k-W&32767;if(U>2&&Q==_(u-se))for(var Ae=Math.min(f,U)-1,Re=Math.min(32767,u),ne=Math.min(258,U);se<=Re&&--K&&k!=W;){if(i[u+z]==i[u+z-se]){for(var ye=0;ye<ne&&i[u+ye]==i[u+ye-se];++ye);if(ye>z){if(z=ye,Z=se,ye>Ae)break;for(var Be=Math.min(se,ye-2),We=0,F=0;F<Be;++F){var Je=u-se+F+32768&32767,De=v[Je],it=Je-De+32768&32767;it>We&&(We=it,W=Je)}}}k=W,W=v[k],se+=k-W+32768&32767}if(Z){E[C++]=268435456|OM[z]<<18|k3[Z];var pe=OM[z]&31,V=k3[Z]&31;D+=t_[pe]+i_[V],++I[257+pe],++T[V],P=u+z,++M}else E[C++]=i[u],++I[i[u]]}}c=U3(i,l,s,E,I,T,D,C,G,u-G,c),!s&&c&7&&(c=n_(l,c+1,GM))}return NM(a,0,n+FM(c)+r)},D$=function(){for(var i=new Lp(256),e=0;e<256;++e){for(var t=e,n=9;--n;)t=(t&1&&3988292384)^t>>>1;i[e]=t}return i}(),O$=function(){var i=-1;return{p:function(e){for(var t=i,n=0;n<e.length;++n)t=D$[t&255^e[n]]^t>>>8;i=t},d:function(){return~i}}},k$=function(i,e,t,n,r){return B$(i,e.level==null?6:e.level,e.mem==null?Math.ceil(Math.max(8,Math.min(13,Math.log(i.length)))*1.5):12+e.mem,t,n,!r)},F3=function(i,e){var t={};for(var n in i)t[n]=i[n];for(var n in e)t[n]=e[n];return t},yr=function(i,e,t){for(;t;++e)i[e]=t,t>>>=8},L$=function(i){if((i[0]&15)!=8||i[0]>>>4>7||(i[0]<<8|i[1])%31)throw"invalid zlib data";if(i[1]&32)throw"invalid zlib data: preset dictionaries not supported"};function U$(i,e){return k$(i,e||{},0,0)}function r_(i,e){return R$((L$(i),i.subarray(2,-4)),e)}var N3=function(i,e,t,n){for(var r in i){var s=i[r],o=e+r;s instanceof Rn?t[o]=[s,n]:Array.isArray(s)?t[o]=[s[0],F3(n,s[1])]:N3(s,o+"/",t,n)}},z3=typeof TextEncoder<"u"&&new TextEncoder,F$=typeof TextDecoder<"u"&&new TextDecoder,N$=0;try{F$.decode(GM,{stream:!0}),N$=1}catch{}function s_(i,e){if(e){for(var t=new Rn(i.length),n=0;n<i.length;++n)t[n]=i.charCodeAt(n);return t}if(z3)return z3.encode(i);for(var r=i.length,s=new Rn(i.length+(i.length>>1)),o=0,a=function(d){s[o++]=d},n=0;n<r;++n){if(o+5>s.length){var l=new Rn(o+8+(r-n<<1));l.set(s),s=l}var c=i.charCodeAt(n);c<128||e?a(c):c<2048?(a(192|c>>6),a(128|c&63)):c>55295&&c<57344?(c=65536+(c&1047552)|i.charCodeAt(++n)&1023,a(240|c>>18),a(128|c>>12&63),a(128|c>>6&63),a(128|c&63)):(a(224|c>>12),a(128|c>>6&63),a(128|c&63))}return NM(s,0,o)}var QM=function(i){var e=0;if(i)for(var t in i){var n=i[t].length;if(n>65535)throw"extra field too long";e+=n+4}return e},j3=function(i,e,t,n,r,s,o,a){var l=n.length,c=t.extra,u=a&&a.length,d=QM(c);yr(i,e,o!=null?33639248:67324752),e+=4,o!=null&&(i[e++]=20,i[e++]=t.os),i[e]=20,e+=2,i[e++]=t.flag<<1|(s==null&&8),i[e++]=r&&8,i[e++]=t.compression&255,i[e++]=t.compression>>8;var p=new Date(t.mtime==null?Date.now():t.mtime),f=p.getFullYear()-1980;if(f<0||f>119)throw"date not in range 1980-2099";if(yr(i,e,f<<25|p.getMonth()+1<<21|p.getDate()<<16|p.getHours()<<11|p.getMinutes()<<5|p.getSeconds()>>>1),e+=4,s!=null&&(yr(i,e,t.crc),yr(i,e+4,s),yr(i,e+8,t.size)),yr(i,e+12,l),yr(i,e+14,d),e+=16,o!=null&&(yr(i,e,u),yr(i,e+6,t.attrs),yr(i,e+10,o),e+=14),i.set(n,e),e+=l,d)for(var m in c){var A=c[m],v=A.length;yr(i,e,+m),yr(i,e+2,v),i.set(A,e+4),e+=4+v}return u&&(i.set(a,e),e+=u),e},z$=function(i,e,t,n,r){yr(i,e,101010256),yr(i,e+8,t),yr(i,e+10,t),yr(i,e+12,n),yr(i,e+16,r)};function j$(i,e){e||(e={});var t={},n=[];N3(i,"",t,e);var r=0,s=0;for(var o in t){var a=t[o],l=a[0],c=a[1],u=c.level==0?0:8,d=s_(o),p=d.length,f=c.comment,m=f&&s_(f),A=m&&m.length,v=QM(c.extra);if(p>65535)throw"filename too long";var g=u?U$(l,c):l,y=g.length,b=O$();b.p(l),n.push(F3(c,{size:l.length,crc:b.d(),c:g,f:d,m,u:p!=o.length||m&&f.length!=A,o:r,compression:u})),r+=30+p+v+y,s+=76+2*(p+v)+(A||0)+y}for(var _=new Rn(s+22),E=r,I=s-r,T=0;T<n.length;++T){var d=n[T];j3(_,d.o,d,d.f,d.u,d.c.length);var M=30+d.f.length+QM(d.extra);_.set(d.c,d.o+M),j3(_,r,d,d.f,d.u,d.c.length,d.o,d.m),r+=16+M+(d.m?d.m.length:0)}return z$(_,r,n.length,I,E),_}class o_ extends ZS{constructor(e){super(e),this.type=Ji}parse(e){const t=Math.pow(2.7182818,2.2);function n(w,R){let N=0;for(let L=0;L<65536;++L)(L==0||w[L>>3]&1<<(L&7))&&(R[N++]=L);const J=N-1;for(;N<65536;)R[N++]=0;return J}function r(w){for(let R=0;R<16384;R++)w[R]={},w[R].len=0,w[R].lit=0,w[R].p=null}const s={l:0,c:0,lc:0};function o(w,R,N,J,L){for(;N<w;)R=R<<8|V(J,L),N+=8;N-=w,s.l=R>>N&(1<<w)-1,s.c=R,s.lc=N}const a=new Array(59);function l(w){for(let N=0;N<=58;++N)a[N]=0;for(let N=0;N<65537;++N)a[w[N]]+=1;let R=0;for(let N=58;N>0;--N){const J=R+a[N]>>1;a[N]=R,R=J}for(let N=0;N<65537;++N){const J=w[N];J>0&&(w[N]=J|a[J]++<<6)}}function c(w,R,N,J,L,X){const H=R;let oe=0,le=0;for(;J<=L;J++){if(H.value-R.value>N)return!1;o(6,oe,le,w,H);const ve=s.l;if(oe=s.c,le=s.lc,X[J]=ve,ve==63){if(H.value-R.value>N)throw new Error("Something wrong with hufUnpackEncTable");o(8,oe,le,w,H);let Ee=s.l+6;if(oe=s.c,le=s.lc,J+Ee>L+1)throw new Error("Something wrong with hufUnpackEncTable");for(;Ee--;)X[J++]=0;J--}else if(ve>=59){let Ee=ve-59+2;if(J+Ee>L+1)throw new Error("Something wrong with hufUnpackEncTable");for(;Ee--;)X[J++]=0;J--}}l(X)}function u(w){return w&63}function d(w){return w>>6}function p(w,R,N,J){for(;R<=N;R++){const L=d(w[R]),X=u(w[R]);if(L>>X)throw new Error("Invalid table entry");if(X>14){const H=J[L>>X-14];if(H.len)throw new Error("Invalid table entry");if(H.lit++,H.p){const oe=H.p;H.p=new Array(H.lit);for(let le=0;le<H.lit-1;++le)H.p[le]=oe[le]}else H.p=new Array(1);H.p[H.lit-1]=R}else if(X){let H=0;for(let oe=1<<14-X;oe>0;oe--){const le=J[(L<<14-X)+H];if(le.len||le.p)throw new Error("Invalid table entry");le.len=X,le.lit=R,H++}}}return!0}const f={c:0,lc:0};function m(w,R,N,J){w=w<<8|V(N,J),R+=8,f.c=w,f.lc=R}const A={c:0,lc:0};function v(w,R,N,J,L,X,H,oe,le){if(w==R){J<8&&(m(N,J,L,X),N=f.c,J=f.lc),J-=8;let ve=N>>J;if(ve=new Uint8Array([ve])[0],oe.value+ve>le)return!1;const Ee=H[oe.value-1];for(;ve-- >0;)H[oe.value++]=Ee}else if(oe.value<le)H[oe.value++]=w;else return!1;A.c=N,A.lc=J}function g(w){return w&65535}function y(w){const R=g(w);return R>32767?R-65536:R}const b={a:0,b:0};function _(w,R){const N=y(w),J=y(R),L=N+(J&1)+(J>>1),X=L,H=L-J;b.a=X,b.b=H}function E(w,R){const N=g(w),J=g(R),L=N-(J>>1)&65535,X=J+L-32768&65535;b.a=X,b.b=L}function I(w,R,N,J,L,X,H){const oe=H<16384,le=N>L?L:N;let ve=1,Ee,Ve;for(;ve<=le;)ve<<=1;for(ve>>=1,Ee=ve,ve>>=1;ve>=1;){Ve=0;const He=Ve+X*(L-Ee),qe=X*ve,ht=X*Ee,et=J*ve,At=J*Ee;let qt,Ci,zi,Xn;for(;Ve<=He;Ve+=ht){let wi=Ve;const ei=Ve+J*(N-Ee);for(;wi<=ei;wi+=At){const mn=wi+et,Ms=wi+qe,En=Ms+et;oe?(_(w[wi+R],w[Ms+R]),qt=b.a,zi=b.b,_(w[mn+R],w[En+R]),Ci=b.a,Xn=b.b,_(qt,Ci),w[wi+R]=b.a,w[mn+R]=b.b,_(zi,Xn),w[Ms+R]=b.a,w[En+R]=b.b):(E(w[wi+R],w[Ms+R]),qt=b.a,zi=b.b,E(w[mn+R],w[En+R]),Ci=b.a,Xn=b.b,E(qt,Ci),w[wi+R]=b.a,w[mn+R]=b.b,E(zi,Xn),w[Ms+R]=b.a,w[En+R]=b.b)}if(N&ve){const mn=wi+qe;oe?_(w[wi+R],w[mn+R]):E(w[wi+R],w[mn+R]),qt=b.a,w[mn+R]=b.b,w[wi+R]=qt}}if(L&ve){let wi=Ve;const ei=Ve+J*(N-Ee);for(;wi<=ei;wi+=At){const mn=wi+et;oe?_(w[wi+R],w[mn+R]):E(w[wi+R],w[mn+R]),qt=b.a,w[mn+R]=b.b,w[wi+R]=qt}}Ee=ve,ve>>=1}return Ve}function T(w,R,N,J,L,X,H,oe,le){let ve=0,Ee=0;const Ve=H,He=Math.trunc(J.value+(L+7)/8);for(;J.value<He;)for(m(ve,Ee,N,J),ve=f.c,Ee=f.lc;Ee>=14;){const ht=ve>>Ee-14&16383,et=R[ht];if(et.len)Ee-=et.len,v(et.lit,X,ve,Ee,N,J,oe,le,Ve),ve=A.c,Ee=A.lc;else{if(!et.p)throw new Error("hufDecode issues");let At;for(At=0;At<et.lit;At++){const qt=u(w[et.p[At]]);for(;Ee<qt&&J.value<He;)m(ve,Ee,N,J),ve=f.c,Ee=f.lc;if(Ee>=qt&&d(w[et.p[At]])==(ve>>Ee-qt&(1<<qt)-1)){Ee-=qt,v(et.p[At],X,ve,Ee,N,J,oe,le,Ve),ve=A.c,Ee=A.lc;break}}if(At==et.lit)throw new Error("hufDecode issues")}}const qe=8-L&7;for(ve>>=qe,Ee-=qe;Ee>0;){const ht=R[ve<<14-Ee&16383];if(ht.len)Ee-=ht.len,v(ht.lit,X,ve,Ee,N,J,oe,le,Ve),ve=A.c,Ee=A.lc;else throw new Error("hufDecode issues")}return!0}function M(w,R,N,J,L,X){const H={value:0},oe=N.value,le=pe(R,N),ve=pe(R,N);N.value+=4;const Ee=pe(R,N);if(N.value+=4,le<0||le>=65537||ve<0||ve>=65537)throw new Error("Something wrong with HUF_ENCSIZE");const Ve=new Array(65537),He=new Array(16384);r(He);const qe=J-(N.value-oe);if(c(w,N,qe,le,ve,Ve),Ee>8*(J-(N.value-oe)))throw new Error("Something wrong with hufUncompress");p(Ve,le,ve,He),T(Ve,He,w,N,Ee,ve,X,L,H)}function D(w,R,N){for(let J=0;J<N;++J)R[J]=w[R[J]]}function C(w){for(let R=1;R<w.length;R++){const N=w[R-1]+w[R]-128;w[R]=N}}function P(w,R){let N=0,J=Math.floor((w.length+1)/2),L=0;const X=w.length-1;for(;!(L>X||(R[L++]=w[N++],L>X));)R[L++]=w[J++]}function G(w){let R=w.byteLength;const N=new Array;let J=0;const L=new DataView(w);for(;R>0;){const X=L.getInt8(J++);if(X<0){const H=-X;R-=H+1;for(let oe=0;oe<H;oe++)N.push(L.getUint8(J++))}else{const H=X;R-=2;const oe=L.getUint8(J++);for(let le=0;le<H+1;le++)N.push(oe)}}return N}function Q(w,R,N,J,L,X){let H=new DataView(X.buffer);const oe=N[w.idx[0]].width,le=N[w.idx[0]].height,ve=3,Ee=Math.floor(oe/8),Ve=Math.ceil(oe/8),He=Math.ceil(le/8),qe=oe-(Ve-1)*8,ht=le-(He-1)*8,et={value:0},At=new Array(ve),qt=new Array(ve),Ci=new Array(ve),zi=new Array(ve),Xn=new Array(ve);for(let ei=0;ei<ve;++ei)Xn[ei]=R[w.idx[ei]],At[ei]=ei<1?0:At[ei-1]+Ve*He,qt[ei]=new Float32Array(64),Ci[ei]=new Uint16Array(64),zi[ei]=new Uint16Array(Ve*64);for(let ei=0;ei<He;++ei){let mn=8;ei==He-1&&(mn=ht);let Ms=8;for(let O=0;O<Ve;++O){O==Ve-1&&(Ms=qe);for(let te=0;te<ve;++te)Ci[te].fill(0),Ci[te][0]=L[At[te]++],k(et,J,Ci[te]),W(Ci[te],qt[te]),U(qt[te]);F(qt);for(let te=0;te<ve;++te)z(qt[te],zi[te],O*64)}let En=0;for(let O=0;O<ve;++O){const te=N[w.idx[O]].type;for(let de=8*ei;de<8*ei+mn;++de){En=Xn[O][de];for(let fe=0;fe<Ee;++fe){const ae=fe*64+(de&7)*8;H.setUint16(En+0*2*te,zi[O][ae+0],!0),H.setUint16(En+1*2*te,zi[O][ae+1],!0),H.setUint16(En+2*2*te,zi[O][ae+2],!0),H.setUint16(En+3*2*te,zi[O][ae+3],!0),H.setUint16(En+4*2*te,zi[O][ae+4],!0),H.setUint16(En+5*2*te,zi[O][ae+5],!0),H.setUint16(En+6*2*te,zi[O][ae+6],!0),H.setUint16(En+7*2*te,zi[O][ae+7],!0),En+=8*2*te}}if(Ee!=Ve)for(let de=8*ei;de<8*ei+mn;++de){const fe=Xn[O][de]+8*Ee*2*te,ae=Ee*64+(de&7)*8;for(let Xe=0;Xe<Ms;++Xe)H.setUint16(fe+Xe*2*te,zi[O][ae+Xe],!0)}}}const wi=new Uint16Array(oe);H=new DataView(X.buffer);for(let ei=0;ei<ve;++ei){N[w.idx[ei]].decoded=!0;const mn=N[w.idx[ei]].type;if(N[ei].type==2)for(let Ms=0;Ms<le;++Ms){const En=Xn[ei][Ms];for(let O=0;O<oe;++O)wi[O]=H.getUint16(En+O*2*mn,!0);for(let O=0;O<oe;++O)H.setFloat32(En+O*2*mn,me(wi[O]),!0)}}}function k(w,R,N){let J,L=1;for(;L<64;)J=R[w.value],J==65280?L=64:J>>8==255?L+=J&255:(N[L]=J,L++),w.value++}function W(w,R){R[0]=me(w[0]),R[1]=me(w[1]),R[2]=me(w[5]),R[3]=me(w[6]),R[4]=me(w[14]),R[5]=me(w[15]),R[6]=me(w[27]),R[7]=me(w[28]),R[8]=me(w[2]),R[9]=me(w[4]),R[10]=me(w[7]),R[11]=me(w[13]),R[12]=me(w[16]),R[13]=me(w[26]),R[14]=me(w[29]),R[15]=me(w[42]),R[16]=me(w[3]),R[17]=me(w[8]),R[18]=me(w[12]),R[19]=me(w[17]),R[20]=me(w[25]),R[21]=me(w[30]),R[22]=me(w[41]),R[23]=me(w[43]),R[24]=me(w[9]),R[25]=me(w[11]),R[26]=me(w[18]),R[27]=me(w[24]),R[28]=me(w[31]),R[29]=me(w[40]),R[30]=me(w[44]),R[31]=me(w[53]),R[32]=me(w[10]),R[33]=me(w[19]),R[34]=me(w[23]),R[35]=me(w[32]),R[36]=me(w[39]),R[37]=me(w[45]),R[38]=me(w[52]),R[39]=me(w[54]),R[40]=me(w[20]),R[41]=me(w[22]),R[42]=me(w[33]),R[43]=me(w[38]),R[44]=me(w[46]),R[45]=me(w[51]),R[46]=me(w[55]),R[47]=me(w[60]),R[48]=me(w[21]),R[49]=me(w[34]),R[50]=me(w[37]),R[51]=me(w[47]),R[52]=me(w[50]),R[53]=me(w[56]),R[54]=me(w[59]),R[55]=me(w[61]),R[56]=me(w[35]),R[57]=me(w[36]),R[58]=me(w[48]),R[59]=me(w[49]),R[60]=me(w[57]),R[61]=me(w[58]),R[62]=me(w[62]),R[63]=me(w[63])}function U(w){const R=.5*Math.cos(.7853975),N=.5*Math.cos(3.14159/16),J=.5*Math.cos(3.14159/8),L=.5*Math.cos(3*3.14159/16),X=.5*Math.cos(5*3.14159/16),H=.5*Math.cos(3*3.14159/8),oe=.5*Math.cos(7*3.14159/16),le=new Array(4),ve=new Array(4),Ee=new Array(4),Ve=new Array(4);for(let He=0;He<8;++He){const qe=He*8;le[0]=J*w[qe+2],le[1]=H*w[qe+2],le[2]=J*w[qe+6],le[3]=H*w[qe+6],ve[0]=N*w[qe+1]+L*w[qe+3]+X*w[qe+5]+oe*w[qe+7],ve[1]=L*w[qe+1]-oe*w[qe+3]-N*w[qe+5]-X*w[qe+7],ve[2]=X*w[qe+1]-N*w[qe+3]+oe*w[qe+5]+L*w[qe+7],ve[3]=oe*w[qe+1]-X*w[qe+3]+L*w[qe+5]-N*w[qe+7],Ee[0]=R*(w[qe+0]+w[qe+4]),Ee[3]=R*(w[qe+0]-w[qe+4]),Ee[1]=le[0]+le[3],Ee[2]=le[1]-le[2],Ve[0]=Ee[0]+Ee[1],Ve[1]=Ee[3]+Ee[2],Ve[2]=Ee[3]-Ee[2],Ve[3]=Ee[0]-Ee[1],w[qe+0]=Ve[0]+ve[0],w[qe+1]=Ve[1]+ve[1],w[qe+2]=Ve[2]+ve[2],w[qe+3]=Ve[3]+ve[3],w[qe+4]=Ve[3]-ve[3],w[qe+5]=Ve[2]-ve[2],w[qe+6]=Ve[1]-ve[1],w[qe+7]=Ve[0]-ve[0]}for(let He=0;He<8;++He)le[0]=J*w[16+He],le[1]=H*w[16+He],le[2]=J*w[48+He],le[3]=H*w[48+He],ve[0]=N*w[8+He]+L*w[24+He]+X*w[40+He]+oe*w[56+He],ve[1]=L*w[8+He]-oe*w[24+He]-N*w[40+He]-X*w[56+He],ve[2]=X*w[8+He]-N*w[24+He]+oe*w[40+He]+L*w[56+He],ve[3]=oe*w[8+He]-X*w[24+He]+L*w[40+He]-N*w[56+He],Ee[0]=R*(w[He]+w[32+He]),Ee[3]=R*(w[He]-w[32+He]),Ee[1]=le[0]+le[3],Ee[2]=le[1]-le[2],Ve[0]=Ee[0]+Ee[1],Ve[1]=Ee[3]+Ee[2],Ve[2]=Ee[3]-Ee[2],Ve[3]=Ee[0]-Ee[1],w[0+He]=Ve[0]+ve[0],w[8+He]=Ve[1]+ve[1],w[16+He]=Ve[2]+ve[2],w[24+He]=Ve[3]+ve[3],w[32+He]=Ve[3]-ve[3],w[40+He]=Ve[2]-ve[2],w[48+He]=Ve[1]-ve[1],w[56+He]=Ve[0]-ve[0]}function F(w){for(let R=0;R<64;++R){const N=w[0][R],J=w[1][R],L=w[2][R];w[0][R]=N+1.5747*L,w[1][R]=N-.1873*J-.4682*L,w[2][R]=N+1.8556*J}}function z(w,R,N){for(let J=0;J<64;++J)R[N+J]=eu.toHalfFloat(Z(w[J]))}function Z(w){return w<=1?Math.sign(w)*Math.pow(Math.abs(w),2.2):Math.sign(w)*Math.pow(t,Math.abs(w)-1)}function K(w){return new DataView(w.array.buffer,w.offset.value,w.size)}function se(w){const R=w.viewer.buffer.slice(w.offset.value,w.offset.value+w.size),N=new Uint8Array(G(R)),J=new Uint8Array(N.length);return C(N),P(N,J),new DataView(J.buffer)}function Ae(w){const R=w.array.slice(w.offset.value,w.offset.value+w.size),N=r_(R),J=new Uint8Array(N.length);return C(N),P(N,J),new DataView(J.buffer)}function Re(w){const R=w.viewer,N={value:w.offset.value},J=new Uint16Array(w.width*w.scanlineBlockSize*(w.channels*w.type)),L=new Uint8Array(8192);let X=0;const H=new Array(w.channels);for(let ht=0;ht<w.channels;ht++)H[ht]={},H[ht].start=X,H[ht].end=H[ht].start,H[ht].nx=w.width,H[ht].ny=w.lines,H[ht].size=w.type,X+=H[ht].nx*H[ht].ny*H[ht].size;const oe=Ke(R,N),le=Ke(R,N);if(le>=8192)throw new Error("Something is wrong with PIZ_COMPRESSION BITMAP_SIZE");if(oe<=le)for(let ht=0;ht<le-oe+1;ht++)L[ht+oe]=Ue(R,N);const ve=new Uint16Array(65536),Ee=n(L,ve),Ve=pe(R,N);M(w.array,R,N,Ve,J,X);for(let ht=0;ht<w.channels;++ht){const et=H[ht];for(let At=0;At<H[ht].size;++At)I(J,et.start+At,et.nx,et.size,et.ny,et.nx*et.size,Ee)}D(ve,J,X);let He=0;const qe=new Uint8Array(J.buffer.byteLength);for(let ht=0;ht<w.lines;ht++)for(let et=0;et<w.channels;et++){const At=H[et],qt=At.nx*At.size,Ci=new Uint8Array(J.buffer,At.end*2,qt*2);qe.set(Ci,He),He+=qt*2,At.end+=qt}return new DataView(qe.buffer)}function ne(w){const R=w.array.slice(w.offset.value,w.offset.value+w.size),N=r_(R),J=w.lines*w.channels*w.width,L=w.type==1?new Uint16Array(J):new Uint32Array(J);let X=0,H=0;const oe=new Array(4);for(let le=0;le<w.lines;le++)for(let ve=0;ve<w.channels;ve++){let Ee=0;switch(w.type){case 1:oe[0]=X,oe[1]=oe[0]+w.width,X=oe[1]+w.width;for(let Ve=0;Ve<w.width;++Ve){const He=N[oe[0]++]<<8|N[oe[1]++];Ee+=He,L[H]=Ee,H++}break;case 2:oe[0]=X,oe[1]=oe[0]+w.width,oe[2]=oe[1]+w.width,X=oe[2]+w.width;for(let Ve=0;Ve<w.width;++Ve){const He=N[oe[0]++]<<24|N[oe[1]++]<<16|N[oe[2]++]<<8;Ee+=He,L[H]=Ee,H++}break}}return new DataView(L.buffer)}function ye(w){const R=w.viewer,N={value:w.offset.value},J=new Uint8Array(w.width*w.lines*(w.channels*w.type*2)),L={version:we(R,N),unknownUncompressedSize:we(R,N),unknownCompressedSize:we(R,N),acCompressedSize:we(R,N),dcCompressedSize:we(R,N),rleCompressedSize:we(R,N),rleUncompressedSize:we(R,N),rleRawSize:we(R,N),totalAcUncompressedCount:we(R,N),totalDcUncompressedCount:we(R,N),acCompression:we(R,N)};if(L.version<2)throw new Error("EXRLoader.parse: "+Vt.compression+" version "+L.version+" is unsupported");const X=new Array;let H=Ke(R,N)-2;for(;H>0;){const et=Be(R.buffer,N),At=Ue(R,N),qt=At>>2&3,Ci=(At>>4)-1,zi=new Int8Array([Ci])[0],Xn=Ue(R,N);X.push({name:et,index:zi,type:Xn,compression:qt}),H-=et.length+3}const oe=Vt.channels,le=new Array(w.channels);for(let et=0;et<w.channels;++et){const At=le[et]={},qt=oe[et];At.name=qt.name,At.compression=0,At.decoded=!1,At.type=qt.pixelType,At.pLinear=qt.pLinear,At.width=w.width,At.height=w.lines}const ve={idx:new Array(3)};for(let et=0;et<w.channels;++et){const At=le[et];for(let qt=0;qt<X.length;++qt){const Ci=X[qt];At.name==Ci.name&&(At.compression=Ci.compression,Ci.index>=0&&(ve.idx[Ci.index]=et),At.offset=et)}}let Ee,Ve,He;if(L.acCompressedSize>0)switch(L.acCompression){case 0:Ee=new Uint16Array(L.totalAcUncompressedCount),M(w.array,R,N,L.acCompressedSize,Ee,L.totalAcUncompressedCount);break;case 1:const et=w.array.slice(N.value,N.value+L.totalAcUncompressedCount),At=r_(et);Ee=new Uint16Array(At.buffer),N.value+=L.totalAcUncompressedCount;break}if(L.dcCompressedSize>0){const et={array:w.array,offset:N,size:L.dcCompressedSize};Ve=new Uint16Array(Ae(et).buffer),N.value+=L.dcCompressedSize}if(L.rleRawSize>0){const et=w.array.slice(N.value,N.value+L.rleCompressedSize),At=r_(et);He=G(At.buffer),N.value+=L.rleCompressedSize}let qe=0;const ht=new Array(le.length);for(let et=0;et<ht.length;++et)ht[et]=new Array;for(let et=0;et<w.lines;++et)for(let At=0;At<le.length;++At)ht[At].push(qe),qe+=le[At].width*w.type*2;Q(ve,ht,le,Ee,Ve,J);for(let et=0;et<le.length;++et){const At=le[et];if(!At.decoded)switch(At.compression){case 2:let qt=0,Ci=0;for(let zi=0;zi<w.lines;++zi){let Xn=ht[et][qt];for(let wi=0;wi<At.width;++wi){for(let ei=0;ei<2*At.type;++ei)J[Xn++]=He[Ci+ei*At.width*At.height];Ci++}qt++}break;case 1:default:throw new Error("EXRLoader.parse: unsupported channel compression")}}return new DataView(J.buffer)}function Be(w,R){const N=new Uint8Array(w);let J=0;for(;N[R.value+J]!=0;)J+=1;const L=new TextDecoder().decode(N.slice(R.value,R.value+J));return R.value=R.value+J+1,L}function We(w,R,N){const J=new TextDecoder().decode(new Uint8Array(w).slice(R.value,R.value+N));return R.value=R.value+N,J}function Je(w,R){const N=it(w,R),J=pe(w,R);return[N,J]}function De(w,R){const N=pe(w,R),J=pe(w,R);return[N,J]}function it(w,R){const N=w.getInt32(R.value,!0);return R.value=R.value+4,N}function pe(w,R){const N=w.getUint32(R.value,!0);return R.value=R.value+4,N}function V(w,R){const N=w[R.value];return R.value=R.value+1,N}function Ue(w,R){const N=w.getUint8(R.value);return R.value=R.value+1,N}const we=function(w,R){let N;return"getBigInt64"in DataView.prototype?N=Number(w.getBigInt64(R.value,!0)):N=w.getUint32(R.value+4,!0)+Number(w.getUint32(R.value,!0)<<32),R.value+=8,N};function xe(w,R){const N=w.getFloat32(R.value,!0);return R.value+=4,N}function Ge(w,R){return eu.toHalfFloat(xe(w,R))}function me(w){const R=(w&31744)>>10,N=w&1023;return(w>>15?-1:1)*(R?R===31?N?NaN:1/0:Math.pow(2,R-15)*(1+N/1024):6103515625e-14*(N/1024))}function Ke(w,R){const N=w.getUint16(R.value,!0);return R.value+=2,N}function nt(w,R){return me(Ke(w,R))}function wt(w,R,N,J){const L=N.value,X=[];for(;N.value<L+J-1;){const H=Be(R,N),oe=it(w,N),le=Ue(w,N);N.value+=3;const ve=it(w,N),Ee=it(w,N);X.push({name:H,pixelType:oe,pLinear:le,xSampling:ve,ySampling:Ee})}return N.value+=1,X}function j(w,R){const N=xe(w,R),J=xe(w,R),L=xe(w,R),X=xe(w,R),H=xe(w,R),oe=xe(w,R),le=xe(w,R),ve=xe(w,R);return{redX:N,redY:J,greenX:L,greenY:X,blueX:H,blueY:oe,whiteX:le,whiteY:ve}}function B(w,R){const N=["NO_COMPRESSION","RLE_COMPRESSION","ZIPS_COMPRESSION","ZIP_COMPRESSION","PIZ_COMPRESSION","PXR24_COMPRESSION","B44_COMPRESSION","B44A_COMPRESSION","DWAA_COMPRESSION","DWAB_COMPRESSION"],J=Ue(w,R);return N[J]}function ce(w,R){const N=pe(w,R),J=pe(w,R),L=pe(w,R),X=pe(w,R);return{xMin:N,yMin:J,xMax:L,yMax:X}}function _e(w,R){const N=["INCREASING_Y"],J=Ue(w,R);return N[J]}function Oe(w,R){const N=xe(w,R),J=xe(w,R);return[N,J]}function Te(w,R){const N=xe(w,R),J=xe(w,R),L=xe(w,R);return[N,J,L]}function ft(w,R,N,J,L){if(J==="string"||J==="stringvector"||J==="iccProfile")return We(R,N,L);if(J==="chlist")return wt(w,R,N,L);if(J==="chromaticities")return j(w,N);if(J==="compression")return B(w,N);if(J==="box2i")return ce(w,N);if(J==="lineOrder")return _e(w,N);if(J==="float")return xe(w,N);if(J==="v2f")return Oe(w,N);if(J==="v3f")return Te(w,N);if(J==="int")return it(w,N);if(J==="rational")return Je(w,N);if(J==="timecode")return De(w,N);if(J==="preview")return N.value+=L,"skipped";N.value+=L}function rt(w,R,N){const J={};if(w.getUint32(0,!0)!=20000630)throw new Error("THREE.EXRLoader: Provided file doesn't appear to be in OpenEXR format.");J.version=w.getUint8(4);const L=w.getUint8(5);J.spec={singleTile:!!(L&2),longName:!!(L&4),deepFormat:!!(L&8),multiPart:!!(L&16)},N.value=8;let X=!0;for(;X;){const H=Be(R,N);if(H==0)X=!1;else{const oe=Be(R,N),le=pe(w,N),ve=ft(w,R,N,oe,le);ve===void 0?console.warn(`THREE.EXRLoader: Skipped unknown header attribute type '${oe}'.`):J[H]=ve}}if(L&-5)throw console.error("THREE.EXRHeader:",J),new Error("THREE.EXRLoader: Provided file is currently unsupported.");return J}function Fe(w,R,N,J,L){const X={size:0,viewer:R,array:N,offset:J,width:w.dataWindow.xMax-w.dataWindow.xMin+1,height:w.dataWindow.yMax-w.dataWindow.yMin+1,channels:w.channels.length,bytesPerLine:null,lines:null,inputSize:null,type:w.channels[0].pixelType,uncompress:null,getter:null,format:null,colorSpace:pi};switch(w.compression){case"NO_COMPRESSION":X.lines=1,X.uncompress=K;break;case"RLE_COMPRESSION":X.lines=1,X.uncompress=se;break;case"ZIPS_COMPRESSION":X.lines=1,X.uncompress=Ae;break;case"ZIP_COMPRESSION":X.lines=16,X.uncompress=Ae;break;case"PIZ_COMPRESSION":X.lines=32,X.uncompress=Re;break;case"PXR24_COMPRESSION":X.lines=16,X.uncompress=ne;break;case"DWAA_COMPRESSION":X.lines=32,X.uncompress=ye;break;case"DWAB_COMPRESSION":X.lines=256,X.uncompress=ye;break;default:throw new Error("EXRLoader.parse: "+w.compression+" is unsupported")}if(X.scanlineBlockSize=X.lines,X.type==1)switch(L){case Oi:X.getter=nt,X.inputSize=2;break;case Ji:X.getter=Ke,X.inputSize=2;break}else if(X.type==2)switch(L){case Oi:X.getter=xe,X.inputSize=4;break;case Ji:X.getter=Ge,X.inputSize=4}else throw new Error("EXRLoader.parse: unsupported pixelType "+X.type+" for "+w.compression+".");X.blockCount=(w.dataWindow.yMax+1)/X.scanlineBlockSize;for(let oe=0;oe<X.blockCount;oe++)we(R,J);X.outputChannels=X.channels==3?4:X.channels;const H=X.width*X.height*X.outputChannels;switch(L){case Oi:X.byteArray=new Float32Array(H),X.channels<X.outputChannels&&X.byteArray.fill(1,0,H);break;case Ji:X.byteArray=new Uint16Array(H),X.channels<X.outputChannels&&X.byteArray.fill(15360,0,H);break;default:console.error("THREE.EXRLoader: unsupported type: ",L);break}return X.bytesPerLine=X.width*X.inputSize*X.channels,X.outputChannels==4?(X.format=di,X.colorSpace=pi):(X.format=Ko,X.colorSpace=is),X}const je=new DataView(e),bt=new Uint8Array(e),Le={value:0},Vt=rt(je,e,Le),ke=Fe(Vt,je,bt,Le,this.type),vt={value:0},st={R:0,G:1,B:2,A:3,Y:0};for(let w=0;w<ke.height/ke.scanlineBlockSize;w++){const R=pe(je,Le);ke.size=pe(je,Le),ke.lines=R+ke.scanlineBlockSize>ke.height?ke.height-R:ke.scanlineBlockSize;const N=ke.size<ke.lines*ke.bytesPerLine?ke.uncompress(ke):K(ke);Le.value+=ke.size;for(let J=0;J<ke.scanlineBlockSize;J++){const L=J+w*ke.scanlineBlockSize;if(L>=ke.height)break;for(let X=0;X<ke.channels;X++){const H=st[Vt.channels[X].name];for(let oe=0;oe<ke.width;oe++){vt.value=(J*(ke.channels*ke.width)+X*ke.width+oe)*ke.inputSize;const le=(ke.height-1-L)*(ke.width*ke.outputChannels)+oe*ke.outputChannels+H;ke.byteArray[le]=ke.getter(N,vt)}}}}return{header:Vt,width:ke.width,height:ke.height,data:ke.byteArray,format:ke.format,colorSpace:ke.colorSpace,type:this.type}}setDataType(e){return this.type=e,this}load(e,t,n,r){function s(o,a){o.colorSpace=a.colorSpace,o.minFilter=St,o.magFilter=St,o.generateMipmaps=!1,o.flipY=!1,t&&t(o,a)}return super.load(e,s,n,r)}}class HM extends ZS{constructor(e){super(e),this.type=Ji}parse(e){const t=function(g,y){switch(g){case 1:throw new Error("THREE.RGBELoader: Read Error: "+(y||""));case 2:throw new Error("THREE.RGBELoader: Write Error: "+(y||""));case 3:throw new Error("THREE.RGBELoader: Bad File Format: "+(y||""));default:case 4:throw new Error("THREE.RGBELoader: Memory Error: "+(y||""))}},n=`
4969
+ */var RU=function(i){return URL.createObjectURL(new Blob([i],{type:"text/javascript"}))};try{URL.revokeObjectURL(RU(""))}catch{RU=function(i){return"data:application/javascript;charset=UTF-8,"+encodeURI(i)}}var Rn=Uint8Array,fs=Uint16Array,Lp=Uint32Array,t_=new Rn([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),i_=new Rn([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),DM=new Rn([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),PU=function(i,e){for(var t=new fs(31),n=0;n<31;++n)t[n]=e+=1<<i[n-1];for(var r=new Lp(t[30]),n=1;n<30;++n)for(var s=t[n];s<t[n+1];++s)r[s]=s-t[n]<<5|n;return[t,r]},BU=PU(t_,2),DU=BU[0],OM=BU[1];DU[28]=258,OM[258]=28;for(var OU=PU(i_,0),C$=OU[0],kU=OU[1],kM=new fs(32768),Ni=0;Ni<32768;++Ni){var $c=(Ni&43690)>>>1|(Ni&21845)<<1;$c=($c&52428)>>>2|($c&13107)<<2,$c=($c&61680)>>>4|($c&3855)<<4,kM[Ni]=(($c&65280)>>>8|($c&255)<<8)>>>1}for(var Qa=function(i,e,t){for(var n=i.length,r=0,s=new fs(e);r<n;++r)++s[i[r]-1];var o=new fs(e);for(r=0;r<e;++r)o[r]=o[r-1]+s[r-1]<<1;var a;if(t){a=new fs(1<<e);var l=15-e;for(r=0;r<n;++r)if(i[r])for(var c=r<<4|i[r],u=e-i[r],d=o[i[r]-1]++<<u,p=d|(1<<u)-1;d<=p;++d)a[kM[d]>>>l]=c}else for(a=new fs(n),r=0;r<n;++r)i[r]&&(a[r]=kM[o[i[r]-1]++]>>>15-i[r]);return a},eh=new Rn(288),Ni=0;Ni<144;++Ni)eh[Ni]=8;for(var Ni=144;Ni<256;++Ni)eh[Ni]=9;for(var Ni=256;Ni<280;++Ni)eh[Ni]=7;for(var Ni=280;Ni<288;++Ni)eh[Ni]=8;for(var zg=new Rn(32),Ni=0;Ni<32;++Ni)zg[Ni]=5;var E$=Qa(eh,9,0),M$=Qa(eh,9,1),T$=Qa(zg,5,0),I$=Qa(zg,5,1),LM=function(i){for(var e=i[0],t=1;t<i.length;++t)i[t]>e&&(e=i[t]);return e},ha=function(i,e,t){var n=e/8|0;return(i[n]|i[n+1]<<8)>>(e&7)&t},UM=function(i,e){var t=e/8|0;return(i[t]|i[t+1]<<8|i[t+2]<<16)>>(e&7)},FM=function(i){return(i/8|0)+(i&7&&1)},NM=function(i,e,t){(e==null||e<0)&&(e=0),(t==null||t>i.length)&&(t=i.length);var n=new(i instanceof fs?fs:i instanceof Lp?Lp:Rn)(t-e);return n.set(i.subarray(e,t)),n},R$=function(i,e,t){var n=i.length;if(!n||t&&!t.l&&n<5)return e||new Rn(0);var r=!e||t,s=!t||t.i;t||(t={}),e||(e=new Rn(n*3));var o=function(Be){var We=e.length;if(Be>We){var Je=new Rn(Math.max(We*2,Be));Je.set(e),e=Je}},a=t.f||0,l=t.p||0,c=t.b||0,u=t.l,d=t.d,p=t.m,f=t.n,m=n*8;do{if(!u){t.f=a=ha(i,l,1);var A=ha(i,l+1,3);if(l+=3,A)if(A==1)u=M$,d=I$,p=9,f=5;else if(A==2){var v=ha(i,l,31)+257,g=ha(i,l+10,15)+4,y=v+ha(i,l+5,31)+1;l+=14;for(var b=new Rn(y),_=new Rn(19),E=0;E<g;++E)_[DM[E]]=ha(i,l+E*3,7);l+=g*3;for(var I=LM(_),T=(1<<I)-1,M=Qa(_,I,1),E=0;E<y;){var D=M[ha(i,l,T)];l+=D&15;var C=D>>>4;if(C<16)b[E++]=C;else{var P=0,G=0;for(C==16?(G=3+ha(i,l,3),l+=2,P=b[E-1]):C==17?(G=3+ha(i,l,7),l+=3):C==18&&(G=11+ha(i,l,127),l+=7);G--;)b[E++]=P}}var Q=b.subarray(0,v),k=b.subarray(v);p=LM(Q),f=LM(k),u=Qa(Q,p,1),d=Qa(k,f,1)}else throw"invalid block type";else{var C=FM(l)+4,W=i[C-4]|i[C-3]<<8,U=C+W;if(U>n){if(s)throw"unexpected EOF";break}r&&o(c+W),e.set(i.subarray(C,U),c),t.b=c+=W,t.p=l=U*8;continue}if(l>m){if(s)throw"unexpected EOF";break}}r&&o(c+131072);for(var F=(1<<p)-1,z=(1<<f)-1,Z=l;;Z=l){var P=u[UM(i,l)&F],K=P>>>4;if(l+=P&15,l>m){if(s)throw"unexpected EOF";break}if(!P)throw"invalid length/literal";if(K<256)e[c++]=K;else if(K==256){Z=l,u=null;break}else{var se=K-254;if(K>264){var E=K-257,Ae=t_[E];se=ha(i,l,(1<<Ae)-1)+DU[E],l+=Ae}var Re=d[UM(i,l)&z],ne=Re>>>4;if(!Re)throw"invalid distance";l+=Re&15;var k=C$[ne];if(ne>3){var Ae=i_[ne];k+=UM(i,l)&(1<<Ae)-1,l+=Ae}if(l>m){if(s)throw"unexpected EOF";break}r&&o(c+131072);for(var ye=c+se;c<ye;c+=4)e[c]=e[c-k],e[c+1]=e[c+1-k],e[c+2]=e[c+2-k],e[c+3]=e[c+3-k];c=ye}}t.l=u,t.p=Z,t.b=c,u&&(a=1,t.m=p,t.d=d,t.n=f)}while(!a);return c==e.length?e:NM(e,0,c)},Xl=function(i,e,t){t<<=e&7;var n=e/8|0;i[n]|=t,i[n+1]|=t>>>8},jg=function(i,e,t){t<<=e&7;var n=e/8|0;i[n]|=t,i[n+1]|=t>>>8,i[n+2]|=t>>>16},zM=function(i,e){for(var t=[],n=0;n<i.length;++n)i[n]&&t.push({s:n,f:i[n]});var r=t.length,s=t.slice();if(!r)return[GM,0];if(r==1){var o=new Rn(t[0].s+1);return o[t[0].s]=1,[o,1]}t.sort(function(E,I){return E.f-I.f}),t.push({s:-1,f:25001});var a=t[0],l=t[1],c=0,u=1,d=2;for(t[0]={s:-1,f:a.f+l.f,l:a,r:l};u!=r-1;)a=t[t[c].f<t[d].f?c++:d++],l=t[c!=u&&t[c].f<t[d].f?c++:d++],t[u++]={s:-1,f:a.f+l.f,l:a,r:l};for(var p=s[0].s,n=1;n<r;++n)s[n].s>p&&(p=s[n].s);var f=new fs(p+1),m=jM(t[u-1],f,0);if(m>e){var n=0,A=0,v=m-e,g=1<<v;for(s.sort(function(I,T){return f[T.s]-f[I.s]||I.f-T.f});n<r;++n){var y=s[n].s;if(f[y]>e)A+=g-(1<<m-f[y]),f[y]=e;else break}for(A>>>=v;A>0;){var b=s[n].s;f[b]<e?A-=1<<e-f[b]++-1:++n}for(;n>=0&&A;--n){var _=s[n].s;f[_]==e&&(--f[_],++A)}m=e}return[new Rn(f),m]},jM=function(i,e,t){return i.s==-1?Math.max(jM(i.l,e,t+1),jM(i.r,e,t+1)):e[i.s]=t},LU=function(i){for(var e=i.length;e&&!i[--e];);for(var t=new fs(++e),n=0,r=i[0],s=1,o=function(l){t[n++]=l},a=1;a<=e;++a)if(i[a]==r&&a!=e)++s;else{if(!r&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(r),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(r);s=1,r=i[a]}return[t.subarray(0,n),e]},Gg=function(i,e){for(var t=0,n=0;n<e.length;++n)t+=i[n]*e[n];return t},n_=function(i,e,t){var n=t.length,r=FM(e+2);i[r]=n&255,i[r+1]=n>>>8,i[r+2]=i[r]^255,i[r+3]=i[r+1]^255;for(var s=0;s<n;++s)i[r+s+4]=t[s];return(r+4+n)*8},UU=function(i,e,t,n,r,s,o,a,l,c,u){Xl(e,u++,t),++r[256];for(var d=zM(r,15),p=d[0],f=d[1],m=zM(s,15),A=m[0],v=m[1],g=LU(p),y=g[0],b=g[1],_=LU(A),E=_[0],I=_[1],T=new fs(19),M=0;M<y.length;++M)T[y[M]&31]++;for(var M=0;M<E.length;++M)T[E[M]&31]++;for(var D=zM(T,7),C=D[0],P=D[1],G=19;G>4&&!C[DM[G-1]];--G);var Q=c+5<<3,k=Gg(r,eh)+Gg(s,zg)+o,W=Gg(r,p)+Gg(s,A)+o+14+3*G+Gg(T,C)+(2*T[16]+3*T[17]+7*T[18]);if(Q<=k&&Q<=W)return n_(e,u,i.subarray(l,l+c));var U,F,z,Z;if(Xl(e,u,1+(W<k)),u+=2,W<k){U=Qa(p,f,0),F=p,z=Qa(A,v,0),Z=A;var K=Qa(C,P,0);Xl(e,u,b-257),Xl(e,u+5,I-1),Xl(e,u+10,G-4),u+=14;for(var M=0;M<G;++M)Xl(e,u+3*M,C[DM[M]]);u+=3*G;for(var se=[y,E],Ae=0;Ae<2;++Ae)for(var Re=se[Ae],M=0;M<Re.length;++M){var ne=Re[M]&31;Xl(e,u,K[ne]),u+=C[ne],ne>15&&(Xl(e,u,Re[M]>>>5&127),u+=Re[M]>>>12)}}else U=E$,F=eh,z=T$,Z=zg;for(var M=0;M<a;++M)if(n[M]>255){var ne=n[M]>>>18&31;jg(e,u,U[ne+257]),u+=F[ne+257],ne>7&&(Xl(e,u,n[M]>>>23&31),u+=t_[ne]);var ye=n[M]&31;jg(e,u,z[ye]),u+=Z[ye],ye>3&&(jg(e,u,n[M]>>>5&8191),u+=i_[ye])}else jg(e,u,U[n[M]]),u+=F[n[M]];return jg(e,u,U[256]),u+F[256]},P$=new Lp([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),GM=new Rn(0),B$=function(i,e,t,n,r,s){var o=i.length,a=new Rn(n+o+5*(1+Math.ceil(o/7e3))+r),l=a.subarray(n,a.length-r),c=0;if(!e||o<8)for(var u=0;u<=o;u+=65535){var d=u+65535;d<o?c=n_(l,c,i.subarray(u,d)):(l[u]=s,c=n_(l,c,i.subarray(u,o)))}else{for(var p=P$[e-1],f=p>>>13,m=p&8191,A=(1<<t)-1,v=new fs(32768),g=new fs(A+1),y=Math.ceil(t/3),b=2*y,_=function(we){return(i[we]^i[we+1]<<y^i[we+2]<<b)&A},E=new Lp(25e3),I=new fs(288),T=new fs(32),M=0,D=0,u=0,C=0,P=0,G=0;u<o;++u){var Q=_(u),k=u&32767,W=g[Q];if(v[k]=W,g[Q]=k,P<=u){var U=o-u;if((M>7e3||C>24576)&&U>423){c=UU(i,l,0,E,I,T,D,C,G,u-G,c),C=M=D=0,G=u;for(var F=0;F<286;++F)I[F]=0;for(var F=0;F<30;++F)T[F]=0}var z=2,Z=0,K=m,se=k-W&32767;if(U>2&&Q==_(u-se))for(var Ae=Math.min(f,U)-1,Re=Math.min(32767,u),ne=Math.min(258,U);se<=Re&&--K&&k!=W;){if(i[u+z]==i[u+z-se]){for(var ye=0;ye<ne&&i[u+ye]==i[u+ye-se];++ye);if(ye>z){if(z=ye,Z=se,ye>Ae)break;for(var Be=Math.min(se,ye-2),We=0,F=0;F<Be;++F){var Je=u-se+F+32768&32767,De=v[Je],it=Je-De+32768&32767;it>We&&(We=it,W=Je)}}}k=W,W=v[k],se+=k-W+32768&32767}if(Z){E[C++]=268435456|OM[z]<<18|kU[Z];var pe=OM[z]&31,V=kU[Z]&31;D+=t_[pe]+i_[V],++I[257+pe],++T[V],P=u+z,++M}else E[C++]=i[u],++I[i[u]]}}c=UU(i,l,s,E,I,T,D,C,G,u-G,c),!s&&c&7&&(c=n_(l,c+1,GM))}return NM(a,0,n+FM(c)+r)},D$=function(){for(var i=new Lp(256),e=0;e<256;++e){for(var t=e,n=9;--n;)t=(t&1&&3988292384)^t>>>1;i[e]=t}return i}(),O$=function(){var i=-1;return{p:function(e){for(var t=i,n=0;n<e.length;++n)t=D$[t&255^e[n]]^t>>>8;i=t},d:function(){return~i}}},k$=function(i,e,t,n,r){return B$(i,e.level==null?6:e.level,e.mem==null?Math.ceil(Math.max(8,Math.min(13,Math.log(i.length)))*1.5):12+e.mem,t,n,!r)},FU=function(i,e){var t={};for(var n in i)t[n]=i[n];for(var n in e)t[n]=e[n];return t},yr=function(i,e,t){for(;t;++e)i[e]=t,t>>>=8},L$=function(i){if((i[0]&15)!=8||i[0]>>>4>7||(i[0]<<8|i[1])%31)throw"invalid zlib data";if(i[1]&32)throw"invalid zlib data: preset dictionaries not supported"};function U$(i,e){return k$(i,e||{},0,0)}function r_(i,e){return R$((L$(i),i.subarray(2,-4)),e)}var NU=function(i,e,t,n){for(var r in i){var s=i[r],o=e+r;s instanceof Rn?t[o]=[s,n]:Array.isArray(s)?t[o]=[s[0],FU(n,s[1])]:NU(s,o+"/",t,n)}},zU=typeof TextEncoder<"u"&&new TextEncoder,F$=typeof TextDecoder<"u"&&new TextDecoder,N$=0;try{F$.decode(GM,{stream:!0}),N$=1}catch{}function s_(i,e){if(e){for(var t=new Rn(i.length),n=0;n<i.length;++n)t[n]=i.charCodeAt(n);return t}if(zU)return zU.encode(i);for(var r=i.length,s=new Rn(i.length+(i.length>>1)),o=0,a=function(d){s[o++]=d},n=0;n<r;++n){if(o+5>s.length){var l=new Rn(o+8+(r-n<<1));l.set(s),s=l}var c=i.charCodeAt(n);c<128||e?a(c):c<2048?(a(192|c>>6),a(128|c&63)):c>55295&&c<57344?(c=65536+(c&1047552)|i.charCodeAt(++n)&1023,a(240|c>>18),a(128|c>>12&63),a(128|c>>6&63),a(128|c&63)):(a(224|c>>12),a(128|c>>6&63),a(128|c&63))}return NM(s,0,o)}var QM=function(i){var e=0;if(i)for(var t in i){var n=i[t].length;if(n>65535)throw"extra field too long";e+=n+4}return e},jU=function(i,e,t,n,r,s,o,a){var l=n.length,c=t.extra,u=a&&a.length,d=QM(c);yr(i,e,o!=null?33639248:67324752),e+=4,o!=null&&(i[e++]=20,i[e++]=t.os),i[e]=20,e+=2,i[e++]=t.flag<<1|(s==null&&8),i[e++]=r&&8,i[e++]=t.compression&255,i[e++]=t.compression>>8;var p=new Date(t.mtime==null?Date.now():t.mtime),f=p.getFullYear()-1980;if(f<0||f>119)throw"date not in range 1980-2099";if(yr(i,e,f<<25|p.getMonth()+1<<21|p.getDate()<<16|p.getHours()<<11|p.getMinutes()<<5|p.getSeconds()>>>1),e+=4,s!=null&&(yr(i,e,t.crc),yr(i,e+4,s),yr(i,e+8,t.size)),yr(i,e+12,l),yr(i,e+14,d),e+=16,o!=null&&(yr(i,e,u),yr(i,e+6,t.attrs),yr(i,e+10,o),e+=14),i.set(n,e),e+=l,d)for(var m in c){var A=c[m],v=A.length;yr(i,e,+m),yr(i,e+2,v),i.set(A,e+4),e+=4+v}return u&&(i.set(a,e),e+=u),e},z$=function(i,e,t,n,r){yr(i,e,101010256),yr(i,e+8,t),yr(i,e+10,t),yr(i,e+12,n),yr(i,e+16,r)};function j$(i,e){e||(e={});var t={},n=[];NU(i,"",t,e);var r=0,s=0;for(var o in t){var a=t[o],l=a[0],c=a[1],u=c.level==0?0:8,d=s_(o),p=d.length,f=c.comment,m=f&&s_(f),A=m&&m.length,v=QM(c.extra);if(p>65535)throw"filename too long";var g=u?U$(l,c):l,y=g.length,b=O$();b.p(l),n.push(FU(c,{size:l.length,crc:b.d(),c:g,f:d,m,u:p!=o.length||m&&f.length!=A,o:r,compression:u})),r+=30+p+v+y,s+=76+2*(p+v)+(A||0)+y}for(var _=new Rn(s+22),E=r,I=s-r,T=0;T<n.length;++T){var d=n[T];jU(_,d.o,d,d.f,d.u,d.c.length);var M=30+d.f.length+QM(d.extra);_.set(d.c,d.o+M),jU(_,r,d,d.f,d.u,d.c.length,d.o,d.m),r+=16+M+(d.m?d.m.length:0)}return z$(_,r,n.length,I,E),_}class o_ extends ZS{constructor(e){super(e),this.type=Ji}parse(e){const t=Math.pow(2.7182818,2.2);function n(w,R){let N=0;for(let L=0;L<65536;++L)(L==0||w[L>>3]&1<<(L&7))&&(R[N++]=L);const J=N-1;for(;N<65536;)R[N++]=0;return J}function r(w){for(let R=0;R<16384;R++)w[R]={},w[R].len=0,w[R].lit=0,w[R].p=null}const s={l:0,c:0,lc:0};function o(w,R,N,J,L){for(;N<w;)R=R<<8|V(J,L),N+=8;N-=w,s.l=R>>N&(1<<w)-1,s.c=R,s.lc=N}const a=new Array(59);function l(w){for(let N=0;N<=58;++N)a[N]=0;for(let N=0;N<65537;++N)a[w[N]]+=1;let R=0;for(let N=58;N>0;--N){const J=R+a[N]>>1;a[N]=R,R=J}for(let N=0;N<65537;++N){const J=w[N];J>0&&(w[N]=J|a[J]++<<6)}}function c(w,R,N,J,L,X){const H=R;let oe=0,le=0;for(;J<=L;J++){if(H.value-R.value>N)return!1;o(6,oe,le,w,H);const ve=s.l;if(oe=s.c,le=s.lc,X[J]=ve,ve==63){if(H.value-R.value>N)throw new Error("Something wrong with hufUnpackEncTable");o(8,oe,le,w,H);let Ee=s.l+6;if(oe=s.c,le=s.lc,J+Ee>L+1)throw new Error("Something wrong with hufUnpackEncTable");for(;Ee--;)X[J++]=0;J--}else if(ve>=59){let Ee=ve-59+2;if(J+Ee>L+1)throw new Error("Something wrong with hufUnpackEncTable");for(;Ee--;)X[J++]=0;J--}}l(X)}function u(w){return w&63}function d(w){return w>>6}function p(w,R,N,J){for(;R<=N;R++){const L=d(w[R]),X=u(w[R]);if(L>>X)throw new Error("Invalid table entry");if(X>14){const H=J[L>>X-14];if(H.len)throw new Error("Invalid table entry");if(H.lit++,H.p){const oe=H.p;H.p=new Array(H.lit);for(let le=0;le<H.lit-1;++le)H.p[le]=oe[le]}else H.p=new Array(1);H.p[H.lit-1]=R}else if(X){let H=0;for(let oe=1<<14-X;oe>0;oe--){const le=J[(L<<14-X)+H];if(le.len||le.p)throw new Error("Invalid table entry");le.len=X,le.lit=R,H++}}}return!0}const f={c:0,lc:0};function m(w,R,N,J){w=w<<8|V(N,J),R+=8,f.c=w,f.lc=R}const A={c:0,lc:0};function v(w,R,N,J,L,X,H,oe,le){if(w==R){J<8&&(m(N,J,L,X),N=f.c,J=f.lc),J-=8;let ve=N>>J;if(ve=new Uint8Array([ve])[0],oe.value+ve>le)return!1;const Ee=H[oe.value-1];for(;ve-- >0;)H[oe.value++]=Ee}else if(oe.value<le)H[oe.value++]=w;else return!1;A.c=N,A.lc=J}function g(w){return w&65535}function y(w){const R=g(w);return R>32767?R-65536:R}const b={a:0,b:0};function _(w,R){const N=y(w),J=y(R),L=N+(J&1)+(J>>1),X=L,H=L-J;b.a=X,b.b=H}function E(w,R){const N=g(w),J=g(R),L=N-(J>>1)&65535,X=J+L-32768&65535;b.a=X,b.b=L}function I(w,R,N,J,L,X,H){const oe=H<16384,le=N>L?L:N;let ve=1,Ee,Ve;for(;ve<=le;)ve<<=1;for(ve>>=1,Ee=ve,ve>>=1;ve>=1;){Ve=0;const He=Ve+X*(L-Ee),qe=X*ve,ht=X*Ee,et=J*ve,At=J*Ee;let qt,Ci,zi,Xn;for(;Ve<=He;Ve+=ht){let wi=Ve;const ei=Ve+J*(N-Ee);for(;wi<=ei;wi+=At){const mn=wi+et,Ms=wi+qe,En=Ms+et;oe?(_(w[wi+R],w[Ms+R]),qt=b.a,zi=b.b,_(w[mn+R],w[En+R]),Ci=b.a,Xn=b.b,_(qt,Ci),w[wi+R]=b.a,w[mn+R]=b.b,_(zi,Xn),w[Ms+R]=b.a,w[En+R]=b.b):(E(w[wi+R],w[Ms+R]),qt=b.a,zi=b.b,E(w[mn+R],w[En+R]),Ci=b.a,Xn=b.b,E(qt,Ci),w[wi+R]=b.a,w[mn+R]=b.b,E(zi,Xn),w[Ms+R]=b.a,w[En+R]=b.b)}if(N&ve){const mn=wi+qe;oe?_(w[wi+R],w[mn+R]):E(w[wi+R],w[mn+R]),qt=b.a,w[mn+R]=b.b,w[wi+R]=qt}}if(L&ve){let wi=Ve;const ei=Ve+J*(N-Ee);for(;wi<=ei;wi+=At){const mn=wi+et;oe?_(w[wi+R],w[mn+R]):E(w[wi+R],w[mn+R]),qt=b.a,w[mn+R]=b.b,w[wi+R]=qt}}Ee=ve,ve>>=1}return Ve}function T(w,R,N,J,L,X,H,oe,le){let ve=0,Ee=0;const Ve=H,He=Math.trunc(J.value+(L+7)/8);for(;J.value<He;)for(m(ve,Ee,N,J),ve=f.c,Ee=f.lc;Ee>=14;){const ht=ve>>Ee-14&16383,et=R[ht];if(et.len)Ee-=et.len,v(et.lit,X,ve,Ee,N,J,oe,le,Ve),ve=A.c,Ee=A.lc;else{if(!et.p)throw new Error("hufDecode issues");let At;for(At=0;At<et.lit;At++){const qt=u(w[et.p[At]]);for(;Ee<qt&&J.value<He;)m(ve,Ee,N,J),ve=f.c,Ee=f.lc;if(Ee>=qt&&d(w[et.p[At]])==(ve>>Ee-qt&(1<<qt)-1)){Ee-=qt,v(et.p[At],X,ve,Ee,N,J,oe,le,Ve),ve=A.c,Ee=A.lc;break}}if(At==et.lit)throw new Error("hufDecode issues")}}const qe=8-L&7;for(ve>>=qe,Ee-=qe;Ee>0;){const ht=R[ve<<14-Ee&16383];if(ht.len)Ee-=ht.len,v(ht.lit,X,ve,Ee,N,J,oe,le,Ve),ve=A.c,Ee=A.lc;else throw new Error("hufDecode issues")}return!0}function M(w,R,N,J,L,X){const H={value:0},oe=N.value,le=pe(R,N),ve=pe(R,N);N.value+=4;const Ee=pe(R,N);if(N.value+=4,le<0||le>=65537||ve<0||ve>=65537)throw new Error("Something wrong with HUF_ENCSIZE");const Ve=new Array(65537),He=new Array(16384);r(He);const qe=J-(N.value-oe);if(c(w,N,qe,le,ve,Ve),Ee>8*(J-(N.value-oe)))throw new Error("Something wrong with hufUncompress");p(Ve,le,ve,He),T(Ve,He,w,N,Ee,ve,X,L,H)}function D(w,R,N){for(let J=0;J<N;++J)R[J]=w[R[J]]}function C(w){for(let R=1;R<w.length;R++){const N=w[R-1]+w[R]-128;w[R]=N}}function P(w,R){let N=0,J=Math.floor((w.length+1)/2),L=0;const X=w.length-1;for(;!(L>X||(R[L++]=w[N++],L>X));)R[L++]=w[J++]}function G(w){let R=w.byteLength;const N=new Array;let J=0;const L=new DataView(w);for(;R>0;){const X=L.getInt8(J++);if(X<0){const H=-X;R-=H+1;for(let oe=0;oe<H;oe++)N.push(L.getUint8(J++))}else{const H=X;R-=2;const oe=L.getUint8(J++);for(let le=0;le<H+1;le++)N.push(oe)}}return N}function Q(w,R,N,J,L,X){let H=new DataView(X.buffer);const oe=N[w.idx[0]].width,le=N[w.idx[0]].height,ve=3,Ee=Math.floor(oe/8),Ve=Math.ceil(oe/8),He=Math.ceil(le/8),qe=oe-(Ve-1)*8,ht=le-(He-1)*8,et={value:0},At=new Array(ve),qt=new Array(ve),Ci=new Array(ve),zi=new Array(ve),Xn=new Array(ve);for(let ei=0;ei<ve;++ei)Xn[ei]=R[w.idx[ei]],At[ei]=ei<1?0:At[ei-1]+Ve*He,qt[ei]=new Float32Array(64),Ci[ei]=new Uint16Array(64),zi[ei]=new Uint16Array(Ve*64);for(let ei=0;ei<He;++ei){let mn=8;ei==He-1&&(mn=ht);let Ms=8;for(let O=0;O<Ve;++O){O==Ve-1&&(Ms=qe);for(let te=0;te<ve;++te)Ci[te].fill(0),Ci[te][0]=L[At[te]++],k(et,J,Ci[te]),W(Ci[te],qt[te]),U(qt[te]);F(qt);for(let te=0;te<ve;++te)z(qt[te],zi[te],O*64)}let En=0;for(let O=0;O<ve;++O){const te=N[w.idx[O]].type;for(let de=8*ei;de<8*ei+mn;++de){En=Xn[O][de];for(let fe=0;fe<Ee;++fe){const ae=fe*64+(de&7)*8;H.setUint16(En+0*2*te,zi[O][ae+0],!0),H.setUint16(En+1*2*te,zi[O][ae+1],!0),H.setUint16(En+2*2*te,zi[O][ae+2],!0),H.setUint16(En+3*2*te,zi[O][ae+3],!0),H.setUint16(En+4*2*te,zi[O][ae+4],!0),H.setUint16(En+5*2*te,zi[O][ae+5],!0),H.setUint16(En+6*2*te,zi[O][ae+6],!0),H.setUint16(En+7*2*te,zi[O][ae+7],!0),En+=8*2*te}}if(Ee!=Ve)for(let de=8*ei;de<8*ei+mn;++de){const fe=Xn[O][de]+8*Ee*2*te,ae=Ee*64+(de&7)*8;for(let Xe=0;Xe<Ms;++Xe)H.setUint16(fe+Xe*2*te,zi[O][ae+Xe],!0)}}}const wi=new Uint16Array(oe);H=new DataView(X.buffer);for(let ei=0;ei<ve;++ei){N[w.idx[ei]].decoded=!0;const mn=N[w.idx[ei]].type;if(N[ei].type==2)for(let Ms=0;Ms<le;++Ms){const En=Xn[ei][Ms];for(let O=0;O<oe;++O)wi[O]=H.getUint16(En+O*2*mn,!0);for(let O=0;O<oe;++O)H.setFloat32(En+O*2*mn,me(wi[O]),!0)}}}function k(w,R,N){let J,L=1;for(;L<64;)J=R[w.value],J==65280?L=64:J>>8==255?L+=J&255:(N[L]=J,L++),w.value++}function W(w,R){R[0]=me(w[0]),R[1]=me(w[1]),R[2]=me(w[5]),R[3]=me(w[6]),R[4]=me(w[14]),R[5]=me(w[15]),R[6]=me(w[27]),R[7]=me(w[28]),R[8]=me(w[2]),R[9]=me(w[4]),R[10]=me(w[7]),R[11]=me(w[13]),R[12]=me(w[16]),R[13]=me(w[26]),R[14]=me(w[29]),R[15]=me(w[42]),R[16]=me(w[3]),R[17]=me(w[8]),R[18]=me(w[12]),R[19]=me(w[17]),R[20]=me(w[25]),R[21]=me(w[30]),R[22]=me(w[41]),R[23]=me(w[43]),R[24]=me(w[9]),R[25]=me(w[11]),R[26]=me(w[18]),R[27]=me(w[24]),R[28]=me(w[31]),R[29]=me(w[40]),R[30]=me(w[44]),R[31]=me(w[53]),R[32]=me(w[10]),R[33]=me(w[19]),R[34]=me(w[23]),R[35]=me(w[32]),R[36]=me(w[39]),R[37]=me(w[45]),R[38]=me(w[52]),R[39]=me(w[54]),R[40]=me(w[20]),R[41]=me(w[22]),R[42]=me(w[33]),R[43]=me(w[38]),R[44]=me(w[46]),R[45]=me(w[51]),R[46]=me(w[55]),R[47]=me(w[60]),R[48]=me(w[21]),R[49]=me(w[34]),R[50]=me(w[37]),R[51]=me(w[47]),R[52]=me(w[50]),R[53]=me(w[56]),R[54]=me(w[59]),R[55]=me(w[61]),R[56]=me(w[35]),R[57]=me(w[36]),R[58]=me(w[48]),R[59]=me(w[49]),R[60]=me(w[57]),R[61]=me(w[58]),R[62]=me(w[62]),R[63]=me(w[63])}function U(w){const R=.5*Math.cos(.7853975),N=.5*Math.cos(3.14159/16),J=.5*Math.cos(3.14159/8),L=.5*Math.cos(3*3.14159/16),X=.5*Math.cos(5*3.14159/16),H=.5*Math.cos(3*3.14159/8),oe=.5*Math.cos(7*3.14159/16),le=new Array(4),ve=new Array(4),Ee=new Array(4),Ve=new Array(4);for(let He=0;He<8;++He){const qe=He*8;le[0]=J*w[qe+2],le[1]=H*w[qe+2],le[2]=J*w[qe+6],le[3]=H*w[qe+6],ve[0]=N*w[qe+1]+L*w[qe+3]+X*w[qe+5]+oe*w[qe+7],ve[1]=L*w[qe+1]-oe*w[qe+3]-N*w[qe+5]-X*w[qe+7],ve[2]=X*w[qe+1]-N*w[qe+3]+oe*w[qe+5]+L*w[qe+7],ve[3]=oe*w[qe+1]-X*w[qe+3]+L*w[qe+5]-N*w[qe+7],Ee[0]=R*(w[qe+0]+w[qe+4]),Ee[3]=R*(w[qe+0]-w[qe+4]),Ee[1]=le[0]+le[3],Ee[2]=le[1]-le[2],Ve[0]=Ee[0]+Ee[1],Ve[1]=Ee[3]+Ee[2],Ve[2]=Ee[3]-Ee[2],Ve[3]=Ee[0]-Ee[1],w[qe+0]=Ve[0]+ve[0],w[qe+1]=Ve[1]+ve[1],w[qe+2]=Ve[2]+ve[2],w[qe+3]=Ve[3]+ve[3],w[qe+4]=Ve[3]-ve[3],w[qe+5]=Ve[2]-ve[2],w[qe+6]=Ve[1]-ve[1],w[qe+7]=Ve[0]-ve[0]}for(let He=0;He<8;++He)le[0]=J*w[16+He],le[1]=H*w[16+He],le[2]=J*w[48+He],le[3]=H*w[48+He],ve[0]=N*w[8+He]+L*w[24+He]+X*w[40+He]+oe*w[56+He],ve[1]=L*w[8+He]-oe*w[24+He]-N*w[40+He]-X*w[56+He],ve[2]=X*w[8+He]-N*w[24+He]+oe*w[40+He]+L*w[56+He],ve[3]=oe*w[8+He]-X*w[24+He]+L*w[40+He]-N*w[56+He],Ee[0]=R*(w[He]+w[32+He]),Ee[3]=R*(w[He]-w[32+He]),Ee[1]=le[0]+le[3],Ee[2]=le[1]-le[2],Ve[0]=Ee[0]+Ee[1],Ve[1]=Ee[3]+Ee[2],Ve[2]=Ee[3]-Ee[2],Ve[3]=Ee[0]-Ee[1],w[0+He]=Ve[0]+ve[0],w[8+He]=Ve[1]+ve[1],w[16+He]=Ve[2]+ve[2],w[24+He]=Ve[3]+ve[3],w[32+He]=Ve[3]-ve[3],w[40+He]=Ve[2]-ve[2],w[48+He]=Ve[1]-ve[1],w[56+He]=Ve[0]-ve[0]}function F(w){for(let R=0;R<64;++R){const N=w[0][R],J=w[1][R],L=w[2][R];w[0][R]=N+1.5747*L,w[1][R]=N-.1873*J-.4682*L,w[2][R]=N+1.8556*J}}function z(w,R,N){for(let J=0;J<64;++J)R[N+J]=eu.toHalfFloat(Z(w[J]))}function Z(w){return w<=1?Math.sign(w)*Math.pow(Math.abs(w),2.2):Math.sign(w)*Math.pow(t,Math.abs(w)-1)}function K(w){return new DataView(w.array.buffer,w.offset.value,w.size)}function se(w){const R=w.viewer.buffer.slice(w.offset.value,w.offset.value+w.size),N=new Uint8Array(G(R)),J=new Uint8Array(N.length);return C(N),P(N,J),new DataView(J.buffer)}function Ae(w){const R=w.array.slice(w.offset.value,w.offset.value+w.size),N=r_(R),J=new Uint8Array(N.length);return C(N),P(N,J),new DataView(J.buffer)}function Re(w){const R=w.viewer,N={value:w.offset.value},J=new Uint16Array(w.width*w.scanlineBlockSize*(w.channels*w.type)),L=new Uint8Array(8192);let X=0;const H=new Array(w.channels);for(let ht=0;ht<w.channels;ht++)H[ht]={},H[ht].start=X,H[ht].end=H[ht].start,H[ht].nx=w.width,H[ht].ny=w.lines,H[ht].size=w.type,X+=H[ht].nx*H[ht].ny*H[ht].size;const oe=Ke(R,N),le=Ke(R,N);if(le>=8192)throw new Error("Something is wrong with PIZ_COMPRESSION BITMAP_SIZE");if(oe<=le)for(let ht=0;ht<le-oe+1;ht++)L[ht+oe]=Ue(R,N);const ve=new Uint16Array(65536),Ee=n(L,ve),Ve=pe(R,N);M(w.array,R,N,Ve,J,X);for(let ht=0;ht<w.channels;++ht){const et=H[ht];for(let At=0;At<H[ht].size;++At)I(J,et.start+At,et.nx,et.size,et.ny,et.nx*et.size,Ee)}D(ve,J,X);let He=0;const qe=new Uint8Array(J.buffer.byteLength);for(let ht=0;ht<w.lines;ht++)for(let et=0;et<w.channels;et++){const At=H[et],qt=At.nx*At.size,Ci=new Uint8Array(J.buffer,At.end*2,qt*2);qe.set(Ci,He),He+=qt*2,At.end+=qt}return new DataView(qe.buffer)}function ne(w){const R=w.array.slice(w.offset.value,w.offset.value+w.size),N=r_(R),J=w.lines*w.channels*w.width,L=w.type==1?new Uint16Array(J):new Uint32Array(J);let X=0,H=0;const oe=new Array(4);for(let le=0;le<w.lines;le++)for(let ve=0;ve<w.channels;ve++){let Ee=0;switch(w.type){case 1:oe[0]=X,oe[1]=oe[0]+w.width,X=oe[1]+w.width;for(let Ve=0;Ve<w.width;++Ve){const He=N[oe[0]++]<<8|N[oe[1]++];Ee+=He,L[H]=Ee,H++}break;case 2:oe[0]=X,oe[1]=oe[0]+w.width,oe[2]=oe[1]+w.width,X=oe[2]+w.width;for(let Ve=0;Ve<w.width;++Ve){const He=N[oe[0]++]<<24|N[oe[1]++]<<16|N[oe[2]++]<<8;Ee+=He,L[H]=Ee,H++}break}}return new DataView(L.buffer)}function ye(w){const R=w.viewer,N={value:w.offset.value},J=new Uint8Array(w.width*w.lines*(w.channels*w.type*2)),L={version:we(R,N),unknownUncompressedSize:we(R,N),unknownCompressedSize:we(R,N),acCompressedSize:we(R,N),dcCompressedSize:we(R,N),rleCompressedSize:we(R,N),rleUncompressedSize:we(R,N),rleRawSize:we(R,N),totalAcUncompressedCount:we(R,N),totalDcUncompressedCount:we(R,N),acCompression:we(R,N)};if(L.version<2)throw new Error("EXRLoader.parse: "+Vt.compression+" version "+L.version+" is unsupported");const X=new Array;let H=Ke(R,N)-2;for(;H>0;){const et=Be(R.buffer,N),At=Ue(R,N),qt=At>>2&3,Ci=(At>>4)-1,zi=new Int8Array([Ci])[0],Xn=Ue(R,N);X.push({name:et,index:zi,type:Xn,compression:qt}),H-=et.length+3}const oe=Vt.channels,le=new Array(w.channels);for(let et=0;et<w.channels;++et){const At=le[et]={},qt=oe[et];At.name=qt.name,At.compression=0,At.decoded=!1,At.type=qt.pixelType,At.pLinear=qt.pLinear,At.width=w.width,At.height=w.lines}const ve={idx:new Array(3)};for(let et=0;et<w.channels;++et){const At=le[et];for(let qt=0;qt<X.length;++qt){const Ci=X[qt];At.name==Ci.name&&(At.compression=Ci.compression,Ci.index>=0&&(ve.idx[Ci.index]=et),At.offset=et)}}let Ee,Ve,He;if(L.acCompressedSize>0)switch(L.acCompression){case 0:Ee=new Uint16Array(L.totalAcUncompressedCount),M(w.array,R,N,L.acCompressedSize,Ee,L.totalAcUncompressedCount);break;case 1:const et=w.array.slice(N.value,N.value+L.totalAcUncompressedCount),At=r_(et);Ee=new Uint16Array(At.buffer),N.value+=L.totalAcUncompressedCount;break}if(L.dcCompressedSize>0){const et={array:w.array,offset:N,size:L.dcCompressedSize};Ve=new Uint16Array(Ae(et).buffer),N.value+=L.dcCompressedSize}if(L.rleRawSize>0){const et=w.array.slice(N.value,N.value+L.rleCompressedSize),At=r_(et);He=G(At.buffer),N.value+=L.rleCompressedSize}let qe=0;const ht=new Array(le.length);for(let et=0;et<ht.length;++et)ht[et]=new Array;for(let et=0;et<w.lines;++et)for(let At=0;At<le.length;++At)ht[At].push(qe),qe+=le[At].width*w.type*2;Q(ve,ht,le,Ee,Ve,J);for(let et=0;et<le.length;++et){const At=le[et];if(!At.decoded)switch(At.compression){case 2:let qt=0,Ci=0;for(let zi=0;zi<w.lines;++zi){let Xn=ht[et][qt];for(let wi=0;wi<At.width;++wi){for(let ei=0;ei<2*At.type;++ei)J[Xn++]=He[Ci+ei*At.width*At.height];Ci++}qt++}break;case 1:default:throw new Error("EXRLoader.parse: unsupported channel compression")}}return new DataView(J.buffer)}function Be(w,R){const N=new Uint8Array(w);let J=0;for(;N[R.value+J]!=0;)J+=1;const L=new TextDecoder().decode(N.slice(R.value,R.value+J));return R.value=R.value+J+1,L}function We(w,R,N){const J=new TextDecoder().decode(new Uint8Array(w).slice(R.value,R.value+N));return R.value=R.value+N,J}function Je(w,R){const N=it(w,R),J=pe(w,R);return[N,J]}function De(w,R){const N=pe(w,R),J=pe(w,R);return[N,J]}function it(w,R){const N=w.getInt32(R.value,!0);return R.value=R.value+4,N}function pe(w,R){const N=w.getUint32(R.value,!0);return R.value=R.value+4,N}function V(w,R){const N=w[R.value];return R.value=R.value+1,N}function Ue(w,R){const N=w.getUint8(R.value);return R.value=R.value+1,N}const we=function(w,R){let N;return"getBigInt64"in DataView.prototype?N=Number(w.getBigInt64(R.value,!0)):N=w.getUint32(R.value+4,!0)+Number(w.getUint32(R.value,!0)<<32),R.value+=8,N};function xe(w,R){const N=w.getFloat32(R.value,!0);return R.value+=4,N}function Ge(w,R){return eu.toHalfFloat(xe(w,R))}function me(w){const R=(w&31744)>>10,N=w&1023;return(w>>15?-1:1)*(R?R===31?N?NaN:1/0:Math.pow(2,R-15)*(1+N/1024):6103515625e-14*(N/1024))}function Ke(w,R){const N=w.getUint16(R.value,!0);return R.value+=2,N}function nt(w,R){return me(Ke(w,R))}function wt(w,R,N,J){const L=N.value,X=[];for(;N.value<L+J-1;){const H=Be(R,N),oe=it(w,N),le=Ue(w,N);N.value+=3;const ve=it(w,N),Ee=it(w,N);X.push({name:H,pixelType:oe,pLinear:le,xSampling:ve,ySampling:Ee})}return N.value+=1,X}function j(w,R){const N=xe(w,R),J=xe(w,R),L=xe(w,R),X=xe(w,R),H=xe(w,R),oe=xe(w,R),le=xe(w,R),ve=xe(w,R);return{redX:N,redY:J,greenX:L,greenY:X,blueX:H,blueY:oe,whiteX:le,whiteY:ve}}function B(w,R){const N=["NO_COMPRESSION","RLE_COMPRESSION","ZIPS_COMPRESSION","ZIP_COMPRESSION","PIZ_COMPRESSION","PXR24_COMPRESSION","B44_COMPRESSION","B44A_COMPRESSION","DWAA_COMPRESSION","DWAB_COMPRESSION"],J=Ue(w,R);return N[J]}function ce(w,R){const N=pe(w,R),J=pe(w,R),L=pe(w,R),X=pe(w,R);return{xMin:N,yMin:J,xMax:L,yMax:X}}function _e(w,R){const N=["INCREASING_Y"],J=Ue(w,R);return N[J]}function Oe(w,R){const N=xe(w,R),J=xe(w,R);return[N,J]}function Te(w,R){const N=xe(w,R),J=xe(w,R),L=xe(w,R);return[N,J,L]}function ft(w,R,N,J,L){if(J==="string"||J==="stringvector"||J==="iccProfile")return We(R,N,L);if(J==="chlist")return wt(w,R,N,L);if(J==="chromaticities")return j(w,N);if(J==="compression")return B(w,N);if(J==="box2i")return ce(w,N);if(J==="lineOrder")return _e(w,N);if(J==="float")return xe(w,N);if(J==="v2f")return Oe(w,N);if(J==="v3f")return Te(w,N);if(J==="int")return it(w,N);if(J==="rational")return Je(w,N);if(J==="timecode")return De(w,N);if(J==="preview")return N.value+=L,"skipped";N.value+=L}function rt(w,R,N){const J={};if(w.getUint32(0,!0)!=20000630)throw new Error("THREE.EXRLoader: Provided file doesn't appear to be in OpenEXR format.");J.version=w.getUint8(4);const L=w.getUint8(5);J.spec={singleTile:!!(L&2),longName:!!(L&4),deepFormat:!!(L&8),multiPart:!!(L&16)},N.value=8;let X=!0;for(;X;){const H=Be(R,N);if(H==0)X=!1;else{const oe=Be(R,N),le=pe(w,N),ve=ft(w,R,N,oe,le);ve===void 0?console.warn(`THREE.EXRLoader: Skipped unknown header attribute type '${oe}'.`):J[H]=ve}}if(L&-5)throw console.error("THREE.EXRHeader:",J),new Error("THREE.EXRLoader: Provided file is currently unsupported.");return J}function Fe(w,R,N,J,L){const X={size:0,viewer:R,array:N,offset:J,width:w.dataWindow.xMax-w.dataWindow.xMin+1,height:w.dataWindow.yMax-w.dataWindow.yMin+1,channels:w.channels.length,bytesPerLine:null,lines:null,inputSize:null,type:w.channels[0].pixelType,uncompress:null,getter:null,format:null,colorSpace:pi};switch(w.compression){case"NO_COMPRESSION":X.lines=1,X.uncompress=K;break;case"RLE_COMPRESSION":X.lines=1,X.uncompress=se;break;case"ZIPS_COMPRESSION":X.lines=1,X.uncompress=Ae;break;case"ZIP_COMPRESSION":X.lines=16,X.uncompress=Ae;break;case"PIZ_COMPRESSION":X.lines=32,X.uncompress=Re;break;case"PXR24_COMPRESSION":X.lines=16,X.uncompress=ne;break;case"DWAA_COMPRESSION":X.lines=32,X.uncompress=ye;break;case"DWAB_COMPRESSION":X.lines=256,X.uncompress=ye;break;default:throw new Error("EXRLoader.parse: "+w.compression+" is unsupported")}if(X.scanlineBlockSize=X.lines,X.type==1)switch(L){case Oi:X.getter=nt,X.inputSize=2;break;case Ji:X.getter=Ke,X.inputSize=2;break}else if(X.type==2)switch(L){case Oi:X.getter=xe,X.inputSize=4;break;case Ji:X.getter=Ge,X.inputSize=4}else throw new Error("EXRLoader.parse: unsupported pixelType "+X.type+" for "+w.compression+".");X.blockCount=(w.dataWindow.yMax+1)/X.scanlineBlockSize;for(let oe=0;oe<X.blockCount;oe++)we(R,J);X.outputChannels=X.channels==3?4:X.channels;const H=X.width*X.height*X.outputChannels;switch(L){case Oi:X.byteArray=new Float32Array(H),X.channels<X.outputChannels&&X.byteArray.fill(1,0,H);break;case Ji:X.byteArray=new Uint16Array(H),X.channels<X.outputChannels&&X.byteArray.fill(15360,0,H);break;default:console.error("THREE.EXRLoader: unsupported type: ",L);break}return X.bytesPerLine=X.width*X.inputSize*X.channels,X.outputChannels==4?(X.format=di,X.colorSpace=pi):(X.format=Ko,X.colorSpace=is),X}const je=new DataView(e),bt=new Uint8Array(e),Le={value:0},Vt=rt(je,e,Le),ke=Fe(Vt,je,bt,Le,this.type),vt={value:0},st={R:0,G:1,B:2,A:3,Y:0};for(let w=0;w<ke.height/ke.scanlineBlockSize;w++){const R=pe(je,Le);ke.size=pe(je,Le),ke.lines=R+ke.scanlineBlockSize>ke.height?ke.height-R:ke.scanlineBlockSize;const N=ke.size<ke.lines*ke.bytesPerLine?ke.uncompress(ke):K(ke);Le.value+=ke.size;for(let J=0;J<ke.scanlineBlockSize;J++){const L=J+w*ke.scanlineBlockSize;if(L>=ke.height)break;for(let X=0;X<ke.channels;X++){const H=st[Vt.channels[X].name];for(let oe=0;oe<ke.width;oe++){vt.value=(J*(ke.channels*ke.width)+X*ke.width+oe)*ke.inputSize;const le=(ke.height-1-L)*(ke.width*ke.outputChannels)+oe*ke.outputChannels+H;ke.byteArray[le]=ke.getter(N,vt)}}}}return{header:Vt,width:ke.width,height:ke.height,data:ke.byteArray,format:ke.format,colorSpace:ke.colorSpace,type:this.type}}setDataType(e){return this.type=e,this}load(e,t,n,r){function s(o,a){o.colorSpace=a.colorSpace,o.minFilter=St,o.magFilter=St,o.generateMipmaps=!1,o.flipY=!1,t&&t(o,a)}return super.load(e,s,n,r)}}class HM extends ZS{constructor(e){super(e),this.type=Ji}parse(e){const t=function(g,y){switch(g){case 1:throw new Error("THREE.RGBELoader: Read Error: "+(y||""));case 2:throw new Error("THREE.RGBELoader: Write Error: "+(y||""));case 3:throw new Error("THREE.RGBELoader: Bad File Format: "+(y||""));default:case 4:throw new Error("THREE.RGBELoader: Memory Error: "+(y||""))}},n=`
4970
4970
  `,r=function(g,y,b){y=y||1024;let _=g.pos,E=-1,I=0,T="",M=String.fromCharCode.apply(null,new Uint16Array(g.subarray(_,_+128)));for(;0>(E=M.indexOf(n))&&I<y&&_<g.byteLength;)T+=M,I+=M.length,_+=128,M+=String.fromCharCode.apply(null,new Uint16Array(g.subarray(_,_+128)));return-1<E?(b!==!1&&(g.pos+=I+E+1),T+M.slice(0,E)):!1},s=function(g){const y=/^#\?(\S+)/,b=/^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/,_=/^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/,E=/^\s*FORMAT=(\S+)\s*$/,I=/^\s*\-Y\s+(\d+)\s+\+X\s+(\d+)\s*$/,T={valid:0,string:"",comments:"",programtype:"RGBE",format:"",gamma:1,exposure:1,width:0,height:0};let M,D;for((g.pos>=g.byteLength||!(M=r(g)))&&t(1,"no header found"),(D=M.match(y))||t(3,"bad initial token"),T.valid|=1,T.programtype=D[1],T.string+=M+`
4971
4971
  `;M=r(g),M!==!1;){if(T.string+=M+`
4972
4972
  `,M.charAt(0)==="#"){T.comments+=M+`
4973
- `;continue}if((D=M.match(b))&&(T.gamma=parseFloat(D[1])),(D=M.match(_))&&(T.exposure=parseFloat(D[1])),(D=M.match(E))&&(T.valid|=2,T.format=D[1]),(D=M.match(I))&&(T.valid|=4,T.height=parseInt(D[1],10),T.width=parseInt(D[2],10)),T.valid&2&&T.valid&4)break}return T.valid&2||t(3,"missing format specifier"),T.valid&4||t(3,"missing image size specifier"),T},o=function(g,y,b){const _=y;if(_<8||_>32767||g[0]!==2||g[1]!==2||g[2]&128)return new Uint8Array(g);_!==(g[2]<<8|g[3])&&t(3,"wrong scanline width");const E=new Uint8Array(4*y*b);E.length||t(4,"unable to allocate buffer space");let I=0,T=0;const M=4*_,D=new Uint8Array(4),C=new Uint8Array(M);let P=b;for(;P>0&&T<g.byteLength;){T+4>g.byteLength&&t(1),D[0]=g[T++],D[1]=g[T++],D[2]=g[T++],D[3]=g[T++],(D[0]!=2||D[1]!=2||(D[2]<<8|D[3])!=_)&&t(3,"bad rgbe scanline format");let G=0,Q;for(;G<M&&T<g.byteLength;){Q=g[T++];const W=Q>128;if(W&&(Q-=128),(Q===0||G+Q>M)&&t(3,"bad scanline data"),W){const U=g[T++];for(let F=0;F<Q;F++)C[G++]=U}else C.set(g.subarray(T,T+Q),G),G+=Q,T+=Q}const k=_;for(let W=0;W<k;W++){let U=0;E[I]=C[W+U],U+=_,E[I+1]=C[W+U],U+=_,E[I+2]=C[W+U],U+=_,E[I+3]=C[W+U],I+=4}P--}return E},a=function(g,y,b,_){const E=g[y+3],I=Math.pow(2,E-128)/255;b[_+0]=g[y+0]*I,b[_+1]=g[y+1]*I,b[_+2]=g[y+2]*I,b[_+3]=1},l=function(g,y,b,_){const E=g[y+3],I=Math.pow(2,E-128)/255;b[_+0]=eu.toHalfFloat(Math.min(g[y+0]*I,65504)),b[_+1]=eu.toHalfFloat(Math.min(g[y+1]*I,65504)),b[_+2]=eu.toHalfFloat(Math.min(g[y+2]*I,65504)),b[_+3]=eu.toHalfFloat(1)},c=new Uint8Array(e);c.pos=0;const u=s(c),d=u.width,p=u.height,f=o(c.subarray(c.pos),d,p);let m,A,v;switch(this.type){case Oi:v=f.length/4;const g=new Float32Array(v*4);for(let b=0;b<v;b++)a(f,b*4,g,b*4);m=g,A=Oi;break;case Ji:v=f.length/4;const y=new Uint16Array(v*4);for(let b=0;b<v;b++)l(f,b*4,y,b*4);m=y,A=Ji;break;default:throw new Error("THREE.RGBELoader: Unsupported type: "+this.type)}return{width:d,height:p,data:m,header:u.string,gamma:u.gamma,exposure:u.exposure,type:A}}setDataType(e){return this.type=e,this}load(e,t,n,r){function s(o,a){switch(o.type){case Oi:case Ji:o.colorSpace=pi,o.minFilter=St,o.magFilter=St,o.generateMipmaps=!1,o.flipY=!0;break}t&&t(o,a)}return super.load(e,s,n,r)}}const G3="NEEDLE_lightmaps",Qg=ee("debuglightmapsextension")||ee("debuglightmaps");var th=(i=>(i[i.Lightmap=0]="Lightmap",i[i.Skybox=1]="Skybox",i[i.Reflection=2]="Reflection",i))(th||{});class G${constructor(e,t,n){h(this,"parser"),h(this,"registry"),h(this,"source"),this.parser=e,this.registry=t,this.source=n}get name(){return G3}afterRoot(e){const t=this.parser.json.extensions;if(t){const n=t[G3];if(n){const r=n.textures;return r!=null&&r.length?(Qg&&console.log(n),new Promise(async(s,o)=>{const a=[];for(const c of r)if(c.pointer){Qg&&console.log(c);let u=null;if(c.pointer.startsWith("/textures/"))Qg&&console.log("Load texture from gltf",c.pointer),u=VE(this.parser,c.pointer).then(d=>this.resolveTexture(c,d));else if(typeof c.pointer=="string"){Qg&&console.log("Load texture from path",c.pointer);const d=kl(this.source,c.pointer);let p;d.endsWith(".exr")?p=new o_(this.parser.options.manager):d.endsWith(".hdr")?p=new HM(this.parser.options.manager):p=new Ba(this.parser.options.manager),u=p.loadAsync(d,void 0).then(f=>this.resolveTexture(c,f))}else c.pointer;u&&a.push(u)}const l=await Jm(a);l!=null&&l.anyFailed&&pt()&&console.error("Failed to load lightmap extension",l),s()})):null}}return null}resolveTexture(e,t){const n=t;Qg&&console.log("Lightmap loaded:",n),n!=null&&n.isTexture&&(this.registry?(n.colorSpace=pi,this.registry.registerTexture(this.source,e.type,n,e.index)):console.log(th[e.type],e.pointer,n))}}const Q3=!!ee("debuglightmaps");class Q${constructor(e){h(this,"_context"),h(this,"_lightmaps",new Map),this._context=e}clear(){this._lightmaps.clear()}registerTexture(e,t,n,r){Q3&&console.log("Registering ",th[t]+' "'+e+'"',n),this._lightmaps.has(e)||this._lightmaps.set(e,new Map);const s=this._lightmaps.get(e),o=s?.get(t)??[];o.length<r&&(o.length=r+1),o[r]=n,s?.set(t,o)}tryGetLightmap(e,t=0){return this.tryGet(e,th.Lightmap,t)}tryGetSkybox(e){return this.tryGet(e,th.Skybox,0)}tryGetReflection(e){return this.tryGet(e,th.Reflection,0)}tryGet(e,t,n){var r;if(!e)return Q3&&console.warn("Missing source id"),null;const s=((r=this._lightmaps.get(e))==null?void 0:r.get(t))??null;return!(s!=null&&s.length)||s.length<=n?null:s[n]}}Ut.lights_fragment_maps=Ut.lights_fragment_maps.replace("vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );",`
4973
+ `;continue}if((D=M.match(b))&&(T.gamma=parseFloat(D[1])),(D=M.match(_))&&(T.exposure=parseFloat(D[1])),(D=M.match(E))&&(T.valid|=2,T.format=D[1]),(D=M.match(I))&&(T.valid|=4,T.height=parseInt(D[1],10),T.width=parseInt(D[2],10)),T.valid&2&&T.valid&4)break}return T.valid&2||t(3,"missing format specifier"),T.valid&4||t(3,"missing image size specifier"),T},o=function(g,y,b){const _=y;if(_<8||_>32767||g[0]!==2||g[1]!==2||g[2]&128)return new Uint8Array(g);_!==(g[2]<<8|g[3])&&t(3,"wrong scanline width");const E=new Uint8Array(4*y*b);E.length||t(4,"unable to allocate buffer space");let I=0,T=0;const M=4*_,D=new Uint8Array(4),C=new Uint8Array(M);let P=b;for(;P>0&&T<g.byteLength;){T+4>g.byteLength&&t(1),D[0]=g[T++],D[1]=g[T++],D[2]=g[T++],D[3]=g[T++],(D[0]!=2||D[1]!=2||(D[2]<<8|D[3])!=_)&&t(3,"bad rgbe scanline format");let G=0,Q;for(;G<M&&T<g.byteLength;){Q=g[T++];const W=Q>128;if(W&&(Q-=128),(Q===0||G+Q>M)&&t(3,"bad scanline data"),W){const U=g[T++];for(let F=0;F<Q;F++)C[G++]=U}else C.set(g.subarray(T,T+Q),G),G+=Q,T+=Q}const k=_;for(let W=0;W<k;W++){let U=0;E[I]=C[W+U],U+=_,E[I+1]=C[W+U],U+=_,E[I+2]=C[W+U],U+=_,E[I+3]=C[W+U],I+=4}P--}return E},a=function(g,y,b,_){const E=g[y+3],I=Math.pow(2,E-128)/255;b[_+0]=g[y+0]*I,b[_+1]=g[y+1]*I,b[_+2]=g[y+2]*I,b[_+3]=1},l=function(g,y,b,_){const E=g[y+3],I=Math.pow(2,E-128)/255;b[_+0]=eu.toHalfFloat(Math.min(g[y+0]*I,65504)),b[_+1]=eu.toHalfFloat(Math.min(g[y+1]*I,65504)),b[_+2]=eu.toHalfFloat(Math.min(g[y+2]*I,65504)),b[_+3]=eu.toHalfFloat(1)},c=new Uint8Array(e);c.pos=0;const u=s(c),d=u.width,p=u.height,f=o(c.subarray(c.pos),d,p);let m,A,v;switch(this.type){case Oi:v=f.length/4;const g=new Float32Array(v*4);for(let b=0;b<v;b++)a(f,b*4,g,b*4);m=g,A=Oi;break;case Ji:v=f.length/4;const y=new Uint16Array(v*4);for(let b=0;b<v;b++)l(f,b*4,y,b*4);m=y,A=Ji;break;default:throw new Error("THREE.RGBELoader: Unsupported type: "+this.type)}return{width:d,height:p,data:m,header:u.string,gamma:u.gamma,exposure:u.exposure,type:A}}setDataType(e){return this.type=e,this}load(e,t,n,r){function s(o,a){switch(o.type){case Oi:case Ji:o.colorSpace=pi,o.minFilter=St,o.magFilter=St,o.generateMipmaps=!1,o.flipY=!0;break}t&&t(o,a)}return super.load(e,s,n,r)}}const GU="NEEDLE_lightmaps",Qg=ee("debuglightmapsextension")||ee("debuglightmaps");var th=(i=>(i[i.Lightmap=0]="Lightmap",i[i.Skybox=1]="Skybox",i[i.Reflection=2]="Reflection",i))(th||{});class G${constructor(e,t,n){h(this,"parser"),h(this,"registry"),h(this,"source"),this.parser=e,this.registry=t,this.source=n}get name(){return GU}afterRoot(e){const t=this.parser.json.extensions;if(t){const n=t[GU];if(n){const r=n.textures;return r!=null&&r.length?(Qg&&console.log(n),new Promise(async(s,o)=>{const a=[];for(const c of r)if(c.pointer){Qg&&console.log(c);let u=null;if(c.pointer.startsWith("/textures/"))Qg&&console.log("Load texture from gltf",c.pointer),u=VE(this.parser,c.pointer).then(d=>this.resolveTexture(c,d));else if(typeof c.pointer=="string"){Qg&&console.log("Load texture from path",c.pointer);const d=kl(this.source,c.pointer);let p;d.endsWith(".exr")?p=new o_(this.parser.options.manager):d.endsWith(".hdr")?p=new HM(this.parser.options.manager):p=new Ba(this.parser.options.manager),u=p.loadAsync(d,void 0).then(f=>this.resolveTexture(c,f))}else c.pointer;u&&a.push(u)}const l=await Jm(a);l!=null&&l.anyFailed&&pt()&&console.error("Failed to load lightmap extension",l),s()})):null}}return null}resolveTexture(e,t){const n=t;Qg&&console.log("Lightmap loaded:",n),n!=null&&n.isTexture&&(this.registry?(n.colorSpace=pi,this.registry.registerTexture(this.source,e.type,n,e.index)):console.log(th[e.type],e.pointer,n))}}const QU=!!ee("debuglightmaps");class Q${constructor(e){h(this,"_context"),h(this,"_lightmaps",new Map),this._context=e}clear(){this._lightmaps.clear()}registerTexture(e,t,n,r){QU&&console.log("Registering ",th[t]+' "'+e+'"',n),this._lightmaps.has(e)||this._lightmaps.set(e,new Map);const s=this._lightmaps.get(e),o=s?.get(t)??[];o.length<r&&(o.length=r+1),o[r]=n,s?.set(t,o)}tryGetLightmap(e,t=0){return this.tryGet(e,th.Lightmap,t)}tryGetSkybox(e){return this.tryGet(e,th.Skybox,0)}tryGetReflection(e){return this.tryGet(e,th.Reflection,0)}tryGet(e,t,n){var r;if(!e)return QU&&console.warn("Missing source id"),null;const s=((r=this._lightmaps.get(e))==null?void 0:r.get(t))??null;return!(s!=null&&s.length)||s.length<=n?null:s[n]}}Ut.lights_fragment_maps=Ut.lights_fragment_maps.replace("vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );",`
4974
4974
  vec2 lUv = vLightMapUv.xy * lightmapScaleOffset.xy + vec2(lightmapScaleOffset.z, (1. - (lightmapScaleOffset.y + lightmapScaleOffset.w)));
4975
4975
  vec4 lightMapTexel = texture2D( lightMap, lUv);
4976
4976
  // The range of RGBM lightmaps goes from 0 to 34.49 (5^2.2) in linear space, and from 0 to 5 in gamma space.
@@ -4993,7 +4993,7 @@ version 0.6.9
4993
4993
  irradiance += 0.;
4994
4994
  #else
4995
4995
  irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );
4996
- #endif`),Ne.lightmap.lightmapScaleOffset={value:new Ye(1,1,0,0)};const Hg=ee("debugphysics"),H3=new Nr;function Vg(i){var e;return((e=i.userData)==null?void 0:e["needle:raycast-mesh"])instanceof ut?i.userData["needle:raycast-mesh"]:(Hg&&(i["needle:warned about missing raycast mesh"]||(i["needle:warned about missing raycast mesh"]=!0,console.warn("No raycast mesh found for object: "+i.name))),null)}function a_(i,e){(i.type==="Mesh"||i.type==="SkinnedMesh")&&(i.userData||(i.userData={}),i.userData["needle:raycast-mesh"]=e,Hg&&delete i["needle:warned about missing raycast mesh"])}class To{constructor(){h(this,"ray"),h(this,"cam"),h(this,"screenPoint"),h(this,"raycaster"),h(this,"results"),h(this,"targets"),h(this,"recursive",!0),h(this,"minDistance"),h(this,"maxDistance"),h(this,"lineThreshold"),h(this,"layerMask"),h(this,"ignore"),h(this,"testObject")}screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new $),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setLayer(e){H3.set(e),this.layerMask=H3}setMask(e){this.layerMask||(this.layerMask=new Nr);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}h(To,"AllLayers",4294967295);class V3{constructor(e,t,n){h(this,"distance"),h(this,"point"),h(this,"object"),this.object=e,this.distance=t,this.point=n}}class W3{constructor(e){h(this,"context"),h(this,"engine"),h(this,"raycaster",new Au),h(this,"defaultRaycastOptions",new To),h(this,"targetBuffer",new Array(1)),h(this,"defaultThresholds",{Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}}),h(this,"sphereResults",new Array),h(this,"sphereMask",new Nr),h(this,"tempBoundingBox",new gi),this.context=e}raycastPhysicsFast(e,t=void 0,n=1/0,r=!0){var s;return((s=this.context.physics.engine)==null?void 0:s.raycast(e,t,n,r))??null}raycastPhysicsFastAndGetNormal(e,t=void 0,n=1/0,r=!0){var s;return((s=this.context.physics.engine)==null?void 0:s.raycastAndGetNormal(e,t,n,r))??null}sphereOverlapPhysics(e,t){var n;return((n=this.context.physics.engine)==null?void 0:n.sphereOverlap(e,t))??null}sphereOverlap(e,t,n=!0){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const r=new un(e,t),s=this.sphereMask;s.enableAll(),s.disable(2);for(const o of this.context.scene.children)this.onSphereOverlap(o,r,s,this.sphereResults,n);return this.sphereResults.sort((o,a)=>o.distance-a.distance)}onSphereOverlap(e,t,n,r,s){if(e.type==="Mesh"&&e.layers.test(n)&&!Ct.isGizmo(e)){const o=e,a=o.geometry;if(a&&(a.boundingBox||a.computeBoundingBox(),a.boundingBox)){o.matrixWorldNeedsUpdate&&o.updateMatrixWorld();const l=this.tempBoundingBox.copy(a.boundingBox).applyMatrix4(o.matrixWorld);if(t.intersectsBox(l)){const c=Rt(e),u=c.distanceTo(t.center),d=new V3(e,u,c);if(r.push(d),!s)return}}}if(e.children)for(const o of e.children){const a=r.length;if(this.onSphereOverlap(o,t,n,r,s),a!=r.length&&!s)return}}raycastFromRay(e,t=null){const n=t??this.defaultRaycastOptions;n.ray=e;const r=this.raycast(n);return n===this.defaultRaycastOptions&&(n.ray=void 0),r}raycast(e=null){e||(e=this.defaultRaycastOptions);const t=e.screenPoint??this.context.input.mousePositionRC,n=e.raycaster??this.raycaster;if(n.near=e.minDistance??0,n.far=e.maxDistance??1/0,n.params=this.defaultThresholds,e.lineThreshold===void 0&&(e.lineThreshold=-1),n.params.Line={threshold:e.lineThreshold},e.ray)n.ray.copy(e.ray);else{const a=e.cam??this.context.mainCamera;if(!a)return Hg&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const l=this.context.xrCamera;this.context.isInXR&&l instanceof bS&&l.cameras.length>0?n.setFromCamera(t,l.cameras[0]):n.setFromCamera(t,a)}let r=e.targets;r||(r=this.targetBuffer,r.length=1,r[0]=this.context.scene);let s=e.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),s||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),s=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof Nr?n.layers.mask=e.layerMask.mask:n.layers.mask=e.layerMask:(n.layers.enableAll(),n.layers.disable(2)),Hg&&(Ct.DrawRay(n.ray.origin,n.ray.direction,16711680,2),console.time("raycast")),s.length=0,this.intersect(this.raycaster,r,s,e),s.sort((a,l)=>a.distance-l.distance);const o=e.ignore;return o!==void 0&&o.length>0&&(s=s.filter(a=>!o.includes(a.object))),Hg&&(console.timeEnd("raycast"),console.log("hits:",s!=null&&s.length?[...s]:"nothing")),s}intersect(e,t,n,r){var s;for(const o of t){if(o.visible===!1||Ct.isGizmo(o)||r.lineThreshold!==void 0&&r.lineThreshold<0&&o instanceof An)continue;const a=(s=r.testObject)==null?void 0:s.call(r,o);if(a!==!1){if(a!=="continue in children"){const l=o,c=l.geometry;if(c){const u=Vg(o);u&&(l.geometry=u),e.intersectObject(o,!1,n),l.geometry=c}}r.recursive!==!1&&this.intersect(e,o.children,n,r)}}return n}}const H$=ee("debugplayerview");var ih=(i=>(i.Browser="browser",i.Headset="headset",i.Handheld="handheld",i))(ih||{});class q3{constructor(e,t){h(this,"userId"),h(this,"context"),h(this,"viewDevice","browser"),h(this,"removed",!1),h(this,"_object"),this.userId=e,this.context=t}get currentObject(){return this._object}set currentObject(e){this._object=e}get isConnected(){return this.context.connection.userIsInRoom(this.userId)}}class X3{constructor(e){h(this,"context"),h(this,"playerViews",new Map),this.context=e}setPlayerView(e,t,n){let r=this.playerViews.get(e);r||(r=new q3(e,this.context),this.playerViews.set(e,r)),r.viewDevice=n,r.currentObject=t,r.removed=!1}getPlayerView(e){if(!!e){if(!this.context.connection.userIsInRoom(e)){this.playerViews.delete(e);return}return this.playerViews.get(e)}}removePlayerView(e,t){const n=this.playerViews.get(e);n?.viewDevice===t&&(H$&&console.log("REMOVE",e),n.removed=!0,this.playerViews.delete(e))}}new Gn;const Wg=new Uint8Array(4);Wg[0]=255,Wg[1]=255,Wg[2]=255,Wg[3]=255;const V$=new Rs(Wg,1,1,di);function Y3(i,e=1){const t="alpha"in i,n=e*e,r=new Uint8Array(4*n),s=Math.floor(i.r*255),o=Math.floor(i.g*255),a=Math.floor(i.b*255);for(let c=0;c<n;c++){const u=c*4;r[u+0]=s,r[u+1]=o,r[u+2]=a,t?r[u+3]=Math.floor(i.alpha*255):r[u+3]=255}const l=new Rs(r,e,e);return l.needsUpdate=!0,l}function W$(i,e,t,n=1,r=3){const s=n*r,o=[i,e,t],a=o.length,l=new Uint8Array(4*a*s),c=new Se;for(let d=0;d<r;d++){const p=Math.floor(d/r*a),f=Ze.clamp(p+1,0,a-1),m=o[p],A=o[f],v=d/r*a%1;c.lerpColors(m,A,v);const g=Math.floor(c.r*255),y=Math.floor(c.g*255),b=Math.floor(c.b*255);for(let _=0;_<n;_++){const E=(d*n+_)*4;l[E+0]=g,l[E+1]=y,l[E+2]=b,l[E+3]=255}}const u=new Rs(l,n,r);return u.needsUpdate=!0,u}function l_(i,e){const t=i.elements;e||(e=[]),e.length=0;for(let n=0;n<16;n+=4){const r=t[n],s=t[n+1],o=t[n+2],a=t[n+3],l=new Ye(r,s,o,a);e.push(l)}return e}const VM=[],J3=[];function q$(i,e){if(VM.length===0)for(let t=0;t<27;t++)VM.push(0);e||(e=VM);for(let t=0;t<27;t++)J3[t]=e[t];e=J3,i.unity_SHAr={value:new Ye(e[9],e[3],e[6],e[0])},i.unity_SHBr={value:new Ye(e[12],e[15],e[18],e[21])},i.unity_SHAg={value:new Ye(e[10],e[4],e[7],e[1])},i.unity_SHBg={value:new Ye(e[13],e[16],e[19],e[22])},i.unity_SHAb={value:new Ye(e[11],e[5],e[8],e[2])},i.unity_SHBb={value:new Ye(e[14],e[17],e[20],e[23])},i.unity_SHC={value:new Ye(e[24],e[25],e[26],1)}}class X${constructor(e,t,n){h(this,"vertexShader"),h(this,"fragmentShader"),h(this,"technique"),this.vertexShader=e,this.fragmentShader=t,this.technique=n}}async function Y$(i,e){if(!i)return console.error("Can not find technique: no shader data"),null;const t=i.programs[e],n=t.vertexShader,r=t.fragmentShader;if(n!==void 0&&r!==void 0){const s=i.shaders[n],o=i.shaders[r];if(s.uri&&o.uri||s.code&&o.code){if(!s.code&&s.uri&&await K3(s),!o.code&&o.uri&&await K3(o),!s.code||!o.code)return null;const a=i.techniques[e];return new X$(s.code,o.code,a)}}return console.error("Shader technique not found",e),null}async function K3(i){const e=i.uri;if(e)if(e.endsWith(".glsl")){const t=await new Gn().loadAsync(e);i.code=t.toString()}else i.code=J$(i.uri)}function J$(i){return decodeURIComponent(Array.prototype.map.call(atob(i),function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}const ua=ee("debugenvlight");var Up=(i=>(i[i.Skybox=0]="Skybox",i[i.Trilight=1]="Trilight",i[i.Flat=3]="Flat",i[i.Custom=4]="Custom",i))(Up||{}),c_=(i=>(i[i.Skybox=0]="Skybox",i[i.Custom=1]="Custom",i))(c_||{});class Z3{constructor(e){h(this,"context"),h(this,"_currentLightSettingsId"),h(this,"_sceneLightSettings"),h(this,"_timevec4",new Ye),h(this,"__currentReflectionId",null),h(this,"_lighting",{}),this.context=e,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}preUpdate(){const e=this.context.time;this._timevec4.x=e.time,this._timevec4.y=Math.sin(e.time),this._timevec4.z=Math.cos(e.time),this._timevec4.w=e.deltaTime}get timeVec4(){return this._timevec4}get environmentIntensity(){if(!this._sceneLightSettings||!this._currentLightSettingsId)return 1;const e=this._sceneLightSettings.get(this._currentLightSettingsId);return e?e.ambientIntensity:1}get sceneLightSettings(){var e;return(e=this._sceneLightSettings)==null?void 0:e.values()}enable(e){var t;e instanceof ni&&(e=e.uri);const n=(t=this._sceneLightSettings)==null?void 0:t.get(e);return n?(ua&&console.log("Enable scene light settings",e,n),e!==this._currentLightSettingsId&&this._currentLightSettingsId&&this.disable(this._currentLightSettingsId),this._currentLightSettingsId=e,n.enabled=!0,!0):(ua&&console.warn("No light settings found for",e),!1)}disable(e){var t;if(e instanceof ni&&(e=e.uri),e==null)return!1;const n=(t=this._sceneLightSettings)==null?void 0:t.get(e);return n?(ua&&console.log("Disable scene light settings",e,n),n.enabled=!1,!0):!1}disableCurrent(){if(this._currentLightSettingsId){const e=this._currentLightSettingsId;return this.disable(this._currentLightSettingsId),e}return null}internalRegisterSceneLightSettings(e){const t=e.sourceId;if(!t){console.error("Missing source id for scene light settings, can not register:",e);return}ua&&console.log("Register "+e?.sourceId+" lighting",e),this._sceneLightSettings||(this._sceneLightSettings=new Map),this._sceneLightSettings.set(t,e)}internalUnregisterSceneLightSettings(e){const t=e.sourceId;if(!t){console.error("Missing source id for scene light settings, can not unregister:",e);return}ua&&console.log("Unregister "+e?.sourceId+" lighting",e),this._sceneLightSettings&&this._sceneLightSettings.delete(t)}internalRegisterReflection(e,t){ua&&console.log("Register reflection",e,t);const n=new $3(this.context,t,1);this._lighting[e]=n}internalGetReflection(e){return this._lighting[e]}internalEnableReflection(e){var t;this.__currentReflectionId=e;const n=(t=this._sceneLightSettings)==null?void 0:t.get(e);switch(ua&&console.log("Enable reflection",e,n?Up[n.ambientMode]:"Unknown ambient mode"),n?.ambientMode){case 0:case 4:const r=this.internalGetReflection(e);if(r&&r.Source){ua&&console.log("Setting environment reflection",r);const s=this.context.scene,o=r.Source;o.mapping=mo,s.environment=o;return}else ua&&console.warn("Could not find reflection for source",e);break}if(n?.environmentReflectionSource===1)switch(n?.ambientMode){case 1:if(n.ambientTrilight){const r=n.ambientTrilight,s=W$(r[0],r[1],r[2],64,64);s.colorSpace=dt,s.mapping=mo,this.context.scene.environment=s}else console.error("Missing ambient trilight",n.sourceId);return;case 3:if(n.ambientLight){const r=Y3(n.ambientLight,64);r.colorSpace=dt,r.mapping=mo,this.context.scene.environment=r}else console.error("Missing ambientlight",n.sourceId);return;default:return}}internalDisableReflection(e){if(e&&e!==this.__currentReflectionId){ua&&console.log("Not disabling reflection for",e,"because it is not the current light settings id",this.__currentReflectionId);return}ua&&console.log("Disable reflection",e);const t=this.context.scene;t.environment=null}}class $3{constructor(e,t,n=1){h(this,"_source"),this._source=t,t.mapping=mo}get Source(){return this._source}}const eF=ee("timescale");let WM=1;typeof eF=="number"&&(WM=eF);class tF{constructor(){h(this,"_time",0),h(this,"_deltaTime",0),h(this,"_deltaTimeUnscaled",0),h(this,"timeScale",1),h(this,"_frame",0),h(this,"clock",new rC),h(this,"_smoothedFps",0),h(this,"_smoothedDeltaTime",0),h(this,"_fpsSamples",[]),h(this,"_fpsSampleIndex",0),typeof WM=="number"&&(this.timeScale=WM)}get time(){return this._time}set time(e){this._time=e}get deltaTime(){return this._deltaTime}set deltaTime(e){this._deltaTime=e}get deltaTimeUnscaled(){return this._deltaTimeUnscaled}get frame(){return this._frame}set frame(e){this._frame=e}get frameCount(){return this.frame}get realtimeSinceStartup(){return this.clock.elapsedTime}get smoothedFps(){return this._smoothedFps}get smoothedDeltaTime(){return 1/this._smoothedFps}update(){this.deltaTime=this.clock.getDelta(),this.deltaTime=Math.min(.1,this.deltaTime),this._deltaTimeUnscaled=this.deltaTime,this.deltaTime<=0&&(this.deltaTime=1e-12),this.deltaTime*=this.timeScale,this.frame+=1,this.time+=this.deltaTime,this._fpsSamples.length<60?this._fpsSamples.push(this.deltaTime):this._fpsSamples[this._fpsSampleIndex++%60]=this.deltaTime;let e=0;for(let t=0;t<this._fpsSamples.length;t++)e+=this._fpsSamples[t];this._smoothedDeltaTime=e/this._fpsSamples.length,this._smoothedFps=1/this._smoothedDeltaTime}}const Io=ee("debuglicense");let Fu="basic";Io&&console.log("License Type: "+Fu);function da(){switch(Fu){case"pro":case"enterprise":return!0}return!1}function qM(){switch(Fu){case"indie":return!0}return!1}function Fp(){return da()||qM()}const iF=[];function K$(i){if(da()||qM())return i(!0);iF.push(i)}function Z$(i){for(const e of iF)try{e(i)}catch{}}ii.registerCallback(bn.ContextRegistered,i=>{tee(i.context),nee(),eee(i.context)});let Nu,XM=!1,h_="";async function $$(){if(Nu)return Nu;if(Fu==="basic")try{const i="https://engine.needle.tools/licensing/check?location="+encodeURIComponent(window.location.href)+"&version="+Fl+"&generator="+encodeURIComponent(_b),e=await fetch(i,{method:"GET"}).catch(t=>{Io&&console.error("License check failed",t)});e?.status===200?(XM=!1,Io&&console.log("License check succeeded"),Fu="pro",Z$(!0)):e?.status===403?(XM=!0,h_=await e.text()):Io&&console.log("License check failed with status "+e?.status)}catch(i){Io&&console.error("License check failed",i)}else Io&&console.log('Runtime license check is skipped because license is already applied as "'+Fu+'"')}Nu=$$();async function eee(i){function e(){const r=document.createElement("div");r.className="needle-forbidden",r.style.cssText=`
4996
+ #endif`),Ne.lightmap.lightmapScaleOffset={value:new Ye(1,1,0,0)};const Hg=ee("debugphysics"),HU=new Nr;function Vg(i){var e;return((e=i.userData)==null?void 0:e["needle:raycast-mesh"])instanceof ut?i.userData["needle:raycast-mesh"]:(Hg&&(i["needle:warned about missing raycast mesh"]||(i["needle:warned about missing raycast mesh"]=!0,console.warn("No raycast mesh found for object: "+i.name))),null)}function a_(i,e){(i.type==="Mesh"||i.type==="SkinnedMesh")&&(i.userData||(i.userData={}),i.userData["needle:raycast-mesh"]=e,Hg&&delete i["needle:warned about missing raycast mesh"])}class To{constructor(){h(this,"ray"),h(this,"cam"),h(this,"screenPoint"),h(this,"raycaster"),h(this,"results"),h(this,"targets"),h(this,"recursive",!0),h(this,"minDistance"),h(this,"maxDistance"),h(this,"lineThreshold"),h(this,"layerMask"),h(this,"ignore"),h(this,"testObject")}screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new $),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setLayer(e){HU.set(e),this.layerMask=HU}setMask(e){this.layerMask||(this.layerMask=new Nr);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}h(To,"AllLayers",4294967295);class VU{constructor(e,t,n){h(this,"distance"),h(this,"point"),h(this,"object"),this.object=e,this.distance=t,this.point=n}}class WU{constructor(e){h(this,"context"),h(this,"engine"),h(this,"raycaster",new Au),h(this,"defaultRaycastOptions",new To),h(this,"targetBuffer",new Array(1)),h(this,"defaultThresholds",{Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}}),h(this,"sphereResults",new Array),h(this,"sphereMask",new Nr),h(this,"tempBoundingBox",new gi),this.context=e}raycastPhysicsFast(e,t=void 0,n=1/0,r=!0){var s;return((s=this.context.physics.engine)==null?void 0:s.raycast(e,t,n,r))??null}raycastPhysicsFastAndGetNormal(e,t=void 0,n=1/0,r=!0){var s;return((s=this.context.physics.engine)==null?void 0:s.raycastAndGetNormal(e,t,n,r))??null}sphereOverlapPhysics(e,t){var n;return((n=this.context.physics.engine)==null?void 0:n.sphereOverlap(e,t))??null}sphereOverlap(e,t,n=!0){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const r=new un(e,t),s=this.sphereMask;s.enableAll(),s.disable(2);for(const o of this.context.scene.children)this.onSphereOverlap(o,r,s,this.sphereResults,n);return this.sphereResults.sort((o,a)=>o.distance-a.distance)}onSphereOverlap(e,t,n,r,s){if(e.type==="Mesh"&&e.layers.test(n)&&!Ct.isGizmo(e)){const o=e,a=o.geometry;if(a&&(a.boundingBox||a.computeBoundingBox(),a.boundingBox)){o.matrixWorldNeedsUpdate&&o.updateMatrixWorld();const l=this.tempBoundingBox.copy(a.boundingBox).applyMatrix4(o.matrixWorld);if(t.intersectsBox(l)){const c=Rt(e),u=c.distanceTo(t.center),d=new VU(e,u,c);if(r.push(d),!s)return}}}if(e.children)for(const o of e.children){const a=r.length;if(this.onSphereOverlap(o,t,n,r,s),a!=r.length&&!s)return}}raycastFromRay(e,t=null){const n=t??this.defaultRaycastOptions;n.ray=e;const r=this.raycast(n);return n===this.defaultRaycastOptions&&(n.ray=void 0),r}raycast(e=null){e||(e=this.defaultRaycastOptions);const t=e.screenPoint??this.context.input.mousePositionRC,n=e.raycaster??this.raycaster;if(n.near=e.minDistance??0,n.far=e.maxDistance??1/0,n.params=this.defaultThresholds,e.lineThreshold===void 0&&(e.lineThreshold=-1),n.params.Line={threshold:e.lineThreshold},e.ray)n.ray.copy(e.ray);else{const a=e.cam??this.context.mainCamera;if(!a)return Hg&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const l=this.context.xrCamera;this.context.isInXR&&l instanceof bS&&l.cameras.length>0?n.setFromCamera(t,l.cameras[0]):n.setFromCamera(t,a)}let r=e.targets;r||(r=this.targetBuffer,r.length=1,r[0]=this.context.scene);let s=e.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),s||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),s=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof Nr?n.layers.mask=e.layerMask.mask:n.layers.mask=e.layerMask:(n.layers.enableAll(),n.layers.disable(2)),Hg&&(Ct.DrawRay(n.ray.origin,n.ray.direction,16711680,2),console.time("raycast")),s.length=0,this.intersect(this.raycaster,r,s,e),s.sort((a,l)=>a.distance-l.distance);const o=e.ignore;return o!==void 0&&o.length>0&&(s=s.filter(a=>!o.includes(a.object))),Hg&&(console.timeEnd("raycast"),console.log("hits:",s!=null&&s.length?[...s]:"nothing")),s}intersect(e,t,n,r){var s;for(const o of t){if(o.visible===!1||Ct.isGizmo(o)||r.lineThreshold!==void 0&&r.lineThreshold<0&&o instanceof An)continue;const a=(s=r.testObject)==null?void 0:s.call(r,o);if(a!==!1){if(a!=="continue in children"){const l=o,c=l.geometry;if(c){const u=Vg(o);u&&(l.geometry=u),e.intersectObject(o,!1,n),l.geometry=c}}r.recursive!==!1&&this.intersect(e,o.children,n,r)}}return n}}const H$=ee("debugplayerview");var ih=(i=>(i.Browser="browser",i.Headset="headset",i.Handheld="handheld",i))(ih||{});class qU{constructor(e,t){h(this,"userId"),h(this,"context"),h(this,"viewDevice","browser"),h(this,"removed",!1),h(this,"_object"),this.userId=e,this.context=t}get currentObject(){return this._object}set currentObject(e){this._object=e}get isConnected(){return this.context.connection.userIsInRoom(this.userId)}}class XU{constructor(e){h(this,"context"),h(this,"playerViews",new Map),this.context=e}setPlayerView(e,t,n){let r=this.playerViews.get(e);r||(r=new qU(e,this.context),this.playerViews.set(e,r)),r.viewDevice=n,r.currentObject=t,r.removed=!1}getPlayerView(e){if(!!e){if(!this.context.connection.userIsInRoom(e)){this.playerViews.delete(e);return}return this.playerViews.get(e)}}removePlayerView(e,t){const n=this.playerViews.get(e);n?.viewDevice===t&&(H$&&console.log("REMOVE",e),n.removed=!0,this.playerViews.delete(e))}}new Gn;const Wg=new Uint8Array(4);Wg[0]=255,Wg[1]=255,Wg[2]=255,Wg[3]=255;const V$=new Rs(Wg,1,1,di);function YU(i,e=1){const t="alpha"in i,n=e*e,r=new Uint8Array(4*n),s=Math.floor(i.r*255),o=Math.floor(i.g*255),a=Math.floor(i.b*255);for(let c=0;c<n;c++){const u=c*4;r[u+0]=s,r[u+1]=o,r[u+2]=a,t?r[u+3]=Math.floor(i.alpha*255):r[u+3]=255}const l=new Rs(r,e,e);return l.needsUpdate=!0,l}function W$(i,e,t,n=1,r=3){const s=n*r,o=[i,e,t],a=o.length,l=new Uint8Array(4*a*s),c=new Se;for(let d=0;d<r;d++){const p=Math.floor(d/r*a),f=Ze.clamp(p+1,0,a-1),m=o[p],A=o[f],v=d/r*a%1;c.lerpColors(m,A,v);const g=Math.floor(c.r*255),y=Math.floor(c.g*255),b=Math.floor(c.b*255);for(let _=0;_<n;_++){const E=(d*n+_)*4;l[E+0]=g,l[E+1]=y,l[E+2]=b,l[E+3]=255}}const u=new Rs(l,n,r);return u.needsUpdate=!0,u}function l_(i,e){const t=i.elements;e||(e=[]),e.length=0;for(let n=0;n<16;n+=4){const r=t[n],s=t[n+1],o=t[n+2],a=t[n+3],l=new Ye(r,s,o,a);e.push(l)}return e}const VM=[],JU=[];function q$(i,e){if(VM.length===0)for(let t=0;t<27;t++)VM.push(0);e||(e=VM);for(let t=0;t<27;t++)JU[t]=e[t];e=JU,i.unity_SHAr={value:new Ye(e[9],e[3],e[6],e[0])},i.unity_SHBr={value:new Ye(e[12],e[15],e[18],e[21])},i.unity_SHAg={value:new Ye(e[10],e[4],e[7],e[1])},i.unity_SHBg={value:new Ye(e[13],e[16],e[19],e[22])},i.unity_SHAb={value:new Ye(e[11],e[5],e[8],e[2])},i.unity_SHBb={value:new Ye(e[14],e[17],e[20],e[23])},i.unity_SHC={value:new Ye(e[24],e[25],e[26],1)}}class X${constructor(e,t,n){h(this,"vertexShader"),h(this,"fragmentShader"),h(this,"technique"),this.vertexShader=e,this.fragmentShader=t,this.technique=n}}async function Y$(i,e){if(!i)return console.error("Can not find technique: no shader data"),null;const t=i.programs[e],n=t.vertexShader,r=t.fragmentShader;if(n!==void 0&&r!==void 0){const s=i.shaders[n],o=i.shaders[r];if(s.uri&&o.uri||s.code&&o.code){if(!s.code&&s.uri&&await KU(s),!o.code&&o.uri&&await KU(o),!s.code||!o.code)return null;const a=i.techniques[e];return new X$(s.code,o.code,a)}}return console.error("Shader technique not found",e),null}async function KU(i){const e=i.uri;if(e)if(e.endsWith(".glsl")){const t=await new Gn().loadAsync(e);i.code=t.toString()}else i.code=J$(i.uri)}function J$(i){return decodeURIComponent(Array.prototype.map.call(atob(i),function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}const ua=ee("debugenvlight");var Up=(i=>(i[i.Skybox=0]="Skybox",i[i.Trilight=1]="Trilight",i[i.Flat=3]="Flat",i[i.Custom=4]="Custom",i))(Up||{}),c_=(i=>(i[i.Skybox=0]="Skybox",i[i.Custom=1]="Custom",i))(c_||{});class ZU{constructor(e){h(this,"context"),h(this,"_currentLightSettingsId"),h(this,"_sceneLightSettings"),h(this,"_timevec4",new Ye),h(this,"__currentReflectionId",null),h(this,"_lighting",{}),this.context=e,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}preUpdate(){const e=this.context.time;this._timevec4.x=e.time,this._timevec4.y=Math.sin(e.time),this._timevec4.z=Math.cos(e.time),this._timevec4.w=e.deltaTime}get timeVec4(){return this._timevec4}get environmentIntensity(){if(!this._sceneLightSettings||!this._currentLightSettingsId)return 1;const e=this._sceneLightSettings.get(this._currentLightSettingsId);return e?e.ambientIntensity:1}get sceneLightSettings(){var e;return(e=this._sceneLightSettings)==null?void 0:e.values()}enable(e){var t;e instanceof ni&&(e=e.uri);const n=(t=this._sceneLightSettings)==null?void 0:t.get(e);return n?(ua&&console.log("Enable scene light settings",e,n),e!==this._currentLightSettingsId&&this._currentLightSettingsId&&this.disable(this._currentLightSettingsId),this._currentLightSettingsId=e,n.enabled=!0,!0):(ua&&console.warn("No light settings found for",e),!1)}disable(e){var t;if(e instanceof ni&&(e=e.uri),e==null)return!1;const n=(t=this._sceneLightSettings)==null?void 0:t.get(e);return n?(ua&&console.log("Disable scene light settings",e,n),n.enabled=!1,!0):!1}disableCurrent(){if(this._currentLightSettingsId){const e=this._currentLightSettingsId;return this.disable(this._currentLightSettingsId),e}return null}internalRegisterSceneLightSettings(e){const t=e.sourceId;if(!t){console.error("Missing source id for scene light settings, can not register:",e);return}ua&&console.log("Register "+e?.sourceId+" lighting",e),this._sceneLightSettings||(this._sceneLightSettings=new Map),this._sceneLightSettings.set(t,e)}internalUnregisterSceneLightSettings(e){const t=e.sourceId;if(!t){console.error("Missing source id for scene light settings, can not unregister:",e);return}ua&&console.log("Unregister "+e?.sourceId+" lighting",e),this._sceneLightSettings&&this._sceneLightSettings.delete(t)}internalRegisterReflection(e,t){ua&&console.log("Register reflection",e,t);const n=new $U(this.context,t,1);this._lighting[e]=n}internalGetReflection(e){return this._lighting[e]}internalEnableReflection(e){var t;this.__currentReflectionId=e;const n=(t=this._sceneLightSettings)==null?void 0:t.get(e);switch(ua&&console.log("Enable reflection",e,n?Up[n.ambientMode]:"Unknown ambient mode"),n?.ambientMode){case 0:case 4:const r=this.internalGetReflection(e);if(r&&r.Source){ua&&console.log("Setting environment reflection",r);const s=this.context.scene,o=r.Source;o.mapping=mo,s.environment=o;return}else ua&&console.warn("Could not find reflection for source",e);break}if(n?.environmentReflectionSource===1)switch(n?.ambientMode){case 1:if(n.ambientTrilight){const r=n.ambientTrilight,s=W$(r[0],r[1],r[2],64,64);s.colorSpace=dt,s.mapping=mo,this.context.scene.environment=s}else console.error("Missing ambient trilight",n.sourceId);return;case 3:if(n.ambientLight){const r=YU(n.ambientLight,64);r.colorSpace=dt,r.mapping=mo,this.context.scene.environment=r}else console.error("Missing ambientlight",n.sourceId);return;default:return}}internalDisableReflection(e){if(e&&e!==this.__currentReflectionId){ua&&console.log("Not disabling reflection for",e,"because it is not the current light settings id",this.__currentReflectionId);return}ua&&console.log("Disable reflection",e);const t=this.context.scene;t.environment=null}}class $U{constructor(e,t,n=1){h(this,"_source"),this._source=t,t.mapping=mo}get Source(){return this._source}}const eF=ee("timescale");let WM=1;typeof eF=="number"&&(WM=eF);class tF{constructor(){h(this,"_time",0),h(this,"_deltaTime",0),h(this,"_deltaTimeUnscaled",0),h(this,"timeScale",1),h(this,"_frame",0),h(this,"clock",new rC),h(this,"_smoothedFps",0),h(this,"_smoothedDeltaTime",0),h(this,"_fpsSamples",[]),h(this,"_fpsSampleIndex",0),typeof WM=="number"&&(this.timeScale=WM)}get time(){return this._time}set time(e){this._time=e}get deltaTime(){return this._deltaTime}set deltaTime(e){this._deltaTime=e}get deltaTimeUnscaled(){return this._deltaTimeUnscaled}get frame(){return this._frame}set frame(e){this._frame=e}get frameCount(){return this.frame}get realtimeSinceStartup(){return this.clock.elapsedTime}get smoothedFps(){return this._smoothedFps}get smoothedDeltaTime(){return 1/this._smoothedFps}update(){this.deltaTime=this.clock.getDelta(),this.deltaTime=Math.min(.1,this.deltaTime),this._deltaTimeUnscaled=this.deltaTime,this.deltaTime<=0&&(this.deltaTime=1e-12),this.deltaTime*=this.timeScale,this.frame+=1,this.time+=this.deltaTime,this._fpsSamples.length<60?this._fpsSamples.push(this.deltaTime):this._fpsSamples[this._fpsSampleIndex++%60]=this.deltaTime;let e=0;for(let t=0;t<this._fpsSamples.length;t++)e+=this._fpsSamples[t];this._smoothedDeltaTime=e/this._fpsSamples.length,this._smoothedFps=1/this._smoothedDeltaTime}}const Io=ee("debuglicense");let Fu="basic";Io&&console.log("License Type: "+Fu);function da(){switch(Fu){case"pro":case"enterprise":return!0}return!1}function qM(){switch(Fu){case"indie":return!0}return!1}function Fp(){return da()||qM()}const iF=[];function K$(i){if(da()||qM())return i(!0);iF.push(i)}function Z$(i){for(const e of iF)try{e(i)}catch{}}ii.registerCallback(bn.ContextRegistered,i=>{tee(i.context),nee(),eee(i.context)});let Nu,XM=!1,h_="";async function $$(){if(Nu)return Nu;if(Fu==="basic")try{const i="https://engine.needle.tools/licensing/check?location="+encodeURIComponent(window.location.href)+"&version="+Fl+"&generator="+encodeURIComponent(_b),e=await fetch(i,{method:"GET"}).catch(t=>{Io&&console.error("License check failed",t)});e?.status===200?(XM=!1,Io&&console.log("License check succeeded"),Fu="pro",Z$(!0)):e?.status===403?(XM=!0,h_=await e.text()):Io&&console.log("License check failed with status "+e?.status)}catch(i){Io&&console.error("License check failed",i)}else Io&&console.log('Runtime license check is skipped because license is already applied as "'+Fu+'"')}Nu=$$();async function eee(i){function e(){const r=document.createElement("div");r.className="needle-forbidden",r.style.cssText=`
4997
4997
  position: fixed;
4998
4998
  top: 0;
4999
4999
  left: 0;
@@ -5250,12 +5250,12 @@ irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );
5250
5250
  </div>
5251
5251
  `;const o=this.attachShadow({mode:"open"});sF(),KM("https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200&display=block",{loadedCallback:()=>{this.handleSizeChange()}}),KM("https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200&display=block",{element:o});const a=s.content.cloneNode(!0);o?.appendChild(a),this.root=o.querySelector("#root"),this.wrapper=(e=this.root)==null?void 0:e.querySelector(".wrapper"),this.options=(t=this.root)==null?void 0:t.querySelector(".options"),this.logoContainer=(n=this.root)==null?void 0:n.querySelector(".logo"),(r=this.root)==null||r.appendChild(this.wrapper),this.wrapper.classList.add("wrapper");const l=oF.create();l.style.minHeight="1rem",this.logoContainer.append(l),this.logoContainer.addEventListener("click",()=>{globalThis.open("https://needle.tools","_blank")}),K$(u=>{u==!0&&da()&&!lF&&(this.logoContainer.style.display=this._userRequestedLogoVisible?"":"none")});let c=-1;new MutationObserver(u=>{var d;this.onChangeDetected(u);const p=this==null?void 0:this.parentNode;(this.style.display!="flex"||this.style.visibility!="visible"||this.style.opacity!="1"||p!=((d=this._domElement)==null?void 0:d.shadowRoot))&&(da()||(clearInterval(c),c=setInterval(()=>{var f,m,A;p!=((f=this._domElement)==null?void 0:f.shadowRoot)&&((A=(m=this._domElement)==null?void 0:m.shadowRoot)==null||A.appendChild(this)),this.style.display="flex",this.style.visibility="visible",this.style.opacity="1"},5)))}).observe(this.root,{childList:!0,subtree:!0,attributes:!0}),p_&&this.___insertDebugOptions()}static create(){return document.createElement(zp,{is:zp})}static getOrCreate(e){let t=e.querySelector(zp);return!t&&e.shadowRoot&&(t=e.shadowRoot.querySelector(zp)),t||(t=Gw.create(),t._domElement=e,e.shadowRoot?e.shadowRoot.appendChild(t):e.appendChild(t)),t}connectedCallback(){var e;window.addEventListener("resize",this.handleSizeChange),(e=this._domElement)==null||e.addEventListener("resize",this.handleSizeChange),this.handleMenuVisible(),this._sizeChangeInterval=setInterval(()=>this.handleSizeChange(void 0,!0),5e3)}disconnectedCallback(){var e;window.removeEventListener("resize",this.handleSizeChange),(e=this._domElement)==null||e.removeEventListener("resize",this.handleSizeChange),clearInterval(this._sizeChangeInterval)}showNeedleLogo(e){if(this._userRequestedLogoVisible=e,!da()||lF){pt()&&console.warn("Needle Menu: You need a PRO license to hide the Needle Engine logo.");return}this.logoContainer.style.display=e?"":"none"}setPosition(e){if(e!=="top"&&e!=="bottom")return console.error("NeedleMenu.setPosition: invalid position",e);this.root.classList.remove("top","bottom"),this.root.classList.add(e)}append(...e){for(const t of e)if(typeof t=="string"){const n=document.createTextNode(t);this.options.appendChild(n)}else this.options.appendChild(t)}appendChild(e){return this.options.appendChild(e)}prepend(...e){for(const t of e)if(typeof t=="string"){const n=document.createTextNode(t);this.options.prepend(n)}else this.options.prepend(t)}onChangeDetected(e){if(!this._isHandlingChange){this._isHandlingChange=!0;try{this.handleMenuVisible();for(const t of e)t.target==this.options&&this.onOptionsChildrenChanged(t)}finally{this._isHandlingChange=!1}}}onOptionsChildrenChanged(e){let t=!1;for(let n=0;n<this.options.children.length;n++)if(this.options.children[n].style.display!="none"){t=!0;break}if(this.logoContainer.classList.toggle("any-options",t),this.handleSizeChange(),e.type==="childList"){let n=!1;const r=Date.now();for(let s=0;s<e.addedNodes.length;s++){const o=e.addedNodes[s],a=this._didSort.get(o);typeof a=="number"&&r-a<100||(this._didSort.set(o,r),n=!0)}if(n){const s=Array.from(this.options.children);s.sort((o,a)=>{const l=parseInt(o.getAttribute("priority")||"0"),c=parseInt(a.getAttribute("priority")||"0");return l-c});for(const o of s)this.options.appendChild(o)}}}handleMenuVisible(){p_&&console.log("Update VisibleState: Any Content?",this.hasAnyContent),this.hasAnyContent?this.root.style.display="":this.root.style.display="none"}get hasAnyContent(){if(this.logoContainer.style.display!="none")return!0;for(let e=0;e<this.options.children.length;e++)if(this.options.children[e].style.display!="none")return!0;return!1}___insertDebugOptions(){window.addEventListener("keydown",n=>{n.key==="p"&&this.setPosition(this.root.classList.contains("top")?"bottom":"top")});const e=document.createElement("button");e.textContent="Hide Buttons",e.onclick=()=>{const n=new Array(this.options.children.length);for(let r=0;r<this.options.children.length;r++)n[r]=this.options.children[r];for(const r of n)this.options.removeChild(r);setTimeout(()=>{for(const r of n)this.options.appendChild(r)},1e3)},this.appendChild(e);const t=document.createElement("button");t.textContent="Toggle Logo",t.addEventListener("click",()=>{this.logoContainer.style.display=this.logoContainer.style.display==="none"?"":"none"}),this.appendChild(t)}}customElements.get(zp)||customElements.define(zp,Gw);const br=ee("debugcontext"),Aee=ee("stats"),yee=ee("debugactive"),bee=ee("debugframerate"),_ee=ee("debugcoroutine"),xee={};class wee{constructor(){h(this,"name"),h(this,"alias"),h(this,"hash"),h(this,"runInBackground"),h(this,"domElement"),h(this,"renderer"),h(this,"camera"),h(this,"scene")}}var Pn=(i=>(i[i.Start=-1]="Start",i[i.EarlyUpdate=0]="EarlyUpdate",i[i.Update=1]="Update",i[i.LateUpdate=2]="LateUpdate",i[i.OnBeforeRender=3]="OnBeforeRender",i[i.OnAfterRender=4]="OnAfterRender",i[i.PrePhysicsStep=9]="PrePhysicsStep",i[i.PostPhysicsStep=10]="PostPhysicsStep",i[i.Undefined=-1]="Undefined",i))(Pn||{});function f_(i,e){if(!i)return;if(!i.isComponent){(pt()||br)&&console.error(`Registered script is not a Needle Engine component.
5252
5252
  The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
5253
- `,i);return}const t=e?.new_scripts??Lt.Current.new_scripts;t.includes(i)||t.push(i)}const qi=class{constructor(i){h(this,"name"),h(this,"alias"),h(this,"isManagedExternally",!1),h(this,"isPaused",!1),h(this,"runInBackground",!1),h(this,"targetFrameRate"),h(this,"physicsSteps",1),h(this,"hash"),h(this,"domElement"),h(this,"_resolutionScaleFactor",1),h(this,"_boundingClientRectFrame",-1),h(this,"_boundingClientRect",null),h(this,"_domX"),h(this,"_domY"),h(this,"xr",null),h(this,"_xrFrame",null),h(this,"_currentFrameEvent",-1),h(this,"scene"),h(this,"renderer"),h(this,"composer",null),h(this,"scripts",[]),h(this,"scripts_pausedChanged",[]),h(this,"scripts_earlyUpdate",[]),h(this,"scripts_update",[]),h(this,"scripts_lateUpdate",[]),h(this,"scripts_onBeforeRender",[]),h(this,"scripts_onAfterRender",[]),h(this,"scripts_WithCorroutines",[]),h(this,"scripts_immersive_vr",[]),h(this,"scripts_immersive_ar",[]),h(this,"coroutines",{}),h(this,"post_setup_callbacks",[]),h(this,"pre_update_callbacks",[]),h(this,"pre_render_callbacks",[]),h(this,"post_render_callbacks",[]),h(this,"pre_update_oneshot_callbacks",[]),h(this,"new_scripts",[]),h(this,"new_script_start",[]),h(this,"new_scripts_pre_setup_callbacks",[]),h(this,"new_scripts_post_setup_callbacks",[]),h(this,"new_scripts_xr",[]),h(this,"mainCameraComponent"),h(this,"_camera",null),h(this,"application"),h(this,"time"),h(this,"input"),h(this,"physics"),h(this,"connection"),h(this,"assets"),h(this,"mainLight",null),h(this,"sceneLighting"),h(this,"addressables"),h(this,"lightmaps"),h(this,"players"),h(this,"menu"),h(this,"_sizeChanged",!1),h(this,"_isCreated",!1),h(this,"_isCreating",!1),h(this,"_isVisible",!1),h(this,"_stats",Aee?new QK:null),h(this,"_intersectionObserver",null),h(this,"_disposeCallbacks",[]),h(this,"maxRenderResolution"),h(this,"_originalCreationArgs"),h(this,"onUnhandledRejection",n=>{this.domElement.dispatchEvent(new CustomEvent("error",{detail:n.reason}))}),h(this,"_cameraStack",[]),h(this,"_onBeforeRenderListeners",new Map),h(this,"_onAfterRenderListeners",new Map),h(this,"_requireDepthTexture",!1),h(this,"_requireColorTexture",!1),h(this,"_renderTarget"),h(this,"_isRendering",!1),h(this,"_createId",0),h(this,"_renderlooperrors",0),h(this,"_lastTimestamp",0),h(this,"_accumulatedTime",0),h(this,"_dispatchReadyAfterFrame",!1),h(this,"_wasPaused",!1),this.name=i?.name||"",this.alias=i?.alias,this.domElement=i?.domElement||document.body,this.hash=i?.hash,i!=null&&i.renderer&&(this.renderer=i.renderer,this.isManagedExternally=!0),i?.runInBackground!==void 0&&(this.runInBackground=i.runInBackground),i!=null&&i.scene?this.scene=i.scene:this.scene=new jr,i!=null&&i.camera&&(this._camera=i.camera),this.application=new Ng(this),this.time=new tF,this.input=new JL(this),this.physics=new W3(this),this.connection=new x3(this),this.assets=new Jk,this.sceneLighting=new Z3(this),this.addressables=new HL(this),this.lightmaps=new Q$(this),this.players=new X3(this),this.menu=new vee(this);const e=()=>this._sizeChanged=!0;window.addEventListener("resize",e),this._disposeCallbacks.push(()=>window.removeEventListener("resize",e));const t=new ResizeObserver(n=>this._sizeChanged=!0);t.observe(this.domElement),this._disposeCallbacks.push(()=>t.disconnect()),this._intersectionObserver=new IntersectionObserver(n=>{this._isVisible=n[0].isIntersecting}),this._disposeCallbacks.push(()=>{var n;return(n=this._intersectionObserver)==null?void 0:n.disconnect()}),ii.register(this)}static get DefaultTargetFrameRate(){return qi._defaultTargetFramerate.value}static set DefaultTargetFrameRate(i){qi._defaultTargetFramerate.value=i}static get DefaultWebGLRendererParameters(){return qi._defaultWebglRendererParameters}get version(){return Fl}static get Current(){return ii.Current}static set Current(i){ii.Current=i}appendHTMLElement(i){return this.domElement.shadowRoot?this.domElement.shadowRoot.appendChild(i):this.domElement.appendChild(i)}get resolutionScaleFactor(){return this._resolutionScaleFactor}set resolutionScaleFactor(i){if(i!==this._resolutionScaleFactor&&typeof i=="number"){if(i<=0){console.error("Invalid resolution scale factor",i);return}this._resolutionScaleFactor=i,this.updateSize()}}calculateBoundingClientRect(){if(this.isInAR){this._domX=0,this._domY=0;return}this._boundingClientRectFrame!==this.time.frame&&(this._boundingClientRectFrame=this.time.frame,this._boundingClientRect=this.domElement.getBoundingClientRect(),this._domX=this._boundingClientRect.x,this._domY=this._boundingClientRect.y)}get domWidth(){return this.isInAR?window.innerWidth:this.domElement.clientWidth}get domHeight(){return this.isInAR?window.innerHeight:this.domElement.clientHeight}get domX(){return this.calculateBoundingClientRect(),this._domX}get domY(){return this.calculateBoundingClientRect(),this._domY}get isInXR(){var i,e;return((e=(i=this.renderer)==null?void 0:i.xr)==null?void 0:e.isPresenting)||!1}get xrSessionMode(){var i;return(i=this.xr)==null?void 0:i.mode}get isInVR(){return this.xrSessionMode==="immersive-vr"}get isInAR(){return this.xrSessionMode==="immersive-ar"}get isInPassThrough(){return this.xr?this.xr.isPassThrough:!1}get xrSession(){var i,e;return(e=(i=this.renderer)==null?void 0:i.xr)==null?void 0:e.getSession()}get xrFrame(){return this._xrFrame}get xrCamera(){var i,e;return this.renderer.xr.isPresenting?(e=(i=this.renderer)==null?void 0:i.xr)==null?void 0:e.getCamera():void 0}get arOverlayElement(){const i=this.domElement;return typeof i.getAROverlayContainer=="function"?i.getAROverlayContainer():this.domElement}get currentFrameEvent(){return this._currentFrameEvent}get mainCamera(){if(this._camera)return this._camera;if(this.mainCameraComponent){const i=this.mainCameraComponent;return i.cam||i.buildCamera(),i.cam}return null}set mainCamera(i){this._camera=i}get rendererData(){return this.sceneLighting}get isCreated(){return this._isCreated}createNewRenderer(i){var e,t,n;if((e=this.renderer)==null||e.dispose(),i={...qi.DefaultWebGLRendererParameters,...i},!i.canvas){const r=(n=(t=this.domElement)==null?void 0:t.shadowRoot)==null?void 0:n.querySelector("canvas");r&&(i.canvas=r,br&&console.log("Using canvas from shadow root",r))}br&&console.log("Using Renderer Parameters:",i,this.domElement),this.renderer=new Pl(i),this.renderer.debug.checkShaderErrors=pt()||ee("checkshadererrors")===!0,this.renderer.toneMappingExposure=1,this.renderer.toneMapping=zs,this.renderer.setClearColor(new Se("lightgrey"),0),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=e1,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputColorSpace=dt,this.input.bindEvents()}internalOnUpdateVisible(){var i,e;(i=this._intersectionObserver)==null||i.disconnect(),(e=this._intersectionObserver)==null||e.observe(this.domElement)}requestSizeUpdate(){this._sizeChanged=!0}updateSize(i=!1){var e,t,n;if(i||!this.isManagedExternally&&((e=this.renderer.xr)==null?void 0:e.isPresenting)===!1){this._sizeChanged=!1;const r=this.resolutionScaleFactor;let s=this.domWidth*r,o=this.domHeight*r;this.maxRenderResolution&&(this.maxRenderResolution.x=Math.max(1,this.maxRenderResolution.x),s=Math.min(this.maxRenderResolution.x,s),this.maxRenderResolution.y=Math.max(1,this.maxRenderResolution.y),o=Math.min(this.maxRenderResolution.y,o));const a=this.mainCamera;this.updateAspect(a),this.renderer.setSize(s,o,!0),this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%",this.composer&&((t=this.composer.setSize)==null||t.call(this.composer,s,o),"setPixelRatio"in this.composer&&typeof this.composer.setPixelRatio=="function"&&((n=this.composer.setPixelRatio)==null||n.call(this.composer,window.devicePixelRatio)))}}updateAspect(i,e,t){if(!i)return;e===void 0&&(e=this.domWidth),t===void 0&&(t=this.domHeight);const n=i.aspect;i.aspect=e/t,n!==i.aspect&&i.updateProjectionMatrix()}recreate(){this.clear(),this.create(this._originalCreationArgs)}async onCreate(i){return this.create(i)}async create(i){try{this._isCreating=!0,i!==this._originalCreationArgs&&(this._originalCreationArgs=Ym(i)),window.addEventListener("unhandledrejection",this.onUnhandledRejection);const e=await this.internalOnCreate(i);return this._isCreated=!0,e}finally{window.removeEventListener("unhandledrejection",this.onUnhandledRejection),this._isCreating=!1}}clear(){var i,e,t,n;ii.dispatchCallback(bn.ContextClearing,this),pa(this.scene,!0,!0),this.scene=new jr,(i=this.addressables)==null||i.dispose(),(e=this.lightmaps)==null||e.clear(),(n=(t=this.physics)==null?void 0:t.engine)==null||n.clearCaches(),this.isManagedExternally||this.renderer&&(this.renderer.renderLists.dispose(),this.renderer.state.reset(),this.renderer.resetState()),ii.dispatchCallback(bn.ContextCleared,this)}dispose(){this.internalOnDestroy()}onDestroy(){this.internalOnDestroy()}internalOnDestroy(){var i,e;this.clear(),(i=this.renderer)==null||i.setAnimationLoop(null),this.renderer&&(this.renderer.setClearAlpha(0),this.renderer.clear(),this.isManagedExternally||(br&&console.log("Disposing renderer"),this.renderer.dispose())),this.scene=null,this.renderer=null,this.input.dispose(),this.menu.onDestroy();for(const t of this._disposeCallbacks)try{t()}catch(n){console.error("Error in on dispose callback:",n,t)}(e=this.domElement)!=null&&e.parentElement&&this.domElement.parentElement.removeChild(this.domElement),this._isCreated=!1,ii.dispatchCallback(bn.ContextDestroyed,this),ii.unregister(this),qi.Current===this&&(qi.Current=null)}registerCoroutineUpdate(i,e,t){return typeof e?.next!="function"?(console.error("Registered invalid coroutine function from "+i.name+`
5253
+ `,i);return}const t=e?.new_scripts??Lt.Current.new_scripts;t.includes(i)||t.push(i)}const qi=class{constructor(i){h(this,"name"),h(this,"alias"),h(this,"isManagedExternally",!1),h(this,"isPaused",!1),h(this,"runInBackground",!1),h(this,"targetFrameRate"),h(this,"physicsSteps",1),h(this,"hash"),h(this,"domElement"),h(this,"_resolutionScaleFactor",1),h(this,"_boundingClientRectFrame",-1),h(this,"_boundingClientRect",null),h(this,"_domX"),h(this,"_domY"),h(this,"xr",null),h(this,"_xrFrame",null),h(this,"_currentFrameEvent",-1),h(this,"scene"),h(this,"renderer"),h(this,"composer",null),h(this,"scripts",[]),h(this,"scripts_pausedChanged",[]),h(this,"scripts_earlyUpdate",[]),h(this,"scripts_update",[]),h(this,"scripts_lateUpdate",[]),h(this,"scripts_onBeforeRender",[]),h(this,"scripts_onAfterRender",[]),h(this,"scripts_WithCorroutines",[]),h(this,"scripts_immersive_vr",[]),h(this,"scripts_immersive_ar",[]),h(this,"coroutines",{}),h(this,"post_setup_callbacks",[]),h(this,"pre_update_callbacks",[]),h(this,"pre_render_callbacks",[]),h(this,"post_render_callbacks",[]),h(this,"pre_update_oneshot_callbacks",[]),h(this,"new_scripts",[]),h(this,"new_script_start",[]),h(this,"new_scripts_pre_setup_callbacks",[]),h(this,"new_scripts_post_setup_callbacks",[]),h(this,"new_scripts_xr",[]),h(this,"mainCameraComponent"),h(this,"_camera",null),h(this,"application"),h(this,"time"),h(this,"input"),h(this,"physics"),h(this,"connection"),h(this,"assets"),h(this,"mainLight",null),h(this,"sceneLighting"),h(this,"addressables"),h(this,"lightmaps"),h(this,"players"),h(this,"menu"),h(this,"_sizeChanged",!1),h(this,"_isCreated",!1),h(this,"_isCreating",!1),h(this,"_isVisible",!1),h(this,"_stats",Aee?new QK:null),h(this,"_intersectionObserver",null),h(this,"_disposeCallbacks",[]),h(this,"maxRenderResolution"),h(this,"_originalCreationArgs"),h(this,"onUnhandledRejection",n=>{this.domElement.dispatchEvent(new CustomEvent("error",{detail:n.reason}))}),h(this,"_cameraStack",[]),h(this,"_onBeforeRenderListeners",new Map),h(this,"_onAfterRenderListeners",new Map),h(this,"_requireDepthTexture",!1),h(this,"_requireColorTexture",!1),h(this,"_renderTarget"),h(this,"_isRendering",!1),h(this,"_createId",0),h(this,"_renderlooperrors",0),h(this,"_lastTimestamp",0),h(this,"_accumulatedTime",0),h(this,"_dispatchReadyAfterFrame",!1),h(this,"_wasPaused",!1),this.name=i?.name||"",this.alias=i?.alias,this.domElement=i?.domElement||document.body,this.hash=i?.hash,i!=null&&i.renderer&&(this.renderer=i.renderer,this.isManagedExternally=!0),i?.runInBackground!==void 0&&(this.runInBackground=i.runInBackground),i!=null&&i.scene?this.scene=i.scene:this.scene=new jr,i!=null&&i.camera&&(this._camera=i.camera),this.application=new Ng(this),this.time=new tF,this.input=new JL(this),this.physics=new WU(this),this.connection=new xU(this),this.assets=new Jk,this.sceneLighting=new ZU(this),this.addressables=new HL(this),this.lightmaps=new Q$(this),this.players=new XU(this),this.menu=new vee(this);const e=()=>this._sizeChanged=!0;window.addEventListener("resize",e),this._disposeCallbacks.push(()=>window.removeEventListener("resize",e));const t=new ResizeObserver(n=>this._sizeChanged=!0);t.observe(this.domElement),this._disposeCallbacks.push(()=>t.disconnect()),this._intersectionObserver=new IntersectionObserver(n=>{this._isVisible=n[0].isIntersecting}),this._disposeCallbacks.push(()=>{var n;return(n=this._intersectionObserver)==null?void 0:n.disconnect()}),ii.register(this)}static get DefaultTargetFrameRate(){return qi._defaultTargetFramerate.value}static set DefaultTargetFrameRate(i){qi._defaultTargetFramerate.value=i}static get DefaultWebGLRendererParameters(){return qi._defaultWebglRendererParameters}get version(){return Fl}static get Current(){return ii.Current}static set Current(i){ii.Current=i}appendHTMLElement(i){return this.domElement.shadowRoot?this.domElement.shadowRoot.appendChild(i):this.domElement.appendChild(i)}get resolutionScaleFactor(){return this._resolutionScaleFactor}set resolutionScaleFactor(i){if(i!==this._resolutionScaleFactor&&typeof i=="number"){if(i<=0){console.error("Invalid resolution scale factor",i);return}this._resolutionScaleFactor=i,this.updateSize()}}calculateBoundingClientRect(){if(this.isInAR){this._domX=0,this._domY=0;return}this._boundingClientRectFrame!==this.time.frame&&(this._boundingClientRectFrame=this.time.frame,this._boundingClientRect=this.domElement.getBoundingClientRect(),this._domX=this._boundingClientRect.x,this._domY=this._boundingClientRect.y)}get domWidth(){return this.isInAR?window.innerWidth:this.domElement.clientWidth}get domHeight(){return this.isInAR?window.innerHeight:this.domElement.clientHeight}get domX(){return this.calculateBoundingClientRect(),this._domX}get domY(){return this.calculateBoundingClientRect(),this._domY}get isInXR(){var i,e;return((e=(i=this.renderer)==null?void 0:i.xr)==null?void 0:e.isPresenting)||!1}get xrSessionMode(){var i;return(i=this.xr)==null?void 0:i.mode}get isInVR(){return this.xrSessionMode==="immersive-vr"}get isInAR(){return this.xrSessionMode==="immersive-ar"}get isInPassThrough(){return this.xr?this.xr.isPassThrough:!1}get xrSession(){var i,e;return(e=(i=this.renderer)==null?void 0:i.xr)==null?void 0:e.getSession()}get xrFrame(){return this._xrFrame}get xrCamera(){var i,e;return this.renderer.xr.isPresenting?(e=(i=this.renderer)==null?void 0:i.xr)==null?void 0:e.getCamera():void 0}get arOverlayElement(){const i=this.domElement;return typeof i.getAROverlayContainer=="function"?i.getAROverlayContainer():this.domElement}get currentFrameEvent(){return this._currentFrameEvent}get mainCamera(){if(this._camera)return this._camera;if(this.mainCameraComponent){const i=this.mainCameraComponent;return i.cam||i.buildCamera(),i.cam}return null}set mainCamera(i){this._camera=i}get rendererData(){return this.sceneLighting}get isCreated(){return this._isCreated}createNewRenderer(i){var e,t,n;if((e=this.renderer)==null||e.dispose(),i={...qi.DefaultWebGLRendererParameters,...i},!i.canvas){const r=(n=(t=this.domElement)==null?void 0:t.shadowRoot)==null?void 0:n.querySelector("canvas");r&&(i.canvas=r,br&&console.log("Using canvas from shadow root",r))}br&&console.log("Using Renderer Parameters:",i,this.domElement),this.renderer=new Pl(i),this.renderer.debug.checkShaderErrors=pt()||ee("checkshadererrors")===!0,this.renderer.toneMappingExposure=1,this.renderer.toneMapping=zs,this.renderer.setClearColor(new Se("lightgrey"),0),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=e1,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputColorSpace=dt,this.input.bindEvents()}internalOnUpdateVisible(){var i,e;(i=this._intersectionObserver)==null||i.disconnect(),(e=this._intersectionObserver)==null||e.observe(this.domElement)}requestSizeUpdate(){this._sizeChanged=!0}updateSize(i=!1){var e,t,n;if(i||!this.isManagedExternally&&((e=this.renderer.xr)==null?void 0:e.isPresenting)===!1){this._sizeChanged=!1;const r=this.resolutionScaleFactor;let s=this.domWidth*r,o=this.domHeight*r;this.maxRenderResolution&&(this.maxRenderResolution.x=Math.max(1,this.maxRenderResolution.x),s=Math.min(this.maxRenderResolution.x,s),this.maxRenderResolution.y=Math.max(1,this.maxRenderResolution.y),o=Math.min(this.maxRenderResolution.y,o));const a=this.mainCamera;this.updateAspect(a),this.renderer.setSize(s,o,!0),this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%",this.composer&&((t=this.composer.setSize)==null||t.call(this.composer,s,o),"setPixelRatio"in this.composer&&typeof this.composer.setPixelRatio=="function"&&((n=this.composer.setPixelRatio)==null||n.call(this.composer,window.devicePixelRatio)))}}updateAspect(i,e,t){if(!i)return;e===void 0&&(e=this.domWidth),t===void 0&&(t=this.domHeight);const n=i.aspect;i.aspect=e/t,n!==i.aspect&&i.updateProjectionMatrix()}recreate(){this.clear(),this.create(this._originalCreationArgs)}async onCreate(i){return this.create(i)}async create(i){try{this._isCreating=!0,i!==this._originalCreationArgs&&(this._originalCreationArgs=Ym(i)),window.addEventListener("unhandledrejection",this.onUnhandledRejection);const e=await this.internalOnCreate(i);return this._isCreated=!0,e}finally{window.removeEventListener("unhandledrejection",this.onUnhandledRejection),this._isCreating=!1}}clear(){var i,e,t,n;ii.dispatchCallback(bn.ContextClearing,this),pa(this.scene,!0,!0),this.scene=new jr,(i=this.addressables)==null||i.dispose(),(e=this.lightmaps)==null||e.clear(),(n=(t=this.physics)==null?void 0:t.engine)==null||n.clearCaches(),this.isManagedExternally||this.renderer&&(this.renderer.renderLists.dispose(),this.renderer.state.reset(),this.renderer.resetState()),ii.dispatchCallback(bn.ContextCleared,this)}dispose(){this.internalOnDestroy()}onDestroy(){this.internalOnDestroy()}internalOnDestroy(){var i,e;this.clear(),(i=this.renderer)==null||i.setAnimationLoop(null),this.renderer&&(this.renderer.setClearAlpha(0),this.renderer.clear(),this.isManagedExternally||(br&&console.log("Disposing renderer"),this.renderer.dispose())),this.scene=null,this.renderer=null,this.input.dispose(),this.menu.onDestroy();for(const t of this._disposeCallbacks)try{t()}catch(n){console.error("Error in on dispose callback:",n,t)}(e=this.domElement)!=null&&e.parentElement&&this.domElement.parentElement.removeChild(this.domElement),this._isCreated=!1,ii.dispatchCallback(bn.ContextDestroyed,this),ii.unregister(this),qi.Current===this&&(qi.Current=null)}registerCoroutineUpdate(i,e,t){return typeof e?.next!="function"?(console.error("Registered invalid coroutine function from "+i.name+`
5254
5254
  Coroutine functions must be generators: "*myCoroutine() {...}"
5255
5255
  Start a coroutine from a component by calling "this.startCoroutine(myCoroutine())"`),e):(this.coroutines[t]||(this.coroutines[t]=[]),this.coroutines[t].push({comp:i,main:e}),e)}unregisterCoroutineUpdate(i,e){if(!this.coroutines[e])return;const t=this.coroutines[e].findIndex(n=>n.main===i);t>=0&&this.coroutines[e].splice(t,1)}stopAllCoroutinesFrom(i){for(const e in this.coroutines){const t=this.coroutines[e];for(let n=t.length-1;n>=0;n--)t[n].comp===i&&t.splice(n,1)}}setCurrentCamera(i){var e;if(!i)return;if(i.cam||i.buildCamera(),!i.cam){console.warn("Camera component is missing camera",i);return}const t=this._cameraStack.indexOf(i);t>=0&&this._cameraStack.splice(t,1),this._cameraStack.push(i),this.mainCameraComponent=i;const n=i.cam;n.isPerspectiveCamera&&this.updateAspect(n),(e=this.mainCameraComponent)==null||e.applyClearFlagsIfIsActiveCamera()}removeCamera(i){if(!i)return;const e=this._cameraStack.indexOf(i);if(e>=0&&this._cameraStack.splice(e,1),this.mainCameraComponent===i&&(this.mainCameraComponent=void 0,this._cameraStack.length>0)){const t=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(t)}}addBeforeRenderListener(i,e){this._onBeforeRenderListeners.has(i.uuid)||(this._onBeforeRenderListeners.set(i.uuid,[]),i.onBeforeRender=this._createRenderCallbackWrapper(i,this._onBeforeRenderListeners)),this._onBeforeRenderListeners.get(i.uuid).push(e)}removeBeforeRenderListener(i,e){if(this._onBeforeRenderListeners.has(i.uuid)){const t=this._onBeforeRenderListeners.get(i.uuid),n=t.indexOf(e);n>=0&&t.splice(n,1)}}addAfterRenderListener(i,e){var t;this._onAfterRenderListeners.has(i.uuid)||(this._onAfterRenderListeners.set(i.uuid,[]),i.onAfterRender=this._createRenderCallbackWrapper(i,this._onAfterRenderListeners)),(t=this._onAfterRenderListeners.get(i.uuid))==null||t.push(e)}removeAfterRenderListener(i,e){if(this._onAfterRenderListeners.has(i.uuid)){const t=this._onAfterRenderListeners.get(i.uuid),n=t.indexOf(e);n>=0&&t.splice(n,1)}}_createRenderCallbackWrapper(i,e){return(t,n,r,s,o,a)=>{const l=e.get(i.uuid);if(l)for(let c=0;c<l.length;c++){const u=l[c];u(t,n,r,s,o,a)}}}get isRendering(){return this._isRendering}setRequireDepth(i){this._requireDepthTexture=i}setRequireColor(i){this._requireColorTexture=i}get depthTexture(){var i;return((i=this._renderTarget)==null?void 0:i.depthTexture)||null}get opaqueColorTexture(){var i;return((i=this._renderTarget)==null?void 0:i.texture)||null}get isVisibleToUser(){if(this.isInXR)return!0;if(!this._isVisible)return!1;const i=getComputedStyle(this.domElement);return i.visibility!=="hidden"&&i.display!=="none"&&i.opacity!=="0"}async internalOnCreate(i){var e,t,n,r,s;const o=++this._createId;br&&console.log("Creating context",this.name,i);const a=globalThis["needle:dependencies:ready"];a instanceof Promise&&(br&&console.log("Waiting for dependencies to be ready"),await a.catch(d=>{(br||pt())&&console.error("Needle Engine dependencies failed to load",d)}).then(()=>{br&&console.log("Needle Engine dependencies are ready")})),this.clear(),this.isManagedExternally===!1&&(this.createNewRenderer(),(e=this.renderer)==null||e.setAnimationLoop(null)),await na(1),qi.Current=this,await ii.dispatchCallback(bn.ContextCreationStart,this);let l=!0,c;try{qi.Current=this,i?c=await this.internalLoadInitialContent(o,i):c=[]}catch(d){console.error(d),l=!1}if(!l||o!==this._createId)return!1;if(this.internalOnUpdateVisible(),!this.renderer)return br&&console.warn("Context has no renderer (perhaps it was disconnected?",this.domElement.isConnected),!1;!this.isManagedExternally&&!this.domElement.shadowRoot&&this.domElement.prepend(this.renderer.domElement),qi.Current=this,qi.Current=this;for(let d=0;d<this.new_scripts.length;d++){const p=this.new_scripts[d];if(p.gameObject!==void 0&&p.gameObject!==null){p.gameObject.userData===void 0&&(p.gameObject.userData={}),p.gameObject.userData.components===void 0&&(p.gameObject.userData.components=[]);const f=p.gameObject.userData.components;f.includes(p)||f.push(p)}}if(this.post_setup_callbacks)for(let d=0;d<this.post_setup_callbacks.length;d++)qi.Current=this,await this.post_setup_callbacks[d](this);if(!this.mainCamera){qi.Current=this;let d=null;ju(this.scene,p=>{const f=p;if(f!=null&&f.isCamera){if(yg(f.gameObject),!f.activeAndEnabled)return;if(f.tag==="MainCamera")return d=f,!0;d=f}}),d?this.setCurrentCamera(d):!ii.dispatchCallback(bn.MissingCamera,this,{files:c})&&!this.mainCamera&&!this.isManagedExternally&&console.warn("Missing camera in main scene",this)}if(this.input.bindEvents(),qi.Current=this,xb(this),this.physics.engine&&((t=this.physics.engine)==null||t.step(0),(n=this.physics.engine)==null||n.postStep()),!this.isManagedExternally&&this.composer&&this.mainCamera){const d=new Mb(this.scene,this.mainCamera);this.renderer.setSize(this.domWidth,this.domHeight),this.composer.addPass(d),this.composer.setSize(this.domWidth,this.domHeight)}this._sizeChanged=!0,this._stats&&(this._stats.showPanel(0),(r=this.domElement.shadowRoot)==null||r.appendChild(this._stats.dom)),br&&cb(this.scene,!0),this.targetFrameRate===void 0?(br&&console.warn("No target framerate set, using default",qi.DefaultTargetFrameRate),this.targetFrameRate=qi._defaultTargetFramerate):br&&console.log("Target framerate set to",this.targetFrameRate),this._dispatchReadyAfterFrame=!0;const u=ii.dispatchCallback(bn.ContextCreated,this,{files:c});return u&&("internalSetLoadingMessage"in this.domElement&&typeof this.domElement.internalSetLoadingMessage=="function"&&((s=this.domElement)==null||s.internalSetLoadingMessage("finish loading")),await u),Ou(this,bn.ContextCreated),br&&console.log("Context Created...",this.renderer,this.renderer.domElement),this._isCreating=!1,this.isManagedExternally||this.restartRenderLoop(),u}async internalLoadInitialContent(i,e){var t,n;const r=new Array;if(e.files.length===0)return r;const s=[...e.files],o={name:"",progress:null,index:0,count:s.length},a=Yo(),l=0;for(let c=0;c<s.length;c++){if(i!==this._createId){br&&console.log("Aborting loading because create id changed",i,this._createId);break}const u=s[c];if(!u.includes(".glb")&&!u.includes(".gltf")){const p=`Needle Engine: found suspicious src "${u}"`;console.warn(p),Bs()&&Qi(p)}(t=e?.onLoadingStart)==null||t.call(this,c,u),br&&console.log("Context Load "+u);const d=await a.loadSync(this,u,u,l,p=>{var f;o.name=u,o.progress=p,o.index=c,o.count=s.length,(f=e.onLoadingProgress)==null||f.call(this,o)});(n=e?.onLoadingFinished)==null||n.call(this,c,u,d??null),d?r.push({src:u,file:d}):console.warn("Could not load file: "+u)}if(i!==this._createId){for(const c of r)if(c&&c.file)for(const u of c.file.scenes)pa(u,!0,!0)}else for(const c of r)c&&c.file&&this.scene.add(c.file.scene);return r}restartRenderLoop(){return this.renderer?this._isCreating?(console.warn("Can not start render loop while creating context"),!1):(this.renderer.setAnimationLoop((i,e)=>{this.isManagedExternally||this.update(i,e)}),!0):(console.error("Can not start render loop without renderer"),!1)}update(i,e){if(e===void 0&&(e=null),pt()||br||PY())try{this.internalStep(i,e),this._renderlooperrors=0}catch(t){this._renderlooperrors+=1,(pt()||br)&&(t instanceof Error||t instanceof TypeError)&&$i("Caught unhandled exception during render-loop - see console for details.",Ws.Error),console.error("Frame #"+this.time.frame+`
5256
5256
  `,t),this._renderlooperrors>=3&&(console.warn("Stopping render loop due to error"),this.renderer.setAnimationLoop(null)),this.domElement.dispatchEvent(new CustomEvent("error",{detail:t}))}else this.internalStep(i,e)}updatePhysics(i){this.internalUpdatePhysics(i)}internalStep(i,e){this.internalOnBeforeRender(i,e)!==!1&&(this.internalOnRender(),this.internalOnAfterRender())}internalOnBeforeRender(i,e){var t;const n=e!==null&&this._xrFrame===null;if(this._xrFrame=e,n&&this.domElement.dispatchEvent(new CustomEvent("xr-session-started",{detail:{context:this,session:this.xrSession,frame:e}})),this._currentFrameEvent=-1,this.isManagedExternally===!1&&this.isInXR===!1&&this.targetFrameRate!==void 0){this._lastTimestamp===0&&(this._lastTimestamp=i),this._accumulatedTime+=(i-this._lastTimestamp)/1e3,this._lastTimestamp=i;let r=this.targetFrameRate;if(typeof r=="object"&&(r=r.value),this._accumulatedTime<1/(r+1))return!1;this._accumulatedTime=0}if((t=this._stats)==null||t.begin(),qi.Current=this,this.onHandlePaused())return!1;for(qi.Current=this,this.time.update(),bee&&console.log("FPS",this.time.smoothedFps.toFixed(0)),xb(this),wb(this.scene),oL(this),Ou(this,-1);this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);const r=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(r)}if(this.pre_update_oneshot_callbacks){for(const r in this.pre_update_oneshot_callbacks)this.pre_update_oneshot_callbacks[r]();this.pre_update_oneshot_callbacks.length=0}if(this.pre_update_callbacks)for(const r in this.pre_update_callbacks)this.pre_update_callbacks[r]();this._currentFrameEvent=0;for(let r=0;r<this.scripts_earlyUpdate.length;r++){const s=this.scripts_earlyUpdate[r];s.activeAndEnabled&&s.earlyUpdate!==void 0&&(qi.Current=this,s.earlyUpdate())}if(this.executeCoroutines(0),Ou(this,0),this.onHandlePaused())return!1;this._currentFrameEvent=1;for(let r=0;r<this.scripts_update.length;r++){const s=this.scripts_update[r];s.activeAndEnabled&&s.update!==void 0&&(qi.Current=this,s.update())}if(this.executeCoroutines(1),Ou(this,1),this.onHandlePaused())return!1;this._currentFrameEvent=2;for(let r=0;r<this.scripts_lateUpdate.length;r++){const s=this.scripts_lateUpdate[r];s.activeAndEnabled&&s.lateUpdate!==void 0&&(qi.Current=this,s.lateUpdate())}if(this.executeCoroutines(2),Ou(this,2),this.onHandlePaused()||(this.physicsSteps===void 0&&(this.physicsSteps=1),this.physics.engine&&this.physicsSteps>0&&this.internalUpdatePhysics(this.physicsSteps),this.onHandlePaused()))return!1;if(this.isVisibleToUser||this.runInBackground){this._currentFrameEvent=3;for(let r=0;r<this.scripts_onBeforeRender.length;r++){const s=this.scripts_onBeforeRender[r];s.activeAndEnabled&&s.onBeforeRender!==void 0&&(qi.Current=this,s.onBeforeRender(e))}if(this.executeCoroutines(3),Ou(this,3),this._sizeChanged&&this.updateSize(),this.pre_render_callbacks)for(const r in this.pre_render_callbacks)this.pre_render_callbacks[r](e)}return!0}internalUpdatePhysics(i){if(!this.physics.engine)return!1;const e=i,t=this.time.deltaTime/e;for(let n=0;n<e;n++)this._currentFrameEvent=9,this.executeCoroutines(9),this.physics.engine.step(t),this._currentFrameEvent=10,this.executeCoroutines(10);return this.physics.engine.postStep(),!0}internalOnRender(){this.isManagedExternally||(kY(this),this._currentFrameEvent=-1,this.renderNow(),this._currentFrameEvent=4)}internalOnAfterRender(){if(this.isVisibleToUser||this.runInBackground){for(let i=0;i<this.scripts_onAfterRender.length;i++){const e=this.scripts_onAfterRender[i];e.activeAndEnabled&&e.onAfterRender!==void 0&&(qi.Current=this,e.onAfterRender())}if(this.executeCoroutines(4),Ou(this,4),this.post_render_callbacks)for(const i in this.post_render_callbacks)this.post_render_callbacks[i]()}this._currentFrameEvent=-1,this.connection.sendBufferedMessagesNow(),this._stats&&(this._stats.end(),this.time.frameCount%150===0&&console.log(this.renderer.info.render.calls+" DrawCalls",`
5257
5257
  Render:`,{...this.renderer.info.render},`
5258
- Memory:`,{...this.renderer.info.memory})),this._dispatchReadyAfterFrame&&(this._dispatchReadyAfterFrame=!1,this.domElement.dispatchEvent(new CustomEvent("ready")),ii.dispatchCallback(bn.ContextFirstFrameRendered,this))}renderNow(i){return!i&&(i=this.mainCamera,!i)?!1:(this._isRendering=!0,this.renderRequiredTextures(),this.composer&&!this.isInXR?this.composer.render(this.time.deltaTime):i&&this.renderer.render(this.scene,i),this._isRendering=!1,!0)}onHandlePaused(){const i=this.evaluatePaused();if(this._wasPaused!==i){yee&&console.log("Paused?",i,"context:"+this.alias);for(let e=0;e<this.scripts_pausedChanged.length;e++){const t=this.scripts_pausedChanged[e];t.activeAndEnabled&&t.onPausedChanged!==void 0&&(qi.Current=this,t.onPausedChanged(i,this._wasPaused))}}return this._wasPaused=i,i}evaluatePaused(){return this.isInXR?!1:this.isPaused?!0:this.runInBackground?!1:!this.isVisibleToUser}renderRequiredTextures(){if(!this.mainCamera||!this._requireDepthTexture&&!this._requireColorTexture)return;if(!this._renderTarget){if(this._renderTarget=new Ht(this.domWidth,this.domHeight),this._requireDepthTexture){const t=new hp(this.domWidth,this.domHeight);this._renderTarget.depthTexture=t}this._requireColorTexture&&(this._renderTarget.texture=new gt,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=Ft,this._renderTarget.texture.magFilter=Ft,this._renderTarget.texture.format=di)}const i=this._renderTarget;i.texture&&(i.texture.colorSpace=this.renderer.outputColorSpace);const e=this.renderer.getRenderTarget();this.renderer.setRenderTarget(i),this.renderer.render(this.scene,this.mainCamera),this.renderer.setRenderTarget(e)}executeCoroutines(i){var e;if(this.coroutines[i]){const n=this.coroutines[i];for(let r=0;r<n.length;r++)try{const s=n[r];if(!s.comp||s.comp.destroyed||!s.main||s.comp.enabled===!1){_ee&&console.log("Removing coroutine",s.comp,s.comp.enabled),n.splice(r,1),--r;continue}const o=s.chained;if(o&&o.length>0){const c=o[o.length-1].next();if(c.done&&o.pop(),t(c)&&(s.chained||(s.chained=[]),s.chained.push(c.value)),!c.done)continue}const a=s.main.next();if(a.done===!0){n.splice(r,1),--r;continue}const l=a.value;if(t(l)){if(l.next().done)continue;s.chained||(s.chained=[]),s.chained.push(l)}else if(l instanceof Promise){const c=l;s.chained||(s.chained=[]);const u=I3(c);(e=s.chained)==null||e.push(u);continue}}catch(s){console.error(s)}}function t(n){return!!(n&&n.next&&n.return)}}};let Lt=qi;h(Lt,"_defaultTargetFramerate",{value:60}),h(Lt,"_defaultWebglRendererParameters",{antialias:!0,alpha:!1,powerPreference:"high-performance"}),ii.registerCallback(bn.ContextCreated,i=>{const e=i.context;mF(e),pF(e)});const m_=ee("debugcomponents"),cF="eff8ba80-635d-11ec-90d6-0242ac120003";class or{constructor(e){h(this,"_originalSeed"),h(this,"_seed"),typeof e=="string"&&(e=or.hash(e)),this._originalSeed=e,this._seed=e}get seed(){return this._seed}set seed(e){this._seed=e}reset(){this._seed=this._originalSeed}generateUUID(e){if(typeof e=="string")return cL(e,cF);const t=this._seed;return this._seed-=1,cL(t.toString(),cF)}initialize(e){typeof e=="string"?this._seed=or.hash(e):this._seed=e}static createFromString(e){return new or(this.hash(e))}static hash(e){let t=0;for(let n=0;n<e.length;n++)t=e.charCodeAt(n)+((t<<5)-t);return t}}var hF=(i=>(i.NewInstanceCreated="new-instance-created",i.InstanceDestroyed="instance-destroyed",i))(hF||{});class uF{constructor(e){h(this,"guid"),this.guid=e}}function g_(i,e,t=!0){if(!i)return;const n=i;if(pa(i,t),!e){console.warn("Can not send destroy: No networking connection provided",i.guid);return}if(!e.isConnected){console.warn("Can not send destroy: not connected",i.guid);return}let r=i.guid;if(!r&&n.uuid&&(r=n.uuid),!r){console.warn("Can not send destroy: failed to find guid",i);return}const s=new uF(r);e.send("instance-destroyed",s,la.Queued)}function dF(i,e){const t=new uF(i);e.send("instance-destroyed",t,la.Queued)}function pF(i){i.connection.beginListen("instance-destroyed",e=>{m_&&console.log("[Remote] Destroyed",i.scene,e);const t=Xg(e.guid,i.scene);t&&pa(t)})}class See{constructor(e,t,n){h(this,"filename"),h(this,"hash"),h(this,"size"),this.filename=e,this.hash=t,this.size=n}}class fF{constructor(e,t){h(this,"guid"),h(this,"originalGuid"),h(this,"seed"),h(this,"visible"),h(this,"hostData"),h(this,"dontSave"),h(this,"parent"),h(this,"position"),h(this,"rotation"),h(this,"scale"),h(this,"preventCreation"),this.originalGuid=e,this.guid=t}}function $M(i,e,t,n){var r;const s=i;if(!s.guid)return console.warn("Can not instantiate: No guid",s),null;if(e.context||(e.context=Lt.Current),!e.context)return console.error("Missing network instantiate options / reference to network connection in sync instantiate"),null;const o=e?{...e}:null,{instance:a,seed:l}=Cee(s,e);if(a){const c=a;if(c.guid){m_&&console.log("[Local] new instance","gameobject:",a?.guid);const u=new fF(s.guid,c.guid);u.seed=l,o&&(o.position&&(u.position={x:o.position.x,y:o.position.y,z:o.position.z}),o.rotation&&(u.rotation={x:o.rotation.x,y:o.rotation.y,z:o.rotation.z,w:o.rotation.w}),o.scale&&(u.scale={x:o.scale.x,y:o.scale.y,z:o.scale.z})),u.position||(u.position={x:c.position.x,y:c.position.y,z:c.position.z}),u.rotation||(u.rotation={x:c.quaternion.x,y:c.quaternion.y,z:c.quaternion.z,w:c.quaternion.w}),u.scale||(u.scale={x:c.scale.x,y:c.scale.y,z:c.scale.z}),u.visible=s.visible,o!=null&&o.parent&&(typeof o.parent=="string"?u.parent=o.parent:u.parent=o.parent.guid),u.hostData=t,n===!1&&(u.dontSave=!0),(r=e?.context)==null||r.connection.send("new-instance-created",u)}else console.warn("Missing guid, can not send new instance event",c)}return a}function v_(){return Math.random()*9999999}function mF(i){i.connection.beginListen("new-instance-created",async e=>{const t=await Eee(e.originalGuid,i.scene);if(e.preventCreation===!0)return;if(!t){console.warn("could not find object that was instantiated: "+e.guid);return}const n=new Sa;e.position&&(n.position=new S(e.position.x,e.position.y,e.position.z)),e.rotation&&(n.rotation=new Me(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w)),e.scale&&(n.scale=new S(e.scale.x,e.scale.y,e.scale.z)),n.parent=e.parent,e.seed&&(n.idProvider=new or(e.seed)),n.visible=e.visible,n.context=i,m_&&i.alias&&console.log("[Remote] instantiate in: "+i.alias);const r=Gp(t,n);r&&(e.parent==="scene"&&i.scene.add(r),m_&&console.log("[Remote] new instance","gameobject:",r?.guid,t))})}function Cee(i,e){const t=v_(),n=e??new Sa;n.idProvider=new or(t);const r=Gp(i,n);return{seed:t,instance:r}}const gF={};function vF(i,e){gF[i]=e}async function Eee(i,e){const t=gF[i];if(t!=null){const n=await t(i);if(n)return n}return AF(i,e)}function AF(i,e){if(e===null||!i)return null;if(e.guid===i)return e;if(e.children)for(const t of e.children){const n=AF(i,t);if(n)return n}return null}const A_=ee("debuggetcomponent"),y_=ee("debuginstantiate");var yF=(i=>(i[i.None=0]="None",i[i.HideInHierarchy=1]="HideInHierarchy",i[i.HideInInspector=2]="HideInInspector",i[i.DontSaveInEditor=4]="DontSaveInEditor",i[i.NotEditable=8]="NotEditable",i[i.DontSaveInBuild=16]="DontSaveInBuild",i[i.DontUnloadUnusedAsset=32]="DontUnloadUnusedAsset",i[i.DontSave=52]="DontSave",i[i.HideAndDontSave=61]="HideAndDontSave",i))(yF||{});class Sa{constructor(){h(this,"idProvider"),h(this,"parent"),h(this,"keepWorldPosition"),h(this,"position"),h(this,"rotation"),h(this,"scale"),h(this,"visible"),h(this,"context")}clone(){var e,t,n;const r=new Sa;return r.idProvider=this.idProvider,r.parent=this.parent,r.keepWorldPosition=this.keepWorldPosition,r.position=(e=this.position)==null?void 0:e.clone(),r.rotation=(t=this.rotation)==null?void 0:t.clone(),r.scale=(n=this.scale)==null?void 0:n.clone(),r}cloneAssign(e){var t,n,r;this.idProvider=e.idProvider,this.parent=e.parent,this.keepWorldPosition=e.keepWorldPosition,this.position=(t=e.position)==null?void 0:t.clone(),this.rotation=(n=e.rotation)==null?void 0:n.clone(),this.scale=(r=e.scale)==null?void 0:r.clone()}}function jp(i){return i.visible}function qg(i,e){return typeof e=="number"&&(e=e>.5),i.visible=e,i.visible}function bF(i){return i[Nl]||b_(i)}function _F(i,e){i[rL]=e}function b_(i){return qo.isUsingInstancing(i)}function Xg(i,e){return xp(i,e,!0,!0)}const xF=Symbol("isDestroyed");function zu(i){return i[xF]}function wF(i,e){i[xF]=e}const eT=Symbol("isDontDestroy");function tT(i,e=!0){i[eT]=e}const __=[],x_=[];function pa(i,e=!0,t=!1){__.length=0,x_.length=0,iT(i,e,!0);for(const n of __)n.gameObject=null,n.context=null;for(const n of x_)wF(n,!0),t&&Ii(n),tL(n);x_.length=0,__.length=0}function iT(i,e=!0,t=!0){var n;if(i==null)return;const r=i;if(r.isComponent){if(r[eT])return;__.push(r);const a=r.gameObject;r.__internalDisable(),r.__internalDestroy(),r.gameObject=a;return}if(i[eT])return;const s=i;A_&&console.log(s),x_.push(s);const o=(n=s.userData)==null?void 0:n.components;if(o!=null&&Array.isArray(o)){let a=o.length;for(let l=0;l<o.length;l++){const c=o[l];iT(c,e,!1),o.length<a&&(a=o.length,l--)}}if(e&&s.children)for(const a of s.children)iT(a,e,!1);t&&s.removeFromParent()}function ju(i,e,t=!0){return SF(i,e,t)}function*nT(i,e,t=!1,n=999,r=0){if(i!=null&&i.userData.components&&!(r>n)){for(const s of i.userData.components)e&&s?.isComponent===!0&&s instanceof e?yield s:yield s;if(t===!0)for(const s of i.children)yield*nT(s,e,!0,n,r+1)}}function SF(i,e,t,n=0){var r;if(i){if(i.isObject3D,n>1e3){console.warn("Failed to iterate components: too many levels");return}if((r=i.userData)!=null&&r.components)for(let s=0;s<i.userData.components.length;s++){const o=i.userData.components[s];if(o?.isComponent===!0){const a=e(o);if(a!==void 0)return a}}if(t&&i.children){const s=n+1;for(let o=0;o<i.children.length;o++){const a=i.children[o];if(!a)continue;const l=SF(a,e,t,s);if(l!==void 0)return l}}}}function Gp(i,e=null){let t=null;e!==null&&(e.x!==void 0?(t=new Sa,t.position=e):t=e);let n=Lt.Current;t!=null&&t.context&&(n=t.context),A_&&n.alias&&console.log("context",n.alias),t&&!t.idProvider&&(t.idProvider=new or(Date.now()));const r=[],s={},o={},a=CF(n,i,t,r,s,o);a&&(Tee(s),Mee(o,s)),A_&&(cb(i,!0),cb(a,!0));const l={};for(const c in r){const u=r[c],d=u.guid;t&&t.idProvider&&(u.guid=t.idProvider.generateUUID(),l[d]=u.guid,A_&&console.log(u.name,u.guid)),f_(u,n),u.__internalNewInstanceCreated&&u.__internalNewInstanceCreated()}for(const c in r){const u=r[c];u.resolveGuids&&u.resolveGuids(l),u.enabled!==!1&&(u.enabled=!0)}return xb(n),a}function CF(i,e,t,n,r,s){var o;if(!e)return null;const a=e.userData;e.userData={};const l=e.children;e.children=[];const c=e.clone(!1);if(w_(c),e.userData=a,e.children=l,r[e.uuid]={original:e,clone:c},y_&&console.log("ADD",e,c),e.type==="SkinnedMesh"&&(s[e.uuid]={original:e,clone:c}),t?.visible!==void 0&&(c.visible=t.visible),t!=null&&t.idProvider){c.uuid=t.idProvider.generateUUID();const d=c;d&&(d.guid=c.uuid)}e.animations&&e.animations.length>0&&(c.animations=[...e.animations]);const u=e.parent;if(u&&u.add(c),t!=null&&t.position?Qr(c,t.position):c.position.copy(e.position),t!=null&&t.rotation?So(c,t.rotation):c.quaternion.copy(e.quaternion),t!=null&&t.scale?c.scale.copy(t.scale):c.scale.copy(e.scale),t!=null&&t.parent&&t.parent!=="scene"){let d=null;if(typeof t.parent=="string"?d=xp(t.parent,i.scene,!0):d=t.parent,d){const p=t.keepWorldPosition===!0?d.attach:d.add;p?p.call(d,c):console.error("Invalid parent object",d,"received when instantiating:",e)}else console.warn("could not find parent:",t.parent)}for(const[d,p]of Object.entries(e.userData))d!=="components"&&(c.userData[d]=p);if((o=e.userData)!=null&&o.components){const d=e.userData.components,p=[];c.userData.components=p;for(let f=0;f<d.length;f++){const m=d[f],A=new m.constructor;Bp(A,m),m[gg]!==void 0&&(A[gg]=m[gg]),p.push(A),A.gameObject=c,n.push(A),mg.dispatchComponentLifecycleEvent(fg.Added,A)}}t&&(t.position=void 0,t.rotation=void 0,t.scale=void 0,t.parent=void 0);for(const d in e.children){const p=e.children[d],f=CF(i,p,t,n,r,s);f&&c.add(f)}return c}function Mee(i,e){for(const t in i){const n=i[t],r=n.original,s=r.skeleton,o=n.clone;if(!s){console.warn("Skinned mesh has no skeleton?",n);continue}const a=s.bones,l=o.skeleton.clone();o.skeleton=l,o.bindMatrix.clone().copy(r.bindMatrix),o.bindMatrixInverse.copy(r.bindMatrixInverse);const c=[];l.bones=c;for(let u=0;u<a.length;u++){const d=a[u],p=e[d.uuid].clone;c.push(p)}}for(const t in i){const n=i[t].clone;n.skeleton.update(),n.bind(n.skeleton,n.bindMatrix),n.updateMatrixWorld(!0)}}function Tee(i){var e;for(const t in i){const n=i[t].clone;if((e=n.userData)!=null&&e.components)for(let r=0;r<n.userData.components.length;r++){const s=n.userData.components[r],o=Object.entries(s);for(const[a,l]of o)if(Array.isArray(l)){const c=[];s[a]=c;for(let u=0;u<l.length;u++){const d=l[u];if(typeof d!="object"){c.push(d);continue}const p=EF(s,a,d,i);p!==void 0?c.push(p):c.push(d)}}else if(typeof l=="object"){const c=EF(s,a,l,i);c!==void 0&&(s[a]=c)}}}}function EF(i,e,t,n){var r,s;if(t!=null)if(t.isComponent===!0){const o=t.gameObject;if(o){const a=o.uuid,l=(r=n[a])==null?void 0:r.clone;if(!l){y_&&console.log("reference did not change",e,i,t);return}const c=o.userData.components.indexOf(t);if(c>=0)return y_&&console.log(e,a),l.userData.components[c];console.warn("could not find component",e,t)}}else if(t.isObject3D===!0){if(e==="gameObject")return;const o=t;if(o){const a=o.uuid,l=(s=n[a])==null?void 0:s.clone;if(l)return y_&&console.log(e,"old",t,"new",l),l}}else{if(t.isVector4||t.isVector3||t.isVector2||t.isQuaternion||t.isEuler||t.isColor===!0)return t.clone();if(t.isEventList===!0)return new t.constructor}}const MF=new Map;function Iee(i,e){if(!i)return;if(!e){console.warn("No prototype found",i,i.prototype,i.constructor);return}const t=MF.get(e);t&&t.apply(i)}function Ree(i){const e=Pee(i.prototype);MF.set(i,e)}function Pee(i){return new Bee(i)}class Bee{constructor(e){h(this,"$symbol"),h(this,"extensions"),h(this,"descriptors"),this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(e),this.descriptors=new Array;for(let t=0;t<this.extensions.length;t++){const n=this.extensions[t],r=Object.getOwnPropertyDescriptor(e,n);r&&this.descriptors.push(r)}}apply(e){if(!e[this.$symbol]){e[this.$symbol]=!0;for(let t=0;t<this.extensions.length;t++){const n=this.extensions[t],r=this.descriptors[t];r&&Object.defineProperty(e,n,r)}}}}function w_(i){i&&i.isObject3D===!0&&Iee(i,ge)}ge.prototype.SetActive=function(i){this.visible=i},ge.prototype.setActive=function(i){this.visible=i},ge.prototype.destroy=function(){pa(this)},ge.prototype.addComponent=function(i,e){return Gu(this,i,e)},ge.prototype.addNewComponent=function(i,e){return Gu(this,i,e)},ge.prototype.removeComponent=function(i){return rT(this,i)},ge.prototype.getOrAddComponent=function(i,e){return Yg(this,i,e)},ge.prototype.getComponent=function(i){return Qu(this,i)},ge.prototype.getComponents=function(i,e){return Jg(this,i,e)},ge.prototype.getComponentInChildren=function(i){return Kg(this,i)},ge.prototype.getComponentsInChildren=function(i,e){return Zg(this,i,e)},ge.prototype.getComponentInParent=function(i){return $g(this,i)},ge.prototype.getComponentsInParent=function(i,e){return S_(this,i,e)},Object.getOwnPropertyDescriptor(ge.prototype,"activeSelf")||Object.defineProperty(ge.prototype,"activeSelf",{get:function(){return jp(this)},set:function(i){qg(this,i)}}),Object.getOwnPropertyDescriptor(ge.prototype,"transform")||Object.defineProperty(ge.prototype,"transform",{get:function(){return this}}),Object.getOwnPropertyDescriptor(ge.prototype,"worldPosition")||Object.defineProperty(ge.prototype,"worldPosition",{get:function(){return this instanceof xE?Rt(this.object):Rt(this)},set:function(i){Qr(this,i)}}),Object.getOwnPropertyDescriptor(ge.prototype,"worldQuaternion")||Object.defineProperty(ge.prototype,"worldQuaternion",{get:function(){return this instanceof xE?xi(this.object):xi(this)},set:function(i){So(this,i)}}),Object.getOwnPropertyDescriptor(ge.prototype,"worldRotation")||Object.defineProperty(ge.prototype,"worldRotation",{get:function(){return rg(this)},set:function(i){vE(this,i)}}),Object.getOwnPropertyDescriptor(ge.prototype,"worldScale")||Object.defineProperty(ge.prototype,"worldScale",{get:function(){return ki(this)},set:function(i){ng(this,i)}}),Object.getOwnPropertyDescriptor(ge.prototype,"worldForward")||Object.defineProperty(ge.prototype,"worldForward",{get:function(){return Zi().set(0,0,1).applyQuaternion(xi(this))}}),Object.getOwnPropertyDescriptor(ge.prototype,"worldRight")||Object.defineProperty(ge.prototype,"worldRight",{get:function(){return Zi().set(1,0,0).applyQuaternion(xi(this))}}),Object.getOwnPropertyDescriptor(ge.prototype,"worldUp")||Object.defineProperty(ge.prototype,"worldUp",{get:function(){return Zi().set(0,1,0).applyQuaternion(xi(this))}}),Ree(ge);const Dee=ee("debuggetcomponent"),TF=()=>Dee||globalThis.NEEDLE_DEBUG_GETCOMPONENT===!0;function Oee(i){return i==null||i.isObject3D?i:i.object&&i.object.isObject3D?i.object:i}function rT(i,e){if(!i||!i.userData.components)return e;const t=i.userData.components.indexOf(e);return t<0||(mg.dispatchComponentLifecycleEvent(fg.Removing,e),e.gameObject=null,i.userData.components.splice(t,1)),e}function Yg(i,e,t){return Qu(i,e)||Gu(i,e,t)}const IF=new or("addComponentIdProvider");function nh(i,e,t=!0){i.userData||(i.userData={}),i.userData.components||(i.userData.components=[]),i.userData.components.push(e),e.gameObject=i,(e.guid===void 0||e.guid==="invalid")&&(e.guid=IF.generateUUID()),w_(i),f_(e);try{t&&e.__internalAwake&&(yg(i),e.activeAndEnabled&&e.__internalAwake()),mg.dispatchComponentLifecycleEvent(fg.Added,e)}catch(n){console.error(n)}return e}function Gu(i,e,t,n){if(typeof e=="function"){const r=new e;t&&r.__internalNewInstanceCreated(t);let s=!0;return n?.callAwake!=null&&(s=n.callAwake),nh(i,r,s)}if(e.destroyed)return console.warn("Can not move/add a destroyed component",e),e;if(e.gameObject===i)return e;if(e.gameObject&&e.gameObject.userData.components){const r=e.gameObject.userData.components.indexOf(e);e.gameObject.userData.components.splice(r,1)}if(!i.userData.components)i.userData.components=[];else if(i.userData.components.includes(e))return e;return i.userData.components.push(e),e.gameObject=i,(e.guid===void 0||e.guid==="invalid")&&(e.guid=IF.generateUUID()),t&&e._internalInit(t),f_(e),e}function RF(i){if(i.gameObject&&i.gameObject.userData.components){const e=i.gameObject.userData.components.indexOf(i);i.gameObject.userData.components.splice(e,1)}i.__internalDisable&&i.__internalDisable(),zl(i,i.context??Lt.Current),i.destroy(),i.gameObject=null}let PF=!1;function BF(i,e,t){var n;if(i==null)return null;if(!i.isObject3D)return console.error("Object is not object3D"),null;if(!((n=i?.userData)!=null&&n.components)||(typeof e=="string"&&(PF||(PF=!0,console.warn(`Accessing components by name is not supported.
5258
+ Memory:`,{...this.renderer.info.memory})),this._dispatchReadyAfterFrame&&(this._dispatchReadyAfterFrame=!1,this.domElement.dispatchEvent(new CustomEvent("ready")),ii.dispatchCallback(bn.ContextFirstFrameRendered,this))}renderNow(i){return!i&&(i=this.mainCamera,!i)?!1:(this._isRendering=!0,this.renderRequiredTextures(),this.composer&&!this.isInXR?this.composer.render(this.time.deltaTime):i&&this.renderer.render(this.scene,i),this._isRendering=!1,!0)}onHandlePaused(){const i=this.evaluatePaused();if(this._wasPaused!==i){yee&&console.log("Paused?",i,"context:"+this.alias);for(let e=0;e<this.scripts_pausedChanged.length;e++){const t=this.scripts_pausedChanged[e];t.activeAndEnabled&&t.onPausedChanged!==void 0&&(qi.Current=this,t.onPausedChanged(i,this._wasPaused))}}return this._wasPaused=i,i}evaluatePaused(){return this.isInXR?!1:this.isPaused?!0:this.runInBackground?!1:!this.isVisibleToUser}renderRequiredTextures(){if(!this.mainCamera||!this._requireDepthTexture&&!this._requireColorTexture)return;if(!this._renderTarget){if(this._renderTarget=new Ht(this.domWidth,this.domHeight),this._requireDepthTexture){const t=new hp(this.domWidth,this.domHeight);this._renderTarget.depthTexture=t}this._requireColorTexture&&(this._renderTarget.texture=new gt,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=Ft,this._renderTarget.texture.magFilter=Ft,this._renderTarget.texture.format=di)}const i=this._renderTarget;i.texture&&(i.texture.colorSpace=this.renderer.outputColorSpace);const e=this.renderer.getRenderTarget();this.renderer.setRenderTarget(i),this.renderer.render(this.scene,this.mainCamera),this.renderer.setRenderTarget(e)}executeCoroutines(i){var e;if(this.coroutines[i]){const n=this.coroutines[i];for(let r=0;r<n.length;r++)try{const s=n[r];if(!s.comp||s.comp.destroyed||!s.main||s.comp.enabled===!1){_ee&&console.log("Removing coroutine",s.comp,s.comp.enabled),n.splice(r,1),--r;continue}const o=s.chained;if(o&&o.length>0){const c=o[o.length-1].next();if(c.done&&o.pop(),t(c)&&(s.chained||(s.chained=[]),s.chained.push(c.value)),!c.done)continue}const a=s.main.next();if(a.done===!0){n.splice(r,1),--r;continue}const l=a.value;if(t(l)){if(l.next().done)continue;s.chained||(s.chained=[]),s.chained.push(l)}else if(l instanceof Promise){const c=l;s.chained||(s.chained=[]);const u=IU(c);(e=s.chained)==null||e.push(u);continue}}catch(s){console.error(s)}}function t(n){return!!(n&&n.next&&n.return)}}};let Lt=qi;h(Lt,"_defaultTargetFramerate",{value:60}),h(Lt,"_defaultWebglRendererParameters",{antialias:!0,alpha:!1,powerPreference:"high-performance"}),ii.registerCallback(bn.ContextCreated,i=>{const e=i.context;mF(e),pF(e)});const m_=ee("debugcomponents"),cF="eff8ba80-635d-11ec-90d6-0242ac120003";class or{constructor(e){h(this,"_originalSeed"),h(this,"_seed"),typeof e=="string"&&(e=or.hash(e)),this._originalSeed=e,this._seed=e}get seed(){return this._seed}set seed(e){this._seed=e}reset(){this._seed=this._originalSeed}generateUUID(e){if(typeof e=="string")return cL(e,cF);const t=this._seed;return this._seed-=1,cL(t.toString(),cF)}initialize(e){typeof e=="string"?this._seed=or.hash(e):this._seed=e}static createFromString(e){return new or(this.hash(e))}static hash(e){let t=0;for(let n=0;n<e.length;n++)t=e.charCodeAt(n)+((t<<5)-t);return t}}var hF=(i=>(i.NewInstanceCreated="new-instance-created",i.InstanceDestroyed="instance-destroyed",i))(hF||{});class uF{constructor(e){h(this,"guid"),this.guid=e}}function g_(i,e,t=!0){if(!i)return;const n=i;if(pa(i,t),!e){console.warn("Can not send destroy: No networking connection provided",i.guid);return}if(!e.isConnected){console.warn("Can not send destroy: not connected",i.guid);return}let r=i.guid;if(!r&&n.uuid&&(r=n.uuid),!r){console.warn("Can not send destroy: failed to find guid",i);return}const s=new uF(r);e.send("instance-destroyed",s,la.Queued)}function dF(i,e){const t=new uF(i);e.send("instance-destroyed",t,la.Queued)}function pF(i){i.connection.beginListen("instance-destroyed",e=>{m_&&console.log("[Remote] Destroyed",i.scene,e);const t=Xg(e.guid,i.scene);t&&pa(t)})}class See{constructor(e,t,n){h(this,"filename"),h(this,"hash"),h(this,"size"),this.filename=e,this.hash=t,this.size=n}}class fF{constructor(e,t){h(this,"guid"),h(this,"originalGuid"),h(this,"seed"),h(this,"visible"),h(this,"hostData"),h(this,"dontSave"),h(this,"parent"),h(this,"position"),h(this,"rotation"),h(this,"scale"),h(this,"preventCreation"),this.originalGuid=e,this.guid=t}}function $M(i,e,t,n){var r;const s=i;if(!s.guid)return console.warn("Can not instantiate: No guid",s),null;if(e.context||(e.context=Lt.Current),!e.context)return console.error("Missing network instantiate options / reference to network connection in sync instantiate"),null;const o=e?{...e}:null,{instance:a,seed:l}=Cee(s,e);if(a){const c=a;if(c.guid){m_&&console.log("[Local] new instance","gameobject:",a?.guid);const u=new fF(s.guid,c.guid);u.seed=l,o&&(o.position&&(u.position={x:o.position.x,y:o.position.y,z:o.position.z}),o.rotation&&(u.rotation={x:o.rotation.x,y:o.rotation.y,z:o.rotation.z,w:o.rotation.w}),o.scale&&(u.scale={x:o.scale.x,y:o.scale.y,z:o.scale.z})),u.position||(u.position={x:c.position.x,y:c.position.y,z:c.position.z}),u.rotation||(u.rotation={x:c.quaternion.x,y:c.quaternion.y,z:c.quaternion.z,w:c.quaternion.w}),u.scale||(u.scale={x:c.scale.x,y:c.scale.y,z:c.scale.z}),u.visible=s.visible,o!=null&&o.parent&&(typeof o.parent=="string"?u.parent=o.parent:u.parent=o.parent.guid),u.hostData=t,n===!1&&(u.dontSave=!0),(r=e?.context)==null||r.connection.send("new-instance-created",u)}else console.warn("Missing guid, can not send new instance event",c)}return a}function v_(){return Math.random()*9999999}function mF(i){i.connection.beginListen("new-instance-created",async e=>{const t=await Eee(e.originalGuid,i.scene);if(e.preventCreation===!0)return;if(!t){console.warn("could not find object that was instantiated: "+e.guid);return}const n=new Sa;e.position&&(n.position=new S(e.position.x,e.position.y,e.position.z)),e.rotation&&(n.rotation=new Me(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w)),e.scale&&(n.scale=new S(e.scale.x,e.scale.y,e.scale.z)),n.parent=e.parent,e.seed&&(n.idProvider=new or(e.seed)),n.visible=e.visible,n.context=i,m_&&i.alias&&console.log("[Remote] instantiate in: "+i.alias);const r=Gp(t,n);r&&(e.parent==="scene"&&i.scene.add(r),m_&&console.log("[Remote] new instance","gameobject:",r?.guid,t))})}function Cee(i,e){const t=v_(),n=e??new Sa;n.idProvider=new or(t);const r=Gp(i,n);return{seed:t,instance:r}}const gF={};function vF(i,e){gF[i]=e}async function Eee(i,e){const t=gF[i];if(t!=null){const n=await t(i);if(n)return n}return AF(i,e)}function AF(i,e){if(e===null||!i)return null;if(e.guid===i)return e;if(e.children)for(const t of e.children){const n=AF(i,t);if(n)return n}return null}const A_=ee("debuggetcomponent"),y_=ee("debuginstantiate");var yF=(i=>(i[i.None=0]="None",i[i.HideInHierarchy=1]="HideInHierarchy",i[i.HideInInspector=2]="HideInInspector",i[i.DontSaveInEditor=4]="DontSaveInEditor",i[i.NotEditable=8]="NotEditable",i[i.DontSaveInBuild=16]="DontSaveInBuild",i[i.DontUnloadUnusedAsset=32]="DontUnloadUnusedAsset",i[i.DontSave=52]="DontSave",i[i.HideAndDontSave=61]="HideAndDontSave",i))(yF||{});class Sa{constructor(){h(this,"idProvider"),h(this,"parent"),h(this,"keepWorldPosition"),h(this,"position"),h(this,"rotation"),h(this,"scale"),h(this,"visible"),h(this,"context")}clone(){var e,t,n;const r=new Sa;return r.idProvider=this.idProvider,r.parent=this.parent,r.keepWorldPosition=this.keepWorldPosition,r.position=(e=this.position)==null?void 0:e.clone(),r.rotation=(t=this.rotation)==null?void 0:t.clone(),r.scale=(n=this.scale)==null?void 0:n.clone(),r}cloneAssign(e){var t,n,r;this.idProvider=e.idProvider,this.parent=e.parent,this.keepWorldPosition=e.keepWorldPosition,this.position=(t=e.position)==null?void 0:t.clone(),this.rotation=(n=e.rotation)==null?void 0:n.clone(),this.scale=(r=e.scale)==null?void 0:r.clone()}}function jp(i){return i.visible}function qg(i,e){return typeof e=="number"&&(e=e>.5),i.visible=e,i.visible}function bF(i){return i[Nl]||b_(i)}function _F(i,e){i[rL]=e}function b_(i){return qo.isUsingInstancing(i)}function Xg(i,e){return xp(i,e,!0,!0)}const xF=Symbol("isDestroyed");function zu(i){return i[xF]}function wF(i,e){i[xF]=e}const eT=Symbol("isDontDestroy");function tT(i,e=!0){i[eT]=e}const __=[],x_=[];function pa(i,e=!0,t=!1){__.length=0,x_.length=0,iT(i,e,!0);for(const n of __)n.gameObject=null,n.context=null;for(const n of x_)wF(n,!0),t&&Ii(n),tL(n);x_.length=0,__.length=0}function iT(i,e=!0,t=!0){var n;if(i==null)return;const r=i;if(r.isComponent){if(r[eT])return;__.push(r);const a=r.gameObject;r.__internalDisable(),r.__internalDestroy(),r.gameObject=a;return}if(i[eT])return;const s=i;A_&&console.log(s),x_.push(s);const o=(n=s.userData)==null?void 0:n.components;if(o!=null&&Array.isArray(o)){let a=o.length;for(let l=0;l<o.length;l++){const c=o[l];iT(c,e,!1),o.length<a&&(a=o.length,l--)}}if(e&&s.children)for(const a of s.children)iT(a,e,!1);t&&s.removeFromParent()}function ju(i,e,t=!0){return SF(i,e,t)}function*nT(i,e,t=!1,n=999,r=0){if(i!=null&&i.userData.components&&!(r>n)){for(const s of i.userData.components)e&&s?.isComponent===!0&&s instanceof e?yield s:yield s;if(t===!0)for(const s of i.children)yield*nT(s,e,!0,n,r+1)}}function SF(i,e,t,n=0){var r;if(i){if(i.isObject3D,n>1e3){console.warn("Failed to iterate components: too many levels");return}if((r=i.userData)!=null&&r.components)for(let s=0;s<i.userData.components.length;s++){const o=i.userData.components[s];if(o?.isComponent===!0){const a=e(o);if(a!==void 0)return a}}if(t&&i.children){const s=n+1;for(let o=0;o<i.children.length;o++){const a=i.children[o];if(!a)continue;const l=SF(a,e,t,s);if(l!==void 0)return l}}}}function Gp(i,e=null){let t=null;e!==null&&(e.x!==void 0?(t=new Sa,t.position=e):t=e);let n=Lt.Current;t!=null&&t.context&&(n=t.context),A_&&n.alias&&console.log("context",n.alias),t&&!t.idProvider&&(t.idProvider=new or(Date.now()));const r=[],s={},o={},a=CF(n,i,t,r,s,o);a&&(Tee(s),Mee(o,s)),A_&&(cb(i,!0),cb(a,!0));const l={};for(const c in r){const u=r[c],d=u.guid;t&&t.idProvider&&(u.guid=t.idProvider.generateUUID(),l[d]=u.guid,A_&&console.log(u.name,u.guid)),f_(u,n),u.__internalNewInstanceCreated&&u.__internalNewInstanceCreated()}for(const c in r){const u=r[c];u.resolveGuids&&u.resolveGuids(l),u.enabled!==!1&&(u.enabled=!0)}return xb(n),a}function CF(i,e,t,n,r,s){var o;if(!e)return null;const a=e.userData;e.userData={};const l=e.children;e.children=[];const c=e.clone(!1);if(w_(c),e.userData=a,e.children=l,r[e.uuid]={original:e,clone:c},y_&&console.log("ADD",e,c),e.type==="SkinnedMesh"&&(s[e.uuid]={original:e,clone:c}),t?.visible!==void 0&&(c.visible=t.visible),t!=null&&t.idProvider){c.uuid=t.idProvider.generateUUID();const d=c;d&&(d.guid=c.uuid)}e.animations&&e.animations.length>0&&(c.animations=[...e.animations]);const u=e.parent;if(u&&u.add(c),t!=null&&t.position?Qr(c,t.position):c.position.copy(e.position),t!=null&&t.rotation?So(c,t.rotation):c.quaternion.copy(e.quaternion),t!=null&&t.scale?c.scale.copy(t.scale):c.scale.copy(e.scale),t!=null&&t.parent&&t.parent!=="scene"){let d=null;if(typeof t.parent=="string"?d=xp(t.parent,i.scene,!0):d=t.parent,d){const p=t.keepWorldPosition===!0?d.attach:d.add;p?p.call(d,c):console.error("Invalid parent object",d,"received when instantiating:",e)}else console.warn("could not find parent:",t.parent)}for(const[d,p]of Object.entries(e.userData))d!=="components"&&(c.userData[d]=p);if((o=e.userData)!=null&&o.components){const d=e.userData.components,p=[];c.userData.components=p;for(let f=0;f<d.length;f++){const m=d[f],A=new m.constructor;Bp(A,m),m[gg]!==void 0&&(A[gg]=m[gg]),p.push(A),A.gameObject=c,n.push(A),mg.dispatchComponentLifecycleEvent(fg.Added,A)}}t&&(t.position=void 0,t.rotation=void 0,t.scale=void 0,t.parent=void 0);for(const d in e.children){const p=e.children[d],f=CF(i,p,t,n,r,s);f&&c.add(f)}return c}function Mee(i,e){for(const t in i){const n=i[t],r=n.original,s=r.skeleton,o=n.clone;if(!s){console.warn("Skinned mesh has no skeleton?",n);continue}const a=s.bones,l=o.skeleton.clone();o.skeleton=l,o.bindMatrix.clone().copy(r.bindMatrix),o.bindMatrixInverse.copy(r.bindMatrixInverse);const c=[];l.bones=c;for(let u=0;u<a.length;u++){const d=a[u],p=e[d.uuid].clone;c.push(p)}}for(const t in i){const n=i[t].clone;n.skeleton.update(),n.bind(n.skeleton,n.bindMatrix),n.updateMatrixWorld(!0)}}function Tee(i){var e;for(const t in i){const n=i[t].clone;if((e=n.userData)!=null&&e.components)for(let r=0;r<n.userData.components.length;r++){const s=n.userData.components[r],o=Object.entries(s);for(const[a,l]of o)if(Array.isArray(l)){const c=[];s[a]=c;for(let u=0;u<l.length;u++){const d=l[u];if(typeof d!="object"){c.push(d);continue}const p=EF(s,a,d,i);p!==void 0?c.push(p):c.push(d)}}else if(typeof l=="object"){const c=EF(s,a,l,i);c!==void 0&&(s[a]=c)}}}}function EF(i,e,t,n){var r,s;if(t!=null)if(t.isComponent===!0){const o=t.gameObject;if(o){const a=o.uuid,l=(r=n[a])==null?void 0:r.clone;if(!l){y_&&console.log("reference did not change",e,i,t);return}const c=o.userData.components.indexOf(t);if(c>=0)return y_&&console.log(e,a),l.userData.components[c];console.warn("could not find component",e,t)}}else if(t.isObject3D===!0){if(e==="gameObject")return;const o=t;if(o){const a=o.uuid,l=(s=n[a])==null?void 0:s.clone;if(l)return y_&&console.log(e,"old",t,"new",l),l}}else{if(t.isVector4||t.isVector3||t.isVector2||t.isQuaternion||t.isEuler||t.isColor===!0)return t.clone();if(t.isEventList===!0)return new t.constructor}}const MF=new Map;function Iee(i,e){if(!i)return;if(!e){console.warn("No prototype found",i,i.prototype,i.constructor);return}const t=MF.get(e);t&&t.apply(i)}function Ree(i){const e=Pee(i.prototype);MF.set(i,e)}function Pee(i){return new Bee(i)}class Bee{constructor(e){h(this,"$symbol"),h(this,"extensions"),h(this,"descriptors"),this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(e),this.descriptors=new Array;for(let t=0;t<this.extensions.length;t++){const n=this.extensions[t],r=Object.getOwnPropertyDescriptor(e,n);r&&this.descriptors.push(r)}}apply(e){if(!e[this.$symbol]){e[this.$symbol]=!0;for(let t=0;t<this.extensions.length;t++){const n=this.extensions[t],r=this.descriptors[t];r&&Object.defineProperty(e,n,r)}}}}function w_(i){i&&i.isObject3D===!0&&Iee(i,ge)}ge.prototype.SetActive=function(i){this.visible=i},ge.prototype.setActive=function(i){this.visible=i},ge.prototype.destroy=function(){pa(this)},ge.prototype.addComponent=function(i,e){return Gu(this,i,e)},ge.prototype.addNewComponent=function(i,e){return Gu(this,i,e)},ge.prototype.removeComponent=function(i){return rT(this,i)},ge.prototype.getOrAddComponent=function(i,e){return Yg(this,i,e)},ge.prototype.getComponent=function(i){return Qu(this,i)},ge.prototype.getComponents=function(i,e){return Jg(this,i,e)},ge.prototype.getComponentInChildren=function(i){return Kg(this,i)},ge.prototype.getComponentsInChildren=function(i,e){return Zg(this,i,e)},ge.prototype.getComponentInParent=function(i){return $g(this,i)},ge.prototype.getComponentsInParent=function(i,e){return S_(this,i,e)},Object.getOwnPropertyDescriptor(ge.prototype,"activeSelf")||Object.defineProperty(ge.prototype,"activeSelf",{get:function(){return jp(this)},set:function(i){qg(this,i)}}),Object.getOwnPropertyDescriptor(ge.prototype,"transform")||Object.defineProperty(ge.prototype,"transform",{get:function(){return this}}),Object.getOwnPropertyDescriptor(ge.prototype,"worldPosition")||Object.defineProperty(ge.prototype,"worldPosition",{get:function(){return this instanceof xE?Rt(this.object):Rt(this)},set:function(i){Qr(this,i)}}),Object.getOwnPropertyDescriptor(ge.prototype,"worldQuaternion")||Object.defineProperty(ge.prototype,"worldQuaternion",{get:function(){return this instanceof xE?xi(this.object):xi(this)},set:function(i){So(this,i)}}),Object.getOwnPropertyDescriptor(ge.prototype,"worldRotation")||Object.defineProperty(ge.prototype,"worldRotation",{get:function(){return rg(this)},set:function(i){vE(this,i)}}),Object.getOwnPropertyDescriptor(ge.prototype,"worldScale")||Object.defineProperty(ge.prototype,"worldScale",{get:function(){return ki(this)},set:function(i){ng(this,i)}}),Object.getOwnPropertyDescriptor(ge.prototype,"worldForward")||Object.defineProperty(ge.prototype,"worldForward",{get:function(){return Zi().set(0,0,1).applyQuaternion(xi(this))}}),Object.getOwnPropertyDescriptor(ge.prototype,"worldRight")||Object.defineProperty(ge.prototype,"worldRight",{get:function(){return Zi().set(1,0,0).applyQuaternion(xi(this))}}),Object.getOwnPropertyDescriptor(ge.prototype,"worldUp")||Object.defineProperty(ge.prototype,"worldUp",{get:function(){return Zi().set(0,1,0).applyQuaternion(xi(this))}}),Ree(ge);const Dee=ee("debuggetcomponent"),TF=()=>Dee||globalThis.NEEDLE_DEBUG_GETCOMPONENT===!0;function Oee(i){return i==null||i.isObject3D?i:i.object&&i.object.isObject3D?i.object:i}function rT(i,e){if(!i||!i.userData.components)return e;const t=i.userData.components.indexOf(e);return t<0||(mg.dispatchComponentLifecycleEvent(fg.Removing,e),e.gameObject=null,i.userData.components.splice(t,1)),e}function Yg(i,e,t){return Qu(i,e)||Gu(i,e,t)}const IF=new or("addComponentIdProvider");function nh(i,e,t=!0){i.userData||(i.userData={}),i.userData.components||(i.userData.components=[]),i.userData.components.push(e),e.gameObject=i,(e.guid===void 0||e.guid==="invalid")&&(e.guid=IF.generateUUID()),w_(i),f_(e);try{t&&e.__internalAwake&&(yg(i),e.activeAndEnabled&&e.__internalAwake()),mg.dispatchComponentLifecycleEvent(fg.Added,e)}catch(n){console.error(n)}return e}function Gu(i,e,t,n){if(typeof e=="function"){const r=new e;t&&r.__internalNewInstanceCreated(t);let s=!0;return n?.callAwake!=null&&(s=n.callAwake),nh(i,r,s)}if(e.destroyed)return console.warn("Can not move/add a destroyed component",e),e;if(e.gameObject===i)return e;if(e.gameObject&&e.gameObject.userData.components){const r=e.gameObject.userData.components.indexOf(e);e.gameObject.userData.components.splice(r,1)}if(!i.userData.components)i.userData.components=[];else if(i.userData.components.includes(e))return e;return i.userData.components.push(e),e.gameObject=i,(e.guid===void 0||e.guid==="invalid")&&(e.guid=IF.generateUUID()),t&&e._internalInit(t),f_(e),e}function RF(i){if(i.gameObject&&i.gameObject.userData.components){const e=i.gameObject.userData.components.indexOf(i);i.gameObject.userData.components.splice(e,1)}i.__internalDisable&&i.__internalDisable(),zl(i,i.context??Lt.Current),i.destroy(),i.gameObject=null}let PF=!1;function BF(i,e,t){var n;if(i==null)return null;if(!i.isObject3D)return console.error("Object is not object3D"),null;if(!((n=i?.userData)!=null&&n.components)||(typeof e=="string"&&(PF||(PF=!0,console.warn(`Accessing components by name is not supported.
5259
5259
  Please use the component type instead. This may keep working in local development but it will fail when bundling your application.
5260
5260
 
5261
5261
  You can import other modules your main module to get access to types
@@ -5478,7 +5478,7 @@ Could not find method ${u.method} on object ${p.name}. Please rename ${u.method}
5478
5478
  in script: `,p),Qi("EventList methods must start with lowercase letter, see console for details");return}else console.warn(`EventList method:
5479
5479
  Could not find method ${u.method} on object ${p.name}`,p,typeof p[u.method])};if(typeof p[u.method]!="function"){let y=!1,b=p;for(;b;){const _=Object.getOwnPropertyDescriptor(b,u.method);if(_&&(_.writable===!0||_.set)){y=!0;break}b=Object.getPrototypeOf(b)}!y&&(pt()||mr)&&g()}}let m=u.argument;m!==void 0?m=d(m):u.arguments!==void 0&&(m=u.arguments.map(d));const A=f?this.createEventMethod(p,u.method,m):void 0,v=new nf(A,u.enabled);if(v.method||(v[Eie]=(o=t.object)==null?void 0:o.name),!p||!v.method){const g=t.object?"Current object: "+t.object.name+", "+t.object.guid:null;p?console.warn('EventList method not found: "'+u.method+'" on',p):console.warn("EventList is missing target - will be ignored",u.target,g,e)}else a.push(v)}const l=new Hn(a);mr&&console.log(l);const c=t.target;return c!==void 0&&t.path!==void 0&&l.setEventTarget(t.path,c),l}}createEventMethod(e,t,n){return(...r)=>{const s=e[t];typeof s=="function"?n!==void 0?Array.isArray(n)?s?.call(e,...n):s?.call(e,n):s?.call(e,...r):e[t]=n}}}const Tie=new Mie;class XN extends Fa{constructor(){super([ef,Ht])}onSerialize(e,t){}onDeserialize(e,t){if(e instanceof gt&&t.type===ef){const n=e,r=new ef(n.image.width,n.image.height,{colorSpace:pi});return r.texture=n,n.isRenderTargetTexture=!0,n.flipY=!0,n.offset.y=1,n.repeat.y=-1,n.needsUpdate=!0,n.mipmaps=[],n instanceof Ra&&(n.isCompressedTexture=!1,n.format=RGBAFormat),r}}}new XN;class YN extends Fa{constructor(){super([URL])}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"&&e.length>0)return kl(t.gltfId,e)}}new YN;var Iie=Object.defineProperty,Rie=Object.getOwnPropertyDescriptor,Pie=(i,e,t,n)=>{for(var r=n>1?void 0:n?Rie(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&Iie(e,t,r),r};class pv extends Ie{awake(){Lo.createIfNoneExists(this.context)}onEnable(){var e;(e=Lo.get(this.context))==null||e.register(this)}onDisable(){var e;(e=Lo.get(this.context))==null||e.unregister(this)}}class Ys extends pv{constructor(){super(...arguments),h(this,"targets",null),h(this,"raycastHits",[]),h(this,"ignoreSkinnedMeshes",!1)}start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??(e=new To),e.targets=this.targets,e.results=this.raycastHits;const t=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=r=>r instanceof Ao?"continue in children":t?t(r):!0);const n=this.context.physics.raycast(e);return e.testObject=t,n}}Pie([x()],Ys.prototype,"ignoreSkinnedMeshes",2);class k_ extends Ys{constructor(){super(),this.ignoreSkinnedMeshes=!0}}class fv extends pv{performRaycast(e){if(!mt.active||!(e!=null&&e.ray))return null;const t=e.ray.origin,n=.01;return this.context.physics.sphereOverlap(t,n)}}class L_{static getObject(e){const t=e[ko];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(t&&(t.canvasGroup=void 0,t.graphic=void 0),e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;const n=this.tryFindCanvasGroup(e);if(n?.isCanvasGroup===!0&&(t&&(t.canvasGroup=n),n.blocksRaycasts===!1||n.interactable===!1))return!1;const r=ju(e,s=>{if(s.isGraphic===!0)return s},!1);return t&&r?.isGraphic===!0&&(t.graphic=r),!(r?.raycastTarget===!1||r?.layer===2)}static tryFindCanvasGroup(e){if(!e)return null;const t=ju(e,n=>{const r=n;if(r.blocksRaycasts!==void 0&&r.interactable!==void 0)return r},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}}function QT(i){return i[ko]||(i.parent?QT(i.parent):null)}function Bie(i){return i.isUI===!0||typeof i[ko]=="object"}function U_(i,e){if(!i)return;const t=i.material;if(t?.isMaterial===!0){const n=i.parent;n&&n.isText,t.side=e.doubleSided??!0?hi:lr,t.shadowSide=e.doubleSided?hi:lr,i.castShadow=e.castShadows?e.castShadows:!1,i.receiveShadow=e.receiveShadows?e.receiveShadows:!1}for(const n of i.children)U_(n,e)}function rf(i,e,t){i[e]===void 0&&console.warn("Field",e,"is undefined on",i);const n=Proxy.revocable(i[e],{set(o,a,l,c){const u=o[a],d=Reflect.set(o,a,l,c);return t(l,u),d}}),r=n.revoke,s=i[e];return n.revoke=()=>{i[e]=s,r()},i[e]=n.proxy,n}const JN=Symbol("Scheduled action");function Die(i,e,t=Pn.OnBeforeRender){let n=i[JN];n||(n=i[JN]={});const r=e.name;n[t]||(n[t]={});const s=n[t];if(s[r])return;function*o(){e?.call(i),s[r]=null}const a=i.startCoroutine(o(),t);s[r]=a}const Zl=ee("debugeventsystem");var HT=(i=>(i.BeforeHandleInput="BeforeHandleInput",i.AfterHandleInput="AfterHandleInput",i))(HT||{});const $l=class extends Ie{constructor(){super(),h(this,"raycaster",[]),h(this,"_handleInputFn"),h(this,"pressedByID",new Map),h(this,"hoveredByID",new Map),h(this,"_sortedHits",[]),h(this,"_testObjectsCache",new Map),h(this,"_currentlyActiveRaycaster",null),h(this,"_currentPointerEventName",null),h(this,"shouldRaycastObject",i=>{var e;let t=null;if(Bie(i)&&(t=(e=i[ko])==null?void 0:e.gameObject),this._testObjectsCache.has(i)||t&&this._testObjectsCache.has(t))return this._testObjectsCache.get(i)===!1?"continue in children":!0;{let n=GT(i,this._currentPointerEventName);if(!n&&t&&(n=GT(t,this._currentPointerEventName)),n){this._testObjectsCache.set(i,!0);for(const r of i.children)this.shouldRaycastObject_AddToYesCache(r);return!0}return this._testObjectsCache.set(i,!1),"continue in children"}}),h(this,"_sortingBuffer",[]),h(this,"_noDepthTestingResults",[]),h(this,"out",{}),h(this,"_capturedPointer",{}),h(this,"pointerEnterSymbol",Symbol("pointerEnter")),h(this,"pointerExitSymbol",Symbol("pointerExit")),h(this,"currentActiveMeshUIComponents",[]),$l.systems.push(this)}static createIfNoneExists(i){this.didSearchEventSystem||(this.didSearchEventSystem=!0,$l.systems.length<=0&&$l.systems.push(...re.findObjectsOfType($l,i)));for(const t of $l.systems)if(t.context===i)return;const e=new ge;re.addNewComponent(e,$l),i.scene.add(e)}static get systems(){const i=Lt.Current;return this._eventSystemMap.has(i)||this._eventSystemMap.set(i,[]),this._eventSystemMap.get(i)}static get(i){const e=this._eventSystemMap.get(i);return e&&e.length>0?e[0]:null}static get instance(){return this.systems[0]}static ensureUpdateMeshUI(i,e,t=!1){dh.update(i,e,t)}static markUIDirty(i){dh.markDirty()}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}onDestroy(){$l.systems.splice($l.systems.indexOf(this),1)}start(){if(this.raycaster.length<=0&&!re.findObjectOfType(pv,this.context)){const i=re.addNewComponent(this.context.scene,Ys);this.raycaster.push(i),(pt()||Zl)&&console.warn("Added an ObjectRaycaster to the scene because no raycaster was found.")}}register(i){var e;i&&this.raycaster&&!this.raycaster.includes(i)&&((e=this.raycaster)==null||e.push(i))}unregister(i){var e,t;const n=(e=this.raycaster)==null?void 0:e.indexOf(i);n!==void 0&&n!==-1&&((t=this.raycaster)==null||t.splice(n,1))}onEnable(){this._handleInputFn??(this._handleInputFn=this.onPointerEvent.bind(this)),this.context.input.addEventListener(Wi.PointerDown,this._handleInputFn),this.context.input.addEventListener(Wi.PointerUp,this._handleInputFn),this.context.input.addEventListener(Wi.PointerMove,this._handleInputFn)}onDisable(){this.context.input.removeEventListener(Wi.PointerDown,this._handleInputFn),this.context.input.removeEventListener(Wi.PointerUp,this._handleInputFn),this.context.input.removeEventListener(Wi.PointerMove,this._handleInputFn)}onBeforeRender(){this.resetMeshUIStates()}onPointerEvent(i){if(i===void 0||i.propagationStopped)return;const e=new em(this.context.input,i);this._currentPointerEventName=i.type,e.inputSource=this.context.input,e.isClick=i.isClick,e.isDoubleClick=i.isDoubleClick,e.isDown=i.type==Wi.PointerDown,e.isUp=i.type==Wi.PointerUp,e.isPressed=this.context.input.getPointerPressed(i.pointerId),Zl&&(e.isDown?console.log("DOWN",e.pointerId):e.isUp&&console.log("UP",e.pointerId),e.isClick&&console.log("CLICK",e.pointerId));const t=new To;i.hasRay?t.ray=i.ray:t.screenPoint=this.context.input.getPointerPositionRC(i.pointerId);const n=this.performRaycast(t);if(n)for(const s of n)s.event=i,i.intersections.push(s);Zl&&e.isClick&&$i("EventSystem: "+e.pointerId+" - "+this.context.time.frame+" - Up:"+e.isUp+", Down:"+e.isDown);const r={sender:this,args:e,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:r})),this.handleIntersections(n,e),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:r}))}shouldRaycastObject_AddToYesCache(i){this._testObjectsCache.set(i,!0);for(const e of i.children)this.shouldRaycastObject_AddToYesCache(e)}performRaycast(i){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,i||(i=new To),i.testObject=this.shouldRaycastObject;for(const e of this.raycaster){if(!e.activeAndEnabled)continue;this._currentlyActiveRaycaster=e;const t=e.performRaycast(i);this._currentlyActiveRaycaster=null,t&&t.length>0&&this._sortedHits.push(...t)}return this._sortedHits.sort((e,t)=>e.distance-t.distance),this._sortedHits}assignHitInformation(i,e){e?(i.intersection=e,i.point=e.point,i.normal=e.normal,i.face=e.face,i.distance=e.distance,i.instanceId=e.instanceId):(i.intersection=void 0,i.point=void 0,i.normal=void 0,i.face=void 0,i.distance=void 0,i.instanceId=void 0)}handleIntersections(i,e){var t;if(i!=null&&i.length){i=this.sortCandidates(i);for(const r of i){if(e.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(e,r),this.handleEventOnObject(r.object,e))return!0}}this.assignHitInformation(e,i?.[0]),this.invokePointerCapture(e);const n=this.hoveredByID.get(e.pointerId);return n&&this.propagatePointerExit(n.obj,n.data,null),this.hoveredByID.delete(e.pointerId),e.isUp&&((t=this.pressedByID.get(e.pointerId))==null||t.handlers.forEach(r=>this.invokeOnPointerUp(e,r)),this.pressedByID.delete(e.pointerId)),!1}sortCandidates(i){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let e=0;e<i.length;e++){const t=i[e],n=t.object;if(n.material&&n.material.depthTest===!1){this._noDepthTestingResults.push(t);continue}this._sortingBuffer.push(t)}for(const e of this._sortingBuffer)this._noDepthTestingResults.push(e);return this._noDepthTestingResults}handleEventOnObject(i,e){if(!this.testIsVisible(i))return e.isClick&&Zl&&console.log("not allowed",i),!1;if(e.pointerId===void 0)return Zl&&console.error("Event without pointer can't be handled",e),!1;e.object=i;const t=i.parent,n=e.isClick??!1;let r=null;if(t&&t.isUI){const l=(e.isPressed||e.isClick)??!1;if(t[ko]){const c=t[ko].gameObject;if(c){if(!L_.isInteractable(c,this.out))return!1;r=this.out.canvasGroup??null,this.handleMeshUIIntersection(i,l),i=c}}}n&&Zl&&console.log(this.context.time.frame,i);const s=this.hoveredByID.get(e.pointerId),o=s?.obj;o!==i&&o&&this.propagatePointerExit(o,s.data,i);const a=this.hoveredByID.get(e.pointerId);if(a?(a.obj=i,a.data=e):this.hoveredByID.set(e.pointerId,{obj:i,data:e}),e.isDown){const l=this.pressedByID.get(e.pointerId);l?(l.obj=i,l.data=e):this.pressedByID.set(e.pointerId,{obj:i,data:e,handlers:new Set})}return(r===null||r.interactable)&&this.handleMainInteraction(i,e,o??null),!0}propagate(i,e){for(;i;)re.foreachComponent(i,t=>{e(t)},!1),i=i.parent}handleMainInteraction(i,e,t){const n=this.pressedByID.get(e.pointerId),r=t!==i;let s=!0;switch(e.event.pointerType){case"mouse":case"touch":const o=this.context.input.getPointerPositionLastFrame(e.pointerId),a=this.context.input.getPointerPosition(e.pointerId);s=o&&!Ze.approximately(o,a);break}this.propagate(i,o=>{var a;const l=o;l.interactable!==!1&&(!l.activeAndEnabled||!l.enabled||(l.onPointerEnter&&r&&this.handlePointerEnter(l,e),e.isDown&&l.onPointerDown&&(l.onPointerDown(e),n?.handlers.add(l),this.handlePointerCapture(e,l)),l.onPointerMove&&(s&&l.onPointerMove(e),this.handlePointerCapture(e,l)),e.isUp&&(l.onPointerUp&&(this.invokeOnPointerUp(e,l),n?.handlers.delete(l)),l.onPointerExit&&((a=e.event)==null?void 0:a.pointerType)===Ub.Touch&&(this.handlePointerExit(l,e),this.hoveredByID.delete(e.pointerId))),e.isClick&&l.onPointerClick&&l.onPointerClick(e)))}),e.isUp&&(n?.handlers.forEach(o=>{this.invokeOnPointerUp(e,o)}),this.pressedByID.delete(e.pointerId))}propagatePointerExit(i,e,t){this.propagate(i,n=>{if(!n.gameObject||n.destroyed)return;const r=n;if(r.onPointerExit){if(t&&this.isChild(t,n.gameObject))return;this.handlePointerExit(r,e)}})}invokeOnPointerUp(i,e){var t;(t=e.onPointerUp)==null||t.call(e,i),this.releasePointerCapture(i,e)}handlePointerEnter(i,e){i.onPointerEnter&&this.updatePointerState(i,e.pointerId,this.pointerEnterSymbol,!0)&&i.onPointerEnter(e),this.updatePointerState(i,e.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(i,e){i.onPointerExit&&this.updatePointerState(i,e.pointerId,this.pointerExitSymbol,!0)&&i.onPointerExit(e),this.updatePointerState(i,e.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(i,e,t,n){let r=i[t];if(n)return r&&r.includes(e)?!1:(r=r||[],r.push(e),i[t]=r,!0);{if(!r||!r.includes(e))return!1;const s=r.indexOf(e);return s!==-1&&r.splice(s,1),!0}}handlePointerCapture(i,e){if(i.z__pointer_ctured){i.z__pointer_ctured=!1;const t=i.pointerId;if(e.onPointerMove){const n=this._capturedPointer[t]||[];n.push(e),this._capturedPointer[t]=n}else pt()&&!e.z__warned_no_pointermove&&(e.z__warned_no_pointermove=!0,console.warn("PointerCapture was requested but the component doesn't implement onPointerMove. It will not receive any pointer events"))}else i.z__pointer_cture_rleased&&(i.z__pointer_cture_rleased=!1,this.releasePointerCapture(i,e))}releasePointerCapture(i,e){const t=i.pointerId;if(this._capturedPointer[t]){const n=this._capturedPointer[t].indexOf(e);n!==-1&&(this._capturedPointer[t].splice(n,1),Zl&&console.log("released pointer capture",t,e,this._capturedPointer))}}invokePointerCapture(i){var e;if(i.event.type===Wi.PointerMove){const t=i.pointerId,n=this._capturedPointer[t];if(n){Zl&&console.log("Captured",t,n);for(let r=0;r<n.length;r++){const s=n[r];if(s.destroyed){n.splice(r,1),r--;continue}(e=s.onPointerMove)==null||e.call(s,i)}}}}isChild(i,e){return!i||!e?!1:i===e?!0:i.parent?this.isChild(i.parent,e):!1}handleMeshUiObjectWithoutShadowDom(i,e){return!i||!i.isUI?!0:this.handleMeshUIIntersection(i,e)}handleMeshUIIntersection(i,e){const t=dh.updateState(i,e);return t&&this.currentActiveMeshUIComponents.push(t),t!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&dh.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let i=0;i<this.currentActiveMeshUIComponents.length;i++){const e=this.currentActiveMeshUIComponents[i];dh.resetState(e)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(i){return i?re.isActiveSelf(i)?this.testIsVisible(i.parent):!1:!0}};let Lo=$l;h(Lo,"_eventSystemMap",new Map),h(Lo,"didSearchEventSystem",!1);class dh{static markDirty(){this.needsUpdate=!0}static update(e,t,n=!1){if(n){e.update();return}const r=t.time.frameCount;for(const s of this.lastUpdateFrame)if(s.context===t){if(r===s.frame)return;s.frame=r;let o=this.needsUpdate||r<1;s.nextUpdate===t.time.frameCount&&(o=!0),o&&(Zl&&console.log("Update threemeshui"),this.needsUpdate=!1,e.update());return}this.lastUpdateFrame=[{context:t,frame:r,nextUpdate:r}],e.update()}static updateState(e,t){let n=null;if(e&&(n=this.findBlockInParent(e),n&&n!==this.lastSelected)){if(n.interactable===!1)return null;this.needsUpdate=!0}return n}static resetLastSelected(){const e=this.lastSelected;e&&(this.lastSelected=null,this.resetState(e))}static resetState(e){e&&(this.needsUpdate=!0)}static findBlockInParent(e){return e?e.isBlock?e:this.findBlockInParent(e.parent):null}}h(dh,"lastSelected",null),h(dh,"lastUpdateFrame",[]),h(dh,"needsUpdate",!1);var Oie=Object.defineProperty,kie=Object.getOwnPropertyDescriptor,pn=(i,e,t,n)=>{for(var r=n>1?void 0:n?kie(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&Oie(e,t,r),r};const Lie=ee("debugorbit"),F_=ee("freecam"),mv=ee("debugcamerafit"),N_=ee("smoothcam"),Uie={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let VT;class gv extends CustomEvent{constructor(e,t){super("target-reached",{detail:{controls:e,type:t}})}}class bi extends Ie{constructor(){super(...arguments),h(this,"autoTarget",!0),h(this,"autoFit",!1),h(this,"enableRotate",!0),h(this,"autoRotate",!1),h(this,"autoRotateSpeed",1),h(this,"minAzimuthAngle",1/0),h(this,"maxAzimuthAngle",1/0),h(this,"minPolarAngle",0),h(this,"maxPolarAngle",Math.PI),h(this,"enableKeys",!0),h(this,"enableDamping",!0),h(this,"dampingFactor",.1),h(this,"enableZoom",!0),h(this,"minZoom",0),h(this,"maxZoom",1/0),h(this,"enablePan",!0),h(this,"lookAtConstraint",null),h(this,"lookAtConstraint01",1),h(this,"allowInterrupt",!0),h(this,"middleClickToFocus",!0),h(this,"doubleClickToFocus",!0),h(this,"useSlerp",!0),h(this,"debugLog",!1),h(this,"targetLerpDuration",1),h(this,"_controls",null),h(this,"_cameraObject",null),h(this,"_lookTargetLerpActive",!1),h(this,"_lookTargetStartPosition",new S),h(this,"_lookTargetEndPosition",new S),h(this,"_lookTargetLerp01",0),h(this,"_lookTargetLerpDuration",0),h(this,"_cameraLerpActive",!1),h(this,"_cameraStartPosition",new S),h(this,"_cameraEndPosition",new S),h(this,"_cameraLerp01",0),h(this,"_cameraLerpDuration",0),h(this,"_inputs",0),h(this,"_enableTime",0),h(this,"_startedListeningToKeyEvents",!1),h(this,"_eventSystem"),h(this,"_afterHandleInputFn"),h(this,"_camera",null),h(this,"_syncedTransform"),h(this,"_didStart",!1),h(this,"_didSetTarget",!1),h(this,"targetElement",null),h(this,"onControlsChangeStarted",()=>{this._syncedTransform&&this._syncedTransform.requestOwnership()}),h(this,"_shouldDisable",!1),h(this,"_haveAttachedKeyboardEvents",!1)}get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){var t;(t=this.controls)==null||t.addEventListener("start",e)}get targetLerpSpeed(){return 5}set targetLerpSpeed(e){this.targetLerpDuration=1/e}awake(){this._didStart=!1,this._didSetTarget=!1,this._startedListeningToKeyEvents=!1}start(){this._didStart=!0,this._eventSystem=Lo.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(HT.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){var e,t;(e=this._controls)==null||e.dispose(),(t=this._eventSystem)==null||t.removeEventListener(HT.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._enableTime=this.context.time.time;const e=re.getComponent(this.gameObject,Ri);this._camera=e;let t=e?.cam;if(!t&&this.gameObject instanceof kt&&(t=this.gameObject),t&&GN(t,this,!0),!this._controls&&t instanceof kt){this._cameraObject=t;const n=this.targetElement??this.context.renderer.domElement,r=t?.quaternion.clone();this._controls=new oie(t,n),t?.quaternion.copy(r),VT===void 0&&(VT={...this._controls.keys})}this._controls&&(F_&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,ra()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),t?.type==="PerspectiveCamera"?F_||(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):F_||(this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom),this._startedListeningToKeyEvents||(this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(window.document.body))),this._syncedTransform=re.getComponent(this.gameObject,uh)??void 0}onDisable(){var e;(e=this._camera)!=null&&e.cam&&GN(this._camera.cam,this,!1),this._controls&&(this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted))}afterHandleInput(e){e.detail.args.pointerId===0&&(e.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!e.detail.args.isPressed||e.detail.args.isUp)&&(this._shouldDisable=!1))}onBeforeRender(){var e,t;if(!this._controls||this._cameraObject!==this.context.mainCamera)return;this.__handleSetTargetWhenBecomingActiveTheFirstTime(),(this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2)||this.context.input.mouseWheelChanged||this.context.input.getPointerPressed(0)&&(e=this.context.input.getPointerPositionDelta(0))!=null&&e.length()||0>.1)&&(this._inputs+=1),this._inputs>0&&this.allowInterrupt&&(this.enableRotate&&(this.autoRotate=!1),this._cameraLerpActive=!1,this._lookTargetLerpActive=!1),this._inputs=0;let n=this.middleClickToFocus&&this.context.input.getPointerClicked(1);if(n||(n=this.doubleClickToFocus&&this.context.input.getPointerDoubleClicked(0)&&this.context.time.time-this._enableTime>.3),n&&this.setTargetFromRaycast(),this._lookTargetLerpActive||this._cameraLerpActive){if(this._cameraLerpActive&&this._cameraObject)if(this._cameraLerp01+=this.context.time.deltaTime/this._cameraLerpDuration,this._cameraLerp01>=1)this._cameraObject.position.copy(this._cameraEndPosition),this._cameraLerpActive=!1,this.dispatchEvent(new gv(this,"camera"));else{const r=Ze.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,r)}if(this._lookTargetLerpActive)if(this._lookTargetLerp01+=this.context.time.deltaTime/this._lookTargetLerpDuration,this._lookTargetLerp01>=1)this._controls.target.copy(this._lookTargetEndPosition),this._lookTargetLerpActive=!1,this.dispatchEvent(new gv(this,"lookat"));else{const r=Ze.easeInOutCubic(this._lookTargetLerp01);this._controls.target.lerpVectors(this._lookTargetStartPosition,this._lookTargetEndPosition,r)}}if(this._controls){if(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!this._shouldDisable&&this._camera===this.context.mainCameraComponent&&!this.context.isInXR,this._controls.keys=this.enableKeys?VT:Uie,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,this._controls.enableDamping=this.enableDamping,this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._controls.enableRotate=this.enableRotate,this._controls.minAzimuthAngle=this.minAzimuthAngle,this._controls.maxAzimuthAngle=this.maxAzimuthAngle,this._controls.minPolarAngle=this.minPolarAngle,this._controls.maxPolarAngle=this.maxPolarAngle,typeof N_=="number"||N_===!0){this._controls.enableDamping=!0;const r=typeof N_=="number"?N_:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,r))}this.allowInterrupt||(this._lookTargetLerpActive&&(this._controls.enablePan=!1),this._cameraLerpActive&&(this._controls.enableRotate=!1,this._controls.autoRotate=!1),(this._lookTargetLerpActive||this._cameraLerpActive)&&(this._controls.enableZoom=!1)),this.context.isInXR||(!F_&&(t=this.lookAtConstraint)!=null&&t.locked&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(),Lie&&Ct.DrawWireSphere(this._controls.target,.1,65280))}}__handleSetTargetWhenBecomingActiveTheFirstTime(){if(!this._didSetTarget&&(this._didSetTarget=!0,this.autoTarget)){const e=re.getComponent(this.gameObject,Ri);if(e&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const t=Rt(e.cam).length(),n=new S(0,0,-t).applyMatrix4(e.cam.matrixWorld);this.setLookTargetPosition(n,!0)}if(!this.autoFit&&!this.setLookTargetFromConstraint()){const t=new To;t.screenPoint=new $(0,0),t.lineThreshold=.1;const n=this.context.physics.raycast(t);n.length>0&&this.setLookTargetPosition(n[0].point,!0),mv&&console.log("OrbitControls hits",...n)}this.autoFit&&this.fitCamera()}}setCameraAndLookTarget(e){if(!e||!(e instanceof ge))return;const t=Rt(e),n=fE(e);this.setTargetFromRaycast(new Ts(t,n)),this.setCameraTargetPosition(t)}setCameraTargetPosition(e,t=!1){var n,r;e&&(e instanceof ge&&(e=Rt(e)),this._cameraEndPosition||(this._cameraEndPosition=new S),this._cameraEndPosition.copy(e),t===!0?(this._cameraLerpActive=!1,(n=this.controllerObject)==null||n.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy((r=this._cameraObject)==null?void 0:r.position),typeof t=="number"?this._cameraLerpDuration=t:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setLookTargetPosition(e=null,t=!1){this._controls&&e&&(e instanceof ge&&(e=Rt(e)),this._lookTargetEndPosition.copy(e),t===!0?this._controls.target.copy(this._lookTargetEndPosition):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof t=="number"?this._lookTargetLerpDuration=t:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(e=0,t=1){var n;if(!this._controls)return!1;const r=(n=this.lookAtConstraint)==null?void 0:n.sources;if(r&&r.length>0){const s=r[e];if(s)return s.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._lookTargetEndPosition,t),!0}return!1}lerpTarget(e,t){return this.lerpLookTarget(e,t)}lerpLookTarget(e,t){this._controls&&(t>=1?this._controls.target.copy(e):this._controls.target.lerp(e,t))}setTargetFromRaycast(e){var t,n;if(!this.controls)return;const r=e?this.context.physics.raycastFromRay(e):this.context.physics.raycast();for(const s of r)if(s.distance>0&&re.isActiveInHierarchy(s.object)){const o=QT(s.object);if(o){const a=o.canvas;if(a!=null&&a.screenspace)break}if(this.setLookTargetPosition(s.point),this.context.mainCamera){const a=Rt(this.context.mainCamera).clone().sub(this.controls.target).add(this._lookTargetEndPosition);(n=(t=this._cameraObject)==null?void 0:t.parent)==null||n.worldToLocal(a),this.setCameraTargetPosition(a)}break}}fitCamera(e,t=1.1,n=!0){const r=this._cameraObject,s=this._controls;if(e!=null&&e.length||(e=this.context.scene.children),e.length<=0||!r||!s)return;const o=new S,a=new S,l=new gi;l.makeEmpty();const c=[];function u(y){let b=!0;if(y.visible&&lie(y)!==!1&&!(y.type==="TransformControlsGizmo"||y.type==="TransformControlsPlane")&&(y instanceof pC&&(b=!1),y instanceof Ny&&(b=!1),y instanceof jN&&(b=!1),y.material instanceof Ey&&(b=!1),y instanceof ue||(b=!1),y!==r&&y.isUI!==!0)){if(b){mv&&console.log(y.name,y.type,y);const _=y.children;y.children=c;const E=y.position,I=y.scale;if(Number.isNaN(E.x)||Number.isNaN(E.y)||Number.isNaN(E.z)){console.warn(`Object "${y.name}" has NaN values in position or scale.... will ignore it`,E,I);return}l.expandByObject(y,!0),y.children=_}for(const _ of y.children)u(_)}}for(const y of e)y.updateMatrixWorld(),u(y);if(r.updateMatrixWorld(),r.updateProjectionMatrix(),l.getCenter(a),l.applyMatrix4(r.matrixWorldInverse),l.getSize(o),l.setFromCenterAndSize(a,o),Number.isNaN(o.x)||Number.isNaN(o.y)||Number.isNaN(o.z)){console.warn("Camera fit size resultet in NaN",r,l,[...e]);return}if(o.length()<=1e-10){mv&&console.warn("Camera fit size is zero",l,[...e]);return}const d=r.fov,p=2*Math.atan(Math.tan(d*Math.PI/360/2)*r.aspect)/Math.PI*360,f=o.y/(2*Math.atan(Math.PI*d/360)),m=o.x/(2*Math.atan(Math.PI*p/360)),A=t*Math.max(f,m)+o.z/2;mv&&console.log("Fit camera to objects",f,m,"distance",A);const v=Rt(r),g=s.target.clone().sub(v).normalize().multiplyScalar(A);if(s.maxDistance=A*10,s.minDistance=A*.01,this.setLookTargetPosition(a,n),this.autoTarget=!1,r.near=A/1e3,r.far=A*100,r.updateMatrixWorld(),r.updateProjectionMatrix(),r.parent){const y=r.parent.worldToLocal(s.target.clone().sub(g));this.setCameraTargetPosition(y,n)}else console.error(`Can not fit camera ${r.name} because it has no parent`);if(mv){const y=new pC(l);this.context.scene.add(y),vE(y,rg(r)),this._haveAttachedKeyboardEvents||(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",b=>{b.code==="KeyF"&&this.fitCamera(e)}))}s.update()}}pn([x()],bi.prototype,"autoTarget",2),pn([x()],bi.prototype,"autoFit",2),pn([x()],bi.prototype,"enableRotate",2),pn([x()],bi.prototype,"autoRotate",2),pn([x()],bi.prototype,"autoRotateSpeed",2),pn([x()],bi.prototype,"minAzimuthAngle",2),pn([x()],bi.prototype,"maxAzimuthAngle",2),pn([x()],bi.prototype,"minPolarAngle",2),pn([x()],bi.prototype,"maxPolarAngle",2),pn([x()],bi.prototype,"enableKeys",2),pn([x()],bi.prototype,"enableDamping",2),pn([x()],bi.prototype,"dampingFactor",2),pn([x()],bi.prototype,"enableZoom",2),pn([x()],bi.prototype,"minZoom",2),pn([x()],bi.prototype,"maxZoom",2),pn([x()],bi.prototype,"enablePan",2),pn([x(cv)],bi.prototype,"lookAtConstraint",2),pn([x()],bi.prototype,"lookAtConstraint01",2),pn([x()],bi.prototype,"allowInterrupt",2),pn([x()],bi.prototype,"middleClickToFocus",2),pn([x()],bi.prototype,"doubleClickToFocus",2),pn([x()],bi.prototype,"targetLerpDuration",2);var Fie=Object.defineProperty,Nie=Object.getOwnPropertyDescriptor,Os=(i,e,t,n)=>{for(var r=n>1?void 0:n?Nie(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&Fie(e,t,r),r},Ju=(i=>(i[i.Skybox=1]="Skybox",i[i.SolidColor=2]="SolidColor",i[i.Uninitialized=4]="Uninitialized",i))(Ju||{});const ec=ee("debugcam"),KN=ee("debugscreenpointtoray");var z_;const vv=(z_=class extends Ie{constructor(){super(...arguments),h(this,"_nearClipPlane",.1),h(this,"_farClipPlane",1e3),h(this,"orthographic",!1),h(this,"orthographicSize",5),h(this,"ARBackgroundAlpha",0),h(this,"_cullingMask",4294967295),h(this,"_backgroundBlurriness",0),h(this,"_backgroundIntensity",1),h(this,"_environmentIntensity"),h(this,"_targetTexture",null),h(this,"_backgroundColor"),h(this,"_fov"),h(this,"_cam",null),h(this,"_clearFlags",2),h(this,"_skybox"),h(this,"_frustum"),h(this,"_projScreenMatrix",new Ce)}get isCamera(){return!0}get aspect(){return this._cam instanceof kt?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(i){this._cam instanceof kt&&this._cam.aspect!==i&&(this._cam.aspect=i,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof kt?this._cam.fov:this._fov}set fieldOfView(i){const e=this.fieldOfView!=i;if(this._fov=i,e&&this._cam&&this._cam instanceof kt){if(this._fov===void 0){console.warn("Can not set undefined fov on PerspectiveCamera");return}this._cam.fov=this._fov,this._cam.updateProjectionMatrix()}}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(i){const e=this._nearClipPlane!=i;this._nearClipPlane=i,this._cam&&e&&(this._cam.near=i,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(i){const e=this._farClipPlane!=i;this._farClipPlane=i,this._cam&&e&&(this._cam.far=i,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(i){i!==this._clearFlags&&(this._clearFlags=i,this.applyClearFlagsIfIsActiveCamera())}set cullingMask(i){this._cullingMask=i,this._cam&&(this._cam.layers.mask=i)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}set cullingLayer(i){this.cullingMask=(1<<i|0)>>>0}set backgroundBlurriness(i){i!==this._backgroundBlurriness&&(i===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(i,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}set backgroundIntensity(i){i!==this._backgroundIntensity&&(i===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(i,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}set environmentIntensity(i){this._environmentIntensity=i}get environmentIntensity(){return this._environmentIntensity}get backgroundColor(){return this._backgroundColor??null}set backgroundColor(i){if(i){if(this._backgroundColor)this._backgroundColor.copy(i);else{if(!i.clone)return;this._backgroundColor=i.clone()}i.alpha===void 0&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera()}}set targetTexture(i){this._targetTexture=i}get targetTexture(){return this._targetTexture}get cam(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(i,e,t){const n=this.cam,r=vv._origin;r.set(i,e,-1),this.context.input.convertScreenspaceToRaycastSpace(r),KN&&console.log("screenPointToRay",i.toFixed(2),e.toFixed(2),"now:",r.x.toFixed(2),r.y.toFixed(2),"isInXR:"+this.context.isInXR),r.z=-1,r.unproject(n);const s=vv._direction.set(r.x,r.y,r.z),o=Rt(n);return s.sub(o),s.normalize(),t?(t.set(o,s),t):new Ts(o.clone(),s.clone())}getFrustum(){return this._frustum||(this._frustum=new nu,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new nu),this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(i,e){return e&&this._projScreenMatrix.multiplyMatrices(this.cam.projectionMatrix,this.cam.matrixWorldInverse),i===this._projScreenMatrix?i:i.copy(this._projScreenMatrix)}awake(){KN&&window.addEventListener("pointerdown",i=>{const e=i.clientX,t=i.clientY;console.log("touch",e.toFixed(2),t.toFixed(2));const n=this.screenPointToRay(e,t),r="#"+Math.floor(Math.random()*16777215).toString(16);Ct.DrawRay(n.origin,n.direction,r,10)})}onEnable(){ec&&console.log(`Camera enabled: "${this.name}". ClearFlags=${Ju[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),jie(this)),this.applyClearFlagsIfIsActiveCamera()}onDisable(){this.context.removeCamera(this)}onBeforeRender(){if(this._cam&&(this._frustum&&this.updateFrustum(),this._clearFlags===2&&this.applyClearFlagsIfIsActiveCamera(),this._targetTexture)){this.context.isManagedExternally&&(this._warnedAboutExternalRenderer||(this._warnedAboutExternalRenderer=!0,console.warn("Rendering with external renderer is not supported yet. This may not work or throw errors. Please remove the the target texture from your camera: "+this.name,this.targetTexture))),this.context.composer;const i=this.context.renderer;if(i){const e=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,i),e?.applyClearFlags()}}}buildCamera(){if(this._cam)return;const i=this.gameObject.isCamera;let e=null;if(i?(e=this.gameObject,e?.layers.enableAll(),e instanceof kt&&(this._fov=e.fov)):e=this.gameObject.children[0],e&&e.isCamera)e instanceof kt&&(this._fov&&(e.fov=this._fov),e.near=this._nearClipPlane,e.far=this._farClipPlane,e.updateProjectionMatrix());else if(!this.orthographic)e=new kt(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(e.fov=this.fieldOfView),this.gameObject.add(e);else{const t=this.orthographicSize*100;e=new Rl(window.innerWidth/-t,window.innerWidth/t,window.innerHeight/t,window.innerHeight/-t,this._nearClipPlane,this._farClipPlane),this.gameObject.add(e)}this._cam=e,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(){this.context.mainCameraComponent===this&&this.applyClearFlags()}applyClearFlags(){if(!this._cam){ec&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this._fov,ec){const i=`Camera "${this.name}" clear flags: ${Ju[this._clearFlags]}`;console.debug(i)}switch(this._clearFlags){case 1:if(vv.backgroundShouldBeTransparent(this.context)&&(!this.ARBackgroundAlpha||this.ARBackgroundAlpha<.001)){this.context.scene.background=null,this.context.renderer.setClearColor(0,0);return}this.enableSkybox(),this._backgroundBlurriness!==void 0?this.context.scene.backgroundBlurriness=this._backgroundBlurriness:ec&&console.warn(`Camera "${this.name}" has no background blurriness`),this._backgroundIntensity!==void 0?this.context.scene.backgroundIntensity=this._backgroundIntensity:ec&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor){let i=this._backgroundColor.alpha;vv.backgroundShouldBeTransparent(this.context)&&(i=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.renderer.setClearColor(this._backgroundColor,i)}else ec&&console.warn(`Camera "${this.name}" has no background color`,this);break;case 4:this.context.scene.background=null,this.context.renderer.setClearColor(0,0);break}}enableSkybox(){this._skybox||(this._skybox=new zie(this)),this._skybox.enable()}static backgroundShouldBeTransparent(i){var e,t,n,r;const s=(e=i.renderer.xr)==null?void 0:e.getSession();if(!s)return!1;if(typeof s._transparent=="boolean")return s._transparent;const o=s.environmentBlendMode;ec&&$i("Environment blend mode: "+o+" on "+navigator.userAgent);let a=o==="additive"||o==="alpha-blend";return i.isInAR&&o==="opaque"&&((t=navigator.userAgent)!=null&&t.includes("OculusBrowser")||(n=navigator.userAgent)!=null&&n.includes("Mozilla")&&(r=navigator.userAgent)!=null&&r.includes("Mobile WebXRViewer/v2"))&&(a=!0),s._transparent=a,a}},h(z_,"_origin",new S),h(z_,"_direction",new S),z_);let Ri=vv;Os([x()],Ri.prototype,"aspect",1),Os([x()],Ri.prototype,"fieldOfView",1),Os([x()],Ri.prototype,"nearClipPlane",1),Os([x()],Ri.prototype,"farClipPlane",1),Os([x()],Ri.prototype,"clearFlags",1),Os([x()],Ri.prototype,"orthographic",2),Os([x()],Ri.prototype,"orthographicSize",2),Os([x()],Ri.prototype,"ARBackgroundAlpha",2),Os([x()],Ri.prototype,"cullingMask",1),Os([x()],Ri.prototype,"backgroundBlurriness",1),Os([x()],Ri.prototype,"backgroundIntensity",1),Os([x()],Ri.prototype,"environmentIntensity",1),Os([x(yi)],Ri.prototype,"backgroundColor",1),Os([x(ef)],Ri.prototype,"targetTexture",1);class zie{constructor(e){h(this,"_camera"),h(this,"_skybox"),this._camera=e}get context(){var e;return(e=this._camera)==null?void 0:e.context}enable(){this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),this._skybox?this.context.scene.background!==this._skybox&&(ec&&console.log(`Camera "${this._camera.name}" set skybox`,this._camera,this._skybox),this._skybox.mapping=mo,this.context.scene.background=this._skybox):(this._did_log_failed_to_find_skybox||(this._did_log_failed_to_find_skybox=!0,console.warn(`Camera "${this._camera.name}" failed to load/find skybox texture`,this._camera.sourceId,this.context.lightmaps,"Current background: ",this.context.scene.background)),(ec||pt())&&Qi(`Camera "${this._camera.name}" has no skybox texture`))}}function jie(i){ee("freecam")&&i.context.mainCameraComponent===i&&re.getOrAddComponent(i.gameObject,bi)}class ph extends Ie{constructor(){super(...arguments),h(this,"_listener",null)}get listener(){return this._listener==null&&(this._listener=new VD),this._listener}awake(){en.registerWaitForAllowAudio(()=>{if(this.destroyed)return;const e=this.listener;if(e==null||e.parent)return;const t=this.context.mainCameraComponent||re.getComponentInParent(this.gameObject,Ri);t!=null&&t.cam?t.cam.add(e):this.gameObject.add(e)})}}var Gie=Object.defineProperty,Qie=Object.getOwnPropertyDescriptor,j_=(i,e,t,n)=>{for(var r=n>1?void 0:n?Qie(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&Gie(e,t,r),r};const Hie=ee("debugsignals");class Av{constructor(){h(this,"guid")}}j_([x()],Av.prototype,"guid",2);class sf{constructor(){h(this,"signal"),h(this,"reaction")}}j_([x(Av)],sf.prototype,"signal",2),j_([x(Hn)],sf.prototype,"reaction",2);var WT;const tc=(WT=class extends Ie{constructor(){super(...arguments),h(this,"events")}static invoke(i){if(tc.receivers[i]){const e=tc.receivers[i];if(!e)return;for(const t of e)t.invoke(i)}}awake(){Hie&&console.log("SignalReceiver awake",this)}onEnable(){if(this.events)for(const i of this.events)tc.receivers[i.signal.guid]||(tc.receivers[i.signal.guid]=[]),tc.receivers[i.signal.guid].push(this)}onDisable(){if(this.events){for(const i of this.events)if(tc.receivers[i.signal.guid]){const e=tc.receivers[i.signal.guid].indexOf(this);e>=0&&tc.receivers[i.signal.guid].splice(e,1)}}}invoke(i){if(!this.events||!Array.isArray(this.events))return;const e=typeof i=="object"?i.guid:i;for(const t of this.events)if(t.signal.guid===e)try{if(t.reaction){if(!t.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",t,this);continue}}else{console.warn("Missing reaction for signal",t,this);continue}t.reaction.invoke()}catch(n){console.error(n)}}},h(WT,"receivers",{}),WT);let of=tc;j_([x(sf)],of.prototype,"events",2);var Js=(i=>(i.Activation="ActivationTrack",i.Animation="AnimationTrack",i.Audio="AudioTrack",i.Control="ControlTrack",i.Marker="MarkerTrack",i.Signal="SignalTrack",i))(Js||{}),Wa=(i=>(i[i.None=0]="None",i[i.Hold=1]="Hold",i[i.Loop=2]="Loop",i[i.PingPong=3]="PingPong",i[i.Continue=4]="Continue",i))(Wa||{}),qT=(i=>(i.Signal="SignalEmitter",i))(qT||{});const qa=ee("debugtimeline");class yv{constructor(){h(this,"director"),h(this,"track")}get muted(){return this.track.muted}set muted(e){var t;e!==this.track.muted&&(this.track.muted=e,(t=this.onMuteChanged)==null||t.call(this))}*forEachClip(e=!1){var t;if((t=this.track)!=null&&t.clips)if(e)for(let n=this.track.clips.length-1;n>=0;n--)yield this.track.clips[n];else for(const n of this.track.clips)yield n}getClipTime(e,t){return t.clipIn+(e-t.start)*t.timeScale}getClipTimeNormalized(e,t){return(e-t.start)/t.duration}evaluateWeight(e,t,n,r=!0){if(t<0||t>=n.length)return 0;const s=n[t];if(r||e>=s.start&&e<=s.end){let o=1;const a=!1;if(s.easeInDuration>0){const l=Math.min((e-s.start)/s.easeInDuration,1);o*=l}if(s.easeOutDuration>0&&!a){const l=Math.min((s.end-e)/s.easeOutDuration,1);o*=l}return o}return 0}}class Vie{constructor(e){h(this,"clip"),h(this,"rootPositionOffset"),h(this,"rootQuaternionOffset"),h(this,"rootStartPosition"),h(this,"rootEndPosition"),h(this,"rootStartQuaternion"),h(this,"rootEndQuaternion");const t=e.getClip();this.clip=t;const n=e.getRoot(),r=n.name+".position",s=n.name+".quaternion";qa&&console.log(t.name,t.tracks,r);for(const o of t.tracks)if(!(o.times.length<=0)){if(o.name.endsWith(r))this.rootStartPosition=new S().fromArray(o.values,0),this.rootEndPosition=new S().fromArray(o.values,o.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),qa&&console.log(this.rootPositionOffset);else if(o.name.endsWith(s)&&(this.rootStartQuaternion=new Me().fromArray(o.values,0),this.rootEndQuaternion=new Me().fromArray(o.values,o.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),qa)){const a=new Fi().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",a)}}}get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}}class G_ extends yv{constructor(){super(...arguments),h(this,"models",[]),h(this,"trackOffset"),h(this,"target"),h(this,"mixer"),h(this,"clips",[]),h(this,"actions",[]),h(this,"_actionOffsets",[]),h(this,"_didBind",!1),h(this,"_animator",null),h(this,"_useclipOffsets",!0),h(this,"_totalOffsetPosition",new S),h(this,"_totalOffsetRotation",new Me),h(this,"_totalOffsetPosition2",new S),h(this,"_totalOffsetRotation2",new Me),h(this,"_summedPos",new S),h(this,"_tempPos",new S),h(this,"_summedRot",new Me),h(this,"_tempRot",new Me),h(this,"_clipRotQuat",new Me)}onStateChanged(){this._animator&&ZN(this._animator.gameObject,this,this.director.isPlaying)}createHooks(e,t){var n,r;if(((n=t.tracks)==null?void 0:n.length)<=0){console.warn("No tracks in AnimationClip",t);return}const s=t.tracks[0].name.split("."),o=s[s.length-2],a=o+".position",l=o+".quaternion";let c=!1,u=!1;for(const d of t.tracks)d.name.endsWith(a)?(c=!0,this.createPositionInterpolant(t,e,d)):d.name.endsWith(l)&&(u=!0,this.createRotationInterpolant(t,e,d));if(!c||!u){const d=(r=this.mixer)==null?void 0:r.getRoot(),p=t.tracks[0],f=p.name.lastIndexOf("."),m=p.name.substring(0,f),A=m.substring(m.lastIndexOf(".")+1),v=d.getObjectByName(A);if(v)if(c){if(!u){const g=t.tracks[0].name.substring(0,f)+".quaternion";qa&&console.warn("Create quaternion track",A,v);const y=v.quaternion,b=new Pa(g,[0,t.duration],[y.x,y.y,y.z,y.w,y.x,y.y,y.z,y.w]);t.tracks.push(b),this.createRotationInterpolant(t,e,b)}}else{const g=m+".position";qa&&console.warn("Create position track",A,v);const y=v.position,b=new Bl(g,[0,t.duration],[y.x,y.y,y.z,y.x,y.y,y.z]);t.tracks.push(b),this.createPositionInterpolant(t,e,b)}}}bind(){if(!this._didBind){this._didBind=!0,qa&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(const e of this.actions){const t=new Vie(e);this._actionOffsets.push(t)}this.target&&(this._animator=re.getComponent(this.target,Sr)??null,this._animator&&ZN(this._animator.gameObject,this,!0));for(const e of this.models){const t=e.asset,n=t.position,r=t.rotation;n&&n.x!==void 0&&(n.isVector3||(t.position=new S(n.x,n.y,n.z)),r.isQuaternion||(t.rotation=new Me(r.x,r.y,r.z,r.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){const e=this.trackOffset.position;e&&(e.isVector3||(this.trackOffset.position=new S(e.x,e.y,e.z)));const t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new Me(t.x,t.y,t.z,t.w)))}}evaluate(e){var t,n,r,s,o,a,l;if(this.track.muted||!this.mixer)return;this.bind(),this._totalOffsetPosition.set(0,0,0),this._totalOffsetRotation.set(0,0,0,1),this._totalOffsetPosition2.set(0,0,0),this._totalOffsetRotation2.set(0,0,0,1);let c=0,u=0,d=!1,p=!1,f=0;for(let m=0;m<this.clips.length;m++){const A=this.models[m],v=this.actions[m],g=A.asset;v.weight=0;const y=e>=A.start&&e<=A.end,b=A.preExtrapolationMode,_=A.postExtrapolationMode,E=m<this.clips.length-1?this.models[m+1]:null;let I=y,T=!1;if(!I&&!d&&A.end<e&&_!==Wa.None?(!E||E.start>e)&&(I=!0,d=!0):m==0&&!I&&!p&&A.start>e&&b!==Wa.None&&(!E||E.start<e)&&(I=!0,T=!0,p=!0),I){let M=1;M*=this.evaluateWeight(e,m,this.models,I),M*=this.director.weight;let D=y;if(T)switch(b){case Wa.Hold:break;case Wa.Loop:e+=A.start,D=!0;break;default:e+=A.start,D=!0;break}let C=this.getClipTime(e,A),P=0;const G=g.duration;if(T&&b===Wa.Hold&&(C=0),D){if(g.loop)for(P+=Math.floor(C/(G+1e-6));C>G;)C-=G}else if(!y&&d)switch(_){case Wa.Hold:C=this.getClipTime(A.end,A);break;case Wa.Loop:C%=G;break;case Wa.PingPong:const k=Math.floor(C/G)%2!==0;C%=G,k&&(C=G-C);break}A.reversed===!0?v.time=v.getClip().duration-C:v.time=C,v.timeScale=0;const Q=Math.max(0,M);if(v.weight=Q,f+=Q,v.clampWhenFinished=!1,v.isRunning()||v.play(),this._useclipOffsets){const k=c==0?this._totalOffsetPosition:this._totalOffsetPosition2,W=c==0?this._totalOffsetRotation:this._totalOffsetRotation2;c<1&&(u=1-M),c+=1;const U=this._summedPos.set(0,0,0),F=this._tempPos.set(0,0,0),z=this._summedRot.identity(),Z=this._tempRot.identity(),K=g.rotation;K&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp(K,M));const se=this._actionOffsets[m];if(se.hasOffsets)for(let Ae=0;Ae<P;Ae++)se.rootPositionOffset?F.copy(se.rootPositionOffset):F.set(0,0,0),F.applyQuaternion(z),this._clipRotQuat&&F.applyQuaternion(this._clipRotQuat),se.rootQuaternionOffset&&(Z.copy(se.rootQuaternionOffset),z.multiply(Z)),U.add(F);this._clipRotQuat&&W.multiply(this._clipRotQuat),W.multiply(z),g.position&&U.add(g.position),k.add(U)}}}if(this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,u),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,u)),this.__mixerError===void 0&&(qa||pt())&&(n=(t=this._animator)==null?void 0:t.runtimeAnimatorController)!=null&&n.mixer&&this.mixer!==((s=(r=this._animator)==null?void 0:r.runtimeAnimatorController)==null?void 0:s.mixer)&&(this.__mixerError=!0,console.error("AnimationTrack mixer is not shared with the animator controller - this might result in the timeline to not animate properly. Please report a bug to the Needle Engine team!",this)),(o=this._animator)!=null&&o.runtimeAnimatorController){const m=Math.max(0,1-f);(l=(a=this._animator)==null?void 0:a.runtimeAnimatorController)==null||l.update(m)}else this.mixer.update(e)}createRotationInterpolant(e,t,n){var r;const s=n.createInterpolant.bind(n),o=new Me;this.ensureTrackOffsets();const a=(r=this.trackOffset)==null?void 0:r.rotation;n.createInterpolant=()=>{const l=s(),c=l.evaluate.bind(l);return l.evaluate=u=>{var d;const p=c(u);if(o.set(p[0],p[1],p[2],p[3]),o.premultiply(this._totalOffsetRotation),a&&o.premultiply(a),this.director.animationCallbackReceivers)for(const f of this.director.animationCallbackReceivers)(d=f?.onTimelineRotation)==null||d.call(f,this.director,this.target,u,o);return p[0]=o.x,p[1]=o.y,p[2]=o.z,p[3]=o.w,p},l}}createPositionInterpolant(e,t,n){var r,s;const o=n.createInterpolant.bind(n),a=new S;this.ensureTrackOffsets();const l=(r=this.trackOffset)==null?void 0:r.rotation,c=(s=this.trackOffset)==null?void 0:s.position;let u;n.createInterpolant=()=>{const d=o(),p=d.evaluate.bind(d);return d.evaluate=f=>{var m,A,v;const g=p(f);if(a.set(g[0],g[1],g[2]),t.removeStartOffset&&(u===void 0?(u=null,u=(A=(m=this._actionOffsets.find(y=>y.clip===e))==null?void 0:m.rootStartPosition)==null?void 0:A.clone()):u!=null&&u.isVector3&&a.sub(u)),a.applyQuaternion(this._totalOffsetRotation),a.add(this._totalOffsetPosition),l&&a.applyQuaternion(l),c&&(a.x-=c.x,a.y+=c.y,a.z+=c.z),this.director.animationCallbackReceivers)for(const y of this.director.animationCallbackReceivers)(v=y?.onTimelinePosition)==null||v.call(y,this.director,this.target,f,a);return g[0]=a.x,g[1]=a.y,g[2]=a.z,g},d}}}const Wie=ee("mutetimeline"),bv=class extends yv{constructor(){super(...arguments),h(this,"models",[]),h(this,"listener"),h(this,"audio",[]),h(this,"audioContextTimeOffset",[]),h(this,"lastTime",0),h(this,"audioSource"),h(this,"_audioLoader",null),h(this,"_playableDirectorResumed",!1)}getAudioFilePath(i){const e=this.director.sourceId;return kl(e,i)}onAllowAudioChanged(i){for(let e=0;e<this.models.length;e++){const t=this.models[e];this.audio[e].setVolume(i?t.asset.volume:0)}}addModel(i){const e=new sC(this.listener);this.audio.push(e);const t=i;t._didTriggerPlay=!1,this.models.push(t)}onDisable(){for(const i of this.audio)i.isPlaying&&i.stop();for(const i of this.models)i._didTriggerPlay=!1}onDestroy(){for(const i of this.audio)i.source&&i?.disconnect();this.audio.length=0}onMuteChanged(){if(this.muted)for(let i=0;i<this.audio.length;i++){const e=this.audio[i];e!=null&&e.isPlaying&&e.stop()}}stop(){for(let i=0;i<this.audio.length;i++){const e=this.audio[i];e!=null&&e.isPlaying&&e.stop()}for(const i of this.models)i._didTriggerPlay=!1}onPauseChanged(){for(let i=0;i<this.audio.length;i++){const e=this.audio[i];e!=null&&e.isPlaying&&e.stop()}this._playableDirectorResumed=this.director.isPlaying}evaluate(i){if(Wie||this.track.muted||this.director.speed<0)return;const e=this.director.context.application.muted,t=this._playableDirectorResumed;this._playableDirectorResumed=!1;const n=e?.1:0;for(let r=0;r<this.models.length;r++){const s=this.models[r],o=this.audio[r],a=s.asset;if((!o||!o.buffer)&&this.isInTimeRange(s,i-1,i+1)&&this.handleAudioLoading(s,o),en.userInteractionRegistered!==!1&&!(o===null||!o.buffer))if(o.playbackRate=this.director.context.time.timeScale*this.director.speed,o.loop=a.loop,i>=s.start&&i<=s.end&&i<this.director.duration){if(!o.isPlaying||!this.director.isPlaying)(t||!s._didTriggerPlay&&this.lastTime<i)&&(s.duration*s.timeScale>.3?o.offset=s.clipIn+(i-s.start)*s.timeScale:o.offset=0,qa&&console.log("Timeline Audio ("+this.track.name+") play with offset "+o.offset+" - "+s.asset.clip),o.play(n),s._didTriggerPlay=!0);else{const c=s.clipIn+(i-s.start)*s.timeScale,u=o.context.currentTime-o._startedAt+o.offset;Math.abs(c-u)>.3&&(o.offset=c,o.stop(),o.play(n))}let l=a.volume;if(this.track.volume!==void 0&&(l*=this.track.volume),e&&(l=0),s.easeInDuration>0){const c=Math.min((i-s.start)/s.easeInDuration,1);l*=c}if(s.easeOutDuration>0){const c=Math.min((s.end-i)/s.easeOutDuration,1);l*=c}o.setVolume(l*this.director.weight)}else s._didTriggerPlay=!1,this.director.isPlaying&&o.isPlaying&&o.stop()}this.lastTime=i}loadAudio(i,e=0,t=0){let n=null;const r=i-t,s=i+e;for(const o of this.models)if(this.isInTimeRange(o,r,s)){const a=this.audio[this.models.indexOf(o)],l=this.handleAudioLoading(o,a);l!==null&&(n===null&&(n=[]),n.push(l))}return n!==null?Promise.all(n):null}isInTimeRange(i,e,t){return e<=i.start&&t>=i.end||e>=i.start&&e<=i.end||t>=i.start&&t<=i.end}static dispose(){bv._audioBuffers.clear()}handleAudioLoading(i,e){this._audioLoader||(this._audioLoader=new Oy);const t=this.getAudioFilePath(i.asset.clip);if(bv._audioBuffers.get(t)){const r=bv._audioBuffers.get(t);return r.then(s=>{s&&e.setBuffer(s)}),r}qa&&console.warn("LOAD audio track",t,this.director.sourceId);const n=new Promise((r,s)=>{this._audioLoader.load(t,o=>{e.setBuffer(o),r(o)},void 0,o=>{console.error("Error loading audio",o),r(null)})});return bv._audioBuffers.set(t,n),n}};let _v=bv;h(_v,"_audioBuffers",new Map);class xv extends yv{constructor(){super(...arguments),h(this,"models",[]),h(this,"didTrigger",[]),h(this,"receivers",[])}evaluate(e){var t;if(this.track.muted)return;const n=this.director.context.time.deltaTime*1.5;for(let r=0;r<this.models.length;r++){const s=this.models[r],o=this.didTrigger[r],a=s.time-e;let l=!1;if(s.retroActive)l=a<=1e-6;else{const c=Math.abs(a);(c===0||c>=1e-5&&c<n)&&(l=!0)}if(l){if(!o)if(qa&&console.log("Trigger signal",e,s.time,s),this.didTrigger[r]=!0,((t=this.receivers)==null?void 0:t.length)<=0)of.invoke(s.asset);else for(const c of this.receivers)c&&c.invoke(s.asset)}else s.emitOnce||(this.didTrigger[r]=!1)}}}class Q_ extends yv{constructor(){super(...arguments),h(this,"models",[]),h(this,"timelines",[]),h(this,"_previousActiveModel",null)}resolveSourceObjects(e){for(let t=this.models.length-1;t>=0;t--){const n=this.models[t].asset;if(!n.sourceObject||typeof n.sourceObject!="object"){console.log("no source object, removing model",t,n),this.models.splice(t,1);continue}else{const r=re.getComponent(n.sourceObject,Ku);this.timelines.push(r),r&&n.updateDirector&&(r.playOnAwake=!1)}}}evaluate(e){var t;this._previousActiveModel=null;for(let n=0;n<this.models.length;n++){const r=this.models[n],s=r.asset;if(e>=r.start&&e<=r.end){this._previousActiveModel=r;const o=this.getClipTime(e,r);if(s.controlActivation){const a=s.sourceObject;a.visible=!0}if(s.updateDirector){const a=this.timelines[n];a&&(a.isPlaying&&a.pause(),a.time=o,a.evaluate())}}else{const o=(t=this._previousActiveModel)==null?void 0:t.asset;if(s.controlActivation){const a=s.sourceObject;o?.sourceObject!==a&&(a.visible=!1)}}}}}const af=ee("debugtimeline"),XT=class extends Ie{constructor(){super(...arguments),h(this,"playableAsset"),h(this,"playOnAwake"),h(this,"extrapolationMode",1),h(this,"waitForAudio",!0),h(this,"_visibilityChangeEvt"),h(this,"_clonedPlayableAsset",!1),h(this,"_speed",1),h(this,"_guidsMap"),h(this,"_isPlaying",!1),h(this,"_internalUpdateRoutine"),h(this,"_isPaused",!1),h(this,"_isStopping",!1),h(this,"_time",0),h(this,"_duration",0),h(this,"_weight",1),h(this,"_animationTracks",[]),h(this,"_audioTracks",[]),h(this,"_signalTracks",[]),h(this,"_controlTracks",[]),h(this,"_customTracks",[]),h(this,"_allTracks",[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks]),h(this,"animationCallbackReceivers",[])}static registerCreateTrack(i,e){this.createTrackFunctions[i]=e}get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(i){typeof i=="number"&&!Number.isNaN(i)?this._time=i:(af||Bs())&&console.error("INVALID TIMELINE.TIME VALUE",i,this.name)}get duration(){return this._duration}set duration(i){this._duration=i}get weight(){return this._weight}set weight(i){this._weight=i}get speed(){return this._speed}set speed(i){this._speed=i}awake(){var i,e,t;af&&console.log(this,(i=this.playableAsset)==null?void 0:i.tracks),this.rebuildGraph(),this.isValid()||console.warn("PlayableDirector is not valid",this.playableAsset,(e=this.playableAsset)==null?void 0:e.tracks,Array.isArray((t=this.playableAsset)==null?void 0:t.tracks),this)}onEnable(){var i,e,t;for(const n of this._audioTracks)(i=n.onEnable)==null||i.call(n);for(const n of this._customTracks)(e=n.onEnable)==null||e.call(n);for(const n of this._animationTracks)(t=n.onEnable)==null||t.call(n);this.playOnAwake&&this.play(),this._visibilityChangeEvt||(this._visibilityChangeEvt=()=>{switch(document.visibilityState){case"hidden":this.setAudioTracksAllowPlaying(!1);break;case"visible":this.setAudioTracksAllowPlaying(!0);break}}),window.addEventListener("visibilitychange",this._visibilityChangeEvt)}onDisable(){var i,e,t;this.stop();for(const n of this._audioTracks)(i=n.onDisable)==null||i.call(n);for(const n of this._customTracks)(e=n.onDisable)==null||e.call(n);for(const n of this._animationTracks)(t=n.onDisable)==null||t.call(n);this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){var i;for(const e of this._allTracks)for(const t of e)(i=t.onDestroy)==null||i.call(t)}rebuildGraph(){this.isValid()&&(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}async play(){if(!this.isValid())return;const i=this._isPaused==!0;if(this._isPaused=!1,!this._isPlaying){if(this._isPlaying=!0,i&&this.invokePauseChangedMethodsOnTracks(),this.waitForAudio){const e=[];for(const t of this._audioTracks){const n=t.loadAudio(this._time,1,0);n&&e.push(n)}if(e.length>0&&(await Promise.all(e),!this._isPlaying))return;for(;this._audioTracks.length>0&&this._isPlaying&&!en.userInteractionRegistered&&this.waitForAudio;)await na(200)}this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate(),Pn.LateUpdate)}}pause(){this.isValid()&&(this._isPlaying=!1,!this._isPaused&&(this._isPaused=!0,this.internalEvaluate(),this.invokePauseChangedMethodsOnTracks(),this.invokeStateChangedMethodsOnTracks()))}stop(){this._isStopping=!0;for(const t of this._audioTracks)t.stop();const i=this._isPaused==!0,e=this._isPlaying;this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.internalEvaluate(),i&&this.invokePauseChangedMethodsOnTracks()),this._isPlaying=!1,this._isPaused=!1,i&&!e&&this.invokePauseChangedMethodsOnTracks(),e&&this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine&&this.stopCoroutine(this._internalUpdateRoutine),this._internalUpdateRoutine=null,this._isStopping=!1}evaluate(){this.internalEvaluate(!0)}isValid(){return this.playableAsset&&this.playableAsset.tracks&&Array.isArray(this.playableAsset.tracks)}*forEachTrack(){for(const i of this._allTracks)for(const e of i)yield e}get audioTracks(){return this._audioTracks}resolveGuids(i){this._guidsMap=i}invokePauseChangedMethodsOnTracks(){var i;for(const e of this.forEachTrack())(i=e.onPauseChanged)==null||i.call(e)}invokeStateChangedMethodsOnTracks(){var i;for(const e of this.forEachTrack())(i=e.onStateChanged)==null||i.call(e,this._isPlaying)}*internalUpdate(){for(;this._isPlaying&&this.activeAndEnabled;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime*this.speed,this.internalEvaluate()),yield}internalEvaluate(i=!1){if(!this.isValid())return;let e=this._time;switch(this.extrapolationMode){case 0:this._speed>0?e=Math.min(e,this._duration):this._speed<0&&(e=Math.max(e,0)),this._time=e;break;case 1:e%=this._duration,this._time=e;break;case 2:if(e>this._duration){this.stop();return}break}const t=this._time;for(const n of this.playableAsset.tracks)if(!n.muted)switch(n.type){case Js.Activation:if(!i&&!this._isPlaying)continue;for(let r=0;r<n.outputs.length;r++){const s=n.outputs[r];if(typeof s=="object"){let o=!1;if(n.clips)for(const l of n.clips)l.start<=t&&t<=l.end&&(o=!0);const a=s;a.visible!==void 0&&a.visible!==o&&(a.visible=o,af&&console.warn(this.name,"set ActivationTrack-"+r,a.name,o,t))}}break}if(!this._isStopping)for(const n of this._animationTracks)n.evaluate(t);for(const n of this._audioTracks)n.evaluate(t);for(const n of this._signalTracks)n.evaluate(t);for(const n of this._controlTracks)n.evaluate(t);for(const n of this._customTracks)n.evaluate(t)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=Ym(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;const i=this.findRoot(this.gameObject);for(const e of this.playableAsset.tracks){for(let t=e.outputs.length-1;t>=0;t--){let n=e.outputs[t];if(typeof n=="string"){this._guidsMap&&this._guidsMap[n]&&(n=this._guidsMap[n]);const r=re.findByGuid(n,i);r===null||typeof r!="object"?(e.outputs.splice(t,1),console.warn("Failed to resolve binding",n,e.name,e.type)):(af&&console.log("Resolved binding",n,"to",r),e.outputs[t]=r)}else if(n===null){if(e.outputs.splice(t,1),XT.createTrackFunctions[e.type])continue;e.type!==Js.Audio&&e.type!==Js.Control&&e.type!==Js.Marker&&e.type!==Js.Signal&&console.warn("Missing binding",n,e.name,e.type,this.name,this.playableAsset.name)}}if(e.type===Js.Control&&e.clips)for(let t=0;t<e.clips.length;t++){const n=e.clips[t];let r=n.asset.sourceObject;if(typeof r=="string"){this._guidsMap&&this._guidsMap[r]&&(r=this._guidsMap[r]);const s=re.findByGuid(r,i);s===null||typeof s!="object"?console.warn("Failed to resolve sourceObject binding",r,e.name,n):(af&&console.log("Resolved binding",r,"to",s),n.asset.sourceObject=s)}}}}findRoot(i){return i.parent?this.findRoot(i.parent):i}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const i of this.playableAsset.tracks)if(i.muted!==!0){if(i.clips)for(const e of i.clips)e.end>this._duration&&(this._duration=e.end);if(i.markers)for(const e of i.markers)e.time>this._duration&&(this._duration=e.time+.001)}}}setupAndCreateTrackHandlers(){var i,e,t;if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let n=re.findObjectOfType(ph,this.context);for(const r of this.playableAsset.tracks){const s=r.type,o=XT.createTrackFunctions[s];if(o!=null){const a=o(this,r);if(typeof a.evaluate=="function"){a.director=this,a.track=r,this._customTracks.push(a);continue}}if(r.type===Js.Animation){if(!r.clips||r.clips.length<=0){af&&console.warn("Animation track has no clips",r);continue}for(let a=r.outputs.length-1;a>=0;a--){let l=r.outputs[a];if(l instanceof ge){const u=re.getOrAddComponent(l,Sr);u&&(l=u)}const c=(i=l?.gameObject)==null?void 0:i.animations;if(c){const u=new G_;u.trackOffset=r.trackOffset,u.director=this,u.track=r;for(let d=0;d<r.clips.length;d++){const p=r.clips[d],f=p.asset;if(!f){console.error(`Timeline ${this.name}: clip #${d} on track "${r.name}" has no animation data`);continue}const m=f.clip;let A=m;if((typeof A=="string"||typeof A=="number")&&(A=c.find(g=>g.name===m)),!A){console.warn("Could not find animationClip for model",p,r.name,this.name,(e=this.playableAsset)==null?void 0:e.name);continue}l instanceof Sr&&l.runtimeAnimatorController&&(l.__internalDidAwakeAndStart||l.initializeRuntimeAnimatorController(),l.runtimeAnimatorController.mixer||l.runtimeAnimatorController.bind(l),u.mixer=l.runtimeAnimatorController.mixer),u.mixer||(u.mixer=new ky(l.gameObject)),u.clips.push(A),u.mixer.uncacheAction(A),u.createHooks(p.asset,A);const v=u.mixer.clipAction(A);u.actions.push(v),u.models.push(p)}this._animationTracks.push(u)}}}else if(r.type===Js.Audio){if(!r.clips||r.clips.length<=0)continue;const a=new _v;a.director=this,a.track=r,a.audioSource=r.outputs.find(l=>l instanceof en),this._audioTracks.push(a),n||(n=(t=this.context.mainCameraComponent)==null?void 0:t.gameObject.addNewComponent(ph)),a.listener=n.listener;for(let l=0;l<r.clips.length;l++){const c=r.clips[l];a.addModel(c)}}else if(r.type===Js.Marker){const a=new xv;if(a.director=this,a.track=r,r.markers)for(const l of r.markers)switch(l.type){case qT.Signal:a.models.push(l),a.didTrigger.push(!1);break}if(a!==null&&a.models.length>0){const l=re.getComponent(this.gameObject,of);l&&(a.receivers.push(l),this._signalTracks.push(a))}}else if(r.type===Js.Signal){const a=new xv;if(a.director=this,a.track=r,r.markers)for(const l of r.markers)a.models.push(l),a.didTrigger.push(!1);for(const l of r.outputs)a.receivers.push(l);this._signalTracks.push(a)}else if(r.type===Js.Control){const a=new Q_;if(a.director=this,a.track=r,r.clips)for(const l of r.clips)a.models.push(l);a.resolveSourceObjects(this.context),this._controlTracks.push(a)}}}setAudioTracksAllowPlaying(i){for(const e of this._audioTracks)e.onAllowAudioChanged(i)}registerAnimationCallback(i){this.animationCallbackReceivers.push(i)}unregisterAnimationCallback(i){const e=this.animationCallbackReceivers.indexOf(i);e!==-1&&this.animationCallbackReceivers.splice(e,1)}};let Ku=XT;h(Ku,"createTrackFunctions",{});const H_=Symbol("objectIsAnimatedData");function ZN(i,e,t){if(!i)return;if(i[H_]===void 0){if(!t)return;i[H_]=new Set}const n=i[H_];t?n.add(e):n.has(e)&&n.delete(e)}function qie(i){if(!i)return!1;const e=i[H_];return e!==void 0&&e.size>0}ii.registerCallback(bn.ContextCreated,i=>{const e=i.context.domElement.getAttribute("autoplay");if(e!==void 0&&(e===""||e==="true")&&i.files)for(const t of i.files)re.foreachComponent(t.file.scene,n=>{if(n.enabled!==!1){if(n instanceof vs&&n.playAutomatically||n instanceof Sr||n instanceof Ku&&n.playOnAwake===!0)return!0;if(n instanceof vs)return n.playAutomatically=!0,!0;if(n instanceof Ku)return n.playOnAwake=!0,!0}},!0)!==!0&&Xie(t.file)});function Xie(i){if(!i||!i.animations)return;for(let t=0;t<i.animations.length;t++){const n=i.animations[t];if(!(!n.tracks||n.tracks.length<=0))for(const r in n.tracks){const s=n.tracks[r],o=s.__objectName??s.name.substring(0,s.name.indexOf("."));let a=i.scene.getObjectByName(o);if(!a&&(a=i.scene.getObjectByProperty("uuid",o),!a))continue;let l=e(a);l||(l=nh(i.scene,new vs));const c=l.animations=l.animations||[];n.name_animator=l.name,c.indexOf(n)<0&&c.push(n)}}function e(t){var n;if(!t)return;const r=(n=t.userData)==null?void 0:n.components;if(r&&r.length>0)for(let s=0;s<r.length;s++){const o=r[s];if(o instanceof Sr||o instanceof vs)return t}return e(t.parent)}}class Yie{constructor(){h(this,"_context")}get context(){return this._context??Lt.Current}get isStateMachineBehaviour(){return!0}}class wv{constructor(e,t,n,r){h(this,"name"),h(this,"nameHash"),h(this,"normalizedTime"),h(this,"length"),h(this,"speed"),h(this,"action"),this.name=e.name,this.nameHash=e.hash,this.normalizedTime=t,this.length=n,this.speed=r,this.action=e.motion.action||null}}function $N(i,e){return{name:"",isLooping:!1,guid:e?.generateUUID()??Nn.generateUUID(),index:-1,clip:new cs(i,1,[])}}var fh=(i=>(i[i.If=1]="If",i[i.IfNot=2]="IfNot",i[i.Greater=3]="Greater",i[i.Less=4]="Less",i[i.Equals=6]="Equals",i[i.NotEqual=7]="NotEqual",i))(fh||{}),YT=(i=>(i[i.Float=1]="Float",i[i.Int=3]="Int",i[i.Bool=4]="Bool",i[i.Trigger=9]="Trigger",i))(YT||{});const As=ee("debuganimatorcontroller"),V_=ee("debugrootmotion");class uo{constructor(e){h(this,"_speed",1),h(this,"normalizedStartOffset",0),h(this,"animator"),h(this,"model"),h(this,"_mixer"),h(this,"_activeState"),h(this,"_activeStates",[]),h(this,"rootMotionHandler"),this.model=e,As&&console.log(this)}static createFromClips(e,t={looping:!1,autoTransition:!0,transitionDuration:0}){const n=[];for(let s=0;s<e.length;s++){const o=e[s],a=[];if(t.autoTransition!==!1){const c=t.transitionDuration??0,u=c/o.duration;let d=s;(t.autoTransition===void 0||t.autoTransition===!0)&&(d=(s+1)%e.length),a.push({exitTime:1-u,offset:0,duration:c,hasExitTime:!0,destinationState:d,conditions:[]})}const l={name:o.name,hash:s,motion:{name:o.name,clip:o,isLooping:t?.looping??!1},transitions:a,behaviours:[]};n.push(l)}const r={name:"AnimatorController",guid:new or(Date.now()).generateUUID(),parameters:[],layers:[{name:"Base Layer",stateMachine:{defaultState:0,states:n}}]};return new uo(r)}play(e,t=-1,n=Number.NEGATIVE_INFINITY,r=0){if(t<0)t=0;else if(t>=this.model.layers.length){console.warn("invalid layer");return}const s=this.model.layers[t].stateMachine;for(const o of s.states)if(o.name===e||o.hash===e){As&&console.log("transition to ",o),this.transitionTo(o,r,n);return}console.warn("Could not find "+e+" to play")}reset(){this.setStartTransition()}setBool(e,t){var n,r;const s=typeof e=="string"?"name":"hash";return(r=(n=this.model)==null?void 0:n.parameters)==null?void 0:r.filter(o=>o[s]===e).forEach(o=>o.value=t)}getBool(e){var t,n,r;const s=typeof e=="string"?"name":"hash";return((r=(n=(t=this.model)==null?void 0:t.parameters)==null?void 0:n.find(o=>o[s]===e))==null?void 0:r.value)??!1}setFloat(e,t){var n,r;const s=typeof e=="string"?"name":"hash",o=(r=(n=this.model)==null?void 0:n.parameters)==null?void 0:r.filter(a=>a[s]===e);return o.forEach(a=>a.value=t),o?.length>0}getFloat(e){var t,n,r;const s=typeof e=="string"?"name":"hash";return((r=(n=(t=this.model)==null?void 0:t.parameters)==null?void 0:n.find(o=>o[s]===e))==null?void 0:r.value)??0}setInteger(e,t){var n,r;const s=typeof e=="string"?"name":"hash";return(r=(n=this.model)==null?void 0:n.parameters)==null?void 0:r.filter(o=>o[s]===e).forEach(o=>o.value=t)}getInteger(e){var t,n,r;const s=typeof e=="string"?"name":"hash";return((r=(n=(t=this.model)==null?void 0:t.parameters)==null?void 0:n.find(o=>o[s]===e))==null?void 0:r.value)??0}setTrigger(e){var t,n;As&&console.log("SET TRIGGER",e);const r=typeof e=="string"?"name":"hash";return(n=(t=this.model)==null?void 0:t.parameters)==null?void 0:n.filter(s=>s[r]===e).forEach(s=>s.value=!0)}resetTrigger(e){var t,n;const r=typeof e=="string"?"name":"hash";return(n=(t=this.model)==null?void 0:t.parameters)==null?void 0:n.filter(s=>s[r]===e).forEach(s=>s.value=!1)}getTrigger(e){var t,n,r;const s=typeof e=="string"?"name":"hash";return((r=(n=(t=this.model)==null?void 0:t.parameters)==null?void 0:n.find(o=>o[s]===e))==null?void 0:r.value)??!1}isInTransition(){return this._activeStates.length>1}setSpeed(e){this._speed=e}FindState(e){return this.findState(e)}findState(e){if(!e)return null;if(Array.isArray(this.model.layers)){for(const t of this.model.layers)for(const n of t.stateMachine.states)if(n.name===e||n.hash==e)return n}return null}getCurrentStateInfo(){if(!this._activeState)return null;const e=this._activeState.motion.action;if(!e)return null;const t=this._activeState.motion.clip.duration,n=t<=0?0:Math.abs(e.time/t);return new wv(this._activeState,n,t,this._speed)}get currentAction(){return this._activeState&&this._activeState.motion.action||null}get context(){var e;return(e=this.animator)==null?void 0:e.context}get mixer(){return this._mixer}bind(e){e?this.animator!==e&&(this.animator=e,this._mixer=new ky(this.animator.gameObject),this.createActions(this.animator)):console.error("AnimatorController.bind: animator is null")}clone(){if(typeof this.model=="string")return console.warn("AnimatorController has not been resolved, can not create model from string",this.model),null;As&&console.warn("AnimatorController clone()",this.model);const e=Ym(this.model,(t,n,r)=>r==null?!0:!(r.type==="Object3D"||r.isObject3D===!0||kk(r)||r.tracks!==void 0||r instanceof uo));return console.assert(e!==this.model),new uo(e)}update(e){var t,n;if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates(e);const r=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&((t=this.rootMotionHandler)==null||t.onBeforeUpdate(e)),this._mixer.update(r),this.animator.applyRootMotion&&((n=this.rootMotionHandler)==null||n.onAfterUpdate(e))}get activeState(){return this._activeState}updateActiveStates(e){for(let t=0;t<this._activeStates.length;t++){const n=this._activeStates[t],r=n.motion;if(!r.action)this._activeStates.splice(t,1),t--;else{const s=r.action;s.weight=e,s.getEffectiveWeight()<=0&&!s.isRunning()&&(As&&console.debug("REMOVE",n.name,s.getEffectiveWeight(),s.isRunning(),s.isScheduled()),this._activeStates.splice(t,1),t--)}}}setStartTransition(){for(const e of this.model.layers){const t=e.stateMachine;t.defaultState===void 0&&(As&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",e),t.defaultState=0);const n=t.states[t.defaultState];this.transitionTo(n,0,this.normalizedStartOffset)}}evaluateTransitions(){var e;let t=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;t=!0}const n=this._activeState,r=n.motion.action;for(const o of n.transitions){if(!o.hasExitTime&&o.conditions.length<=0)continue;let a=!0;for(const l of o.conditions)if(!this.evaluateCondition(l)){a=!1;break}if(a)if(r){const l=n.motion.clip.duration,c=l<=0?1:Math.abs(r.time/l);let u=!1;if(o.hasExitTime?r.timeScale>0?u=c>=o.exitTime:r.timeScale<0&&(u=1-c>=o.exitTime):u=!0,u){for(const d of o.conditions){const p=this.model.parameters.find(f=>f.name===d.parameter);p?.type===YT.Trigger&&p.value&&(p.value=!1)}r.clampWhenFinished=!0,As&&console.log("transition to "+o.destinationState,o,c,o.exitTime,o.hasExitTime),this.transitionTo(o.destinationState,o.duration,o.offset);return}}else{this.transitionTo(o.destinationState,o.duration,o.offset);return}}if(r){let o=n.speed??1;n.speedParameter&&(o*=this.getFloat(n.speedParameter)),o!==void 0&&(r.timeScale=o*this._speed)}let s=!1;if(n.motion.isLooping&&r&&(r.time>=r.getClip().duration?(s=!0,r.reset(),r.time=0,r.play()):r.time<=0&&r.timeScale<0&&(s=!0,r.reset(),r.time=r.getClip().duration,r.play())),!s&&n&&!t&&r&&this.animator&&n.behaviours){const o=r?.getClip().duration,a=r.time/o,l=new wv(this._activeState,a,o,this._speed);for(const c of n.behaviours)c.instance&&((e=c.instance.onStateUpdate)==null||e.call(c.instance,this.animator,l,0))}}getState(e,t){return typeof e=="number"&&(e==-1&&(e=this.model.layers[t].stateMachine.defaultState,e===void 0&&(As&&console.warn("AnimatorController default state is undefined: ",this.model,"Layer: "+t),e=0)),e=this.model.layers[t].stateMachine.states[e]),e}transitionTo(e,t,n){var r,s,o,a,l,c,u,d;if(!this.animator)return;const p=0;if(e=this.getState(e,p),!(e!=null&&e.motion)||!e.motion.clip||!(e.motion.clip instanceof cs))return;const f=this._activeState===e;if(f){const g=e.motion;if(!g.action_loopback&&g.clip){const y=this.rootMotionHandler?this.animator.gameObject.matrix.clone():null;this._mixer.uncacheAction(g.clip,this.animator.gameObject),y&&y.decompose(this.animator.gameObject.position,this.animator.gameObject.quaternion,this.animator.gameObject.scale),g.action_loopback=this.createAction(g.clip)}}if((r=this._activeState)!=null&&r.behaviours&&this._activeState.motion.action){const g=(s=this._activeState)==null?void 0:s.motion.clip.duration,y=this._activeState.motion.action.time/g,b=new wv(this._activeState,y,g,this._speed);for(const _ of this._activeState.behaviours)(a=(o=_.instance)==null?void 0:o.onStateExit)==null||a.call(_.instance,this.animator,b,p)}const m=(l=this._activeState)==null?void 0:l.motion.action;m&&m.fadeOut(t),f&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=m);const A=this._activeState;this._activeState=e;const v=(c=e.motion)==null?void 0:c.action;if(v){if(n=Math.max(0,Math.min(1,n)),e.cycleOffsetParameter){let y=this.getFloat(e.cycleOffsetParameter);typeof y=="number"?(y<0&&(y+=1),n+=y,n%=1):As&&console.warn("AnimatorController cycle offset parameter is not a number",e.cycleOffsetParameter)}else typeof e.cycleOffset=="number"&&(n+=e.cycleOffset,n%=1);v.isRunning()&&v.stop(),v.reset(),v.enabled=!0;const g=e.motion.clip.duration;if(v.time=f?0:n*g,v.timeScale<0&&(v.time=g-v.time),v.clampWhenFinished=!0,v.setLoop(dm,0),t>0?v.fadeIn(t):v.weight=1,v.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(v),this._activeStates.includes(e)||this._activeStates.push(e),this._activeState.behaviours){const y=new wv(e,n,g,this._speed);for(const b of this._activeState.behaviours)(d=(u=b.instance)==null?void 0:u.onStateEnter)==null||d.call(b.instance,this.animator,y,p)}}else As&&(e.__warned_no_motion||(e.__warned_no_motion=!0,console.warn("No action",e.motion,this)));As&&console.log("TRANSITION FROM "+A?.name+" TO "+e.name,t,m,v,v?.getEffectiveTimeScale(),v?.getEffectiveWeight(),v?.isRunning(),v?.isScheduled(),v?.paused)}createAction(e){var t,n;if(this._mixer.existingAction(e)&&this._mixer.uncacheAction(e,(t=this.animator)==null?void 0:t.gameObject),(n=this.animator)!=null&&n.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new Jie(this));const r=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,r,e)}else return this._mixer.clipAction(e)}evaluateCondition(e){const t=this.model.parameters.find(n=>n.name===e.parameter);if(!t)return!1;switch(e.mode){case fh.If:return t.value===!0;case fh.IfNot:return t.value===!1;case fh.Greater:return t.value>e.threshold;case fh.Less:return t.value<e.threshold;case fh.Equals:return t.value===e.threshold;case fh.NotEqual:return t.value!==e.threshold}return!1}createActions(e){var t,n,r,s;As&&console.log("AnimatorController createActions",this.model);for(const o of this.model.layers){const a=o.stateMachine;for(let l=0;l<a.states.length;l++){const c=a.states[l];c.transitions||(c.transitions=[]);for(const u of c.transitions)u.conditions||(u.conditions=[]);if(c.motion||(c.motion=$N(c.name)),this.animator&&c.motion.clips){const u=(t=c.motion.clips)==null?void 0:t.find(d=>{var p,f;return d.node.name===((f=(p=this.animator)==null?void 0:p.gameObject)==null?void 0:f.name)});u?c.motion.clip=u.clip:(As||pt())&&console.warn('Could not find clip for animator "'+((r=(n=this.animator)==null?void 0:n.gameObject)==null?void 0:r.name)+'"',c.motion.clips.map(d=>d.node.name))}if(!c.motion.clip){const u=new cs(void 0,void 0,[]);c.motion.clip=u}if((s=c.motion)!=null&&s.clip){const u=c.motion.clip;if(u instanceof cs){const d=this.createAction(u);c.motion.action=d}else(As||pt())&&console.warn("No valid animationclip assigned",c)}if(c.behaviours&&Array.isArray(c.behaviours))for(const u of c.behaviours){if(!(u!=null&&u.typeName))continue;const d=q.get(u.typeName),p=new d;p.isStateMachineBehaviour&&(p._context=this.context??void 0,Bp(p,u.properties),u.instance=p),As&&console.log("Created animator controller behaviour",c.name,u.typeName,u.properties,p)}}}}*enumerateActions(){if(this.model.layers)for(const e of this.model.layers){const t=e.stateMachine;for(let n=0;n<t.states.length;n++){const r=t.states[n];r!=null&&r.motion&&(r.motion.action&&(yield r.motion.action),r.motion.action_loopback&&(yield r.motion.action_loopback))}}}}class e4{constructor(e,t){h(this,"track"),h(this,"createdInterpolant"),h(this,"originalEvaluate"),h(this,"customEvaluate"),this.track=e;const n=e,r=n.createInterpolant.bind(e);n.createInterpolant=()=>(n.createInterpolant=r,this.createdInterpolant=r(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=s=>{if(!this.originalEvaluate)return;const o=this.originalEvaluate(s);return t(s,o)},this.createdInterpolant.evaluate=this.customEvaluate,this.createdInterpolant)}dispose(){this.createdInterpolant&&this.originalEvaluate&&(this.createdInterpolant.evaluate=this.originalEvaluate),this.track=void 0,this.createdInterpolant=null,this.originalEvaluate=void 0,this.customEvaluate=void 0}}const ir=class{constructor(i,e,t,n,r){if(h(this,"_action"),h(this,"root"),h(this,"clip"),h(this,"positionWrapper",null),h(this,"rotationWrapper",null),h(this,"context"),h(this,"positionChange",new S),h(this,"rotationChange",new Me),h(this,"_prevTime",0),this.context=i,this.root=e,this.clip=t,ir.firstKeyframeRotation[this.cacheId]||(ir.firstKeyframeRotation[this.cacheId]=new Me),r){const s=r.values;ir.firstKeyframeRotation[this.cacheId].set(s[0],s[1],s[2],s[3])}ir.spaceRotation[this.cacheId]||(ir.spaceRotation[this.cacheId]=new Me),ir.effectiveSpaceRotation[this.cacheId]||(ir.effectiveSpaceRotation[this.cacheId]=new Me),ir.clipOffsetRotation[this.cacheId]=new Me,r&&ir.clipOffsetRotation[this.cacheId].set(r.values[0],r.values[1],r.values[2],r.values[3]).invert(),this.handlePosition(t,n),this.handleRotation(t,r)}set action(i){this._action=i}get action(){return this._action}get cacheId(){return this.root.uuid}onStart(i){if(i.getClip()!==this.clip)return;ir.lastObjRotation[this.cacheId]||(ir.lastObjRotation[this.cacheId]=this.root.quaternion.clone());const e=ir.lastObjRotation[this.cacheId];if(ir.spaceRotation[this.cacheId].copy(e),V_){const t=new Fi().setFromQuaternion(e);console.log("START",this.clip.name,Ze.toDegrees(t.y),this.root.position.z)}}getClipRotationOffset(){return ir.clipOffsetRotation[this.cacheId]}handlePosition(i,e){if(e){const t=this.root;V_&&t.add(new yo),ir.lastObjPosition[this.cacheId]||(ir.lastObjPosition[this.cacheId]=this.root.position.clone());const n=new S,r=new S;this.positionWrapper=new e4(e,(s,o)=>{const a=this.action.getEffectiveWeight();return V_&&t.position.length()>8&&t.position.set(0,t.position.y,0),s>this._prevTime&&(n.set(o[0],o[1],o[2]),n.sub(r),n.multiplyScalar(a),n.applyQuaternion(this.getClipRotationOffset()),n.applyQuaternion(t.quaternion),this.positionChange.copy(n)),r.fromArray(o),this._prevTime=s,o[0]=0,o[1]=0,o[2]=0,o})}}handleRotation(i,e){if(e){if(V_){const s=e.values,o=new Fi().setFromQuaternion(new Me(s[0],s[1],s[2],s[3]));console.log(i.name,e.name,"FIRST ROTATION IN TRACK",Ze.toDegrees(o.y));const a=e.values.length-4,l=new Me().set(s[a],s[a+1],s[a+2],s[a+3]),c=new Fi().setFromQuaternion(l);console.log(i.name,e.name,"LAST ROTATION IN TRACK",Ze.toDegrees(c.y))}let t=0;const n=new Me,r=new Me;this.rotationWrapper=new e4(e,(s,o)=>(s>t&&(r.set(o[0],o[1],o[2],o[3]),n.invert(),r.multiply(n),this.rotationChange.copy(r)),n.fromArray(o),t=s,o[0]=0,o[1]=0,o[2]=0,o[3]=1,o))}}onBeforeUpdate(i){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(i){return!this.action||(i*=this.action.getEffectiveWeight(),i<=0)?!1:(this.positionChange.multiplyScalar(i),this.rotationChange.slerp(ir.identityQuaternion,1-i),!0)}};let mh=ir;h(mh,"lastObjPosition",{}),h(mh,"lastObjRotation",{}),h(mh,"firstKeyframeRotation",{}),h(mh,"spaceRotation",{}),h(mh,"effectiveSpaceRotation",{}),h(mh,"clipOffsetRotation",{}),h(mh,"identityQuaternion",new Me);class Jie{constructor(e){h(this,"controller"),h(this,"handler",[]),h(this,"root"),h(this,"basePosition",new S),h(this,"baseQuaternion",new Me),h(this,"baseRotation",new Fi),h(this,"summedPosition",new S),h(this,"summedRotation",new Me),this.controller=e}createClip(e,t,n){this.root=t,t&&"name"in t&&t.name;const r=this.findRootTrack(n,".position"),s=this.findRootTrack(n,".quaternion"),o=new mh(this.controller.context,t,n,r,s);this.handler.push(o);const a=e.clipAction(n);return o.action=a,a}onStart(e){for(const t of this.handler)t.onStart(e)}onBeforeUpdate(e){this.basePosition.copy(this.root.position),this.baseQuaternion.copy(this.root.quaternion);for(const t of this.handler)t.onBeforeUpdate(e)}onAfterUpdate(e){if(!(e<=0)){this.root.position.copy(this.basePosition),this.root.quaternion.copy(this.baseQuaternion),this.summedPosition.set(0,0,0),this.summedRotation.set(0,0,0,1);for(const t of this.handler)t.onAfterUpdate(e)&&(this.summedPosition.add(t.positionChange),this.summedRotation.multiply(t.rotationChange));this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation)}}findRootTrack(e,t){const n=e.tracks;if(!n)return null;for(const r of n)if(r.name.endsWith(t))return r;return null}}class Kie extends Fa{onSerialize(e,t){}onDeserialize(e,t){if(t.type===uo&&e?.__type==="AnimatorController")return new uo(e)}}new Kie(uo);var Zie=Object.defineProperty,$ie=Object.getOwnPropertyDescriptor,W_=(i,e,t,n)=>{for(var r=n>1?void 0:n?$ie(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&Zie(e,t,r),r};const Uo=ee("debuganimator");class Sr extends Ie{constructor(){super(...arguments),h(this,"applyRootMotion",!1),h(this,"hasRootMotion",!1),h(this,"keepAnimatorControllerStateOnDisable",!1),h(this,"_parametersAreDirty",!1),h(this,"_isDirty",!1),h(this,"_speed",1),h(this,"_normalizedStartOffset",0),h(this,"_animatorController",null),h(this,"_initializeWithRuntimeAnimatorController")}set runtimeAnimatorController(e){var t;this._animatorController&&this._animatorController.model===e||(e?e instanceof uo?(e.animator&&e.animator!==this&&(console.warn("AnimatorController can not be bound to multiple animators",(t=e.model)==null?void 0:t.name),e.model||console.error("AnimatorController has no model"),e=new uo(e.model)),this._animatorController=e,this._animatorController.bind(this)):(Uo&&console.log("Assign animator controller",e,this),this._animatorController=new uo(e),this.__didAwake&&this._animatorController.bind(this)):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}getCurrentStateInfo(){var e;return(e=this.runtimeAnimatorController)==null?void 0:e.getCurrentStateInfo()}get currentAction(){var e;return((e=this.runtimeAnimatorController)==null?void 0:e.currentAction)||null}get parametersAreDirty(){return this._parametersAreDirty}get isDirty(){return this._isDirty}Play(e,t=-1,n=Number.NEGATIVE_INFINITY,r=0){this.play(e,t,n,r)}play(e,t=-1,n=Number.NEGATIVE_INFINITY,r=0){var s;(s=this.runtimeAnimatorController)==null||s.play(e,t,n,r),this._isDirty=!0}Reset(){this.reset()}reset(){var e;(e=this._animatorController)==null||e.reset(),this._isDirty=!0}SetBool(e,t){this.setBool(e,t)}setBool(e,t){var n,r;Uo&&console.log("setBool",e,t),((n=this.runtimeAnimatorController)==null?void 0:n.getBool(e))!==t&&(this._parametersAreDirty=!0),(r=this.runtimeAnimatorController)==null||r.setBool(e,t)}GetBool(e){return this.getBool(e)}getBool(e){var t;const n=((t=this.runtimeAnimatorController)==null?void 0:t.getBool(e))??!1;return Uo&&console.log("getBool",e,n),n}toggleBool(e){this.setBool(e,!this.getBool(e))}SetFloat(e,t){this.setFloat(e,t)}setFloat(e,t){var n,r;((n=this.runtimeAnimatorController)==null?void 0:n.getFloat(e))!==t&&(this._parametersAreDirty=!0),Uo&&console.log("setFloat",e,t),(r=this.runtimeAnimatorController)==null||r.setFloat(e,t)}GetFloat(e){return this.getFloat(e)}getFloat(e){var t;const n=((t=this.runtimeAnimatorController)==null?void 0:t.getFloat(e))??-1;return Uo&&console.log("getFloat",e,n),n}SetInteger(e,t){this.setInteger(e,t)}setInteger(e,t){var n,r;((n=this.runtimeAnimatorController)==null?void 0:n.getInteger(e))!==t&&(this._parametersAreDirty=!0),Uo&&console.log("setInteger",e,t),(r=this.runtimeAnimatorController)==null||r.setInteger(e,t)}GetInteger(e){return this.getInteger(e)}getInteger(e){var t;const n=((t=this.runtimeAnimatorController)==null?void 0:t.getInteger(e))??-1;return Uo&&console.log("getInteger",e,n),n}SetTrigger(e){this.setTrigger(e)}setTrigger(e){var t;this._parametersAreDirty=!0,Uo&&console.log("setTrigger",e),(t=this.runtimeAnimatorController)==null||t.setTrigger(e)}ResetTrigger(e){this.resetTrigger(e)}resetTrigger(e){var t;this._parametersAreDirty=!0,Uo&&console.log("resetTrigger",e),(t=this.runtimeAnimatorController)==null||t.resetTrigger(e)}GetTrigger(e){this.getTrigger(e)}getTrigger(e){var t;const n=(t=this.runtimeAnimatorController)==null?void 0:t.getTrigger(e);return Uo&&console.log("getTrigger",e,n),n}IsInTransition(){return this.isInTransition()}isInTransition(){var e;return((e=this.runtimeAnimatorController)==null?void 0:e.isInTransition())??!1}SetSpeed(e){return this.setSpeed(e)}setSpeed(e){var t;e!==this._speed&&(Uo&&console.log("setSpeed",e),this._speed=e,((t=this._animatorController)==null?void 0:t.animator)==this&&this._animatorController.setSpeed(e))}set minMaxSpeed(e){var t;this._speed=Ze.lerp(e.x,e.y,Math.random()),((t=this._animatorController)==null?void 0:t.animator)==this&&this._animatorController.setSpeed(this._speed)}set minMaxOffsetNormalized(e){var t;this._normalizedStartOffset=Ze.lerp(e.x,e.y,Math.random()),((t=this.runtimeAnimatorController)==null?void 0:t.animator)==this&&(this.runtimeAnimatorController.normalizedStartOffset=this._normalizedStartOffset)}awake(){Uo&&console.log("ANIMATOR",this.name,this),this.gameObject&&this.initializeRuntimeAnimatorController()}initializeRuntimeAnimatorController(e=!1){const t=e||this.runtimeAnimatorController!==this._initializeWithRuntimeAnimatorController;if(this.runtimeAnimatorController&&t){const n=this.runtimeAnimatorController.clone();this._initializeWithRuntimeAnimatorController=n,n?(console.assert(this.runtimeAnimatorController!==n),this.runtimeAnimatorController=n,console.assert(this.runtimeAnimatorController===n),this.runtimeAnimatorController.bind(this),this.runtimeAnimatorController.setSpeed(this._speed),this.runtimeAnimatorController.normalizedStartOffset=this._normalizedStartOffset):console.warn("Could not clone animator controller",this.runtimeAnimatorController)}}onDisable(){var e;this.keepAnimatorControllerStateOnDisable||(e=this._animatorController)==null||e.reset()}onBeforeRender(){this._isDirty=!1,this._parametersAreDirty=!1,!qie(this.gameObject)&&this._animatorController&&this._animatorController.update(1)}}W_([x()],Sr.prototype,"applyRootMotion",2),W_([x()],Sr.prototype,"hasRootMotion",2),W_([x()],Sr.prototype,"keepAnimatorControllerStateOnDisable",2),W_([x()],Sr.prototype,"runtimeAnimatorController",1);const Zu=ee("debugusdzanimation"),JT=ee("debugusdzanimationserialization");class q_{constructor(e,t,n){h(this,"_start"),h(this,"ext"),h(this,"root"),h(this,"clip"),this.ext=e,this.root=t,this.clip=n}get start(){return this._start===void 0&&(this._start=this.ext.getStartTime01(this.root,this.clip)),this._start}get duration(){return this.clip.duration}}const t4=class{constructor(i,e,t){h(this,"clip"),h(this,"pos"),h(this,"rot"),h(this,"scale"),h(this,"root"),h(this,"target"),h(this,"duration",0),h(this,"useRootMotion",!1),this.root=i,this.target=e,this.clip=t,t?this.duration=t.duration:this.duration=t4.restPoseClipDuration;const n=re.getComponent(i,Sr);n&&(this.useRootMotion=n.applyRootMotion)}get frameRate(){return 60}addTrack(i){if(!this.clip){console.error("This is a rest clip but you're trying to add tracks to it \u2013 this is likely a bug");return}i.name.endsWith("position")&&(this.pos=i),i.name.endsWith("quaternion")&&(this.rot=i),i.name.endsWith("scale")&&(this.scale=i)}getFrames(){var i,e,t,n,r,s;return this.clip?Math.max(((e=(i=this.pos)==null?void 0:i.times)==null?void 0:e.length)??0,((n=(t=this.rot)==null?void 0:t.times)==null?void 0:n.length)??0,((s=(r=this.scale)==null?void 0:r.times)==null?void 0:s.length)??0):2}getDuration(){return this.duration}getSortedTimesArray(i=!0,e=!0,t=!0){var n,r,s;if(!this.clip)return[0,this.duration];const o=(n=this.pos)==null?void 0:n.times,a=(r=this.rot)==null?void 0:r.times,l=(s=this.scale)==null?void 0:s.times,c=[];if(i&&o)for(const u of o)c.push(u);if(e&&a)for(const u of a)c.push(u);if(t&&l)for(const u of l)c.push(u);return c.includes(0)||c.push(0),c.sort((u,d)=>u-d),[...new Set(c)]}*getValues(i,e=!0,t=!0,n=!0){var r,s,o;const a=new S,l=new Me,c=new S(1,1,1),u=this.target,d=e?(r=this.pos)==null?void 0:r.createInterpolant():void 0,p=t?(s=this.rot)==null?void 0:s.createInterpolant():void 0,f=n?(o=this.scale)==null?void 0:o.createInterpolant():void 0;d||a.set(u.position.x,u.position.y,u.position.z),p||l.set(u.quaternion.x,u.quaternion.y,u.quaternion.z,u.quaternion.w),f||c.set(u.scale.x,u.scale.y,u.scale.z);for(let m=0;m<i.length;m++){const A=i[m];if(d){const v=d.evaluate(A);a.set(v[0],v[1],v[2])}if(p){const v=p.evaluate(A);l.set(v[0],v[1],v[2],v[3])}if(f){const v=f.evaluate(A);c.set(v[0],v[1],v[2])}if(this.useRootMotion&&u===this.root){const v=new Ce;v.compose(a,l,c),v.multiply(u.matrix),v.decompose(a,l,c)}yield{time:A,translation:a,rotation:l,scale:c,index:m}}}};let Xr=t4;h(Xr,"animationDurationPadding",1/60),h(Xr,"restPoseClipDuration",1/60);class Sv{constructor(e){h(this,"dict",new Map),h(this,"rootTargetMap",new Map),h(this,"rootAndClipToRegisteredAnimationMap",new Map),h(this,"rootToRegisteredClipCount",new Map),h(this,"serializers",[]),h(this,"injectRestPoses",!1),h(this,"injectImplicitBehaviours",!1),this.injectRestPoses=e,this.injectImplicitBehaviours=e}get extensionName(){return"animation"}getStartTimeCode(){return!this.injectRestPoses||this.rootAndClipToRegisteredAnimationMap.size===0?0:(Xr.restPoseClipDuration+Xr.animationDurationPadding)*60}getEndTimeCode(){let e=0;for(const[t,n]of this.rootAndClipToRegisteredAnimationMap){const r=n.start+n.duration;r>e&&(e=r)}return e*60}getClipCount(e){let t=this.rootToRegisteredClipCount.get(e);return this.injectRestPoses&&(t=t?t-1:0),t??0}getStartTime01(e,t){const n=this.rootTargetMap.get(e);if(!n)return 0;const r=this.dict.get(n[0]);if(!r)return console.error("Trying to get start time for root that has no animation data",e,t,...this.dict),0;let s=0;for(let o=0;o<r.length&&r[o].clip!==t;o++)s+=r[o].getDuration()+Xr.animationDurationPadding;return s}registerAnimation(e,t){if(!t||!e)return null;this.rootTargetMap.has(e)||this.rootTargetMap.set(e,[]);const n=e.uuid+t.uuid;if(this.rootAndClipToRegisteredAnimationMap.has(n))return this.rootAndClipToRegisteredAnimationMap.get(n);Zu&&console.log("registerAnimation",e,t);const r=this.injectRestPoses?1:0,s=this.rootToRegisteredClipCount.get(e)??r,o=this.rootTargetMap.get(e),a=new Set(o);if(t.tracks)for(const c of t.tracks){const u=Qt.parseTrackName(c.name),d=Qt.findNode(e,u.nodeName);if(!d){console.warn("no object found for track",c.name,"using "+e.name+" instead");continue}this.dict.has(d)||this.dict.set(d,[]);const p=this.dict.get(d);if(!p){console.warn("no transform data found for target ",d,"at slot "+s+", this is likely a bug");continue}if(a.delete(d),this.injectRestPoses&&!p[0]){const m=new Xr(null,d,void 0);p[0]=m}let f=p[s];f||(f=new Xr(e,d,t),p[s]=f),f.addTrack(c),o!=null&&o.includes(d)||o==null||o.push(d)}for(const c of a){const u=this.dict.get(c);if(!u)continue;if(this.injectRestPoses&&!u[0]){const p=new Xr(null,c,void 0);u[0]=p}let d=u[s];d||(Zu&&console.log("Adding padding clip for ",c,t,"at slot",s),d=new Xr(e,c,t),u[s]=d)}const l=new q_(this,e,t);return this.rootAndClipToRegisteredAnimationMap.set(n,l),this.rootToRegisteredClipCount.set(e,s+1),l}onAfterHierarchy(e){Zu&&console.log("Animation clips per animation target node",this.dict)}onAfterBuildDocument(e){var t,n;for(const r of this.serializers){const s=(t=r.model)==null?void 0:t.parent,o=s?.isDynamic===!0;JT&&console.log(o,(n=r.model)==null?void 0:n.parent),o&&r.registerCallback(s)}}onExportObject(e,t,n){re.foreachComponent(e,s=>{const o=s;typeof o.createAnimation=="function"&&o.createAnimation(this,t,n)},!1);const r=new ene(e,this.dict);this.serializers.push(r),r.registerCallback(t)}}class ene{constructor(e,t){h(this,"object"),h(this,"dict"),h(this,"model"),h(this,"callback"),this.object=e,this.dict=t}registerCallback(e){this.model&&this.callback&&this.model.removeEventListener("serialize",this.callback),this.callback||(this.callback=this.onSerialize.bind(this)),JT&&console.log("REPARENT",e),this.model=e,this.model.addEventListener("serialize",this.callback)}skinnedMeshExport(e,t){var n;const r=this.model,s=this.dict;if(r&&r.skinnedMesh){let o=function(M){const D=[];for(const[C,P]of M){let G=`${C} : [`;const Q=[];for(const k of P)Q.push(`(${er(k.x)}, ${er(k.y)}, ${er(k.z)})`);G=G.concat(Q.join(", ")),G=G.concat("],"),D.push(G)}return D},a=function(M){const D=[];for(const[C,P]of M){let G=`${C} : [`;const Q=[];for(const k of P)Q.push(`(${er(k.w)}, ${er(k.x)}, ${er(k.y)}, ${er(k.z)})`);G=G.concat(Q.join(", ")),G=G.concat("],"),D.push(G)}return D},l=function(M){let D,C=!0;const P=new Map;for(const[Q,k]of M){D===void 0&&(D=k.length),D!==k.length&&(C=!1);let W=0;for(const U of k)W++,U||(P.has(Q)||P.set(Q,[]),P.get(Q).push(W))}Zu&&console.log("Bone count: ",M.size,"TransformData entries per bone: ",D,"Undefined bone entries: ",P),console.assert(C,"All bones should have the same number of TransformData entries",M),console.assert(P.size===0,"All TransformData entries should be set",P);const G=[];for(const[Q,k]of M){const W=new Array;let U=0;for(let F=0;F<k.length;F++)W.push(U),U+=k[F].getDuration()+Xr.animationDurationPadding;for(let F=0;F<k.length;F++){const z=k[F],Z=W[F];G.length<=F&&G.push({pos:[],rot:[],scale:[],timeOffset:Z});const K=G[F];K.pos.push(...z.getSortedTimesArray(!0,!1,!1)),K.rot.push(...z.getSortedTimesArray(!1,!0,!1)),K.scale.push(...z.getSortedTimesArray(!1,!1,!0))}}for(const Q of G)Q.pos.sort((k,W)=>k-W),Q.rot.sort((k,W)=>k-W),Q.scale.sort((k,W)=>k-W),Q.pos=[...new Set(Q.pos)],Q.rot=[...new Set(Q.rot)],Q.scale=[...new Set(Q.scale)];return G},c=function(M,D,C){const P=new Map,G=new Map,Q=new Map,k=D.length;for(const W of C){const U=M.get(W);let F;U?console.assert(U.length===k,"We should have the same number of TransformData entries for each bone",U,D):F=new Xr(null,W,void 0);for(let z=0;z<k;z++){const Z=U?U[z]:F,K=D[z];for(const{time:se,translation:Ae}of Z.getValues(K.pos,!0,!1,!1)){const Re=(se+K.timeOffset)*60;P.has(Re)||P.set(Re,new Array),P.get(Re).push(Ae.clone())}for(const{time:se,rotation:Ae}of Z.getValues(K.rot,!1,!0,!1)){const Re=(se+K.timeOffset)*60;G.has(Re)||G.set(Re,new Array),G.get(Re).push(Ae.clone())}for(const{time:se,scale:Ae}of Z.getValues(K.scale,!1,!1,!0)){const Re=(se+K.timeOffset)*60;Q.has(Re)||Q.set(Re,new Array),Q.get(Re).push(Ae.clone())}}}return{position:P.size==0?void 0:P,quaternion:G.size==0?void 0:G,scale:Q.size==0?void 0:Q}},u=function(M){const D=[];for(const C of M)D.push(`(${er(C.x)}, ${er(C.y)}, ${er(C.z)})`);return D.join(", ")},d=function(M){const D=[];for(const C of M)D.push(`(${er(C.w)}, ${er(C.x)}, ${er(C.y)}, ${er(C.z)})`);return D.join(", ")},p=function(M){const D=new Map;if(Zu){const C=new Array;for(const[P,G]of s)C.push(P.uuid+": "+G.length+" "+G.map(Q=>{var k;return(k=Q.clip)==null?void 0:k.uuid.substring(0,6)}).join(" "));console.log(`getPerBoneTransformData
5480
5480
  `+C.join(`
5481
- `))}for(const C of M){const P=s.get(C);P&&D.set(C,P)}return D},f=function(M){const D=p(M),C=l(D);return c(D,C,M)};const m=r.skinnedMesh.skeleton,A=new Array;for(const M in m.bones){const D=m.bones[M],C=m.boneInverses[M];A.push({bone:D,inverse:C})}for(const M of vN(m.bones))A.push({bone:M,inverse:M.matrixWorld.clone().invert()});const v=A[0].bone.parent;v||console.error("No bone parent found for skinned mesh during USDZ export",r.skinnedMesh),A.sort((M,D)=>Yp(M.bone,v)>Yp(D.bone,v)?1:-1);const g=[],y=[],b=[],_=[];for(const{bone:M}of A)g.push(M.matrix.clone()),y.push(M.position),b.push(M.quaternion),_.push(M.scale);const E=A.map(M=>'"'+Yp(M.bone,v)+'"').join(", "),I=A.map(M=>Jp(M.inverse.clone().invert())).join(", ");e.beginBlock('def Skeleton "Rig"'),e.appendLine(`uniform matrix4d[] bindTransforms = [${I}]`),e.appendLine(`uniform token[] joints = [${E}]`),e.appendLine('uniform token purpose = "guide"'),e.appendLine(`uniform matrix4d[] restTransforms = [${g.map(M=>Jp(M)).join(", ")}]`),e.appendLine(`matrix4d xformOp:transform = ${Jp(new Ce)}`),e.appendLine('uniform token[] xformOpOrder = ["xformOp:transform"]');const T=f(A.map(M=>M.bone));if(Zu){let M=1e7,D=0;for(const C of((n=T.position)==null?void 0:n.keys())??[])M=Math.min(M,C),D=Math.max(D,C);console.log("Time samples",M,D,T)}if(e.beginBlock('def SkelAnimation "_anim"'),e.appendLine(`uniform token[] joints = [${E}]`),e.appendLine(`quatf[] rotations = [${d(b)}]`),T&&T.quaternion){e.beginBlock("quatf[] rotations.timeSamples = {","");const M=a(T.quaternion);for(const D of M)e.appendLine(D);e.closeBlock()}if(e.appendLine(`half3[] scales = [${u(_)}]`),T&&T.scale){e.beginBlock("half3[] scales.timeSamples = {","");const M=o(T.scale);for(const D of M)e.appendLine(D);e.closeBlock()}if(e.appendLine(`float3[] translations = [${u(y)}]`),T&&T.position){e.beginBlock("float3[] translations.timeSamples = {","");const M=o(T.position);for(const D of M)e.appendLine(D);e.closeBlock()}e.closeBlock(),e.closeBlock()}}onSerialize(e,t){var n;if(!this.model)return;const r=this.dict.get(this.object);if(r)for(let u=0;u<r.length;u++)r[u]===void 0&&(r[u]=new Xr(null,this.object,void 0));this.skinnedMeshExport(e,t);const s=this.object,o=this.dict.get(s);if(!o||s.isSkinnedMesh)return;JT&&console.log("SERIALIZE",this.model.name,this.object.type,o);const a=new Ce;e.appendLine("matrix4d xformOp:transform.timeSamples = {"),e.indent++;const l=new Array;let c=0;for(let u=0;u<o.length;u++){if(l.push(c),o[u]===void 0){console.error("Got an undefined transform data, this is likely a bug.",s,o);continue}c+=o[u].getDuration()+Xr.animationDurationPadding}for(let u=0;u<o.length;u++){const d=o[u];if(!d)continue;const p=l[u];{const f=d.getSortedTimesArray();if(!f||f.length===0){console.error("got an animated object but no time values?",s,d);continue}if(Zu){const m=((n=d.clip)==null?void 0:n.name)??"rest",A=d.getDuration();console.log("Write .timeSamples:",m,p,A,o),e.appendLine("# "+m+": start="+(p*d.frameRate).toFixed(3)+", length="+(A*d.frameRate).toFixed(3)+", frames="+d.getFrames())}for(const{time:m,translation:A,rotation:v,scale:g}of d.getValues(f)){a.compose(A,v,g);const y=`${(p+m)*d.frameRate}: ${Jp(a)},`;e.appendLine(y)}}}e.indent--,e.appendLine("}")}}var tne=Object.defineProperty,ine=Object.getOwnPropertyDescriptor,i4=(i,e,t,n)=>{for(var r=n>1?void 0:n?ine(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&tne(e,t,r),r};const n4=ee("debugpost");class Bt{constructor(e){h(this,"_active",!0),h(this,"_value"),h(this,"_valueRaw"),h(this,"_defaultValue"),h(this,"valueProcessor"),h(this,"onValueChanged"),this._value=e,this._defaultValue=e,this._valueRaw=e}get overrideState(){return this._active}set overrideState(e){if(this._active===e)return;this._active=e;const t=e?this._valueRaw:this._defaultValue;this.processValue(t,!0)}get value(){return this._valueRaw}set value(e){this.processValue(e,!1)}set defaultValue(e){this._defaultValue=e}__init(){this.processValue(this._valueRaw,!0)}processValue(e,t){if(e==null||!t&&this.testIfValueChanged(e)===!1)return;const n=this._value;if(n4){let r=!0;if(typeof n=="number"&&typeof e=="number"){const s=n?.toFixed(4),o=e?.toFixed(4);s!=o?r=!0:r=!1}r&&console.log("VolumeParameter: value changed from",n,"to",e)}!this._active&&this._defaultValue!==void 0?(this._value=this._defaultValue,e=this._defaultValue,this._valueRaw=e):(this._valueRaw=e,this._active&&this.valueProcessor&&(e=this.valueProcessor(e)),this._value=e),this.onValueChanged?this.onValueChanged(e,n,this):n4&&console.log("VolumeParameter: onValueChanged not set")}testIfValueChanged(e){return this._valueRaw!==e}}i4([x()],Bt.prototype,"overrideState",1),i4([x()],Bt.prototype,"value",1);var nne=Object.defineProperty,rne=Object.getOwnPropertyDescriptor,sne=(i,e,t,n)=>{for(var r=n>1?void 0:n?rne(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&nne(e,t,r),r};const one=ee("debugpost");class Yr extends Ie{constructor(e=void 0){if(super(),h(this,"active",!0),h(this,"_result"),h(this,"_didCreateVolumeParameters",!1),e){this.ensureVolumeParameters();for(const t of Object.keys(e)){const n=e[t],r=this[t];r instanceof Bt&&(r.value=n)}}}onEnable(){this.__internalDidAwakeAndStart&&(this.active=!0)}onDisable(){this.active=!1}init(){}apply(){var e;return this.ensureVolumeParameters(),this._result||(this._result=(e=this.onCreateEffect)==null?void 0:e.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){one&&console.warn("DISPOSE",this),this._result&&(Array.isArray(this._result)?this._result.forEach(e=>e.dispose()):this._result.dispose()),this._result=void 0}initParameters(){const e=Object.keys(this);for(const t of e){const n=this[t];n instanceof Bt&&n.__init()}}onAfterDeserialize(e,t){if(typeof e=="object"){const n=this.$serializedTypes;if(n){for(const r of Object.keys(n))if(n[r]===Bt){const s=e[r];if(s!==void 0){const o=this[r];o.value=s}}}}}onEditorModification(e){const t=e.propertyName;if(this[t]instanceof Bt){const n=e.value;return this[t].value=n,!0}}ensureVolumeParameters(){if(this._didCreateVolumeParameters)return;this._didCreateVolumeParameters=!0;const e=this.$serializedTypes;if(e)for(const t of Object.keys(e))e[t]===Bt&&(this[t]||(this[t]=new Bt))}}sne([x()],Yr.prototype,"active",2);var ane=Object.defineProperty,lne=Object.getOwnPropertyDescriptor,cne=(i,e,t,n)=>{for(var r=n>1?void 0:n?lne(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&ane(e,t,r),r};const hne=ee("debugpost"),KT={};function Fo(i,e){KT[i]=e}function une(i){return i.__type in KT?KT[i.__type]:(hne&&i.__type&&console.warn("Unknown postprocessing type",i.__type,i),Yr)}class Cv{constructor(){h(this,"components",[])}init(){var e;(e=this.components)==null||e.forEach(t=>t.init())}}cne([Zp([i=>une(i),Yr])],Cv.prototype,"components",2);var dne=Object.defineProperty,pne=Object.getOwnPropertyDescriptor,fne=(i,e,t,n)=>{for(var r=n>1?void 0:n?pne(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&dne(e,t,r),r};class Ev extends Yr{constructor(){super(...arguments),h(this,"preset")}get typeName(){return"Antialiasing"}onCreateEffect(){const e=new IL({preset:Pp.HIGH,edgeDetectionMode:FE.DEPTH});return this.preset.onValueChanged=t=>{e.applyPreset(t)},e}}fne([x(Bt)],Ev.prototype,"preset",2),Fo("Antialiasing",Ev);const mne=ee("debugusdz");class zh{constructor(){h(this,"files",new Array)}static getName(e){var t;const n=e.split(".").pop();let r=(t=e.split(".").slice(0,-1).join(".").split("/").pop())==null?void 0:t.replace(".","_");return r||(r="Audio_"+Math.random().toString(36).substring(2,15)),Jl(r)+"."+n}get extensionName(){return"Audio"}onExportObject(e,t,n){const r=re.getComponents(e,en);if(r.length)for(const s of r){if(!s.clip||typeof s.clip!="string"||!s.playOnAwake)continue;const o=s.clip.split("/").pop()||"Audio",a=zh.getName(s.clip),l=Jl(a);this.files.some(c=>c.path===s.clip)||this.files.push({path:s.clip,name:a}),n.quickLookCompatible||t.addEventListener("serialize",(c,u)=>{c.appendLine(),c.beginBlock(`def SpatialAudio "${l}"`,"(",!1),c.appendLine(`displayName = "${o}"`),c.closeBlock(")"),c.beginBlock(),c.appendLine(`uniform asset filePath = @audio/${a}@`),c.appendLine(`uniform token auralMode = "${s.spatialBlend>0?"spatial":"nonSpatial"}"`),c.appendLine(`uniform token playbackMode = "${s.loop?"loopFromStage":"onceFromStart"}"`),c.appendLine(`uniform float gain = ${s.volume}`),c.closeBlock()})}}async onAfterSerialize(e){for(const t of this.files){const n="audio/"+t.name;if(e.files[n]){mne&&console.warn("Audio file with name "+n+" already exists in the context. Skipping.");continue}const r=await(await(await fetch(t.path)).blob()).arrayBuffer(),s=new Uint8Array(r);e.files[n]=s}}}const $u=ee("debugautosync"),ZT=Symbol("syncerId");class gne{constructor(){h(this,"_syncers",{})}getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];const t=new vne(e);return t[ZT]=e.guid,this._syncers[t[ZT]]=t,t}removeSyncer(e){delete this._syncers[e[ZT]]}}const $T=new gne;class vne{constructor(e){h(this,"comp"),h(this,"hasChanges",!1),h(this,"changedProperties",{}),h(this,"data",{}),h(this,"_boundEvent"),h(this,"_handleReceivingMethod"),h(this,"_isReceiving",!1),h(this,"_isInit",!1),this.comp=e}get networkingKey(){return this.comp.guid}init(e){if(this._isInit)return;this._isInit=!0,this.comp=e,this._boundEvent=this.onHandleSending.bind(this),this.comp.context.post_render_callbacks.push(this._boundEvent),this._handleReceivingMethod=this.onHandleReceiving.bind(this),this.comp.context.connection.beginListen(this.networkingKey,this._handleReceivingMethod);const t=this.comp.context.connection.tryGetState(this.comp.guid);t&&this.onHandleReceiving(t)}destroy(){this._isInit&&(this._boundEvent&&this.comp.context.post_render_callbacks.splice(this.comp.context.post_render_callbacks.indexOf(this._boundEvent),1),this._handleReceivingMethod&&this.comp.context.connection.stopListen(this.networkingKey,this._handleReceivingMethod),this.comp=null,this._isInit=!1)}notifyChanged(e,t){this._isReceiving||($u&&console.log("Property changed: "+e,t),this.hasChanges=!0,this.changedProperties[e]=t)}onHandleSending(){if(!this.hasChanges)return;this.hasChanges=!1;const e=this.comp.context.connection;if(!e||!e.isConnected){for(const t in this.changedProperties)delete this.changedProperties[t];return}for(const t in this.data)delete this.data[t];this.data.guid=this.comp.guid;for(const t in this.changedProperties){const n=this.changedProperties[t];delete this.changedProperties[t],this.data[t]=n}e.send(this.networkingKey,this.data)}onHandleReceiving(e){if($u&&console.log("RECEIVE",this.comp.name,this.comp.guid,e),!this._isInit||!this.comp)return;const t=e.guid;if(!(t&&t!==this.comp.guid)){$u&&console.log("RECEIVED",this.comp.name,this.comp.guid,e);try{this._isReceiving=!0;for(const n in e){if(n==="guid")continue;const r=e[n];this.comp[n]=r,$u&&console.log("SET",n,r)}}catch(n){console.error(n)}finally{this._isReceiving=!1}}}}function Ane(i,e){let t=e!==i;return!t&&i&&e&&(Array.isArray(i)&&Array.isArray(e)||typeof i=="object"&&typeof e=="object")&&(t=!0),t}const Mv=Symbol("AutoSyncHandler");function yne(i){if(i[Mv])return i[Mv];const e=$T.getOrCreateSyncer(i);return e?.init(i),i[Mv]=e,e}function bne(i){const e=i[Mv];e&&($T.removeSyncer(e),e.destroy(),delete i[Mv])}const eI=function(i){return function(e,t){var n;let r="";typeof t=="string"?r=t:r=t.name;let s=null,o;typeof i=="string"?o=e[i]:typeof i=="function"&&(o=i);const a=e,l=a.__internalAwake;if(typeof l!="function"){($u||pt())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+((n=e?.constructor)==null?void 0:n.name)+'" is not supported',e);return}$u&&console.log(r);const c=Symbol(r);a.__internalAwake=function(){if(this[c]!==void 0)return;this[c]=this[r],s=$T.getOrCreateSyncer(this);const d=Object.getOwnPropertyDescriptor(this,r);if(d?.set===void 0){let p=!1;Object.defineProperty(this,r,{set:function(f){var m;const A=this[c];if(this[c]=f,p){pt()&&console.warn("Recursive call detected",r);return}p=!0;try{const v=Ane(f,A);$u&&console.log("SyncField assignment",r,"changed?",v,f),v&&o?.call(this,f,A)!==!1&&((m=yne(this))==null||m.notifyChanged(r,f))}finally{p=!1}},get:function(){return this[c]},configurable:!0,enumerable:!0})}s?.init(this),l.call(this)};const u=a.__internalDestroy;a.__internalDestroy=function(){bne(this),u.call(this)}}};var _ne=Object.defineProperty,xne=Object.getOwnPropertyDescriptor,X_=(i,e,t,n)=>{for(var r=n>1?void 0:n?xne(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&_ne(e,t,r),r};const Ks=ee("debugplayersync");class lf extends Ie{constructor(){super(...arguments),h(this,"autoSync",!0),h(this,"asset"),h(this,"onPlayerSpawned"),h(this,"_localInstance"),h(this,"onJoinedRoom",()=>{Ks&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()})}awake(){this.watchTabVisible(),this.onPlayerSpawned||(this.onPlayerSpawned=new Hn)}onEnable(){this.context.connection.beginListen(Jt.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(Jt.JoinedRoom,this.onJoinedRoom),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(Jt.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(Jt.JoinedRoom,this.onJoinedRoom)}async getInstance(){var e,t,n,r,s,o;if(this._localInstance)return this._localInstance;if(Ks&&console.log("PlayerSync.createInstance",(e=this.asset)==null?void 0:e.uri),!((t=this.asset)!=null&&t.asset)&&!((n=this.asset)!=null&&n.uri))return console.error('PlayerSync: can not create an instance because "asset" is not set!'),null;this._localInstance=(r=this.asset)==null?void 0:r.instantiateSynced({parent:this.gameObject},!0);const a=await this._localInstance;if(a){const l=re.getComponent(a,No);l?(l.owner=this.context.connection.connectionId,(s=this.onPlayerSpawned)==null||s.invoke(a)):(this._localInstance=void 0,console.error("<strong>Failed finding PlayerState on "+((o=this.asset)==null?void 0:o.uri)+"</strong>: please make sure the asset has a PlayerState component!"),re.destroySynced(a))}else this._localInstance=void 0,console.warn("PlayerSync: failed instantiating asset!");return this._localInstance}destroyInstance(){var e;(e=this._localInstance)==null||e.then(t=>(Ks&&console.log("PlayerSync.destroyInstance",t),re.destroySynced(t))),this._localInstance=void 0}watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=No.all.length-1;t>=0;t--){const n=No.all[t];(!n.owner||!this.context.connection.userIsInRoom(n.owner))&&n.doDestroy()}})}}X_([x()],lf.prototype,"autoSync",2),X_([x(ni)],lf.prototype,"asset",2),X_([x(Hn)],lf.prototype,"onPlayerSpawned",2);var r4=(i=>(i.OwnerChanged="ownerChanged",i))(r4||{}),Tv;const Cr=(Tv=class extends Ie{constructor(){super(...arguments),h(this,"onOwnerChangeEvent",new Hn),h(this,"onFirstOwnerChangeEvent",new Hn),h(this,"hasOwner",!1),h(this,"owner"),h(this,"dontDestroy",!1),h(this,"onUserLeftRoom",i=>{if(i.userId===this.owner){Ks&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}})}static get all(){return Cr._all}static get local(){return Cr._local}static getFor(i){if(i instanceof ge)return re.getComponentInParent(i,Cr);if(i instanceof Ie)return re.getComponentInParent(i.gameObject,Cr)}static isLocalPlayer(i){const e=Cr.getFor(i);return e?.isLocalPlayer??!1}static addEventListener(i,e){return this._callbacks[i]||(this._callbacks[i]=[]),this._callbacks[i].push(e),e}static removeEventListener(i,e){if(!this._callbacks[i])return;const t=this._callbacks[i].indexOf(e);t>=0&&this._callbacks[i].splice(t,1)}static dispatchEvent(i,e){if(this._callbacks[i])for(const t of this._callbacks[i])t(e)}get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(i,e){var t,n;Ks&&console.log("PlayerSync.onOwnerChange",this,"newOwner",i,"oldOwner",e);const r=Cr._local.indexOf(this);r>=0&&Cr._local.splice(r,1);const s={playerState:this,oldValue:e,newValue:i};if(this.hasOwner||(this.hasOwner=!0,(t=this.onFirstOwnerChangeEvent)==null||t.invoke(s)),(n=this.onOwnerChangeEvent)==null||n.invoke(s),this.owner===this.context.connection.connectionId){Cr._local.push(this);const a=new CustomEvent("local-owner-changed",{detail:s});this.dispatchEvent(a)}const o=new CustomEvent("owner-changed",{detail:s});this.dispatchEvent(o),Cr.dispatchEvent("ownerChanged",o)}awake(){Cr.all.push(this),Ks&&console.log("Registered new PlayerState",this.guid,Cr.all.length-1,Cr.all),this.context.connection.beginListen(Jt.UserLeftRoom,this.onUserLeftRoom)}async start(){Ks&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await na(300),this.context.connection.userIsInRoom(this.owner)==!1&&(Ks&&console.log(`PlayerSync.start \u2192 doDestroy "${this.name}" because user "${this.owner}" is not in room anymore...`,"Currently in room:",...this.context.connection.usersInRoom()),this.doDestroy())):this.owner||(Ks&&console.warn("PlayerState.start \u2192 owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?Ks&&console.warn("PlayerState.start \u2192 owner is still undefined but dontDestroy is set to true",this.name):(Ks&&console.warn(`PlayerState.start \u2192 owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):Ks&&console.log("PlayerState.start \u2192 owner is assigned",this.owner)},2e3))}doDestroy(){Ks&&console.log("PlayerSync.doDestroy \u2192 syncDestroy",this.name),g_(this.gameObject,this.context.connection)}onDestroy(){if(this.context.connection.stopListen(Jt.UserLeftRoom,this.onUserLeftRoom),Cr.all.splice(Cr.all.indexOf(this),1),this.isLocalPlayer){const i=Cr._local.indexOf(this);i>=0&&Cr._local.splice(i,1)}}},h(Tv,"_all",[]),h(Tv,"_local",[]),h(Tv,"_callbacks",{}),Tv);let No=Cr;X_([eI(No.prototype.onOwnerChange)],No.prototype,"owner",2);const wne=ee("debugavatar"),Xa=class extends Ie{constructor(){super(...arguments),h(this,"connectionId"),h(this,"avatar")}static getAvatar(i){return i>=0&&i<Xa.instances.length?Xa.instances[i]:null}static onAvatarMarkerCreated(i){return Xa._onNewAvatarMarkerAdded.push(i),i}static onAvatarMarkerDestroyed(i){return Xa._onAvatarMarkerDestroyed.push(i),i}awake(){Xa.instances.push(this),wne&&console.log(this);for(const i of Xa._onNewAvatarMarkerAdded)i({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){Xa.instances.splice(Xa.instances.indexOf(this),1);for(const i of Xa._onAvatarMarkerDestroyed)i({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}};let Er=Xa;h(Er,"instances",[]),h(Er,"_onNewAvatarMarkerAdded",[]),h(Er,"_onAvatarMarkerDestroyed",[]);var Sne=Object.defineProperty,Cne=Object.getOwnPropertyDescriptor,Ene=(i,e,t,n)=>{for(var r=n>1?void 0:n?Cne(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&Sne(e,t,r),r};const cf=ee("debugxrflags"),s4=ee("disablexrflags");s4&&console.warn("XRFlags are disabled");var Ya=(i=>(i[i.Never=0]="Never",i[i.Browser=1]="Browser",i[i.AR=2]="AR",i[i.VR=4]="VR",i[i.FirstPerson=8]="FirstPerson",i[i.ThirdPerson=16]="ThirdPerson",i[i.All=4294967295]="All",i))(Ya||{});const o4=class{constructor(){h(this,"Mask",17)}Has(i){return(this.Mask&i)!==0}Set(i){cf&&console.warn("Set XR flag state to",i),this.Mask=i,Zs.Apply()}Enable(i){this.Mask|=i,Zs.Apply()}Disable(i){this.Mask&=~i,Zs.Apply()}Toggle(i){this.Mask^=i,Zs.Apply()}EnableAll(){this.Mask=-1,Zs.Apply()}DisableAll(){this.Mask=0,Zs.Apply()}};let ys=o4;h(ys,"Global",new o4);var Iv;const ic=(Iv=class extends Ie{constructor(){super(...arguments),h(this,"visibleIn")}static Apply(){for(const i of this.registry)i.UpdateVisible(ys.Global)}awake(){ic.registry.push(this)}onEnable(){ic.firstApply?this.UpdateVisible(ys.Global):(ic.firstApply=!0,ic.Apply())}onDestroy(){const i=ic.registry.indexOf(this);i>=0&&ic.registry.splice(i,1)}get isOn(){return this.gameObject.visible}UpdateVisible(i=null){if(s4)return;let e;const t=i;if(t&&typeof t=="number"&&(console.assert(typeof t=="number","XRFlag.UpdateVisible: state must be a number",t),cf&&console.log(t),ic.buffer.Mask=t,i=ic.buffer),i instanceof ys?(cf&&console.warn(this.name,"use passed in mask",i.Mask,this.visibleIn),e=i.Has(this.visibleIn)):(cf&&console.log(this.name,"use global mask"),ys.Global.Has(this.visibleIn)),e!==void 0)if(e)cf&&console.log(this.name,"is visible",this.gameObject.uuid),re.setActive(this.gameObject,!0);else{if(cf&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},h(Iv,"registry",[]),h(Iv,"firstApply"),h(Iv,"buffer",new ys),Iv);let Zs=ic;Ene([x()],Zs.prototype,"visibleIn",2);var Mne=Object.defineProperty,Tne=Object.getOwnPropertyDescriptor,tI=(i,e,t,n)=>{for(var r=n>1?void 0:n?Tne(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&Mne(e,t,r),r};const Rv=ee("debugwebxr"),a4=new Me().setFromAxisAngle(new S(0,1,0),Math.PI);class ed extends Ie{constructor(){super(...arguments),h(this,"head"),h(this,"leftHand"),h(this,"rightHand"),h(this,"_syncTransforms")}async onEnterXR(e){if(!this.activeAndEnabled)return;Rv&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const t=No.getFor(this);if(t!=null&&t.owner){const n=this.gameObject.addNewComponent(Er);n.avatar=this.gameObject,n.connectionId=t.owner}else this.context.connection.isConnected?console.error("No player state found for avatar",this):t&&!this.context.connection.isConnected&&(t.dontDestroy=!0)}onLeaveXR(e){const t=this.gameObject.getComponent(Er);t&&t.destroy()}onUpdateXR(e){var t,n;if(!this.activeAndEnabled)return;const r=No.isLocalPlayer(this);if(!r)return;const s=e.xr;if(s.rig&&s.rig.gameObject!==this.gameObject.parent&&(this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),this.gameObject.scale.set(1,1,1),s.rig.gameObject.add(this.gameObject)),this._syncTransforms&&r)for(const c of this._syncTransforms)c.fastMode=!0,c.isOwned()||c.requestOwnership();if(this.head&&this.context.mainCamera){const c=this.head.asset;if(c.position.copy(this.context.mainCamera.position),c.quaternion.copy(this.context.mainCamera.quaternion),c.quaternion.x*=-1,this.context.time.frameCount%10===0){const u=re.getComponentsInChildren(this.head.asset,Zs);for(const d of u)d.enabled=!1,d.gameObject.visible=!1}}const o=e.xr.leftController,a=(t=this.leftHand)==null?void 0:t.asset;o&&a&&(a.position.copy(o.gripPosition),a.quaternion.copy(o.gripQuaternion),a.quaternion.multiply(a4),a.visible=o.isTracking);const l=e.xr.rightController;if(l&&(n=this.rightHand)!=null&&n.asset){const c=this.rightHand.asset;c.position.copy(l.gripPosition),c.quaternion.copy(l.gripQuaternion),c.quaternion.multiply(a4),c.visible=l.isTracking}}onBeforeRender(){this.context.time.frame%10===0&&this.updateRemoteAvatarVisibility()}updateRemoteAvatarVisibility(){var e,t,n;if(this.context.connection.isConnected){const r=No.getFor(this);if(r&&r.isLocalPlayer==!1){const s=mt.getXRSync(this.context);if(s&&s.hasState(r.owner)){this.tryFindAvatarObjectsIfMissing();const o=(e=this.leftHand)==null?void 0:e.asset;o&&(o.visible=s?.isTracking(r.owner,"left")??!1);const a=(t=this.rightHand)==null?void 0:t.asset;a&&(a.visible=s?.isTracking(r.owner,"right")??!1)}if((n=this.head)!=null&&n.asset){const o=re.getComponentsInChildren(this.head.asset,Zs);for(const a of o)a.enabled=!1,a.gameObject.visible=!0}}}}tryFindAvatarObjectsIfMissing(){if(!this.head||!this.leftHand||!this.rightHand){const e={head:this.head,leftHand:this.leftHand,rightHand:this.rightHand};M3.tryFindAvatarObjects(this.gameObject,this.sourceId||"",e),e.head&&(this.head=e.head),e.leftHand&&(this.leftHand=e.leftHand),e.rightHand&&(this.rightHand=e.rightHand)}}async prepareAvatar(){if(this.tryFindAvatarObjectsIfMissing(),this.head)this.head instanceof ge&&(this.head=new ni("",this.sourceId,this.head));else{const e=new ge;e.name="Head";const t=Fg.createPrimitive(Uu.Cube);e.add(t),this.gameObject.add(e),this.head=new ni("",this.sourceId,e),Rv&&console.log("Create head",e)}if(this.rightHand)this.rightHand instanceof ge&&(this.rightHand=new ni("",this.sourceId,this.rightHand));else{const e=new ge;e.name="Right Hand",this.gameObject.add(e),this.rightHand=new ni("",this.sourceId,e),Rv&&console.log("Create right hand",e)}if(this.leftHand)this.leftHand instanceof ge&&(this.leftHand=new ni("",this.sourceId,this.leftHand));else{const e=new ge;e.name="Left Hand",this.gameObject.add(e),this.leftHand=new ni("",this.sourceId,e),Rv&&console.log("Create left hand",e)}await this.loadAvatarObjects(this.head,this.leftHand,this.rightHand),No.isLocalPlayer(this.gameObject)&&(this._syncTransforms=re.getComponentsInChildren(this.gameObject,uh))}async loadAvatarObjects(e,t,n){const r=e.loadAssetAsync(),s=t.loadAssetAsync(),o=n.loadAssetAsync(),a=new Array;r&&a.push(r),s&&a.push(s),o&&a.push(o);const l=await Jm(a);Rv&&console.log("Avatar loaded results:",l)}}tI([x(ni)],ed.prototype,"head",2),tI([x(ni)],ed.prototype,"leftHand",2),tI([x(ni)],ed.prototype,"rightHand",2);class Ja{static Add(e,t,n=null){if(t){for(const r of this.Pois)if(r.obj===t)return;this.Pois.push({obj:t,avatar:n}),this.LastChangeTime=e.time.time}}static Remove(e,t){var n;if(t){for(const r of this.Pois)if(r.obj===t){this.Pois.splice(this.Pois.indexOf(r),1),this.LastChangeTime=e?.time.time??((n=Lt.Current)==null?void 0:n.time.time);return}}}}h(Ja,"Pois",[]),h(Ja,"LastChangeTime",0);class Ine{constructor(){h(this,"guid"),h(this,"position",new S)}}class Pv extends Ie{constructor(){super(...arguments),h(this,"target",null),h(this,"avatar",null),h(this,"_model",null),h(this,"_targetModel",new Ine),h(this,"_currentTargetObject",null),h(this,"_lastUpdateTime",0),h(this,"_lookDuration",0),h(this,"_lastPoiChangedTime",0)}set controlledTarget(e){this.target=e;const t=q.get("MoveRandom");if(t&&this.target){const n=re.getComponent(this.target,t);n&&n.destroy()}}awake(){if(this.avatar=re.getComponentInParent(this.gameObject,Er),this.avatar){const e=re.getComponentInParent(this.gameObject,Er);this._model=new IM(this.context.connection,this.guid),e!=null&&e.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",e=>{var t;this.target&&e&&e.guid===((t=this.avatar)==null?void 0:t.guid)&&Qr(this.target,e.position)})}update(){var e;if((!this.context.connection.isConnected||(e=this._model)!=null&&e.hasOwnership)&&(Ja.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=Ja.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){const t=Rt(this._currentTargetObject);Qr(this.target,t),this.context.connection.isConnected&&this.avatar&&(this.context.connection.send("avatar-look-target-changed",this._targetModel),this._targetModel.guid=this.avatar.guid,this._targetModel.position.copy(t))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;const e=Ja.Pois;if(e.length>0){const t=e[Math.floor(Math.random()*e.length)];if(t&&t.obj){if(t.avatar&&t.avatar===this.avatar)return;this._currentTargetObject=t.obj}}}}}const hf=ee("debugnetworkingstreams");var Ka=(i=>(i.Connected="peer-user-connected",i.StreamReceived="receive-stream",i.StreamEnded="call-ended",i.Disconnected="peer-user-disconnected",i.UserJoined="user-joined",i))(Ka||{});class l4{constructor(e,t){h(this,"type","call-ended"),h(this,"userId"),h(this,"direction"),this.userId=e,this.direction=t}}class c4{constructor(e,t){h(this,"type","receive-stream"),h(this,"stream"),h(this,"target"),this.stream=e,this.target=t}}class Rne{constructor(e,t){h(this,"guid"),h(this,"peerId"),h(this,"dontSave",!0),this.guid=e.id,this.peerId=t}}var h4=(i=>(i.Incoming="incoming",i.Outgoing="outgoing",i))(h4||{});class Pne extends Jn{constructor(e,t,n){super(),h(this,"userId"),h(this,"direction"),h(this,"call"),h(this,"_stream",null),h(this,"_isDisposed",!1),this.userId=e,this.call=t,this.direction=n,this._stream=null,t.on("stream",r=>{if(hf&&console.log("Receive video",r.getAudioTracks(),r.getVideoTracks()),this._stream=r,n==="incoming"){const s=new c4(r,this);this.dispatchEvent(s)}}),t.on("close",()=>{this.dispatchEvent(new l4(e,n))})}get stream(){return this._stream}close(){this._isDisposed||(this._isDisposed=!0,this.call.close(),nc(this._stream))}get isOpen(){var e;return((e=this.call.peerConnection)==null?void 0:e.connectionState)==="connected"}get isOpening(){var e;return((e=this.call.peerConnection)==null?void 0:e.connectionState)==="connecting"}get isClosed(){return!this.isOpen}}const Bv=class extends Jn{constructor(i,e){super(),h(this,"id"),h(this,"context"),h(this,"_peer"),h(this,"_incomingCalls",[]),h(this,"_outgoingCalls",[]),h(this,"_enabled",!1),h(this,"_enabledPeer",!1),h(this,"onConnectRoomFn",this.onConnectRoom.bind(this)),h(this,"onPeerConnectFn",this.onPeerConnect.bind(this)),h(this,"onPeerReceiveCallFn",this.onPeerReceivingCall.bind(this)),this.context=i,this.id=e,this.setupPeer(),navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia}static getOrCreate(i,e){if(Bv.instances.has(e))return Bv.instances.get(e);const t=new Bv(i,e);return Bv.instances.set(e,t),t}getMyPeerId(){if(this.context.connection.connectionId)return this.getPeerIdFromUserId(this.context.connection.connectionId)}getPeerIdFromUserId(i){return this.id+"-"+i}getUserIdFromPeerId(i){return i.substring(this.id.length+1)}makeCall(i,e){var t;const n={metadata:{userId:this.context.connection.connectionId}},r=(t=this._peer)==null?void 0:t.call(i,e,n);if(r)return this.registerCall(r,"outgoing")}get peer(){return this._peer}enable(){this._enabled||(this._enabled=!0,this.context.connection.beginListen(Jt.JoinedRoom,this.onConnectRoomFn),this.subscribePeerEvents())}disable(){this._enabled&&(this._enabled=!1,this.context.connection.stopListen(Jt.JoinedRoom,this.onConnectRoomFn),this.unsubscribePeerEvents())}onConnectRoom(){this.setupPeer()}setupPeer(){if(this.context.connection.connectionId&&!this._enabledPeer){if(this._enabledPeer=!0,!this._peer){const i=this.getMyPeerId();i?this._peer=m3(i):console.error("Failed to setup peerjs because we dont have a connection id",this.context.connection.connectionId)}this._enabled&&this.subscribePeerEvents()}}subscribePeerEvents(){this._peer&&(this._peer.on("open",this.onPeerConnectFn),this._peer.on("call",this.onPeerReceiveCallFn))}unsubscribePeerEvents(){this._peer&&(this._peer.off("open",this.onPeerConnectFn),this._peer.off("call",this.onPeerReceiveCallFn))}onPeerConnect(i){hf&&console.log("Peer connected as",i),this.context.connection.send("peer-user-connected",new Rne(this,i))}onPeerReceivingCall(i){i.answer(),this.registerCall(i,"incoming")}registerCall(i,e){const t=i.metadata;(!t||!t.userId)&&console.error("Missing call metadata",i);const n=t.userId;e==="incoming"&&hf?console.log("Receive call from",i.metadata):hf&&console.log("Make call to",i.metadata);const r=e==="incoming"?this._incomingCalls:this._outgoingCalls,s=new Pne(n,i,e);return r.push(s),i.on("error",o=>{console.error("Call error",o)}),i.on("close",()=>{hf&&console.log("Call ended",i.metadata),i.close();const o=r.indexOf(s);o!==-1&&r.splice(o,1)}),s.addEventListener("call-ended",o=>{this.dispatchEvent(o)}),e==="incoming"&&(s.addEventListener("receive-stream",o=>{this.dispatchEvent(o)}),i.on("stream",()=>{let o=0;const a=setInterval(()=>{const l=o===0;!s.isOpen&&l&&(o+=1,clearInterval(a),s.close())},2e3)})),s}};let Y_=Bv;h(Y_,"instances",new Map);class Z0 extends Jn{constructor(e,t){super(),h(this,"context"),h(this,"peer"),h(this,"_sendingStreams",new Map),h(this,"debug",!1),h(this,"onJoinedRoom",n=>{this.debug&&console.log(`${n.userId} joined room and I'm currently sending ${this._sendingStreams.size} streams`),this._sendingStreams.size>0&&this.updateSendingCalls()}),h(this,"onReceiveStream",n=>{this.debug&&console.log("RECEIVE STREAM",n),this.dispatchEvent({type:"receive-stream",target:this,stream:n.stream,userId:n.userId})}),h(this,"onCallEnded",n=>{this.dispatchEvent(n)}),h(this,"onUserConnected",n=>{if(this.peer.id===n.guid){this.debug&&console.log("USER CONNECTED",n.guid,n);const r=this._sendingStreams.keys().next().value;this.peer.makeCall(n.peerId,r)}}),h(this,"onUserLeft",n=>{this.stopCallsToUsersThatAreNotInTheRoomAnymore()}),this.context=e,this.peer=t,hf&&(this.debug=!0)}static create(e){const t=Y_.getOrCreate(e.context,e.context.connection.connectionId);return new Z0(e.context,t)}startSendingStream(e){this._sendingStreams.has(e)?console.warn("Received start sending stream with stream that is already being sent"):(this._sendingStreams.set(e,[]),this.updateSendingCalls())}stopSendingStream(e){if(e){const t=this._sendingStreams.get(e);if(t){this.debug&&console.log("Closing calls",t);for(const n of t)n.close()}this._sendingStreams.delete(e),t&&this.debug&&console.log("Currently sending",this._sendingStreams)}}enable(){this.peer.enable(),this.peer.addEventListener("receive-stream",this.onReceiveStream),this.peer.addEventListener("call-ended",this.onCallEnded),this.context.connection.beginListen("peer-user-connected",this.onUserConnected),this.context.connection.beginListen(Jt.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Jt.UserJoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Jt.UserLeftRoom,this.onUserLeft)}disable(){this.peer.disable(),this.peer.removeEventListener("receive-stream",this.onReceiveStream),this.peer.removeEventListener("call-ended",this.onCallEnded),this.context.connection.stopListen("peer-user-connected",this.onUserConnected),this.context.connection.stopListen(Jt.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Jt.UserJoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Jt.UserLeftRoom,this.onUserLeft)}updateSendingCalls(){var e;let t=!1;const n=this.context.connection.connectionId;for(const r of this._sendingStreams.keys()){const s=this._sendingStreams.get(r)||[];for(const o of this.context.connection.usersInRoom()){if(o===n)continue;const a=s.find(l=>l.userId===o);if(!a||((e=a.stream)==null?void 0:e.active)===!1){this.debug&&console.log("Starting call to",o,n);const l=this.peer.makeCall(this.peer.getPeerIdFromUserId(o),r);l&&(t=!0,s.push(l))}}this._sendingStreams.set(r,s)}this.stopCallsToUsersThatAreNotInTheRoomAnymore(),t&&this.debug&&console.log("Currently sending",this._sendingStreams)}stopCallsToUsersThatAreNotInTheRoomAnymore(){for(const e of this._sendingStreams.keys()){const t=this._sendingStreams.get(e);if(t)for(let n=t.length-1;n>=0;n--){const r=t[n];this.context.connection.userIsInRoom(r.userId)||(r.close(),t.splice(n,1))}}}}function nc(i){if(i&&i instanceof MediaStream)for(const e of i.getTracks())e.stop()}var Bne=Object.defineProperty,Dne=Object.getOwnPropertyDescriptor,u4=(i,e,t,n)=>{for(var r=n>1?void 0:n?Dne(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&Bne(e,t,r),r};const One="noVoip",kne=ee("debugvoip");class td extends Ie{constructor(){super(...arguments),h(this,"autoConnect",!1),h(this,"runInBackground",!0),h(this,"debug",!1),h(this,"_net"),h(this,"_outputStream",null),h(this,"onJoinedRoom",async()=>{await na(300),this.autoConnect&&!this.isSending&&this.connect()}),h(this,"_incomingStreams",new Map),h(this,"onReceiveStream",e=>{const t=e.target.userId,n=e.stream,r=this._incomingStreams.get(t);if(r)r.srcObject=n,r.setAttribute("autoplay","true");else{const s=new Audio;this._incomingStreams.set(t,s),s.setAttribute("autoplay","true"),s.srcObject=n}}),h(this,"onStreamEnded",e=>{const t=this._incomingStreams.get(e.userId);nc(t?.srcObject),this._incomingStreams.delete(e.userId)}),h(this,"onEnabledChanged",()=>{for(const e of this._incomingStreams){const t=e[1];t.muted=!this.enabled}}),h(this,"onVisibilityChanged",()=>{if(this.runInBackground)return;const e=document.visibilityState!=="visible";this.setMuted(e);for(const t of this._incomingStreams){const n=t[1];n.muted=e}})}awake(){kne&&(this.debug=!0),this.debug&&window.addEventListener("keydown",async e=>{e.key==="v"&&(console.log("MUTE?",!this.isMuted),this.setMuted(!this.isMuted))})}onEnable(){this._net||(this._net=Z0.create(this)),this._net.addEventListener(Ka.StreamReceived,this.onReceiveStream),this._net.addEventListener(Ka.StreamEnded,this.onStreamEnded),this._net.enable(),this.autoConnect&&(this.context.connection.isConnected?this.connect():this.context.connection.beginListen(Jt.JoinedRoom,this.onJoinedRoom)),this.onEnabledChanged(),window.addEventListener("visibilitychange",this.onVisibilityChanged)}onDisable(){var e;this._net.stopSendingStream(this._outputStream),this._net.removeEventListener(Ka.StreamReceived,this.onReceiveStream),this._net.removeEventListener(Ka.StreamEnded,this.onStreamEnded),(e=this._net)==null||e.disable(),this.context.connection.stopListen(Jt.JoinedRoom,this.onJoinedRoom),this.onEnabledChanged(),window.removeEventListener("visibilitychange",this.onVisibilityChanged)}get isSending(){return this._outputStream!=null&&this._outputStream.active}async connect(e){if(this.context.connection.isConnected){if(!await xC())return console.error("Cannot connect to voice chat - microphone permissions not granted"),!1}else return console.error("Cannot connect to voice chat - not connected to server"),!1;return this._net.stopSendingStream(this._outputStream),nc(this._outputStream),this._outputStream=await this.getAudioStream(e),this._outputStream?(this._net.startSendingStream(this._outputStream),!0):(await xC()?console.error("VOIP: Could not get audio stream - please make sure to connect an audio device and grant microphone permissions"):AE("Microphone permissions not granted: Please grant microphone permissions to use voice chat"),!1)}disconnect(){this._net.stopSendingStream(this._outputStream),nc(this._outputStream),this._outputStream=null}setMuted(e){var t;const n=(t=this._outputStream)==null?void 0:t.getAudioTracks();if(n)for(const r of n)r.enabled=!e}get isMuted(){var e;if(this._outputStream===null)return!1;const t=(e=this._outputStream)==null?void 0:e.getAudioTracks();if(t){for(const n of t)if(!n.enabled)return!0}return!1}getFrequency(e){return this.unsupported_getfrequency||(this.unsupported_getfrequency=!0,pt()&&Qi("VOIP: getFrequency is currently not supported"),console.warn("VOIP: getFrequency is currently not supported")),null}async getAudioStream(e){return navigator.mediaDevices.getUserMedia?await navigator.mediaDevices.getUserMedia({audio:e??!0,video:!1}).catch(t=>(console.warn("VOIP failed getting audio stream",t),null)):(console.error("No getDisplayMedia support"),null)}}u4([x()],td.prototype,"autoConnect",2),u4([x()],td.prototype,"runInBackground",2);var Lne=Object.defineProperty,Une=Object.getOwnPropertyDescriptor,d4=(i,e,t,n)=>{for(var r=n>1?void 0:n?Une(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&Lne(e,t,r),r};const Fne=ee("debugmouth");class Dv extends Ie{constructor(){super(...arguments),h(this,"idle",[]),h(this,"talking",[]),h(this,"marker",null),h(this,"voip",null),h(this,"lastMouthChangeTime",0),h(this,"mouthChangeLength",0)}awake(){setTimeout(()=>{this.voip=re.findObjectOfType(td,this.context),this.marker||(this.marker=re.getComponentInParent(this.gameObject,Er))},3e3)}update(){var e;if(!this.voip||this.context.time.frameCount%10!==0)return;let t=((e=this.marker)==null?void 0:e.connectionId)??null;if(!t){Fne&&(t=null);return}const n=this.voip.getFrequency(t)??0;this.updateLips(n)}updateLips(e){if(this.context.time.time-this.lastMouthChangeTime>this.mouthChangeLength){if(this.mouthChangeLength=.05+Math.random()*.1,this.talking&&this.talking.length>0&&e>30){this.lastMouthChangeTime=this.context.time.time;const t=Math.floor(Math.random()*this.talking.length);this.setMouthShapeActive(this.talking,t)}else if(this.idle.length>0&&this.context.time.time-this.lastMouthChangeTime>.5){this.lastMouthChangeTime=this.context.time.time;const t=Math.floor(Math.random()*this.idle.length);this.setMouthShapeActive(this.idle,t)}}}setMouthShapeActive(e,t){if(e){e!=this.idle?this.idle.map(n=>n.visible=!1):this.talking.map(n=>n.visible=!1);for(let n=0;n<e.length;n++){const r=e[n];r&&(r.visible=n===t)}}}}d4([x(ge)],Dv.prototype,"idle",2),d4([x(ge)],Dv.prototype,"talking",2);class iI extends Ie{constructor(){super(...arguments),h(this,"voip",null),h(this,"marker",null),h(this,"_startPosition",null)}awake(){this.voip=re.findObjectOfType(td,this.context),this.marker=re.getComponentInParent(this.gameObject,Er)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!==0)return;const e=this.marker.connectionId,t=this.voip.getFrequency(e);if(t==null)return;this._startPosition||(this._startPosition=this.gameObject.position.clone());const n=t/100;this.gameObject.position.y=this._startPosition.y+n*.07}}var Nne=Object.defineProperty,zne=Object.getOwnPropertyDescriptor,J_=(i,e,t,n)=>{for(var r=n>1?void 0:n?zne(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&Nne(e,t,r),r};class id extends Ie{constructor(){super(...arguments),h(this,"eyes",[]),h(this,"lastBlinkTime",0),h(this,"blinkLength",0),h(this,"eyesOpen",!0),h(this,"state",null)}awake(){this.state=re.getComponentInParent(this.gameObject,Zs)}update(){if(!(!this.gameObject||!this.gameObject.visible||!this.eyes||!Array.isArray(this.eyes)||this.eyes.length===0)&&this.context.time.time-this.lastBlinkTime>this.blinkLength){if(this.lastBlinkTime=this.context.time.time,this.state&&!this.state.isOn||!this.activeAndEnabled)return;if(this.eyesOpen=!this.eyesOpen,this.blinkLength=Math.random(),this.eyesOpen?(this.blinkLength*=3,this.blinkLength+=.5,Math.random()<.1&&(this.blinkLength=.1+Math.random()*.2)):(this.blinkLength*=Math.random()*.2,this.blinkLength+=.1),Math.random()<.1&&(this.blinkLength*=3),this.blinkLength=Math.max(.2,this.blinkLength),this.blinkLength=Math.min(3,this.blinkLength),this.eyes)for(const e of this.eyes)e&&(e.visible=this.eyesOpen)}}}J_([x(ge)],id.prototype,"eyes",2),J_([x()],id.prototype,"lastBlinkTime",2),J_([x()],id.prototype,"blinkLength",2),J_([x()],id.prototype,"eyesOpen",2);var jne=Object.defineProperty,Gne=Object.getOwnPropertyDescriptor,nI=(i,e,t,n)=>{for(var r=n>1?void 0:n?Gne(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&jne(e,t,r),r},rI;const p4=(rI=class extends Ie{constructor(){super(...arguments),h(this,"head",null),h(this,"eyes",null),h(this,"target",null),h(this,"brain",null),h(this,"vec",new S),h(this,"currentTargetPoint",new S)}awake(){this.brain||(this.brain=re.getComponentInParent(this.gameObject,Pv)),this.brain||(console.log("No look at brain found, adding it now"),this.brain=re.addNewComponent(this.gameObject,Pv)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}update(){const i=this.target;if(i&&this.head){const e=this.eyes;if(e){const t=Rt(i);this.currentTargetPoint.lerp(t,this.context.time.deltaTime/.1);const n=Rt(this.head),r=this.vec.copy(this.currentTargetPoint).sub(n).normalize();if(r.length()<.1)return;const s=p4.forward;if(s.set(0,0,1),s.applyQuaternion(xi(this.head)),s.dot(r)>.45)for(let o=0;o<e.length;o++)e[o].lookAt(this.currentTargetPoint)}}}},h(rI,"forward",new S(0,0,1)),rI);let uf=p4;nI([x(ge)],uf.prototype,"head",2),nI([x(ge)],uf.prototype,"eyes",2),nI([x(ge)],uf.prototype,"target",2);const Ov=ee("debugavatar");class K_{constructor(e,t,n,r){h(this,"root"),h(this,"head"),h(this,"leftHand"),h(this,"rigthHand");var s;this.root=e,this.head=t,this.leftHand=n,this.rigthHand=r,(s=this.root)==null||s.traverse(o=>o.layers.set(2))}get isValid(){return this.head!==null&&this.head!==void 0}}class sI{constructor(){h(this,"avatarRegistryUrl",null)}async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let n=null;if(typeof t=="string"){if(n=await this.loadAvatar(e,t),!n){const s=new Sa;n=re.instantiate(xp(t,e.scene),s)}}else n=t;if(!n)return null;const r=this.findAvatar(n);return r.isValid?(Ov&&console.log("[Custom Avatar] valid config",t,Ov?r:""),r):(console.warn("[Custom Avatar] config isn't valid",t,Ov?r:""),null)}async loadAvatar(e,t){if(console.assert(t!=null&&typeof t=="string","Avatar id must not be null"),t.length<=0||!t)return null;if(Ov&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const r=await fetch("./"+t);let s=null;if(r.ok){const a=await r.blob();a&&(s=await a.arrayBuffer())}if(!s&&(s=await tM(t,t,0,"no url here go away",!0),!s))return null;const o=await Yo().parseSync(e,s,null,0);return o?.scene??null}const n=new Hp;return rv(n,e),new Promise((r,s)=>{const o=this.avatarRegistryUrl+"/"+t;n.load(o,async a=>{await Yo().createBuiltinComponents(e,o,a,null,void 0),r(a.scene)},a=>{Ov&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),r(null)})})}cacheModel(e,t){}findAvatar(e){const t=e;let n=t;n.children.length==1&&(n=e.children[0]);let r=this.findAvatarPart(n,["head"]);const s=this.findAvatarPart(n,["left","hand"]),o=this.findAvatarPart(n,["right","hand"]);if(!r){r=t;const a=new S;new gi().setFromObject(r).getSize(a);const l=Math.max(a.x,a.y,a.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+l+" meters! Should be < 0.3m"),l>.3&&r.scale.multiplyScalar(1/l*.3)}return new K_(t,r,s,o)}findAvatarPart(e,t){const n=e.name.toLowerCase();let r=!0;for(const s of t){if(!r)break;n.indexOf(s)===-1&&(r=!1)}if(r)return e;if(e.children)for(const s of e.children){const o=this.findAvatarPart(s,t);if(o)return o}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}var Qne=Object.defineProperty,Hne=Object.getOwnPropertyDescriptor,oI=(i,e,t,n)=>{for(var r=n>1?void 0:n?Hne(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&Qne(e,t,r),r};class df extends Ie{constructor(){super(...arguments),h(this,"length",1),h(this,"depthTest",!0),h(this,"isGizmo",!0),h(this,"_axes",null)}onEnable(){if(this.isGizmo&&!wg)return;this._axes||(this._axes=new yo(this.length)),this._axes.layers.disableAll(),this._axes.layers.set(this.layer),this.gameObject.add(this._axes);const e=this._axes.material;e&&e.depthTest!==void 0&&(e.depthTest=this.depthTest)}onDisable(){this._axes&&this.gameObject.remove(this._axes)}}oI([x()],df.prototype,"length",2),oI([x()],df.prototype,"depthTest",2),oI([x()],df.prototype,"isGizmo",2);class aI extends Ie{constructor(){super(...arguments),h(this,"from"),h(this,"to"),h(this,"hint"),h(this,"desiredDistance",1)}onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;const e=Rt(this.to).clone(),t=Rt(this.from).clone(),n=e.distanceTo(t),r=e.clone();r.sub(t);const s=t.clone();s.add(e),s.multiplyScalar(.5);const o=Rt(this.hint).clone();o.sub(s);const a=new S;a.crossVectors(o,r),a.crossVectors(r,a),a.normalize();const l=n*.5,c=Math.max(this.desiredDistance,l),u=Math.sqrt(c*c-l*l),d=a.clone();d.multiplyScalar(u),d.add(s),Qr(this.gameObject,d);const p=s.clone();p.sub(a),this.gameObject.lookAt(p)}}const Vne=ee("debugusdzbehaviours");class Z_{constructor(){h(this,"behaviours",[]),h(this,"behaviourComponents",[]),h(this,"behaviourComponentsCopy",[])}get extensionName(){return"Behaviour"}addBehavior(e){this.behaviours.push(e)}onBeforeBuildDocument(e){const t=[];return e.root.traverse(n=>{re.foreachComponent(n,r=>{var s;const o=r;if(typeof o.createBehaviours=="function"||typeof o.beforeCreateDocument=="function"||typeof o.afterCreateDocument=="function"||typeof o.afterSerialize=="function"){this.behaviourComponents.push(o);const a=(s=o.beforeCreateDocument)==null?void 0:s.call(o,this,e);a instanceof Promise&&t.push(a)}},!1)}),Promise.all(t)}onExportObject(e,t,n){var r;for(const s of this.behaviourComponents)(r=s.createBehaviours)==null||r.call(s,this,t,n)}onAfterBuildDocument(e){for(const t of this.behaviourComponents)typeof t.afterCreateDocument=="function"&&t.afterCreateDocument(this,e);this.behaviourComponentsCopy=this.behaviourComponents.slice(),this.behaviourComponents.length=0}onAfterHierarchy(e,t){var n;if((n=this.behaviours)!=null&&n.length){t.beginBlock('def Scope "Behaviors"');for(const r of this.behaviours)r.writeTo(this,e.document,t);t.closeBlock()}}async onAfterSerialize(e){Vne&&console.log("onAfterSerialize behaviours",this.behaviourComponentsCopy);for(const t of this.behaviourComponentsCopy)typeof t.afterSerialize=="function"&&(t.afterSerialize.constructor.name==="AsyncFunction"?await t.afterSerialize(this,e):t.afterSerialize(this,e));this.behaviours.length=0}}var Wne=Object.defineProperty,qne=Object.getOwnPropertyDescriptor,lI=(i,e,t,n)=>{for(var r=n>1?void 0:n?qne(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&Wne(e,t,r),r},cI;const f4=(cI=class extends Yr{constructor(){super(...arguments),h(this,"threshold"),h(this,"intensity"),h(this,"scatter"),h(this,"selectiveBloom")}get typeName(){return"Bloom"}init(){this.threshold.defaultValue=1,this.intensity.defaultValue=0,this.scatter.defaultValue=.2,this.selectiveBloom?(this.threshold.valueProcessor=i=>i,this.intensity.valueProcessor=i=>i,this.scatter.valueProcessor=i=>1*Math.PI*(1-i)):(this.threshold.valueProcessor=i=>i,this.intensity.valueProcessor=i=>i,this.scatter.valueProcessor=i=>100*(1-i))}onCreateEffect(){let i;if(this.selectiveBloom==null&&(this.selectiveBloom=f4.useSelectiveBloom),this.selectiveBloom){const e=i=new EL(this.context.scene,this.context.mainCamera,{blendFunction:zt.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,intensity:this.intensity.value});e.inverted=!0}else i=new QE({blendFunction:zt.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,intensity:this.intensity.value});return this.intensity.onValueChanged=e=>{i.intensity=e},this.threshold.onValueChanged=e=>{i.luminanceMaterial.threshold=e},this.scatter.onValueChanged=e=>{i.luminancePass.enabled=!0,i.luminanceMaterial.smoothing=e},i}},h(cI,"useSelectiveBloom",!1),cI);let nd=f4;lI([x(Bt)],nd.prototype,"threshold",2),lI([x(Bt)],nd.prototype,"intensity",2),lI([x(Bt)],nd.prototype,"scatter",2),Fo("Bloom",nd);const pf="NEEDLE_progressive",Jr=ee("debugprogressive"),hI=Symbol("needle-progressive-texture"),ff=new Map;if(Jr){let i=function(){e+=1,$i(`Toggle LOD level: ${e}<br/>Registered objects: ${ff.size}`),console.log("Toggle LOD level",e,ff);const n=ii.Current;ff.forEach((r,s)=>{for(const o of r.keys){const a=s[o];if(a instanceof ut){const l=Ui.getMeshLODInformation(a),c=l?Math.min(e,l.lods.length):0;s["DEBUG:LOD"]=c,Ui.assignMeshLOD(n,r.sourceId,s,c),l&&(t=Math.max(t,l.lods.length-1))}else if(s instanceof It){Ui.assignTextureLOD(n,r.sourceId,s,e);break}}}),e>=t&&(e=-1)},e=-1,t=2;window.addEventListener("keyup",n=>{n.key==="p"&&i()}),ii.registerCallback(bn.ContextCreated,n=>{const r=document.createElement("button");r.innerText="Toggle Progressive",r.onclick=i,n.context.menu.appendChild(r)})}function m4(i,e,t){var n;if(!Jr)return;ff.has(i)||ff.set(i,{keys:[],sourceId:t});const r=ff.get(i);((n=r?.keys)==null?void 0:n.includes(e))==!1&&r.keys.push(e)}const $s=class{constructor(i,e,t){h(this,"parser"),h(this,"sourceId"),h(this,"context"),this.parser=i,this.sourceId=e,this.context=t}get name(){return pf}static getMeshLODInformation(i){const e=this.getAssignedLODInformation(i);return e!=null&&e.key?this.lodInfos.get(e.key):null}static hasLODLevelAvailable(i,e){var t;if(i instanceof It){for(const s of Object.keys(i)){const o=i[s];if(o instanceof gt&&this.hasLODLevelAvailable(o,e))return!0}return!1}else if(i instanceof os){for(const s of i.children)if(s instanceof ue&&this.hasLODLevelAvailable(s,e))return!0}let n,r;if(i instanceof ue?n=i.geometry:i instanceof gt&&(n=i),n&&(t=n?.userData)!=null&&t.LODS){const s=n.userData.LODS;if(r=this.lodInfos.get(s.key),e===void 0)return r!=null;if(r)return Array.isArray(r.lods)?e<r.lods.length:e===0}return!1}static assignMeshLOD(i,e,t,n){if(!t)return Promise.resolve(null);if(t instanceof ue){const r=t.geometry,s=this.getAssignedLODInformation(r);if(!s)return Promise.resolve(null);Vg(t)||a_(t,t.geometry);const o=this.onProgressiveLoadStart(i,e,t,null);return t["LOD:requested level"]=n,$s.getOrLoadLOD(i,e,r,n).then(a=>{if(t["LOD:requested level"]===n){if(delete t["LOD:requested level"],Array.isArray(a)){const l=s.index||0;a=a[l]}a&&r!=a&&(Jr=="verbose"&&console.log("Progressive Mesh "+t.name+" loaded",r,"\u2192",a,`
5481
+ `))}for(const C of M){const P=s.get(C);P&&D.set(C,P)}return D},f=function(M){const D=p(M),C=l(D);return c(D,C,M)};const m=r.skinnedMesh.skeleton,A=new Array;for(const M in m.bones){const D=m.bones[M],C=m.boneInverses[M];A.push({bone:D,inverse:C})}for(const M of vN(m.bones))A.push({bone:M,inverse:M.matrixWorld.clone().invert()});const v=A[0].bone.parent;v||console.error("No bone parent found for skinned mesh during USDZ export",r.skinnedMesh),A.sort((M,D)=>Yp(M.bone,v)>Yp(D.bone,v)?1:-1);const g=[],y=[],b=[],_=[];for(const{bone:M}of A)g.push(M.matrix.clone()),y.push(M.position),b.push(M.quaternion),_.push(M.scale);const E=A.map(M=>'"'+Yp(M.bone,v)+'"').join(", "),I=A.map(M=>Jp(M.inverse.clone().invert())).join(", ");e.beginBlock('def Skeleton "Rig"'),e.appendLine(`uniform matrix4d[] bindTransforms = [${I}]`),e.appendLine(`uniform token[] joints = [${E}]`),e.appendLine('uniform token purpose = "guide"'),e.appendLine(`uniform matrix4d[] restTransforms = [${g.map(M=>Jp(M)).join(", ")}]`),e.appendLine(`matrix4d xformOp:transform = ${Jp(new Ce)}`),e.appendLine('uniform token[] xformOpOrder = ["xformOp:transform"]');const T=f(A.map(M=>M.bone));if(Zu){let M=1e7,D=0;for(const C of((n=T.position)==null?void 0:n.keys())??[])M=Math.min(M,C),D=Math.max(D,C);console.log("Time samples",M,D,T)}if(e.beginBlock('def SkelAnimation "_anim"'),e.appendLine(`uniform token[] joints = [${E}]`),e.appendLine(`quatf[] rotations = [${d(b)}]`),T&&T.quaternion){e.beginBlock("quatf[] rotations.timeSamples = {","");const M=a(T.quaternion);for(const D of M)e.appendLine(D);e.closeBlock()}if(e.appendLine(`half3[] scales = [${u(_)}]`),T&&T.scale){e.beginBlock("half3[] scales.timeSamples = {","");const M=o(T.scale);for(const D of M)e.appendLine(D);e.closeBlock()}if(e.appendLine(`float3[] translations = [${u(y)}]`),T&&T.position){e.beginBlock("float3[] translations.timeSamples = {","");const M=o(T.position);for(const D of M)e.appendLine(D);e.closeBlock()}e.closeBlock(),e.closeBlock()}}onSerialize(e,t){var n;if(!this.model)return;const r=this.dict.get(this.object);if(r)for(let u=0;u<r.length;u++)r[u]===void 0&&(r[u]=new Xr(null,this.object,void 0));this.skinnedMeshExport(e,t);const s=this.object,o=this.dict.get(s);if(!o||s.isSkinnedMesh)return;JT&&console.log("SERIALIZE",this.model.name,this.object.type,o);const a=new Ce;e.appendLine("matrix4d xformOp:transform.timeSamples = {"),e.indent++;const l=new Array;let c=0;for(let u=0;u<o.length;u++){if(l.push(c),o[u]===void 0){console.error("Got an undefined transform data, this is likely a bug.",s,o);continue}c+=o[u].getDuration()+Xr.animationDurationPadding}for(let u=0;u<o.length;u++){const d=o[u];if(!d)continue;const p=l[u];{const f=d.getSortedTimesArray();if(!f||f.length===0){console.error("got an animated object but no time values?",s,d);continue}if(Zu){const m=((n=d.clip)==null?void 0:n.name)??"rest",A=d.getDuration();console.log("Write .timeSamples:",m,p,A,o),e.appendLine("# "+m+": start="+(p*d.frameRate).toFixed(3)+", length="+(A*d.frameRate).toFixed(3)+", frames="+d.getFrames())}for(const{time:m,translation:A,rotation:v,scale:g}of d.getValues(f)){a.compose(A,v,g);const y=`${(p+m)*d.frameRate}: ${Jp(a)},`;e.appendLine(y)}}}e.indent--,e.appendLine("}")}}var tne=Object.defineProperty,ine=Object.getOwnPropertyDescriptor,i4=(i,e,t,n)=>{for(var r=n>1?void 0:n?ine(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&tne(e,t,r),r};const n4=ee("debugpost");class Bt{constructor(e){h(this,"_active",!0),h(this,"_value"),h(this,"_valueRaw"),h(this,"_defaultValue"),h(this,"valueProcessor"),h(this,"onValueChanged"),this._value=e,this._defaultValue=e,this._valueRaw=e}get overrideState(){return this._active}set overrideState(e){if(this._active===e)return;this._active=e;const t=e?this._valueRaw:this._defaultValue;this.processValue(t,!0)}get value(){return this._valueRaw}set value(e){this.processValue(e,!1)}set defaultValue(e){this._defaultValue=e}__init(){this.processValue(this._valueRaw,!0)}processValue(e,t){if(e==null||!t&&this.testIfValueChanged(e)===!1)return;const n=this._value;if(n4){let r=!0;if(typeof n=="number"&&typeof e=="number"){const s=n?.toFixed(4),o=e?.toFixed(4);s!=o?r=!0:r=!1}r&&console.log("VolumeParameter: value changed from",n,"to",e)}!this._active&&this._defaultValue!==void 0?(this._value=this._defaultValue,e=this._defaultValue,this._valueRaw=e):(this._valueRaw=e,this._active&&this.valueProcessor&&(e=this.valueProcessor(e)),this._value=e),this.onValueChanged?this.onValueChanged(e,n,this):n4&&console.log("VolumeParameter: onValueChanged not set")}testIfValueChanged(e){return this._valueRaw!==e}}i4([x()],Bt.prototype,"overrideState",1),i4([x()],Bt.prototype,"value",1);var nne=Object.defineProperty,rne=Object.getOwnPropertyDescriptor,sne=(i,e,t,n)=>{for(var r=n>1?void 0:n?rne(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&nne(e,t,r),r};const one=ee("debugpost");class Yr extends Ie{constructor(e=void 0){if(super(),h(this,"active",!0),h(this,"_result"),h(this,"_didCreateVolumeParameters",!1),e){this.ensureVolumeParameters();for(const t of Object.keys(e)){const n=e[t],r=this[t];r instanceof Bt&&(r.value=n)}}}onEnable(){this.__internalDidAwakeAndStart&&(this.active=!0)}onDisable(){this.active=!1}init(){}apply(){var e;return this.ensureVolumeParameters(),this._result||(this._result=(e=this.onCreateEffect)==null?void 0:e.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){one&&console.warn("DISPOSE",this),this._result&&(Array.isArray(this._result)?this._result.forEach(e=>e.dispose()):this._result.dispose()),this._result=void 0}initParameters(){const e=Object.keys(this);for(const t of e){const n=this[t];n instanceof Bt&&n.__init()}}onAfterDeserialize(e,t){if(typeof e=="object"){const n=this.$serializedTypes;if(n){for(const r of Object.keys(n))if(n[r]===Bt){const s=e[r];if(s!==void 0){const o=this[r];o.value=s}}}}}onEditorModification(e){const t=e.propertyName;if(this[t]instanceof Bt){const n=e.value;return this[t].value=n,!0}}ensureVolumeParameters(){if(this._didCreateVolumeParameters)return;this._didCreateVolumeParameters=!0;const e=this.$serializedTypes;if(e)for(const t of Object.keys(e))e[t]===Bt&&(this[t]||(this[t]=new Bt))}}sne([x()],Yr.prototype,"active",2);var ane=Object.defineProperty,lne=Object.getOwnPropertyDescriptor,cne=(i,e,t,n)=>{for(var r=n>1?void 0:n?lne(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&ane(e,t,r),r};const hne=ee("debugpost"),KT={};function Fo(i,e){KT[i]=e}function une(i){return i.__type in KT?KT[i.__type]:(hne&&i.__type&&console.warn("Unknown postprocessing type",i.__type,i),Yr)}class Cv{constructor(){h(this,"components",[])}init(){var e;(e=this.components)==null||e.forEach(t=>t.init())}}cne([Zp([i=>une(i),Yr])],Cv.prototype,"components",2);var dne=Object.defineProperty,pne=Object.getOwnPropertyDescriptor,fne=(i,e,t,n)=>{for(var r=n>1?void 0:n?pne(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&dne(e,t,r),r};class Ev extends Yr{constructor(){super(...arguments),h(this,"preset")}get typeName(){return"Antialiasing"}onCreateEffect(){const e=new IL({preset:Pp.HIGH,edgeDetectionMode:FE.DEPTH});return this.preset.onValueChanged=t=>{e.applyPreset(t)},e}}fne([x(Bt)],Ev.prototype,"preset",2),Fo("Antialiasing",Ev);const mne=ee("debugusdz");class zh{constructor(){h(this,"files",new Array)}static getName(e){var t;const n=e.split(".").pop();let r=(t=e.split(".").slice(0,-1).join(".").split("/").pop())==null?void 0:t.replace(".","_");return r||(r="Audio_"+Math.random().toString(36).substring(2,15)),Jl(r)+"."+n}get extensionName(){return"Audio"}onExportObject(e,t,n){const r=re.getComponents(e,en);if(r.length)for(const s of r){if(!s.clip||typeof s.clip!="string"||!s.playOnAwake)continue;const o=s.clip.split("/").pop()||"Audio",a=zh.getName(s.clip),l=Jl(a);this.files.some(c=>c.path===s.clip)||this.files.push({path:s.clip,name:a}),n.quickLookCompatible||t.addEventListener("serialize",(c,u)=>{c.appendLine(),c.beginBlock(`def SpatialAudio "${l}"`,"(",!1),c.appendLine(`displayName = "${o}"`),c.closeBlock(")"),c.beginBlock(),c.appendLine(`uniform asset filePath = @audio/${a}@`),c.appendLine(`uniform token auralMode = "${s.spatialBlend>0?"spatial":"nonSpatial"}"`),c.appendLine(`uniform token playbackMode = "${s.loop?"loopFromStage":"onceFromStart"}"`),c.appendLine(`uniform float gain = ${s.volume}`),c.closeBlock()})}}async onAfterSerialize(e){for(const t of this.files){const n="audio/"+t.name;if(e.files[n]){mne&&console.warn("Audio file with name "+n+" already exists in the context. Skipping.");continue}const r=await(await(await fetch(t.path)).blob()).arrayBuffer(),s=new Uint8Array(r);e.files[n]=s}}}const $u=ee("debugautosync"),ZT=Symbol("syncerId");class gne{constructor(){h(this,"_syncers",{})}getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];const t=new vne(e);return t[ZT]=e.guid,this._syncers[t[ZT]]=t,t}removeSyncer(e){delete this._syncers[e[ZT]]}}const $T=new gne;class vne{constructor(e){h(this,"comp"),h(this,"hasChanges",!1),h(this,"changedProperties",{}),h(this,"data",{}),h(this,"_boundEvent"),h(this,"_handleReceivingMethod"),h(this,"_isReceiving",!1),h(this,"_isInit",!1),this.comp=e}get networkingKey(){return this.comp.guid}init(e){if(this._isInit)return;this._isInit=!0,this.comp=e,this._boundEvent=this.onHandleSending.bind(this),this.comp.context.post_render_callbacks.push(this._boundEvent),this._handleReceivingMethod=this.onHandleReceiving.bind(this),this.comp.context.connection.beginListen(this.networkingKey,this._handleReceivingMethod);const t=this.comp.context.connection.tryGetState(this.comp.guid);t&&this.onHandleReceiving(t)}destroy(){this._isInit&&(this._boundEvent&&this.comp.context.post_render_callbacks.splice(this.comp.context.post_render_callbacks.indexOf(this._boundEvent),1),this._handleReceivingMethod&&this.comp.context.connection.stopListen(this.networkingKey,this._handleReceivingMethod),this.comp=null,this._isInit=!1)}notifyChanged(e,t){this._isReceiving||($u&&console.log("Property changed: "+e,t),this.hasChanges=!0,this.changedProperties[e]=t)}onHandleSending(){if(!this.hasChanges)return;this.hasChanges=!1;const e=this.comp.context.connection;if(!e||!e.isConnected){for(const t in this.changedProperties)delete this.changedProperties[t];return}for(const t in this.data)delete this.data[t];this.data.guid=this.comp.guid;for(const t in this.changedProperties){const n=this.changedProperties[t];delete this.changedProperties[t],this.data[t]=n}e.send(this.networkingKey,this.data)}onHandleReceiving(e){if($u&&console.log("RECEIVE",this.comp.name,this.comp.guid,e),!this._isInit||!this.comp)return;const t=e.guid;if(!(t&&t!==this.comp.guid)){$u&&console.log("RECEIVED",this.comp.name,this.comp.guid,e);try{this._isReceiving=!0;for(const n in e){if(n==="guid")continue;const r=e[n];this.comp[n]=r,$u&&console.log("SET",n,r)}}catch(n){console.error(n)}finally{this._isReceiving=!1}}}}function Ane(i,e){let t=e!==i;return!t&&i&&e&&(Array.isArray(i)&&Array.isArray(e)||typeof i=="object"&&typeof e=="object")&&(t=!0),t}const Mv=Symbol("AutoSyncHandler");function yne(i){if(i[Mv])return i[Mv];const e=$T.getOrCreateSyncer(i);return e?.init(i),i[Mv]=e,e}function bne(i){const e=i[Mv];e&&($T.removeSyncer(e),e.destroy(),delete i[Mv])}const eI=function(i){return function(e,t){var n;let r="";typeof t=="string"?r=t:r=t.name;let s=null,o;typeof i=="string"?o=e[i]:typeof i=="function"&&(o=i);const a=e,l=a.__internalAwake;if(typeof l!="function"){($u||pt())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+((n=e?.constructor)==null?void 0:n.name)+'" is not supported',e);return}$u&&console.log(r);const c=Symbol(r);a.__internalAwake=function(){if(this[c]!==void 0)return;this[c]=this[r],s=$T.getOrCreateSyncer(this);const d=Object.getOwnPropertyDescriptor(this,r);if(d?.set===void 0){let p=!1;Object.defineProperty(this,r,{set:function(f){var m;const A=this[c];if(this[c]=f,p){pt()&&console.warn("Recursive call detected",r);return}p=!0;try{const v=Ane(f,A);$u&&console.log("SyncField assignment",r,"changed?",v,f),v&&o?.call(this,f,A)!==!1&&((m=yne(this))==null||m.notifyChanged(r,f))}finally{p=!1}},get:function(){return this[c]},configurable:!0,enumerable:!0})}s?.init(this),l.call(this)};const u=a.__internalDestroy;a.__internalDestroy=function(){bne(this),u.call(this)}}};var _ne=Object.defineProperty,xne=Object.getOwnPropertyDescriptor,X_=(i,e,t,n)=>{for(var r=n>1?void 0:n?xne(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&_ne(e,t,r),r};const Ks=ee("debugplayersync");class lf extends Ie{constructor(){super(...arguments),h(this,"autoSync",!0),h(this,"asset"),h(this,"onPlayerSpawned"),h(this,"_localInstance"),h(this,"onJoinedRoom",()=>{Ks&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()})}awake(){this.watchTabVisible(),this.onPlayerSpawned||(this.onPlayerSpawned=new Hn)}onEnable(){this.context.connection.beginListen(Jt.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(Jt.JoinedRoom,this.onJoinedRoom),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(Jt.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(Jt.JoinedRoom,this.onJoinedRoom)}async getInstance(){var e,t,n,r,s,o;if(this._localInstance)return this._localInstance;if(Ks&&console.log("PlayerSync.createInstance",(e=this.asset)==null?void 0:e.uri),!((t=this.asset)!=null&&t.asset)&&!((n=this.asset)!=null&&n.uri))return console.error('PlayerSync: can not create an instance because "asset" is not set!'),null;this._localInstance=(r=this.asset)==null?void 0:r.instantiateSynced({parent:this.gameObject},!0);const a=await this._localInstance;if(a){const l=re.getComponent(a,No);l?(l.owner=this.context.connection.connectionId,(s=this.onPlayerSpawned)==null||s.invoke(a)):(this._localInstance=void 0,console.error("<strong>Failed finding PlayerState on "+((o=this.asset)==null?void 0:o.uri)+"</strong>: please make sure the asset has a PlayerState component!"),re.destroySynced(a))}else this._localInstance=void 0,console.warn("PlayerSync: failed instantiating asset!");return this._localInstance}destroyInstance(){var e;(e=this._localInstance)==null||e.then(t=>(Ks&&console.log("PlayerSync.destroyInstance",t),re.destroySynced(t))),this._localInstance=void 0}watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=No.all.length-1;t>=0;t--){const n=No.all[t];(!n.owner||!this.context.connection.userIsInRoom(n.owner))&&n.doDestroy()}})}}X_([x()],lf.prototype,"autoSync",2),X_([x(ni)],lf.prototype,"asset",2),X_([x(Hn)],lf.prototype,"onPlayerSpawned",2);var r4=(i=>(i.OwnerChanged="ownerChanged",i))(r4||{}),Tv;const Cr=(Tv=class extends Ie{constructor(){super(...arguments),h(this,"onOwnerChangeEvent",new Hn),h(this,"onFirstOwnerChangeEvent",new Hn),h(this,"hasOwner",!1),h(this,"owner"),h(this,"dontDestroy",!1),h(this,"onUserLeftRoom",i=>{if(i.userId===this.owner){Ks&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}})}static get all(){return Cr._all}static get local(){return Cr._local}static getFor(i){if(i instanceof ge)return re.getComponentInParent(i,Cr);if(i instanceof Ie)return re.getComponentInParent(i.gameObject,Cr)}static isLocalPlayer(i){const e=Cr.getFor(i);return e?.isLocalPlayer??!1}static addEventListener(i,e){return this._callbacks[i]||(this._callbacks[i]=[]),this._callbacks[i].push(e),e}static removeEventListener(i,e){if(!this._callbacks[i])return;const t=this._callbacks[i].indexOf(e);t>=0&&this._callbacks[i].splice(t,1)}static dispatchEvent(i,e){if(this._callbacks[i])for(const t of this._callbacks[i])t(e)}get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(i,e){var t,n;Ks&&console.log("PlayerSync.onOwnerChange",this,"newOwner",i,"oldOwner",e);const r=Cr._local.indexOf(this);r>=0&&Cr._local.splice(r,1);const s={playerState:this,oldValue:e,newValue:i};if(this.hasOwner||(this.hasOwner=!0,(t=this.onFirstOwnerChangeEvent)==null||t.invoke(s)),(n=this.onOwnerChangeEvent)==null||n.invoke(s),this.owner===this.context.connection.connectionId){Cr._local.push(this);const a=new CustomEvent("local-owner-changed",{detail:s});this.dispatchEvent(a)}const o=new CustomEvent("owner-changed",{detail:s});this.dispatchEvent(o),Cr.dispatchEvent("ownerChanged",o)}awake(){Cr.all.push(this),Ks&&console.log("Registered new PlayerState",this.guid,Cr.all.length-1,Cr.all),this.context.connection.beginListen(Jt.UserLeftRoom,this.onUserLeftRoom)}async start(){Ks&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await na(300),this.context.connection.userIsInRoom(this.owner)==!1&&(Ks&&console.log(`PlayerSync.start \u2192 doDestroy "${this.name}" because user "${this.owner}" is not in room anymore...`,"Currently in room:",...this.context.connection.usersInRoom()),this.doDestroy())):this.owner||(Ks&&console.warn("PlayerState.start \u2192 owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?Ks&&console.warn("PlayerState.start \u2192 owner is still undefined but dontDestroy is set to true",this.name):(Ks&&console.warn(`PlayerState.start \u2192 owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):Ks&&console.log("PlayerState.start \u2192 owner is assigned",this.owner)},2e3))}doDestroy(){Ks&&console.log("PlayerSync.doDestroy \u2192 syncDestroy",this.name),g_(this.gameObject,this.context.connection)}onDestroy(){if(this.context.connection.stopListen(Jt.UserLeftRoom,this.onUserLeftRoom),Cr.all.splice(Cr.all.indexOf(this),1),this.isLocalPlayer){const i=Cr._local.indexOf(this);i>=0&&Cr._local.splice(i,1)}}},h(Tv,"_all",[]),h(Tv,"_local",[]),h(Tv,"_callbacks",{}),Tv);let No=Cr;X_([eI(No.prototype.onOwnerChange)],No.prototype,"owner",2);const wne=ee("debugavatar"),Xa=class extends Ie{constructor(){super(...arguments),h(this,"connectionId"),h(this,"avatar")}static getAvatar(i){return i>=0&&i<Xa.instances.length?Xa.instances[i]:null}static onAvatarMarkerCreated(i){return Xa._onNewAvatarMarkerAdded.push(i),i}static onAvatarMarkerDestroyed(i){return Xa._onAvatarMarkerDestroyed.push(i),i}awake(){Xa.instances.push(this),wne&&console.log(this);for(const i of Xa._onNewAvatarMarkerAdded)i({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){Xa.instances.splice(Xa.instances.indexOf(this),1);for(const i of Xa._onAvatarMarkerDestroyed)i({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}};let Er=Xa;h(Er,"instances",[]),h(Er,"_onNewAvatarMarkerAdded",[]),h(Er,"_onAvatarMarkerDestroyed",[]);var Sne=Object.defineProperty,Cne=Object.getOwnPropertyDescriptor,Ene=(i,e,t,n)=>{for(var r=n>1?void 0:n?Cne(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&Sne(e,t,r),r};const cf=ee("debugxrflags"),s4=ee("disablexrflags");s4&&console.warn("XRFlags are disabled");var Ya=(i=>(i[i.Never=0]="Never",i[i.Browser=1]="Browser",i[i.AR=2]="AR",i[i.VR=4]="VR",i[i.FirstPerson=8]="FirstPerson",i[i.ThirdPerson=16]="ThirdPerson",i[i.All=4294967295]="All",i))(Ya||{});const o4=class{constructor(){h(this,"Mask",17)}Has(i){return(this.Mask&i)!==0}Set(i){cf&&console.warn("Set XR flag state to",i),this.Mask=i,Zs.Apply()}Enable(i){this.Mask|=i,Zs.Apply()}Disable(i){this.Mask&=~i,Zs.Apply()}Toggle(i){this.Mask^=i,Zs.Apply()}EnableAll(){this.Mask=-1,Zs.Apply()}DisableAll(){this.Mask=0,Zs.Apply()}};let ys=o4;h(ys,"Global",new o4);var Iv;const ic=(Iv=class extends Ie{constructor(){super(...arguments),h(this,"visibleIn")}static Apply(){for(const i of this.registry)i.UpdateVisible(ys.Global)}awake(){ic.registry.push(this)}onEnable(){ic.firstApply?this.UpdateVisible(ys.Global):(ic.firstApply=!0,ic.Apply())}onDestroy(){const i=ic.registry.indexOf(this);i>=0&&ic.registry.splice(i,1)}get isOn(){return this.gameObject.visible}UpdateVisible(i=null){if(s4)return;let e;const t=i;if(t&&typeof t=="number"&&(console.assert(typeof t=="number","XRFlag.UpdateVisible: state must be a number",t),cf&&console.log(t),ic.buffer.Mask=t,i=ic.buffer),i instanceof ys?(cf&&console.warn(this.name,"use passed in mask",i.Mask,this.visibleIn),e=i.Has(this.visibleIn)):(cf&&console.log(this.name,"use global mask"),ys.Global.Has(this.visibleIn)),e!==void 0)if(e)cf&&console.log(this.name,"is visible",this.gameObject.uuid),re.setActive(this.gameObject,!0);else{if(cf&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},h(Iv,"registry",[]),h(Iv,"firstApply"),h(Iv,"buffer",new ys),Iv);let Zs=ic;Ene([x()],Zs.prototype,"visibleIn",2);var Mne=Object.defineProperty,Tne=Object.getOwnPropertyDescriptor,tI=(i,e,t,n)=>{for(var r=n>1?void 0:n?Tne(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&Mne(e,t,r),r};const Rv=ee("debugwebxr"),a4=new Me().setFromAxisAngle(new S(0,1,0),Math.PI);class ed extends Ie{constructor(){super(...arguments),h(this,"head"),h(this,"leftHand"),h(this,"rightHand"),h(this,"_syncTransforms")}async onEnterXR(e){if(!this.activeAndEnabled)return;Rv&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const t=No.getFor(this);if(t!=null&&t.owner){const n=this.gameObject.addNewComponent(Er);n.avatar=this.gameObject,n.connectionId=t.owner}else this.context.connection.isConnected?console.error("No player state found for avatar",this):t&&!this.context.connection.isConnected&&(t.dontDestroy=!0)}onLeaveXR(e){const t=this.gameObject.getComponent(Er);t&&t.destroy()}onUpdateXR(e){var t,n;if(!this.activeAndEnabled)return;const r=No.isLocalPlayer(this);if(!r)return;const s=e.xr;if(s.rig&&s.rig.gameObject!==this.gameObject.parent&&(this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),this.gameObject.scale.set(1,1,1),s.rig.gameObject.add(this.gameObject)),this._syncTransforms&&r)for(const c of this._syncTransforms)c.fastMode=!0,c.isOwned()||c.requestOwnership();if(this.head&&this.context.mainCamera){const c=this.head.asset;if(c.position.copy(this.context.mainCamera.position),c.quaternion.copy(this.context.mainCamera.quaternion),c.quaternion.x*=-1,this.context.time.frameCount%10===0){const u=re.getComponentsInChildren(this.head.asset,Zs);for(const d of u)d.enabled=!1,d.gameObject.visible=!1}}const o=e.xr.leftController,a=(t=this.leftHand)==null?void 0:t.asset;o&&a&&(a.position.copy(o.gripPosition),a.quaternion.copy(o.gripQuaternion),a.quaternion.multiply(a4),a.visible=o.isTracking);const l=e.xr.rightController;if(l&&(n=this.rightHand)!=null&&n.asset){const c=this.rightHand.asset;c.position.copy(l.gripPosition),c.quaternion.copy(l.gripQuaternion),c.quaternion.multiply(a4),c.visible=l.isTracking}}onBeforeRender(){this.context.time.frame%10===0&&this.updateRemoteAvatarVisibility()}updateRemoteAvatarVisibility(){var e,t,n;if(this.context.connection.isConnected){const r=No.getFor(this);if(r&&r.isLocalPlayer==!1){const s=mt.getXRSync(this.context);if(s&&s.hasState(r.owner)){this.tryFindAvatarObjectsIfMissing();const o=(e=this.leftHand)==null?void 0:e.asset;o&&(o.visible=s?.isTracking(r.owner,"left")??!1);const a=(t=this.rightHand)==null?void 0:t.asset;a&&(a.visible=s?.isTracking(r.owner,"right")??!1)}if((n=this.head)!=null&&n.asset){const o=re.getComponentsInChildren(this.head.asset,Zs);for(const a of o)a.enabled=!1,a.gameObject.visible=!0}}}}tryFindAvatarObjectsIfMissing(){if(!this.head||!this.leftHand||!this.rightHand){const e={head:this.head,leftHand:this.leftHand,rightHand:this.rightHand};MU.tryFindAvatarObjects(this.gameObject,this.sourceId||"",e),e.head&&(this.head=e.head),e.leftHand&&(this.leftHand=e.leftHand),e.rightHand&&(this.rightHand=e.rightHand)}}async prepareAvatar(){if(this.tryFindAvatarObjectsIfMissing(),this.head)this.head instanceof ge&&(this.head=new ni("",this.sourceId,this.head));else{const e=new ge;e.name="Head";const t=Fg.createPrimitive(Uu.Cube);e.add(t),this.gameObject.add(e),this.head=new ni("",this.sourceId,e),Rv&&console.log("Create head",e)}if(this.rightHand)this.rightHand instanceof ge&&(this.rightHand=new ni("",this.sourceId,this.rightHand));else{const e=new ge;e.name="Right Hand",this.gameObject.add(e),this.rightHand=new ni("",this.sourceId,e),Rv&&console.log("Create right hand",e)}if(this.leftHand)this.leftHand instanceof ge&&(this.leftHand=new ni("",this.sourceId,this.leftHand));else{const e=new ge;e.name="Left Hand",this.gameObject.add(e),this.leftHand=new ni("",this.sourceId,e),Rv&&console.log("Create left hand",e)}await this.loadAvatarObjects(this.head,this.leftHand,this.rightHand),No.isLocalPlayer(this.gameObject)&&(this._syncTransforms=re.getComponentsInChildren(this.gameObject,uh))}async loadAvatarObjects(e,t,n){const r=e.loadAssetAsync(),s=t.loadAssetAsync(),o=n.loadAssetAsync(),a=new Array;r&&a.push(r),s&&a.push(s),o&&a.push(o);const l=await Jm(a);Rv&&console.log("Avatar loaded results:",l)}}tI([x(ni)],ed.prototype,"head",2),tI([x(ni)],ed.prototype,"leftHand",2),tI([x(ni)],ed.prototype,"rightHand",2);class Ja{static Add(e,t,n=null){if(t){for(const r of this.Pois)if(r.obj===t)return;this.Pois.push({obj:t,avatar:n}),this.LastChangeTime=e.time.time}}static Remove(e,t){var n;if(t){for(const r of this.Pois)if(r.obj===t){this.Pois.splice(this.Pois.indexOf(r),1),this.LastChangeTime=e?.time.time??((n=Lt.Current)==null?void 0:n.time.time);return}}}}h(Ja,"Pois",[]),h(Ja,"LastChangeTime",0);class Ine{constructor(){h(this,"guid"),h(this,"position",new S)}}class Pv extends Ie{constructor(){super(...arguments),h(this,"target",null),h(this,"avatar",null),h(this,"_model",null),h(this,"_targetModel",new Ine),h(this,"_currentTargetObject",null),h(this,"_lastUpdateTime",0),h(this,"_lookDuration",0),h(this,"_lastPoiChangedTime",0)}set controlledTarget(e){this.target=e;const t=q.get("MoveRandom");if(t&&this.target){const n=re.getComponent(this.target,t);n&&n.destroy()}}awake(){if(this.avatar=re.getComponentInParent(this.gameObject,Er),this.avatar){const e=re.getComponentInParent(this.gameObject,Er);this._model=new IM(this.context.connection,this.guid),e!=null&&e.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",e=>{var t;this.target&&e&&e.guid===((t=this.avatar)==null?void 0:t.guid)&&Qr(this.target,e.position)})}update(){var e;if((!this.context.connection.isConnected||(e=this._model)!=null&&e.hasOwnership)&&(Ja.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=Ja.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){const t=Rt(this._currentTargetObject);Qr(this.target,t),this.context.connection.isConnected&&this.avatar&&(this.context.connection.send("avatar-look-target-changed",this._targetModel),this._targetModel.guid=this.avatar.guid,this._targetModel.position.copy(t))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;const e=Ja.Pois;if(e.length>0){const t=e[Math.floor(Math.random()*e.length)];if(t&&t.obj){if(t.avatar&&t.avatar===this.avatar)return;this._currentTargetObject=t.obj}}}}}const hf=ee("debugnetworkingstreams");var Ka=(i=>(i.Connected="peer-user-connected",i.StreamReceived="receive-stream",i.StreamEnded="call-ended",i.Disconnected="peer-user-disconnected",i.UserJoined="user-joined",i))(Ka||{});class l4{constructor(e,t){h(this,"type","call-ended"),h(this,"userId"),h(this,"direction"),this.userId=e,this.direction=t}}class c4{constructor(e,t){h(this,"type","receive-stream"),h(this,"stream"),h(this,"target"),this.stream=e,this.target=t}}class Rne{constructor(e,t){h(this,"guid"),h(this,"peerId"),h(this,"dontSave",!0),this.guid=e.id,this.peerId=t}}var h4=(i=>(i.Incoming="incoming",i.Outgoing="outgoing",i))(h4||{});class Pne extends Jn{constructor(e,t,n){super(),h(this,"userId"),h(this,"direction"),h(this,"call"),h(this,"_stream",null),h(this,"_isDisposed",!1),this.userId=e,this.call=t,this.direction=n,this._stream=null,t.on("stream",r=>{if(hf&&console.log("Receive video",r.getAudioTracks(),r.getVideoTracks()),this._stream=r,n==="incoming"){const s=new c4(r,this);this.dispatchEvent(s)}}),t.on("close",()=>{this.dispatchEvent(new l4(e,n))})}get stream(){return this._stream}close(){this._isDisposed||(this._isDisposed=!0,this.call.close(),nc(this._stream))}get isOpen(){var e;return((e=this.call.peerConnection)==null?void 0:e.connectionState)==="connected"}get isOpening(){var e;return((e=this.call.peerConnection)==null?void 0:e.connectionState)==="connecting"}get isClosed(){return!this.isOpen}}const Bv=class extends Jn{constructor(i,e){super(),h(this,"id"),h(this,"context"),h(this,"_peer"),h(this,"_incomingCalls",[]),h(this,"_outgoingCalls",[]),h(this,"_enabled",!1),h(this,"_enabledPeer",!1),h(this,"onConnectRoomFn",this.onConnectRoom.bind(this)),h(this,"onPeerConnectFn",this.onPeerConnect.bind(this)),h(this,"onPeerReceiveCallFn",this.onPeerReceivingCall.bind(this)),this.context=i,this.id=e,this.setupPeer(),navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia}static getOrCreate(i,e){if(Bv.instances.has(e))return Bv.instances.get(e);const t=new Bv(i,e);return Bv.instances.set(e,t),t}getMyPeerId(){if(this.context.connection.connectionId)return this.getPeerIdFromUserId(this.context.connection.connectionId)}getPeerIdFromUserId(i){return this.id+"-"+i}getUserIdFromPeerId(i){return i.substring(this.id.length+1)}makeCall(i,e){var t;const n={metadata:{userId:this.context.connection.connectionId}},r=(t=this._peer)==null?void 0:t.call(i,e,n);if(r)return this.registerCall(r,"outgoing")}get peer(){return this._peer}enable(){this._enabled||(this._enabled=!0,this.context.connection.beginListen(Jt.JoinedRoom,this.onConnectRoomFn),this.subscribePeerEvents())}disable(){this._enabled&&(this._enabled=!1,this.context.connection.stopListen(Jt.JoinedRoom,this.onConnectRoomFn),this.unsubscribePeerEvents())}onConnectRoom(){this.setupPeer()}setupPeer(){if(this.context.connection.connectionId&&!this._enabledPeer){if(this._enabledPeer=!0,!this._peer){const i=this.getMyPeerId();i?this._peer=mU(i):console.error("Failed to setup peerjs because we dont have a connection id",this.context.connection.connectionId)}this._enabled&&this.subscribePeerEvents()}}subscribePeerEvents(){this._peer&&(this._peer.on("open",this.onPeerConnectFn),this._peer.on("call",this.onPeerReceiveCallFn))}unsubscribePeerEvents(){this._peer&&(this._peer.off("open",this.onPeerConnectFn),this._peer.off("call",this.onPeerReceiveCallFn))}onPeerConnect(i){hf&&console.log("Peer connected as",i),this.context.connection.send("peer-user-connected",new Rne(this,i))}onPeerReceivingCall(i){i.answer(),this.registerCall(i,"incoming")}registerCall(i,e){const t=i.metadata;(!t||!t.userId)&&console.error("Missing call metadata",i);const n=t.userId;e==="incoming"&&hf?console.log("Receive call from",i.metadata):hf&&console.log("Make call to",i.metadata);const r=e==="incoming"?this._incomingCalls:this._outgoingCalls,s=new Pne(n,i,e);return r.push(s),i.on("error",o=>{console.error("Call error",o)}),i.on("close",()=>{hf&&console.log("Call ended",i.metadata),i.close();const o=r.indexOf(s);o!==-1&&r.splice(o,1)}),s.addEventListener("call-ended",o=>{this.dispatchEvent(o)}),e==="incoming"&&(s.addEventListener("receive-stream",o=>{this.dispatchEvent(o)}),i.on("stream",()=>{let o=0;const a=setInterval(()=>{const l=o===0;!s.isOpen&&l&&(o+=1,clearInterval(a),s.close())},2e3)})),s}};let Y_=Bv;h(Y_,"instances",new Map);class Z0 extends Jn{constructor(e,t){super(),h(this,"context"),h(this,"peer"),h(this,"_sendingStreams",new Map),h(this,"debug",!1),h(this,"onJoinedRoom",n=>{this.debug&&console.log(`${n.userId} joined room and I'm currently sending ${this._sendingStreams.size} streams`),this._sendingStreams.size>0&&this.updateSendingCalls()}),h(this,"onReceiveStream",n=>{this.debug&&console.log("RECEIVE STREAM",n),this.dispatchEvent({type:"receive-stream",target:this,stream:n.stream,userId:n.userId})}),h(this,"onCallEnded",n=>{this.dispatchEvent(n)}),h(this,"onUserConnected",n=>{if(this.peer.id===n.guid){this.debug&&console.log("USER CONNECTED",n.guid,n);const r=this._sendingStreams.keys().next().value;this.peer.makeCall(n.peerId,r)}}),h(this,"onUserLeft",n=>{this.stopCallsToUsersThatAreNotInTheRoomAnymore()}),this.context=e,this.peer=t,hf&&(this.debug=!0)}static create(e){const t=Y_.getOrCreate(e.context,e.context.connection.connectionId);return new Z0(e.context,t)}startSendingStream(e){this._sendingStreams.has(e)?console.warn("Received start sending stream with stream that is already being sent"):(this._sendingStreams.set(e,[]),this.updateSendingCalls())}stopSendingStream(e){if(e){const t=this._sendingStreams.get(e);if(t){this.debug&&console.log("Closing calls",t);for(const n of t)n.close()}this._sendingStreams.delete(e),t&&this.debug&&console.log("Currently sending",this._sendingStreams)}}enable(){this.peer.enable(),this.peer.addEventListener("receive-stream",this.onReceiveStream),this.peer.addEventListener("call-ended",this.onCallEnded),this.context.connection.beginListen("peer-user-connected",this.onUserConnected),this.context.connection.beginListen(Jt.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Jt.UserJoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Jt.UserLeftRoom,this.onUserLeft)}disable(){this.peer.disable(),this.peer.removeEventListener("receive-stream",this.onReceiveStream),this.peer.removeEventListener("call-ended",this.onCallEnded),this.context.connection.stopListen("peer-user-connected",this.onUserConnected),this.context.connection.stopListen(Jt.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Jt.UserJoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Jt.UserLeftRoom,this.onUserLeft)}updateSendingCalls(){var e;let t=!1;const n=this.context.connection.connectionId;for(const r of this._sendingStreams.keys()){const s=this._sendingStreams.get(r)||[];for(const o of this.context.connection.usersInRoom()){if(o===n)continue;const a=s.find(l=>l.userId===o);if(!a||((e=a.stream)==null?void 0:e.active)===!1){this.debug&&console.log("Starting call to",o,n);const l=this.peer.makeCall(this.peer.getPeerIdFromUserId(o),r);l&&(t=!0,s.push(l))}}this._sendingStreams.set(r,s)}this.stopCallsToUsersThatAreNotInTheRoomAnymore(),t&&this.debug&&console.log("Currently sending",this._sendingStreams)}stopCallsToUsersThatAreNotInTheRoomAnymore(){for(const e of this._sendingStreams.keys()){const t=this._sendingStreams.get(e);if(t)for(let n=t.length-1;n>=0;n--){const r=t[n];this.context.connection.userIsInRoom(r.userId)||(r.close(),t.splice(n,1))}}}}function nc(i){if(i&&i instanceof MediaStream)for(const e of i.getTracks())e.stop()}var Bne=Object.defineProperty,Dne=Object.getOwnPropertyDescriptor,u4=(i,e,t,n)=>{for(var r=n>1?void 0:n?Dne(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&Bne(e,t,r),r};const One="noVoip",kne=ee("debugvoip");class td extends Ie{constructor(){super(...arguments),h(this,"autoConnect",!1),h(this,"runInBackground",!0),h(this,"debug",!1),h(this,"_net"),h(this,"_outputStream",null),h(this,"onJoinedRoom",async()=>{await na(300),this.autoConnect&&!this.isSending&&this.connect()}),h(this,"_incomingStreams",new Map),h(this,"onReceiveStream",e=>{const t=e.target.userId,n=e.stream,r=this._incomingStreams.get(t);if(r)r.srcObject=n,r.setAttribute("autoplay","true");else{const s=new Audio;this._incomingStreams.set(t,s),s.setAttribute("autoplay","true"),s.srcObject=n}}),h(this,"onStreamEnded",e=>{const t=this._incomingStreams.get(e.userId);nc(t?.srcObject),this._incomingStreams.delete(e.userId)}),h(this,"onEnabledChanged",()=>{for(const e of this._incomingStreams){const t=e[1];t.muted=!this.enabled}}),h(this,"onVisibilityChanged",()=>{if(this.runInBackground)return;const e=document.visibilityState!=="visible";this.setMuted(e);for(const t of this._incomingStreams){const n=t[1];n.muted=e}})}awake(){kne&&(this.debug=!0),this.debug&&window.addEventListener("keydown",async e=>{e.key==="v"&&(console.log("MUTE?",!this.isMuted),this.setMuted(!this.isMuted))})}onEnable(){this._net||(this._net=Z0.create(this)),this._net.addEventListener(Ka.StreamReceived,this.onReceiveStream),this._net.addEventListener(Ka.StreamEnded,this.onStreamEnded),this._net.enable(),this.autoConnect&&(this.context.connection.isConnected?this.connect():this.context.connection.beginListen(Jt.JoinedRoom,this.onJoinedRoom)),this.onEnabledChanged(),window.addEventListener("visibilitychange",this.onVisibilityChanged)}onDisable(){var e;this._net.stopSendingStream(this._outputStream),this._net.removeEventListener(Ka.StreamReceived,this.onReceiveStream),this._net.removeEventListener(Ka.StreamEnded,this.onStreamEnded),(e=this._net)==null||e.disable(),this.context.connection.stopListen(Jt.JoinedRoom,this.onJoinedRoom),this.onEnabledChanged(),window.removeEventListener("visibilitychange",this.onVisibilityChanged)}get isSending(){return this._outputStream!=null&&this._outputStream.active}async connect(e){if(this.context.connection.isConnected){if(!await xC())return console.error("Cannot connect to voice chat - microphone permissions not granted"),!1}else return console.error("Cannot connect to voice chat - not connected to server"),!1;return this._net.stopSendingStream(this._outputStream),nc(this._outputStream),this._outputStream=await this.getAudioStream(e),this._outputStream?(this._net.startSendingStream(this._outputStream),!0):(await xC()?console.error("VOIP: Could not get audio stream - please make sure to connect an audio device and grant microphone permissions"):AE("Microphone permissions not granted: Please grant microphone permissions to use voice chat"),!1)}disconnect(){this._net.stopSendingStream(this._outputStream),nc(this._outputStream),this._outputStream=null}setMuted(e){var t;const n=(t=this._outputStream)==null?void 0:t.getAudioTracks();if(n)for(const r of n)r.enabled=!e}get isMuted(){var e;if(this._outputStream===null)return!1;const t=(e=this._outputStream)==null?void 0:e.getAudioTracks();if(t){for(const n of t)if(!n.enabled)return!0}return!1}getFrequency(e){return this.unsupported_getfrequency||(this.unsupported_getfrequency=!0,pt()&&Qi("VOIP: getFrequency is currently not supported"),console.warn("VOIP: getFrequency is currently not supported")),null}async getAudioStream(e){return navigator.mediaDevices.getUserMedia?await navigator.mediaDevices.getUserMedia({audio:e??!0,video:!1}).catch(t=>(console.warn("VOIP failed getting audio stream",t),null)):(console.error("No getDisplayMedia support"),null)}}u4([x()],td.prototype,"autoConnect",2),u4([x()],td.prototype,"runInBackground",2);var Lne=Object.defineProperty,Une=Object.getOwnPropertyDescriptor,d4=(i,e,t,n)=>{for(var r=n>1?void 0:n?Une(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&Lne(e,t,r),r};const Fne=ee("debugmouth");class Dv extends Ie{constructor(){super(...arguments),h(this,"idle",[]),h(this,"talking",[]),h(this,"marker",null),h(this,"voip",null),h(this,"lastMouthChangeTime",0),h(this,"mouthChangeLength",0)}awake(){setTimeout(()=>{this.voip=re.findObjectOfType(td,this.context),this.marker||(this.marker=re.getComponentInParent(this.gameObject,Er))},3e3)}update(){var e;if(!this.voip||this.context.time.frameCount%10!==0)return;let t=((e=this.marker)==null?void 0:e.connectionId)??null;if(!t){Fne&&(t=null);return}const n=this.voip.getFrequency(t)??0;this.updateLips(n)}updateLips(e){if(this.context.time.time-this.lastMouthChangeTime>this.mouthChangeLength){if(this.mouthChangeLength=.05+Math.random()*.1,this.talking&&this.talking.length>0&&e>30){this.lastMouthChangeTime=this.context.time.time;const t=Math.floor(Math.random()*this.talking.length);this.setMouthShapeActive(this.talking,t)}else if(this.idle.length>0&&this.context.time.time-this.lastMouthChangeTime>.5){this.lastMouthChangeTime=this.context.time.time;const t=Math.floor(Math.random()*this.idle.length);this.setMouthShapeActive(this.idle,t)}}}setMouthShapeActive(e,t){if(e){e!=this.idle?this.idle.map(n=>n.visible=!1):this.talking.map(n=>n.visible=!1);for(let n=0;n<e.length;n++){const r=e[n];r&&(r.visible=n===t)}}}}d4([x(ge)],Dv.prototype,"idle",2),d4([x(ge)],Dv.prototype,"talking",2);class iI extends Ie{constructor(){super(...arguments),h(this,"voip",null),h(this,"marker",null),h(this,"_startPosition",null)}awake(){this.voip=re.findObjectOfType(td,this.context),this.marker=re.getComponentInParent(this.gameObject,Er)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!==0)return;const e=this.marker.connectionId,t=this.voip.getFrequency(e);if(t==null)return;this._startPosition||(this._startPosition=this.gameObject.position.clone());const n=t/100;this.gameObject.position.y=this._startPosition.y+n*.07}}var Nne=Object.defineProperty,zne=Object.getOwnPropertyDescriptor,J_=(i,e,t,n)=>{for(var r=n>1?void 0:n?zne(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&Nne(e,t,r),r};class id extends Ie{constructor(){super(...arguments),h(this,"eyes",[]),h(this,"lastBlinkTime",0),h(this,"blinkLength",0),h(this,"eyesOpen",!0),h(this,"state",null)}awake(){this.state=re.getComponentInParent(this.gameObject,Zs)}update(){if(!(!this.gameObject||!this.gameObject.visible||!this.eyes||!Array.isArray(this.eyes)||this.eyes.length===0)&&this.context.time.time-this.lastBlinkTime>this.blinkLength){if(this.lastBlinkTime=this.context.time.time,this.state&&!this.state.isOn||!this.activeAndEnabled)return;if(this.eyesOpen=!this.eyesOpen,this.blinkLength=Math.random(),this.eyesOpen?(this.blinkLength*=3,this.blinkLength+=.5,Math.random()<.1&&(this.blinkLength=.1+Math.random()*.2)):(this.blinkLength*=Math.random()*.2,this.blinkLength+=.1),Math.random()<.1&&(this.blinkLength*=3),this.blinkLength=Math.max(.2,this.blinkLength),this.blinkLength=Math.min(3,this.blinkLength),this.eyes)for(const e of this.eyes)e&&(e.visible=this.eyesOpen)}}}J_([x(ge)],id.prototype,"eyes",2),J_([x()],id.prototype,"lastBlinkTime",2),J_([x()],id.prototype,"blinkLength",2),J_([x()],id.prototype,"eyesOpen",2);var jne=Object.defineProperty,Gne=Object.getOwnPropertyDescriptor,nI=(i,e,t,n)=>{for(var r=n>1?void 0:n?Gne(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&jne(e,t,r),r},rI;const p4=(rI=class extends Ie{constructor(){super(...arguments),h(this,"head",null),h(this,"eyes",null),h(this,"target",null),h(this,"brain",null),h(this,"vec",new S),h(this,"currentTargetPoint",new S)}awake(){this.brain||(this.brain=re.getComponentInParent(this.gameObject,Pv)),this.brain||(console.log("No look at brain found, adding it now"),this.brain=re.addNewComponent(this.gameObject,Pv)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}update(){const i=this.target;if(i&&this.head){const e=this.eyes;if(e){const t=Rt(i);this.currentTargetPoint.lerp(t,this.context.time.deltaTime/.1);const n=Rt(this.head),r=this.vec.copy(this.currentTargetPoint).sub(n).normalize();if(r.length()<.1)return;const s=p4.forward;if(s.set(0,0,1),s.applyQuaternion(xi(this.head)),s.dot(r)>.45)for(let o=0;o<e.length;o++)e[o].lookAt(this.currentTargetPoint)}}}},h(rI,"forward",new S(0,0,1)),rI);let uf=p4;nI([x(ge)],uf.prototype,"head",2),nI([x(ge)],uf.prototype,"eyes",2),nI([x(ge)],uf.prototype,"target",2);const Ov=ee("debugavatar");class K_{constructor(e,t,n,r){h(this,"root"),h(this,"head"),h(this,"leftHand"),h(this,"rigthHand");var s;this.root=e,this.head=t,this.leftHand=n,this.rigthHand=r,(s=this.root)==null||s.traverse(o=>o.layers.set(2))}get isValid(){return this.head!==null&&this.head!==void 0}}class sI{constructor(){h(this,"avatarRegistryUrl",null)}async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let n=null;if(typeof t=="string"){if(n=await this.loadAvatar(e,t),!n){const s=new Sa;n=re.instantiate(xp(t,e.scene),s)}}else n=t;if(!n)return null;const r=this.findAvatar(n);return r.isValid?(Ov&&console.log("[Custom Avatar] valid config",t,Ov?r:""),r):(console.warn("[Custom Avatar] config isn't valid",t,Ov?r:""),null)}async loadAvatar(e,t){if(console.assert(t!=null&&typeof t=="string","Avatar id must not be null"),t.length<=0||!t)return null;if(Ov&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const r=await fetch("./"+t);let s=null;if(r.ok){const a=await r.blob();a&&(s=await a.arrayBuffer())}if(!s&&(s=await tM(t,t,0,"no url here go away",!0),!s))return null;const o=await Yo().parseSync(e,s,null,0);return o?.scene??null}const n=new Hp;return rv(n,e),new Promise((r,s)=>{const o=this.avatarRegistryUrl+"/"+t;n.load(o,async a=>{await Yo().createBuiltinComponents(e,o,a,null,void 0),r(a.scene)},a=>{Ov&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),r(null)})})}cacheModel(e,t){}findAvatar(e){const t=e;let n=t;n.children.length==1&&(n=e.children[0]);let r=this.findAvatarPart(n,["head"]);const s=this.findAvatarPart(n,["left","hand"]),o=this.findAvatarPart(n,["right","hand"]);if(!r){r=t;const a=new S;new gi().setFromObject(r).getSize(a);const l=Math.max(a.x,a.y,a.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+l+" meters! Should be < 0.3m"),l>.3&&r.scale.multiplyScalar(1/l*.3)}return new K_(t,r,s,o)}findAvatarPart(e,t){const n=e.name.toLowerCase();let r=!0;for(const s of t){if(!r)break;n.indexOf(s)===-1&&(r=!1)}if(r)return e;if(e.children)for(const s of e.children){const o=this.findAvatarPart(s,t);if(o)return o}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}var Qne=Object.defineProperty,Hne=Object.getOwnPropertyDescriptor,oI=(i,e,t,n)=>{for(var r=n>1?void 0:n?Hne(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&Qne(e,t,r),r};class df extends Ie{constructor(){super(...arguments),h(this,"length",1),h(this,"depthTest",!0),h(this,"isGizmo",!0),h(this,"_axes",null)}onEnable(){if(this.isGizmo&&!wg)return;this._axes||(this._axes=new yo(this.length)),this._axes.layers.disableAll(),this._axes.layers.set(this.layer),this.gameObject.add(this._axes);const e=this._axes.material;e&&e.depthTest!==void 0&&(e.depthTest=this.depthTest)}onDisable(){this._axes&&this.gameObject.remove(this._axes)}}oI([x()],df.prototype,"length",2),oI([x()],df.prototype,"depthTest",2),oI([x()],df.prototype,"isGizmo",2);class aI extends Ie{constructor(){super(...arguments),h(this,"from"),h(this,"to"),h(this,"hint"),h(this,"desiredDistance",1)}onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;const e=Rt(this.to).clone(),t=Rt(this.from).clone(),n=e.distanceTo(t),r=e.clone();r.sub(t);const s=t.clone();s.add(e),s.multiplyScalar(.5);const o=Rt(this.hint).clone();o.sub(s);const a=new S;a.crossVectors(o,r),a.crossVectors(r,a),a.normalize();const l=n*.5,c=Math.max(this.desiredDistance,l),u=Math.sqrt(c*c-l*l),d=a.clone();d.multiplyScalar(u),d.add(s),Qr(this.gameObject,d);const p=s.clone();p.sub(a),this.gameObject.lookAt(p)}}const Vne=ee("debugusdzbehaviours");class Z_{constructor(){h(this,"behaviours",[]),h(this,"behaviourComponents",[]),h(this,"behaviourComponentsCopy",[])}get extensionName(){return"Behaviour"}addBehavior(e){this.behaviours.push(e)}onBeforeBuildDocument(e){const t=[];return e.root.traverse(n=>{re.foreachComponent(n,r=>{var s;const o=r;if(typeof o.createBehaviours=="function"||typeof o.beforeCreateDocument=="function"||typeof o.afterCreateDocument=="function"||typeof o.afterSerialize=="function"){this.behaviourComponents.push(o);const a=(s=o.beforeCreateDocument)==null?void 0:s.call(o,this,e);a instanceof Promise&&t.push(a)}},!1)}),Promise.all(t)}onExportObject(e,t,n){var r;for(const s of this.behaviourComponents)(r=s.createBehaviours)==null||r.call(s,this,t,n)}onAfterBuildDocument(e){for(const t of this.behaviourComponents)typeof t.afterCreateDocument=="function"&&t.afterCreateDocument(this,e);this.behaviourComponentsCopy=this.behaviourComponents.slice(),this.behaviourComponents.length=0}onAfterHierarchy(e,t){var n;if((n=this.behaviours)!=null&&n.length){t.beginBlock('def Scope "Behaviors"');for(const r of this.behaviours)r.writeTo(this,e.document,t);t.closeBlock()}}async onAfterSerialize(e){Vne&&console.log("onAfterSerialize behaviours",this.behaviourComponentsCopy);for(const t of this.behaviourComponentsCopy)typeof t.afterSerialize=="function"&&(t.afterSerialize.constructor.name==="AsyncFunction"?await t.afterSerialize(this,e):t.afterSerialize(this,e));this.behaviours.length=0}}var Wne=Object.defineProperty,qne=Object.getOwnPropertyDescriptor,lI=(i,e,t,n)=>{for(var r=n>1?void 0:n?qne(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&Wne(e,t,r),r},cI;const f4=(cI=class extends Yr{constructor(){super(...arguments),h(this,"threshold"),h(this,"intensity"),h(this,"scatter"),h(this,"selectiveBloom")}get typeName(){return"Bloom"}init(){this.threshold.defaultValue=1,this.intensity.defaultValue=0,this.scatter.defaultValue=.2,this.selectiveBloom?(this.threshold.valueProcessor=i=>i,this.intensity.valueProcessor=i=>i,this.scatter.valueProcessor=i=>1*Math.PI*(1-i)):(this.threshold.valueProcessor=i=>i,this.intensity.valueProcessor=i=>i,this.scatter.valueProcessor=i=>100*(1-i))}onCreateEffect(){let i;if(this.selectiveBloom==null&&(this.selectiveBloom=f4.useSelectiveBloom),this.selectiveBloom){const e=i=new EL(this.context.scene,this.context.mainCamera,{blendFunction:zt.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,intensity:this.intensity.value});e.inverted=!0}else i=new QE({blendFunction:zt.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,intensity:this.intensity.value});return this.intensity.onValueChanged=e=>{i.intensity=e},this.threshold.onValueChanged=e=>{i.luminanceMaterial.threshold=e},this.scatter.onValueChanged=e=>{i.luminancePass.enabled=!0,i.luminanceMaterial.smoothing=e},i}},h(cI,"useSelectiveBloom",!1),cI);let nd=f4;lI([x(Bt)],nd.prototype,"threshold",2),lI([x(Bt)],nd.prototype,"intensity",2),lI([x(Bt)],nd.prototype,"scatter",2),Fo("Bloom",nd);const pf="NEEDLE_progressive",Jr=ee("debugprogressive"),hI=Symbol("needle-progressive-texture"),ff=new Map;if(Jr){let i=function(){e+=1,$i(`Toggle LOD level: ${e}<br/>Registered objects: ${ff.size}`),console.log("Toggle LOD level",e,ff);const n=ii.Current;ff.forEach((r,s)=>{for(const o of r.keys){const a=s[o];if(a instanceof ut){const l=Ui.getMeshLODInformation(a),c=l?Math.min(e,l.lods.length):0;s["DEBUG:LOD"]=c,Ui.assignMeshLOD(n,r.sourceId,s,c),l&&(t=Math.max(t,l.lods.length-1))}else if(s instanceof It){Ui.assignTextureLOD(n,r.sourceId,s,e);break}}}),e>=t&&(e=-1)},e=-1,t=2;window.addEventListener("keyup",n=>{n.key==="p"&&i()}),ii.registerCallback(bn.ContextCreated,n=>{const r=document.createElement("button");r.innerText="Toggle Progressive",r.onclick=i,n.context.menu.appendChild(r)})}function m4(i,e,t){var n;if(!Jr)return;ff.has(i)||ff.set(i,{keys:[],sourceId:t});const r=ff.get(i);((n=r?.keys)==null?void 0:n.includes(e))==!1&&r.keys.push(e)}const $s=class{constructor(i,e,t){h(this,"parser"),h(this,"sourceId"),h(this,"context"),this.parser=i,this.sourceId=e,this.context=t}get name(){return pf}static getMeshLODInformation(i){const e=this.getAssignedLODInformation(i);return e!=null&&e.key?this.lodInfos.get(e.key):null}static hasLODLevelAvailable(i,e){var t;if(i instanceof It){for(const s of Object.keys(i)){const o=i[s];if(o instanceof gt&&this.hasLODLevelAvailable(o,e))return!0}return!1}else if(i instanceof os){for(const s of i.children)if(s instanceof ue&&this.hasLODLevelAvailable(s,e))return!0}let n,r;if(i instanceof ue?n=i.geometry:i instanceof gt&&(n=i),n&&(t=n?.userData)!=null&&t.LODS){const s=n.userData.LODS;if(r=this.lodInfos.get(s.key),e===void 0)return r!=null;if(r)return Array.isArray(r.lods)?e<r.lods.length:e===0}return!1}static assignMeshLOD(i,e,t,n){if(!t)return Promise.resolve(null);if(t instanceof ue){const r=t.geometry,s=this.getAssignedLODInformation(r);if(!s)return Promise.resolve(null);Vg(t)||a_(t,t.geometry);const o=this.onProgressiveLoadStart(i,e,t,null);return t["LOD:requested level"]=n,$s.getOrLoadLOD(i,e,r,n).then(a=>{if(t["LOD:requested level"]===n){if(delete t["LOD:requested level"],Array.isArray(a)){const l=s.index||0;a=a[l]}a&&r!=a&&(Jr=="verbose"&&console.log("Progressive Mesh "+t.name+" loaded",r,"\u2192",a,`
5482
5482
  `,t),a instanceof ut&&(t.geometry=a,Jr&&m4(t,"geometry",e)))}return this.onProgressiveLoadEnd(o),a}).catch(a=>(this.onProgressiveLoadEnd(o),console.error("Error loading mesh LOD",t,a),null))}else Jr&&console.error("Invalid call to assignMeshLOD: Request mesh LOD but the object is not a mesh",t);return Promise.resolve(null)}static assignTextureLOD(i,e,t,n=0){if(!t)return Promise.resolve(null);if(t instanceof It){const r=t,s=[],o=new Array;if(r instanceof Hm)for(const a of Object.keys(r.uniforms)){const l=r.uniforms[a].value;if(l instanceof gt){const c=this.assignTextureLODForSlot(i,e,l,n,r,a);s.push(c),o.push(a)}}else for(const a of Object.keys(r)){const l=r[a];if(l instanceof gt){const c=this.assignTextureLODForSlot(i,e,l,n,r,a);s.push(c),o.push(a)}}return Jm(s).then(a=>{const l=new Array;for(let c=0;c<a.results.length;c++){const u=a.results[c],d=o[c];u instanceof gt?l.push({slot:d,texture:u}):l.push({slot:d,texture:null})}return l})}if(t instanceof gt){const r=t;return this.assignTextureLODForSlot(i,e,r,n,null,null)}return Promise.resolve(null)}static assignTextureLODForSlot(i,e,t,n,r,s){if(t?.isTexture!==!0)return Promise.resolve(null);const o=this.onProgressiveLoadStart(i,e,r,s);return $s.getOrLoadLOD(i,e,t,n).then(a=>Array.isArray(a)?null:a?.isTexture===!0?(a!=t&&(r&&s&&(r[s]=a),Jr&&s&&r&&m4(r,s,e)),this.onProgressiveLoadEnd(o),a):(Jr&&console.warn("No LOD found for",n,t,a),this.onProgressiveLoadEnd(o),null)).catch(a=>(this.onProgressiveLoadEnd(o),console.error("Error loading LOD",t,a),null))}afterRoot(i){var e,t;Jr&&console.log("AFTER",this.sourceId,i),(e=this.parser.json.textures)==null||e.forEach((r,s)=>{if(r!=null&&r.extensions){const o=r?.extensions[pf];o&&this.parser.getDependency("texture",s).then(a=>{Jr&&console.log("> Progressive: register texture",s,a.name,a.uuid,a,o),a.source&&(a.source[hI]=o);const l=a.uuid;return a.userData||(a.userData={}),$s.assignLODInformation(a,l,0,0,void 0),$s.lodInfos.set(l,o),$s.lowresCache.set(l,a),a}).catch(a=>{console.error(`Error loading progressive texture ${s}
5483
5483
  `,a)})}}),(t=this.parser.json.meshes)==null||t.forEach((r,s)=>{if(r!=null&&r.extensions){const o=r?.extensions[pf];o&&o.lods&&this.parser.getDependency("mesh",s).then(a=>{Jr&&console.log("> Progressive: register mesh",s,a.name,o,a.uuid,a);const l=a.uuid,c=o.lods.length;if(a instanceof ue)n(l,a,c,void 0,o),$s.lowresCache.set(l,a.geometry);else{const u=new Array;for(let d=0;d<a.children.length;d++){const p=a.children[d];p instanceof ue&&(u.push(p.geometry),n(l,p,c,d,o))}$s.lowresCache.set(l,u)}return a}).catch(a=>{console.error(`Error loading progressive mesh ${s}
5484
5484
  `,a)})}});const n=(r,s,o,a,l)=>{const c=s.geometry;c["needle:raycast-mesh"]=!0,c&&!Vg(s)&&(Jr&&console.log("Set raycast mesh",s.name,s.uuid,c),a_(s,c),yb(c,!0).forEach(u=>{u instanceof ue&&a_(u,c)})),c.userData||(c.userData={}),$s.assignLODInformation(c,r,o,a,l.density),$s.lodInfos.set(r,l)};return null}static async getOrLoadLOD(i,e,t,n){var r,s,o;const a=Jr=="verbose",l=t.userData.LODS;if(!l)return null;const c=l?.key;let u;if(t instanceof gt&&t.source&&t.source[hI]&&(u=t.source[hI]),u||(u=$s.lodInfos.get(c)),u){if(n>0){let f=!1;const m=Array.isArray(u.lods);if(m&&n>=u.lods.length?f=!0:m||(f=!0),f)return this.lowresCache.get(c)}const d=Array.isArray(u.lods)?u.lods[n].path:u.lods;if(!d)return Jr&&!u["missing:uri"]&&(u["missing:uri"]=!0,console.warn("Missing uri for progressive asset for LOD "+n,u)),null;const p=kl(e,d);if(p.endsWith(".glb")||p.endsWith(".gltf")){if(!u.guid)return console.warn("missing pointer for glb/gltf texture",u),null;const f=p+"_"+u.guid,m=this.previouslyLoaded.get(f);if(m!==void 0){a&&console.log(`LOD ${n} was already loading/loaded: ${f}`);let g=await m.catch(b=>(console.error(`Error loading LOD ${n} from ${p}
@@ -6213,7 +6213,7 @@ Texture:`,n),this.setLightmapDebugMaterial()),this.applyLightmap())}updateLightm
6213
6213
  gl_FragColor = lightMapTexel;
6214
6214
  gl_FragColor.a = 1.;
6215
6215
  }
6216
- `,defines:{USE_LIGHTMAP:""}})}}var cse=Object.defineProperty,hse=Object.getOwnPropertyDescriptor,hc=(i,e,t,n)=>{for(var r=n>1?void 0:n?hse(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&cse(e,t,r),r};const Kv=ee("debugrenderer"),use=ee("debugskinnedmesh"),G4=ee("noinstancing"),ud=ee("debugprogressive"),Q4=ee("noprogressive"),dse=ee("wireframe");class kI{constructor(){h(this,"path",null),h(this,"asset",null),h(this,"default")}}class pse{constructor(e,t){h(this,"_renderer"),h(this,"_targets",[]),h(this,"_indexMapMaxIndex"),h(this,"_indexMap"),h(this,"_changed",!1),this._renderer=e;const n=this.setMaterial.bind(this),r=this.getMaterial.bind(this),s=e.gameObject;if(this._targets=[],s)switch(s.type){case"Group":this._targets=[...s.children];break;case"SkinnedMesh":case"Mesh":this._targets.push(s);break}let o=!1,a,l=0;for(let c=0;c<this._targets.length;c++){const u=this._targets[c];if(!u)continue;const d=u.material;if(d){d.shadowSide=d.side;for(let p=0;p<t.length;p++){const f=t[p];if(!f){o=!0;continue}if(d.name===f.name){a===void 0&&(a=new Map),a.set(p,c),l=Math.max(l,p);break}}}}if(o){this._indexMapMaxIndex=l,this._indexMap=a;const c=`Renderer ${e.name} was initialized with missing materials - this may lead to unexpected behaviour when trying to access sharedMaterials by index.`;console.warn(c),Bs()&&Qi("Found renderer with missing materials: please check the console for details.")}return new Proxy(this,{get(c,u){if(typeof u=="string"){const d=parseInt(u);if(!isNaN(d))return r(d)}return c[u]},set(c,u,d){return typeof u=="string"&&n(d,Number.parseInt(u)),Reflect.set(c,u,d)?(d instanceof It&&(c.changed=!0),!0):!1}})}get changed(){return this._changed}set changed(e){e===!0&&Kv&&console.warn("SharedMaterials have changed: "+this._renderer.name,this),this._changed=e}is(e){return this._renderer===e}get length(){return this._indexMapMaxIndex!==void 0?this._indexMapMaxIndex+1:this._targets.length}*[Symbol.iterator](){for(let e=0;e<this.length;e++)yield this.getMaterial(e)}resolveIndex(e){const t=this._indexMap;return t&&t.has(e)?t.get(e):e}setMaterial(e,t){if(t=this.resolveIndex(t),t<0||t>=this._targets.length)return;const n=this._targets[t];!n||n.material===void 0||(n.material=e,this.changed=!0)}getMaterial(e){if(e=this.resolveIndex(e),e<0)return null;const t=this._targets;if(e>=t.length)return null;const n=t[e];return n?n.material:null}}var LI;const Zv=(LI=class extends Ie{constructor(){super(...arguments),h(this,"receiveShadows",!1),h(this,"shadowCastingMode",0),h(this,"lightmapIndex",-1),h(this,"lightmapScaleOffset",new Ye(1,1,0,0)),h(this,"enableInstancing"),h(this,"renderOrder"),h(this,"allowOcclusionWhenDynamic",!0),h(this,"probeAnchor"),h(this,"reflectionProbeUsage",0),h(this,"_lightmaps"),h(this,"_sharedMeshes",[]),h(this,"_sharedMaterials"),h(this,"_originalMaterials"),h(this,"_lightmapTextureOverride"),h(this,"allowProgressiveLoading",!0),h(this,"_firstFrame",-1),h(this,"_isInstancingEnabled",!1),h(this,"handles"),h(this,"_wasVisible",!1),h(this,"onBeforeRenderThree",(i,e,t,n,r,s)=>{var o;if(!this._wasVisible&&this.context.time.frame>this._firstFrame+1&&(ud&&console.debug("onBeforeRenderThree: Object becomes visible for the first time",this.name,this.context.time.frame),this._wasVisible=!0),r.envMapIntensity!==void 0){const a=this.hasLightmap?Math.PI:1,l=((o=this.context.mainCameraComponent)==null?void 0:o.environmentIntensity)??1;r.envMapIntensity=Math.max(0,l*this.context.sceneLighting.environmentIntensity/a)}if(this._lightmaps)for(const a of this._lightmaps)a.updateLightmapUniforms(r)}),h(this,"automaticallyUpdateLODLevel",!0),h(this,"hasTextureLODs",!0),h(this,"hasMeshLODs",!0),h(this,"_lastLodLevel",-1),h(this,"_nextLodTestTime",0),h(this,"_randomLodLevelCheckFrameOffset",Math.floor(Math.random()*100)),h(this,"_sphere",new un),h(this,"_box",new gi),h(this,"_reflectionProbe",null)}static setInstanced(i,e){const t=Yg(i,Zv);return t.setInstancingEnabled(e),t}static isInstanced(i){const e=Qu(i,Zv);return e?e.isInstancingActive:qo.isUsingInstancing(i)}static setVisible(i,e){Sf(i,e)}get sharedMesh(){if(this.gameObject.type==="Mesh")return this.gameObject;if(this.gameObject.type==="SkinnesMesh")return this.gameObject;if(this.gameObject.type==="Group")return this.gameObject.children[0]}get sharedMeshes(){if(this.destroyed||!this.gameObject)return this._sharedMeshes;if(this._sharedMeshes.length=0,this.gameObject.type==="Group")for(const i of this.gameObject.children)(i.type==="Mesh"||i.type==="SkinnedMesh")&&this._sharedMeshes.push(i);else(this.gameObject.type==="Mesh"||this.gameObject.type==="SkinnedMesh")&&this._sharedMeshes.push(this.gameObject);return this._sharedMeshes}get sharedMaterial(){return this.sharedMaterials[0]}set sharedMaterial(i){this.sharedMaterials[0]!==i&&(this.sharedMaterials[0]=i,this.applyLightmapping())}get material(){return this.sharedMaterials[0]}set material(i){this.sharedMaterial=i}set sharedMaterials(i){if(!this._originalMaterials)this._originalMaterials=i;else if(i){let e=!1;for(let t=0;t<this._sharedMaterials.length;t++){const n=t<i.length?i[t]:null;n&&n instanceof It?this.sharedMaterials[t]=n:e||(e=!0,console.warn("Can not assign null as material: "+this.name,n))}}}get sharedMaterials(){return(!this._sharedMaterials||!this._sharedMaterials.is(this))&&(this._originalMaterials||(this._originalMaterials=[]),this._sharedMaterials=new pse(this,this._originalMaterials)),this._sharedMaterials}static get shouldSuppressInstancing(){return G4}get lightmap(){var i;return(i=this._lightmaps)!=null&&i.length?this._lightmaps[0].lightmap:null}set lightmap(i){var e;if(this._lightmapTextureOverride=i,i===void 0&&(i=this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex)),(e=this._lightmaps)!=null&&e.length)for(const t of this._lightmaps)t.lightmap=i}get hasLightmap(){return this.lightmap!=null}registering(){this.enabled||this.setVisibility(!1)}awake(){if(this._firstFrame=this.context.time.frame,Kv&&console.log("Renderer ",this.name,this),this.clearInstancingState(),this.probeAnchor&&Kv&&this.probeAnchor.add(new yo(.2)),this._reflectionProbe=null,this.isMultiMaterialObject(this.gameObject)){for(const i of this.gameObject.children)this.context.addBeforeRenderListener(i,this.onBeforeRenderThree),i.layers.mask=this.gameObject.layers.mask;if(this.renderOrder!==void 0){let i=0;for(let e=0;e<this.gameObject.children.length;e++){const t=this.gameObject.children[e];if(!(!this.isMeshOrSkinnedMesh(t)||re.getComponent(t,Zv))){if(this.renderOrder.length<=i){console.warn("Incorrect renderOrder element count",this,this.renderOrder.length+" but expected "+this.gameObject.children.length,"Index: "+i,"ChildElement:",t);continue}t.renderOrder=this.renderOrder[i],i+=1}}}}else this.isMeshOrSkinnedMesh(this.gameObject)?(this.context.addBeforeRenderListener(this.gameObject,this.onBeforeRenderThree),this.renderOrder!==void 0&&this.renderOrder.length>0&&(this.gameObject.renderOrder=this.renderOrder[0])):this.context.addBeforeRenderListener(this.gameObject,this.onBeforeRenderThree);if(this.applyLightmapping(),dse)for(let i=0;i<this.sharedMaterials.length;i++){const e=this.sharedMaterials[i];e&&(e.wireframe=!0)}}applyLightmapping(){var i;if(this.lightmapIndex>=0){const e=this.gameObject.type,t=this._lightmapTextureOverride!==void 0?this._lightmapTextureOverride:this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex);if(t){if(this._lightmaps||(this._lightmaps=[]),e==="Mesh"){const n=this.gameObject.material;if(n!=null&&n.isMeshBasicMaterial)n&&console.warn("Lightmapping is not supported on MeshBasicMaterial",n.name);else{if(this._lightmaps.length<=0){const r=new Jv(this.gameObject,this.context);this._lightmaps.push(r)}this._lightmaps[0].init(this.lightmapIndex,this.lightmapScaleOffset,t)}}else if(this.isMultiMaterialObject(this.gameObject)&&this.sharedMaterials.length>0)for(let n=0;n<this.gameObject.children.length;n++){const r=this.gameObject.children[n];if(!((i=r.material)!=null&&i.isMeshBasicMaterial)){let s;n>=this._lightmaps.length?(s=new Jv(r,this.context),this._lightmaps.push(s)):s=this._lightmaps[n],s.init(this.lightmapIndex,this.lightmapScaleOffset,t)}}}else Kv&&console.warn("Lightmap not found",this.sourceId,this.lightmapIndex)}}get isInstancingActive(){return this.handles!=null&&this.handles.length>0&&this._isInstancingEnabled}setInstancingEnabled(i){if(this._isInstancingEnabled===i)return i&&(this.handles===void 0||this.handles!=null&&this.handles.length>0);if(this._isInstancingEnabled=i,i){if(this.enableInstancing===void 0&&(this.enableInstancing=!0),this.handles===void 0){if(this.handles=Xv.instance.setup(this,this.gameObject,this.context,null,{rend:this,foundMeshes:0,useMatrixWorldAutoUpdate:this.useInstanceMatrixWorldAutoUpdate()}),this.handles)return re.markAsInstancedRendered(this.gameObject,!0),!0}else if(this.handles!==null){for(const e of this.handles)e.updateInstanceMatrix(!0),e.add();return re.markAsInstancedRendered(this.gameObject,!0),!0}}else{if(this.handles)for(const e of this.handles)e.remove(this.destroyed);return!0}return!1}clearInstancingState(){this._isInstancingEnabled=!1,this.handles=void 0}useInstanceMatrixWorldAutoUpdate(){return!0}start(){if(this.enableInstancing&&!G4&&(this.setInstancingEnabled(!0),qo.markDirty(this.gameObject)),this.gameObject.frustumCulled=this.allowOcclusionWhenDynamic,this.isMultiMaterialObject(this.gameObject))for(let i=0;i<this.gameObject.children.length;i++){const e=this.gameObject.children[i];e.frustumCulled=this.allowOcclusionWhenDynamic}}onEnable(){this.sharedMeshes,this.setVisibility(!0),this._isInstancingEnabled||this.enableInstancing?this.__internalDidAwakeAndStart&&this.setInstancingEnabled(!0):this.enabled&&this.applyStencil(),this.updateReflectionProbe(),this.testIfLODLevelsAreAvailable()}onDisable(){this.setVisibility(!1),this.handles&&this.handles.length>0&&this.setInstancingEnabled(!1)}onDestroy(){if(this.handles=null,this.isMultiMaterialObject(this.gameObject))for(const i of this.gameObject.children)this.context.removeBeforeRenderListener(i,this.onBeforeRenderThree);else this.context.removeBeforeRenderListener(this.gameObject,this.onBeforeRenderThree)}onBeforeRender(){var i,e;if(this.gameObject){if(Kv==this.name&&this.gameObject instanceof ue){this.gameObject.geometry.computeBoundingSphere();const t=Zi(this.gameObject.geometry.boundingSphere.center).applyMatrix4(this.gameObject.matrixWorld);Ct.DrawWireSphere(t,this.gameObject.geometry.boundingSphere.radius,56831)}if(this.isMultiMaterialObject(this.gameObject)&&((i=this.gameObject.children)==null?void 0:i.length)>0)for(const t of this.gameObject.children)this.applySettings(t);else this.applySettings(this.gameObject);if(this.sharedMaterials.changed&&(this.sharedMaterials.changed=!1,this.applyLightmapping()),(e=this.handles)!=null&&e.length&&this.gameObject[vg]===!0){this.gameObject[vg]=!1;for(let t=this.handles.length-1;t>=0;t--)this.handles[t].updateInstanceMatrix();this.gameObject.matrixWorldNeedsUpdate=!1}if(this.handles&&this.handles.length<=0&&re.markAsInstancedRendered(this.gameObject,!1),this._isInstancingEnabled&&this.handles)for(let t=0;t<this.handles.length;t++){const n=this.handles[t];Sf(n.object,!1)}this._wasVisible&&this.allowProgressiveLoading&&this.automaticallyUpdateLODLevel&&this.updateLODs(),this.reflectionProbeUsage!==0&&this._reflectionProbe&&this._reflectionProbe.onSet(this)}}onAfterRender(){if(this._isInstancingEnabled&&this.handles)for(let i=0;i<this.handles.length;i++){const e=this.handles[i];this._wasVisible=!0,Sf(e.object,!0)}this.reflectionProbeUsage!==0&&this._reflectionProbe&&this._reflectionProbe.onUnset(this),ud&&this._lastLodLevel>=0&&this.drawGizmoLodLevel(!1)}testIfLODLevelsAreAvailable(){this.automaticallyUpdateLODLevel=!1,this.hasMeshLODs=!1,this.hasTextureLODs=!1;for(const i of this.sharedMeshes)if(Ui.hasLODLevelAvailable(i)){this.automaticallyUpdateLODLevel=!0,this.hasMeshLODs=!0;break}for(const i of this.sharedMaterials)if(i&&Ui.hasLODLevelAvailable(i)){this.automaticallyUpdateLODLevel=!0,this.hasTextureLODs=!0;break}ud&&console.log(`${this.name}
6216
+ `,defines:{USE_LIGHTMAP:""}})}}var cse=Object.defineProperty,hse=Object.getOwnPropertyDescriptor,hc=(i,e,t,n)=>{for(var r=n>1?void 0:n?hse(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&cse(e,t,r),r};const Kv=ee("debugrenderer"),use=ee("debugskinnedmesh"),G4=ee("noinstancing"),ud=ee("debugprogressive"),Q4=ee("noprogressive"),dse=ee("wireframe");class kI{constructor(){h(this,"path",null),h(this,"asset",null),h(this,"default")}}class pse{constructor(e,t){h(this,"_renderer"),h(this,"_targets",[]),h(this,"_indexMapMaxIndex"),h(this,"_indexMap"),h(this,"_changed",!1),this._renderer=e;const n=this.setMaterial.bind(this),r=this.getMaterial.bind(this),s=e.gameObject;if(this._targets=[],s)switch(s.type){case"Group":this._targets=[...s.children];break;case"SkinnedMesh":case"Mesh":this._targets.push(s);break}let o=!1,a,l=0;for(let c=0;c<this._targets.length;c++){const u=this._targets[c];if(!u)continue;const d=u.material;if(d){d.shadowSide=d.side;for(let p=0;p<t.length;p++){const f=t[p];if(!f){o=!0;continue}if(d.name===f.name){a===void 0&&(a=new Map),a.set(p,c),l=Math.max(l,p);break}}}}if(o){this._indexMapMaxIndex=l,this._indexMap=a;const c=`Renderer ${e.name} was initialized with missing materials - this may lead to unexpected behaviour when trying to access sharedMaterials by index.`;console.warn(c),Bs()&&Qi("Found renderer with missing materials: please check the console for details.")}return new Proxy(this,{get(c,u){if(typeof u=="string"){const d=parseInt(u);if(!isNaN(d))return r(d)}return c[u]},set(c,u,d){return typeof u=="string"&&n(d,Number.parseInt(u)),Reflect.set(c,u,d)?(d instanceof It&&(c.changed=!0),!0):!1}})}get changed(){return this._changed}set changed(e){e===!0&&Kv&&console.warn("SharedMaterials have changed: "+this._renderer.name,this),this._changed=e}is(e){return this._renderer===e}get length(){return this._indexMapMaxIndex!==void 0?this._indexMapMaxIndex+1:this._targets.length}*[Symbol.iterator](){for(let e=0;e<this.length;e++)yield this.getMaterial(e)}resolveIndex(e){const t=this._indexMap;return t&&t.has(e)?t.get(e):e}setMaterial(e,t){if(t=this.resolveIndex(t),t<0||t>=this._targets.length)return;const n=this._targets[t];!n||n.material===void 0||(n.material=e,this.changed=!0)}getMaterial(e){if(e=this.resolveIndex(e),e<0)return null;const t=this._targets;if(e>=t.length)return null;const n=t[e];return n?n.material:null}}var LI;const Zv=(LI=class extends Ie{constructor(){super(...arguments),h(this,"receiveShadows",!1),h(this,"shadowCastingMode",0),h(this,"lightmapIndex",-1),h(this,"lightmapScaleOffset",new Ye(1,1,0,0)),h(this,"enableInstancing"),h(this,"renderOrder"),h(this,"allowOcclusionWhenDynamic",!0),h(this,"probeAnchor"),h(this,"reflectionProbeUsage",0),h(this,"_lightmaps"),h(this,"_sharedMeshes",[]),h(this,"_sharedMaterials"),h(this,"_originalMaterials"),h(this,"_lightmapTextureOverride"),h(this,"allowProgressiveLoading",!0),h(this,"_firstFrame",-1),h(this,"_isInstancingEnabled",!1),h(this,"handles"),h(this,"_wasVisible",!1),h(this,"onBeforeRenderThree",(i,e,t,n,r,s)=>{var o;if(!this._wasVisible&&this.context.time.frame>this._firstFrame+1&&(ud&&console.debug("onBeforeRenderThree: Object becomes visible for the first time",this.name,this.context.time.frame),this._wasVisible=!0),r.envMapIntensity!==void 0){const a=this.hasLightmap?Math.PI:1,l=((o=this.context.mainCameraComponent)==null?void 0:o.environmentIntensity)??1;r.envMapIntensity=Math.max(0,l*this.context.sceneLighting.environmentIntensity/a)}if(this._lightmaps)for(const a of this._lightmaps)a.updateLightmapUniforms(r)}),h(this,"automaticallyUpdateLODLevel",!0),h(this,"hasTextureLODs",!0),h(this,"hasMeshLODs",!0),h(this,"_lastLodLevel",-1),h(this,"_nextLodTestTime",0),h(this,"_randomLodLevelCheckFrameOffset",Math.floor(Math.random()*100)),h(this,"_sphere",new un),h(this,"_box",new gi),h(this,"_reflectionProbe",null)}static setInstanced(i,e){const t=Yg(i,Zv);return t.setInstancingEnabled(e),t}static isInstanced(i){const e=Qu(i,Zv);return e?e.isInstancingActive:qo.isUsingInstancing(i)}static setVisible(i,e){Sf(i,e)}get sharedMesh(){if(this.gameObject.type==="Mesh")return this.gameObject;if(this.gameObject.type==="SkinnesMesh")return this.gameObject;if(this.gameObject.type==="Group")return this.gameObject.children[0]}get sharedMeshes(){if(this.destroyed||!this.gameObject)return this._sharedMeshes;if(this._sharedMeshes.length=0,this.gameObject.type==="Group")for(const i of this.gameObject.children)(i.type==="Mesh"||i.type==="SkinnedMesh")&&this._sharedMeshes.push(i);else(this.gameObject.type==="Mesh"||this.gameObject.type==="SkinnedMesh")&&this._sharedMeshes.push(this.gameObject);return this._sharedMeshes}get sharedMaterial(){return this.sharedMaterials[0]}set sharedMaterial(i){this.sharedMaterials[0]!==i&&(this.sharedMaterials[0]=i,this.applyLightmapping())}get material(){return this.sharedMaterials[0]}set material(i){this.sharedMaterial=i}set sharedMaterials(i){if(!this._originalMaterials)this._originalMaterials=i;else if(i){let e=!1;for(let t=0;t<this._sharedMaterials.length;t++){const n=t<i.length?i[t]:null;n&&n instanceof It?this.sharedMaterials[t]=n:e||(e=!0,console.warn("Can not assign null as material: "+this.name,n))}}}get sharedMaterials(){return(!this._sharedMaterials||!this._sharedMaterials.is(this))&&(this._originalMaterials||(this._originalMaterials=[]),this._sharedMaterials=new pse(this,this._originalMaterials)),this._sharedMaterials}static get shouldSuppressInstancing(){return G4}get lightmap(){var i;return(i=this._lightmaps)!=null&&i.length?this._lightmaps[0].lightmap:null}set lightmap(i){var e;if(this._lightmapTextureOverride=i,i===void 0&&(i=this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex)),(e=this._lightmaps)!=null&&e.length)for(const t of this._lightmaps)t.lightmap=i}get hasLightmap(){return this.lightmap!=null}registering(){this.enabled||this.setVisibility(!1)}awake(){if(this._firstFrame=this.context.time.frame,Kv&&console.log("Renderer ",this.name,this),this.clearInstancingState(),this.probeAnchor&&Kv&&this.probeAnchor.add(new yo(.2)),this._reflectionProbe=null,this.isMultiMaterialObject(this.gameObject)){for(const i of this.gameObject.children)this.context.addBeforeRenderListener(i,this.onBeforeRenderThree),i.layers.mask=this.gameObject.layers.mask;if(this.renderOrder!==void 0){let i=0;for(let e=0;e<this.gameObject.children.length;e++){const t=this.gameObject.children[e];if(!(!this.isMeshOrSkinnedMesh(t)||re.getComponent(t,Zv))){if(this.renderOrder.length<=i){console.warn("Incorrect renderOrder element count",this,this.renderOrder.length+" but expected "+this.gameObject.children.length,"Index: "+i,"ChildElement:",t);continue}t.renderOrder=this.renderOrder[i],i+=1}}}}else this.isMeshOrSkinnedMesh(this.gameObject)?(this.context.addBeforeRenderListener(this.gameObject,this.onBeforeRenderThree),this.renderOrder!==void 0&&this.renderOrder.length>0&&(this.gameObject.renderOrder=this.renderOrder[0])):this.context.addBeforeRenderListener(this.gameObject,this.onBeforeRenderThree);if(this.applyLightmapping(),dse)for(let i=0;i<this.sharedMaterials.length;i++){const e=this.sharedMaterials[i];e&&(e.wireframe=!0)}}applyLightmapping(){var i;if(this.lightmapIndex>=0){const e=this.gameObject.type,t=this._lightmapTextureOverride!==void 0?this._lightmapTextureOverride:this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex);if(t){if(this._lightmaps||(this._lightmaps=[]),e==="Mesh"){const n=this.gameObject.material;if(n!=null&&n.isMeshBasicMaterial)n&&console.warn("Lightmapping is not supported on MeshBasicMaterial",n.name);else{if(this._lightmaps.length<=0){const r=new Jv(this.gameObject,this.context);this._lightmaps.push(r)}this._lightmaps[0].init(this.lightmapIndex,this.lightmapScaleOffset,t)}}else if(this.isMultiMaterialObject(this.gameObject)&&this.sharedMaterials.length>0)for(let n=0;n<this.gameObject.children.length;n++){const r=this.gameObject.children[n];if(!((i=r.material)!=null&&i.isMeshBasicMaterial)){let s;n>=this._lightmaps.length?(s=new Jv(r,this.context),this._lightmaps.push(s)):s=this._lightmaps[n],s.init(this.lightmapIndex,this.lightmapScaleOffset,t)}}}else Kv&&console.warn("Lightmap not found",this.sourceId,this.lightmapIndex)}}get isInstancingActive(){return this.handles!=null&&this.handles.length>0&&this._isInstancingEnabled}setInstancingEnabled(i){if(this._isInstancingEnabled===i)return i&&(this.handles===void 0||this.handles!=null&&this.handles.length>0);if(this._isInstancingEnabled=i,i){if(this.enableInstancing===void 0&&(this.enableInstancing=!0),this.handles===void 0){if(this.handles=Xv.instance.setup(this,this.gameObject,this.context,null,{rend:this,foundMeshes:0,useMatrixWorldAutoUpdate:this.useInstanceMatrixWorldAutoUpdate()}),this.handles)return re.markAsInstancedRendered(this.gameObject,!0),!0}else if(this.handles!==null){for(const e of this.handles)e.updateInstanceMatrix(!0),e.add();return re.markAsInstancedRendered(this.gameObject,!0),!0}}else{if(this.handles)for(const e of this.handles)e.remove(this.destroyed);return!0}return!1}clearInstancingState(){this._isInstancingEnabled=!1,this.handles=void 0}useInstanceMatrixWorldAutoUpdate(){return!0}start(){if(this.enableInstancing&&!G4&&(this.setInstancingEnabled(!0),qo.markDirty(this.gameObject)),this.gameObject.frustumCulled=this.allowOcclusionWhenDynamic,this.isMultiMaterialObject(this.gameObject))for(let i=0;i<this.gameObject.children.length;i++){const e=this.gameObject.children[i];e.frustumCulled=this.allowOcclusionWhenDynamic}}onEnable(){this.sharedMeshes,this.setVisibility(!0),this._isInstancingEnabled||this.enableInstancing==!0||Array.isArray(this.enableInstancing)&&this.enableInstancing.some(i=>i)?this.__internalDidAwakeAndStart&&this.setInstancingEnabled(!0):this.enabled&&this.applyStencil(),this.updateReflectionProbe(),this.testIfLODLevelsAreAvailable()}onDisable(){this.setVisibility(!1),this.handles&&this.handles.length>0&&this.setInstancingEnabled(!1)}onDestroy(){if(this.handles=null,this.isMultiMaterialObject(this.gameObject))for(const i of this.gameObject.children)this.context.removeBeforeRenderListener(i,this.onBeforeRenderThree);else this.context.removeBeforeRenderListener(this.gameObject,this.onBeforeRenderThree)}onBeforeRender(){var i,e;if(this.gameObject){if(Kv==this.name&&this.gameObject instanceof ue){this.gameObject.geometry.computeBoundingSphere();const t=Zi(this.gameObject.geometry.boundingSphere.center).applyMatrix4(this.gameObject.matrixWorld);Ct.DrawWireSphere(t,this.gameObject.geometry.boundingSphere.radius,56831)}if(this.isMultiMaterialObject(this.gameObject)&&((i=this.gameObject.children)==null?void 0:i.length)>0)for(const t of this.gameObject.children)this.applySettings(t);else this.applySettings(this.gameObject);if(this.sharedMaterials.changed&&(this.sharedMaterials.changed=!1,this.applyLightmapping()),(e=this.handles)!=null&&e.length&&this.gameObject[vg]===!0){this.gameObject[vg]=!1;for(let t=this.handles.length-1;t>=0;t--)this.handles[t].updateInstanceMatrix();this.gameObject.matrixWorldNeedsUpdate=!1}if(this.handles&&this.handles.length<=0&&re.markAsInstancedRendered(this.gameObject,!1),this._isInstancingEnabled&&this.handles)for(let t=0;t<this.handles.length;t++){const n=this.handles[t];Sf(n.object,!1)}this._wasVisible&&this.allowProgressiveLoading&&this.automaticallyUpdateLODLevel&&this.updateLODs(),this.reflectionProbeUsage!==0&&this._reflectionProbe&&this._reflectionProbe.onSet(this)}}onAfterRender(){if(this._isInstancingEnabled&&this.handles)for(let i=0;i<this.handles.length;i++){const e=this.handles[i];this._wasVisible=!0,Sf(e.object,!0)}this.reflectionProbeUsage!==0&&this._reflectionProbe&&this._reflectionProbe.onUnset(this),ud&&this._lastLodLevel>=0&&this.drawGizmoLodLevel(!1)}testIfLODLevelsAreAvailable(){this.automaticallyUpdateLODLevel=!1,this.hasMeshLODs=!1,this.hasTextureLODs=!1;for(const i of this.sharedMeshes)if(Ui.hasLODLevelAvailable(i)){this.automaticallyUpdateLODLevel=!0,this.hasMeshLODs=!0;break}for(const i of this.sharedMaterials)if(i&&Ui.hasLODLevelAvailable(i)){this.automaticallyUpdateLODLevel=!0,this.hasTextureLODs=!0;break}ud&&console.log(`${this.name}
6217
6217
  Mesh LODs available? ${this.hasMeshLODs?"YES":"NO"}
6218
6218
  Texture LODs available? ${this.hasTextureLODs?"YES":"NO"}`)}updateLODs(){let i=0;this.hasMeshLODs&&(i=this.calculateLodLevel());const e=0;for(const t of this.sharedMaterials)t&&this.loadProgressiveTextures(t,e);if(i>=0)for(let t=0;t<this.sharedMeshes.length;t++){const n=this.sharedMeshes[t];n&&this.loadProgressiveMeshes(n,i)}}calculateLodLevel(i=!1){var e;if(!i&&(this.context.time.frame+this._randomLodLevelCheckFrameOffset)%3!=0)return this._lastLodLevel;if(this.context.time.realtimeSinceStartup<this._nextLodTestTime)return this._lastLodLevel;const t=10;let n=t+1;if(this.context.mainCamera){const r=ra()?.6:.4;for(const s of this.sharedMeshes){if(n<=0)break;if(!s)continue;if(ud&&s["DEBUG:LOD"]!=null)return this._lastLodLevel=s["DEBUG:LOD"];let o=0;const a=Ui.getMeshLODInformation(s.geometry);a?.density!=null&&(o=Math.log2(a.density||0)/2-6);const l=(e=this.context.mainCameraComponent)==null?void 0:e.getFrustum();if(!(l!=null&&l.intersectsObject(s))){if(ud&&s.geometry.boundingSphere){const u=s.geometry.boundingSphere;this._sphere.copy(u),this._sphere.applyMatrix4(s.matrixWorld),Ct.DrawWireSphere(this._sphere.center,this._sphere.radius*1.01,16733525,.5)}continue}const c=s.geometry.boundingBox;if(c&&this.context.mainCamera instanceof kt){if(s.geometry.attributes.color&&s.geometry.attributes.color.count<100&&s.geometry.boundingSphere&&(this._sphere.copy(s.geometry.boundingSphere),this._sphere.applyMatrix4(s.matrixWorld),this._sphere.containsPoint(Rt(this.context.mainCamera)))){n=0;break}this._box.copy(c),this._box.applyMatrix4(s.matrixWorld),this._box.applyMatrix4(this.context.mainCameraComponent.getProjectionScreenMatrix(Zv.tempMatrix));let u=this._box.getSize(Zi()).y/2;u/=Math.pow(2,o-.5);let d=999,p=r;for(let f=0;f<t;f++){if(u>p){d=f;break}p/=2}d<n&&(n=d)}}}return n=Math.round(n),this._lastLodLevel!=n&&(this._nextLodTestTime=this.context.time.realtimeSinceStartup+.5,ud&&(ud=="verbose"&&console.warn(`LOD Level changed from ${this._lastLodLevel} to ${n} for ${this.name}`),this.drawGizmoLodLevel(!0))),this._lastLodLevel=n,n}drawGizmoLodLevel(i){const e=this._lastLodLevel,t=this.context.mainCamera.worldForward,n=this.context.mainCamera.worldPosition;for(const r of this.sharedMeshes)if(r&&r.geometry.boundingSphere){const s=r.geometry.boundingSphere;this._sphere.copy(s),this._sphere.applyMatrix4(r.matrixWorld);const o=this._sphere.center,a=this._sphere.radius,l=["#76c43e","#bcc43e","#c4ac3e","#c4673e","#ff3e3e"];if(i)Ct.DrawWireSphere(o,a,l[e],.1);else{const c="LOD "+e+`
6219
6219
  `+r.geometry.index.count/3,u=Zi(t).multiplyScalar(a*.7).add(o),d=u.distanceTo(n);r.geometry.index.count/3;const p=l[Math.min(l.length-1,e)]+"88",f=Math.min(10,a);Ct.DrawLabel(u,c,d*.001+f*.03,void 0,16777215,p)}}}applyStencil(){II.applyStencil(this)}loadProgressiveTextures(i,e){return!Q4&&i&&this.allowProgressiveLoading&&(i.userData||(i.userData={}),i.userData.LOD!==e)?(i.userData.LOD=e,Ui.assignTextureLOD(this.context,this.sourceId,i,e)):Promise.resolve(!0)}loadProgressiveMeshes(i,e){if(!Q4&&i&&this.allowProgressiveLoading&&(i.userData||(i.userData={}),i.userData.LOD!==e)){i.userData.LOD=e;const t=i.geometry;return Ui.assignMeshLOD(this.context,this.sourceId,i,e).then(n=>{if(n&&i.userData.LOD==e&&t!=i.geometry&&(this.applyLightmapping(),this.handles))for(const r of this.handles)r.setGeometry(i.geometry)})}return!0}applySettings(i){i.receiveShadow=this.receiveShadows,this.shadowCastingMode==1?i.castShadow=!0:i.castShadow=!1}updateReflectionProbe(){if(this._reflectionProbe=null,this.reflectionProbeUsage!==0){if(!this.probeAnchor)return;this.startCoroutine(this._updateReflectionProbe(),Pn.LateUpdate)}}*_updateReflectionProbe(){const i=this.probeAnchor||this.gameObject,e=!!this.probeAnchor;this._reflectionProbe=Cf.get(i,this.context,e,this.probeAnchor)}setVisibility(i){if(!this.isMultiMaterialObject(this.gameObject))Sf(this.gameObject,i);else for(const e of this.gameObject.children)this.isMeshOrSkinnedMesh(e)&&Sf(e,i)}isMultiMaterialObject(i){return i.type==="Group"}isMeshOrSkinnedMesh(i){return i.type==="Mesh"||i.type==="SkinnedMesh"}},h(LI,"tempMatrix",new Ce),LI);let Sn=Zv;hc([x()],Sn.prototype,"receiveShadows",2),hc([x()],Sn.prototype,"shadowCastingMode",2),hc([x()],Sn.prototype,"lightmapIndex",2),hc([x(Ye)],Sn.prototype,"lightmapScaleOffset",2),hc([x()],Sn.prototype,"enableInstancing",2),hc([x()],Sn.prototype,"renderOrder",2),hc([x()],Sn.prototype,"allowOcclusionWhenDynamic",2),hc([x(ge)],Sn.prototype,"probeAnchor",2),hc([x()],Sn.prototype,"reflectionProbeUsage",2);class $v extends Sn{}class UI extends $v{constructor(){super(...arguments),h(this,"_needUpdateBoundingSphere",!1)}awake(){var e;super.awake(),this.allowOcclusionWhenDynamic=!1,(e=this.gameObject.parent)==null||e.updateWorldMatrix(!1,!0),this.markBoundsDirty()}onAfterRender(){if(super.onAfterRender(),this.gameObject instanceof Ao&&this._needUpdateBoundingSphere){this._needUpdateBoundingSphere=!1;const e=this.gameObject.geometry,t=Vg(this.gameObject);t&&(this.gameObject.geometry=t),this.gameObject.computeBoundingSphere(),this.gameObject.geometry=e}if(use&&this.gameObject instanceof Ao&&this.gameObject.boundingSphere){const e=Zi(this.gameObject.boundingSphere.center).applyMatrix4(this.gameObject.matrixWorld);Ct.DrawWireSphere(e,this.gameObject.boundingSphere.radius,"red")}}markBoundsDirty(){this._needUpdateBoundingSphere=!0}}var fse=Object.defineProperty,mse=Object.getOwnPropertyDescriptor,ie=(i,e,t,n)=>{for(var r=n>1?void 0:n?mse(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&fse(e,t,r),r};const vx=ee("debugparticles");var uc=(i=>(i[i.Billboard=0]="Billboard",i[i.Stretch=1]="Stretch",i[i.HorizontalBillboard=2]="HorizontalBillboard",i[i.VerticalBillboard=3]="VerticalBillboard",i[i.Mesh=4]="Mesh",i))(uc||{});let Ch=class{constructor(){h(this,"alphaKeys"),h(this,"colorKeys")}get duration(){return 1}evaluate(i,e){let t,n=0,r=null,s=0;for(let o=0;o<this.alphaKeys.length;o++){const a=this.alphaKeys[o];(a.time<i||!t)&&(t=a,n=o)}for(let o=0;o<this.colorKeys.length;o++){const a=this.colorKeys[o];(a.time<i||!r)&&(r=a,s=o)}if(r)if(s+1<this.colorKeys.length){const o=this.colorKeys[s+1],a=Ze.remap(i,r.time,o.time,0,1);e.r=Ze.lerp(r.color.r,o.color.r,a),e.g=Ze.lerp(r.color.g,o.color.g,a),e.b=Ze.lerp(r.color.b,o.color.b,a)}else e.r=r.color.r,e.g=r.color.g,e.b=r.color.b;if(t)if(n+1<this.alphaKeys.length){const o=this.alphaKeys[n+1],a=Ze.remap(i,t.time,o.time,0,1);e.alpha=Ze.lerp(t.alpha,o.alpha,a)}else e.alpha=t.alpha;return e}};ie([x()],Ch.prototype,"alphaKeys",2),ie([x()],Ch.prototype,"colorKeys",2);var e0=(i=>(i[i.Local=0]="Local",i[i.World=1]="World",i[i.Custom=2]="Custom",i))(e0||{}),Ax=(i=>(i[i.Sphere=0]="Sphere",i[i.SphereShell=1]="SphereShell",i[i.Hemisphere=2]="Hemisphere",i[i.HemisphereShell=3]="HemisphereShell",i[i.Cone=4]="Cone",i[i.Box=5]="Box",i[i.Mesh=6]="Mesh",i[i.ConeShell=7]="ConeShell",i[i.ConeVolume=8]="ConeVolume",i[i.ConeVolumeShell=9]="ConeVolumeShell",i[i.Circle=10]="Circle",i[i.CircleEdge=11]="CircleEdge",i[i.SingleSidedEdge=12]="SingleSidedEdge",i[i.MeshRenderer=13]="MeshRenderer",i[i.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",i[i.BoxShell=15]="BoxShell",i[i.BoxEdge=16]="BoxEdge",i[i.Donut=17]="Donut",i[i.Rectangle=18]="Rectangle",i[i.Sprite=19]="Sprite",i[i.SpriteRenderer=20]="SpriteRenderer",i))(Ax||{});const H4=class{constructor(){h(this,"mode"),h(this,"constant"),h(this,"constantMin"),h(this,"constantMax"),h(this,"curve"),h(this,"curveMin"),h(this,"curveMax"),h(this,"curveMultiplier")}clone(){var i,e,t;const n=new H4;return n.mode=this.mode,n.constant=this.constant,n.constantMin=this.constantMin,n.constantMax=this.constantMax,n.curve=(i=this.curve)==null?void 0:i.clone(),n.curveMin=(e=this.curveMin)==null?void 0:e.clone(),n.curveMax=(t=this.curveMax)==null?void 0:t.clone(),n.curveMultiplier=this.curveMultiplier,n}evaluate(i,e){const t=e===void 0?Math.random():e;switch(this.mode){case 0:return this.constant;case 1:return i=Ze.clamp01(i),this.curve.evaluate(i)*this.curveMultiplier;case 2:const n=i*this.curveMin.duration,r=i*this.curveMax.duration;return Ze.lerp(this.curveMin.evaluate(n),this.curveMax.evaluate(r),t%1)*this.curveMultiplier;case 3:return Ze.lerp(this.constantMin,this.constantMax,t%1);default:this.curveMax.evaluate(i)*this.curveMultiplier;break}return 0}getMax(){switch(this.mode){case 0:return this.constant;case 1:return this.getMaxFromCurve(this.curve)*this.curveMultiplier;case 2:return Math.max(this.getMaxFromCurve(this.curveMin),this.getMaxFromCurve(this.curveMax))*this.curveMultiplier;case 3:return Math.max(this.constantMin,this.constantMax);default:return 0}}getMaxFromCurve(i){if(!i)return 0;let e=Number.MIN_VALUE;for(let t=0;t<i.keys.length;t++){const n=i.keys[t];n.value>e&&(e=n.value)}return e}};let lt=H4;ie([x()],lt.prototype,"mode",2),ie([x()],lt.prototype,"constant",2),ie([x()],lt.prototype,"constantMin",2),ie([x()],lt.prototype,"constantMax",2),ie([x(Xu)],lt.prototype,"curve",2),ie([x(Xu)],lt.prototype,"curveMin",2),ie([x(Xu)],lt.prototype,"curveMax",2),ie([x()],lt.prototype,"curveMultiplier",2);var yx;const ba=(yx=class{constructor(){h(this,"mode"),h(this,"color"),h(this,"colorMin"),h(this,"colorMax"),h(this,"gradient"),h(this,"gradientMin"),h(this,"gradientMax")}evaluate(i,e){const t=e===void 0?Math.random():e;switch(this.mode){case 0:return this.color;case 1:return this.gradient.evaluate(i,ba._temp),ba._temp;case 2:return ba._temp.lerpColors(this.colorMin,this.colorMax,t);case 3:return this.gradientMin.evaluate(i,ba._temp),this.gradientMax.evaluate(i,ba._temp2),ba._temp.lerp(ba._temp2,t)}return ba._temp.set(16711935),ba._temp.alpha=1,ba._temp}},h(yx,"_temp",new yi(0,0,0,1)),h(yx,"_temp2",new yi(0,0,0,1)),yx);let Ls=ba;ie([x(yi)],Ls.prototype,"color",2),ie([x(yi)],Ls.prototype,"colorMin",2),ie([x(yi)],Ls.prototype,"colorMax",2),ie([x(Ch)],Ls.prototype,"gradient",2),ie([x(Ch)],Ls.prototype,"gradientMin",2),ie([x(Ch)],Ls.prototype,"gradientMax",2);var FI=(i=>(i[i.Hierarchy=0]="Hierarchy",i[i.Local=1]="Local",i[i.Shape=2]="Shape",i))(FI||{});class Ir{constructor(){h(this,"cullingMode"),h(this,"duration"),h(this,"emitterVelocityMode"),h(this,"flipRotation"),h(this,"gravityModifier"),h(this,"gravityModifierMultiplier"),h(this,"loop"),h(this,"maxParticles"),h(this,"playOnAwake"),h(this,"prewarm"),h(this,"ringBufferLoopRange"),h(this,"ringBufferMode"),h(this,"scalingMode"),h(this,"simulationSpace"),h(this,"simulationSpeed"),h(this,"startColor"),h(this,"startDelay"),h(this,"startDelayMultiplier"),h(this,"startLifetime"),h(this,"startLifetimeMultiplier"),h(this,"startRotation"),h(this,"startRotationMultiplier"),h(this,"startRotation3D"),h(this,"startRotationX"),h(this,"startRotationXMultiplier"),h(this,"startRotationY"),h(this,"startRotationYMultiplier"),h(this,"startRotationZ"),h(this,"startRotationZMultiplier"),h(this,"startSize"),h(this,"startSize3D"),h(this,"startSizeMultiplier"),h(this,"startSizeX"),h(this,"startSizeXMultiplier"),h(this,"startSizeY"),h(this,"startSizeYMultiplier"),h(this,"startSizeZ"),h(this,"startSizeZMultiplier"),h(this,"startSpeed"),h(this,"startSpeedMultiplier"),h(this,"stopAction"),h(this,"useUnscaledTime")}}ie([x(lt)],Ir.prototype,"gravityModifier",2),ie([x(Ls)],Ir.prototype,"startColor",2),ie([x(lt)],Ir.prototype,"startDelay",2),ie([x(lt)],Ir.prototype,"startLifetime",2),ie([x(lt)],Ir.prototype,"startRotation",2),ie([x(lt)],Ir.prototype,"startRotationX",2),ie([x(lt)],Ir.prototype,"startRotationY",2),ie([x(lt)],Ir.prototype,"startRotationZ",2),ie([x(lt)],Ir.prototype,"startSize",2),ie([x(lt)],Ir.prototype,"startSizeX",2),ie([x(lt)],Ir.prototype,"startSizeY",2),ie([x(lt)],Ir.prototype,"startSizeZ",2),ie([x(lt)],Ir.prototype,"startSpeed",2);class t0{constructor(){h(this,"cycleCount"),h(this,"maxCount"),h(this,"minCount"),h(this,"probability"),h(this,"repeatInterval"),h(this,"time"),h(this,"count"),h(this,"_performed",0)}reset(){this._performed=0}run(e){if(e<=this.time)return 0;let t=0;if(this.cycleCount===0||this._performed<this.cycleCount){const n=this.time+this.repeatInterval*this._performed;if(e>=n&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:t=this.count.constant;break;case 3:t=Ze.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:t=this.count.curve.evaluate(Math.random());break;case 2:const r=Math.random();t=Ze.lerp(this.count.curveMin.evaluate(r),this.count.curveMax.evaluate(r),Math.random());break}}return t}}class el{constructor(){h(this,"enabled"),h(this,"bursts"),h(this,"rateOverTime"),h(this,"rateOverTimeMultiplier"),h(this,"rateOverDistance"),h(this,"rateOverDistanceMultiplier"),h(this,"system")}get burstCount(){var e;return((e=this.bursts)==null?void 0:e.length)??0}reset(){var e;(e=this.bursts)==null||e.forEach(t=>t.reset())}getBurst(){let e=0;if(this.burstCount>0)for(let t=0;t<this.burstCount;t++){const n=this.bursts[t];this.system.main.loop&&n.time>=this.system.time&&n.reset(),e+=Math.round(n.run(this.system.time))}return e}}ie([x()],el.prototype,"enabled",2),ie([x()],el.prototype,"bursts",2),ie([x(lt)],el.prototype,"rateOverTime",2),ie([x()],el.prototype,"rateOverTimeMultiplier",2),ie([x(lt)],el.prototype,"rateOverDistance",2),ie([x()],el.prototype,"rateOverDistanceMultiplier",2);class i0{constructor(){h(this,"enabled"),h(this,"color")}}ie([x(Ls)],i0.prototype,"color",2);class Eh{constructor(){h(this,"enabled"),h(this,"separateAxes"),h(this,"size"),h(this,"sizeMultiplier"),h(this,"x"),h(this,"xMultiplier"),h(this,"y"),h(this,"yMultiplier"),h(this,"z"),h(this,"zMultiplier"),h(this,"_time",0),h(this,"_temp",new S)}evaluate(e,t,n){if(t||(t=this._temp),!this.enabled)return t.x=t.y=t.z=1,t;if(this.separateAxes)t.x=this.x.evaluate(e,n)*this.xMultiplier,t.y=this.y.evaluate(e,n)*this.yMultiplier,t.z=this.z.evaluate(e,n)*this.zMultiplier;else{const r=this.size.evaluate(e,n)*this.sizeMultiplier;t.x=r}return t}}ie([x(lt)],Eh.prototype,"size",2),ie([x(lt)],Eh.prototype,"x",2),ie([x(lt)],Eh.prototype,"y",2),ie([x(lt)],Eh.prototype,"z",2);var bx;const n0=(bx=class{constructor(){h(this,"shapeType",5),h(this,"enabled",!0),h(this,"alignToDirection",!1),h(this,"angle",0),h(this,"arc",360),h(this,"arcSpread"),h(this,"arcSpeedMultiplier"),h(this,"arcMode"),h(this,"boxThickness"),h(this,"position"),h(this,"rotation"),h(this,"_rotation",new Fi),h(this,"scale"),h(this,"radius"),h(this,"radiusThickness"),h(this,"sphericalDirectionAmount"),h(this,"randomDirectionAmount"),h(this,"randomPositionAmount"),h(this,"meshShapeType"),h(this,"meshRenderer"),h(this,"_meshObj"),h(this,"_meshGeometry"),h(this,"system"),h(this,"_space"),h(this,"_worldSpaceMatrix",new Ce),h(this,"_worldSpaceMatrixInverse",new Ce),h(this,"_vector",new S(0,0,0)),h(this,"_temp",new S(0,0,0)),h(this,"_triangle",new Es),h(this,"_dir",new S),h(this,"_loopTime",0),h(this,"_loopDirection",1),vx&&console.log(this)}get type(){return Ax[this.shapeType]}initialize(i){this.onInitialize(i),i.position.copy(this._vector)}toJSON(){return this}clone(){return new n0}setMesh(i){this.meshRenderer=i,i?(this._meshObj=i.sharedMeshes[Math.floor(Math.random()*i.sharedMeshes.length)],this._meshGeometry=this._meshObj.geometry):(this._meshObj=void 0,this._meshGeometry=void 0)}update(i,e,t,n){this.system=i,this._space=t,t===1&&(this._worldSpaceMatrix.copy(n.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}applyRotation(i){const e=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return e&&(this._rotation.x=Ze.toRadians(this.rotation.x),this._rotation.y=Ze.toRadians(this.rotation.y),this._rotation.z=Ze.toRadians(this.rotation.z),this._rotation.order="ZYX",i.applyEuler(this._rotation)),e}onInitialize(i){this._vector.set(0,0,0),i.mesh=void 0,i.mesh_geometry=void 0;const e=this._temp.copy(this.position),t=this._space===1;t&&e.applyQuaternion(this.system.worldQuaternion);let n=this.radius;if(t&&(n*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:vx&&Ct.DrawWireBox(this.position,this.scale,14540253,1),this._vector.x=Math.random()*this.scale.x-this.scale.x/2,this._vector.y=Math.random()*this.scale.y-this.scale.y/2,this._vector.z=Math.random()*this.scale.z-this.scale.z/2,this._vector.add(e);break;case 4:this.randomConePoint(this.position,this.angle,n,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 10:this.randomCirclePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 13:const r=this.meshRenderer;r?.destroyed==!1&&this.setMesh(r);const s=i.mesh=this._meshObj,o=i.mesh_geometry=this._meshGeometry;if(s&&o)switch(this.meshShapeType){case 0:{const a=o.getAttribute("position"),l=Math.floor(Math.random()*a.count);this._vector.fromBufferAttribute(a,l),this._vector.applyMatrix4(s.matrixWorld),i.mesh_normal=l}break;case 1:break;case 2:{const a=o.index;if(a){let l=Math.random(),c=Math.random();l+c>1&&(l=1-l,c=1-c);const u=Math.floor(Math.random()*(a.count/3));let d=u*3,p=u*3+1,f=u*3+2;d=a.getX(d),p=a.getX(p),f=a.getX(f);const m=o.getAttribute("position");this._triangle.a.fromBufferAttribute(m,d),this._triangle.b.fromBufferAttribute(m,p),this._triangle.c.fromBufferAttribute(m,f),this._vector.set(0,0,0).addScaledVector(this._triangle.a,l).addScaledVector(this._triangle.b,c).addScaledVector(this._triangle.c,1-(l+c)),this._vector.applyMatrix4(s.matrixWorld),i.mesh_normal=u}}break}break;default:this._vector.set(0,0,0),pt()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",Ax[this.shapeType]),globalThis.__particlesystem_shapetype_unsupported=!0);break}this.randomizePosition(this._vector,this.randomPositionAmount)}this.applyRotation(this._vector),t&&(this._vector.applyQuaternion(this.system.worldQuaternion),this._vector.add(this.system.worldPos)),vx&&Ct.DrawSphere(this._vector,.03,16711680,.5,!0)}getDirection(i,e){var t;if(!this.enabled)return this._dir.set(0,0,1),this._dir;switch(this.shapeType){case 5:this._dir.set(0,0,1);break;case 4:this._dir.set(0,0,1);break;case 10:case 0:const n=e.x,r=e.y,s=e.z;this._dir.set(n,r,s),(t=this.system)!=null&&t.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;case 13:const o=i.mesh,a=i.mesh_geometry;if(o&&a)switch(this.meshShapeType){case 0:{const l=a.getAttribute("normal"),c=i.mesh_normal;this._dir.fromBufferAttribute(l,c)}break;case 1:break;case 2:{const l=a.index;if(l){const c=i.mesh_normal,u=l.getX(c*3),d=l.getX(c*3+1),p=l.getX(c*3+2),f=a.getAttribute("position"),m=Zi(),A=Zi(),v=Zi();m.fromBufferAttribute(f,u),A.fromBufferAttribute(f,d),v.fromBufferAttribute(f,p),m.sub(A),v.sub(A),m.cross(v),this._dir.copy(m).multiplyScalar(-1);const g=xi(o);this._dir.applyQuaternion(g)}}break}break;default:this._dir.set(0,0,1);break}return this._space===1&&this._dir.applyQuaternion(this.system.worldQuaternion),this.applyRotation(this._dir),this._dir.normalize(),this.spherizeDirection(this._dir,this.sphericalDirectionAmount),this.randomizeDirection(this._dir,this.randomDirectionAmount),vx&&(Ct.DrawSphere(e,.01,8925952,.5,!0),Ct.DrawDirection(e,this._dir,8925952,.5,!0)),this._dir}randomizePosition(i,e){if(e<=0)return;const t=n0._tempVec;t.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),t.x*=e*this.scale.x,t.y*=e*this.scale.y,t.z*=e*this.scale.z,i.add(t)}randomizeDirection(i,e){if(e===0)return;const t=n0._randomQuat,n=n0._tempVec;n.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),t.setFromAxisAngle(n,e*Math.random()*Math.PI),i.applyQuaternion(t)}spherizeDirection(i,e){if(e===0)return;const t=Math.random()*Math.PI*2,n=Math.acos(1-Math.random()*2),r=Math.sin(n)*Math.cos(t),s=Math.sin(n)*Math.sin(t),o=Math.cos(n),a=new S(r,s,o);i.lerp(a,e)}randomSpherePoint(i,e,t,n,r){const s=Math.random(),o=Math.random(),a=2*Math.PI*s*(n/360),l=Math.acos(2*o-1),c=Ze.lerp(1,1-Math.pow(1-Math.random(),Math.PI),t)*e,u=i.x+this.scale.x*(-c*Math.sin(l)*Math.cos(a)),d=i.y+this.scale.y*(c*Math.sin(l)*Math.sin(a)),p=i.z+this.scale.z*(c*Math.cos(l));r.x=u,r.y=d,r.z=p}randomCirclePoint(i,e,t,n,r){const s=Math.random(),o=2*Math.PI*s*(n/360),a=Ze.lerp(1,1-Math.pow(1-Math.random(),Math.PI),t)*e,l=i.x+this.scale.x*a*Math.cos(o),c=i.y+this.scale.y*a*Math.sin(o),u=i.z;r.x=l,r.y=c,r.z=u}randomConePoint(i,e,t,n,r,s,o){let a=0,l=0;switch(s){case 0:a=Math.random(),l=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:a=.5,l=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let c=2*Math.PI*a*(r/360);switch(s){case 2:case 1:c+=Math.PI+.5,c+=this._loopTime*Math.PI*2,c%=Ze.toRadians(r);break}const u=Math.acos(2*l-1),d=Ze.lerp(1,1-Math.pow(1-Math.random(),Math.PI),n)*t,p=i.x+-d*Math.sin(u)*Math.cos(c),f=i.y+d*Math.sin(u)*Math.sin(c),m=i.z;o.x=p*this.scale.x,o.y=f*this.scale.y,o.z=m*this.scale.z}},h(bx,"_randomQuat",new Me),h(bx,"_tempVec",new S),bx);let sn=n0;ie([x()],sn.prototype,"shapeType",2),ie([x()],sn.prototype,"enabled",2),ie([x()],sn.prototype,"alignToDirection",2),ie([x()],sn.prototype,"angle",2),ie([x()],sn.prototype,"arc",2),ie([x()],sn.prototype,"arcSpread",2),ie([x()],sn.prototype,"arcSpeedMultiplier",2),ie([x()],sn.prototype,"arcMode",2),ie([x(S)],sn.prototype,"boxThickness",2),ie([x(S)],sn.prototype,"position",2),ie([x(S)],sn.prototype,"rotation",2),ie([x(S)],sn.prototype,"scale",2),ie([x()],sn.prototype,"radius",2),ie([x()],sn.prototype,"radiusThickness",2),ie([x()],sn.prototype,"sphericalDirectionAmount",2),ie([x()],sn.prototype,"randomDirectionAmount",2),ie([x()],sn.prototype,"randomPositionAmount",2),ie([x()],sn.prototype,"meshShapeType",2),ie([x($v)],sn.prototype,"meshRenderer",2);class _i{constructor(){h(this,"damping"),h(this,"enabled"),h(this,"frequency"),h(this,"octaveCount"),h(this,"octaveMultiplier"),h(this,"octaveScale"),h(this,"positionAmount"),h(this,"quality"),h(this,"remap"),h(this,"remapEnabled"),h(this,"remapMultiplier"),h(this,"remapX"),h(this,"remapXMultiplier"),h(this,"remapY"),h(this,"remapYMultiplier"),h(this,"remapZ"),h(this,"remapZMultiplier"),h(this,"scrollSpeedMultiplier"),h(this,"separateAxes"),h(this,"strengthMultiplier"),h(this,"strengthX"),h(this,"strengthXMultiplier"),h(this,"strengthY"),h(this,"strengthYMultiplier"),h(this,"strengthZ"),h(this,"strengthZMultiplier"),h(this,"_noise"),h(this,"_time",0),h(this,"_temp",new S)}update(e){this._time+=e.time.deltaTime*this.scrollSpeedMultiplier}apply(e,t,n,r,s,o){if(!this.enabled)return;this._noise||(this._noise=Fre(()=>0));const a=this._temp.set(t.x,t.y,t.z).multiplyScalar(this.frequency),l=this._noise(a.x,a.y,a.z,this._time),c=this._noise(a.x,a.y,a.z,this._time+1e3*this.frequency),u=this._noise(a.x,a.y,a.z,this._time+2e3*this.frequency);this._temp.set(l,c,u).normalize();const d=s/o;let p=this.positionAmount.evaluate(d);this.separateAxes?(this._temp.x*=p*this.strengthXMultiplier,this._temp.y*=p*this.strengthYMultiplier,this._temp.z*=p*this.strengthZMultiplier):(this.strengthX&&(p*=this.strengthX.evaluate(d)*1.5),this._temp.multiplyScalar(p)),n.x+=this._temp.x,n.y+=this._temp.y,n.z+=this._temp.z}}ie([x()],_i.prototype,"damping",2),ie([x()],_i.prototype,"enabled",2),ie([x()],_i.prototype,"frequency",2),ie([x()],_i.prototype,"octaveCount",2),ie([x()],_i.prototype,"octaveMultiplier",2),ie([x()],_i.prototype,"octaveScale",2),ie([x(lt)],_i.prototype,"positionAmount",2),ie([x()],_i.prototype,"quality",2),ie([x(lt)],_i.prototype,"remap",2),ie([x()],_i.prototype,"remapEnabled",2),ie([x()],_i.prototype,"remapMultiplier",2),ie([x(lt)],_i.prototype,"remapX",2),ie([x()],_i.prototype,"remapXMultiplier",2),ie([x(lt)],_i.prototype,"remapY",2),ie([x()],_i.prototype,"remapYMultiplier",2),ie([x(lt)],_i.prototype,"remapZ",2),ie([x()],_i.prototype,"remapZMultiplier",2),ie([x()],_i.prototype,"scrollSpeedMultiplier",2),ie([x()],_i.prototype,"separateAxes",2),ie([x()],_i.prototype,"strengthMultiplier",2),ie([x(lt)],_i.prototype,"strengthX",2),ie([x()],_i.prototype,"strengthXMultiplier",2),ie([x(lt)],_i.prototype,"strengthY",2),ie([x()],_i.prototype,"strengthYMultiplier",2),ie([x(lt)],_i.prototype,"strengthZ",2),ie([x()],_i.prototype,"strengthZMultiplier",2);class Xi{constructor(){h(this,"enabled"),h(this,"attachRibbonToTransform",!1),h(this,"colorOverLifetime"),h(this,"colorOverTrail"),h(this,"dieWithParticles",!0),h(this,"inheritParticleColor",!0),h(this,"lifetime"),h(this,"lifetimeMultiplier"),h(this,"minVertexDistance",.2),h(this,"mode",0),h(this,"ratio",1),h(this,"ribbonCount",1),h(this,"shadowBias",0),h(this,"sizeAffectsLifetime",!1),h(this,"sizeAffectsWidth",!1),h(this,"splitSubEmitterRibbons",!1),h(this,"textureMode",0),h(this,"widthOverTrail"),h(this,"widthOverTrailMultiplier"),h(this,"worldSpace",!1)}getWidth(e,t,n,r){const s=this.widthOverTrail.evaluate(n,r);return e*=s,e}getColor(e,t,n){const r=this.colorOverTrail.evaluate(n),s=this.colorOverLifetime.evaluate(t);e.x*=r.r*s.r,e.y*=r.g*s.g,e.z*=r.b*s.b,e.w*=r.alpha*s.alpha}}ie([x()],Xi.prototype,"enabled",2),ie([x()],Xi.prototype,"attachRibbonToTransform",2),ie([x(Ls)],Xi.prototype,"colorOverLifetime",2),ie([x(Ls)],Xi.prototype,"colorOverTrail",2),ie([x()],Xi.prototype,"dieWithParticles",2),ie([x()],Xi.prototype,"inheritParticleColor",2),ie([x(lt)],Xi.prototype,"lifetime",2),ie([x()],Xi.prototype,"lifetimeMultiplier",2),ie([x()],Xi.prototype,"minVertexDistance",2),ie([x()],Xi.prototype,"mode",2),ie([x()],Xi.prototype,"ratio",2),ie([x()],Xi.prototype,"ribbonCount",2),ie([x()],Xi.prototype,"shadowBias",2),ie([x()],Xi.prototype,"sizeAffectsLifetime",2),ie([x()],Xi.prototype,"sizeAffectsWidth",2),ie([x()],Xi.prototype,"splitSubEmitterRibbons",2),ie([x()],Xi.prototype,"textureMode",2),ie([x(lt)],Xi.prototype,"widthOverTrail",2),ie([x()],Xi.prototype,"widthOverTrailMultiplier",2),ie([x()],Xi.prototype,"worldSpace",2);class on{constructor(){h(this,"enabled"),h(this,"space",0),h(this,"orbitalX"),h(this,"orbitalY"),h(this,"orbitalZ"),h(this,"orbitalXMultiplier"),h(this,"orbitalYMultiplier"),h(this,"orbitalZMultiplier"),h(this,"orbitalOffsetX"),h(this,"orbitalOffsetY"),h(this,"orbitalOffsetZ"),h(this,"speedModifier"),h(this,"speedModifierMultiplier"),h(this,"x"),h(this,"xMultiplier"),h(this,"y"),h(this,"yMultiplier"),h(this,"z"),h(this,"zMultiplier"),h(this,"_system"),h(this,"_temp",new S),h(this,"_temp2",new S),h(this,"_temp3",new S),h(this,"_hasOrbital",!1),h(this,"_index",0),h(this,"_orbitalMatrix",new Ce)}update(e){this._system=e}init(e){this._index==0&&(e.debug=!0),this._index+=1,e.orbitx=this.orbitalX.evaluate(Math.random()),e.orbity=this.orbitalY.evaluate(Math.random()),e.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=e.orbitx!=0||e.orbity!=0||e.orbitz!=0}apply(e,t,n,r,s,o,a){var l;if(!this.enabled)return;const c=o/a,u=this.speedModifier.evaluate(c)*this.speedModifierMultiplier,d=this.x.evaluate(c),p=this.y.evaluate(c),f=this.z.evaluate(c);if(this._temp.set(-d,p,f),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&((l=this._system)==null?void 0:l.worldPos)){const m=this._temp2.set(n.x,n.y,n.z),A=this.orbitalXMultiplier,v=this.orbitalYMultiplier,g=this.orbitalZMultiplier,y=u*Math.PI*2*10,b=Math.cos(y*A),_=Math.sin(y*A),E=Math.cos(y*v),I=Math.sin(y*v),T=Math.cos(y*g),M=Math.sin(y*g),D=m.x*(E*T)+m.y*(E*M)+m.z*-I,C=m.x*(_*I*T-b*M)+m.y*(_*I*M+b*T)+m.z*(_*E),P=m.x*(b*I*T+_*M)+m.y*(b*I*M-_*T)+m.z*(b*E),G=this._temp3.set(m.x-D,m.y-C,m.z-P);G.normalize(),G.multiplyScalar(.2/s*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),r.x+=G.x,r.y+=G.y,r.z+=G.z}r.x+=this._temp.x,r.y+=this._temp.y,r.z+=this._temp.z,r.x*=u,r.y*=u,r.z*=u}}ie([x()],on.prototype,"enabled",2),ie([x()],on.prototype,"space",2),ie([x(lt)],on.prototype,"orbitalX",2),ie([x(lt)],on.prototype,"orbitalY",2),ie([x(lt)],on.prototype,"orbitalZ",2),ie([x()],on.prototype,"orbitalXMultiplier",2),ie([x()],on.prototype,"orbitalYMultiplier",2),ie([x()],on.prototype,"orbitalZMultiplier",2),ie([x()],on.prototype,"orbitalOffsetX",2),ie([x()],on.prototype,"orbitalOffsetY",2),ie([x()],on.prototype,"orbitalOffsetZ",2),ie([x(lt)],on.prototype,"speedModifier",2),ie([x()],on.prototype,"speedModifierMultiplier",2),ie([x(lt)],on.prototype,"x",2),ie([x()],on.prototype,"xMultiplier",2),ie([x(lt)],on.prototype,"y",2),ie([x()],on.prototype,"yMultiplier",2),ie([x(lt)],on.prototype,"z",2),ie([x()],on.prototype,"zMultiplier",2);class Rr{constructor(){h(this,"animation"),h(this,"enabled"),h(this,"cycleCount"),h(this,"frameOverTime"),h(this,"frameOverTimeMultiplier"),h(this,"numTilesX"),h(this,"numTilesY"),h(this,"startFrame"),h(this,"startFrameMultiplier"),h(this,"rowMode"),h(this,"rowIndex"),h(this,"spriteCount"),h(this,"timeMode")}sampleOnceAtStart(){if(this.timeMode===0)switch(this.frameOverTime.mode){case 0:case 3:case 2:case 1:return!0}return!1}getStartIndex(){return this.sampleOnceAtStart()?Math.random()*(this.numTilesX*this.numTilesY):0}evaluate(e){if(!this.sampleOnceAtStart())return this.getIndex(e)}getIndex(e){const t=this.numTilesX*this.numTilesY;e=e*this.cycleCount;let n=this.frameOverTime.evaluate(e%1);return n*=this.frameOverTimeMultiplier,n*=t,n=n%t,n=Math.floor(n),n}}ie([x()],Rr.prototype,"animation",2),ie([x()],Rr.prototype,"enabled",2),ie([x()],Rr.prototype,"cycleCount",2),ie([x(lt)],Rr.prototype,"frameOverTime",2),ie([x()],Rr.prototype,"frameOverTimeMultiplier",2),ie([x()],Rr.prototype,"numTilesX",2),ie([x()],Rr.prototype,"numTilesY",2),ie([x(lt)],Rr.prototype,"startFrame",2),ie([x()],Rr.prototype,"startFrameMultiplier",2),ie([x()],Rr.prototype,"rowMode",2),ie([x()],Rr.prototype,"rowIndex",2),ie([x()],Rr.prototype,"spriteCount",2),ie([x()],Rr.prototype,"timeMode",2);class jo{constructor(){h(this,"enabled"),h(this,"separateAxes"),h(this,"x"),h(this,"xMultiplier"),h(this,"y"),h(this,"yMultiplier"),h(this,"z"),h(this,"zMultiplier")}evaluate(e,t){return this.enabled?this.separateAxes?0:this.z.evaluate(e,t)*-1:0}}ie([x()],jo.prototype,"enabled",2),ie([x()],jo.prototype,"separateAxes",2),ie([x(lt)],jo.prototype,"x",2),ie([x()],jo.prototype,"xMultiplier",2),ie([x(lt)],jo.prototype,"y",2),ie([x()],jo.prototype,"yMultiplier",2),ie([x(lt)],jo.prototype,"z",2),ie([x()],jo.prototype,"zMultiplier",2);class io{constructor(){h(this,"enabled"),h(this,"range"),h(this,"separateAxes"),h(this,"x"),h(this,"xMultiplier"),h(this,"y"),h(this,"yMultiplier"),h(this,"z"),h(this,"zMultiplier")}evaluate(e,t){if(!this.enabled)return 0;if(!this.separateAxes){const n=Ze.lerp(this.range.x,this.range.y,t);return this.z.evaluate(n)*-1}return 0}}ie([x()],io.prototype,"enabled",2),ie([x()],io.prototype,"range",2),ie([x()],io.prototype,"separateAxes",2),ie([x(lt)],io.prototype,"x",2),ie([x()],io.prototype,"xMultiplier",2),ie([x(lt)],io.prototype,"y",2),ie([x()],io.prototype,"yMultiplier",2),ie([x(lt)],io.prototype,"z",2),ie([x()],io.prototype,"zMultiplier",2);class Dn{constructor(){h(this,"enabled"),h(this,"dampen"),h(this,"drag"),h(this,"dragMultiplier"),h(this,"limit"),h(this,"limitMultiplier"),h(this,"separateAxes"),h(this,"limitX"),h(this,"limitXMultiplier"),h(this,"limitY"),h(this,"limitYMultiplier"),h(this,"limitZ"),h(this,"limitZMultiplier"),h(this,"multiplyDragByParticleSize",!1),h(this,"multiplyDragByParticleVelocity",!1),h(this,"space"),h(this,"_temp",new S),h(this,"_temp2",new S)}apply(e,t,n,r,s,o,a){if(this.enabled){const l=this.limit.evaluate(s)*this.limitMultiplier;if(t.length()>l){this._temp.copy(t).normalize().multiplyScalar(l);const c=this.dampen*.5;t.x=Ze.lerp(t.x,this._temp.x,c),t.y=Ze.lerp(t.y,this._temp.y,c),t.z=Ze.lerp(t.z,this._temp.z,c),n.x=Ze.lerp(n.x,this._temp.x,c),n.y=Ze.lerp(n.y,this._temp.y,c),n.z=Ze.lerp(n.z,this._temp.z,c)}}}}ie([x()],Dn.prototype,"enabled",2),ie([x()],Dn.prototype,"dampen",2),ie([x(lt)],Dn.prototype,"drag",2),ie([x()],Dn.prototype,"dragMultiplier",2),ie([x(lt)],Dn.prototype,"limit",2),ie([x()],Dn.prototype,"limitMultiplier",2),ie([x()],Dn.prototype,"separateAxes",2),ie([x(lt)],Dn.prototype,"limitX",2),ie([x()],Dn.prototype,"limitXMultiplier",2),ie([x(lt)],Dn.prototype,"limitY",2),ie([x()],Dn.prototype,"limitYMultiplier",2),ie([x(lt)],Dn.prototype,"limitZ",2),ie([x()],Dn.prototype,"limitZMultiplier",2),ie([x()],Dn.prototype,"multiplyDragByParticleSize",2),ie([x()],Dn.prototype,"multiplyDragByParticleVelocity",2),ie([x()],Dn.prototype,"space",2);const V4=class{constructor(){h(this,"enabled"),h(this,"curve"),h(this,"curveMultiplier"),h(this,"mode"),h(this,"system"),h(this,"_temp",new S),h(this,"_firstUpdate",!0),h(this,"_frames",0)}clone(){var i;const e=new V4;return e.enabled=this.enabled,e.curve=(i=this.curve)==null?void 0:i.clone(),e.curveMultiplier=this.curveMultiplier,e.mode=this.mode,e}get _lastWorldPosition(){return this.system._iv_lastWorldPosition||(this.system._iv_lastWorldPosition=new S),this.system._iv_lastWorldPosition}get _velocity(){return this.system._iv_velocity||(this.system._iv_velocity=new S),this.system._iv_velocity}awake(i){this.system=i,this.reset()}reset(){this._firstUpdate=!0}update(i){this.enabled&&this.system.worldspace!==!1&&(this._firstUpdate?(this._firstUpdate=!1,this._velocity.set(0,0,0),this._lastWorldPosition.copy(this.system.worldPos)):this._lastWorldPosition&&(this._velocity.copy(this.system.worldPos).sub(this._lastWorldPosition).multiplyScalar(1/this.system.deltaTime),this._lastWorldPosition.copy(this.system.worldPos)))}applyInitial(i){if(this.enabled&&this.system.worldspace!==!1&&this.mode===0){const e=this.curve.evaluate(Math.random(),Math.random());this._temp.copy(this._velocity).multiplyScalar(e),i.add(this._temp)}}applyCurrent(i,e,t){if(this.enabled&&this.system&&this.system.worldspace!==!1&&this.mode===1){const n=this.curve.evaluate(e,t);this._temp.copy(this._velocity).multiplyScalar(n),i.add(this._temp)}}};let Mh=V4;ie([x()],Mh.prototype,"enabled",2),ie([x(lt)],Mh.prototype,"curve",2),ie([x()],Mh.prototype,"curveMultiplier",2),ie([x()],Mh.prototype,"mode",2);class _s{constructor(){h(this,"enabled"),h(this,"range"),h(this,"separateAxes"),h(this,"size"),h(this,"sizeMultiplier"),h(this,"x"),h(this,"xMultiplier"),h(this,"y"),h(this,"yMultiplier"),h(this,"z"),h(this,"zMultiplier")}evaluate(e,t,n,r){const s=e.length(),o=Ze.remap(s,this.range.x,this.range.y,0,1),a=this.size.evaluate(o,n);return r*a}}ie([x()],_s.prototype,"enabled",2),ie([x($)],_s.prototype,"range",2),ie([x()],_s.prototype,"separateAxes",2),ie([x(lt)],_s.prototype,"size",2),ie([x()],_s.prototype,"sizeMultiplier",2),ie([x(lt)],_s.prototype,"x",2),ie([x()],_s.prototype,"xMultiplier",2),ie([x(lt)],_s.prototype,"y",2),ie([x()],_s.prototype,"yMultiplier",2),ie([x(lt)],_s.prototype,"z",2),ie([x()],_s.prototype,"zMultiplier",2);class dd{constructor(){h(this,"enabled"),h(this,"range"),h(this,"color")}evaluate(e,t,n){const r=e.length(),s=Ze.remap(r,this.range.x,this.range.y,0,1),o=this.color.evaluate(s,t);n.x*=o.r,n.y*=o.g,n.z*=o.b,n.w*=o.alpha}}ie([x()],dd.prototype,"enabled",2),ie([x($)],dd.prototype,"range",2),ie([x(Ls)],dd.prototype,"color",2);const gse={name:"HorizontalBlurShader",uniforms:{tDiffuse:{value:null},h:{value:1/512}},vertexShader:`
@@ -6922,7 +6922,7 @@ void main() {
6922
6922
  vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
6923
6923
 
6924
6924
  #include <fog_vertex>
6925
- }`);new S(0,0,1);var Gae=function(i){Ff(t,i);var e=Nf(t);function t(n){var r;return _t(this,t),r=e.call(this,n),Y($t(r),"positionBuffer",void 0),Y($t(r),"previousBuffer",void 0),Y($t(r),"nextBuffer",void 0),Y($t(r),"uvBuffer",void 0),Y($t(r),"sideBuffer",void 0),Y($t(r),"widthBuffer",void 0),Y($t(r),"colorBuffer",void 0),Y($t(r),"indexBuffer",void 0),Y($t(r),"vector_",new S),Y($t(r),"vector2_",new S),Y($t(r),"vector3_",new S),Y($t(r),"quaternion_",new Me),r.maxParticles=1e4,r.setupBuffers(),r.rebuildMaterial(),r}return xt(t,[{key:"setupBuffers",value:function(){this.geometry&&this.geometry.dispose(),this.geometry=new ut,this.indexBuffer=new $e(new Uint32Array(this.maxParticles*6),1),this.indexBuffer.setUsage(Ur),this.geometry.setIndex(this.indexBuffer),this.positionBuffer=new $e(new Float32Array(this.maxParticles*6),3),this.positionBuffer.setUsage(Ur),this.geometry.setAttribute("position",this.positionBuffer),this.previousBuffer=new $e(new Float32Array(this.maxParticles*6),3),this.previousBuffer.setUsage(Ur),this.geometry.setAttribute("previous",this.previousBuffer),this.nextBuffer=new $e(new Float32Array(this.maxParticles*6),3),this.nextBuffer.setUsage(Ur),this.geometry.setAttribute("next",this.nextBuffer),this.widthBuffer=new $e(new Float32Array(this.maxParticles*2),1),this.widthBuffer.setUsage(Ur),this.geometry.setAttribute("width",this.widthBuffer),this.sideBuffer=new $e(new Float32Array(this.maxParticles*2),1),this.sideBuffer.setUsage(Ur),this.geometry.setAttribute("side",this.sideBuffer),this.uvBuffer=new $e(new Float32Array(this.maxParticles*4),2),this.uvBuffer.setUsage(Ur),this.geometry.setAttribute("uv",this.uvBuffer),this.colorBuffer=new $e(new Float32Array(this.maxParticles*8),4),this.colorBuffer.setUsage(Ur),this.geometry.setAttribute("color",this.colorBuffer)}},{key:"expandBuffers",value:function(n){for(;n>=this.maxParticles;)this.maxParticles*=2;this.setupBuffers()}},{key:"rebuildMaterial",value:function(){this.layers.mask=this.settings.layers.mask;var n={lineWidth:{value:1},map:{value:null},useMap:{value:0},alphaMap:{value:null},useAlphaMap:{value:0},resolution:{value:new $(1,1)},sizeAttenuation:{value:1},visibility:{value:1},alphaTest:{value:0},repeat:{value:new $(1,1)}},r={};if(r.USE_UV="",r.USE_COLOR_ALPHA="",this.settings.material.map&&(r.USE_MAP="",r.MAP_UV=MR(this.settings.material.map.channel),n.map=new be(this.settings.material.map),n.mapTransform=new be(new Dt().copy(this.settings.material.map.matrix))),this.settings.renderMode===tt.Trail)this.material=new Tt({uniforms:n,defines:r,vertexShader:jae,fragmentShader:zae,transparent:this.settings.material.transparent,depthWrite:!this.settings.material.transparent,side:this.settings.material.side,blending:this.settings.material.blending||Vh});else throw new Error("render mode unavailable")}},{key:"update",value:function(){var n=this,r=0,s=0,o=0;this.systems.forEach(function(a){for(var l=0;l<a.particleNum;l++)o+=a.particles[l].previous.length*2}),o>this.maxParticles&&this.expandBuffers(o),this.systems.forEach(function(a){var l=n.quaternion_,c=n.vector2_,u=n.vector3_;a.emitter.matrixWorld.decompose(c,l,u);for(var d=a.particles,p=a.particleNum,f=n.settings.uTileCount,m=n.settings.vTileCount,A=1/f,v=1/m,g=0;g<p;g++){var y=d[g],b=y.uvTile%m,_=Math.floor(y.uvTile/m),E=y.previous.values(),I=E.next(),T=I.value,M=T;I.done||(I=E.next());var D=void 0;I.value!==void 0?D=I.value:D=M;for(var C=0;C<y.previous.length;C++,r+=2){if(n.positionBuffer.setXYZ(r,M.position.x,M.position.y,M.position.z),n.positionBuffer.setXYZ(r+1,M.position.x,M.position.y,M.position.z),a.worldSpace?(n.positionBuffer.setXYZ(r,M.position.x,M.position.y,M.position.z),n.positionBuffer.setXYZ(r+1,M.position.x,M.position.y,M.position.z)):(y.parentMatrix?n.vector_.copy(M.position).applyMatrix4(y.parentMatrix):n.vector_.copy(M.position).applyMatrix4(a.emitter.matrixWorld),n.positionBuffer.setXYZ(r,n.vector_.x,n.vector_.y,n.vector_.z),n.positionBuffer.setXYZ(r+1,n.vector_.x,n.vector_.y,n.vector_.z)),a.worldSpace?(n.previousBuffer.setXYZ(r,T.position.x,T.position.y,T.position.z),n.previousBuffer.setXYZ(r+1,T.position.x,T.position.y,T.position.z)):(y.parentMatrix?n.vector_.copy(T.position).applyMatrix4(y.parentMatrix):n.vector_.copy(T.position).applyMatrix4(a.emitter.matrixWorld),n.previousBuffer.setXYZ(r,n.vector_.x,n.vector_.y,n.vector_.z),n.previousBuffer.setXYZ(r+1,n.vector_.x,n.vector_.y,n.vector_.z)),a.worldSpace?(n.nextBuffer.setXYZ(r,D.position.x,D.position.y,D.position.z),n.nextBuffer.setXYZ(r+1,D.position.x,D.position.y,D.position.z)):(y.parentMatrix?n.vector_.copy(D.position).applyMatrix4(y.parentMatrix):n.vector_.copy(D.position).applyMatrix4(a.emitter.matrixWorld),n.nextBuffer.setXYZ(r,n.vector_.x,n.vector_.y,n.vector_.z),n.nextBuffer.setXYZ(r+1,n.vector_.x,n.vector_.y,n.vector_.z)),n.sideBuffer.setX(r,-1),n.sideBuffer.setX(r+1,1),a.worldSpace)n.widthBuffer.setX(r,M.size),n.widthBuffer.setX(r+1,M.size);else if(y.parentMatrix)n.widthBuffer.setX(r,M.size),n.widthBuffer.setX(r+1,M.size);else{var P=(Math.abs(u.x)+Math.abs(u.y)+Math.abs(u.z))/3;n.widthBuffer.setX(r,M.size*P),n.widthBuffer.setX(r+1,M.size*P)}n.uvBuffer.setXY(r,(C/y.previous.length+b)*A,(m-_-1)*v),n.uvBuffer.setXY(r+1,(C/y.previous.length+b)*A,(m-_)*v),n.colorBuffer.setXYZW(r,M.color.x,M.color.y,M.color.z,M.color.w),n.colorBuffer.setXYZW(r+1,M.color.x,M.color.y,M.color.z,M.color.w),C+1<y.previous.length&&(n.indexBuffer.setX(s*3,r),n.indexBuffer.setX(s*3+1,r+1),n.indexBuffer.setX(s*3+2,r+2),s++,n.indexBuffer.setX(s*3,r+2),n.indexBuffer.setX(s*3+1,r+1),n.indexBuffer.setX(s*3+2,r+3),s++),T=M,M=D,I.done||(I=E.next(),I.value!==void 0&&(D=I.value))}}}),this.positionBuffer.updateRange.count=r*3,this.positionBuffer.needsUpdate=!0,this.previousBuffer.updateRange.count=r*3,this.previousBuffer.needsUpdate=!0,this.nextBuffer.updateRange.count=r*3,this.nextBuffer.needsUpdate=!0,this.sideBuffer.updateRange.count=r,this.sideBuffer.needsUpdate=!0,this.widthBuffer.updateRange.count=r,this.widthBuffer.needsUpdate=!0,this.uvBuffer.updateRange.count=r*2,this.uvBuffer.needsUpdate=!0,this.colorBuffer.updateRange.count=r*4,this.colorBuffer.needsUpdate=!0,this.indexBuffer.updateRange.count=s*3,this.indexBuffer.needsUpdate=!0,this.geometry.setDrawRange(0,s*3)}},{key:"dispose",value:function(){this.geometry.dispose()}}]),t}(Kz),Qae=function(i){Ff(t,i);var e=Nf(t);function t(){var n;return _t(this,t),n=e.call(this),Y($t(n),"batches",[]),Y($t(n),"systemToBatchIndex",new Map),Y($t(n),"type","BatchedRenderer"),n}return xt(t,[{key:"addSystem",value:function(n){n._renderer=this;for(var r=n.getRendererSettings(),s=0;s<this.batches.length;s++)if(t.equals(this.batches[s].settings,r)){this.batches[s].addSystem(n),this.systemToBatchIndex.set(n,s);return}var o;switch(r.renderMode){case tt.Trail:o=new Gae(r);break;case tt.Mesh:case tt.BillBoard:case tt.VerticalBillBoard:case tt.HorizontalBillBoard:case tt.StretchedBillBoard:o=new Nae(r);break}o.addSystem(n),this.batches.push(o),this.systemToBatchIndex.set(n,this.batches.length-1),this.add(o)}},{key:"deleteSystem",value:function(n){var r=this.systemToBatchIndex.get(n);r!=null&&(this.batches[r].removeSystem(n),this.systemToBatchIndex.delete(n))}},{key:"updateSystem",value:function(n){this.deleteSystem(n),this.addSystem(n)}},{key:"update",value:function(n){this.systemToBatchIndex.forEach(function(s,o){o.update(n)});for(var r=0;r<this.batches.length;r++)this.batches[r].update()}}],[{key:"equals",value:function(n,r){return n.material.side===r.material.side&&n.material.blending===r.material.blending&&n.material.transparent===r.material.transparent&&n.material.type===r.material.type&&n.material.alphaTest===r.material.alphaTest&&n.material.map===r.material.map&&n.renderMode===r.renderMode&&n.uTileCount===r.uTileCount&&n.vTileCount===r.vTileCount&&n.instancingGeometry===r.instancingGeometry&&n.renderOrder===r.renderOrder&&n.layers.mask===r.layers.mask}}]),t}(ge),Hae=Qae,$z=function(){function i(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:new S;_t(this,i),Y(this,"locations",[]),this.scaleX=e,this.scaleY=t,this.position=n}return xt(i,[{key:"transform",value:function(e,t){e.x=this.locations[t%this.locations.length].x*this.scaleX+this.position.x,e.y=this.locations[t%this.locations.length].y*this.scaleY+this.position.y,e.z=this.position.z}},{key:"clone",value:function(){var e=new i(this.scaleX,this.scaleY,this.position.clone());return e.locations=this.locations.map(function(t){return t.clone()}),e}},{key:"toJSON",value:function(){return{scaleX:this.scaleX,scaleY:this.scaleY,position:this.position,locations:this.locations.map(function(e){return{x:e.x,y:e.y}})}}},{key:"fromImage",value:function(e,t){var n=document.createElement("canvas");n.width=e.width,n.height=e.height;var r=n.getContext("2d");if(r){r.drawImage(e,0,0);var s=r.getImageData(0,0,n.width,n.height,{colorSpace:"srgb"});n.remove(),this.locations.length=0;for(var o=0;o<s.height;o++)for(var a=0;a<s.width;a++)s.data[(o*s.width+a)*4+3]>t&&this.locations.push(new $(a,s.height-o))}}}],[{key:"fromJSON",value:function(e){var t=new i(e.scaleX,e.scaleY,new S(e.position[0],e.position[1],e.position[2]));return t.locations=e.locations.map(function(n){return new $(n.x,n.y)}),t}}]),i}();function Vae(i){switch(i.type){case"TextureSequencer":return $z.fromJSON(i);default:return new $z}}var Wae=function(){function i(e){_t(this,i),Y(this,"type","ApplySequences"),Y(this,"sequencers",[]),Y(this,"time",0),Y(this,"index",0),Y(this,"pCount",0),Y(this,"delay",void 0),Y(this,"tempV",new S),this.delay=e}return xt(i,[{key:"initialize",value:function(e){e.id=this.pCount,e.dst=new S,e.begin=new S,e.inMotion=!1,this.pCount++}},{key:"reset",value:function(){this.time=0,this.index=0,this.pCount=0}},{key:"update",value:function(e,t){var n=this.sequencers[this.index],r=e.id*this.delay;this.time>=n[0].a+r&&this.time<=n[0].b+r?(e.inMotion||(e.inMotion=!0,e.begin.copy(e.position),n[1].transform(e.dst,e.id)),e.position.lerpVectors(e.begin,e.dst,i.BEZIER.genValue((this.time-n[0].a-r)/(n[0].b-n[0].a)))):this.time>n[0].b+r&&(e.inMotion=!1)}},{key:"frameUpdate",value:function(e){for(;this.index+1<this.sequencers.length&&this.time>=this.sequencers[this.index+1][0].a;)this.index++;this.time+=e}},{key:"appendSequencer",value:function(e,t){this.sequencers.push([e,t])}},{key:"toJSON",value:function(){return{type:this.type,delay:this.delay,sequencers:this.sequencers.map(function(e){var t=zf(e,2),n=t[0],r=t[1];return{range:n.toJSON(),sequencer:r.toJSON()}})}}},{key:"clone",value:function(){var e=new i(this.delay);return e.sequencers=this.sequencers.map(function(t){return[t[0].clone(),t[1].clone()]}),e}}],[{key:"fromJSON",value:function(e){var t=new i(e.delay);return e.sequencers.forEach(function(n){t.sequencers.push([Pi(n.range),Vae(n.sequencer)])}),t}}]),i}();Y(Wae,"BEZIER",new yR(0,0,1,1));var he=function(i){return i[i.Number=0]="Number",i[i.Vec2=1]="Vec2",i[i.Vec3=2]="Vec3",i[i.Vec4=3]="Vec4",i[i.Boolean=4]="Boolean",i[i.AnyType=5]="AnyType",i}({}),ej=xt(function i(e,t,n,r){_t(this,i),Y(this,"input",void 0),Y(this,"inputIndex",void 0),Y(this,"output",void 0),Y(this,"outputIndex",void 0),this.input=e,this.inputIndex=t,this.input.outputs[t].push(this),this.output=n,this.outputIndex=r,this.output.inputs[r]=this}),qae=function(){function i(){_t(this,i),Y(this,"visited",new Set),Y(this,"graph_",void 0),Y(this,"context_",void 0),i.Instance=this}return xt(i,[{key:"traverse",value:function(e){if(this.context_===void 0)throw new Error("context is undefined");if(this.graph_===void 0)throw new Error("graph is undefined");this.visited.add(e.id);for(var t=[],n=0;n<e.inputs.length;n++)if(e.inputs[n]instanceof ej){var r=e.inputs[n].input;this.visited.has(r.id)||this.traverse(r),t.push(r.outputValues[e.inputs[n].inputIndex])}else t.push(e.inputs[n].getValue(this.context_));e.func(this.context_,t,e.outputValues),this.graph_.nodesInOrder.push(e)}},{key:"executeCompiledGraph",value:function(){if(this.context_===void 0)throw new Error("context is undefined");if(this.graph_===void 0)throw new Error("graph is undefined");for(var e=this.graph_.nodesInOrder,t=0;t<e.length;t++){for(var n=[],r=e[t],s=0;s<r.inputs.length;s++)if(r.inputs[s]instanceof ej)n.push(r.inputs[s].input.outputValues[r.inputs[s].inputIndex]);else if(r.inputs[s]!==void 0)n.push(r.inputs[s].getValue(this.context_));else throw new Error("miss input for node ".concat(r.id));r.func(this.context_,n,r.outputValues)}}},{key:"run",value:function(e,t){if(this.graph_=e,this.context_=t,e.compiled)this.executeCompiledGraph();else{e.nodesInOrder.length=0,this.visited.clear();for(var n=0;n<e.outputNodes.length;n++){var r=e.outputNodes[n];this.traverse(r)}e.compiled=!0}}}]),i}();Y(qae,"Instance",void 0);var ai=function(){function i(e){_t(this,i),Y(this,"name",void 0),Y(this,"nodeTypeSignatures",[]),this.name=e}return xt(i,[{key:"addSignature",value:function(e,t,n){this.nodeTypeSignatures.push({inputTypes:e,outputTypes:t,func:n})}}]),i}(),Qx=new ai("add");Qx.addSignature([he.Number,he.Number],[he.Number],function(i,e,t,n){n[0]=t[0]+t[1]}),Qx.addSignature([he.Vec2,he.Vec2],[he.Vec2],function(i,e,t,n){n[0].addVectors(t[0],t[1])}),Qx.addSignature([he.Vec3,he.Vec3],[he.Vec3],function(i,e,t,n){n[0].addVectors(t[0],t[1])}),Qx.addSignature([he.Vec4,he.Vec4],[he.Vec4],function(i,e,t,n){n[0].addVectors(t[0],t[1])});var Hx=new ai("sub");Hx.addSignature([he.Number,he.Number],[he.Number],function(i,e,t,n){n[0]=t[0]-t[1]}),Hx.addSignature([he.Vec2,he.Vec2],[he.Vec2],function(i,e,t,n){n[0].subVectors(t[0],t[1])}),Hx.addSignature([he.Vec3,he.Vec3],[he.Vec3],function(i,e,t,n){n[0].subVectors(t[0],t[1])}),Hx.addSignature([he.Vec4,he.Vec4],[he.Vec4],function(i,e,t,n){n[0].subVectors(t[0],t[1])});var Vx=new ai("mul");Vx.addSignature([he.Number,he.Number],[he.Number],function(i,e,t,n){n[0]=t[0]*t[1]}),Vx.addSignature([he.Vec2,he.Number],[he.Vec2],function(i,e,t,n){n[0].copy(t[0]).multiplyScalar(t[1])}),Vx.addSignature([he.Vec3,he.Number],[he.Vec3],function(i,e,t,n){n[0].copy(t[0]).multiplyScalar(t[1])}),Vx.addSignature([he.Vec4,he.Number],[he.Vec4],function(i,e,t,n){n[0].copy(t[0]).multiplyScalar(t[1])});var Wx=new ai("div");Wx.addSignature([he.Number,he.Number],[he.Number],function(i,e,t,n){n[0]=t[0]/t[1]}),Wx.addSignature([he.Vec2,he.Number],[he.Vec2],function(i,e,t,n){n[0].copy(t[0]).divideScalar(t[1])}),Wx.addSignature([he.Vec3,he.Number],[he.Vec3],function(i,e,t,n){n[0].copy(t[0]).divideScalar(t[1])}),Wx.addSignature([he.Vec4,he.Number],[he.Vec4],function(i,e,t,n){n[0].copy(t[0]).divideScalar(t[1])});var Xae=new ai("sin");Xae.addSignature([he.Number],[he.Number],function(i,e,t,n){n[0]=Math.sin(t[0])});var Yae=new ai("cos");Yae.addSignature([he.Number],[he.Number],function(i,e,t,n){n[0]=Math.cos(t[0])});var Jae=new ai("tan");Jae.addSignature([he.Number],[he.Number],function(i,e,t,n){n[0]=Math.tan(t[0])});var Kae=new ai("abs");Kae.addSignature([he.Number],[he.Number],function(i,e,t,n){n[0]=Math.abs(t[0])});var Zae=new ai("min");Zae.addSignature([he.Number,he.Number],[he.Number],function(i,e,t,n){n[0]=Math.min(t[0],t[1])});var $ae=new ai("max");$ae.addSignature([he.Number,he.Number],[he.Number],function(i,e,t,n){n[0]=Math.max(t[0],t[1])});var TR=new ai("dot");TR.addSignature([he.Vec2,he.Vec2],[he.Number],function(i,e,t,n){n[0]=t[0].dot(t[1])}),TR.addSignature([he.Vec3,he.Vec3],[he.Number],function(i,e,t,n){n[0]=t[0].dot(t[1])}),TR.addSignature([he.Vec4,he.Vec4],[he.Number],function(i,e,t,n){n[0]=t[0].dot(t[1])});var ele=new ai("cross");ele.addSignature([he.Vec3,he.Vec3],[he.Vec3],function(i,e,t,n){n[0].crossVectors(t[0],t[1])});var IR=new ai("length");IR.addSignature([he.Vec2],[he.Number],function(i,e,t,n){n[0]=t[0].length()}),IR.addSignature([he.Vec3],[he.Number],function(i,e,t,n){n[0]=t[0].length()}),IR.addSignature([he.Vec4],[he.Number],function(i,e,t,n){n[0]=t[0].length()});var RR=new ai("lengthSq");RR.addSignature([he.Vec2],[he.Number],function(i,e,t,n){n[0]=t[0].lengthSq()}),RR.addSignature([he.Vec3],[he.Number],function(i,e,t,n){n[0]=t[0].lengthSq()}),RR.addSignature([he.Vec4],[he.Number],function(i,e,t,n){n[0]=t[0].lengthSq()});var PR=new ai("normalize");PR.addSignature([he.Vec2],[he.Vec2],function(i,e,t,n){n[0].copy(t[0]).normalize()}),PR.addSignature([he.Vec3],[he.Vec3],function(i,e,t,n){n[0].copy(t[0]).normalize()}),PR.addSignature([he.Vec4],[he.Vec4],function(i,e,t,n){n[0].copy(t[0]).normalize()});var tj=new ai("distance");tj.addSignature([he.Vec2,he.Vec2],[he.Number],function(i,e,t,n){n[0]=t[0].distanceTo(t[1])}),tj.addSignature([he.Vec3,he.Vec3],[he.Number],function(i,e,t,n){n[0]=t[0].distanceTo(t[1])});var tle=new ai("and");tle.addSignature([he.Boolean,he.Boolean],[he.Boolean],function(i,e,t,n){n[0]=t[0]&&t[1]});var ile=new ai("or");ile.addSignature([he.Boolean,he.Boolean],[he.Boolean],function(i,e,t,n){n[0]=t[0]||t[1]});var nle=new ai("not");nle.addSignature([he.Boolean],[he.Boolean],function(i,e,t,n){n[0]=!t[0]});var qx=new ai("equal");qx.addSignature([he.Number,he.Number],[he.Boolean],function(i,e,t,n){n[0]=t[0]===t[1]}),qx.addSignature([he.Vec2,he.Vec2],[he.Boolean],function(i,e,t,n){n[0]=t[0].equals(t[1])}),qx.addSignature([he.Vec3,he.Vec3],[he.Boolean],function(i,e,t,n){n[0]=t[0].equals(t[1])}),qx.addSignature([he.Vec4,he.Vec4],[he.Boolean],function(i,e,t,n){n[0]=t[0].equals(t[1])});var rle=new ai("lessThan");rle.addSignature([he.Number,he.Number],[he.Boolean],function(i,e,t,n){n[0]=t[0]<t[1]});var sle=new ai("greaterThan");sle.addSignature([he.Number,he.Number],[he.Boolean],function(i,e,t,n){n[0]=t[0]>t[1]});var ole=new ai("lessThanOrEqual");ole.addSignature([he.Number,he.Number],[he.Boolean],function(i,e,t,n){n[0]=t[0]<=t[1]});var ale=new ai("greaterThanOrEqual");ale.addSignature([he.Number,he.Number],[he.Boolean],function(i,e,t,n){n[0]=t[0]>=t[1]});var lle=new ai("if");lle.addSignature([he.Boolean,he.AnyType,he.AnyType],[he.AnyType],function(i,e,t,n){n[0]=t[0]?t[1]:t[2]});var cle=new ai("number");cle.addSignature([],[he.Number],function(i,e,t,n){n[0]=e.value});var hle=new ai("vec2");hle.addSignature([],[he.Vec2],function(i,e,t,n){n[0]=e.value});var ule=new ai("vec3");ule.addSignature([],[he.Vec3],function(i,e,t,n){n[0]=e.value});var dle=new ai("vec4");dle.addSignature([],[he.Vec4],function(i,e,t,n){n[0]=e.value});var ple=new ai("bool");ple.addSignature([],[he.Boolean],function(i,e,t,n){n[0]=e.value});var fle=new ai("particlePosition");fle.addSignature([],[he.Vec3],function(i,e,t,n){n[0]=i.particle[e.property]});var mle=new ai("particleVelocity");mle.addSignature([],[he.Vec3],function(i,e,t,n){n[0]=i.particle[e.property]});var gle=new ai("particleRotation");gle.addSignature([],[he.Number],function(i,e,t,n){n[0]=i.particle[e.property]});var vle=new ai("particleAge");vle.addSignature([],[he.Number],function(i,e,t,n){n[0]=i.particle[e.property]});var w0=new ai("output");w0.addSignature([he.Number],[he.Number],function(i,e,t,n){n[0]=t[0]}),w0.addSignature([he.Vec2],[he.Vec2],function(i,e,t,n){n[0]=t[0]}),w0.addSignature([he.Vec3],[he.Vec3],function(i,e,t,n){n[0]=t[0]}),w0.addSignature([he.Vec4],[he.Vec4],function(i,e,t,n){n[0]=t[0]}),w0.addSignature([he.Boolean],[he.Boolean],function(i,e,t,n){n[0]=t[0]}),console.log("%c Particle system powered by three.quarks. https://quarks.art/","font-size: 16px; font-weight: bold;");var Ale=Object.defineProperty,yle=Object.getOwnPropertyDescriptor,an=(i,e,t,n)=>{for(var r=n>1?void 0:n?yle(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&Ale(e,t,r),r};const S0=ee("debugparticles"),ble=ee("noprogressive"),_le=ee("debugprogressive");var BR=(i=>(i[i.Birth=0]="Birth",i[i.Collision=1]="Collision",i[i.Death=2]="Death",i[i.Trigger=3]="Trigger",i[i.Manual=4]="Manual",i))(BR||{});class Qo extends Ie{constructor(){super(...arguments),h(this,"renderMode"),h(this,"particleMaterial"),h(this,"trailMaterial"),h(this,"particleMesh"),h(this,"maxParticleSize"),h(this,"minParticleSize"),h(this,"velocityScale"),h(this,"cameraVelocityScale"),h(this,"lengthScale")}start(){if(this.maxParticleSize!==.5&&this.minParticleSize!==0&&pt()){const e=`ParticleSystem "${this.name}" has non-default min/max particle size. This may not render correctly. Please set min size to 0 and the max size to 0.5 and use the "StartSize" setting instead`;console.warn(e)}}get transparent(){var e;return((e=this.particleMaterial)==null?void 0:e.transparent)??!1}getMaterial(e=!1){let t=e===!0&&this.trailMaterial?this.trailMaterial:this.particleMaterial;return t&&e&&t.side===lr&&(t=t.clone(),t.side=cn,e?this.trailMaterial=t:this.particleMaterial=t),t&&!ble&&t._didRequestTextureLOD===void 0&&(t._didRequestTextureLOD=0,_le&&console.log("Load material LOD",t.name),Ui.assignTextureLOD(this.context,this.sourceId,t)),t}getMesh(e){let t=null;if(!t&&(this.particleMesh instanceof ue&&(t=this.particleMesh.geometry),t===null)){t=new Un(1,1);const n=t.attributes.uv;for(let r=0;r<n.count;r++)n.setX(r,1-n.getX(r))}return new ue(t,this.getMaterial())}}an([x()],Qo.prototype,"renderMode",2),an([x(It)],Qo.prototype,"particleMaterial",2),an([x(It)],Qo.prototype,"trailMaterial",2),an([x()],Qo.prototype,"maxParticleSize",2),an([x()],Qo.prototype,"minParticleSize",2),an([x()],Qo.prototype,"velocityScale",2),an([x()],Qo.prototype,"cameraVelocityScale",2),an([x()],Qo.prototype,"lengthScale",2);class Xx{constructor(e,t=1){h(this,"_curve"),h(this,"_factor"),h(this,"type","function"),this._curve=e,this._factor=t}genValue(e){return this._curve.evaluate(e,Math.random())*this._factor}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}}class DR{constructor(e){h(this,"type","value"),h(this,"system"),this.system=e}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}}class xle extends DR{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class wle extends DR{constructor(){super(...arguments),h(this,"_lastPosition",new S),h(this,"_lastDistance",0)}update(){const e=Rt(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(e),this._lastPosition.copy(e)}genValue(){if(!this.system.isPlaying||!this.system.emission.enabled||this.system.currentParticles>=this.system.maxParticles)return 0;let e=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){const r=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let s=this._lastDistance/this.system.deltaTime*r;Number.isFinite(s)||(s=0),e+=s}const t=this.system.emission.getBurst();t>0&&(e+=t/this.system.deltaTime);const n=this.system.maxParticles-this.system.currentParticles;return Ze.clamp(e,0,n/this.system.deltaTime)}}class Sle extends DR{genValue(){return this.system.isPlaying,0}}class Dh{constructor(e){h(this,"system"),h(this,"type"),this.type=Object.getPrototypeOf(this).constructor.name||"ParticleSystemBaseBehaviour",e&&(this.system=e)}get context(){return this.system.context}initialize(e){}update(e,t){}frameUpdate(e){}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}reset(){}}class Cle extends Dh{constructor(){super(...arguments),h(this,"type","NeedleTextureSheet")}update(e,t){const n=this.system.textureSheetAnimation;if(n.enabled){const r=e.age/e.life,s=n.evaluate(r);s!==void 0&&(e.uvTile=s)}}}const ij=Symbol("particleRotation");class Ele extends Dh{constructor(){super(...arguments),h(this,"type","NeedleRotation")}initialize(e){e[ij]=Math.random()}update(e,t){if(e.rotation===void 0)return;const n=e.age/e.life;if(typeof e.rotation=="number"&&(this.system.rotationOverLifetime.enabled?e.rotation+=this.system.rotationOverLifetime.evaluate(n,e[ij])*t:this.system.renderer.renderMode===uc.Billboard&&(e.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const r=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(n,r)*t}}}const nj=Symbol("sizeLerpFactor"),Mle=new S;class Tle extends Dh{constructor(){super(...arguments),h(this,"type","NeedleSize"),h(this,"_minSize",0),h(this,"_maxSize",1)}initialize(e){e[nj]=Math.random(),this._minSize=this.system.renderer.minParticleSize,this._maxSize=this.system.renderer.maxParticleSize}update(e,t){const n=e.age/e.life;let r=1;this.system.sizeOverLifetime.enabled&&(r*=this.system.sizeOverLifetime.evaluate(n,void 0,e[nj]).x);let s=1;if(this.system.renderer.renderMode!==uc.Mesh&&(s=this.system.worldScale.x/this.system.cameraScale),e.size=e.startSize*r*s,this.system.localspace){const o=lj(this.system,Mle);e.size*=o.x}}}const jf=Symbol("particleLife"),OR=Symbol("trailLifetime"),rj=Symbol("trailStartLength"),kR=Symbol("trailWidthRandom");class Ile extends Dh{constructor(){super(...arguments),h(this,"type","NeedleTrail")}initialize(e){e instanceof A0&&(e[jf]=e.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(e[OR]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),e.life+=e[OR]),e[rj]=e.length,e[kR]=Math.random())}update(e){var t;if((t=this.system.trails)!=null&&t.enabled&&e instanceof A0){const n=e,r=e.age/e[jf],s=e.previous.values(),o=e.previous.length;for(let a=0;a<o;a++){const l=s.next().value,c=1-a/(o-1);let u=e.size;u<=0&&!this.system.trails.sizeAffectsWidth&&(u=20*this.system.trails.widthOverTrail.evaluate(.5,n[kR])),l.size=this.system.trails.getWidth(u,r,c,n[kR]),l.color.copy(e.color),this.system.trails.getColor(l.color,r,c)}if(e.age>e[jf]){e.velocity.set(0,0,0);const a=(e.age-e[jf])/e[OR];n.length=Ze.lerp(e[rj],0,a)}}}}const Yx=Symbol("startVelocity"),sj=Symbol("gravityModifier"),LR=Symbol("gravitySpeed"),Jx=Symbol("velocity lerp factor"),UR=new S;class Rle extends Dh{constructor(){super(...arguments),h(this,"type","NeedleVelocity"),h(this,"_gravityDirection",new S)}initialize(e){var t,n;const r=this.system.main.simulationSpeed;e.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random()),e.velocity.copy(this.system.shape.getDirection(e,e.position)).multiplyScalar(e.startSpeed),(t=this.system.inheritVelocity)!=null&&t.enabled&&this.system.inheritVelocity.applyInitial(e.velocity),e[Yx]?e[Yx].copy(e.velocity):e[Yx]=e.velocity.clone();const s=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());e[sj]=s*r,e[LR]=s*r*.5,e[Jx]=Math.random(),(n=this.system.velocityOverLifetime)==null||n.init(e),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===e0.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(e,t){var n;const r=e[Yx],s=e[sj];if(s!==0){const p=s*e[LR];UR.copy(this._gravityDirection).multiplyScalar(p),e[LR]+=t*.05,r.add(UR)}e.velocity.copy(r);const o=e.age/e.life;(n=this.system.inheritVelocity)!=null&&n.enabled&&this.system.inheritVelocity.applyCurrent(e.velocity,o,e[Jx]);const a=this.system.noise;a.enabled&&a.apply(0,e.position,e.velocity,t,e.age,e.life);const l=this.system.sizeBySpeed;l!=null&&l.enabled&&(e.size=l.evaluate(e.velocity,o,e[Jx],e.size));const c=this.system.colorBySpeed;c!=null&&c.enabled&&c.evaluate(e.velocity,e[Jx],e.color);const u=this.system.velocityOverLifetime;u.enabled&&u.apply(e,0,e.position,e.velocity,t,e.age,e.life);const d=this.system.limitVelocityOverLifetime;d.enabled&&d.apply(e.position,r,e.velocity,e.size,o,t,1),this.system.worldspace&&e.velocity.multiply(this.system.worldScale)}}const oj=Symbol("colorLerpFactor"),aj=new yi(1,1,1,1),Sd=new yi(1,1,1,1);class Ple extends Dh{constructor(){super(...arguments),h(this,"type","NeedleColor")}initialize(e){}_init(e){const t=this.system.renderer.particleMaterial;Sd.copy(this.system.main.startColor.evaluate(Math.random())),t!=null&&t.color&&(aj.copy(t.color),Sd.multiply(aj)),Sd.convertLinearToSRGB(),e.startColor.set(Sd.r,Sd.g,Sd.b,Sd.alpha),e.color.copy(e.startColor),e[oj]=Math.random()}update(e,t){if(e.age===0&&this._init(e),this.system.colorOverLifetime.enabled){const n=e.age/e.life,r=this.system.colorOverLifetime.color.evaluate(n,e[oj]);e.color.set(r.r,r.g,r.b,r.alpha).multiply(e.startColor)}else e.color.copy(e.startColor)}}class Ble{constructor(e){h(this,"system"),h(this,"emission"),h(this,"autoDestroy"),h(this,"startLength"),h(this,"emissionBursts"),h(this,"onlyUsedByOther"),h(this,"behaviors",[]),h(this,"rendererEmitterSettings",{startLength:new Zr(220),followLocalOrigin:!1}),h(this,"flatWhiteTexture"),h(this,"clonedTexture",{original:void 0,clone:void 0}),this.system=e,this.emission=new wle(this.system)}get anim(){return this.system.textureSheetAnimation}get prewarm(){return!1}get material(){return this.system.renderer.getMaterial(this.system.trails.enabled)}get layers(){return this.system.gameObject.layers}update(){this.emission.update()}get looping(){return this.system.main.loop}get duration(){return this.system.duration}get shape(){return this.system.shape}get startLife(){return new Xx(this.system.main.startLifetime)}get startSpeed(){return new Xx(this.system.main.startSpeed)}get startRotation(){return new Xx(this.system.main.startRotation)}get startSize(){return new Xx(this.system.main.startSize)}get startColor(){return new Gx(new Ye(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new Sle(this.system)}get instancingGeometry(){return this.system.renderer.getMesh(this.system.renderer.renderMode).geometry}get renderMode(){if(this.system.trails.enabled===!0)return tt.Trail;switch(this.system.renderer.renderMode){case uc.Billboard:return tt.BillBoard;case uc.Stretch:return tt.StretchedBillBoard;case uc.HorizontalBillboard:return tt.HorizontalBillBoard;case uc.VerticalBillboard:return tt.VerticalBillBoard;case uc.Mesh:return tt.Mesh}return tt.BillBoard}get speedFactor(){var e;let t=this.system.main.simulationSpeed;return((e=this.system.renderer)==null?void 0:e.renderMode)===uc.Stretch&&(t*=this.system.renderer.velocityScale??1),t}get texture(){const e=this.material;if(e&&e.map){const t=e.map;if(this.clonedTexture.original!==t||!this.clonedTexture.clone){const n=t.clone();n.premultiplyAlpha=!1,n.colorSpace=pi,this.clonedTexture.original=t,this.clonedTexture.clone=n}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=Y3(new yi(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new xle(this.system)}get uTileCount(){var e;return this.anim.enabled?(e=this.anim)==null?void 0:e.numTilesX:void 0}get vTileCount(){var e;return this.anim.enabled?(e=this.anim)==null?void 0:e.numTilesY:void 0}get renderOrder(){return 1}get blending(){var e;return((e=this.system.renderer.particleMaterial)==null?void 0:e.blending)??Sc}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===e0.World}}class Dle{constructor(){h(this,"burstIndex",0),h(this,"burstWaveIndex",0),h(this,"time",0),h(this,"waitEmiting",0)}}const Kx=class extends Ie{constructor(){super(...arguments),h(this,"_state"),h(this,"colorOverLifetime"),h(this,"main"),h(this,"emission"),h(this,"sizeOverLifetime"),h(this,"shape"),h(this,"noise"),h(this,"trails"),h(this,"velocityOverLifetime"),h(this,"limitVelocityOverLifetime"),h(this,"inheritVelocity"),h(this,"colorBySpeed"),h(this,"textureSheetAnimation"),h(this,"rotationOverLifetime"),h(this,"rotationBySpeed"),h(this,"sizeBySpeed"),h(this,"_cameraScale",1),h(this,"__worldQuaternion",new Me),h(this,"_worldQuaternionInverted",new Me),h(this,"_worldScale",new S),h(this,"_worldPositionFrame",-1),h(this,"_worldPos",new S),h(this,"_renderer"),h(this,"_batchSystem"),h(this,"_particleSystem"),h(this,"_interface"),h(this,"_container"),h(this,"_time",0),h(this,"_isPlaying",!0),h(this,"_isUsedAsSubsystem",!1),h(this,"_didPreWarm",!1),h(this,"_bursts"),h(this,"_subEmitterSystems"),h(this,"_lastBatchesCount",-1),h(this,"lastMaterialVersion",-1)}play(i=!1){var e;i&&re.foreachComponent(this.gameObject,t=>{t instanceof Kx&&t!==this&&t.play(!1)},!0),this._isPlaying=!0,this._particleSystem&&(this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1),(e=this.emission)==null||e.reset()}pause(i=!0){i&&re.foreachComponent(this.gameObject,e=>{e instanceof Kx&&e!==this&&e.pause(!1)},!0),this._isPlaying=!1}stop(i=!0,e=!1){i&&re.foreachComponent(this.gameObject,t=>{t instanceof Kx&&t!==this&&t.stop(!1,e)},!0),this._isPlaying=!1,this._time=0,e&&this.reset()}reset(){var i;this._time=0,this._particleSystem&&(this._particleSystem.particleNum=0,this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1,(i=this.emission)==null||i.reset())}emit(i){if(this._particleSystem){this.onUpdate(),i=Math.min(i,this.maxParticles-this.currentParticles),this._state||(this._state=new Dle),this._state.waitEmiting=i,this._state.time=0;const e=this._particleSystem.emitEnded;this._particleSystem.emitEnded=!1,this._particleSystem.emit(this.deltaTime,this._state,this._particleSystem.emitter.matrixWorld),this._particleSystem.emitEnded=e}}get playOnAwake(){return this.main.playOnAwake}set playOnAwake(i){this.main.playOnAwake=i}get renderer(){return this._renderer}get isPlaying(){return this._isPlaying}get currentParticles(){var i;return((i=this._particleSystem)==null?void 0:i.particleNum)??0}get maxParticles(){return this.main.maxParticles}get time(){return this._time}get duration(){return this.main.duration}get deltaTime(){return this.context.time.deltaTime*this.main.simulationSpeed}get scale(){return this.gameObject.scale.x}get cameraScale(){return this._cameraScale}get container(){return this._container}get worldspace(){return this.main.simulationSpace===e0.World}get localspace(){return this.main.simulationSpace===e0.Local}get worldQuaternion(){return this.__worldQuaternion}get worldQuaternionInverted(){return this._worldQuaternionInverted}get worldScale(){return this._worldScale}get worldPos(){return this._worldPositionFrame!==this.context.time.frame&&(this._worldPositionFrame=this.context.time.frame,Rt(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}addBehaviour(i){return this._particleSystem?(i instanceof Dh&&(i.system=this),pt()&&console.log("add behaviour",i),this._particleSystem.addBehavior(i),!0):!1}removeAllBehaviours(){return this._particleSystem?(this._particleSystem.behaviors.length=0,!0):!1}get behaviours(){return this._particleSystem?this._particleSystem.behaviors:null}get particleSystem(){return this._particleSystem??null}set bursts(i){for(let e=0;e<i.length;e++){const t=i[e];if(!(t instanceof t0)){const n=new t0;Bp(n,t),i[e]=n}}this._bursts=i}set subEmitterSystems(i){for(let e=0;e<i.length;e++){const t=i[e];if(!(t instanceof C0)){const n=new C0;Bp(n,t),i[e]=n}}S0&&i.length>0&&console.log("SubEmitters: ",i,this),this._subEmitterSystems=i}onAfterDeserialize(i){if(this._subEmitterSystems&&Array.isArray(this._subEmitterSystems))for(const e of this._subEmitterSystems)e._deserialize(this.context,this.gameObject)}awake(){if(this._worldPositionFrame=-1,this._renderer=this.gameObject.getComponent(Qo),!this.main)throw new Error("Not Supported: ParticleSystem needs a serialized MainModule. Creating new particle systems at runtime is currently not supported.");this._container=new ge,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new Hae,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new Ble(this),this._particleSystem=new Dae(this._interface),this._particleSystem.addBehavior(new Tle(this)),this._particleSystem.addBehavior(new Ple(this)),this._particleSystem.addBehavior(new Cle(this)),this._particleSystem.addBehavior(new Ele(this)),this._particleSystem.addBehavior(new Rle(this)),this._particleSystem.addBehavior(new Ile(this)),this._batchSystem.addSystem(this._particleSystem);const i=this._particleSystem.emitter;this.context.scene.add(i),this.inheritVelocity.system&&this.inheritVelocity.system!==this&&(this.inheritVelocity=this.inheritVelocity.clone()),this.inheritVelocity.awake(this),S0&&(console.log(this),this.gameObject.add(new yo(1)))}start(){this.addSubParticleSystems(),this.updateLayers()}onDestroy(){var i,e,t,n;(i=this._container)==null||i.removeFromParent(),(e=this._batchSystem)==null||e.removeFromParent(),(t=this._particleSystem)==null||t.emitter.removeFromParent(),(n=this._particleSystem)==null||n.dispose()}onEnable(){this.main&&(this.inheritVelocity&&(this.inheritVelocity.system=this),this._batchSystem&&(this._batchSystem.visible=!0),this.playOnAwake&&this.play(),this._isPlaying=this.playOnAwake)}onDisable(){this._batchSystem&&(this._batchSystem.visible=!1)}onBeforeRender(){var i;this.main&&(this._didPreWarm===!1&&((i=this.main)==null?void 0:i.prewarm)===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){var i;if(!((i=this.emission)!=null&&i.enabled)||this.emission.rateOverTime.getMax()<=0)return;const e=1/60,t=this.main.duration,n=this.main.startLifetime.getMax(),r=1e3,s=Math.min(Math.max(t,n)/Math.max(.01,this.main.simulationSpeed),r),o=Math.ceil(s/e),a=Date.now();S0&&console.log(`Particles ${this.name} - Prewarm for ${o} frames (${s} sec). Duration: ${t}, Lifetime: ${n}`);for(let l=0;l<o&&!(this.currentParticles>=this.maxParticles);l++){const c=Date.now()-a;if(c>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${c}`);break}this.onUpdate(),this.onSimulate(e)}}onSimulate(i){if(this._batchSystem){let e=this.context.time.frameCount%60===0;this._lastBatchesCount!==this._batchSystem.batches.length&&(this._lastBatchesCount=this._batchSystem.batches.length,e=!0),e&&this.updateLayers(),this._batchSystem.update(i)}this._time+=i,this._time>this.duration&&(this._time=0)}updateLayers(){if(this._batchSystem)for(let i=0;i<this._batchSystem.batches.length;i++){const e=this._batchSystem.batches[i];e.layers.disableAll();const t=this.layer;e.layers.mask=1<<t}}onUpdate(){var i,e;const t=this.renderer.getMaterial(this.trails.enabled);if(t&&t.version!=this.lastMaterialVersion&&this._particleSystem&&(this.lastMaterialVersion=t.version,this._particleSystem.texture=this._interface.texture),this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const n=this.context.mainCamera;if(n){const o=ki(n);this._cameraScale=o.x}const r=!this.worldspace,s=this.gameObject;if(xi(s,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),ki(this.gameObject,this._worldScale),r&&this._container&&(i=this.gameObject)!=null&&i.parent){const o=lj(this,UR);this._container.matrix.makeScale(o.x,o.y,o.z),this._container.matrix.makeRotationFromQuaternion(this.__worldQuaternion),this._container.matrix.setPosition(this.worldPos),this._container.matrix.scale(this.gameObject.scale)}this.emission.system=this,this._interface.update(),this.shape.update(this,this.context,this.main.simulationSpace,this.gameObject),this.noise.update(this.context),(e=this.inheritVelocity)==null||e.update(this.context),this.velocityOverLifetime.update(this)}addSubParticleSystems(){var i;if(this._subEmitterSystems&&this._particleSystem)for(const e of this._subEmitterSystems){e.particleSystem&&(e.particleSystem.__internalAwake?e.particleSystem.__internalAwake():pt()&&console.warn("SubParticleSystem serialization issue(?)",e.particleSystem,e));const t=(i=e.particleSystem)==null?void 0:i._particleSystem;if(t){e.particleSystem._isUsedAsSubsystem=!0;const n=new Zx(this,this._particleSystem,e.particleSystem,t);n.emitterType=e.type,n.emitterProbability=e.emitProbability,this._particleSystem.addBehavior(n)}else S0&&console.warn("Could not add SubParticleSystem",e,this)}}};let kn=Kx;an([x(i0)],kn.prototype,"colorOverLifetime",2),an([x(Ir)],kn.prototype,"main",2),an([x(el)],kn.prototype,"emission",2),an([x(Eh)],kn.prototype,"sizeOverLifetime",2),an([x(sn)],kn.prototype,"shape",2),an([x(_i)],kn.prototype,"noise",2),an([x(Xi)],kn.prototype,"trails",2),an([x(on)],kn.prototype,"velocityOverLifetime",2),an([x(Dn)],kn.prototype,"limitVelocityOverLifetime",2),an([x(Mh)],kn.prototype,"inheritVelocity",2),an([x(dd)],kn.prototype,"colorBySpeed",2),an([x(Rr)],kn.prototype,"textureSheetAnimation",2),an([x(jo)],kn.prototype,"rotationOverLifetime",2),an([x(io)],kn.prototype,"rotationBySpeed",2),an([x(_s)],kn.prototype,"sizeBySpeed",2);class C0{constructor(){h(this,"particleSystem"),h(this,"emitProbability",1),h(this,"properties"),h(this,"type")}_deserialize(e,t){const n=this.particleSystem;if(n instanceof kn)return;let r="";n&&typeof n.guid=="string"&&(r=n.guid,this.particleSystem=re.findByGuid(r,t)),S0&&!(this.particleSystem instanceof kn)&&console.warn("Could not find particle system for sub emitter",r,t,this)}}function lj(i,e){if(e.set(1,1,1),i.gameObject.parent&&i.localspace)switch(i.main.scalingMode){case FI.Local:e=ki(i.gameObject.parent,e),e.x=1/e.x,e.y=1/e.y,e.z=1/e.z;break;default:if(!i.unsupported_scaling_mode){i.unsupported_scaling_mode=!0;const t="ParticleSystem scale mode "+FI[i.main.scalingMode]+" is not supported";pt()&&Qi(t),console.warn(t,i.name,i)}e=ki(i.gameObject,e);break}return e}new S(1,1,1),new S(0,0,1);class Zx{constructor(e,t,n,r){h(this,"type","NeedleParticleSubEmitter"),h(this,"emitterType"),h(this,"emitterProbability"),h(this,"q_",new Me),h(this,"v_",new S),h(this,"v2_",new S),h(this,"_emitterMatrix",new Ce),h(this,"_circularBuffer"),this.system=e,this.particleSystem=t,this.subSystem=n,this.subParticleSystem=r,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const s=1e3;this._circularBuffer=new bo(()=>new Ce,s)}clone(){throw new Error("Method not implemented.")}initialize(e){e.emissionState={burstIndex:0,burstWaveIndex:0,time:0,waitEmiting:0},this._emitterMatrix.copy(this.subSystem.matrixWorld).invert().premultiply(this.system.matrixWorld),this._emitterMatrix.setPosition(0,0,0),this.emitterType===BR.Birth&&this.run(e)}update(e,t){this.run(e)}frameUpdate(e){}toJSON(){}reset(){}run(e){if(this.subSystem.currentParticles>=this.subSystem.main.maxParticles||!this.subParticleSystem||!e.emissionState||this.emitterProbability&&Math.random()>this.emitterProbability)return;const t=this.system.deltaTime;if(this.emitterType===BR.Death){let r=e.life;if(e[jf]!==void 0&&(r=e[jf]),!(e.age+t*1.2>=r))return;const s=this.subSystem.main.maxParticles-this.subSystem.currentParticles;e.emissionState.waitEmiting=s}const n=new Ce;n.set(1,0,0,e.position.x,0,1,0,e.position.y,0,0,1,e.position.z,0,0,0,1),this.particleSystem.worldSpace||n.multiplyMatrices(this._emitterMatrix,n),this.subParticleSystem.emit(t,e.emissionState,n)}}var Ole=Object.defineProperty,kle=Object.getOwnPropertyDescriptor,Lle=(i,e,t,n)=>{for(var r=n>1?void 0:n?kle(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&Ole(e,t,r),r};class E0 extends Yr{constructor(){super(...arguments),h(this,"granularity")}get typeName(){return"PixelationEffect"}onCreateEffect(){const e=new CL;return this.granularity.onValueChanged=t=>{e.granularity=t},e}}Lle([x(Bt)],E0.prototype,"granularity",2),Fo("PixelationEffect",E0);class nm extends Ie{constructor(){super(...arguments),h(this,"_didAssignPlayerColor",!1),h(this,"tryAssignColor",()=>{const e=re.getComponentInParent(this.gameObject,No);if(e&&e.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(e.owner),!0;const t=re.getComponentInParent(this.gameObject,Er);return t!=null&&t.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(t.connectionId),!0):!1})}onEnable(){this.context.connection.beginListen(Jt.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(Jt.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield T3(.2),!this.tryAssignColor()););}assignUserColor(e){const t=nm.hashCode(e),n=nm.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){const r=this.gameObject;this.assignColor(n,e,r)}else if(this.gameObject.children)for(const r of this.gameObject.children){const s=r;s.material&&s.material.color&&this.assignColor(n,e,s)}}assignColor(e,t,n){let r=n.material;r&&(r._playerMaterial!==t&&(r=r.clone(),r._playerMaterial=t,n.material=r),r.color=e)}static hashCode(e){var t=0,n,r;if(e.length===0)return t;for(n=0;n<e.length;n++)r=e.charCodeAt(n),t=(t<<5)-t+r,t|=0;return t}static colorFromHashCode(e){const t=(e&16711680)>>16,n=(e&65280)>>8,r=e&255;return new Se(t/255,n/255,r/255)}}async function FR(i){const{NeedleEngineHTMLElement:e}=await Promise.resolve().then(()=>Yhe);e.observedAttributes.includes(i)||e.observedAttributes.push(i)}var Ule=Object.defineProperty,Fle=Object.getOwnPropertyDescriptor,$x=(i,e,t,n)=>{for(var r=n>1?void 0:n?Fle(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&Ule(e,t,r),r};const sl=ee("debugskybox");FR("skybox-image"),FR("environment-image");function cj(i,e,t,n,r){const s=new pc;s.allowDrop=!1,s.allowNetworking=!1,s.background=t,s.environment=n,re.addComponent(i.scene,s);const o=a=>{typeof a=="string"&&(sl&&console.log(r,"CHANGED TO",a),s.setSkybox(a))};return AO(i.domElement,r,o),s.addEventListener("destroy",()=>{sl&&console.log("Destroyed attribute remote skybox",r),yO(i.domElement,r,o)}),s.setSkybox(e)}ii.addContextCreatedCallback(i=>{var e;const t=i.context,n=t.domElement.getAttribute("skybox-image"),r=t.domElement.getAttribute("environment-image"),s=new Array;if(n){sl&&console.log("Creating remote skybox to load "+n),((e=t.mainCameraComponent)==null?void 0:e.clearFlags)!==Ju.Skybox&&console.warn('"skybox-image" attribute has no effect: camera clearflags are not set to "Skybox"');const o=cj(t,n,!0,!1,"skybox-image");s.push(o)}if(r){sl&&console.log("Creating remote environment to load "+r);const o=cj(t,r,!1,!0,"environment-image");s.push(o)}return s.length>0?Jm(s):Promise.resolve()});function hj(){return globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES||(globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES=new Array),globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES}function Nle(i){const e=hj().find(t=>t.src===i);return e?(sl&&console.log("Skybox: Found previously loaded texture for "+i),e.texture):null}async function zle(i){const e=await i;EE(e,!0),Ii(e)}function jle(i,e){const t=hj();for(;t.length>5;){const n=t.shift();n&&zle(n.texture)}e.then(n=>EE(n,!1)),t.push({src:i,texture:e})}class pc extends Ie{constructor(){super(...arguments),h(this,"url"),h(this,"allowDrop",!0),h(this,"background",!0),h(this,"environment",!0),h(this,"allowNetworking",!0),h(this,"_loader"),h(this,"_prevUrl"),h(this,"_prevLoadedEnvironment"),h(this,"_prevEnvironment",null),h(this,"_prevBackground",null),h(this,"dragOverEvent"),h(this,"dropEvent")}onEnable(){this.setSkybox(this.url),this.registerDropEvents()}onDisable(){var e;this.context.scene.environment===this._prevLoadedEnvironment&&(this.context.scene.environment=this._prevEnvironment,Ri.backgroundShouldBeTransparent(this.context)||(this.context.scene.background=this._prevBackground),this._prevLoadedEnvironment=void 0),this.unregisterDropEvents(),(e=this.context.mainCameraComponent)==null||e.applyClearFlags()}urlChangedSyncField(){this.allowNetworking&&this.setSkybox(this.url)}async setSkybox(e){var t;if(!this.activeAndEnabled||!e)return!1;if(!(e!=null&&e.endsWith(".hdr"))&&!e.endsWith(".exr")&&!e.endsWith(".jpg")&&!e.endsWith(".png")&&!e.endsWith(".jpeg")&&console.warn("Potentially invalid skybox url",this.url,"on",this.name),sl&&console.log("Remote skybox url?: "+e),this._prevUrl===e&&this._prevLoadedEnvironment)return this.applySkybox(),!0;(t=this._prevLoadedEnvironment)==null||t.dispose(),this._prevLoadedEnvironment=void 0,this._prevUrl=e;const n=await this.loadTexture(e);if(!n||!this.enabled)return!1;this.url=e;const r=e.lastIndexOf("/");return n.name=e.substring(r>=0?r+1:0),this._loader instanceof Ba&&(n.colorSpace=dt),this._prevLoadedEnvironment=n,this.applySkybox(),!0}async loadTexture(e){var t,n,r,s,o;if(!e)return Promise.resolve(null);const a=Nle(e);if(a){const d=await a;if(((n=(t=d.source)==null?void 0:t.data)==null?void 0:n.length)>0||(o=(s=(r=d.source)==null?void 0:r.data)==null?void 0:s.data)!=null&&o.length)return d}const l=e.endsWith(".exr"),c=e.endsWith(".hdr");l?this._loader instanceof o_||(this._loader=new o_):c?this._loader instanceof HM||(this._loader=new HM):this._loader instanceof Ba||(this._loader=new Ba),sl&&console.log("Loading skybox: "+e);const u=this._loader.loadAsync(e);return jle(e,u),await u}applySkybox(){var e;const t=this._prevLoadedEnvironment;t&&(t.mapping=Nd,t.needsUpdate=!0,this.context.scene.background!==t&&(this._prevBackground=this.context.scene.background),this.context.scene.environment!==t&&(this._prevEnvironment=this.context.scene.environment),sl&&console.log("Set remote skybox",this.url),this.environment&&(this.context.scene.environment=t),this.background&&!Ri.backgroundShouldBeTransparent(this.context)&&(this.context.scene.background=t),((e=this.context.mainCameraComponent)==null?void 0:e.backgroundBlurriness)!==void 0&&(this.context.scene.backgroundBlurriness=this.context.mainCameraComponent.backgroundBlurriness))}registerDropEvents(){this.dragOverEvent||(this.dragOverEvent=e=>{if(this.allowDrop&&e.dataTransfer)for(const t of e.dataTransfer.types)t==="text/uri-list"&&e.preventDefault()},this.dropEvent=e=>{var t,n,r,s;if(this.allowDrop&&(e.preventDefault(),!!e.dataTransfer)){for(const o of e.dataTransfer.types)if(o==="text/uri-list"){const a=e.dataTransfer.getData(o);sl&&console.log(o,a);let l=(n=(t=new RegExp(/polyhaven.com\/asset_img\/.+?\/(?<name>.+)\.png/).exec(a))==null?void 0:t.groups)==null?void 0:n.name;if(l||(l=(s=(r=new RegExp(/polyhaven\.com\/a\/(?<name>.+)/).exec(a))==null?void 0:r.groups)==null?void 0:s.name),sl&&console.log(l),l){const c="https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/"+l+"_1k.exr";this.setSkybox(c)}else console.warn("Could not resolve skybox name from dropped url",a)}}},this.context.domElement.addEventListener("dragover",this.dragOverEvent),this.context.domElement.addEventListener("drop",this.dropEvent))}unregisterDropEvents(){this.dragOverEvent&&(this.context.domElement.removeEventListener("dragover",this.dragOverEvent),this.context.domElement.removeEventListener("drop",this.dropEvent))}}$x([eI(pc.prototype.urlChangedSyncField),x(URL)],pc.prototype,"url",2),$x([x()],pc.prototype,"allowDrop",2),$x([x()],pc.prototype,"background",2),$x([x()],pc.prototype,"environment",2);var Gle=Object.defineProperty,Qle=Object.getOwnPropertyDescriptor,so=(i,e,t,n)=>{for(var r=n>1?void 0:n?Qle(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&Gle(e,t,r),r};const oo=ee("debugsceneswitcher"),ew="scene";FR(ew);const Oh=Promise.resolve(!1);class $r extends Ie{constructor(){super(...arguments),h(this,"autoLoadFirstScene",!0),h(this,"scenes"),h(this,"loadingScene"),h(this,"queryParameterName","scene"),h(this,"useSceneName",!0),h(this,"clamp",!0),h(this,"useHistory",!0),h(this,"useKeyboard",!0),h(this,"useSwipe",!0),h(this,"useSceneLighting",!0),h(this,"preloadNext",1),h(this,"preloadPrevious",1),h(this,"preloadConcurrent",2),h(this,"_currentIndex",-1),h(this,"_currentScene"),h(this,"_engineElementOverserver"),h(this,"_preloadScheduler"),h(this,"onPopState",async e=>{if(!this.useHistory)return;const t=this.useHistory;try{this.useHistory=!1;let n=!1;if(this.queryParameterName&&(n=await this.tryLoadFromQueryParam()),!n){const r=e?.state;if(r&&r.startsWith(this.guid)){const s=r.substr(this.guid.length+2);oo&&console.log("PopState",s),await this.trySelectSceneFromValue(s)}}}finally{this.useHistory=t}}),h(this,"normalizedSwipeThresholdX",.1),h(this,"_didSwipe",!1),h(this,"onInputPointerMove",e=>{if(this.useSwipe&&!this._didSwipe&&e.button===0&&e.pointerType==="touch"&&this.context.input.getPointerPressedCount()===1){const t=this.context.input.getPointerPositionDelta(e.button);if(t){const n=t.x/this.context.domWidth;n>=this.normalizedSwipeThresholdX?(this._didSwipe=!0,this.selectPrev()):n<=-this.normalizedSwipeThresholdX&&(this._didSwipe=!0,this.selectNext())}}}),h(this,"onInputPointerUp",e=>{e.button===0&&(this._didSwipe=!1)}),h(this,"onInputKeyDown",e=>{if(!this.useKeyboard||!this.scenes)return;const t=e.key.toLowerCase();if(!t)return;const n=parseInt(t)-1;if(n>=0){this.trySelectSceneFromValue(n);return}switch(t){case"arrowright":case"d":this.selectNext();break;case"arrowleft":case"a":this.selectPrev();break}}),h(this,"__lastSwitchScene"),h(this,"__lastSwitchScenePromise"),h(this,"_currentlyLoadingScene"),h(this,"_lastLoadingScene"),h(this,"_loadingScenePromise"),h(this,"_isCurrentlyLoading",!1),h(this,"_currentLoadingProgress")}get currentIndex(){return this._currentIndex}get currentLoadingProgress(){return this._currentLoadingProgress}get currentlyLoadingScene(){return this._currentlyLoadingScene}get currentlyLoadedScene(){return this._currentScene}awake(){oo&&console.log("SceneSwitcher",this)}async onEnable(){if(globalThis.addEventListener("popstate",this.onPopState),this.context.input.addEventListener(Wi.KeyDown,this.onInputKeyDown),this.context.input.addEventListener(Wi.PointerMove,this.onInputPointerMove),this.context.input.addEventListener(Wi.PointerUp,this.onInputPointerUp),this._engineElementOverserver||(this._engineElementOverserver=new MutationObserver(e=>{for(const t of e)if(t.type==="attributes"&&t.attributeName===ew){const n=this.context.domElement.getAttribute(ew);n!==null&&this.trySelectSceneFromValue(n)}})),this._engineElementOverserver.observe(this.context.domElement,{attributes:!0}),this._preloadScheduler||(this._preloadScheduler=new Hle(this)),this._preloadScheduler.maxLoadAhead=this.preloadNext,this._preloadScheduler.maxLoadBehind=this.preloadPrevious,this._preloadScheduler.maxConcurrent=this.preloadConcurrent,this._preloadScheduler.begin(),this.autoLoadFirstScene&&this._currentIndex===-1&&!await this.tryLoadFromQueryParam()){const e=this.context.domElement.getAttribute(ew);try{(e===null||!await this.trySelectSceneFromValue(e))&&this._currentIndex===-1&&this.select(0)}finally{}}}onDisable(){var e;globalThis.removeEventListener("popstate",this.onPopState),this.context.input.removeEventListener(Wi.KeyDown,this.onInputKeyDown),this.context.input.removeEventListener(Wi.PointerMove,this.onInputPointerMove),this.context.input.removeEventListener(Wi.PointerUp,this.onInputPointerUp),(e=this._preloadScheduler)==null||e.stop()}selectNext(){return this.select(this._currentIndex+1)}selectPrev(){return this.select(this._currentIndex-1)}select(e){var t,n,r;if(oo&&console.log("select",e),typeof e=="object"&&console.warn('Switching to "'+e+'" might not work. Please either use an index or a AssetReference (not a scene reference)'),typeof e=="string"){const o=(t=this.scenes)==null?void 0:t.find(a=>a.uri===e);if(!o){const a=ni.getOrCreate(this.sourceId??"",e,this.context);return this.switchScene(a)}if(o)e=(n=this.scenes)==null?void 0:n.indexOf(o);else return Oh}if(!((r=this.scenes)!=null&&r.length))return Oh;if(e<0){if(this.clamp)return Oh;e=this.scenes.length-1}else if(e>=this.scenes.length){if(this.clamp)return Oh;e=0}const s=this.scenes[e];return this.switchScene(s)}async switchScene(e){if(!(e instanceof ni)){const t=typeof e;return t==="string"?this.select(e):t==="number"?this.select(e):(console.warn("SceneSwitcher: Can't switch to scene",e,"of type",t),!1)}return e.uri===this.sourceId?(console.warn("SceneSwitcher: can't load own scene - prevent recursive loading",this.sourceId),!1):this.__lastSwitchScene===e&&this.__lastSwitchScenePromise?this.__lastSwitchScenePromise:(this.__lastSwitchScene=e,this.__lastSwitchScenePromise=this.__internalSwitchScene(e),await this.__lastSwitchScenePromise)}async __internalSwitchScene(e){var t,n;if(this._currentScene){oo&&console.log("UNLOAD",e.uri);const s=this.tryGetSceneEventListener(this._currentScene.asset);if(s!=null&&s.sceneClosing){const o=s.sceneClosing();o instanceof Promise&&await o}this._currentScene.unload()}this._currentScene=void 0;const r=this._currentIndex=((t=this.scenes)==null?void 0:t.indexOf(e))??-1;try{this._currentlyLoadingScene=e,this._currentLoadingProgress=new ProgressEvent("progress",{loaded:0,total:1});const s=new CustomEvent("loadscene-start",{detail:{scene:e,switcher:this,index:r}});this.dispatchEvent(s),await this.onStartLoading(),await e.loadAssetAsync((a,l)=>{this._currentLoadingProgress=l,this.dispatchEvent(l)}).catch(console.error),await this.onEndLoading();const o=new CustomEvent("loadscene-finished",{detail:{scene:e,switcher:this,index:r}});if(this.dispatchEvent(o),this._currentLoadingProgress=void 0,this._currentlyLoadingScene=void 0,o.defaultPrevented)return oo&&console.warn("Adding loaded scene prevented:",e,o),!1;if(!e.asset)return oo&&console.warn("Failed loading scene:",e),!1;if(this._currentIndex===r){if(oo&&console.log("ADD",e.uri),this._currentScene=e,re.add(e.asset,this.gameObject),this.useSceneLighting&&this.context.sceneLighting.enable(e),this.useHistory&&r>=0){let l=r.toString();if(this.useSceneName&&(l=uj(e.uri)),(n=this.queryParameterName)!=null&&n.length)Hy(this.queryParameterName,l,this.useHistory);else{const c=history.state,u=this.guid+"::"+r;c!==u&&history.pushState(u,"unused",location.href)}}const a=this.tryGetSceneEventListener(e.asset);if(a!=null&&a.sceneOpened){const l=a.sceneOpened(this);l instanceof Promise&&await l}return!0}}catch(s){console.error(s)}return!1}preload(e){if(e>=0&&e<this.scenes.length){const t=this.scenes[e];if(t instanceof ni)return t.preload()}return Oh}tryLoadFromQueryParam(){var e;if(!((e=this.queryParameterName)!=null&&e.length))return Oh;const t=ee(this.queryParameterName);return typeof t=="boolean"?Oh:this.trySelectSceneFromValue(t)}trySelectSceneFromValue(e){if(typeof e=="string"){const t=parseInt(e);if(t>=0&&t<this.scenes.length)return this.select(t);{const n=e.toLowerCase();for(let r=0;r<this.scenes.length;r++){const s=this.scenes[r];if(s&&uj(s.uri).toLowerCase().includes(n))return this.select(r)}}}else if(typeof e=="number"&&e>=0&&e<this.scenes.length)return this.select(e);return Bs()&&console.warn('Can not find scene: "'+e+'"',this),Oh}async onStartLoading(){var e,t;if(this._isCurrentlyLoading=!0,this.loadingScene&&(this._lastLoadingScene!==this.loadingScene&&(this._loadingScenePromise=void 0),this._lastLoadingScene=this.loadingScene,this._loadingScenePromise||(this._loadingScenePromise=(e=this.loadingScene)==null?void 0:e.loadAssetAsync()),await this._loadingScenePromise,this._isCurrentlyLoading&&(t=this.loadingScene)!=null&&t.asset)){oo&&console.log("Add loading scene",this.loadingScene.uri,this.loadingScene.asset);const n=this.loadingScene.asset;re.add(n,this.gameObject);const r=this.tryGetSceneEventListener(n);if(r!=null&&r.sceneOpened){const s=r.sceneOpened(this);s instanceof Promise&&await s}}}async onEndLoading(){var e;if(this._isCurrentlyLoading=!1,(e=this.loadingScene)!=null&&e.asset){oo&&console.log("Remove loading scene",this.loadingScene.uri);const t=this.loadingScene.asset,n=this.tryGetSceneEventListener(t);if(typeof n?.sceneClosing=="function"){const r=n.sceneClosing();r instanceof Promise&&await r}re.remove(t)}}tryGetSceneEventListener(e,t=0){const n=re.foreachComponent(e,r=>r.sceneClosing?r:void 0);if(t===0&&!n&&e.children.length)for(const r of e.children){const s=this.tryGetSceneEventListener(r,t+1);if(s)return s}return n||null}}so([x()],$r.prototype,"autoLoadFirstScene",2),so([x(ni)],$r.prototype,"scenes",2),so([x(ni)],$r.prototype,"loadingScene",2),so([x()],$r.prototype,"queryParameterName",2),so([x()],$r.prototype,"useSceneName",2),so([x()],$r.prototype,"clamp",2),so([x()],$r.prototype,"useHistory",2),so([x()],$r.prototype,"useKeyboard",2),so([x()],$r.prototype,"useSwipe",2),so([x()],$r.prototype,"useSceneLighting",2),so([x()],$r.prototype,"preloadNext",2),so([x()],$r.prototype,"preloadPrevious",2),so([x()],$r.prototype,"preloadConcurrent",2);function uj(i){const e=i.split("/").pop(),t=e?.split(".").shift();return t!=null&&t.length?t:i}class Hle{constructor(e,t=1,n=1,r=2){h(this,"maxLoadAhead"),h(this,"maxLoadBehind"),h(this,"maxConcurrent"),h(this,"_isRunning",!1),h(this,"_switcher"),h(this,"_loadTasks",[]),h(this,"_maxConcurrentLoads",1),this._switcher=e,this.maxLoadAhead=t,this.maxLoadBehind=n,this.maxConcurrent=r}begin(){if(this._isRunning)return;oo&&console.log("Preload begin"),this._isRunning=!0;let e=-1,t,n;const r=this._switcher.scenes,s=setInterval(()=>{if(this.allLoaded()&&(oo&&console.log("All scenes loaded"),this.stop()),!this._isRunning){clearInterval(s);return}if(this.canLoadNewScene()===!1)return;e!==this._switcher.currentIndex&&(e=this._switcher.currentIndex,n=0,t=0);const o=n%2===0;o&&(t+=1),n+=1;const a=o?this.maxLoadAhead:this.maxLoadBehind;if(t>a)return;const l=o?e+t:e-t;if(l<0||l<0||l>=r.length)return;const c=r[l];new Vle(l,c,this._loadTasks)},200)}stop(){this._isRunning=!1}canLoadNewScene(){return this._loadTasks.length<this._maxConcurrentLoads}allLoaded(){if(this._switcher.scenes){for(const e of this._switcher.scenes)if(e?.isLoaded()===!1)return!1}return!0}}class Vle{constructor(e,t,n){h(this,"index"),h(this,"asset"),h(this,"tasks"),this.index=e,this.asset=t,this.tasks=n,n.push(this),this.awaitLoading()}async awaitLoading(){this.asset&&!this.asset.isLoaded()&&(oo&&console.log("Preload start: "+this.asset.uri,this.index),await this.asset.preload(),oo&&console.log("Preload finished: "+this.asset.uri,this.index));const e=this.tasks.indexOf(this);e>=0&&this.tasks.splice(e,1)}}function Wle(){return new Promise((i,e)=>{const t=()=>{t!=null&&(document.removeEventListener("pointerdown",t),document.removeEventListener("click",t),document.removeEventListener("dragstart",t),document.removeEventListener("touchstart",t),i())};document.addEventListener("pointerdown",t),document.addEventListener("click",t),document.addEventListener("dragstart",t),document.addEventListener("touchstart",t)})}async function qle(i){await Wle(),i()}var Xle=Object.defineProperty,Yle=Object.getOwnPropertyDescriptor,ao=(i,e,t,n)=>{for(var r=n>1?void 0:n?Yle(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&Xle(e,t,r),r};const rr=ee("debugvideo");var dj=(i=>(i[i.None=0]="None",i[i.AdjustHeight=1]="AdjustHeight",i[i.AdjustWidth=2]="AdjustWidth",i))(dj||{}),pj=(i=>(i[i.VideoClip=0]="VideoClip",i[i.Url=1]="Url",i))(pj||{}),fj=(i=>(i[i.CameraFarPlane=0]="CameraFarPlane",i[i.CameraNearPlane=1]="CameraNearPlane",i[i.RenderTexture=2]="RenderTexture",i[i.MaterialOverride=3]="MaterialOverride",i))(fj||{});class qn extends Ie{constructor(){super(),h(this,"playOnAwake",!0),h(this,"aspectMode",0),h(this,"clip",null),h(this,"source",1),h(this,"url",null),h(this,"renderMode"),h(this,"targetMaterialProperty"),h(this,"targetMaterialRenderer"),h(this,"targetTexture"),h(this,"time",0),h(this,"_playbackSpeed",1),h(this,"_isLooping",!1),h(this,"_muted",!1),h(this,"_audioOutputMode",2),h(this,"playInBackground",!0),h(this,"_crossOrigin","anonymous"),h(this,"_videoElement",null),h(this,"_videoTexture",null),h(this,"_videoMaterial",null),h(this,"_isPlaying",!1),h(this,"wasPlaying",!1),h(this,"visibilityChanged",e=>{switch(document.visibilityState){case"hidden":this.playInBackground||(this.wasPlaying=this._isPlaying,this.pause());break;case"visible":this.wasPlaying&&!this._isPlaying&&this.play();break}}),h(this,"_receivedInput",!1),h(this,"_overlay",null),h(this,"_targetObjects"),h(this,"_updateAspectRoutineId",-1),h(this,"_hls"),h(this,"onHlsAvailable",()=>{var e;rr&&console.log("HLS: available",this.clip),!(!this.shouldUseM3U8||!this.url)&&(this._hls||(this._hls=new Hls),this.videoElement.autoplay=!0,this._hls.loadSource(this.url),this._hls.attachMedia(this.videoElement),(e=this._videoElement)==null||e.play(),rr&&console.log("HLS: loaded",this.clip))}),qle(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[],ee("videoscreenspace")&&window.addEventListener("keydown",e=>{e.key==="f"&&(this.screenspace=!this.screenspace)})}get playbackSpeed(){var e;return((e=this._videoElement)==null?void 0:e.playbackRate)??this._playbackSpeed}set playbackSpeed(e){this._playbackSpeed=e,this._videoElement&&(this._videoElement.playbackRate=e)}get isLooping(){var e;return((e=this._videoElement)==null?void 0:e.loop)??this._isLooping}set isLooping(e){this._isLooping=e,this._videoElement&&(this._videoElement.loop=e)}get currentTime(){var e;return((e=this._videoElement)==null?void 0:e.currentTime)??this.time}set currentTime(e){this._videoElement?this._videoElement.currentTime=e:this.time=e}get isPlaying(){const e=this._videoElement;return!!(e&&(e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>e.HAVE_CURRENT_DATA||e.srcObject&&e.srcObject.active))}get crossOrigin(){var e;return((e=this._videoElement)==null?void 0:e.crossOrigin)??this._crossOrigin}set crossOrigin(e){this._crossOrigin=e,this._videoElement&&(e!==null?this._videoElement.setAttribute("crossorigin",e):this._videoElement.removeAttribute("crossorigin"))}get videoMaterial(){return!this._videoMaterial&&!this.create(!1)?null:this._videoMaterial}get videoTexture(){return!this._videoTexture&&!this.create(!1)?null:this._videoTexture}get videoElement(){return!this._videoElement&&!this.create(!1)?null:this._videoElement}get muted(){var e;return((e=this._videoElement)==null?void 0:e.muted)??this._muted}set muted(e){this._muted=e,this._videoElement&&(this._videoElement.muted=e)}get currentVideo(){return this.clip}set audioOutputMode(e){e!==this._audioOutputMode&&(e===1&&pt()&&console.warn("VideoAudioOutputMode.AudioSource is not yet implemented"),this._audioOutputMode=e,this.updateVideoElementSettings())}get audioOutputMode(){return this._audioOutputMode}preloadVideo(){rr&&console.log("Video Preload: "+this.name,this.clip),this.create(!1)}preload(){this.preloadVideo()}setVideo(e){this.clip=e,this.source=0,this._videoElement?(this._videoElement.srcObject=e,this._isPlaying&&this.play(),this.updateAspect()):this.create(this.playOnAwake)}setClipURL(e){this.url!==e&&(this.url=e,this.source=1,rr&&console.log("set url",e),this._videoElement?e.endsWith(".m3u8")?this.ensureM3U8CanBePlayed():(this._videoElement.src=e,this._isPlaying&&(this.stop(),this.play())):this.create(this.playOnAwake))}onEnable(){var e,t;rr&&console.log("VideoPlayer.onEnable",pj[this.source],this.clip,this.url,this),window.addEventListener("visibilitychange",this.visibilityChanged),this.playOnAwake===!0?this.create(!0):this.preloadVideo(),this.screenspace?(e=this._overlay)==null||e.start():(t=this._overlay)==null||t.stop()}onDisable(){var e;window.removeEventListener("visibilitychange",this.visibilityChanged),(e=this._overlay)==null||e.stop(),this.pause()}onDestroy(){var e;this._videoElement&&((e=this.videoElement)==null||e.remove(),this._videoElement=null),this._videoTexture&&(this._videoTexture.dispose(),this._videoTexture=null)}play(){var e,t;if(this._videoElement||this.create(!1),!this._videoElement){rr&&console.warn("Can not play: no video element found",this);return}if(!(this._isPlaying&&!((e=this._videoElement)!=null&&e.ended)&&!((t=this._videoElement)!=null&&t.paused))){if(this._isPlaying=!0,this._receivedInput||(this._videoElement.muted=!0),this.handleBeginPlaying(!1),this.shouldUseM3U8){this.ensureM3U8CanBePlayed();return}rr&&console.log("Video Play()",this.clip,this._videoElement,this.time),this._videoElement.currentTime=this.time,this._videoElement.play().catch(n=>{var r;console.log(n),rr&&console.error("Error playing video",n,"CODE="+n.code,(r=this.videoElement)==null?void 0:r.src,this),setTimeout(()=>{this._isPlaying&&!this.destroyed&&this.activeAndEnabled&&this.play()},1e3)}),rr&&console.log("play",this._videoElement,this.time)}}stop(){this._isPlaying=!1,this.time=0,this._videoElement&&(this._videoElement.currentTime=0,this._videoElement.pause(),rr&&console.log("STOP",this))}pause(){var e,t;this.time=((e=this._videoElement)==null?void 0:e.currentTime)??0,this._isPlaying=!1,(t=this._videoElement)==null||t.pause(),rr&&console.log("PAUSE",this,this.currentTime)}create(e){let t;switch(this.source){case 0:t=this.clip;break;case 1:t=this.url,!(t!=null&&t.length)&&typeof this.clip=="string"&&(t=this.clip);break}return t?(this._videoElement||(rr&&console.warn("Create VideoElement",this),this._videoElement=this.createVideoElement(),this.context.domElement.shadowRoot.prepend(this._videoElement),this.updateVideoElementStyles()),typeof t=="string"?(rr&&console.log("Set Video src",t),this._videoElement.src=t):(rr&&console.log("Set Video srcObject",t),this._videoElement.srcObject=t),this._videoTexture||(this._videoTexture=new nD(this._videoElement)),this._videoTexture.flipY=!1,this._videoTexture.colorSpace=dt,e&&this.handleBeginPlaying(e),rr&&console.log("Video: handle playing done...",t,e),!0):(rr&&console.warn("No video source set",this),!1)}updateAspect(){this.aspectMode!==0&&this.startCoroutine(this.updateAspectImpl())}get screenspace(){var e;return((e=this._overlay)==null?void 0:e.enabled)??!1}set screenspace(e){var t;if(e){if(!this._videoTexture)return;this._overlay||(this._overlay=new Jle(this.context)),this._overlay.add(this._videoTexture)}else(t=this._overlay)==null||t.remove(this._videoTexture);this._overlay&&(this._overlay.enabled=e)}createVideoElement(){const e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),rr&&console.log("created video element",e),e}handleBeginPlaying(e){var t,n;if(!this.activeAndEnabled||!this._videoElement)return;this._targetObjects.length=0;let r=this.gameObject;switch(this.renderMode){case 3:r=(t=this.targetMaterialRenderer)==null?void 0:t.gameObject,r||(r=(n=re.getComponent(this.gameObject,Sn))==null?void 0:n.gameObject);break;case 2:console.error("VideoPlayer renderTexture not implemented yet. Please use material override instead");return}if(!r){console.error("Missing target for video material renderer",this.name,fj[this.renderMode],this);return}const s=r.material;if(s){this._targetObjects.push(r),s!==this._videoMaterial&&(this._videoMaterial=s.clone(),r.material=this._videoMaterial);const o="map",a=this._videoMaterial;if(!this.targetMaterialProperty)a[o]=this._videoTexture;else switch(this.targetMaterialProperty){default:a[o]=this._videoTexture;break}}else{console.warn("Can not play video, no material found, this might be a multimaterial case which is not supported yet");return}this.updateVideoElementSettings(),this.updateVideoElementStyles(),e&&(this.shouldUseM3U8&&this.ensureM3U8CanBePlayed(),this.play())}updateVideoElementSettings(){if(!this._videoElement)return;this._videoElement.loop=this._isLooping,this._videoElement.currentTime=this.currentTime,this._videoElement.playbackRate=this._playbackSpeed,this._videoElement.playsInline=!0;let e=!this._receivedInput||this.audioOutputMode===0;!e&&this._muted&&(e=!0),this._videoElement.muted=e,this.playOnAwake&&(this._videoElement.autoplay=!0)}updateVideoElementStyles(){this._videoElement&&(this._videoElement.style.userSelect="none",this._videoElement.style.visibility="hidden",this._videoElement.style.display="none",this.updateAspect())}*updateAspectImpl(){const e=++this._updateAspectRoutineId,t=void 0,n=this.clip;for(;e===this._updateAspectRoutineId&&this.aspectMode!==0&&this.clip&&n===this.clip&&this._isPlaying;){if(!n||typeof n=="string")return;let r;for(const s of n.getVideoTracks()){const o=s.getSettings();if(o&&o.width&&o.height){r=o.width/o.height;break}else r=this.context.renderer.domElement.clientWidth/this.context.renderer.domElement.clientHeight}if(r===void 0){for(let s=0;s<10;s++)yield;if(!this.isPlaying)break;continue}if(t===r){yield;continue}for(const s of this._targetObjects){let o=1;if(s.parent){const a=ki(s.parent);o=a.x/a.y}switch(this.aspectMode){case 1:s.scale.y=1/r*s.scale.x*o;break;case 2:s.scale.x=r*s.scale.y*o;break}}for(let s=0;s<3;s++)yield}}get shouldUseM3U8(){return this.url!=null&&this.url.endsWith(".m3u8")&&this.source===1}ensureM3U8CanBePlayed(){if(!this.shouldUseM3U8)return;let e=document.head.querySelector("script[data-hls_library]");e?globalThis.Hls?this.onHlsAvailable():e.addEventListener("load",this.onHlsAvailable):(rr&&console.log("HLS: load script"),e=document.createElement("script"),e.dataset.hls_library="hls.js",e.src="https://cdn.jsdelivr.net/npm/hls.js@1",e.addEventListener("load",this.onHlsAvailable),document.head.append(e))}}ao([x()],qn.prototype,"playOnAwake",2),ao([x()],qn.prototype,"aspectMode",2),ao([x(URL)],qn.prototype,"clip",2),ao([x()],qn.prototype,"source",2),ao([x(URL)],qn.prototype,"url",2),ao([x()],qn.prototype,"renderMode",2),ao([x()],qn.prototype,"targetMaterialProperty",2),ao([x(Sn)],qn.prototype,"targetMaterialRenderer",2),ao([x(gt)],qn.prototype,"targetTexture",2),ao([x()],qn.prototype,"time",2),ao([x()],qn.prototype,"playbackSpeed",1),ao([x()],qn.prototype,"isLooping",1),ao([x()],qn.prototype,"audioOutputMode",1);class Jle{constructor(e){h(this,"context"),h(this,"_videos",[]),h(this,"_screenspaceModeQuad"),h(this,"_isInScreenspaceMode",!1),h(this,"_input"),this.context=e,this._input=new Kle(this)}get enabled(){return this._isInScreenspaceMode}set enabled(e){e?this.start():this.stop()}add(e){this._videos.indexOf(e)===-1&&this._videos.push(e)}remove(e){if(!e)return;const t=this._videos.indexOf(e);t>=0&&this._videos.splice(t,1)}start(){var e;if(this._isInScreenspaceMode||this._videos.length<0)return;const t=this._videos[this._videos.length-1];if(!t)return;if(this._isInScreenspaceMode=!0,!this._screenspaceModeQuad){if(this._screenspaceModeQuad=Fg.createPrimitive(Uu.Quad,{material:new Zle(t)}),!this._screenspaceModeQuad)return;this._screenspaceModeQuad.geometry.scale(2,2,2)}const n=this._screenspaceModeQuad;this.context.scene.add(n),this.updateScreenspaceMaterialUniforms();const r=n.material;r?.reset(),(e=this._input)==null||e.enable(r)}stop(){var e;this._isInScreenspaceMode=!1,this._screenspaceModeQuad&&((e=this._input)==null||e.disable(),this._screenspaceModeQuad.removeFromParent())}updateScreenspaceMaterialUniforms(){var e;const t=(e=this._screenspaceModeQuad)==null?void 0:e.material;t&&(t.screenAspect=this.context.domElement.clientWidth/this.context.domElement.clientHeight)}}class Kle{constructor(e){h(this,"_onResizeScreenFn"),h(this,"_onKeyUpFn"),h(this,"_onMouseWheelFn"),h(this,"context"),h(this,"overlay"),h(this,"_material"),h(this,"_isPinching",!1),h(this,"_lastPinch",0),this.overlay=e,this.context=e.context}enable(e){this._material=e,window.addEventListener("resize",this._onResizeScreenFn=()=>{this.overlay.updateScreenspaceMaterialUniforms()}),window.addEventListener("keyup",this._onKeyUpFn=r=>{r.key==="Escape"&&this.overlay.stop()}),window.addEventListener("wheel",this._onMouseWheelFn=r=>{this.overlay.enabled&&(e.zoom+=r.deltaY*5e-4,r.preventDefault())},{passive:!1});const t=new $;window.addEventListener("mousemove",r=>{if(this.overlay.enabled&&this.context.input.getPointerPressed(0)){const s=new $(r.movementX,r.movementY);s.x/=this.context.domElement.clientWidth,s.y/=this.context.domElement.clientHeight,t.set(s.x,s.y),t.multiplyScalar(e.zoom/-this.context.time.deltaTime*.01),e.offset=e.offset.add(t)}}),window.addEventListener("pointermove",r=>{this.overlay.enabled&&this.context.input.getPointerPressed(0)&&this.context.input.getTouchesPressedCount()===1&&(t.set(r.movementX,r.movementY),t.multiplyScalar(e.zoom*-this.context.time.deltaTime*.05),e.offset=e.offset.add(t))});let n=0;window.addEventListener("touchstart",r=>{if(r.touches.length<2){this.context.time.time-n<.3&&this.overlay.stop(),n=this.context.time.time;return}this._isPinching=!0,this._lastPinch=0}),window.addEventListener("touchmove",r=>{if(!this._isPinching||!this._material)return;const s=r.touches[0],o=r.touches[1],a=s.clientX-o.clientX,l=s.clientY-o.clientY,c=Math.sqrt(a*a+l*l);if(this._lastPinch!==0){const u=c-this._lastPinch;this._material.zoom-=u*.004}this._lastPinch=c}),window.addEventListener("touchend",()=>{this._isPinching=!1})}disable(){this._onResizeScreenFn&&(window.removeEventListener("resize",this._onResizeScreenFn),this._onResizeScreenFn=void 0),this._onKeyUpFn&&(window.removeEventListener("keyup",this._onKeyUpFn),this._onKeyUpFn=void 0),this._onMouseWheelFn&&(window.removeEventListener("wheel",this._onMouseWheelFn),this._onMouseWheelFn=void 0)}}class Zle extends Tt{constructor(e){super(),h(this,"_offset",new $),this.uniforms={map:{value:e},screenAspect:{value:1},offsetScale:{value:new Ye(0,0,1,1)}},this.vertexShader=`
6925
+ }`);new S(0,0,1);var Gae=function(i){Ff(t,i);var e=Nf(t);function t(n){var r;return _t(this,t),r=e.call(this,n),Y($t(r),"positionBuffer",void 0),Y($t(r),"previousBuffer",void 0),Y($t(r),"nextBuffer",void 0),Y($t(r),"uvBuffer",void 0),Y($t(r),"sideBuffer",void 0),Y($t(r),"widthBuffer",void 0),Y($t(r),"colorBuffer",void 0),Y($t(r),"indexBuffer",void 0),Y($t(r),"vector_",new S),Y($t(r),"vector2_",new S),Y($t(r),"vector3_",new S),Y($t(r),"quaternion_",new Me),r.maxParticles=1e4,r.setupBuffers(),r.rebuildMaterial(),r}return xt(t,[{key:"setupBuffers",value:function(){this.geometry&&this.geometry.dispose(),this.geometry=new ut,this.indexBuffer=new $e(new Uint32Array(this.maxParticles*6),1),this.indexBuffer.setUsage(Ur),this.geometry.setIndex(this.indexBuffer),this.positionBuffer=new $e(new Float32Array(this.maxParticles*6),3),this.positionBuffer.setUsage(Ur),this.geometry.setAttribute("position",this.positionBuffer),this.previousBuffer=new $e(new Float32Array(this.maxParticles*6),3),this.previousBuffer.setUsage(Ur),this.geometry.setAttribute("previous",this.previousBuffer),this.nextBuffer=new $e(new Float32Array(this.maxParticles*6),3),this.nextBuffer.setUsage(Ur),this.geometry.setAttribute("next",this.nextBuffer),this.widthBuffer=new $e(new Float32Array(this.maxParticles*2),1),this.widthBuffer.setUsage(Ur),this.geometry.setAttribute("width",this.widthBuffer),this.sideBuffer=new $e(new Float32Array(this.maxParticles*2),1),this.sideBuffer.setUsage(Ur),this.geometry.setAttribute("side",this.sideBuffer),this.uvBuffer=new $e(new Float32Array(this.maxParticles*4),2),this.uvBuffer.setUsage(Ur),this.geometry.setAttribute("uv",this.uvBuffer),this.colorBuffer=new $e(new Float32Array(this.maxParticles*8),4),this.colorBuffer.setUsage(Ur),this.geometry.setAttribute("color",this.colorBuffer)}},{key:"expandBuffers",value:function(n){for(;n>=this.maxParticles;)this.maxParticles*=2;this.setupBuffers()}},{key:"rebuildMaterial",value:function(){this.layers.mask=this.settings.layers.mask;var n={lineWidth:{value:1},map:{value:null},useMap:{value:0},alphaMap:{value:null},useAlphaMap:{value:0},resolution:{value:new $(1,1)},sizeAttenuation:{value:1},visibility:{value:1},alphaTest:{value:0},repeat:{value:new $(1,1)}},r={};if(r.USE_UV="",r.USE_COLOR_ALPHA="",this.settings.material.map&&(r.USE_MAP="",r.MAP_UV=MR(this.settings.material.map.channel),n.map=new be(this.settings.material.map),n.mapTransform=new be(new Dt().copy(this.settings.material.map.matrix))),this.settings.renderMode===tt.Trail)this.material=new Tt({uniforms:n,defines:r,vertexShader:jae,fragmentShader:zae,transparent:this.settings.material.transparent,depthWrite:!this.settings.material.transparent,side:this.settings.material.side,blending:this.settings.material.blending||Vh});else throw new Error("render mode unavailable")}},{key:"update",value:function(){var n=this,r=0,s=0,o=0;this.systems.forEach(function(a){for(var l=0;l<a.particleNum;l++)o+=a.particles[l].previous.length*2}),o>this.maxParticles&&this.expandBuffers(o),this.systems.forEach(function(a){var l=n.quaternion_,c=n.vector2_,u=n.vector3_;a.emitter.matrixWorld.decompose(c,l,u);for(var d=a.particles,p=a.particleNum,f=n.settings.uTileCount,m=n.settings.vTileCount,A=1/f,v=1/m,g=0;g<p;g++){var y=d[g],b=y.uvTile%m,_=Math.floor(y.uvTile/m),E=y.previous.values(),I=E.next(),T=I.value,M=T;I.done||(I=E.next());var D=void 0;I.value!==void 0?D=I.value:D=M;for(var C=0;C<y.previous.length;C++,r+=2){if(n.positionBuffer.setXYZ(r,M.position.x,M.position.y,M.position.z),n.positionBuffer.setXYZ(r+1,M.position.x,M.position.y,M.position.z),a.worldSpace?(n.positionBuffer.setXYZ(r,M.position.x,M.position.y,M.position.z),n.positionBuffer.setXYZ(r+1,M.position.x,M.position.y,M.position.z)):(y.parentMatrix?n.vector_.copy(M.position).applyMatrix4(y.parentMatrix):n.vector_.copy(M.position).applyMatrix4(a.emitter.matrixWorld),n.positionBuffer.setXYZ(r,n.vector_.x,n.vector_.y,n.vector_.z),n.positionBuffer.setXYZ(r+1,n.vector_.x,n.vector_.y,n.vector_.z)),a.worldSpace?(n.previousBuffer.setXYZ(r,T.position.x,T.position.y,T.position.z),n.previousBuffer.setXYZ(r+1,T.position.x,T.position.y,T.position.z)):(y.parentMatrix?n.vector_.copy(T.position).applyMatrix4(y.parentMatrix):n.vector_.copy(T.position).applyMatrix4(a.emitter.matrixWorld),n.previousBuffer.setXYZ(r,n.vector_.x,n.vector_.y,n.vector_.z),n.previousBuffer.setXYZ(r+1,n.vector_.x,n.vector_.y,n.vector_.z)),a.worldSpace?(n.nextBuffer.setXYZ(r,D.position.x,D.position.y,D.position.z),n.nextBuffer.setXYZ(r+1,D.position.x,D.position.y,D.position.z)):(y.parentMatrix?n.vector_.copy(D.position).applyMatrix4(y.parentMatrix):n.vector_.copy(D.position).applyMatrix4(a.emitter.matrixWorld),n.nextBuffer.setXYZ(r,n.vector_.x,n.vector_.y,n.vector_.z),n.nextBuffer.setXYZ(r+1,n.vector_.x,n.vector_.y,n.vector_.z)),n.sideBuffer.setX(r,-1),n.sideBuffer.setX(r+1,1),a.worldSpace)n.widthBuffer.setX(r,M.size),n.widthBuffer.setX(r+1,M.size);else if(y.parentMatrix)n.widthBuffer.setX(r,M.size),n.widthBuffer.setX(r+1,M.size);else{var P=(Math.abs(u.x)+Math.abs(u.y)+Math.abs(u.z))/3;n.widthBuffer.setX(r,M.size*P),n.widthBuffer.setX(r+1,M.size*P)}n.uvBuffer.setXY(r,(C/y.previous.length+b)*A,(m-_-1)*v),n.uvBuffer.setXY(r+1,(C/y.previous.length+b)*A,(m-_)*v),n.colorBuffer.setXYZW(r,M.color.x,M.color.y,M.color.z,M.color.w),n.colorBuffer.setXYZW(r+1,M.color.x,M.color.y,M.color.z,M.color.w),C+1<y.previous.length&&(n.indexBuffer.setX(s*3,r),n.indexBuffer.setX(s*3+1,r+1),n.indexBuffer.setX(s*3+2,r+2),s++,n.indexBuffer.setX(s*3,r+2),n.indexBuffer.setX(s*3+1,r+1),n.indexBuffer.setX(s*3+2,r+3),s++),T=M,M=D,I.done||(I=E.next(),I.value!==void 0&&(D=I.value))}}}),this.positionBuffer.updateRange.count=r*3,this.positionBuffer.needsUpdate=!0,this.previousBuffer.updateRange.count=r*3,this.previousBuffer.needsUpdate=!0,this.nextBuffer.updateRange.count=r*3,this.nextBuffer.needsUpdate=!0,this.sideBuffer.updateRange.count=r,this.sideBuffer.needsUpdate=!0,this.widthBuffer.updateRange.count=r,this.widthBuffer.needsUpdate=!0,this.uvBuffer.updateRange.count=r*2,this.uvBuffer.needsUpdate=!0,this.colorBuffer.updateRange.count=r*4,this.colorBuffer.needsUpdate=!0,this.indexBuffer.updateRange.count=s*3,this.indexBuffer.needsUpdate=!0,this.geometry.setDrawRange(0,s*3)}},{key:"dispose",value:function(){this.geometry.dispose()}}]),t}(Kz),Qae=function(i){Ff(t,i);var e=Nf(t);function t(){var n;return _t(this,t),n=e.call(this),Y($t(n),"batches",[]),Y($t(n),"systemToBatchIndex",new Map),Y($t(n),"type","BatchedRenderer"),n}return xt(t,[{key:"addSystem",value:function(n){n._renderer=this;for(var r=n.getRendererSettings(),s=0;s<this.batches.length;s++)if(t.equals(this.batches[s].settings,r)){this.batches[s].addSystem(n),this.systemToBatchIndex.set(n,s);return}var o;switch(r.renderMode){case tt.Trail:o=new Gae(r);break;case tt.Mesh:case tt.BillBoard:case tt.VerticalBillBoard:case tt.HorizontalBillBoard:case tt.StretchedBillBoard:o=new Nae(r);break}o.addSystem(n),this.batches.push(o),this.systemToBatchIndex.set(n,this.batches.length-1),this.add(o)}},{key:"deleteSystem",value:function(n){var r=this.systemToBatchIndex.get(n);r!=null&&(this.batches[r].removeSystem(n),this.systemToBatchIndex.delete(n))}},{key:"updateSystem",value:function(n){this.deleteSystem(n),this.addSystem(n)}},{key:"update",value:function(n){this.systemToBatchIndex.forEach(function(s,o){o.update(n)});for(var r=0;r<this.batches.length;r++)this.batches[r].update()}}],[{key:"equals",value:function(n,r){return n.material.side===r.material.side&&n.material.blending===r.material.blending&&n.material.transparent===r.material.transparent&&n.material.type===r.material.type&&n.material.alphaTest===r.material.alphaTest&&n.material.map===r.material.map&&n.renderMode===r.renderMode&&n.uTileCount===r.uTileCount&&n.vTileCount===r.vTileCount&&n.instancingGeometry===r.instancingGeometry&&n.renderOrder===r.renderOrder&&n.layers.mask===r.layers.mask}}]),t}(ge),Hae=Qae,$z=function(){function i(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:new S;_t(this,i),Y(this,"locations",[]),this.scaleX=e,this.scaleY=t,this.position=n}return xt(i,[{key:"transform",value:function(e,t){e.x=this.locations[t%this.locations.length].x*this.scaleX+this.position.x,e.y=this.locations[t%this.locations.length].y*this.scaleY+this.position.y,e.z=this.position.z}},{key:"clone",value:function(){var e=new i(this.scaleX,this.scaleY,this.position.clone());return e.locations=this.locations.map(function(t){return t.clone()}),e}},{key:"toJSON",value:function(){return{scaleX:this.scaleX,scaleY:this.scaleY,position:this.position,locations:this.locations.map(function(e){return{x:e.x,y:e.y}})}}},{key:"fromImage",value:function(e,t){var n=document.createElement("canvas");n.width=e.width,n.height=e.height;var r=n.getContext("2d");if(r){r.drawImage(e,0,0);var s=r.getImageData(0,0,n.width,n.height,{colorSpace:"srgb"});n.remove(),this.locations.length=0;for(var o=0;o<s.height;o++)for(var a=0;a<s.width;a++)s.data[(o*s.width+a)*4+3]>t&&this.locations.push(new $(a,s.height-o))}}}],[{key:"fromJSON",value:function(e){var t=new i(e.scaleX,e.scaleY,new S(e.position[0],e.position[1],e.position[2]));return t.locations=e.locations.map(function(n){return new $(n.x,n.y)}),t}}]),i}();function Vae(i){switch(i.type){case"TextureSequencer":return $z.fromJSON(i);default:return new $z}}var Wae=function(){function i(e){_t(this,i),Y(this,"type","ApplySequences"),Y(this,"sequencers",[]),Y(this,"time",0),Y(this,"index",0),Y(this,"pCount",0),Y(this,"delay",void 0),Y(this,"tempV",new S),this.delay=e}return xt(i,[{key:"initialize",value:function(e){e.id=this.pCount,e.dst=new S,e.begin=new S,e.inMotion=!1,this.pCount++}},{key:"reset",value:function(){this.time=0,this.index=0,this.pCount=0}},{key:"update",value:function(e,t){var n=this.sequencers[this.index],r=e.id*this.delay;this.time>=n[0].a+r&&this.time<=n[0].b+r?(e.inMotion||(e.inMotion=!0,e.begin.copy(e.position),n[1].transform(e.dst,e.id)),e.position.lerpVectors(e.begin,e.dst,i.BEZIER.genValue((this.time-n[0].a-r)/(n[0].b-n[0].a)))):this.time>n[0].b+r&&(e.inMotion=!1)}},{key:"frameUpdate",value:function(e){for(;this.index+1<this.sequencers.length&&this.time>=this.sequencers[this.index+1][0].a;)this.index++;this.time+=e}},{key:"appendSequencer",value:function(e,t){this.sequencers.push([e,t])}},{key:"toJSON",value:function(){return{type:this.type,delay:this.delay,sequencers:this.sequencers.map(function(e){var t=zf(e,2),n=t[0],r=t[1];return{range:n.toJSON(),sequencer:r.toJSON()}})}}},{key:"clone",value:function(){var e=new i(this.delay);return e.sequencers=this.sequencers.map(function(t){return[t[0].clone(),t[1].clone()]}),e}}],[{key:"fromJSON",value:function(e){var t=new i(e.delay);return e.sequencers.forEach(function(n){t.sequencers.push([Pi(n.range),Vae(n.sequencer)])}),t}}]),i}();Y(Wae,"BEZIER",new yR(0,0,1,1));var he=function(i){return i[i.Number=0]="Number",i[i.Vec2=1]="Vec2",i[i.Vec3=2]="Vec3",i[i.Vec4=3]="Vec4",i[i.Boolean=4]="Boolean",i[i.AnyType=5]="AnyType",i}({}),ej=xt(function i(e,t,n,r){_t(this,i),Y(this,"input",void 0),Y(this,"inputIndex",void 0),Y(this,"output",void 0),Y(this,"outputIndex",void 0),this.input=e,this.inputIndex=t,this.input.outputs[t].push(this),this.output=n,this.outputIndex=r,this.output.inputs[r]=this}),qae=function(){function i(){_t(this,i),Y(this,"visited",new Set),Y(this,"graph_",void 0),Y(this,"context_",void 0),i.Instance=this}return xt(i,[{key:"traverse",value:function(e){if(this.context_===void 0)throw new Error("context is undefined");if(this.graph_===void 0)throw new Error("graph is undefined");this.visited.add(e.id);for(var t=[],n=0;n<e.inputs.length;n++)if(e.inputs[n]instanceof ej){var r=e.inputs[n].input;this.visited.has(r.id)||this.traverse(r),t.push(r.outputValues[e.inputs[n].inputIndex])}else t.push(e.inputs[n].getValue(this.context_));e.func(this.context_,t,e.outputValues),this.graph_.nodesInOrder.push(e)}},{key:"executeCompiledGraph",value:function(){if(this.context_===void 0)throw new Error("context is undefined");if(this.graph_===void 0)throw new Error("graph is undefined");for(var e=this.graph_.nodesInOrder,t=0;t<e.length;t++){for(var n=[],r=e[t],s=0;s<r.inputs.length;s++)if(r.inputs[s]instanceof ej)n.push(r.inputs[s].input.outputValues[r.inputs[s].inputIndex]);else if(r.inputs[s]!==void 0)n.push(r.inputs[s].getValue(this.context_));else throw new Error("miss input for node ".concat(r.id));r.func(this.context_,n,r.outputValues)}}},{key:"run",value:function(e,t){if(this.graph_=e,this.context_=t,e.compiled)this.executeCompiledGraph();else{e.nodesInOrder.length=0,this.visited.clear();for(var n=0;n<e.outputNodes.length;n++){var r=e.outputNodes[n];this.traverse(r)}e.compiled=!0}}}]),i}();Y(qae,"Instance",void 0);var ai=function(){function i(e){_t(this,i),Y(this,"name",void 0),Y(this,"nodeTypeSignatures",[]),this.name=e}return xt(i,[{key:"addSignature",value:function(e,t,n){this.nodeTypeSignatures.push({inputTypes:e,outputTypes:t,func:n})}}]),i}(),Qx=new ai("add");Qx.addSignature([he.Number,he.Number],[he.Number],function(i,e,t,n){n[0]=t[0]+t[1]}),Qx.addSignature([he.Vec2,he.Vec2],[he.Vec2],function(i,e,t,n){n[0].addVectors(t[0],t[1])}),Qx.addSignature([he.Vec3,he.Vec3],[he.Vec3],function(i,e,t,n){n[0].addVectors(t[0],t[1])}),Qx.addSignature([he.Vec4,he.Vec4],[he.Vec4],function(i,e,t,n){n[0].addVectors(t[0],t[1])});var Hx=new ai("sub");Hx.addSignature([he.Number,he.Number],[he.Number],function(i,e,t,n){n[0]=t[0]-t[1]}),Hx.addSignature([he.Vec2,he.Vec2],[he.Vec2],function(i,e,t,n){n[0].subVectors(t[0],t[1])}),Hx.addSignature([he.Vec3,he.Vec3],[he.Vec3],function(i,e,t,n){n[0].subVectors(t[0],t[1])}),Hx.addSignature([he.Vec4,he.Vec4],[he.Vec4],function(i,e,t,n){n[0].subVectors(t[0],t[1])});var Vx=new ai("mul");Vx.addSignature([he.Number,he.Number],[he.Number],function(i,e,t,n){n[0]=t[0]*t[1]}),Vx.addSignature([he.Vec2,he.Number],[he.Vec2],function(i,e,t,n){n[0].copy(t[0]).multiplyScalar(t[1])}),Vx.addSignature([he.Vec3,he.Number],[he.Vec3],function(i,e,t,n){n[0].copy(t[0]).multiplyScalar(t[1])}),Vx.addSignature([he.Vec4,he.Number],[he.Vec4],function(i,e,t,n){n[0].copy(t[0]).multiplyScalar(t[1])});var Wx=new ai("div");Wx.addSignature([he.Number,he.Number],[he.Number],function(i,e,t,n){n[0]=t[0]/t[1]}),Wx.addSignature([he.Vec2,he.Number],[he.Vec2],function(i,e,t,n){n[0].copy(t[0]).divideScalar(t[1])}),Wx.addSignature([he.Vec3,he.Number],[he.Vec3],function(i,e,t,n){n[0].copy(t[0]).divideScalar(t[1])}),Wx.addSignature([he.Vec4,he.Number],[he.Vec4],function(i,e,t,n){n[0].copy(t[0]).divideScalar(t[1])});var Xae=new ai("sin");Xae.addSignature([he.Number],[he.Number],function(i,e,t,n){n[0]=Math.sin(t[0])});var Yae=new ai("cos");Yae.addSignature([he.Number],[he.Number],function(i,e,t,n){n[0]=Math.cos(t[0])});var Jae=new ai("tan");Jae.addSignature([he.Number],[he.Number],function(i,e,t,n){n[0]=Math.tan(t[0])});var Kae=new ai("abs");Kae.addSignature([he.Number],[he.Number],function(i,e,t,n){n[0]=Math.abs(t[0])});var Zae=new ai("min");Zae.addSignature([he.Number,he.Number],[he.Number],function(i,e,t,n){n[0]=Math.min(t[0],t[1])});var $ae=new ai("max");$ae.addSignature([he.Number,he.Number],[he.Number],function(i,e,t,n){n[0]=Math.max(t[0],t[1])});var TR=new ai("dot");TR.addSignature([he.Vec2,he.Vec2],[he.Number],function(i,e,t,n){n[0]=t[0].dot(t[1])}),TR.addSignature([he.Vec3,he.Vec3],[he.Number],function(i,e,t,n){n[0]=t[0].dot(t[1])}),TR.addSignature([he.Vec4,he.Vec4],[he.Number],function(i,e,t,n){n[0]=t[0].dot(t[1])});var ele=new ai("cross");ele.addSignature([he.Vec3,he.Vec3],[he.Vec3],function(i,e,t,n){n[0].crossVectors(t[0],t[1])});var IR=new ai("length");IR.addSignature([he.Vec2],[he.Number],function(i,e,t,n){n[0]=t[0].length()}),IR.addSignature([he.Vec3],[he.Number],function(i,e,t,n){n[0]=t[0].length()}),IR.addSignature([he.Vec4],[he.Number],function(i,e,t,n){n[0]=t[0].length()});var RR=new ai("lengthSq");RR.addSignature([he.Vec2],[he.Number],function(i,e,t,n){n[0]=t[0].lengthSq()}),RR.addSignature([he.Vec3],[he.Number],function(i,e,t,n){n[0]=t[0].lengthSq()}),RR.addSignature([he.Vec4],[he.Number],function(i,e,t,n){n[0]=t[0].lengthSq()});var PR=new ai("normalize");PR.addSignature([he.Vec2],[he.Vec2],function(i,e,t,n){n[0].copy(t[0]).normalize()}),PR.addSignature([he.Vec3],[he.Vec3],function(i,e,t,n){n[0].copy(t[0]).normalize()}),PR.addSignature([he.Vec4],[he.Vec4],function(i,e,t,n){n[0].copy(t[0]).normalize()});var tj=new ai("distance");tj.addSignature([he.Vec2,he.Vec2],[he.Number],function(i,e,t,n){n[0]=t[0].distanceTo(t[1])}),tj.addSignature([he.Vec3,he.Vec3],[he.Number],function(i,e,t,n){n[0]=t[0].distanceTo(t[1])});var tle=new ai("and");tle.addSignature([he.Boolean,he.Boolean],[he.Boolean],function(i,e,t,n){n[0]=t[0]&&t[1]});var ile=new ai("or");ile.addSignature([he.Boolean,he.Boolean],[he.Boolean],function(i,e,t,n){n[0]=t[0]||t[1]});var nle=new ai("not");nle.addSignature([he.Boolean],[he.Boolean],function(i,e,t,n){n[0]=!t[0]});var qx=new ai("equal");qx.addSignature([he.Number,he.Number],[he.Boolean],function(i,e,t,n){n[0]=t[0]===t[1]}),qx.addSignature([he.Vec2,he.Vec2],[he.Boolean],function(i,e,t,n){n[0]=t[0].equals(t[1])}),qx.addSignature([he.Vec3,he.Vec3],[he.Boolean],function(i,e,t,n){n[0]=t[0].equals(t[1])}),qx.addSignature([he.Vec4,he.Vec4],[he.Boolean],function(i,e,t,n){n[0]=t[0].equals(t[1])});var rle=new ai("lessThan");rle.addSignature([he.Number,he.Number],[he.Boolean],function(i,e,t,n){n[0]=t[0]<t[1]});var sle=new ai("greaterThan");sle.addSignature([he.Number,he.Number],[he.Boolean],function(i,e,t,n){n[0]=t[0]>t[1]});var ole=new ai("lessThanOrEqual");ole.addSignature([he.Number,he.Number],[he.Boolean],function(i,e,t,n){n[0]=t[0]<=t[1]});var ale=new ai("greaterThanOrEqual");ale.addSignature([he.Number,he.Number],[he.Boolean],function(i,e,t,n){n[0]=t[0]>=t[1]});var lle=new ai("if");lle.addSignature([he.Boolean,he.AnyType,he.AnyType],[he.AnyType],function(i,e,t,n){n[0]=t[0]?t[1]:t[2]});var cle=new ai("number");cle.addSignature([],[he.Number],function(i,e,t,n){n[0]=e.value});var hle=new ai("vec2");hle.addSignature([],[he.Vec2],function(i,e,t,n){n[0]=e.value});var ule=new ai("vec3");ule.addSignature([],[he.Vec3],function(i,e,t,n){n[0]=e.value});var dle=new ai("vec4");dle.addSignature([],[he.Vec4],function(i,e,t,n){n[0]=e.value});var ple=new ai("bool");ple.addSignature([],[he.Boolean],function(i,e,t,n){n[0]=e.value});var fle=new ai("particlePosition");fle.addSignature([],[he.Vec3],function(i,e,t,n){n[0]=i.particle[e.property]});var mle=new ai("particleVelocity");mle.addSignature([],[he.Vec3],function(i,e,t,n){n[0]=i.particle[e.property]});var gle=new ai("particleRotation");gle.addSignature([],[he.Number],function(i,e,t,n){n[0]=i.particle[e.property]});var vle=new ai("particleAge");vle.addSignature([],[he.Number],function(i,e,t,n){n[0]=i.particle[e.property]});var w0=new ai("output");w0.addSignature([he.Number],[he.Number],function(i,e,t,n){n[0]=t[0]}),w0.addSignature([he.Vec2],[he.Vec2],function(i,e,t,n){n[0]=t[0]}),w0.addSignature([he.Vec3],[he.Vec3],function(i,e,t,n){n[0]=t[0]}),w0.addSignature([he.Vec4],[he.Vec4],function(i,e,t,n){n[0]=t[0]}),w0.addSignature([he.Boolean],[he.Boolean],function(i,e,t,n){n[0]=t[0]}),console.log("%c Particle system powered by three.quarks. https://quarks.art/","font-size: 16px; font-weight: bold;");var Ale=Object.defineProperty,yle=Object.getOwnPropertyDescriptor,an=(i,e,t,n)=>{for(var r=n>1?void 0:n?yle(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&Ale(e,t,r),r};const S0=ee("debugparticles"),ble=ee("noprogressive"),_le=ee("debugprogressive");var BR=(i=>(i[i.Birth=0]="Birth",i[i.Collision=1]="Collision",i[i.Death=2]="Death",i[i.Trigger=3]="Trigger",i[i.Manual=4]="Manual",i))(BR||{});class Qo extends Ie{constructor(){super(...arguments),h(this,"renderMode"),h(this,"particleMaterial"),h(this,"trailMaterial"),h(this,"particleMesh"),h(this,"maxParticleSize"),h(this,"minParticleSize"),h(this,"velocityScale"),h(this,"cameraVelocityScale"),h(this,"lengthScale")}start(){if(this.maxParticleSize!==.5&&this.minParticleSize!==0&&pt()){const e=`ParticleSystem "${this.name}" has non-default min/max particle size. This may not render correctly. Please set min size to 0 and the max size to 0.5 and use the "StartSize" setting instead`;console.warn(e)}}get transparent(){var e;return((e=this.particleMaterial)==null?void 0:e.transparent)??!1}getMaterial(e=!1){let t=e===!0&&this.trailMaterial?this.trailMaterial:this.particleMaterial;return t&&e&&t.side===lr&&(t=t.clone(),t.side=cn,e?this.trailMaterial=t:this.particleMaterial=t),t&&!ble&&t._didRequestTextureLOD===void 0&&(t._didRequestTextureLOD=0,_le&&console.log("Load material LOD",t.name),Ui.assignTextureLOD(this.context,this.sourceId,t)),t}getMesh(e){let t=null;if(!t&&(this.particleMesh instanceof ue&&(t=this.particleMesh.geometry),t===null)){t=new Un(1,1);const n=t.attributes.uv;for(let r=0;r<n.count;r++)n.setX(r,1-n.getX(r))}return new ue(t,this.getMaterial())}}an([x()],Qo.prototype,"renderMode",2),an([x(It)],Qo.prototype,"particleMaterial",2),an([x(It)],Qo.prototype,"trailMaterial",2),an([x()],Qo.prototype,"maxParticleSize",2),an([x()],Qo.prototype,"minParticleSize",2),an([x()],Qo.prototype,"velocityScale",2),an([x()],Qo.prototype,"cameraVelocityScale",2),an([x()],Qo.prototype,"lengthScale",2);class Xx{constructor(e,t=1){h(this,"_curve"),h(this,"_factor"),h(this,"type","function"),this._curve=e,this._factor=t}genValue(e){return this._curve.evaluate(e,Math.random())*this._factor}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}}class DR{constructor(e){h(this,"type","value"),h(this,"system"),this.system=e}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}}class xle extends DR{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class wle extends DR{constructor(){super(...arguments),h(this,"_lastPosition",new S),h(this,"_lastDistance",0)}update(){const e=Rt(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(e),this._lastPosition.copy(e)}genValue(){if(!this.system.isPlaying||!this.system.emission.enabled||this.system.currentParticles>=this.system.maxParticles)return 0;let e=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){const r=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let s=this._lastDistance/this.system.deltaTime*r;Number.isFinite(s)||(s=0),e+=s}const t=this.system.emission.getBurst();t>0&&(e+=t/this.system.deltaTime);const n=this.system.maxParticles-this.system.currentParticles;return Ze.clamp(e,0,n/this.system.deltaTime)}}class Sle extends DR{genValue(){return this.system.isPlaying,0}}class Dh{constructor(e){h(this,"system"),h(this,"type"),this.type=Object.getPrototypeOf(this).constructor.name||"ParticleSystemBaseBehaviour",e&&(this.system=e)}get context(){return this.system.context}initialize(e){}update(e,t){}frameUpdate(e){}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}reset(){}}class Cle extends Dh{constructor(){super(...arguments),h(this,"type","NeedleTextureSheet")}update(e,t){const n=this.system.textureSheetAnimation;if(n.enabled){const r=e.age/e.life,s=n.evaluate(r);s!==void 0&&(e.uvTile=s)}}}const ij=Symbol("particleRotation");class Ele extends Dh{constructor(){super(...arguments),h(this,"type","NeedleRotation")}initialize(e){e[ij]=Math.random()}update(e,t){if(e.rotation===void 0)return;const n=e.age/e.life;if(typeof e.rotation=="number"&&(this.system.rotationOverLifetime.enabled?e.rotation+=this.system.rotationOverLifetime.evaluate(n,e[ij])*t:this.system.renderer.renderMode===uc.Billboard&&(e.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const r=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(n,r)*t}}}const nj=Symbol("sizeLerpFactor"),Mle=new S;class Tle extends Dh{constructor(){super(...arguments),h(this,"type","NeedleSize"),h(this,"_minSize",0),h(this,"_maxSize",1)}initialize(e){e[nj]=Math.random(),this._minSize=this.system.renderer.minParticleSize,this._maxSize=this.system.renderer.maxParticleSize}update(e,t){const n=e.age/e.life;let r=1;this.system.sizeOverLifetime.enabled&&(r*=this.system.sizeOverLifetime.evaluate(n,void 0,e[nj]).x);let s=1;if(this.system.renderer.renderMode!==uc.Mesh&&(s=this.system.worldScale.x/this.system.cameraScale),e.size=e.startSize*r*s,this.system.localspace){const o=lj(this.system,Mle);e.size*=o.x}}}const jf=Symbol("particleLife"),OR=Symbol("trailLifetime"),rj=Symbol("trailStartLength"),kR=Symbol("trailWidthRandom");class Ile extends Dh{constructor(){super(...arguments),h(this,"type","NeedleTrail")}initialize(e){e instanceof A0&&(e[jf]=e.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(e[OR]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),e.life+=e[OR]),e[rj]=e.length,e[kR]=Math.random())}update(e){var t;if((t=this.system.trails)!=null&&t.enabled&&e instanceof A0){const n=e,r=e.age/e[jf],s=e.previous.values(),o=e.previous.length;for(let a=0;a<o;a++){const l=s.next().value,c=1-a/(o-1);let u=e.size;u<=0&&!this.system.trails.sizeAffectsWidth&&(u=20*this.system.trails.widthOverTrail.evaluate(.5,n[kR])),l.size=this.system.trails.getWidth(u,r,c,n[kR]),l.color.copy(e.color),this.system.trails.getColor(l.color,r,c)}if(e.age>e[jf]){e.velocity.set(0,0,0);const a=(e.age-e[jf])/e[OR];n.length=Ze.lerp(e[rj],0,a)}}}}const Yx=Symbol("startVelocity"),sj=Symbol("gravityModifier"),LR=Symbol("gravitySpeed"),Jx=Symbol("velocity lerp factor"),UR=new S;class Rle extends Dh{constructor(){super(...arguments),h(this,"type","NeedleVelocity"),h(this,"_gravityDirection",new S)}initialize(e){var t,n;const r=this.system.main.simulationSpeed;e.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random()),e.velocity.copy(this.system.shape.getDirection(e,e.position)).multiplyScalar(e.startSpeed),(t=this.system.inheritVelocity)!=null&&t.enabled&&this.system.inheritVelocity.applyInitial(e.velocity),e[Yx]?e[Yx].copy(e.velocity):e[Yx]=e.velocity.clone();const s=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());e[sj]=s*r,e[LR]=s*r*.5,e[Jx]=Math.random(),(n=this.system.velocityOverLifetime)==null||n.init(e),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===e0.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(e,t){var n;const r=e[Yx],s=e[sj];if(s!==0){const p=s*e[LR];UR.copy(this._gravityDirection).multiplyScalar(p),e[LR]+=t*.05,r.add(UR)}e.velocity.copy(r);const o=e.age/e.life;(n=this.system.inheritVelocity)!=null&&n.enabled&&this.system.inheritVelocity.applyCurrent(e.velocity,o,e[Jx]);const a=this.system.noise;a.enabled&&a.apply(0,e.position,e.velocity,t,e.age,e.life);const l=this.system.sizeBySpeed;l!=null&&l.enabled&&(e.size=l.evaluate(e.velocity,o,e[Jx],e.size));const c=this.system.colorBySpeed;c!=null&&c.enabled&&c.evaluate(e.velocity,e[Jx],e.color);const u=this.system.velocityOverLifetime;u.enabled&&u.apply(e,0,e.position,e.velocity,t,e.age,e.life);const d=this.system.limitVelocityOverLifetime;d.enabled&&d.apply(e.position,r,e.velocity,e.size,o,t,1),this.system.worldspace&&e.velocity.multiply(this.system.worldScale)}}const oj=Symbol("colorLerpFactor"),aj=new yi(1,1,1,1),Sd=new yi(1,1,1,1);class Ple extends Dh{constructor(){super(...arguments),h(this,"type","NeedleColor")}initialize(e){}_init(e){const t=this.system.renderer.particleMaterial;Sd.copy(this.system.main.startColor.evaluate(Math.random())),t!=null&&t.color&&(aj.copy(t.color),Sd.multiply(aj)),Sd.convertLinearToSRGB(),e.startColor.set(Sd.r,Sd.g,Sd.b,Sd.alpha),e.color.copy(e.startColor),e[oj]=Math.random()}update(e,t){if(e.age===0&&this._init(e),this.system.colorOverLifetime.enabled){const n=e.age/e.life,r=this.system.colorOverLifetime.color.evaluate(n,e[oj]);e.color.set(r.r,r.g,r.b,r.alpha).multiply(e.startColor)}else e.color.copy(e.startColor)}}class Ble{constructor(e){h(this,"system"),h(this,"emission"),h(this,"autoDestroy"),h(this,"startLength"),h(this,"emissionBursts"),h(this,"onlyUsedByOther"),h(this,"behaviors",[]),h(this,"rendererEmitterSettings",{startLength:new Zr(220),followLocalOrigin:!1}),h(this,"flatWhiteTexture"),h(this,"clonedTexture",{original:void 0,clone:void 0}),this.system=e,this.emission=new wle(this.system)}get anim(){return this.system.textureSheetAnimation}get prewarm(){return!1}get material(){return this.system.renderer.getMaterial(this.system.trails.enabled)}get layers(){return this.system.gameObject.layers}update(){this.emission.update()}get looping(){return this.system.main.loop}get duration(){return this.system.duration}get shape(){return this.system.shape}get startLife(){return new Xx(this.system.main.startLifetime)}get startSpeed(){return new Xx(this.system.main.startSpeed)}get startRotation(){return new Xx(this.system.main.startRotation)}get startSize(){return new Xx(this.system.main.startSize)}get startColor(){return new Gx(new Ye(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new Sle(this.system)}get instancingGeometry(){return this.system.renderer.getMesh(this.system.renderer.renderMode).geometry}get renderMode(){if(this.system.trails.enabled===!0)return tt.Trail;switch(this.system.renderer.renderMode){case uc.Billboard:return tt.BillBoard;case uc.Stretch:return tt.StretchedBillBoard;case uc.HorizontalBillboard:return tt.HorizontalBillBoard;case uc.VerticalBillboard:return tt.VerticalBillBoard;case uc.Mesh:return tt.Mesh}return tt.BillBoard}get speedFactor(){var e;let t=this.system.main.simulationSpeed;return((e=this.system.renderer)==null?void 0:e.renderMode)===uc.Stretch&&(t*=this.system.renderer.velocityScale??1),t}get texture(){const e=this.material;if(e&&e.map){const t=e.map;if(this.clonedTexture.original!==t||!this.clonedTexture.clone){const n=t.clone();n.premultiplyAlpha=!1,n.colorSpace=pi,this.clonedTexture.original=t,this.clonedTexture.clone=n}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=YU(new yi(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new xle(this.system)}get uTileCount(){var e;return this.anim.enabled?(e=this.anim)==null?void 0:e.numTilesX:void 0}get vTileCount(){var e;return this.anim.enabled?(e=this.anim)==null?void 0:e.numTilesY:void 0}get renderOrder(){return 1}get blending(){var e;return((e=this.system.renderer.particleMaterial)==null?void 0:e.blending)??Sc}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===e0.World}}class Dle{constructor(){h(this,"burstIndex",0),h(this,"burstWaveIndex",0),h(this,"time",0),h(this,"waitEmiting",0)}}const Kx=class extends Ie{constructor(){super(...arguments),h(this,"_state"),h(this,"colorOverLifetime"),h(this,"main"),h(this,"emission"),h(this,"sizeOverLifetime"),h(this,"shape"),h(this,"noise"),h(this,"trails"),h(this,"velocityOverLifetime"),h(this,"limitVelocityOverLifetime"),h(this,"inheritVelocity"),h(this,"colorBySpeed"),h(this,"textureSheetAnimation"),h(this,"rotationOverLifetime"),h(this,"rotationBySpeed"),h(this,"sizeBySpeed"),h(this,"_cameraScale",1),h(this,"__worldQuaternion",new Me),h(this,"_worldQuaternionInverted",new Me),h(this,"_worldScale",new S),h(this,"_worldPositionFrame",-1),h(this,"_worldPos",new S),h(this,"_renderer"),h(this,"_batchSystem"),h(this,"_particleSystem"),h(this,"_interface"),h(this,"_container"),h(this,"_time",0),h(this,"_isPlaying",!0),h(this,"_isUsedAsSubsystem",!1),h(this,"_didPreWarm",!1),h(this,"_bursts"),h(this,"_subEmitterSystems"),h(this,"_lastBatchesCount",-1),h(this,"lastMaterialVersion",-1)}play(i=!1){var e;i&&re.foreachComponent(this.gameObject,t=>{t instanceof Kx&&t!==this&&t.play(!1)},!0),this._isPlaying=!0,this._particleSystem&&(this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1),(e=this.emission)==null||e.reset()}pause(i=!0){i&&re.foreachComponent(this.gameObject,e=>{e instanceof Kx&&e!==this&&e.pause(!1)},!0),this._isPlaying=!1}stop(i=!0,e=!1){i&&re.foreachComponent(this.gameObject,t=>{t instanceof Kx&&t!==this&&t.stop(!1,e)},!0),this._isPlaying=!1,this._time=0,e&&this.reset()}reset(){var i;this._time=0,this._particleSystem&&(this._particleSystem.particleNum=0,this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1,(i=this.emission)==null||i.reset())}emit(i){if(this._particleSystem){this.onUpdate(),i=Math.min(i,this.maxParticles-this.currentParticles),this._state||(this._state=new Dle),this._state.waitEmiting=i,this._state.time=0;const e=this._particleSystem.emitEnded;this._particleSystem.emitEnded=!1,this._particleSystem.emit(this.deltaTime,this._state,this._particleSystem.emitter.matrixWorld),this._particleSystem.emitEnded=e}}get playOnAwake(){return this.main.playOnAwake}set playOnAwake(i){this.main.playOnAwake=i}get renderer(){return this._renderer}get isPlaying(){return this._isPlaying}get currentParticles(){var i;return((i=this._particleSystem)==null?void 0:i.particleNum)??0}get maxParticles(){return this.main.maxParticles}get time(){return this._time}get duration(){return this.main.duration}get deltaTime(){return this.context.time.deltaTime*this.main.simulationSpeed}get scale(){return this.gameObject.scale.x}get cameraScale(){return this._cameraScale}get container(){return this._container}get worldspace(){return this.main.simulationSpace===e0.World}get localspace(){return this.main.simulationSpace===e0.Local}get worldQuaternion(){return this.__worldQuaternion}get worldQuaternionInverted(){return this._worldQuaternionInverted}get worldScale(){return this._worldScale}get worldPos(){return this._worldPositionFrame!==this.context.time.frame&&(this._worldPositionFrame=this.context.time.frame,Rt(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}addBehaviour(i){return this._particleSystem?(i instanceof Dh&&(i.system=this),pt()&&console.log("add behaviour",i),this._particleSystem.addBehavior(i),!0):!1}removeAllBehaviours(){return this._particleSystem?(this._particleSystem.behaviors.length=0,!0):!1}get behaviours(){return this._particleSystem?this._particleSystem.behaviors:null}get particleSystem(){return this._particleSystem??null}set bursts(i){for(let e=0;e<i.length;e++){const t=i[e];if(!(t instanceof t0)){const n=new t0;Bp(n,t),i[e]=n}}this._bursts=i}set subEmitterSystems(i){for(let e=0;e<i.length;e++){const t=i[e];if(!(t instanceof C0)){const n=new C0;Bp(n,t),i[e]=n}}S0&&i.length>0&&console.log("SubEmitters: ",i,this),this._subEmitterSystems=i}onAfterDeserialize(i){if(this._subEmitterSystems&&Array.isArray(this._subEmitterSystems))for(const e of this._subEmitterSystems)e._deserialize(this.context,this.gameObject)}awake(){if(this._worldPositionFrame=-1,this._renderer=this.gameObject.getComponent(Qo),!this.main)throw new Error("Not Supported: ParticleSystem needs a serialized MainModule. Creating new particle systems at runtime is currently not supported.");this._container=new ge,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new Hae,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new Ble(this),this._particleSystem=new Dae(this._interface),this._particleSystem.addBehavior(new Tle(this)),this._particleSystem.addBehavior(new Ple(this)),this._particleSystem.addBehavior(new Cle(this)),this._particleSystem.addBehavior(new Ele(this)),this._particleSystem.addBehavior(new Rle(this)),this._particleSystem.addBehavior(new Ile(this)),this._batchSystem.addSystem(this._particleSystem);const i=this._particleSystem.emitter;this.context.scene.add(i),this.inheritVelocity.system&&this.inheritVelocity.system!==this&&(this.inheritVelocity=this.inheritVelocity.clone()),this.inheritVelocity.awake(this),S0&&(console.log(this),this.gameObject.add(new yo(1)))}start(){this.addSubParticleSystems(),this.updateLayers()}onDestroy(){var i,e,t,n;(i=this._container)==null||i.removeFromParent(),(e=this._batchSystem)==null||e.removeFromParent(),(t=this._particleSystem)==null||t.emitter.removeFromParent(),(n=this._particleSystem)==null||n.dispose()}onEnable(){this.main&&(this.inheritVelocity&&(this.inheritVelocity.system=this),this._batchSystem&&(this._batchSystem.visible=!0),this.playOnAwake&&this.play(),this._isPlaying=this.playOnAwake)}onDisable(){this._batchSystem&&(this._batchSystem.visible=!1)}onBeforeRender(){var i;this.main&&(this._didPreWarm===!1&&((i=this.main)==null?void 0:i.prewarm)===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){var i;if(!((i=this.emission)!=null&&i.enabled)||this.emission.rateOverTime.getMax()<=0)return;const e=1/60,t=this.main.duration,n=this.main.startLifetime.getMax(),r=1e3,s=Math.min(Math.max(t,n)/Math.max(.01,this.main.simulationSpeed),r),o=Math.ceil(s/e),a=Date.now();S0&&console.log(`Particles ${this.name} - Prewarm for ${o} frames (${s} sec). Duration: ${t}, Lifetime: ${n}`);for(let l=0;l<o&&!(this.currentParticles>=this.maxParticles);l++){const c=Date.now()-a;if(c>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${c}`);break}this.onUpdate(),this.onSimulate(e)}}onSimulate(i){if(this._batchSystem){let e=this.context.time.frameCount%60===0;this._lastBatchesCount!==this._batchSystem.batches.length&&(this._lastBatchesCount=this._batchSystem.batches.length,e=!0),e&&this.updateLayers(),this._batchSystem.update(i)}this._time+=i,this._time>this.duration&&(this._time=0)}updateLayers(){if(this._batchSystem)for(let i=0;i<this._batchSystem.batches.length;i++){const e=this._batchSystem.batches[i];e.layers.disableAll();const t=this.layer;e.layers.mask=1<<t}}onUpdate(){var i,e;const t=this.renderer.getMaterial(this.trails.enabled);if(t&&t.version!=this.lastMaterialVersion&&this._particleSystem&&(this.lastMaterialVersion=t.version,this._particleSystem.texture=this._interface.texture),this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const n=this.context.mainCamera;if(n){const o=ki(n);this._cameraScale=o.x}const r=!this.worldspace,s=this.gameObject;if(xi(s,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),ki(this.gameObject,this._worldScale),r&&this._container&&(i=this.gameObject)!=null&&i.parent){const o=lj(this,UR);this._container.matrix.makeScale(o.x,o.y,o.z),this._container.matrix.makeRotationFromQuaternion(this.__worldQuaternion),this._container.matrix.setPosition(this.worldPos),this._container.matrix.scale(this.gameObject.scale)}this.emission.system=this,this._interface.update(),this.shape.update(this,this.context,this.main.simulationSpace,this.gameObject),this.noise.update(this.context),(e=this.inheritVelocity)==null||e.update(this.context),this.velocityOverLifetime.update(this)}addSubParticleSystems(){var i;if(this._subEmitterSystems&&this._particleSystem)for(const e of this._subEmitterSystems){e.particleSystem&&(e.particleSystem.__internalAwake?e.particleSystem.__internalAwake():pt()&&console.warn("SubParticleSystem serialization issue(?)",e.particleSystem,e));const t=(i=e.particleSystem)==null?void 0:i._particleSystem;if(t){e.particleSystem._isUsedAsSubsystem=!0;const n=new Zx(this,this._particleSystem,e.particleSystem,t);n.emitterType=e.type,n.emitterProbability=e.emitProbability,this._particleSystem.addBehavior(n)}else S0&&console.warn("Could not add SubParticleSystem",e,this)}}};let kn=Kx;an([x(i0)],kn.prototype,"colorOverLifetime",2),an([x(Ir)],kn.prototype,"main",2),an([x(el)],kn.prototype,"emission",2),an([x(Eh)],kn.prototype,"sizeOverLifetime",2),an([x(sn)],kn.prototype,"shape",2),an([x(_i)],kn.prototype,"noise",2),an([x(Xi)],kn.prototype,"trails",2),an([x(on)],kn.prototype,"velocityOverLifetime",2),an([x(Dn)],kn.prototype,"limitVelocityOverLifetime",2),an([x(Mh)],kn.prototype,"inheritVelocity",2),an([x(dd)],kn.prototype,"colorBySpeed",2),an([x(Rr)],kn.prototype,"textureSheetAnimation",2),an([x(jo)],kn.prototype,"rotationOverLifetime",2),an([x(io)],kn.prototype,"rotationBySpeed",2),an([x(_s)],kn.prototype,"sizeBySpeed",2);class C0{constructor(){h(this,"particleSystem"),h(this,"emitProbability",1),h(this,"properties"),h(this,"type")}_deserialize(e,t){const n=this.particleSystem;if(n instanceof kn)return;let r="";n&&typeof n.guid=="string"&&(r=n.guid,this.particleSystem=re.findByGuid(r,t)),S0&&!(this.particleSystem instanceof kn)&&console.warn("Could not find particle system for sub emitter",r,t,this)}}function lj(i,e){if(e.set(1,1,1),i.gameObject.parent&&i.localspace)switch(i.main.scalingMode){case FI.Local:e=ki(i.gameObject.parent,e),e.x=1/e.x,e.y=1/e.y,e.z=1/e.z;break;default:if(!i.unsupported_scaling_mode){i.unsupported_scaling_mode=!0;const t="ParticleSystem scale mode "+FI[i.main.scalingMode]+" is not supported";pt()&&Qi(t),console.warn(t,i.name,i)}e=ki(i.gameObject,e);break}return e}new S(1,1,1),new S(0,0,1);class Zx{constructor(e,t,n,r){h(this,"type","NeedleParticleSubEmitter"),h(this,"emitterType"),h(this,"emitterProbability"),h(this,"q_",new Me),h(this,"v_",new S),h(this,"v2_",new S),h(this,"_emitterMatrix",new Ce),h(this,"_circularBuffer"),this.system=e,this.particleSystem=t,this.subSystem=n,this.subParticleSystem=r,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const s=1e3;this._circularBuffer=new bo(()=>new Ce,s)}clone(){throw new Error("Method not implemented.")}initialize(e){e.emissionState={burstIndex:0,burstWaveIndex:0,time:0,waitEmiting:0},this._emitterMatrix.copy(this.subSystem.matrixWorld).invert().premultiply(this.system.matrixWorld),this._emitterMatrix.setPosition(0,0,0),this.emitterType===BR.Birth&&this.run(e)}update(e,t){this.run(e)}frameUpdate(e){}toJSON(){}reset(){}run(e){if(this.subSystem.currentParticles>=this.subSystem.main.maxParticles||!this.subParticleSystem||!e.emissionState||this.emitterProbability&&Math.random()>this.emitterProbability)return;const t=this.system.deltaTime;if(this.emitterType===BR.Death){let r=e.life;if(e[jf]!==void 0&&(r=e[jf]),!(e.age+t*1.2>=r))return;const s=this.subSystem.main.maxParticles-this.subSystem.currentParticles;e.emissionState.waitEmiting=s}const n=new Ce;n.set(1,0,0,e.position.x,0,1,0,e.position.y,0,0,1,e.position.z,0,0,0,1),this.particleSystem.worldSpace||n.multiplyMatrices(this._emitterMatrix,n),this.subParticleSystem.emit(t,e.emissionState,n)}}var Ole=Object.defineProperty,kle=Object.getOwnPropertyDescriptor,Lle=(i,e,t,n)=>{for(var r=n>1?void 0:n?kle(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&Ole(e,t,r),r};class E0 extends Yr{constructor(){super(...arguments),h(this,"granularity")}get typeName(){return"PixelationEffect"}onCreateEffect(){const e=new CL;return this.granularity.onValueChanged=t=>{e.granularity=t},e}}Lle([x(Bt)],E0.prototype,"granularity",2),Fo("PixelationEffect",E0);class nm extends Ie{constructor(){super(...arguments),h(this,"_didAssignPlayerColor",!1),h(this,"tryAssignColor",()=>{const e=re.getComponentInParent(this.gameObject,No);if(e&&e.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(e.owner),!0;const t=re.getComponentInParent(this.gameObject,Er);return t!=null&&t.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(t.connectionId),!0):!1})}onEnable(){this.context.connection.beginListen(Jt.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(Jt.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield TU(.2),!this.tryAssignColor()););}assignUserColor(e){const t=nm.hashCode(e),n=nm.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){const r=this.gameObject;this.assignColor(n,e,r)}else if(this.gameObject.children)for(const r of this.gameObject.children){const s=r;s.material&&s.material.color&&this.assignColor(n,e,s)}}assignColor(e,t,n){let r=n.material;r&&(r._playerMaterial!==t&&(r=r.clone(),r._playerMaterial=t,n.material=r),r.color=e)}static hashCode(e){var t=0,n,r;if(e.length===0)return t;for(n=0;n<e.length;n++)r=e.charCodeAt(n),t=(t<<5)-t+r,t|=0;return t}static colorFromHashCode(e){const t=(e&16711680)>>16,n=(e&65280)>>8,r=e&255;return new Se(t/255,n/255,r/255)}}async function FR(i){const{NeedleEngineHTMLElement:e}=await Promise.resolve().then(()=>Yhe);e.observedAttributes.includes(i)||e.observedAttributes.push(i)}var Ule=Object.defineProperty,Fle=Object.getOwnPropertyDescriptor,$x=(i,e,t,n)=>{for(var r=n>1?void 0:n?Fle(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&Ule(e,t,r),r};const sl=ee("debugskybox");FR("skybox-image"),FR("environment-image");function cj(i,e,t,n,r){const s=new pc;s.allowDrop=!1,s.allowNetworking=!1,s.background=t,s.environment=n,re.addComponent(i.scene,s);const o=a=>{typeof a=="string"&&(sl&&console.log(r,"CHANGED TO",a),s.setSkybox(a))};return AO(i.domElement,r,o),s.addEventListener("destroy",()=>{sl&&console.log("Destroyed attribute remote skybox",r),yO(i.domElement,r,o)}),s.setSkybox(e)}ii.addContextCreatedCallback(i=>{var e;const t=i.context,n=t.domElement.getAttribute("skybox-image"),r=t.domElement.getAttribute("environment-image"),s=new Array;if(n){sl&&console.log("Creating remote skybox to load "+n),((e=t.mainCameraComponent)==null?void 0:e.clearFlags)!==Ju.Skybox&&console.warn('"skybox-image" attribute has no effect: camera clearflags are not set to "Skybox"');const o=cj(t,n,!0,!1,"skybox-image");s.push(o)}if(r){sl&&console.log("Creating remote environment to load "+r);const o=cj(t,r,!1,!0,"environment-image");s.push(o)}return s.length>0?Jm(s):Promise.resolve()});function hj(){return globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES||(globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES=new Array),globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES}function Nle(i){const e=hj().find(t=>t.src===i);return e?(sl&&console.log("Skybox: Found previously loaded texture for "+i),e.texture):null}async function zle(i){const e=await i;EE(e,!0),Ii(e)}function jle(i,e){const t=hj();for(;t.length>5;){const n=t.shift();n&&zle(n.texture)}e.then(n=>EE(n,!1)),t.push({src:i,texture:e})}class pc extends Ie{constructor(){super(...arguments),h(this,"url"),h(this,"allowDrop",!0),h(this,"background",!0),h(this,"environment",!0),h(this,"allowNetworking",!0),h(this,"_loader"),h(this,"_prevUrl"),h(this,"_prevLoadedEnvironment"),h(this,"_prevEnvironment",null),h(this,"_prevBackground",null),h(this,"dragOverEvent"),h(this,"dropEvent")}onEnable(){this.setSkybox(this.url),this.registerDropEvents()}onDisable(){var e;this.context.scene.environment===this._prevLoadedEnvironment&&(this.context.scene.environment=this._prevEnvironment,Ri.backgroundShouldBeTransparent(this.context)||(this.context.scene.background=this._prevBackground),this._prevLoadedEnvironment=void 0),this.unregisterDropEvents(),(e=this.context.mainCameraComponent)==null||e.applyClearFlags()}urlChangedSyncField(){this.allowNetworking&&this.setSkybox(this.url)}async setSkybox(e){var t;if(!this.activeAndEnabled||!e)return!1;if(!(e!=null&&e.endsWith(".hdr"))&&!e.endsWith(".exr")&&!e.endsWith(".jpg")&&!e.endsWith(".png")&&!e.endsWith(".jpeg")&&console.warn("Potentially invalid skybox url",this.url,"on",this.name),sl&&console.log("Remote skybox url?: "+e),this._prevUrl===e&&this._prevLoadedEnvironment)return this.applySkybox(),!0;(t=this._prevLoadedEnvironment)==null||t.dispose(),this._prevLoadedEnvironment=void 0,this._prevUrl=e;const n=await this.loadTexture(e);if(!n||!this.enabled)return!1;this.url=e;const r=e.lastIndexOf("/");return n.name=e.substring(r>=0?r+1:0),this._loader instanceof Ba&&(n.colorSpace=dt),this._prevLoadedEnvironment=n,this.applySkybox(),!0}async loadTexture(e){var t,n,r,s,o;if(!e)return Promise.resolve(null);const a=Nle(e);if(a){const d=await a;if(((n=(t=d.source)==null?void 0:t.data)==null?void 0:n.length)>0||(o=(s=(r=d.source)==null?void 0:r.data)==null?void 0:s.data)!=null&&o.length)return d}const l=e.endsWith(".exr"),c=e.endsWith(".hdr");l?this._loader instanceof o_||(this._loader=new o_):c?this._loader instanceof HM||(this._loader=new HM):this._loader instanceof Ba||(this._loader=new Ba),sl&&console.log("Loading skybox: "+e);const u=this._loader.loadAsync(e);return jle(e,u),await u}applySkybox(){var e;const t=this._prevLoadedEnvironment;t&&(t.mapping=Nd,t.needsUpdate=!0,this.context.scene.background!==t&&(this._prevBackground=this.context.scene.background),this.context.scene.environment!==t&&(this._prevEnvironment=this.context.scene.environment),sl&&console.log("Set remote skybox",this.url),this.environment&&(this.context.scene.environment=t),this.background&&!Ri.backgroundShouldBeTransparent(this.context)&&(this.context.scene.background=t),((e=this.context.mainCameraComponent)==null?void 0:e.backgroundBlurriness)!==void 0&&(this.context.scene.backgroundBlurriness=this.context.mainCameraComponent.backgroundBlurriness))}registerDropEvents(){this.dragOverEvent||(this.dragOverEvent=e=>{if(this.allowDrop&&e.dataTransfer)for(const t of e.dataTransfer.types)t==="text/uri-list"&&e.preventDefault()},this.dropEvent=e=>{var t,n,r,s;if(this.allowDrop&&(e.preventDefault(),!!e.dataTransfer)){for(const o of e.dataTransfer.types)if(o==="text/uri-list"){const a=e.dataTransfer.getData(o);sl&&console.log(o,a);let l=(n=(t=new RegExp(/polyhaven.com\/asset_img\/.+?\/(?<name>.+)\.png/).exec(a))==null?void 0:t.groups)==null?void 0:n.name;if(l||(l=(s=(r=new RegExp(/polyhaven\.com\/a\/(?<name>.+)/).exec(a))==null?void 0:r.groups)==null?void 0:s.name),sl&&console.log(l),l){const c="https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/"+l+"_1k.exr";this.setSkybox(c)}else console.warn("Could not resolve skybox name from dropped url",a)}}},this.context.domElement.addEventListener("dragover",this.dragOverEvent),this.context.domElement.addEventListener("drop",this.dropEvent))}unregisterDropEvents(){this.dragOverEvent&&(this.context.domElement.removeEventListener("dragover",this.dragOverEvent),this.context.domElement.removeEventListener("drop",this.dropEvent))}}$x([eI(pc.prototype.urlChangedSyncField),x(URL)],pc.prototype,"url",2),$x([x()],pc.prototype,"allowDrop",2),$x([x()],pc.prototype,"background",2),$x([x()],pc.prototype,"environment",2);var Gle=Object.defineProperty,Qle=Object.getOwnPropertyDescriptor,so=(i,e,t,n)=>{for(var r=n>1?void 0:n?Qle(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&Gle(e,t,r),r};const oo=ee("debugsceneswitcher"),ew="scene";FR(ew);const Oh=Promise.resolve(!1);class $r extends Ie{constructor(){super(...arguments),h(this,"autoLoadFirstScene",!0),h(this,"scenes"),h(this,"loadingScene"),h(this,"queryParameterName","scene"),h(this,"useSceneName",!0),h(this,"clamp",!0),h(this,"useHistory",!0),h(this,"useKeyboard",!0),h(this,"useSwipe",!0),h(this,"useSceneLighting",!0),h(this,"preloadNext",1),h(this,"preloadPrevious",1),h(this,"preloadConcurrent",2),h(this,"_currentIndex",-1),h(this,"_currentScene"),h(this,"_engineElementOverserver"),h(this,"_preloadScheduler"),h(this,"onPopState",async e=>{if(!this.useHistory)return;const t=this.useHistory;try{this.useHistory=!1;let n=!1;if(this.queryParameterName&&(n=await this.tryLoadFromQueryParam()),!n){const r=e?.state;if(r&&r.startsWith(this.guid)){const s=r.substr(this.guid.length+2);oo&&console.log("PopState",s),await this.trySelectSceneFromValue(s)}}}finally{this.useHistory=t}}),h(this,"normalizedSwipeThresholdX",.1),h(this,"_didSwipe",!1),h(this,"onInputPointerMove",e=>{if(this.useSwipe&&!this._didSwipe&&e.button===0&&e.pointerType==="touch"&&this.context.input.getPointerPressedCount()===1){const t=this.context.input.getPointerPositionDelta(e.button);if(t){const n=t.x/this.context.domWidth;n>=this.normalizedSwipeThresholdX?(this._didSwipe=!0,this.selectPrev()):n<=-this.normalizedSwipeThresholdX&&(this._didSwipe=!0,this.selectNext())}}}),h(this,"onInputPointerUp",e=>{e.button===0&&(this._didSwipe=!1)}),h(this,"onInputKeyDown",e=>{if(!this.useKeyboard||!this.scenes)return;const t=e.key.toLowerCase();if(!t)return;const n=parseInt(t)-1;if(n>=0){this.trySelectSceneFromValue(n);return}switch(t){case"arrowright":case"d":this.selectNext();break;case"arrowleft":case"a":this.selectPrev();break}}),h(this,"__lastSwitchScene"),h(this,"__lastSwitchScenePromise"),h(this,"_currentlyLoadingScene"),h(this,"_lastLoadingScene"),h(this,"_loadingScenePromise"),h(this,"_isCurrentlyLoading",!1),h(this,"_currentLoadingProgress")}get currentIndex(){return this._currentIndex}get currentLoadingProgress(){return this._currentLoadingProgress}get currentlyLoadingScene(){return this._currentlyLoadingScene}get currentlyLoadedScene(){return this._currentScene}awake(){oo&&console.log("SceneSwitcher",this)}async onEnable(){if(globalThis.addEventListener("popstate",this.onPopState),this.context.input.addEventListener(Wi.KeyDown,this.onInputKeyDown),this.context.input.addEventListener(Wi.PointerMove,this.onInputPointerMove),this.context.input.addEventListener(Wi.PointerUp,this.onInputPointerUp),this._engineElementOverserver||(this._engineElementOverserver=new MutationObserver(e=>{for(const t of e)if(t.type==="attributes"&&t.attributeName===ew){const n=this.context.domElement.getAttribute(ew);n!==null&&this.trySelectSceneFromValue(n)}})),this._engineElementOverserver.observe(this.context.domElement,{attributes:!0}),this._preloadScheduler||(this._preloadScheduler=new Hle(this)),this._preloadScheduler.maxLoadAhead=this.preloadNext,this._preloadScheduler.maxLoadBehind=this.preloadPrevious,this._preloadScheduler.maxConcurrent=this.preloadConcurrent,this._preloadScheduler.begin(),this.autoLoadFirstScene&&this._currentIndex===-1&&!await this.tryLoadFromQueryParam()){const e=this.context.domElement.getAttribute(ew);try{(e===null||!await this.trySelectSceneFromValue(e))&&this._currentIndex===-1&&this.select(0)}finally{}}}onDisable(){var e;globalThis.removeEventListener("popstate",this.onPopState),this.context.input.removeEventListener(Wi.KeyDown,this.onInputKeyDown),this.context.input.removeEventListener(Wi.PointerMove,this.onInputPointerMove),this.context.input.removeEventListener(Wi.PointerUp,this.onInputPointerUp),(e=this._preloadScheduler)==null||e.stop()}selectNext(){return this.select(this._currentIndex+1)}selectPrev(){return this.select(this._currentIndex-1)}select(e){var t,n,r;if(oo&&console.log("select",e),typeof e=="object"&&console.warn('Switching to "'+e+'" might not work. Please either use an index or a AssetReference (not a scene reference)'),typeof e=="string"){const o=(t=this.scenes)==null?void 0:t.find(a=>a.uri===e);if(!o){const a=ni.getOrCreate(this.sourceId??"",e,this.context);return this.switchScene(a)}if(o)e=(n=this.scenes)==null?void 0:n.indexOf(o);else return Oh}if(!((r=this.scenes)!=null&&r.length))return Oh;if(e<0){if(this.clamp)return Oh;e=this.scenes.length-1}else if(e>=this.scenes.length){if(this.clamp)return Oh;e=0}const s=this.scenes[e];return this.switchScene(s)}async switchScene(e){if(!(e instanceof ni)){const t=typeof e;return t==="string"?this.select(e):t==="number"?this.select(e):(console.warn("SceneSwitcher: Can't switch to scene",e,"of type",t),!1)}return e.uri===this.sourceId?(console.warn("SceneSwitcher: can't load own scene - prevent recursive loading",this.sourceId),!1):this.__lastSwitchScene===e&&this.__lastSwitchScenePromise?this.__lastSwitchScenePromise:(this.__lastSwitchScene=e,this.__lastSwitchScenePromise=this.__internalSwitchScene(e),await this.__lastSwitchScenePromise)}async __internalSwitchScene(e){var t,n;if(this._currentScene){oo&&console.log("UNLOAD",e.uri);const s=this.tryGetSceneEventListener(this._currentScene.asset);if(s!=null&&s.sceneClosing){const o=s.sceneClosing();o instanceof Promise&&await o}this._currentScene.unload()}this._currentScene=void 0;const r=this._currentIndex=((t=this.scenes)==null?void 0:t.indexOf(e))??-1;try{this._currentlyLoadingScene=e,this._currentLoadingProgress=new ProgressEvent("progress",{loaded:0,total:1});const s=new CustomEvent("loadscene-start",{detail:{scene:e,switcher:this,index:r}});this.dispatchEvent(s),await this.onStartLoading(),await e.loadAssetAsync((a,l)=>{this._currentLoadingProgress=l,this.dispatchEvent(l)}).catch(console.error),await this.onEndLoading();const o=new CustomEvent("loadscene-finished",{detail:{scene:e,switcher:this,index:r}});if(this.dispatchEvent(o),this._currentLoadingProgress=void 0,this._currentlyLoadingScene=void 0,o.defaultPrevented)return oo&&console.warn("Adding loaded scene prevented:",e,o),!1;if(!e.asset)return oo&&console.warn("Failed loading scene:",e),!1;if(this._currentIndex===r){if(oo&&console.log("ADD",e.uri),this._currentScene=e,re.add(e.asset,this.gameObject),this.useSceneLighting&&this.context.sceneLighting.enable(e),this.useHistory&&r>=0){let l=r.toString();if(this.useSceneName&&(l=uj(e.uri)),(n=this.queryParameterName)!=null&&n.length)Hy(this.queryParameterName,l,this.useHistory);else{const c=history.state,u=this.guid+"::"+r;c!==u&&history.pushState(u,"unused",location.href)}}const a=this.tryGetSceneEventListener(e.asset);if(a!=null&&a.sceneOpened){const l=a.sceneOpened(this);l instanceof Promise&&await l}return!0}}catch(s){console.error(s)}return!1}preload(e){if(e>=0&&e<this.scenes.length){const t=this.scenes[e];if(t instanceof ni)return t.preload()}return Oh}tryLoadFromQueryParam(){var e;if(!((e=this.queryParameterName)!=null&&e.length))return Oh;const t=ee(this.queryParameterName);return typeof t=="boolean"?Oh:this.trySelectSceneFromValue(t)}trySelectSceneFromValue(e){if(typeof e=="string"){const t=parseInt(e);if(t>=0&&t<this.scenes.length)return this.select(t);{const n=e.toLowerCase();for(let r=0;r<this.scenes.length;r++){const s=this.scenes[r];if(s&&uj(s.uri).toLowerCase().includes(n))return this.select(r)}}}else if(typeof e=="number"&&e>=0&&e<this.scenes.length)return this.select(e);return Bs()&&console.warn('Can not find scene: "'+e+'"',this),Oh}async onStartLoading(){var e,t;if(this._isCurrentlyLoading=!0,this.loadingScene&&(this._lastLoadingScene!==this.loadingScene&&(this._loadingScenePromise=void 0),this._lastLoadingScene=this.loadingScene,this._loadingScenePromise||(this._loadingScenePromise=(e=this.loadingScene)==null?void 0:e.loadAssetAsync()),await this._loadingScenePromise,this._isCurrentlyLoading&&(t=this.loadingScene)!=null&&t.asset)){oo&&console.log("Add loading scene",this.loadingScene.uri,this.loadingScene.asset);const n=this.loadingScene.asset;re.add(n,this.gameObject);const r=this.tryGetSceneEventListener(n);if(r!=null&&r.sceneOpened){const s=r.sceneOpened(this);s instanceof Promise&&await s}}}async onEndLoading(){var e;if(this._isCurrentlyLoading=!1,(e=this.loadingScene)!=null&&e.asset){oo&&console.log("Remove loading scene",this.loadingScene.uri);const t=this.loadingScene.asset,n=this.tryGetSceneEventListener(t);if(typeof n?.sceneClosing=="function"){const r=n.sceneClosing();r instanceof Promise&&await r}re.remove(t)}}tryGetSceneEventListener(e,t=0){const n=re.foreachComponent(e,r=>r.sceneClosing?r:void 0);if(t===0&&!n&&e.children.length)for(const r of e.children){const s=this.tryGetSceneEventListener(r,t+1);if(s)return s}return n||null}}so([x()],$r.prototype,"autoLoadFirstScene",2),so([x(ni)],$r.prototype,"scenes",2),so([x(ni)],$r.prototype,"loadingScene",2),so([x()],$r.prototype,"queryParameterName",2),so([x()],$r.prototype,"useSceneName",2),so([x()],$r.prototype,"clamp",2),so([x()],$r.prototype,"useHistory",2),so([x()],$r.prototype,"useKeyboard",2),so([x()],$r.prototype,"useSwipe",2),so([x()],$r.prototype,"useSceneLighting",2),so([x()],$r.prototype,"preloadNext",2),so([x()],$r.prototype,"preloadPrevious",2),so([x()],$r.prototype,"preloadConcurrent",2);function uj(i){const e=i.split("/").pop(),t=e?.split(".").shift();return t!=null&&t.length?t:i}class Hle{constructor(e,t=1,n=1,r=2){h(this,"maxLoadAhead"),h(this,"maxLoadBehind"),h(this,"maxConcurrent"),h(this,"_isRunning",!1),h(this,"_switcher"),h(this,"_loadTasks",[]),h(this,"_maxConcurrentLoads",1),this._switcher=e,this.maxLoadAhead=t,this.maxLoadBehind=n,this.maxConcurrent=r}begin(){if(this._isRunning)return;oo&&console.log("Preload begin"),this._isRunning=!0;let e=-1,t,n;const r=this._switcher.scenes,s=setInterval(()=>{if(this.allLoaded()&&(oo&&console.log("All scenes loaded"),this.stop()),!this._isRunning){clearInterval(s);return}if(this.canLoadNewScene()===!1)return;e!==this._switcher.currentIndex&&(e=this._switcher.currentIndex,n=0,t=0);const o=n%2===0;o&&(t+=1),n+=1;const a=o?this.maxLoadAhead:this.maxLoadBehind;if(t>a)return;const l=o?e+t:e-t;if(l<0||l<0||l>=r.length)return;const c=r[l];new Vle(l,c,this._loadTasks)},200)}stop(){this._isRunning=!1}canLoadNewScene(){return this._loadTasks.length<this._maxConcurrentLoads}allLoaded(){if(this._switcher.scenes){for(const e of this._switcher.scenes)if(e?.isLoaded()===!1)return!1}return!0}}class Vle{constructor(e,t,n){h(this,"index"),h(this,"asset"),h(this,"tasks"),this.index=e,this.asset=t,this.tasks=n,n.push(this),this.awaitLoading()}async awaitLoading(){this.asset&&!this.asset.isLoaded()&&(oo&&console.log("Preload start: "+this.asset.uri,this.index),await this.asset.preload(),oo&&console.log("Preload finished: "+this.asset.uri,this.index));const e=this.tasks.indexOf(this);e>=0&&this.tasks.splice(e,1)}}function Wle(){return new Promise((i,e)=>{const t=()=>{t!=null&&(document.removeEventListener("pointerdown",t),document.removeEventListener("click",t),document.removeEventListener("dragstart",t),document.removeEventListener("touchstart",t),i())};document.addEventListener("pointerdown",t),document.addEventListener("click",t),document.addEventListener("dragstart",t),document.addEventListener("touchstart",t)})}async function qle(i){await Wle(),i()}var Xle=Object.defineProperty,Yle=Object.getOwnPropertyDescriptor,ao=(i,e,t,n)=>{for(var r=n>1?void 0:n?Yle(e,t):e,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(n?o(e,t,r):o(r))||r);return n&&r&&Xle(e,t,r),r};const rr=ee("debugvideo");var dj=(i=>(i[i.None=0]="None",i[i.AdjustHeight=1]="AdjustHeight",i[i.AdjustWidth=2]="AdjustWidth",i))(dj||{}),pj=(i=>(i[i.VideoClip=0]="VideoClip",i[i.Url=1]="Url",i))(pj||{}),fj=(i=>(i[i.CameraFarPlane=0]="CameraFarPlane",i[i.CameraNearPlane=1]="CameraNearPlane",i[i.RenderTexture=2]="RenderTexture",i[i.MaterialOverride=3]="MaterialOverride",i))(fj||{});class qn extends Ie{constructor(){super(),h(this,"playOnAwake",!0),h(this,"aspectMode",0),h(this,"clip",null),h(this,"source",1),h(this,"url",null),h(this,"renderMode"),h(this,"targetMaterialProperty"),h(this,"targetMaterialRenderer"),h(this,"targetTexture"),h(this,"time",0),h(this,"_playbackSpeed",1),h(this,"_isLooping",!1),h(this,"_muted",!1),h(this,"_audioOutputMode",2),h(this,"playInBackground",!0),h(this,"_crossOrigin","anonymous"),h(this,"_videoElement",null),h(this,"_videoTexture",null),h(this,"_videoMaterial",null),h(this,"_isPlaying",!1),h(this,"wasPlaying",!1),h(this,"visibilityChanged",e=>{switch(document.visibilityState){case"hidden":this.playInBackground||(this.wasPlaying=this._isPlaying,this.pause());break;case"visible":this.wasPlaying&&!this._isPlaying&&this.play();break}}),h(this,"_receivedInput",!1),h(this,"_overlay",null),h(this,"_targetObjects"),h(this,"_updateAspectRoutineId",-1),h(this,"_hls"),h(this,"onHlsAvailable",()=>{var e;rr&&console.log("HLS: available",this.clip),!(!this.shouldUseM3U8||!this.url)&&(this._hls||(this._hls=new Hls),this.videoElement.autoplay=!0,this._hls.loadSource(this.url),this._hls.attachMedia(this.videoElement),(e=this._videoElement)==null||e.play(),rr&&console.log("HLS: loaded",this.clip))}),qle(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[],ee("videoscreenspace")&&window.addEventListener("keydown",e=>{e.key==="f"&&(this.screenspace=!this.screenspace)})}get playbackSpeed(){var e;return((e=this._videoElement)==null?void 0:e.playbackRate)??this._playbackSpeed}set playbackSpeed(e){this._playbackSpeed=e,this._videoElement&&(this._videoElement.playbackRate=e)}get isLooping(){var e;return((e=this._videoElement)==null?void 0:e.loop)??this._isLooping}set isLooping(e){this._isLooping=e,this._videoElement&&(this._videoElement.loop=e)}get currentTime(){var e;return((e=this._videoElement)==null?void 0:e.currentTime)??this.time}set currentTime(e){this._videoElement?this._videoElement.currentTime=e:this.time=e}get isPlaying(){const e=this._videoElement;return!!(e&&(e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>e.HAVE_CURRENT_DATA||e.srcObject&&e.srcObject.active))}get crossOrigin(){var e;return((e=this._videoElement)==null?void 0:e.crossOrigin)??this._crossOrigin}set crossOrigin(e){this._crossOrigin=e,this._videoElement&&(e!==null?this._videoElement.setAttribute("crossorigin",e):this._videoElement.removeAttribute("crossorigin"))}get videoMaterial(){return!this._videoMaterial&&!this.create(!1)?null:this._videoMaterial}get videoTexture(){return!this._videoTexture&&!this.create(!1)?null:this._videoTexture}get videoElement(){return!this._videoElement&&!this.create(!1)?null:this._videoElement}get muted(){var e;return((e=this._videoElement)==null?void 0:e.muted)??this._muted}set muted(e){this._muted=e,this._videoElement&&(this._videoElement.muted=e)}get currentVideo(){return this.clip}set audioOutputMode(e){e!==this._audioOutputMode&&(e===1&&pt()&&console.warn("VideoAudioOutputMode.AudioSource is not yet implemented"),this._audioOutputMode=e,this.updateVideoElementSettings())}get audioOutputMode(){return this._audioOutputMode}preloadVideo(){rr&&console.log("Video Preload: "+this.name,this.clip),this.create(!1)}preload(){this.preloadVideo()}setVideo(e){this.clip=e,this.source=0,this._videoElement?(this._videoElement.srcObject=e,this._isPlaying&&this.play(),this.updateAspect()):this.create(this.playOnAwake)}setClipURL(e){this.url!==e&&(this.url=e,this.source=1,rr&&console.log("set url",e),this._videoElement?e.endsWith(".m3u8")?this.ensureM3U8CanBePlayed():(this._videoElement.src=e,this._isPlaying&&(this.stop(),this.play())):this.create(this.playOnAwake))}onEnable(){var e,t;rr&&console.log("VideoPlayer.onEnable",pj[this.source],this.clip,this.url,this),window.addEventListener("visibilitychange",this.visibilityChanged),this.playOnAwake===!0?this.create(!0):this.preloadVideo(),this.screenspace?(e=this._overlay)==null||e.start():(t=this._overlay)==null||t.stop()}onDisable(){var e;window.removeEventListener("visibilitychange",this.visibilityChanged),(e=this._overlay)==null||e.stop(),this.pause()}onDestroy(){var e;this._videoElement&&((e=this.videoElement)==null||e.remove(),this._videoElement=null),this._videoTexture&&(this._videoTexture.dispose(),this._videoTexture=null)}play(){var e,t;if(this._videoElement||this.create(!1),!this._videoElement){rr&&console.warn("Can not play: no video element found",this);return}if(!(this._isPlaying&&!((e=this._videoElement)!=null&&e.ended)&&!((t=this._videoElement)!=null&&t.paused))){if(this._isPlaying=!0,this._receivedInput||(this._videoElement.muted=!0),this.handleBeginPlaying(!1),this.shouldUseM3U8){this.ensureM3U8CanBePlayed();return}rr&&console.log("Video Play()",this.clip,this._videoElement,this.time),this._videoElement.currentTime=this.time,this._videoElement.play().catch(n=>{var r;console.log(n),rr&&console.error("Error playing video",n,"CODE="+n.code,(r=this.videoElement)==null?void 0:r.src,this),setTimeout(()=>{this._isPlaying&&!this.destroyed&&this.activeAndEnabled&&this.play()},1e3)}),rr&&console.log("play",this._videoElement,this.time)}}stop(){this._isPlaying=!1,this.time=0,this._videoElement&&(this._videoElement.currentTime=0,this._videoElement.pause(),rr&&console.log("STOP",this))}pause(){var e,t;this.time=((e=this._videoElement)==null?void 0:e.currentTime)??0,this._isPlaying=!1,(t=this._videoElement)==null||t.pause(),rr&&console.log("PAUSE",this,this.currentTime)}create(e){let t;switch(this.source){case 0:t=this.clip;break;case 1:t=this.url,!(t!=null&&t.length)&&typeof this.clip=="string"&&(t=this.clip);break}return t?(this._videoElement||(rr&&console.warn("Create VideoElement",this),this._videoElement=this.createVideoElement(),this.context.domElement.shadowRoot.prepend(this._videoElement),this.updateVideoElementStyles()),typeof t=="string"?(rr&&console.log("Set Video src",t),this._videoElement.src=t):(rr&&console.log("Set Video srcObject",t),this._videoElement.srcObject=t),this._videoTexture||(this._videoTexture=new nD(this._videoElement)),this._videoTexture.flipY=!1,this._videoTexture.colorSpace=dt,e&&this.handleBeginPlaying(e),rr&&console.log("Video: handle playing done...",t,e),!0):(rr&&console.warn("No video source set",this),!1)}updateAspect(){this.aspectMode!==0&&this.startCoroutine(this.updateAspectImpl())}get screenspace(){var e;return((e=this._overlay)==null?void 0:e.enabled)??!1}set screenspace(e){var t;if(e){if(!this._videoTexture)return;this._overlay||(this._overlay=new Jle(this.context)),this._overlay.add(this._videoTexture)}else(t=this._overlay)==null||t.remove(this._videoTexture);this._overlay&&(this._overlay.enabled=e)}createVideoElement(){const e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),rr&&console.log("created video element",e),e}handleBeginPlaying(e){var t,n;if(!this.activeAndEnabled||!this._videoElement)return;this._targetObjects.length=0;let r=this.gameObject;switch(this.renderMode){case 3:r=(t=this.targetMaterialRenderer)==null?void 0:t.gameObject,r||(r=(n=re.getComponent(this.gameObject,Sn))==null?void 0:n.gameObject);break;case 2:console.error("VideoPlayer renderTexture not implemented yet. Please use material override instead");return}if(!r){console.error("Missing target for video material renderer",this.name,fj[this.renderMode],this);return}const s=r.material;if(s){this._targetObjects.push(r),s!==this._videoMaterial&&(this._videoMaterial=s.clone(),r.material=this._videoMaterial);const o="map",a=this._videoMaterial;if(!this.targetMaterialProperty)a[o]=this._videoTexture;else switch(this.targetMaterialProperty){default:a[o]=this._videoTexture;break}}else{console.warn("Can not play video, no material found, this might be a multimaterial case which is not supported yet");return}this.updateVideoElementSettings(),this.updateVideoElementStyles(),e&&(this.shouldUseM3U8&&this.ensureM3U8CanBePlayed(),this.play())}updateVideoElementSettings(){if(!this._videoElement)return;this._videoElement.loop=this._isLooping,this._videoElement.currentTime=this.currentTime,this._videoElement.playbackRate=this._playbackSpeed,this._videoElement.playsInline=!0;let e=!this._receivedInput||this.audioOutputMode===0;!e&&this._muted&&(e=!0),this._videoElement.muted=e,this.playOnAwake&&(this._videoElement.autoplay=!0)}updateVideoElementStyles(){this._videoElement&&(this._videoElement.style.userSelect="none",this._videoElement.style.visibility="hidden",this._videoElement.style.display="none",this.updateAspect())}*updateAspectImpl(){const e=++this._updateAspectRoutineId,t=void 0,n=this.clip;for(;e===this._updateAspectRoutineId&&this.aspectMode!==0&&this.clip&&n===this.clip&&this._isPlaying;){if(!n||typeof n=="string")return;let r;for(const s of n.getVideoTracks()){const o=s.getSettings();if(o&&o.width&&o.height){r=o.width/o.height;break}else r=this.context.renderer.domElement.clientWidth/this.context.renderer.domElement.clientHeight}if(r===void 0){for(let s=0;s<10;s++)yield;if(!this.isPlaying)break;continue}if(t===r){yield;continue}for(const s of this._targetObjects){let o=1;if(s.parent){const a=ki(s.parent);o=a.x/a.y}switch(this.aspectMode){case 1:s.scale.y=1/r*s.scale.x*o;break;case 2:s.scale.x=r*s.scale.y*o;break}}for(let s=0;s<3;s++)yield}}get shouldUseM3U8(){return this.url!=null&&this.url.endsWith(".m3u8")&&this.source===1}ensureM3U8CanBePlayed(){if(!this.shouldUseM3U8)return;let e=document.head.querySelector("script[data-hls_library]");e?globalThis.Hls?this.onHlsAvailable():e.addEventListener("load",this.onHlsAvailable):(rr&&console.log("HLS: load script"),e=document.createElement("script"),e.dataset.hls_library="hls.js",e.src="https://cdn.jsdelivr.net/npm/hls.js@1",e.addEventListener("load",this.onHlsAvailable),document.head.append(e))}}ao([x()],qn.prototype,"playOnAwake",2),ao([x()],qn.prototype,"aspectMode",2),ao([x(URL)],qn.prototype,"clip",2),ao([x()],qn.prototype,"source",2),ao([x(URL)],qn.prototype,"url",2),ao([x()],qn.prototype,"renderMode",2),ao([x()],qn.prototype,"targetMaterialProperty",2),ao([x(Sn)],qn.prototype,"targetMaterialRenderer",2),ao([x(gt)],qn.prototype,"targetTexture",2),ao([x()],qn.prototype,"time",2),ao([x()],qn.prototype,"playbackSpeed",1),ao([x()],qn.prototype,"isLooping",1),ao([x()],qn.prototype,"audioOutputMode",1);class Jle{constructor(e){h(this,"context"),h(this,"_videos",[]),h(this,"_screenspaceModeQuad"),h(this,"_isInScreenspaceMode",!1),h(this,"_input"),this.context=e,this._input=new Kle(this)}get enabled(){return this._isInScreenspaceMode}set enabled(e){e?this.start():this.stop()}add(e){this._videos.indexOf(e)===-1&&this._videos.push(e)}remove(e){if(!e)return;const t=this._videos.indexOf(e);t>=0&&this._videos.splice(t,1)}start(){var e;if(this._isInScreenspaceMode||this._videos.length<0)return;const t=this._videos[this._videos.length-1];if(!t)return;if(this._isInScreenspaceMode=!0,!this._screenspaceModeQuad){if(this._screenspaceModeQuad=Fg.createPrimitive(Uu.Quad,{material:new Zle(t)}),!this._screenspaceModeQuad)return;this._screenspaceModeQuad.geometry.scale(2,2,2)}const n=this._screenspaceModeQuad;this.context.scene.add(n),this.updateScreenspaceMaterialUniforms();const r=n.material;r?.reset(),(e=this._input)==null||e.enable(r)}stop(){var e;this._isInScreenspaceMode=!1,this._screenspaceModeQuad&&((e=this._input)==null||e.disable(),this._screenspaceModeQuad.removeFromParent())}updateScreenspaceMaterialUniforms(){var e;const t=(e=this._screenspaceModeQuad)==null?void 0:e.material;t&&(t.screenAspect=this.context.domElement.clientWidth/this.context.domElement.clientHeight)}}class Kle{constructor(e){h(this,"_onResizeScreenFn"),h(this,"_onKeyUpFn"),h(this,"_onMouseWheelFn"),h(this,"context"),h(this,"overlay"),h(this,"_material"),h(this,"_isPinching",!1),h(this,"_lastPinch",0),this.overlay=e,this.context=e.context}enable(e){this._material=e,window.addEventListener("resize",this._onResizeScreenFn=()=>{this.overlay.updateScreenspaceMaterialUniforms()}),window.addEventListener("keyup",this._onKeyUpFn=r=>{r.key==="Escape"&&this.overlay.stop()}),window.addEventListener("wheel",this._onMouseWheelFn=r=>{this.overlay.enabled&&(e.zoom+=r.deltaY*5e-4,r.preventDefault())},{passive:!1});const t=new $;window.addEventListener("mousemove",r=>{if(this.overlay.enabled&&this.context.input.getPointerPressed(0)){const s=new $(r.movementX,r.movementY);s.x/=this.context.domElement.clientWidth,s.y/=this.context.domElement.clientHeight,t.set(s.x,s.y),t.multiplyScalar(e.zoom/-this.context.time.deltaTime*.01),e.offset=e.offset.add(t)}}),window.addEventListener("pointermove",r=>{this.overlay.enabled&&this.context.input.getPointerPressed(0)&&this.context.input.getTouchesPressedCount()===1&&(t.set(r.movementX,r.movementY),t.multiplyScalar(e.zoom*-this.context.time.deltaTime*.05),e.offset=e.offset.add(t))});let n=0;window.addEventListener("touchstart",r=>{if(r.touches.length<2){this.context.time.time-n<.3&&this.overlay.stop(),n=this.context.time.time;return}this._isPinching=!0,this._lastPinch=0}),window.addEventListener("touchmove",r=>{if(!this._isPinching||!this._material)return;const s=r.touches[0],o=r.touches[1],a=s.clientX-o.clientX,l=s.clientY-o.clientY,c=Math.sqrt(a*a+l*l);if(this._lastPinch!==0){const u=c-this._lastPinch;this._material.zoom-=u*.004}this._lastPinch=c}),window.addEventListener("touchend",()=>{this._isPinching=!1})}disable(){this._onResizeScreenFn&&(window.removeEventListener("resize",this._onResizeScreenFn),this._onResizeScreenFn=void 0),this._onKeyUpFn&&(window.removeEventListener("keyup",this._onKeyUpFn),this._onKeyUpFn=void 0),this._onMouseWheelFn&&(window.removeEventListener("wheel",this._onMouseWheelFn),this._onMouseWheelFn=void 0)}}class Zle extends Tt{constructor(e){super(),h(this,"_offset",new $),this.uniforms={map:{value:e},screenAspect:{value:1},offsetScale:{value:new Ye(0,0,1,1)}},this.vertexShader=`
6926
6926
  uniform sampler2D map;
6927
6927
  uniform float screenAspect;
6928
6928
  uniform vec4 offsetScale;
@@ -7441,4 +7441,4 @@ Please refer to the documentation on <a href="https://fwd.needle.tools/needle-en
7441
7441
  `,this.shadowRoot&&this.shadowRoot.appendChild(e.content.cloneNode(!0)),this._context=new Lt({domElement:this}),this.addEventListener("error",this.onError)}static get observedAttributes(){return qhe}get loadingProgress01(){return this._loadingProgress01}get loadingFinished(){return this.loadingProgress01>.999}get cameraControls(){const e=this.getAttribute("camera-controls");return!(e===null||e==="False"||e==="false"||e==="0")}getContext(){return new Promise((e,t)=>{if(this._context&&this.loadingFinished)e(this._context);else{const n=()=>{this.removeEventListener("loadfinished",n),this._context&&this.loadingFinished&&e(this._context)};this.addEventListener("loadfinished",n)}})}get context(){return this._context}get Context(){return this._context}async connectedCallback(){if(ln&&console.log("<needle-engine> connected"),this.addEventListener("xr-session-started",this.onXRSessionStarted),this.onSetupDesktop(),!this.getAttribute("src")){const t=globalThis["needle:codegen_files"];ln&&console.log('src is null, trying to load from globalThis["needle:codegen_files"]',t),t&&(ln&&console.log('globalThis["needle:codegen_files"]',t),this.setAttribute("src",t))}ln&&console.log("src",this.getAttribute("src"));const e=this._loadId;setTimeout(()=>{this.isConnected!==!1&&e===this._loadId&&this.onLoad()},1),Fl!=null&&Fl.length&&this.setAttribute("version",Fl)}disconnectedCallback(){var e;this.removeEventListener("xr-session-started",this.onXRSessionStarted),this._didFullyLoad=!1;const t=this.getAttribute("keep-alive"),n=t==null||t?.length>0&&t!=="true"&&t!=="1";ln&&console.warn('<needle-engine> disconnected, keep-alive: "'+t+'"',typeof t,"Dispose=",n),n?(ln&&console.warn("<needle-engine> dispose"),(e=this._context)==null||e.dispose(),this._context=null,this._lastSourceFiles=null,this._loadId+=1):ln&&console.warn("<needle-engine> is not disposed because keep-alive is set")}attributeChangedCallback(e,t,n){switch(ln&&console.log("attributeChangedCallback",e,t,n),e){case"src":ln&&console.warn("src changed to type:",typeof n,', from "',t,'" to "',n,'"'),this.onLoad();break;case"hash":this._context&&(this._context.hash=n);break;case"loadstart":case"progress":case"loadfinished":typeof n=="string"&&n.length>0&&(ln&&console.log(e+" attribute changed",n),this.registerEventFromAttribute(e,n));break;case"dracoDecoderPath":ln&&console.log("dracoDecoderPath",n),sN(n);break;case"dracoDecoderType":n==="wasm"||n==="js"?(ln&&console.log("dracoDecoderType",n),oN(n)):console.error("Invalid dracoDecoderType",n,"expected js or wasm");break;case"ktx2DecoderPath":ln&&console.log("ktx2DecoderPath",n),aN(n);break}}async onLoad(){var e,t;if(!this.isConnected)return;if(this._context||(ln&&console.warn("Create new context"),this._context=new Lt({domElement:this})),!this._context){console.error("Needle Engine: Context not initialized");return}const n=this.getSourceFiles();if(n==null||n.length<=0)ln&&console.warn("Clear scene",n),this._context.clear();else if(!this.checkIfSourceHasChanged(n,this._lastSourceFiles))return;this._lastSourceFiles=n;const r=++this._loadId,s=this.getAttribute("alias");this.classList.add("loading");const o=Fp();this.ensureLoadStartIsRegistered();let a=this.dispatchEvent(new CustomEvent("loadstart",{detail:{context:this._context,alias:s},cancelable:!0}));if(o){const m=this.getAttribute("hide-loading-overlay");m!=null&&m!=="0"&&(a=!1)}a===!1&&!o&&(pt()||(a=!0),console.warn("Needle Engine: You need a commercial license to override the default loading view. Visit https://needle.tools/pricing"),pt()&&Qi('You need a <a target="_blank" href="https://needle.tools/pricing">commercial license</a> to override the default loading view. This will not work in production.')),!this._loadingView&&a&&(this._loadingView=new aT(this)),a&&(this._didFullyLoad!==!0?(e=this._loadingView)==null||e.onLoadingBegin("begin load"):setTimeout(()=>{this._loadingView&&this._loadingProgress01<.3&&this._loadId===r&&this._loadingView.onLoadingBegin("begin load")},300)),ln&&console.warn("--------------",r,"Needle Engine: Begin loading",s??"",n),this.onBeforeBeginLoading();const l=[],c={context:this._context,name:"",progress:{},index:0,count:n.length,totalProgress01:this._loadingProgress01},u=new CustomEvent("progress",{detail:c}),d=new Array,p={files:n,onLoadingProgress:m=>{var A;const v=m.index;!d[v]&&m.name&&(d[v]=Xhe(m.name)),m.name=d[v],a&&((A=this._loadingView)==null||A.onLoadingUpdate(m)),c.name=m.name,c.progress=m.progress,this._loadingProgress01=sT(m),c.totalProgress01=this._loadingProgress01,this.dispatchEvent(u)},onLoadingFinished:(m,A,v)=>{v&&l.push({src:A,file:v})}},f=this.getAttribute("hash");f!=null&&(this._context.hash=f),this._context.alias=s,await this._context.create(p),this._loadId===r&&(ln&&console.warn("--------------",r,"Needle Engine: finished loading",s??"",n),this._loadingProgress01=1,a&&((t=this._loadingView)==null||t.onLoadingUpdate(1,"creating scene")),this._didFullyLoad=!0,this.classList.remove("loading"),this.classList.add("loading-finished"),this.dispatchEvent(new CustomEvent("loadfinished",{detail:{context:this._context,src:s,loadedFiles:l}})))}internalSetLoadingMessage(e){var t;(t=this._loadingView)==null||t.setMessage(e)}getSourceFiles(){const e=this.getAttribute("src");if(!e)return[];let t;Array.isArray(e)?t=e:e.startsWith("[")&&e.endsWith("]")?t=JSON.parse(e):e.includes(",")?t=e.split(","):t=[e];for(let n=t.length-1;n>=0;n--){const r=t[n];(r==="null"||r==="undefined"||r?.length<=0)&&t.splice(n,1)}return t}checkIfSourceHasChanged(e,t){if(e?.length!==t?.length||e==null&&t!==null||e!==null&&t==null)return!0;if(e!==null&&t!==null){for(let n=0;n<e?.length;n++)if(e[n]!==t[n])return!0}return!1}ensureLoadStartIsRegistered(){const e=this.getAttribute("loadstart");e&&this.registerEventFromAttribute("loadstart",e)}registerEventFromAttribute(e,t){const n=this._previouslyRegisteredMap.get(e);if(n&&(this._previouslyRegisteredMap.delete(e),this.removeEventListener(e,n)),typeof t=="string"&&t.length>0)try{const r=(0,eval)(t);typeof r=="function"&&(this._previouslyRegisteredMap.set(e,r),this.addEventListener(e,s=>r?.call(globalThis,this._context,s)))}catch(r){console.error("Error registering event "+e+'="'+t+`" failed with the following error:
7442
7442
  `,r)}}getAROverlayContainer(){return this._overlay_ar.createOverlayContainer(this)}getVROverlayContainer(){for(let e=0;e<this.children.length;e++){const t=this.children[e];if(t.classList.contains("vr"))return t}return null}onEnterAR(e){var t;this.onSetupAR();const n=this.getAROverlayContainer();this._overlay_ar.onBegin(this._context,n,e),this.dispatchEvent(new CustomEvent("enter-ar",{detail:{session:e,context:this._context,htmlContainer:(t=this._overlay_ar)==null?void 0:t.ARContainer}}))}onExitAR(e){var t;this._overlay_ar.onEnd(this._context),this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-ar",{detail:{session:e,context:this._context,htmlContainer:(t=this._overlay_ar)==null?void 0:t.ARContainer}}))}onEnterVR(e){this.onSetupVR(),this.dispatchEvent(new CustomEvent("enter-vr",{detail:{session:e,context:this._context}}))}onExitVR(e){this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-vr",{detail:{session:e,context:this._context}}))}onSetupAR(){this.classList.add(z0),this.classList.remove(j0);const e=this.getAROverlayContainer();ln&&console.warn("onSetupAR:",e),e&&(e.classList.add(z0),e.classList.remove(j0)),this.foreachHtmlElement(t=>this.setupElementsForMode(t,UF))}onSetupVR(){this.classList.remove(z0),this.classList.remove(j0),this.foreachHtmlElement(e=>this.setupElementsForMode(e,Vj))}onSetupDesktop(){this.classList.remove(z0),this.classList.add(j0);const e=this.getAROverlayContainer();e&&(e.classList.remove(z0),e.classList.add(j0)),this.foreachHtmlElement(t=>this.setupElementsForMode(t,Wj))}setupElementsForMode(e,t,n=null){var r,s;if(!(e===((s=(r=this._context)==null?void 0:r.renderer)==null?void 0:s.domElement)||e.id==="VRButton"||e.id==="ARButton"))if(e.classList.contains(t))e.style.visibility="visible",e.style.display==="none"&&(e.style.display="block");else for(const o of Whe)e.classList.contains(o)&&(e.style.visibility="hidden",e.style.display="none")}foreachHtmlElement(e){for(let t=0;t<this.children.length;t++){const n=this.children[t];n.style&&e(n)}}onBeforeBeginLoading(){const e=this.getAttribute("dracoDecoderPath");e&&(ln&&console.log("using custom draco decoder path",e),sN(e));const t=this.getAttribute("dracoDecoderType");t&&(ln&&console.log("using custom draco decoder type",t),oN(t));const n=this.getAttribute("ktx2DecoderPath");n&&(ln&&console.log("using custom ktx2 decoder path",n),aN(n))}}typeof window<"u"&&!window.customElements.get(Hj)&&window.customElements.define(Hj,u2);function Xhe(i){const e=i.split("/");let t=e[e.length-1];const n=t.indexOf("?");n>0&&(t=t.substring(0,n));const r=t.split(".").pop();if((r==="glb"||r==="gltf")&&(t=t.substring(0,t.length-4)),t=decodeURIComponent(t),t.length>3){let s="";for(let o=0;o<t.length;o++){let a=t[o];if(a===" "&&s.length<=0)continue;const l=s.length===0;l==!1&&a===a.toUpperCase()?s+=" "+a:(l&&(a=a.toUpperCase()),s+=a)}return ln&&console.log("displayName",t,s),s}return ln&&console.log("displayName",t),t}const Yhe=Object.freeze(Object.defineProperty({__proto__:null,NeedleEngineHTMLElement:u2},Symbol.toStringTag,{value:"Module"}));function Jhe(){Ng.registerWaitForAllowAudio(()=>{const i=Dy.getContext();i.addEventListener("statechange",()=>{setTimeout(()=>{const e=i.state;(e==="suspended"||e==="interrupted")&&i.resume().then(()=>{console.log("AudioContext resumed successfully")}).catch(t=>{console.log("Failed to resume AudioContext: "+t)})},500)})})}setTimeout(Jhe,1e3);const ww=ee("debughotreload");let G0=!1;const Q0=new Map;function Khe(){return G0}function Zhe(i){var e;if(G0)return;const t=i.constructor.name;Q0.has(t)?(e=Q0.get(t))==null||e.push(i):Q0.set(t,[i])}function $he(i){if(G0)return;const e=i.constructor.name,t=Q0.get(e);if(!t)return;const n=t.indexOf(i);n!==-1&&t.splice(n,1)}let qj=!1;function eue(){if(ww||qj)return;qj=!0;const i=console.error;console.error=(...e)=>{if(e.length){const t=e[0];if(typeof t=="string"&&t.includes("[hmr] Failed to reload ")){console.log("[Needle Engine] Hot reloading failed"),window.location.reload();return}}i.apply(console,e)}}function tue(i){ww&&console.log("[HMR] Apply changes",i,Object.keys(i)),eue();for(const e of Object.keys(i))try{G0=!0;const t=q.get(e);if(!t){ww&&console.log("[HMR] Type not found: "+e);continue}const n=i[e],r=Q0.get(n.name);let s="[Needle Engine] Updating type: "+e;const o=r?.length??-1;o>0?s+=" x"+o:s+=" - no instances",console.log(s);const a=Object.getOwnPropertyNames(t.prototype),l=Object.getOwnPropertyDescriptors(n.prototype);for(const c in l)l[c].writable&&(t.prototype[c]=i[e].prototype[c]);for(const c of a)l[c]||delete t.prototype[c];if(r){const c=new n,u=Object.getOwnPropertyDescriptors(c);for(const d of r){const p=d,f=p.isComponent===!0,m=f?p.activeAndEnabled:!0,A=f?p.context:void 0;try{if(f&&A&&zl(p,A),f&&m&&(p.enabled=!1),d.onBeforeHotReloadFields&&d.onBeforeHotReloadFields()===!1)continue;for(const v in u)if(u[v].writable){if(d[v]===void 0)d[v]=c[v];else if(typeof d[v]=="function"&&!d[v].prototype){const g=d[v],y=g.name,b="bound ";if(y===b)continue;const _=g.name.substring(b.length),E=n.prototype[_];E&&(d[v]=E.bind(d))}}d.onAfterHotReloadFields&&d.onAfterHotReloadFields()}finally{f&&A&&RE(p,A),f&&m&&(p.enabled=!0)}}}}catch(t){if(ww)console.error(t);else return!1}finally{G0=!1,Oa(Ws.Log,"Script changes applied (HMR)")}return!0}let ze;const H0=new Array(32).fill(void 0);H0.push(void 0,null,!0,!1),H0.length;let d2=new Int32Array;function Xj(){return d2.byteLength===0&&(d2=new Int32Array(ze.memory.buffer)),d2}const iue=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});iue.decode();function yt(i,e){if(!(i instanceof e))throw new Error(`expected instance of ${e.name}`);return i.ptr}let p2=new Float32Array;function nue(){return p2.byteLength===0&&(p2=new Float32Array(ze.memory.buffer)),p2}let V0=32;function Yj(i){if(V0==1)throw new Error("out of js stack");return H0[--V0]=i,V0}let f2=new Uint32Array;function rue(){return f2.byteLength===0&&(f2=new Uint32Array(ze.memory.buffer)),f2}let ho=0;function Od(i,e){const t=e(4*i.length);return nue().set(i,t/4),ho=i.length,t}function Sw(i,e){const t=e(4*i.length);return rue().set(i,t/4),ho=i.length,t}class Qw{static __wrap(e){const t=Object.create(Qw.prototype);return t.ptr=e,t}__destroy_into_raw(){const e=this.ptr;return this.ptr=0,e}free(){const e=this.__destroy_into_raw();ze.__wbg_raweventqueue_free(e)}constructor(e){const t=ze.raweventqueue_new(e);return Qw.__wrap(t)}drainCollisionEvents(e){try{ze.raweventqueue_drainCollisionEvents(this.ptr,Yj(e))}finally{H0[V0++]=void 0}}drainContactForceEvents(e){try{ze.raweventqueue_drainContactForceEvents(this.ptr,Yj(e))}finally{H0[V0++]=void 0}}clear(){ze.raweventqueue_clear(this.ptr)}}class Al{static __wrap(e){const t=Object.create(Al.prototype);return t.ptr=e,t}__destroy_into_raw(){const e=this.ptr;return this.ptr=0,e}free(){const e=this.__destroy_into_raw();ze.__wbg_rawgenericjoint_free(e)}static spherical(e,t){yt(e,ct),yt(t,ct);const n=ze.rawgenericjoint_spherical(e.ptr,t.ptr);return Al.__wrap(n)}static prismatic(e,t,n,r,s,o){yt(e,ct),yt(t,ct),yt(n,ct);const a=ze.rawgenericjoint_prismatic(e.ptr,t.ptr,n.ptr,r,s,o);return a===0?void 0:Al.__wrap(a)}static fixed(e,t,n,r){yt(e,ct),yt(t,ar),yt(n,ct),yt(r,ar);const s=ze.rawgenericjoint_fixed(e.ptr,t.ptr,n.ptr,r.ptr);return Al.__wrap(s)}static revolute(e,t,n){yt(e,ct),yt(t,ct),yt(n,ct);const r=ze.rawgenericjoint_revolute(e.ptr,t.ptr,n.ptr);return r===0?void 0:Al.__wrap(r)}}class M2{static __wrap(e){const t=Object.create(M2.prototype);return t.ptr=e,t}__destroy_into_raw(){const e=this.ptr;return this.ptr=0,e}free(){const e=this.__destroy_into_raw();ze.__wbg_rawpointprojection_free(e)}point(){const e=ze.rawkinematiccharactercontroller_computedMovement(this.ptr);return ct.__wrap(e)}isInside(){return ze.rawkinematiccharactercontroller_computedGrounded(this.ptr)!==0}}class T2{static __wrap(e){const t=Object.create(T2.prototype);return t.ptr=e,t}__destroy_into_raw(){const e=this.ptr;return this.ptr=0,e}free(){const e=this.__destroy_into_raw();ze.__wbg_rawrayintersection_free(e)}normal(){const e=ze.rawcharactercollision_worldWitness1(this.ptr);return ct.__wrap(e)}toi(){return ze.rawcharactercollision_toi(this.ptr)}featureType(){return ze.rawrayintersection_featureType(this.ptr)>>>0}featureId(){try{const n=ze.__wbindgen_add_to_stack_pointer(-16);ze.rawrayintersection_featureId(n,this.ptr);var e=Xj()[n/4+0],t=Xj()[n/4+1];return e===0?void 0:t>>>0}finally{ze.__wbindgen_add_to_stack_pointer(16)}}}class ar{static __wrap(e){const t=Object.create(ar.prototype);return t.ptr=e,t}__destroy_into_raw(){const e=this.ptr;return this.ptr=0,e}free(){const e=this.__destroy_into_raw();ze.__wbg_rawrotation_free(e)}constructor(e,t,n,r){const s=ze.rawrotation_new(e,t,n,r);return ar.__wrap(s)}static identity(){const e=ze.rawrotation_identity();return ar.__wrap(e)}get x(){return ze.rawintegrationparameters_dt(this.ptr)}get y(){return ze.rawrotation_y(this.ptr)}get z(){return ze.rawcharactercollision_toi(this.ptr)}get w(){return ze.rawrotation_w(this.ptr)}}class jt{static __wrap(e){const t=Object.create(jt.prototype);return t.ptr=e,t}__destroy_into_raw(){const e=this.ptr;return this.ptr=0,e}free(){const e=this.__destroy_into_raw();ze.__wbg_rawshape_free(e)}static cuboid(e,t,n){const r=ze.rawshape_cuboid(e,t,n);return jt.__wrap(r)}static roundCuboid(e,t,n,r){const s=ze.rawshape_roundCuboid(e,t,n,r);return jt.__wrap(s)}static ball(e){const t=ze.rawshape_ball(e);return jt.__wrap(t)}static halfspace(e){yt(e,ct);const t=ze.rawshape_halfspace(e.ptr);return jt.__wrap(t)}static capsule(e,t){const n=ze.rawshape_capsule(e,t);return jt.__wrap(n)}static cylinder(e,t){const n=ze.rawshape_cylinder(e,t);return jt.__wrap(n)}static roundCylinder(e,t,n){const r=ze.rawshape_roundCylinder(e,t,n);return jt.__wrap(r)}static cone(e,t){const n=ze.rawshape_cone(e,t);return jt.__wrap(n)}static roundCone(e,t,n){const r=ze.rawshape_roundCone(e,t,n);return jt.__wrap(r)}static polyline(e,t){const n=Od(e,ze.__wbindgen_malloc),r=ho,s=Sw(t,ze.__wbindgen_malloc),o=ho,a=ze.rawshape_polyline(n,r,s,o);return jt.__wrap(a)}static trimesh(e,t){const n=Od(e,ze.__wbindgen_malloc),r=ho,s=Sw(t,ze.__wbindgen_malloc),o=ho,a=ze.rawshape_trimesh(n,r,s,o);return jt.__wrap(a)}static heightfield(e,t,n,r){const s=Od(n,ze.__wbindgen_malloc),o=ho;yt(r,ct);const a=ze.rawshape_heightfield(e,t,s,o,r.ptr);return jt.__wrap(a)}static segment(e,t){yt(e,ct),yt(t,ct);const n=ze.rawshape_segment(e.ptr,t.ptr);return jt.__wrap(n)}static triangle(e,t,n){yt(e,ct),yt(t,ct),yt(n,ct);const r=ze.rawshape_triangle(e.ptr,t.ptr,n.ptr);return jt.__wrap(r)}static roundTriangle(e,t,n,r){yt(e,ct),yt(t,ct),yt(n,ct);const s=ze.rawshape_roundTriangle(e.ptr,t.ptr,n.ptr,r);return jt.__wrap(s)}static convexHull(e){const t=Od(e,ze.__wbindgen_malloc),n=ho,r=ze.rawshape_convexHull(t,n);return r===0?void 0:jt.__wrap(r)}static roundConvexHull(e,t){const n=Od(e,ze.__wbindgen_malloc),r=ho,s=ze.rawshape_roundConvexHull(n,r,t);return s===0?void 0:jt.__wrap(s)}static convexMesh(e,t){const n=Od(e,ze.__wbindgen_malloc),r=ho,s=Sw(t,ze.__wbindgen_malloc),o=ho,a=ze.rawshape_convexMesh(n,r,s,o);return a===0?void 0:jt.__wrap(a)}static roundConvexMesh(e,t,n){const r=Od(e,ze.__wbindgen_malloc),s=ho,o=Sw(t,ze.__wbindgen_malloc),a=ho,l=ze.rawshape_roundConvexMesh(r,s,o,a,n);return l===0?void 0:jt.__wrap(l)}castShape(e,t,n,r,s,o,a,l,c){yt(e,ct),yt(t,ar),yt(n,ct),yt(r,jt),yt(s,ct),yt(o,ar),yt(a,ct);const u=ze.rawshape_castShape(this.ptr,e.ptr,t.ptr,n.ptr,r.ptr,s.ptr,o.ptr,a.ptr,l,c);return u===0?void 0:R2.__wrap(u)}intersectsShape(e,t,n,r,s){return yt(e,ct),yt(t,ar),yt(n,jt),yt(r,ct),yt(s,ar),ze.rawshape_intersectsShape(this.ptr,e.ptr,t.ptr,n.ptr,r.ptr,s.ptr)!==0}contactShape(e,t,n,r,s,o){yt(e,ct),yt(t,ar),yt(n,jt),yt(r,ct),yt(s,ar);const a=ze.rawshape_contactShape(this.ptr,e.ptr,t.ptr,n.ptr,r.ptr,s.ptr,o);return a===0?void 0:I2.__wrap(a)}containsPoint(e,t,n){return yt(e,ct),yt(t,ar),yt(n,ct),ze.rawshape_containsPoint(this.ptr,e.ptr,t.ptr,n.ptr)!==0}projectPoint(e,t,n,r){yt(e,ct),yt(t,ar),yt(n,ct);const s=ze.rawshape_projectPoint(this.ptr,e.ptr,t.ptr,n.ptr,r);return M2.__wrap(s)}intersectsRay(e,t,n,r,s){return yt(e,ct),yt(t,ar),yt(n,ct),yt(r,ct),ze.rawshape_intersectsRay(this.ptr,e.ptr,t.ptr,n.ptr,r.ptr,s)!==0}castRay(e,t,n,r,s,o){return yt(e,ct),yt(t,ar),yt(n,ct),yt(r,ct),ze.rawshape_castRay(this.ptr,e.ptr,t.ptr,n.ptr,r.ptr,s,o)}castRayAndGetNormal(e,t,n,r,s,o){yt(e,ct),yt(t,ar),yt(n,ct),yt(r,ct);const a=ze.rawshape_castRayAndGetNormal(this.ptr,e.ptr,t.ptr,n.ptr,r.ptr,s,o);return a===0?void 0:T2.__wrap(a)}}class I2{static __wrap(e){const t=Object.create(I2.prototype);return t.ptr=e,t}__destroy_into_raw(){const e=this.ptr;return this.ptr=0,e}free(){const e=this.__destroy_into_raw();ze.__wbg_rawshapecontact_free(e)}distance(){return ze.rawshapecontact_distance(this.ptr)}point1(){const e=ze.rawkinematiccharactercontroller_computedMovement(this.ptr);return ct.__wrap(e)}point2(){const e=ze.rawcharactercollision_worldWitness1(this.ptr);return ct.__wrap(e)}normal1(){const e=ze.rawshapecollidertoi_witness2(this.ptr);return ct.__wrap(e)}normal2(){const e=ze.rawcharactercollision_worldNormal1(this.ptr);return ct.__wrap(e)}}class R2{static __wrap(e){const t=Object.create(R2.prototype);return t.ptr=e,t}__destroy_into_raw(){const e=this.ptr;return this.ptr=0,e}free(){const e=this.__destroy_into_raw();ze.__wbg_rawshapetoi_free(e)}toi(){return ze.rawintegrationparameters_dt(this.ptr)}witness1(){const e=ze.rawshapetoi_witness1(this.ptr);return ct.__wrap(e)}witness2(){const e=ze.rawcontactforceevent_total_force(this.ptr);return ct.__wrap(e)}normal1(){const e=ze.rawshapetoi_normal1(this.ptr);return ct.__wrap(e)}normal2(){const e=ze.rawshapetoi_normal2(this.ptr);return ct.__wrap(e)}}class ct{static __wrap(e){const t=Object.create(ct.prototype);return t.ptr=e,t}__destroy_into_raw(){const e=this.ptr;return this.ptr=0,e}free(){const e=this.__destroy_into_raw();ze.__wbg_rawvector_free(e)}static zero(){const e=ze.rawvector_zero();return ct.__wrap(e)}constructor(e,t,n){const r=ze.rawvector_new(e,t,n);return ct.__wrap(r)}get x(){return ze.rawintegrationparameters_dt(this.ptr)}set x(e){ze.rawintegrationparameters_set_dt(this.ptr,e)}get y(){return ze.rawrotation_y(this.ptr)}set y(e){ze.rawvector_set_y(this.ptr,e)}get z(){return ze.rawcharactercollision_toi(this.ptr)}set z(e){ze.rawintegrationparameters_set_erp(this.ptr,e)}xyz(){const e=ze.rawvector_xyz(this.ptr);return ct.__wrap(e)}yxz(){const e=ze.rawvector_yxz(this.ptr);return ct.__wrap(e)}zxy(){const e=ze.rawvector_zxy(this.ptr);return ct.__wrap(e)}xzy(){const e=ze.rawvector_xzy(this.ptr);return ct.__wrap(e)}yzx(){const e=ze.rawvector_yzx(this.ptr);return ct.__wrap(e)}zyx(){const e=ze.rawvector_zyx(this.ptr);return ct.__wrap(e)}}class sue{constructor(e,t,n){this.x=e,this.y=t,this.z=n}}class Pe{static new(e,t,n){return new sue(e,t,n)}static intoRaw(e){return new ct(e.x,e.y,e.z)}static zeros(){return Pe.new(0,0,0)}static fromRaw(e){if(!e)return null;let t=Pe.new(e.x,e.y,e.z);return e.free(),t}static copy(e,t){e.x=t.x,e.y=t.y,e.z=t.z}}class Jj{constructor(e,t,n,r){this.x=e,this.y=t,this.z=n,this.w=r}}class Bi{static identity(){return new Jj(0,0,0,1)}static fromRaw(e){if(!e)return null;let t=new Jj(e.x,e.y,e.z,e.w);return e.free(),t}static intoRaw(e){return new ar(e.x,e.y,e.z,e.w)}static copy(e,t){e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w}}class oue{constructor(e){this.elements=e}get m11(){return this.elements[0]}get m12(){return this.elements[1]}get m21(){return this.m12}get m13(){return this.elements[2]}get m31(){return this.m13}get m22(){return this.elements[3]}get m23(){return this.elements[4]}get m32(){return this.m23}get m33(){return this.elements[5]}}class Kj{static fromRaw(e){const t=new oue(e.elements());return e.free(),t}}var W0,fl,Zj,Ln,m2,Zt,Cw,Yf,$j,g2,e5,t5;(function(i){i[i.Dynamic=0]="Dynamic",i[i.Fixed=1]="Fixed",i[i.KinematicPositionBased=2]="KinematicPositionBased",i[i.KinematicVelocityBased=3]="KinematicVelocityBased"})(W0||(W0={}));class i5{constructor(e,t,n){this.rawSet=e,this.colliderSet=t,this.handle=n}finalizeDeserialization(e){this.colliderSet=e}isValid(){return this.rawSet.contains(this.handle)}lockTranslations(e,t){return this.rawSet.rbLockTranslations(this.handle,e,t)}lockRotations(e,t){return this.rawSet.rbLockRotations(this.handle,e,t)}setEnabledTranslations(e,t,n,r){return this.rawSet.rbSetEnabledTranslations(this.handle,e,t,n,r)}restrictTranslations(e,t,n,r){this.setEnabledTranslations(e,t,n,r)}setEnabledRotations(e,t,n,r){return this.rawSet.rbSetEnabledRotations(this.handle,e,t,n,r)}restrictRotations(e,t,n,r){this.setEnabledRotations(e,t,n,r)}dominanceGroup(){return this.rawSet.rbDominanceGroup(this.handle)}setDominanceGroup(e){this.rawSet.rbSetDominanceGroup(this.handle,e)}enableCcd(e){this.rawSet.rbEnableCcd(this.handle,e)}translation(){let e=this.rawSet.rbTranslation(this.handle);return Pe.fromRaw(e)}rotation(){let e=this.rawSet.rbRotation(this.handle);return Bi.fromRaw(e)}nextTranslation(){let e=this.rawSet.rbNextTranslation(this.handle);return Pe.fromRaw(e)}nextRotation(){let e=this.rawSet.rbNextRotation(this.handle);return Bi.fromRaw(e)}setTranslation(e,t){this.rawSet.rbSetTranslation(this.handle,e.x,e.y,e.z,t)}setLinvel(e,t){let n=Pe.intoRaw(e);this.rawSet.rbSetLinvel(this.handle,n,t),n.free()}gravityScale(){return this.rawSet.rbGravityScale(this.handle)}setGravityScale(e,t){this.rawSet.rbSetGravityScale(this.handle,e,t)}setRotation(e,t){this.rawSet.rbSetRotation(this.handle,e.x,e.y,e.z,e.w,t)}setAngvel(e,t){let n=Pe.intoRaw(e);this.rawSet.rbSetAngvel(this.handle,n,t),n.free()}setNextKinematicTranslation(e){this.rawSet.rbSetNextKinematicTranslation(this.handle,e.x,e.y,e.z)}setNextKinematicRotation(e){this.rawSet.rbSetNextKinematicRotation(this.handle,e.x,e.y,e.z,e.w)}linvel(){return Pe.fromRaw(this.rawSet.rbLinvel(this.handle))}angvel(){return Pe.fromRaw(this.rawSet.rbAngvel(this.handle))}mass(){return this.rawSet.rbMass(this.handle)}effectiveInvMass(){return Pe.fromRaw(this.rawSet.rbEffectiveInvMass(this.handle))}invMass(){return this.rawSet.rbInvMass(this.handle)}localCom(){return Pe.fromRaw(this.rawSet.rbLocalCom(this.handle))}worldCom(){return Pe.fromRaw(this.rawSet.rbWorldCom(this.handle))}invPrincipalInertiaSqrt(){return Pe.fromRaw(this.rawSet.rbInvPrincipalInertiaSqrt(this.handle))}principalInertia(){return Pe.fromRaw(this.rawSet.rbPrincipalInertia(this.handle))}principalInertiaLocalFrame(){return Bi.fromRaw(this.rawSet.rbPrincipalInertiaLocalFrame(this.handle))}effectiveWorldInvInertiaSqrt(){return Kj.fromRaw(this.rawSet.rbEffectiveWorldInvInertiaSqrt(this.handle))}effectiveAngularInertia(){return Kj.fromRaw(this.rawSet.rbEffectiveAngularInertia(this.handle))}sleep(){this.rawSet.rbSleep(this.handle)}wakeUp(){this.rawSet.rbWakeUp(this.handle)}isCcdEnabled(){return this.rawSet.rbIsCcdEnabled(this.handle)}numColliders(){return this.rawSet.rbNumColliders(this.handle)}collider(e){return this.colliderSet.get(this.rawSet.rbCollider(this.handle,e))}setEnabled(e){this.rawSet.rbSetEnabled(this.handle,e)}isEnabled(){return this.rawSet.rbIsEnabled(this.handle)}bodyType(){return this.rawSet.rbBodyType(this.handle)}setBodyType(e,t){return this.rawSet.rbSetBodyType(this.handle,e,t)}isSleeping(){return this.rawSet.rbIsSleeping(this.handle)}isMoving(){return this.rawSet.rbIsMoving(this.handle)}isFixed(){return this.rawSet.rbIsFixed(this.handle)}isKinematic(){return this.rawSet.rbIsKinematic(this.handle)}isDynamic(){return this.rawSet.rbIsDynamic(this.handle)}linearDamping(){return this.rawSet.rbLinearDamping(this.handle)}angularDamping(){return this.rawSet.rbAngularDamping(this.handle)}setLinearDamping(e){this.rawSet.rbSetLinearDamping(this.handle,e)}recomputeMassPropertiesFromColliders(){this.rawSet.rbRecomputeMassPropertiesFromColliders(this.handle,this.colliderSet.raw)}setAdditionalMass(e,t){this.rawSet.rbSetAdditionalMass(this.handle,e,t)}setAdditionalMassProperties(e,t,n,r,s){let o=Pe.intoRaw(t),a=Pe.intoRaw(n),l=Bi.intoRaw(r);this.rawSet.rbSetAdditionalMassProperties(this.handle,e,o,a,l,s),o.free(),a.free(),l.free()}setAngularDamping(e){this.rawSet.rbSetAngularDamping(this.handle,e)}resetForces(e){this.rawSet.rbResetForces(this.handle,e)}resetTorques(e){this.rawSet.rbResetTorques(this.handle,e)}addForce(e,t){const n=Pe.intoRaw(e);this.rawSet.rbAddForce(this.handle,n,t),n.free()}applyImpulse(e,t){const n=Pe.intoRaw(e);this.rawSet.rbApplyImpulse(this.handle,n,t),n.free()}addTorque(e,t){const n=Pe.intoRaw(e);this.rawSet.rbAddTorque(this.handle,n,t),n.free()}applyTorqueImpulse(e,t){const n=Pe.intoRaw(e);this.rawSet.rbApplyTorqueImpulse(this.handle,n,t),n.free()}addForceAtPoint(e,t,n){const r=Pe.intoRaw(e),s=Pe.intoRaw(t);this.rawSet.rbAddForceAtPoint(this.handle,r,s,n),r.free(),s.free()}applyImpulseAtPoint(e,t,n){const r=Pe.intoRaw(e),s=Pe.intoRaw(t);this.rawSet.rbApplyImpulseAtPoint(this.handle,r,s,n),r.free(),s.free()}}(function(i){i[i.Revolute=0]="Revolute",i[i.Fixed=1]="Fixed",i[i.Prismatic=2]="Prismatic",i[i.Spherical=3]="Spherical"})(fl||(fl={})),function(i){i[i.AccelerationBased=0]="AccelerationBased",i[i.ForceBased=1]="ForceBased"}(Zj||(Zj={}));class tm{constructor(){}static fixed(e,t,n,r){let s=new tm;return s.anchor1=e,s.anchor2=n,s.frame1=t,s.frame2=r,s.jointType=fl.Fixed,s}static spherical(e,t){let n=new tm;return n.anchor1=e,n.anchor2=t,n.jointType=fl.Spherical,n}static prismatic(e,t,n){let r=new tm;return r.anchor1=e,r.anchor2=t,r.axis=n,r.jointType=fl.Prismatic,r}static revolute(e,t,n){let r=new tm;return r.anchor1=e,r.anchor2=t,r.axis=n,r.jointType=fl.Revolute,r}intoRaw(){let e,t,n=Pe.intoRaw(this.anchor1),r=Pe.intoRaw(this.anchor2),s=!1,o=0,a=0;switch(this.jointType){case fl.Fixed:let l=Bi.intoRaw(this.frame1),c=Bi.intoRaw(this.frame2);t=Al.fixed(n,l,r,c),l.free(),c.free();break;case fl.Prismatic:e=Pe.intoRaw(this.axis),this.limitsEnabled&&(s=!0,o=this.limits[0],a=this.limits[1]),t=Al.prismatic(n,r,e,s,o,a),e.free();break;case fl.Spherical:t=Al.spherical(n,r);break;case fl.Revolute:e=Pe.intoRaw(this.axis),t=Al.revolute(n,r,e),e.free()}return n.free(),r.free(),t}}(function(i){i[i.Average=0]="Average",i[i.Min=1]="Min",i[i.Multiply=2]="Multiply",i[i.Max=3]="Max"})(Ln||(Ln={}));class $0{constructor(e,t,n,r,s){this.distance=e,this.point1=t,this.point2=n,this.normal1=r,this.normal2=s}static fromRaw(e){if(!e)return null;const t=new $0(e.distance(),Pe.fromRaw(e.point1()),Pe.fromRaw(e.point2()),Pe.fromRaw(e.normal1()),Pe.fromRaw(e.normal2()));return e.free(),t}}(function(i){i[i.Vertex=0]="Vertex",i[i.Edge=1]="Edge",i[i.Face=2]="Face",i[i.Unknown=3]="Unknown"})(m2||(m2={}));class Hw{constructor(e,t){this.point=e,this.isInside=t}static fromRaw(e){if(!e)return null;const t=new Hw(Pe.fromRaw(e.point()),e.isInside());return e.free(),t}}class aue{constructor(e,t){this.origin=e,this.dir=t}pointAt(e){return{x:this.origin.x+this.dir.x*e,y:this.origin.y+this.dir.y*e,z:this.origin.z+this.dir.z*e}}}class Vw{constructor(e,t,n,r){this.featureType=m2.Unknown,this.featureId=void 0,this.toi=e,this.normal=t,r!==void 0&&(this.featureId=r),n!==void 0&&(this.featureType=n)}static fromRaw(e){if(!e)return null;const t=new Vw(e.toi(),Pe.fromRaw(e.normal()),e.featureType(),e.featureId());return e.free(),t}}class eA{constructor(e,t,n,r,s){this.toi=e,this.witness1=t,this.witness2=n,this.normal1=r,this.normal2=s}static fromRaw(e,t){if(!t)return null;const n=new eA(t.toi(),Pe.fromRaw(t.witness1()),Pe.fromRaw(t.witness2()),Pe.fromRaw(t.normal1()),Pe.fromRaw(t.normal2()));return t.free(),n}}class P2 extends eA{constructor(e,t,n,r,s,o){super(t,n,r,s,o),this.collider=e}static fromRaw(e,t){if(!t)return null;const n=new P2(e.get(t.colliderHandle()),t.toi(),Pe.fromRaw(t.witness1()),Pe.fromRaw(t.witness2()),Pe.fromRaw(t.normal1()),Pe.fromRaw(t.normal2()));return t.free(),n}}class sr{static fromRaw(e,t){const n=e.coShapeType(t);let r,s,o,a,l,c,u;switch(n){case Zt.Ball:return new v2(e.coRadius(t));case Zt.Cuboid:return r=e.coHalfExtents(t),new n5(r.x,r.y,r.z);case Zt.RoundCuboid:return r=e.coHalfExtents(t),s=e.coRoundRadius(t),new r5(r.x,r.y,r.z,s);case Zt.Capsule:return l=e.coHalfHeight(t),c=e.coRadius(t),new s5(l,c);case Zt.Segment:return o=e.coVertices(t),new o5(Pe.new(o[0],o[1],o[2]),Pe.new(o[3],o[4],o[5]));case Zt.Polyline:return o=e.coVertices(t),a=e.coIndices(t),new c5(o,a);case Zt.Triangle:return o=e.coVertices(t),new a5(Pe.new(o[0],o[1],o[2]),Pe.new(o[3],o[4],o[5]),Pe.new(o[6],o[7],o[8]));case Zt.RoundTriangle:return o=e.coVertices(t),s=e.coRoundRadius(t),new l5(Pe.new(o[0],o[1],o[2]),Pe.new(o[3],o[4],o[5]),Pe.new(o[6],o[7],o[8]),s);case Zt.HalfSpace:return u=Pe.fromRaw(e.coHalfspaceNormal(t)),new lue(u);case Zt.TriMesh:return o=e.coVertices(t),a=e.coIndices(t),new h5(o,a);case Zt.HeightField:const d=e.coHeightfieldScale(t),p=e.coHeightfieldHeights(t),f=e.coHeightfieldNRows(t),m=e.coHeightfieldNCols(t);return new u5(f,m,p,d);case Zt.ConvexPolyhedron:return o=e.coVertices(t),a=e.coIndices(t),new A2(o,a);case Zt.RoundConvexPolyhedron:return o=e.coVertices(t),a=e.coIndices(t),s=e.coRoundRadius(t),new y2(o,a,s);case Zt.Cylinder:return l=e.coHalfHeight(t),c=e.coRadius(t),new d5(l,c);case Zt.RoundCylinder:return l=e.coHalfHeight(t),c=e.coRadius(t),s=e.coRoundRadius(t),new p5(l,c,s);case Zt.Cone:return l=e.coHalfHeight(t),c=e.coRadius(t),new f5(l,c);case Zt.RoundCone:return l=e.coHalfHeight(t),c=e.coRadius(t),s=e.coRoundRadius(t),new m5(l,c,s);default:throw new Error("unknown shape type: "+n)}}castShape(e,t,n,r,s,o,a,l,c){let u=Pe.intoRaw(e),d=Bi.intoRaw(t),p=Pe.intoRaw(n),f=Pe.intoRaw(s),m=Bi.intoRaw(o),A=Pe.intoRaw(a),v=this.intoRaw(),g=r.intoRaw(),y=eA.fromRaw(null,v.castShape(u,d,p,g,f,m,A,l,c));return u.free(),d.free(),p.free(),f.free(),m.free(),A.free(),v.free(),g.free(),y}intersectsShape(e,t,n,r,s){let o=Pe.intoRaw(e),a=Bi.intoRaw(t),l=Pe.intoRaw(r),c=Bi.intoRaw(s),u=this.intoRaw(),d=n.intoRaw(),p=u.intersectsShape(o,a,d,l,c);return o.free(),a.free(),l.free(),c.free(),u.free(),d.free(),p}contactShape(e,t,n,r,s,o){let a=Pe.intoRaw(e),l=Bi.intoRaw(t),c=Pe.intoRaw(r),u=Bi.intoRaw(s),d=this.intoRaw(),p=n.intoRaw(),f=$0.fromRaw(d.contactShape(a,l,p,c,u,o));return a.free(),l.free(),c.free(),u.free(),d.free(),p.free(),f}containsPoint(e,t,n){let r=Pe.intoRaw(e),s=Bi.intoRaw(t),o=Pe.intoRaw(n),a=this.intoRaw(),l=a.containsPoint(r,s,o);return r.free(),s.free(),o.free(),a.free(),l}projectPoint(e,t,n,r){let s=Pe.intoRaw(e),o=Bi.intoRaw(t),a=Pe.intoRaw(n),l=this.intoRaw(),c=Hw.fromRaw(l.projectPoint(s,o,a,r));return s.free(),o.free(),a.free(),l.free(),c}intersectsRay(e,t,n,r){let s=Pe.intoRaw(t),o=Bi.intoRaw(n),a=Pe.intoRaw(e.origin),l=Pe.intoRaw(e.dir),c=this.intoRaw(),u=c.intersectsRay(s,o,a,l,r);return s.free(),o.free(),a.free(),l.free(),c.free(),u}castRay(e,t,n,r,s){let o=Pe.intoRaw(t),a=Bi.intoRaw(n),l=Pe.intoRaw(e.origin),c=Pe.intoRaw(e.dir),u=this.intoRaw(),d=u.castRay(o,a,l,c,r,s);return o.free(),a.free(),l.free(),c.free(),u.free(),d}castRayAndGetNormal(e,t,n,r,s){let o=Pe.intoRaw(t),a=Bi.intoRaw(n),l=Pe.intoRaw(e.origin),c=Pe.intoRaw(e.dir),u=this.intoRaw(),d=Vw.fromRaw(u.castRayAndGetNormal(o,a,l,c,r,s));return o.free(),a.free(),l.free(),c.free(),u.free(),d}}(function(i){i[i.Ball=0]="Ball",i[i.Cuboid=1]="Cuboid",i[i.Capsule=2]="Capsule",i[i.Segment=3]="Segment",i[i.Polyline=4]="Polyline",i[i.Triangle=5]="Triangle",i[i.TriMesh=6]="TriMesh",i[i.HeightField=7]="HeightField",i[i.ConvexPolyhedron=9]="ConvexPolyhedron",i[i.Cylinder=10]="Cylinder",i[i.Cone=11]="Cone",i[i.RoundCuboid=12]="RoundCuboid",i[i.RoundTriangle=13]="RoundTriangle",i[i.RoundCylinder=14]="RoundCylinder",i[i.RoundCone=15]="RoundCone",i[i.RoundConvexPolyhedron=16]="RoundConvexPolyhedron",i[i.HalfSpace=17]="HalfSpace"})(Zt||(Zt={}));class v2 extends sr{constructor(e){super(),this.type=Zt.Ball,this.radius=e}intoRaw(){return jt.ball(this.radius)}}class lue extends sr{constructor(e){super(),this.type=Zt.HalfSpace,this.normal=e}intoRaw(){let e=Pe.intoRaw(this.normal),t=jt.halfspace(e);return e.free(),t}}class n5 extends sr{constructor(e,t,n){super(),this.type=Zt.Cuboid,this.halfExtents=Pe.new(e,t,n)}intoRaw(){return jt.cuboid(this.halfExtents.x,this.halfExtents.y,this.halfExtents.z)}}class r5 extends sr{constructor(e,t,n,r){super(),this.type=Zt.RoundCuboid,this.halfExtents=Pe.new(e,t,n),this.borderRadius=r}intoRaw(){return jt.roundCuboid(this.halfExtents.x,this.halfExtents.y,this.halfExtents.z,this.borderRadius)}}class s5 extends sr{constructor(e,t){super(),this.type=Zt.Capsule,this.halfHeight=e,this.radius=t}intoRaw(){return jt.capsule(this.halfHeight,this.radius)}}class o5 extends sr{constructor(e,t){super(),this.type=Zt.Segment,this.a=e,this.b=t}intoRaw(){let e=Pe.intoRaw(this.a),t=Pe.intoRaw(this.b),n=jt.segment(e,t);return e.free(),t.free(),n}}class a5 extends sr{constructor(e,t,n){super(),this.type=Zt.Triangle,this.a=e,this.b=t,this.c=n}intoRaw(){let e=Pe.intoRaw(this.a),t=Pe.intoRaw(this.b),n=Pe.intoRaw(this.c),r=jt.triangle(e,t,n);return e.free(),t.free(),n.free(),r}}class l5 extends sr{constructor(e,t,n,r){super(),this.type=Zt.RoundTriangle,this.a=e,this.b=t,this.c=n,this.borderRadius=r}intoRaw(){let e=Pe.intoRaw(this.a),t=Pe.intoRaw(this.b),n=Pe.intoRaw(this.c),r=jt.roundTriangle(e,t,n,this.borderRadius);return e.free(),t.free(),n.free(),r}}class c5 extends sr{constructor(e,t){super(),this.type=Zt.Polyline,this.vertices=e,this.indices=t??new Uint32Array(0)}intoRaw(){return jt.polyline(this.vertices,this.indices)}}class h5 extends sr{constructor(e,t){super(),this.type=Zt.TriMesh,this.vertices=e,this.indices=t}intoRaw(){return jt.trimesh(this.vertices,this.indices)}}class A2 extends sr{constructor(e,t){super(),this.type=Zt.ConvexPolyhedron,this.vertices=e,this.indices=t}intoRaw(){return this.indices?jt.convexMesh(this.vertices,this.indices):jt.convexHull(this.vertices)}}class y2 extends sr{constructor(e,t,n){super(),this.type=Zt.RoundConvexPolyhedron,this.vertices=e,this.indices=t,this.borderRadius=n}intoRaw(){return this.indices?jt.roundConvexMesh(this.vertices,this.indices,this.borderRadius):jt.roundConvexHull(this.vertices,this.borderRadius)}}class u5 extends sr{constructor(e,t,n,r){super(),this.type=Zt.HeightField,this.nrows=e,this.ncols=t,this.heights=n,this.scale=r}intoRaw(){let e=Pe.intoRaw(this.scale),t=jt.heightfield(this.nrows,this.ncols,this.heights,e);return e.free(),t}}class d5 extends sr{constructor(e,t){super(),this.type=Zt.Cylinder,this.halfHeight=e,this.radius=t}intoRaw(){return jt.cylinder(this.halfHeight,this.radius)}}class p5 extends sr{constructor(e,t,n){super(),this.type=Zt.RoundCylinder,this.borderRadius=n,this.halfHeight=e,this.radius=t}intoRaw(){return jt.roundCylinder(this.halfHeight,this.radius,this.borderRadius)}}class f5 extends sr{constructor(e,t){super(),this.type=Zt.Cone,this.halfHeight=e,this.radius=t}intoRaw(){return jt.cone(this.halfHeight,this.radius)}}class m5 extends sr{constructor(e,t,n){super(),this.type=Zt.RoundCone,this.halfHeight=e,this.radius=t,this.borderRadius=n}intoRaw(){return jt.roundCone(this.halfHeight,this.radius,this.borderRadius)}}(function(i){i[i.DYNAMIC_DYNAMIC=1]="DYNAMIC_DYNAMIC",i[i.DYNAMIC_KINEMATIC=12]="DYNAMIC_KINEMATIC",i[i.DYNAMIC_FIXED=2]="DYNAMIC_FIXED",i[i.KINEMATIC_KINEMATIC=52224]="KINEMATIC_KINEMATIC",i[i.KINEMATIC_FIXED=8704]="KINEMATIC_FIXED",i[i.FIXED_FIXED=32]="FIXED_FIXED",i[i.DEFAULT=15]="DEFAULT",i[i.ALL=60943]="ALL"})(Cw||(Cw={}));class g5{constructor(e,t,n,r){this.colliderSet=e,this.handle=t,this._parent=n,this._shape=r}finalizeDeserialization(e){this.handle!=null&&(this._parent=e.get(this.colliderSet.raw.coParent(this.handle)))}ensureShapeIsCached(){this._shape||(this._shape=sr.fromRaw(this.colliderSet.raw,this.handle))}get shape(){return this.ensureShapeIsCached(),this._shape}isValid(){return this.colliderSet.raw.contains(this.handle)}translation(){return Pe.fromRaw(this.colliderSet.raw.coTranslation(this.handle))}rotation(){return Bi.fromRaw(this.colliderSet.raw.coRotation(this.handle))}isSensor(){return this.colliderSet.raw.coIsSensor(this.handle)}setSensor(e){this.colliderSet.raw.coSetSensor(this.handle,e)}setShape(e){let t=e.intoRaw();this.colliderSet.raw.coSetShape(this.handle,t),t.free(),this._shape=e}setEnabled(e){this.colliderSet.raw.coSetEnabled(this.handle,e)}isEnabled(){return this.colliderSet.raw.coIsEnabled(this.handle)}setRestitution(e){this.colliderSet.raw.coSetRestitution(this.handle,e)}setFriction(e){this.colliderSet.raw.coSetFriction(this.handle,e)}frictionCombineRule(){return this.colliderSet.raw.coFrictionCombineRule(this.handle)}setFrictionCombineRule(e){this.colliderSet.raw.coSetFrictionCombineRule(this.handle,e)}restitutionCombineRule(){return this.colliderSet.raw.coRestitutionCombineRule(this.handle)}setRestitutionCombineRule(e){this.colliderSet.raw.coSetRestitutionCombineRule(this.handle,e)}setCollisionGroups(e){this.colliderSet.raw.coSetCollisionGroups(this.handle,e)}setSolverGroups(e){this.colliderSet.raw.coSetSolverGroups(this.handle,e)}activeHooks(){return this.colliderSet.raw.coActiveHooks(this.handle)}setActiveHooks(e){this.colliderSet.raw.coSetActiveHooks(this.handle,e)}activeEvents(){return this.colliderSet.raw.coActiveEvents(this.handle)}setActiveEvents(e){this.colliderSet.raw.coSetActiveEvents(this.handle,e)}activeCollisionTypes(){return this.colliderSet.raw.coActiveCollisionTypes(this.handle)}setContactForceEventThreshold(e){return this.colliderSet.raw.coSetContactForceEventThreshold(this.handle,e)}contactForceEventThreshold(){return this.colliderSet.raw.coContactForceEventThreshold(this.handle)}setActiveCollisionTypes(e){this.colliderSet.raw.coSetActiveCollisionTypes(this.handle,e)}setDensity(e){this.colliderSet.raw.coSetDensity(this.handle,e)}setMass(e){this.colliderSet.raw.coSetMass(this.handle,e)}setMassProperties(e,t,n,r){let s=Pe.intoRaw(t),o=Pe.intoRaw(n),a=Bi.intoRaw(r);this.colliderSet.raw.coSetMassProperties(this.handle,e,s,o,a),s.free(),o.free(),a.free()}setTranslation(e){this.colliderSet.raw.coSetTranslation(this.handle,e.x,e.y,e.z)}setTranslationWrtParent(e){this.colliderSet.raw.coSetTranslationWrtParent(this.handle,e.x,e.y,e.z)}setRotation(e){this.colliderSet.raw.coSetRotation(this.handle,e.x,e.y,e.z,e.w)}setRotationWrtParent(e){this.colliderSet.raw.coSetRotationWrtParent(this.handle,e.x,e.y,e.z,e.w)}shapeType(){return this.colliderSet.raw.coShapeType(this.handle)}halfExtents(){return Pe.fromRaw(this.colliderSet.raw.coHalfExtents(this.handle))}setHalfExtents(e){const t=Pe.intoRaw(e);this.colliderSet.raw.coSetHalfExtents(this.handle,t)}radius(){return this.colliderSet.raw.coRadius(this.handle)}setRadius(e){this.colliderSet.raw.coSetRadius(this.handle,e)}roundRadius(){return this.colliderSet.raw.coRoundRadius(this.handle)}setRoundRadius(e){this.colliderSet.raw.coSetRoundRadius(this.handle,e)}halfHeight(){return this.colliderSet.raw.coHalfHeight(this.handle)}setHalfHeight(e){this.colliderSet.raw.coSetHalfHeight(this.handle,e)}vertices(){return this.colliderSet.raw.coVertices(this.handle)}indices(){return this.colliderSet.raw.coIndices(this.handle)}heightfieldHeights(){return this.colliderSet.raw.coHeightfieldHeights(this.handle)}heightfieldScale(){let e=this.colliderSet.raw.coHeightfieldScale(this.handle);return Pe.fromRaw(e)}heightfieldNRows(){return this.colliderSet.raw.coHeightfieldNRows(this.handle)}heightfieldNCols(){return this.colliderSet.raw.coHeightfieldNCols(this.handle)}parent(){return this._parent}friction(){return this.colliderSet.raw.coFriction(this.handle)}restitution(){return this.colliderSet.raw.coRestitution(this.handle)}density(){return this.colliderSet.raw.coDensity(this.handle)}mass(){return this.colliderSet.raw.coMass(this.handle)}volume(){return this.colliderSet.raw.coVolume(this.handle)}collisionGroups(){return this.colliderSet.raw.coCollisionGroups(this.handle)}solverGroups(){return this.colliderSet.raw.coSolverGroups(this.handle)}containsPoint(e){let t=Pe.intoRaw(e),n=this.colliderSet.raw.coContainsPoint(this.handle,t);return t.free(),n}projectPoint(e,t){let n=Pe.intoRaw(e),r=Hw.fromRaw(this.colliderSet.raw.coProjectPoint(this.handle,n,t));return n.free(),r}intersectsRay(e,t){let n=Pe.intoRaw(e.origin),r=Pe.intoRaw(e.dir),s=this.colliderSet.raw.coIntersectsRay(this.handle,n,r,t);return n.free(),r.free(),s}castShape(e,t,n,r,s,o,a){let l=Pe.intoRaw(e),c=Pe.intoRaw(n),u=Bi.intoRaw(r),d=Pe.intoRaw(s),p=t.intoRaw(),f=eA.fromRaw(this.colliderSet,this.colliderSet.raw.coCastShape(this.handle,l,p,c,u,d,o,a));return l.free(),c.free(),u.free(),d.free(),p.free(),f}castCollider(e,t,n,r,s){let o=Pe.intoRaw(e),a=Pe.intoRaw(n),l=P2.fromRaw(this.colliderSet,this.colliderSet.raw.coCastCollider(this.handle,o,t.handle,a,r,s));return o.free(),a.free(),l}intersectsShape(e,t,n){let r=Pe.intoRaw(t),s=Bi.intoRaw(n),o=e.intoRaw(),a=this.colliderSet.raw.coIntersectsShape(this.handle,o,r,s);return r.free(),s.free(),o.free(),a}contactShape(e,t,n,r){let s=Pe.intoRaw(t),o=Bi.intoRaw(n),a=e.intoRaw(),l=$0.fromRaw(this.colliderSet.raw.coContactShape(this.handle,a,s,o,r));return s.free(),o.free(),a.free(),l}contactCollider(e,t){return $0.fromRaw(this.colliderSet.raw.coContactCollider(this.handle,e.handle,t))}castRay(e,t,n){let r=Pe.intoRaw(e.origin),s=Pe.intoRaw(e.dir),o=this.colliderSet.raw.coCastRay(this.handle,r,s,t,n);return r.free(),s.free(),o}castRayAndGetNormal(e,t,n){let r=Pe.intoRaw(e.origin),s=Pe.intoRaw(e.dir),o=Vw.fromRaw(this.colliderSet.raw.coCastRayAndGetNormal(this.handle,r,s,t,n));return r.free(),s.free(),o}}(function(i){i[i.Density=0]="Density",i[i.Mass=1]="Mass",i[i.MassProps=2]="MassProps"})(Yf||(Yf={}));class Yi{constructor(e){this.enabled=!0,this.shape=e,this.massPropsMode=Yf.Density,this.density=1,this.friction=.5,this.restitution=0,this.rotation=Bi.identity(),this.translation=Pe.zeros(),this.isSensor=!1,this.collisionGroups=4294967295,this.solverGroups=4294967295,this.frictionCombineRule=Ln.Average,this.restitutionCombineRule=Ln.Average,this.activeCollisionTypes=Cw.DEFAULT,this.activeEvents=0,this.activeHooks=0,this.mass=0,this.centerOfMass=Pe.zeros(),this.contactForceEventThreshold=0,this.principalAngularInertia=Pe.zeros(),this.angularInertiaLocalFrame=Bi.identity()}static ball(e){const t=new v2(e);return new Yi(t)}static capsule(e,t){const n=new s5(e,t);return new Yi(n)}static segment(e,t){const n=new o5(e,t);return new Yi(n)}static triangle(e,t,n){const r=new a5(e,t,n);return new Yi(r)}static roundTriangle(e,t,n,r){const s=new l5(e,t,n,r);return new Yi(s)}static polyline(e,t){const n=new c5(e,t);return new Yi(n)}static trimesh(e,t){const n=new h5(e,t);return new Yi(n)}static cuboid(e,t,n){const r=new n5(e,t,n);return new Yi(r)}static roundCuboid(e,t,n,r){const s=new r5(e,t,n,r);return new Yi(s)}static heightfield(e,t,n,r){const s=new u5(e,t,n,r);return new Yi(s)}static cylinder(e,t){const n=new d5(e,t);return new Yi(n)}static roundCylinder(e,t,n){const r=new p5(e,t,n);return new Yi(r)}static cone(e,t){const n=new f5(e,t);return new Yi(n)}static roundCone(e,t,n){const r=new m5(e,t,n);return new Yi(r)}static convexHull(e){const t=new A2(e,null);return new Yi(t)}static convexMesh(e,t){const n=new A2(e,t);return new Yi(n)}static roundConvexHull(e,t){const n=new y2(e,null,t);return new Yi(n)}static roundConvexMesh(e,t,n){const r=new y2(e,t,n);return new Yi(r)}setTranslation(e,t,n){if(typeof e!="number"||typeof t!="number"||typeof n!="number")throw TypeError("The translation components must be numbers.");return this.translation={x:e,y:t,z:n},this}setRotation(e){return Bi.copy(this.rotation,e),this}setSensor(e){return this.isSensor=e,this}setEnabled(e){return this.enabled=e,this}setDensity(e){return this.massPropsMode=Yf.Density,this.density=e,this}setMass(e){return this.massPropsMode=Yf.Mass,this.mass=e,this}setMassProperties(e,t,n,r){return this.massPropsMode=Yf.MassProps,this.mass=e,Pe.copy(this.centerOfMass,t),Pe.copy(this.principalAngularInertia,n),Bi.copy(this.angularInertiaLocalFrame,r),this}setRestitution(e){return this.restitution=e,this}setFriction(e){return this.friction=e,this}setFrictionCombineRule(e){return this.frictionCombineRule=e,this}setRestitutionCombineRule(e){return this.restitutionCombineRule=e,this}setCollisionGroups(e){return this.collisionGroups=e,this}setSolverGroups(e){return this.solverGroups=e,this}setActiveHooks(e){return this.activeHooks=e,this}setActiveEvents(e){return this.activeEvents=e,this}setActiveCollisionTypes(e){return this.activeCollisionTypes=e,this}setContactForceEventThreshold(e){return this.contactForceEventThreshold=e,this}}(function(i){i[i.EXCLUDE_FIXED=1]="EXCLUDE_FIXED",i[i.EXCLUDE_KINEMATIC=2]="EXCLUDE_KINEMATIC",i[i.EXCLUDE_DYNAMIC=4]="EXCLUDE_DYNAMIC",i[i.EXCLUDE_SENSORS=8]="EXCLUDE_SENSORS",i[i.EXCLUDE_SOLIDS=16]="EXCLUDE_SOLIDS",i[i.ONLY_DYNAMIC=3]="ONLY_DYNAMIC",i[i.ONLY_KINEMATIC=5]="ONLY_KINEMATIC",i[i.ONLY_FIXED=6]="ONLY_FIXED"})($j||($j={})),function(i){i[i.COLLISION_EVENTS=1]="COLLISION_EVENTS",i[i.CONTACT_FORCE_EVENTS=2]="CONTACT_FORCE_EVENTS"}(g2||(g2={}));class cue{free(){this.raw&&this.raw.free(),this.raw=void 0}collider1(){return this.raw.collider1()}collider2(){return this.raw.collider2()}totalForce(){return Pe.fromRaw(this.raw.total_force())}totalForceMagnitude(){return this.raw.total_force_magnitude()}maxForceDirection(){return Pe.fromRaw(this.raw.max_force_direction())}maxForceMagnitude(){return this.raw.max_force_magnitude()}}class hue{constructor(e,t){this.raw=t||new Qw(e)}free(){this.raw&&this.raw.free(),this.raw=void 0}drainCollisionEvents(e){this.raw.drainCollisionEvents(e)}drainContactForceEvents(e){let t=new cue;this.raw.drainContactForceEvents(n=>{t.raw=n,e(t),t.free()})}clear(){this.raw.clear()}}(function(i){i[i.FILTER_CONTACT_PAIRS=1]="FILTER_CONTACT_PAIRS",i[i.FILTER_INTERSECTION_PAIRS=2]="FILTER_INTERSECTION_PAIRS"})(e5||(e5={})),function(i){i[i.EMPTY=0]="EMPTY",i[i.COMPUTE_IMPULSE=1]="COMPUTE_IMPULSE"}(t5||(t5={}));for(var Iue={byteLength:function(i){var e=v5(i),t=e[0],n=e[1];return 3*(t+n)/4-n},toByteArray:function(i){var e,t,n=v5(i),r=n[0],s=n[1],o=new uue(function(c,u,d){return 3*(u+d)/4-d}(0,r,s)),a=0,l=s>0?r-4:r;for(t=0;t<l;t+=4)e=Vo[i.charCodeAt(t)]<<18|Vo[i.charCodeAt(t+1)]<<12|Vo[i.charCodeAt(t+2)]<<6|Vo[i.charCodeAt(t+3)],o[a++]=e>>16&255,o[a++]=e>>8&255,o[a++]=255&e;return s===2&&(e=Vo[i.charCodeAt(t)]<<2|Vo[i.charCodeAt(t+1)]>>4,o[a++]=255&e),s===1&&(e=Vo[i.charCodeAt(t)]<<10|Vo[i.charCodeAt(t+1)]<<4|Vo[i.charCodeAt(t+2)]>>2,o[a++]=e>>8&255,o[a++]=255&e),o},fromByteArray:function(i){for(var e,t=i.length,n=t%3,r=[],s=16383,o=0,a=t-n;o<a;o+=s)r.push(pue(i,o,o+s>a?a:o+s));return n===1?(e=i[t-1],r.push(ml[e>>2]+ml[e<<4&63]+"==")):n===2&&(e=(i[t-2]<<8)+i[t-1],r.push(ml[e>>10]+ml[e>>4&63]+ml[e<<2&63]+"=")),r.join("")}},ml=[],Vo=[],uue=typeof Uint8Array<"u"?Uint8Array:Array,b2="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Jf=0,due=b2.length;Jf<due;++Jf)ml[Jf]=b2[Jf],Vo[b2.charCodeAt(Jf)]=Jf;function v5(i){var e=i.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var t=i.indexOf("=");return t===-1&&(t=e),[t,t===e?0:4-t%4]}function pue(i,e,t){for(var n,r,s=[],o=e;o<t;o+=3)n=(i[o]<<16&16711680)+(i[o+1]<<8&65280)+(255&i[o+2]),s.push(ml[(r=n)>>18&63]+ml[r>>12&63]+ml[r>>6&63]+ml[63&r]);return s.join("")}Vo["-".charCodeAt(0)]=62,Vo["_".charCodeAt(0)]=63;const fue=Symbol("object"),_2=new bo(()=>new S,20);class A5{constructor(e,t,n,r,s,o){h(this,"_point"),h(this,"_normal"),h(this,"_tangentVelocity"),h(this,"distance"),h(this,"impulse"),h(this,"friction"),this._point=e,this.distance=t,this._normal=n,this.impulse=r,this.friction=s,this._tangentVelocity=o}get point(){return _2.get().set(this._point.x,this._point.y,this._point.z)}get normal(){return _2.get().set(this._normal.x,this._normal.y,this._normal.z)}get tangentVelocity(){return _2.get().set(this._tangentVelocity.x,this._tangentVelocity.y,this._tangentVelocity.z)}}class y5{constructor(e,t,n){h(this,"contacts"),h(this,"me"),h(this,"_collider"),h(this,"_gameObject"),this.me=e,this._collider=t,this._gameObject=t.gameObject,this.contacts=n}get collider(){return this._collider}get gameObject(){return this._gameObject}get rigidBody(){var e;return(e=this.collider)==null?void 0:e.attachedRigidbody}}class b5{constructor(e,t){h(this,"object"),h(this,"collider"),this.object=e,this.collider=t}}const es=ee("debugphysics"),x2=ee("debugcolliderplacement"),w2=ee("debugcollisions"),mue=ee("showcolliders"),S2=ee("debugraycasts"),Ns=Symbol("needle component"),Ss=Symbol("physics body"),_5=Symbol("rigidbody");let Kf;globalThis.false=globalThis.false!==void 0?globalThis.false:!0,es&&console.log("Use Rapier",!1,globalThis.false);const Ew=class{constructor(){h(this,"debugRenderColliders",!1),h(this,"debugRenderRaycasts",!1),h(this,"context"),h(this,"_initializePromise"),h(this,"_isInitialized",!1),h(this,"rapierRay",new aue({x:0,y:0,z:0},{x:0,y:0,z:1})),h(this,"raycastVectorsBuffer",new bo(()=>new S,10)),h(this,"rapierSphere",null),h(this,"rapierColliderArray",[]),h(this,"rapierIdentityRotation",{x:0,y:0,z:0,w:1}),h(this,"rapierForwardVector",{x:0,y:0,z:1}),h(this,"enabled",!1),h(this,"_tempPosition",new S),h(this,"_tempQuaternion",new Me),h(this,"_tempScale",new S),h(this,"_tempMatrix",new Ce),h(this,"_isUpdatingPhysicsWorld",!1),h(this,"_world"),h(this,"_hasCreatedWorld",!1),h(this,"eventQueue"),h(this,"collisionHandler"),h(this,"objects",[]),h(this,"bodies",[]),h(this,"_meshCache",new Map),h(this,"_gravity",{x:0,y:-9.81,z:0}),h(this,"lines"),h(this,"_tempCenterPos",new S),h(this,"_tempCenterVec",new S),h(this,"_tempCenterQuaternion",new Me)}removeBody(i){var e,t,n;if(!i)return;this.validate();const r=i[Ss];if(i[Ss]=null,r&&this.world){const s=this.objects.findIndex(o=>o===i);if(s>=0){const o=this.bodies[s];if(this.bodies.splice(s,1),this.objects.splice(s,1),o instanceof g5){const a=o;(e=this.world)==null||e.removeCollider(a,!0);const l=a.parent();l&&l.numColliders()<=0&&(l[Ns]||(t=this.world)==null||t.removeRigidBody(l))}else o instanceof i5&&(o.numColliders()<=0?(n=this.world)==null||n.removeRigidBody(o):pt()&&(o.did_log_removing||setTimeout(()=>{o.numColliders()>0&&(o.did_log_removing=!0,console.warn("RapierPhysics: removing rigidbody with colliders from the physics world is not possible right now, please remove the colliders first"))},1)))}}}updateBody(i,e,t){if(this.validate(),!!this.enabled&&!(i.destroyed||!i.gameObject)&&!(!e&&!t))if(i.isCollider===!0)console.warn("TODO: implement updating collider position");else{const n=i,r=n[Ss];r&&this.syncPhysicsBody(n.gameObject,r,e,t)}}updateProperties(i){if(this.validate(),i.isCollider){const e=i,t=e[Ss];t&&(this.internalUpdateColliderProperties(e,t),e.sharedMaterial&&this.updatePhysicsMaterial(e))}else{const e=i,t=this.internal_getRigidbody(e);t&&this.internalUpdateRigidbodyProperties(e,t)}}addForce(i,e,t){this.validate();const n=this.internal_getRigidbody(i);n?n.addForce(e,t):console.warn("Rigidbody doesn't exist: can not apply force")}addImpulse(i,e,t){this.validate();const n=this.internal_getRigidbody(i);n?n.applyImpulse(e,t):console.warn("Rigidbody doesn't exist: can not apply impulse")}getLinearVelocity(i){this.validate();const e=this.internal_getRigidbody(i);return e?e.linvel():null}getAngularVelocity(i){this.validate();const e=this.internal_getRigidbody(i);return e?e.angvel():null}resetForces(i,e){this.validate();const t=this.internal_getRigidbody(i);t?.resetForces(e)}resetTorques(i,e){this.validate();const t=this.internal_getRigidbody(i);t?.resetTorques(e)}applyImpulse(i,e,t){this.validate();const n=this.internal_getRigidbody(i);n?n.applyImpulse(e,t):console.warn("Rigidbody doesn't exist: can not apply impulse")}wakeup(i){this.validate();const e=this.internal_getRigidbody(i);e?e.wakeUp():console.warn("Rigidbody doesn't exist: can not wake up")}isSleeping(i){this.validate();const e=this.internal_getRigidbody(i);return e?.isSleeping()}setAngularVelocity(i,e,t){this.validate();const n=this.internal_getRigidbody(i);n?n.setAngvel(e,t):console.warn("Rigidbody doesn't exist: can not set angular velocity")}setLinearVelocity(i,e,t){this.validate();const n=this.internal_getRigidbody(i);n?n.setLinvel(e,t):console.warn("Rigidbody doesn't exist: can not set linear velocity")}async initialize(i){return this.context=i,this._initializePromise||(this._initializePromise=this.internalInitialization()),this._initializePromise}async internalInitialization(){return es&&console.log("Initialize rapier physics engine"),"env"in import.meta&&{}.VITE_NEEDLE_USE_RAPIER==="false"&&es&&console.log("Rapier disabled"),!1}validate(){this._isInitialized||es&&(this._lastWarnTime=this._lastWarnTime??0,Date.now()-this._lastWarnTime>1e3&&(this._lastWarnTime=Date.now(),console.warn("Physics engine is not initialized")))}raycast(i,e,t,n){var r;t===void 0&&(t=1/0),n===void 0&&(n=!0);const s=this.getPhysicsRay(this.rapierRay,i,e);if(!s)return null;(this.debugRenderRaycasts||S2)&&Ct.DrawRay(s.origin,s.dir,255,1);const o=(r=this.world)==null?void 0:r.castRay(s,t,n,void 0,void 0,void 0,void 0,a=>{var l;return!((l=a[Ns])!=null&&l.gameObject.layers.isEnabled(2))});if(o){const a=s.pointAt(o.toi),l=this.raycastVectorsBuffer.get();return l.set(a.x,a.y,a.z),{point:l,collider:o.collider[Ns]}}return null}raycastAndGetNormal(i,e,t,n){var r;t===void 0&&(t=1/0),n===void 0&&(n=!0);const s=this.getPhysicsRay(this.rapierRay,i,e);if(!s)return null;(this.debugRenderRaycasts||S2)&&Ct.DrawRay(s.origin,s.dir,255,1);const o=(r=this.world)==null?void 0:r.castRayAndGetNormal(s,t,n,void 0,void 0,void 0,void 0,a=>{var l;return!((l=a[Ns])!=null&&l.gameObject.layers.isEnabled(2))});if(o){const a=s.pointAt(o.toi),l=o.normal,c=this.raycastVectorsBuffer.get(),u=this.raycastVectorsBuffer.get();return c.set(a.x,a.y,a.z),u.set(l.x,l.y,l.z),{point:c,normal:u,collider:o.collider[Ns]}}return null}getPhysicsRay(i,e,t){var n,r,s;const o=(n=this.context)==null?void 0:n.mainCamera;if(e===void 0){const c=(r=this.context)==null?void 0:r.input.getPointerPosition(0);if(c)e=c;else return null}if(e.z===void 0){if(!o)return console.error("Can not perform raycast from 2d point - no main camera found"),null;const c=this.raycastVectorsBuffer.get();c.x=e.x,c.y=e.y,c.z=0,(c.x>1||c.y>1||c.y<-1||c.x<-1)&&(es&&console.warn("Converting screenspace to raycast space",c),(s=this.context)==null||s.input.convertScreenspaceToRaycastSpace(c)),c.unproject(o),e=c}const a=e;i.origin.x=a.x,i.origin.y=a.y,i.origin.z=a.z;const l=this.raycastVectorsBuffer.get();if(t)l.set(t.x,t.y,t.z);else{if(!o)return console.error("Can not perform raycast - no camera found"),null;l.set(i.origin.x,i.origin.y,i.origin.z);const c=Rt(o);l.sub(c)}return l.normalize(),i.dir.x=l.x,i.dir.y=l.y,i.dir.z=l.z,i}sphereOverlap(i,e){return this.rapierColliderArray.length=0,this.world?(this.rapierSphere||(this.rapierSphere=new v2(e)),this.rapierSphere.radius=e,(this.debugRenderRaycasts||S2)&&Ct.DrawWireSphere(i,e,3359999,1),this.world.intersectionsWithShape(i,this.rapierIdentityRotation,this.rapierSphere,t=>{const n=t[Ns],r=new b5(n.gameObject,n);return this.rapierColliderArray.push(r),!0},void 0,void 0,void 0,void 0,t=>t.isSensor()?!1:t[Ns].gameObject.layers.isEnabled(2)==!1),this.rapierColliderArray):this.rapierColliderArray}get world(){return this._world}get isUpdating(){return this._isUpdatingPhysicsWorld}get gravity(){var i;return((i=this.world)==null?void 0:i.gravity)??this._gravity}set gravity(i){this.world?this.world.gravity=i:this._gravity=i}clearCaches(){var i,e,t,n;this._meshCache.clear(),(i=this.eventQueue)!=null&&i.raw&&((e=this.eventQueue)==null||e.free()),(t=this.world)!=null&&t.bodies&&((n=this.world)==null||n.free())}async addBoxCollider(i,e){if(this._isInitialized||await this.initialize(i.context),!i.activeAndEnabled)return;if(!this.enabled){es&&console.warn("Physics are disabled");return}const t=i.gameObject,n=ki(t,this._tempPosition).multiply(e);n.multiplyScalar(.5),n.x<0&&(n.x=Math.abs(n.x)),n.y<0&&(n.y=Math.abs(n.y)),n.z<0&&(n.z=Math.abs(n.z)),n.x==0&&(n.x=1e-7),n.y==0&&(n.y=1e-7),n.z==0&&(n.z=1e-7);const r=Yi.cuboid(n.x,n.y,n.z);this.createCollider(i,r)}async addSphereCollider(i){if(this._isInitialized||await this.initialize(i.context),!i.activeAndEnabled)return;if(!this.enabled){es&&console.warn("Physics are disabled");return}const e=Yi.ball(.5);this.createCollider(i,e),this.updateProperties(i)}async addCapsuleCollider(i,e,t){if(this._isInitialized||await this.initialize(i.context),!i.activeAndEnabled)return;if(!this.enabled){es&&console.warn("Physics are disabled");return}const n=i.gameObject,r=ki(n,this._tempPosition);r.x=Math.abs(r.x),r.y=Math.abs(r.y);const s=t*r.x;e=Math.max(e,s*2);const o=Ze.clamp(e*.5*r.y-t*r.x,0,Number.MAX_SAFE_INTEGER),a=Yi.capsule(o,s);this.createCollider(i,a)}async addMeshCollider(i,e,t,n){var r,s,o;if(this._isInitialized||await this.initialize(i.context),!i.activeAndEnabled)return;if(!this.enabled){es&&console.warn("Physics are disabled");return}let a=e.geometry;if(!a){es&&console.warn("Missing mesh geometry",e.name);return}(s=(r=a.index)==null?void 0:r.array)!=null&&s.length||(console.warn(`Your MeshCollider is missing vertices or indices in the assined mesh "${e.name}". Consider providing an indexed geometry.`),a=$ee(a));let l=a.getAttribute("position").array;const c=(o=a.index)==null?void 0:o.array;if(Math.abs(n.x-1)>1e-4||Math.abs(n.y-1)>1e-4||Math.abs(n.z-1)>1e-4){const d=a.uuid+"_"+n.x+"_"+n.y+"_"+n.z+"_"+t;if(this._meshCache.has(d))es&&console.warn("Use cached mesh collider"),l=this._meshCache.get(d);else{console.warn(`Your MeshCollider "${i.name}" is scaled (${n.x}, ${n.y}, ${n.z})
7443
7443
  this is not optimal for performance since this isn't supported by the Rapier physics engine yet. Consider applying the scale to the collider mesh`);const p=new Float32Array(l.length);for(let f=0;f<l.length;f+=3)p[f]=l[f]*n.x,p[f+1]=l[f+1]*n.y,p[f+2]=l[f+2]*n.z;l=p,this._meshCache.set(d,p)}}const u=t?Yi.convexHull(l):Yi.trimesh(l,c);u&&this.createCollider(i,u)}updatePhysicsMaterial(i){if(!i)return;const e=i.sharedMaterial,t=i[Ss];if(t&&e){if(e.bounciness!==void 0&&t.setRestitution(e.bounciness),e.bounceCombine!==void 0)switch(e.bounceCombine){case tr.Average:t.setRestitutionCombineRule(Ln.Average);break;case tr.Maximum:t.setRestitutionCombineRule(Ln.Max);break;case tr.Minimum:t.setRestitutionCombineRule(Ln.Min);break;case tr.Multiply:t.setRestitutionCombineRule(Ln.Multiply);break}if(e.dynamicFriction!==void 0&&t.setFriction(e.dynamicFriction),e.frictionCombine!==void 0)switch(e.frictionCombine){case tr.Average:t.setFrictionCombineRule(Ln.Average);break;case tr.Maximum:t.setFrictionCombineRule(Ln.Max);break;case tr.Minimum:t.setFrictionCombineRule(Ln.Min);break;case tr.Multiply:t.setFrictionCombineRule(Ln.Multiply);break}}}getBody(i){return i?i[Ss]:null}getComponent(i){return i?i[Ns]:null}createCollider(i,e){var t;if(!this.world)throw new Error("Physics world not initialized");const n=this._tempMatrix;let r;i.attachedRigidbody?r=this.getRigidbody(i,this._tempMatrix):(es&&console.log("Create collider without rigidbody",i.name),n.makeRotationFromQuaternion(xi(i.gameObject)),n.setPosition(Rt(i.gameObject))),n.decompose(this._tempPosition,this._tempQuaternion,this._tempScale),this.tryApplyCenter(i,this._tempPosition),e.setTranslation(this._tempPosition.x,this._tempPosition.y,this._tempPosition.z),e.setRotation(this._tempQuaternion),e.setSensor(i.isTrigger);const s=i.sharedMaterial;if(s){if(s.bounciness!==void 0&&e.setRestitution(s.bounciness),s.bounceCombine!==void 0)switch(s.bounceCombine){case tr.Average:e.setRestitutionCombineRule(Ln.Average);break;case tr.Maximum:e.setRestitutionCombineRule(Ln.Max);break;case tr.Minimum:e.setRestitutionCombineRule(Ln.Min);break;case tr.Multiply:e.setRestitutionCombineRule(Ln.Multiply);break}if(s.dynamicFriction!==void 0&&e.setFriction(s.dynamicFriction),s.frictionCombine!==void 0)switch(s.frictionCombine){case tr.Average:e.setFrictionCombineRule(Ln.Average);break;case tr.Maximum:e.setFrictionCombineRule(Ln.Max);break;case tr.Minimum:e.setFrictionCombineRule(Ln.Min);break;case tr.Multiply:e.setFrictionCombineRule(Ln.Multiply);break}}((t=i.attachedRigidbody)==null?void 0:t.autoMass)===!1&&(e.setDensity(1e-6),e.setMass(1e-6));try{const o=this.world.createCollider(e,r);return o[Ns]=i,i[Ss]=o,o.setActiveEvents(g2.COLLISION_EVENTS),o.setActiveCollisionTypes(Cw.ALL),this.objects.push(i),this.bodies.push(o),this.updateColliderCollisionGroups(i),o}catch(o){return console.error('Error creating collider "'+i.name+`"
7444
- Error:`,o),null}}updateColliderCollisionGroups(i){const e=i[Ss],t=i.membership;let n=0;if(t==null)n=4294967295;else for(let o=0;o<t.length;o++){const a=t[o];n|=1<<a}const r=i.filter;let s=0;if(r==null)s=4294967295;else for(let o=0;o<r.length;o++){const a=r[o];s|=1<<a}e.setCollisionGroups(n<<16|s)}getRigidbody(i,e){if(!this.world)throw new Error("Physics world not initialized");let t=null;if(i.attachedRigidbody){const n=i.attachedRigidbody;if(t=n[Ss],!t){const r=n.isKinematic&&!x2;es&&console.log("Create rigidbody",r);const s=r?Kf.RigidBodyDesc.kinematicPositionBased():Kf.RigidBodyDesc.dynamic(),o=Rt(i.attachedRigidbody.gameObject);s.setTranslation(o.x,o.y,o.z),s.setRotation(xi(i.attachedRigidbody.gameObject)),t=this.world.createRigidBody(s),this.bodies.push(t),this.objects.push(n)}t[Ns]=n,n[Ss]=t,this.internalUpdateRigidbodyProperties(n,t),this.getRigidbodyRelativeMatrix(i.gameObject,n.gameObject,e),i[_5]=t}else{const n=Kf.RigidBodyDesc.kinematicPositionBased(),r=Rt(i.gameObject);n.setTranslation(r.x,r.y,r.z),n.setRotation(xi(i.gameObject)),t=this.world.createRigidBody(n),e.identity(),t[Ns]=null}return t}internal_getRigidbody(i){return i.isCollider===!0?i[_5]:i[Ss]}internalUpdateColliderProperties(i,e){const t=e.shape;let n=!1;switch(t.type){case Zt.Ball:{const d=t,p=i,f=i.gameObject,m=ki(f,this._tempPosition),A=Math.abs(p.radius*m.x);n=d.radius!==A,d.radius=A,n&&e.setShape(d);break}case Zt.Cuboid:const r=t,s=i,o=i.gameObject,a=ki(o,this._tempPosition),l=s.size.x*.5*a.x,c=s.size.y*.5*a.y,u=s.size.z*.5*a.z;n=r.halfExtents.x!==l||r.halfExtents.y!==c||r.halfExtents.z!==u,r.halfExtents.x=l,r.halfExtents.y=c,r.halfExtents.z=u,n&&e.setShape(r);break}if(n){const r=i.attachedRigidbody;if(r!=null&&r.autoMass){const s=this.getBody(r);s?.recomputeMassPropertiesFromColliders()}}this.updateColliderCollisionGroups(i),i.isTrigger!==e.isSensor()&&e.setSensor(i.isTrigger)}internalUpdateRigidbodyProperties(i,e){if(e.enableCcd(i.collisionDetectionMode!==B_.Discrete),e.setLinearDamping(i.drag),e.setAngularDamping(i.angularDrag),e.setGravityScale(i.useGravity?i.gravityScale:0,!0),i.dominanceGroup<=127&&i.dominanceGroup>=-127?e.setDominanceGroup(Math.floor(i.dominanceGroup)):e.setDominanceGroup(0),i.autoMass){e.setAdditionalMass(0,!1);for(let t=0;t<e.numColliders();t++)e.collider(t).setDensity(1);e.recomputeMassPropertiesFromColliders()}else{e.setAdditionalMass(i.mass,!1);for(let t=0;t<e.numColliders();t++)e.collider(t).setDensity(1e-7);e.recomputeMassPropertiesFromColliders()}e.setEnabledRotations(!i.lockRotationX,!i.lockRotationY,!i.lockRotationZ,!1),e.setEnabledTranslations(!i.lockPositionX,!i.lockPositionY,!i.lockPositionZ,!1),i.isKinematic?e.setBodyType(Kf.RigidBodyType.KinematicPositionBased,!1):e.setBodyType(Kf.RigidBodyType.Dynamic,!1)}step(i){this.world&&this.enabled&&(this._isUpdatingPhysicsWorld=!0,this.eventQueue||(this.eventQueue=new hue(!1)),i&&(this.world.timestep=Ze.lerp(this.world.timestep,i,.8)),this.world.step(this.eventQueue),this._isUpdatingPhysicsWorld=!1)}postStep(){this.world&&this.enabled&&(this._isUpdatingPhysicsWorld=!0,this.syncObjects(),this._isUpdatingPhysicsWorld=!1,this.eventQueue&&!this.collisionHandler&&(this.collisionHandler=new gue(this.world,this.eventQueue)),this.collisionHandler&&(this.collisionHandler.handleCollisionEvents(),this.collisionHandler.update()),this.updateDebugRendering(this.world))}updateDebugRendering(i){var e,t,n;if(es||x2||mue||this.debugRenderColliders===!0){if(!this.lines){const s=new vn({color:7855479,fog:!1}),o=new ut;this.lines=new Hs(o,s),this.lines.layers.disableAll(),this.lines.layers.enable(2)}this.lines.parent!==((e=this.context)==null?void 0:e.scene)&&((t=this.context)==null||t.scene.add(this.lines));const r=i.debugRender();this.lines.geometry.setAttribute("position",new $e(r.vertices,3)),this.lines.geometry.setAttribute("color",new $e(r.colors,4))}else this.lines&&((n=this.context)==null||n.scene.remove(this.lines))}syncObjects(){if(!x2)for(let i=0;i<this.bodies.length;i++){const e=this.objects[i],t=this.bodies[i],n=e;if(n?.isCollider===!0&&!n.attachedRigidbody){const a=t.parent();a?this.syncPhysicsBody(e.gameObject,a,!0,!0):this.syncPhysicsBody(e.gameObject,t,!0,!0);continue}const r=t.translation(),s=t.rotation();if(Number.isNaN(r.x)||Number.isNaN(s.x)){!n.__COLLIDER_NAN&&pt()&&(console.warn("Collider has NaN values",n.name,n.gameObject,t),n.__COLLIDER_NAN=!0);continue}const o=e.center;if(o&&o.isVector3){this._tempQuaternion.set(s.x,s.y,s.z,s.w);const a=this._tempPosition.copy(o).applyQuaternion(this._tempQuaternion),l=ki(e.gameObject);a.multiply(l),r.x-=a.x,r.y-=a.y,r.z-=a.z}Su(e.gameObject,r.x,r.y,r.z),pE(e.gameObject,s.x,s.y,s.z,s.w)}}syncPhysicsBody(i,e,t,n){if(e instanceof i5){const r=Rt(i,this._tempPosition),s=xi(i,this._tempQuaternion);switch(e.bodyType()){case W0.Fixed:case W0.KinematicPositionBased:case W0.KinematicVelocityBased:t&&e.setNextKinematicTranslation(r),n&&e.setNextKinematicRotation(s);break;default:t&&e.setTranslation(r,!1),n&&e.setRotation(s,!1);break}}else if(e instanceof g5){const r=Rt(i,this._tempPosition),s=xi(i,this._tempQuaternion),o=e[Ns];if(this.tryApplyCenter(o,r),t){const a=e.translation();(a.x!==r.x||a.y!==r.y||a.z!==r.z)&&e.setTranslation(r)}if(n){const a=e.rotation();(a.x!==s.x||a.y!==s.y||a.z!==s.z||a.w!==s.w)&&e.setRotation(s)}}}tryApplyCenter(i,e){const t=i.center;t&&i.gameObject&&(t.x!==0||t.y!==0||t.z!==0)&&(this._tempCenterPos.x=-t.x,this._tempCenterPos.y=t.y,this._tempCenterPos.z=t.z,ki(i.gameObject,this._tempCenterVec),this._tempCenterPos.multiply(this._tempCenterVec),i.attachedRigidbody?this._tempCenterPos.applyQuaternion(i.gameObject.quaternion):(xi(i.gameObject,this._tempCenterQuaternion),this._tempCenterPos.applyQuaternion(this._tempCenterQuaternion)),e.x+=this._tempCenterPos.x,e.y+=this._tempCenterPos.y,e.z+=this._tempCenterPos.z)}getRigidbodyRelativeMatrix(i,e,t,n){if(n===void 0&&(n=Ew._matricesBuffer,n.length=0),i===e){const r=ki(i,this._tempPosition);t.makeScale(r.x,r.y,r.z);for(let s=n.length-1;s>=0;s--)t.multiply(n[s]);return t}return n.push(i.matrix),i.parent&&this.getRigidbodyRelativeMatrix(i.parent,e,t,n),t}addFixedJoint(i,e){if(!this.world){console.error("Physics world not initialized");return}const t=i[Ss],n=e[Ss];this.calculateJointRelativeMatrices(i.gameObject,e.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const r=tm.fixed(Ew.centerConnectionPos,Ew.centerConnectionRot,this._tempPosition,this._tempQuaternion),s=this.world.createImpulseJoint(r,t,n,!0);es&&console.log("ADD FIXED JOINT",s)}addHingeJoint(i,e,t,n){if(!this.world){console.error("Physics world not initialized");return}const r=i[Ss],s=e[Ss];this.calculateJointRelativeMatrices(i.gameObject,e.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const o=Kf.JointData.revolute(t,this._tempPosition,n),a=this.world.createImpulseJoint(o,r,s,!0);es&&console.log("ADD HINGE JOINT",a)}calculateJointRelativeMatrices(i,e,t){i.updateWorldMatrix(!0,!1),e.updateWorldMatrix(!0,!1);const n=i.matrixWorld,r=e.matrixWorld;n.elements[0]=1,n.elements[5]=1,n.elements[10]=1,r.elements[0]=1,r.elements[5]=1,r.elements[10]=1,t.copy(r).premultiply(n.invert()).invert()}};let q0=Ew;h(q0,"_didLoadPhysicsEngine",!1),h(q0,"_matricesBuffer",[]),h(q0,"centerConnectionPos",{x:0,y:0,z:0}),h(q0,"centerConnectionRot",{x:0,y:0,z:0,w:1});class gue{constructor(e,t){h(this,"world"),h(this,"eventQueue"),h(this,"activeCollisions",[]),h(this,"activeCollisionsStay",[]),h(this,"activeTriggers",[]),this.world=e,this.eventQueue=t}handleCollisionEvents(){this.eventQueue&&this.world&&this.eventQueue.drainCollisionEvents((e,t,n)=>{const r=this.world.getCollider(e),s=this.world.getCollider(t);if(!r||!s)return;const o=r[Ns],a=s[Ns];w2&&console.log("EVT",o.name,a.name,n,r,s),o&&a&&(n?(this.onCollisionStarted(o,r,a,s),this.onCollisionStarted(a,s,o,r)):(this.onCollisionEnded(o,a),this.onCollisionEnded(a,o)))})}update(){this.onHandleCollisionStay()}onCollisionStarted(e,t,n,r){let s=null;if(e.isTrigger||n.isTrigger)ju(e.gameObject,o=>{o.onTriggerEnter&&!o.destroyed&&o.onTriggerEnter(n),this.activeTriggers.push({collider:e,component:o,otherCollider:n})});else{const o=e.gameObject;this.world.contactPair(t,r,(a,l)=>{ju(o,c=>{var u;if(c.destroyed)return;const d=c.onCollisionEnter||c.onCollisionStay||c.onCollisionExit;if(d||w2){if(!s){const p=[],f=a.normal();for(let m=0;m<a.numSolverContacts();m++){const A=a.solverContactPoint(m),v=a.contactImpulse(m);if(A){const g=a.contactDist(m),y=a.solverContactFriction(m),b=a.solverContactTangentVelocity(m),_=new A5(A,g,f,v,y,b);p.push(_),w2&&Ct.DrawDirection(A,f,16711680,3,!0)}}s=new y5(o,n,p)}if(d){const p={collider:e,component:c,collision:s};this.activeCollisions.push(p),c.onCollisionStay&&this.activeCollisionsStay.push(p),(u=c.onCollisionEnter)==null||u.call(c,s)}}})})}}onHandleCollisionStay(){for(const e of this.activeCollisionsStay){const t=e.component;if(!t.destroyed&&t.activeAndEnabled&&t.onCollisionStay){if(e.collision.collider.destroyed)continue;const n=e.collision;t.onCollisionStay(n)}}for(const e of this.activeTriggers){const t=e.component;if(!t.destroyed&&t.activeAndEnabled&&t.onTriggerStay){const n=e.otherCollider;if(n.destroyed)continue;t.onTriggerStay(n)}}}onCollisionEnded(e,t){if(!(e.destroyed||t.destroyed)){for(let n=0;n<this.activeCollisions.length;n++){const r=this.activeCollisions[n],s=r.collider;if(s.destroyed||r.collision.collider.destroyed){this.activeCollisions.splice(n,1),n--;continue}if(s===e&&r.collision.collider===t){const o=r.component;if(this.activeCollisions.splice(n,1),n--,o.activeAndEnabled&&o.onCollisionExit){const a=r.collision;o.onCollisionExit(a)}}}for(let n=0;n<this.activeCollisionsStay.length;n++){const r=this.activeCollisionsStay[n],s=r.collider;if(s.destroyed||r.collision.collider.destroyed){this.activeCollisionsStay.splice(n,1),n--;continue}if(s===e&&r.collision.collider===t){const o=r.component;if(this.activeCollisionsStay.splice(n,1),n--,o.activeAndEnabled&&o.onCollisionExit){const a=r.collision;o.onCollisionExit(a)}}}for(let n=0;n<this.activeTriggers.length;n++){const r=this.activeTriggers[n],s=r.collider;if(s.destroyed||r.otherCollider.destroyed){this.activeTriggers.splice(n,1),n--;continue}if(s===e&&r.otherCollider===t){const o=r.component;if(this.activeTriggers.splice(n,1),n--,o.activeAndEnabled&&o.onTriggerExit){const a=r.otherCollider;o.onTriggerExit(a)}}}}}}function vue(i,e,t,n="image/webp",r){if(!i&&(i=ii.Current,!i))return console.error("Can not save screenshot: No needle-engine context found or provided."),null;if(!r&&(r=i.mainCamera,!r))return console.error("No camera found"),null;const s=i.renderer.domElement.width,o=i.renderer.domElement.height;e||(e=s),t||(t=o);const a=window.devicePixelRatio||1;e/=a,t/=a,i.renderer.domElement.style.width=e+"px",i.renderer.domElement.style.height=t+"px";try{const l=i.renderer.domElement;return i.renderer.setSize(e,t,!1),r instanceof kt&&i.updateAspect(r,e,t),i.renderNow(),l.toDataURL(n)}finally{i.renderer.setSize(s,o,!1),i.updateSize()}return null}let X0=null;function Aue(i,e){if(i){if(!i.startsWith("data:image")){console.error("Can not save image: Data url is not an image",i);return}X0||(X0=document.createElement("a")),X0.href=i,X0.download=e,X0.click()}}Object.defineProperty(kt.prototype,"fov",{get:function(){return this._fov},set:function(i){const e=i!==this._fov;this._fov=i,e&&this.view!==void 0&&this.updateProjectionMatrix()}}),Object.defineProperty(kt.prototype,"near",{get:function(){return this._near},set:function(i){const e=i!==this._near;this._near=i,e&&this.view!==void 0&&this.updateProjectionMatrix()}}),Object.defineProperty(kt.prototype,"far",{get:function(){return this._far},set:function(i){const e=i!==this._far;this._far=i,e&&this.view!==void 0&&this.updateProjectionMatrix()}});const Mw=ee("debugmissingcamera");ii.registerCallback(bn.MissingCamera,i=>{var e,t,n;Mw&&console.warn("Creating missing camera");const r=i.context.scene,s=new ge;s.name="Default Fallback Camera",r.add(s);const o=new Ri;o.sourceId=((t=(e=i.files)==null?void 0:e[0])==null?void 0:t.src)??"unknown",(n=i.context.domElement.getAttribute("skybox-image"))!=null&&n.length||0>0||i.context.lightmaps.tryGetSkybox(o.sourceId)?o.clearFlags=Ju.Skybox:o.clearFlags=Ju.SolidColor,o.backgroundColor=new yi(.5,.5,.5,1),o.fieldOfView=35,o.backgroundBlurriness=.2;const a=nh(s,o,!0);return s.position.x=0,s.position.y=1,s.position.z=2,x5(i.context,a),a}),ii.registerCallback(bn.ContextCreated,i=>{if(!i.context.mainCamera){Mw&&console.log("Will not auto-fit because a default camera exists");return}const e=i.context.domElement;if(e?.cameraControls===!0){const t=aie(i.context.mainCamera);if(t?.isCameraController===!0){Mw&&console.log("Will not auto-fit because a camera controller exists");return}x5(i.context)}});function x5(i,e){e=e??i.mainCameraComponent;const t=e?.gameObject;if(Mw&&console.log("Creating default camera controls",e?.name),t){const n=Yg(t,bi);n.sourceId=e?.sourceId??"unknown";const r=i.domElement.getAttribute("auto-rotate");n.autoRotate=r!==void 0&&(r===""||r==="true"),n.autoRotateSpeed=.5;const s=i,o=()=>{s.pre_render_callbacks.splice(s.pre_render_callbacks.indexOf(o),1),n.fitCamera()};s.pre_render_callbacks.push(o)}else console.warn("Missing camera object, can not add orbit controls")}const C2={Context:Lt,glTF:{loadFromURL:h2}};globalThis.Needle!==void 0&&console.warn("Needle Engine is already imported"),globalThis.Needle=C2;function w5(i){for(const e in i)C2[e]=i[e]}w5(kee),w5(khe);for(const i of Object.getOwnPropertyNames(re))switch(i){case"prototype":case"constructor":case"length":case"name":continue;default:C2[i]=re[i];break}globalThis.THREE?console.warn("Threejs is already imported"):globalThis.THREE=j9;class yue{constructor(e){if(this._retries=0,!Number.isInteger(e)||e<0)throw new Error("Backoff must be a positive integer");this.backoff=e}get retries(){return this._retries}get current(){return this.backoff}next(){return this._retries++,this.backoff}reset(){this._retries=0}}class bue{constructor(e,t){if(this._retries=0,!Number.isInteger(e)||e<0)throw new Error("Base must be a positive integer or zero");if(t!==void 0&&(!Number.isInteger(t)||t<0))throw new Error("ExpMax must be a undefined, a positive integer or zero");this.base=e,this.expMax=t,this.i=0}get retries(){return this._retries}get current(){return this.base*Math.pow(2,this.i)}next(){return this._retries++,this.i=this.expMax===void 0?this.i+1:Math.min(this.i+1,this.expMax),this.current}reset(){this._retries=0,this.i=0}}class _ue{constructor(e,t,n){if(this.i=0,this._retries=0,e<0)throw new Error("Initial must be a positive number or zero");if(t<0)throw new Error("Increment must be a positive number or zero");if(n!==void 0&&n<0)throw new Error("Max must be undefined, a positive number or zero");if(n!==void 0&&n<e)throw new Error("Max must be undefined or greater than or equal to initial");this.initial=e,this.increment=t,this.max=n}get retries(){return this._retries}get current(){return this.max===void 0?this.initial+this.increment*this.i:Math.min(this.initial+this.increment*this.i,this.max)}next(){return this._retries++,this.i++,this.current}reset(){this._retries=0,this.i=0}}class xue{constructor(){this.elements=[]}add(e){this.elements.push(e)}clear(){this.elements.length=0}forEach(e){this.elements.forEach(e)}length(){return this.elements.length}isEmpty(){return this.elements.length===0}peek(){return this.elements[0]}read(){return this.elements.shift()}}class wue{constructor(e){if(!Number.isInteger(e)||e<=0)throw new Error("Capacity must be a positive integer");this.elements=new Array(e+1),this.head=0,this.tail=0}add(e){this.elements[this.head]=e,this.head=(this.head+1)%this.elements.length,this.head===this.tail&&(this.tail=(this.tail+1)%this.elements.length)}clear(){this.head=0,this.tail=0}forEach(e){for(let t=this.tail;t!==this.head;t=(t+1)%this.elements.length)e(this.elements[t])}length(){return this.tail===this.head?0:this.tail<this.head?this.head-this.tail:this.elements.length-this.tail+this.head}isEmpty(){return this.head===this.tail}peek(){return this.isEmpty()?void 0:this.elements[this.tail]}read(){const e=this.peek();return e!==void 0&&(this.tail=(this.tail+1)%this.elements.length),e}}var Si;(function(i){i.open="open",i.close="close",i.error="error",i.message="message",i.retry="retry",i.reconnect="reconnect"})(Si||(Si={}));class S5{constructor(e,t,n){var r,s,o,a,l,c,u,d,p,f,m,A,v,g,y;this._closedByUser=!1,this.handleOpenEvent=b=>this.handleEvent(Si.open,b),this.handleErrorEvent=b=>this.handleEvent(Si.error,b),this.handleCloseEvent=b=>this.handleEvent(Si.close,b),this.handleMessageEvent=b=>this.handleEvent(Si.message,b),this._url=e,this._protocols=t,this._options={buffer:n?.buffer,retry:{maxRetries:(r=n?.retry)===null||r===void 0?void 0:r.maxRetries,instantReconnect:(s=n?.retry)===null||s===void 0?void 0:s.instantReconnect,backoff:(o=n?.retry)===null||o===void 0?void 0:o.backoff},listeners:{open:[...(l=(a=n?.listeners)===null||a===void 0?void 0:a.open)!==null&&l!==void 0?l:[]],close:[...(u=(c=n?.listeners)===null||c===void 0?void 0:c.close)!==null&&u!==void 0?u:[]],error:[...(p=(d=n?.listeners)===null||d===void 0?void 0:d.error)!==null&&p!==void 0?p:[]],message:[...(m=(f=n?.listeners)===null||f===void 0?void 0:f.message)!==null&&m!==void 0?m:[]],retry:[...(v=(A=n?.listeners)===null||A===void 0?void 0:A.retry)!==null&&v!==void 0?v:[]],reconnect:[...(y=(g=n?.listeners)===null||g===void 0?void 0:g.reconnect)!==null&&y!==void 0?y:[]]}},this._underlyingWebsocket=this.tryConnect()}get url(){return this._url}get protocols(){return this._protocols}get buffer(){return this._options.buffer}get maxRetries(){return this._options.retry.maxRetries}get instantReconnect(){return this._options.retry.instantReconnect}get backoff(){return this._options.retry.backoff}get closedByUser(){return this._closedByUser}get lastConnection(){return this._lastConnection}get underlyingWebsocket(){return this._underlyingWebsocket}get readyState(){return this._underlyingWebsocket.readyState}get bufferedAmount(){return this._underlyingWebsocket.bufferedAmount}get extensions(){return this._underlyingWebsocket.extensions}get binaryType(){return this._underlyingWebsocket.binaryType}set binaryType(e){this._underlyingWebsocket.binaryType=e}send(e){this.closedByUser||(this._underlyingWebsocket.readyState===this._underlyingWebsocket.OPEN?this._underlyingWebsocket.send(e):this.buffer!==void 0&&this.buffer.add(e))}close(e,t){this.cancelScheduledConnectionRetry(),this._closedByUser=!0,this._underlyingWebsocket.close(e,t)}addEventListener(e,t,n){this._options.listeners[e].push({listener:t,options:n})}removeEventListener(e,t,n){const r=s=>s.listener!==t||s.options!==n;this._options.listeners[e]=this._options.listeners[e].filter(r)}tryConnect(){return this._underlyingWebsocket=new WebSocket(this.url,this.protocols),this._underlyingWebsocket.addEventListener(Si.open,this.handleOpenEvent),this._underlyingWebsocket.addEventListener(Si.close,this.handleCloseEvent),this._underlyingWebsocket.addEventListener(Si.error,this.handleErrorEvent),this._underlyingWebsocket.addEventListener(Si.message,this.handleMessageEvent),this._underlyingWebsocket}clearWebsocket(){this._underlyingWebsocket.removeEventListener(Si.open,this.handleOpenEvent),this._underlyingWebsocket.removeEventListener(Si.close,this.handleCloseEvent),this._underlyingWebsocket.removeEventListener(Si.error,this.handleErrorEvent),this._underlyingWebsocket.removeEventListener(Si.message,this.handleMessageEvent),this._underlyingWebsocket.close()}dispatchEvent(e,t){const n=this._options.listeners[e],r=[];n.forEach(({listener:s,options:o})=>{s(this,t),(o===void 0||o.once===void 0||!o.once)&&r.push({listener:s,options:o})}),this._options.listeners[e]=r}handleEvent(e,t){switch(e){case Si.close:this.dispatchEvent(e,t),this.scheduleConnectionRetryIfNeeded();break;case Si.open:if(this.backoff!==void 0&&this._lastConnection!==void 0){const n={retries:this.backoff.retries,lastConnection:new Date(this._lastConnection)},r=new CustomEvent(Si.reconnect,{detail:n});this.dispatchEvent(Si.reconnect,r),this.backoff.reset()}this._lastConnection=new Date,this.dispatchEvent(e,t),this.sendBufferedData();break;case Si.retry:this.dispatchEvent(e,t),this.clearWebsocket(),this.tryConnect();break;default:this.dispatchEvent(e,t);break}}sendBufferedData(){if(this.buffer!==void 0)for(let e=this.buffer.read();e!==void 0;e=this.buffer.read())this.send(e)}scheduleConnectionRetryIfNeeded(){if(this.closedByUser||this.backoff===void 0)return;const e=n=>{const r=new CustomEvent(Si.retry,{detail:n});this.handleEvent(Si.retry,r)},t={backoff:this._options.retry.instantReconnect===!0?0:this.backoff.next(),retries:this._options.retry.instantReconnect===!0?0:this.backoff.retries,lastConnection:this._lastConnection};(this._options.retry.maxRetries===void 0||t.retries<=this._options.retry.maxRetries)&&(this.retryTimeout=globalThis.setTimeout(()=>e(t),t.backoff))}cancelScheduledConnectionRetry(){globalThis.clearTimeout(this.retryTimeout)}}class Sue{constructor(e){this._url=e}get url(){return this._url}withProtocols(e){return this._protocols=e,this}get protocols(){return this._protocols}withMaxRetries(e){var t;return this._options=Object.assign(Object.assign({},this._options),{retry:Object.assign(Object.assign({},(t=this._options)===null||t===void 0?void 0:t.retry),{maxRetries:e})}),this}get maxRetries(){var e,t;return(t=(e=this._options)===null||e===void 0?void 0:e.retry)===null||t===void 0?void 0:t.maxRetries}withInstantReconnect(e){var t;return this._options=Object.assign(Object.assign({},this._options),{retry:Object.assign(Object.assign({},(t=this._options)===null||t===void 0?void 0:t.retry),{instantReconnect:e})}),this}get instantReconnect(){var e,t;return(t=(e=this._options)===null||e===void 0?void 0:e.retry)===null||t===void 0?void 0:t.instantReconnect}withBackoff(e){var t;return this._options=Object.assign(Object.assign({},this._options),{retry:Object.assign(Object.assign({},(t=this._options)===null||t===void 0?void 0:t.retry),{backoff:e})}),this}get backoff(){var e,t;return(t=(e=this._options)===null||e===void 0?void 0:e.retry)===null||t===void 0?void 0:t.backoff}withBuffer(e){return this._options=Object.assign(Object.assign({},this._options),{buffer:e}),this}get buffer(){var e;return(e=this._options)===null||e===void 0?void 0:e.buffer}onOpen(e,t){return this.addListener(Si.open,e,t),this}onClose(e,t){return this.addListener(Si.close,e,t),this}onError(e,t){return this.addListener(Si.error,e,t),this}onMessage(e,t){return this.addListener(Si.message,e,t),this}onRetry(e,t){return this.addListener(Si.retry,e,t),this}onReconnect(e,t){return this.addListener(Si.reconnect,e,t),this}build(){return new S5(this._url,this._protocols,this._options)}addListener(e,t,n){var r,s,o,a,l,c,u,d,p,f,m,A,v,g,y,b,_,E,I,T,M;return this._options=Object.assign(Object.assign({},this._options),{listeners:{open:(o=(s=(r=this._options)===null||r===void 0?void 0:r.listeners)===null||s===void 0?void 0:s.open)!==null&&o!==void 0?o:[],close:(c=(l=(a=this._options)===null||a===void 0?void 0:a.listeners)===null||l===void 0?void 0:l.close)!==null&&c!==void 0?c:[],error:(p=(d=(u=this._options)===null||u===void 0?void 0:u.listeners)===null||d===void 0?void 0:d.error)!==null&&p!==void 0?p:[],message:(A=(m=(f=this._options)===null||f===void 0?void 0:f.listeners)===null||m===void 0?void 0:m.message)!==null&&A!==void 0?A:[],retry:(y=(g=(v=this._options)===null||v===void 0?void 0:v.listeners)===null||g===void 0?void 0:g.retry)!==null&&y!==void 0?y:[],reconnect:(E=(_=(b=this._options)===null||b===void 0?void 0:b.listeners)===null||_===void 0?void 0:_.reconnect)!==null&&E!==void 0?E:[],[e]:[...(M=(T=(I=this._options)===null||I===void 0?void 0:I.listeners)===null||T===void 0?void 0:T[e])!==null&&M!==void 0?M:[],{listener:t,options:n}]}}),this}}const Cue=Object.freeze(Object.defineProperty({__proto__:null,ArrayQueue:xue,ConstantBackoff:yue,ExponentialBackoff:bue,LinearBackoff:_ue,RingQueue:wue,Websocket:S5,WebsocketBuilder:Sue,get WebsocketEvent(){return Si}},Symbol.toStringTag,{value:"Module"})),Wo={node:"node",material:"material",camera:"camera",light:"light"},kd="KHR_animation_pointer",Eue={CUBICSPLINE:void 0,LINEAR:Ta,STEP:Rc},C5=Qt.findNode;let E5=!1;class Mue{constructor(e){this.parser=e,this.name=kd,this.animationPointerResolver=null}setAnimationPointerResolver(e){return this.animationPointerResolver=e,this}_patchPropertyBindingFindNode(){E5||(E5=!0,Qt.findNode=function(e,t){if(t.startsWith(".materials.")){const n=t.substring(11).substring(t.indexOf(".")),r=n.indexOf("."),s=r<0?n:n.substring(0,r);let o=null;return e.traverse(a=>{o!==null||a.type!=="Mesh"&&a.type!=="SkinnedMesh"||a.material&&(a.material.uuid===s||a.material.name===s)&&(o=a.material,o!==null&&(n.endsWith(".map")?o=o.map:n.endsWith(".emissiveMap")&&(o=o.emissiveMap)))}),o}else if(t.startsWith(".nodes.")||t.startsWith(".lights.")||t.startsWith(".cameras.")){const n=t.split(".");let r;for(let s=1;s<n.length;s++){const o=n[s];if(o.length==36)r=e.getObjectByProperty("uuid",o);else if(r&&r[o]){const a=Number.parseInt(o);let l=o;a>=0&&(l=a),r=r[l]}else{const a=e.getObjectByName(o);a&&(r=a)}}if(!r){const s=C5(e,n[2]);return s||console.warn(kd+": Property binding not found",t,e,e.name,n),s}return r}return C5(e,t)})}loadAnimationTargetFromChannel(e){const t=e.target,n=t.node!==void 0?t.node:t.id;return this.parser.getDependency("node",n)}loadAnimationTargetFromChannelWithAnimationPointer(e){this._havePatchedPropertyBindings||this._patchPropertyBindingFindNode();const t=e.target,n=t.extensions&&t.extensions[kd]&&t.path&&t.path==="pointer";if(!n)return null;let r,s=Wo.node,o;if(n){const l=t.extensions[kd];let c=l.pointer;if(!c){console.warn("Invalid path",l,t);return}if(c.startsWith("/materials/")?s=Wo.material:c.startsWith("/extensions/KHR_lights_punctual/lights/")?s=Wo.light:c.startsWith("/cameras/")&&(s=Wo.camera),o=this._tryResolveTargetId(c,s),o===null||isNaN(o)){console.warn("Failed resolving animation node id: "+o,c);return}switch(s){case Wo.material:const d=("/materials/"+o.toString()+"/").length,p=c.substring(0,d);switch(r=c.substring(d),r){case"pbrMetallicRoughness/baseColorFactor":r="color";break;case"pbrMetallicRoughness/roughnessFactor":r="roughness";break;case"pbrMetallicRoughness/metallicFactor":r="metalness";break;case"emissiveFactor":r="emissive";break;case"alphaCutoff":r="alphaTest";break;case"occlusionTexture/strength":r="aoMapIntensity";break;case"normalTexture/scale":r="normalScale";break;case"pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/scale":r="map/repeat";break;case"pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/offset":r="map/offset";break;case"emissiveTexture/extensions/KHR_texture_transform/scale":r="emissiveMap/repeat";break;case"emissiveTexture/extensions/KHR_texture_transform/offset":r="emissiveMap/offset";break;case"extensions/KHR_materials_emissive_strength/emissiveStrength":r="emissiveIntensity";break;case"extensions/KHR_materials_transmission/transmissionFactor":r="transmission";break;case"extensions/KHR_materials_ior/ior":r="ior";break;case"extensions/KHR_materials_volume/thicknessFactor":r="thickness";break;case"extensions/KHR_materials_volume/attenuationColor":r="attenuationColor";break;case"extensions/KHR_materials_volume/attenuationDistance":r="attenuationDistance";break;case"extensions/KHR_materials_iridescence/iridescenceFactor":r="iridescence";break;case"extensions/KHR_materials_iridescence/iridescenceIor":r="iridescenceIOR";break;case"extensions/KHR_materials_iridescence/iridescenceThicknessMinimum":r="iridescenceThicknessRange[0]";break;case"extensions/KHR_materials_iridescence/iridescenceThicknessMaximum":r="iridescenceThicknessRange[1]";break;case"extensions/KHR_materials_clearcoat/clearcoatFactor":r="clearcoat";break;case"extensions/KHR_materials_clearcoat/clearcoatRoughnessFactor":r="clearcoatRoughness";break;case"extensions/KHR_materials_sheen/sheenColorFactor":r="sheenColor";break;case"extensions/KHR_materials_sheen/sheenRoughnessFactor":r="sheenRoughness";break;case"extensions/KHR_materials_specular/specularFactor":r="specularIntensity";break;case"extensions/KHR_materials_specular/specularColorFactor":r="specularColor";break}c=p+r;break;case Wo.node:const f=("/nodes/"+o.toString()+"/").length,m=c.substring(0,f);switch(r=c.substring(f),r){case"translation":r="position";break;case"rotation":r="quaternion";break;case"scale":r="scale";break;case"weights":r="morphTargetInfluences";break}c=m+r;break;case Wo.light:const A=("/extensions/KHR_lights_punctual/lights/"+o.toString()+"/").length;switch(r=c.substring(A),r){case"color":break;case"intensity":break;case"spot/innerConeAngle":r="penumbra";break;case"spot/outerConeAngle":r="angle";break;case"range":r="distance";break}c="/lights/"+o.toString()+"/"+r;break;case Wo.camera:const v=("/cameras/"+o.toString()+"/").length,g=c.substring(0,v);switch(r=c.substring(v),r){case"perspective/yfov":r="fov";break;case"perspective/znear":case"orthographic/znear":r="near";break;case"perspective/zfar":case"orthographic/zfar":r="far";break;case"perspective/aspect":r="aspect";break;case"orthographic/xmag":r="zoom";break;case"orthographic/ymag":r="zoom";break}c=g+r;break}const u=this.animationPointerResolver;u&&u.resolvePath&&(c=u.resolvePath(c)),t.extensions[kd].pointer=c}if(o===null||isNaN(o)){console.warn("Failed resolving animation node id: "+o,t);return}let a;return s===Wo.node?a=this.parser.getDependency("node",o):s===Wo.material?a=this.parser.getDependency("material",o):s===Wo.light?a=this.parser.getDependency("light",o):s===Wo.camera?a=this.parser.getDependency("camera",o):console.error("Unhandled type",s),a}createAnimationTracksWithAnimationPointer(e,t,n,r,s){if(!(s.extensions&&s.extensions[kd]&&s.path&&s.path==="pointer"))return null;let o=s.extensions[kd].pointer;if(!o)return null;const a=[];o=o.replaceAll("/",".");const l=o.split(".");var c=e.name!==void 0&&e.name!==null?e.name:e.uuid;if(l[2]=c,l[3]==="morphTargetInfluences"&&e.type==="Group"){for(const d of e.children)d instanceof Ao&&d.morphTargetInfluences&&(l[3]=d.name,l[4]="morphTargetInfluences",u(this.parser));return a}u(this.parser);function u(d){o=l.join(".");let p;switch(n.itemSize){case 1:p=zc;break;case 2:case 3:p=Bl;break;case 4:o.endsWith(".quaternion")?p=Pa:p=Ty;break}const f=r.interpolation!==void 0?Eue[r.interpolation]:Ta;let m=d._getArrayFromAccessor(n);o.endsWith(".fov")&&(m=m.map(v=>v/Math.PI*180));const A=new p(o,t.array,m,f);if(f==="CUBICSPLINE"&&d._createCubicSplineTrackInterpolant(A),a.push(A),o&&n.itemSize===4&&o.startsWith(".materials.")&&o.endsWith(".color")){const v=new Float32Array(m.length/4);for(let y=0,b=m.length/4;y<b;y+=1)v[y]=m[y*4+3];const g=new p(o.replace(".color",".opacity"),t.array,v,f);f==="CUBICSPLINE"&&d._createCubicSplineTrackInterpolant(A),a.push(g)}}return a}_tryResolveTargetId(e,t){let n="";return t==="node"?n=e.substring(7):t==="material"?n=e.substring(11):t==="light"?n=e.substring(39):t==="camera"&&(n=e.substring(9)),n=n.substring(0,n.indexOf("/")),Number.parseInt(n)}loadAnimation(e){const t=this,n=this.parser.json,r=this.parser,s=n.animations[e],o=s.name?s.name:"animation_"+e,a=[],l=[],c=[],u=[],d=[];for(let p=0,f=s.channels.length;p<f;p++){const m=s.channels[p],A=s.samplers[m.sampler],v=m.target,g=s.parameters!==void 0?s.parameters[A.input]:A.input,y=s.parameters!==void 0?s.parameters[A.output]:A.output;let b=t.loadAnimationTargetFromChannelWithAnimationPointer(m);b||(b=t.loadAnimationTargetFromChannel(m)),a.push(b),l.push(r.getDependency("accessor",g)),c.push(r.getDependency("accessor",y)),u.push(A),d.push(v)}return Promise.all([Promise.all(a),Promise.all(l),Promise.all(c),Promise.all(u),Promise.all(d)]).then(function(p){const f=p[0],m=p[1],A=p[2],v=p[3],g=p[4],y=[];for(let b=0,_=f.length;b<_;b++){const E=f[b],I=m[b],T=A[b],M=v[b],D=g[b];if(E===void 0)continue;E.updateMatrix&&(E.updateMatrix(),E.matrixAutoUpdate=!0);let C=t.createAnimationTracksWithAnimationPointer(E,I,T,M,D);if(C||(C=r._createAnimationTracks(E,I,T,M,D)),C)for(let P=0;P<C.length;P++)y.push(C[P])}return new cs(o,void 0,y)})}}const Tue=Object.freeze(Object.defineProperty({__proto__:null,GLTFAnimationPointerExtension:Mue},Symbol.toStringTag,{value:"Module"}));export{fue as $physicsKey,li as ActionBuilder,LT as ActionCollection,ma as ActionModel,HL as Addressables,av as AlignmentConstraint,Up as AmbientMode,vs as Animation,Xu as AnimationCurve,Sv as AnimationExtension,G_ as AnimationTrackHandler,Sr as Animator,fh as AnimatorConditionMode,uo as AnimatorController,YT as AnimatorControllerParameterType,wv as AnimatorStateInfo,Ev as Antialiasing,Ng as Application,Zb as ApplicationEvents,Jk as AssetDatabase,ni as AssetReference,zh as AudioExtension,ph as AudioListener,en as AudioSource,_v as AudioTrackHandler,ed as Avatar,id as AvatarBlink_Simple,uf as AvatarEyeLook_Rotation,sI as AvatarLoader,Er as AvatarMarker,K_ as AvatarModel,Pv as Avatar_Brain_LookAt,Dv as Avatar_MouthShapes,iI as Avatar_MustacheShake,Ja as Avatar_POI,tf as Axes,df as AxesHelper,TE as BUILD_TIME,Ca as BaseUIComponent,aI as BasicIKConstraint,Z_ as BehaviorExtension,_r as BehaviorModel,Ie as Behaviour,nd as Bloom,Lv as BoxCollider,rd as BoxGizmo,Za as BoxHelperComponent,rc as Button,h4 as CallDirection,nf as CallInfo,Ri as Camera,gv as CameraTargetReachedEvent,Mr as Canvas,bh as CanvasGroup,gh as CapsuleCollider,Af as ChangeMaterialOnClick,ad as ChangeTransformOnClick,cd as CharacterController,ac as CharacterControllerInput,Qv as ChromaticAberration,bo as CircularBuffer,Ju as ClearFlags,Wa as ClipExtrapolation,zo as Collider,y5 as Collision,B_ as CollisionDetectionMode,wh as ColorAdjustments,dd as ColorBySpeedModule,i0 as ColorOverLifetimeModule,Ie as Component,fg as ComponentEvents,mg as ComponentLifecycleEvents,b3 as ConnectionEvents,A5 as ContactPoint,Th as ContactShadows,Lt as Context,wee as ContextArgs,bn as ContextEvent,ii as ContextRegistry,Q_ as ControlTrackHandler,Rh as CustomBranding,Aa as CustomShader,c_ as DefaultReflectionMode,VI as Deletable,Cx as DeleteBox,_a as DepthOfField,Ex as DeviceFlag,WI as DocumentExtension,Go as DragControls,Z4 as DragMode,l0 as DropListener,vd as Duplicatable,pf as EXTENSION_NAME,el as EmissionModule,bf as EmphasizeOnClick,aT as EngineLoadingView,Hn as EventList,D_ as EventListEvent,Lo as EventSystem,Ix as EventTrigger,kI as FieldWithDefault,Lb as FileReference,WL as FileReferenceSerializer,iz as FileSpawnModel,tz as File_Event,tR as FixedJoint,iR as FlyControls,Df as Fog,Pn as FrameEvent,_b as GENERATOR,re as GameObject,Ct as Gizmos,d0 as GltfExport,cR as GltfExportBox,Dd as GltfLoadEvent,Fj as GltfLoadEventType,Ch as Gradient,sd as Graphic,k_ as GraphicRaycaster,oa as Graphics,Lf as GridHelper,bI as GridLayoutGroup,Ad as GroundProjectedEnv,lh as GroupActionModel,yF as HideFlags,wI as HideOnStart,c0 as HingeJoint,yI as HorizontalLayoutGroup,See as HostData,vf as Image,Ob as ImageReference,VL as ImageReferenceSerializer,Mh as InheritVelocityModule,JL as Input,za as InputEventQueue,Wi as InputEvents,bd as InputField,Yv as InstanceHandle,Xv as InstancingHandler,qo as InstancingUtil,hF as InstantiateEvent,or as InstantiateIdProvider,Sa as InstantiateOptions,HI as Interactable,m$ as JoinedRoomResponse,xZ as KeyEventArgs,Do as Keyframe,m0 as LODGroup,_d as LODModel,g$ as LeftRoomResponse,Fs as Light,$3 as LightData,Dn as LimitVelocityOverLifetimeModule,Lee as LoadingElementOptions,pR as LogStats,Ws as LogType,xd as LookAt,cv as LookAtConstraint,Ir as MainModule,qT as MarkerType,Nv as MaskableGraphic,Ze as Mathf,mf as MeshCollider,$v as MeshRenderer,lt as MinMaxCurve,Ls as MinMaxGradient,Ui as NEEDLE_progressive,Cg as NEKeyboardEvent,Hl as NEPointerEvent,ii as NeedleEngine,u2 as NeedleEngineHTMLElement,l2 as NeedleGltfLoader,Bh as NeedleMenu,gb as NeedlePatchesKey,sM as NeedleXRController,mt as NeedleXRSession,w3 as NeedleXRSync,M3 as NeedleXRUtils,Lx as NestedGltf,x3 as NetworkConnection,Ka as NetworkedStreamEvents,Z0 as NetworkedStreams,gd as Networking,fF as NewInstanceModel,_i as NoiseModule,Ys as ObjectRaycaster,Fg as ObjectUtils,wd as OffsetConstraint,ab as OneEuroFilter,hE as OneEuroFilterXYZ,Uf as OpenURL,bi as OrbitControls,gf as Outline,_3 as OwnershipEvent,IM as OwnershipModel,Ah as Padding,t0 as ParticleBurst,Zx as ParticleSubEmitter,kn as ParticleSystem,Dh as ParticleSystemBaseBehaviour,Qo as ParticleSystemRenderer,Ax as ParticleSystemShapeType,Y_ as PeerHandle,v3 as PeerNetworking,W3 as Physics,tr as PhysicsMaterialCombine,E0 as PixelationEffect,_f as PlayAnimationOnClick,_h as PlayAudioOnClick,Ku as PlayableDirector,nm as PlayerColor,No as PlayerState,r4 as PlayerStateEvent,lf as PlayerSync,q3 as PlayerView,X3 as PlayerViewManager,em as PointerEventData,Ub as PointerType,Yr as PostProcessingEffect,ax as PostProcessingHandler,xf as PreliminaryAction,jv as PreliminaryTrigger,Uu as PrimitiveType,Kt as Progress,g4 as ProgressiveLoadingInfo,Jm as PromiseAllWithErrors,wC as PromiseErrorResult,yi as RGBAColor,q0 as RapierPhysics,nx as RawImage,To as RaycastOptions,mI as Rect,bs as RectTransform,Cf as ReflectionProbe,q_ as RegisteredAnimationInfo,pc as RemoteSkybox,ef as RenderTexture,XN as RenderTextureSerializer,Sn as Renderer,Z3 as RendererData,Jv as RendererLightmap,Li as Rigidbody,wn as RigidbodyConstraints,Jt as RoomEvents,io as RotationBySpeedModule,jo as RotationOverLifetimeModule,fx as SceneLightSettings,$r as SceneSwitcher,Ed as ScreenCapture,fc as ScreenSpaceAmbientOcclusion,xa as ScreenSpaceAmbientOcclusionN8,la as SendQueue,YE as SerializationContext,ld as SetActiveOnClick,T0 as ShadowCatcher,sn as ShapeModule,Av as SignalAsset,of as SignalReceiver,sf as SignalReceiverEvent,xv as SignalTrackHandler,fI as Size,_s as SizeBySpeedModule,Eh as SizeOverLifetimeModule,UI as SkinnedMeshRenderer,kh as SmoothFollow,fv as SpatialGrabRaycaster,I0 as SpatialHtml,B0 as SpatialTrigger,ol as SpatialTriggerReceiver,sw as SpectatorCamera,kv as SphereCollider,V3 as SphereIntersection,b5 as SphereOverlapResult,mc as Sprite,Qf as SpriteData,al as SpriteRenderer,D0 as SpriteSheet,Yie as StateMachineBehaviour,l4 as StreamEndedEvent,c4 as StreamReceivedEvent,C0 as SubEmitterSystem,lw as SyncedCamera,gc as SyncedRoom,uh as SyncedTransform,SI as TapGestureTrigger,cw as TeleportTarget,JR as TestRunner,KR as TestSimulateUserData,xs as Text,xx as TextBuilder,o0 as TextExtension,Rr as TextureSheetAnimationModule,ll as TiltShiftEffect,tF as Time,O0 as ToneMapping,yv as TrackHandler,Js as TrackType,Xi as TrailModule,Xr as TransformData,Td as TransformGizmo,xr as TriggerBuilder,Wu as TriggerModel,q as TypeStore,L_ as UIRaycastUtils,dv as UIRootComponent,Bo as USDObject,Wn as USDZExporter,Ih as USDZText,wx as USDZUIExtension,$E as Upload_Result,YN as UriSerializer,a0 as UsageMarker,v$ as UserJoinedOrLeftRoomModel,Fl as VERSION,kT as VariantAction,on as VelocityOverLifetimeModule,AI as VerticalLayoutGroup,qn as VideoPlayer,ih as ViewDevice,Id as Vignette,Gv as VisibilityAction,td as Voip,Wv as Volume,Bt as VolumeParameter,Cv as VolumeProfile,S$ as WaitForFrames,I3 as WaitForPromise,T3 as WaitForSeconds,bc as Watch,dw as WebARCameraBackground,no as WebARSessionRoot,Aw as WebXR,Rf as WebXRButtonFactory,bw as WebXRImageTracking,vc as WebXRImageTrackingModel,Uh as WebXRPlaneTracking,Bd as WebXRTrackedImage,U0 as XRControllerFollow,hl as XRControllerModel,Ho as XRControllerMovement,Zs as XRFlag,xw as XRRig,ys as XRState,Ya as XRStateFlag,n2 as __Ignore,tL as __internalNotifyObjectDestroyed,Nl as activeInHierarchyFieldName,AO as addAttributeChangeCallback,Gu as addComponent,ose as addCustomExtensionPlugin,nz as addFile,rz as addFileFromUrl,Ghe as addGltfLoadEventListener,nh as addNewComponent,mb as addPatch,w_ as apply,tue as applyHMRChanges,pF as beginListenDestroy,sz as beginListenFileSpawn,mF as beginListenInstantiate,hM as binaryIdentifierCasts,xee as build_scene_functions,Ru as builtinComponentKeyName,sT as calculateProgress01,wie as colorSerializer,O_ as componentSerializer,Lk as copyTexture,c2 as createGLTFLoader,$N as createMotion,ps as debugNet,Lg as debugOwner,Ym as deepClone,na as delay,gO as delayForFrames,Pb as deserializeObject,pa as destroy,RF as destroyComponentInstance,Ii as disposeObjectResources,nc as disposeStream,QL as download,tM as download_file,gg as editorGuidKeyName,MI as effectsOrder,Mp as enableSpatialConsole,Tie as eventListSerializer,Xg as findByGuid,DF as findObjectOfType,OF as findObjectsOfType,yb as findResourceUsers,ju as foreachComponent,nT as foreachComponentEnumerator,nY as forward,bO as generateQRCode,v_ as generateSeed,Qu as getComponent,Kg as getComponentInChildren,$g as getComponentInParent,Jg as getComponents,Zg as getComponentsInChildren,S_ as getComponentsInParent,mN as getFormattedDate,Z9 as getIp,$9 as getIpAndLocation,K9 as getIpCloudflare,Yo as getLoader,Yg as getOrAddComponent,ee as getParam,oY as getParentHierarchyPath,q9 as getPath,u$ as getPeerOptions,m3 as getPeerjsInstance,Vg as getRaycastMesh,TY as getResourceUserCount,wu as getTempQuaternion,Zi as getTempVector,Xm as getUrlParams,fE as getWorldDirection,mE as getWorldEuler,Rt as getWorldPosition,xi as getWorldQuaternion,rg as getWorldRotation,ki as getWorldScale,Fp as hasCommercialLicense,qM as hasIndieLicense,GT as hasPointerEventComponent,da as hasProLicense,eM as hash,xN as imageToCanvas,Gp as instantiate,bF as isActiveInHierarchy,jp as isActiveSelf,kk as isAnimationAction,Q9 as isDebugMode,yu as isDesktop,zu as isDestroyed,pt as isDevEnvironment,EY as isDisposed,hO as isHostedOnGlitch,Khe as isHotReloading,Bs as isLocalNetwork,ra as isMobileDevice,bu as isMozillaXR,qy as isQuest,Zk as isResourceTrackingEnabled,Cp as isSafari,b_ as isUsingInstancing,Sp as isiOS,h2 as loadSync,cb as logHierarchy,KX as lookAtInverse,ig as lookAtObject,V9 as makeId,bC as makeIdFromRandomWords,_F as markAsInstancedRendered,xC as microphonePermissionsGranted,G9 as nameof,uO as nameofFactory,qN as objectSerializer,fie as onBeforeRender,die as onInitialized,pie as onStart,HN as onUpdate,zj as parseSync,gie as prefix,dO as pushState,W9 as randomNumber,uM as registerBinaryType,f_ as registerComponent,BI as registerComponentExtension,Fo as registerCustomEffectType,F4 as registerExportExtensions,DI as registerExtensions,Zhe as registerHotReloadType,Kw as registerLoader,vF as registerPrefabProvider,WK as registerType,vO as relativePathPrefix,yO as removeAttributeChangeCallback,rT as removeComponent,ase as removeCustomImportExtensionType,Qhe as removeGltfLoadEventListener,xY as removePatch,kl as resolveUrl,mO as sanitizeString,Aue as saveImage,vue as screenshot,dF as sendDestroyed,x as serializable,kL as serializeObject,Zp as serializeable,qg as setActive,rW as setAllowOverlayMessages,wF as setDestroyed,pY as setDevEnvironment,EE as setDisposable,tT as setDontDestroy,AC as setOrAddParamsToUrl,H9 as setParam,Hy as setParamWithoutReload,d$ as setPeerOptions,a_ as setRaycastMesh,CY as setResourceTrackingEnabled,yC as setState,gE as setWorldEuler,Qr as setWorldPosition,Su as setWorldPositionXYZ,So as setWorldQuaternion,pE as setWorldQuaternionXYZW,vE as setWorldRotation,sg as setWorldRotationXYZ,ng as setWorldScale,AE as showBalloonError,$i as showBalloonMessage,Qi as showBalloonWarning,BC as showDebugConsole,YX as slerp,g_ as syncDestroy,eI as syncField,$M as syncInstantiate,aY as textureToCanvas,tU as tryCastBinary,xp as tryFindObject,Qj as tryFindObjectByName,Vhe as tryFindScript,iU as tryGetGuid,$he as unregisterHotReloadType,_C as unwatchWrite,GL as upload_file,wr as validate,Wy as watchWrite};
7444
+ Error:`,o),null}}updateColliderCollisionGroups(i){const e=i[Ss],t=i.membership;let n=0;if(t==null)n=4294967295;else for(let o=0;o<t.length;o++){const a=t[o];n|=1<<a}const r=i.filter;let s=0;if(r==null)s=4294967295;else for(let o=0;o<r.length;o++){const a=r[o];s|=1<<a}e.setCollisionGroups(n<<16|s)}getRigidbody(i,e){if(!this.world)throw new Error("Physics world not initialized");let t=null;if(i.attachedRigidbody){const n=i.attachedRigidbody;if(t=n[Ss],!t){const r=n.isKinematic&&!x2;es&&console.log("Create rigidbody",r);const s=r?Kf.RigidBodyDesc.kinematicPositionBased():Kf.RigidBodyDesc.dynamic(),o=Rt(i.attachedRigidbody.gameObject);s.setTranslation(o.x,o.y,o.z),s.setRotation(xi(i.attachedRigidbody.gameObject)),t=this.world.createRigidBody(s),this.bodies.push(t),this.objects.push(n)}t[Ns]=n,n[Ss]=t,this.internalUpdateRigidbodyProperties(n,t),this.getRigidbodyRelativeMatrix(i.gameObject,n.gameObject,e),i[_5]=t}else{const n=Kf.RigidBodyDesc.kinematicPositionBased(),r=Rt(i.gameObject);n.setTranslation(r.x,r.y,r.z),n.setRotation(xi(i.gameObject)),t=this.world.createRigidBody(n),e.identity(),t[Ns]=null}return t}internal_getRigidbody(i){return i.isCollider===!0?i[_5]:i[Ss]}internalUpdateColliderProperties(i,e){const t=e.shape;let n=!1;switch(t.type){case Zt.Ball:{const d=t,p=i,f=i.gameObject,m=ki(f,this._tempPosition),A=Math.abs(p.radius*m.x);n=d.radius!==A,d.radius=A,n&&e.setShape(d);break}case Zt.Cuboid:const r=t,s=i,o=i.gameObject,a=ki(o,this._tempPosition),l=s.size.x*.5*a.x,c=s.size.y*.5*a.y,u=s.size.z*.5*a.z;n=r.halfExtents.x!==l||r.halfExtents.y!==c||r.halfExtents.z!==u,r.halfExtents.x=l,r.halfExtents.y=c,r.halfExtents.z=u,n&&e.setShape(r);break}if(n){const r=i.attachedRigidbody;if(r!=null&&r.autoMass){const s=this.getBody(r);s?.recomputeMassPropertiesFromColliders()}}this.updateColliderCollisionGroups(i),i.isTrigger!==e.isSensor()&&e.setSensor(i.isTrigger)}internalUpdateRigidbodyProperties(i,e){if(e.enableCcd(i.collisionDetectionMode!==B_.Discrete),e.setLinearDamping(i.drag),e.setAngularDamping(i.angularDrag),e.setGravityScale(i.useGravity?i.gravityScale:0,!0),i.dominanceGroup<=127&&i.dominanceGroup>=-127?e.setDominanceGroup(Math.floor(i.dominanceGroup)):e.setDominanceGroup(0),i.autoMass){e.setAdditionalMass(0,!1);for(let t=0;t<e.numColliders();t++)e.collider(t).setDensity(1);e.recomputeMassPropertiesFromColliders()}else{e.setAdditionalMass(i.mass,!1);for(let t=0;t<e.numColliders();t++)e.collider(t).setDensity(1e-7);e.recomputeMassPropertiesFromColliders()}e.setEnabledRotations(!i.lockRotationX,!i.lockRotationY,!i.lockRotationZ,!1),e.setEnabledTranslations(!i.lockPositionX,!i.lockPositionY,!i.lockPositionZ,!1),i.isKinematic?e.setBodyType(Kf.RigidBodyType.KinematicPositionBased,!1):e.setBodyType(Kf.RigidBodyType.Dynamic,!1)}step(i){this.world&&this.enabled&&(this._isUpdatingPhysicsWorld=!0,this.eventQueue||(this.eventQueue=new hue(!1)),i&&(this.world.timestep=Ze.lerp(this.world.timestep,i,.8)),this.world.step(this.eventQueue),this._isUpdatingPhysicsWorld=!1)}postStep(){this.world&&this.enabled&&(this._isUpdatingPhysicsWorld=!0,this.syncObjects(),this._isUpdatingPhysicsWorld=!1,this.eventQueue&&!this.collisionHandler&&(this.collisionHandler=new gue(this.world,this.eventQueue)),this.collisionHandler&&(this.collisionHandler.handleCollisionEvents(),this.collisionHandler.update()),this.updateDebugRendering(this.world))}updateDebugRendering(i){var e,t,n;if(es||x2||mue||this.debugRenderColliders===!0){if(!this.lines){const s=new vn({color:7855479,fog:!1}),o=new ut;this.lines=new Hs(o,s),this.lines.layers.disableAll(),this.lines.layers.enable(2)}this.lines.parent!==((e=this.context)==null?void 0:e.scene)&&((t=this.context)==null||t.scene.add(this.lines));const r=i.debugRender();this.lines.geometry.setAttribute("position",new $e(r.vertices,3)),this.lines.geometry.setAttribute("color",new $e(r.colors,4))}else this.lines&&((n=this.context)==null||n.scene.remove(this.lines))}syncObjects(){if(!x2)for(let i=0;i<this.bodies.length;i++){const e=this.objects[i],t=this.bodies[i],n=e;if(n?.isCollider===!0&&!n.attachedRigidbody){const a=t.parent();a?this.syncPhysicsBody(e.gameObject,a,!0,!0):this.syncPhysicsBody(e.gameObject,t,!0,!0);continue}const r=t.translation(),s=t.rotation();if(Number.isNaN(r.x)||Number.isNaN(s.x)){!n.__COLLIDER_NAN&&pt()&&(console.warn("Collider has NaN values",n.name,n.gameObject,t),n.__COLLIDER_NAN=!0);continue}const o=e.center;if(o&&o.isVector3){this._tempQuaternion.set(s.x,s.y,s.z,s.w);const a=this._tempPosition.copy(o).applyQuaternion(this._tempQuaternion),l=ki(e.gameObject);a.multiply(l),r.x-=a.x,r.y-=a.y,r.z-=a.z}Su(e.gameObject,r.x,r.y,r.z),pE(e.gameObject,s.x,s.y,s.z,s.w)}}syncPhysicsBody(i,e,t,n){if(e instanceof i5){const r=Rt(i,this._tempPosition),s=xi(i,this._tempQuaternion);switch(e.bodyType()){case W0.Fixed:case W0.KinematicPositionBased:case W0.KinematicVelocityBased:t&&e.setNextKinematicTranslation(r),n&&e.setNextKinematicRotation(s);break;default:t&&e.setTranslation(r,!1),n&&e.setRotation(s,!1);break}}else if(e instanceof g5){const r=Rt(i,this._tempPosition),s=xi(i,this._tempQuaternion),o=e[Ns];if(this.tryApplyCenter(o,r),t){const a=e.translation();(a.x!==r.x||a.y!==r.y||a.z!==r.z)&&e.setTranslation(r)}if(n){const a=e.rotation();(a.x!==s.x||a.y!==s.y||a.z!==s.z||a.w!==s.w)&&e.setRotation(s)}}}tryApplyCenter(i,e){const t=i.center;t&&i.gameObject&&(t.x!==0||t.y!==0||t.z!==0)&&(this._tempCenterPos.x=-t.x,this._tempCenterPos.y=t.y,this._tempCenterPos.z=t.z,ki(i.gameObject,this._tempCenterVec),this._tempCenterPos.multiply(this._tempCenterVec),i.attachedRigidbody?this._tempCenterPos.applyQuaternion(i.gameObject.quaternion):(xi(i.gameObject,this._tempCenterQuaternion),this._tempCenterPos.applyQuaternion(this._tempCenterQuaternion)),e.x+=this._tempCenterPos.x,e.y+=this._tempCenterPos.y,e.z+=this._tempCenterPos.z)}getRigidbodyRelativeMatrix(i,e,t,n){if(n===void 0&&(n=Ew._matricesBuffer,n.length=0),i===e){const r=ki(i,this._tempPosition);t.makeScale(r.x,r.y,r.z);for(let s=n.length-1;s>=0;s--)t.multiply(n[s]);return t}return n.push(i.matrix),i.parent&&this.getRigidbodyRelativeMatrix(i.parent,e,t,n),t}addFixedJoint(i,e){if(!this.world){console.error("Physics world not initialized");return}const t=i[Ss],n=e[Ss];this.calculateJointRelativeMatrices(i.gameObject,e.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const r=tm.fixed(Ew.centerConnectionPos,Ew.centerConnectionRot,this._tempPosition,this._tempQuaternion),s=this.world.createImpulseJoint(r,t,n,!0);es&&console.log("ADD FIXED JOINT",s)}addHingeJoint(i,e,t,n){if(!this.world){console.error("Physics world not initialized");return}const r=i[Ss],s=e[Ss];this.calculateJointRelativeMatrices(i.gameObject,e.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const o=Kf.JointData.revolute(t,this._tempPosition,n),a=this.world.createImpulseJoint(o,r,s,!0);es&&console.log("ADD HINGE JOINT",a)}calculateJointRelativeMatrices(i,e,t){i.updateWorldMatrix(!0,!1),e.updateWorldMatrix(!0,!1);const n=i.matrixWorld,r=e.matrixWorld;n.elements[0]=1,n.elements[5]=1,n.elements[10]=1,r.elements[0]=1,r.elements[5]=1,r.elements[10]=1,t.copy(r).premultiply(n.invert()).invert()}};let q0=Ew;h(q0,"_didLoadPhysicsEngine",!1),h(q0,"_matricesBuffer",[]),h(q0,"centerConnectionPos",{x:0,y:0,z:0}),h(q0,"centerConnectionRot",{x:0,y:0,z:0,w:1});class gue{constructor(e,t){h(this,"world"),h(this,"eventQueue"),h(this,"activeCollisions",[]),h(this,"activeCollisionsStay",[]),h(this,"activeTriggers",[]),this.world=e,this.eventQueue=t}handleCollisionEvents(){this.eventQueue&&this.world&&this.eventQueue.drainCollisionEvents((e,t,n)=>{const r=this.world.getCollider(e),s=this.world.getCollider(t);if(!r||!s)return;const o=r[Ns],a=s[Ns];w2&&console.log("EVT",o.name,a.name,n,r,s),o&&a&&(n?(this.onCollisionStarted(o,r,a,s),this.onCollisionStarted(a,s,o,r)):(this.onCollisionEnded(o,a),this.onCollisionEnded(a,o)))})}update(){this.onHandleCollisionStay()}onCollisionStarted(e,t,n,r){let s=null;if(e.isTrigger||n.isTrigger)ju(e.gameObject,o=>{o.onTriggerEnter&&!o.destroyed&&o.onTriggerEnter(n),this.activeTriggers.push({collider:e,component:o,otherCollider:n})});else{const o=e.gameObject;this.world.contactPair(t,r,(a,l)=>{ju(o,c=>{var u;if(c.destroyed)return;const d=c.onCollisionEnter||c.onCollisionStay||c.onCollisionExit;if(d||w2){if(!s){const p=[],f=a.normal();for(let m=0;m<a.numSolverContacts();m++){const A=a.solverContactPoint(m),v=a.contactImpulse(m);if(A){const g=a.contactDist(m),y=a.solverContactFriction(m),b=a.solverContactTangentVelocity(m),_=new A5(A,g,f,v,y,b);p.push(_),w2&&Ct.DrawDirection(A,f,16711680,3,!0)}}s=new y5(o,n,p)}if(d){const p={collider:e,component:c,collision:s};this.activeCollisions.push(p),c.onCollisionStay&&this.activeCollisionsStay.push(p),(u=c.onCollisionEnter)==null||u.call(c,s)}}})})}}onHandleCollisionStay(){for(const e of this.activeCollisionsStay){const t=e.component;if(!t.destroyed&&t.activeAndEnabled&&t.onCollisionStay){if(e.collision.collider.destroyed)continue;const n=e.collision;t.onCollisionStay(n)}}for(const e of this.activeTriggers){const t=e.component;if(!t.destroyed&&t.activeAndEnabled&&t.onTriggerStay){const n=e.otherCollider;if(n.destroyed)continue;t.onTriggerStay(n)}}}onCollisionEnded(e,t){if(!(e.destroyed||t.destroyed)){for(let n=0;n<this.activeCollisions.length;n++){const r=this.activeCollisions[n],s=r.collider;if(s.destroyed||r.collision.collider.destroyed){this.activeCollisions.splice(n,1),n--;continue}if(s===e&&r.collision.collider===t){const o=r.component;if(this.activeCollisions.splice(n,1),n--,o.activeAndEnabled&&o.onCollisionExit){const a=r.collision;o.onCollisionExit(a)}}}for(let n=0;n<this.activeCollisionsStay.length;n++){const r=this.activeCollisionsStay[n],s=r.collider;if(s.destroyed||r.collision.collider.destroyed){this.activeCollisionsStay.splice(n,1),n--;continue}if(s===e&&r.collision.collider===t){const o=r.component;if(this.activeCollisionsStay.splice(n,1),n--,o.activeAndEnabled&&o.onCollisionExit){const a=r.collision;o.onCollisionExit(a)}}}for(let n=0;n<this.activeTriggers.length;n++){const r=this.activeTriggers[n],s=r.collider;if(s.destroyed||r.otherCollider.destroyed){this.activeTriggers.splice(n,1),n--;continue}if(s===e&&r.otherCollider===t){const o=r.component;if(this.activeTriggers.splice(n,1),n--,o.activeAndEnabled&&o.onTriggerExit){const a=r.otherCollider;o.onTriggerExit(a)}}}}}}function vue(i,e,t,n="image/webp",r){if(!i&&(i=ii.Current,!i))return console.error("Can not save screenshot: No needle-engine context found or provided."),null;if(!r&&(r=i.mainCamera,!r))return console.error("No camera found"),null;const s=i.renderer.domElement.width,o=i.renderer.domElement.height;e||(e=s),t||(t=o);const a=window.devicePixelRatio||1;e/=a,t/=a,i.renderer.domElement.style.width=e+"px",i.renderer.domElement.style.height=t+"px";try{const l=i.renderer.domElement;return i.renderer.setSize(e,t,!1),r instanceof kt&&i.updateAspect(r,e,t),i.renderNow(),l.toDataURL(n)}finally{i.renderer.setSize(s,o,!1),i.updateSize()}return null}let X0=null;function Aue(i,e){if(i){if(!i.startsWith("data:image")){console.error("Can not save image: Data url is not an image",i);return}X0||(X0=document.createElement("a")),X0.href=i,X0.download=e,X0.click()}}Object.defineProperty(kt.prototype,"fov",{get:function(){return this._fov},set:function(i){const e=i!==this._fov;this._fov=i,e&&this.view!==void 0&&this.updateProjectionMatrix()}}),Object.defineProperty(kt.prototype,"near",{get:function(){return this._near},set:function(i){const e=i!==this._near;this._near=i,e&&this.view!==void 0&&this.updateProjectionMatrix()}}),Object.defineProperty(kt.prototype,"far",{get:function(){return this._far},set:function(i){const e=i!==this._far;this._far=i,e&&this.view!==void 0&&this.updateProjectionMatrix()}});const Mw=ee("debugmissingcamera");ii.registerCallback(bn.MissingCamera,i=>{var e,t,n;Mw&&console.warn("Creating missing camera");const r=i.context.scene,s=new ge;s.name="Default Fallback Camera",r.add(s);const o=new Ri;o.sourceId=((t=(e=i.files)==null?void 0:e[0])==null?void 0:t.src)??"unknown",(n=i.context.domElement.getAttribute("skybox-image"))!=null&&n.length||0>0||i.context.lightmaps.tryGetSkybox(o.sourceId)?o.clearFlags=Ju.Skybox:o.clearFlags=Ju.SolidColor,o.backgroundColor=new yi(.5,.5,.5,1),o.fieldOfView=35,o.backgroundBlurriness=.2;const a=nh(s,o,!0);return s.position.x=0,s.position.y=1,s.position.z=2,x5(i.context,a),a}),ii.registerCallback(bn.ContextCreated,i=>{if(!i.context.mainCamera){Mw&&console.log("Will not auto-fit because a default camera exists");return}const e=i.context.domElement;if(e?.cameraControls===!0){const t=aie(i.context.mainCamera);if(t?.isCameraController===!0){Mw&&console.log("Will not auto-fit because a camera controller exists");return}x5(i.context)}});function x5(i,e){e=e??i.mainCameraComponent;const t=e?.gameObject;if(Mw&&console.log("Creating default camera controls",e?.name),t){const n=Yg(t,bi);n.sourceId=e?.sourceId??"unknown";const r=i.domElement.getAttribute("auto-rotate");n.autoRotate=r!==void 0&&(r===""||r==="true"),n.autoRotateSpeed=.5;const s=i,o=()=>{s.pre_render_callbacks.splice(s.pre_render_callbacks.indexOf(o),1),n.fitCamera()};s.pre_render_callbacks.push(o)}else console.warn("Missing camera object, can not add orbit controls")}const C2={Context:Lt,glTF:{loadFromURL:h2}};globalThis.Needle!==void 0&&console.warn("Needle Engine is already imported"),globalThis.Needle=C2;function w5(i){for(const e in i)C2[e]=i[e]}w5(kee),w5(khe);for(const i of Object.getOwnPropertyNames(re))switch(i){case"prototype":case"constructor":case"length":case"name":continue;default:C2[i]=re[i];break}globalThis.THREE?console.warn("Threejs is already imported"):globalThis.THREE=j9;class yue{constructor(e){if(this._retries=0,!Number.isInteger(e)||e<0)throw new Error("Backoff must be a positive integer");this.backoff=e}get retries(){return this._retries}get current(){return this.backoff}next(){return this._retries++,this.backoff}reset(){this._retries=0}}class bue{constructor(e,t){if(this._retries=0,!Number.isInteger(e)||e<0)throw new Error("Base must be a positive integer or zero");if(t!==void 0&&(!Number.isInteger(t)||t<0))throw new Error("ExpMax must be a undefined, a positive integer or zero");this.base=e,this.expMax=t,this.i=0}get retries(){return this._retries}get current(){return this.base*Math.pow(2,this.i)}next(){return this._retries++,this.i=this.expMax===void 0?this.i+1:Math.min(this.i+1,this.expMax),this.current}reset(){this._retries=0,this.i=0}}class _ue{constructor(e,t,n){if(this.i=0,this._retries=0,e<0)throw new Error("Initial must be a positive number or zero");if(t<0)throw new Error("Increment must be a positive number or zero");if(n!==void 0&&n<0)throw new Error("Max must be undefined, a positive number or zero");if(n!==void 0&&n<e)throw new Error("Max must be undefined or greater than or equal to initial");this.initial=e,this.increment=t,this.max=n}get retries(){return this._retries}get current(){return this.max===void 0?this.initial+this.increment*this.i:Math.min(this.initial+this.increment*this.i,this.max)}next(){return this._retries++,this.i++,this.current}reset(){this._retries=0,this.i=0}}class xue{constructor(){this.elements=[]}add(e){this.elements.push(e)}clear(){this.elements.length=0}forEach(e){this.elements.forEach(e)}length(){return this.elements.length}isEmpty(){return this.elements.length===0}peek(){return this.elements[0]}read(){return this.elements.shift()}}class wue{constructor(e){if(!Number.isInteger(e)||e<=0)throw new Error("Capacity must be a positive integer");this.elements=new Array(e+1),this.head=0,this.tail=0}add(e){this.elements[this.head]=e,this.head=(this.head+1)%this.elements.length,this.head===this.tail&&(this.tail=(this.tail+1)%this.elements.length)}clear(){this.head=0,this.tail=0}forEach(e){for(let t=this.tail;t!==this.head;t=(t+1)%this.elements.length)e(this.elements[t])}length(){return this.tail===this.head?0:this.tail<this.head?this.head-this.tail:this.elements.length-this.tail+this.head}isEmpty(){return this.head===this.tail}peek(){return this.isEmpty()?void 0:this.elements[this.tail]}read(){const e=this.peek();return e!==void 0&&(this.tail=(this.tail+1)%this.elements.length),e}}var Si;(function(i){i.open="open",i.close="close",i.error="error",i.message="message",i.retry="retry",i.reconnect="reconnect"})(Si||(Si={}));class S5{constructor(e,t,n){var r,s,o,a,l,c,u,d,p,f,m,A,v,g,y;this._closedByUser=!1,this.handleOpenEvent=b=>this.handleEvent(Si.open,b),this.handleErrorEvent=b=>this.handleEvent(Si.error,b),this.handleCloseEvent=b=>this.handleEvent(Si.close,b),this.handleMessageEvent=b=>this.handleEvent(Si.message,b),this._url=e,this._protocols=t,this._options={buffer:n?.buffer,retry:{maxRetries:(r=n?.retry)===null||r===void 0?void 0:r.maxRetries,instantReconnect:(s=n?.retry)===null||s===void 0?void 0:s.instantReconnect,backoff:(o=n?.retry)===null||o===void 0?void 0:o.backoff},listeners:{open:[...(l=(a=n?.listeners)===null||a===void 0?void 0:a.open)!==null&&l!==void 0?l:[]],close:[...(u=(c=n?.listeners)===null||c===void 0?void 0:c.close)!==null&&u!==void 0?u:[]],error:[...(p=(d=n?.listeners)===null||d===void 0?void 0:d.error)!==null&&p!==void 0?p:[]],message:[...(m=(f=n?.listeners)===null||f===void 0?void 0:f.message)!==null&&m!==void 0?m:[]],retry:[...(v=(A=n?.listeners)===null||A===void 0?void 0:A.retry)!==null&&v!==void 0?v:[]],reconnect:[...(y=(g=n?.listeners)===null||g===void 0?void 0:g.reconnect)!==null&&y!==void 0?y:[]]}},this._underlyingWebsocket=this.tryConnect()}get url(){return this._url}get protocols(){return this._protocols}get buffer(){return this._options.buffer}get maxRetries(){return this._options.retry.maxRetries}get instantReconnect(){return this._options.retry.instantReconnect}get backoff(){return this._options.retry.backoff}get closedByUser(){return this._closedByUser}get lastConnection(){return this._lastConnection}get underlyingWebsocket(){return this._underlyingWebsocket}get readyState(){return this._underlyingWebsocket.readyState}get bufferedAmount(){return this._underlyingWebsocket.bufferedAmount}get extensions(){return this._underlyingWebsocket.extensions}get binaryType(){return this._underlyingWebsocket.binaryType}set binaryType(e){this._underlyingWebsocket.binaryType=e}send(e){this.closedByUser||(this._underlyingWebsocket.readyState===this._underlyingWebsocket.OPEN?this._underlyingWebsocket.send(e):this.buffer!==void 0&&this.buffer.add(e))}close(e,t){this.cancelScheduledConnectionRetry(),this._closedByUser=!0,this._underlyingWebsocket.close(e,t)}addEventListener(e,t,n){this._options.listeners[e].push({listener:t,options:n})}removeEventListener(e,t,n){const r=s=>s.listener!==t||s.options!==n;this._options.listeners[e]=this._options.listeners[e].filter(r)}tryConnect(){return this._underlyingWebsocket=new WebSocket(this.url,this.protocols),this._underlyingWebsocket.addEventListener(Si.open,this.handleOpenEvent),this._underlyingWebsocket.addEventListener(Si.close,this.handleCloseEvent),this._underlyingWebsocket.addEventListener(Si.error,this.handleErrorEvent),this._underlyingWebsocket.addEventListener(Si.message,this.handleMessageEvent),this._underlyingWebsocket}clearWebsocket(){this._underlyingWebsocket.removeEventListener(Si.open,this.handleOpenEvent),this._underlyingWebsocket.removeEventListener(Si.close,this.handleCloseEvent),this._underlyingWebsocket.removeEventListener(Si.error,this.handleErrorEvent),this._underlyingWebsocket.removeEventListener(Si.message,this.handleMessageEvent),this._underlyingWebsocket.close()}dispatchEvent(e,t){const n=this._options.listeners[e],r=[];n.forEach(({listener:s,options:o})=>{s(this,t),(o===void 0||o.once===void 0||!o.once)&&r.push({listener:s,options:o})}),this._options.listeners[e]=r}handleEvent(e,t){switch(e){case Si.close:this.dispatchEvent(e,t),this.scheduleConnectionRetryIfNeeded();break;case Si.open:if(this.backoff!==void 0&&this._lastConnection!==void 0){const n={retries:this.backoff.retries,lastConnection:new Date(this._lastConnection)},r=new CustomEvent(Si.reconnect,{detail:n});this.dispatchEvent(Si.reconnect,r),this.backoff.reset()}this._lastConnection=new Date,this.dispatchEvent(e,t),this.sendBufferedData();break;case Si.retry:this.dispatchEvent(e,t),this.clearWebsocket(),this.tryConnect();break;default:this.dispatchEvent(e,t);break}}sendBufferedData(){if(this.buffer!==void 0)for(let e=this.buffer.read();e!==void 0;e=this.buffer.read())this.send(e)}scheduleConnectionRetryIfNeeded(){if(this.closedByUser||this.backoff===void 0)return;const e=n=>{const r=new CustomEvent(Si.retry,{detail:n});this.handleEvent(Si.retry,r)},t={backoff:this._options.retry.instantReconnect===!0?0:this.backoff.next(),retries:this._options.retry.instantReconnect===!0?0:this.backoff.retries,lastConnection:this._lastConnection};(this._options.retry.maxRetries===void 0||t.retries<=this._options.retry.maxRetries)&&(this.retryTimeout=globalThis.setTimeout(()=>e(t),t.backoff))}cancelScheduledConnectionRetry(){globalThis.clearTimeout(this.retryTimeout)}}class Sue{constructor(e){this._url=e}get url(){return this._url}withProtocols(e){return this._protocols=e,this}get protocols(){return this._protocols}withMaxRetries(e){var t;return this._options=Object.assign(Object.assign({},this._options),{retry:Object.assign(Object.assign({},(t=this._options)===null||t===void 0?void 0:t.retry),{maxRetries:e})}),this}get maxRetries(){var e,t;return(t=(e=this._options)===null||e===void 0?void 0:e.retry)===null||t===void 0?void 0:t.maxRetries}withInstantReconnect(e){var t;return this._options=Object.assign(Object.assign({},this._options),{retry:Object.assign(Object.assign({},(t=this._options)===null||t===void 0?void 0:t.retry),{instantReconnect:e})}),this}get instantReconnect(){var e,t;return(t=(e=this._options)===null||e===void 0?void 0:e.retry)===null||t===void 0?void 0:t.instantReconnect}withBackoff(e){var t;return this._options=Object.assign(Object.assign({},this._options),{retry:Object.assign(Object.assign({},(t=this._options)===null||t===void 0?void 0:t.retry),{backoff:e})}),this}get backoff(){var e,t;return(t=(e=this._options)===null||e===void 0?void 0:e.retry)===null||t===void 0?void 0:t.backoff}withBuffer(e){return this._options=Object.assign(Object.assign({},this._options),{buffer:e}),this}get buffer(){var e;return(e=this._options)===null||e===void 0?void 0:e.buffer}onOpen(e,t){return this.addListener(Si.open,e,t),this}onClose(e,t){return this.addListener(Si.close,e,t),this}onError(e,t){return this.addListener(Si.error,e,t),this}onMessage(e,t){return this.addListener(Si.message,e,t),this}onRetry(e,t){return this.addListener(Si.retry,e,t),this}onReconnect(e,t){return this.addListener(Si.reconnect,e,t),this}build(){return new S5(this._url,this._protocols,this._options)}addListener(e,t,n){var r,s,o,a,l,c,u,d,p,f,m,A,v,g,y,b,_,E,I,T,M;return this._options=Object.assign(Object.assign({},this._options),{listeners:{open:(o=(s=(r=this._options)===null||r===void 0?void 0:r.listeners)===null||s===void 0?void 0:s.open)!==null&&o!==void 0?o:[],close:(c=(l=(a=this._options)===null||a===void 0?void 0:a.listeners)===null||l===void 0?void 0:l.close)!==null&&c!==void 0?c:[],error:(p=(d=(u=this._options)===null||u===void 0?void 0:u.listeners)===null||d===void 0?void 0:d.error)!==null&&p!==void 0?p:[],message:(A=(m=(f=this._options)===null||f===void 0?void 0:f.listeners)===null||m===void 0?void 0:m.message)!==null&&A!==void 0?A:[],retry:(y=(g=(v=this._options)===null||v===void 0?void 0:v.listeners)===null||g===void 0?void 0:g.retry)!==null&&y!==void 0?y:[],reconnect:(E=(_=(b=this._options)===null||b===void 0?void 0:b.listeners)===null||_===void 0?void 0:_.reconnect)!==null&&E!==void 0?E:[],[e]:[...(M=(T=(I=this._options)===null||I===void 0?void 0:I.listeners)===null||T===void 0?void 0:T[e])!==null&&M!==void 0?M:[],{listener:t,options:n}]}}),this}}const Cue=Object.freeze(Object.defineProperty({__proto__:null,ArrayQueue:xue,ConstantBackoff:yue,ExponentialBackoff:bue,LinearBackoff:_ue,RingQueue:wue,Websocket:S5,WebsocketBuilder:Sue,get WebsocketEvent(){return Si}},Symbol.toStringTag,{value:"Module"})),Wo={node:"node",material:"material",camera:"camera",light:"light"},kd="KHR_animation_pointer",Eue={CUBICSPLINE:void 0,LINEAR:Ta,STEP:Rc},C5=Qt.findNode;let E5=!1;class Mue{constructor(e){this.parser=e,this.name=kd,this.animationPointerResolver=null}setAnimationPointerResolver(e){return this.animationPointerResolver=e,this}_patchPropertyBindingFindNode(){E5||(E5=!0,Qt.findNode=function(e,t){if(t.startsWith(".materials.")){const n=t.substring(11).substring(t.indexOf(".")),r=n.indexOf("."),s=r<0?n:n.substring(0,r);let o=null;return e.traverse(a=>{o!==null||a.type!=="Mesh"&&a.type!=="SkinnedMesh"||a.material&&(a.material.uuid===s||a.material.name===s)&&(o=a.material,o!==null&&(n.endsWith(".map")?o=o.map:n.endsWith(".emissiveMap")&&(o=o.emissiveMap)))}),o}else if(t.startsWith(".nodes.")||t.startsWith(".lights.")||t.startsWith(".cameras.")){const n=t.split(".");let r;for(let s=1;s<n.length;s++){const o=n[s];if(o.length==36)r=e.getObjectByProperty("uuid",o);else if(r&&r[o]){const a=Number.parseInt(o);let l=o;a>=0&&(l=a),r=r[l]}else{const a=e.getObjectByName(o);a&&(r=a)}}if(!r){const s=C5(e,n[2]);return s||console.warn(kd+": Property binding not found",t,e,e.name,n),s}return r}return C5(e,t)})}loadAnimationTargetFromChannel(e){const t=e.target,n=t.node!==void 0?t.node:t.id;return this.parser.getDependency("node",n)}loadAnimationTargetFromChannelWithAnimationPointer(e){this._havePatchedPropertyBindings||this._patchPropertyBindingFindNode();const t=e.target,n=t.extensions&&t.extensions[kd]&&t.path&&t.path==="pointer";if(!n)return null;let r,s=Wo.node,o;if(n){const l=t.extensions[kd];let c=l.pointer;if(!c){console.warn("Invalid path",l,t);return}if(c.startsWith("/materials/")?s=Wo.material:c.startsWith("/extensions/KHR_lights_punctual/lights/")?s=Wo.light:c.startsWith("/cameras/")&&(s=Wo.camera),o=this._tryResolveTargetId(c,s),o===null||isNaN(o)){console.warn("Failed resolving animation node id: "+o,c);return}switch(s){case Wo.material:const d=("/materials/"+o.toString()+"/").length,p=c.substring(0,d);switch(r=c.substring(d),r){case"pbrMetallicRoughness/baseColorFactor":r="color";break;case"pbrMetallicRoughness/roughnessFactor":r="roughness";break;case"pbrMetallicRoughness/metallicFactor":r="metalness";break;case"emissiveFactor":r="emissive";break;case"alphaCutoff":r="alphaTest";break;case"occlusionTexture/strength":r="aoMapIntensity";break;case"normalTexture/scale":r="normalScale";break;case"pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/scale":r="map/repeat";break;case"pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/offset":r="map/offset";break;case"emissiveTexture/extensions/KHR_texture_transform/scale":r="emissiveMap/repeat";break;case"emissiveTexture/extensions/KHR_texture_transform/offset":r="emissiveMap/offset";break;case"extensions/KHR_materials_emissive_strength/emissiveStrength":r="emissiveIntensity";break;case"extensions/KHR_materials_transmission/transmissionFactor":r="transmission";break;case"extensions/KHR_materials_ior/ior":r="ior";break;case"extensions/KHR_materials_volume/thicknessFactor":r="thickness";break;case"extensions/KHR_materials_volume/attenuationColor":r="attenuationColor";break;case"extensions/KHR_materials_volume/attenuationDistance":r="attenuationDistance";break;case"extensions/KHR_materials_iridescence/iridescenceFactor":r="iridescence";break;case"extensions/KHR_materials_iridescence/iridescenceIor":r="iridescenceIOR";break;case"extensions/KHR_materials_iridescence/iridescenceThicknessMinimum":r="iridescenceThicknessRange[0]";break;case"extensions/KHR_materials_iridescence/iridescenceThicknessMaximum":r="iridescenceThicknessRange[1]";break;case"extensions/KHR_materials_clearcoat/clearcoatFactor":r="clearcoat";break;case"extensions/KHR_materials_clearcoat/clearcoatRoughnessFactor":r="clearcoatRoughness";break;case"extensions/KHR_materials_sheen/sheenColorFactor":r="sheenColor";break;case"extensions/KHR_materials_sheen/sheenRoughnessFactor":r="sheenRoughness";break;case"extensions/KHR_materials_specular/specularFactor":r="specularIntensity";break;case"extensions/KHR_materials_specular/specularColorFactor":r="specularColor";break}c=p+r;break;case Wo.node:const f=("/nodes/"+o.toString()+"/").length,m=c.substring(0,f);switch(r=c.substring(f),r){case"translation":r="position";break;case"rotation":r="quaternion";break;case"scale":r="scale";break;case"weights":r="morphTargetInfluences";break}c=m+r;break;case Wo.light:const A=("/extensions/KHR_lights_punctual/lights/"+o.toString()+"/").length;switch(r=c.substring(A),r){case"color":break;case"intensity":break;case"spot/innerConeAngle":r="penumbra";break;case"spot/outerConeAngle":r="angle";break;case"range":r="distance";break}c="/lights/"+o.toString()+"/"+r;break;case Wo.camera:const v=("/cameras/"+o.toString()+"/").length,g=c.substring(0,v);switch(r=c.substring(v),r){case"perspective/yfov":r="fov";break;case"perspective/znear":case"orthographic/znear":r="near";break;case"perspective/zfar":case"orthographic/zfar":r="far";break;case"perspective/aspect":r="aspect";break;case"orthographic/xmag":r="zoom";break;case"orthographic/ymag":r="zoom";break}c=g+r;break}const u=this.animationPointerResolver;u&&u.resolvePath&&(c=u.resolvePath(c)),t.extensions[kd].pointer=c}if(o===null||isNaN(o)){console.warn("Failed resolving animation node id: "+o,t);return}let a;return s===Wo.node?a=this.parser.getDependency("node",o):s===Wo.material?a=this.parser.getDependency("material",o):s===Wo.light?a=this.parser.getDependency("light",o):s===Wo.camera?a=this.parser.getDependency("camera",o):console.error("Unhandled type",s),a}createAnimationTracksWithAnimationPointer(e,t,n,r,s){if(!(s.extensions&&s.extensions[kd]&&s.path&&s.path==="pointer"))return null;let o=s.extensions[kd].pointer;if(!o)return null;const a=[];o=o.replaceAll("/",".");const l=o.split(".");var c=e.name!==void 0&&e.name!==null?e.name:e.uuid;if(l[2]=c,l[3]==="morphTargetInfluences"&&e.type==="Group"){for(const d of e.children)d instanceof Ao&&d.morphTargetInfluences&&(l[3]=d.name,l[4]="morphTargetInfluences",u(this.parser));return a}u(this.parser);function u(d){o=l.join(".");let p;switch(n.itemSize){case 1:p=zc;break;case 2:case 3:p=Bl;break;case 4:o.endsWith(".quaternion")?p=Pa:p=Ty;break}const f=r.interpolation!==void 0?Eue[r.interpolation]:Ta;let m=d._getArrayFromAccessor(n);o.endsWith(".fov")&&(m=m.map(v=>v/Math.PI*180));const A=new p(o,t.array,m,f);if(f==="CUBICSPLINE"&&d._createCubicSplineTrackInterpolant(A),a.push(A),o&&n.itemSize===4&&o.startsWith(".materials.")&&o.endsWith(".color")){const v=new Float32Array(m.length/4);for(let y=0,b=m.length/4;y<b;y+=1)v[y]=m[y*4+3];const g=new p(o.replace(".color",".opacity"),t.array,v,f);f==="CUBICSPLINE"&&d._createCubicSplineTrackInterpolant(A),a.push(g)}}return a}_tryResolveTargetId(e,t){let n="";return t==="node"?n=e.substring(7):t==="material"?n=e.substring(11):t==="light"?n=e.substring(39):t==="camera"&&(n=e.substring(9)),n=n.substring(0,n.indexOf("/")),Number.parseInt(n)}loadAnimation(e){const t=this,n=this.parser.json,r=this.parser,s=n.animations[e],o=s.name?s.name:"animation_"+e,a=[],l=[],c=[],u=[],d=[];for(let p=0,f=s.channels.length;p<f;p++){const m=s.channels[p],A=s.samplers[m.sampler],v=m.target,g=s.parameters!==void 0?s.parameters[A.input]:A.input,y=s.parameters!==void 0?s.parameters[A.output]:A.output;let b=t.loadAnimationTargetFromChannelWithAnimationPointer(m);b||(b=t.loadAnimationTargetFromChannel(m)),a.push(b),l.push(r.getDependency("accessor",g)),c.push(r.getDependency("accessor",y)),u.push(A),d.push(v)}return Promise.all([Promise.all(a),Promise.all(l),Promise.all(c),Promise.all(u),Promise.all(d)]).then(function(p){const f=p[0],m=p[1],A=p[2],v=p[3],g=p[4],y=[];for(let b=0,_=f.length;b<_;b++){const E=f[b],I=m[b],T=A[b],M=v[b],D=g[b];if(E===void 0)continue;E.updateMatrix&&(E.updateMatrix(),E.matrixAutoUpdate=!0);let C=t.createAnimationTracksWithAnimationPointer(E,I,T,M,D);if(C||(C=r._createAnimationTracks(E,I,T,M,D)),C)for(let P=0;P<C.length;P++)y.push(C[P])}return new cs(o,void 0,y)})}}const Tue=Object.freeze(Object.defineProperty({__proto__:null,GLTFAnimationPointerExtension:Mue},Symbol.toStringTag,{value:"Module"}));export{fue as $physicsKey,li as ActionBuilder,LT as ActionCollection,ma as ActionModel,HL as Addressables,av as AlignmentConstraint,Up as AmbientMode,vs as Animation,Xu as AnimationCurve,Sv as AnimationExtension,G_ as AnimationTrackHandler,Sr as Animator,fh as AnimatorConditionMode,uo as AnimatorController,YT as AnimatorControllerParameterType,wv as AnimatorStateInfo,Ev as Antialiasing,Ng as Application,Zb as ApplicationEvents,Jk as AssetDatabase,ni as AssetReference,zh as AudioExtension,ph as AudioListener,en as AudioSource,_v as AudioTrackHandler,ed as Avatar,id as AvatarBlink_Simple,uf as AvatarEyeLook_Rotation,sI as AvatarLoader,Er as AvatarMarker,K_ as AvatarModel,Pv as Avatar_Brain_LookAt,Dv as Avatar_MouthShapes,iI as Avatar_MustacheShake,Ja as Avatar_POI,tf as Axes,df as AxesHelper,TE as BUILD_TIME,Ca as BaseUIComponent,aI as BasicIKConstraint,Z_ as BehaviorExtension,_r as BehaviorModel,Ie as Behaviour,nd as Bloom,Lv as BoxCollider,rd as BoxGizmo,Za as BoxHelperComponent,rc as Button,h4 as CallDirection,nf as CallInfo,Ri as Camera,gv as CameraTargetReachedEvent,Mr as Canvas,bh as CanvasGroup,gh as CapsuleCollider,Af as ChangeMaterialOnClick,ad as ChangeTransformOnClick,cd as CharacterController,ac as CharacterControllerInput,Qv as ChromaticAberration,bo as CircularBuffer,Ju as ClearFlags,Wa as ClipExtrapolation,zo as Collider,y5 as Collision,B_ as CollisionDetectionMode,wh as ColorAdjustments,dd as ColorBySpeedModule,i0 as ColorOverLifetimeModule,Ie as Component,fg as ComponentEvents,mg as ComponentLifecycleEvents,bU as ConnectionEvents,A5 as ContactPoint,Th as ContactShadows,Lt as Context,wee as ContextArgs,bn as ContextEvent,ii as ContextRegistry,Q_ as ControlTrackHandler,Rh as CustomBranding,Aa as CustomShader,c_ as DefaultReflectionMode,VI as Deletable,Cx as DeleteBox,_a as DepthOfField,Ex as DeviceFlag,WI as DocumentExtension,Go as DragControls,Z4 as DragMode,l0 as DropListener,vd as Duplicatable,pf as EXTENSION_NAME,el as EmissionModule,bf as EmphasizeOnClick,aT as EngineLoadingView,Hn as EventList,D_ as EventListEvent,Lo as EventSystem,Ix as EventTrigger,kI as FieldWithDefault,Lb as FileReference,WL as FileReferenceSerializer,iz as FileSpawnModel,tz as File_Event,tR as FixedJoint,iR as FlyControls,Df as Fog,Pn as FrameEvent,_b as GENERATOR,re as GameObject,Ct as Gizmos,d0 as GltfExport,cR as GltfExportBox,Dd as GltfLoadEvent,Fj as GltfLoadEventType,Ch as Gradient,sd as Graphic,k_ as GraphicRaycaster,oa as Graphics,Lf as GridHelper,bI as GridLayoutGroup,Ad as GroundProjectedEnv,lh as GroupActionModel,yF as HideFlags,wI as HideOnStart,c0 as HingeJoint,yI as HorizontalLayoutGroup,See as HostData,vf as Image,Ob as ImageReference,VL as ImageReferenceSerializer,Mh as InheritVelocityModule,JL as Input,za as InputEventQueue,Wi as InputEvents,bd as InputField,Yv as InstanceHandle,Xv as InstancingHandler,qo as InstancingUtil,hF as InstantiateEvent,or as InstantiateIdProvider,Sa as InstantiateOptions,HI as Interactable,m$ as JoinedRoomResponse,xZ as KeyEventArgs,Do as Keyframe,m0 as LODGroup,_d as LODModel,g$ as LeftRoomResponse,Fs as Light,$U as LightData,Dn as LimitVelocityOverLifetimeModule,Lee as LoadingElementOptions,pR as LogStats,Ws as LogType,xd as LookAt,cv as LookAtConstraint,Ir as MainModule,qT as MarkerType,Nv as MaskableGraphic,Ze as Mathf,mf as MeshCollider,$v as MeshRenderer,lt as MinMaxCurve,Ls as MinMaxGradient,Ui as NEEDLE_progressive,Cg as NEKeyboardEvent,Hl as NEPointerEvent,ii as NeedleEngine,u2 as NeedleEngineHTMLElement,l2 as NeedleGltfLoader,Bh as NeedleMenu,gb as NeedlePatchesKey,sM as NeedleXRController,mt as NeedleXRSession,wU as NeedleXRSync,MU as NeedleXRUtils,Lx as NestedGltf,xU as NetworkConnection,Ka as NetworkedStreamEvents,Z0 as NetworkedStreams,gd as Networking,fF as NewInstanceModel,_i as NoiseModule,Ys as ObjectRaycaster,Fg as ObjectUtils,wd as OffsetConstraint,ab as OneEuroFilter,hE as OneEuroFilterXYZ,Uf as OpenURL,bi as OrbitControls,gf as Outline,_U as OwnershipEvent,IM as OwnershipModel,Ah as Padding,t0 as ParticleBurst,Zx as ParticleSubEmitter,kn as ParticleSystem,Dh as ParticleSystemBaseBehaviour,Qo as ParticleSystemRenderer,Ax as ParticleSystemShapeType,Y_ as PeerHandle,vU as PeerNetworking,WU as Physics,tr as PhysicsMaterialCombine,E0 as PixelationEffect,_f as PlayAnimationOnClick,_h as PlayAudioOnClick,Ku as PlayableDirector,nm as PlayerColor,No as PlayerState,r4 as PlayerStateEvent,lf as PlayerSync,qU as PlayerView,XU as PlayerViewManager,em as PointerEventData,Ub as PointerType,Yr as PostProcessingEffect,ax as PostProcessingHandler,xf as PreliminaryAction,jv as PreliminaryTrigger,Uu as PrimitiveType,Kt as Progress,g4 as ProgressiveLoadingInfo,Jm as PromiseAllWithErrors,wC as PromiseErrorResult,yi as RGBAColor,q0 as RapierPhysics,nx as RawImage,To as RaycastOptions,mI as Rect,bs as RectTransform,Cf as ReflectionProbe,q_ as RegisteredAnimationInfo,pc as RemoteSkybox,ef as RenderTexture,XN as RenderTextureSerializer,Sn as Renderer,ZU as RendererData,Jv as RendererLightmap,Li as Rigidbody,wn as RigidbodyConstraints,Jt as RoomEvents,io as RotationBySpeedModule,jo as RotationOverLifetimeModule,fx as SceneLightSettings,$r as SceneSwitcher,Ed as ScreenCapture,fc as ScreenSpaceAmbientOcclusion,xa as ScreenSpaceAmbientOcclusionN8,la as SendQueue,YE as SerializationContext,ld as SetActiveOnClick,T0 as ShadowCatcher,sn as ShapeModule,Av as SignalAsset,of as SignalReceiver,sf as SignalReceiverEvent,xv as SignalTrackHandler,fI as Size,_s as SizeBySpeedModule,Eh as SizeOverLifetimeModule,UI as SkinnedMeshRenderer,kh as SmoothFollow,fv as SpatialGrabRaycaster,I0 as SpatialHtml,B0 as SpatialTrigger,ol as SpatialTriggerReceiver,sw as SpectatorCamera,kv as SphereCollider,VU as SphereIntersection,b5 as SphereOverlapResult,mc as Sprite,Qf as SpriteData,al as SpriteRenderer,D0 as SpriteSheet,Yie as StateMachineBehaviour,l4 as StreamEndedEvent,c4 as StreamReceivedEvent,C0 as SubEmitterSystem,lw as SyncedCamera,gc as SyncedRoom,uh as SyncedTransform,SI as TapGestureTrigger,cw as TeleportTarget,JR as TestRunner,KR as TestSimulateUserData,xs as Text,xx as TextBuilder,o0 as TextExtension,Rr as TextureSheetAnimationModule,ll as TiltShiftEffect,tF as Time,O0 as ToneMapping,yv as TrackHandler,Js as TrackType,Xi as TrailModule,Xr as TransformData,Td as TransformGizmo,xr as TriggerBuilder,Wu as TriggerModel,q as TypeStore,L_ as UIRaycastUtils,dv as UIRootComponent,Bo as USDObject,Wn as USDZExporter,Ih as USDZText,wx as USDZUIExtension,$E as Upload_Result,YN as UriSerializer,a0 as UsageMarker,v$ as UserJoinedOrLeftRoomModel,Fl as VERSION,kT as VariantAction,on as VelocityOverLifetimeModule,AI as VerticalLayoutGroup,qn as VideoPlayer,ih as ViewDevice,Id as Vignette,Gv as VisibilityAction,td as Voip,Wv as Volume,Bt as VolumeParameter,Cv as VolumeProfile,S$ as WaitForFrames,IU as WaitForPromise,TU as WaitForSeconds,bc as Watch,dw as WebARCameraBackground,no as WebARSessionRoot,Aw as WebXR,Rf as WebXRButtonFactory,bw as WebXRImageTracking,vc as WebXRImageTrackingModel,Uh as WebXRPlaneTracking,Bd as WebXRTrackedImage,U0 as XRControllerFollow,hl as XRControllerModel,Ho as XRControllerMovement,Zs as XRFlag,xw as XRRig,ys as XRState,Ya as XRStateFlag,n2 as __Ignore,tL as __internalNotifyObjectDestroyed,Nl as activeInHierarchyFieldName,AO as addAttributeChangeCallback,Gu as addComponent,ose as addCustomExtensionPlugin,nz as addFile,rz as addFileFromUrl,Ghe as addGltfLoadEventListener,nh as addNewComponent,mb as addPatch,w_ as apply,tue as applyHMRChanges,pF as beginListenDestroy,sz as beginListenFileSpawn,mF as beginListenInstantiate,hM as binaryIdentifierCasts,xee as build_scene_functions,Ru as builtinComponentKeyName,sT as calculateProgress01,wie as colorSerializer,O_ as componentSerializer,Lk as copyTexture,c2 as createGLTFLoader,$N as createMotion,ps as debugNet,Lg as debugOwner,Ym as deepClone,na as delay,gO as delayForFrames,Pb as deserializeObject,pa as destroy,RF as destroyComponentInstance,Ii as disposeObjectResources,nc as disposeStream,QL as download,tM as download_file,gg as editorGuidKeyName,MI as effectsOrder,Mp as enableSpatialConsole,Tie as eventListSerializer,Xg as findByGuid,DF as findObjectOfType,OF as findObjectsOfType,yb as findResourceUsers,ju as foreachComponent,nT as foreachComponentEnumerator,nY as forward,bO as generateQRCode,v_ as generateSeed,Qu as getComponent,Kg as getComponentInChildren,$g as getComponentInParent,Jg as getComponents,Zg as getComponentsInChildren,S_ as getComponentsInParent,mN as getFormattedDate,Z9 as getIp,$9 as getIpAndLocation,K9 as getIpCloudflare,Yo as getLoader,Yg as getOrAddComponent,ee as getParam,oY as getParentHierarchyPath,q9 as getPath,u$ as getPeerOptions,mU as getPeerjsInstance,Vg as getRaycastMesh,TY as getResourceUserCount,wu as getTempQuaternion,Zi as getTempVector,Xm as getUrlParams,fE as getWorldDirection,mE as getWorldEuler,Rt as getWorldPosition,xi as getWorldQuaternion,rg as getWorldRotation,ki as getWorldScale,Fp as hasCommercialLicense,qM as hasIndieLicense,GT as hasPointerEventComponent,da as hasProLicense,eM as hash,xN as imageToCanvas,Gp as instantiate,bF as isActiveInHierarchy,jp as isActiveSelf,kk as isAnimationAction,Q9 as isDebugMode,yu as isDesktop,zu as isDestroyed,pt as isDevEnvironment,EY as isDisposed,hO as isHostedOnGlitch,Khe as isHotReloading,Bs as isLocalNetwork,ra as isMobileDevice,bu as isMozillaXR,qy as isQuest,Zk as isResourceTrackingEnabled,Cp as isSafari,b_ as isUsingInstancing,Sp as isiOS,h2 as loadSync,cb as logHierarchy,KX as lookAtInverse,ig as lookAtObject,V9 as makeId,bC as makeIdFromRandomWords,_F as markAsInstancedRendered,xC as microphonePermissionsGranted,G9 as nameof,uO as nameofFactory,qN as objectSerializer,fie as onBeforeRender,die as onInitialized,pie as onStart,HN as onUpdate,zj as parseSync,gie as prefix,dO as pushState,W9 as randomNumber,uM as registerBinaryType,f_ as registerComponent,BI as registerComponentExtension,Fo as registerCustomEffectType,F4 as registerExportExtensions,DI as registerExtensions,Zhe as registerHotReloadType,Kw as registerLoader,vF as registerPrefabProvider,WK as registerType,vO as relativePathPrefix,yO as removeAttributeChangeCallback,rT as removeComponent,ase as removeCustomImportExtensionType,Qhe as removeGltfLoadEventListener,xY as removePatch,kl as resolveUrl,mO as sanitizeString,Aue as saveImage,vue as screenshot,dF as sendDestroyed,x as serializable,kL as serializeObject,Zp as serializeable,qg as setActive,rW as setAllowOverlayMessages,wF as setDestroyed,pY as setDevEnvironment,EE as setDisposable,tT as setDontDestroy,AC as setOrAddParamsToUrl,H9 as setParam,Hy as setParamWithoutReload,d$ as setPeerOptions,a_ as setRaycastMesh,CY as setResourceTrackingEnabled,yC as setState,gE as setWorldEuler,Qr as setWorldPosition,Su as setWorldPositionXYZ,So as setWorldQuaternion,pE as setWorldQuaternionXYZW,vE as setWorldRotation,sg as setWorldRotationXYZ,ng as setWorldScale,AE as showBalloonError,$i as showBalloonMessage,Qi as showBalloonWarning,BC as showDebugConsole,YX as slerp,g_ as syncDestroy,eI as syncField,$M as syncInstantiate,aY as textureToCanvas,t3 as tryCastBinary,xp as tryFindObject,Qj as tryFindObjectByName,Vhe as tryFindScript,i3 as tryGetGuid,$he as unregisterHotReloadType,_C as unwatchWrite,GL as upload_file,wr as validate,Wy as watchWrite};