@needle-tools/engine 3.32.18-alpha → 3.32.19-alpha

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.
@@ -3944,7 +3944,7 @@ Open this page console: `+A.toString())}const t=$s()||RD()&&Se();if(t&&(Cz(),Jq(
3944
3944
  }
3945
3945
  }
3946
3946
  `,bo?.prepend(e),t===!0&&Wk()<=0&&hz(),console.log("\u{1F335} Debug console has loaded")}},A.src="https://unpkg.com/vconsole@latest/dist/vconsole.min.js",document.body.appendChild(A)}function pz(){return document.querySelector("#__vconsole .vc-switch")||null}function Dz(){return document.querySelector("#__vconsole")||null}const yz=iA("nodevlogs");function wi(t,A=vo.Log){ta(A,t)}function Ci(t){wi(t,vo.Warn)}function qq(t){wi(t,vo.Error)}let eG;function Se(){return yz?!1:eG!==void 0?eG:pI()}function wz(t){eG=t}const Xr=new AE,iI=new w,yn=new w,Xt=new FA,Lq={X:new w(1,0,0),Y:new w(0,1,0),Z:new w(0,0,1)},tG={type:"change"},xq={type:"mouseDown"},Yq={type:"mouseUp",mode:null},Tq={type:"objectChange"};class Sz extends wA{constructor(A,e){super(),e===void 0&&(console.warn('THREE.TransformControls: The second parameter "domElement" is now mandatory.'),e=document),this.isTransformControls=!0,this.visible=!1,this.domElement=e,this.domElement.style.touchAction="none";const i=new gG;this._gizmo=i,this.add(i);const g=new Rz;this._plane=g,this.add(g);const I=this;function o(l,p){let D=p;Object.defineProperty(I,l,{get:function(){return D!==void 0?D:p},set:function(S){D!==S&&(D=S,g[l]=S,i[l]=S,I.dispatchEvent({type:l+"-changed",value:S}),I.dispatchEvent(tG))}}),I[l]=p,g[l]=p,i[l]=p}o("camera",A),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 s=new w,C=new w,a=new FA,n=new FA,B=new w,Q=new FA,E=new w,h=new w,d=new w,u=0,c=new w;o("worldPosition",s),o("worldPositionStart",C),o("worldQuaternion",a),o("worldQuaternionStart",n),o("cameraPosition",B),o("cameraQuaternion",Q),o("pointStart",E),o("pointEnd",h),o("rotationAxis",d),o("rotationAngle",u),o("eye",c),this._offset=new w,this._startNorm=new w,this._endNorm=new w,this._cameraScale=new w,this._parentPosition=new w,this._parentQuaternion=new FA,this._parentQuaternionInv=new FA,this._parentScale=new w,this._worldScaleStart=new w,this._worldQuaternionInv=new FA,this._worldScale=new w,this._positionStart=new w,this._quaternionStart=new FA,this._scaleStart=new w,this._getPointer=fz.bind(this),this._onPointerDown=kz.bind(this),this._onPointerHover=mz.bind(this),this._onPointerMove=Gz.bind(this),this._onPointerUp=Mz.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(A){if(this.object===void 0||this.dragging===!0)return;Xr.setFromCamera(A,this.camera);const e=iG(this._gizmo.picker[this.mode],Xr);e?this.axis=e.object.name:this.axis=null}pointerDown(A){if(!(this.object===void 0||this.dragging===!0||A.button!==0)&&this.axis!==null){Xr.setFromCamera(A,this.camera);const e=iG(this._plane,Xr,!0);e&&(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(e.point).sub(this.worldPositionStart)),this.dragging=!0,xq.mode=this.mode,this.dispatchEvent(xq)}}pointerMove(A){const e=this.axis,i=this.mode,g=this.object;let I=this.space;if(i==="scale"?I="local":(e==="E"||e==="XYZE"||e==="XYZ")&&(I="world"),g===void 0||e===null||this.dragging===!1||A.button!==-1)return;Xr.setFromCamera(A,this.camera);const o=iG(this._plane,Xr,!0);if(o){if(this.pointEnd.copy(o.point).sub(this.worldPositionStart),i==="translate")this._offset.copy(this.pointEnd).sub(this.pointStart),I==="local"&&e!=="XYZ"&&this._offset.applyQuaternion(this._worldQuaternionInv),e.indexOf("X")===-1&&(this._offset.x=0),e.indexOf("Y")===-1&&(this._offset.y=0),e.indexOf("Z")===-1&&(this._offset.z=0),I==="local"&&e!=="XYZ"?this._offset.applyQuaternion(this._quaternionStart).divide(this._parentScale):this._offset.applyQuaternion(this._parentQuaternionInv).divide(this._parentScale),g.position.copy(this._offset).add(this._positionStart),this.translationSnap&&(I==="local"&&(g.position.applyQuaternion(Xt.copy(this._quaternionStart).invert()),e.search("X")!==-1&&(g.position.x=Math.round(g.position.x/this.translationSnap)*this.translationSnap),e.search("Y")!==-1&&(g.position.y=Math.round(g.position.y/this.translationSnap)*this.translationSnap),e.search("Z")!==-1&&(g.position.z=Math.round(g.position.z/this.translationSnap)*this.translationSnap),g.position.applyQuaternion(this._quaternionStart)),I==="world"&&(g.parent&&g.position.add(iI.setFromMatrixPosition(g.parent.matrixWorld)),e.search("X")!==-1&&(g.position.x=Math.round(g.position.x/this.translationSnap)*this.translationSnap),e.search("Y")!==-1&&(g.position.y=Math.round(g.position.y/this.translationSnap)*this.translationSnap),e.search("Z")!==-1&&(g.position.z=Math.round(g.position.z/this.translationSnap)*this.translationSnap),g.parent&&g.position.sub(iI.setFromMatrixPosition(g.parent.matrixWorld))));else if(i==="scale"){if(e.search("XYZ")!==-1){let s=this.pointEnd.length()/this.pointStart.length();this.pointEnd.dot(this.pointStart)<0&&(s*=-1),yn.set(s,s,s)}else iI.copy(this.pointStart),yn.copy(this.pointEnd),iI.applyQuaternion(this._worldQuaternionInv),yn.applyQuaternion(this._worldQuaternionInv),yn.divide(iI),e.search("X")===-1&&(yn.x=1),e.search("Y")===-1&&(yn.y=1),e.search("Z")===-1&&(yn.z=1);g.scale.copy(this._scaleStart).multiply(yn),this.scaleSnap&&(e.search("X")!==-1&&(g.scale.x=Math.round(g.scale.x/this.scaleSnap)*this.scaleSnap||this.scaleSnap),e.search("Y")!==-1&&(g.scale.y=Math.round(g.scale.y/this.scaleSnap)*this.scaleSnap||this.scaleSnap),e.search("Z")!==-1&&(g.scale.z=Math.round(g.scale.z/this.scaleSnap)*this.scaleSnap||this.scaleSnap))}else if(i==="rotate"){this._offset.copy(this.pointEnd).sub(this.pointStart);const s=20/this.worldPosition.distanceTo(iI.setFromMatrixPosition(this.camera.matrixWorld));let C=!1;e==="XYZE"?(this.rotationAxis.copy(this._offset).cross(this.eye).normalize(),this.rotationAngle=this._offset.dot(iI.copy(this.rotationAxis).cross(this.eye))*s):(e==="X"||e==="Y"||e==="Z")&&(this.rotationAxis.copy(Lq[e]),iI.copy(Lq[e]),I==="local"&&iI.applyQuaternion(this.worldQuaternion),iI.cross(this.eye),iI.length()===0?C=!0:this.rotationAngle=this._offset.dot(iI.normalize())*s),(e==="E"||C)&&(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),I==="local"&&e!=="E"&&e!=="XYZE"?(g.quaternion.copy(this._quaternionStart),g.quaternion.multiply(Xt.setFromAxisAngle(this.rotationAxis,this.rotationAngle)).normalize()):(this.rotationAxis.applyQuaternion(this._parentQuaternionInv),g.quaternion.copy(Xt.setFromAxisAngle(this.rotationAxis,this.rotationAngle)),g.quaternion.multiply(this._quaternionStart).normalize())}this.dispatchEvent(tG),this.dispatchEvent(Tq)}}pointerUp(A){A.button===0&&(this.dragging&&this.axis!==null&&(Yq.mode=this.mode,this.dispatchEvent(Yq)),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(A){A.geometry&&A.geometry.dispose(),A.material&&A.material.dispose()})}attach(A){return this.object=A,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(tG),this.dispatchEvent(Tq),this.pointStart.copy(this.pointEnd))}getRaycaster(){return Xr}getMode(){return this.mode}setMode(A){this.mode=A}setTranslationSnap(A){this.translationSnap=A}setRotationSnap(A){this.rotationSnap=A}setScaleSnap(A){this.scaleSnap=A}setSize(A){this.size=A}setSpace(A){this.space=A}}function fz(t){if(this.domElement.ownerDocument.pointerLockElement)return{x:0,y:0,button:t.button};{const A=this.domElement.getBoundingClientRect();return{x:(t.clientX-A.left)/A.width*2-1,y:-(t.clientY-A.top)/A.height*2+1,button:t.button}}}function mz(t){if(this.enabled)switch(t.pointerType){case"mouse":case"pen":this.pointerHover(this._getPointer(t));break}}function kz(t){this.enabled&&(document.pointerLockElement||this.domElement.setPointerCapture(t.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.pointerHover(this._getPointer(t)),this.pointerDown(this._getPointer(t)))}function Gz(t){this.enabled&&this.pointerMove(this._getPointer(t))}function Mz(t){this.enabled&&(this.domElement.releasePointerCapture(t.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.pointerUp(this._getPointer(t)))}function iG(t,A,e){const i=A.intersectObject(t,!0);for(let g=0;g<i.length;g++)if(i[g].object.visible||e)return i[g];return!1}const ND=new Wg,qt=new w(0,1,0),Hq=new w(0,0,0),_q=new NA,FD=new FA,KD=new FA,eC=new w,Oq=new NA,Tc=new w(1,0,0),$r=new w(0,1,0),Hc=new w(0,0,1),JD=new w,_c=new w,Oc=new w;class gG extends wA{constructor(){super(),this.isTransformControlsGizmo=!0,this.type="TransformControlsGizmo";const A=new st({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),e=new Ui({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),i=A.clone();i.opacity=.15;const g=e.clone();g.opacity=.5;const I=A.clone();I.color.setHex(16711680);const o=A.clone();o.color.setHex(65280);const s=A.clone();s.color.setHex(255);const C=A.clone();C.color.setHex(16711680),C.opacity=.5;const a=A.clone();a.color.setHex(65280),a.opacity=.5;const n=A.clone();n.color.setHex(255),n.opacity=.5;const B=A.clone();B.opacity=.25;const Q=A.clone();Q.color.setHex(16776960),Q.opacity=.25,A.clone().color.setHex(16776960);const E=A.clone();E.color.setHex(7895160);const h=new qi(0,.04,.1,12);h.translate(0,.05,0);const d=new _t(.08,.08,.08);d.translate(0,.04,0);const u=new le;u.setAttribute("position",new Ce([0,0,0,1,0,0],3));const c=new qi(.0075,.0075,.5,3);c.translate(0,.25,0);function l(Y,P){const b=new _a(Y,.0075,3,64,P*Math.PI*2);return b.rotateY(Math.PI/2),b.rotateX(Math.PI/2),b}function p(){const Y=new le;return Y.setAttribute("position",new Ce([0,0,0,1,1,1],3)),Y}const D={X:[[new DA(h,I),[.5,0,0],[0,0,-Math.PI/2]],[new DA(h,I),[-.5,0,0],[0,0,Math.PI/2]],[new DA(c,I),[0,0,0],[0,0,-Math.PI/2]]],Y:[[new DA(h,o),[0,.5,0]],[new DA(h,o),[0,-.5,0],[Math.PI,0,0]],[new DA(c,o)]],Z:[[new DA(h,s),[0,0,.5],[Math.PI/2,0,0]],[new DA(h,s),[0,0,-.5],[-Math.PI/2,0,0]],[new DA(c,s),null,[Math.PI/2,0,0]]],XYZ:[[new DA(new Ha(.1,0),B.clone()),[0,0,0]]],XY:[[new DA(new _t(.15,.15,.01),n.clone()),[.15,.15,0]]],YZ:[[new DA(new _t(.15,.15,.01),C.clone()),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new DA(new _t(.15,.15,.01),a.clone()),[.15,0,.15],[-Math.PI/2,0,0]]]},S={X:[[new DA(new qi(.2,0,.6,4),i),[.3,0,0],[0,0,-Math.PI/2]],[new DA(new qi(.2,0,.6,4),i),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new DA(new qi(.2,0,.6,4),i),[0,.3,0]],[new DA(new qi(.2,0,.6,4),i),[0,-.3,0],[0,0,Math.PI]]],Z:[[new DA(new qi(.2,0,.6,4),i),[0,0,.3],[Math.PI/2,0,0]],[new DA(new qi(.2,0,.6,4),i),[0,0,-.3],[-Math.PI/2,0,0]]],XYZ:[[new DA(new Ha(.2,0),i)]],XY:[[new DA(new _t(.2,.2,.01),i),[.15,.15,0]]],YZ:[[new DA(new _t(.2,.2,.01),i),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new DA(new _t(.2,.2,.01),i),[.15,0,.15],[-Math.PI/2,0,0]]]},k={START:[[new DA(new Ha(.01,2),g),null,null,null,"helper"]],END:[[new DA(new Ha(.01,2),g),null,null,null,"helper"]],DELTA:[[new Ni(p(),g),null,null,null,"helper"]],X:[[new Ni(u,g.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new Ni(u,g.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new Ni(u,g.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},f={XYZE:[[new DA(l(.5,1),E),null,[0,Math.PI/2,0]]],X:[[new DA(l(.5,.5),I)]],Y:[[new DA(l(.5,.5),o),null,[0,0,-Math.PI/2]]],Z:[[new DA(l(.5,.5),s),null,[0,Math.PI/2,0]]],E:[[new DA(l(.75,1),Q),null,[0,Math.PI/2,0]]]},U={AXIS:[[new Ni(u,g.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]]},M={XYZE:[[new DA(new Ls(.25,10,8),i)]],X:[[new DA(new _a(.5,.1,4,24),i),[0,0,0],[0,-Math.PI/2,-Math.PI/2]]],Y:[[new DA(new _a(.5,.1,4,24),i),[0,0,0],[Math.PI/2,0,0]]],Z:[[new DA(new _a(.5,.1,4,24),i),[0,0,0],[0,0,-Math.PI/2]]],E:[[new DA(new _a(.75,.1,2,24),i)]]},m={X:[[new DA(d,I),[.5,0,0],[0,0,-Math.PI/2]],[new DA(c,I),[0,0,0],[0,0,-Math.PI/2]],[new DA(d,I),[-.5,0,0],[0,0,Math.PI/2]]],Y:[[new DA(d,o),[0,.5,0]],[new DA(c,o)],[new DA(d,o),[0,-.5,0],[0,0,Math.PI]]],Z:[[new DA(d,s),[0,0,.5],[Math.PI/2,0,0]],[new DA(c,s),[0,0,0],[Math.PI/2,0,0]],[new DA(d,s),[0,0,-.5],[-Math.PI/2,0,0]]],XY:[[new DA(new _t(.15,.15,.01),n),[.15,.15,0]]],YZ:[[new DA(new _t(.15,.15,.01),C),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new DA(new _t(.15,.15,.01),a),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new DA(new _t(.1,.1,.1),B.clone())]]},x={X:[[new DA(new qi(.2,0,.6,4),i),[.3,0,0],[0,0,-Math.PI/2]],[new DA(new qi(.2,0,.6,4),i),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new DA(new qi(.2,0,.6,4),i),[0,.3,0]],[new DA(new qi(.2,0,.6,4),i),[0,-.3,0],[0,0,Math.PI]]],Z:[[new DA(new qi(.2,0,.6,4),i),[0,0,.3],[Math.PI/2,0,0]],[new DA(new qi(.2,0,.6,4),i),[0,0,-.3],[-Math.PI/2,0,0]]],XY:[[new DA(new _t(.2,.2,.01),i),[.15,.15,0]]],YZ:[[new DA(new _t(.2,.2,.01),i),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new DA(new _t(.2,.2,.01),i),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new DA(new _t(.2,.2,.2),i),[0,0,0]]]},L={X:[[new Ni(u,g.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new Ni(u,g.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new Ni(u,g.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]};function V(Y){const P=new wA;for(const b in Y)for(let T=Y[b].length;T--;){const _=Y[b][T][0].clone(),eA=Y[b][T][1],$=Y[b][T][2],IA=Y[b][T][3],yA=Y[b][T][4];_.name=b,_.tag=yA,eA&&_.position.set(eA[0],eA[1],eA[2]),$&&_.rotation.set($[0],$[1],$[2]),IA&&_.scale.set(IA[0],IA[1],IA[2]),_.updateMatrix();const xA=_.geometry.clone();xA.applyMatrix4(_.matrix),_.geometry=xA,_.renderOrder=1/0,_.position.set(0,0,0),_.rotation.set(0,0,0),_.scale.set(1,1,1),P.add(_)}return P}this.gizmo={},this.picker={},this.helper={},this.add(this.gizmo.translate=V(D)),this.add(this.gizmo.rotate=V(f)),this.add(this.gizmo.scale=V(m)),this.add(this.picker.translate=V(S)),this.add(this.picker.rotate=V(M)),this.add(this.picker.scale=V(x)),this.add(this.helper.translate=V(k)),this.add(this.helper.rotate=V(U)),this.add(this.helper.scale=V(L)),this.picker.translate.visible=!1,this.picker.rotate.visible=!1,this.picker.scale.visible=!1}updateMatrixWorld(A){const e=(this.mode==="scale"?"local":this.space)==="local"?this.worldQuaternion:KD;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 i=[];i=i.concat(this.picker[this.mode].children),i=i.concat(this.gizmo[this.mode].children),i=i.concat(this.helper[this.mode].children);for(let g=0;g<i.length;g++){const I=i[g];I.visible=!0,I.rotation.set(0,0,0),I.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),I.scale.set(1,1,1).multiplyScalar(o*this.size/4),I.tag==="helper"){I.visible=!1,I.name==="AXIS"?(I.visible=!!this.axis,this.axis==="X"&&(Xt.setFromEuler(ND.set(0,0,0)),I.quaternion.copy(e).multiply(Xt),Math.abs(qt.copy(Tc).applyQuaternion(e).dot(this.eye))>.9&&(I.visible=!1)),this.axis==="Y"&&(Xt.setFromEuler(ND.set(0,0,Math.PI/2)),I.quaternion.copy(e).multiply(Xt),Math.abs(qt.copy($r).applyQuaternion(e).dot(this.eye))>.9&&(I.visible=!1)),this.axis==="Z"&&(Xt.setFromEuler(ND.set(0,Math.PI/2,0)),I.quaternion.copy(e).multiply(Xt),Math.abs(qt.copy(Hc).applyQuaternion(e).dot(this.eye))>.9&&(I.visible=!1)),this.axis==="XYZE"&&(Xt.setFromEuler(ND.set(0,Math.PI/2,0)),qt.copy(this.rotationAxis),I.quaternion.setFromRotationMatrix(_q.lookAt(Hq,qt,$r)),I.quaternion.multiply(Xt),I.visible=this.dragging),this.axis==="E"&&(I.visible=!1)):I.name==="START"?(I.position.copy(this.worldPositionStart),I.visible=this.dragging):I.name==="END"?(I.position.copy(this.worldPosition),I.visible=this.dragging):I.name==="DELTA"?(I.position.copy(this.worldPositionStart),I.quaternion.copy(this.worldQuaternionStart),iI.set(1e-10,1e-10,1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1),iI.applyQuaternion(this.worldQuaternionStart.clone().invert()),I.scale.copy(iI),I.visible=this.dragging):(I.quaternion.copy(e),this.dragging?I.position.copy(this.worldPositionStart):I.position.copy(this.worldPosition),this.axis&&(I.visible=this.axis.search(I.name)!==-1));continue}I.quaternion.copy(e),this.mode==="translate"||this.mode==="scale"?(I.name==="X"&&Math.abs(qt.copy(Tc).applyQuaternion(e).dot(this.eye))>.99&&(I.scale.set(1e-10,1e-10,1e-10),I.visible=!1),I.name==="Y"&&Math.abs(qt.copy($r).applyQuaternion(e).dot(this.eye))>.99&&(I.scale.set(1e-10,1e-10,1e-10),I.visible=!1),I.name==="Z"&&Math.abs(qt.copy(Hc).applyQuaternion(e).dot(this.eye))>.99&&(I.scale.set(1e-10,1e-10,1e-10),I.visible=!1),I.name==="XY"&&Math.abs(qt.copy(Hc).applyQuaternion(e).dot(this.eye))<.2&&(I.scale.set(1e-10,1e-10,1e-10),I.visible=!1),I.name==="YZ"&&Math.abs(qt.copy(Tc).applyQuaternion(e).dot(this.eye))<.2&&(I.scale.set(1e-10,1e-10,1e-10),I.visible=!1),I.name==="XZ"&&Math.abs(qt.copy($r).applyQuaternion(e).dot(this.eye))<.2&&(I.scale.set(1e-10,1e-10,1e-10),I.visible=!1)):this.mode==="rotate"&&(FD.copy(e),qt.copy(this.eye).applyQuaternion(Xt.copy(e).invert()),I.name.search("E")!==-1&&I.quaternion.setFromRotationMatrix(_q.lookAt(this.eye,Hq,$r)),I.name==="X"&&(Xt.setFromAxisAngle(Tc,Math.atan2(-qt.y,qt.z)),Xt.multiplyQuaternions(FD,Xt),I.quaternion.copy(Xt)),I.name==="Y"&&(Xt.setFromAxisAngle($r,Math.atan2(qt.x,qt.z)),Xt.multiplyQuaternions(FD,Xt),I.quaternion.copy(Xt)),I.name==="Z"&&(Xt.setFromAxisAngle(Hc,Math.atan2(qt.y,qt.x)),Xt.multiplyQuaternions(FD,Xt),I.quaternion.copy(Xt))),I.visible=I.visible&&(I.name.indexOf("X")===-1||this.showX),I.visible=I.visible&&(I.name.indexOf("Y")===-1||this.showY),I.visible=I.visible&&(I.name.indexOf("Z")===-1||this.showZ),I.visible=I.visible&&(I.name.indexOf("E")===-1||this.showX&&this.showY&&this.showZ),I.material._color=I.material._color||I.material.color.clone(),I.material._opacity=I.material._opacity||I.material.opacity,I.material.color.copy(I.material._color),I.material.opacity=I.material._opacity,this.enabled&&this.axis&&(I.name===this.axis||this.axis.split("").some(function(s){return I.name===s}))&&(I.material.color.setHex(16776960),I.material.opacity=1)}super.updateMatrixWorld(A)}}class Rz extends DA{constructor(){super(new Cg(1e5,1e5,2,2),new st({visible:!1,wireframe:!0,side:dt,transparent:!0,opacity:.1,toneMapped:!1})),this.isTransformControlsPlane=!0,this.type="TransformControlsPlane"}updateMatrixWorld(A){let e=this.space;switch(this.position.copy(this.worldPosition),this.mode==="scale"&&(e="local"),JD.copy(Tc).applyQuaternion(e==="local"?this.worldQuaternion:KD),_c.copy($r).applyQuaternion(e==="local"?this.worldQuaternion:KD),Oc.copy(Hc).applyQuaternion(e==="local"?this.worldQuaternion:KD),qt.copy(_c),this.mode){case"translate":case"scale":switch(this.axis){case"X":qt.copy(this.eye).cross(JD),eC.copy(JD).cross(qt);break;case"Y":qt.copy(this.eye).cross(_c),eC.copy(_c).cross(qt);break;case"Z":qt.copy(this.eye).cross(Oc),eC.copy(Oc).cross(qt);break;case"XY":eC.copy(Oc);break;case"YZ":eC.copy(JD);break;case"XZ":qt.copy(Oc),eC.copy(_c);break;case"XYZ":case"E":eC.set(0,0,0);break}break;case"rotate":default:eC.set(0,0,0)}eC.length()===0?this.quaternion.copy(this.cameraQuaternion):(Oq.lookAt(iI.set(0,0,0),eC,qt),this.quaternion.setFromRotationMatrix(Oq)),super.updateMatrixWorld(A)}}const Uz=iA("debugpatch");function vD(t,A,e,i){const g=Uz===A;if(!e&&!i)return;const I=A+"___needle";Fz(t,A,e,i);const o=Object.getOwnPropertyDescriptor(t,A),s=t[A];g&&console.log("Patch",t.constructor.name,A,o,s),o?(g&&console.log("Apply patch with existing descriptor",t.constructor.name,A,o),typeof o.value=="function"&&(t[A]=jq(o.value,t,A))):(g&&console.log("Create patch with new property",t.constructor.name,A,o),Object.defineProperty(t,A,{set:function(C){if(typeof C=="function")this[I]=jq(C,t,A);else{const a=this[I];Wq(t,A,this,a,C),this[I]=C,Vq(t,A,this,a,C)}},get:function(){const C=this[I];return typeof C=="function"&&C[I]?C[I]:C}}))}function Nz(t,A,e){const i=oG(t,A);if(i)for(let g=i.length-1;g>=0;g--){const I=i[g];I.prefix===e&&(I.prefix=null),I.postfix===e&&(I.postfix=null),!I.prefix&&!I.postfix&&i.splice(g,1)}}const Pq=Symbol("Needle:Patches:WrappedFunction");function jq(t,A,e){if(t[Pq])return t;const i=function(...g){Wq(A,e,this,...g);const I=t.apply(this,g);return Vq(A,e,this,I,...g),I};return i[Pq]=!0,i}const bD="Needle:Patches";function IG(){return globalThis[bD]||(globalThis[bD]=new WeakMap),globalThis[bD]}function oG(t,A){const e=IG().get(t);return e?e.get(A):null}function Fz(t,A,e,i){let g=IG().get(t);g||(g=new Map,IG().set(t,g));let I=g.get(A);I||(I=[],g.set(A,I)),I.push({prefix:e,postfix:i})}function Wq(t,A,e,...i){var g;if(!e)return;const I=oG(t,A);if(I)for(const o of I)(g=o.prefix)==null||g.call(e,...i)}function Vq(t,A,e,i,...g){var I;if(!e)return;const o=oG(t,A);if(o)for(const s of o)(I=s.postfix)==null||I.call(e,i,...g)}const Zq=Symbol("gltf-loader-internal-usage-tracker"),Kz=iA("debugusers"),qD=class{constructor(t){r(this,"parser"),r(this,"_getDependency"),r(this,"_loadingId"),r(this,"_loadedObjects",new Set),this.parser=t,this._getDependency=this.parser.getDependency,this._loadingId=Date.now().toString()}get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(t){return qD._loadingProcesses>0}beforeRoot(){qD._loadingProcesses++;const t=this,A=this._getDependency;return this.parser.getDependency=function(e,i){const g=A.call(this,e,i);return g.then(I=>(I&&(t._loadedObjects.add(I),I[Zq]=t._loadingId),I)),g},null}afterRoot(t){qD._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const A of this._loadedObjects)delete A[Zq],A instanceof wA&&(A.parent||A instanceof DA&&(Kz&&console.warn("> GLTF LOADER: Mesh not used in scene!",A),A.material=null,A.geometry=null));return null}};let sG=qD;r(sG,"_loadingProcesses",0);class zq{constructor(){window.addEventListener("unhandledrejection",A=>{var e;if(A.defaultPrevented)return;const i=(e=A?.reason)==null?void 0:e.path;if(i){const g=i[0];g&&g.tagName==="IMG"&&(console.warn(`Could not load image:
3947
- `+g.src),A.preventDefault())}})}}const LD=iA("trackresources");function Xq(){return LD==="dispose"}let AB=!0;LD===0&&(AB=!1);function Jz(t){AB=t}function $q(){return AB}const AL=Symbol("disposable");function CG(t,A){t&&(t[AL]=A,eB&&console.warn("Set disposable",A,t))}const eL=Symbol("disposed");function vz(t){return t[eL]===!0}function Yt(t){var A;if(t){if(t[AL]===!1){eB&&console.warn("Object is marked as not disposable",t);return}if(t[eL]=!0,t instanceof eI)Yt(t.environment),Yt(t.background),Yt(t.customDepthMaterial),Yt(t.customDistanceMaterial);else if(t instanceof ls)Yt(t.geometry),Yt(t.material),Yt(t.skeleton),Yt(t.bindMatrix),Yt(t.bindMatrixInverse),Yt(t.customDepthMaterial),Yt(t.customDistanceMaterial),t.geometry=null,t.material=null;else if(t instanceof DA)Yt(t.geometry),Yt(t.material),Yt(t.customDepthMaterial),Yt(t.customDistanceMaterial),t.geometry=null,t.material=null;else if(t instanceof le){oE(t);for(const e of Object.keys(t.attributes)){const i=t.attributes[e];Yt(i)}}else if(t instanceof Ae||t instanceof qI)eB&&console.warn("BufferAttribute dispose not supported",t.count);else if(t instanceof Array)for(const e of t)e instanceof qe&&Yt(e);else if(t instanceof qe){oE(t);for(const i of Object.keys(t)){const g=t[i];g instanceof Ye&&(Yt(g),t[i]=null)}const e=t.uniforms;if(e)for(const i of Object.keys(e)){const g=e[i];g instanceof Ye?(Yt(g),e[i]=null):g instanceof UA&&(Yt(g.value),g.value=null)}}else t instanceof Ye?(oE(t),oE(t.source),((A=t.source)==null?void 0:A.data)instanceof ImageBitmap&&oE(t.source.data)):t instanceof Jh?(oE(t.boneTexture),t.boneTexture=null):t instanceof fc||!(t instanceof wA)&&eB&&console.warn("Unknown object type",t)}}function oE(t){t&&((eB||Xq()||LD)&&console.warn("\u{1F9E8} FREE",t),t instanceof ImageBitmap?t.close():t instanceof HC?t.data=null:t.dispose())}function tL(t){(t instanceof DA||t instanceof ls)&&(t.material=null,t.geometry=null)}const bz=new Set;function aG(t,A,e=null,i){if(i||(i=bz,i.clear()),!t)return i;const g=t[Pc];if(g)for(const I of g)i.has(I)||e?.call(null,I)!==!1&&(i.add(I),A&&aG(I,!0,e,i));return i}function qz(t){return t[jc]}const eB=iA("debugresourceusers")||iA("debugmemory"),Pc=Symbol("needle-resource-users"),jc=Symbol("needle-resource-users-count");function DI(t,A){vD(t,A,function(e,i){AB&&(xD(Pc,this,e,!1),xD(Pc,this,i,!0))})}AB&&(DI(DA.prototype,"material"),DI(DA.prototype,"geometry"),DI(qe.prototype,"map"),DI(qe.prototype,"bumpMap"),DI(qe.prototype,"alphaMap"),DI(qe.prototype,"normalMap"),DI(qe.prototype,"displacementMap"),DI(qe.prototype,"roughnessMap"),DI(qe.prototype,"metalnessMap"),DI(qe.prototype,"emissiveMap"),DI(qe.prototype,"specularMap"),DI(qe.prototype,"envMap"),DI(qe.prototype,"lightMap"),DI(qe.prototype,"aoMap"),DI(qe.prototype,"gradientMap"));function Lz(t){if(AB===!1)return;const A=t[Pc];if(A)for(const e of A)xD(Pc,e,t,!1)}AB&&vD(qe.prototype,"dispose",function(){Lz(this)});let nG=0;function xD(t,A,e,i){if(nG>0)return;if(Array.isArray(e)){for(const I of e)xD(t,A,I,i);return}if(!e)return;let g=e[t];if(g||(g=new Set),i){if(A&&!g.has(A)){g.add(A);let I=e[jc]||0;I+=1,e[jc]=I,eB&&console.warn(`\u{1F7E2} Added user of "${e.type}"`,A,e,I,"users:",g)}}else if(A&&g.has(A)){g.delete(A);let I=e[jc]||0;I>0&&(I-=1,e[jc]=I),eB&&console.warn(`\u{1F534} Removed user of "${e.type}"`,A,e,I,"users:",g),I<=0&&(sG.isLoading(e)||(LD&&console.warn(`\u{1F534} Removed all user of "${e.type}"`,e),Xq()&&Yt(e)))}e[t]=g}try{vD(zC.prototype,"render",function(){nG++},function(){nG--})}catch(t){console.warn("Could not wrap WebGLRenderer.render",t)}var Wc=(t=>(t.Added="component-added",t.Removing="removing-component",t))(Wc||{});const iL=iA("debugcomponentevents");class Vc{static addComponentLifecylceEventListener(A,e){this.eventListeners.has(A)&&this.eventListeners.set(A,[]);let i=this.eventListeners.get(A);i||(i=[]),i.push(e),this.eventListeners.set(A,i),iL&&console.log("Added event listener for "+A,this.eventListeners)}static removeComponentLifecylceEventListener(A,e){const i=this.eventListeners.get(A);if(!i)return;const g=i.indexOf(e);g<0||i.splice(g,1)}static dispatchComponentLifecycleEvent(A,e){const i=this.eventListeners.get(A);if(iL&&console.log("Dispatching event "+A,i),!!i)for(const g of i)g(e)}}r(Vc,"eventListeners",new Map);const gL=iA("debugdefines");sE('if(!globalThis[""3.32.18-alpha""]) globalThis[""3.32.18-alpha""] = "0.0.0";'),sE('if(!globalThis[""undefined""]) globalThis[""undefined""] = "unknown";'),sE('if(!globalThis[""Fri Feb 09 2024 20:31:55 GMT+0800 (Pacific Standard Time)""]) globalThis[""Fri Feb 09 2024 20:31:55 GMT+0800 (Pacific Standard Time)""] = "unknown";'),sE('globalThis["__NEEDLE_ENGINE_VERSION__"] = "3.32.18-alpha";'),sE('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),sE('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Fri Feb 09 2024 20:31:55 GMT+0800 (Pacific Standard Time)";');const ga="3.32.18-alpha",YD="undefined",xz="Fri Feb 09 2024 20:31:55 GMT+0800 (Pacific Standard Time)";gL&&console.log(`Engine version: ${ga} (generator: ${YD})
3947
+ `+g.src),A.preventDefault())}})}}const LD=iA("trackresources");function Xq(){return LD==="dispose"}let AB=!0;LD===0&&(AB=!1);function Jz(t){AB=t}function $q(){return AB}const AL=Symbol("disposable");function CG(t,A){t&&(t[AL]=A,eB&&console.warn("Set disposable",A,t))}const eL=Symbol("disposed");function vz(t){return t[eL]===!0}function Yt(t){var A;if(t){if(t[AL]===!1){eB&&console.warn("Object is marked as not disposable",t);return}if(t[eL]=!0,t instanceof eI)Yt(t.environment),Yt(t.background),Yt(t.customDepthMaterial),Yt(t.customDistanceMaterial);else if(t instanceof ls)Yt(t.geometry),Yt(t.material),Yt(t.skeleton),Yt(t.bindMatrix),Yt(t.bindMatrixInverse),Yt(t.customDepthMaterial),Yt(t.customDistanceMaterial),t.geometry=null,t.material=null;else if(t instanceof DA)Yt(t.geometry),Yt(t.material),Yt(t.customDepthMaterial),Yt(t.customDistanceMaterial),t.geometry=null,t.material=null;else if(t instanceof le){oE(t);for(const e of Object.keys(t.attributes)){const i=t.attributes[e];Yt(i)}}else if(t instanceof Ae||t instanceof qI)eB&&console.warn("BufferAttribute dispose not supported",t.count);else if(t instanceof Array)for(const e of t)e instanceof qe&&Yt(e);else if(t instanceof qe){oE(t);for(const i of Object.keys(t)){const g=t[i];g instanceof Ye&&(Yt(g),t[i]=null)}const e=t.uniforms;if(e)for(const i of Object.keys(e)){const g=e[i];g instanceof Ye?(Yt(g),e[i]=null):g instanceof UA&&(Yt(g.value),g.value=null)}}else t instanceof Ye?(oE(t),oE(t.source),((A=t.source)==null?void 0:A.data)instanceof ImageBitmap&&oE(t.source.data)):t instanceof Jh?(oE(t.boneTexture),t.boneTexture=null):t instanceof fc||!(t instanceof wA)&&eB&&console.warn("Unknown object type",t)}}function oE(t){t&&((eB||Xq()||LD)&&console.warn("\u{1F9E8} FREE",t),t instanceof ImageBitmap?t.close():t instanceof HC?t.data=null:t.dispose())}function tL(t){(t instanceof DA||t instanceof ls)&&(t.material=null,t.geometry=null)}const bz=new Set;function aG(t,A,e=null,i){if(i||(i=bz,i.clear()),!t)return i;const g=t[Pc];if(g)for(const I of g)i.has(I)||e?.call(null,I)!==!1&&(i.add(I),A&&aG(I,!0,e,i));return i}function qz(t){return t[jc]}const eB=iA("debugresourceusers")||iA("debugmemory"),Pc=Symbol("needle-resource-users"),jc=Symbol("needle-resource-users-count");function DI(t,A){vD(t,A,function(e,i){AB&&(xD(Pc,this,e,!1),xD(Pc,this,i,!0))})}AB&&(DI(DA.prototype,"material"),DI(DA.prototype,"geometry"),DI(qe.prototype,"map"),DI(qe.prototype,"bumpMap"),DI(qe.prototype,"alphaMap"),DI(qe.prototype,"normalMap"),DI(qe.prototype,"displacementMap"),DI(qe.prototype,"roughnessMap"),DI(qe.prototype,"metalnessMap"),DI(qe.prototype,"emissiveMap"),DI(qe.prototype,"specularMap"),DI(qe.prototype,"envMap"),DI(qe.prototype,"lightMap"),DI(qe.prototype,"aoMap"),DI(qe.prototype,"gradientMap"));function Lz(t){if(AB===!1)return;const A=t[Pc];if(A)for(const e of A)xD(Pc,e,t,!1)}AB&&vD(qe.prototype,"dispose",function(){Lz(this)});let nG=0;function xD(t,A,e,i){if(nG>0)return;if(Array.isArray(e)){for(const I of e)xD(t,A,I,i);return}if(!e)return;let g=e[t];if(g||(g=new Set),i){if(A&&!g.has(A)){g.add(A);let I=e[jc]||0;I+=1,e[jc]=I,eB&&console.warn(`\u{1F7E2} Added user of "${e.type}"`,A,e,I,"users:",g)}}else if(A&&g.has(A)){g.delete(A);let I=e[jc]||0;I>0&&(I-=1,e[jc]=I),eB&&console.warn(`\u{1F534} Removed user of "${e.type}"`,A,e,I,"users:",g),I<=0&&(sG.isLoading(e)||(LD&&console.warn(`\u{1F534} Removed all user of "${e.type}"`,e),Xq()&&Yt(e)))}e[t]=g}try{vD(zC.prototype,"render",function(){nG++},function(){nG--})}catch(t){console.warn("Could not wrap WebGLRenderer.render",t)}var Wc=(t=>(t.Added="component-added",t.Removing="removing-component",t))(Wc||{});const iL=iA("debugcomponentevents");class Vc{static addComponentLifecylceEventListener(A,e){this.eventListeners.has(A)&&this.eventListeners.set(A,[]);let i=this.eventListeners.get(A);i||(i=[]),i.push(e),this.eventListeners.set(A,i),iL&&console.log("Added event listener for "+A,this.eventListeners)}static removeComponentLifecylceEventListener(A,e){const i=this.eventListeners.get(A);if(!i)return;const g=i.indexOf(e);g<0||i.splice(g,1)}static dispatchComponentLifecycleEvent(A,e){const i=this.eventListeners.get(A);if(iL&&console.log("Dispatching event "+A,i),!!i)for(const g of i)g(e)}}r(Vc,"eventListeners",new Map);const gL=iA("debugdefines");sE('if(!globalThis[""3.32.19-alpha""]) globalThis[""3.32.19-alpha""] = "0.0.0";'),sE('if(!globalThis[""undefined""]) globalThis[""undefined""] = "unknown";'),sE('if(!globalThis[""Fri Feb 09 2024 21:56:34 GMT+0800 (Pacific Standard Time)""]) globalThis[""Fri Feb 09 2024 21:56:34 GMT+0800 (Pacific Standard Time)""] = "unknown";'),sE('globalThis["__NEEDLE_ENGINE_VERSION__"] = "3.32.19-alpha";'),sE('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),sE('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Fri Feb 09 2024 21:56:34 GMT+0800 (Pacific Standard Time)";');const ga="3.32.19-alpha",YD="undefined",xz="Fri Feb 09 2024 21:56:34 GMT+0800 (Pacific Standard Time)";gL&&console.log(`Engine version: ${ga} (generator: ${YD})
3948
3948
  Project built at ${xz}`);const Ia="needle_isActiveInHierarchy",tB="builtin_components",Zc="needle_editor_guid";function sE(t){try{(0,eval)(t)}catch(A){gL&&console.error(A)}}const zc=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),IL=Symbol("isUsingInstancing"),oL=Symbol("instancingRenderer"),rG=Symbol("instancingAutoUpdateBounds");class Ts{static isUsingInstancing(A){return A[IL]===!0}static getRenderer(A){return A[oL]||null}setAutoUpdateBounds(A,e){const i=Ts.getRenderer(A);i&&(i[rG]=e)}static markDirty(A,e=!0){if(A&&(this.isUsingInstancing(A)&&(A[zc]=!0,A.matrixWorldNeedsUpdate=!0),e))for(const i of A.children)Ts.markDirty(i,!0)}}function iB(t,A){try{A?t(A):t()}catch(e){return console.error(e),!1}return!0}const BG=iA("debugnewscripts"),Yz=iA("debughierarchy"),$t=[];function Tz(){return $t.length>0}function TD(t){if(!(t.new_scripts.length<=0)){if(BG&&console.log("Register new components",t.new_scripts.length,[...t.new_scripts],t.alias?"element: "+t.alias:t.hash,t),t.new_scripts_pre_setup_callbacks.length>0){for(const A of t.new_scripts_pre_setup_callbacks)A&&A();t.new_scripts_pre_setup_callbacks.length=0}$t.length=0,t.new_scripts.length>0&&$t.push(...t.new_scripts),t.new_scripts.length=0;for(let A=0;A<$t.length;A++)try{const e=$t[A];if(e.isComponent!==!0){(Se()||BG)&&console.error(`Registered script is not a Needle Engine component.
3949
3949
  The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
3950
3950
  `,e),$t.splice(A,1),A--;continue}if(e.destroyed)continue;if(!e.gameObject){console.error("MISSING GAMEOBJECT - will ignore",e),$t.splice(A,1),A--;continue}e.context=t,Xc(e.gameObject),QG(e,t)}catch(e){console.error(e),oa($t[A],t),$t.splice(A,1),A--}for(let A=0;A<$t.length;A++)try{const e=$t[A];if(e.destroyed){oa($t[A],t),$t.splice(A,1),A--;continue}if(e.registering)try{e.registering()}catch(i){console.error(i)}e.__internalAwake!==void 0&&(e.gameObject||console.error("MISSING GAMEOBJECT",e,e.gameObject),Xc(e.gameObject),e.activeAndEnabled&&iB(e.__internalAwake.bind(e)))}catch(e){console.error(e),oa($t[A],t),$t.splice(A,1),A--}for(let A=0;A<$t.length;A++)try{const e=$t[A];if(e.destroyed||e.enabled===!1||(Xc(e.gameObject),e.activeAndEnabled===!1))continue;e.__internalEnable!==void 0&&(e.enabled=!0,iB(e.__internalEnable.bind(e)))}catch(e){console.error(e),oa($t[A],t),$t.splice(A,1),A--}for(let A=0;A<$t.length;A++)try{const e=$t[A];if(e.destroyed||!e.gameObject)continue;t.new_script_start.push(e)}catch(e){console.error(e),oa($t[A],t),$t.splice(A,1),A--}$t.length=0;for(const A of t.new_scripts_post_setup_callbacks)A&&A();t.new_scripts_post_setup_callbacks.length=0}}function Hz(t){t&&(t.__internalDisable(!0),oa(t,t.context))}function sL(t,A){for(let e=0;e<t.new_script_start.length;e++)try{const i=t.new_script_start[e];if(A!==void 0&&i.gameObject!==A||i.destroyed||i.activeAndEnabled===!1)continue;iB(i.__internalAwake.bind(i)),i.enabled&&(iB(i.__internalEnable.bind(i)),iB(i.__internalStart.bind(i)),t.new_script_start.splice(e,1),e--)}catch(i){console.error(i),oa(t.new_script_start[e],t),t.new_script_start.splice(e,1),e--}}function QG(t,A){A.scripts.indexOf(t)===-1&&(A.scripts.push(t),t.earlyUpdate&&A.scripts_earlyUpdate.push(t),t.update&&A.scripts_update.push(t),t.lateUpdate&&A.scripts_lateUpdate.push(t),t.onBeforeRender&&A.scripts_onBeforeRender.push(t),t.onAfterRender&&A.scripts_onAfterRender.push(t),t.onPausedChanged&&A.scripts_pausedChanged.push(t),EG(t,null)&&A.new_scripts_xr.push(t),EG(t,"immersive-vr")&&A.scripts_immersive_vr.push(t),EG(t,"immersive-ar")&&A.scripts_immersive_ar.push(t))}function oa(t,A){qo(t,A.new_scripts),qo(t,A.new_script_start),qo(t,A.scripts),qo(t,A.scripts_earlyUpdate),qo(t,A.scripts_update),qo(t,A.scripts_lateUpdate),qo(t,A.scripts_onBeforeRender),qo(t,A.scripts_onAfterRender),qo(t,A.scripts_pausedChanged),qo(t,A.new_scripts_xr),qo(t,A.scripts_immersive_vr),qo(t,A.scripts_immersive_ar),A.stopAllCoroutinesFrom(t)}function qo(t,A){const e=A.indexOf(t);e>=0&&A.splice(e,1)}function EG(t,A){var e;if(t){const i=t;if(i.onBeforeXR||i.onEnterXR||i.onUpdateXR||i.onLeaveXR||i.onXRControllerAdded||i.onXRControllerRemoved)return!(A!=null&&((e=i.supportsXR)==null?void 0:e.call(i,A))===!1)}return!1}function HD(t){if(t||(t=mt.Current.scene),!t){console.trace("Invalid call - no current context.");return}const A=wE(t);CL(t,A,!0)||(BG||Se()?console.error(`Error updating hierarchy
@@ -4988,10 +4988,12 @@ Pinch: ${(A=this.getGesture("pinch"))==null?void 0:A.value.toFixed(3)}`),g+=`
4988
4988
  `+i.uuid,.01,5,0,new Mt(1,1,1,.1))}this.emitPointerEvent(n,0,"pinch",!1,null,B)}}}}}onUpdateMove(){var A,e;let i=!1;if(this._lastPointerMovePosition.distanceTo(this.gripWorldPosition)>.02&&(i=!0),i||this._lastPointerMoveQuaternion.angleTo(this.gripWorldQuaternion)>.02&&(i=!0),i){this._didMoveLastFrame=!0,this._lastPointerMovePosition.copy(this.gripWorldPosition),this._lastPointerMoveQuaternion.copy(this.gripWorldQuaternion),Fn&&Fe.DrawLabel(this.rayWorldPosition.add(this.object.worldForward.multiplyScalar(.1)),"move",.01);let g=this.xr.context.input.getFirstPressedButtonForPointer(this.index);g===void 0&&(g=0);const I=(e=(A=this.gamepad)==null?void 0:A.buttons[g])==null?void 0:e.value;this.emitPointerEvent("pointermove",g,"none",!1,null,I)}else this._didMoveLastFrame=!1}emitPointerEvent(A,e,i,g,I=null,o){if(!this.emitEvents){Fn&&A!==Ai.PointerMove&&console.warn("Pointer events are disabled for this controller",this.index,A,e);return}if(this.xr.mode==="immersive-vr"||this.xr.isPassThrough){this.pointerInit.origin=this,this.pointerInit.pointerId=this.index*10+e,this.pointerInit.pointerType=this.hand?"hand":"controller",this.pointerInit.button=e,this.pointerInit.buttonName=i,this.pointerInit.isPrimary=g,this.pointerInit.mode=this.inputSource.targetRayMode,this.pointerInit.ray=this.ray,this.pointerInit.device=this.object,this.pointerInit.pressure=o;const s=ve.Current;ve.Current=this.xr.context,Fn&&A!=="pointermove"&&console.warn("Pointer event",A,e,i,{...this.pointerInit}),this.xr.context.input.createInputEvent(new ra(A,I,this.pointerInit)),ve.Current=s}}}class mH{constructor(){r(this,"isDown",!1),r(this,"isUp",!1),r(this,"pressed",!1),r(this,"value",0)}}class kH{constructor(){r(this,"touched",!1),r(this,"pressed",!1),r(this,"value",0),r(this,"isDown",!1),r(this,"isUp",!1)}}const Nl=iA("debugwebxr");class yR{constructor(A,e){r(this,"controllerStates",[]),r(this,"userId"),r(this,"context"),r(this,"userStateEvtName"),r(this,"onReceivedControllerState",i=>{Nl&&console.log(`XRSync: Received change for ${this.userId}: ${i.type} ${i.handedness}; tracked=${i.isTracking}`);let g=!1;for(let I=0;I<this.controllerStates.length;I++)if(this.controllerStates[I].index===i.index){this.controllerStates[I]=i,g=!0;break}g||this.controllerStates.push(i)}),this.userId=A,this.context=e,this.userStateEvtName="xr-sync-user-state-"+A,this.context.connection.beginListen(this.userStateEvtName,this.onReceivedControllerState)}dispose(){this.context.connection.stopListen(this.userStateEvtName,this.onReceivedControllerState)}update(A){if(this.context.connection.isConnected!=!1){for(let e=this.controllerStates.length-1;e>=0;e--){const i=this.controllerStates[e];let g=!1;for(let I=0;I<A.controllers.length;I++)A.controllers[I].index===i.index&&(g=!0);g||(Nl&&console.log(`XRSync: ${i.type} ${i.handedness} removed`,i.index),this.controllerStates.splice(e,1),this.sendControllerRemoved(i))}for(const e of A.controllers)this.updateControllerStates(e)}}onExitXR(A){for(const e of this.controllerStates)this.sendControllerRemoved(e);this.controllerStates.length=0}sendControllerRemoved(A){A.isTracking=!1,A.guid="",this.context.connection.send(this.userStateEvtName,A),this.context.connection.sendDeleteRemoteState(A.guid)}updateControllerStates(A){const e=this.controllerStates.find(i=>i.index===A.index);if(e){let i=!1;i||(i=e.isTracking!=A.isTracking),i&&(e.isTracking=A.isTracking,this.context.connection.send(this.userStateEvtName,e))}else{const i={guid:this.userId+"-"+A.index,isTracking:A.isTracking,handedness:A.side,index:A.index,type:A.hand?"hand":"controller"};this.controllerStates.push(i),this.context.connection.send(this.userStateEvtName,i),Nl&&console.log(`XRSync: ${i.type} ${i.handedness} added`,i.index)}}}class GH{constructor(A){r(this,"context"),r(this,"onJoinedRoom",()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(Nl&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new yR(this.context.connection.connectionId,this.context)));for(const e of this.context.connection.usersInRoom())this._states.has(e)||this._states.set(e,new yR(e,this.context))}}),r(this,"onLeftRoom",()=>{if(this.context.connection.connectionId&&!this._states.has(this.context.connection.connectionId)){const e=this._states.get(this.context.connection.connectionId);e?.dispose(),this._states.delete(this.context.connection.connectionId)}}),r(this,"onOtherUserJoinedRoom",e=>{const i=e.userId;this._states.has(i)||(Nl&&console.log("XRSync: Remote user joined room",i),this._states.set(i,new yR(i,this.context)))}),r(this,"onOtherUserLeftRoom",e=>{const i=e.userId;if(!this._states.has(i)){const g=this._states.get(i);g?.dispose(),this._states.delete(i)}}),r(this,"_states",new Map),this.context=A,this.context.connection.beginListen(ht.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ht.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(ht.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(ht.UserLeftRoom,this.onOtherUserLeftRoom)}hasState(A){return A?this._states.has(A):!1}isTracking(A,e){if(!A)return;const i=this._states.get(A);if(!i)return;const g=i.controllerStates.find(I=>I.handedness===e);return g?.isTracking||!1}getDeviceType(A,e){if(!A)return;const i=this._states.get(A);if(!i)return;const g=i.controllerStates.find(I=>I.handedness===e);return g?.type||"unknown"}destroy(){this.context.connection.stopListen(ht.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ht.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(ht.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(ht.UserLeftRoom,this.onOtherUserLeftRoom)}onUpdate(A){if(this.context.connection.isConnected&&this.context.connection.connectionId){const e=this._states.get(this.context.connection.connectionId);e?.update(A)}}onExitXR(A){if(this.context.connection.isConnected&&this.context.connection.connectionId){const e=this._states.get(this.context.connection.connectionId);e?.onExitXR(A)}}}class MH{constructor(){r(this,"_fadeToColorQuad"),r(this,"_fadeToColorMaterial"),r(this,"_requestedFadeValue",0),r(this,"_transitionPromise",null),r(this,"_transitionResolve",null),this._fadeToColorMaterial=new st({color:0,transparent:!0,depthTest:!1,fog:!1,side:dt}),this._fadeToColorQuad=new DA(new Cg(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(A,e){const i=this._fadeToColorQuad,g=this._fadeToColorMaterial;i.parent!==A&&g.opacity>0?A.add(i):g.opacity===0&&i.removeFromParent(),i.layers.set(2),i.material=this._fadeToColorMaterial,i.position.z=-1,i.renderOrder=1/0;const I=this._requestedFadeValue;g.opacity=Ie.lerp(g.opacity,I,e/.03),Math.abs(g.opacity-I)<=.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 A=new Promise(e=>{this._transitionResolve=e});return this._transitionPromise=A,A}}var EB=(t=>(t[t.Quad=0]="Quad",t[t.Cube=1]="Cube",t[t.Sphere=2]="Sphere",t))(EB||{});class DE{static createPrimitive(A,e){let i;switch(A){case 0:const g=new Cg(1,1,1,1),I=e?.material??new OI({color:16777215});i=new DA(g,I);break;case 1:const o=new _t(1,1,1),s=e?.material??new OI({color:16777215});i=new DA(o,s);break;case 2:const C=new Ls(.5,16,16),a=e?.material??new OI({color:16777215});i=new DA(C,a);break}return e!=null&&e.name&&(i.name=e.name),e!=null&&e.position&&i.position.set(e.position.x,e.position.y,e.position.z),e!=null&&e.rotation&&i.rotation.set(e.rotation.x,e.rotation.y,e.rotation.z),e!=null&&e.scale&&i.scale.set(e.scale.x,e.scale.y,e.scale.z),i}}const RH=class{constructor(t,A,e){r(this,"_session"),r(this,"_mode"),r(this,"_init"),r(this,"_renderer"),r(this,"_camera"),r(this,"_scene"),r(this,"onEnd",()=>{var i;(i=this._session)==null||i.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()}),r(this,"_lastTime",0),r(this,"onFrame",(i,g)=>{const I=i-this._lastTime;this.update(i,I),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera)}),r(this,"_spheres",[]),this._mode=t,this._init=A,this._session=e,this._session.addEventListener("end",this.onEnd),this._renderer=new zC({alpha:!0}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(e),this._renderer.xr.enabled=!0,this._camera=new Pe,this._scene=new eI,this._scene.add(this._camera),this.setupScene()}static get active(){return this._active}static async start(t,A){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(!A)return console.error("XRSessionInit must be provided"),null;this._requestInFlight=!0;const e=await navigator.xr.requestSession(t,A);return e.addEventListener("end",()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new RH(t,A,e),this._active):(e.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 Jo(100)),this._active=null}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 t={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,t}async onBeforeHandoff(){const t=DE.createPrimitive(EB.Cube);t.position.z=-3,t.position.y=.5,this._scene.add(t),await Jo(4e3),this._scene.clear(),await Jo(100)}setupScene(){this._scene.background=new mA(0),this._scene.add(new wD(5,10,1118481,2236962));const t=new $Q(16777215,1);t.position.set(2,2,2),t.castShadow=!1,this._scene.add(t);const A=new $Q(16777215,1);A.position.set(-2,-2,-2),A.castShadow=!1,this._scene.add(A);const e=50;for(let i=0;i<100;i++){const g=DE.createPrimitive(EB.Sphere,{material:new OI({color:2236962,metalness:1,roughness:.8})});g.position.x=Ie.random(-e,e),g.position.y=Ie.random(3,40),g.position.z=Ie.random(-e,e),g.scale.multiplyScalar(2),this._spheres.push(g),this._scene.add(g)}}update(t,A){const e=t*4e-4;for(let i=0;i<this._spheres.length;i++){const g=this._spheres[i];g.position.y+=Math.sin(e+i*.5)*.002}}};let Fl=RH;r(Fl,"_active",null),r(Fl,"_requestInFlight",!1);const aI=iA("debugwebxr"),QtA=iA("stats");function EtA(t){let A=null;const e=t;return e.getAROverlayContainer?A=e.getAROverlayContainer():A=t,A}htA();function htA(){var t;if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent)){console.warn("WebXRViewer does not support addEventListener");return}(t=navigator.xr)==null||t.addEventListener("sessiongranted",()=>{console.log("Received Session Granted...");const A=sessionStorage.getItem("needle_xr_session_mode"),e=sessionStorage.getItem("needle_xr_session_init");if(A&&e){console.log("Session Granted: Restore last session");const i=JSON.parse(e);de.start(A,i).catch(g=>console.warn(g))}else de.start("immersive-vr").catch(i=>console.warn("Session Granted failed:",i))})}}function ctA(t,A){sessionStorage.setItem("needle_xr_session_mode",t),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(A))}function ltA(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}if(xc()&&Se()&&window.addEventListener("keydown",t=>{t.key==="x"&&de.active&&de.stop()}),iA("simulatewebxrloading")){mt.registerCallback(Yi.ContextCreationStart,async A=>{await Jo(3e3),setTimeout(async()=>{const e=await Fl.handoff();e?de.setSession(e.mode,e.session,e.init,ve.Current):de.start("immersive-vr")},6e3)});let t=!1;window.addEventListener("click",()=>{t||(t=!0,Fl.start("immersive-vr",de.getDefaultSessionInit("immersive-vr")))})}const hB=class{constructor(t,A,e,i){r(this,"context"),r(this,"session"),r(this,"mode"),r(this,"controllers",[]),r(this,"_rigScale",1),r(this,"_lastRigScaleUpdate",-1),r(this,"_rigs",[]),r(this,"_viewerHitTestSource",null),r(this,"_defaultRig"),r(this,"_xr_scripts"),r(this,"_xr_update_scripts",[]),r(this,"_inactive_scripts",[]),r(this,"_controllerAdded"),r(this,"_controllerRemoved"),r(this,"_originalCameraWorldPosition"),r(this,"_originalCameraWorldRotation"),r(this,"_originalCameraWorldScale"),r(this,"_originalCameraParent"),r(this,"_mainCamera",null),r(this,"onRendererSessionSet",()=>{this.running&&(this.context.renderer.xr.enabled=!0,this.context.renderer.xr.updateCamera(this.context.mainCamera))}),r(this,"onInputSourceAdded",s=>{if(s.targetRayMode==="screen")return;let C=0;for(let n=0;n<this.session.inputSources.length;n++)if(this.session.inputSources[n]===s){C=n;break}if(this.controllers.find(n=>n.inputSource===s))return;const a=new DR(this,s,C);this.controllers.push(a),this.controllers.sort((n,B)=>n.index-B.index),this._newControllers.push(a),this.invokeControllerEvent(a,this._controllerAdded,"added")}),r(this,"_ended",!1),r(this,"_newControllers",[]),r(this,"onEnd",s=>{var C,a,n,B;if(this._ended)return;this._ended=!0,aI&&console.log("XR Session ended"),ltA(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,m9(this.onBefore,Pi.LateUpdate);const Q=this.context.pre_render_callbacks.indexOf(this.onBeforeRender);Q>=0&&this.context.pre_render_callbacks.splice(Q,1);const E=this.context.post_render_callbacks.indexOf(this.onAfterRender);E>=0&&this.context.post_render_callbacks.splice(E,1),this.context.xr=null,this.context.renderer.xr.enabled=!1,(C=this.context.mainCameraComponent)==null||C.applyClearFlags();for(const h of hB._xrEndListeners)h({xr:this});for(let h=0;h<this.controllers.length;h++)this.disconnectInputSource(this.controllers[h].inputSource);for(const h of this._xr_scripts)(a=h?.onLeaveXR)==null||a.call(h,{xr:this});(n=this.sync)==null||n.onExitXR(this),this.context.mainCamera&&((B=this._originalCameraParent)==null||B.add(this.context.mainCamera),this._originalCameraWorldPosition&&CI(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&_o(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&Gl(this.context.mainCamera,this._originalCameraWorldScale)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent()}),r(this,"_didStart",!1),r(this,"onBefore",s=>{var C,a,n,B,Q,E,h,d;const u=s.xrFrame;if(!u)return;this.context.xr=this,this.context.mainCameraComponent&&this.context.mainCameraComponent!==this._mainCamera&&(this._mainCamera=this.context.mainCameraComponent),((C=this.rig)==null?void 0:C.isActive)==!1&&(aI&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig&&(a=this._mainCamera)!=null&&a.gameObject&&((B=(n=this._mainCamera)==null?void 0:n.gameObject)==null?void 0:B.parent)!==this.rig.gameObject&&this.rig.gameObject.add((Q=this._mainCamera)==null?void 0:Q.gameObject),this.internalUpdateState(),this.applyCustomForward();const c={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const l=[...this.context.new_scripts_xr];for(let p=0;p<l.length;p++){const D=this.context.new_scripts_xr[p];if(!D||D.destroyed||((E=D.supportsXR)==null?void 0:E.call(D,this.mode))==!1){this.context.new_scripts_xr.splice(p,1);continue}if(!D.activeAndEnabled){this.context.new_scripts_xr.splice(p,1),this.markInactive(D);continue}if(this.addScript(D)){this.invokeCallback_EnterXR(D);for(const S of this.controllers)this.invokeCallback_ControllerAdded(D,S)}}}}else{this._didStart=!0;for(const p of hB._xrStartListeners)p(c);const l=[...this._xr_scripts];aI&&console.log("NeedleXRSession start, handle scripts:",l);for(const p of l){if(p.destroyed){this._script_to_remove.push(p);continue}if(!p.activeAndEnabled){this.markInactive(p);continue}this.invokeCallback_EnterXR(p);for(const D of this.controllers)this.invokeCallback_ControllerAdded(p,D)}}this.syncCameraCullingMask();for(const l of this.controllers)l.onUpdate(u);for(const l of this._newControllers)for(const p of this._xr_scripts){if(p.destroyed){this._script_to_remove.push(p);continue}p.onXRControllerAdded&&p.onXRControllerAdded({xr:this,controller:l,change:"added"})}this._newControllers.length=0;for(const l of this._xr_update_scripts){if(l.destroyed===!0){this._script_to_remove.push(l);continue}if(l.activeAndEnabled===!1){this.markInactive(l);continue}l.onUpdateXR&&l.onUpdateXR(c)}if(this.handleInactiveScripts(),this._script_to_remove.length>0){const l=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const p of l)!p.destroyed&&this.running&&((h=p.onLeaveXR)==null||h.call(p,c)),this.removeScript(p)}(d=this.sync)==null||d.onUpdate(this),this.onRenderDebug()}),r(this,"onBeforeRender",()=>{this.context.mainCamera&&this.updateFade(this.context.mainCamera)}),r(this,"onAfterRender",()=>{if(this.onUpdateFade_PostRender(),xc()){const s=this.context.renderer;if(s.xr.isPresenting&&this.context.mainCamera){const C=s.xr.enabled,a=s.getRenderTarget();s.xr.enabled=!1,s.setRenderTarget(null),s.render(this.context.scene,this.context.mainCamera),s.xr.enabled=C,s.setRenderTarget(a)}}}),r(this,"_script_to_remove",[]),r(this,"_camera"),r(this,"_cameraRenderParent",new wA().rotateY(Math.PI)),r(this,"_previousCameraParent"),r(this,"_customforward",!0),r(this,"originalCameraNearPlane"),r(this,"_viewerPose"),r(this,"_transformOrientation",new FA),r(this,"_transformPosition",new w),r(this,"_transition");var g,I,o;ctA(t,i.init),this.session=A,this.mode=t,this.context=e,this.context.xr=this,this.context.renderer.xr.setSession(this.session).then(this.onRendererSessionSet),this._xr_scripts=[...i.scripts],this._xr_update_scripts=this._xr_scripts.filter(s=>typeof s.onUpdateXR=="function"),this._controllerAdded=i.controller_added,this._controllerRemoved=i.controller_removed,Il(this.onBefore,Pi.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),((g=i.init.optionalFeatures)!=null&&g.includes("hit-test")||(I=i.init.requiredFeatures)!=null&&I.includes("hit-test"))&&A.requestReferenceSpace("viewer").then(s=>{var C,a;return(a=(C=A.requestHitTestSource)==null?void 0:C.call(A,{space:s}))==null?void 0:a.then(n=>this._viewerHitTestSource=n)}).catch(s=>console.warn(s)),this.context.mainCamera&&(this._originalCameraWorldPosition=Ne(this.context.mainCamera,new w),this._originalCameraWorldRotation=Kt(this.context.mainCamera,new FA),this._originalCameraWorldScale=ai(this.context.mainCamera,new w),this._originalCameraParent=this.context.mainCamera.parent),(o=this.context.mainCameraComponent)==null||o.applyClearFlags(),this._defaultRig=new ntA,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(const s of this.session.inputSources)this.onInputSourceAdded(s);this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",s=>{for(const C of s.removed)this.disconnectInputSource(C);for(const C of s.added)this.onInputSourceAdded(C)})}static getXRSync(t){return this._sync||(this._sync=new GH(t)),this._sync}static get currentSessionRequest(){return this._currentSessionRequestMode}static get active(){return this._activeSession}static get activeMode(){var t;return((t=this._activeSession)==null?void 0:t.mode)??null}static get xrSystem(){return"xr"in navigator?navigator.xr:void 0}static isXRSupported(){return Promise.all([this.isVRSupported(),this.isARSupported()]).then(t=>t.some(A=>A)).catch(()=>!1)}static isVRSupported(){var t;return((t=this.xrSystem)==null?void 0:t.isSessionSupported("immersive-vr").catch(A=>(aI&&console.error(A),!1)))??Promise.resolve(!1)}static isARSupported(){var t;return((t=this.xrSystem)==null?void 0:t.isSessionSupported("immersive-ar").catch(A=>(aI&&console.error(A),!1)))??Promise.resolve(!1)}static onSessionRequestStart(t){this._sessionRequestStartListeners.push(t)}static offSessionRequestStart(t){const A=this._sessionRequestStartListeners.indexOf(t);A>=0&&this._sessionRequestStartListeners.splice(A,1)}static onSessionRequestEnd(t){this._sessionRequestEndListeners.push(t)}static offSessionRequestEnd(t){const A=this._sessionRequestEndListeners.indexOf(t);A>=0&&this._sessionRequestEndListeners.splice(A,1)}static onXRSessionStart(t){this._xrStartListeners.push(t)}static offXRSessionStart(t){const A=this._xrStartListeners.indexOf(t);A>=0&&this._xrStartListeners.splice(A,1)}static onXRSessionEnd(t){this._xrEndListeners.push(t)}static offXRSessionEnd(t){const A=this._xrEndListeners.indexOf(t);A>=0&&this._xrEndListeners.splice(A,1)}static onControllerAdded(t){this._controllerAddedListeners.push(t)}static offControllerAdded(t){const A=this._controllerAddedListeners.indexOf(t);A>=0&&this._controllerAddedListeners.splice(A,1)}static onControllerRemoved(t){this._controllerRemovedListeners.push(t)}static offControllerRemoved(t){const A=this._controllerRemovedListeners.indexOf(t);A>=0&&this._controllerRemovedListeners.splice(A,1)}static offerSession(t,A,e){return"xr"in navigator&&navigator.xr&&"offerSession"in navigator.xr?(typeof navigator.xr.offerSession=="function"&&(console.log("WebXR offerSession is available - requesting mode: "+t),A=="default"&&(A=this.getDefaultSessionInit(t)),navigator.xr.offerSession(t,{...A}).then(i=>hB.setSession(t,i,A,e)).catch(i=>{console.log("XRSession offer rejected (perhaps because another call to offerSession was made or a call to requestSession was made)")})),!0):!1}static getDefaultSessionInit(t){switch(t){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",t),{}}}static async start(t,A,e){var i,g,I,o;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(aI||Se())&&Ci("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(e||(e=ve.Current),e||(e=mt.All[0]),!e)throw new Error("No Needle Engine Context found");switch(A||(A={}),t){case"immersive-ar":{if(await((i=this.xrSystem)==null?void 0:i.isSessionSupported("immersive-ar"))!==!0)return console.error(t+" is not supported by this browser."),null;const a=this.getDefaultSessionInit(t),n=EtA(e.domElement);n&&!RD()&&(a.domOverlay={root:n},a.optionalFeatures.push("dom-overlay")),A={...a,...A}}break;case"immersive-vr":{if(await((g=this.xrSystem)==null?void 0:g.isSessionSupported("immersive-vr"))!==!0)return console.error(t+" is not supported by this browser."),null;A={...this.getDefaultSessionInit(t),...A}}break;default:console.warn("No default session init for mode",t);break}await Fl.stop();const s=t=="immersive-ar"?e.scripts_immersive_ar:e.scripts_immersive_vr;aI?console.log(`%cRequesting ${t} session`,"font-weight:bold;",A,s):console.log(`%cRequesting ${t} session`,"font-weight:bold;");for(const a of s)a.onBeforeXR&&a.onBeforeXR(t,A);for(const a of this._sessionRequestStartListeners)a({mode:t,init:A});aI&&wi("Requesting "+t+" session ("+Date.now()+")"),this._currentSessionRequest=(I=navigator.xr)==null?void 0:I.requestSession(t,A),this._currentSessionRequestMode=t;const C=await((o=this._currentSessionRequest)==null?void 0:o.catch(a=>{console.error(a,"Code: "+a.code),a.code===9&&Ci("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:"&&Ci("XR requires a secure connection (HTTPS)")}));this._currentSessionRequest=void 0,this._currentSessionRequestMode=null;for(const a of this._sessionRequestEndListeners)a({mode:t,init:A,newSession:C||null});return C?this.setSession(t,C,A,e):(console.warn("XR Session request was rejected"),null)}static setSession(t,A,e,i){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const g=t=="immersive-ar"?i.scripts_immersive_ar:i.scripts_immersive_vr;return this._activeSession=new hB(t,A,i,{scripts:g,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:e}),A.addEventListener("end",this.onEnd),aI?console.log(`%cStarted ${t} session`,"font-weight:bold;",g):console.log(`%cStarted ${t} session`,"font-weight:bold;"),this._activeSession}static stop(){var t;(t=this._activeSession)==null||t.end()}get sync(){return hB._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(t=>t.isLeft)}get rightController(){return this.controllers.find(t=>t.isRight)}getController(t){return this.controllers.find(A=>A.side===t)||null}get isPassThrough(){return!!(this.environmentBlendMode!=="opaque"&&this.interactionMode==="world-space"||this.mode==="immersive-ar"&&this.environmentBlendMode!=="opaque"&&this.controllers.some(t=>t.inputSource.targetRayMode==="tracked-pointer")||Se()&&xc()&&this.mode==="immersive-ar")}get isAR(){return this.mode==="immersive-ar"}get isVR(){return this.mode==="immersive-vr"}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 t=this.frame.getImageTrackingResults();for(const A of t)if(A.trackingState==="tracked")return!0}catch{return!1}return!1}get rig(){const t=this._rigs[0]??null;return t!=null&&t.gameObject&&cB(t.gameObject)||t?.isActive===!1?(this.updateActiveXRRig(),this._rigs[0]??null):t}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(t){this._rigs.indexOf(t)>=0||(t.priority===void 0&&(t.priority=0),this._rigs.push(t),this.updateActiveXRRig())}removeRig(t){const A=this._rigs.indexOf(t);A!==-1&&(this._rigs.splice(A,1),this.updateActiveXRRig())}setRigActive(t){const A=this._rigs.indexOf(t);this._rigs.splice(A,1),this._rigs.unshift(t),this.updateActiveXRRig()}updateActiveXRRig(){const t=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 A=this._rigs[0];A&&A.priority===void 0&&(A.priority=0);for(let e=1;e<this._rigs.length;e++){const i=this._rigs[e];if(i.isActive){if(cB(i.gameObject)){this._rigs.splice(e,1),e--;continue}(!A||A.isActive===!1||i.priority!==void 0&&i.priority>A.priority)&&(A=i)}}if(t!==A){const e=this._rigs.indexOf(A);e>=0&&this._rigs.splice(e,1),this._rigs.unshift(A)}aI&&(t===A?console.log("Updated Active XR Rig:",A,"prev:",t):console.log("Updated Active XRRig:",A," (the same as before)"))}getHitTest(t){if(t)return this.getControllerHitTest(t);if(!this._viewerHitTestSource)return null;const A=this._viewerHitTestSource,e=this.frame.getHitTestResults(A);if(e.length>0){const i=e[0];return this.convertHitTestResult(i)}return null}getControllerHitTest(t){const A=t.hitTestSource;if(!A)return null;const e=this.frame.getHitTestResultsForTransientInput(A);for(const i of e)if(i.inputSource===t.inputSource)for(const g of i.results)return this.convertHitTestResult(g);return null}convertHitTestResult(t){const A=this.context.renderer.xr.getReferenceSpace(),e=A&&t.getPose(A);if(e){const i=_i(e.transform.position),g=rB(e.transform.orientation),I=this.context.mainCamera;if(I?.parent!==this._cameraRenderParent&&i.applyMatrix4(Ty),I!=null&&I.parent){i.applyMatrix4(I.parent.matrixWorld),g.multiply(Gs);const o=Kt(I.parent);o.premultiply(Gs),g.premultiply(o)}return{hit:t,position:i,quaternion:g}}return null}convertSpace(t){const A=_i(t.position);A.applyMatrix4(Ty);const e=rB(t.orientation);return e.premultiply(Gs),{position:A,quaternion:e}}end(){this._ended||this.session.end().catch(t=>console.warn(t))}disconnectInputSource(t){for(let A=this.controllers.length-1;A>=0;A--){const e=this.controllers[A];if(e.inputSource===t){this.controllers.splice(A,1),this.invokeControllerEvent(e,this._controllerRemoved,"removed");const i={xr:this,controller:e,change:"removed"};for(const g of this._xr_scripts)g.onXRControllerRemoved&&g.onXRControllerRemoved(i);e.onDisconnected()}}}onRenderDebug(){if(aI)for(const t of this.controllers)t.onRenderDebug();if((aI||QtA)&&this.rig){const t=this.rig.gameObject.worldPosition,A=this.rig.gameObject.worldForward;t.add(A.multiplyScalar(1.5));const e=this.rig.gameObject.worldUp;t.add(e.multiplyScalar(2.5));let i="";if(i+=this.context.time.smoothedFps.toFixed(1),aI)for(const g of this.controllers)i+=`
4989
4989
  ${g.hand?"hand":"ctrl"} ${g.inputSource.handedness}[${g.index}] con:${g.connected} tr:${g.isTracking}`;Fe.DrawLabel(t,i)}}addScript(t){return this._xr_scripts.includes(t)?!1:(aI&&console.log("Register new XRScript",t),this._xr_scripts.push(t),typeof t.onUpdateXR=="function"&&this._xr_update_scripts.push(t),!0)}markInactive(t){if(!(this._inactive_scripts.indexOf(t)>=0)){this.removeScript(t,!1),this._inactive_scripts.push(t);for(const A of this.controllers)this.invokeCallback_ControllerRemoved(t,A);this.invokeCallback_LeaveXR(t)}}handleInactiveScripts(){if(this._inactive_scripts.length>0)for(let t=this._inactive_scripts.length-1;t>=0;t--){const A=this._inactive_scripts[t];if(A.activeAndEnabled){this._inactive_scripts.splice(t,1),this.addScript(A),this.invokeCallback_EnterXR(A);for(const e of this.controllers)this.invokeCallback_ControllerAdded(A,e)}}}removeScript(t,A=!0){aI&&console.log("Remove XRScript",t);const e=this._xr_scripts.indexOf(t);e>=0&&this._xr_scripts.splice(e,1);const i=this._xr_update_scripts.indexOf(t);if(i>=0&&this._xr_update_scripts.splice(i,1),A){const g=this._inactive_scripts.indexOf(t);g>=0&&this._inactive_scripts.splice(g,1)}}invokeCallback_EnterXR(t){t.onEnterXR&&t.onEnterXR({xr:this})}invokeCallback_ControllerAdded(t,A){t.onXRControllerAdded&&t.onXRControllerAdded({xr:this,controller:A,change:"added"})}invokeCallback_ControllerRemoved(t,A){t.onXRControllerRemoved&&t.onXRControllerRemoved({xr:this,controller:A,change:"removed"})}invokeCallback_LeaveXR(t){t.onLeaveXR&&!t.destroyed&&t.onLeaveXR({xr:this})}syncCameraCullingMask(){var t;const A=this.context.xrCamera,e=(t=this.context.mainCameraComponent)==null?void 0:t.cullingMask;if(A&&e!==void 0){for(const i of A.cameras)i.layers.mask=e;A.layers.mask=e}else if(A){for(const i of A.cameras)i.layers.enableAll();A.layers.enableAll()}}invokeControllerEvent(t,A,e){for(let i=A.length-1;i>=0;i--){const g=A[i];if(g)try{g({xr:this,controller:t,change:e})}catch(I){console.error(I)}}}applyCustomForward(){var t;if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,(t=this._previousCameraParent)==null||t.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);let A=.02;if(this.rig){const e=ai(this.rig.gameObject);A*=e.x}this._camera instanceof Pe&&this._camera.near>A&&(this.originalCameraNearPlane=this._camera.near,this._camera.near=A)}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof Pe&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane)}internalUpdateState(){const t=this.context.renderer.xr.getReferenceSpace();if(!t){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(t),this._viewerPose){const A=this._viewerPose.transform;this._transformPosition.set(A.position.x,A.position.y,A.position.z),this._transformOrientation.set(A.orientation.x,A.orientation.y,A.orientation.z,A.orientation.w)}}get transition(){return this._transition||(this._transition=new MH),this._transition}fadeTransition(){return this._transition||(this._transition=new MH),this._transition.fadeTransition()}updateFade(t){this._transition&&t instanceof Pe&&this._transition.update(t,this.context.time.deltaTime)}onUpdateFade_PostRender(){var t;(t=this._transition)==null||t.remove()}};let de=hB;r(de,"_sync",null),r(de,"_currentSessionRequestMode",null),r(de,"_currentSessionRequest"),r(de,"_activeSession"),r(de,"_sessionRequestStartListeners",[]),r(de,"_sessionRequestEndListeners",[]),r(de,"_xrStartListeners",[]),r(de,"_xrEndListeners",[]),r(de,"_controllerAddedListeners",[]),r(de,"_controllerRemovedListeners",[]),r(de,"onEnd",()=>{aI&&console.log("XR Session ended"),hB._activeSession=null});const wR=iA("debugwebxr");class UH{static tryFindAvatarObjects(A,e,i){if(i.head&&i.leftHand&&i.rightHand)return;const g=A.name.toLocaleLowerCase();!i.head&&g.includes("head")&&(wR&&console.log("FOUND AVATAR HEAD",A.name),i.head=new Ct("",e,A)),g.includes("hand")&&(!i.leftHand&&g.includes("left")&&(wR&&console.log("FOUND AVATAR LEFT HAND",A.name),i.leftHand=new Ct("",e,A)),!i.rightHand&&g.includes("right")&&(wR&&console.log("FOUND AVATAR RIGHT HAND",A.name),i.rightHand=new Ct("",e,A)));for(let I=0;I<A.children.length;I++){if(i.head&&i.leftHand&&i.rightHand)return;const o=A.children[I];this.tryFindAvatarObjects(o,e,i)}}}const mI=new w,NH=new w,FH=new FA,dtA=iA("debuggizmos"),Da=8947848,sC=class{static isGizmo(t){return t[fR]!==void 0}static DrawLabel(t,A,e=.05,i=0,g,I,o){var s;if(!sC.enabled)return null;g||(g=Da);const C=((s=de.active)==null?void 0:s.rigScale)??1,a=Oi.getTextLabel(i,A,e*C,g,I);return o instanceof wA&&o.add(a),a.position.x=t.x,a.position.y=t.y,a.position.z=t.z,a}static DrawRay(t,A,e=Da,i=0,g=!0){if(!sC.enabled)return;const I=Oi.getLine(i),o=I.geometry.getAttribute("position");o.setXYZ(0,t.x,t.y,t.z),mI.set(A.x,A.y,A.z).multiplyScalar(999999999),o.setXYZ(1,t.x+mI.x,t.y+mI.y,t.z+mI.z),o.needsUpdate=!0,I.material.color.set(e),I.material.depthTest=g,I.material.depthWrite=!1}static DrawDirection(t,A,e=Da,i=0,g=!0,I=1){if(!sC.enabled)return;const o=Oi.getLine(i),s=o.geometry.getAttribute("position");s.setXYZ(0,t.x,t.y,t.z),A.w!==void 0?(mI.set(0,0,-I),FH.set(A.x,A.y,A.z,A.w),mI.applyQuaternion(FH)):(mI.set(A.x,A.y,A.z),mI.multiplyScalar(I)),s.setXYZ(1,t.x+mI.x,t.y+mI.y,t.z+mI.z),s.needsUpdate=!0,o.material.color.set(e),o.material.depthTest=g,o.material.depthWrite=!1}static DrawLine(t,A,e=Da,i=0,g=!0){if(!sC.enabled)return;const I=Oi.getLine(i),o=I.geometry.getAttribute("position");o.setXYZ(0,t.x,t.y,t.z),o.setXYZ(1,A.x,A.y,A.z),o.needsUpdate=!0,I.material.color.set(e),I.material.depthTest=g,I.material.depthWrite=!1}static DrawWireSphere(t,A,e=Da,i=0,g=!0){if(!sC.enabled)return;const I=Oi.getSphere(A,i,!0);BB(I,t.x,t.y,t.z),I.material.color.set(e),I.material.depthTest=g,I.material.depthWrite=!1}static DrawSphere(t,A,e=Da,i=0,g=!0){if(!sC.enabled)return;const I=Oi.getSphere(A,i,!1);BB(I,t.x,t.y,t.z),I.material.color.set(e),I.material.depthTest=g,I.material.depthWrite=!1}static DrawWireBox(t,A,e=Da,i=0,g=!0){if(!sC.enabled)return;const I=Oi.getBox(i);I.position.set(t.x,t.y,t.z),I.scale.set(A.x,A.y,A.z),I.material.color.set(e),I.material.depthTest=g,I.material.wireframe=!0,I.material.depthWrite=!1}static DrawWireBox3(t,A=Da,e=0,i=!0){if(!sC.enabled)return;const g=Oi.getBox(e);g.position.copy(t.getCenter(mI)),g.scale.copy(t.getSize(mI)),g.material.color.set(A),g.material.depthTest=i,g.material.wireframe=!0,g.material.depthWrite=!1}static DrawArrow(t,A,e=Da,i=0,g=!0,I=!1){if(!sC.enabled)return;const o=Oi.getArrowHead(i);o.position.set(A.x,A.y,A.z),o.quaternion.setFromUnitVectors(this._up.set(0,1,0),mI.set(A.x,A.y,A.z).sub(NH.set(t.x,t.y,t.z)).normalize());const s=mI.set(A.x,A.y,A.z).sub(NH.set(t.x,t.y,t.z)).length()*.1;o.scale.set(s,s,s),o.material.color.set(e),o.material.depthTest=g,o.material.wireframe=I,this.DrawLine(t,A,e,i,g)}};let Fe=sC;r(Fe,"enabled",!0),r(Fe,"_up",new w(0,1,0));const utA=new _t(1,1,1);function SR(t=null){const A=new mA(t??14540253),e=new Ek(utA);return new oo(e,new Ui({color:A}))}const fR=Symbol("GizmoCache");class Oi{static ensureFont(){let A=pE.FontLibrary.getFontFamily(this.familyName);if(!A){A=pE.FontLibrary.addFontFamily(this.familyName);const e=A.addVariant("normal","normal","./include/needle/arial-msdf.json","./include/needle/arial.png");e?.addEventListener("ready",()=>{pE.update()})}}static getTextLabel(A,e,i,g,I){this.ensureFont();let o=this.textLabelCache.pop(),s=1;I&&typeof I=="string"&&I?.length>=8&&I.startsWith("#")?(s=parseInt(I.substring(7),16)/255,I=I.substring(0,7),dtA&&console.log(I,s)):typeof I=="object"&&I.a!==void 0&&(s=I.a);const C={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:i,color:g,lineHeight:1,backgroundColor:I??void 0,backgroundOpacity:s,textContent:e,borderRadius:.5*i,padding:.8*i,whiteSpace:"pre"};if(o)o.set(C);else{o=new rR(C);const a=this,n=o;n.setText=function(B){this.set({textContent:B}),a.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(ve.Current,o,A,this.textLabelCache),o}static getBox(A){let e=this.boxesCache.pop();if(!e){const i=new _t(1,1,1);e=new DA(i)}return this.registerTimedObject(ve.Current,e,A,this.boxesCache),e}static getLine(A){let e=this.linesCache.pop();if(!e){e=new Ni;let i=e.geometry.getAttribute("position");i||(i=new Ae(new Float32Array(2*3),3),e.geometry.setAttribute("position",i))}return e.frustumCulled=!1,this.registerTimedObject(ve.Current,e,A,this.linesCache),e}static getSphere(A,e,i){let g=this.spheresCache.pop();return g||(g=new DA(new Ls(1,8,8))),g.scale.set(A,A,A),g.material.wireframe=i,this.registerTimedObject(ve.Current,g,e,this.spheresCache),g}static getArrowHead(A){let e=this.arrowHeadsCache.pop();return e||(e=new DA(new qi(0,.5,1,8))),this.registerTimedObject(ve.Current,e,A,this.arrowHeadsCache),e}static registerTimedObject(A,e,i,g){const I=this.contextBeforeRenderCallbacks.get(A),o=this.contextPostRenderCallbacks.get(A);if(I){if(A.pre_render_callbacks[A.pre_render_callbacks.length-1]!==I){const s=A.pre_render_callbacks.indexOf(I);s>=0&&A.pre_render_callbacks.splice(s,1),A.pre_render_callbacks.push(I)}}else{const s=()=>{this.onBeforeRender(A,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(A,s),A.pre_render_callbacks.push(s)}if(o){if(A.post_render_callbacks[A.post_render_callbacks.length-1]!==o){const s=A.post_render_callbacks.indexOf(o);s>=0&&A.post_render_callbacks.splice(s,1),A.post_render_callbacks.push(o)}}else{const s=()=>{this.onPostRender(A,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(A,s),A.post_render_callbacks.push(s)}e.traverse(s=>{s.layers.disableAll(),s.layers.enable(2)}),e.renderOrder=999999,e[fR]=g,this.timedObjectsBuffer.push(e),this.timesBuffer.push(ve.Current.time.realtimeSinceStartup+i),A.scene.add(e)}static onBeforeRender(A,e){this.tmuiNeedsUpdate&&pE.update();for(let i=0;i<e.length;i++){const g=e[i];if(A.mainCamera&&g instanceof pE.MeshUIBaseElement){if(cB(g))continue;const I=A.isInVR,o=!1,s=!I;BR(g,A.mainCamera,o,s)}}}static onPostRender(A,e,i){const g=A.time.realtimeSinceStartup;for(let I=e.length-1;I>=0;I--){const o=e[I];g>i[I]&&(e.splice(I,1),i.splice(I,1),o.removeFromParent(),cB(o)!=!0&&o[fR].push(o))}}}r(Oi,"familyName","needle-gizmos"),r(Oi,"linesCache",[]),r(Oi,"spheresCache",[]),r(Oi,"boxesCache",[]),r(Oi,"arrowHeadsCache",[]),r(Oi,"textLabelCache",[]),r(Oi,"timedObjectsBuffer",new Array),r(Oi,"timesBuffer",new Array),r(Oi,"contextPostRenderCallbacks",new Map),r(Oi,"contextBeforeRenderCallbacks",new Map),r(Oi,"tmuiNeedsUpdate",!1);const ptA=iA("debugphysics"),KH=new hI;class Oo{constructor(){r(this,"ray"),r(this,"cam"),r(this,"screenPoint"),r(this,"raycaster"),r(this,"results"),r(this,"targets"),r(this,"recursive",!0),r(this,"minDistance"),r(this,"maxDistance"),r(this,"lineThreshold"),r(this,"layerMask"),r(this,"ignore"),r(this,"testObject")}screenPointFromOffset(A,e){this.screenPoint===void 0&&(this.screenPoint=new tA),this.screenPoint.x=A/window.innerWidth*2-1,this.screenPoint.y=-(e/window.innerHeight)*2+1}setLayer(A){KH.set(A),this.layerMask=KH}setMask(A){this.layerMask||(this.layerMask=new hI);const e=this.layerMask;e?e.mask=A:this.layerMask=A}}r(Oo,"AllLayers",4294967295);class JH{constructor(A,e,i){r(this,"distance"),r(this,"point"),r(this,"object"),this.object=A,this.distance=e,this.point=i}}class vH{constructor(A){r(this,"context"),r(this,"engine"),r(this,"raycaster",new AE),r(this,"defaultRaycastOptions",new Oo),r(this,"targetBuffer",new Array(1)),r(this,"defaultThresholds",{Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}}),r(this,"sphereResults",new Array),r(this,"sphereMask",new hI),r(this,"tempBoundingBox",new Ft),this.context=A}raycastPhysicsFast(A,e=void 0,i=1/0,g=!0){var I;return((I=this.context.physics.engine)==null?void 0:I.raycast(A,e,i,g))??null}raycastPhysicsFastAndGetNormal(A,e=void 0,i=1/0,g=!0){var I;return((I=this.context.physics.engine)==null?void 0:I.raycastAndGetNormal(A,e,i,g))??null}sphereOverlapPhysics(A,e){var i;return((i=this.context.physics.engine)==null?void 0:i.sphereOverlap(A,e))??null}sphereOverlap(A,e,i=!0){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const g=new Ri(A,e),I=this.sphereMask;I.enableAll(),I.disable(2);for(const o of this.context.scene.children)this.onSphereOverlap(o,g,I,this.sphereResults,i);return this.sphereResults.sort((o,s)=>o.distance-s.distance)}onSphereOverlap(A,e,i,g,I){if(A.type==="Mesh"&&A.layers.test(i)&&!Fe.isGizmo(A)){const o=A,s=o.geometry;if(s&&(s.boundingBox||s.computeBoundingBox(),s.boundingBox)){o.matrixWorldNeedsUpdate&&o.updateMatrixWorld();const C=this.tempBoundingBox.copy(s.boundingBox).applyMatrix4(o.matrixWorld);if(e.intersectsBox(C)){const a=Ne(A),n=a.distanceTo(e.center),B=new JH(A,n,a);if(g.push(B),!I)return}}}if(A.children)for(const o of A.children){const s=g.length;if(this.onSphereOverlap(o,e,i,g,I),s!=g.length&&!I)return}}raycastFromRay(A,e=null){const i=e??this.defaultRaycastOptions;i.ray=A;const g=this.raycast(i);return i===this.defaultRaycastOptions&&(i.ray=void 0),g}raycast(A=null){A||(A=this.defaultRaycastOptions);const e=A.screenPoint??this.context.input.mousePositionRC,i=A.raycaster??this.raycaster;if(i.near=A.minDistance??0,i.far=A.maxDistance??1/0,i.params=this.defaultThresholds,A.lineThreshold===void 0&&(A.lineThreshold=-1),i.params.Line={threshold:A.lineThreshold},A.ray)i.ray.copy(A.ray);else{const s=A.cam??this.context.mainCamera;if(!s)return ptA&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];i.setFromCamera(e,s)}let g=A.targets;g||(g=this.targetBuffer,g.length=1,g[0]=this.context.scene);let I=A.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),I||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),I=this.defaultRaycastOptions.results),A.layerMask!==void 0?A.layerMask instanceof hI?i.layers.mask=A.layerMask.mask:i.layers.mask=A.layerMask:(i.layers.enableAll(),i.layers.disable(2)),I.length=0,this.intersect(this.raycaster,g,I,A),I.sort((s,C)=>s.distance-C.distance);const o=A.ignore;return o!==void 0&&o.length>0&&(I=I.filter(s=>!o.includes(s.object))),I}intersect(A,e,i,g){var I;for(const o of e){if(o.visible===!1||Fe.isGizmo(o)||g.lineThreshold!==void 0&&g.lineThreshold<0&&o instanceof Ni)continue;const s=(I=g.testObject)==null?void 0:I.call(g,o);s!==!1&&(s!=="continue in children"&&A.intersectObject(o,!1,i),g.recursive!==!1&&this.intersect(A,o.children,i,g))}return i}}const DtA=iA("debugplayerview");var Kn=(t=>(t.Browser="browser",t.Headset="headset",t.Handheld="handheld",t))(Kn||{});class bH{constructor(A,e){r(this,"userId"),r(this,"context"),r(this,"viewDevice","browser"),r(this,"removed",!1),r(this,"_object"),this.userId=A,this.context=e}get currentObject(){return this._object}set currentObject(A){this._object=A}get isConnected(){return this.context.connection.userIsInRoom(this.userId)}}class qH{constructor(A){r(this,"context"),r(this,"playerViews",new Map),this.context=A}setPlayerView(A,e,i){let g=this.playerViews.get(A);g||(g=new bH(A,this.context),this.playerViews.set(A,g)),g.viewDevice=i,g.currentObject=e,g.removed=!1}getPlayerView(A){if(!!A){if(!this.context.connection.userIsInRoom(A)){this.playerViews.delete(A);return}return this.playerViews.get(A)}}removePlayerView(A,e){const i=this.playerViews.get(A);i?.viewDevice===e&&(DtA&&console.log("REMOVE",A),i.removed=!0,this.playerViews.delete(A))}}new gg;const Kl=new Uint8Array(4);Kl[0]=255,Kl[1]=255,Kl[2]=255,Kl[3]=255;const ytA=new Io(Kl,1,1,yt);function LH(t,A=1){const e="alpha"in t,i=A*A,g=new Uint8Array(4*i),I=Math.floor(t.r*255),o=Math.floor(t.g*255),s=Math.floor(t.b*255);for(let a=0;a<i;a++){const n=a*4;g[n+0]=I,g[n+1]=o,g[n+2]=s,e?g[n+3]=Math.floor(t.alpha*255):g[n+3]=255}const C=new Io(g,A,A);return C.needsUpdate=!0,C}function wtA(t,A,e,i=1,g=3){const I=i*g,o=[t,A,e],s=o.length,C=new Uint8Array(4*s*I),a=new mA;for(let B=0;B<g;B++){const Q=Math.floor(B/g*s),E=Ie.clamp(Q+1,0,s-1),h=o[Q],d=o[E],u=B/g*s%1;a.lerpColors(h,d,u);const c=Math.floor(a.r*255),l=Math.floor(a.g*255),p=Math.floor(a.b*255);for(let D=0;D<i;D++){const S=(B*i+D)*4;C[S+0]=c,C[S+1]=l,C[S+2]=p,C[S+3]=255}}const n=new Io(C,i,g);return n.needsUpdate=!0,n}function Hy(t,A){const e=t.elements;A||(A=[]),A.length=0;for(let i=0;i<16;i+=4){const g=e[i],I=e[i+1],o=e[i+2],s=e[i+3],C=new ie(g,I,o,s);A.push(C)}return A}const mR=[],xH=[];function StA(t,A){if(mR.length===0)for(let e=0;e<27;e++)mR.push(0);A||(A=mR);for(let e=0;e<27;e++)xH[e]=A[e];A=xH,t.unity_SHAr={value:new ie(A[9],A[3],A[6],A[0])},t.unity_SHBr={value:new ie(A[12],A[15],A[18],A[21])},t.unity_SHAg={value:new ie(A[10],A[4],A[7],A[1])},t.unity_SHBg={value:new ie(A[13],A[16],A[19],A[22])},t.unity_SHAb={value:new ie(A[11],A[5],A[8],A[2])},t.unity_SHBb={value:new ie(A[14],A[17],A[20],A[23])},t.unity_SHC={value:new ie(A[24],A[25],A[26],1)}}class ftA{constructor(A,e,i){r(this,"vertexShader"),r(this,"fragmentShader"),r(this,"technique"),this.vertexShader=A,this.fragmentShader=e,this.technique=i}}async function mtA(t,A){if(!t)return console.error("Can not find technique: no shader data"),null;const e=t.programs[A],i=e.vertexShader,g=e.fragmentShader;if(i!==void 0&&g!==void 0){const I=t.shaders[i],o=t.shaders[g];if(I.uri&&o.uri||I.code&&o.code){if(!I.code&&I.uri&&await YH(I),!o.code&&o.uri&&await YH(o),!I.code||!o.code)return null;const s=t.techniques[A];return new ftA(I.code,o.code,s)}}return console.error("Shader technique not found",A),null}async function YH(t){const A=t.uri;if(A)if(A.endsWith(".glsl")){const e=await new gg().loadAsync(A);t.code=e.toString()}else t.code=ktA(t.uri)}function ktA(t){return decodeURIComponent(Array.prototype.map.call(atob(t),function(A){return"%"+("00"+A.charCodeAt(0).toString(16)).slice(-2)}).join(""))}const CC=iA("debugenvlight");var yE=(t=>(t[t.Skybox=0]="Skybox",t[t.Trilight=1]="Trilight",t[t.Flat=3]="Flat",t[t.Custom=4]="Custom",t))(yE||{}),_y=(t=>(t[t.Skybox=0]="Skybox",t[t.Custom=1]="Custom",t))(_y||{});class TH{constructor(A){r(this,"context"),r(this,"_currentLightSettingsId"),r(this,"_sceneLightSettings"),r(this,"_timevec4",new ie),r(this,"__currentReflectionId",null),r(this,"_lighting",{}),this.context=A,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}preUpdate(){const A=this.context.time;this._timevec4.x=A.time,this._timevec4.y=Math.sin(A.time),this._timevec4.z=Math.cos(A.time),this._timevec4.w=A.deltaTime}get timeVec4(){return this._timevec4}get environmentIntensity(){if(!this._sceneLightSettings||!this._currentLightSettingsId)return 1;const A=this._sceneLightSettings.get(this._currentLightSettingsId);return A?A.ambientIntensity:1}get sceneLightSettings(){var A;return(A=this._sceneLightSettings)==null?void 0:A.values()}enable(A){var e;A instanceof Ct&&(A=A.uri);const i=(e=this._sceneLightSettings)==null?void 0:e.get(A);return i?(CC&&console.log("Enable scene light settings",A,i),A!==this._currentLightSettingsId&&this._currentLightSettingsId&&this.disable(this._currentLightSettingsId),this._currentLightSettingsId=A,i.enabled=!0,!0):!1}disable(A){var e;if(A instanceof Ct&&(A=A.uri),A==null)return!1;const i=(e=this._sceneLightSettings)==null?void 0:e.get(A);return i?(CC&&console.log("Disable scene light settings",A,i),i.enabled=!1,!0):!1}disableCurrent(){if(this._currentLightSettingsId){const A=this._currentLightSettingsId;return this.disable(this._currentLightSettingsId),A}return null}internalRegisterSceneLightSettings(A){const e=A.sourceId;if(!e){console.error("Missing source id for scene light settings, can not register:",A);return}CC&&console.log("Register "+A?.sourceId+" lighting",A),this._sceneLightSettings||(this._sceneLightSettings=new Map),this._sceneLightSettings.set(e,A)}internalUnregisterSceneLightSettings(A){const e=A.sourceId;if(!e){console.error("Missing source id for scene light settings, can not unregister:",A);return}CC&&console.log("Unregister "+A?.sourceId+" lighting",A),this._sceneLightSettings&&this._sceneLightSettings.delete(e)}internalRegisterReflection(A,e){CC&&console.log("Register reflection",A,e);const i=new HH(this.context,e,1);this._lighting[A]=i}internalGetReflection(A){return this._lighting[A]}internalEnableReflection(A){var e;this.__currentReflectionId=A;const i=(e=this._sceneLightSettings)==null?void 0:e.get(A);switch(CC&&console.log("Enable reflection",A,i?yE[i.ambientMode]:"Unknown ambient mode"),i?.ambientMode){case 0:case 4:const g=this.internalGetReflection(A);if(g&&g.Source){CC&&console.log("Setting environment reflection",g);const I=this.context.scene,o=g.Source;o.colorSpace=_e,o.mapping=Ro,I.environment=o;return}else CC&&console.warn("Could not find reflection for source",A);break}if(i?.environmentReflectionSource===1)switch(i?.ambientMode){case 1:if(i.ambientTrilight){const g=i.ambientTrilight,I=wtA(g[0],g[1],g[2],64,64);I.colorSpace=_e,I.mapping=Ro,this.context.scene.environment=I}else console.error("Missing ambient trilight",i.sourceId);return;case 3:if(i.ambientLight){const g=LH(i.ambientLight,64);g.colorSpace=_e,g.mapping=Ro,this.context.scene.environment=g}else console.error("Missing ambientlight",i.sourceId);return;default:return}}internalDisableReflection(A){if(A&&A!==this.__currentReflectionId){CC&&console.log("Not disabling reflection for",A,"because it is not the current light settings id",this.__currentReflectionId);return}CC&&console.log("Disable reflection",A);const e=this.context.scene;e.environment=null}}class HH{constructor(A,e,i=1){r(this,"_context"),r(this,"_source"),r(this,"_sphericalHarmonics",null),r(this,"_sphericalHarmonicsArray"),r(this,"_ambientScale",1),r(this,"_lightProbe"),this._context=A,this._source=e,this._ambientScale=i,e.mapping=Ro,e.colorSpace=_e}get Source(){return this._source}get Array(){return this._sphericalHarmonicsArray}}const _H=iA("timescale");let kR=1;typeof _H=="number"&&(kR=_H);class OH{constructor(){r(this,"deltaTime",0),r(this,"time",0),r(this,"timeScale",1),r(this,"frame",0),r(this,"clock",new Gk),r(this,"_smoothedFps",0),r(this,"_smoothedDeltaTime",0),r(this,"_fpsSamples",[]),r(this,"_fpsSampleIndex",0),typeof kR=="number"&&(this.timeScale=kR)}get realtimeSinceStartup(){return this.clock.elapsedTime}get frameCount(){return this.frame}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.deltaTime*=this.timeScale,this.deltaTime<=0&&(this.deltaTime=1e-12),this.frame+=1,this.time+=this.deltaTime,this._fpsSamples.length<60?this._fpsSamples.push(this.deltaTime):this._fpsSamples[this._fpsSampleIndex++%60]=this.deltaTime;let A=0;for(let e=0;e<this._fpsSamples.length;e++)A+=this._fpsSamples[e];this._smoothedDeltaTime=A/this._fpsSamples.length,this._smoothedFps=1/this._smoothedDeltaTime}}const ZI=iA("debugcontext"),GtA=iA("stats"),MtA=iA("debugactive"),RtA=iA("debugframerate"),UtA=iA("debugcoroutine"),NtA={};class FtA{constructor(){r(this,"name"),r(this,"alias"),r(this,"hash"),r(this,"runInBackground"),r(this,"domElement"),r(this,"renderer"),r(this,"camera"),r(this,"scene")}}var Pi=(t=>(t[t.Start=-1]="Start",t[t.EarlyUpdate=0]="EarlyUpdate",t[t.Update=1]="Update",t[t.LateUpdate=2]="LateUpdate",t[t.OnBeforeRender=3]="OnBeforeRender",t[t.OnAfterRender=4]="OnAfterRender",t[t.PrePhysicsStep=9]="PrePhysicsStep",t[t.PostPhysicsStep=10]="PostPhysicsStep",t[t.Undefined=-1]="Undefined",t))(Pi||{});function Oy(t,A){if(!t)return;if(!t.isComponent){(Se()||ZI)&&console.error(`Registered script is not a Needle Engine component.
4990
4990
  The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
4991
- `,t);return}const e=A?.new_scripts??ve.Current.new_scripts;e.includes(t)||e.push(t)}const ii=class{constructor(t){r(this,"name"),r(this,"alias"),r(this,"isManagedExternally",!1),r(this,"isPaused",!1),r(this,"runInBackground",!1),r(this,"targetFrameRate"),r(this,"physicsSteps",1),r(this,"hash"),r(this,"domElement"),r(this,"_resolutionScaleFactor",1),r(this,"_boundingClientRectFrame",-1),r(this,"_boundingClientRect",null),r(this,"_domX"),r(this,"_domY"),r(this,"xr",null),r(this,"_xrFrame",null),r(this,"_currentFrameEvent",-1),r(this,"scene"),r(this,"renderer"),r(this,"composer",null),r(this,"scripts",[]),r(this,"scripts_pausedChanged",[]),r(this,"scripts_earlyUpdate",[]),r(this,"scripts_update",[]),r(this,"scripts_lateUpdate",[]),r(this,"scripts_onBeforeRender",[]),r(this,"scripts_onAfterRender",[]),r(this,"scripts_WithCorroutines",[]),r(this,"scripts_immersive_vr",[]),r(this,"scripts_immersive_ar",[]),r(this,"coroutines",{}),r(this,"post_setup_callbacks",[]),r(this,"pre_update_callbacks",[]),r(this,"pre_render_callbacks",[]),r(this,"post_render_callbacks",[]),r(this,"pre_update_oneshot_callbacks",[]),r(this,"new_scripts",[]),r(this,"new_script_start",[]),r(this,"new_scripts_pre_setup_callbacks",[]),r(this,"new_scripts_post_setup_callbacks",[]),r(this,"new_scripts_xr",[]),r(this,"mainCameraComponent"),r(this,"_camera",null),r(this,"application"),r(this,"time"),r(this,"input"),r(this,"physics"),r(this,"connection"),r(this,"assets"),r(this,"mainLight",null),r(this,"sceneLighting"),r(this,"addressables"),r(this,"lightmaps"),r(this,"players"),r(this,"_sizeChanged",!1),r(this,"_isCreated",!1),r(this,"_isCreating",!1),r(this,"_isVisible",!1),r(this,"_stats",GtA?new A9:null),r(this,"_intersectionObserver",null),r(this,"_disposeCallbacks",[]),r(this,"_originalCreationArgs"),r(this,"onUnhandledRejection",i=>{this.domElement.dispatchEvent(new CustomEvent("error",{detail:i.reason}))}),r(this,"_cameraStack",[]),r(this,"_onBeforeRenderListeners",new Map),r(this,"_onAfterRenderListeners",new Map),r(this,"_requireDepthTexture",!1),r(this,"_requireColorTexture",!1),r(this,"_renderTarget"),r(this,"_isRendering",!1),r(this,"_createId",0),r(this,"_renderlooperrors",0),r(this,"_lastTimestamp",0),r(this,"_accumulatedTime",0),r(this,"_dispatchReadyAfterFrame",!1),r(this,"_wasPaused",!1),this.name=t?.name||"",this.alias=t?.alias,this.domElement=t?.domElement||document.body,this.hash=t?.hash,t!=null&&t.renderer&&(this.renderer=t.renderer,this.isManagedExternally=!0),t?.runInBackground!==void 0&&(this.runInBackground=t.runInBackground),t!=null&&t.scene?this.scene=t.scene:this.scene=new eI,t!=null&&t.camera&&(this._camera=t.camera),this.application=new WL(this),this.time=new OH,this.input=new zL(this),this.physics=new vH(this),this.connection=new JY(this),this.assets=new zq,this.sceneLighting=new TH(this),this.addressables=new PL(this),this.lightmaps=new P9(this),this.players=new qH(this);const A=()=>this._sizeChanged=!0;window.addEventListener("resize",A),this._disposeCallbacks.push(()=>window.removeEventListener("resize",A));const e=new ResizeObserver(i=>this._sizeChanged=!0);e.observe(this.domElement),this._disposeCallbacks.push(()=>e.disconnect()),this._intersectionObserver=new IntersectionObserver(i=>{this._isVisible=i[0].isIntersecting}),this._disposeCallbacks.push(()=>{var i;return(i=this._intersectionObserver)==null?void 0:i.disconnect()}),mt.register(this)}static get DefaultTargetFrameRate(){return ii._defaultTargetFramerate.value}static set DefaultTargetFrameRate(t){ii._defaultTargetFramerate.value=t}static get DefaultWebGLRendererParameters(){return ii._defaultWebglRendererParameters}get version(){return ga}static get Current(){return mt.Current}static set Current(t){mt.Current=t}appendHTMLElement(t){return this.domElement.shadowRoot?this.domElement.shadowRoot.appendChild(t):this.domElement.appendChild(t)}get resolutionScaleFactor(){return this._resolutionScaleFactor}set resolutionScaleFactor(t){if(t!==this._resolutionScaleFactor&&typeof t=="number"){if(t<=0){console.error("Invalid resolution scale factor",t);return}this._resolutionScaleFactor=t,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 t,A;return((A=(t=this.renderer)==null?void 0:t.xr)==null?void 0:A.isPresenting)||!1}get xrSessionMode(){var t;return(t=this.xr)==null?void 0:t.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 t,A;return(A=(t=this.renderer)==null?void 0:t.xr)==null?void 0:A.getSession()}get xrFrame(){return this._xrFrame}get xrCamera(){var t,A;return(A=(t=this.renderer)==null?void 0:t.xr)==null?void 0:A.getCamera()}get arOverlayElement(){const t=this.domElement;return typeof t.getAROverlayContainer=="function"?t.getAROverlayContainer():this.domElement}get currentFrameEvent(){return this._currentFrameEvent}get mainCamera(){if(this._camera)return this._camera;if(this.mainCameraComponent){const t=this.mainCameraComponent;return t.cam||t.buildCamera(),t.cam}return null}set mainCamera(t){this._camera=t}get rendererData(){return this.sceneLighting}get isCreated(){return this._isCreated}createNewRenderer(){var t,A,e;(t=this.renderer)==null||t.dispose();const i={...ii.DefaultWebGLRendererParameters};if(!i.canvas){const g=(e=(A=this.domElement)==null?void 0:A.shadowRoot)==null?void 0:e.querySelector("canvas");g&&(i.canvas=g,ZI&&console.log("Using canvas from shadow root",g))}ZI&&console.log("Using Renderer Parameters:",i,this.domElement),this.renderer=new zC(i),this.renderer.debug.checkShaderErrors=Se()||iA("checkshadererrors")===!0,this.renderer.toneMappingExposure=1,this.renderer.toneMapping=YI,this.renderer.setClearColor(new mA("lightgrey"),0),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=mf,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputColorSpace=_e,this.renderer.useLegacyLights=!1,this.input.bindEvents()}internalOnUpdateVisible(){var t,A;(t=this._intersectionObserver)==null||t.disconnect(),(A=this._intersectionObserver)==null||A.observe(this.domElement)}requestSizeUpdate(){this._sizeChanged=!0}updateSize(t=!1){var A,e,i;if(t||!this.isManagedExternally&&((A=this.renderer.xr)==null?void 0:A.isPresenting)===!1){this._sizeChanged=!1;const g=this.resolutionScaleFactor,I=this.domWidth*g,o=this.domHeight*g,s=this.mainCamera;this.updateAspect(s),this.renderer.setSize(I,o,!0),this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%",this.composer&&((e=this.composer.setSize)==null||e.call(this.composer,I,o),"setPixelRatio"in this.composer&&typeof this.composer.setPixelRatio=="function"&&((i=this.composer.setPixelRatio)==null||i.call(this.composer,window.devicePixelRatio)))}}updateAspect(t,A,e){if(!t)return;A===void 0&&(A=this.domWidth),e===void 0&&(e=this.domHeight);const i=t.aspect;t.aspect=A/e,i!==t.aspect&&t.updateProjectionMatrix()}recreate(){this.clear(),this.create(this._originalCreationArgs)}async onCreate(t){return this.create(t)}async create(t){try{this._isCreating=!0,t!==this._originalCreationArgs&&(this._originalCreationArgs=Lc(t)),window.addEventListener("unhandledrejection",this.onUnhandledRejection);const A=await this.internalOnCreate(t);return this._isCreated=!0,A}finally{window.removeEventListener("unhandledrejection",this.onUnhandledRejection),this._isCreating=!1}}clear(){var t,A,e,i;mt.dispatchCallback(Yi.ContextClearing,this),Ms(this.scene,!0,!0),this.scene=new eI,(t=this.addressables)==null||t.dispose(),(A=this.lightmaps)==null||A.clear(),(i=(e=this.physics)==null?void 0:e.engine)==null||i.clearCaches(),this.isManagedExternally||this.renderer&&(this.renderer.renderLists.dispose(),this.renderer.state.reset(),this.renderer.resetState()),mt.dispatchCallback(Yi.ContextCleared,this)}dispose(){this.internalOnDestroy()}onDestroy(){this.internalOnDestroy()}internalOnDestroy(){var t,A;this.clear(),(t=this.renderer)==null||t.setAnimationLoop(null),this.renderer&&(this.renderer.setClearAlpha(0),this.renderer.clear(),this.isManagedExternally||(ZI&&console.log("Disposing renderer"),this.renderer.dispose())),this.scene=null,this.renderer=null,this.input.dispose();for(const e of this._disposeCallbacks)try{e()}catch(i){console.error("Error in on dispose callback:",i,e)}(A=this.domElement)!=null&&A.parentElement&&this.domElement.parentElement.removeChild(this.domElement),this._isCreated=!1,mt.dispatchCallback(Yi.ContextDestroyed,this),mt.unregister(this),ii.Current===this&&(ii.Current=null)}registerCoroutineUpdate(t,A,e){return typeof A?.next!="function"?(console.error("Registered invalid coroutine function from "+t.name+`
4991
+ `,t);return}const e=A?.new_scripts??ve.Current.new_scripts;e.includes(t)||e.push(t)}const ii=class{constructor(t){r(this,"name"),r(this,"alias"),r(this,"isManagedExternally",!1),r(this,"isPaused",!1),r(this,"runInBackground",!1),r(this,"targetFrameRate"),r(this,"physicsSteps",1),r(this,"hash"),r(this,"domElement"),r(this,"_resolutionScaleFactor",1),r(this,"_boundingClientRectFrame",-1),r(this,"_boundingClientRect",null),r(this,"_domX"),r(this,"_domY"),r(this,"xr",null),r(this,"_xrFrame",null),r(this,"_currentFrameEvent",-1),r(this,"scene"),r(this,"renderer"),r(this,"composer",null),r(this,"scripts",[]),r(this,"scripts_pausedChanged",[]),r(this,"scripts_earlyUpdate",[]),r(this,"scripts_update",[]),r(this,"scripts_lateUpdate",[]),r(this,"scripts_onBeforeRender",[]),r(this,"scripts_onAfterRender",[]),r(this,"scripts_WithCorroutines",[]),r(this,"scripts_immersive_vr",[]),r(this,"scripts_immersive_ar",[]),r(this,"coroutines",{}),r(this,"post_setup_callbacks",[]),r(this,"pre_update_callbacks",[]),r(this,"pre_render_callbacks",[]),r(this,"post_render_callbacks",[]),r(this,"pre_update_oneshot_callbacks",[]),r(this,"new_scripts",[]),r(this,"new_script_start",[]),r(this,"new_scripts_pre_setup_callbacks",[]),r(this,"new_scripts_post_setup_callbacks",[]),r(this,"new_scripts_xr",[]),r(this,"mainCameraComponent"),r(this,"_camera",null),r(this,"application"),r(this,"time"),r(this,"input"),r(this,"physics"),r(this,"connection"),r(this,"assets"),r(this,"mainLight",null),r(this,"sceneLighting"),r(this,"addressables"),r(this,"lightmaps"),r(this,"players"),r(this,"_sizeChanged",!1),r(this,"_isCreated",!1),r(this,"_isCreating",!1),r(this,"_isVisible",!1),r(this,"_stats",GtA?new A9:null),r(this,"_intersectionObserver",null),r(this,"_disposeCallbacks",[]),r(this,"_originalCreationArgs"),r(this,"onUnhandledRejection",i=>{this.domElement.dispatchEvent(new CustomEvent("error",{detail:i.reason}))}),r(this,"_cameraStack",[]),r(this,"_onBeforeRenderListeners",new Map),r(this,"_onAfterRenderListeners",new Map),r(this,"_requireDepthTexture",!1),r(this,"_requireColorTexture",!1),r(this,"_renderTarget"),r(this,"_isRendering",!1),r(this,"_createId",0),r(this,"_renderlooperrors",0),r(this,"_lastTimestamp",0),r(this,"_accumulatedTime",0),r(this,"_dispatchReadyAfterFrame",!1),r(this,"_wasPaused",!1),this.name=t?.name||"",this.alias=t?.alias,this.domElement=t?.domElement||document.body,this.hash=t?.hash,t!=null&&t.renderer&&(this.renderer=t.renderer,this.isManagedExternally=!0),t?.runInBackground!==void 0&&(this.runInBackground=t.runInBackground),t!=null&&t.scene?this.scene=t.scene:this.scene=new eI,t!=null&&t.camera&&(this._camera=t.camera),this.application=new WL(this),this.time=new OH,this.input=new zL(this),this.physics=new vH(this),this.connection=new JY(this),this.assets=new zq,this.sceneLighting=new TH(this),this.addressables=new PL(this),this.lightmaps=new P9(this),this.players=new qH(this);const A=()=>this._sizeChanged=!0;window.addEventListener("resize",A),this._disposeCallbacks.push(()=>window.removeEventListener("resize",A));const e=new ResizeObserver(i=>this._sizeChanged=!0);e.observe(this.domElement),this._disposeCallbacks.push(()=>e.disconnect()),this._intersectionObserver=new IntersectionObserver(i=>{this._isVisible=i[0].isIntersecting}),this._disposeCallbacks.push(()=>{var i;return(i=this._intersectionObserver)==null?void 0:i.disconnect()}),mt.register(this)}static get DefaultTargetFrameRate(){return ii._defaultTargetFramerate.value}static set DefaultTargetFrameRate(t){ii._defaultTargetFramerate.value=t}static get DefaultWebGLRendererParameters(){return ii._defaultWebglRendererParameters}get version(){return ga}static get Current(){return mt.Current}static set Current(t){mt.Current=t}appendHTMLElement(t){return this.domElement.shadowRoot?this.domElement.shadowRoot.appendChild(t):this.domElement.appendChild(t)}get resolutionScaleFactor(){return this._resolutionScaleFactor}set resolutionScaleFactor(t){if(t!==this._resolutionScaleFactor&&typeof t=="number"){if(t<=0){console.error("Invalid resolution scale factor",t);return}this._resolutionScaleFactor=t,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 t,A;return((A=(t=this.renderer)==null?void 0:t.xr)==null?void 0:A.isPresenting)||!1}get xrSessionMode(){var t;return(t=this.xr)==null?void 0:t.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 t,A;return(A=(t=this.renderer)==null?void 0:t.xr)==null?void 0:A.getSession()}get xrFrame(){return this._xrFrame}get xrCamera(){var t,A;return(A=(t=this.renderer)==null?void 0:t.xr)==null?void 0:A.getCamera()}get arOverlayElement(){const t=this.domElement;return typeof t.getAROverlayContainer=="function"?t.getAROverlayContainer():this.domElement}get currentFrameEvent(){return this._currentFrameEvent}get mainCamera(){if(this._camera)return this._camera;if(this.mainCameraComponent){const t=this.mainCameraComponent;return t.cam||t.buildCamera(),t.cam}return null}set mainCamera(t){this._camera=t}get rendererData(){return this.sceneLighting}get isCreated(){return this._isCreated}createNewRenderer(t){var A,e,i;if((A=this.renderer)==null||A.dispose(),t={...ii.DefaultWebGLRendererParameters,...t},!t.canvas){const g=(i=(e=this.domElement)==null?void 0:e.shadowRoot)==null?void 0:i.querySelector("canvas");g&&(t.canvas=g,ZI&&console.log("Using canvas from shadow root",g))}ZI&&console.log("Using Renderer Parameters:",t,this.domElement),this.renderer=new zC(t),this.renderer.debug.checkShaderErrors=Se()||iA("checkshadererrors")===!0,this.renderer.toneMappingExposure=1,this.renderer.toneMapping=YI,this.renderer.setClearColor(new mA("lightgrey"),0),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=mf,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputColorSpace=_e,this.renderer.useLegacyLights=!1,this.input.bindEvents()}internalOnUpdateVisible(){var t,A;(t=this._intersectionObserver)==null||t.disconnect(),(A=this._intersectionObserver)==null||A.observe(this.domElement)}requestSizeUpdate(){this._sizeChanged=!0}updateSize(t=!1){var A,e,i;if(t||!this.isManagedExternally&&((A=this.renderer.xr)==null?void 0:A.isPresenting)===!1){this._sizeChanged=!1;const g=this.resolutionScaleFactor,I=this.domWidth*g,o=this.domHeight*g,s=this.mainCamera;this.updateAspect(s),this.renderer.setSize(I,o,!0),this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%",this.composer&&((e=this.composer.setSize)==null||e.call(this.composer,I,o),"setPixelRatio"in this.composer&&typeof this.composer.setPixelRatio=="function"&&((i=this.composer.setPixelRatio)==null||i.call(this.composer,window.devicePixelRatio)))}}updateAspect(t,A,e){if(!t)return;A===void 0&&(A=this.domWidth),e===void 0&&(e=this.domHeight);const i=t.aspect;t.aspect=A/e,i!==t.aspect&&t.updateProjectionMatrix()}recreate(){this.clear(),this.create(this._originalCreationArgs)}async onCreate(t){return this.create(t)}async create(t){try{this._isCreating=!0,t!==this._originalCreationArgs&&(this._originalCreationArgs=Lc(t)),window.addEventListener("unhandledrejection",this.onUnhandledRejection);const A=await this.internalOnCreate(t);return this._isCreated=!0,A}finally{window.removeEventListener("unhandledrejection",this.onUnhandledRejection),this._isCreating=!1}}clear(){var t,A,e,i;mt.dispatchCallback(Yi.ContextClearing,this),Ms(this.scene,!0,!0),this.scene=new eI,(t=this.addressables)==null||t.dispose(),(A=this.lightmaps)==null||A.clear(),(i=(e=this.physics)==null?void 0:e.engine)==null||i.clearCaches(),this.isManagedExternally||this.renderer&&(this.renderer.renderLists.dispose(),this.renderer.state.reset(),this.renderer.resetState()),mt.dispatchCallback(Yi.ContextCleared,this)}dispose(){this.internalOnDestroy()}onDestroy(){this.internalOnDestroy()}internalOnDestroy(){var t,A;this.clear(),(t=this.renderer)==null||t.setAnimationLoop(null),this.renderer&&(this.renderer.setClearAlpha(0),this.renderer.clear(),this.isManagedExternally||(ZI&&console.log("Disposing renderer"),this.renderer.dispose())),this.scene=null,this.renderer=null,this.input.dispose();for(const e of this._disposeCallbacks)try{e()}catch(i){console.error("Error in on dispose callback:",i,e)}(A=this.domElement)!=null&&A.parentElement&&this.domElement.parentElement.removeChild(this.domElement),this._isCreated=!1,mt.dispatchCallback(Yi.ContextDestroyed,this),mt.unregister(this),ii.Current===this&&(ii.Current=null)}registerCoroutineUpdate(t,A,e){return typeof A?.next!="function"?(console.error("Registered invalid coroutine function from "+t.name+`
4992
4992
  Coroutine functions must be generators: "*myCoroutine() {...}"
4993
4993
  Start a coroutine from a component by calling "this.startCoroutine(myCoroutine())"`),A):(this.coroutines[e]||(this.coroutines[e]=[]),this.coroutines[e].push({comp:t,main:A}),A)}unregisterCoroutineUpdate(t,A){if(!this.coroutines[A])return;const e=this.coroutines[A].findIndex(i=>i.main===t);e>=0&&this.coroutines[A].splice(e,1)}stopAllCoroutinesFrom(t){for(const A in this.coroutines){const e=this.coroutines[A];for(let i=e.length-1;i>=0;i--)e[i].comp===t&&e.splice(i,1)}}setCurrentCamera(t){var A;if(!t)return;if(t.cam||t.buildCamera(),!t.cam){console.warn("Camera component is missing camera",t);return}const e=this._cameraStack.indexOf(t);e>=0&&this._cameraStack.splice(e,1),this._cameraStack.push(t),this.mainCameraComponent=t;const i=t.cam;i.isPerspectiveCamera&&this.updateAspect(i),(A=this.mainCameraComponent)==null||A.applyClearFlagsIfIsActiveCamera()}removeCamera(t){if(!t)return;const A=this._cameraStack.indexOf(t);if(A>=0&&this._cameraStack.splice(A,1),this.mainCameraComponent===t&&(this.mainCameraComponent=void 0,this._cameraStack.length>0)){const e=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(e)}}addBeforeRenderListener(t,A){this._onBeforeRenderListeners.has(t.uuid)||(this._onBeforeRenderListeners.set(t.uuid,[]),t.onBeforeRender=this._createRenderCallbackWrapper(t,this._onBeforeRenderListeners)),this._onBeforeRenderListeners.get(t.uuid).push(A)}removeBeforeRenderListener(t,A){if(this._onBeforeRenderListeners.has(t.uuid)){const e=this._onBeforeRenderListeners.get(t.uuid),i=e.indexOf(A);i>=0&&e.splice(i,1)}}addAfterRenderListener(t,A){var e;this._onAfterRenderListeners.has(t.uuid)||(this._onAfterRenderListeners.set(t.uuid,[]),t.onAfterRender=this._createRenderCallbackWrapper(t,this._onAfterRenderListeners)),(e=this._onAfterRenderListeners.get(t.uuid))==null||e.push(A)}removeAfterRenderListener(t,A){if(this._onAfterRenderListeners.has(t.uuid)){const e=this._onAfterRenderListeners.get(t.uuid),i=e.indexOf(A);i>=0&&e.splice(i,1)}}_createRenderCallbackWrapper(t,A){return(e,i,g,I,o,s)=>{const C=A.get(t.uuid);if(C)for(let a=0;a<C.length;a++){const n=C[a];n(e,i,g,I,o,s)}}}get isRendering(){return this._isRendering}setRequireDepth(t){this._requireDepthTexture=t}setRequireColor(t){this._requireColorTexture=t}get depthTexture(){var t;return((t=this._renderTarget)==null?void 0:t.depthTexture)||null}get opaqueColorTexture(){var t;return((t=this._renderTarget)==null?void 0:t.texture)||null}get isVisibleToUser(){if(this.isInXR)return!0;if(!this._isVisible)return!1;const t=getComputedStyle(this.domElement);return t.visibility!=="hidden"&&t.display!=="none"&&t.opacity!=="0"}async internalOnCreate(t){var A,e,i,g,I;const o=++this._createId;ZI&&console.log("Creating context",this.name,t),this.clear(),this.isManagedExternally===!1&&(this.createNewRenderer(),(A=this.renderer)==null||A.setAnimationLoop(null)),await Jo(1),ii.Current=this,await mt.dispatchCallback(Yi.ContextCreationStart,this);let s=!0,C;try{ii.Current=this,t?C=await this.internalLoadInitialContent(o,t):C=[]}catch(n){console.error(n),s=!1}if(!s||o!==this._createId)return!1;if(this.internalOnUpdateVisible(),!this.renderer)return ZI&&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),ii.Current=this,ii.Current=this;for(let n=0;n<this.new_scripts.length;n++){const B=this.new_scripts[n];if(B.gameObject!==void 0&&B.gameObject!==null){B.gameObject.userData===void 0&&(B.gameObject.userData={}),B.gameObject.userData.components===void 0&&(B.gameObject.userData.components=[]);const Q=B.gameObject.userData.components;Q.includes(B)||Q.push(B)}}if(this.post_setup_callbacks)for(let n=0;n<this.post_setup_callbacks.length;n++)ii.Current=this,await this.post_setup_callbacks[n](this);if(!this.mainCamera){ii.Current=this;let n=null;lB(this.scene,B=>{const Q=B;if(Q!=null&&Q.isCamera){if(Xc(Q.gameObject),!Q.activeAndEnabled)return;if(Q.tag==="MainCamera")return n=Q,!0;n=Q}}),n?this.setCurrentCamera(n):!mt.dispatchCallback(Yi.MissingCamera,this,{files:C})&&!this.mainCamera&&!this.isManagedExternally&&console.warn("Missing camera in main scene",this)}if(this.input.bindEvents(),ii.Current=this,TD(this),this.physics.engine&&((e=this.physics.engine)==null||e.step(0),(i=this.physics.engine)==null||i.postStep()),!this.isManagedExternally&&this.composer&&this.mainCamera){const n=new VD(this.scene,this.mainCamera);this.renderer.setSize(this.domWidth,this.domHeight),this.composer.addPass(n),this.composer.setSize(this.domWidth,this.domHeight)}this._sizeChanged=!0,this._stats&&(this._stats.showPanel(0),(g=this.domElement.shadowRoot)==null||g.appendChild(this._stats.dom)),ZI&&Yy(this.scene,!0),this.targetFrameRate===void 0?(ZI&&console.warn("No target framerate set, using default",ii.DefaultTargetFrameRate),this.targetFrameRate=ii._defaultTargetFramerate):ZI&&console.log("Target framerate set to",this.targetFrameRate),this._dispatchReadyAfterFrame=!0;const a=mt.dispatchCallback(Yi.ContextCreated,this,{files:C});return a&&("internalSetLoadingMessage"in this.domElement&&typeof this.domElement.internalSetLoadingMessage=="function"&&((I=this.domElement)==null||I.internalSetLoadingMessage("finish loading")),await a),IB(this,Yi.ContextCreated),ZI&&console.log("Context Created...",this.renderer,this.renderer.domElement),this._isCreating=!1,this.isManagedExternally||this.restartRenderLoop(),a}async internalLoadInitialContent(t,A){var e,i;const g=new Array;if(A.files.length===0)return g;const I=[...A.files],o={name:"",progress:null,index:0,count:I.length},s=Bs(),C=0;for(let a=0;a<I.length;a++){if(t!==this._createId){ZI&&console.log("Aborting loading because create id changed",t,this._createId);break}const n=I[a];if(!n.includes(".glb")&&!n.includes(".gltf")){const Q=`Needle Engine: found suspicious src "${n}"`;console.warn(Q),pI()&&Ci(Q)}(e=A?.onLoadingStart)==null||e.call(this,a,n),ZI&&console.log("Context Load "+n);const B=await s.loadSync(this,n,n,C,Q=>{var E;o.name=n,o.progress=Q,o.index=a,o.count=I.length,(E=A.onLoadingProgress)==null||E.call(this,o)});(i=A?.onLoadingFinished)==null||i.call(this,a,n,B??null),B?g.push({src:n,file:B}):console.warn("Could not load file: "+n)}if(t!==this._createId){for(const a of g)if(a&&a.file)for(const n of a.file.scenes)Ms(n,!0,!0)}else for(const a of g)a&&a.file&&this.scene.add(a.file.scene);return g}restartRenderLoop(){return this.renderer?this._isCreating?(console.warn("Can not start render loop while creating context"),!1):(this.renderer.setAnimationLoop((t,A)=>{this.isManagedExternally||this.update(t,A)}),!0):(console.error("Can not start render loop without renderer"),!1)}update(t,A){if(A===void 0&&(A=null),Se()||ZI||Tz())try{this.internalStep(t,A),this._renderlooperrors=0}catch(e){this._renderlooperrors+=1,(Se()||ZI)&&(e instanceof Error||e instanceof TypeError)&&wi("Caught unhandled exception during render-loop - see console for details.",vo.Error),console.error("Frame #"+this.time.frame+`
4994
- `,e),this._renderlooperrors>=3&&(console.warn("Stopping render loop due to error"),this.renderer.setAnimationLoop(null)),this.domElement.dispatchEvent(new CustomEvent("error",{detail:e}))}else this.internalStep(t,A)}updatePhysics(t){this.internalUpdatePhysics(t)}internalStep(t,A){this.internalOnBeforeRender(t,A)!==!1&&(this.internalOnRender(),this.internalOnAfterRender())}internalOnBeforeRender(t,A){var e;const i=A!==null&&this._xrFrame===null;if(this._xrFrame=A,i&&this.domElement.dispatchEvent(new CustomEvent("xr-session-started",{detail:{context:this,session:this.xrSession,frame:A}})),this._currentFrameEvent=-1,this.isManagedExternally===!1&&this.isInXR===!1&&this.targetFrameRate!==void 0){this._lastTimestamp===0&&(this._lastTimestamp=t),this._accumulatedTime+=(t-this._lastTimestamp)/1e3,this._lastTimestamp=t;let g=this.targetFrameRate;if(typeof g=="object"&&(g=g.value),this._accumulatedTime<1/(g+1))return!1;this._accumulatedTime=0}if((e=this._stats)==null||e.begin(),ii.Current=this,this.onHandlePaused())return!1;for(ii.Current=this,this.time.update(),RtA&&console.log("FPS",this.time.smoothedFps.toFixed(0)),TD(this),HD(this.scene),sL(this),IB(this,-1);this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);const g=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(g)}if(this.pre_update_oneshot_callbacks){for(const g in this.pre_update_oneshot_callbacks)this.pre_update_oneshot_callbacks[g]();this.pre_update_oneshot_callbacks.length=0}if(this.pre_update_callbacks)for(const g in this.pre_update_callbacks)this.pre_update_callbacks[g]();this._currentFrameEvent=0;for(let g=0;g<this.scripts_earlyUpdate.length;g++){const I=this.scripts_earlyUpdate[g];I.activeAndEnabled&&I.earlyUpdate!==void 0&&(ii.Current=this,I.earlyUpdate())}if(this.executeCoroutines(0),IB(this,0),this.onHandlePaused())return!1;this._currentFrameEvent=1;for(let g=0;g<this.scripts_update.length;g++){const I=this.scripts_update[g];I.activeAndEnabled&&I.update!==void 0&&(ii.Current=this,I.update())}if(this.executeCoroutines(1),IB(this,1),this.onHandlePaused())return!1;this._currentFrameEvent=2;for(let g=0;g<this.scripts_lateUpdate.length;g++){const I=this.scripts_lateUpdate[g];I.activeAndEnabled&&I.lateUpdate!==void 0&&(ii.Current=this,I.lateUpdate())}if(this.executeCoroutines(2),IB(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 g=0;g<this.scripts_onBeforeRender.length;g++){const I=this.scripts_onBeforeRender[g];I.activeAndEnabled&&I.onBeforeRender!==void 0&&(ii.Current=this,I.onBeforeRender(A))}if(this.executeCoroutines(3),IB(this,3),this._sizeChanged&&this.updateSize(),this.pre_render_callbacks)for(const g in this.pre_render_callbacks)this.pre_render_callbacks[g](A)}return!0}internalUpdatePhysics(t){if(!this.physics.engine)return!1;const A=t,e=this.time.deltaTime/A;for(let i=0;i<A;i++)this._currentFrameEvent=9,this.executeCoroutines(9),this.physics.engine.step(e),this._currentFrameEvent=10,this.executeCoroutines(10);return this.physics.engine.postStep(),!0}internalOnRender(){this.isManagedExternally||(Oz(this),this._currentFrameEvent=-1,this.renderNow(),this._currentFrameEvent=4)}internalOnAfterRender(){if(this.isVisibleToUser||this.runInBackground){for(let t=0;t<this.scripts_onAfterRender.length;t++){const A=this.scripts_onAfterRender[t];A.activeAndEnabled&&A.onAfterRender!==void 0&&(ii.Current=this,A.onAfterRender())}if(this.executeCoroutines(4),IB(this,4),this.post_render_callbacks)for(const t in this.post_render_callbacks)this.post_render_callbacks[t]()}this._currentFrameEvent=-1,this.connection.sendBufferedMessagesNow(),this._stats&&(this._stats.end(),this.time.frameCount%150===0&&console.log({...this.renderer.info.memory},{...this.renderer.info.render})),this._dispatchReadyAfterFrame&&(this._dispatchReadyAfterFrame=!1,this.domElement.dispatchEvent(new CustomEvent("ready")),mt.dispatchCallback(Yi.ContextFirstFrameRendered,this))}renderNow(t){return!t&&(t=this.mainCamera,!t)?!1:(this._isRendering=!0,this.renderRequiredTextures(),this.composer&&!this.isInXR?this.composer.render(this.time.deltaTime):t&&this.renderer.render(this.scene,t),this._isRendering=!1,!0)}onHandlePaused(){const t=this.evaluatePaused();if(this._wasPaused!==t){MtA&&console.log("Paused?",t,"context:"+this.alias);for(let A=0;A<this.scripts_pausedChanged.length;A++){const e=this.scripts_pausedChanged[A];e.activeAndEnabled&&e.onPausedChanged!==void 0&&(ii.Current=this,e.onPausedChanged(t,this._wasPaused))}}return this._wasPaused=t,t}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 tt(this.domWidth,this.domHeight),this._requireDepthTexture){const e=new TQ(this.domWidth,this.domHeight);this._renderTarget.depthTexture=e}this._requireColorTexture&&(this._renderTarget.texture=new Ye,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=He,this._renderTarget.texture.magFilter=He,this._renderTarget.texture.format=yt)}const t=this._renderTarget;t.texture&&(t.texture.colorSpace=this.renderer.outputColorSpace);const A=this.renderer.getRenderTarget();this.renderer.setRenderTarget(t),this.renderer.render(this.scene,this.mainCamera),this.renderer.setRenderTarget(A)}executeCoroutines(t){var A;if(this.coroutines[t]){const i=this.coroutines[t];for(let g=0;g<i.length;g++)try{const I=i[g];if(!I.comp||I.comp.destroyed||!I.main||I.comp.enabled===!1){UtA&&console.log("Removing coroutine",I.comp,I.comp.enabled),i.splice(g,1),--g;continue}const o=I.chained;if(o&&o.length>0){const a=o[o.length-1].next();if(a.done&&o.pop(),e(a)&&(I.chained||(I.chained=[]),I.chained.push(a.value)),!a.done)continue}const s=I.main.next();if(s.done===!0){i.splice(g,1),--g;continue}const C=s.value;if(e(C)){if(C.next().done)continue;I.chained||(I.chained=[]),I.chained.push(C)}else if(C instanceof Promise){const a=C;I.chained||(I.chained=[]);const n=ZL(a);(A=I.chained)==null||A.push(n);continue}}catch(I){console.error(I)}}function e(i){return!!(i&&i.next&&i.return)}}};let ve=ii;r(ve,"_defaultTargetFramerate",{value:60}),r(ve,"_defaultWebglRendererParameters",{antialias:!0,alpha:!1}),mt.registerCallback(Yi.ContextCreated,t=>{const A=t.context;XH(A),ZH(A)});const Py=iA("debugcomponents"),PH="eff8ba80-635d-11ec-90d6-0242ac120003";class Dg{constructor(A){r(this,"_originalSeed"),r(this,"_seed"),typeof A=="string"&&(A=Dg.hash(A)),this._originalSeed=A,this._seed=A}get seed(){return this._seed}set seed(A){this._seed=A}reset(){this._seed=this._originalSeed}generateUUID(A){if(typeof A=="string")return rL(A,PH);const e=this._seed;return this._seed-=1,rL(e.toString(),PH)}initialize(A){typeof A=="string"?this._seed=Dg.hash(A):this._seed=A}static createFromString(A){return new Dg(this.hash(A))}static hash(A){let e=0;for(let i=0;i<A.length;i++)e=A.charCodeAt(i)+((e<<5)-e);return e}}var jH=(t=>(t.NewInstanceCreated="new-instance-created",t.InstanceDestroyed="instance-destroyed",t))(jH||{});class WH{constructor(A){r(this,"guid"),this.guid=A}}function jy(t,A,e=!0){if(!t)return;const i=t;if(Ms(t,e),!A){console.warn("Can not send destroy: No networking connection provided",t.guid);return}if(!A.isConnected){console.warn("Can not send destroy: not connected",t.guid);return}let g=t.guid;if(!g&&i.uuid&&(g=i.uuid),!g){console.warn("Can not send destroy: failed to find guid",t);return}const I=new WH(g);A.send("instance-destroyed",I,ps.Queued)}function VH(t,A){const e=new WH(t);A.send("instance-destroyed",e,ps.Queued)}function ZH(t){t.connection.beginListen("instance-destroyed",A=>{Py&&console.log("[Remote] Destroyed",t.scene,A);const e=vl(A.guid,t.scene);e&&Ms(e)})}class KtA{constructor(A,e,i){r(this,"filename"),r(this,"hash"),r(this,"size"),this.filename=A,this.hash=e,this.size=i}}class zH{constructor(A,e){r(this,"guid"),r(this,"originalGuid"),r(this,"seed"),r(this,"visible"),r(this,"hostData"),r(this,"dontSave"),r(this,"parent"),r(this,"position"),r(this,"rotation"),r(this,"scale"),r(this,"preventCreation"),this.originalGuid=A,this.guid=e}}function GR(t,A,e,i){var g;const I=t;if(!I.guid)return console.warn("Can not instantiate: No guid",I),null;if(A.context||(A.context=ve.Current),!A.context)return console.error("Missing network instantiate options / reference to network connection in sync instantiate"),null;const o=A?{...A}:null,{instance:s,seed:C}=JtA(I,A);if(s){const a=s;if(a.guid){Py&&console.log("[Local] new instance","gameobject:",s?.guid);const n=new zH(I.guid,a.guid);n.seed=C,o&&(o.position&&(n.position={x:o.position.x,y:o.position.y,z:o.position.z}),o.rotation&&(n.rotation={x:o.rotation.x,y:o.rotation.y,z:o.rotation.z,w:o.rotation.w}),o.scale&&(n.scale={x:o.scale.x,y:o.scale.y,z:o.scale.z})),n.position||(n.position={x:a.position.x,y:a.position.y,z:a.position.z}),n.rotation||(n.rotation={x:a.quaternion.x,y:a.quaternion.y,z:a.quaternion.z,w:a.quaternion.w}),n.scale||(n.scale={x:a.scale.x,y:a.scale.y,z:a.scale.z}),n.visible=I.visible,o!=null&&o.parent&&(typeof o.parent=="string"?n.parent=o.parent:n.parent=o.parent.guid),n.hostData=e,i===!1&&(n.dontSave=!0),(g=A?.context)==null||g.connection.send("new-instance-created",n)}else console.warn("Missing guid, can not send new instance event",a)}return s}function Wy(){return Math.random()*9999999}function XH(t){t.connection.beginListen("new-instance-created",async A=>{const e=await vtA(A.originalGuid,t.scene);if(A.preventCreation===!0)return;if(!e){console.warn("could not find object that was instantiated: "+A.guid);return}const i=new xs;A.position&&(i.position=new w(A.position.x,A.position.y,A.position.z)),A.rotation&&(i.rotation=new FA(A.rotation.x,A.rotation.y,A.rotation.z,A.rotation.w)),A.scale&&(i.scale=new w(A.scale.x,A.scale.y,A.scale.z)),i.parent=A.parent,A.seed&&(i.idProvider=new Dg(A.seed)),i.visible=A.visible,i.context=t,Py&&t.alias&&console.log("[Remote] instantiate in: "+t.alias);const g=SE(e,i);g&&(A.parent==="scene"&&t.scene.add(g),Py&&console.log("[Remote] new instance","gameobject:",g?.guid,e))})}function JtA(t,A){const e=Wy(),i=A??new xs;i.idProvider=new Dg(e);const g=SE(t,i);return{seed:e,instance:g}}const $H={};function A2(t,A){$H[t]=A}async function vtA(t,A){const e=$H[t];if(e!=null){const i=await e(t);if(i)return i}return e2(t,A)}function e2(t,A){if(A===null||!t)return null;if(A.guid===t)return A;if(A.children)for(const e of A.children){const i=e2(t,e);if(i)return i}return null}const Vy=iA("debuggetcomponent"),Zy=iA("debuginstantiate");var t2=(t=>(t[t.None=0]="None",t[t.HideInHierarchy=1]="HideInHierarchy",t[t.HideInInspector=2]="HideInInspector",t[t.DontSaveInEditor=4]="DontSaveInEditor",t[t.NotEditable=8]="NotEditable",t[t.DontSaveInBuild=16]="DontSaveInBuild",t[t.DontUnloadUnusedAsset=32]="DontUnloadUnusedAsset",t[t.DontSave=52]="DontSave",t[t.HideAndDontSave=61]="HideAndDontSave",t))(t2||{});class xs{constructor(){r(this,"idProvider"),r(this,"parent"),r(this,"keepWorldPosition"),r(this,"position"),r(this,"rotation"),r(this,"scale"),r(this,"visible"),r(this,"context")}clone(){var A,e,i;const g=new xs;return g.idProvider=this.idProvider,g.parent=this.parent,g.keepWorldPosition=this.keepWorldPosition,g.position=(A=this.position)==null?void 0:A.clone(),g.rotation=(e=this.rotation)==null?void 0:e.clone(),g.scale=(i=this.scale)==null?void 0:i.clone(),g}cloneAssign(A){var e,i,g;this.idProvider=A.idProvider,this.parent=A.parent,this.keepWorldPosition=A.keepWorldPosition,this.position=(e=A.position)==null?void 0:e.clone(),this.rotation=(i=A.rotation)==null?void 0:i.clone(),this.scale=(g=A.scale)==null?void 0:g.clone()}}function wE(t){return t.visible}function Jl(t,A){return typeof A=="number"&&(A=A>.5),t.visible=A,t.visible}function i2(t){return t[Ia]||zy(t)}function g2(t,A){t[IL]=A}function zy(t){return Ts.isUsingInstancing(t)}function vl(t,A){return eE(t,A,!0,!0)}const I2=Symbol("isDestroyed");function cB(t){return t[I2]}function o2(t,A){t[I2]=A}const MR=Symbol("isDontDestroy");function RR(t,A=!0){t[MR]=A}const Xy=[],$y=[];function Ms(t,A=!0,e=!1){Xy.length=0,$y.length=0,UR(t,A,e,!0);for(const i of Xy)i.gameObject=null,i.context=null;for(const i of $y)o2(i,!0),e&&Yt(i),tL(i);$y.length=0,Xy.length=0}function UR(t,A=!0,e=!1,i=!0){if(t==null)return;const g=t;if(g.isComponent){if(g[MR])return;Xy.push(g);const s=g.gameObject;g.__internalDisable(),g.__internalDestroy(),g.gameObject=s;return}if(t[MR])return;const I=t;Vy&&console.log(I),$y.push(I);const o=I.userData.components;if(o){let s=o.length;for(let C=0;C<o.length;C++){const a=o[C];UR(a,A,e,!1),o.length<s&&(s=o.length,C--)}}if(A&&I.children)for(const s of I.children)UR(s,A,e,!1);i&&I.removeFromParent()}function lB(t,A,e=!0){return s2(t,A,e)}function*NR(t,A,e=!1,i=999,g=0){if(t!=null&&t.userData.components&&!(g>i)){for(const I of t.userData.components)A&&I?.isComponent===!0&&I instanceof A?yield I:yield I;if(e===!0)for(const I of t.children)yield*NR(I,A,!0,i,g+1)}}function s2(t,A,e,i=0){var g;if(t){if(t.isObject3D,i>1e3){console.warn("Failed to iterate components: too many levels");return}if((g=t.userData)!=null&&g.components)for(let I=0;I<t.userData.components.length;I++){const o=t.userData.components[I];if(o?.isComponent===!0){const s=A(o);if(s!==void 0)return s}}if(e&&t.children){const I=i+1;for(let o=0;o<t.children.length;o++){const s=t.children[o];if(!s)continue;const C=s2(s,A,e,I);if(C!==void 0)return C}}}}function SE(t,A=null){let e=null;A!==null&&(A.x!==void 0?(e=new xs,e.position=A):e=A);let i=ve.Current;e!=null&&e.context&&(i=e.context),Vy&&i.alias&&console.log("context",i.alias),e&&!e.idProvider&&(e.idProvider=new Dg(Date.now()));const g=[],I={},o={},s=C2(i,t,e,g,I,o);s&&(qtA(I),btA(o,I)),Vy&&(Yy(t,!0),Yy(s,!0));const C={};for(const a in g){const n=g[a],B=n.guid;e&&e.idProvider&&(n.guid=e.idProvider.generateUUID(),C[B]=n.guid,Vy&&console.log(n.name,n.guid)),Oy(n,i),n.__internalNewInstanceCreated&&n.__internalNewInstanceCreated()}for(const a in g){const n=g[a];n.resolveGuids&&n.resolveGuids(C),n.enabled!==!1&&(n.enabled=!0)}return TD(i),s}function C2(t,A,e,i,g,I){var o;if(!A)return null;const s=A.userData;A.userData={};const C=A.children;A.children=[];const a=A.clone(!1);if(Aw(a),A.userData=s,A.children=C,g[A.uuid]={original:A,clone:a},Zy&&console.log("ADD",A,a),A.type==="SkinnedMesh"&&(I[A.uuid]={original:A,clone:a}),e?.visible!==void 0&&(a.visible=e.visible),e!=null&&e.idProvider){a.uuid=e.idProvider.generateUUID();const B=a;B&&(B.guid=a.uuid)}A.animations&&A.animations.length>0&&(a.animations=[...A.animations]);const n=A.parent;if(n&&n.add(a),e!=null&&e.position?CI(a,e.position):a.position.copy(A.position),e!=null&&e.rotation?_o(a,e.rotation):a.quaternion.copy(A.quaternion),e!=null&&e.scale?a.scale.copy(e.scale):a.scale.copy(A.scale),e!=null&&e.parent&&e.parent!=="scene"){let B=null;if(typeof e.parent=="string"?B=eE(e.parent,t.scene,!0):B=e.parent,B){const Q=e.keepWorldPosition===!0?B.attach:B.add;Q?Q.call(B,a):console.error("Invalid parent object",B,"received when instantiating:",A)}else console.warn("could not find parent:",e.parent)}for(const[B,Q]of Object.entries(A.userData))B!=="components"&&(a.userData[B]=Q);if((o=A.userData)!=null&&o.components){const B=A.userData.components,Q=[];a.userData.components=Q;for(let E=0;E<B.length;E++){const h=B[E],d=new h.constructor;BE(d,h),h[Zc]!==void 0&&(d[Zc]=h[Zc]),Q.push(d),d.gameObject=a,i.push(d),Vc.dispatchComponentLifecycleEvent(Wc.Added,d)}}e&&(e.position=void 0,e.rotation=void 0,e.scale=void 0,e.parent=void 0);for(const B in A.children){const Q=A.children[B],E=C2(t,Q,e,i,g,I);E&&a.add(E)}return a}function btA(t,A){for(const e in t){const i=t[e],g=i.original,I=g.skeleton,o=i.clone;if(!I){console.warn("Skinned mesh has no skeleton?",i);continue}const s=I.bones,C=o.skeleton.clone();o.skeleton=C,o.bindMatrix.clone().copy(g.bindMatrix),o.bindMatrixInverse.copy(g.bindMatrixInverse);const a=[];C.bones=a;for(let n=0;n<s.length;n++){const B=s[n],Q=A[B.uuid].clone;a.push(Q)}}for(const e in t){const i=t[e].clone;i.skeleton.update(),i.bind(i.skeleton,i.bindMatrix),i.updateMatrixWorld(!0)}}function qtA(t){var A;for(const e in t){const i=t[e].clone;if((A=i.userData)!=null&&A.components)for(let g=0;g<i.userData.components.length;g++){const I=i.userData.components[g],o=Object.entries(I);for(const[s,C]of o)if(Array.isArray(C)){const a=[];I[s]=a;for(let n=0;n<C.length;n++){const B=C[n];if(typeof B!="object"){a.push(B);continue}const Q=a2(I,s,B,t);Q!==void 0?a.push(Q):a.push(B)}}else if(typeof C=="object"){const a=a2(I,s,C,t);a!==void 0&&(I[s]=a)}}}}function a2(t,A,e,i){var g,I;if(e!=null)if(e.isComponent===!0){const o=e.gameObject;if(o){const s=o.uuid,C=(g=i[s])==null?void 0:g.clone;if(!C){Zy&&console.log("reference did not change",A,t,e);return}const a=o.userData.components.indexOf(e);if(a>=0)return Zy&&console.log(A,s),C.userData.components[a];console.warn("could not find component",A,e)}}else if(e.isObject3D===!0){if(A==="gameObject")return;const o=e;if(o){const s=o.uuid,C=(I=i[s])==null?void 0:I.clone;if(C)return Zy&&console.log(A,"old",e,"new",C),C}}else{if(e.isVector4||e.isVector3||e.isVector2||e.isQuaternion||e.isEuler||e.isColor===!0)return e.clone();if(e.isEventList===!0)return new e.constructor}}const n2=new Map;function LtA(t,A){if(!t)return;if(!A){console.warn("No prototype found",t,t.prototype,t.constructor);return}const e=n2.get(A);e&&e.apply(t)}function xtA(t){const A=YtA(t.prototype);n2.set(t,A)}function YtA(t){return new TtA(t)}class TtA{constructor(A){r(this,"$symbol"),r(this,"extensions"),r(this,"descriptors"),this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(A),this.descriptors=new Array;for(let e=0;e<this.extensions.length;e++){const i=this.extensions[e],g=Object.getOwnPropertyDescriptor(A,i);g&&this.descriptors.push(g)}}apply(A){if(!A[this.$symbol]){A[this.$symbol]=!0;for(let e=0;e<this.extensions.length;e++){const i=this.extensions[e],g=this.descriptors[e];g&&Object.defineProperty(A,i,g)}}}}function Aw(t){t&&t.isObject3D===!0&&LtA(t,wA)}wA.prototype.SetActive=function(t){this.visible=t},wA.prototype.setActive=function(t){this.visible=t},wA.prototype.destroy=function(){Ms(this)},wA.prototype.addComponent=function(t){return JR(this,t)},wA.prototype.addNewComponent=function(t){return Jn(this,new t)},wA.prototype.removeComponent=function(t){return KR(this,t)},wA.prototype.getOrAddComponent=function(t){return ew(this,t)},wA.prototype.getComponent=function(t){return fE(this,t)},wA.prototype.getComponents=function(t,A){return bl(this,t,A)},wA.prototype.getComponentInChildren=function(t){return ql(this,t)},wA.prototype.getComponentsInChildren=function(t,A){return Ll(this,t,A)},wA.prototype.getComponentInParent=function(t){return xl(this,t)},wA.prototype.getComponentsInParent=function(t,A){return tw(this,t,A)},Object.getOwnPropertyDescriptor(wA.prototype,"activeSelf")||Object.defineProperty(wA.prototype,"activeSelf",{get:function(){return wE(this)},set:function(t){Jl(this,t)}}),Object.getOwnPropertyDescriptor(wA.prototype,"transform")||Object.defineProperty(wA.prototype,"transform",{get:function(){return this}}),Object.getOwnPropertyDescriptor(wA.prototype,"worldPosition")||Object.defineProperty(wA.prototype,"worldPosition",{get:function(){return this instanceof gG?Ne(this.object):Ne(this)},set:function(t){CI(this,t)}}),Object.getOwnPropertyDescriptor(wA.prototype,"worldQuaternion")||Object.defineProperty(wA.prototype,"worldQuaternion",{get:function(){return this instanceof gG?Kt(this.object):Kt(this)},set:function(t){_o(this,t)}}),Object.getOwnPropertyDescriptor(wA.prototype,"worldRotation")||Object.defineProperty(wA.prototype,"worldRotation",{get:function(){return Ml(this)},set:function(t){uR(this,t)}}),Object.getOwnPropertyDescriptor(wA.prototype,"worldScale")||Object.defineProperty(wA.prototype,"worldScale",{get:function(){return ai(this)},set:function(t){Gl(this,t)}}),Object.getOwnPropertyDescriptor(wA.prototype,"worldForward")||Object.defineProperty(wA.prototype,"worldForward",{get:function(){return _i().set(0,0,1).applyQuaternion(Kt(this))}}),Object.getOwnPropertyDescriptor(wA.prototype,"worldRight")||Object.defineProperty(wA.prototype,"worldRight",{get:function(){return _i().set(1,0,0).applyQuaternion(Kt(this))}}),Object.getOwnPropertyDescriptor(wA.prototype,"worldUp")||Object.defineProperty(wA.prototype,"worldUp",{get:function(){return _i().set(0,1,0).applyQuaternion(Kt(this))}}),xtA(wA);const FR=iA("debuggetcomponent");function HtA(t){return t==null||t.isObject3D?t:t.object&&t.object.isObject3D?t.object:t}function KR(t,A){if(!t||!t.userData.components)return;const e=t.userData.components.indexOf(A);e<0||(Vc.dispatchComponentLifecycleEvent(Wc.Removing,A),A.gameObject=null,t.userData.components.splice(e,1))}function ew(t,A){const e=fE(t,A);if(e)return e;const i=new A;return Jn(t,i)}const r2=new Dg("addComponentIdProvider");function Jn(t,A,e=!0){t.userData||(t.userData={}),t.userData.components||(t.userData.components=[]),t.userData.components.push(A),A.gameObject=t,(A.guid===void 0||A.guid==="invalid")&&(A.guid=r2.generateUUID()),Aw(t),Oy(A);try{e&&A.__internalAwake&&(Xc(t),A.activeAndEnabled&&A.__internalAwake()),Vc.dispatchComponentLifecycleEvent(Wc.Added,A)}catch(i){console.error(i)}return A}function JR(t,A){if(typeof A=="function")return Jn(t,new A);if(A.destroyed)return console.warn("Can not move/add a destroyed component",A),A;if(A.gameObject===t)return A;if(A.gameObject&&A.gameObject.userData.components){const e=A.gameObject.userData.components.indexOf(A);A.gameObject.userData.components.splice(e,1)}if(!t.userData.components)t.userData.components=[];else if(t.userData.components.includes(A))return A;return t.userData.components.push(A),A.gameObject=t,(A.guid===void 0||A.guid==="invalid")&&(A.guid=r2.generateUUID()),Oy(A),A}function B2(t){if(t.gameObject&&t.gameObject.userData.components){const A=t.gameObject.userData.components.indexOf(t);t.gameObject.userData.components.splice(A,1)}t.__internalDisable&&t.__internalDisable(),oa(t,t.context??ve.Current),t.destroy(),t.gameObject=null}let Q2=!1;function E2(t,A,e){var i;if(t==null)return null;if(!t.isObject3D)return console.error("Object is not object3D"),null;if(!((i=t?.userData)!=null&&i.components)||(typeof A=="string"&&(Q2||(Q2=!0,console.warn(`Accessing components by name is not supported.
4994
+ `,e),this._renderlooperrors>=3&&(console.warn("Stopping render loop due to error"),this.renderer.setAnimationLoop(null)),this.domElement.dispatchEvent(new CustomEvent("error",{detail:e}))}else this.internalStep(t,A)}updatePhysics(t){this.internalUpdatePhysics(t)}internalStep(t,A){this.internalOnBeforeRender(t,A)!==!1&&(this.internalOnRender(),this.internalOnAfterRender())}internalOnBeforeRender(t,A){var e;const i=A!==null&&this._xrFrame===null;if(this._xrFrame=A,i&&this.domElement.dispatchEvent(new CustomEvent("xr-session-started",{detail:{context:this,session:this.xrSession,frame:A}})),this._currentFrameEvent=-1,this.isManagedExternally===!1&&this.isInXR===!1&&this.targetFrameRate!==void 0){this._lastTimestamp===0&&(this._lastTimestamp=t),this._accumulatedTime+=(t-this._lastTimestamp)/1e3,this._lastTimestamp=t;let g=this.targetFrameRate;if(typeof g=="object"&&(g=g.value),this._accumulatedTime<1/(g+1))return!1;this._accumulatedTime=0}if((e=this._stats)==null||e.begin(),ii.Current=this,this.onHandlePaused())return!1;for(ii.Current=this,this.time.update(),RtA&&console.log("FPS",this.time.smoothedFps.toFixed(0)),TD(this),HD(this.scene),sL(this),IB(this,-1);this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);const g=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(g)}if(this.pre_update_oneshot_callbacks){for(const g in this.pre_update_oneshot_callbacks)this.pre_update_oneshot_callbacks[g]();this.pre_update_oneshot_callbacks.length=0}if(this.pre_update_callbacks)for(const g in this.pre_update_callbacks)this.pre_update_callbacks[g]();this._currentFrameEvent=0;for(let g=0;g<this.scripts_earlyUpdate.length;g++){const I=this.scripts_earlyUpdate[g];I.activeAndEnabled&&I.earlyUpdate!==void 0&&(ii.Current=this,I.earlyUpdate())}if(this.executeCoroutines(0),IB(this,0),this.onHandlePaused())return!1;this._currentFrameEvent=1;for(let g=0;g<this.scripts_update.length;g++){const I=this.scripts_update[g];I.activeAndEnabled&&I.update!==void 0&&(ii.Current=this,I.update())}if(this.executeCoroutines(1),IB(this,1),this.onHandlePaused())return!1;this._currentFrameEvent=2;for(let g=0;g<this.scripts_lateUpdate.length;g++){const I=this.scripts_lateUpdate[g];I.activeAndEnabled&&I.lateUpdate!==void 0&&(ii.Current=this,I.lateUpdate())}if(this.executeCoroutines(2),IB(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 g=0;g<this.scripts_onBeforeRender.length;g++){const I=this.scripts_onBeforeRender[g];I.activeAndEnabled&&I.onBeforeRender!==void 0&&(ii.Current=this,I.onBeforeRender(A))}if(this.executeCoroutines(3),IB(this,3),this._sizeChanged&&this.updateSize(),this.pre_render_callbacks)for(const g in this.pre_render_callbacks)this.pre_render_callbacks[g](A)}return!0}internalUpdatePhysics(t){if(!this.physics.engine)return!1;const A=t,e=this.time.deltaTime/A;for(let i=0;i<A;i++)this._currentFrameEvent=9,this.executeCoroutines(9),this.physics.engine.step(e),this._currentFrameEvent=10,this.executeCoroutines(10);return this.physics.engine.postStep(),!0}internalOnRender(){this.isManagedExternally||(Oz(this),this._currentFrameEvent=-1,this.renderNow(),this._currentFrameEvent=4)}internalOnAfterRender(){if(this.isVisibleToUser||this.runInBackground){for(let t=0;t<this.scripts_onAfterRender.length;t++){const A=this.scripts_onAfterRender[t];A.activeAndEnabled&&A.onAfterRender!==void 0&&(ii.Current=this,A.onAfterRender())}if(this.executeCoroutines(4),IB(this,4),this.post_render_callbacks)for(const t in this.post_render_callbacks)this.post_render_callbacks[t]()}this._currentFrameEvent=-1,this.connection.sendBufferedMessagesNow(),this._stats&&(this._stats.end(),this.time.frameCount%150===0&&console.log(this.renderer.info.render.calls+" DrawCalls",`
4995
+ Render:`,{...this.renderer.info.render},`
4996
+ Memory:`,{...this.renderer.info.memory})),this._dispatchReadyAfterFrame&&(this._dispatchReadyAfterFrame=!1,this.domElement.dispatchEvent(new CustomEvent("ready")),mt.dispatchCallback(Yi.ContextFirstFrameRendered,this))}renderNow(t){return!t&&(t=this.mainCamera,!t)?!1:(this._isRendering=!0,this.renderRequiredTextures(),this.composer&&!this.isInXR?this.composer.render(this.time.deltaTime):t&&this.renderer.render(this.scene,t),this._isRendering=!1,!0)}onHandlePaused(){const t=this.evaluatePaused();if(this._wasPaused!==t){MtA&&console.log("Paused?",t,"context:"+this.alias);for(let A=0;A<this.scripts_pausedChanged.length;A++){const e=this.scripts_pausedChanged[A];e.activeAndEnabled&&e.onPausedChanged!==void 0&&(ii.Current=this,e.onPausedChanged(t,this._wasPaused))}}return this._wasPaused=t,t}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 tt(this.domWidth,this.domHeight),this._requireDepthTexture){const e=new TQ(this.domWidth,this.domHeight);this._renderTarget.depthTexture=e}this._requireColorTexture&&(this._renderTarget.texture=new Ye,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=He,this._renderTarget.texture.magFilter=He,this._renderTarget.texture.format=yt)}const t=this._renderTarget;t.texture&&(t.texture.colorSpace=this.renderer.outputColorSpace);const A=this.renderer.getRenderTarget();this.renderer.setRenderTarget(t),this.renderer.render(this.scene,this.mainCamera),this.renderer.setRenderTarget(A)}executeCoroutines(t){var A;if(this.coroutines[t]){const i=this.coroutines[t];for(let g=0;g<i.length;g++)try{const I=i[g];if(!I.comp||I.comp.destroyed||!I.main||I.comp.enabled===!1){UtA&&console.log("Removing coroutine",I.comp,I.comp.enabled),i.splice(g,1),--g;continue}const o=I.chained;if(o&&o.length>0){const a=o[o.length-1].next();if(a.done&&o.pop(),e(a)&&(I.chained||(I.chained=[]),I.chained.push(a.value)),!a.done)continue}const s=I.main.next();if(s.done===!0){i.splice(g,1),--g;continue}const C=s.value;if(e(C)){if(C.next().done)continue;I.chained||(I.chained=[]),I.chained.push(C)}else if(C instanceof Promise){const a=C;I.chained||(I.chained=[]);const n=ZL(a);(A=I.chained)==null||A.push(n);continue}}catch(I){console.error(I)}}function e(i){return!!(i&&i.next&&i.return)}}};let ve=ii;r(ve,"_defaultTargetFramerate",{value:60}),r(ve,"_defaultWebglRendererParameters",{antialias:!0,alpha:!1}),mt.registerCallback(Yi.ContextCreated,t=>{const A=t.context;XH(A),ZH(A)});const Py=iA("debugcomponents"),PH="eff8ba80-635d-11ec-90d6-0242ac120003";class Dg{constructor(A){r(this,"_originalSeed"),r(this,"_seed"),typeof A=="string"&&(A=Dg.hash(A)),this._originalSeed=A,this._seed=A}get seed(){return this._seed}set seed(A){this._seed=A}reset(){this._seed=this._originalSeed}generateUUID(A){if(typeof A=="string")return rL(A,PH);const e=this._seed;return this._seed-=1,rL(e.toString(),PH)}initialize(A){typeof A=="string"?this._seed=Dg.hash(A):this._seed=A}static createFromString(A){return new Dg(this.hash(A))}static hash(A){let e=0;for(let i=0;i<A.length;i++)e=A.charCodeAt(i)+((e<<5)-e);return e}}var jH=(t=>(t.NewInstanceCreated="new-instance-created",t.InstanceDestroyed="instance-destroyed",t))(jH||{});class WH{constructor(A){r(this,"guid"),this.guid=A}}function jy(t,A,e=!0){if(!t)return;const i=t;if(Ms(t,e),!A){console.warn("Can not send destroy: No networking connection provided",t.guid);return}if(!A.isConnected){console.warn("Can not send destroy: not connected",t.guid);return}let g=t.guid;if(!g&&i.uuid&&(g=i.uuid),!g){console.warn("Can not send destroy: failed to find guid",t);return}const I=new WH(g);A.send("instance-destroyed",I,ps.Queued)}function VH(t,A){const e=new WH(t);A.send("instance-destroyed",e,ps.Queued)}function ZH(t){t.connection.beginListen("instance-destroyed",A=>{Py&&console.log("[Remote] Destroyed",t.scene,A);const e=vl(A.guid,t.scene);e&&Ms(e)})}class KtA{constructor(A,e,i){r(this,"filename"),r(this,"hash"),r(this,"size"),this.filename=A,this.hash=e,this.size=i}}class zH{constructor(A,e){r(this,"guid"),r(this,"originalGuid"),r(this,"seed"),r(this,"visible"),r(this,"hostData"),r(this,"dontSave"),r(this,"parent"),r(this,"position"),r(this,"rotation"),r(this,"scale"),r(this,"preventCreation"),this.originalGuid=A,this.guid=e}}function GR(t,A,e,i){var g;const I=t;if(!I.guid)return console.warn("Can not instantiate: No guid",I),null;if(A.context||(A.context=ve.Current),!A.context)return console.error("Missing network instantiate options / reference to network connection in sync instantiate"),null;const o=A?{...A}:null,{instance:s,seed:C}=JtA(I,A);if(s){const a=s;if(a.guid){Py&&console.log("[Local] new instance","gameobject:",s?.guid);const n=new zH(I.guid,a.guid);n.seed=C,o&&(o.position&&(n.position={x:o.position.x,y:o.position.y,z:o.position.z}),o.rotation&&(n.rotation={x:o.rotation.x,y:o.rotation.y,z:o.rotation.z,w:o.rotation.w}),o.scale&&(n.scale={x:o.scale.x,y:o.scale.y,z:o.scale.z})),n.position||(n.position={x:a.position.x,y:a.position.y,z:a.position.z}),n.rotation||(n.rotation={x:a.quaternion.x,y:a.quaternion.y,z:a.quaternion.z,w:a.quaternion.w}),n.scale||(n.scale={x:a.scale.x,y:a.scale.y,z:a.scale.z}),n.visible=I.visible,o!=null&&o.parent&&(typeof o.parent=="string"?n.parent=o.parent:n.parent=o.parent.guid),n.hostData=e,i===!1&&(n.dontSave=!0),(g=A?.context)==null||g.connection.send("new-instance-created",n)}else console.warn("Missing guid, can not send new instance event",a)}return s}function Wy(){return Math.random()*9999999}function XH(t){t.connection.beginListen("new-instance-created",async A=>{const e=await vtA(A.originalGuid,t.scene);if(A.preventCreation===!0)return;if(!e){console.warn("could not find object that was instantiated: "+A.guid);return}const i=new xs;A.position&&(i.position=new w(A.position.x,A.position.y,A.position.z)),A.rotation&&(i.rotation=new FA(A.rotation.x,A.rotation.y,A.rotation.z,A.rotation.w)),A.scale&&(i.scale=new w(A.scale.x,A.scale.y,A.scale.z)),i.parent=A.parent,A.seed&&(i.idProvider=new Dg(A.seed)),i.visible=A.visible,i.context=t,Py&&t.alias&&console.log("[Remote] instantiate in: "+t.alias);const g=SE(e,i);g&&(A.parent==="scene"&&t.scene.add(g),Py&&console.log("[Remote] new instance","gameobject:",g?.guid,e))})}function JtA(t,A){const e=Wy(),i=A??new xs;i.idProvider=new Dg(e);const g=SE(t,i);return{seed:e,instance:g}}const $H={};function A2(t,A){$H[t]=A}async function vtA(t,A){const e=$H[t];if(e!=null){const i=await e(t);if(i)return i}return e2(t,A)}function e2(t,A){if(A===null||!t)return null;if(A.guid===t)return A;if(A.children)for(const e of A.children){const i=e2(t,e);if(i)return i}return null}const Vy=iA("debuggetcomponent"),Zy=iA("debuginstantiate");var t2=(t=>(t[t.None=0]="None",t[t.HideInHierarchy=1]="HideInHierarchy",t[t.HideInInspector=2]="HideInInspector",t[t.DontSaveInEditor=4]="DontSaveInEditor",t[t.NotEditable=8]="NotEditable",t[t.DontSaveInBuild=16]="DontSaveInBuild",t[t.DontUnloadUnusedAsset=32]="DontUnloadUnusedAsset",t[t.DontSave=52]="DontSave",t[t.HideAndDontSave=61]="HideAndDontSave",t))(t2||{});class xs{constructor(){r(this,"idProvider"),r(this,"parent"),r(this,"keepWorldPosition"),r(this,"position"),r(this,"rotation"),r(this,"scale"),r(this,"visible"),r(this,"context")}clone(){var A,e,i;const g=new xs;return g.idProvider=this.idProvider,g.parent=this.parent,g.keepWorldPosition=this.keepWorldPosition,g.position=(A=this.position)==null?void 0:A.clone(),g.rotation=(e=this.rotation)==null?void 0:e.clone(),g.scale=(i=this.scale)==null?void 0:i.clone(),g}cloneAssign(A){var e,i,g;this.idProvider=A.idProvider,this.parent=A.parent,this.keepWorldPosition=A.keepWorldPosition,this.position=(e=A.position)==null?void 0:e.clone(),this.rotation=(i=A.rotation)==null?void 0:i.clone(),this.scale=(g=A.scale)==null?void 0:g.clone()}}function wE(t){return t.visible}function Jl(t,A){return typeof A=="number"&&(A=A>.5),t.visible=A,t.visible}function i2(t){return t[Ia]||zy(t)}function g2(t,A){t[IL]=A}function zy(t){return Ts.isUsingInstancing(t)}function vl(t,A){return eE(t,A,!0,!0)}const I2=Symbol("isDestroyed");function cB(t){return t[I2]}function o2(t,A){t[I2]=A}const MR=Symbol("isDontDestroy");function RR(t,A=!0){t[MR]=A}const Xy=[],$y=[];function Ms(t,A=!0,e=!1){Xy.length=0,$y.length=0,UR(t,A,e,!0);for(const i of Xy)i.gameObject=null,i.context=null;for(const i of $y)o2(i,!0),e&&Yt(i),tL(i);$y.length=0,Xy.length=0}function UR(t,A=!0,e=!1,i=!0){if(t==null)return;const g=t;if(g.isComponent){if(g[MR])return;Xy.push(g);const s=g.gameObject;g.__internalDisable(),g.__internalDestroy(),g.gameObject=s;return}if(t[MR])return;const I=t;Vy&&console.log(I),$y.push(I);const o=I.userData.components;if(o){let s=o.length;for(let C=0;C<o.length;C++){const a=o[C];UR(a,A,e,!1),o.length<s&&(s=o.length,C--)}}if(A&&I.children)for(const s of I.children)UR(s,A,e,!1);i&&I.removeFromParent()}function lB(t,A,e=!0){return s2(t,A,e)}function*NR(t,A,e=!1,i=999,g=0){if(t!=null&&t.userData.components&&!(g>i)){for(const I of t.userData.components)A&&I?.isComponent===!0&&I instanceof A?yield I:yield I;if(e===!0)for(const I of t.children)yield*NR(I,A,!0,i,g+1)}}function s2(t,A,e,i=0){var g;if(t){if(t.isObject3D,i>1e3){console.warn("Failed to iterate components: too many levels");return}if((g=t.userData)!=null&&g.components)for(let I=0;I<t.userData.components.length;I++){const o=t.userData.components[I];if(o?.isComponent===!0){const s=A(o);if(s!==void 0)return s}}if(e&&t.children){const I=i+1;for(let o=0;o<t.children.length;o++){const s=t.children[o];if(!s)continue;const C=s2(s,A,e,I);if(C!==void 0)return C}}}}function SE(t,A=null){let e=null;A!==null&&(A.x!==void 0?(e=new xs,e.position=A):e=A);let i=ve.Current;e!=null&&e.context&&(i=e.context),Vy&&i.alias&&console.log("context",i.alias),e&&!e.idProvider&&(e.idProvider=new Dg(Date.now()));const g=[],I={},o={},s=C2(i,t,e,g,I,o);s&&(qtA(I),btA(o,I)),Vy&&(Yy(t,!0),Yy(s,!0));const C={};for(const a in g){const n=g[a],B=n.guid;e&&e.idProvider&&(n.guid=e.idProvider.generateUUID(),C[B]=n.guid,Vy&&console.log(n.name,n.guid)),Oy(n,i),n.__internalNewInstanceCreated&&n.__internalNewInstanceCreated()}for(const a in g){const n=g[a];n.resolveGuids&&n.resolveGuids(C),n.enabled!==!1&&(n.enabled=!0)}return TD(i),s}function C2(t,A,e,i,g,I){var o;if(!A)return null;const s=A.userData;A.userData={};const C=A.children;A.children=[];const a=A.clone(!1);if(Aw(a),A.userData=s,A.children=C,g[A.uuid]={original:A,clone:a},Zy&&console.log("ADD",A,a),A.type==="SkinnedMesh"&&(I[A.uuid]={original:A,clone:a}),e?.visible!==void 0&&(a.visible=e.visible),e!=null&&e.idProvider){a.uuid=e.idProvider.generateUUID();const B=a;B&&(B.guid=a.uuid)}A.animations&&A.animations.length>0&&(a.animations=[...A.animations]);const n=A.parent;if(n&&n.add(a),e!=null&&e.position?CI(a,e.position):a.position.copy(A.position),e!=null&&e.rotation?_o(a,e.rotation):a.quaternion.copy(A.quaternion),e!=null&&e.scale?a.scale.copy(e.scale):a.scale.copy(A.scale),e!=null&&e.parent&&e.parent!=="scene"){let B=null;if(typeof e.parent=="string"?B=eE(e.parent,t.scene,!0):B=e.parent,B){const Q=e.keepWorldPosition===!0?B.attach:B.add;Q?Q.call(B,a):console.error("Invalid parent object",B,"received when instantiating:",A)}else console.warn("could not find parent:",e.parent)}for(const[B,Q]of Object.entries(A.userData))B!=="components"&&(a.userData[B]=Q);if((o=A.userData)!=null&&o.components){const B=A.userData.components,Q=[];a.userData.components=Q;for(let E=0;E<B.length;E++){const h=B[E],d=new h.constructor;BE(d,h),h[Zc]!==void 0&&(d[Zc]=h[Zc]),Q.push(d),d.gameObject=a,i.push(d),Vc.dispatchComponentLifecycleEvent(Wc.Added,d)}}e&&(e.position=void 0,e.rotation=void 0,e.scale=void 0,e.parent=void 0);for(const B in A.children){const Q=A.children[B],E=C2(t,Q,e,i,g,I);E&&a.add(E)}return a}function btA(t,A){for(const e in t){const i=t[e],g=i.original,I=g.skeleton,o=i.clone;if(!I){console.warn("Skinned mesh has no skeleton?",i);continue}const s=I.bones,C=o.skeleton.clone();o.skeleton=C,o.bindMatrix.clone().copy(g.bindMatrix),o.bindMatrixInverse.copy(g.bindMatrixInverse);const a=[];C.bones=a;for(let n=0;n<s.length;n++){const B=s[n],Q=A[B.uuid].clone;a.push(Q)}}for(const e in t){const i=t[e].clone;i.skeleton.update(),i.bind(i.skeleton,i.bindMatrix),i.updateMatrixWorld(!0)}}function qtA(t){var A;for(const e in t){const i=t[e].clone;if((A=i.userData)!=null&&A.components)for(let g=0;g<i.userData.components.length;g++){const I=i.userData.components[g],o=Object.entries(I);for(const[s,C]of o)if(Array.isArray(C)){const a=[];I[s]=a;for(let n=0;n<C.length;n++){const B=C[n];if(typeof B!="object"){a.push(B);continue}const Q=a2(I,s,B,t);Q!==void 0?a.push(Q):a.push(B)}}else if(typeof C=="object"){const a=a2(I,s,C,t);a!==void 0&&(I[s]=a)}}}}function a2(t,A,e,i){var g,I;if(e!=null)if(e.isComponent===!0){const o=e.gameObject;if(o){const s=o.uuid,C=(g=i[s])==null?void 0:g.clone;if(!C){Zy&&console.log("reference did not change",A,t,e);return}const a=o.userData.components.indexOf(e);if(a>=0)return Zy&&console.log(A,s),C.userData.components[a];console.warn("could not find component",A,e)}}else if(e.isObject3D===!0){if(A==="gameObject")return;const o=e;if(o){const s=o.uuid,C=(I=i[s])==null?void 0:I.clone;if(C)return Zy&&console.log(A,"old",e,"new",C),C}}else{if(e.isVector4||e.isVector3||e.isVector2||e.isQuaternion||e.isEuler||e.isColor===!0)return e.clone();if(e.isEventList===!0)return new e.constructor}}const n2=new Map;function LtA(t,A){if(!t)return;if(!A){console.warn("No prototype found",t,t.prototype,t.constructor);return}const e=n2.get(A);e&&e.apply(t)}function xtA(t){const A=YtA(t.prototype);n2.set(t,A)}function YtA(t){return new TtA(t)}class TtA{constructor(A){r(this,"$symbol"),r(this,"extensions"),r(this,"descriptors"),this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(A),this.descriptors=new Array;for(let e=0;e<this.extensions.length;e++){const i=this.extensions[e],g=Object.getOwnPropertyDescriptor(A,i);g&&this.descriptors.push(g)}}apply(A){if(!A[this.$symbol]){A[this.$symbol]=!0;for(let e=0;e<this.extensions.length;e++){const i=this.extensions[e],g=this.descriptors[e];g&&Object.defineProperty(A,i,g)}}}}function Aw(t){t&&t.isObject3D===!0&&LtA(t,wA)}wA.prototype.SetActive=function(t){this.visible=t},wA.prototype.setActive=function(t){this.visible=t},wA.prototype.destroy=function(){Ms(this)},wA.prototype.addComponent=function(t){return JR(this,t)},wA.prototype.addNewComponent=function(t){return Jn(this,new t)},wA.prototype.removeComponent=function(t){return KR(this,t)},wA.prototype.getOrAddComponent=function(t){return ew(this,t)},wA.prototype.getComponent=function(t){return fE(this,t)},wA.prototype.getComponents=function(t,A){return bl(this,t,A)},wA.prototype.getComponentInChildren=function(t){return ql(this,t)},wA.prototype.getComponentsInChildren=function(t,A){return Ll(this,t,A)},wA.prototype.getComponentInParent=function(t){return xl(this,t)},wA.prototype.getComponentsInParent=function(t,A){return tw(this,t,A)},Object.getOwnPropertyDescriptor(wA.prototype,"activeSelf")||Object.defineProperty(wA.prototype,"activeSelf",{get:function(){return wE(this)},set:function(t){Jl(this,t)}}),Object.getOwnPropertyDescriptor(wA.prototype,"transform")||Object.defineProperty(wA.prototype,"transform",{get:function(){return this}}),Object.getOwnPropertyDescriptor(wA.prototype,"worldPosition")||Object.defineProperty(wA.prototype,"worldPosition",{get:function(){return this instanceof gG?Ne(this.object):Ne(this)},set:function(t){CI(this,t)}}),Object.getOwnPropertyDescriptor(wA.prototype,"worldQuaternion")||Object.defineProperty(wA.prototype,"worldQuaternion",{get:function(){return this instanceof gG?Kt(this.object):Kt(this)},set:function(t){_o(this,t)}}),Object.getOwnPropertyDescriptor(wA.prototype,"worldRotation")||Object.defineProperty(wA.prototype,"worldRotation",{get:function(){return Ml(this)},set:function(t){uR(this,t)}}),Object.getOwnPropertyDescriptor(wA.prototype,"worldScale")||Object.defineProperty(wA.prototype,"worldScale",{get:function(){return ai(this)},set:function(t){Gl(this,t)}}),Object.getOwnPropertyDescriptor(wA.prototype,"worldForward")||Object.defineProperty(wA.prototype,"worldForward",{get:function(){return _i().set(0,0,1).applyQuaternion(Kt(this))}}),Object.getOwnPropertyDescriptor(wA.prototype,"worldRight")||Object.defineProperty(wA.prototype,"worldRight",{get:function(){return _i().set(1,0,0).applyQuaternion(Kt(this))}}),Object.getOwnPropertyDescriptor(wA.prototype,"worldUp")||Object.defineProperty(wA.prototype,"worldUp",{get:function(){return _i().set(0,1,0).applyQuaternion(Kt(this))}}),xtA(wA);const FR=iA("debuggetcomponent");function HtA(t){return t==null||t.isObject3D?t:t.object&&t.object.isObject3D?t.object:t}function KR(t,A){if(!t||!t.userData.components)return;const e=t.userData.components.indexOf(A);e<0||(Vc.dispatchComponentLifecycleEvent(Wc.Removing,A),A.gameObject=null,t.userData.components.splice(e,1))}function ew(t,A){const e=fE(t,A);if(e)return e;const i=new A;return Jn(t,i)}const r2=new Dg("addComponentIdProvider");function Jn(t,A,e=!0){t.userData||(t.userData={}),t.userData.components||(t.userData.components=[]),t.userData.components.push(A),A.gameObject=t,(A.guid===void 0||A.guid==="invalid")&&(A.guid=r2.generateUUID()),Aw(t),Oy(A);try{e&&A.__internalAwake&&(Xc(t),A.activeAndEnabled&&A.__internalAwake()),Vc.dispatchComponentLifecycleEvent(Wc.Added,A)}catch(i){console.error(i)}return A}function JR(t,A){if(typeof A=="function")return Jn(t,new A);if(A.destroyed)return console.warn("Can not move/add a destroyed component",A),A;if(A.gameObject===t)return A;if(A.gameObject&&A.gameObject.userData.components){const e=A.gameObject.userData.components.indexOf(A);A.gameObject.userData.components.splice(e,1)}if(!t.userData.components)t.userData.components=[];else if(t.userData.components.includes(A))return A;return t.userData.components.push(A),A.gameObject=t,(A.guid===void 0||A.guid==="invalid")&&(A.guid=r2.generateUUID()),Oy(A),A}function B2(t){if(t.gameObject&&t.gameObject.userData.components){const A=t.gameObject.userData.components.indexOf(t);t.gameObject.userData.components.splice(A,1)}t.__internalDisable&&t.__internalDisable(),oa(t,t.context??ve.Current),t.destroy(),t.gameObject=null}let Q2=!1;function E2(t,A,e){var i;if(t==null)return null;if(!t.isObject3D)return console.error("Object is not object3D"),null;if(!((i=t?.userData)!=null&&i.components)||(typeof A=="string"&&(Q2||(Q2=!0,console.warn(`Accessing components by name is not supported.
4995
4997
  Please use the component type instead. This may keep working in local development but it will fail when bundling your application.
4996
4998
 
4997
4999
  You can import other modules your main module to get access to types
@@ -5405,9 +5407,9 @@ ${o.join(`
5405
5407
 
5406
5408
  }
5407
5409
  `}function f_(t){return`(${t.r}, ${t.g}, ${t.b})`}function m_(t){return`(${t.x}, ${t.y})`}const k_=[1023,33777,33778,33779,35842,35843,37496,37808,37809,37810,37811,37812,37813,37814,37815,37816,37817,37818,37819,37820,37821,36492];iA("debugusdz");const G_=class{constructor(t,A,e){r(this,"id"),r(this,"trigger"),r(this,"action"),r(this,"exclusive",!1),this.id="Behavior_"+rw(t)+"_"+G_.global_id++,this.trigger=A,this.action=e}makeExclusive(t){return this.exclusive=t,this}writeTo(t,A,e){if(!this.trigger||!this.action)return;e.beginBlock(`def Preliminary_Behavior "${this.id}"`),e.appendLine(`rel actions = <${this.action.id}>`),e.appendLine(`uniform bool exclusive = ${this.exclusive}`);let i="";if(Array.isArray(this.trigger)){i="[";for(let g=0;g<this.trigger.length;g++){const I=this.trigger[g];i+="<"+I.id+">",g+1<this.trigger.length&&(i+=", ")}i+="]"}else i=`<${this.trigger.id}>`;if(e.appendLine(`rel triggers = ${i} `),e.appendLine(),Array.isArray(this.trigger))for(const g of this.trigger)g.writeTo(A,e),e.appendLine();else this.trigger.writeTo(A,e);e.appendLine(),this.action.writeTo(A,e),e.closeBlock()}};let Fg=G_;r(Fg,"global_id",0);function pU(t,A){var e,i;let g="";if(Array.isArray(t)){let I="[ ";for(let o=0;o<t.length;o++){let s=t[o];if(typeof s=="string")I+=s;else if(typeof s=="object"){s.isObject3D&&(s=A.findById(s.uuid));const C=(e=s.getPath)==null?void 0:e.call(s);I+=C}o+1<t.length&&(I+=", ")}I+=" ]",g=I}else typeof t=="object"&&(t.isObject3D&&(t=A.findById(t.uuid)),g=(i=t.getPath)==null?void 0:i.call(t));return g}const M_=class{constructor(t,A){r(this,"id"),r(this,"targetId"),r(this,"tokenId"),r(this,"type"),r(this,"distance"),t&&(this.targetId=t),A?this.id=A:this.id="Trigger_"+M_.global_id++}writeTo(t,A){A.beginBlock(`def Preliminary_Trigger "${this.id}"`),this.targetId&&(typeof this.targetId!="string"&&(this.targetId=pU(this.targetId,t)),A.appendLine("rel affectedObjects = "+this.targetId)),this.tokenId&&A.appendLine(`token info:id = "${this.tokenId}"`),this.type&&A.appendLine(`token type = "${this.type}"`),typeof this.distance=="number"&&A.appendLine(`double distance = ${this.distance}`),A.closeBlock()}};let wB=M_;r(wB,"global_id",0);class Kg{static sceneStartTrigger(){const A=new wB;return A.targetId=void 0,A.tokenId="SceneTransition",A.type="enter",A}static tapTrigger(A){const e=new wB(A);return e.tokenId="TapGesture",e}static isTapTrigger(A){return A?.tokenId==="TapGesture"}static proximityToCameraTrigger(A,e){const i=new wB(A);return i.tokenId="ProximityToCamera",i.distance=e,i}}class xn{constructor(A,e){r(this,"id"),r(this,"actions"),r(this,"loops",0),r(this,"performCount",1),r(this,"type","serial"),this.id=A,this.actions=e}static getId(){return this.global_id++}addAction(A){return this.actions.push(A),this}makeParallel(){return this.type="parallel",this}makeSequence(){return this.type="serial",this}makeLooping(){return this.loops=1,this}makeRepeat(A){return this.performCount=A,this}writeTo(A,e){e.beginBlock(`def Preliminary_Action "${this.id}"`),e.beginArray("rel actions");for(const i of this.actions){if(!i)continue;const g=i===this.actions[this.actions.length-1];e.appendLine("<"+i.id+">"+(g?"":", "))}e.closeArray(),e.appendLine(),e.appendLine('token info:id = "Group"'),e.appendLine(`bool loops = ${this.loops} `),e.appendLine(`int performCount = ${this.performCount} `),e.appendLine(`token type = "${this.type}"`),e.appendLine();for(const i of this.actions)i&&(i.writeTo(A,e),e.appendLine());e.closeBlock()}}r(xn,"global_id",0);var DU=(t=>(t[t.pop=0]="pop",t[t.blink=1]="blink",t[t.bounce=2]="bounce",t[t.flip=3]="flip",t[t.float=4]="float",t[t.jiggle=5]="jiggle",t[t.pulse=6]="pulse",t[t.spin=7]="spin",t))(DU||{}),yU=(t=>(t.Relative="relative",t.Absolute="absolute",t))(yU||{}),R_=(t=>(t.Allow="allow",t.Ignore="ignore",t.Stop="stop",t))(R_||{});const wU=class{constructor(t,A){r(this,"id"),r(this,"tokenId"),r(this,"affectedObjects"),r(this,"easeType"),r(this,"motionType"),r(this,"duration"),r(this,"moveDistance"),r(this,"style"),r(this,"type"),r(this,"front"),r(this,"up"),r(this,"start"),r(this,"animationSpeed"),r(this,"reversed"),r(this,"pingPong"),r(this,"xFormTarget"),r(this,"audio"),r(this,"gain"),r(this,"auralMode"),r(this,"multiplePerformOperation"),t&&(this.affectedObjects=t),A?this.id=A:this.id="Action",this.id+="_"+wU.global_id++}clone(){const t=new wU,A=t.id;return Object.assign(t,this),t.id=A,t}writeTo(t,A){A.beginBlock(`def Preliminary_Action "${this.id}"`),this.affectedObjects&&(typeof this.affectedObjects!="string"&&(this.affectedObjects=pU(this.affectedObjects,t)),A.appendLine("rel affectedObjects = "+this.affectedObjects)),typeof this.duration=="number"&&A.appendLine(`double duration = ${this.duration} `),this.easeType&&A.appendLine(`token easeType = "${this.easeType}"`),this.tokenId&&A.appendLine(`token info:id = "${this.tokenId}"`),this.motionType&&A.appendLine(`token motionType = "${this.motionType}"`),typeof this.moveDistance=="number"&&A.appendLine(`double moveDistance = ${this.moveDistance} `),this.style&&A.appendLine(`token style = "${this.style}"`),this.type&&A.appendLine(`token type = "${this.type}"`),this.front&&A.appendLine(`vector3d front = (${this.front.x}, ${this.front.y}, ${this.front.z})`),this.up&&A.appendLine(`vector3d upVector = (${this.up.x}, ${this.up.y}, ${this.up.z})`),typeof this.start=="number"&&A.appendLine(`double start = ${this.start} `),typeof this.animationSpeed=="number"&&A.appendLine(`double animationSpeed = ${this.animationSpeed} `),typeof this.reversed=="boolean"&&A.appendLine(`bool reversed = ${this.reversed}`),typeof this.pingPong=="boolean"&&A.appendLine(`bool reverses = ${this.pingPong}`),this.xFormTarget&&(typeof this.xFormTarget!="string"&&(this.xFormTarget=pU(this.xFormTarget,t)),A.appendLine(`rel xformTarget = ${this.xFormTarget}`)),typeof this.audio=="string"&&A.appendLine(`asset audio = @${this.audio}@`),typeof this.gain=="number"&&A.appendLine(`double gain = ${this.gain}`),typeof this.auralMode=="string"&&A.appendLine(`token auralMode = "${this.auralMode}"`),typeof this.multiplePerformOperation=="string"&&A.appendLine(`token multiplePerformOperation = "${this.multiplePerformOperation}"`),A.closeBlock()}};let Fs=wU;r(Fs,"global_id",0);let YE=class Kh{constructor(A,e,i){r(this,"x",0),r(this,"y",0),r(this,"z",0),this.x=A,this.y=e,this.z=i}static get up(){return new Kh(0,1,0)}static get right(){return new Kh(1,0,0)}static get forward(){return new Kh(0,0,1)}static get back(){return new Kh(0,0,-1)}static get zero(){return new Kh(0,0,0)}};var SU=(t=>(t.Play="play",t.Pause="pause",t.Stop="stop",t))(SU||{}),fU=(t=>(t.Spatial="spatial",t.NonSpatial="nonSpatial",t.Ambient="ambient",t))(fU||{});class Et{static sequence(...A){return new xn("group_"+xn.getId(),A).makeSequence()}static parallel(...A){return new xn("group_"+xn.getId(),A).makeParallel()}static fadeAction(A,e,i){const g=new Fs(A);return g.tokenId="Visibility",g.type=i?"show":"hide",g.duration=e,g.style="basic",g.motionType="none",g.moveDistance=0,g.easeType="none",g}static startAnimationAction(A,e,i=0,g=1,I=!1,o=!1){const s=new Fs(A);if(s.tokenId="StartAnimation",s.start=e,s.duration=i,s.animationSpeed=g,s.reversed=I,s.pingPong=o,s.multiplePerformOperation="allow",I&&(s.start-=i),o){s.pingPong=!1;const C=s.clone();return C.reversed=!I,C.start=s.start,C.reversed&&(C.start-=i),Et.sequence(s,C)}return s}static waitAction(A){const e=new Fs;return e.tokenId="Wait",e.duration=A,e}static lookAtCameraAction(A,e=9999999999999,i,g){const I=new Fs(A);return I.tokenId="LookAtCamera",I.duration=e,I.front=i??YE.forward,I.up=g??YE.up,I}static emphasize(A,e,i=2,g=1,I="basic"){const o=new Fs(A);return o.tokenId="Emphasize",o.duration=e,o.style=I??"basic",o.motionType=DU[i],o.moveDistance=g,o}static transformAction(A,e,i,g,I="inout"){const o=new Fs(A);return o.tokenId="Transform",o.duration=i,o.type=g,o.easeType=I,Array.isArray(e)&&console.error("Transform target must not be an array",e),o.xFormTarget=e,o}static playAudioAction(A,e,i="play",g=1,I="spatial"){const o=new Fs(A);return o.tokenId="Audio",o.type=i,o.audio=e,o.gain=g,o.auralMode=I,o.multiplePerformOperation="allow",o}}class LgA{constructor(A){r(this,"object"),r(this,"model"),this.object=A}get id(){return this.object.uuid}apply(A){if(!this.model&&(this.model=A.findById(this.object.uuid),!this.model)){console.error("could not find model with id "+this.object.uuid);return}this.onApply(A)}}class mU extends LgA{constructor(A,e,i,g){super(A),r(this,"matrix"),r(this,"material"),r(this,"geometry"),r(this,"_enableAction"),r(this,"_disableAction"),this.matrix=e,this.material=i,this.geometry=g}onApply(A){var e,i;const g=this.model;if(!g)return;(e=g.parent)!=null&&e.isDynamic||Wo.createEmptyParent(g);const I=g.clone();this.matrix&&(I.matrix=this.matrix),this.material&&(I.material=this.material),this.geometry&&(I.geometry=this.geometry),(i=g.parent)==null||i.add(I)}enable(){return this._enableAction?this._enableAction:(this._enableAction=Et.fadeAction(this.object,0,!0),this._enableAction)}disable(){return this._disableAction?this._disableAction:(this._disableAction=Et.fadeAction(this.object,0,!1),this._disableAction)}}class kU{constructor(A){r(this,"actions"),r(this,"sortedActions"),this.actions=[...A]}organize(){this.sortedActions={};for(const A of this.actions){const e=A.id;this.sortedActions[e]||(this.sortedActions[e]=[]),this.sortedActions[e].push(A)}}getActions(A){return this.sortedActions||this.organize(),this.sortedActions[A.uuid]}}var xgA=Object.defineProperty,YgA=Object.getOwnPropertyDescriptor,U_=(t,A,e,i)=>{for(var g=i>1?void 0:i?YgA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&xgA(A,e,g),g};class Xl extends JA{constructor(){super(...arguments),r(this,"from"),r(this,"to"),r(this,"width",0),r(this,"centered",!0),r(this,"_centerPos")}awake(){this._centerPos=new w}update(){if(!this.from||!this.to)return;const A=Ne(this.from).clone(),e=Ne(this.to).clone(),i=A.distanceTo(e);this._centerPos.copy(A),this._centerPos.add(e),this._centerPos.multiplyScalar(.5),CI(this.gameObject,this.centered?this._centerPos:A),this.gameObject.lookAt(Ne(this.to).clone()),this.gameObject.scale.set(this.width,this.width,i)}}U_([y(aA)],Xl.prototype,"from",2),U_([y(aA)],Xl.prototype,"to",2);var TgA=Object.defineProperty,HgA=Object.getOwnPropertyDescriptor,$l=(t,A,e,i)=>{for(var g=i>1?void 0:i?HgA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&TgA(A,e,g),g};const TE=iA("debuganimation");class no extends JA{constructor(){super(...arguments),r(this,"playAutomatically",!0),r(this,"randomStartTime",!0),r(this,"minMaxSpeed"),r(this,"minMaxOffsetNormalized"),r(this,"loop",!0),r(this,"clampWhenFinished",!1),r(this,"_tempAnimationClipBeforeGameObjectExisted",null),r(this,"_tempAnimationsArray"),r(this,"mixer"),r(this,"_actions",[]),r(this,"_currentActions",[]),r(this,"_handles",[]),r(this,"_didInit",!1)}get clip(){var A;return(A=this.animations)!=null&&A.length?this.animations[0]:null}set clip(A){if(!this.__didAwake){TE&&console.warn("Assign clip during serialization",A),this._tempAnimationClipBeforeGameObjectExisted=A;return}A&&(this.gameObject.animations||(this.gameObject.animations=[]),!this.animations.includes(A)&&(this.animations.length>0?this.animations.splice(0,0,A):this.animations.push(A)))}set clips(A){this.animations=A}set animations(A){A==null||!Array.isArray(A)||(this.gameObject?this.gameObject.animations=A:this._tempAnimationsArray=A)}get animations(){return this.gameObject.animations||this._tempAnimationsArray||[]}get currentAction(){return this._currentActions[0]}get currentActions(){return this._currentActions}get actions(){return this._actions}set actions(A){this._actions=A}awake(){TE&&console.log("Animation Awake",this.name,this),this._tempAnimationsArray&&(this.animations=this._tempAnimationsArray,this._tempAnimationsArray=void 0),this._tempAnimationClipBeforeGameObjectExisted&&(this.clip=this._tempAnimationClipBeforeGameObjectExisted,this._tempAnimationClipBeforeGameObjectExisted=null),this.playAutomatically&&this.init()}onEnable(){var A;if(this.playAutomatically&&((A=this.animations)==null?void 0:A.length)>0&&this.currentActions.length<=0){const e=Math.floor(Math.random()*this.actions.length);this.play(e)}}start(){this.randomStartTime&&this.currentAction&&(this.currentAction.time=Math.random()*this.currentAction.getClip().duration)}update(){this.mixer&&this.mixer.update(this.context.time.deltaTime)}getAction(A){var e;return(e=this.actions)==null?void 0:e.find(i=>i.getClip().name===A)}get isPlaying(){for(let A=0;A<this.actions.length;A++)if(this.actions[A].isRunning())return!0;return!1}play(A=0,e){if(TE&&console.log("PLAY",A),this.init(),!this.mixer){TE&&console.warn("Missing mixer",this);return}A===void 0&&(A=0);let i=A;if(typeof A=="number"){if(A>=this.animations.length){TE&&console.log("No animation at index",A);return}i=this.animations[A]}else typeof A=="string"&&(i=this.animations.find(I=>I.name===A));if(!i){console.error("Could not find clip",A);return}e||(e={}),e.minMaxOffsetNormalized||(e.minMaxOffsetNormalized=this.minMaxOffsetNormalized),e.minMaxSpeed||(e.minMaxSpeed=this.minMaxSpeed),e.loop===void 0&&(e.loop=this.loop),e.clampWhenFinished===void 0&&(e.clampWhenFinished=this.clampWhenFinished);for(const I of this.actions)if(I.getClip()===i)return this.internalOnPlay(I,e);if(!(i instanceof PI)){console.warn("Clip is no AnimationClip",i,"on object: "+this.name);return}const g=this.mixer.clipAction(i);return this.actions.push(g),this.internalOnPlay(g,e)}internalOnPlay(A,e){var i=this.currentAction;if(i===A&&i.isRunning()&&i.time<i.getClip().duration){const s=this.tryFindHandle(A);if(s)return s.getPromise()}const g=e?.exclusive??!0;e!=null&&e.fadeDuration?(g&&i?.fadeOut(e.fadeDuration),A.fadeIn(e.fadeDuration)):g&&i?.stop(),A.reset(),A.enabled=!0,A.time=0,A.timeScale=1;const I=A.getClip();e!=null&&e.minMaxOffsetNormalized&&(A.time=Ie.lerp(e.minMaxOffsetNormalized.x,e.minMaxOffsetNormalized.y,Math.random())*I.duration),e!=null&&e.minMaxSpeed&&(A.timeScale=Ie.lerp(e.minMaxSpeed.x,e.minMaxSpeed.y,Math.random())),e!=null&&e.clampWhenFinished&&(A.clampWhenFinished=!0),e?.startTime!==void 0&&(A.time=e.startTime),e?.loop!==void 0?A.loop=e.loop?om:ec:A.loop=ec,A.play(),TE&&console.log("PLAY",A.getClip().name,A);const o=new _gA(A,this.mixer,e,s=>{this._handles.splice(this._handles.indexOf(o),1)});return this._handles.push(o),o.getPromise()}tryFindHandle(A){for(const e of this._handles)if(e.action===A)return e}init(){this._didInit||(this._didInit=!0,this.gameObject&&(this.actions=[],this.mixer=new uD(this.gameObject)))}}$l([y()],no.prototype,"playAutomatically",2),$l([y()],no.prototype,"randomStartTime",2),$l([y()],no.prototype,"loop",2),$l([y()],no.prototype,"clampWhenFinished",2),$l([y(PI)],no.prototype,"clips",1);class _gA{constructor(A,e,i,g){r(this,"mixer"),r(this,"action"),r(this,"promise",null),r(this,"resolve",null),r(this,"reject",null),r(this,"_options"),r(this,"_resolveCallback",null),r(this,"_rejectCallback",null),r(this,"_loopCallback"),r(this,"_finishedCallback"),r(this,"_resolvedOrRejectedCallback"),this.action=A,this.mixer=e,this._resolvedOrRejectedCallback=g,this._options=i}getPromise(){return this.promise?this.promise:(this.promise=new Promise((A,e)=>{this._resolveCallback=A,this._rejectCallback=e,this.resolve=this.onResolve.bind(this),this.reject=this.onReject.bind(this)}),this._loopCallback=this.onLoop.bind(this),this._finishedCallback=this.onFinished.bind(this),this.mixer.addEventListener("loop",this._loopCallback),this.mixer.addEventListener("finished",this._finishedCallback),this.promise)}_update(){this._options&&this._options.endTime!==void 0&&this.action.time>this._options.endTime&&(this._options.loop===!0?this.action.time=this._options.startTime??0:(this.action.time=this._options.endTime,this.action.timeScale=0,this.onResolve()))}onResolve(){var A,e;this.dispose(),(A=this._resolvedOrRejectedCallback)==null||A.call(this,this),(e=this._resolveCallback)==null||e.call(this,this.action)}onReject(A){var e,i;this.dispose(),(e=this._resolvedOrRejectedCallback)==null||e.call(this,this),(i=this._rejectCallback)==null||i.call(this,A)}onLoop(A){}onFinished(A){A.action===this.action&&this.onResolve()}dispose(){this._loopCallback&&this.mixer.removeEventListener("loop",this._loopCallback),this._finishedCallback&&this.mixer.removeEventListener("finished",this._finishedCallback),this._loopCallback=void 0,this._finishedCallback=void 0}}var OgA=Object.defineProperty,PgA=Object.getOwnPropertyDescriptor,Yn=(t,A,e,i)=>{for(var g=i>1?void 0:i?PgA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&OgA(A,e,g),g};class fa{constructor(){r(this,"time"),r(this,"value"),r(this,"inTangent"),r(this,"inWeight"),r(this,"outTangent"),r(this,"outWeight"),r(this,"weightedMode")}}Yn([y()],fa.prototype,"time",2),Yn([y()],fa.prototype,"value",2),Yn([y()],fa.prototype,"inTangent",2),Yn([y()],fa.prototype,"inWeight",2),Yn([y()],fa.prototype,"outTangent",2),Yn([y()],fa.prototype,"outWeight",2),Yn([y()],fa.prototype,"weightedMode",2);const GU=class{constructor(){r(this,"keys")}clone(){var t;const A=new GU;return A.keys=((t=this.keys)==null?void 0:t.map(e=>{const i=new fa;return i.time=e.time,i.value=e.value,i.inTangent=e.inTangent,i.inWeight=e.inWeight,i.outTangent=e.outTangent,i.outWeight=e.outWeight,i.weightedMode=e.weightedMode,i}))||[],A}get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(t){if(!this.keys||this.keys.length==0)return 0;if(this.keys[0].time>=t)return this.keys[0].value;for(let A=0;A<this.keys.length;A++){const e=this.keys[A];if(e.time<=t)if(A+1<this.keys.length){const i=this.keys[A+1];if(i.time<t)continue;return!isFinite(e.outTangent)||!isFinite(i.inTangent)?e.value:GU.interpolateValue(t,e,i)}else return e.value}return this.keys[this.keys.length-1].value}static interpolateValue(t,A,e){const i=A.time,g=A.value,I=A.outTangent,o=e.time,s=e.value,C=e.inTangent,a=o-i,n=a*a,B=n*a,Q=((I+C)*a-2*(s-g))/B,E=(3*(s-g)-(C+2*I)*a)/n,h=I,d=g,u=t-i,c=u*u,l=c*u;return Q*l+E*c+h*u+d}};let SB=GU;Yn([y(fa)],SB.prototype,"keys",2);class jgA extends Ni{constructor(A,e=1,i=16,g=2){const I=new le,o=i+g*2,s=new Float32Array((o*3+3)*3);I.setAttribute("position",new Ae(s,3));const C=new Ui({color:65280}),a=new Ui({color:16776960});super(I,[a,C]),this.audio=A,this.range=e,this.divisionsInnerAngle=i,this.divisionsOuterAngle=g,this.type="PositionalAudioHelper",this.update()}update(){const A=this.audio,e=this.range,i=this.divisionsInnerAngle,g=this.divisionsOuterAngle,I=eg.degToRad(A.panner.coneInnerAngle),o=eg.degToRad(A.panner.coneOuterAngle),s=I/2,C=o/2;let a=0,n=0,B,Q;const E=this.geometry,h=E.attributes.position;E.clearGroups();function d(u,c,l,p){const D=(c-u)/l;for(h.setXYZ(a,0,0,0),n++,B=u;B<c;B+=D)Q=a+n,h.setXYZ(Q,Math.sin(B)*e,0,Math.cos(B)*e),h.setXYZ(Q+1,Math.sin(Math.min(B+D,c))*e,0,Math.cos(Math.min(B+D,c))*e),h.setXYZ(Q+2,0,0,0),n+=3;E.addGroup(a,n,p),a+=n,n=0}d(-C,-s,g,0),d(-s,s,i,1),d(s,C,g,0),h.needsUpdate=!0,I===o&&(this.material[0].visible=!1)}dispose(){this.geometry.dispose(),this.material[0].dispose(),this.material[1].dispose()}}var WgA=Object.defineProperty,VgA=Object.getOwnPropertyDescriptor,nC=(t,A,e,i)=>{for(var g=i>1?void 0:i?VgA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&WgA(A,e,g),g};const nI=iA("debugaudio");let lw=!1;const dw=[];function uw(){if(lw)return;Se()&&console.log("User interaction registered: audio can now be played"),lw=!0;const t=[...dw];dw.length=0,t.forEach(A=>A())}document.addEventListener("pointerdown",uw),document.addEventListener("click",uw),document.addEventListener("dragstart",uw),document.addEventListener("touchstart",uw);const Tn=class extends JA{constructor(){super(...arguments),r(this,"clip",""),r(this,"playOnAwake",!1),r(this,"preload",!1),r(this,"_spatialBlend",0),r(this,"_minDistance",1),r(this,"_maxDistance",100),r(this,"_volume",1),r(this,"rollOffMode",0),r(this,"playInBackground",!0),r(this,"_loop",!1),r(this,"sound",null),r(this,"helper",null),r(this,"wasPlaying",!1),r(this,"audioLoader",null),r(this,"shouldPlay",!1),r(this,"_lastClipStartedLoading",null),r(this,"_audioElement",null),r(this,"onVisibilityChanged",()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||$s())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":nI&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,Tn.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&Tn.userInteractionRegistered&&this.wasPlaying&&this.play();break}}),r(this,"onApplicationMuteChanged",()=>{var t,A;this.context.application.muted?(t=this.sound)==null||t.setVolume(0):(A=this.sound)==null||A.setVolume(this.volume)}),r(this,"createAudio",t=>{nI&&console.log("AudioBuffer finished loading",t);const A=this.Sound;if(!A){nI&&console.warn("Failed getting sound?",this.name);return}A.isPlaying&&A.stop(),t&&A.setBuffer(t),A.loop=this._loop,this.context.application.muted?A.setVolume(0):A.setVolume(this.volume),A.autoplay=this.shouldPlay&&Tn.userInteractionRegistered,this.applySpatialDistanceSettings(),A.isPlaying&&A.stop(),Tn.registerWaitForAllowAudio(this.__onAllowAudioCallback)}),r(this,"__onAllowAudioCallback",()=>{this.shouldPlay&&this.play()}),r(this,"_lastContextTime",0),r(this,"_hasEnded",!0),r(this,"_needUpdateSpatialDistanceSettings",!1)}static get userInteractionRegistered(){return lw}static registerWaitForAllowAudio(t){if(t!==null){if(lw){t();return}dw.indexOf(t)===-1&&dw.push(t)}}get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(t){this._loop=t,this.sound&&this.sound.setLoop(t)}get spatialBlend(){return this._spatialBlend}set spatialBlend(t){t!==this._spatialBlend&&(this._spatialBlend=t,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(t){this._minDistance!==t&&(this._minDistance=t,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(t){this._maxDistance!==t&&(this._maxDistance=t,this._needUpdateSpatialDistanceSettings=!0)}get volume(){return this._volume}set volume(t){this._volume=t,this.sound&&!this.context.application.muted&&(nI&&console.log(this.name,"audio set volume",t),this.sound.setVolume(t))}get Sound(){var t;if(!this.sound&&Tn.userInteractionRegistered){let A=aA.getComponent(this.context.mainCamera,On)??aA.findObjectOfType(On,this.context);!A&&this.context.mainCamera&&(A=aA.addNewComponent(this.context.mainCamera,On)),A!=null&&A.listener?(this.sound=new Xb(A.listener),(t=this.gameObject)==null||t.add(this.sound)):nI&&console.warn("No audio listener found in scene - can not play audio")}return this.sound}get ShouldPlay(){return this.shouldPlay}get audioContext(){var t;return(t=this.sound)==null?void 0:t.context}awake(){nI&&console.log(this),this.audioLoader=new dD,this.playOnAwake&&(this.shouldPlay=!0),this.preload&&typeof this.clip=="string"&&this.audioLoader.load(this.clip,this.createAudio,()=>{},console.error)}onEnable(){this.sound&&this.gameObject.add(this.sound),Tn.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():Tn.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(iy.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(iy.MuteChanged,this.onApplicationMuteChanged),this.pause()}applySpatialDistanceSettings(){const t=this.sound;if(!t)return;this._needUpdateSpatialDistanceSettings=!1;const A=Ie.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(nI&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+A),t.setRefDistance(A),t.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:t.setDistanceModel("exponential");break;case 1:t.setDistanceModel("linear");break}this.spatialBlend>0?nI&&!this.helper&&(this.helper=new jgA(t,t.getRefDistance()),t.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}async onNewClip(t){if(t&&(this.clip=t),typeof t=="string")if(nI&&console.log(t),t.endsWith(".mp3")||t.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new dD),this.shouldPlay=!0,this._lastClipStartedLoading===t){nI&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=t,nI&&console.log("load audio",t);const A=await this.audioLoader.loadAsync(t).catch(console.error);this._lastClipStartedLoading=null,A&&this.createAudio(A)}else console.warn("Unsupported audio clip type",t);else this.shouldPlay=!0,this.createAudio()}play(t=void 0){var A,e,i;!t&&this.clip&&(t=this.clip),t!==void 0&&typeof t!="string"&&!(t instanceof MediaStream)&&(Se()&&console.warn("Called play on AudioSource with unknown argument type:",t+`
5408
- Using the assigned clip instead:`,this.clip),t=this.clip);let g=!this.sound||t&&t!==this.clip;if(typeof t=="string"&&!this.audioLoader&&(g=!0),(t instanceof MediaStream||typeof t=="string")&&(this.clip=t),g){this.shouldPlay=!0,this.onNewClip(t);return}if(this.shouldPlay=!0,this._hasEnded=!1,nI&&console.log("play",(A=this.sound)==null?void 0:A.getVolume(),this.sound),this.sound&&!this.sound.isPlaying){const I=this.context.application.muted;I&&this.sound.setVolume(0),(e=this.gameObject)==null||e.add(this.sound),this.clip instanceof MediaStream?(this.sound.setMediaStreamSource(this.clip),this._audioElement||(this._audioElement=document.createElement("audio"),this._audioElement.style.display="none"),this._audioElement.parentNode||(i=this.context.domElement.shadowRoot)==null||i.append(this._audioElement),this._audioElement.srcObject=this.clip,this._audioElement.autoplay=!1):(this._audioElement&&this._audioElement.remove(),this.sound.play(I?.1:0))}}pause(){var t,A;nI&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=(t=this.sound)==null?void 0:t.context.currentTime,this.sound.pause()),(A=this._audioElement)==null||A.remove()}stop(){var t,A;nI&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=(t=this.sound)==null?void 0:t.context.currentTime,nI&&console.log(this._lastContextTime),this.sound.stop()),(A=this._audioElement)==null||A.remove()}get isPlaying(){var t;return((t=this.sound)==null?void 0:t.isPlaying)??!1}set isPlaying(t){}get time(){var t,A;return(t=this.sound)!=null&&t.source?((A=this.sound.source)==null?void 0:A.context.currentTime)-this._lastContextTime+this.sound.offset:0}set time(t){if(this.sound){if(t===this.sound.offset)return;const A=this.isPlaying;this.stop(),this.sound.offset=t,A&&this.play()}}update(){this.helper&&(this.isPlaying&&this.helper.update(),this.helper.visible=this.isPlaying),this._needUpdateSpatialDistanceSettings&&this.applySpatialDistanceSettings(),this.sound&&!this.sound.isPlaying&&this.shouldPlay&&!this._hasEnded&&(this._hasEnded=!0,nI&&console.log("Audio clip ended",this.clip),this.dispatchEvent(new CustomEvent("ended",{detail:this})))}};let fi=Tn;nC([y(URL)],fi.prototype,"clip",2),nC([y()],fi.prototype,"playOnAwake",2),nC([y()],fi.prototype,"preload",2),nC([y()],fi.prototype,"loop",1),nC([y()],fi.prototype,"spatialBlend",1),nC([y()],fi.prototype,"minDistance",1),nC([y()],fi.prototype,"maxDistance",1),nC([y()],fi.prototype,"volume",1),nC([y()],fi.prototype,"rollOffMode",2),nC([y()],fi.prototype,"playInBackground",2);const N_={type:"change"},MU={type:"start"},F_={type:"end"},pw=new to,K_=new lI,ZgA=Math.cos(70*eg.DEG2RAD);let zgA=class extends ng{constructor(t,A){super(),this.object=t,this.domElement=A,this.domElement.style.touchAction="none",this.enabled=!0,this.target=new w,this.cursor=new w,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:Sr.ROTATE,MIDDLE:Sr.DOLLY,RIGHT:Sr.PAN},this.touches={ONE:fr.ROTATE,TWO:fr.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this.getPolarAngle=function(){return o.phi},this.getAzimuthalAngle=function(){return o.theta},this.getDistance=function(){return this.object.position.distanceTo(this.target)},this.listenToKeyEvents=function(j){j.addEventListener("keydown",se),this._domElementKeyEvents=j},this.stopListenToKeyEvents=function(){this._domElementKeyEvents.removeEventListener("keydown",se),this._domElementKeyEvents=null},this.saveState=function(){e.target0.copy(e.target),e.position0.copy(e.object.position),e.zoom0=e.object.zoom},this.reset=function(){e.target.copy(e.target0),e.object.position.copy(e.position0),e.object.zoom=e.zoom0,e.object.updateProjectionMatrix(),e.dispatchEvent(N_),e.update(),g=i.NONE},this.update=function(){const j=new w,G=new FA().setFromUnitVectors(t.up,new w(0,1,0)),F=G.clone().invert(),H=new w,O=new FA,J=new w,Z=2*Math.PI;return function(QA=null){const uA=e.object.getWorldPosition(t.position);j.copy(uA).sub(e.target),j.applyQuaternion(G),o.setFromVector3(j),e.autoRotate&&g===i.NONE&&L(m(QA)),e.enableDamping?(o.theta+=s.theta*e.dampingFactor,o.phi+=s.phi*e.dampingFactor):(o.theta+=s.theta,o.phi+=s.phi);let pA=e.minAzimuthAngle,SA=e.maxAzimuthAngle;isFinite(pA)&&isFinite(SA)&&(pA<-Math.PI?pA+=Z:pA>Math.PI&&(pA-=Z),SA<-Math.PI?SA+=Z:SA>Math.PI&&(SA-=Z),pA<=SA?o.theta=Math.max(pA,Math.min(SA,o.theta)):o.theta=o.theta>(pA+SA)/2?Math.max(pA,o.theta):Math.min(SA,o.theta)),o.phi=Math.max(e.minPolarAngle,Math.min(e.maxPolarAngle,o.phi)),o.makeSafe(),e.enableDamping===!0?e.target.addScaledVector(n,e.dampingFactor):e.target.add(n),e.target.sub(e.cursor),e.target.clampLength(e.minTargetRadius,e.maxTargetRadius),e.target.add(e.cursor),e.zoomToCursor&&k||e.object.isOrthographicCamera?o.radius=$(o.radius):(e.enableDamping?a=eg.lerp(a,C,e.dampingFactor):a=C,o.radius=$(o.radius*a)),j.setFromSpherical(o),j.applyQuaternion(F),uA.copy(e.target).add(j),e.object.parent?e.object.parent.worldToLocal(uA):e.object.position.copy(uA),e.object.lookAt(e.target),e.enableDamping===!0?(s.theta*=1-e.dampingFactor,s.phi*=1-e.dampingFactor,n.multiplyScalar(1-e.dampingFactor)):(s.set(0,0,0),n.set(0,0,0));let KA=!1;if(e.zoomToCursor&&k){let PA=null;if(e.object.isPerspectiveCamera){const ZA=j.length();PA=$(ZA*C);const zA=ZA-PA;e.object.position.addScaledVector(D,zA),e.object.updateMatrixWorld()}else if(e.object.isOrthographicCamera){const ZA=new w(S.x,S.y,0);ZA.unproject(e.object),e.object.zoom=Math.max(e.minZoom,Math.min(e.maxZoom,e.object.zoom/C)),e.object.updateProjectionMatrix(),KA=!0;const zA=new w(S.x,S.y,0);zA.unproject(e.object),e.object.position.sub(zA).add(ZA),e.object.updateMatrixWorld(),PA=j.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),e.zoomToCursor=!1;PA!==null&&(this.screenSpacePanning?e.target.set(0,0,-1).transformDirection(e.object.matrix).multiplyScalar(PA).add(e.object.position):(pw.origin.copy(e.object.position),pw.direction.set(0,0,-1).transformDirection(e.object.matrix),Math.abs(e.object.up.dot(pw.direction))<ZgA?t.lookAt(e.target):(K_.setFromNormalAndCoplanarPoint(e.object.up,e.target),pw.intersectPlane(K_,e.target))))}else e.object.isOrthographicCamera&&(KA=C!==1,KA&&(e.object.zoom=Math.max(e.minZoom,Math.min(e.maxZoom,e.object.zoom/C)),e.object.updateProjectionMatrix()));return C=1,k=!1,KA||H.distanceToSquared(e.object.position)>I||8*(1-O.dot(e.object.quaternion))>I||J.distanceToSquared(e.target)>0?(e.dispatchEvent(N_),H.copy(e.object.position),O.copy(e.object.quaternion),J.copy(e.target),!0):!1}}(),this.dispose=function(){e.domElement.removeEventListener("contextmenu",be),e.domElement.removeEventListener("pointerdown",q),e.domElement.removeEventListener("pointercancel",CA),e.domElement.removeEventListener("wheel",LA),e.domElement.removeEventListener("pointermove",N),e.domElement.removeEventListener("pointerup",CA),e._domElementKeyEvents!==null&&(e._domElementKeyEvents.removeEventListener("keydown",se),e._domElementKeyEvents=null)};const e=this,i={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6};let g=i.NONE;const I=1e-6,o=new Fk,s=new Fk;let C=1,a=1;const n=new w,B=new tA,Q=new tA,E=new tA,h=new tA,d=new tA,u=new tA,c=new tA,l=new tA,p=new tA,D=new w,S=new tA;let k=!1;const f=[],U={};let M=!1;function m(j){return j!==null?2*Math.PI/60*e.autoRotateSpeed*j:2*Math.PI/60/60*e.autoRotateSpeed}function x(j){const G=Math.abs(j*.01);return Math.pow(.95,e.zoomSpeed*G)}function L(j){s.theta-=j}function V(j){s.phi-=j}const Y=function(){const j=new w;return function(G,F){j.setFromMatrixColumn(F,0),j.multiplyScalar(-G),n.add(j)}}(),P=function(){const j=new w;return function(G,F){e.screenSpacePanning===!0?j.setFromMatrixColumn(F,1):(j.setFromMatrixColumn(F,0),j.crossVectors(e.object.up,j)),j.multiplyScalar(G),n.add(j)}}(),b=function(){const j=new w,G=new w;return function(F,H){const O=e.domElement;if(e.object.isPerspectiveCamera){e.object.getWorldPosition(G),j.copy(G).sub(e.target);let J=j.length();J*=Math.tan(e.object.fov/2*Math.PI/180),Y(2*F*J/O.clientHeight,e.object.matrixWorld),P(2*H*J/O.clientHeight,e.object.matrixWorld)}else e.object.isOrthographicCamera?(Y(F*(e.object.right-e.object.left)/e.object.zoom/O.clientWidth,e.object.matrixWorld),P(H*(e.object.top-e.object.bottom)/e.object.zoom/O.clientHeight,e.object.matrixWorld)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),e.enablePan=!1)}}();function T(j){e.object.isPerspectiveCamera||e.object.isOrthographicCamera?C/=j:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),e.enableZoom=!1)}function _(j){e.object.isPerspectiveCamera||e.object.isOrthographicCamera?C*=j:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),e.enableZoom=!1)}function eA(j,G){if(!e.zoomToCursor)return;k=!0;const F=e.domElement.getBoundingClientRect(),H=j-F.left,O=G-F.top,J=F.width,Z=F.height;S.x=H/J*2-1,S.y=-(O/Z)*2+1,D.set(S.x,S.y,1).unproject(e.object).sub(e.object.position).normalize()}function $(j){return Math.max(e.minDistance,Math.min(e.maxDistance,j))}function IA(j){B.set(j.clientX,j.clientY)}function yA(j){eA(j.clientX,j.clientX),c.set(j.clientX,j.clientY)}function xA(j){h.set(j.clientX,j.clientY)}function OA(j){Q.set(j.clientX,j.clientY),E.subVectors(Q,B).multiplyScalar(e.rotateSpeed);const G=e.domElement;L(2*Math.PI*E.x/G.clientHeight),V(2*Math.PI*E.y/G.clientHeight),B.copy(Q),e.update()}function $A(j){l.set(j.clientX,j.clientY),p.subVectors(l,c),p.y>0?T(x(p.y)):p.y<0&&_(x(p.y)),c.copy(l),e.update()}function rA(j){d.set(j.clientX,j.clientY),u.subVectors(d,h).multiplyScalar(e.panSpeed),b(u.x,u.y),h.copy(d),e.update()}function RA(j){eA(j.clientX,j.clientY),j.deltaY<0?_(x(j.deltaY)):j.deltaY>0&&T(x(j.deltaY)),e.update()}function jA(j){let G=!1;switch(j.code){case e.keys.UP:j.ctrlKey||j.metaKey||j.shiftKey?V(2*Math.PI*e.rotateSpeed/e.domElement.clientHeight):b(0,e.keyPanSpeed),G=!0;break;case e.keys.BOTTOM:j.ctrlKey||j.metaKey||j.shiftKey?V(-2*Math.PI*e.rotateSpeed/e.domElement.clientHeight):b(0,-e.keyPanSpeed),G=!0;break;case e.keys.LEFT:j.ctrlKey||j.metaKey||j.shiftKey?L(2*Math.PI*e.rotateSpeed/e.domElement.clientHeight):b(e.keyPanSpeed,0),G=!0;break;case e.keys.RIGHT:j.ctrlKey||j.metaKey||j.shiftKey?L(-2*Math.PI*e.rotateSpeed/e.domElement.clientHeight):b(-e.keyPanSpeed,0),G=!0;break}G&&(j.preventDefault(),e.update())}function YA(j){if(f.length===1)B.set(j.pageX,j.pageY);else{const G=Qe(j),F=.5*(j.pageX+G.x),H=.5*(j.pageY+G.y);B.set(F,H)}}function WA(j){if(f.length===1)h.set(j.pageX,j.pageY);else{const G=Qe(j),F=.5*(j.pageX+G.x),H=.5*(j.pageY+G.y);h.set(F,H)}}function BA(j){const G=Qe(j),F=j.pageX-G.x,H=j.pageY-G.y,O=Math.sqrt(F*F+H*H);c.set(0,O)}function TA(j){e.enableZoom&&BA(j),e.enablePan&&WA(j)}function W(j){e.enableZoom&&BA(j),e.enableRotate&&YA(j)}function GA(j){if(f.length==1)Q.set(j.pageX,j.pageY);else{const F=Qe(j),H=.5*(j.pageX+F.x),O=.5*(j.pageY+F.y);Q.set(H,O)}E.subVectors(Q,B).multiplyScalar(e.rotateSpeed);const G=e.domElement;L(2*Math.PI*E.x/G.clientHeight),V(2*Math.PI*E.y/G.clientHeight),B.copy(Q)}function fA(j){if(f.length===1)d.set(j.pageX,j.pageY);else{const G=Qe(j),F=.5*(j.pageX+G.x),H=.5*(j.pageY+G.y);d.set(F,H)}u.subVectors(d,h).multiplyScalar(e.panSpeed),b(u.x,u.y),h.copy(d)}function _A(j){const G=Qe(j),F=j.pageX-G.x,H=j.pageY-G.y,O=Math.sqrt(F*F+H*H);l.set(0,O),p.set(0,Math.pow(l.y/c.y,e.zoomSpeed)),T(p.y),c.copy(l);const J=(j.pageX+G.x)*.5,Z=(j.pageY+G.y)*.5;eA(J,Z)}function hA(j){e.enableZoom&&_A(j),e.enablePan&&fA(j)}function Ee(j){e.enableZoom&&_A(j),e.enableRotate&&GA(j)}function q(j){e.enabled!==!1&&(f.length===0&&(e.domElement.addEventListener("pointermove",N),e.domElement.addEventListener("pointerup",CA)),ne(j),j.pointerType==="touch"?De(j):bA(j))}function N(j){e.enabled!==!1&&(j.pointerType==="touch"?vA(j):MA(j))}function CA(j){switch(Be(j),f.length){case 0:e.domElement.removeEventListener("pointermove",N),e.domElement.removeEventListener("pointerup",CA),e.dispatchEvent(F_),g=i.NONE;break;case 1:const G=f[0],F=U[G];De({pointerId:G,pageX:F.x,pageY:F.y});break}}function bA(j){let G;switch(j.button){case 0:G=e.mouseButtons.LEFT;break;case 1:G=e.mouseButtons.MIDDLE;break;case 2:G=e.mouseButtons.RIGHT;break;default:G=-1}switch(G){case Sr.DOLLY:if(e.enableZoom===!1)return;yA(j),g=i.DOLLY;break;case Sr.ROTATE:if(j.ctrlKey||j.metaKey||j.shiftKey){if(e.enablePan===!1)return;xA(j),g=i.PAN}else{if(e.enableRotate===!1)return;IA(j),g=i.ROTATE}break;case Sr.PAN:if(j.ctrlKey||j.metaKey||j.shiftKey){if(e.enableRotate===!1)return;IA(j),g=i.ROTATE}else{if(e.enablePan===!1)return;xA(j),g=i.PAN}break;default:g=i.NONE}g!==i.NONE&&e.dispatchEvent(MU)}function MA(j){switch(g){case i.ROTATE:if(e.enableRotate===!1)return;OA(j);break;case i.DOLLY:if(e.enableZoom===!1)return;$A(j);break;case i.PAN:if(e.enablePan===!1)return;rA(j);break}}function LA(j){e.enabled===!1||e.enableZoom===!1||g!==i.NONE||(j.preventDefault(),e.dispatchEvent(MU),RA(ge(j)),e.dispatchEvent(F_))}function ge(j){const G=j.deltaMode,F={clientX:j.clientX,clientY:j.clientY,deltaY:j.deltaY};switch(G){case 1:F.deltaY*=16;break;case 2:F.deltaY*=100;break}return j.ctrlKey&&!M&&(F.deltaY*=10),F}function HA(j){j.key==="Control"&&(M=!0,e.domElement.getRootNode().addEventListener("keyup",XA,{passive:!0,capture:!0}))}function XA(j){j.key==="Control"&&(M=!1,e.domElement.getRootNode().removeEventListener("keyup",XA,{passive:!0,capture:!0}))}function se(j){e.enabled===!1||e.enablePan===!1||jA(j)}function De(j){switch(kA(j),f.length){case 1:switch(e.touches.ONE){case fr.ROTATE:if(e.enableRotate===!1)return;YA(j),g=i.TOUCH_ROTATE;break;case fr.PAN:if(e.enablePan===!1)return;WA(j),g=i.TOUCH_PAN;break;default:g=i.NONE}break;case 2:switch(e.touches.TWO){case fr.DOLLY_PAN:if(e.enableZoom===!1&&e.enablePan===!1)return;TA(j),g=i.TOUCH_DOLLY_PAN;break;case fr.DOLLY_ROTATE:if(e.enableZoom===!1&&e.enableRotate===!1)return;W(j),g=i.TOUCH_DOLLY_ROTATE;break;default:g=i.NONE}break;default:g=i.NONE}g!==i.NONE&&e.dispatchEvent(MU)}function vA(j){switch(kA(j),g){case i.TOUCH_ROTATE:if(e.enableRotate===!1)return;GA(j),e.update();break;case i.TOUCH_PAN:if(e.enablePan===!1)return;fA(j),e.update();break;case i.TOUCH_DOLLY_PAN:if(e.enableZoom===!1&&e.enablePan===!1)return;hA(j),e.update();break;case i.TOUCH_DOLLY_ROTATE:if(e.enableZoom===!1&&e.enableRotate===!1)return;Ee(j),e.update();break;default:g=i.NONE}}function be(j){e.enabled!==!1&&j.preventDefault()}function ne(j){f.push(j.pointerId)}function Be(j){delete U[j.pointerId];for(let G=0;G<f.length;G++)if(f[G]==j.pointerId){f.splice(G,1);return}}function kA(j){let G=U[j.pointerId];G===void 0&&(G=new tA,U[j.pointerId]=G),G.set(j.pageX,j.pageY)}function Qe(j){const G=j.pointerId===f[0]?f[1]:f[0];return U[G]}e.domElement.addEventListener("contextmenu",be),e.domElement.addEventListener("pointerdown",q),e.domElement.addEventListener("pointercancel",CA),e.domElement.addEventListener("wheel",LA,{passive:!1}),e.domElement.getRootNode().addEventListener("keydown",HA,{passive:!0,capture:!0}),this.update()}};class J_ extends DA{constructor(A,e,i,g=128){if(e<=0||i<=0||g<=0)throw new Error("GroundedSkybox height, radius, and resolution must be positive.");const I=new Ls(i,2*g,g);I.scale(1,1,-1);const o=I.getAttribute("position"),s=new w;for(let C=0;C<o.count;++C)if(s.fromBufferAttribute(o,C),s.y<0){const a=-e*3/2,n=s.y<a?-e/s.y:1-s.y*s.y/(3*a*a);s.multiplyScalar(n),s.toArray(o.array,3*C)}o.needsUpdate=!0,super(I,new st({map:A,depthWrite:!1}))}}const Dw=Symbol("cameraController");function XgA(t){return t[Dw]}function v_(t,A,e){e?t[Dw]=A:t[Dw]===A&&(t[Dw]=null)}const b_=Symbol("camera autofit");function $gA(t){return t[b_]===void 0?!0:t[b_]!==!1}var AIA=Object.defineProperty,eIA=Object.getOwnPropertyDescriptor,tIA=(t,A,e,i)=>{for(var g=i>1?void 0:i?eIA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&AIA(A,e,g),g};class Ad extends JA{constructor(){super(...arguments),r(this,"constraintActive",!0),r(this,"locked",!1),r(this,"sources",[])}}tIA([y(wA)],Ad.prototype,"sources",2);function iIA(t){Il(t,Yi.ContextCreated)}function gIA(t){Il(t,Pi.Start)}function q_(t){Il(t,Pi.Update)}function IIA(t){Il(t,Pi.OnBeforeRender)}class fB{constructor(){r(this,"bb",null),r(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}static sizeOf(){return 12}static createVec3(A,e,i,g){return A.prep(4,12),A.writeFloat32(g),A.writeFloat32(i),A.writeFloat32(e),A.offset()}}class L_{constructor(){r(this,"bb",null),r(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}position(A){return(A||new fB).__init(this.bb_pos,this.bb)}rotation(A){return(A||new fB).__init(this.bb_pos+12,this.bb)}scale(A){return(A||new fB).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(A,e,i,g,I,o,s,C,a,n){return A.prep(4,36),A.prep(4,12),A.writeFloat32(n),A.writeFloat32(a),A.writeFloat32(C),A.prep(4,12),A.writeFloat32(s),A.writeFloat32(o),A.writeFloat32(I),A.prep(4,12),A.writeFloat32(g),A.writeFloat32(i),A.writeFloat32(e),A.offset()}}class Va{constructor(){r(this,"bb",null),r(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}static getRootAsSyncedTransformModel(A,e){return(e||new Va).__init(A.readInt32(A.position())+A.position(),A)}static getSizePrefixedRootAsSyncedTransformModel(A,e){return A.setPosition(A.position()+$G),(e||new Va).__init(A.readInt32(A.position())+A.position(),A)}guid(A){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,A):null}fast(){const A=this.bb.__offset(this.bb_pos,6);return A?!!this.bb.readInt8(this.bb_pos+A):!1}transform(A){const e=this.bb.__offset(this.bb_pos,8);return e?(A||new L_).__init(this.bb_pos+e,this.bb):null}dontSave(){const A=this.bb.__offset(this.bb_pos,10);return A?!!this.bb.readInt8(this.bb_pos+A):!1}static startSyncedTransformModel(A){A.startObject(4)}static addGuid(A,e){A.addFieldOffset(0,e,0)}static addFast(A,e){A.addFieldInt8(1,+e,0)}static addTransform(A,e){A.addFieldStruct(2,e,0)}static addDontSave(A,e){A.addFieldInt8(3,+e,0)}static endSyncedTransformModel(A){return A.endObject()}static finishSyncedTransformModelBuffer(A,e){A.finish(e)}static finishSizePrefixedSyncedTransformModelBuffer(A,e){A.finish(e,void 0,!0)}}var cg=(t=>(t[t.Average=0]="Average",t[t.Multiply=1]="Multiply",t[t.Minimum=2]="Minimum",t[t.Maximum=3]="Maximum",t))(cg||{}),yw=(t=>(t[t.Discrete=0]="Discrete",t[t.Continuous=1]="Continuous",t))(yw||{}),vi=(t=>(t[t.None=0]="None",t[t.FreezePositionX=2]="FreezePositionX",t[t.FreezePositionY=4]="FreezePositionY",t[t.FreezePositionZ=8]="FreezePositionZ",t[t.FreezePosition=14]="FreezePosition",t[t.FreezeRotationX=16]="FreezeRotationX",t[t.FreezeRotationY=32]="FreezeRotationY",t[t.FreezeRotationZ=64]="FreezeRotationZ",t[t.FreezeRotation=112]="FreezeRotation",t[t.FreezeAll=126]="FreezeAll",t))(vi||{}),HE=(t=>(t[t.None=0]="None",t[t.X=2]="X",t[t.Y=4]="Y",t[t.Z=8]="Z",t[t.All=-1]="All",t))(HE||{});const Jg=function(t,A){return function(e,i,g){oIA(e,i,g,t,A)}};function oIA(t,A,e,i,g){if(!g&&!i&&!t.onValidate)return;if(e!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",t,A,e),wi("Invalid usage of validate decorator. Only fields can be validated. Property: "+A,vo.Error);return}let I="";if(typeof A=="string"?I=A:I=A.name,t.__internalAwake){const o=Symbol(I),s=t.__internalAwake;t.__internalAwake=function(){var C;if(!this.onValidate){Se()&&console.warn('Usage of @validate decorate detected but there is no onValidate method in your class: "'+((C=t.constructor)==null?void 0:C.name)+'"');return}if(this[o]===void 0){this[o]=this[I];const a=this[I];if(a instanceof tA||a instanceof w||a instanceof ie||a instanceof FA){const n=this[I];MD(n,()=>{this.onValidate(I)})}Object.defineProperty(this,I,{set:function(n){var B;if(this[FG]===!0)this[o]=n;else{i?.call(this,n);const Q=this[o];this[o]=n,(B=this.onValidate)==null||B.call(this,I,Q)}},get:function(){return g?.call(this),this[o]}})}s.call(this)}}}const sIA=function(t){return function(A,e,i){let g="";typeof e=="string"?g=e:g=e.name;const I=t.prototype,o=Object.getOwnPropertyDescriptor(I,g);if(!(o!=null&&o.value)){console.warn("Can not apply prefix: type does not have method named",e,t);return}const s=o.value,C=A[g];Object.defineProperty(I,g,{value:function(...a){const n=C?.call(this,...a);if(n instanceof Promise){n.then(B=>{if(B!==!1)return s.call(this,...a)});return}if(n!==!1)return s.call(this,...a)}})}};var CIA=Object.defineProperty,aIA=Object.getOwnPropertyDescriptor,Vo=(t,A,e,i)=>{for(var g=i>1?void 0:i?aIA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&CIA(A,e,g),g};class nIA{constructor(A,e){r(this,"positionChanged",!1),r(this,"rotationChanged",!1),r(this,"position"),r(this,"quaternion"),r(this,"_positionKeys",["x","y","z"]),r(this,"_quaternionKeys",["_x","_y","_z","_w"]),r(this,"mute",!1),r(this,"context"),r(this,"obj"),r(this,"_positionWatch"),r(this,"_rotationWatch"),this.context=e,this.obj=A}get isDirty(){return this.positionChanged||this.rotationChanged}reset(A=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,A){if(this.position)for(const e of this._positionKeys)delete this.position[e];if(this.quaternion)for(const e of this._quaternionKeys)delete this.quaternion[e]}}syncValues(){for(const A of this._positionKeys)this.position[A]=this.obj.position[A];for(const A of this._quaternionKeys)this.quaternion[A]=this.obj.quaternion[A]}applyValues(){if(this.positionChanged&&this.position)for(const A of this._positionKeys){const e=this.position[A];e!==void 0&&(this.obj.position[A]=e)}if(this.rotationChanged&&this.quaternion)for(const A of this._quaternionKeys){const e=this.quaternion[A];e!==void 0&&(this.obj.quaternion[A]=e)}}start(A,e){this.reset(),A&&(this._positionWatch||(this._positionWatch=new Oa(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((I,o)=>{var s;if((s=this.context.physics.engine)!=null&&s.isUpdating||this.mute)return;const C=this.position[o];Math.abs(C-I)<1e-5||(this.position[o]=I,this.positionChanged=!0)})),e&&(this._rotationWatch||(this._rotationWatch=new Oa(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((I,o)=>{var s;if((s=this.context.physics.engine)!=null&&s.isUpdating||this.mute)return;const C=this.quaternion[o];Math.abs(C-I)<1e-5||(this.quaternion[o]=I,this.rotationChanged=!0)}));const i=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),g=new NA;this.obj.matrixWorld.multiplyMatrices=(I,o)=>{var s;return(s=this.context.physics.engine)!=null&&s.isUpdating||this.mute||g.equals(I)||(this.positionChanged=!0,this.rotationChanged=!0,g.copy(I)),i(I,o)}}stop(){var A,e;(A=this._positionWatch)==null||A.revoke(),(e=this._rotationWatch)==null||e.revoke()}}var RU;const UU=(RU=class extends JA{constructor(){super(...arguments),r(this,"autoMass",!0),r(this,"_mass",0),r(this,"useGravity",!0),r(this,"constraints",vi.None),r(this,"isKinematic",!1),r(this,"drag",0),r(this,"angularDrag",1),r(this,"detectCollisions",!0),r(this,"sleepThreshold",.01),r(this,"collisionDetectionMode",yw.Discrete),r(this,"_gravityScale",1),r(this,"dominanceGroup",0),r(this,"_propertiesChanged",!1),r(this,"_currentVelocity",new w),r(this,"_smoothedVelocity",new w),r(this,"_smoothedVelocityGetter",new w),r(this,"_lastPosition",new w),r(this,"_watch")}set mass(t){t!==this._mass&&(this._mass=t,this._propertiesChanged=!0,this.__didAwake&&(this.autoMass=!1))}get mass(){var t,A;return this.autoMass?((A=(t=this.context.physics.engine)==null?void 0:t.getBody(this))==null?void 0:A.mass())??-1:this._mass}get lockPositionX(){return(this.constraints&vi.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&vi.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&vi.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&vi.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&vi.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&vi.FreezeRotationZ)!==0}set lockPositionX(t){t?this.constraints|=vi.FreezePositionX:this.constraints&=~vi.FreezePositionX}set lockPositionY(t){t?this.constraints|=vi.FreezePositionY:this.constraints&=~vi.FreezePositionY}set lockPositionZ(t){t?this.constraints|=vi.FreezePositionZ:this.constraints&=~vi.FreezePositionZ}set lockRotationX(t){t?this.constraints|=vi.FreezeRotationX:this.constraints&=~vi.FreezeRotationX}set lockRotationY(t){t?this.constraints|=vi.FreezeRotationY:this.constraints&=~vi.FreezeRotationY}set lockRotationZ(t){t?this.constraints|=vi.FreezeRotationZ:this.constraints&=~vi.FreezeRotationZ}set gravityScale(t){this._gravityScale=t}get gravityScale(){return this._gravityScale}awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new nIA(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),Pi.LateUpdate)}onDisable(){var t,A;(t=this._watch)==null||t.stop(),(A=this.context.physics.engine)==null||A.removeBody(this)}onDestroy(){var t;(t=this.context.physics.engine)==null||t.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){for(var t,A,e,i;;)this._propertiesChanged&&(this._propertiesChanged=!1,(t=this.context.physics.engine)==null||t.updateProperties(this)),(A=this._watch)!=null&&A.isDirty?(this._watch.mute=!0,this._watch.applyValues(),(e=this.context.physics.engine)==null||e.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):(i=this._watch)==null||i.syncValues(),this.captureVelocity(),yield}teleport(t,A=!0){var e;(e=this._watch)==null||e.reset(!0),A?this.gameObject.position.set(t.x,t.y,t.z):this.setWorldPosition(t.x,t.y,t.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(t=!0){var A;(A=this.context.physics.engine)==null||A.resetForces(this,t)}resetTorques(t=!0){var A;(A=this.context.physics.engine)==null||A.resetTorques(this,t)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){var t;(t=this.context.physics.engine)==null||t.wakeup(this)}get isSleeping(){var t;return(t=this.context.physics.engine)==null?void 0:t.isSleeping(this)}updateProperties(){var t;return this._propertiesChanged=!1,(t=this.context.physics.engine)==null?void 0:t.updateProperties(this)}applyForce(t,A,e=!0){var i;this._propertiesChanged&&this.updateProperties(),(i=this.context.physics.engine)==null||i.addForce(this,t,e)}applyImpulse(t,A=!0){var e;this._propertiesChanged&&this.updateProperties(),(e=this.context.physics.engine)==null||e.applyImpulse(this,t,A)}setForce(t,A,e,i=!0){var g,I,o;(g=this.context.physics.engine)==null||g.resetForces(this,i),typeof t=="number"?(A??(A=0),e??(e=0),(I=this.context.physics.engine)==null||I.addForce(this,{x:t,y:A,z:e},i)):(o=this.context.physics.engine)==null||o.addForce(this,t,i)}getVelocity(){var t;const A=(t=this.context.physics.engine)==null?void 0:t.getLinearVelocity(this);return A?(this._currentVelocity.x=A.x,this._currentVelocity.y=A.y,this._currentVelocity.z=A.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(t,A,e,i=!0){var g,I;if(t instanceof w){const o=t;(g=this.context.physics.engine)==null||g.setLinearVelocity(this,o,i);return}A===void 0||e===void 0||(I=this.context.physics.engine)==null||I.setLinearVelocity(this,{x:t,y:A,z:e},i)}getAngularVelocity(){var t;const A=(t=this.context.physics.engine)==null?void 0:t.getAngularVelocity(this);return A?(this._currentVelocity.x=A.x,this._currentVelocity.y=A.y,this._currentVelocity.z=A.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setAngularVelocity(t,A,e,i=!0){var g,I;if(t instanceof w){const o=t;(g=this.context.physics.engine)==null||g.setAngularVelocity(this,o,i);return}A===void 0||e===void 0||(I=this.context.physics.engine)==null||I.setAngularVelocity(this,{x:t,y:A,z:e},i)}setTorque(t,A,e){this.setAngularVelocity(t,A,e)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(t=null){}captureVelocity(){const t=Ne(this.gameObject);UU.tempPosition.copy(t);const A=t.sub(this._lastPosition);this._lastPosition.copy(UU.tempPosition),this._smoothedVelocity.lerp(A,this.context.time.deltaTime/.1)}},r(RU,"tempPosition",new w),RU);let Pt=UU;Vo([Jg()],Pt.prototype,"autoMass",2),Vo([y()],Pt.prototype,"mass",1),Vo([Jg(),y()],Pt.prototype,"useGravity",2),Vo([Jg(),y()],Pt.prototype,"constraints",2),Vo([Jg(),y()],Pt.prototype,"isKinematic",2),Vo([Jg(),y()],Pt.prototype,"drag",2),Vo([Jg(),y()],Pt.prototype,"angularDrag",2),Vo([Jg(),y()],Pt.prototype,"detectCollisions",2),Vo([Jg(),y()],Pt.prototype,"sleepThreshold",2),Vo([Jg(),y()],Pt.prototype,"collisionDetectionMode",2),Vo([Jg()],Pt.prototype,"_gravityScale",2),Vo([Jg()],Pt.prototype,"dominanceGroup",2);const ma=iA("debugsync"),ed="STRS";tM(ed,Va.getRootAsSyncedTransformModel);const rC=new Ju;function x_(t,A,e=!0){rC.clear();const i=rC.createString(t);Va.startSyncedTransformModel(rC),Va.addGuid(rC,i),Va.addFast(rC,e);const g=A.worldPosition,I=A.worldEuler,o=A.gameObject.scale;Va.addTransform(rC,L_.createTransform(rC,g.x,g.y,g.z,I.x,I.y,I.z,o.x,o.y,o.z));const s=Va.endSyncedTransformModel(rC);return rC.finish(s,ed),rC.asUint8Array()}let NU=0,td=0;q_(t=>{var A;const e=(A=t.connection.currentServerUrl)!=null&&A.includes("glitch")?10:40;td=Math.floor(NU/e),NU=0,ma&&td>0&&console.log("Sync Transform Fast Interval",td)});class Hn extends JA{constructor(){super(...arguments),r(this,"overridePhysics",!0),r(this,"interpolatePosition",!0),r(this,"interpolateRotation",!0),r(this,"fastMode",!1),r(this,"syncDestroy",!1),r(this,"_model",null),r(this,"_needsUpdate",!0),r(this,"rb",null),r(this,"_wasKinematic",!1),r(this,"_receivedDataBefore",!1),r(this,"_targetPosition"),r(this,"_targetRotation"),r(this,"_receivedFastUpdate",!1),r(this,"_shouldRequestOwnership",!1),r(this,"joinedRoomCallback",null),r(this,"receivedDataCallback",null),r(this,"tempEuler",new Wg),r(this,"receivedUpdate",!1),r(this,"lastWorldPos"),r(this,"lastWorldRotation")}requestOwnership(){ma&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}hasOwnership(){var A;return((A=this._model)==null?void 0:A.hasOwnership)??void 0}isOwned(){var A;return(A=this._model)==null?void 0:A.isOwned}awake(){ma&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new w,this._targetRotation=new FA,this.lastWorldPos=new w,this.lastWorldRotation=new FA,this.rb=aA.getComponentInChildren(this.gameObject,Pt),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new pM(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(ht.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(ed,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&VH(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(ht.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(ed,this.receivedDataCallback)}tryGetLastState(){const A=this.context.connection.tryGetState(this.guid);A&&this.onReceivedData(A)}onReceivedData(A){var e;if(!this.destroyed&&typeof A.guid=="function"&&A.guid()===this.guid){ma&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,A),this.receivedUpdate=!0,this._receivedFastUpdate=A.fast();const i=A.transform();if(i){Ts.markDirty(this.gameObject,!0);const g=i.position();g&&(this.interpolatePosition&&((e=this._targetPosition)==null||e.set(g.x(),g.y(),g.z())),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(g.x(),g.y(),g.z()));const I=i.rotation();I&&(this.tempEuler.set(I.x(),I.y(),I.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&dR(this.gameObject,this.tempEuler))}this._receivedDataBefore=!0}}onEnable(){this.lastWorldPos.copy(this.worldPosition),this.lastWorldRotation.copy(this.worldQuaternion),this._needsUpdate=!0,this._model&&this._model.updateIsOwned()}onDisable(){this._model&&this._model.freeOwnership()}onBeforeRender(){if(!this.activeAndEnabled||!this.context.connection.isConnected)return;if(!this.context.connection.isInRoom||!this._model){ma&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());const A=this.worldPosition,e=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){const I=A.distanceTo(this.lastWorldPos),o=e.angleTo(this.lastWorldRotation),s=this._model.hasOwnership||this.fastMode?1e-4:.001;(I>s||o>s)&&(this._model.hasOwnership?this._needsUpdate=!0:(ma&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastWorldPos),this.worldPosition=this.lastWorldPos,A.copy(this.lastWorldPos),this.worldQuaternion=this.lastWorldRotation,e.copy(this.lastWorldRotation),Ts.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const I=this._receivedFastUpdate||this.fastMode?.5:.3;let o=!1;if(this.interpolatePosition&&this._targetPosition){const s=this.worldPosition;s.lerp(this._targetPosition,I),this.worldPosition=s,o=!0}if(this.interpolateRotation&&this._targetRotation){const s=this.worldQuaternion;s.slerp(this._targetRotation,I),this.worldQuaternion=s,o=!0}o&&Ts.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastWorldPos.copy(A),this.lastWorldRotation.copy(e),!this._model)return;if(!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership){this.rb&&(this.rb.isKinematic=this._model.isOwned??!1,this.rb.setVelocity(0,0,0));return}this.rb&&(this._wasKinematic!==void 0&&(ma&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic),this.gameObject.position.distanceTo(new w(0,0,0))>1e3&&(ma&&console.log("RESET",this.name),this.gameObject.position.set(0,1,0),this.rb.setVelocity(0,0,0)));const i=10,g=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%i===0||g)){if(NU++,g&&td>0&&this.context.time.frameCount%td!==0)return;ma&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this.overridePhysics&&this.rb,this._needsUpdate=!1;const I=x_(this.guid,this,!!g);this.context.connection.sendBinary(I)}}}const rIA=iA("debugshadowcomponents");aR.prototype.interactable={get(){return this.interactive},set(t){this.interactable=t}};const Zo=Symbol("shadowDomOwner");class Ys extends JA{constructor(){super(...arguments),r(this,"_shadowComponent",null),r(this,"_controlsChildLayout",!0),r(this,"_root"),r(this,"_parentComponent")}isRoot(){var A;return((A=this.Root)==null?void 0:A.gameObject)===this.gameObject}get canvas(){const A=this.Root;return A!=null&&A.isCanvas?A:null}get Canvas(){return this.canvas}markDirty(){zo.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(A){this._shadowComponent=A}get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(A){this._controlsChildLayout=A,this.shadowComponent&&(this.shadowComponent.autoLayout=A)}get Root(){return this._root===void 0&&(this._root=aA.getComponentInParent(this.gameObject,id)),this._root}__internalNewInstanceCreated(){super.__internalNewInstanceCreated(),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0}onEnable(){super.onEnable()}addShadowComponent(A,e){var i;this.removeShadowComponent();const g=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=aA.getComponentInParent(g,Ys),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}A.name=this.name+" ("+(this.constructor.name??"UI")+")",A.autoLayout=this._parentComponent.controlsChildLayout,A[Zo]=this,this.setShadowComponentOwner(A);let I=!1;if(((i=this.Root)==null?void 0:i.gameObject)===this.gameObject)this.gameObject.add(A);else{const o=this._parentComponent.shadowComponent;o&&(o?.add(A),I=!0)}this.shadowComponent=A,e&&e.shadowComponent&&this.shadowComponent&&e.shadowComponent.add(this.shadowComponent),el&&A.add(new Fo(.5)),this.onAfterAddedToScene(),I&&hH(),rIA&&console.log(this.shadowComponent)}setShadowComponentOwner(A){if(A&&(A[Zo]===void 0||A[Zo]===this)&&(A[Zo]=this,A.children))for(const e of A.children)this.setShadowComponentOwner(e)}traverseOwnedShadowComponents(A,e,i){if(A&&A[Zo]===e){i(A);for(const g of A.children)this.traverseOwnedShadowComponents(g,e,i)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(A){this.shadowComponent&&(this.shadowComponent.interactable=A)}}class id extends Ys{awake(){super.awake()}}class vh{constructor(A,e){r(this,"event"),r(this,"button"),r(this,"buttonName"),r(this,"_used",!1),r(this,"_propagationStopped",!1),r(this,"z__pointer_ctured",!1),r(this,"z__pointer_cture_rleased",!1),r(this,"inputSource"),r(this,"object"),r(this,"point"),r(this,"normal"),r(this,"face"),r(this,"distance"),r(this,"instanceId"),r(this,"isDown"),r(this,"isUp"),r(this,"isPressed"),r(this,"isClick"),r(this,"isDoubleClick"),r(this,"input"),this.event=e,this.input=A,this.button=e.button}get deviceIndex(){return this.event.deviceIndex}get pointerId(){return this.event.pointerId}get pressure(){return this.event.pressure}get used(){return this._used}use(){this._used||(this._used=!0,this.pointerId!==void 0&&this.input.setPointerUsed(this.pointerId))}get propagationStopped(){return this._propagationStopped}stopPropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}stopImmediatePropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}setPointerCapture(){this.z__pointer_ctured=!0}releasePointerCapture(){this.z__pointer_cture_rleased=!0}get mode(){return this.event.mode}clone(){const A=new vh(this.input,this.event);return Object.assign(A,this),A}Use(){this.use()}StopPropagation(){this.event.stopImmediatePropagation()}}function FU(t,A){return aA.foreachComponent(t,e=>{if(!e.enabled)return;const i=e;if(A)switch(A){case"pointerdown":if(i.onPointerDown)return!0;break;case"pointerup":if(i.onPointerUp||i.onPointerClick)return!0;break;case"pointermove":if(i.onPointerEnter||i.onPointerExit||i.onPointerMove)return!0;break}else if(i.onPointerDown||i.onPointerUp||i.onPointerEnter||i.onPointerExit||i.onPointerClick)return!0},!1)===!0}var BIA=Object.defineProperty,QIA=Object.getOwnPropertyDescriptor,EIA=(t,A,e,i)=>{for(var g=i>1?void 0:i?QIA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&BIA(A,e,g),g};class gd extends JA{awake(){zo.createIfNoneExists(this.context)}onEnable(){var A;(A=zo.get(this.context))==null||A.register(this)}onDisable(){var A;(A=zo.get(this.context))==null||A.unregister(this)}}class ro extends gd{constructor(){super(...arguments),r(this,"targets",null),r(this,"raycastHits",[]),r(this,"ignoreSkinnedMeshes",!1)}start(){this.targets=[this.gameObject]}performRaycast(A=null){if(!this.targets)return null;A??(A=new Oo),A.targets=this.targets,A.results=this.raycastHits;const e=A.testObject;this.ignoreSkinnedMeshes&&(A.testObject=g=>g instanceof ls?"continue in children":e?e(g):!0);const i=this.context.physics.raycast(A);return A.testObject=e,i}}EIA([y()],ro.prototype,"ignoreSkinnedMeshes",2);class ww extends ro{constructor(){super(),this.ignoreSkinnedMeshes=!0}}class Id extends gd{performRaycast(A){if(!de.active||!(A!=null&&A.ray))return null;const e=A.ray.origin,i=.01;return this.context.physics.sphereOverlap(e,i)}}class Sw{static getObject(A){const e=A[Zo];return e&&(e.isComponent===!0?A=e.gameObject:A=e),A}static isInteractable(A,e){if(e&&(e.canvasGroup=void 0,e.graphic=void 0),A==null||!A.visible||(A=this.getObject(A),!A.visible))return!1;const i=this.tryFindCanvasGroup(A);if(i?.isCanvasGroup===!0&&(e&&(e.canvasGroup=i),i.blocksRaycasts===!1||i.interactable===!1))return!1;const g=lB(A,I=>{if(I.isGraphic===!0)return I},!1);return e&&g?.isGraphic===!0&&(e.graphic=g),!(g?.raycastTarget===!1||g?.layer===2)}static tryFindCanvasGroup(A){if(!A)return null;const e=lB(A,i=>{const g=i;if(g.blocksRaycasts!==void 0&&g.interactable!==void 0)return g},!1);return e!==void 0?e:this.tryFindCanvasGroup(A.parent)}}function KU(t){return t[Zo]||(t.parent?KU(t.parent):null)}function hIA(t){return t.isUI===!0||typeof t[Zo]=="object"}function fw(t,A){if(!t)return;const e=t.material;if(e?.isMaterial===!0){const i=t.parent;i&&i.isText,e.side=A.doubleSided??!0?dt:yg,e.shadowSide=A.doubleSided?dt:yg,t.castShadow=A.castShadows?A.castShadows:!1,t.receiveShadow=A.receiveShadows?A.receiveShadows:!1}for(const i of t.children)fw(i,A)}function _E(t,A,e){t[A]===void 0&&console.warn("Field",A,"is undefined on",t);const i=Proxy.revocable(t[A],{set(o,s,C,a){const n=o[s],B=Reflect.set(o,s,C,a);return e(C,n),B}}),g=i.revoke,I=t[A];return i.revoke=()=>{t[A]=I,g()},t[A]=i.proxy,i}const Y_=Symbol("Scheduled action");function cIA(t,A,e=Pi.OnBeforeRender){let i=t[Y_];i||(i=t[Y_]={});const g=A.name;i[e]||(i[e]={});const I=i[e];if(I[g])return;function*o(){A?.call(t),I[g]=null}const s=t.startCoroutine(o(),e);I[g]=s}const ka=iA("debugeventsystem");var JU=(t=>(t.BeforeHandleInput="BeforeHandleInput",t.AfterHandleInput="AfterHandleInput",t))(JU||{});const Ga=class extends JA{constructor(){super(),r(this,"raycaster",[]),r(this,"_handleInputFn"),r(this,"pressedByID",new Map),r(this,"hoveredByID",new Map),r(this,"_sortedHits",[]),r(this,"_testObjectsCache",new Map),r(this,"_currentlyActiveRaycaster",null),r(this,"_currentPointerEventName",null),r(this,"shouldRaycastObject",t=>{var A;let e=null;if(hIA(t)&&(e=(A=t[Zo])==null?void 0:A.gameObject),this._testObjectsCache.has(t)||e&&this._testObjectsCache.has(e))return this._testObjectsCache.get(t)===!1?"continue in children":!0;{let i=FU(t,this._currentPointerEventName);if(!i&&e&&(i=FU(e,this._currentPointerEventName)),i){this._testObjectsCache.set(t,!0);for(const g of t.children)this.shouldRaycastObject_AddToYesCache(g);return!0}return this._testObjectsCache.set(t,!1),"continue in children"}}),r(this,"_sortingBuffer",[]),r(this,"_noDepthTestingResults",[]),r(this,"out",{}),r(this,"_capturedPointer",{}),r(this,"pointerEnterSymbol",Symbol("pointerEnter")),r(this,"pointerExitSymbol",Symbol("pointerExit")),r(this,"currentActiveMeshUIComponents",[]),Ga.systems.push(this)}static createIfNoneExists(t){this.didSearchEventSystem||(this.didSearchEventSystem=!0,Ga.systems.length<=0&&Ga.systems.push(...aA.findObjectsOfType(Ga,t)));for(const e of Ga.systems)if(e.context===t)return;const A=new wA;aA.addNewComponent(A,Ga),t.scene.add(A)}static get systems(){const t=ve.Current;return this._eventSystemMap.has(t)||this._eventSystemMap.set(t,[]),this._eventSystemMap.get(t)}static get(t){const A=this._eventSystemMap.get(t);return A&&A.length>0?A[0]:null}static get instance(){return this.systems[0]}static ensureUpdateMeshUI(t,A,e=!1){_n.update(t,A,e)}static markUIDirty(t){_n.markDirty()}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}onDestroy(){Ga.systems.splice(Ga.systems.indexOf(this),1)}start(){if(this.raycaster.length<=0&&!aA.findObjectOfType(gd,this.context)){const t=aA.addNewComponent(this.context.scene,ro);this.raycaster.push(t),(Se()||ka)&&console.warn("Added an ObjectRaycaster to the scene because no raycaster was found.")}}register(t){var A;t&&this.raycaster&&!this.raycaster.includes(t)&&((A=this.raycaster)==null||A.push(t))}unregister(t){var A,e;const i=(A=this.raycaster)==null?void 0:A.indexOf(t);i!==void 0&&i!==-1&&((e=this.raycaster)==null||e.splice(i,1))}onEnable(){this._handleInputFn??(this._handleInputFn=this.onPointerEvent.bind(this)),this.context.input.addEventListener(Ai.PointerDown,this._handleInputFn),this.context.input.addEventListener(Ai.PointerUp,this._handleInputFn),this.context.input.addEventListener(Ai.PointerMove,this._handleInputFn)}onDisable(){this.context.input.removeEventListener(Ai.PointerDown,this._handleInputFn),this.context.input.removeEventListener(Ai.PointerUp,this._handleInputFn),this.context.input.removeEventListener(Ai.PointerMove,this._handleInputFn)}onBeforeRender(){this.resetMeshUIStates()}onPointerEvent(t){if(t===void 0||t.propagationStopped)return;const A=new vh(this.context.input,t);this._currentPointerEventName=t.type,A.inputSource=this.context.input,A.isClick=t.isClick,A.isDoubleClick=t.isDoubleClick,A.isDown=t.type==Ai.PointerDown,A.isUp=t.type==Ai.PointerUp,A.isPressed=this.context.input.getPointerPressed(t.pointerId),ka&&(A.isDown?console.log("DOWN",A.pointerId):A.isUp&&console.log("UP",A.pointerId),A.isClick&&console.log("CLICK",A.pointerId));const e=new Oo;t.ray?e.ray=t.ray:e.screenPoint=this.context.input.getPointerPositionRC(t.pointerId);const i=this.performRaycast(e);ka&&A.isClick&&wi("EventSystem: "+A.pointerId+" - "+this.context.time.frame+" - Up:"+A.isUp+", Down:"+A.isDown);const g={sender:this,args:A,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:g})),this.handleIntersections(i,A),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:g}))}shouldRaycastObject_AddToYesCache(t){this._testObjectsCache.set(t,!0);for(const A of t.children)this.shouldRaycastObject_AddToYesCache(A)}performRaycast(t){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,t||(t=new Oo),t.testObject=this.shouldRaycastObject;for(const A of this.raycaster){if(!A.activeAndEnabled)continue;this._currentlyActiveRaycaster=A;const e=A.performRaycast(t);this._currentlyActiveRaycaster=null,e&&e.length>0&&this._sortedHits.push(...e)}return this._sortedHits.sort((A,e)=>A.distance-e.distance),this._sortedHits}assignHitInformation(t,A){A?(t.point=A.point,t.normal=A.normal,t.face=A.face,t.distance=A.distance,t.instanceId=A.instanceId):(t.point=void 0,t.normal=void 0,t.face=void 0,t.distance=void 0,t.instanceId=void 0)}handleIntersections(t,A){var e;if(t!=null&&t.length){t=this.sortCandidates(t);for(const g of t){if(A.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(A,g),this.handleEventOnObject(g.object,A))return!0}}this.assignHitInformation(A,t?.[0]),this.invokePointerCapture(A);const i=this.hoveredByID.get(A.pointerId);return i&&this.propagatePointerExit(i.obj,i.data,null),this.hoveredByID.delete(A.pointerId),A.isUp&&((e=this.pressedByID.get(A.pointerId))==null||e.handlers.forEach(g=>this.invokeOnPointerUp(A,g)),this.pressedByID.delete(A.pointerId)),!1}sortCandidates(t){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let A=0;A<t.length;A++){const e=t[A],i=e.object;if(i.material&&i.material.depthTest===!1){this._noDepthTestingResults.push(e);continue}this._sortingBuffer.push(e)}for(const A of this._sortingBuffer)this._noDepthTestingResults.push(A);return this._noDepthTestingResults}handleEventOnObject(t,A){if(!this.testIsVisible(t))return A.isClick&&ka&&console.log("not allowed",t),!1;if(A.pointerId===void 0)return ka&&console.error("Event without pointer can't be handled",A),!1;A.object=t;const e=t.parent;let i=!1;const g=A.isClick??!1;let I=null;if(e&&e.isUI){const a=(A.isPressed||A.isClick)??!1;if(e[Zo]){const n=e[Zo].gameObject;if(n){if(!Sw.isInteractable(n,this.out))return!1;I=this.out.canvasGroup??null,this.handleMeshUIIntersection(t,a),t=n,i=!0}}if(!i&&this.handleMeshUiObjectWithoutShadowDom(e,a))return!0}g&&ka&&console.log(this.context.time.frame,t);const o=this.hoveredByID.get(A.pointerId),s=o?.obj;s!==t&&s&&this.propagatePointerExit(s,o.data,t);const C=this.hoveredByID.get(A.pointerId);if(C?(C.obj=t,C.data=A):this.hoveredByID.set(A.pointerId,{obj:t,data:A}),A.isDown){const a=this.pressedByID.get(A.pointerId);a?(a.obj=t,a.data=A):this.pressedByID.set(A.pointerId,{obj:t,data:A,handlers:new Set})}return(I===null||I.interactable)&&this.handleMainInteraction(t,A,s??null),!0}propagate(t,A){for(;t;)aA.foreachComponent(t,e=>{A(e)},!1),t=t.parent}handleMainInteraction(t,A,e){const i=this.pressedByID.get(A.pointerId),g=e!==t;let I=!0;switch(A.event.pointerType){case"mouse":case"touch":const o=this.context.input.getPointerPositionLastFrame(A.pointerId),s=this.context.input.getPointerPosition(A.pointerId);I=o&&!Ie.approximately(o,s);break}this.propagate(t,o=>{const s=o;s.interactable!==!1&&(!s.activeAndEnabled||!s.enabled||(s.onPointerEnter&&g&&this.handlePointerEnter(s,A),A.isDown&&s.onPointerDown&&(s.onPointerDown(A),i?.handlers.add(s),this.handlePointerCapture(A,s)),s.onPointerMove&&(I&&s.onPointerMove(A),this.handlePointerCapture(A,s)),A.isUp&&s.onPointerUp&&(this.invokeOnPointerUp(A,s),i?.handlers.delete(s)),A.isClick&&s.onPointerClick&&s.onPointerClick(A)))}),A.isUp&&(i?.handlers.forEach(o=>{this.invokeOnPointerUp(A,o)}),this.pressedByID.delete(A.pointerId))}propagatePointerExit(t,A,e){this.propagate(t,i=>{if(!i.gameObject||i.destroyed)return;const g=i;if(g.onPointerExit){if(e&&this.isChild(e,i.gameObject))return;this.handlePointerExit(g,A)}})}invokeOnPointerUp(t,A){var e;(e=A.onPointerUp)==null||e.call(A,t),this.releasePointerCapture(t,A)}handlePointerEnter(t,A){t.onPointerEnter&&this.updatePointerState(t,A.pointerId,this.pointerEnterSymbol,!0)&&t.onPointerEnter(A),this.updatePointerState(t,A.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(t,A){t.onPointerExit&&this.updatePointerState(t,A.pointerId,this.pointerExitSymbol,!0)&&t.onPointerExit(A),this.updatePointerState(t,A.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(t,A,e,i){let g=t[e];if(i)return g&&g.includes(A)?!1:(g=g||[],g.push(A),t[e]=g,!0);{if(!g||!g.includes(A))return!1;const I=g.indexOf(A);return I!==-1&&g.splice(I,1),!0}}handlePointerCapture(t,A){if(t.z__pointer_ctured){t.z__pointer_ctured=!1;const e=t.pointerId;if(A.onPointerMove){const i=this._capturedPointer[e]||[];i.push(A),this._capturedPointer[e]=i}else Se()&&!A.z__warned_no_pointermove&&(A.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 t.z__pointer_cture_rleased&&(t.z__pointer_cture_rleased=!1,this.releasePointerCapture(t,A))}releasePointerCapture(t,A){const e=t.pointerId;if(this._capturedPointer[e]){const i=this._capturedPointer[e].indexOf(A);i!==-1&&(this._capturedPointer[e].splice(i,1),ka&&console.log("released pointer capture",e,A,this._capturedPointer))}}invokePointerCapture(t){var A;if(t.event.type===Ai.PointerMove){const e=t.pointerId,i=this._capturedPointer[e];if(i){ka&&console.log("Captured",e,i);for(let g=0;g<i.length;g++){const I=i[g];if(I.destroyed){i.splice(g,1),g--;continue}(A=I.onPointerMove)==null||A.call(I,t)}}}}isChild(t,A){return!t||!A?!1:t===A?!0:t.parent?this.isChild(t.parent,A):!1}handleMeshUiObjectWithoutShadowDom(t,A){return!t||!t.isUI?!0:this.handleMeshUIIntersection(t,A)}handleMeshUIIntersection(t,A){const e=_n.updateState(t,A);return e&&this.currentActiveMeshUIComponents.push(e),e!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&_n.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let t=0;t<this.currentActiveMeshUIComponents.length;t++){const A=this.currentActiveMeshUIComponents[t];_n.resetState(A)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(t){return t?aA.isActiveSelf(t)?this.testIsVisible(t.parent):!1:!0}};let zo=Ga;r(zo,"_eventSystemMap",new Map),r(zo,"didSearchEventSystem",!1);class _n{static markDirty(){this.needsUpdate=!0}static update(A,e,i=!1){if(i){A.update();return}const g=e.time.frameCount;for(const I of this.lastUpdateFrame)if(I.context===e){if(g===I.frame)return;I.frame=g;let o=this.needsUpdate||g<1;I.nextUpdate===e.time.frameCount&&(o=!0),o&&(ka&&console.log("Update threemeshui"),this.needsUpdate=!1,A.update());return}this.lastUpdateFrame=[{context:e,frame:g,nextUpdate:g}],A.update()}static updateState(A,e){let i=null;if(A&&(i=this.findBlockInParent(A),i&&i!==this.lastSelected)){if(i.interactable===!1)return null;this.needsUpdate=!0}return i}static resetLastSelected(){const A=this.lastSelected;A&&(this.lastSelected=null,this.resetState(A))}static resetState(A){A&&(this.needsUpdate=!0)}static findBlockInParent(A){return A?A.isBlock?A:this.findBlockInParent(A.parent):null}}r(_n,"lastSelected",null),r(_n,"lastUpdateFrame",[]),r(_n,"needsUpdate",!1);var lIA=Object.defineProperty,dIA=Object.getOwnPropertyDescriptor,vg=(t,A,e,i)=>{for(var g=i>1?void 0:i?dIA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&lIA(A,e,g),g};const uIA=iA("debugorbit"),mw=iA("freecam"),od=iA("debugcamerafit"),kw=iA("smoothcam"),pIA={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let vU;class sd extends CustomEvent{constructor(A,e){super("target-reached",{detail:{controls:A,type:e}})}}class jt extends JA{constructor(){super(...arguments),r(this,"autoFit",!1),r(this,"enableRotate",!0),r(this,"autoRotate",!1),r(this,"autoRotateSpeed",1),r(this,"enableKeys",!0),r(this,"enableDamping",!0),r(this,"dampingFactor",.1),r(this,"enableZoom",!0),r(this,"minZoom",0),r(this,"maxZoom",1/0),r(this,"enablePan",!0),r(this,"lookAtConstraint",null),r(this,"lookAtConstraint01",1),r(this,"allowInterrupt",!0),r(this,"middleClickToFocus",!0),r(this,"doubleClickToFocus",!0),r(this,"useSlerp",!0),r(this,"debugLog",!1),r(this,"targetLerpDuration",1),r(this,"autoTarget",!0),r(this,"_controls",null),r(this,"_cameraObject",null),r(this,"_lookTargetLerpActive",!1),r(this,"_lookTargetStartPosition",new w),r(this,"_lookTargetEndPosition",new w),r(this,"_lookTargetLerp01",0),r(this,"_lookTargetLerpDuration",0),r(this,"_cameraLerpActive",!1),r(this,"_cameraStartPosition",new w),r(this,"_cameraEndPosition",new w),r(this,"_cameraLerp01",0),r(this,"_cameraLerpDuration",0),r(this,"_inputs",0),r(this,"_enableTime",0),r(this,"_startedListeningToKeyEvents",!1),r(this,"_eventSystem"),r(this,"_afterHandleInputFn"),r(this,"_camera",null),r(this,"_syncedTransform"),r(this,"_didStart",!1),r(this,"targetElement",null),r(this,"onControlsChangeStarted",()=>{this._syncedTransform&&this._syncedTransform.requestOwnership()}),r(this,"_shouldDisable",!1),r(this,"_haveAttachedKeyboardEvents",!1)}get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(A){var e;(e=this.controls)==null||e.addEventListener("start",A)}get targetLerpSpeed(){return 5}set targetLerpSpeed(A){this.targetLerpDuration=1/A}awake(){this._didStart=!1,this._startedListeningToKeyEvents=!1}start(){if(this._didStart=!0,this.autoTarget&&this._controls){const A=aA.getComponent(this.gameObject,Wt);if(A&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const e=Ne(A.cam).length(),i=new w(0,0,-e).applyMatrix4(A.cam.matrixWorld);this.setLookTargetPosition(i,!0)}if(this.autoTarget&&!this.setLookTargetFromConstraint()){const e=new Oo;e.screenPoint=new tA(0,0),e.lineThreshold=.1;const i=this.context.physics.raycast(e);i.length>0&&this.setLookTargetPosition(i[0].point,!0),od&&console.log("OrbitControls hits",...i)}this.autoFit&&this.fitCamera()}this._eventSystem=zo.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(JU.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){var A,e;(A=this._controls)==null||A.dispose(),(e=this._eventSystem)==null||e.removeEventListener(JU.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._enableTime=this.context.time.time;const A=aA.getComponent(this.gameObject,Wt);this._camera=A;const e=A?.cam;if(e&&v_(e,this,!0),!this._controls){if(!e){console.warn("OrbitControls: Requires a Camera component on the same object as this component.");return}e&&(this._cameraObject=e);const i=this.targetElement??this.context.renderer.domElement,g=e?.quaternion.clone();this._controls=new zgA(e,i),e?.quaternion.copy(g),vU===void 0&&(vU={...this._controls.keys})}this._controls&&(mw&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,$s()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),e?.type==="PerspectiveCamera"?mw||(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):mw||(this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom),this._startedListeningToKeyEvents||(this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(window.document.body))),this._syncedTransform=aA.getComponent(this.gameObject,Hn)??void 0}onDisable(){var A;(A=this._camera)!=null&&A.cam&&v_(this._camera.cam,this,!1),this._controls&&(this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted))}afterHandleInput(A){A.detail.args.pointerId===0&&(A.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!A.detail.args.isPressed||A.detail.args.isUp)&&(this._shouldDisable=!1))}onBeforeRender(){var A,e;if(!this._controls||this._cameraObject!==this.context.mainCamera)return;(this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2)||this.context.input.mouseWheelChanged||this.context.input.getPointerPressed(0)&&(A=this.context.input.getPointerPositionDelta(0))!=null&&A.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 i=this.middleClickToFocus&&this.context.input.getPointerClicked(1);if(i||(i=this.doubleClickToFocus&&this.context.input.getPointerDoubleClicked(0)&&this.context.time.time-this._enableTime>.3),i&&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 sd(this,"camera"));else{const g=Ie.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,g)}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 sd(this,"lookat"));else{const g=Ie.easeInOutCubic(this._lookTargetLerp01);this._controls.target.lerpVectors(this._lookTargetStartPosition,this._lookTargetEndPosition,g)}}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?vU:pIA,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,typeof kw=="number"||kw===!0){this._controls.enableDamping=!0;const g=typeof kw=="number"?kw:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,g))}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||(!mw&&(e=this.lookAtConstraint)!=null&&e.locked&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(),uIA&&Fe.DrawWireSphere(this._controls.target,.1,65280))}}setCameraAndLookTarget(A){if(!A||!(A instanceof wA))return;const e=Ne(A),i=cR(A);this.setTargetFromRaycast(new to(e,i)),this.setCameraTargetPosition(e)}setCameraTargetPosition(A,e=!1){var i,g;A&&(A instanceof wA&&(A=Ne(A)),this._cameraEndPosition||(this._cameraEndPosition=new w),this._cameraEndPosition.copy(A),e===!0?(this._cameraLerpActive=!1,(i=this.controllerObject)==null||i.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy((g=this._cameraObject)==null?void 0:g.position),typeof e=="number"?this._cameraLerpDuration=e:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setLookTargetPosition(A=null,e=!1){this._controls&&A&&(A instanceof wA&&(A=Ne(A)),this._lookTargetEndPosition.copy(A),e===!0?this._controls.target.copy(this._lookTargetEndPosition):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof e=="number"?this._lookTargetLerpDuration=e:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(A=0,e=1){var i;if(!this._controls)return!1;const g=(i=this.lookAtConstraint)==null?void 0:i.sources;if(g&&g.length>0){const I=g[A];if(I)return I.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._lookTargetEndPosition,e),!0}return!1}lerpTarget(A,e){return this.lerpLookTarget(A,e)}lerpLookTarget(A,e){this._controls&&(e>=1?this._controls.target.copy(A):this._controls.target.lerp(A,e))}setTargetFromRaycast(A){var e,i;if(!this.controls)return;const g=A?this.context.physics.raycastFromRay(A):this.context.physics.raycast();for(const I of g)if(I.distance>0&&aA.isActiveInHierarchy(I.object)){const o=KU(I.object);if(o){const s=o.canvas;if(s!=null&&s.screenspace)break}if(this.setLookTargetPosition(I.point),this.context.mainCamera){const s=Ne(this.context.mainCamera).clone().sub(this.controls.target).add(this._lookTargetEndPosition);(i=(e=this._cameraObject)==null?void 0:e.parent)==null||i.worldToLocal(s),this.setCameraTargetPosition(s)}break}}fitCamera(A,e=1.1,i=!0){const g=this._cameraObject,I=this._controls;if(A!=null&&A.length||(A=this.context.scene.children),A.length<=0||!g||!I)return;const o=new w,s=new w,C=new Ft;C.makeEmpty();const a=[];function n(l){let p=!0;if(l.visible&&$gA(l)!==!1&&!(l.type==="TransformControlsGizmo"||l.type==="TransformControlsPlane")&&(l instanceof bk&&(p=!1),l instanceof wD&&(p=!1),l instanceof J_&&(p=!1),l.material instanceof nD&&(p=!1),l instanceof DA||(p=!1),l!==g&&l.isUI!==!0)){if(p){od&&console.log(l.name,l.type,l);const D=l.children;l.children=a;const S=l.position,k=l.scale;if(Number.isNaN(S.x)||Number.isNaN(S.y)||Number.isNaN(S.z)){console.warn(`Object "${l.name}" has NaN values in position or scale.... will ignore it`,S,k);return}C.expandByObject(l,!0),l.children=D}for(const D of l.children)n(D)}}for(const l of A)l.updateMatrixWorld(),n(l);if(g.updateMatrixWorld(),g.updateProjectionMatrix(),C.getCenter(s),C.applyMatrix4(g.matrixWorldInverse),C.getSize(o),C.setFromCenterAndSize(s,o),Number.isNaN(o.x)||Number.isNaN(o.y)||Number.isNaN(o.z)){console.warn("Camera fit size resultet in NaN",g,C,[...A]);return}if(o.length()<=1e-10){od&&console.warn("Camera fit size is zero",C,[...A]);return}const B=g.fov,Q=2*Math.atan(Math.tan(B*Math.PI/360/2)*g.aspect)/Math.PI*360,E=o.y/(2*Math.atan(Math.PI*B/360)),h=o.x/(2*Math.atan(Math.PI*Q/360)),d=e*Math.max(E,h)+o.z/2;od&&console.log("Fit camera to objects",E,h,"distance",d);const u=Ne(g),c=I.target.clone().sub(u).normalize().multiplyScalar(d);if(I.maxDistance=d*10,I.minDistance=d*.01,this.setLookTargetPosition(s,i),this.autoTarget=!1,g.near=d/1e3,g.far=d*100,g.updateMatrixWorld(),g.updateProjectionMatrix(),g.parent){const l=g.parent.worldToLocal(I.target.clone().sub(c));this.setCameraTargetPosition(l,i)}else console.error(`Can not fit camera ${g.name} because it has no parent`);if(od){const l=new bk(C);this.context.scene.add(l),uR(l,Ml(g)),this._haveAttachedKeyboardEvents||(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",p=>{p.code==="KeyF"&&this.fitCamera(A)}))}I.update()}}vg([y()],jt.prototype,"autoFit",2),vg([y()],jt.prototype,"enableRotate",2),vg([y()],jt.prototype,"autoRotate",2),vg([y()],jt.prototype,"autoRotateSpeed",2),vg([y()],jt.prototype,"enableKeys",2),vg([y()],jt.prototype,"enableDamping",2),vg([y()],jt.prototype,"dampingFactor",2),vg([y()],jt.prototype,"enableZoom",2),vg([y()],jt.prototype,"minZoom",2),vg([y()],jt.prototype,"maxZoom",2),vg([y()],jt.prototype,"enablePan",2),vg([y(Ad)],jt.prototype,"lookAtConstraint",2),vg([y()],jt.prototype,"lookAtConstraint01",2),vg([y()],jt.prototype,"allowInterrupt",2),vg([y()],jt.prototype,"middleClickToFocus",2),vg([y()],jt.prototype,"doubleClickToFocus",2),vg([y()],jt.prototype,"targetLerpDuration",2);var DIA=Object.defineProperty,yIA=Object.getOwnPropertyDescriptor,Bo=(t,A,e,i)=>{for(var g=i>1?void 0:i?yIA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&DIA(A,e,g),g},mB=(t=>(t[t.Skybox=1]="Skybox",t[t.SolidColor=2]="SolidColor",t[t.Uninitialized=4]="Uninitialized",t))(mB||{});const kB=iA("debugcam"),T_=iA("debugscreenpointtoray");var Gw;const Cd=(Gw=class extends JA{constructor(){super(...arguments),r(this,"_nearClipPlane",.1),r(this,"_farClipPlane",1e3),r(this,"orthographic",!1),r(this,"orthographicSize",5),r(this,"ARBackgroundAlpha",0),r(this,"_cullingMask",4294967295),r(this,"_backgroundBlurriness"),r(this,"_backgroundIntensity"),r(this,"_environmentIntensity"),r(this,"_targetTexture",null),r(this,"_backgroundColor"),r(this,"_fov"),r(this,"_cam",null),r(this,"_clearFlags",2),r(this,"_skybox")}get isCamera(){return!0}get aspect(){return this._cam instanceof Pe?this._cam.aspect:this.context.domWidth/this.context.domHeight}get fieldOfView(){return this._cam instanceof Pe?this._cam.fov:this._fov}set fieldOfView(t){const A=this.fieldOfView!=t;if(this._fov=t,A&&this._cam&&this._cam instanceof Pe){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(t){const A=this._nearClipPlane!=t;this._nearClipPlane=t,this._cam&&A&&(this._cam.near=t,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(t){const A=this._farClipPlane!=t;this._farClipPlane=t,this._cam&&A&&(this._cam.far=t,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(t){t!==this._clearFlags&&(this._clearFlags=t,this.applyClearFlagsIfIsActiveCamera())}set cullingMask(t){this._cullingMask=t,this._cam&&(this._cam.layers.mask=t)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}set cullingLayer(t){this.cullingMask=(1<<t|0)>>>0}set backgroundBlurriness(t){t!==this._backgroundBlurriness&&(t===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(t,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}set backgroundIntensity(t){t!==this._backgroundIntensity&&(t===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(t,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}set environmentIntensity(t){this._environmentIntensity=t}get environmentIntensity(){return this._environmentIntensity}get backgroundColor(){return this._backgroundColor??null}set backgroundColor(t){if(t){if(this._backgroundColor)this._backgroundColor.copy(t);else{if(!t.clone)return;this._backgroundColor=t.clone()}t.alpha===void 0&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera()}}set targetTexture(t){this._targetTexture=t}get targetTexture(){return this._targetTexture}get cam(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(t,A,e){const i=this.cam,g=Cd._origin;g.set(t,A,-1),this.context.input.convertScreenspaceToRaycastSpace(g),T_&&console.log("screenPointToRay",t.toFixed(2),A.toFixed(2),"now:",g.x.toFixed(2),g.y.toFixed(2),"isInXR:"+this.context.isInXR),g.z=-1,g.unproject(i);const I=Cd._direction.set(g.x,g.y,g.z),o=Ne(i);return I.sub(o),I.normalize(),e?(e.set(o,I),e):new to(o.clone(),I.clone())}awake(){T_&&window.addEventListener("pointerdown",t=>{const A=t.clientX,e=t.clientY;console.log("touch",A.toFixed(2),e.toFixed(2));const i=this.screenPointToRay(A,e),g="#"+Math.floor(Math.random()*16777215).toString(16);Fe.DrawRay(i.origin,i.direction,g,10)})}onEnable(){kB&&console.log(`Camera enabled: "${this.name}". ClearFlags=${mB[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),SIA(this)),this.applyClearFlagsIfIsActiveCamera()}onDisable(){this.context.removeCamera(this)}onBeforeRender(){if(this._cam&&(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 t=this.context.renderer;if(t){const A=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,t),A?.applyClearFlags()}}}buildCamera(){if(this._cam)return;const t=this.gameObject.isCamera;let A=null;if(t?(A=this.gameObject,A?.layers.enableAll(),A instanceof Pe&&(this._fov=A.fov)):A=this.gameObject.children[0],A&&A.isCamera)A instanceof Pe&&(this._fov&&(A.fov=this._fov),A.near=this._nearClipPlane,A.far=this._farClipPlane,A.updateProjectionMatrix());else if(!this.orthographic)A=new Pe(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(A.fov=this.fieldOfView),this.gameObject.add(A);else{const e=this.orthographicSize*100;A=new ZC(window.innerWidth/-e,window.innerWidth/e,window.innerHeight/e,window.innerHeight/-e,this._nearClipPlane,this._farClipPlane),this.gameObject.add(A)}this._cam=A,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(){this.context.mainCameraComponent===this&&this.applyClearFlags()}applyClearFlags(){if(!this._cam){kB&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this._fov,kB){const t=`Camera "${this.name}" clear flags: ${mB[this._clearFlags]}`;console.log(t)}switch(this._clearFlags){case 1:if(Cd.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),this._backgroundIntensity!==void 0&&(this.context.scene.backgroundIntensity=this._backgroundIntensity);break;case 2:if(this._backgroundColor){let t=this._backgroundColor.alpha;Cd.backgroundShouldBeTransparent(this.context)&&(t=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.renderer.setClearColor(this._backgroundColor,t)}else kB&&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 wIA(this)),this._skybox.enable()}static backgroundShouldBeTransparent(t){var A,e,i,g;const I=(A=t.renderer.xr)==null?void 0:A.getSession();if(!I)return!1;if(typeof I._transparent=="boolean")return I._transparent;const o=I.environmentBlendMode;kB&&wi("Environment blend mode: "+o+" on "+navigator.userAgent);let s=o==="additive"||o==="alpha-blend";return t.isInAR&&o==="opaque"&&((e=navigator.userAgent)!=null&&e.includes("OculusBrowser")||(i=navigator.userAgent)!=null&&i.includes("Mozilla")&&(g=navigator.userAgent)!=null&&g.includes("Mobile WebXRViewer/v2"))&&(s=!0),I._transparent=s,s}},r(Gw,"_origin",new w),r(Gw,"_direction",new w),Gw);let Wt=Cd;Bo([y()],Wt.prototype,"fieldOfView",1),Bo([y()],Wt.prototype,"nearClipPlane",1),Bo([y()],Wt.prototype,"farClipPlane",1),Bo([y()],Wt.prototype,"clearFlags",1),Bo([y()],Wt.prototype,"orthographic",2),Bo([y()],Wt.prototype,"orthographicSize",2),Bo([y()],Wt.prototype,"ARBackgroundAlpha",2),Bo([y()],Wt.prototype,"cullingMask",1),Bo([y()],Wt.prototype,"backgroundBlurriness",1),Bo([y()],Wt.prototype,"backgroundIntensity",1),Bo([y()],Wt.prototype,"environmentIntensity",1),Bo([y(Mt)],Wt.prototype,"backgroundColor",1),Bo([y(KE)],Wt.prototype,"targetTexture",1);class wIA{constructor(A){r(this,"_camera"),r(this,"_skybox"),this._camera=A}get context(){var A;return(A=this._camera)==null?void 0:A.context}enable(){this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),this._skybox?this.context.scene.background!==this._skybox&&(kB&&console.log(`Camera "${this._camera.name}" set skybox`,this._camera,this._skybox),this._skybox.colorSpace=_e,this._skybox.mapping=Ro,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)),(kB||Se())&&Ci(`Camera "${this._camera.name}" has no skybox texture`))}}function SIA(t){iA("freecam")&&t.context.mainCameraComponent===t&&aA.getOrAddComponent(t.gameObject,jt)}class On extends JA{constructor(){super(...arguments),r(this,"_listener",null)}get listener(){return this._listener==null&&(this._listener=new Zb),this._listener}awake(){fi.registerWaitForAllowAudio(()=>{if(this.destroyed)return;const A=this.listener;if(A==null||A.parent)return;const e=this.context.mainCameraComponent||aA.getComponentInParent(this.gameObject,Wt);e!=null&&e.cam?e.cam.add(A):this.gameObject.add(A)})}}var fIA=Object.defineProperty,mIA=Object.getOwnPropertyDescriptor,Mw=(t,A,e,i)=>{for(var g=i>1?void 0:i?mIA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&fIA(A,e,g),g};const kIA=iA("debugsignals");class ad{constructor(){r(this,"guid")}}Mw([y()],ad.prototype,"guid",2);class OE{constructor(){r(this,"signal"),r(this,"reaction")}}Mw([y(ad)],OE.prototype,"signal",2),Mw([y(Eg)],OE.prototype,"reaction",2);var bU;const Ma=(bU=class extends JA{constructor(){super(...arguments),r(this,"events")}static invoke(t){if(Ma.receivers[t]){const A=Ma.receivers[t];if(!A)return;for(const e of A)e.invoke(t)}}awake(){kIA&&console.log("SignalReceiver awake",this)}onEnable(){if(this.events)for(const t of this.events)Ma.receivers[t.signal.guid]||(Ma.receivers[t.signal.guid]=[]),Ma.receivers[t.signal.guid].push(this)}onDisable(){if(this.events){for(const t of this.events)if(Ma.receivers[t.signal.guid]){const A=Ma.receivers[t.signal.guid].indexOf(this);A>=0&&Ma.receivers[t.signal.guid].splice(A,1)}}}invoke(t){if(!this.events||!Array.isArray(this.events))return;const A=typeof t=="object"?t.guid:t;for(const e of this.events)if(e.signal.guid===A)try{if(e.reaction){if(!e.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",e,this);continue}}else{console.warn("Missing reaction for signal",e,this);continue}e.reaction.invoke()}catch(i){console.error(i)}}},r(bU,"receivers",{}),bU);let PE=Ma;Mw([y(OE)],PE.prototype,"events",2);var Qo=(t=>(t.Activation="ActivationTrack",t.Animation="AnimationTrack",t.Audio="AudioTrack",t.Control="ControlTrack",t.Marker="MarkerTrack",t.Signal="SignalTrack",t))(Qo||{}),BC=(t=>(t[t.None=0]="None",t[t.Hold=1]="Hold",t[t.Loop=2]="Loop",t[t.PingPong=3]="PingPong",t[t.Continue=4]="Continue",t))(BC||{}),qU=(t=>(t.Signal="SignalEmitter",t))(qU||{});const QC=iA("debugtimeline");class nd{constructor(){r(this,"director"),r(this,"track")}get muted(){return this.track.muted}set muted(A){var e;A!==this.track.muted&&(this.track.muted=A,(e=this.onMuteChanged)==null||e.call(this))}*forEachClip(A=!1){var e;if((e=this.track)!=null&&e.clips)if(A)for(let i=this.track.clips.length-1;i>=0;i--)yield this.track.clips[i];else for(const i of this.track.clips)yield i}getClipTime(A,e){return e.clipIn+(A-e.start)*e.timeScale}getClipTimeNormalized(A,e){return(A-e.start)/e.duration}evaluateWeight(A,e,i,g=!0){if(e<0||e>=i.length)return 0;const I=i[e];if(g||A>=I.start&&A<=I.end){let o=1;const s=!1;if(I.easeInDuration>0){const C=Math.min((A-I.start)/I.easeInDuration,1);o*=C}if(I.easeOutDuration>0&&!s){const C=Math.min((I.end-A)/I.easeOutDuration,1);o*=C}return o}return 0}}class GIA{constructor(A){r(this,"clip"),r(this,"rootPositionOffset"),r(this,"rootQuaternionOffset"),r(this,"rootStartPosition"),r(this,"rootEndPosition"),r(this,"rootStartQuaternion"),r(this,"rootEndQuaternion");const e=A.getClip();this.clip=e;const i=A.getRoot(),g=i.name+".position",I=i.name+".quaternion";QC&&console.log(e.name,e.tracks,g);for(const o of e.tracks)if(!(o.times.length<=0)){if(o.name.endsWith(g))this.rootStartPosition=new w().fromArray(o.values,0),this.rootEndPosition=new w().fromArray(o.values,o.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),QC&&console.log(this.rootPositionOffset);else if(o.name.endsWith(I)&&(this.rootStartQuaternion=new FA().fromArray(o.values,0),this.rootEndQuaternion=new FA().fromArray(o.values,o.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),QC)){const s=new Wg().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",s)}}}get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}}class Rw extends nd{constructor(){super(...arguments),r(this,"models",[]),r(this,"trackOffset"),r(this,"target"),r(this,"mixer"),r(this,"clips",[]),r(this,"actions",[]),r(this,"_actionOffsets",[]),r(this,"_didBind",!1),r(this,"_animator",null),r(this,"_useclipOffsets",!0),r(this,"_totalOffsetPosition",new w),r(this,"_totalOffsetRotation",new FA),r(this,"_totalOffsetPosition2",new w),r(this,"_totalOffsetRotation2",new FA),r(this,"_summedPos",new w),r(this,"_tempPos",new w),r(this,"_summedRot",new FA),r(this,"_tempRot",new FA),r(this,"_clipRotQuat",new FA)}onStateChanged(){this._animator&&H_(this._animator.gameObject,this,this.director.isPlaying)}createHooks(A,e){var i,g;if(((i=e.tracks)==null?void 0:i.length)<=0){console.warn("No tracks in AnimationClip",e);return}const I=e.tracks[0].name.split("."),o=I[I.length-2],s=o+".position",C=o+".quaternion";let a=!1,n=!1;for(const B of e.tracks)B.name.endsWith(s)?(a=!0,this.createPositionInterpolant(e,A,B)):B.name.endsWith(C)&&(n=!0,this.createRotationInterpolant(e,A,B));if(!a||!n){const B=(g=this.mixer)==null?void 0:g.getRoot(),Q=e.tracks[0],E=Q.name.lastIndexOf("."),h=Q.name.substring(0,E),d=h.substring(h.lastIndexOf(".")+1),u=B.getObjectByName(d);if(u)if(a){if(!n){const c=e.tracks[0].name.substring(0,E)+".quaternion";QC&&console.warn("Create quaternion track",d,u);const l=u.quaternion,p=new zs(c,[0,e.duration],[l.x,l.y,l.z,l.w,l.x,l.y,l.z,l.w]);e.tracks.push(p),this.createRotationInterpolant(e,A,p)}}else{const c=h+".position";QC&&console.warn("Create position track",d,u);const l=u.position,p=new XC(c,[0,e.duration],[l.x,l.y,l.z,l.x,l.y,l.z]);e.tracks.push(p),this.createPositionInterpolant(e,A,p)}}}bind(){if(!this._didBind){this._didBind=!0,QC&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(const A of this.actions){const e=new GIA(A);this._actionOffsets.push(e)}this.target&&(this._animator=aA.getComponent(this.target,bg)??null,this._animator&&H_(this._animator.gameObject,this,!0));for(const A of this.models){const e=A.asset,i=e.position,g=e.rotation;i&&i.x!==void 0&&(i.isVector3||(e.position=new w(i.x,i.y,i.z)),g.isQuaternion||(e.rotation=new FA(g.x,g.y,g.z,g.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){const A=this.trackOffset.position;A&&(A.isVector3||(this.trackOffset.position=new w(A.x,A.y,A.z)));const e=this.trackOffset.rotation;e&&(e.isQuaternion||(this.trackOffset.rotation=new FA(e.x,e.y,e.z,e.w)))}}evaluate(A){var e,i,g,I,o,s,C;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 a=0,n=0,B=!1,Q=!1,E=0;for(let h=0;h<this.clips.length;h++){const d=this.models[h],u=this.actions[h],c=d.asset;u.weight=0;const l=A>=d.start&&A<=d.end,p=d.preExtrapolationMode,D=d.postExtrapolationMode,S=h<this.clips.length-1?this.models[h+1]:null;let k=l,f=!1;if(!k&&!B&&d.end<A&&D!==BC.None?(!S||S.start>A)&&(k=!0,B=!0):h==0&&!k&&!Q&&d.start>A&&p!==BC.None&&(!S||S.start<A)&&(k=!0,f=!0,Q=!0),k){let U=1;U*=this.evaluateWeight(A,h,this.models,k),U*=this.director.weight;let M=l;if(f)switch(p){case BC.Hold:break;case BC.Loop:A+=d.start,M=!0;break;default:A+=d.start,M=!0;break}let m=this.getClipTime(A,d),x=0;const L=c.duration;if(f&&p===BC.Hold&&(m=0),M){if(c.loop)for(x+=Math.floor(m/(L+1e-6));m>L;)m-=L}else if(!l&&B)switch(D){case BC.Hold:m=this.getClipTime(d.end,d);break;case BC.Loop:m%=L;break;case BC.PingPong:const Y=Math.floor(m/L)%2!==0;m%=L,Y&&(m=L-m);break}d.reversed===!0?u.time=u.getClip().duration-m:u.time=m,u.timeScale=0;const V=Math.max(0,U);if(u.weight=V,E+=V,u.clampWhenFinished=!1,u.isRunning()||u.play(),this._useclipOffsets){const Y=a==0?this._totalOffsetPosition:this._totalOffsetPosition2,P=a==0?this._totalOffsetRotation:this._totalOffsetRotation2;a<1&&(n=1-U),a+=1;const b=this._summedPos.set(0,0,0),T=this._tempPos.set(0,0,0),_=this._summedRot.identity(),eA=this._tempRot.identity(),$=c.rotation;$&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp($,U));const IA=this._actionOffsets[h];if(IA.hasOffsets)for(let yA=0;yA<x;yA++)IA.rootPositionOffset?T.copy(IA.rootPositionOffset):T.set(0,0,0),T.applyQuaternion(_),this._clipRotQuat&&T.applyQuaternion(this._clipRotQuat),IA.rootQuaternionOffset&&(eA.copy(IA.rootQuaternionOffset),_.multiply(eA)),b.add(T);this._clipRotQuat&&P.multiply(this._clipRotQuat),P.multiply(_),c.position&&b.add(c.position),Y.add(b)}}}if(this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,n),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,n)),this.__mixerError===void 0&&(QC||Se())&&(i=(e=this._animator)==null?void 0:e.runtimeAnimatorController)!=null&&i.mixer&&this.mixer!==((I=(g=this._animator)==null?void 0:g.runtimeAnimatorController)==null?void 0:I.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 h=Math.max(0,1-E);(C=(s=this._animator)==null?void 0:s.runtimeAnimatorController)==null||C.update(h)}else this.mixer.update(A)}createRotationInterpolant(A,e,i){var g;const I=i.createInterpolant.bind(i),o=new FA;this.ensureTrackOffsets();const s=(g=this.trackOffset)==null?void 0:g.rotation;i.createInterpolant=()=>{const C=I(),a=C.evaluate.bind(C);return C.evaluate=n=>{var B;const Q=a(n);if(o.set(Q[0],Q[1],Q[2],Q[3]),o.premultiply(this._totalOffsetRotation),s&&o.premultiply(s),this.director.animationCallbackReceivers)for(const E of this.director.animationCallbackReceivers)(B=E?.onTimelineRotation)==null||B.call(E,this.director,this.target,n,o);return Q[0]=o.x,Q[1]=o.y,Q[2]=o.z,Q[3]=o.w,Q},C}}createPositionInterpolant(A,e,i){var g,I;const o=i.createInterpolant.bind(i),s=new w;this.ensureTrackOffsets();const C=(g=this.trackOffset)==null?void 0:g.rotation,a=(I=this.trackOffset)==null?void 0:I.position;let n;i.createInterpolant=()=>{const B=o(),Q=B.evaluate.bind(B);return B.evaluate=E=>{var h,d,u;const c=Q(E);if(s.set(c[0],c[1],c[2]),e.removeStartOffset&&(n===void 0?(n=null,n=(d=(h=this._actionOffsets.find(l=>l.clip===A))==null?void 0:h.rootStartPosition)==null?void 0:d.clone()):n!=null&&n.isVector3&&s.sub(n)),s.applyQuaternion(this._totalOffsetRotation),s.add(this._totalOffsetPosition),C&&s.applyQuaternion(C),a&&(s.x-=a.x,s.y+=a.y,s.z+=a.z),this.director.animationCallbackReceivers)for(const l of this.director.animationCallbackReceivers)(u=l?.onTimelinePosition)==null||u.call(l,this.director,this.target,E,s);return c[0]=s.x,c[1]=s.y,c[2]=s.z,c},B}}}const MIA=iA("mutetimeline"),rd=class extends nd{constructor(){super(...arguments),r(this,"models",[]),r(this,"listener"),r(this,"audio",[]),r(this,"audioContextTimeOffset",[]),r(this,"lastTime",0),r(this,"audioSource"),r(this,"_audioLoader",null),r(this,"_playableDirectorResumed",!1)}getAudioFilePath(t){const A=this.director.sourceId;return pn(A,t)}onAllowAudioChanged(t){for(let A=0;A<this.models.length;A++){const e=this.models[A];this.audio[A].setVolume(t?e.asset.volume:0)}}addModel(t){const A=new Mk(this.listener);this.audio.push(A);const e=t;e._didTriggerPlay=!1,this.models.push(e)}onDisable(){for(const t of this.audio)t.isPlaying&&t.stop();for(const t of this.models)t._didTriggerPlay=!1}onDestroy(){for(const t of this.audio)t.source&&t?.disconnect();this.audio.length=0}onMuteChanged(){if(this.muted)for(let t=0;t<this.audio.length;t++){const A=this.audio[t];A!=null&&A.isPlaying&&A.stop()}}stop(){for(let t=0;t<this.audio.length;t++){const A=this.audio[t];A!=null&&A.isPlaying&&A.stop()}for(const t of this.models)t._didTriggerPlay=!1}onPauseChanged(){for(let t=0;t<this.audio.length;t++){const A=this.audio[t];A!=null&&A.isPlaying&&A.stop()}this._playableDirectorResumed=this.director.isPlaying}evaluate(t){if(MIA||this.track.muted||this.director.speed<0)return;const A=this.director.context.application.muted,e=this._playableDirectorResumed;this._playableDirectorResumed=!1;const i=A?.1:0;for(let g=0;g<this.models.length;g++){const I=this.models[g],o=this.audio[g],s=I.asset;if((!o||!o.buffer)&&this.isInTimeRange(I,t-1,t+1)&&this.handleAudioLoading(I,o),fi.userInteractionRegistered!==!1&&!(o===null||!o.buffer))if(o.playbackRate=this.director.context.time.timeScale*this.director.speed,o.loop=s.loop,t>=I.start&&t<=I.end&&t<this.director.duration){if(!o.isPlaying||!this.director.isPlaying)(e||!I._didTriggerPlay&&this.lastTime<t)&&(I.duration*I.timeScale>.3?o.offset=I.clipIn+(t-I.start)*I.timeScale:o.offset=0,QC&&console.log("Timeline Audio ("+this.track.name+") play with offset "+o.offset+" - "+I.asset.clip),o.play(i),I._didTriggerPlay=!0);else{const a=I.clipIn+(t-I.start)*I.timeScale,n=o.context.currentTime-o._startedAt+o.offset;Math.abs(a-n)>.3&&(o.offset=a,o.stop(),o.play(i))}let C=s.volume;if(this.track.volume!==void 0&&(C*=this.track.volume),A&&(C=0),I.easeInDuration>0){const a=Math.min((t-I.start)/I.easeInDuration,1);C*=a}if(I.easeOutDuration>0){const a=Math.min((I.end-t)/I.easeOutDuration,1);C*=a}o.setVolume(C*this.director.weight)}else I._didTriggerPlay=!1,this.director.isPlaying&&o.isPlaying&&o.stop()}this.lastTime=t}loadAudio(t,A=0,e=0){let i=null;const g=t-e,I=t+A;for(const o of this.models)if(this.isInTimeRange(o,g,I)){const s=this.audio[this.models.indexOf(o)],C=this.handleAudioLoading(o,s);C!==null&&(i===null&&(i=[]),i.push(C))}return i!==null?Promise.all(i):null}isInTimeRange(t,A,e){return A<=t.start&&e>=t.end||A>=t.start&&A<=t.end||e>=t.start&&e<=t.end}static dispose(){rd._audioBuffers.clear()}handleAudioLoading(t,A){this._audioLoader||(this._audioLoader=new dD);const e=this.getAudioFilePath(t.asset.clip);if(rd._audioBuffers.get(e)){const g=rd._audioBuffers.get(e);return g.then(I=>{I&&A.setBuffer(I)}),g}QC&&console.warn("LOAD audio track",e,this.director.sourceId);const i=new Promise((g,I)=>{this._audioLoader.load(e,o=>{A.setBuffer(o),g(o)},void 0,o=>{console.error("Error loading audio",o),g(null)})});return rd._audioBuffers.set(e,i),i}};let Bd=rd;r(Bd,"_audioBuffers",new Map);class Qd extends nd{constructor(){super(...arguments),r(this,"models",[]),r(this,"didTrigger",[]),r(this,"receivers",[])}evaluate(A){var e;if(this.track.muted)return;const i=this.director.context.time.deltaTime*1.5;for(let g=0;g<this.models.length;g++){const I=this.models[g],o=this.didTrigger[g],s=I.time-A;let C=!1;if(I.retroActive)C=s<=1e-6;else{const a=Math.abs(s);(a===0||a>=1e-5&&a<i)&&(C=!0)}if(C){if(!o)if(QC&&console.log("Trigger signal",A,I.time,I),this.didTrigger[g]=!0,((e=this.receivers)==null?void 0:e.length)<=0)PE.invoke(I.asset);else for(const a of this.receivers)a&&a.invoke(I.asset)}else I.emitOnce||(this.didTrigger[g]=!1)}}}class Uw extends nd{constructor(){super(...arguments),r(this,"models",[]),r(this,"timelines",[]),r(this,"_previousActiveModel",null)}resolveSourceObjects(A){for(let e=this.models.length-1;e>=0;e--){const i=this.models[e].asset;if(!i.sourceObject||typeof i.sourceObject!="object"){console.log("no source object, removing model",e,i),this.models.splice(e,1);continue}else{const g=aA.getComponent(i.sourceObject,GB);this.timelines.push(g),g&&i.updateDirector&&(g.playOnAwake=!1)}}}evaluate(A){var e;this._previousActiveModel=null;for(let i=0;i<this.models.length;i++){const g=this.models[i],I=g.asset;if(A>=g.start&&A<=g.end){this._previousActiveModel=g;const o=this.getClipTime(A,g);if(I.controlActivation){const s=I.sourceObject;s.visible=!0}if(I.updateDirector){const s=this.timelines[i];s&&(s.isPlaying&&s.pause(),s.time=o,s.evaluate())}}else{const o=(e=this._previousActiveModel)==null?void 0:e.asset;if(I.controlActivation){const s=I.sourceObject;o?.sourceObject!==s&&(s.visible=!1)}}}}}const jE=iA("debugtimeline"),LU=class extends JA{constructor(){super(...arguments),r(this,"playableAsset"),r(this,"playOnAwake"),r(this,"extrapolationMode",1),r(this,"waitForAudio",!0),r(this,"_visibilityChangeEvt"),r(this,"_clonedPlayableAsset",!1),r(this,"_speed",1),r(this,"_guidsMap"),r(this,"_isPlaying",!1),r(this,"_internalUpdateRoutine"),r(this,"_isPaused",!1),r(this,"_isStopping",!1),r(this,"_time",0),r(this,"_duration",0),r(this,"_weight",1),r(this,"_animationTracks",[]),r(this,"_audioTracks",[]),r(this,"_signalTracks",[]),r(this,"_controlTracks",[]),r(this,"_customTracks",[]),r(this,"_allTracks",[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks]),r(this,"animationCallbackReceivers",[])}static registerCreateTrack(t,A){this.createTrackFunctions[t]=A}get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(t){typeof t=="number"&&!Number.isNaN(t)?this._time=t:(jE||pI())&&console.error("INVALID TIMELINE.TIME VALUE",t,this.name)}get duration(){return this._duration}set duration(t){this._duration=t}get weight(){return this._weight}set weight(t){this._weight=t}get speed(){return this._speed}set speed(t){this._speed=t}awake(){var t,A,e;jE&&console.log(this,(t=this.playableAsset)==null?void 0:t.tracks),this.rebuildGraph(),this.isValid()||console.warn("PlayableDirector is not valid",this.playableAsset,(A=this.playableAsset)==null?void 0:A.tracks,Array.isArray((e=this.playableAsset)==null?void 0:e.tracks),this)}onEnable(){var t,A,e;for(const i of this._audioTracks)(t=i.onEnable)==null||t.call(i);for(const i of this._customTracks)(A=i.onEnable)==null||A.call(i);for(const i of this._animationTracks)(e=i.onEnable)==null||e.call(i);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 t,A,e;this.stop();for(const i of this._audioTracks)(t=i.onDisable)==null||t.call(i);for(const i of this._customTracks)(A=i.onDisable)==null||A.call(i);for(const i of this._animationTracks)(e=i.onDisable)==null||e.call(i);this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){var t;for(const A of this._allTracks)for(const e of A)(t=e.onDestroy)==null||t.call(e)}rebuildGraph(){this.isValid()&&(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}async play(){if(!this.isValid())return;const t=this._isPaused==!0;if(this._isPaused=!1,!this._isPlaying){if(this._isPlaying=!0,t&&this.invokePauseChangedMethodsOnTracks(),this.waitForAudio){const A=[];for(const e of this._audioTracks){const i=e.loadAudio(this._time,1,0);i&&A.push(i)}if(A.length>0&&(await Promise.all(A),!this._isPlaying))return;for(;this._audioTracks.length>0&&this._isPlaying&&!fi.userInteractionRegistered&&this.waitForAudio;)await Jo(200)}this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate(),Pi.LateUpdate)}}pause(){this.isValid()&&(this._isPlaying=!1,!this._isPaused&&(this._isPaused=!0,this.internalEvaluate(),this.invokePauseChangedMethodsOnTracks(),this.invokeStateChangedMethodsOnTracks()))}stop(){this._isStopping=!0;for(const e of this._audioTracks)e.stop();const t=this._isPaused==!0,A=this._isPlaying;this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.internalEvaluate(),t&&this.invokePauseChangedMethodsOnTracks()),this._isPlaying=!1,this._isPaused=!1,t&&!A&&this.invokePauseChangedMethodsOnTracks(),A&&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 t of this._allTracks)for(const A of t)yield A}get audioTracks(){return this._audioTracks}resolveGuids(t){this._guidsMap=t}invokePauseChangedMethodsOnTracks(){var t;for(const A of this.forEachTrack())(t=A.onPauseChanged)==null||t.call(A)}invokeStateChangedMethodsOnTracks(){var t;for(const A of this.forEachTrack())(t=A.onStateChanged)==null||t.call(A,this._isPlaying)}*internalUpdate(){for(;this._isPlaying&&this.activeAndEnabled;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime*this.speed,this.internalEvaluate()),yield}internalEvaluate(t=!1){if(!this.isValid())return;let A=this._time;switch(this.extrapolationMode){case 0:this._speed>0?A=Math.min(A,this._duration):this._speed<0&&(A=Math.max(A,0)),this._time=A;break;case 1:A%=this._duration,this._time=A;break;case 2:if(A>this._duration){this.stop();return}break}const e=this._time;for(const i of this.playableAsset.tracks)if(!i.muted)switch(i.type){case Qo.Activation:if(!t&&!this._isPlaying)continue;for(let g=0;g<i.outputs.length;g++){const I=i.outputs[g];if(typeof I=="object"){let o=!1;if(i.clips)for(const C of i.clips)C.start<=e&&e<=C.end&&(o=!0);const s=I;s.visible!==void 0&&s.visible!==o&&(s.visible=o,jE&&console.warn(this.name,"set ActivationTrack-"+g,s.name,o,e))}}break}if(!this._isStopping)for(const i of this._animationTracks)i.evaluate(e);for(const i of this._audioTracks)i.evaluate(e);for(const i of this._signalTracks)i.evaluate(e);for(const i of this._controlTracks)i.evaluate(e);for(const i of this._customTracks)i.evaluate(e)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=Lc(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;const t=this.findRoot(this.gameObject);for(const A of this.playableAsset.tracks){for(let e=A.outputs.length-1;e>=0;e--){let i=A.outputs[e];if(typeof i=="string"){this._guidsMap&&this._guidsMap[i]&&(i=this._guidsMap[i]);const g=aA.findByGuid(i,t);g===null||typeof g!="object"?(A.outputs.splice(e,1),console.warn("Failed to resolve binding",i,A.name,A.type)):(jE&&console.log("Resolved binding",i,"to",g),A.outputs[e]=g)}else if(i===null){if(A.outputs.splice(e,1),LU.createTrackFunctions[A.type])continue;A.type!==Qo.Audio&&A.type!==Qo.Control&&A.type!==Qo.Marker&&A.type!==Qo.Signal&&console.warn("Missing binding",i,A.name,A.type,this.name,this.playableAsset.name)}}if(A.type===Qo.Control&&A.clips)for(let e=0;e<A.clips.length;e++){const i=A.clips[e];let g=i.asset.sourceObject;if(typeof g=="string"){this._guidsMap&&this._guidsMap[g]&&(g=this._guidsMap[g]);const I=aA.findByGuid(g,t);I===null||typeof I!="object"?console.warn("Failed to resolve sourceObject binding",g,A.name,i):(jE&&console.log("Resolved binding",g,"to",I),i.asset.sourceObject=I)}}}}findRoot(t){return t.parent?this.findRoot(t.parent):t}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const t of this.playableAsset.tracks)if(t.muted!==!0){if(t.clips)for(const A of t.clips)A.end>this._duration&&(this._duration=A.end);if(t.markers)for(const A of t.markers)A.time>this._duration&&(this._duration=A.time+.001)}}}setupAndCreateTrackHandlers(){var t,A,e;if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let i=aA.findObjectOfType(On,this.context);for(const g of this.playableAsset.tracks){const I=g.type,o=LU.createTrackFunctions[I];if(o!=null){const s=o(this,g);if(typeof s.evaluate=="function"){s.director=this,s.track=g,this._customTracks.push(s);continue}}if(g.type===Qo.Animation){if(!g.clips||g.clips.length<=0){jE&&console.warn("Animation track has no clips",g);continue}for(let s=g.outputs.length-1;s>=0;s--){let C=g.outputs[s];if(C instanceof wA){const n=aA.getOrAddComponent(C,bg);n&&(C=n)}const a=(t=C?.gameObject)==null?void 0:t.animations;if(a){const n=new Rw;n.trackOffset=g.trackOffset,n.director=this,n.track=g;for(let B=0;B<g.clips.length;B++){const Q=g.clips[B],E=Q.asset;if(!E){console.error(`Timeline ${this.name}: clip #${B} on track "${g.name}" has no animation data`);continue}const h=E.clip;let d=h;if((typeof d=="string"||typeof d=="number")&&(d=a.find(c=>c.name===h)),!d){console.warn("Could not find animationClip for model",Q,g.name,this.name,(A=this.playableAsset)==null?void 0:A.name);continue}C instanceof bg&&C.runtimeAnimatorController&&(C.__internalDidAwakeAndStart||C.initializeRuntimeAnimatorController(),C.runtimeAnimatorController.mixer||C.runtimeAnimatorController.bind(C),n.mixer=C.runtimeAnimatorController.mixer),n.mixer||(n.mixer=new uD(C.gameObject)),n.clips.push(d),n.mixer.uncacheAction(d),n.createHooks(Q.asset,d);const u=n.mixer.clipAction(d);n.actions.push(u),n.models.push(Q)}this._animationTracks.push(n)}}}else if(g.type===Qo.Audio){if(!g.clips||g.clips.length<=0)continue;const s=new Bd;s.director=this,s.track=g,s.audioSource=g.outputs.find(C=>C instanceof fi),this._audioTracks.push(s),i||(i=(e=this.context.mainCameraComponent)==null?void 0:e.gameObject.addNewComponent(On)),s.listener=i.listener;for(let C=0;C<g.clips.length;C++){const a=g.clips[C];s.addModel(a)}}else if(g.type===Qo.Marker){const s=new Qd;if(s.director=this,s.track=g,g.markers)for(const C of g.markers)switch(C.type){case qU.Signal:s.models.push(C),s.didTrigger.push(!1);break}if(s!==null&&s.models.length>0){const C=aA.getComponent(this.gameObject,PE);C&&(s.receivers.push(C),this._signalTracks.push(s))}}else if(g.type===Qo.Signal){const s=new Qd;if(s.director=this,s.track=g,g.markers)for(const C of g.markers)s.models.push(C),s.didTrigger.push(!1);for(const C of g.outputs)s.receivers.push(C);this._signalTracks.push(s)}else if(g.type===Qo.Control){const s=new Uw;if(s.director=this,s.track=g,g.clips)for(const C of g.clips)s.models.push(C);s.resolveSourceObjects(this.context),this._controlTracks.push(s)}}}setAudioTracksAllowPlaying(t){for(const A of this._audioTracks)A.onAllowAudioChanged(t)}registerAnimationCallback(t){this.animationCallbackReceivers.push(t)}unregisterAnimationCallback(t){const A=this.animationCallbackReceivers.indexOf(t);A!==-1&&this.animationCallbackReceivers.splice(A,1)}};let GB=LU;r(GB,"createTrackFunctions",{});const Nw=Symbol("objectIsAnimatedData");function H_(t,A,e){if(!t)return;if(t[Nw]===void 0){if(!e)return;t[Nw]=new Set}const i=t[Nw];e?i.add(A):i.has(A)&&i.delete(A)}function RIA(t){if(!t)return!1;const A=t[Nw];return A!==void 0&&A.size>0}mt.registerCallback(Yi.ContextCreated,t=>{const A=t.context.domElement.getAttribute("autoplay");if(A!==void 0&&(A===""||A==="true")&&t.files)for(const e of t.files)aA.foreachComponent(e.file.scene,i=>{if(i.enabled!==!1){if(i instanceof no&&i.playAutomatically||i instanceof bg||i instanceof GB&&i.playOnAwake===!0)return!0;if(i instanceof no)return i.playAutomatically=!0,!0;if(i instanceof GB)return i.playOnAwake=!0,!0}},!0)!==!0&&UIA(e.file)});function UIA(t){if(!t||!t.animations)return;for(let e=0;e<t.animations.length;e++){const i=t.animations[e];if(!(!i.tracks||i.tracks.length<=0))for(const g in i.tracks){const I=i.tracks[g],o=I.__objectName??I.name.substring(0,I.name.indexOf("."));let s=t.scene.getObjectByName(o);if(!s&&(s=t.scene.getObjectByProperty("uuid",o),!s))continue;let C=A(s);C||(C=Jn(t.scene,new no));const a=C.animations=C.animations||[];i.name_animator=C.name,a.indexOf(i)<0&&a.push(i)}}function A(e){var i;if(!e)return;const g=(i=e.userData)==null?void 0:i.components;if(g&&g.length>0)for(let I=0;I<g.length;I++){const o=g[I];if(o instanceof bg||o instanceof no)return e}return A(e.parent)}}class NIA{constructor(){r(this,"_context")}get context(){return this._context??ve.Current}get isStateMachineBehaviour(){return!0}}class Fw{constructor(A,e,i,g){r(this,"_name"),r(this,"_nameHash"),r(this,"_normalizedTime"),r(this,"_length"),r(this,"_speed"),this._name=A.name,this._nameHash=A.hash,this._normalizedTime=e,this._length=i,this._speed=g}get name(){return this._name}get nameHash(){return this._nameHash}get normalizedTime(){return this._normalizedTime}get length(){return this._length}get speed(){return this._speed}}function __(t,A){return{name:"",isLooping:!1,guid:A?.generateUUID()??eg.generateUUID(),index:-1,clip:new PI(t,1,[])}}var Pn=(t=>(t[t.If=1]="If",t[t.IfNot=2]="IfNot",t[t.Greater=3]="Greater",t[t.Less=4]="Less",t[t.Equals=6]="Equals",t[t.NotEqual=7]="NotEqual",t))(Pn||{}),xU=(t=>(t[t.Float=1]="Float",t[t.Int=3]="Int",t[t.Bool=4]="Bool",t[t.Trigger=9]="Trigger",t))(xU||{});const GI=iA("debuganimatorcontroller"),Kw=iA("debugrootmotion");class ko{constructor(A){r(this,"normalizedStartOffset",0),r(this,"_speed",1),r(this,"animator"),r(this,"model"),r(this,"_mixer"),r(this,"_activeState"),r(this,"_activeStates",[]),r(this,"rootMotionHandler"),this.model=A,GI&&console.log(this)}static createFromClips(A,e={looping:!1,autoTransition:!0,transitionDuration:0}){const i=[];for(let I=0;I<A.length;I++){const o=A[I],s=[];if(e.autoTransition!==!1){const a=e.transitionDuration??0,n=a/o.duration;let B=I;(e.autoTransition===void 0||e.autoTransition===!0)&&(B=(I+1)%A.length),s.push({exitTime:1-n,offset:0,duration:a,hasExitTime:!0,destinationState:B,conditions:[]})}const C={name:o.name,hash:I,motion:{name:o.name,clip:o,isLooping:e?.looping??!1},transitions:s,behaviours:[]};i.push(C)}const g={name:"AnimatorController",guid:new Dg(Date.now()).generateUUID(),parameters:[],layers:[{name:"Base Layer",stateMachine:{defaultState:0,states:i}}]};return new ko(g)}play(A,e=-1,i=Number.NEGATIVE_INFINITY,g=0){if(e<0)e=0;else if(e>=this.model.layers.length){console.warn("invalid layer");return}const I=this.model.layers[e].stateMachine;for(const o of I.states)if(o.name===A||o.hash===A){GI&&console.log("transition to ",o),this.transitionTo(o,g,i);return}console.warn("Could not find "+A+" to play")}reset(){this.setStartTransition()}setBool(A,e){var i,g;const I=typeof A=="string"?"name":"hash";return(g=(i=this.model)==null?void 0:i.parameters)==null?void 0:g.filter(o=>o[I]===A).forEach(o=>o.value=e)}getBool(A){var e,i,g;const I=typeof A=="string"?"name":"hash";return((g=(i=(e=this.model)==null?void 0:e.parameters)==null?void 0:i.find(o=>o[I]===A))==null?void 0:g.value)??!1}setFloat(A,e){var i,g;const I=typeof A=="string"?"name":"hash",o=(g=(i=this.model)==null?void 0:i.parameters)==null?void 0:g.filter(s=>s[I]===A);return o.forEach(s=>s.value=e),o?.length>0}getFloat(A){var e,i,g;const I=typeof A=="string"?"name":"hash";return((g=(i=(e=this.model)==null?void 0:e.parameters)==null?void 0:i.find(o=>o[I]===A))==null?void 0:g.value)??0}setInteger(A,e){var i,g;const I=typeof A=="string"?"name":"hash";return(g=(i=this.model)==null?void 0:i.parameters)==null?void 0:g.filter(o=>o[I]===A).forEach(o=>o.value=e)}getInteger(A){var e,i,g;const I=typeof A=="string"?"name":"hash";return((g=(i=(e=this.model)==null?void 0:e.parameters)==null?void 0:i.find(o=>o[I]===A))==null?void 0:g.value)??0}setTrigger(A){var e,i;GI&&console.log("SET TRIGGER",A);const g=typeof A=="string"?"name":"hash";return(i=(e=this.model)==null?void 0:e.parameters)==null?void 0:i.filter(I=>I[g]===A).forEach(I=>I.value=!0)}resetTrigger(A){var e,i;const g=typeof A=="string"?"name":"hash";return(i=(e=this.model)==null?void 0:e.parameters)==null?void 0:i.filter(I=>I[g]===A).forEach(I=>I.value=!1)}getTrigger(A){var e,i,g;const I=typeof A=="string"?"name":"hash";return((g=(i=(e=this.model)==null?void 0:e.parameters)==null?void 0:i.find(o=>o[I]===A))==null?void 0:g.value)??!1}isInTransition(){return this._activeStates.length>1}setSpeed(A){this._speed=A}FindState(A){return this.findState(A)}findState(A){if(!A)return null;if(Array.isArray(this.model.layers)){for(const e of this.model.layers)for(const i of e.stateMachine.states)if(i.name===A||i.hash==A)return i}return null}get context(){var A;return(A=this.animator)==null?void 0:A.context}get mixer(){return this._mixer}bind(A){A?this.animator!==A&&(this.animator=A,this._mixer=new uD(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;GI&&console.warn("AnimatorController clone()",this.model);const A=Lc(this.model,(e,i,g)=>g==null?!0:!(g.type==="Object3D"||g.isObject3D===!0||wH(g)||g.tracks!==void 0||g instanceof ko));return console.assert(A!==this.model),new ko(A)}update(A){var e,i;if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates(A);const g=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&((e=this.rootMotionHandler)==null||e.onBeforeUpdate(A)),this._mixer.update(g),this.animator.applyRootMotion&&((i=this.rootMotionHandler)==null||i.onAfterUpdate(A))}get activeState(){return this._activeState}updateActiveStates(A){for(let e=0;e<this._activeStates.length;e++){const i=this._activeStates[e],g=i.motion;if(!g.action)this._activeStates.splice(e,1),e--;else{const I=g.action;I.weight=A,I.getEffectiveWeight()<=0&&!I.isRunning()&&(GI&&console.debug("REMOVE",i.name,I.getEffectiveWeight(),I.isRunning(),I.isScheduled()),this._activeStates.splice(e,1),e--)}}}setStartTransition(){for(const A of this.model.layers){const e=A.stateMachine;e.defaultState===void 0&&(GI&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",A),e.defaultState=0);const i=e.states[e.defaultState];this.transitionTo(i,0,this.normalizedStartOffset)}}evaluateTransitions(){var A;let e=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;e=!0}const i=this._activeState,g=i.motion.action;for(const o of i.transitions){if(!o.hasExitTime&&o.conditions.length<=0)continue;let s=!0;for(const C of o.conditions)if(!this.evaluateCondition(C)){s=!1;break}if(s)if(g){const C=i.motion.clip.duration,a=C<=0?1:Math.abs(g.time/C);let n=!1;if(o.hasExitTime?g.timeScale>0?n=a>=o.exitTime:g.timeScale<0&&(n=1-a>=o.exitTime):n=!0,n){for(const B of o.conditions){const Q=this.model.parameters.find(E=>E.name===B.parameter);Q?.type===xU.Trigger&&Q.value&&(Q.value=!1)}g.clampWhenFinished=!0,GI&&console.log("transition to "+o.destinationState,o,a,o.exitTime,o.hasExitTime),this.transitionTo(o.destinationState,o.duration,o.offset);return}}else{this.transitionTo(o.destinationState,o.duration,o.offset);return}}if(g){let o=i.speed??1;i.speedParameter&&(o*=this.getFloat(i.speedParameter)),o!==void 0&&(g.timeScale=o*this._speed)}let I=!1;if(i.motion.isLooping&&g&&(g.time>=g.getClip().duration?(I=!0,g.reset(),g.time=0,g.play()):g.time<=0&&g.timeScale<0&&(I=!0,g.reset(),g.time=g.getClip().duration,g.play())),!I&&i&&!e&&g&&this.animator&&i.behaviours){const o=g?.getClip().duration,s=g.time/o,C=new Fw(this._activeState,s,o,this._speed);for(const a of i.behaviours)a.instance&&((A=a.instance.onStateUpdate)==null||A.call(a.instance,this.animator,C,0))}}getState(A,e){return typeof A=="number"&&(A==-1&&(A=this.model.layers[e].stateMachine.defaultState,A===void 0&&(GI&&console.warn("AnimatorController default state is undefined: ",this.model,"Layer: "+e),A=0)),A=this.model.layers[e].stateMachine.states[A]),A}transitionTo(A,e,i){var g,I,o,s,C,a,n,B;if(!this.animator)return;const Q=0;if(A=this.getState(A,Q),!(A!=null&&A.motion)||!A.motion.clip||!(A.motion.clip instanceof PI))return;const E=this._activeState===A;if(E){const c=A.motion;if(!c.action_loopback&&c.clip){const l=this.rootMotionHandler?this.animator.gameObject.matrix.clone():null;this._mixer.uncacheAction(c.clip,this.animator.gameObject),l&&l.decompose(this.animator.gameObject.position,this.animator.gameObject.quaternion,this.animator.gameObject.scale),c.action_loopback=this.createAction(c.clip)}}if((g=this._activeState)!=null&&g.behaviours&&this._activeState.motion.action){const c=(I=this._activeState)==null?void 0:I.motion.clip.duration,l=this._activeState.motion.action.time/c,p=new Fw(this._activeState,l,c,this._speed);for(const D of this._activeState.behaviours)(s=(o=D.instance)==null?void 0:o.onStateExit)==null||s.call(D.instance,this.animator,p,Q)}const h=(C=this._activeState)==null?void 0:C.motion.action;h&&h.fadeOut(e),E&&(A.motion.action=A.motion.action_loopback,A.motion.action_loopback=h);const d=this._activeState;this._activeState=A;const u=(a=A.motion)==null?void 0:a.action;if(u){if(i=Math.max(0,Math.min(1,i)),A.cycleOffsetParameter){let l=this.getFloat(A.cycleOffsetParameter);typeof l=="number"?(l<0&&(l+=1),i+=l,i%=1):GI&&console.warn("AnimatorController cycle offset parameter is not a number",A.cycleOffsetParameter)}else typeof A.cycleOffset=="number"&&(i+=A.cycleOffset,i%=1);u.isRunning()&&u.stop(),u.reset(),u.enabled=!0;const c=A.motion.clip.duration;if(u.time=E?0:i*c,u.timeScale<0&&(u.time=c-u.time),u.clampWhenFinished=!0,u.setLoop(ec,0),e>0?u.fadeIn(e):u.weight=1,u.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(u),this._activeStates.includes(A)||this._activeStates.push(A),this._activeState.behaviours){const l=new Fw(A,i,c,this._speed);for(const p of this._activeState.behaviours)(B=(n=p.instance)==null?void 0:n.onStateEnter)==null||B.call(p.instance,this.animator,l,Q)}}else GI&&(A.__warned_no_motion||(A.__warned_no_motion=!0,console.warn("No action",A.motion,this)));GI&&console.log("TRANSITION FROM "+d?.name+" TO "+A.name,e,h,u,u?.getEffectiveTimeScale(),u?.getEffectiveWeight(),u?.isRunning(),u?.isScheduled(),u?.paused)}createAction(A){var e,i;if(this._mixer.existingAction(A)&&this._mixer.uncacheAction(A,(e=this.animator)==null?void 0:e.gameObject),(i=this.animator)!=null&&i.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new FIA(this));const g=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,g,A)}else return this._mixer.clipAction(A)}evaluateCondition(A){const e=this.model.parameters.find(i=>i.name===A.parameter);if(!e)return!1;switch(A.mode){case Pn.If:return e.value===!0;case Pn.IfNot:return e.value===!1;case Pn.Greater:return e.value>A.threshold;case Pn.Less:return e.value<A.threshold;case Pn.Equals:return e.value===A.threshold;case Pn.NotEqual:return e.value!==A.threshold}return!1}createActions(A){var e,i,g,I;GI&&console.log("AnimatorController createActions",this.model);for(const o of this.model.layers){const s=o.stateMachine;for(let C=0;C<s.states.length;C++){const a=s.states[C];a.transitions||(a.transitions=[]);for(const n of a.transitions)n.conditions||(n.conditions=[]);if(a.motion||(a.motion=__(a.name)),this.animator&&a.motion.clips){const n=(e=a.motion.clips)==null?void 0:e.find(B=>{var Q,E;return B.node.name===((E=(Q=this.animator)==null?void 0:Q.gameObject)==null?void 0:E.name)});n?a.motion.clip=n.clip:(GI||Se())&&console.warn('Could not find clip for animator "'+((g=(i=this.animator)==null?void 0:i.gameObject)==null?void 0:g.name)+'"',a.motion.clips.map(B=>B.node.name))}if(!a.motion.clip){const n=new PI(void 0,void 0,[]);a.motion.clip=n}if((I=a.motion)!=null&&I.clip){const n=a.motion.clip;if(n instanceof PI){const B=this.createAction(n);a.motion.action=B}else(GI||Se())&&console.warn("No valid animationclip assigned",a)}if(a.behaviours&&Array.isArray(a.behaviours))for(const n of a.behaviours){if(!(n!=null&&n.typeName))continue;const B=z.get(n.typeName),Q=new B;Q.isStateMachineBehaviour&&(Q._context=this.context??void 0,BE(Q,n.properties),n.instance=Q),GI&&console.log("Created animator controller behaviour",a.name,n.typeName,n.properties,Q)}}}}*enumerateActions(){if(this.model.layers)for(const A of this.model.layers){const e=A.stateMachine;for(let i=0;i<e.states.length;i++){const g=e.states[i];g!=null&&g.motion&&(g.motion.action&&(yield g.motion.action),g.motion.action_loopback&&(yield g.motion.action_loopback))}}}}class O_{constructor(A,e){r(this,"track"),r(this,"createdInterpolant"),r(this,"originalEvaluate"),r(this,"customEvaluate"),this.track=A;const i=A,g=i.createInterpolant.bind(A);i.createInterpolant=()=>(i.createInterpolant=g,this.createdInterpolant=g(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=I=>{if(!this.originalEvaluate)return;const o=this.originalEvaluate(I);return e(I,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 lg=class{constructor(t,A,e,i,g){if(r(this,"_action"),r(this,"root"),r(this,"clip"),r(this,"positionWrapper",null),r(this,"rotationWrapper",null),r(this,"context"),r(this,"positionChange",new w),r(this,"rotationChange",new FA),r(this,"_prevTime",0),this.context=t,this.root=A,this.clip=e,lg.firstKeyframeRotation[this.cacheId]||(lg.firstKeyframeRotation[this.cacheId]=new FA),g){const I=g.values;lg.firstKeyframeRotation[this.cacheId].set(I[0],I[1],I[2],I[3])}lg.spaceRotation[this.cacheId]||(lg.spaceRotation[this.cacheId]=new FA),lg.effectiveSpaceRotation[this.cacheId]||(lg.effectiveSpaceRotation[this.cacheId]=new FA),lg.clipOffsetRotation[this.cacheId]=new FA,g&&lg.clipOffsetRotation[this.cacheId].set(g.values[0],g.values[1],g.values[2],g.values[3]).invert(),this.handlePosition(e,i),this.handleRotation(e,g)}set action(t){this._action=t}get action(){return this._action}get cacheId(){return this.root.uuid}onStart(t){if(t.getClip()!==this.clip)return;lg.lastObjRotation[this.cacheId]||(lg.lastObjRotation[this.cacheId]=this.root.quaternion.clone());const A=lg.lastObjRotation[this.cacheId];if(lg.spaceRotation[this.cacheId].copy(A),Kw){const e=new Wg().setFromQuaternion(A);console.log("START",this.clip.name,Ie.toDegrees(e.y),this.root.position.z)}}getClipRotationOffset(){return lg.clipOffsetRotation[this.cacheId]}handlePosition(t,A){if(A){const e=this.root;Kw&&e.add(new Fo),lg.lastObjPosition[this.cacheId]||(lg.lastObjPosition[this.cacheId]=this.root.position.clone());const i=new w,g=new w;this.positionWrapper=new O_(A,(I,o)=>{const s=this.action.getEffectiveWeight();return Kw&&e.position.length()>8&&e.position.set(0,e.position.y,0),I>this._prevTime&&(i.set(o[0],o[1],o[2]),i.sub(g),i.multiplyScalar(s),i.applyQuaternion(this.getClipRotationOffset()),i.applyQuaternion(e.quaternion),this.positionChange.copy(i)),g.fromArray(o),this._prevTime=I,o[0]=0,o[1]=0,o[2]=0,o})}}handleRotation(t,A){if(A){if(Kw){const I=A.values,o=new Wg().setFromQuaternion(new FA(I[0],I[1],I[2],I[3]));console.log(t.name,A.name,"FIRST ROTATION IN TRACK",Ie.toDegrees(o.y));const s=A.values.length-4,C=new FA().set(I[s],I[s+1],I[s+2],I[s+3]),a=new Wg().setFromQuaternion(C);console.log(t.name,A.name,"LAST ROTATION IN TRACK",Ie.toDegrees(a.y))}let e=0;const i=new FA,g=new FA;this.rotationWrapper=new O_(A,(I,o)=>(I>e&&(g.set(o[0],o[1],o[2],o[3]),i.invert(),g.multiply(i),this.rotationChange.copy(g)),i.fromArray(o),e=I,o[0]=0,o[1]=0,o[2]=0,o[3]=1,o))}}onBeforeUpdate(t){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(t){return!this.action||(t*=this.action.getEffectiveWeight(),t<=0)?!1:(this.positionChange.multiplyScalar(t),this.rotationChange.slerp(lg.identityQuaternion,1-t),!0)}};let jn=lg;r(jn,"lastObjPosition",{}),r(jn,"lastObjRotation",{}),r(jn,"firstKeyframeRotation",{}),r(jn,"spaceRotation",{}),r(jn,"effectiveSpaceRotation",{}),r(jn,"clipOffsetRotation",{}),r(jn,"identityQuaternion",new FA);class FIA{constructor(A){r(this,"controller"),r(this,"handler",[]),r(this,"root"),r(this,"basePosition",new w),r(this,"baseQuaternion",new FA),r(this,"baseRotation",new Wg),r(this,"summedPosition",new w),r(this,"summedRotation",new FA),this.controller=A}createClip(A,e,i){this.root=e,e&&"name"in e&&e.name;const g=this.findRootTrack(i,".position"),I=this.findRootTrack(i,".quaternion"),o=new jn(this.controller.context,e,i,g,I);this.handler.push(o);const s=A.clipAction(i);return o.action=s,s}onStart(A){for(const e of this.handler)e.onStart(A)}onBeforeUpdate(A){this.basePosition.copy(this.root.position),this.baseQuaternion.copy(this.root.quaternion);for(const e of this.handler)e.onBeforeUpdate(A)}onAfterUpdate(A){if(!(A<=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 e of this.handler)e.onAfterUpdate(A)&&(this.summedPosition.add(e.positionChange),this.summedRotation.multiply(e.rotationChange));this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation)}}findRootTrack(A,e){const i=A.tracks;if(!i)return null;for(const g of i)if(g.name.endsWith(e))return g;return null}}class KIA extends na{onSerialize(A,e){}onDeserialize(A,e){if(e.type===ko&&A?.__type==="AnimatorController")return new ko(A)}}new KIA(ko);var JIA=Object.defineProperty,vIA=Object.getOwnPropertyDescriptor,Jw=(t,A,e,i)=>{for(var g=i>1?void 0:i?vIA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&JIA(A,e,g),g};const Xo=iA("debuganimator");class bg extends JA{constructor(){super(...arguments),r(this,"applyRootMotion",!1),r(this,"hasRootMotion",!1),r(this,"keepAnimatorControllerStateOnDisable",!1),r(this,"_parametersAreDirty",!1),r(this,"_isDirty",!1),r(this,"speed",1),r(this,"normalizedStartOffset",0),r(this,"_animatorController",null),r(this,"_initializeWithRuntimeAnimatorController")}set runtimeAnimatorController(A){var e;this._animatorController&&this._animatorController.model===A||(A?A instanceof ko?(A.animator&&A.animator!==this&&(console.warn("AnimatorController can not be bound to multiple animators",(e=A.model)==null?void 0:e.name),A.model||console.error("AnimatorController has no model"),A=new ko(A.model)),this._animatorController=A,this._animatorController.bind(this)):(Xo&&console.log("Assign animator controller",A,this),this._animatorController=new ko(A),this.__didAwake&&this._animatorController.bind(this)):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}get parametersAreDirty(){return this._parametersAreDirty}get isDirty(){return this._isDirty}Play(A,e=-1,i=Number.NEGATIVE_INFINITY,g=0){this.play(A,e,i,g)}play(A,e=-1,i=Number.NEGATIVE_INFINITY,g=0){var I;(I=this.runtimeAnimatorController)==null||I.play(A,e,i,g),this._isDirty=!0}Reset(){this.reset()}reset(){var A;(A=this._animatorController)==null||A.reset(),this._isDirty=!0}SetBool(A,e){this.setBool(A,e)}setBool(A,e){var i,g;Xo&&console.log("setBool",A,e),((i=this.runtimeAnimatorController)==null?void 0:i.getBool(A))!==e&&(this._parametersAreDirty=!0),(g=this.runtimeAnimatorController)==null||g.setBool(A,e)}GetBool(A){return this.getBool(A)}getBool(A){var e;const i=((e=this.runtimeAnimatorController)==null?void 0:e.getBool(A))??!1;return Xo&&console.log("getBool",A,i),i}toggleBool(A){this.setBool(A,!this.getBool(A))}SetFloat(A,e){this.setFloat(A,e)}setFloat(A,e){var i,g;((i=this.runtimeAnimatorController)==null?void 0:i.getFloat(A))!==e&&(this._parametersAreDirty=!0),Xo&&console.log("setFloat",A,e),(g=this.runtimeAnimatorController)==null||g.setFloat(A,e)}GetFloat(A){return this.getFloat(A)}getFloat(A){var e;const i=((e=this.runtimeAnimatorController)==null?void 0:e.getFloat(A))??-1;return Xo&&console.log("getFloat",A,i),i}SetInteger(A,e){this.setInteger(A,e)}setInteger(A,e){var i,g;((i=this.runtimeAnimatorController)==null?void 0:i.getInteger(A))!==e&&(this._parametersAreDirty=!0),Xo&&console.log("setInteger",A,e),(g=this.runtimeAnimatorController)==null||g.setInteger(A,e)}GetInteger(A){return this.getInteger(A)}getInteger(A){var e;const i=((e=this.runtimeAnimatorController)==null?void 0:e.getInteger(A))??-1;return Xo&&console.log("getInteger",A,i),i}SetTrigger(A){this.setTrigger(A)}setTrigger(A){var e;this._parametersAreDirty=!0,Xo&&console.log("setTrigger",A),(e=this.runtimeAnimatorController)==null||e.setTrigger(A)}ResetTrigger(A){this.resetTrigger(A)}resetTrigger(A){var e;this._parametersAreDirty=!0,Xo&&console.log("resetTrigger",A),(e=this.runtimeAnimatorController)==null||e.resetTrigger(A)}GetTrigger(A){this.getTrigger(A)}getTrigger(A){var e;const i=(e=this.runtimeAnimatorController)==null?void 0:e.getTrigger(A);return Xo&&console.log("getTrigger",A,i),i}IsInTransition(){return this.isInTransition()}isInTransition(){var A;return((A=this.runtimeAnimatorController)==null?void 0:A.isInTransition())??!1}SetSpeed(A){return this.setSpeed(A)}setSpeed(A){var e;A!==this.speed&&(Xo&&console.log("setSpeed",A),this.speed=A,(e=this._animatorController)==null||e.setSpeed(A))}set minMaxSpeed(A){this.speed=Ie.lerp(A.x,A.y,Math.random())}set minMaxOffsetNormalized(A){this.normalizedStartOffset=Ie.lerp(A.x,A.y,Math.random()),this.runtimeAnimatorController&&(this.runtimeAnimatorController.normalizedStartOffset=this.normalizedStartOffset)}awake(){Xo&&console.log("ANIMATOR",this.name,this),this.gameObject&&this.initializeRuntimeAnimatorController()}initializeRuntimeAnimatorController(A=!1){const e=A||this.runtimeAnimatorController!==this._initializeWithRuntimeAnimatorController;if(this.runtimeAnimatorController&&e){const i=this.runtimeAnimatorController.clone();this._initializeWithRuntimeAnimatorController=i,i?(console.assert(this.runtimeAnimatorController!==i),this.runtimeAnimatorController=i,console.assert(this.runtimeAnimatorController===i),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 A;this.keepAnimatorControllerStateOnDisable||(A=this._animatorController)==null||A.reset()}onBeforeRender(){this._isDirty=!1,this._parametersAreDirty=!1,!RIA(this.gameObject)&&this._animatorController&&this._animatorController.update(1)}}Jw([y()],bg.prototype,"applyRootMotion",2),Jw([y()],bg.prototype,"hasRootMotion",2),Jw([y()],bg.prototype,"keepAnimatorControllerStateOnDisable",2),Jw([y()],bg.prototype,"runtimeAnimatorController",1);const WE=iA("debugusdzanimation"),YU=iA("debugusdzanimationserialization");class vw{constructor(A,e,i){r(this,"_start"),r(this,"ext"),r(this,"root"),r(this,"clip"),this.ext=A,this.root=e,this.clip=i}get start(){return this._start===void 0&&(this._start=this.ext.getStartTime01(this.root,this.clip)),this._start}get duration(){return this.clip.duration}}class $o{constructor(A,e,i){r(this,"clip"),r(this,"pos"),r(this,"rot"),r(this,"scale"),r(this,"root"),r(this,"target"),r(this,"duration",0),r(this,"useRootMotion",!1),this.root=A,this.target=e,this.clip=i,i?this.duration=i.duration:this.duration=1/this.frameRate;const g=aA.getComponent(A,bg);g&&(this.useRootMotion=g.applyRootMotion)}get frameRate(){return 60}addTrack(A){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}A.name.endsWith("position")&&(this.pos=A),A.name.endsWith("quaternion")&&(this.rot=A),A.name.endsWith("scale")&&(this.scale=A)}getFrames(){var A,e,i,g,I,o;return this.clip?Math.max(((e=(A=this.pos)==null?void 0:A.times)==null?void 0:e.length)??0,((g=(i=this.rot)==null?void 0:i.times)==null?void 0:g.length)??0,((o=(I=this.scale)==null?void 0:I.times)==null?void 0:o.length)??0):2}getDuration(){return this.duration}getSortedTimesArray(A=!0,e=!0,i=!0){var g,I,o;if(!this.clip)return[0,this.duration];const s=(g=this.pos)==null?void 0:g.times,C=(I=this.rot)==null?void 0:I.times,a=(o=this.scale)==null?void 0:o.times,n=[];if(A&&s)for(const B of s)n.push(B);if(e&&C)for(const B of C)n.push(B);if(i&&a)for(const B of a)n.push(B);return n.includes(0)||n.push(0),n.sort((B,Q)=>B-Q),[...new Set(n)]}*getValues(A,e=!0,i=!0,g=!0){var I,o,s;const C=new w,a=new FA,n=new w(1,1,1),B=this.target,Q=e?(I=this.pos)==null?void 0:I.createInterpolant():void 0,E=i?(o=this.rot)==null?void 0:o.createInterpolant():void 0,h=g?(s=this.scale)==null?void 0:s.createInterpolant():void 0;Q||C.set(B.position.x,B.position.y,B.position.z),E||a.set(B.quaternion.x,B.quaternion.y,B.quaternion.z,B.quaternion.w),h||n.set(B.scale.x,B.scale.y,B.scale.z);for(let d=0;d<A.length;d++){const u=A[d];if(Q){const c=Q.evaluate(u);C.set(c[0],c[1],c[2])}if(E){const c=E.evaluate(u);a.set(c[0],c[1],c[2],c[3])}if(h){const c=h.evaluate(u);n.set(c[0],c[1],c[2])}if(this.useRootMotion&&B===this.root){const c=new NA;c.compose(C,a,n),c.multiply(B.matrix),c.decompose(C,a,n)}yield{time:u,translation:C,rotation:a,scale:n,index:d}}}}r($o,"animationDurationPadding",1);class Ed{constructor(A){r(this,"dict",new Map),r(this,"rootTargetMap",new Map),r(this,"rootAndClipToRegisteredAnimationMap",new Map),r(this,"rootToRegisteredClipCount",new Map),r(this,"serializers",[]),r(this,"injectRestPoses",!1),r(this,"injectImplicitBehaviours",!1),this.injectRestPoses=A,this.injectImplicitBehaviours=A}get extensionName(){return"animation"}getClipCount(A){let e=this.rootToRegisteredClipCount.get(A);return this.injectRestPoses&&(e=e?e-1:0),e??0}getStartTime01(A,e){const i=this.rootTargetMap.get(A);if(!i)return 0;const g=this.dict.get(i[0]);if(!g)return console.error("Trying to get start time for root that has no animation data",A,e,...this.dict),0;let I=0;for(let o=0;o<g.length&&g[o].clip!==e;o++)I+=g[o].getDuration()+$o.animationDurationPadding;return I}registerAnimation(A,e){if(!e||!A)return null;this.rootTargetMap.has(A)||this.rootTargetMap.set(A,[]);const i=A.uuid+e.uuid;if(this.rootAndClipToRegisteredAnimationMap.has(i))return this.rootAndClipToRegisteredAnimationMap.get(i);WE&&console.log("registerAnimation",A,e);const g=this.injectRestPoses?1:0,I=this.rootToRegisteredClipCount.get(A)??g,o=this.rootTargetMap.get(A),s=new Set(o);if(e.tracks)for(const a of e.tracks){const n=We.parseTrackName(a.name),B=We.findNode(A,n.nodeName);if(!B){console.warn("no object found for track",a.name,"using "+A.name+" instead");continue}this.dict.has(B)||this.dict.set(B,[]);const Q=this.dict.get(B);if(!Q)continue;if(s.delete(B),this.injectRestPoses&&!Q[0]){const h=new $o(null,B,void 0);Q[0]=h}let E=Q[I];E||(E=new $o(A,B,e),Q[I]=E),E.addTrack(a),o!=null&&o.includes(B)||o==null||o.push(B)}for(const a of s){const n=this.dict.get(a);if(!n)continue;if(this.injectRestPoses&&!n[0]){const Q=new $o(null,a,void 0);n[0]=Q}let B=n[I];B||(WE&&console.log("Adding padding clip for ",a,e),B=new $o(A,a,e),n[I]=B)}const C=new vw(this,A,e);return this.rootAndClipToRegisteredAnimationMap.set(i,C),this.rootToRegisteredClipCount.set(A,I+1),C}onAfterHierarchy(A){WE&&console.log("Animation clips per animation target node",this.dict)}onAfterBuildDocument(A){var e,i;for(const g of this.serializers){const I=(e=g.model)==null?void 0:e.parent,o=I?.isDynamic===!0;YU&&console.log(o,(i=g.model)==null?void 0:i.parent),o&&g.registerCallback(I)}}onExportObject(A,e,i){aA.foreachComponent(A,I=>{const o=I;typeof o.createAnimation=="function"&&o.createAnimation(this,e,i)},!1);const g=new bIA(A,this.dict);this.serializers.push(g),g.registerCallback(e)}}class bIA{constructor(A,e){r(this,"object"),r(this,"dict"),r(this,"model"),r(this,"callback"),this.object=A,this.dict=e}registerCallback(A){this.model&&this.callback&&this.model.removeEventListener("serialize",this.callback),this.callback||(this.callback=this.onSerialize.bind(this)),YU&&console.log("REPARENT",A),this.model=A,this.model.addEventListener("serialize",this.callback)}skinnedMeshExport(A,e){const i=this.model,g=this.dict;if(i&&i.skinnedMesh){let I=function(f){const U=[];for(const[M,m]of f){let x=`${M} : [`;const L=[];for(const V of m)L.push(`(${hg(V.x)}, ${hg(V.y)}, ${hg(V.z)})`);x=x.concat(L.join(", ")),x=x.concat("],"),U.push(x)}return U},o=function(f){const U=[];for(const[M,m]of f){let x=`${M} : [`;const L=[];for(const V of m)L.push(`(${hg(V.w)}, ${hg(V.x)}, ${hg(V.y)}, ${hg(V.z)})`);x=x.concat(L.join(", ")),x=x.concat("],"),U.push(x)}return U},s=function(f){let U=!0,M;for(const[x,L]of f)if(M===void 0&&(M=L.length),M!==L.length){U=!1;break}WE&&console.log("Bone count: ",f.size,"TransformData entries per bone: ",M),console.assert(U,"All bones should have the same number of TransformData entries",f);const m=[];for(const[x,L]of f){const V=new Array;let Y=0;for(let P=0;P<L.length;P++)V.push(Y),Y+=L[P].getDuration()+$o.animationDurationPadding;for(let P=0;P<L.length;P++){const b=L[P],T=V[P];m.length<=P&&m.push({pos:[],rot:[],scale:[],timeOffset:T});const _=m[P];_.pos.push(...b.getSortedTimesArray(!0,!1,!1)),_.rot.push(...b.getSortedTimesArray(!1,!0,!1)),_.scale.push(...b.getSortedTimesArray(!1,!1,!0))}}for(const x of m)x.pos.sort((L,V)=>L-V),x.rot.sort((L,V)=>L-V),x.scale.sort((L,V)=>L-V),x.pos=[...new Set(x.pos)],x.rot=[...new Set(x.rot)],x.scale=[...new Set(x.scale)];return m},C=function(f,U,M){const m=new Map,x=new Map,L=new Map,V=U.length;for(const Y of M){const P=f.get(Y);let b;P?console.assert(P.length===V,"We should have the same number of TransformData entries for each bone",P,U):b=new $o(null,Y,void 0);for(let T=0;T<V;T++){const _=P?P[T]:b,eA=U[T];for(const{time:$,translation:IA}of _.getValues(eA.pos,!0,!1,!1)){const yA=($+eA.timeOffset)*60;m.has(yA)||m.set(yA,new Array),m.get(yA).push(IA.clone())}for(const{time:$,rotation:IA}of _.getValues(eA.rot,!1,!0,!1)){const yA=($+eA.timeOffset)*60;x.has(yA)||x.set(yA,new Array),x.get(yA).push(IA.clone())}for(const{time:$,scale:IA}of _.getValues(eA.scale,!1,!1,!0)){const yA=($+eA.timeOffset)*60;L.has(yA)||L.set(yA,new Array),L.get(yA).push(IA.clone())}}}return{position:m.size==0?void 0:m,quaternion:x.size==0?void 0:x,scale:L.size==0?void 0:L}},a=function(f){const U=[];for(const M of f)U.push(`(${hg(M.x)}, ${hg(M.y)}, ${hg(M.z)})`);return U.join(", ")},n=function(f){const U=[];for(const M of f)U.push(`(${hg(M.w)}, ${hg(M.x)}, ${hg(M.y)}, ${hg(M.z)})`);return U.join(", ")},B=function(f){const U=new Map;if(WE){const M=new Array;for(const[m,x]of g)M.push(m.uuid+": "+x.length+" "+x.map(L=>{var V;return(V=L.clip)==null?void 0:V.uuid.substring(0,6)}).join(" "));console.log(`getPerBoneTransformData
5410
+ Using the assigned clip instead:`,this.clip),t=this.clip);let g=!this.sound||t&&t!==this.clip;if(typeof t=="string"&&!this.audioLoader&&(g=!0),(t instanceof MediaStream||typeof t=="string")&&(this.clip=t),g){this.shouldPlay=!0,this.onNewClip(t);return}if(this.shouldPlay=!0,this._hasEnded=!1,nI&&console.log("play",(A=this.sound)==null?void 0:A.getVolume(),this.sound),this.sound&&!this.sound.isPlaying){const I=this.context.application.muted;I&&this.sound.setVolume(0),(e=this.gameObject)==null||e.add(this.sound),this.clip instanceof MediaStream?(this.sound.setMediaStreamSource(this.clip),this._audioElement||(this._audioElement=document.createElement("audio"),this._audioElement.style.display="none"),this._audioElement.parentNode||(i=this.context.domElement.shadowRoot)==null||i.append(this._audioElement),this._audioElement.srcObject=this.clip,this._audioElement.autoplay=!1):(this._audioElement&&this._audioElement.remove(),this.sound.play(I?.1:0))}}pause(){var t,A;nI&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=(t=this.sound)==null?void 0:t.context.currentTime,this.sound.pause()),(A=this._audioElement)==null||A.remove()}stop(){var t,A;nI&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=(t=this.sound)==null?void 0:t.context.currentTime,nI&&console.log(this._lastContextTime),this.sound.stop()),(A=this._audioElement)==null||A.remove()}get isPlaying(){var t;return((t=this.sound)==null?void 0:t.isPlaying)??!1}set isPlaying(t){}get time(){var t,A;return(t=this.sound)!=null&&t.source?((A=this.sound.source)==null?void 0:A.context.currentTime)-this._lastContextTime+this.sound.offset:0}set time(t){if(this.sound){if(t===this.sound.offset)return;const A=this.isPlaying;this.stop(),this.sound.offset=t,A&&this.play()}}update(){this.helper&&(this.isPlaying&&this.helper.update(),this.helper.visible=this.isPlaying),this._needUpdateSpatialDistanceSettings&&this.applySpatialDistanceSettings(),this.sound&&!this.sound.isPlaying&&this.shouldPlay&&!this._hasEnded&&(this._hasEnded=!0,nI&&console.log("Audio clip ended",this.clip),this.dispatchEvent(new CustomEvent("ended",{detail:this})))}};let fi=Tn;nC([y(URL)],fi.prototype,"clip",2),nC([y()],fi.prototype,"playOnAwake",2),nC([y()],fi.prototype,"preload",2),nC([y()],fi.prototype,"loop",1),nC([y()],fi.prototype,"spatialBlend",1),nC([y()],fi.prototype,"minDistance",1),nC([y()],fi.prototype,"maxDistance",1),nC([y()],fi.prototype,"volume",1),nC([y()],fi.prototype,"rollOffMode",2),nC([y()],fi.prototype,"playInBackground",2);const N_={type:"change"},MU={type:"start"},F_={type:"end"},pw=new to,K_=new lI,ZgA=Math.cos(70*eg.DEG2RAD);let zgA=class extends ng{constructor(t,A){super(),this.object=t,this.domElement=A,this.domElement.style.touchAction="none",this.enabled=!0,this.target=new w,this.cursor=new w,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:Sr.ROTATE,MIDDLE:Sr.DOLLY,RIGHT:Sr.PAN},this.touches={ONE:fr.ROTATE,TWO:fr.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this.getPolarAngle=function(){return o.phi},this.getAzimuthalAngle=function(){return o.theta},this.getDistance=function(){return this.object.position.distanceTo(this.target)},this.listenToKeyEvents=function(j){j.addEventListener("keydown",se),this._domElementKeyEvents=j},this.stopListenToKeyEvents=function(){this._domElementKeyEvents.removeEventListener("keydown",se),this._domElementKeyEvents=null},this.saveState=function(){e.target0.copy(e.target),e.position0.copy(e.object.position),e.zoom0=e.object.zoom},this.reset=function(){e.target.copy(e.target0),e.object.position.copy(e.position0),e.object.zoom=e.zoom0,e.object.updateProjectionMatrix(),e.dispatchEvent(N_),e.update(),g=i.NONE},this.update=function(){const j=new w,G=new FA().setFromUnitVectors(t.up,new w(0,1,0)),F=G.clone().invert(),H=new w,O=new FA,J=new w,Z=2*Math.PI;return function(QA=null){const uA=e.object.getWorldPosition(t.position);j.copy(uA).sub(e.target),j.applyQuaternion(G),o.setFromVector3(j),e.autoRotate&&g===i.NONE&&L(m(QA)),e.enableDamping?(o.theta+=s.theta*e.dampingFactor,o.phi+=s.phi*e.dampingFactor):(o.theta+=s.theta,o.phi+=s.phi);let pA=e.minAzimuthAngle,SA=e.maxAzimuthAngle;isFinite(pA)&&isFinite(SA)&&(pA<-Math.PI?pA+=Z:pA>Math.PI&&(pA-=Z),SA<-Math.PI?SA+=Z:SA>Math.PI&&(SA-=Z),pA<=SA?o.theta=Math.max(pA,Math.min(SA,o.theta)):o.theta=o.theta>(pA+SA)/2?Math.max(pA,o.theta):Math.min(SA,o.theta)),o.phi=Math.max(e.minPolarAngle,Math.min(e.maxPolarAngle,o.phi)),o.makeSafe(),e.enableDamping===!0?e.target.addScaledVector(n,e.dampingFactor):e.target.add(n),e.target.sub(e.cursor),e.target.clampLength(e.minTargetRadius,e.maxTargetRadius),e.target.add(e.cursor),e.zoomToCursor&&k||e.object.isOrthographicCamera?o.radius=$(o.radius):(e.enableDamping?a=eg.lerp(a,C,e.dampingFactor):a=C,o.radius=$(o.radius*a)),j.setFromSpherical(o),j.applyQuaternion(F),uA.copy(e.target).add(j),e.object.parent?e.object.parent.worldToLocal(uA):e.object.position.copy(uA),e.object.lookAt(e.target),e.enableDamping===!0?(s.theta*=1-e.dampingFactor,s.phi*=1-e.dampingFactor,n.multiplyScalar(1-e.dampingFactor)):(s.set(0,0,0),n.set(0,0,0));let KA=!1;if(e.zoomToCursor&&k){let PA=null;if(e.object.isPerspectiveCamera){const ZA=j.length();PA=$(ZA*C);const zA=ZA-PA;e.object.position.addScaledVector(D,zA),e.object.updateMatrixWorld()}else if(e.object.isOrthographicCamera){const ZA=new w(S.x,S.y,0);ZA.unproject(e.object),e.object.zoom=Math.max(e.minZoom,Math.min(e.maxZoom,e.object.zoom/C)),e.object.updateProjectionMatrix(),KA=!0;const zA=new w(S.x,S.y,0);zA.unproject(e.object),e.object.position.sub(zA).add(ZA),e.object.updateMatrixWorld(),PA=j.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),e.zoomToCursor=!1;PA!==null&&(this.screenSpacePanning?e.target.set(0,0,-1).transformDirection(e.object.matrix).multiplyScalar(PA).add(e.object.position):(pw.origin.copy(e.object.position),pw.direction.set(0,0,-1).transformDirection(e.object.matrix),Math.abs(e.object.up.dot(pw.direction))<ZgA?t.lookAt(e.target):(K_.setFromNormalAndCoplanarPoint(e.object.up,e.target),pw.intersectPlane(K_,e.target))))}else e.object.isOrthographicCamera&&(KA=C!==1,KA&&(e.object.zoom=Math.max(e.minZoom,Math.min(e.maxZoom,e.object.zoom/C)),e.object.updateProjectionMatrix()));return C=1,k=!1,KA||H.distanceToSquared(e.object.position)>I||8*(1-O.dot(e.object.quaternion))>I||J.distanceToSquared(e.target)>0?(e.dispatchEvent(N_),H.copy(e.object.position),O.copy(e.object.quaternion),J.copy(e.target),!0):!1}}(),this.dispose=function(){e.domElement.removeEventListener("contextmenu",be),e.domElement.removeEventListener("pointerdown",q),e.domElement.removeEventListener("pointercancel",CA),e.domElement.removeEventListener("wheel",LA),e.domElement.removeEventListener("pointermove",N),window.removeEventListener("pointerup",CA),e._domElementKeyEvents!==null&&(e._domElementKeyEvents.removeEventListener("keydown",se),e._domElementKeyEvents=null)};const e=this,i={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6};let g=i.NONE;const I=1e-6,o=new Fk,s=new Fk;let C=1,a=1;const n=new w,B=new tA,Q=new tA,E=new tA,h=new tA,d=new tA,u=new tA,c=new tA,l=new tA,p=new tA,D=new w,S=new tA;let k=!1;const f=[],U={};let M=!1;function m(j){return j!==null?2*Math.PI/60*e.autoRotateSpeed*j:2*Math.PI/60/60*e.autoRotateSpeed}function x(j){const G=Math.abs(j*.01);return Math.pow(.95,e.zoomSpeed*G)}function L(j){s.theta-=j}function V(j){s.phi-=j}const Y=function(){const j=new w;return function(G,F){j.setFromMatrixColumn(F,0),j.multiplyScalar(-G),n.add(j)}}(),P=function(){const j=new w;return function(G,F){e.screenSpacePanning===!0?j.setFromMatrixColumn(F,1):(j.setFromMatrixColumn(F,0),j.crossVectors(e.object.up,j)),j.multiplyScalar(G),n.add(j)}}(),b=function(){const j=new w,G=new w;return function(F,H){const O=e.domElement;if(e.object.isPerspectiveCamera){e.object.getWorldPosition(G),j.copy(G).sub(e.target);let J=j.length();J*=Math.tan(e.object.fov/2*Math.PI/180),Y(2*F*J/O.clientHeight,e.object.matrixWorld),P(2*H*J/O.clientHeight,e.object.matrixWorld)}else e.object.isOrthographicCamera?(Y(F*(e.object.right-e.object.left)/e.object.zoom/O.clientWidth,e.object.matrixWorld),P(H*(e.object.top-e.object.bottom)/e.object.zoom/O.clientHeight,e.object.matrixWorld)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),e.enablePan=!1)}}();function T(j){e.object.isPerspectiveCamera||e.object.isOrthographicCamera?C/=j:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),e.enableZoom=!1)}function _(j){e.object.isPerspectiveCamera||e.object.isOrthographicCamera?C*=j:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),e.enableZoom=!1)}function eA(j,G){if(!e.zoomToCursor)return;k=!0;const F=e.domElement.getBoundingClientRect(),H=j-F.left,O=G-F.top,J=F.width,Z=F.height;S.x=H/J*2-1,S.y=-(O/Z)*2+1,D.set(S.x,S.y,1).unproject(e.object).sub(e.object.position).normalize()}function $(j){return Math.max(e.minDistance,Math.min(e.maxDistance,j))}function IA(j){B.set(j.clientX,j.clientY)}function yA(j){eA(j.clientX,j.clientX),c.set(j.clientX,j.clientY)}function xA(j){h.set(j.clientX,j.clientY)}function OA(j){Q.set(j.clientX,j.clientY),E.subVectors(Q,B).multiplyScalar(e.rotateSpeed);const G=e.domElement;L(2*Math.PI*E.x/G.clientHeight),V(2*Math.PI*E.y/G.clientHeight),B.copy(Q),e.update()}function $A(j){l.set(j.clientX,j.clientY),p.subVectors(l,c),p.y>0?T(x(p.y)):p.y<0&&_(x(p.y)),c.copy(l),e.update()}function rA(j){d.set(j.clientX,j.clientY),u.subVectors(d,h).multiplyScalar(e.panSpeed),b(u.x,u.y),h.copy(d),e.update()}function RA(j){eA(j.clientX,j.clientY),j.deltaY<0?_(x(j.deltaY)):j.deltaY>0&&T(x(j.deltaY)),e.update()}function jA(j){let G=!1;switch(j.code){case e.keys.UP:j.ctrlKey||j.metaKey||j.shiftKey?V(2*Math.PI*e.rotateSpeed/e.domElement.clientHeight):b(0,e.keyPanSpeed),G=!0;break;case e.keys.BOTTOM:j.ctrlKey||j.metaKey||j.shiftKey?V(-2*Math.PI*e.rotateSpeed/e.domElement.clientHeight):b(0,-e.keyPanSpeed),G=!0;break;case e.keys.LEFT:j.ctrlKey||j.metaKey||j.shiftKey?L(2*Math.PI*e.rotateSpeed/e.domElement.clientHeight):b(e.keyPanSpeed,0),G=!0;break;case e.keys.RIGHT:j.ctrlKey||j.metaKey||j.shiftKey?L(-2*Math.PI*e.rotateSpeed/e.domElement.clientHeight):b(-e.keyPanSpeed,0),G=!0;break}G&&(j.preventDefault(),e.update())}function YA(j){if(f.length===1)B.set(j.pageX,j.pageY);else{const G=Qe(j),F=.5*(j.pageX+G.x),H=.5*(j.pageY+G.y);B.set(F,H)}}function WA(j){if(f.length===1)h.set(j.pageX,j.pageY);else{const G=Qe(j),F=.5*(j.pageX+G.x),H=.5*(j.pageY+G.y);h.set(F,H)}}function BA(j){const G=Qe(j),F=j.pageX-G.x,H=j.pageY-G.y,O=Math.sqrt(F*F+H*H);c.set(0,O)}function TA(j){e.enableZoom&&BA(j),e.enablePan&&WA(j)}function W(j){e.enableZoom&&BA(j),e.enableRotate&&YA(j)}function GA(j){if(f.length==1)Q.set(j.pageX,j.pageY);else{const F=Qe(j),H=.5*(j.pageX+F.x),O=.5*(j.pageY+F.y);Q.set(H,O)}E.subVectors(Q,B).multiplyScalar(e.rotateSpeed);const G=e.domElement;L(2*Math.PI*E.x/G.clientHeight),V(2*Math.PI*E.y/G.clientHeight),B.copy(Q)}function fA(j){if(f.length===1)d.set(j.pageX,j.pageY);else{const G=Qe(j),F=.5*(j.pageX+G.x),H=.5*(j.pageY+G.y);d.set(F,H)}u.subVectors(d,h).multiplyScalar(e.panSpeed),b(u.x,u.y),h.copy(d)}function _A(j){const G=Qe(j),F=j.pageX-G.x,H=j.pageY-G.y,O=Math.sqrt(F*F+H*H);l.set(0,O),p.set(0,Math.pow(l.y/c.y,e.zoomSpeed)),T(p.y),c.copy(l);const J=(j.pageX+G.x)*.5,Z=(j.pageY+G.y)*.5;eA(J,Z)}function hA(j){e.enableZoom&&_A(j),e.enablePan&&fA(j)}function Ee(j){e.enableZoom&&_A(j),e.enableRotate&&GA(j)}function q(j){e.enabled!==!1&&(f.length===0&&(e.domElement.addEventListener("pointermove",N),window.addEventListener("pointerup",CA)),ne(j),j.pointerType==="touch"?De(j):bA(j))}function N(j){e.enabled!==!1&&(j.pointerType==="touch"?vA(j):MA(j))}function CA(j){switch(Be(j),f.length){case 0:e.domElement.removeEventListener("pointermove",N),e.domElement.removeEventListener("pointerup",CA),e.dispatchEvent(F_),g=i.NONE;break;case 1:const G=f[0],F=U[G];De({pointerId:G,pageX:F.x,pageY:F.y});break}}function bA(j){let G;switch(j.button){case 0:G=e.mouseButtons.LEFT;break;case 1:G=e.mouseButtons.MIDDLE;break;case 2:G=e.mouseButtons.RIGHT;break;default:G=-1}switch(G){case Sr.DOLLY:if(e.enableZoom===!1)return;yA(j),g=i.DOLLY;break;case Sr.ROTATE:if(j.ctrlKey||j.metaKey||j.shiftKey){if(e.enablePan===!1)return;xA(j),g=i.PAN}else{if(e.enableRotate===!1)return;IA(j),g=i.ROTATE}break;case Sr.PAN:if(j.ctrlKey||j.metaKey||j.shiftKey){if(e.enableRotate===!1)return;IA(j),g=i.ROTATE}else{if(e.enablePan===!1)return;xA(j),g=i.PAN}break;default:g=i.NONE}g!==i.NONE&&e.dispatchEvent(MU)}function MA(j){switch(g){case i.ROTATE:if(e.enableRotate===!1)return;OA(j);break;case i.DOLLY:if(e.enableZoom===!1)return;$A(j);break;case i.PAN:if(e.enablePan===!1)return;rA(j);break}}function LA(j){e.enabled===!1||e.enableZoom===!1||g!==i.NONE||(j.preventDefault(),e.dispatchEvent(MU),RA(ge(j)),e.dispatchEvent(F_))}function ge(j){const G=j.deltaMode,F={clientX:j.clientX,clientY:j.clientY,deltaY:j.deltaY};switch(G){case 1:F.deltaY*=16;break;case 2:F.deltaY*=100;break}return j.ctrlKey&&!M&&(F.deltaY*=10),F}function HA(j){j.key==="Control"&&(M=!0,e.domElement.getRootNode().addEventListener("keyup",XA,{passive:!0,capture:!0}))}function XA(j){j.key==="Control"&&(M=!1,e.domElement.getRootNode().removeEventListener("keyup",XA,{passive:!0,capture:!0}))}function se(j){e.enabled===!1||e.enablePan===!1||jA(j)}function De(j){switch(kA(j),f.length){case 1:switch(e.touches.ONE){case fr.ROTATE:if(e.enableRotate===!1)return;YA(j),g=i.TOUCH_ROTATE;break;case fr.PAN:if(e.enablePan===!1)return;WA(j),g=i.TOUCH_PAN;break;default:g=i.NONE}break;case 2:switch(e.touches.TWO){case fr.DOLLY_PAN:if(e.enableZoom===!1&&e.enablePan===!1)return;TA(j),g=i.TOUCH_DOLLY_PAN;break;case fr.DOLLY_ROTATE:if(e.enableZoom===!1&&e.enableRotate===!1)return;W(j),g=i.TOUCH_DOLLY_ROTATE;break;default:g=i.NONE}break;default:g=i.NONE}g!==i.NONE&&e.dispatchEvent(MU)}function vA(j){switch(kA(j),g){case i.TOUCH_ROTATE:if(e.enableRotate===!1)return;GA(j),e.update();break;case i.TOUCH_PAN:if(e.enablePan===!1)return;fA(j),e.update();break;case i.TOUCH_DOLLY_PAN:if(e.enableZoom===!1&&e.enablePan===!1)return;hA(j),e.update();break;case i.TOUCH_DOLLY_ROTATE:if(e.enableZoom===!1&&e.enableRotate===!1)return;Ee(j),e.update();break;default:g=i.NONE}}function be(j){e.enabled!==!1&&j.preventDefault()}function ne(j){f.push(j.pointerId)}function Be(j){delete U[j.pointerId];for(let G=0;G<f.length;G++)if(f[G]==j.pointerId){f.splice(G,1);return}}function kA(j){let G=U[j.pointerId];G===void 0&&(G=new tA,U[j.pointerId]=G),G.set(j.pageX,j.pageY)}function Qe(j){const G=j.pointerId===f[0]?f[1]:f[0];return U[G]}e.domElement.addEventListener("contextmenu",be),e.domElement.addEventListener("pointerdown",q),e.domElement.addEventListener("pointercancel",CA),e.domElement.addEventListener("wheel",LA,{passive:!1}),e.domElement.getRootNode().addEventListener("keydown",HA,{passive:!0,capture:!0}),this.update()}};class J_ extends DA{constructor(A,e,i,g=128){if(e<=0||i<=0||g<=0)throw new Error("GroundedSkybox height, radius, and resolution must be positive.");const I=new Ls(i,2*g,g);I.scale(1,1,-1);const o=I.getAttribute("position"),s=new w;for(let C=0;C<o.count;++C)if(s.fromBufferAttribute(o,C),s.y<0){const a=-e*3/2,n=s.y<a?-e/s.y:1-s.y*s.y/(3*a*a);s.multiplyScalar(n),s.toArray(o.array,3*C)}o.needsUpdate=!0,super(I,new st({map:A,depthWrite:!1}))}}const Dw=Symbol("cameraController");function XgA(t){return t[Dw]}function v_(t,A,e){e?t[Dw]=A:t[Dw]===A&&(t[Dw]=null)}const b_=Symbol("camera autofit");function $gA(t){return t[b_]===void 0?!0:t[b_]!==!1}var AIA=Object.defineProperty,eIA=Object.getOwnPropertyDescriptor,tIA=(t,A,e,i)=>{for(var g=i>1?void 0:i?eIA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&AIA(A,e,g),g};class Ad extends JA{constructor(){super(...arguments),r(this,"constraintActive",!0),r(this,"locked",!1),r(this,"sources",[])}}tIA([y(wA)],Ad.prototype,"sources",2);function iIA(t){Il(t,Yi.ContextCreated)}function gIA(t){Il(t,Pi.Start)}function q_(t){Il(t,Pi.Update)}function IIA(t){Il(t,Pi.OnBeforeRender)}class fB{constructor(){r(this,"bb",null),r(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}static sizeOf(){return 12}static createVec3(A,e,i,g){return A.prep(4,12),A.writeFloat32(g),A.writeFloat32(i),A.writeFloat32(e),A.offset()}}class L_{constructor(){r(this,"bb",null),r(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}position(A){return(A||new fB).__init(this.bb_pos,this.bb)}rotation(A){return(A||new fB).__init(this.bb_pos+12,this.bb)}scale(A){return(A||new fB).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(A,e,i,g,I,o,s,C,a,n){return A.prep(4,36),A.prep(4,12),A.writeFloat32(n),A.writeFloat32(a),A.writeFloat32(C),A.prep(4,12),A.writeFloat32(s),A.writeFloat32(o),A.writeFloat32(I),A.prep(4,12),A.writeFloat32(g),A.writeFloat32(i),A.writeFloat32(e),A.offset()}}class Va{constructor(){r(this,"bb",null),r(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}static getRootAsSyncedTransformModel(A,e){return(e||new Va).__init(A.readInt32(A.position())+A.position(),A)}static getSizePrefixedRootAsSyncedTransformModel(A,e){return A.setPosition(A.position()+$G),(e||new Va).__init(A.readInt32(A.position())+A.position(),A)}guid(A){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,A):null}fast(){const A=this.bb.__offset(this.bb_pos,6);return A?!!this.bb.readInt8(this.bb_pos+A):!1}transform(A){const e=this.bb.__offset(this.bb_pos,8);return e?(A||new L_).__init(this.bb_pos+e,this.bb):null}dontSave(){const A=this.bb.__offset(this.bb_pos,10);return A?!!this.bb.readInt8(this.bb_pos+A):!1}static startSyncedTransformModel(A){A.startObject(4)}static addGuid(A,e){A.addFieldOffset(0,e,0)}static addFast(A,e){A.addFieldInt8(1,+e,0)}static addTransform(A,e){A.addFieldStruct(2,e,0)}static addDontSave(A,e){A.addFieldInt8(3,+e,0)}static endSyncedTransformModel(A){return A.endObject()}static finishSyncedTransformModelBuffer(A,e){A.finish(e)}static finishSizePrefixedSyncedTransformModelBuffer(A,e){A.finish(e,void 0,!0)}}var cg=(t=>(t[t.Average=0]="Average",t[t.Multiply=1]="Multiply",t[t.Minimum=2]="Minimum",t[t.Maximum=3]="Maximum",t))(cg||{}),yw=(t=>(t[t.Discrete=0]="Discrete",t[t.Continuous=1]="Continuous",t))(yw||{}),vi=(t=>(t[t.None=0]="None",t[t.FreezePositionX=2]="FreezePositionX",t[t.FreezePositionY=4]="FreezePositionY",t[t.FreezePositionZ=8]="FreezePositionZ",t[t.FreezePosition=14]="FreezePosition",t[t.FreezeRotationX=16]="FreezeRotationX",t[t.FreezeRotationY=32]="FreezeRotationY",t[t.FreezeRotationZ=64]="FreezeRotationZ",t[t.FreezeRotation=112]="FreezeRotation",t[t.FreezeAll=126]="FreezeAll",t))(vi||{}),HE=(t=>(t[t.None=0]="None",t[t.X=2]="X",t[t.Y=4]="Y",t[t.Z=8]="Z",t[t.All=-1]="All",t))(HE||{});const Jg=function(t,A){return function(e,i,g){oIA(e,i,g,t,A)}};function oIA(t,A,e,i,g){if(!g&&!i&&!t.onValidate)return;if(e!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",t,A,e),wi("Invalid usage of validate decorator. Only fields can be validated. Property: "+A,vo.Error);return}let I="";if(typeof A=="string"?I=A:I=A.name,t.__internalAwake){const o=Symbol(I),s=t.__internalAwake;t.__internalAwake=function(){var C;if(!this.onValidate){Se()&&console.warn('Usage of @validate decorate detected but there is no onValidate method in your class: "'+((C=t.constructor)==null?void 0:C.name)+'"');return}if(this[o]===void 0){this[o]=this[I];const a=this[I];if(a instanceof tA||a instanceof w||a instanceof ie||a instanceof FA){const n=this[I];MD(n,()=>{this.onValidate(I)})}Object.defineProperty(this,I,{set:function(n){var B;if(this[FG]===!0)this[o]=n;else{i?.call(this,n);const Q=this[o];this[o]=n,(B=this.onValidate)==null||B.call(this,I,Q)}},get:function(){return g?.call(this),this[o]}})}s.call(this)}}}const sIA=function(t){return function(A,e,i){let g="";typeof e=="string"?g=e:g=e.name;const I=t.prototype,o=Object.getOwnPropertyDescriptor(I,g);if(!(o!=null&&o.value)){console.warn("Can not apply prefix: type does not have method named",e,t);return}const s=o.value,C=A[g];Object.defineProperty(I,g,{value:function(...a){const n=C?.call(this,...a);if(n instanceof Promise){n.then(B=>{if(B!==!1)return s.call(this,...a)});return}if(n!==!1)return s.call(this,...a)}})}};var CIA=Object.defineProperty,aIA=Object.getOwnPropertyDescriptor,Vo=(t,A,e,i)=>{for(var g=i>1?void 0:i?aIA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&CIA(A,e,g),g};class nIA{constructor(A,e){r(this,"positionChanged",!1),r(this,"rotationChanged",!1),r(this,"position"),r(this,"quaternion"),r(this,"_positionKeys",["x","y","z"]),r(this,"_quaternionKeys",["_x","_y","_z","_w"]),r(this,"mute",!1),r(this,"context"),r(this,"obj"),r(this,"_positionWatch"),r(this,"_rotationWatch"),this.context=e,this.obj=A}get isDirty(){return this.positionChanged||this.rotationChanged}reset(A=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,A){if(this.position)for(const e of this._positionKeys)delete this.position[e];if(this.quaternion)for(const e of this._quaternionKeys)delete this.quaternion[e]}}syncValues(){for(const A of this._positionKeys)this.position[A]=this.obj.position[A];for(const A of this._quaternionKeys)this.quaternion[A]=this.obj.quaternion[A]}applyValues(){if(this.positionChanged&&this.position)for(const A of this._positionKeys){const e=this.position[A];e!==void 0&&(this.obj.position[A]=e)}if(this.rotationChanged&&this.quaternion)for(const A of this._quaternionKeys){const e=this.quaternion[A];e!==void 0&&(this.obj.quaternion[A]=e)}}start(A,e){this.reset(),A&&(this._positionWatch||(this._positionWatch=new Oa(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((I,o)=>{var s;if((s=this.context.physics.engine)!=null&&s.isUpdating||this.mute)return;const C=this.position[o];Math.abs(C-I)<1e-5||(this.position[o]=I,this.positionChanged=!0)})),e&&(this._rotationWatch||(this._rotationWatch=new Oa(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((I,o)=>{var s;if((s=this.context.physics.engine)!=null&&s.isUpdating||this.mute)return;const C=this.quaternion[o];Math.abs(C-I)<1e-5||(this.quaternion[o]=I,this.rotationChanged=!0)}));const i=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),g=new NA;this.obj.matrixWorld.multiplyMatrices=(I,o)=>{var s;return(s=this.context.physics.engine)!=null&&s.isUpdating||this.mute||g.equals(I)||(this.positionChanged=!0,this.rotationChanged=!0,g.copy(I)),i(I,o)}}stop(){var A,e;(A=this._positionWatch)==null||A.revoke(),(e=this._rotationWatch)==null||e.revoke()}}var RU;const UU=(RU=class extends JA{constructor(){super(...arguments),r(this,"autoMass",!0),r(this,"_mass",0),r(this,"useGravity",!0),r(this,"constraints",vi.None),r(this,"isKinematic",!1),r(this,"drag",0),r(this,"angularDrag",1),r(this,"detectCollisions",!0),r(this,"sleepThreshold",.01),r(this,"collisionDetectionMode",yw.Discrete),r(this,"_gravityScale",1),r(this,"dominanceGroup",0),r(this,"_propertiesChanged",!1),r(this,"_currentVelocity",new w),r(this,"_smoothedVelocity",new w),r(this,"_smoothedVelocityGetter",new w),r(this,"_lastPosition",new w),r(this,"_watch")}set mass(t){t!==this._mass&&(this._mass=t,this._propertiesChanged=!0,this.__didAwake&&(this.autoMass=!1))}get mass(){var t,A;return this.autoMass?((A=(t=this.context.physics.engine)==null?void 0:t.getBody(this))==null?void 0:A.mass())??-1:this._mass}get lockPositionX(){return(this.constraints&vi.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&vi.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&vi.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&vi.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&vi.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&vi.FreezeRotationZ)!==0}set lockPositionX(t){t?this.constraints|=vi.FreezePositionX:this.constraints&=~vi.FreezePositionX}set lockPositionY(t){t?this.constraints|=vi.FreezePositionY:this.constraints&=~vi.FreezePositionY}set lockPositionZ(t){t?this.constraints|=vi.FreezePositionZ:this.constraints&=~vi.FreezePositionZ}set lockRotationX(t){t?this.constraints|=vi.FreezeRotationX:this.constraints&=~vi.FreezeRotationX}set lockRotationY(t){t?this.constraints|=vi.FreezeRotationY:this.constraints&=~vi.FreezeRotationY}set lockRotationZ(t){t?this.constraints|=vi.FreezeRotationZ:this.constraints&=~vi.FreezeRotationZ}set gravityScale(t){this._gravityScale=t}get gravityScale(){return this._gravityScale}awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new nIA(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),Pi.LateUpdate)}onDisable(){var t,A;(t=this._watch)==null||t.stop(),(A=this.context.physics.engine)==null||A.removeBody(this)}onDestroy(){var t;(t=this.context.physics.engine)==null||t.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){for(var t,A,e,i;;)this._propertiesChanged&&(this._propertiesChanged=!1,(t=this.context.physics.engine)==null||t.updateProperties(this)),(A=this._watch)!=null&&A.isDirty?(this._watch.mute=!0,this._watch.applyValues(),(e=this.context.physics.engine)==null||e.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):(i=this._watch)==null||i.syncValues(),this.captureVelocity(),yield}teleport(t,A=!0){var e;(e=this._watch)==null||e.reset(!0),A?this.gameObject.position.set(t.x,t.y,t.z):this.setWorldPosition(t.x,t.y,t.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(t=!0){var A;(A=this.context.physics.engine)==null||A.resetForces(this,t)}resetTorques(t=!0){var A;(A=this.context.physics.engine)==null||A.resetTorques(this,t)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){var t;(t=this.context.physics.engine)==null||t.wakeup(this)}get isSleeping(){var t;return(t=this.context.physics.engine)==null?void 0:t.isSleeping(this)}updateProperties(){var t;return this._propertiesChanged=!1,(t=this.context.physics.engine)==null?void 0:t.updateProperties(this)}applyForce(t,A,e=!0){var i;this._propertiesChanged&&this.updateProperties(),(i=this.context.physics.engine)==null||i.addForce(this,t,e)}applyImpulse(t,A=!0){var e;this._propertiesChanged&&this.updateProperties(),(e=this.context.physics.engine)==null||e.applyImpulse(this,t,A)}setForce(t,A,e,i=!0){var g,I,o;(g=this.context.physics.engine)==null||g.resetForces(this,i),typeof t=="number"?(A??(A=0),e??(e=0),(I=this.context.physics.engine)==null||I.addForce(this,{x:t,y:A,z:e},i)):(o=this.context.physics.engine)==null||o.addForce(this,t,i)}getVelocity(){var t;const A=(t=this.context.physics.engine)==null?void 0:t.getLinearVelocity(this);return A?(this._currentVelocity.x=A.x,this._currentVelocity.y=A.y,this._currentVelocity.z=A.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(t,A,e,i=!0){var g,I;if(t instanceof w){const o=t;(g=this.context.physics.engine)==null||g.setLinearVelocity(this,o,i);return}A===void 0||e===void 0||(I=this.context.physics.engine)==null||I.setLinearVelocity(this,{x:t,y:A,z:e},i)}getAngularVelocity(){var t;const A=(t=this.context.physics.engine)==null?void 0:t.getAngularVelocity(this);return A?(this._currentVelocity.x=A.x,this._currentVelocity.y=A.y,this._currentVelocity.z=A.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setAngularVelocity(t,A,e,i=!0){var g,I;if(t instanceof w){const o=t;(g=this.context.physics.engine)==null||g.setAngularVelocity(this,o,i);return}A===void 0||e===void 0||(I=this.context.physics.engine)==null||I.setAngularVelocity(this,{x:t,y:A,z:e},i)}setTorque(t,A,e){this.setAngularVelocity(t,A,e)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(t=null){}captureVelocity(){const t=Ne(this.gameObject);UU.tempPosition.copy(t);const A=t.sub(this._lastPosition);this._lastPosition.copy(UU.tempPosition),this._smoothedVelocity.lerp(A,this.context.time.deltaTime/.1)}},r(RU,"tempPosition",new w),RU);let Pt=UU;Vo([Jg()],Pt.prototype,"autoMass",2),Vo([y()],Pt.prototype,"mass",1),Vo([Jg(),y()],Pt.prototype,"useGravity",2),Vo([Jg(),y()],Pt.prototype,"constraints",2),Vo([Jg(),y()],Pt.prototype,"isKinematic",2),Vo([Jg(),y()],Pt.prototype,"drag",2),Vo([Jg(),y()],Pt.prototype,"angularDrag",2),Vo([Jg(),y()],Pt.prototype,"detectCollisions",2),Vo([Jg(),y()],Pt.prototype,"sleepThreshold",2),Vo([Jg(),y()],Pt.prototype,"collisionDetectionMode",2),Vo([Jg()],Pt.prototype,"_gravityScale",2),Vo([Jg()],Pt.prototype,"dominanceGroup",2);const ma=iA("debugsync"),ed="STRS";tM(ed,Va.getRootAsSyncedTransformModel);const rC=new Ju;function x_(t,A,e=!0){rC.clear();const i=rC.createString(t);Va.startSyncedTransformModel(rC),Va.addGuid(rC,i),Va.addFast(rC,e);const g=A.worldPosition,I=A.worldEuler,o=A.gameObject.scale;Va.addTransform(rC,L_.createTransform(rC,g.x,g.y,g.z,I.x,I.y,I.z,o.x,o.y,o.z));const s=Va.endSyncedTransformModel(rC);return rC.finish(s,ed),rC.asUint8Array()}let NU=0,td=0;q_(t=>{var A;const e=(A=t.connection.currentServerUrl)!=null&&A.includes("glitch")?10:40;td=Math.floor(NU/e),NU=0,ma&&td>0&&console.log("Sync Transform Fast Interval",td)});class Hn extends JA{constructor(){super(...arguments),r(this,"overridePhysics",!0),r(this,"interpolatePosition",!0),r(this,"interpolateRotation",!0),r(this,"fastMode",!1),r(this,"syncDestroy",!1),r(this,"_model",null),r(this,"_needsUpdate",!0),r(this,"rb",null),r(this,"_wasKinematic",!1),r(this,"_receivedDataBefore",!1),r(this,"_targetPosition"),r(this,"_targetRotation"),r(this,"_receivedFastUpdate",!1),r(this,"_shouldRequestOwnership",!1),r(this,"joinedRoomCallback",null),r(this,"receivedDataCallback",null),r(this,"tempEuler",new Wg),r(this,"receivedUpdate",!1),r(this,"lastWorldPos"),r(this,"lastWorldRotation")}requestOwnership(){ma&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}hasOwnership(){var A;return((A=this._model)==null?void 0:A.hasOwnership)??void 0}isOwned(){var A;return(A=this._model)==null?void 0:A.isOwned}awake(){ma&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new w,this._targetRotation=new FA,this.lastWorldPos=new w,this.lastWorldRotation=new FA,this.rb=aA.getComponentInChildren(this.gameObject,Pt),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new pM(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(ht.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(ed,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&VH(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(ht.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(ed,this.receivedDataCallback)}tryGetLastState(){const A=this.context.connection.tryGetState(this.guid);A&&this.onReceivedData(A)}onReceivedData(A){var e;if(!this.destroyed&&typeof A.guid=="function"&&A.guid()===this.guid){ma&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,A),this.receivedUpdate=!0,this._receivedFastUpdate=A.fast();const i=A.transform();if(i){Ts.markDirty(this.gameObject,!0);const g=i.position();g&&(this.interpolatePosition&&((e=this._targetPosition)==null||e.set(g.x(),g.y(),g.z())),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(g.x(),g.y(),g.z()));const I=i.rotation();I&&(this.tempEuler.set(I.x(),I.y(),I.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&dR(this.gameObject,this.tempEuler))}this._receivedDataBefore=!0}}onEnable(){this.lastWorldPos.copy(this.worldPosition),this.lastWorldRotation.copy(this.worldQuaternion),this._needsUpdate=!0,this._model&&this._model.updateIsOwned()}onDisable(){this._model&&this._model.freeOwnership()}onBeforeRender(){if(!this.activeAndEnabled||!this.context.connection.isConnected)return;if(!this.context.connection.isInRoom||!this._model){ma&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());const A=this.worldPosition,e=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){const I=A.distanceTo(this.lastWorldPos),o=e.angleTo(this.lastWorldRotation),s=this._model.hasOwnership||this.fastMode?1e-4:.001;(I>s||o>s)&&(this._model.hasOwnership?this._needsUpdate=!0:(ma&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastWorldPos),this.worldPosition=this.lastWorldPos,A.copy(this.lastWorldPos),this.worldQuaternion=this.lastWorldRotation,e.copy(this.lastWorldRotation),Ts.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const I=this._receivedFastUpdate||this.fastMode?.5:.3;let o=!1;if(this.interpolatePosition&&this._targetPosition){const s=this.worldPosition;s.lerp(this._targetPosition,I),this.worldPosition=s,o=!0}if(this.interpolateRotation&&this._targetRotation){const s=this.worldQuaternion;s.slerp(this._targetRotation,I),this.worldQuaternion=s,o=!0}o&&Ts.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastWorldPos.copy(A),this.lastWorldRotation.copy(e),!this._model)return;if(!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership){this.rb&&(this.rb.isKinematic=this._model.isOwned??!1,this.rb.setVelocity(0,0,0));return}this.rb&&(this._wasKinematic!==void 0&&(ma&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic),this.gameObject.position.distanceTo(new w(0,0,0))>1e3&&(ma&&console.log("RESET",this.name),this.gameObject.position.set(0,1,0),this.rb.setVelocity(0,0,0)));const i=10,g=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%i===0||g)){if(NU++,g&&td>0&&this.context.time.frameCount%td!==0)return;ma&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this.overridePhysics&&this.rb,this._needsUpdate=!1;const I=x_(this.guid,this,!!g);this.context.connection.sendBinary(I)}}}const rIA=iA("debugshadowcomponents");aR.prototype.interactable={get(){return this.interactive},set(t){this.interactable=t}};const Zo=Symbol("shadowDomOwner");class Ys extends JA{constructor(){super(...arguments),r(this,"_shadowComponent",null),r(this,"_controlsChildLayout",!0),r(this,"_root"),r(this,"_parentComponent")}isRoot(){var A;return((A=this.Root)==null?void 0:A.gameObject)===this.gameObject}get canvas(){const A=this.Root;return A!=null&&A.isCanvas?A:null}get Canvas(){return this.canvas}markDirty(){zo.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(A){this._shadowComponent=A}get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(A){this._controlsChildLayout=A,this.shadowComponent&&(this.shadowComponent.autoLayout=A)}get Root(){return this._root===void 0&&(this._root=aA.getComponentInParent(this.gameObject,id)),this._root}__internalNewInstanceCreated(){super.__internalNewInstanceCreated(),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0}onEnable(){super.onEnable()}addShadowComponent(A,e){var i;this.removeShadowComponent();const g=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=aA.getComponentInParent(g,Ys),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}A.name=this.name+" ("+(this.constructor.name??"UI")+")",A.autoLayout=this._parentComponent.controlsChildLayout,A[Zo]=this,this.setShadowComponentOwner(A);let I=!1;if(((i=this.Root)==null?void 0:i.gameObject)===this.gameObject)this.gameObject.add(A);else{const o=this._parentComponent.shadowComponent;o&&(o?.add(A),I=!0)}this.shadowComponent=A,e&&e.shadowComponent&&this.shadowComponent&&e.shadowComponent.add(this.shadowComponent),el&&A.add(new Fo(.5)),this.onAfterAddedToScene(),I&&hH(),rIA&&console.log(this.shadowComponent)}setShadowComponentOwner(A){if(A&&(A[Zo]===void 0||A[Zo]===this)&&(A[Zo]=this,A.children))for(const e of A.children)this.setShadowComponentOwner(e)}traverseOwnedShadowComponents(A,e,i){if(A&&A[Zo]===e){i(A);for(const g of A.children)this.traverseOwnedShadowComponents(g,e,i)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(A){this.shadowComponent&&(this.shadowComponent.interactable=A)}}class id extends Ys{awake(){super.awake()}}class vh{constructor(A,e){r(this,"event"),r(this,"button"),r(this,"buttonName"),r(this,"_used",!1),r(this,"_propagationStopped",!1),r(this,"z__pointer_ctured",!1),r(this,"z__pointer_cture_rleased",!1),r(this,"inputSource"),r(this,"object"),r(this,"point"),r(this,"normal"),r(this,"face"),r(this,"distance"),r(this,"instanceId"),r(this,"isDown"),r(this,"isUp"),r(this,"isPressed"),r(this,"isClick"),r(this,"isDoubleClick"),r(this,"input"),this.event=e,this.input=A,this.button=e.button}get deviceIndex(){return this.event.deviceIndex}get pointerId(){return this.event.pointerId}get pressure(){return this.event.pressure}get used(){return this._used}use(){this._used||(this._used=!0,this.pointerId!==void 0&&this.input.setPointerUsed(this.pointerId))}get propagationStopped(){return this._propagationStopped}stopPropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}stopImmediatePropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}setPointerCapture(){this.z__pointer_ctured=!0}releasePointerCapture(){this.z__pointer_cture_rleased=!0}get mode(){return this.event.mode}clone(){const A=new vh(this.input,this.event);return Object.assign(A,this),A}Use(){this.use()}StopPropagation(){this.event.stopImmediatePropagation()}}function FU(t,A){return aA.foreachComponent(t,e=>{if(!e.enabled)return;const i=e;if(A)switch(A){case"pointerdown":if(i.onPointerDown)return!0;break;case"pointerup":if(i.onPointerUp||i.onPointerClick)return!0;break;case"pointermove":if(i.onPointerEnter||i.onPointerExit||i.onPointerMove)return!0;break}else if(i.onPointerDown||i.onPointerUp||i.onPointerEnter||i.onPointerExit||i.onPointerClick)return!0},!1)===!0}var BIA=Object.defineProperty,QIA=Object.getOwnPropertyDescriptor,EIA=(t,A,e,i)=>{for(var g=i>1?void 0:i?QIA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&BIA(A,e,g),g};class gd extends JA{awake(){zo.createIfNoneExists(this.context)}onEnable(){var A;(A=zo.get(this.context))==null||A.register(this)}onDisable(){var A;(A=zo.get(this.context))==null||A.unregister(this)}}class ro extends gd{constructor(){super(...arguments),r(this,"targets",null),r(this,"raycastHits",[]),r(this,"ignoreSkinnedMeshes",!1)}start(){this.targets=[this.gameObject]}performRaycast(A=null){if(!this.targets)return null;A??(A=new Oo),A.targets=this.targets,A.results=this.raycastHits;const e=A.testObject;this.ignoreSkinnedMeshes&&(A.testObject=g=>g instanceof ls?"continue in children":e?e(g):!0);const i=this.context.physics.raycast(A);return A.testObject=e,i}}EIA([y()],ro.prototype,"ignoreSkinnedMeshes",2);class ww extends ro{constructor(){super(),this.ignoreSkinnedMeshes=!0}}class Id extends gd{performRaycast(A){if(!de.active||!(A!=null&&A.ray))return null;const e=A.ray.origin,i=.01;return this.context.physics.sphereOverlap(e,i)}}class Sw{static getObject(A){const e=A[Zo];return e&&(e.isComponent===!0?A=e.gameObject:A=e),A}static isInteractable(A,e){if(e&&(e.canvasGroup=void 0,e.graphic=void 0),A==null||!A.visible||(A=this.getObject(A),!A.visible))return!1;const i=this.tryFindCanvasGroup(A);if(i?.isCanvasGroup===!0&&(e&&(e.canvasGroup=i),i.blocksRaycasts===!1||i.interactable===!1))return!1;const g=lB(A,I=>{if(I.isGraphic===!0)return I},!1);return e&&g?.isGraphic===!0&&(e.graphic=g),!(g?.raycastTarget===!1||g?.layer===2)}static tryFindCanvasGroup(A){if(!A)return null;const e=lB(A,i=>{const g=i;if(g.blocksRaycasts!==void 0&&g.interactable!==void 0)return g},!1);return e!==void 0?e:this.tryFindCanvasGroup(A.parent)}}function KU(t){return t[Zo]||(t.parent?KU(t.parent):null)}function hIA(t){return t.isUI===!0||typeof t[Zo]=="object"}function fw(t,A){if(!t)return;const e=t.material;if(e?.isMaterial===!0){const i=t.parent;i&&i.isText,e.side=A.doubleSided??!0?dt:yg,e.shadowSide=A.doubleSided?dt:yg,t.castShadow=A.castShadows?A.castShadows:!1,t.receiveShadow=A.receiveShadows?A.receiveShadows:!1}for(const i of t.children)fw(i,A)}function _E(t,A,e){t[A]===void 0&&console.warn("Field",A,"is undefined on",t);const i=Proxy.revocable(t[A],{set(o,s,C,a){const n=o[s],B=Reflect.set(o,s,C,a);return e(C,n),B}}),g=i.revoke,I=t[A];return i.revoke=()=>{t[A]=I,g()},t[A]=i.proxy,i}const Y_=Symbol("Scheduled action");function cIA(t,A,e=Pi.OnBeforeRender){let i=t[Y_];i||(i=t[Y_]={});const g=A.name;i[e]||(i[e]={});const I=i[e];if(I[g])return;function*o(){A?.call(t),I[g]=null}const s=t.startCoroutine(o(),e);I[g]=s}const ka=iA("debugeventsystem");var JU=(t=>(t.BeforeHandleInput="BeforeHandleInput",t.AfterHandleInput="AfterHandleInput",t))(JU||{});const Ga=class extends JA{constructor(){super(),r(this,"raycaster",[]),r(this,"_handleInputFn"),r(this,"pressedByID",new Map),r(this,"hoveredByID",new Map),r(this,"_sortedHits",[]),r(this,"_testObjectsCache",new Map),r(this,"_currentlyActiveRaycaster",null),r(this,"_currentPointerEventName",null),r(this,"shouldRaycastObject",t=>{var A;let e=null;if(hIA(t)&&(e=(A=t[Zo])==null?void 0:A.gameObject),this._testObjectsCache.has(t)||e&&this._testObjectsCache.has(e))return this._testObjectsCache.get(t)===!1?"continue in children":!0;{let i=FU(t,this._currentPointerEventName);if(!i&&e&&(i=FU(e,this._currentPointerEventName)),i){this._testObjectsCache.set(t,!0);for(const g of t.children)this.shouldRaycastObject_AddToYesCache(g);return!0}return this._testObjectsCache.set(t,!1),"continue in children"}}),r(this,"_sortingBuffer",[]),r(this,"_noDepthTestingResults",[]),r(this,"out",{}),r(this,"_capturedPointer",{}),r(this,"pointerEnterSymbol",Symbol("pointerEnter")),r(this,"pointerExitSymbol",Symbol("pointerExit")),r(this,"currentActiveMeshUIComponents",[]),Ga.systems.push(this)}static createIfNoneExists(t){this.didSearchEventSystem||(this.didSearchEventSystem=!0,Ga.systems.length<=0&&Ga.systems.push(...aA.findObjectsOfType(Ga,t)));for(const e of Ga.systems)if(e.context===t)return;const A=new wA;aA.addNewComponent(A,Ga),t.scene.add(A)}static get systems(){const t=ve.Current;return this._eventSystemMap.has(t)||this._eventSystemMap.set(t,[]),this._eventSystemMap.get(t)}static get(t){const A=this._eventSystemMap.get(t);return A&&A.length>0?A[0]:null}static get instance(){return this.systems[0]}static ensureUpdateMeshUI(t,A,e=!1){_n.update(t,A,e)}static markUIDirty(t){_n.markDirty()}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}onDestroy(){Ga.systems.splice(Ga.systems.indexOf(this),1)}start(){if(this.raycaster.length<=0&&!aA.findObjectOfType(gd,this.context)){const t=aA.addNewComponent(this.context.scene,ro);this.raycaster.push(t),(Se()||ka)&&console.warn("Added an ObjectRaycaster to the scene because no raycaster was found.")}}register(t){var A;t&&this.raycaster&&!this.raycaster.includes(t)&&((A=this.raycaster)==null||A.push(t))}unregister(t){var A,e;const i=(A=this.raycaster)==null?void 0:A.indexOf(t);i!==void 0&&i!==-1&&((e=this.raycaster)==null||e.splice(i,1))}onEnable(){this._handleInputFn??(this._handleInputFn=this.onPointerEvent.bind(this)),this.context.input.addEventListener(Ai.PointerDown,this._handleInputFn),this.context.input.addEventListener(Ai.PointerUp,this._handleInputFn),this.context.input.addEventListener(Ai.PointerMove,this._handleInputFn)}onDisable(){this.context.input.removeEventListener(Ai.PointerDown,this._handleInputFn),this.context.input.removeEventListener(Ai.PointerUp,this._handleInputFn),this.context.input.removeEventListener(Ai.PointerMove,this._handleInputFn)}onBeforeRender(){this.resetMeshUIStates()}onPointerEvent(t){if(t===void 0||t.propagationStopped)return;const A=new vh(this.context.input,t);this._currentPointerEventName=t.type,A.inputSource=this.context.input,A.isClick=t.isClick,A.isDoubleClick=t.isDoubleClick,A.isDown=t.type==Ai.PointerDown,A.isUp=t.type==Ai.PointerUp,A.isPressed=this.context.input.getPointerPressed(t.pointerId),ka&&(A.isDown?console.log("DOWN",A.pointerId):A.isUp&&console.log("UP",A.pointerId),A.isClick&&console.log("CLICK",A.pointerId));const e=new Oo;t.ray?e.ray=t.ray:e.screenPoint=this.context.input.getPointerPositionRC(t.pointerId);const i=this.performRaycast(e);ka&&A.isClick&&wi("EventSystem: "+A.pointerId+" - "+this.context.time.frame+" - Up:"+A.isUp+", Down:"+A.isDown);const g={sender:this,args:A,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:g})),this.handleIntersections(i,A),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:g}))}shouldRaycastObject_AddToYesCache(t){this._testObjectsCache.set(t,!0);for(const A of t.children)this.shouldRaycastObject_AddToYesCache(A)}performRaycast(t){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,t||(t=new Oo),t.testObject=this.shouldRaycastObject;for(const A of this.raycaster){if(!A.activeAndEnabled)continue;this._currentlyActiveRaycaster=A;const e=A.performRaycast(t);this._currentlyActiveRaycaster=null,e&&e.length>0&&this._sortedHits.push(...e)}return this._sortedHits.sort((A,e)=>A.distance-e.distance),this._sortedHits}assignHitInformation(t,A){A?(t.point=A.point,t.normal=A.normal,t.face=A.face,t.distance=A.distance,t.instanceId=A.instanceId):(t.point=void 0,t.normal=void 0,t.face=void 0,t.distance=void 0,t.instanceId=void 0)}handleIntersections(t,A){var e;if(t!=null&&t.length){t=this.sortCandidates(t);for(const g of t){if(A.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(A,g),this.handleEventOnObject(g.object,A))return!0}}this.assignHitInformation(A,t?.[0]),this.invokePointerCapture(A);const i=this.hoveredByID.get(A.pointerId);return i&&this.propagatePointerExit(i.obj,i.data,null),this.hoveredByID.delete(A.pointerId),A.isUp&&((e=this.pressedByID.get(A.pointerId))==null||e.handlers.forEach(g=>this.invokeOnPointerUp(A,g)),this.pressedByID.delete(A.pointerId)),!1}sortCandidates(t){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let A=0;A<t.length;A++){const e=t[A],i=e.object;if(i.material&&i.material.depthTest===!1){this._noDepthTestingResults.push(e);continue}this._sortingBuffer.push(e)}for(const A of this._sortingBuffer)this._noDepthTestingResults.push(A);return this._noDepthTestingResults}handleEventOnObject(t,A){if(!this.testIsVisible(t))return A.isClick&&ka&&console.log("not allowed",t),!1;if(A.pointerId===void 0)return ka&&console.error("Event without pointer can't be handled",A),!1;A.object=t;const e=t.parent;let i=!1;const g=A.isClick??!1;let I=null;if(e&&e.isUI){const a=(A.isPressed||A.isClick)??!1;if(e[Zo]){const n=e[Zo].gameObject;if(n){if(!Sw.isInteractable(n,this.out))return!1;I=this.out.canvasGroup??null,this.handleMeshUIIntersection(t,a),t=n,i=!0}}if(!i&&this.handleMeshUiObjectWithoutShadowDom(e,a))return!0}g&&ka&&console.log(this.context.time.frame,t);const o=this.hoveredByID.get(A.pointerId),s=o?.obj;s!==t&&s&&this.propagatePointerExit(s,o.data,t);const C=this.hoveredByID.get(A.pointerId);if(C?(C.obj=t,C.data=A):this.hoveredByID.set(A.pointerId,{obj:t,data:A}),A.isDown){const a=this.pressedByID.get(A.pointerId);a?(a.obj=t,a.data=A):this.pressedByID.set(A.pointerId,{obj:t,data:A,handlers:new Set})}return(I===null||I.interactable)&&this.handleMainInteraction(t,A,s??null),!0}propagate(t,A){for(;t;)aA.foreachComponent(t,e=>{A(e)},!1),t=t.parent}handleMainInteraction(t,A,e){const i=this.pressedByID.get(A.pointerId),g=e!==t;let I=!0;switch(A.event.pointerType){case"mouse":case"touch":const o=this.context.input.getPointerPositionLastFrame(A.pointerId),s=this.context.input.getPointerPosition(A.pointerId);I=o&&!Ie.approximately(o,s);break}this.propagate(t,o=>{const s=o;s.interactable!==!1&&(!s.activeAndEnabled||!s.enabled||(s.onPointerEnter&&g&&this.handlePointerEnter(s,A),A.isDown&&s.onPointerDown&&(s.onPointerDown(A),i?.handlers.add(s),this.handlePointerCapture(A,s)),s.onPointerMove&&(I&&s.onPointerMove(A),this.handlePointerCapture(A,s)),A.isUp&&s.onPointerUp&&(this.invokeOnPointerUp(A,s),i?.handlers.delete(s)),A.isClick&&s.onPointerClick&&s.onPointerClick(A)))}),A.isUp&&(i?.handlers.forEach(o=>{this.invokeOnPointerUp(A,o)}),this.pressedByID.delete(A.pointerId))}propagatePointerExit(t,A,e){this.propagate(t,i=>{if(!i.gameObject||i.destroyed)return;const g=i;if(g.onPointerExit){if(e&&this.isChild(e,i.gameObject))return;this.handlePointerExit(g,A)}})}invokeOnPointerUp(t,A){var e;(e=A.onPointerUp)==null||e.call(A,t),this.releasePointerCapture(t,A)}handlePointerEnter(t,A){t.onPointerEnter&&this.updatePointerState(t,A.pointerId,this.pointerEnterSymbol,!0)&&t.onPointerEnter(A),this.updatePointerState(t,A.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(t,A){t.onPointerExit&&this.updatePointerState(t,A.pointerId,this.pointerExitSymbol,!0)&&t.onPointerExit(A),this.updatePointerState(t,A.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(t,A,e,i){let g=t[e];if(i)return g&&g.includes(A)?!1:(g=g||[],g.push(A),t[e]=g,!0);{if(!g||!g.includes(A))return!1;const I=g.indexOf(A);return I!==-1&&g.splice(I,1),!0}}handlePointerCapture(t,A){if(t.z__pointer_ctured){t.z__pointer_ctured=!1;const e=t.pointerId;if(A.onPointerMove){const i=this._capturedPointer[e]||[];i.push(A),this._capturedPointer[e]=i}else Se()&&!A.z__warned_no_pointermove&&(A.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 t.z__pointer_cture_rleased&&(t.z__pointer_cture_rleased=!1,this.releasePointerCapture(t,A))}releasePointerCapture(t,A){const e=t.pointerId;if(this._capturedPointer[e]){const i=this._capturedPointer[e].indexOf(A);i!==-1&&(this._capturedPointer[e].splice(i,1),ka&&console.log("released pointer capture",e,A,this._capturedPointer))}}invokePointerCapture(t){var A;if(t.event.type===Ai.PointerMove){const e=t.pointerId,i=this._capturedPointer[e];if(i){ka&&console.log("Captured",e,i);for(let g=0;g<i.length;g++){const I=i[g];if(I.destroyed){i.splice(g,1),g--;continue}(A=I.onPointerMove)==null||A.call(I,t)}}}}isChild(t,A){return!t||!A?!1:t===A?!0:t.parent?this.isChild(t.parent,A):!1}handleMeshUiObjectWithoutShadowDom(t,A){return!t||!t.isUI?!0:this.handleMeshUIIntersection(t,A)}handleMeshUIIntersection(t,A){const e=_n.updateState(t,A);return e&&this.currentActiveMeshUIComponents.push(e),e!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&_n.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let t=0;t<this.currentActiveMeshUIComponents.length;t++){const A=this.currentActiveMeshUIComponents[t];_n.resetState(A)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(t){return t?aA.isActiveSelf(t)?this.testIsVisible(t.parent):!1:!0}};let zo=Ga;r(zo,"_eventSystemMap",new Map),r(zo,"didSearchEventSystem",!1);class _n{static markDirty(){this.needsUpdate=!0}static update(A,e,i=!1){if(i){A.update();return}const g=e.time.frameCount;for(const I of this.lastUpdateFrame)if(I.context===e){if(g===I.frame)return;I.frame=g;let o=this.needsUpdate||g<1;I.nextUpdate===e.time.frameCount&&(o=!0),o&&(ka&&console.log("Update threemeshui"),this.needsUpdate=!1,A.update());return}this.lastUpdateFrame=[{context:e,frame:g,nextUpdate:g}],A.update()}static updateState(A,e){let i=null;if(A&&(i=this.findBlockInParent(A),i&&i!==this.lastSelected)){if(i.interactable===!1)return null;this.needsUpdate=!0}return i}static resetLastSelected(){const A=this.lastSelected;A&&(this.lastSelected=null,this.resetState(A))}static resetState(A){A&&(this.needsUpdate=!0)}static findBlockInParent(A){return A?A.isBlock?A:this.findBlockInParent(A.parent):null}}r(_n,"lastSelected",null),r(_n,"lastUpdateFrame",[]),r(_n,"needsUpdate",!1);var lIA=Object.defineProperty,dIA=Object.getOwnPropertyDescriptor,vg=(t,A,e,i)=>{for(var g=i>1?void 0:i?dIA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&lIA(A,e,g),g};const uIA=iA("debugorbit"),mw=iA("freecam"),od=iA("debugcamerafit"),kw=iA("smoothcam"),pIA={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let vU;class sd extends CustomEvent{constructor(A,e){super("target-reached",{detail:{controls:A,type:e}})}}class jt extends JA{constructor(){super(...arguments),r(this,"autoFit",!1),r(this,"enableRotate",!0),r(this,"autoRotate",!1),r(this,"autoRotateSpeed",1),r(this,"enableKeys",!0),r(this,"enableDamping",!0),r(this,"dampingFactor",.1),r(this,"enableZoom",!0),r(this,"minZoom",0),r(this,"maxZoom",1/0),r(this,"enablePan",!0),r(this,"lookAtConstraint",null),r(this,"lookAtConstraint01",1),r(this,"allowInterrupt",!0),r(this,"middleClickToFocus",!0),r(this,"doubleClickToFocus",!0),r(this,"useSlerp",!0),r(this,"debugLog",!1),r(this,"targetLerpDuration",1),r(this,"autoTarget",!0),r(this,"_controls",null),r(this,"_cameraObject",null),r(this,"_lookTargetLerpActive",!1),r(this,"_lookTargetStartPosition",new w),r(this,"_lookTargetEndPosition",new w),r(this,"_lookTargetLerp01",0),r(this,"_lookTargetLerpDuration",0),r(this,"_cameraLerpActive",!1),r(this,"_cameraStartPosition",new w),r(this,"_cameraEndPosition",new w),r(this,"_cameraLerp01",0),r(this,"_cameraLerpDuration",0),r(this,"_inputs",0),r(this,"_enableTime",0),r(this,"_startedListeningToKeyEvents",!1),r(this,"_eventSystem"),r(this,"_afterHandleInputFn"),r(this,"_camera",null),r(this,"_syncedTransform"),r(this,"_didStart",!1),r(this,"targetElement",null),r(this,"onControlsChangeStarted",()=>{this._syncedTransform&&this._syncedTransform.requestOwnership()}),r(this,"_shouldDisable",!1),r(this,"_haveAttachedKeyboardEvents",!1)}get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(A){var e;(e=this.controls)==null||e.addEventListener("start",A)}get targetLerpSpeed(){return 5}set targetLerpSpeed(A){this.targetLerpDuration=1/A}awake(){this._didStart=!1,this._startedListeningToKeyEvents=!1}start(){if(this._didStart=!0,this.autoTarget&&this._controls){const A=aA.getComponent(this.gameObject,Wt);if(A&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const e=Ne(A.cam).length(),i=new w(0,0,-e).applyMatrix4(A.cam.matrixWorld);this.setLookTargetPosition(i,!0)}if(this.autoTarget&&!this.setLookTargetFromConstraint()){const e=new Oo;e.screenPoint=new tA(0,0),e.lineThreshold=.1;const i=this.context.physics.raycast(e);i.length>0&&this.setLookTargetPosition(i[0].point,!0),od&&console.log("OrbitControls hits",...i)}this.autoFit&&this.fitCamera()}this._eventSystem=zo.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(JU.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){var A,e;(A=this._controls)==null||A.dispose(),(e=this._eventSystem)==null||e.removeEventListener(JU.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._enableTime=this.context.time.time;const A=aA.getComponent(this.gameObject,Wt);this._camera=A;const e=A?.cam;if(e&&v_(e,this,!0),!this._controls){if(!e){console.warn("OrbitControls: Requires a Camera component on the same object as this component.");return}e&&(this._cameraObject=e);const i=this.targetElement??this.context.renderer.domElement,g=e?.quaternion.clone();this._controls=new zgA(e,i),e?.quaternion.copy(g),vU===void 0&&(vU={...this._controls.keys})}this._controls&&(mw&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,$s()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),e?.type==="PerspectiveCamera"?mw||(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):mw||(this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom),this._startedListeningToKeyEvents||(this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(window.document.body))),this._syncedTransform=aA.getComponent(this.gameObject,Hn)??void 0}onDisable(){var A;(A=this._camera)!=null&&A.cam&&v_(this._camera.cam,this,!1),this._controls&&(this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted))}afterHandleInput(A){A.detail.args.pointerId===0&&(A.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!A.detail.args.isPressed||A.detail.args.isUp)&&(this._shouldDisable=!1))}onBeforeRender(){var A,e;if(!this._controls||this._cameraObject!==this.context.mainCamera)return;(this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2)||this.context.input.mouseWheelChanged||this.context.input.getPointerPressed(0)&&(A=this.context.input.getPointerPositionDelta(0))!=null&&A.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 i=this.middleClickToFocus&&this.context.input.getPointerClicked(1);if(i||(i=this.doubleClickToFocus&&this.context.input.getPointerDoubleClicked(0)&&this.context.time.time-this._enableTime>.3),i&&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 sd(this,"camera"));else{const g=Ie.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,g)}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 sd(this,"lookat"));else{const g=Ie.easeInOutCubic(this._lookTargetLerp01);this._controls.target.lerpVectors(this._lookTargetStartPosition,this._lookTargetEndPosition,g)}}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?vU:pIA,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,typeof kw=="number"||kw===!0){this._controls.enableDamping=!0;const g=typeof kw=="number"?kw:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,g))}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||(!mw&&(e=this.lookAtConstraint)!=null&&e.locked&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(),uIA&&Fe.DrawWireSphere(this._controls.target,.1,65280))}}setCameraAndLookTarget(A){if(!A||!(A instanceof wA))return;const e=Ne(A),i=cR(A);this.setTargetFromRaycast(new to(e,i)),this.setCameraTargetPosition(e)}setCameraTargetPosition(A,e=!1){var i,g;A&&(A instanceof wA&&(A=Ne(A)),this._cameraEndPosition||(this._cameraEndPosition=new w),this._cameraEndPosition.copy(A),e===!0?(this._cameraLerpActive=!1,(i=this.controllerObject)==null||i.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy((g=this._cameraObject)==null?void 0:g.position),typeof e=="number"?this._cameraLerpDuration=e:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setLookTargetPosition(A=null,e=!1){this._controls&&A&&(A instanceof wA&&(A=Ne(A)),this._lookTargetEndPosition.copy(A),e===!0?this._controls.target.copy(this._lookTargetEndPosition):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof e=="number"?this._lookTargetLerpDuration=e:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(A=0,e=1){var i;if(!this._controls)return!1;const g=(i=this.lookAtConstraint)==null?void 0:i.sources;if(g&&g.length>0){const I=g[A];if(I)return I.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._lookTargetEndPosition,e),!0}return!1}lerpTarget(A,e){return this.lerpLookTarget(A,e)}lerpLookTarget(A,e){this._controls&&(e>=1?this._controls.target.copy(A):this._controls.target.lerp(A,e))}setTargetFromRaycast(A){var e,i;if(!this.controls)return;const g=A?this.context.physics.raycastFromRay(A):this.context.physics.raycast();for(const I of g)if(I.distance>0&&aA.isActiveInHierarchy(I.object)){const o=KU(I.object);if(o){const s=o.canvas;if(s!=null&&s.screenspace)break}if(this.setLookTargetPosition(I.point),this.context.mainCamera){const s=Ne(this.context.mainCamera).clone().sub(this.controls.target).add(this._lookTargetEndPosition);(i=(e=this._cameraObject)==null?void 0:e.parent)==null||i.worldToLocal(s),this.setCameraTargetPosition(s)}break}}fitCamera(A,e=1.1,i=!0){const g=this._cameraObject,I=this._controls;if(A!=null&&A.length||(A=this.context.scene.children),A.length<=0||!g||!I)return;const o=new w,s=new w,C=new Ft;C.makeEmpty();const a=[];function n(l){let p=!0;if(l.visible&&$gA(l)!==!1&&!(l.type==="TransformControlsGizmo"||l.type==="TransformControlsPlane")&&(l instanceof bk&&(p=!1),l instanceof wD&&(p=!1),l instanceof J_&&(p=!1),l.material instanceof nD&&(p=!1),l instanceof DA||(p=!1),l!==g&&l.isUI!==!0)){if(p){od&&console.log(l.name,l.type,l);const D=l.children;l.children=a;const S=l.position,k=l.scale;if(Number.isNaN(S.x)||Number.isNaN(S.y)||Number.isNaN(S.z)){console.warn(`Object "${l.name}" has NaN values in position or scale.... will ignore it`,S,k);return}C.expandByObject(l,!0),l.children=D}for(const D of l.children)n(D)}}for(const l of A)l.updateMatrixWorld(),n(l);if(g.updateMatrixWorld(),g.updateProjectionMatrix(),C.getCenter(s),C.applyMatrix4(g.matrixWorldInverse),C.getSize(o),C.setFromCenterAndSize(s,o),Number.isNaN(o.x)||Number.isNaN(o.y)||Number.isNaN(o.z)){console.warn("Camera fit size resultet in NaN",g,C,[...A]);return}if(o.length()<=1e-10){od&&console.warn("Camera fit size is zero",C,[...A]);return}const B=g.fov,Q=2*Math.atan(Math.tan(B*Math.PI/360/2)*g.aspect)/Math.PI*360,E=o.y/(2*Math.atan(Math.PI*B/360)),h=o.x/(2*Math.atan(Math.PI*Q/360)),d=e*Math.max(E,h)+o.z/2;od&&console.log("Fit camera to objects",E,h,"distance",d);const u=Ne(g),c=I.target.clone().sub(u).normalize().multiplyScalar(d);if(I.maxDistance=d*10,I.minDistance=d*.01,this.setLookTargetPosition(s,i),this.autoTarget=!1,g.near=d/1e3,g.far=d*100,g.updateMatrixWorld(),g.updateProjectionMatrix(),g.parent){const l=g.parent.worldToLocal(I.target.clone().sub(c));this.setCameraTargetPosition(l,i)}else console.error(`Can not fit camera ${g.name} because it has no parent`);if(od){const l=new bk(C);this.context.scene.add(l),uR(l,Ml(g)),this._haveAttachedKeyboardEvents||(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",p=>{p.code==="KeyF"&&this.fitCamera(A)}))}I.update()}}vg([y()],jt.prototype,"autoFit",2),vg([y()],jt.prototype,"enableRotate",2),vg([y()],jt.prototype,"autoRotate",2),vg([y()],jt.prototype,"autoRotateSpeed",2),vg([y()],jt.prototype,"enableKeys",2),vg([y()],jt.prototype,"enableDamping",2),vg([y()],jt.prototype,"dampingFactor",2),vg([y()],jt.prototype,"enableZoom",2),vg([y()],jt.prototype,"minZoom",2),vg([y()],jt.prototype,"maxZoom",2),vg([y()],jt.prototype,"enablePan",2),vg([y(Ad)],jt.prototype,"lookAtConstraint",2),vg([y()],jt.prototype,"lookAtConstraint01",2),vg([y()],jt.prototype,"allowInterrupt",2),vg([y()],jt.prototype,"middleClickToFocus",2),vg([y()],jt.prototype,"doubleClickToFocus",2),vg([y()],jt.prototype,"targetLerpDuration",2);var DIA=Object.defineProperty,yIA=Object.getOwnPropertyDescriptor,Bo=(t,A,e,i)=>{for(var g=i>1?void 0:i?yIA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&DIA(A,e,g),g},mB=(t=>(t[t.Skybox=1]="Skybox",t[t.SolidColor=2]="SolidColor",t[t.Uninitialized=4]="Uninitialized",t))(mB||{});const kB=iA("debugcam"),T_=iA("debugscreenpointtoray");var Gw;const Cd=(Gw=class extends JA{constructor(){super(...arguments),r(this,"_nearClipPlane",.1),r(this,"_farClipPlane",1e3),r(this,"orthographic",!1),r(this,"orthographicSize",5),r(this,"ARBackgroundAlpha",0),r(this,"_cullingMask",4294967295),r(this,"_backgroundBlurriness"),r(this,"_backgroundIntensity"),r(this,"_environmentIntensity"),r(this,"_targetTexture",null),r(this,"_backgroundColor"),r(this,"_fov"),r(this,"_cam",null),r(this,"_clearFlags",2),r(this,"_skybox")}get isCamera(){return!0}get aspect(){return this._cam instanceof Pe?this._cam.aspect:this.context.domWidth/this.context.domHeight}get fieldOfView(){return this._cam instanceof Pe?this._cam.fov:this._fov}set fieldOfView(t){const A=this.fieldOfView!=t;if(this._fov=t,A&&this._cam&&this._cam instanceof Pe){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(t){const A=this._nearClipPlane!=t;this._nearClipPlane=t,this._cam&&A&&(this._cam.near=t,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(t){const A=this._farClipPlane!=t;this._farClipPlane=t,this._cam&&A&&(this._cam.far=t,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(t){t!==this._clearFlags&&(this._clearFlags=t,this.applyClearFlagsIfIsActiveCamera())}set cullingMask(t){this._cullingMask=t,this._cam&&(this._cam.layers.mask=t)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}set cullingLayer(t){this.cullingMask=(1<<t|0)>>>0}set backgroundBlurriness(t){t!==this._backgroundBlurriness&&(t===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(t,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}set backgroundIntensity(t){t!==this._backgroundIntensity&&(t===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(t,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}set environmentIntensity(t){this._environmentIntensity=t}get environmentIntensity(){return this._environmentIntensity}get backgroundColor(){return this._backgroundColor??null}set backgroundColor(t){if(t){if(this._backgroundColor)this._backgroundColor.copy(t);else{if(!t.clone)return;this._backgroundColor=t.clone()}t.alpha===void 0&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera()}}set targetTexture(t){this._targetTexture=t}get targetTexture(){return this._targetTexture}get cam(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(t,A,e){const i=this.cam,g=Cd._origin;g.set(t,A,-1),this.context.input.convertScreenspaceToRaycastSpace(g),T_&&console.log("screenPointToRay",t.toFixed(2),A.toFixed(2),"now:",g.x.toFixed(2),g.y.toFixed(2),"isInXR:"+this.context.isInXR),g.z=-1,g.unproject(i);const I=Cd._direction.set(g.x,g.y,g.z),o=Ne(i);return I.sub(o),I.normalize(),e?(e.set(o,I),e):new to(o.clone(),I.clone())}awake(){T_&&window.addEventListener("pointerdown",t=>{const A=t.clientX,e=t.clientY;console.log("touch",A.toFixed(2),e.toFixed(2));const i=this.screenPointToRay(A,e),g="#"+Math.floor(Math.random()*16777215).toString(16);Fe.DrawRay(i.origin,i.direction,g,10)})}onEnable(){kB&&console.log(`Camera enabled: "${this.name}". ClearFlags=${mB[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),SIA(this)),this.applyClearFlagsIfIsActiveCamera()}onDisable(){this.context.removeCamera(this)}onBeforeRender(){if(this._cam&&(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 t=this.context.renderer;if(t){const A=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,t),A?.applyClearFlags()}}}buildCamera(){if(this._cam)return;const t=this.gameObject.isCamera;let A=null;if(t?(A=this.gameObject,A?.layers.enableAll(),A instanceof Pe&&(this._fov=A.fov)):A=this.gameObject.children[0],A&&A.isCamera)A instanceof Pe&&(this._fov&&(A.fov=this._fov),A.near=this._nearClipPlane,A.far=this._farClipPlane,A.updateProjectionMatrix());else if(!this.orthographic)A=new Pe(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(A.fov=this.fieldOfView),this.gameObject.add(A);else{const e=this.orthographicSize*100;A=new ZC(window.innerWidth/-e,window.innerWidth/e,window.innerHeight/e,window.innerHeight/-e,this._nearClipPlane,this._farClipPlane),this.gameObject.add(A)}this._cam=A,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(){this.context.mainCameraComponent===this&&this.applyClearFlags()}applyClearFlags(){if(!this._cam){kB&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this._fov,kB){const t=`Camera "${this.name}" clear flags: ${mB[this._clearFlags]}`;console.log(t)}switch(this._clearFlags){case 1:if(Cd.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),this._backgroundIntensity!==void 0&&(this.context.scene.backgroundIntensity=this._backgroundIntensity);break;case 2:if(this._backgroundColor){let t=this._backgroundColor.alpha;Cd.backgroundShouldBeTransparent(this.context)&&(t=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.renderer.setClearColor(this._backgroundColor,t)}else kB&&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 wIA(this)),this._skybox.enable()}static backgroundShouldBeTransparent(t){var A,e,i,g;const I=(A=t.renderer.xr)==null?void 0:A.getSession();if(!I)return!1;if(typeof I._transparent=="boolean")return I._transparent;const o=I.environmentBlendMode;kB&&wi("Environment blend mode: "+o+" on "+navigator.userAgent);let s=o==="additive"||o==="alpha-blend";return t.isInAR&&o==="opaque"&&((e=navigator.userAgent)!=null&&e.includes("OculusBrowser")||(i=navigator.userAgent)!=null&&i.includes("Mozilla")&&(g=navigator.userAgent)!=null&&g.includes("Mobile WebXRViewer/v2"))&&(s=!0),I._transparent=s,s}},r(Gw,"_origin",new w),r(Gw,"_direction",new w),Gw);let Wt=Cd;Bo([y()],Wt.prototype,"fieldOfView",1),Bo([y()],Wt.prototype,"nearClipPlane",1),Bo([y()],Wt.prototype,"farClipPlane",1),Bo([y()],Wt.prototype,"clearFlags",1),Bo([y()],Wt.prototype,"orthographic",2),Bo([y()],Wt.prototype,"orthographicSize",2),Bo([y()],Wt.prototype,"ARBackgroundAlpha",2),Bo([y()],Wt.prototype,"cullingMask",1),Bo([y()],Wt.prototype,"backgroundBlurriness",1),Bo([y()],Wt.prototype,"backgroundIntensity",1),Bo([y()],Wt.prototype,"environmentIntensity",1),Bo([y(Mt)],Wt.prototype,"backgroundColor",1),Bo([y(KE)],Wt.prototype,"targetTexture",1);class wIA{constructor(A){r(this,"_camera"),r(this,"_skybox"),this._camera=A}get context(){var A;return(A=this._camera)==null?void 0:A.context}enable(){this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),this._skybox?this.context.scene.background!==this._skybox&&(kB&&console.log(`Camera "${this._camera.name}" set skybox`,this._camera,this._skybox),this._skybox.colorSpace=_e,this._skybox.mapping=Ro,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)),(kB||Se())&&Ci(`Camera "${this._camera.name}" has no skybox texture`))}}function SIA(t){iA("freecam")&&t.context.mainCameraComponent===t&&aA.getOrAddComponent(t.gameObject,jt)}class On extends JA{constructor(){super(...arguments),r(this,"_listener",null)}get listener(){return this._listener==null&&(this._listener=new Zb),this._listener}awake(){fi.registerWaitForAllowAudio(()=>{if(this.destroyed)return;const A=this.listener;if(A==null||A.parent)return;const e=this.context.mainCameraComponent||aA.getComponentInParent(this.gameObject,Wt);e!=null&&e.cam?e.cam.add(A):this.gameObject.add(A)})}}var fIA=Object.defineProperty,mIA=Object.getOwnPropertyDescriptor,Mw=(t,A,e,i)=>{for(var g=i>1?void 0:i?mIA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&fIA(A,e,g),g};const kIA=iA("debugsignals");class ad{constructor(){r(this,"guid")}}Mw([y()],ad.prototype,"guid",2);class OE{constructor(){r(this,"signal"),r(this,"reaction")}}Mw([y(ad)],OE.prototype,"signal",2),Mw([y(Eg)],OE.prototype,"reaction",2);var bU;const Ma=(bU=class extends JA{constructor(){super(...arguments),r(this,"events")}static invoke(t){if(Ma.receivers[t]){const A=Ma.receivers[t];if(!A)return;for(const e of A)e.invoke(t)}}awake(){kIA&&console.log("SignalReceiver awake",this)}onEnable(){if(this.events)for(const t of this.events)Ma.receivers[t.signal.guid]||(Ma.receivers[t.signal.guid]=[]),Ma.receivers[t.signal.guid].push(this)}onDisable(){if(this.events){for(const t of this.events)if(Ma.receivers[t.signal.guid]){const A=Ma.receivers[t.signal.guid].indexOf(this);A>=0&&Ma.receivers[t.signal.guid].splice(A,1)}}}invoke(t){if(!this.events||!Array.isArray(this.events))return;const A=typeof t=="object"?t.guid:t;for(const e of this.events)if(e.signal.guid===A)try{if(e.reaction){if(!e.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",e,this);continue}}else{console.warn("Missing reaction for signal",e,this);continue}e.reaction.invoke()}catch(i){console.error(i)}}},r(bU,"receivers",{}),bU);let PE=Ma;Mw([y(OE)],PE.prototype,"events",2);var Qo=(t=>(t.Activation="ActivationTrack",t.Animation="AnimationTrack",t.Audio="AudioTrack",t.Control="ControlTrack",t.Marker="MarkerTrack",t.Signal="SignalTrack",t))(Qo||{}),BC=(t=>(t[t.None=0]="None",t[t.Hold=1]="Hold",t[t.Loop=2]="Loop",t[t.PingPong=3]="PingPong",t[t.Continue=4]="Continue",t))(BC||{}),qU=(t=>(t.Signal="SignalEmitter",t))(qU||{});const QC=iA("debugtimeline");class nd{constructor(){r(this,"director"),r(this,"track")}get muted(){return this.track.muted}set muted(A){var e;A!==this.track.muted&&(this.track.muted=A,(e=this.onMuteChanged)==null||e.call(this))}*forEachClip(A=!1){var e;if((e=this.track)!=null&&e.clips)if(A)for(let i=this.track.clips.length-1;i>=0;i--)yield this.track.clips[i];else for(const i of this.track.clips)yield i}getClipTime(A,e){return e.clipIn+(A-e.start)*e.timeScale}getClipTimeNormalized(A,e){return(A-e.start)/e.duration}evaluateWeight(A,e,i,g=!0){if(e<0||e>=i.length)return 0;const I=i[e];if(g||A>=I.start&&A<=I.end){let o=1;const s=!1;if(I.easeInDuration>0){const C=Math.min((A-I.start)/I.easeInDuration,1);o*=C}if(I.easeOutDuration>0&&!s){const C=Math.min((I.end-A)/I.easeOutDuration,1);o*=C}return o}return 0}}class GIA{constructor(A){r(this,"clip"),r(this,"rootPositionOffset"),r(this,"rootQuaternionOffset"),r(this,"rootStartPosition"),r(this,"rootEndPosition"),r(this,"rootStartQuaternion"),r(this,"rootEndQuaternion");const e=A.getClip();this.clip=e;const i=A.getRoot(),g=i.name+".position",I=i.name+".quaternion";QC&&console.log(e.name,e.tracks,g);for(const o of e.tracks)if(!(o.times.length<=0)){if(o.name.endsWith(g))this.rootStartPosition=new w().fromArray(o.values,0),this.rootEndPosition=new w().fromArray(o.values,o.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),QC&&console.log(this.rootPositionOffset);else if(o.name.endsWith(I)&&(this.rootStartQuaternion=new FA().fromArray(o.values,0),this.rootEndQuaternion=new FA().fromArray(o.values,o.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),QC)){const s=new Wg().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",s)}}}get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}}class Rw extends nd{constructor(){super(...arguments),r(this,"models",[]),r(this,"trackOffset"),r(this,"target"),r(this,"mixer"),r(this,"clips",[]),r(this,"actions",[]),r(this,"_actionOffsets",[]),r(this,"_didBind",!1),r(this,"_animator",null),r(this,"_useclipOffsets",!0),r(this,"_totalOffsetPosition",new w),r(this,"_totalOffsetRotation",new FA),r(this,"_totalOffsetPosition2",new w),r(this,"_totalOffsetRotation2",new FA),r(this,"_summedPos",new w),r(this,"_tempPos",new w),r(this,"_summedRot",new FA),r(this,"_tempRot",new FA),r(this,"_clipRotQuat",new FA)}onStateChanged(){this._animator&&H_(this._animator.gameObject,this,this.director.isPlaying)}createHooks(A,e){var i,g;if(((i=e.tracks)==null?void 0:i.length)<=0){console.warn("No tracks in AnimationClip",e);return}const I=e.tracks[0].name.split("."),o=I[I.length-2],s=o+".position",C=o+".quaternion";let a=!1,n=!1;for(const B of e.tracks)B.name.endsWith(s)?(a=!0,this.createPositionInterpolant(e,A,B)):B.name.endsWith(C)&&(n=!0,this.createRotationInterpolant(e,A,B));if(!a||!n){const B=(g=this.mixer)==null?void 0:g.getRoot(),Q=e.tracks[0],E=Q.name.lastIndexOf("."),h=Q.name.substring(0,E),d=h.substring(h.lastIndexOf(".")+1),u=B.getObjectByName(d);if(u)if(a){if(!n){const c=e.tracks[0].name.substring(0,E)+".quaternion";QC&&console.warn("Create quaternion track",d,u);const l=u.quaternion,p=new zs(c,[0,e.duration],[l.x,l.y,l.z,l.w,l.x,l.y,l.z,l.w]);e.tracks.push(p),this.createRotationInterpolant(e,A,p)}}else{const c=h+".position";QC&&console.warn("Create position track",d,u);const l=u.position,p=new XC(c,[0,e.duration],[l.x,l.y,l.z,l.x,l.y,l.z]);e.tracks.push(p),this.createPositionInterpolant(e,A,p)}}}bind(){if(!this._didBind){this._didBind=!0,QC&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(const A of this.actions){const e=new GIA(A);this._actionOffsets.push(e)}this.target&&(this._animator=aA.getComponent(this.target,bg)??null,this._animator&&H_(this._animator.gameObject,this,!0));for(const A of this.models){const e=A.asset,i=e.position,g=e.rotation;i&&i.x!==void 0&&(i.isVector3||(e.position=new w(i.x,i.y,i.z)),g.isQuaternion||(e.rotation=new FA(g.x,g.y,g.z,g.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){const A=this.trackOffset.position;A&&(A.isVector3||(this.trackOffset.position=new w(A.x,A.y,A.z)));const e=this.trackOffset.rotation;e&&(e.isQuaternion||(this.trackOffset.rotation=new FA(e.x,e.y,e.z,e.w)))}}evaluate(A){var e,i,g,I,o,s,C;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 a=0,n=0,B=!1,Q=!1,E=0;for(let h=0;h<this.clips.length;h++){const d=this.models[h],u=this.actions[h],c=d.asset;u.weight=0;const l=A>=d.start&&A<=d.end,p=d.preExtrapolationMode,D=d.postExtrapolationMode,S=h<this.clips.length-1?this.models[h+1]:null;let k=l,f=!1;if(!k&&!B&&d.end<A&&D!==BC.None?(!S||S.start>A)&&(k=!0,B=!0):h==0&&!k&&!Q&&d.start>A&&p!==BC.None&&(!S||S.start<A)&&(k=!0,f=!0,Q=!0),k){let U=1;U*=this.evaluateWeight(A,h,this.models,k),U*=this.director.weight;let M=l;if(f)switch(p){case BC.Hold:break;case BC.Loop:A+=d.start,M=!0;break;default:A+=d.start,M=!0;break}let m=this.getClipTime(A,d),x=0;const L=c.duration;if(f&&p===BC.Hold&&(m=0),M){if(c.loop)for(x+=Math.floor(m/(L+1e-6));m>L;)m-=L}else if(!l&&B)switch(D){case BC.Hold:m=this.getClipTime(d.end,d);break;case BC.Loop:m%=L;break;case BC.PingPong:const Y=Math.floor(m/L)%2!==0;m%=L,Y&&(m=L-m);break}d.reversed===!0?u.time=u.getClip().duration-m:u.time=m,u.timeScale=0;const V=Math.max(0,U);if(u.weight=V,E+=V,u.clampWhenFinished=!1,u.isRunning()||u.play(),this._useclipOffsets){const Y=a==0?this._totalOffsetPosition:this._totalOffsetPosition2,P=a==0?this._totalOffsetRotation:this._totalOffsetRotation2;a<1&&(n=1-U),a+=1;const b=this._summedPos.set(0,0,0),T=this._tempPos.set(0,0,0),_=this._summedRot.identity(),eA=this._tempRot.identity(),$=c.rotation;$&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp($,U));const IA=this._actionOffsets[h];if(IA.hasOffsets)for(let yA=0;yA<x;yA++)IA.rootPositionOffset?T.copy(IA.rootPositionOffset):T.set(0,0,0),T.applyQuaternion(_),this._clipRotQuat&&T.applyQuaternion(this._clipRotQuat),IA.rootQuaternionOffset&&(eA.copy(IA.rootQuaternionOffset),_.multiply(eA)),b.add(T);this._clipRotQuat&&P.multiply(this._clipRotQuat),P.multiply(_),c.position&&b.add(c.position),Y.add(b)}}}if(this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,n),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,n)),this.__mixerError===void 0&&(QC||Se())&&(i=(e=this._animator)==null?void 0:e.runtimeAnimatorController)!=null&&i.mixer&&this.mixer!==((I=(g=this._animator)==null?void 0:g.runtimeAnimatorController)==null?void 0:I.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 h=Math.max(0,1-E);(C=(s=this._animator)==null?void 0:s.runtimeAnimatorController)==null||C.update(h)}else this.mixer.update(A)}createRotationInterpolant(A,e,i){var g;const I=i.createInterpolant.bind(i),o=new FA;this.ensureTrackOffsets();const s=(g=this.trackOffset)==null?void 0:g.rotation;i.createInterpolant=()=>{const C=I(),a=C.evaluate.bind(C);return C.evaluate=n=>{var B;const Q=a(n);if(o.set(Q[0],Q[1],Q[2],Q[3]),o.premultiply(this._totalOffsetRotation),s&&o.premultiply(s),this.director.animationCallbackReceivers)for(const E of this.director.animationCallbackReceivers)(B=E?.onTimelineRotation)==null||B.call(E,this.director,this.target,n,o);return Q[0]=o.x,Q[1]=o.y,Q[2]=o.z,Q[3]=o.w,Q},C}}createPositionInterpolant(A,e,i){var g,I;const o=i.createInterpolant.bind(i),s=new w;this.ensureTrackOffsets();const C=(g=this.trackOffset)==null?void 0:g.rotation,a=(I=this.trackOffset)==null?void 0:I.position;let n;i.createInterpolant=()=>{const B=o(),Q=B.evaluate.bind(B);return B.evaluate=E=>{var h,d,u;const c=Q(E);if(s.set(c[0],c[1],c[2]),e.removeStartOffset&&(n===void 0?(n=null,n=(d=(h=this._actionOffsets.find(l=>l.clip===A))==null?void 0:h.rootStartPosition)==null?void 0:d.clone()):n!=null&&n.isVector3&&s.sub(n)),s.applyQuaternion(this._totalOffsetRotation),s.add(this._totalOffsetPosition),C&&s.applyQuaternion(C),a&&(s.x-=a.x,s.y+=a.y,s.z+=a.z),this.director.animationCallbackReceivers)for(const l of this.director.animationCallbackReceivers)(u=l?.onTimelinePosition)==null||u.call(l,this.director,this.target,E,s);return c[0]=s.x,c[1]=s.y,c[2]=s.z,c},B}}}const MIA=iA("mutetimeline"),rd=class extends nd{constructor(){super(...arguments),r(this,"models",[]),r(this,"listener"),r(this,"audio",[]),r(this,"audioContextTimeOffset",[]),r(this,"lastTime",0),r(this,"audioSource"),r(this,"_audioLoader",null),r(this,"_playableDirectorResumed",!1)}getAudioFilePath(t){const A=this.director.sourceId;return pn(A,t)}onAllowAudioChanged(t){for(let A=0;A<this.models.length;A++){const e=this.models[A];this.audio[A].setVolume(t?e.asset.volume:0)}}addModel(t){const A=new Mk(this.listener);this.audio.push(A);const e=t;e._didTriggerPlay=!1,this.models.push(e)}onDisable(){for(const t of this.audio)t.isPlaying&&t.stop();for(const t of this.models)t._didTriggerPlay=!1}onDestroy(){for(const t of this.audio)t.source&&t?.disconnect();this.audio.length=0}onMuteChanged(){if(this.muted)for(let t=0;t<this.audio.length;t++){const A=this.audio[t];A!=null&&A.isPlaying&&A.stop()}}stop(){for(let t=0;t<this.audio.length;t++){const A=this.audio[t];A!=null&&A.isPlaying&&A.stop()}for(const t of this.models)t._didTriggerPlay=!1}onPauseChanged(){for(let t=0;t<this.audio.length;t++){const A=this.audio[t];A!=null&&A.isPlaying&&A.stop()}this._playableDirectorResumed=this.director.isPlaying}evaluate(t){if(MIA||this.track.muted||this.director.speed<0)return;const A=this.director.context.application.muted,e=this._playableDirectorResumed;this._playableDirectorResumed=!1;const i=A?.1:0;for(let g=0;g<this.models.length;g++){const I=this.models[g],o=this.audio[g],s=I.asset;if((!o||!o.buffer)&&this.isInTimeRange(I,t-1,t+1)&&this.handleAudioLoading(I,o),fi.userInteractionRegistered!==!1&&!(o===null||!o.buffer))if(o.playbackRate=this.director.context.time.timeScale*this.director.speed,o.loop=s.loop,t>=I.start&&t<=I.end&&t<this.director.duration){if(!o.isPlaying||!this.director.isPlaying)(e||!I._didTriggerPlay&&this.lastTime<t)&&(I.duration*I.timeScale>.3?o.offset=I.clipIn+(t-I.start)*I.timeScale:o.offset=0,QC&&console.log("Timeline Audio ("+this.track.name+") play with offset "+o.offset+" - "+I.asset.clip),o.play(i),I._didTriggerPlay=!0);else{const a=I.clipIn+(t-I.start)*I.timeScale,n=o.context.currentTime-o._startedAt+o.offset;Math.abs(a-n)>.3&&(o.offset=a,o.stop(),o.play(i))}let C=s.volume;if(this.track.volume!==void 0&&(C*=this.track.volume),A&&(C=0),I.easeInDuration>0){const a=Math.min((t-I.start)/I.easeInDuration,1);C*=a}if(I.easeOutDuration>0){const a=Math.min((I.end-t)/I.easeOutDuration,1);C*=a}o.setVolume(C*this.director.weight)}else I._didTriggerPlay=!1,this.director.isPlaying&&o.isPlaying&&o.stop()}this.lastTime=t}loadAudio(t,A=0,e=0){let i=null;const g=t-e,I=t+A;for(const o of this.models)if(this.isInTimeRange(o,g,I)){const s=this.audio[this.models.indexOf(o)],C=this.handleAudioLoading(o,s);C!==null&&(i===null&&(i=[]),i.push(C))}return i!==null?Promise.all(i):null}isInTimeRange(t,A,e){return A<=t.start&&e>=t.end||A>=t.start&&A<=t.end||e>=t.start&&e<=t.end}static dispose(){rd._audioBuffers.clear()}handleAudioLoading(t,A){this._audioLoader||(this._audioLoader=new dD);const e=this.getAudioFilePath(t.asset.clip);if(rd._audioBuffers.get(e)){const g=rd._audioBuffers.get(e);return g.then(I=>{I&&A.setBuffer(I)}),g}QC&&console.warn("LOAD audio track",e,this.director.sourceId);const i=new Promise((g,I)=>{this._audioLoader.load(e,o=>{A.setBuffer(o),g(o)},void 0,o=>{console.error("Error loading audio",o),g(null)})});return rd._audioBuffers.set(e,i),i}};let Bd=rd;r(Bd,"_audioBuffers",new Map);class Qd extends nd{constructor(){super(...arguments),r(this,"models",[]),r(this,"didTrigger",[]),r(this,"receivers",[])}evaluate(A){var e;if(this.track.muted)return;const i=this.director.context.time.deltaTime*1.5;for(let g=0;g<this.models.length;g++){const I=this.models[g],o=this.didTrigger[g],s=I.time-A;let C=!1;if(I.retroActive)C=s<=1e-6;else{const a=Math.abs(s);(a===0||a>=1e-5&&a<i)&&(C=!0)}if(C){if(!o)if(QC&&console.log("Trigger signal",A,I.time,I),this.didTrigger[g]=!0,((e=this.receivers)==null?void 0:e.length)<=0)PE.invoke(I.asset);else for(const a of this.receivers)a&&a.invoke(I.asset)}else I.emitOnce||(this.didTrigger[g]=!1)}}}class Uw extends nd{constructor(){super(...arguments),r(this,"models",[]),r(this,"timelines",[]),r(this,"_previousActiveModel",null)}resolveSourceObjects(A){for(let e=this.models.length-1;e>=0;e--){const i=this.models[e].asset;if(!i.sourceObject||typeof i.sourceObject!="object"){console.log("no source object, removing model",e,i),this.models.splice(e,1);continue}else{const g=aA.getComponent(i.sourceObject,GB);this.timelines.push(g),g&&i.updateDirector&&(g.playOnAwake=!1)}}}evaluate(A){var e;this._previousActiveModel=null;for(let i=0;i<this.models.length;i++){const g=this.models[i],I=g.asset;if(A>=g.start&&A<=g.end){this._previousActiveModel=g;const o=this.getClipTime(A,g);if(I.controlActivation){const s=I.sourceObject;s.visible=!0}if(I.updateDirector){const s=this.timelines[i];s&&(s.isPlaying&&s.pause(),s.time=o,s.evaluate())}}else{const o=(e=this._previousActiveModel)==null?void 0:e.asset;if(I.controlActivation){const s=I.sourceObject;o?.sourceObject!==s&&(s.visible=!1)}}}}}const jE=iA("debugtimeline"),LU=class extends JA{constructor(){super(...arguments),r(this,"playableAsset"),r(this,"playOnAwake"),r(this,"extrapolationMode",1),r(this,"waitForAudio",!0),r(this,"_visibilityChangeEvt"),r(this,"_clonedPlayableAsset",!1),r(this,"_speed",1),r(this,"_guidsMap"),r(this,"_isPlaying",!1),r(this,"_internalUpdateRoutine"),r(this,"_isPaused",!1),r(this,"_isStopping",!1),r(this,"_time",0),r(this,"_duration",0),r(this,"_weight",1),r(this,"_animationTracks",[]),r(this,"_audioTracks",[]),r(this,"_signalTracks",[]),r(this,"_controlTracks",[]),r(this,"_customTracks",[]),r(this,"_allTracks",[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks]),r(this,"animationCallbackReceivers",[])}static registerCreateTrack(t,A){this.createTrackFunctions[t]=A}get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(t){typeof t=="number"&&!Number.isNaN(t)?this._time=t:(jE||pI())&&console.error("INVALID TIMELINE.TIME VALUE",t,this.name)}get duration(){return this._duration}set duration(t){this._duration=t}get weight(){return this._weight}set weight(t){this._weight=t}get speed(){return this._speed}set speed(t){this._speed=t}awake(){var t,A,e;jE&&console.log(this,(t=this.playableAsset)==null?void 0:t.tracks),this.rebuildGraph(),this.isValid()||console.warn("PlayableDirector is not valid",this.playableAsset,(A=this.playableAsset)==null?void 0:A.tracks,Array.isArray((e=this.playableAsset)==null?void 0:e.tracks),this)}onEnable(){var t,A,e;for(const i of this._audioTracks)(t=i.onEnable)==null||t.call(i);for(const i of this._customTracks)(A=i.onEnable)==null||A.call(i);for(const i of this._animationTracks)(e=i.onEnable)==null||e.call(i);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 t,A,e;this.stop();for(const i of this._audioTracks)(t=i.onDisable)==null||t.call(i);for(const i of this._customTracks)(A=i.onDisable)==null||A.call(i);for(const i of this._animationTracks)(e=i.onDisable)==null||e.call(i);this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){var t;for(const A of this._allTracks)for(const e of A)(t=e.onDestroy)==null||t.call(e)}rebuildGraph(){this.isValid()&&(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}async play(){if(!this.isValid())return;const t=this._isPaused==!0;if(this._isPaused=!1,!this._isPlaying){if(this._isPlaying=!0,t&&this.invokePauseChangedMethodsOnTracks(),this.waitForAudio){const A=[];for(const e of this._audioTracks){const i=e.loadAudio(this._time,1,0);i&&A.push(i)}if(A.length>0&&(await Promise.all(A),!this._isPlaying))return;for(;this._audioTracks.length>0&&this._isPlaying&&!fi.userInteractionRegistered&&this.waitForAudio;)await Jo(200)}this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate(),Pi.LateUpdate)}}pause(){this.isValid()&&(this._isPlaying=!1,!this._isPaused&&(this._isPaused=!0,this.internalEvaluate(),this.invokePauseChangedMethodsOnTracks(),this.invokeStateChangedMethodsOnTracks()))}stop(){this._isStopping=!0;for(const e of this._audioTracks)e.stop();const t=this._isPaused==!0,A=this._isPlaying;this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.internalEvaluate(),t&&this.invokePauseChangedMethodsOnTracks()),this._isPlaying=!1,this._isPaused=!1,t&&!A&&this.invokePauseChangedMethodsOnTracks(),A&&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 t of this._allTracks)for(const A of t)yield A}get audioTracks(){return this._audioTracks}resolveGuids(t){this._guidsMap=t}invokePauseChangedMethodsOnTracks(){var t;for(const A of this.forEachTrack())(t=A.onPauseChanged)==null||t.call(A)}invokeStateChangedMethodsOnTracks(){var t;for(const A of this.forEachTrack())(t=A.onStateChanged)==null||t.call(A,this._isPlaying)}*internalUpdate(){for(;this._isPlaying&&this.activeAndEnabled;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime*this.speed,this.internalEvaluate()),yield}internalEvaluate(t=!1){if(!this.isValid())return;let A=this._time;switch(this.extrapolationMode){case 0:this._speed>0?A=Math.min(A,this._duration):this._speed<0&&(A=Math.max(A,0)),this._time=A;break;case 1:A%=this._duration,this._time=A;break;case 2:if(A>this._duration){this.stop();return}break}const e=this._time;for(const i of this.playableAsset.tracks)if(!i.muted)switch(i.type){case Qo.Activation:if(!t&&!this._isPlaying)continue;for(let g=0;g<i.outputs.length;g++){const I=i.outputs[g];if(typeof I=="object"){let o=!1;if(i.clips)for(const C of i.clips)C.start<=e&&e<=C.end&&(o=!0);const s=I;s.visible!==void 0&&s.visible!==o&&(s.visible=o,jE&&console.warn(this.name,"set ActivationTrack-"+g,s.name,o,e))}}break}if(!this._isStopping)for(const i of this._animationTracks)i.evaluate(e);for(const i of this._audioTracks)i.evaluate(e);for(const i of this._signalTracks)i.evaluate(e);for(const i of this._controlTracks)i.evaluate(e);for(const i of this._customTracks)i.evaluate(e)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=Lc(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;const t=this.findRoot(this.gameObject);for(const A of this.playableAsset.tracks){for(let e=A.outputs.length-1;e>=0;e--){let i=A.outputs[e];if(typeof i=="string"){this._guidsMap&&this._guidsMap[i]&&(i=this._guidsMap[i]);const g=aA.findByGuid(i,t);g===null||typeof g!="object"?(A.outputs.splice(e,1),console.warn("Failed to resolve binding",i,A.name,A.type)):(jE&&console.log("Resolved binding",i,"to",g),A.outputs[e]=g)}else if(i===null){if(A.outputs.splice(e,1),LU.createTrackFunctions[A.type])continue;A.type!==Qo.Audio&&A.type!==Qo.Control&&A.type!==Qo.Marker&&A.type!==Qo.Signal&&console.warn("Missing binding",i,A.name,A.type,this.name,this.playableAsset.name)}}if(A.type===Qo.Control&&A.clips)for(let e=0;e<A.clips.length;e++){const i=A.clips[e];let g=i.asset.sourceObject;if(typeof g=="string"){this._guidsMap&&this._guidsMap[g]&&(g=this._guidsMap[g]);const I=aA.findByGuid(g,t);I===null||typeof I!="object"?console.warn("Failed to resolve sourceObject binding",g,A.name,i):(jE&&console.log("Resolved binding",g,"to",I),i.asset.sourceObject=I)}}}}findRoot(t){return t.parent?this.findRoot(t.parent):t}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const t of this.playableAsset.tracks)if(t.muted!==!0){if(t.clips)for(const A of t.clips)A.end>this._duration&&(this._duration=A.end);if(t.markers)for(const A of t.markers)A.time>this._duration&&(this._duration=A.time+.001)}}}setupAndCreateTrackHandlers(){var t,A,e;if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let i=aA.findObjectOfType(On,this.context);for(const g of this.playableAsset.tracks){const I=g.type,o=LU.createTrackFunctions[I];if(o!=null){const s=o(this,g);if(typeof s.evaluate=="function"){s.director=this,s.track=g,this._customTracks.push(s);continue}}if(g.type===Qo.Animation){if(!g.clips||g.clips.length<=0){jE&&console.warn("Animation track has no clips",g);continue}for(let s=g.outputs.length-1;s>=0;s--){let C=g.outputs[s];if(C instanceof wA){const n=aA.getOrAddComponent(C,bg);n&&(C=n)}const a=(t=C?.gameObject)==null?void 0:t.animations;if(a){const n=new Rw;n.trackOffset=g.trackOffset,n.director=this,n.track=g;for(let B=0;B<g.clips.length;B++){const Q=g.clips[B],E=Q.asset;if(!E){console.error(`Timeline ${this.name}: clip #${B} on track "${g.name}" has no animation data`);continue}const h=E.clip;let d=h;if((typeof d=="string"||typeof d=="number")&&(d=a.find(c=>c.name===h)),!d){console.warn("Could not find animationClip for model",Q,g.name,this.name,(A=this.playableAsset)==null?void 0:A.name);continue}C instanceof bg&&C.runtimeAnimatorController&&(C.__internalDidAwakeAndStart||C.initializeRuntimeAnimatorController(),C.runtimeAnimatorController.mixer||C.runtimeAnimatorController.bind(C),n.mixer=C.runtimeAnimatorController.mixer),n.mixer||(n.mixer=new uD(C.gameObject)),n.clips.push(d),n.mixer.uncacheAction(d),n.createHooks(Q.asset,d);const u=n.mixer.clipAction(d);n.actions.push(u),n.models.push(Q)}this._animationTracks.push(n)}}}else if(g.type===Qo.Audio){if(!g.clips||g.clips.length<=0)continue;const s=new Bd;s.director=this,s.track=g,s.audioSource=g.outputs.find(C=>C instanceof fi),this._audioTracks.push(s),i||(i=(e=this.context.mainCameraComponent)==null?void 0:e.gameObject.addNewComponent(On)),s.listener=i.listener;for(let C=0;C<g.clips.length;C++){const a=g.clips[C];s.addModel(a)}}else if(g.type===Qo.Marker){const s=new Qd;if(s.director=this,s.track=g,g.markers)for(const C of g.markers)switch(C.type){case qU.Signal:s.models.push(C),s.didTrigger.push(!1);break}if(s!==null&&s.models.length>0){const C=aA.getComponent(this.gameObject,PE);C&&(s.receivers.push(C),this._signalTracks.push(s))}}else if(g.type===Qo.Signal){const s=new Qd;if(s.director=this,s.track=g,g.markers)for(const C of g.markers)s.models.push(C),s.didTrigger.push(!1);for(const C of g.outputs)s.receivers.push(C);this._signalTracks.push(s)}else if(g.type===Qo.Control){const s=new Uw;if(s.director=this,s.track=g,g.clips)for(const C of g.clips)s.models.push(C);s.resolveSourceObjects(this.context),this._controlTracks.push(s)}}}setAudioTracksAllowPlaying(t){for(const A of this._audioTracks)A.onAllowAudioChanged(t)}registerAnimationCallback(t){this.animationCallbackReceivers.push(t)}unregisterAnimationCallback(t){const A=this.animationCallbackReceivers.indexOf(t);A!==-1&&this.animationCallbackReceivers.splice(A,1)}};let GB=LU;r(GB,"createTrackFunctions",{});const Nw=Symbol("objectIsAnimatedData");function H_(t,A,e){if(!t)return;if(t[Nw]===void 0){if(!e)return;t[Nw]=new Set}const i=t[Nw];e?i.add(A):i.has(A)&&i.delete(A)}function RIA(t){if(!t)return!1;const A=t[Nw];return A!==void 0&&A.size>0}mt.registerCallback(Yi.ContextCreated,t=>{const A=t.context.domElement.getAttribute("autoplay");if(A!==void 0&&(A===""||A==="true")&&t.files)for(const e of t.files)aA.foreachComponent(e.file.scene,i=>{if(i.enabled!==!1){if(i instanceof no&&i.playAutomatically||i instanceof bg||i instanceof GB&&i.playOnAwake===!0)return!0;if(i instanceof no)return i.playAutomatically=!0,!0;if(i instanceof GB)return i.playOnAwake=!0,!0}},!0)!==!0&&UIA(e.file)});function UIA(t){if(!t||!t.animations)return;for(let e=0;e<t.animations.length;e++){const i=t.animations[e];if(!(!i.tracks||i.tracks.length<=0))for(const g in i.tracks){const I=i.tracks[g],o=I.__objectName??I.name.substring(0,I.name.indexOf("."));let s=t.scene.getObjectByName(o);if(!s&&(s=t.scene.getObjectByProperty("uuid",o),!s))continue;let C=A(s);C||(C=Jn(t.scene,new no));const a=C.animations=C.animations||[];i.name_animator=C.name,a.indexOf(i)<0&&a.push(i)}}function A(e){var i;if(!e)return;const g=(i=e.userData)==null?void 0:i.components;if(g&&g.length>0)for(let I=0;I<g.length;I++){const o=g[I];if(o instanceof bg||o instanceof no)return e}return A(e.parent)}}class NIA{constructor(){r(this,"_context")}get context(){return this._context??ve.Current}get isStateMachineBehaviour(){return!0}}class Fw{constructor(A,e,i,g){r(this,"_name"),r(this,"_nameHash"),r(this,"_normalizedTime"),r(this,"_length"),r(this,"_speed"),this._name=A.name,this._nameHash=A.hash,this._normalizedTime=e,this._length=i,this._speed=g}get name(){return this._name}get nameHash(){return this._nameHash}get normalizedTime(){return this._normalizedTime}get length(){return this._length}get speed(){return this._speed}}function __(t,A){return{name:"",isLooping:!1,guid:A?.generateUUID()??eg.generateUUID(),index:-1,clip:new PI(t,1,[])}}var Pn=(t=>(t[t.If=1]="If",t[t.IfNot=2]="IfNot",t[t.Greater=3]="Greater",t[t.Less=4]="Less",t[t.Equals=6]="Equals",t[t.NotEqual=7]="NotEqual",t))(Pn||{}),xU=(t=>(t[t.Float=1]="Float",t[t.Int=3]="Int",t[t.Bool=4]="Bool",t[t.Trigger=9]="Trigger",t))(xU||{});const GI=iA("debuganimatorcontroller"),Kw=iA("debugrootmotion");class ko{constructor(A){r(this,"normalizedStartOffset",0),r(this,"_speed",1),r(this,"animator"),r(this,"model"),r(this,"_mixer"),r(this,"_activeState"),r(this,"_activeStates",[]),r(this,"rootMotionHandler"),this.model=A,GI&&console.log(this)}static createFromClips(A,e={looping:!1,autoTransition:!0,transitionDuration:0}){const i=[];for(let I=0;I<A.length;I++){const o=A[I],s=[];if(e.autoTransition!==!1){const a=e.transitionDuration??0,n=a/o.duration;let B=I;(e.autoTransition===void 0||e.autoTransition===!0)&&(B=(I+1)%A.length),s.push({exitTime:1-n,offset:0,duration:a,hasExitTime:!0,destinationState:B,conditions:[]})}const C={name:o.name,hash:I,motion:{name:o.name,clip:o,isLooping:e?.looping??!1},transitions:s,behaviours:[]};i.push(C)}const g={name:"AnimatorController",guid:new Dg(Date.now()).generateUUID(),parameters:[],layers:[{name:"Base Layer",stateMachine:{defaultState:0,states:i}}]};return new ko(g)}play(A,e=-1,i=Number.NEGATIVE_INFINITY,g=0){if(e<0)e=0;else if(e>=this.model.layers.length){console.warn("invalid layer");return}const I=this.model.layers[e].stateMachine;for(const o of I.states)if(o.name===A||o.hash===A){GI&&console.log("transition to ",o),this.transitionTo(o,g,i);return}console.warn("Could not find "+A+" to play")}reset(){this.setStartTransition()}setBool(A,e){var i,g;const I=typeof A=="string"?"name":"hash";return(g=(i=this.model)==null?void 0:i.parameters)==null?void 0:g.filter(o=>o[I]===A).forEach(o=>o.value=e)}getBool(A){var e,i,g;const I=typeof A=="string"?"name":"hash";return((g=(i=(e=this.model)==null?void 0:e.parameters)==null?void 0:i.find(o=>o[I]===A))==null?void 0:g.value)??!1}setFloat(A,e){var i,g;const I=typeof A=="string"?"name":"hash",o=(g=(i=this.model)==null?void 0:i.parameters)==null?void 0:g.filter(s=>s[I]===A);return o.forEach(s=>s.value=e),o?.length>0}getFloat(A){var e,i,g;const I=typeof A=="string"?"name":"hash";return((g=(i=(e=this.model)==null?void 0:e.parameters)==null?void 0:i.find(o=>o[I]===A))==null?void 0:g.value)??0}setInteger(A,e){var i,g;const I=typeof A=="string"?"name":"hash";return(g=(i=this.model)==null?void 0:i.parameters)==null?void 0:g.filter(o=>o[I]===A).forEach(o=>o.value=e)}getInteger(A){var e,i,g;const I=typeof A=="string"?"name":"hash";return((g=(i=(e=this.model)==null?void 0:e.parameters)==null?void 0:i.find(o=>o[I]===A))==null?void 0:g.value)??0}setTrigger(A){var e,i;GI&&console.log("SET TRIGGER",A);const g=typeof A=="string"?"name":"hash";return(i=(e=this.model)==null?void 0:e.parameters)==null?void 0:i.filter(I=>I[g]===A).forEach(I=>I.value=!0)}resetTrigger(A){var e,i;const g=typeof A=="string"?"name":"hash";return(i=(e=this.model)==null?void 0:e.parameters)==null?void 0:i.filter(I=>I[g]===A).forEach(I=>I.value=!1)}getTrigger(A){var e,i,g;const I=typeof A=="string"?"name":"hash";return((g=(i=(e=this.model)==null?void 0:e.parameters)==null?void 0:i.find(o=>o[I]===A))==null?void 0:g.value)??!1}isInTransition(){return this._activeStates.length>1}setSpeed(A){this._speed=A}FindState(A){return this.findState(A)}findState(A){if(!A)return null;if(Array.isArray(this.model.layers)){for(const e of this.model.layers)for(const i of e.stateMachine.states)if(i.name===A||i.hash==A)return i}return null}get context(){var A;return(A=this.animator)==null?void 0:A.context}get mixer(){return this._mixer}bind(A){A?this.animator!==A&&(this.animator=A,this._mixer=new uD(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;GI&&console.warn("AnimatorController clone()",this.model);const A=Lc(this.model,(e,i,g)=>g==null?!0:!(g.type==="Object3D"||g.isObject3D===!0||wH(g)||g.tracks!==void 0||g instanceof ko));return console.assert(A!==this.model),new ko(A)}update(A){var e,i;if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates(A);const g=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&((e=this.rootMotionHandler)==null||e.onBeforeUpdate(A)),this._mixer.update(g),this.animator.applyRootMotion&&((i=this.rootMotionHandler)==null||i.onAfterUpdate(A))}get activeState(){return this._activeState}updateActiveStates(A){for(let e=0;e<this._activeStates.length;e++){const i=this._activeStates[e],g=i.motion;if(!g.action)this._activeStates.splice(e,1),e--;else{const I=g.action;I.weight=A,I.getEffectiveWeight()<=0&&!I.isRunning()&&(GI&&console.debug("REMOVE",i.name,I.getEffectiveWeight(),I.isRunning(),I.isScheduled()),this._activeStates.splice(e,1),e--)}}}setStartTransition(){for(const A of this.model.layers){const e=A.stateMachine;e.defaultState===void 0&&(GI&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",A),e.defaultState=0);const i=e.states[e.defaultState];this.transitionTo(i,0,this.normalizedStartOffset)}}evaluateTransitions(){var A;let e=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;e=!0}const i=this._activeState,g=i.motion.action;for(const o of i.transitions){if(!o.hasExitTime&&o.conditions.length<=0)continue;let s=!0;for(const C of o.conditions)if(!this.evaluateCondition(C)){s=!1;break}if(s)if(g){const C=i.motion.clip.duration,a=C<=0?1:Math.abs(g.time/C);let n=!1;if(o.hasExitTime?g.timeScale>0?n=a>=o.exitTime:g.timeScale<0&&(n=1-a>=o.exitTime):n=!0,n){for(const B of o.conditions){const Q=this.model.parameters.find(E=>E.name===B.parameter);Q?.type===xU.Trigger&&Q.value&&(Q.value=!1)}g.clampWhenFinished=!0,GI&&console.log("transition to "+o.destinationState,o,a,o.exitTime,o.hasExitTime),this.transitionTo(o.destinationState,o.duration,o.offset);return}}else{this.transitionTo(o.destinationState,o.duration,o.offset);return}}if(g){let o=i.speed??1;i.speedParameter&&(o*=this.getFloat(i.speedParameter)),o!==void 0&&(g.timeScale=o*this._speed)}let I=!1;if(i.motion.isLooping&&g&&(g.time>=g.getClip().duration?(I=!0,g.reset(),g.time=0,g.play()):g.time<=0&&g.timeScale<0&&(I=!0,g.reset(),g.time=g.getClip().duration,g.play())),!I&&i&&!e&&g&&this.animator&&i.behaviours){const o=g?.getClip().duration,s=g.time/o,C=new Fw(this._activeState,s,o,this._speed);for(const a of i.behaviours)a.instance&&((A=a.instance.onStateUpdate)==null||A.call(a.instance,this.animator,C,0))}}getState(A,e){return typeof A=="number"&&(A==-1&&(A=this.model.layers[e].stateMachine.defaultState,A===void 0&&(GI&&console.warn("AnimatorController default state is undefined: ",this.model,"Layer: "+e),A=0)),A=this.model.layers[e].stateMachine.states[A]),A}transitionTo(A,e,i){var g,I,o,s,C,a,n,B;if(!this.animator)return;const Q=0;if(A=this.getState(A,Q),!(A!=null&&A.motion)||!A.motion.clip||!(A.motion.clip instanceof PI))return;const E=this._activeState===A;if(E){const c=A.motion;if(!c.action_loopback&&c.clip){const l=this.rootMotionHandler?this.animator.gameObject.matrix.clone():null;this._mixer.uncacheAction(c.clip,this.animator.gameObject),l&&l.decompose(this.animator.gameObject.position,this.animator.gameObject.quaternion,this.animator.gameObject.scale),c.action_loopback=this.createAction(c.clip)}}if((g=this._activeState)!=null&&g.behaviours&&this._activeState.motion.action){const c=(I=this._activeState)==null?void 0:I.motion.clip.duration,l=this._activeState.motion.action.time/c,p=new Fw(this._activeState,l,c,this._speed);for(const D of this._activeState.behaviours)(s=(o=D.instance)==null?void 0:o.onStateExit)==null||s.call(D.instance,this.animator,p,Q)}const h=(C=this._activeState)==null?void 0:C.motion.action;h&&h.fadeOut(e),E&&(A.motion.action=A.motion.action_loopback,A.motion.action_loopback=h);const d=this._activeState;this._activeState=A;const u=(a=A.motion)==null?void 0:a.action;if(u){if(i=Math.max(0,Math.min(1,i)),A.cycleOffsetParameter){let l=this.getFloat(A.cycleOffsetParameter);typeof l=="number"?(l<0&&(l+=1),i+=l,i%=1):GI&&console.warn("AnimatorController cycle offset parameter is not a number",A.cycleOffsetParameter)}else typeof A.cycleOffset=="number"&&(i+=A.cycleOffset,i%=1);u.isRunning()&&u.stop(),u.reset(),u.enabled=!0;const c=A.motion.clip.duration;if(u.time=E?0:i*c,u.timeScale<0&&(u.time=c-u.time),u.clampWhenFinished=!0,u.setLoop(ec,0),e>0?u.fadeIn(e):u.weight=1,u.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(u),this._activeStates.includes(A)||this._activeStates.push(A),this._activeState.behaviours){const l=new Fw(A,i,c,this._speed);for(const p of this._activeState.behaviours)(B=(n=p.instance)==null?void 0:n.onStateEnter)==null||B.call(p.instance,this.animator,l,Q)}}else GI&&(A.__warned_no_motion||(A.__warned_no_motion=!0,console.warn("No action",A.motion,this)));GI&&console.log("TRANSITION FROM "+d?.name+" TO "+A.name,e,h,u,u?.getEffectiveTimeScale(),u?.getEffectiveWeight(),u?.isRunning(),u?.isScheduled(),u?.paused)}createAction(A){var e,i;if(this._mixer.existingAction(A)&&this._mixer.uncacheAction(A,(e=this.animator)==null?void 0:e.gameObject),(i=this.animator)!=null&&i.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new FIA(this));const g=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,g,A)}else return this._mixer.clipAction(A)}evaluateCondition(A){const e=this.model.parameters.find(i=>i.name===A.parameter);if(!e)return!1;switch(A.mode){case Pn.If:return e.value===!0;case Pn.IfNot:return e.value===!1;case Pn.Greater:return e.value>A.threshold;case Pn.Less:return e.value<A.threshold;case Pn.Equals:return e.value===A.threshold;case Pn.NotEqual:return e.value!==A.threshold}return!1}createActions(A){var e,i,g,I;GI&&console.log("AnimatorController createActions",this.model);for(const o of this.model.layers){const s=o.stateMachine;for(let C=0;C<s.states.length;C++){const a=s.states[C];a.transitions||(a.transitions=[]);for(const n of a.transitions)n.conditions||(n.conditions=[]);if(a.motion||(a.motion=__(a.name)),this.animator&&a.motion.clips){const n=(e=a.motion.clips)==null?void 0:e.find(B=>{var Q,E;return B.node.name===((E=(Q=this.animator)==null?void 0:Q.gameObject)==null?void 0:E.name)});n?a.motion.clip=n.clip:(GI||Se())&&console.warn('Could not find clip for animator "'+((g=(i=this.animator)==null?void 0:i.gameObject)==null?void 0:g.name)+'"',a.motion.clips.map(B=>B.node.name))}if(!a.motion.clip){const n=new PI(void 0,void 0,[]);a.motion.clip=n}if((I=a.motion)!=null&&I.clip){const n=a.motion.clip;if(n instanceof PI){const B=this.createAction(n);a.motion.action=B}else(GI||Se())&&console.warn("No valid animationclip assigned",a)}if(a.behaviours&&Array.isArray(a.behaviours))for(const n of a.behaviours){if(!(n!=null&&n.typeName))continue;const B=z.get(n.typeName),Q=new B;Q.isStateMachineBehaviour&&(Q._context=this.context??void 0,BE(Q,n.properties),n.instance=Q),GI&&console.log("Created animator controller behaviour",a.name,n.typeName,n.properties,Q)}}}}*enumerateActions(){if(this.model.layers)for(const A of this.model.layers){const e=A.stateMachine;for(let i=0;i<e.states.length;i++){const g=e.states[i];g!=null&&g.motion&&(g.motion.action&&(yield g.motion.action),g.motion.action_loopback&&(yield g.motion.action_loopback))}}}}class O_{constructor(A,e){r(this,"track"),r(this,"createdInterpolant"),r(this,"originalEvaluate"),r(this,"customEvaluate"),this.track=A;const i=A,g=i.createInterpolant.bind(A);i.createInterpolant=()=>(i.createInterpolant=g,this.createdInterpolant=g(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=I=>{if(!this.originalEvaluate)return;const o=this.originalEvaluate(I);return e(I,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 lg=class{constructor(t,A,e,i,g){if(r(this,"_action"),r(this,"root"),r(this,"clip"),r(this,"positionWrapper",null),r(this,"rotationWrapper",null),r(this,"context"),r(this,"positionChange",new w),r(this,"rotationChange",new FA),r(this,"_prevTime",0),this.context=t,this.root=A,this.clip=e,lg.firstKeyframeRotation[this.cacheId]||(lg.firstKeyframeRotation[this.cacheId]=new FA),g){const I=g.values;lg.firstKeyframeRotation[this.cacheId].set(I[0],I[1],I[2],I[3])}lg.spaceRotation[this.cacheId]||(lg.spaceRotation[this.cacheId]=new FA),lg.effectiveSpaceRotation[this.cacheId]||(lg.effectiveSpaceRotation[this.cacheId]=new FA),lg.clipOffsetRotation[this.cacheId]=new FA,g&&lg.clipOffsetRotation[this.cacheId].set(g.values[0],g.values[1],g.values[2],g.values[3]).invert(),this.handlePosition(e,i),this.handleRotation(e,g)}set action(t){this._action=t}get action(){return this._action}get cacheId(){return this.root.uuid}onStart(t){if(t.getClip()!==this.clip)return;lg.lastObjRotation[this.cacheId]||(lg.lastObjRotation[this.cacheId]=this.root.quaternion.clone());const A=lg.lastObjRotation[this.cacheId];if(lg.spaceRotation[this.cacheId].copy(A),Kw){const e=new Wg().setFromQuaternion(A);console.log("START",this.clip.name,Ie.toDegrees(e.y),this.root.position.z)}}getClipRotationOffset(){return lg.clipOffsetRotation[this.cacheId]}handlePosition(t,A){if(A){const e=this.root;Kw&&e.add(new Fo),lg.lastObjPosition[this.cacheId]||(lg.lastObjPosition[this.cacheId]=this.root.position.clone());const i=new w,g=new w;this.positionWrapper=new O_(A,(I,o)=>{const s=this.action.getEffectiveWeight();return Kw&&e.position.length()>8&&e.position.set(0,e.position.y,0),I>this._prevTime&&(i.set(o[0],o[1],o[2]),i.sub(g),i.multiplyScalar(s),i.applyQuaternion(this.getClipRotationOffset()),i.applyQuaternion(e.quaternion),this.positionChange.copy(i)),g.fromArray(o),this._prevTime=I,o[0]=0,o[1]=0,o[2]=0,o})}}handleRotation(t,A){if(A){if(Kw){const I=A.values,o=new Wg().setFromQuaternion(new FA(I[0],I[1],I[2],I[3]));console.log(t.name,A.name,"FIRST ROTATION IN TRACK",Ie.toDegrees(o.y));const s=A.values.length-4,C=new FA().set(I[s],I[s+1],I[s+2],I[s+3]),a=new Wg().setFromQuaternion(C);console.log(t.name,A.name,"LAST ROTATION IN TRACK",Ie.toDegrees(a.y))}let e=0;const i=new FA,g=new FA;this.rotationWrapper=new O_(A,(I,o)=>(I>e&&(g.set(o[0],o[1],o[2],o[3]),i.invert(),g.multiply(i),this.rotationChange.copy(g)),i.fromArray(o),e=I,o[0]=0,o[1]=0,o[2]=0,o[3]=1,o))}}onBeforeUpdate(t){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(t){return!this.action||(t*=this.action.getEffectiveWeight(),t<=0)?!1:(this.positionChange.multiplyScalar(t),this.rotationChange.slerp(lg.identityQuaternion,1-t),!0)}};let jn=lg;r(jn,"lastObjPosition",{}),r(jn,"lastObjRotation",{}),r(jn,"firstKeyframeRotation",{}),r(jn,"spaceRotation",{}),r(jn,"effectiveSpaceRotation",{}),r(jn,"clipOffsetRotation",{}),r(jn,"identityQuaternion",new FA);class FIA{constructor(A){r(this,"controller"),r(this,"handler",[]),r(this,"root"),r(this,"basePosition",new w),r(this,"baseQuaternion",new FA),r(this,"baseRotation",new Wg),r(this,"summedPosition",new w),r(this,"summedRotation",new FA),this.controller=A}createClip(A,e,i){this.root=e,e&&"name"in e&&e.name;const g=this.findRootTrack(i,".position"),I=this.findRootTrack(i,".quaternion"),o=new jn(this.controller.context,e,i,g,I);this.handler.push(o);const s=A.clipAction(i);return o.action=s,s}onStart(A){for(const e of this.handler)e.onStart(A)}onBeforeUpdate(A){this.basePosition.copy(this.root.position),this.baseQuaternion.copy(this.root.quaternion);for(const e of this.handler)e.onBeforeUpdate(A)}onAfterUpdate(A){if(!(A<=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 e of this.handler)e.onAfterUpdate(A)&&(this.summedPosition.add(e.positionChange),this.summedRotation.multiply(e.rotationChange));this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation)}}findRootTrack(A,e){const i=A.tracks;if(!i)return null;for(const g of i)if(g.name.endsWith(e))return g;return null}}class KIA extends na{onSerialize(A,e){}onDeserialize(A,e){if(e.type===ko&&A?.__type==="AnimatorController")return new ko(A)}}new KIA(ko);var JIA=Object.defineProperty,vIA=Object.getOwnPropertyDescriptor,Jw=(t,A,e,i)=>{for(var g=i>1?void 0:i?vIA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&JIA(A,e,g),g};const Xo=iA("debuganimator");class bg extends JA{constructor(){super(...arguments),r(this,"applyRootMotion",!1),r(this,"hasRootMotion",!1),r(this,"keepAnimatorControllerStateOnDisable",!1),r(this,"_parametersAreDirty",!1),r(this,"_isDirty",!1),r(this,"speed",1),r(this,"normalizedStartOffset",0),r(this,"_animatorController",null),r(this,"_initializeWithRuntimeAnimatorController")}set runtimeAnimatorController(A){var e;this._animatorController&&this._animatorController.model===A||(A?A instanceof ko?(A.animator&&A.animator!==this&&(console.warn("AnimatorController can not be bound to multiple animators",(e=A.model)==null?void 0:e.name),A.model||console.error("AnimatorController has no model"),A=new ko(A.model)),this._animatorController=A,this._animatorController.bind(this)):(Xo&&console.log("Assign animator controller",A,this),this._animatorController=new ko(A),this.__didAwake&&this._animatorController.bind(this)):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}get parametersAreDirty(){return this._parametersAreDirty}get isDirty(){return this._isDirty}Play(A,e=-1,i=Number.NEGATIVE_INFINITY,g=0){this.play(A,e,i,g)}play(A,e=-1,i=Number.NEGATIVE_INFINITY,g=0){var I;(I=this.runtimeAnimatorController)==null||I.play(A,e,i,g),this._isDirty=!0}Reset(){this.reset()}reset(){var A;(A=this._animatorController)==null||A.reset(),this._isDirty=!0}SetBool(A,e){this.setBool(A,e)}setBool(A,e){var i,g;Xo&&console.log("setBool",A,e),((i=this.runtimeAnimatorController)==null?void 0:i.getBool(A))!==e&&(this._parametersAreDirty=!0),(g=this.runtimeAnimatorController)==null||g.setBool(A,e)}GetBool(A){return this.getBool(A)}getBool(A){var e;const i=((e=this.runtimeAnimatorController)==null?void 0:e.getBool(A))??!1;return Xo&&console.log("getBool",A,i),i}toggleBool(A){this.setBool(A,!this.getBool(A))}SetFloat(A,e){this.setFloat(A,e)}setFloat(A,e){var i,g;((i=this.runtimeAnimatorController)==null?void 0:i.getFloat(A))!==e&&(this._parametersAreDirty=!0),Xo&&console.log("setFloat",A,e),(g=this.runtimeAnimatorController)==null||g.setFloat(A,e)}GetFloat(A){return this.getFloat(A)}getFloat(A){var e;const i=((e=this.runtimeAnimatorController)==null?void 0:e.getFloat(A))??-1;return Xo&&console.log("getFloat",A,i),i}SetInteger(A,e){this.setInteger(A,e)}setInteger(A,e){var i,g;((i=this.runtimeAnimatorController)==null?void 0:i.getInteger(A))!==e&&(this._parametersAreDirty=!0),Xo&&console.log("setInteger",A,e),(g=this.runtimeAnimatorController)==null||g.setInteger(A,e)}GetInteger(A){return this.getInteger(A)}getInteger(A){var e;const i=((e=this.runtimeAnimatorController)==null?void 0:e.getInteger(A))??-1;return Xo&&console.log("getInteger",A,i),i}SetTrigger(A){this.setTrigger(A)}setTrigger(A){var e;this._parametersAreDirty=!0,Xo&&console.log("setTrigger",A),(e=this.runtimeAnimatorController)==null||e.setTrigger(A)}ResetTrigger(A){this.resetTrigger(A)}resetTrigger(A){var e;this._parametersAreDirty=!0,Xo&&console.log("resetTrigger",A),(e=this.runtimeAnimatorController)==null||e.resetTrigger(A)}GetTrigger(A){this.getTrigger(A)}getTrigger(A){var e;const i=(e=this.runtimeAnimatorController)==null?void 0:e.getTrigger(A);return Xo&&console.log("getTrigger",A,i),i}IsInTransition(){return this.isInTransition()}isInTransition(){var A;return((A=this.runtimeAnimatorController)==null?void 0:A.isInTransition())??!1}SetSpeed(A){return this.setSpeed(A)}setSpeed(A){var e;A!==this.speed&&(Xo&&console.log("setSpeed",A),this.speed=A,(e=this._animatorController)==null||e.setSpeed(A))}set minMaxSpeed(A){this.speed=Ie.lerp(A.x,A.y,Math.random())}set minMaxOffsetNormalized(A){this.normalizedStartOffset=Ie.lerp(A.x,A.y,Math.random()),this.runtimeAnimatorController&&(this.runtimeAnimatorController.normalizedStartOffset=this.normalizedStartOffset)}awake(){Xo&&console.log("ANIMATOR",this.name,this),this.gameObject&&this.initializeRuntimeAnimatorController()}initializeRuntimeAnimatorController(A=!1){const e=A||this.runtimeAnimatorController!==this._initializeWithRuntimeAnimatorController;if(this.runtimeAnimatorController&&e){const i=this.runtimeAnimatorController.clone();this._initializeWithRuntimeAnimatorController=i,i?(console.assert(this.runtimeAnimatorController!==i),this.runtimeAnimatorController=i,console.assert(this.runtimeAnimatorController===i),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 A;this.keepAnimatorControllerStateOnDisable||(A=this._animatorController)==null||A.reset()}onBeforeRender(){this._isDirty=!1,this._parametersAreDirty=!1,!RIA(this.gameObject)&&this._animatorController&&this._animatorController.update(1)}}Jw([y()],bg.prototype,"applyRootMotion",2),Jw([y()],bg.prototype,"hasRootMotion",2),Jw([y()],bg.prototype,"keepAnimatorControllerStateOnDisable",2),Jw([y()],bg.prototype,"runtimeAnimatorController",1);const WE=iA("debugusdzanimation"),YU=iA("debugusdzanimationserialization");class vw{constructor(A,e,i){r(this,"_start"),r(this,"ext"),r(this,"root"),r(this,"clip"),this.ext=A,this.root=e,this.clip=i}get start(){return this._start===void 0&&(this._start=this.ext.getStartTime01(this.root,this.clip)),this._start}get duration(){return this.clip.duration}}class $o{constructor(A,e,i){r(this,"clip"),r(this,"pos"),r(this,"rot"),r(this,"scale"),r(this,"root"),r(this,"target"),r(this,"duration",0),r(this,"useRootMotion",!1),this.root=A,this.target=e,this.clip=i,i?this.duration=i.duration:this.duration=1/this.frameRate;const g=aA.getComponent(A,bg);g&&(this.useRootMotion=g.applyRootMotion)}get frameRate(){return 60}addTrack(A){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}A.name.endsWith("position")&&(this.pos=A),A.name.endsWith("quaternion")&&(this.rot=A),A.name.endsWith("scale")&&(this.scale=A)}getFrames(){var A,e,i,g,I,o;return this.clip?Math.max(((e=(A=this.pos)==null?void 0:A.times)==null?void 0:e.length)??0,((g=(i=this.rot)==null?void 0:i.times)==null?void 0:g.length)??0,((o=(I=this.scale)==null?void 0:I.times)==null?void 0:o.length)??0):2}getDuration(){return this.duration}getSortedTimesArray(A=!0,e=!0,i=!0){var g,I,o;if(!this.clip)return[0,this.duration];const s=(g=this.pos)==null?void 0:g.times,C=(I=this.rot)==null?void 0:I.times,a=(o=this.scale)==null?void 0:o.times,n=[];if(A&&s)for(const B of s)n.push(B);if(e&&C)for(const B of C)n.push(B);if(i&&a)for(const B of a)n.push(B);return n.includes(0)||n.push(0),n.sort((B,Q)=>B-Q),[...new Set(n)]}*getValues(A,e=!0,i=!0,g=!0){var I,o,s;const C=new w,a=new FA,n=new w(1,1,1),B=this.target,Q=e?(I=this.pos)==null?void 0:I.createInterpolant():void 0,E=i?(o=this.rot)==null?void 0:o.createInterpolant():void 0,h=g?(s=this.scale)==null?void 0:s.createInterpolant():void 0;Q||C.set(B.position.x,B.position.y,B.position.z),E||a.set(B.quaternion.x,B.quaternion.y,B.quaternion.z,B.quaternion.w),h||n.set(B.scale.x,B.scale.y,B.scale.z);for(let d=0;d<A.length;d++){const u=A[d];if(Q){const c=Q.evaluate(u);C.set(c[0],c[1],c[2])}if(E){const c=E.evaluate(u);a.set(c[0],c[1],c[2],c[3])}if(h){const c=h.evaluate(u);n.set(c[0],c[1],c[2])}if(this.useRootMotion&&B===this.root){const c=new NA;c.compose(C,a,n),c.multiply(B.matrix),c.decompose(C,a,n)}yield{time:u,translation:C,rotation:a,scale:n,index:d}}}}r($o,"animationDurationPadding",1);class Ed{constructor(A){r(this,"dict",new Map),r(this,"rootTargetMap",new Map),r(this,"rootAndClipToRegisteredAnimationMap",new Map),r(this,"rootToRegisteredClipCount",new Map),r(this,"serializers",[]),r(this,"injectRestPoses",!1),r(this,"injectImplicitBehaviours",!1),this.injectRestPoses=A,this.injectImplicitBehaviours=A}get extensionName(){return"animation"}getClipCount(A){let e=this.rootToRegisteredClipCount.get(A);return this.injectRestPoses&&(e=e?e-1:0),e??0}getStartTime01(A,e){const i=this.rootTargetMap.get(A);if(!i)return 0;const g=this.dict.get(i[0]);if(!g)return console.error("Trying to get start time for root that has no animation data",A,e,...this.dict),0;let I=0;for(let o=0;o<g.length&&g[o].clip!==e;o++)I+=g[o].getDuration()+$o.animationDurationPadding;return I}registerAnimation(A,e){if(!e||!A)return null;this.rootTargetMap.has(A)||this.rootTargetMap.set(A,[]);const i=A.uuid+e.uuid;if(this.rootAndClipToRegisteredAnimationMap.has(i))return this.rootAndClipToRegisteredAnimationMap.get(i);WE&&console.log("registerAnimation",A,e);const g=this.injectRestPoses?1:0,I=this.rootToRegisteredClipCount.get(A)??g,o=this.rootTargetMap.get(A),s=new Set(o);if(e.tracks)for(const a of e.tracks){const n=We.parseTrackName(a.name),B=We.findNode(A,n.nodeName);if(!B){console.warn("no object found for track",a.name,"using "+A.name+" instead");continue}this.dict.has(B)||this.dict.set(B,[]);const Q=this.dict.get(B);if(!Q)continue;if(s.delete(B),this.injectRestPoses&&!Q[0]){const h=new $o(null,B,void 0);Q[0]=h}let E=Q[I];E||(E=new $o(A,B,e),Q[I]=E),E.addTrack(a),o!=null&&o.includes(B)||o==null||o.push(B)}for(const a of s){const n=this.dict.get(a);if(!n)continue;if(this.injectRestPoses&&!n[0]){const Q=new $o(null,a,void 0);n[0]=Q}let B=n[I];B||(WE&&console.log("Adding padding clip for ",a,e),B=new $o(A,a,e),n[I]=B)}const C=new vw(this,A,e);return this.rootAndClipToRegisteredAnimationMap.set(i,C),this.rootToRegisteredClipCount.set(A,I+1),C}onAfterHierarchy(A){WE&&console.log("Animation clips per animation target node",this.dict)}onAfterBuildDocument(A){var e,i;for(const g of this.serializers){const I=(e=g.model)==null?void 0:e.parent,o=I?.isDynamic===!0;YU&&console.log(o,(i=g.model)==null?void 0:i.parent),o&&g.registerCallback(I)}}onExportObject(A,e,i){aA.foreachComponent(A,I=>{const o=I;typeof o.createAnimation=="function"&&o.createAnimation(this,e,i)},!1);const g=new bIA(A,this.dict);this.serializers.push(g),g.registerCallback(e)}}class bIA{constructor(A,e){r(this,"object"),r(this,"dict"),r(this,"model"),r(this,"callback"),this.object=A,this.dict=e}registerCallback(A){this.model&&this.callback&&this.model.removeEventListener("serialize",this.callback),this.callback||(this.callback=this.onSerialize.bind(this)),YU&&console.log("REPARENT",A),this.model=A,this.model.addEventListener("serialize",this.callback)}skinnedMeshExport(A,e){const i=this.model,g=this.dict;if(i&&i.skinnedMesh){let I=function(f){const U=[];for(const[M,m]of f){let x=`${M} : [`;const L=[];for(const V of m)L.push(`(${hg(V.x)}, ${hg(V.y)}, ${hg(V.z)})`);x=x.concat(L.join(", ")),x=x.concat("],"),U.push(x)}return U},o=function(f){const U=[];for(const[M,m]of f){let x=`${M} : [`;const L=[];for(const V of m)L.push(`(${hg(V.w)}, ${hg(V.x)}, ${hg(V.y)}, ${hg(V.z)})`);x=x.concat(L.join(", ")),x=x.concat("],"),U.push(x)}return U},s=function(f){let U=!0,M;for(const[x,L]of f)if(M===void 0&&(M=L.length),M!==L.length){U=!1;break}WE&&console.log("Bone count: ",f.size,"TransformData entries per bone: ",M),console.assert(U,"All bones should have the same number of TransformData entries",f);const m=[];for(const[x,L]of f){const V=new Array;let Y=0;for(let P=0;P<L.length;P++)V.push(Y),Y+=L[P].getDuration()+$o.animationDurationPadding;for(let P=0;P<L.length;P++){const b=L[P],T=V[P];m.length<=P&&m.push({pos:[],rot:[],scale:[],timeOffset:T});const _=m[P];_.pos.push(...b.getSortedTimesArray(!0,!1,!1)),_.rot.push(...b.getSortedTimesArray(!1,!0,!1)),_.scale.push(...b.getSortedTimesArray(!1,!1,!0))}}for(const x of m)x.pos.sort((L,V)=>L-V),x.rot.sort((L,V)=>L-V),x.scale.sort((L,V)=>L-V),x.pos=[...new Set(x.pos)],x.rot=[...new Set(x.rot)],x.scale=[...new Set(x.scale)];return m},C=function(f,U,M){const m=new Map,x=new Map,L=new Map,V=U.length;for(const Y of M){const P=f.get(Y);let b;P?console.assert(P.length===V,"We should have the same number of TransformData entries for each bone",P,U):b=new $o(null,Y,void 0);for(let T=0;T<V;T++){const _=P?P[T]:b,eA=U[T];for(const{time:$,translation:IA}of _.getValues(eA.pos,!0,!1,!1)){const yA=($+eA.timeOffset)*60;m.has(yA)||m.set(yA,new Array),m.get(yA).push(IA.clone())}for(const{time:$,rotation:IA}of _.getValues(eA.rot,!1,!0,!1)){const yA=($+eA.timeOffset)*60;x.has(yA)||x.set(yA,new Array),x.get(yA).push(IA.clone())}for(const{time:$,scale:IA}of _.getValues(eA.scale,!1,!1,!0)){const yA=($+eA.timeOffset)*60;L.has(yA)||L.set(yA,new Array),L.get(yA).push(IA.clone())}}}return{position:m.size==0?void 0:m,quaternion:x.size==0?void 0:x,scale:L.size==0?void 0:L}},a=function(f){const U=[];for(const M of f)U.push(`(${hg(M.x)}, ${hg(M.y)}, ${hg(M.z)})`);return U.join(", ")},n=function(f){const U=[];for(const M of f)U.push(`(${hg(M.w)}, ${hg(M.x)}, ${hg(M.y)}, ${hg(M.z)})`);return U.join(", ")},B=function(f){const U=new Map;if(WE){const M=new Array;for(const[m,x]of g)M.push(m.uuid+": "+x.length+" "+x.map(L=>{var V;return(V=L.clip)==null?void 0:V.uuid.substring(0,6)}).join(" "));console.log(`getPerBoneTransformData
5409
5411
  `+M.join(`
5410
- `))}for(const M of f){const m=g.get(M);m&&U.set(M,m)}return U},Q=function(f){const U=B(f),M=s(U);return C(U,M,f)};const E=i.skinnedMesh.skeleton,h=new Array;for(const f in E.bones){const U=E.bones[f],M=E.boneInverses[f];h.push({bone:U,inverse:M})}for(const f of h_(E.bones))h.push({bone:f,inverse:f.matrixWorld.clone().invert()});const d=h[0].bone.parent;d||console.error("No bone parent found for skinned mesh during USDZ export",i.skinnedMesh),h.sort((f,U)=>LE(f.bone,d)>LE(U.bone,d)?1:-1);const u=[],c=[],l=[],p=[];for(const{bone:f}of h)u.push(f.matrix.clone()),c.push(f.position),l.push(f.quaternion),p.push(f.scale);const D=h.map(f=>'"'+LE(f.bone,d)+'"').join(", "),S=h.map(f=>xE(f.inverse.clone().invert())).join(", ");A.beginBlock('def Skeleton "Rig"'),A.appendLine(`uniform matrix4d[] bindTransforms = [${S}]`),A.appendLine(`uniform token[] joints = [${D}]`),A.appendLine('uniform token purpose = "guide"'),A.appendLine(`uniform matrix4d[] restTransforms = [${u.map(f=>xE(f)).join(", ")}]`),A.appendLine(`matrix4d xformOp:transform = ${xE(new NA)}`),A.appendLine('uniform token[] xformOpOrder = ["xformOp:transform"]');const k=Q(h.map(f=>f.bone));if(A.beginBlock('def SkelAnimation "_anim"'),A.appendLine(`uniform token[] joints = [${D}]`),A.appendLine(`quatf[] rotations = [${n(l)}]`),k&&k.quaternion){A.beginBlock("quatf[] rotations.timeSamples = {","");const f=o(k.quaternion);for(const U of f)A.appendLine(U);A.closeBlock()}if(A.appendLine(`half3[] scales = [${a(p)}]`),k&&k.scale){A.beginBlock("half3[] scales.timeSamples = {","");const f=I(k.scale);for(const U of f)A.appendLine(U);A.closeBlock()}if(A.appendLine(`float3[] translations = [${a(c)}]`),k&&k.position){A.beginBlock("float3[] translations.timeSamples = {","");const f=I(k.position);for(const U of f)A.appendLine(U);A.closeBlock()}A.closeBlock(),A.closeBlock()}}onSerialize(A,e){var i;if(!this.model)return;this.skinnedMeshExport(A,e);const g=this.object,I=this.dict.get(g);if(!I||g.isSkinnedMesh)return;YU&&console.log("SERIALIZE",this.model.name,this.object.type,I);const o=new NA;A.appendLine("matrix4d xformOp:transform.timeSamples = {"),A.indent++;const s=new Array;let C=0;for(let a=0;a<I.length;a++)s.push(C),C+=I[a].getDuration()+$o.animationDurationPadding;for(let a=0;a<I.length;a++){const n=I[a];if(!n)continue;const B=s[a];{const Q=n.getSortedTimesArray();if(!Q||Q.length===0){console.error("got an animated object but no time values?",g,n);continue}if(WE){const E=((i=n.clip)==null?void 0:i.name)??"rest",h=n.getDuration();console.log("Write .timeSamples:",E,B,h,I),A.appendLine("# "+E+": start="+(B*n.frameRate).toFixed(3)+", length="+(h*n.frameRate).toFixed(3)+", frames="+n.getFrames())}for(const{time:E,translation:h,rotation:d,scale:u}of n.getValues(Q)){o.compose(h,d,u);const c=`${(B+E)*n.frameRate}: ${xE(o)},`;A.appendLine(c)}}}A.indent--,A.appendLine("}")}}var qIA=Object.defineProperty,LIA=Object.getOwnPropertyDescriptor,P_=(t,A,e,i)=>{for(var g=i>1?void 0:i?LIA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&qIA(A,e,g),g};const j_=iA("debugpost");class Ke{constructor(A){r(this,"_active",!0),r(this,"_value"),r(this,"_valueRaw"),r(this,"_defaultValue"),r(this,"valueProcessor"),r(this,"onValueChanged"),this._value=A,this._defaultValue=A,this._valueRaw=A}get overrideState(){return this._active}set overrideState(A){if(this._active===A)return;this._active=A;const e=A?this._valueRaw:this._defaultValue;this.processValue(e,!0)}get value(){return this._valueRaw}set value(A){this.processValue(A,!1)}set defaultValue(A){this._defaultValue=A}__init(){this.processValue(this._valueRaw,!0)}processValue(A,e){if(A==null||!e&&this.testIfValueChanged(A)===!1)return;const i=this._value;j_&&console.log("VolumeParameter: value changed from",i,"to",A),!this._active&&this._defaultValue!==void 0?(this._value=this._defaultValue,A=this._defaultValue,this._valueRaw=A):(this._valueRaw=A,this._active&&this.valueProcessor&&(A=this.valueProcessor(A)),this._value=A),this.onValueChanged?this.onValueChanged(A,i,this):j_&&console.log("VolumeParameter: onValueChanged not set")}testIfValueChanged(A){return this._valueRaw!==A}}P_([y()],Ke.prototype,"overrideState",1),P_([y()],Ke.prototype,"value",1);var xIA=Object.defineProperty,YIA=Object.getOwnPropertyDescriptor,TIA=(t,A,e,i)=>{for(var g=i>1?void 0:i?YIA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&xIA(A,e,g),g};const HIA=iA("debugpost");class rI extends JA{constructor(A=void 0){if(super(),r(this,"active",!0),r(this,"_result"),r(this,"_didCreateVolumeParameters",!1),A){this.ensureVolumeParameters();for(const e of Object.keys(A)){const i=A[e],g=this[e];g instanceof Ke&&(g.value=i)}}}onEnable(){this.__internalDidAwakeAndStart&&(this.active=!0)}onDisable(){this.active=!1}init(){}apply(){var A;return this.ensureVolumeParameters(),this._result||(this._result=(A=this.onCreateEffect)==null?void 0:A.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){HIA&&console.warn("DISPOSE",this),this._result&&(Array.isArray(this._result)?this._result.forEach(A=>A.dispose()):this._result.dispose()),this._result=void 0}initParameters(){const A=Object.keys(this);for(const e of A){const i=this[e];i instanceof Ke&&i.__init()}}onAfterDeserialize(A,e){if(typeof A=="object"){const i=this.$serializedTypes;if(i){for(const g of Object.keys(i))if(i[g]===Ke){const I=A[g];if(I!==void 0){const o=this[g];o.value=I}}}}}onEditorModification(A){const e=A.propertyName;if(this[e]instanceof Ke){const i=A.value;return this[e].value=i,!0}}ensureVolumeParameters(){if(this._didCreateVolumeParameters)return;this._didCreateVolumeParameters=!0;const A=this.$serializedTypes;if(A)for(const e of Object.keys(A))A[e]===Ke&&(this[e]||(this[e]=new Ke))}}TIA([y()],rI.prototype,"active",2);var _IA=Object.defineProperty,OIA=Object.getOwnPropertyDescriptor,PIA=(t,A,e,i)=>{for(var g=i>1?void 0:i?OIA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&_IA(A,e,g),g};const jIA=iA("debugpost"),TU={};function As(t,A){TU[t]=A}function WIA(t){return t.__type in TU?TU[t.__type]:(jIA&&t.__type&&console.warn("Unknown postprocessing type",t.__type,t),rI)}class hd{constructor(){r(this,"components",[])}init(){var A;(A=this.components)==null||A.forEach(e=>e.init())}}PIA([RE([t=>WIA(t),rI])],hd.prototype,"components",2);var VIA=Object.defineProperty,ZIA=Object.getOwnPropertyDescriptor,zIA=(t,A,e,i)=>{for(var g=i>1?void 0:i?ZIA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&VIA(A,e,g),g};class cd extends rI{constructor(){super(...arguments),r(this,"preset")}get typeName(){return"Antialiasing"}onCreateEffect(){const A=new WX({preset:aE.HIGH,edgeDetectionMode:pG.DEPTH});return this.preset.onValueChanged=e=>{A.applyPreset(e)},A}}zIA([y(Ke)],cd.prototype,"preset",2),As("Antialiasing",cd);class bw{constructor(){r(this,"files",[])}get extensionName(){return"Audio"}onExportObject(A,e,i){const g=aA.getComponents(A,fi);if(g.length)for(const I of g){if(!I.clip||typeof I.clip!="string"||!I.playOnAwake)continue;const o=I.clip.split("/").pop();this.files.includes(I.clip)||this.files.push(I.clip),e.addEventListener("serialize",(s,C)=>{s.appendLine(),s.beginBlock(`def SpatialAudio "${e.name}"`),s.appendLine(`uniform asset filePath = @audio/${o}@`),s.appendLine(`uniform token auralMode = "${I.spatialBlend>0?"spatial":"nonSpatial"}"`),s.appendLine(`uniform token playbackMode = "${I.loop?"loopFromStage":"onceFromStart"}"`),s.appendLine(`uniform float gain = ${I.volume}`),s.closeBlock()})}}async onAfterSerialize(A){for(const e of this.files){const i=e.split("/").pop(),g=await(await(await fetch(e)).blob()).arrayBuffer(),I=new Uint8Array(g);A.files["audio/"+i]=I}}}const MB=iA("debugautosync"),HU=Symbol("syncerId");class XIA{constructor(){r(this,"_syncers",{})}getOrCreateSyncer(A){if(!A.guid)return null;if(this._syncers[A.guid])return this._syncers[A.guid];const e=new $IA(A);return e[HU]=A.guid,this._syncers[e[HU]]=e,e}removeSyncer(A){delete this._syncers[A[HU]]}}const _U=new XIA;class $IA{constructor(A){r(this,"comp"),r(this,"hasChanges",!1),r(this,"changedProperties",{}),r(this,"data",{}),r(this,"_boundEvent"),r(this,"_handleReceivingMethod"),r(this,"_isReceiving",!1),r(this,"_isInit",!1),this.comp=A}get networkingKey(){return this.comp.guid}init(A){if(this._isInit)return;this._isInit=!0,this.comp=A,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 e=this.comp.context.connection.tryGetState(this.comp.guid);e&&this.onHandleReceiving(e)}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(A,e){this._isReceiving||(MB&&console.log("Property changed: "+A,e),this.hasChanges=!0,this.changedProperties[A]=e)}onHandleSending(){if(!this.hasChanges)return;this.hasChanges=!1;const A=this.comp.context.connection;if(!A||!A.isConnected){for(const e in this.changedProperties)delete this.changedProperties[e];return}for(const e in this.data)delete this.data[e];this.data.guid=this.comp.guid;for(const e in this.changedProperties){const i=this.changedProperties[e];delete this.changedProperties[e],this.data[e]=i}A.send(this.networkingKey,this.data)}onHandleReceiving(A){if(MB&&console.log("RECEIVE",this.comp.name,this.comp.guid,A),!this._isInit||!this.comp)return;const e=A.guid;if(!(e&&e!==this.comp.guid)){MB&&console.log("RECEIVED",this.comp.name,this.comp.guid,A);try{this._isReceiving=!0;for(const i in A){if(i==="guid")continue;const g=A[i];this.comp[i]=g,MB&&console.log("SET",i,g)}}catch(i){console.error(i)}finally{this._isReceiving=!1}}}}function AoA(t,A){let e=A!==t;return!e&&t&&A&&(Array.isArray(t)&&Array.isArray(A)||typeof t=="object"&&typeof A=="object")&&(e=!0),e}const ld=Symbol("AutoSyncHandler");function eoA(t){if(t[ld])return t[ld];const A=_U.getOrCreateSyncer(t);return A?.init(t),t[ld]=A,A}function toA(t){const A=t[ld];A&&(_U.removeSyncer(A),A.destroy(),delete t[ld])}const OU=function(t){return function(A,e){var i;let g="";typeof e=="string"?g=e:g=e.name;let I=null,o;typeof t=="string"?o=A[t]:typeof t=="function"&&(o=t);const s=A,C=s.__internalAwake;if(typeof C!="function"){(MB||Se())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+((i=A?.constructor)==null?void 0:i.name)+'" is not supported',A);return}MB&&console.log(g);const a=Symbol(g);s.__internalAwake=function(){if(this[a]!==void 0)return;this[a]=this[g],I=_U.getOrCreateSyncer(this);const B=Object.getOwnPropertyDescriptor(this,g);if(B?.set===void 0){let Q=!1;Object.defineProperty(this,g,{set:function(E){var h;const d=this[a];if(this[a]=E,Q){Se()&&console.warn("Recursive call detected",g);return}Q=!0;try{const u=AoA(E,d);MB&&console.log("SyncField assignment",g,"changed?",u,E),u&&o?.call(this,E,d)!==!1&&((h=eoA(this))==null||h.notifyChanged(g,E))}finally{Q=!1}},get:function(){return this[a]},configurable:!0,enumerable:!0})}I?.init(this),C.call(this)};const n=s.__internalDestroy;s.__internalDestroy=function(){toA(this),n.call(this)}}};var ioA=Object.defineProperty,goA=Object.getOwnPropertyDescriptor,qw=(t,A,e,i)=>{for(var g=i>1?void 0:i?goA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&ioA(A,e,g),g};const es=iA("debugplayersync");class VE extends JA{constructor(){super(...arguments),r(this,"autoSync",!0),r(this,"asset"),r(this,"onPlayerSpawned"),r(this,"_localInstance"),r(this,"onJoinedRoom",()=>{es&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()})}awake(){this.watchTabVisible(),this.onPlayerSpawned||(this.onPlayerSpawned=new Eg)}onEnable(){this.context.connection.beginListen(ht.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(ht.JoinedRoom,this.onJoinedRoom),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(ht.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(ht.JoinedRoom,this.onJoinedRoom)}async getInstance(){var A,e,i,g,I,o;if(this._localInstance)return this._localInstance;if(es&&console.log("PlayerSync.createInstance",(A=this.asset)==null?void 0:A.uri),!((e=this.asset)!=null&&e.asset)&&!((i=this.asset)!=null&&i.uri))return console.error('PlayerSync: can not create an instance because "asset" is not set!'),null;this._localInstance=(g=this.asset)==null?void 0:g.instantiateSynced({parent:this.gameObject},!0);const s=await this._localInstance;if(s){const C=aA.getComponent(s,ts);C?(C.owner=this.context.connection.connectionId,(I=this.onPlayerSpawned)==null||I.invoke(s)):(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!"),aA.destroySynced(s))}else this._localInstance=void 0,console.warn("PlayerSync: failed instantiating asset!");return this._localInstance}destroyInstance(){var A;(A=this._localInstance)==null||A.then(e=>(es&&console.log("PlayerSync.destroyInstance",e),aA.destroySynced(e))),this._localInstance=void 0}watchTabVisible(){window.addEventListener("visibilitychange",A=>{if(document.visibilityState==="visible")for(let e=ts.all.length-1;e>=0;e--){const i=ts.all[e];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}}qw([y()],VE.prototype,"autoSync",2),qw([y(Ct)],VE.prototype,"asset",2),qw([y(Eg)],VE.prototype,"onPlayerSpawned",2);var W_=(t=>(t.OwnerChanged="ownerChanged",t))(W_||{}),dd;const qg=(dd=class extends JA{constructor(){super(...arguments),r(this,"onOwnerChangeEvent",new Eg),r(this,"onFirstOwnerChangeEvent",new Eg),r(this,"hasOwner",!1),r(this,"owner"),r(this,"dontDestroy",!1),r(this,"onUserLeftRoom",t=>{if(t.userId===this.owner){es&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}})}static get all(){return qg._all}static get local(){return qg._local}static getFor(t){if(t instanceof wA)return aA.getComponentInParent(t,qg);if(t instanceof JA)return aA.getComponentInParent(t.gameObject,qg)}static isLocalPlayer(t){const A=qg.getFor(t);return A?.isLocalPlayer??!1}static addEventListener(t,A){return this._callbacks[t]||(this._callbacks[t]=[]),this._callbacks[t].push(A),A}static removeEventListener(t,A){if(!this._callbacks[t])return;const e=this._callbacks[t].indexOf(A);e>=0&&this._callbacks[t].splice(e,1)}static dispatchEvent(t,A){if(this._callbacks[t])for(const e of this._callbacks[t])e(A)}get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(t,A){var e,i;es&&console.log("PlayerSync.onOwnerChange",this,"newOwner",t,"oldOwner",A);const g=qg._local.indexOf(this);g>=0&&qg._local.splice(g,1);const I={playerState:this,oldValue:A,newValue:t};if(this.hasOwner||(this.hasOwner=!0,(e=this.onFirstOwnerChangeEvent)==null||e.invoke(I)),(i=this.onOwnerChangeEvent)==null||i.invoke(I),this.owner===this.context.connection.connectionId){qg._local.push(this);const s=new CustomEvent("local-owner-changed",{detail:I});this.dispatchEvent(s)}const o=new CustomEvent("owner-changed",{detail:I});this.dispatchEvent(o),qg.dispatchEvent("ownerChanged",o)}awake(){qg.all.push(this),es&&console.log("Registered new PlayerState",this.guid,qg.all.length-1,qg.all),this.context.connection.beginListen(ht.UserLeftRoom,this.onUserLeftRoom)}async start(){es&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await Jo(300),this.context.connection.userIsInRoom(this.owner)==!1&&(es&&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||(es&&console.warn("PlayerState.start \u2192 owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?es&&console.warn("PlayerState.start \u2192 owner is still undefined but dontDestroy is set to true",this.name):(es&&console.warn(`PlayerState.start \u2192 owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):console.log("PlayerState.start \u2192 owner is assigned",this.owner)},2e3))}doDestroy(){es&&console.log("PlayerSync.doDestroy \u2192 syncDestroy",this.name),jy(this.gameObject,this.context.connection)}onDestroy(){if(this.context.connection.stopListen(ht.UserLeftRoom,this.onUserLeftRoom),qg.all.splice(qg.all.indexOf(this),1),this.isLocalPlayer){const t=qg._local.indexOf(this);t>=0&&qg._local.splice(t,1)}}},r(dd,"_all",[]),r(dd,"_local",[]),r(dd,"_callbacks",{}),dd);let ts=qg;qw([OU(ts.prototype.onOwnerChange)],ts.prototype,"owner",2);const IoA=iA("debugavatar"),EC=class extends JA{constructor(){super(...arguments),r(this,"connectionId"),r(this,"avatar")}static getAvatar(t){return t>=0&&t<EC.instances.length?EC.instances[t]:null}static onAvatarMarkerCreated(t){return EC._onNewAvatarMarkerAdded.push(t),t}static onAvatarMarkerDestroyed(t){return EC._onAvatarMarkerDestroyed.push(t),t}awake(){EC.instances.push(this),IoA&&console.log(this);for(const t of EC._onNewAvatarMarkerAdded)t({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){EC.instances.splice(EC.instances.indexOf(this),1);for(const t of EC._onAvatarMarkerDestroyed)t({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}};let Lg=EC;r(Lg,"instances",[]),r(Lg,"_onNewAvatarMarkerAdded",[]),r(Lg,"_onAvatarMarkerDestroyed",[]);var ooA=Object.defineProperty,soA=Object.getOwnPropertyDescriptor,CoA=(t,A,e,i)=>{for(var g=i>1?void 0:i?soA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&ooA(A,e,g),g};const ZE=iA("debugxrflags"),V_=iA("disablexrflags");V_&&console.warn("XRFlags are disabled");var hC=(t=>(t[t.Never=0]="Never",t[t.Browser=1]="Browser",t[t.AR=2]="AR",t[t.VR=4]="VR",t[t.FirstPerson=8]="FirstPerson",t[t.ThirdPerson=16]="ThirdPerson",t[t.All=4294967295]="All",t))(hC||{});const Z_=class{constructor(){r(this,"Mask",17)}Has(t){return(this.Mask&t)!==0}Set(t){ZE&&console.warn("Set XR flag state to",t),this.Mask=t,Eo.Apply()}Enable(t){this.Mask|=t,Eo.Apply()}Disable(t){this.Mask&=~t,Eo.Apply()}Toggle(t){this.Mask^=t,Eo.Apply()}EnableAll(){this.Mask=-1,Eo.Apply()}DisableAll(){this.Mask=0,Eo.Apply()}};let MI=Z_;r(MI,"Global",new Z_);var ud;const Ra=(ud=class extends JA{constructor(){super(...arguments),r(this,"visibleIn")}static Apply(){for(const t of this.registry)t.UpdateVisible(MI.Global)}awake(){Ra.registry.push(this)}onEnable(){Ra.firstApply?this.UpdateVisible(MI.Global):(Ra.firstApply=!0,Ra.Apply())}onDestroy(){const t=Ra.registry.indexOf(this);t>=0&&Ra.registry.splice(t,1)}get isOn(){return this.gameObject.visible}UpdateVisible(t=null){if(V_)return;let A;const e=t;if(e&&typeof e=="number"&&(console.assert(typeof e=="number","XRFlag.UpdateVisible: state must be a number",e),ZE&&console.log(e),Ra.buffer.Mask=e,t=Ra.buffer),t instanceof MI?(ZE&&console.warn(this.name,"use passed in mask",t.Mask,this.visibleIn),A=t.Has(this.visibleIn)):(ZE&&console.log(this.name,"use global mask"),MI.Global.Has(this.visibleIn)),A!==void 0)if(A)ZE&&console.log(this.name,"is visible",this.gameObject.uuid),aA.setActive(this.gameObject,!0);else{if(ZE&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},r(ud,"registry",[]),r(ud,"firstApply"),r(ud,"buffer",new MI),ud);let Eo=Ra;CoA([y()],Eo.prototype,"visibleIn",2);var aoA=Object.defineProperty,noA=Object.getOwnPropertyDescriptor,PU=(t,A,e,i)=>{for(var g=i>1?void 0:i?noA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&aoA(A,e,g),g};const pd=iA("debugwebxr"),z_=new FA().setFromAxisAngle(new w(0,1,0),Math.PI);class RB extends JA{constructor(){super(...arguments),r(this,"head"),r(this,"leftHand"),r(this,"rightHand"),r(this,"_syncTransforms")}async onEnterXR(A){if(!this.activeAndEnabled)return;pd&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const e=ts.getFor(this);if(e!=null&&e.owner){const i=this.gameObject.addNewComponent(Lg);i.avatar=this.gameObject,i.connectionId=e.owner}else this.context.connection.isConnected?console.error("No player state found for avatar",this):e&&!this.context.connection.isConnected&&(e.dontDestroy=!0)}onLeaveXR(A){const e=this.gameObject.getComponent(Lg);e&&e.destroy()}onUpdateXR(A){var e,i;if(!this.activeAndEnabled)return;const g=ts.isLocalPlayer(this);if(!g)return;const I=A.xr;if(I.rig&&I.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),I.rig.gameObject.add(this.gameObject)),this._syncTransforms&&g)for(const a of this._syncTransforms)a.fastMode=!0,a.isOwned()||a.requestOwnership();if(this.head&&this.context.mainCamera){const a=this.head.asset;if(a.position.copy(this.context.mainCamera.position),a.quaternion.copy(this.context.mainCamera.quaternion),a.quaternion.x*=-1,this.context.time.frameCount%10===0){const n=aA.getComponentsInChildren(this.head.asset,Eo);for(const B of n)B.enabled=!1,B.gameObject.visible=!1}}const o=A.xr.leftController,s=(e=this.leftHand)==null?void 0:e.asset;o&&s&&(s.position.copy(o.gripPosition),s.quaternion.copy(o.gripQuaternion),s.quaternion.multiply(z_),s.visible=o.isTracking);const C=A.xr.rightController;if(C&&(i=this.rightHand)!=null&&i.asset){const a=this.rightHand.asset;a.position.copy(C.gripPosition),a.quaternion.copy(C.gripQuaternion),a.quaternion.multiply(z_),a.visible=C.isTracking}}onBeforeRender(){this.context.time.frame%10===0&&this.updateRemoteAvatarVisibility()}updateRemoteAvatarVisibility(){var A,e,i;if(this.context.connection.isConnected){const g=ts.getFor(this);if(g&&g.isLocalPlayer==!1){const I=de.getXRSync(this.context);if(I&&I.hasState(g.owner)){this.tryFindAvatarObjectsIfMissing();const o=(A=this.leftHand)==null?void 0:A.asset;o&&(o.visible=I?.isTracking(g.owner,"left")??!1);const s=(e=this.rightHand)==null?void 0:e.asset;s&&(s.visible=I?.isTracking(g.owner,"right")??!1)}if((i=this.head)!=null&&i.asset){const o=aA.getComponentsInChildren(this.head.asset,Eo);for(const s of o)s.enabled=!1,s.gameObject.visible=!0}}}}tryFindAvatarObjectsIfMissing(){if(!this.head||!this.leftHand||!this.rightHand){const A={head:this.head,leftHand:this.leftHand,rightHand:this.rightHand};UH.tryFindAvatarObjects(this.gameObject,this.sourceId||"",A),A.head&&(this.head=A.head),A.leftHand&&(this.leftHand=A.leftHand),A.rightHand&&(this.rightHand=A.rightHand)}}async prepareAvatar(){if(this.tryFindAvatarObjectsIfMissing(),this.head)this.head instanceof wA&&(this.head=new Ct("",this.sourceId,this.head));else{const A=new wA;A.name="Head";const e=DE.createPrimitive(EB.Cube);A.add(e),this.gameObject.add(A),this.head=new Ct("",this.sourceId,A),pd&&console.log("Create head",A)}if(this.rightHand)this.rightHand instanceof wA&&(this.rightHand=new Ct("",this.sourceId,this.rightHand));else{const A=new wA;A.name="Right Hand",this.gameObject.add(A),this.rightHand=new Ct("",this.sourceId,A),pd&&console.log("Create right hand",A)}if(this.leftHand)this.leftHand instanceof wA&&(this.leftHand=new Ct("",this.sourceId,this.leftHand));else{const A=new wA;A.name="Left Hand",this.gameObject.add(A),this.leftHand=new Ct("",this.sourceId,A),pd&&console.log("Create left hand",A)}await this.loadAvatarObjects(this.head,this.leftHand,this.rightHand),ts.isLocalPlayer(this.gameObject)&&(this._syncTransforms=aA.getComponentsInChildren(this.gameObject,Hn))}async loadAvatarObjects(A,e,i){const g=A.loadAssetAsync(),I=e.loadAssetAsync(),o=i.loadAssetAsync(),s=new Array;g&&s.push(g),I&&s.push(I),o&&s.push(o);const C=await Yc(s);pd&&console.log("Avatar loaded results:",C)}}PU([y(Ct)],RB.prototype,"head",2),PU([y(Ct)],RB.prototype,"leftHand",2),PU([y(Ct)],RB.prototype,"rightHand",2);class cC{static Add(A,e,i=null){if(e){for(const g of this.Pois)if(g.obj===e)return;this.Pois.push({obj:e,avatar:i}),this.LastChangeTime=A.time.time}}static Remove(A,e){var i;if(e){for(const g of this.Pois)if(g.obj===e){this.Pois.splice(this.Pois.indexOf(g),1),this.LastChangeTime=A?.time.time??((i=ve.Current)==null?void 0:i.time.time);return}}}}r(cC,"Pois",[]),r(cC,"LastChangeTime",0);class roA{constructor(){r(this,"guid"),r(this,"position",new w)}}class Dd extends JA{constructor(){super(...arguments),r(this,"target",null),r(this,"avatar",null),r(this,"_model",null),r(this,"_targetModel",new roA),r(this,"_currentTargetObject",null),r(this,"_lastUpdateTime",0),r(this,"_lookDuration",0),r(this,"_lastPoiChangedTime",0)}set controlledTarget(A){this.target=A;const e=z.get("MoveRandom");if(e&&this.target){const i=aA.getComponent(this.target,e);i&&i.destroy()}}awake(){if(this.avatar=aA.getComponentInParent(this.gameObject,Lg),this.avatar){const A=aA.getComponentInParent(this.gameObject,Lg);this._model=new pM(this.context.connection,this.guid),A!=null&&A.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",A=>{var e;this.target&&A&&A.guid===((e=this.avatar)==null?void 0:e.guid)&&CI(this.target,A.position)})}update(){var A;if((!this.context.connection.isConnected||(A=this._model)!=null&&A.hasOwnership)&&(cC.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=cC.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){const e=Ne(this._currentTargetObject);CI(this.target,e),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(e))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;const A=cC.Pois;if(A.length>0){const e=A[Math.floor(Math.random()*A.length)];if(e&&e.obj){if(e.avatar&&e.avatar===this.avatar)return;this._currentTargetObject=e.obj}}}}}const zE=iA("debugnetworkingstreams");var lC=(t=>(t.Connected="peer-user-connected",t.StreamReceived="receive-stream",t.StreamEnded="call-ended",t.Disconnected="peer-user-disconnected",t.UserJoined="user-joined",t))(lC||{});class X_{constructor(A,e){r(this,"type","call-ended"),r(this,"userId"),r(this,"direction"),this.userId=A,this.direction=e}}class $_{constructor(A,e){r(this,"type","receive-stream"),r(this,"stream"),r(this,"target"),this.stream=A,this.target=e}}class BoA{constructor(A,e){r(this,"guid"),r(this,"peerId"),r(this,"dontSave",!0),this.guid=A.id,this.peerId=e}}var AO=(t=>(t.Incoming="incoming",t.Outgoing="outgoing",t))(AO||{});class QoA extends ng{constructor(A,e,i){super(),r(this,"userId"),r(this,"direction"),r(this,"call"),r(this,"_stream",null),r(this,"_isDisposed",!1),this.userId=A,this.call=e,this.direction=i,this._stream=null,e.on("stream",g=>{if(zE&&console.log("Receive video",g.getAudioTracks(),g.getVideoTracks()),this._stream=g,i==="incoming"){const I=new $_(g,this);this.dispatchEvent(I)}}),e.on("close",()=>{this.dispatchEvent(new X_(A,i))})}get stream(){return this._stream}close(){this._isDisposed||(this._isDisposed=!0,this.call.close(),Ua(this._stream))}get isOpen(){var A;return((A=this.call.peerConnection)==null?void 0:A.connectionState)==="connected"}get isOpening(){var A;return((A=this.call.peerConnection)==null?void 0:A.connectionState)==="connecting"}get isClosed(){return!this.isOpen}}const yd=class extends ng{constructor(t,A){super(),r(this,"id"),r(this,"context"),r(this,"_peer"),r(this,"_incomingCalls",[]),r(this,"_outgoingCalls",[]),r(this,"_enabled",!1),r(this,"_enabledPeer",!1),r(this,"onConnectRoomFn",this.onConnectRoom.bind(this)),r(this,"onPeerConnectFn",this.onPeerConnect.bind(this)),r(this,"onPeerReceiveCallFn",this.onPeerReceivingCall.bind(this)),this.context=t,this.id=A,this.setupPeer(),navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia}static getOrCreate(t,A){if(yd.instances.has(A))return yd.instances.get(A);const e=new yd(t,A);return yd.instances.set(A,e),e}getMyPeerId(){if(this.context.connection.connectionId)return this.getPeerIdFromUserId(this.context.connection.connectionId)}getPeerIdFromUserId(t){return this.id+"-"+t}getUserIdFromPeerId(t){return t.substring(this.id.length+1)}makeCall(t,A){var e;const i={metadata:{userId:this.context.connection.connectionId}},g=(e=this._peer)==null?void 0:e.call(t,A,i);if(g)return this.registerCall(g,"outgoing")}get peer(){return this._peer}enable(){this._enabled||(this._enabled=!0,this.context.connection.beginListen(ht.JoinedRoom,this.onConnectRoomFn),this.subscribePeerEvents())}disable(){this._enabled&&(this._enabled=!1,this.context.connection.stopListen(ht.JoinedRoom,this.onConnectRoomFn),this.unsubscribePeerEvents())}onConnectRoom(){this.setupPeer()}setupPeer(){if(this.context.connection.connectionId&&!this._enabledPeer){if(this._enabledPeer=!0,!this._peer){const t=this.getMyPeerId();t?this._peer=GY(t):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(t){zE&&console.log("Peer connected as",t),this.context.connection.send("peer-user-connected",new BoA(this,t))}onPeerReceivingCall(t){t.answer(),this.registerCall(t,"incoming")}registerCall(t,A){const e=t.metadata;(!e||!e.userId)&&console.error("Missing call metadata",t);const i=e.userId;A==="incoming"&&zE?console.log("Receive call from",t.metadata):zE&&console.log("Make call to",t.metadata);const g=A==="incoming"?this._incomingCalls:this._outgoingCalls,I=new QoA(i,t,A);return g.push(I),t.on("error",o=>{console.error("Call error",o)}),t.on("close",()=>{zE&&console.log("Call ended",t.metadata),t.close();const o=g.indexOf(I);o!==-1&&g.splice(o,1)}),I.addEventListener("call-ended",o=>{this.dispatchEvent(o)}),A==="incoming"&&(I.addEventListener("receive-stream",o=>{this.dispatchEvent(o)}),t.on("stream",()=>{let o=0;const s=setInterval(()=>{const C=o===0;!I.isOpen&&C&&(o+=1,clearInterval(s),I.close())},2e3)})),I}};let Lw=yd;r(Lw,"instances",new Map);class vu extends ng{constructor(A,e){super(),r(this,"context"),r(this,"peer"),r(this,"_sendingStreams",new Map),r(this,"debug",!1),r(this,"onJoinedRoom",i=>{this.debug&&console.log(`${i.userId} joined room and I'm currently sending ${this._sendingStreams.size} streams`),this._sendingStreams.size>0&&this.updateSendingCalls()}),r(this,"onReceiveStream",i=>{this.debug&&console.log("RECEIVE STREAM",i),this.dispatchEvent({type:"receive-stream",target:this,stream:i.stream,userId:i.userId})}),r(this,"onCallEnded",i=>{this.dispatchEvent(i)}),r(this,"onUserConnected",i=>{if(this.peer.id===i.guid){this.debug&&console.log("USER CONNECTED",i.guid,i);const g=this._sendingStreams.keys().next().value;this.peer.makeCall(i.peerId,g)}}),r(this,"onUserLeft",i=>{this.stopCallsToUsersThatAreNotInTheRoomAnymore()}),this.context=A,this.peer=e,zE&&(this.debug=!0)}static create(A){const e=Lw.getOrCreate(A.context,A.context.connection.connectionId);return new vu(A.context,e)}startSendingStream(A){this._sendingStreams.has(A)?console.warn("Received start sending stream with stream that is already being sent"):(this._sendingStreams.set(A,[]),this.updateSendingCalls())}stopSendingStream(A){if(A){const e=this._sendingStreams.get(A);if(e){this.debug&&console.log("Closing calls",e);for(const i of e)i.close()}this._sendingStreams.delete(A),e&&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(ht.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ht.UserJoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ht.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(ht.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ht.UserJoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ht.UserLeftRoom,this.onUserLeft)}updateSendingCalls(){var A;let e=!1;const i=this.context.connection.connectionId;for(const g of this._sendingStreams.keys()){const I=this._sendingStreams.get(g)||[];for(const o of this.context.connection.usersInRoom()){if(o===i)continue;const s=I.find(C=>C.userId===o);if(!s||((A=s.stream)==null?void 0:A.active)===!1){this.debug&&console.log("Starting call to",o,i);const C=this.peer.makeCall(this.peer.getPeerIdFromUserId(o),g);C&&(e=!0,I.push(C))}}this._sendingStreams.set(g,I)}this.stopCallsToUsersThatAreNotInTheRoomAnymore(),e&&this.debug&&console.log("Currently sending",this._sendingStreams)}stopCallsToUsersThatAreNotInTheRoomAnymore(){for(const A of this._sendingStreams.keys()){const e=this._sendingStreams.get(A);if(e)for(let i=e.length-1;i>=0;i--){const g=e[i];this.context.connection.userIsInRoom(g.userId)||(g.close(),e.splice(i,1))}}}}function Ua(t){if(t&&t instanceof MediaStream)for(const A of t.getTracks())A.stop()}var EoA=Object.defineProperty,hoA=Object.getOwnPropertyDescriptor,eO=(t,A,e,i)=>{for(var g=i>1?void 0:i?hoA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&EoA(A,e,g),g};const coA="noVoip",loA=iA("debugvoip");class UB extends JA{constructor(){super(...arguments),r(this,"autoConnect",!1),r(this,"runInBackground",!0),r(this,"debug",!1),r(this,"_net"),r(this,"_outputStream",null),r(this,"onJoinedRoom",async()=>{await Jo(300),this.autoConnect&&!this.isSending&&this.connect()}),r(this,"_incomingStreams",new Map),r(this,"onReceiveStream",A=>{const e=A.target.userId,i=A.stream,g=this._incomingStreams.get(e);if(g)g.srcObject=i,g.setAttribute("autoplay","true");else{const I=new Audio;this._incomingStreams.set(e,I),I.setAttribute("autoplay","true"),I.srcObject=i}}),r(this,"onStreamEnded",A=>{const e=this._incomingStreams.get(A.userId);Ua(e?.srcObject),this._incomingStreams.delete(A.userId)}),r(this,"onEnabledChanged",()=>{for(const A of this._incomingStreams){const e=A[1];e.muted=!this.enabled}}),r(this,"onVisibilityChanged",()=>{if(this.runInBackground)return;const A=document.visibilityState!=="visible";this.setMuted(A);for(const e of this._incomingStreams){const i=e[1];i.muted=A}})}awake(){loA&&(this.debug=!0),this.debug&&window.addEventListener("keydown",async A=>{A.key==="v"&&(console.log("MUTE?",!this.isMuted),this.setMuted(!this.isMuted))})}onEnable(){this._net||(this._net=vu.create(this)),this._net.addEventListener(lC.StreamReceived,this.onReceiveStream),this._net.addEventListener(lC.StreamEnded,this.onStreamEnded),this._net.enable(),this.autoConnect&&(this.context.connection.isConnected?this.connect():this.context.connection.beginListen(ht.JoinedRoom,this.onJoinedRoom)),this.onEnabledChanged(),window.addEventListener("visibilitychange",this.onVisibilityChanged)}onDisable(){var A;this._net.stopSendingStream(this._outputStream),this._net.removeEventListener(lC.StreamReceived,this.onReceiveStream),this._net.removeEventListener(lC.StreamEnded,this.onStreamEnded),(A=this._net)==null||A.disable(),this.context.connection.stopListen(ht.JoinedRoom,this.onJoinedRoom),this.onEnabledChanged(),window.removeEventListener("visibilitychange",this.onVisibilityChanged)}get isSending(){return this._outputStream!=null&&this._outputStream.active}async connect(A){if(this.context.connection.isConnected){if(!await Ok())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),Ua(this._outputStream),this._outputStream=await this.getAudioStream(A),this._outputStream?(this._net.startSendingStream(this._outputStream),!0):(await Ok()?console.error("VOIP: Could not get audio stream - please make sure to connect an audio device and grant microphone permissions"):qq("Microphone permissions not granted: Please grant microphone permissions to use voice chat"),!1)}disconnect(){this._net.stopSendingStream(this._outputStream),Ua(this._outputStream),this._outputStream=null}setMuted(A){var e;const i=(e=this._outputStream)==null?void 0:e.getAudioTracks();if(i)for(const g of i)g.enabled=!A}get isMuted(){var A;if(this._outputStream===null)return!1;const e=(A=this._outputStream)==null?void 0:A.getAudioTracks();if(e){for(const i of e)if(!i.enabled)return!0}return!1}getFrequency(A){return this.unsupported_getfrequency||(this.unsupported_getfrequency=!0,Se()&&Ci("VOIP: getFrequency is currently not supported"),console.warn("VOIP: getFrequency is currently not supported")),null}async getAudioStream(A){return navigator.mediaDevices.getUserMedia?await navigator.mediaDevices.getUserMedia({audio:A??!0,video:!1}).catch(e=>(console.warn("VOIP failed getting audio stream",e),null)):(console.error("No getDisplayMedia support"),null)}}eO([y()],UB.prototype,"autoConnect",2),eO([y()],UB.prototype,"runInBackground",2);var doA=Object.defineProperty,uoA=Object.getOwnPropertyDescriptor,tO=(t,A,e,i)=>{for(var g=i>1?void 0:i?uoA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&doA(A,e,g),g};const poA=iA("debugmouth");class wd extends JA{constructor(){super(...arguments),r(this,"idle",[]),r(this,"talking",[]),r(this,"marker",null),r(this,"voip",null),r(this,"lastMouthChangeTime",0),r(this,"mouthChangeLength",0)}awake(){setTimeout(()=>{this.voip=aA.findObjectOfType(UB,this.context),this.marker||(this.marker=aA.getComponentInParent(this.gameObject,Lg))},3e3)}update(){var A;if(!this.voip||this.context.time.frameCount%10!==0)return;let e=((A=this.marker)==null?void 0:A.connectionId)??null;if(!e){poA&&(e=null);return}const i=this.voip.getFrequency(e)??0;this.updateLips(i)}updateLips(A){if(this.context.time.time-this.lastMouthChangeTime>this.mouthChangeLength){if(this.mouthChangeLength=.05+Math.random()*.1,this.talking&&this.talking.length>0&&A>30){this.lastMouthChangeTime=this.context.time.time;const e=Math.floor(Math.random()*this.talking.length);this.setMouthShapeActive(this.talking,e)}else if(this.idle.length>0&&this.context.time.time-this.lastMouthChangeTime>.5){this.lastMouthChangeTime=this.context.time.time;const e=Math.floor(Math.random()*this.idle.length);this.setMouthShapeActive(this.idle,e)}}}setMouthShapeActive(A,e){if(A){A!=this.idle?this.idle.map(i=>i.visible=!1):this.talking.map(i=>i.visible=!1);for(let i=0;i<A.length;i++){const g=A[i];g&&(g.visible=i===e)}}}}tO([y(wA)],wd.prototype,"idle",2),tO([y(wA)],wd.prototype,"talking",2);class jU extends JA{constructor(){super(...arguments),r(this,"voip",null),r(this,"marker",null),r(this,"_startPosition",null)}awake(){this.voip=aA.findObjectOfType(UB,this.context),this.marker=aA.getComponentInParent(this.gameObject,Lg)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!==0)return;const A=this.marker.connectionId,e=this.voip.getFrequency(A);if(e==null)return;this._startPosition||(this._startPosition=this.gameObject.position.clone());const i=e/100;this.gameObject.position.y=this._startPosition.y+i*.07}}var DoA=Object.defineProperty,yoA=Object.getOwnPropertyDescriptor,xw=(t,A,e,i)=>{for(var g=i>1?void 0:i?yoA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&DoA(A,e,g),g};class NB extends JA{constructor(){super(...arguments),r(this,"eyes",[]),r(this,"lastBlinkTime",0),r(this,"blinkLength",0),r(this,"eyesOpen",!0),r(this,"state",null)}awake(){this.state=aA.getComponentInParent(this.gameObject,Eo)}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 A of this.eyes)A&&(A.visible=this.eyesOpen)}}}xw([y(wA)],NB.prototype,"eyes",2),xw([y()],NB.prototype,"lastBlinkTime",2),xw([y()],NB.prototype,"blinkLength",2),xw([y()],NB.prototype,"eyesOpen",2);var woA=Object.defineProperty,SoA=Object.getOwnPropertyDescriptor,WU=(t,A,e,i)=>{for(var g=i>1?void 0:i?SoA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&woA(A,e,g),g},VU;const iO=(VU=class extends JA{constructor(){super(...arguments),r(this,"head",null),r(this,"eyes",null),r(this,"target",null),r(this,"brain",null),r(this,"vec",new w),r(this,"currentTargetPoint",new w)}awake(){this.brain||(this.brain=aA.getComponentInParent(this.gameObject,Dd)),this.brain||(console.log("No look at brain found, adding it now"),this.brain=aA.addNewComponent(this.gameObject,Dd)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}update(){const t=this.target;if(t&&this.head){const A=this.eyes;if(A){const e=Ne(t);this.currentTargetPoint.lerp(e,this.context.time.deltaTime/.1);const i=Ne(this.head),g=this.vec.copy(this.currentTargetPoint).sub(i).normalize();if(g.length()<.1)return;const I=iO.forward;if(I.set(0,0,1),I.applyQuaternion(Kt(this.head)),I.dot(g)>.45)for(let o=0;o<A.length;o++)A[o].lookAt(this.currentTargetPoint)}}}},r(VU,"forward",new w(0,0,1)),VU);let XE=iO;WU([y(wA)],XE.prototype,"head",2),WU([y(wA)],XE.prototype,"eyes",2),WU([y(wA)],XE.prototype,"target",2);const Sd=iA("debugavatar");class Yw{constructor(A,e,i,g){r(this,"root"),r(this,"head"),r(this,"leftHand"),r(this,"rigthHand");var I;this.root=A,this.head=e,this.leftHand=i,this.rigthHand=g,(I=this.root)==null||I.traverse(o=>o.layers.set(2))}get isValid(){return this.head!==null&&this.head!==void 0}}class ZU{constructor(){r(this,"avatarRegistryUrl",null)}async getOrCreateNewAvatarInstance(A,e){if(!e)return console.error("Can not create avatar: failed to provide id or root object"),null;let i=null;if(typeof e=="string"){if(i=await this.loadAvatar(A,e),!i){const I=new xs;i=aA.instantiate(eE(e,A.scene),I)}}else i=e;if(!i)return null;const g=this.findAvatar(i);return g.isValid?(Sd&&console.log("[Custom Avatar] valid config",e,Sd?g:""),g):(console.warn("[Custom Avatar] config isn't valid",e,Sd?g:""),null)}async loadAvatar(A,e){if(console.assert(e!=null&&typeof e=="string","Avatar id must not be null"),e.length<=0||!e)return null;if(Sd&&console.log("[Custom Avatar] "+e+", loading..."),e.endsWith(".glb")||(e+=".glb"),this.avatarRegistryUrl===null){const g=await fetch("./"+e);let I=null;if(g.ok){const s=await g.blob();s&&(I=await s.arrayBuffer())}if(!I&&(I=await bG(e,e,0,"no url here go away",!0),!I))return null;const o=await Bs().parseSync(A,I,null,0);return o?.scene??null}const i=new GE;return Ol(i,A),new Promise((g,I)=>{const o=this.avatarRegistryUrl+"/"+e;i.load(o,async s=>{await Bs().createBuiltinComponents(A,o,s,null,void 0),g(s.scene)},s=>{Sd&&console.log("[Custom Avatar] "+s.loaded/s.total*100+"% loaded of "+s.total/1024+"kB")},s=>{console.error("[Custom Avatar] Error when loading: "+s),g(null)})})}cacheModel(A,e){}findAvatar(A){const e=A;let i=e;i.children.length==1&&(i=A.children[0]);let g=this.findAvatarPart(i,["head"]);const I=this.findAvatarPart(i,["left","hand"]),o=this.findAvatarPart(i,["right","hand"]);if(!g){g=e;const s=new w;new Ft().setFromObject(g).getSize(s);const C=Math.max(s.x,s.y,s.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+C+" meters! Should be < 0.3m"),C>.3&&g.scale.multiplyScalar(1/C*.3)}return new Yw(e,g,I,o)}findAvatarPart(A,e){const i=A.name.toLowerCase();let g=!0;for(const I of e){if(!g)break;i.indexOf(I)===-1&&(g=!1)}if(g)return A;if(A.children)for(const I of A.children){const o=this.findAvatarPart(I,e);if(o)return o}return null}handleCustomAvatarErrors(A){if(!A.ok)throw Error(A.statusText);return A}}var foA=Object.defineProperty,moA=Object.getOwnPropertyDescriptor,zU=(t,A,e,i)=>{for(var g=i>1?void 0:i?moA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&foA(A,e,g),g};class $E extends JA{constructor(){super(...arguments),r(this,"length",1),r(this,"depthTest",!0),r(this,"isGizmo",!0),r(this,"_axes",null)}onEnable(){if(this.isGizmo&&!el)return;this._axes||(this._axes=new Fo(this.length)),this._axes.layers.disableAll(),this._axes.layers.set(this.layer),this.gameObject.add(this._axes);const A=this._axes.material;A&&A.depthTest!==void 0&&(A.depthTest=this.depthTest)}onDisable(){this._axes&&this.gameObject.remove(this._axes)}}zU([y()],$E.prototype,"length",2),zU([y()],$E.prototype,"depthTest",2),zU([y()],$E.prototype,"isGizmo",2);class XU extends JA{constructor(){super(...arguments),r(this,"from"),r(this,"to"),r(this,"hint"),r(this,"desiredDistance",1)}onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;const A=Ne(this.to).clone(),e=Ne(this.from).clone(),i=A.distanceTo(e),g=A.clone();g.sub(e);const I=e.clone();I.add(A),I.multiplyScalar(.5);const o=Ne(this.hint).clone();o.sub(I);const s=new w;s.crossVectors(o,g),s.crossVectors(g,s),s.normalize();const C=i*.5,a=Math.max(this.desiredDistance,C),n=Math.sqrt(a*a-C*C),B=s.clone();B.multiplyScalar(n),B.add(I),CI(this.gameObject,B);const Q=I.clone();Q.sub(s),this.gameObject.lookAt(Q)}}const koA=iA("debugusdz");class Tw{constructor(){r(this,"behaviours",[]),r(this,"behaviourComponents",[]),r(this,"behaviourComponentsCopy",[])}get extensionName(){return"Behaviour"}addBehavior(A){this.behaviours.push(A)}onBeforeBuildDocument(A){const e=[];return A.root.traverse(i=>{aA.foreachComponent(i,g=>{var I;const o=g;if(typeof o.createBehaviours=="function"||typeof o.beforeCreateDocument=="function"||typeof o.afterCreateDocument=="function"||typeof o.afterSerialize=="function"){this.behaviourComponents.push(o);const s=(I=o.beforeCreateDocument)==null?void 0:I.call(o,this,A);s instanceof Promise&&e.push(s)}},!1)}),Promise.all(e)}onExportObject(A,e,i){var g;for(const I of this.behaviourComponents)(g=I.createBehaviours)==null||g.call(I,this,e,i)}onAfterBuildDocument(A){for(const e of this.behaviourComponents)typeof e.afterCreateDocument=="function"&&e.afterCreateDocument(this,A);this.behaviourComponentsCopy=this.behaviourComponents.slice(),this.behaviourComponents.length=0}onAfterHierarchy(A,e){var i;if((i=this.behaviours)!=null&&i.length){e.beginBlock('def Scope "Behaviors"');for(const g of this.behaviours)g.writeTo(this,A.document,e);e.closeBlock()}}async onAfterSerialize(A){koA&&console.log("onAfterSerialize behaviours",this.behaviourComponentsCopy);for(const e of this.behaviourComponentsCopy)typeof e.afterSerialize=="function"&&(e.afterSerialize.constructor.name==="AsyncFunction"?await e.afterSerialize(this,A):e.afterSerialize(this,A));this.behaviours.length=0}}var GoA=Object.defineProperty,MoA=Object.getOwnPropertyDescriptor,$U=(t,A,e,i)=>{for(var g=i>1?void 0:i?MoA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&GoA(A,e,g),g};class FB extends rI{constructor(){super(...arguments),r(this,"threshold"),r(this,"intensity"),r(this,"scatter"),r(this,"selectiveBloom",!0)}get typeName(){return"Bloom"}init(){this.threshold.defaultValue=1,this.intensity.defaultValue=0,this.scatter.defaultValue=.2,this.selectiveBloom?(this.threshold.valueProcessor=A=>A,this.intensity.valueProcessor=A=>A,this.scatter.valueProcessor=A=>1*Math.PI*(1-A)):(this.threshold.valueProcessor=A=>A,this.intensity.valueProcessor=A=>A,this.scatter.valueProcessor=A=>100*(1-A))}onCreateEffect(){let A;if(this.selectiveBloom){const e=A=new ML(this.context.scene,this.context.mainCamera,{blendFunction:je.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,intensity:this.intensity.value});e.inverted=!0}else A=new mG;return this.intensity.onValueChanged=e=>{A.intensity=e},this.threshold.onValueChanged=e=>{A.luminanceMaterial.threshold=e},this.scatter.onValueChanged=e=>{A.luminancePass.enabled=!0,A.luminanceMaterial.smoothing=e},A}}$U([y(Ke)],FB.prototype,"threshold",2),$U([y(Ke)],FB.prototype,"intensity",2),$U([y(Ke)],FB.prototype,"scatter",2),As("Bloom",FB);var RoA=Object.defineProperty,UoA=Object.getOwnPropertyDescriptor,zI=(t,A,e,i)=>{for(var g=i>1?void 0:i?UoA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&RoA(A,e,g),g};class is extends JA{constructor(){super(...arguments),r(this,"attachedRigidbody",null),r(this,"isTrigger",!1),r(this,"sharedMaterial"),r(this,"membership",[0]),r(this,"filter"),r(this,"updateProperties",()=>{var A;(A=this.context.physics.engine)==null||A.updateProperties(this)})}get isCollider(){return!0}awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Pt))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Pt))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Pt))}onDisable(){var A;(A=this.context.physics.engine)==null||A.removeBody(this)}get body(){var A;return(A=this.context.physics.engine)==null?void 0:A.getBody(this)}updatePhysicsMaterial(){var A;(A=this.context.physics.engine)==null||A.updatePhysicsMaterial(this)}}zI([y(Pt)],is.prototype,"attachedRigidbody",2),zI([y()],is.prototype,"isTrigger",2),zI([y()],is.prototype,"sharedMaterial",2),zI([y()],is.prototype,"membership",2),zI([y()],is.prototype,"filter",2);class fd extends is{constructor(){super(...arguments),r(this,"radius",.5),r(this,"center",new w(0,0,0))}onEnable(){var A;super.onEnable(),(A=this.context.physics.engine)==null||A.addSphereCollider(this),MD(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),_k(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}}zI([Jg(),y()],fd.prototype,"radius",2),zI([y(w)],fd.prototype,"center",2);class md extends is{constructor(){super(...arguments),r(this,"size",new w(1,1,1)),r(this,"center",new w(0,0,0))}onEnable(){var A;super.onEnable(),(A=this.context.physics.engine)==null||A.addBoxCollider(this,this.size),MD(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),_k(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}}zI([Jg(),y(w)],md.prototype,"size",2),zI([y(w)],md.prototype,"center",2);class Ah extends is{constructor(){super(...arguments),r(this,"sharedMesh"),r(this,"convex",!1)}onEnable(){var A,e,i,g,I;if(super.onEnable(),(A=this.sharedMesh)!=null&&A.isMesh||this.gameObject instanceof DA&&(this.sharedMesh=this.gameObject),(e=this.sharedMesh)!=null&&e.isMesh)(i=this.context.physics.engine)==null||i.addMeshCollider(this,this.sharedMesh,this.convex,ai(this.gameObject));else{const o=this.sharedMesh;if(o!=null&&o.isGroup){console.warn(`MeshCollider mesh is a group "${((g=this.sharedMesh)==null?void 0:g.name)||this.gameObject.name}", adding all children as colliders. This is currently not fully supported (colliders can not be removed from world again)`,this);for(const s in o.children){const C=o.children[s];C.isMesh&&((I=this.context.physics.engine)==null||I.addMeshCollider(this,C,this.convex,ai(this.gameObject)))}}}}}zI([y()],Ah.prototype,"sharedMesh",2),zI([y()],Ah.prototype,"convex",2);class Wn extends is{constructor(){super(...arguments),r(this,"center",new w(0,0,0)),r(this,"radius",.5),r(this,"height",2)}onEnable(){var A;super.onEnable(),(A=this.context.physics.engine)==null||A.addCapsuleCollider(this,this.height,this.radius)}}zI([y(w)],Wn.prototype,"center",2),zI([y()],Wn.prototype,"radius",2),zI([y()],Wn.prototype,"height",2);var NoA=Object.defineProperty,FoA=Object.getOwnPropertyDescriptor,AN=(t,A,e,i)=>{for(var g=i>1?void 0:i?FoA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&NoA(A,e,g),g};class KB extends JA{constructor(){super(...arguments),r(this,"objectBounds",!1),r(this,"color"),r(this,"isGizmo",!0),r(this,"_gizmoObject",null),r(this,"_boxHelper",null)}onEnable(){this.isGizmo&&!el||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new vk(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=SR(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),Pi.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(var A;this._boxHelper;)(A=this._boxHelper)==null||A.update(),yield}}AN([y()],KB.prototype,"objectBounds",2),AN([y(mA)],KB.prototype,"color",2),AN([y()],KB.prototype,"isGizmo",2);class KoA extends EH{constructor(A,e={}){super(A),A._simpleState__activeStates=[],A._simpleState__normalStyles={},A._simpleState__states=e,A._simpleState__statesProperties={};for(const i in e)for(const g in e[i])A._simpleState__statesProperties[g]||(A._simpleState__statesProperties[g]=[]),A._simpleState__statesProperties[g].push(i);for(const i of A._components)A._simpleState__statesProperties[i.id]&&(A._simpleState__normalStyles[i.id]=i.inline?i.inline:i._value);A.__overridedSet=A.set,A.set=this.storeSet.bind(A),A.renderStates=this.renderStates.bind(A),A.setupState=this.setupState.bind(A),A.setState=this.setState.bind(A),A.activatePseudoState=this.activatePseudoState.bind(A),A.deactivatePseudoState=this.deactivatePseudoState.bind(A),A.togglePseudoState=this.togglePseudoState.bind(A)}act(){}attach(){}detach(){}setupState(A,e){this._simpleState__states[A]=e;const i=[];for(const g in e)this._simpleState__statesProperties[g]||(this._simpleState__statesProperties[g]=[],i.push(g)),this._simpleState__statesProperties[g].push(A);for(const g of this._components)i.indexOf(g.id)>-1&&(this._simpleState__normalStyles[g.id]=g.inline?g.inline:g._value)}renderStates(){let A={...this._simpleState__normalStyles};for(const e in this._simpleState__states)this._simpleState__activeStates.indexOf(e)>-1&&(A={...A,...this._simpleState__states[e]});this.set(A,!1)}storeSet(A,e=!0){if(e)for(const i in A)this._simpleState__statesProperties[i]&&(this._simpleState__normalStyles[i]=A[i]);this.__overridedSet(A)}activatePseudoState(A){this._simpleState__activeStates.indexOf(A)===-1&&(this._simpleState__activeStates.push(A),this.renderStates())}deactivatePseudoState(A){const e=this._simpleState__activeStates.indexOf(A);e>-1&&(this._simpleState__activeStates.splice(e,1),this.renderStates())}togglePseudoState(A){const e=this._simpleState__activeStates.indexOf(A);e>-1?this._simpleState__activeStates.splice(e,1):this._simpleState__activeStates.push(A),this.renderStates()}setState(A){Array.isArray(A)?this._simpleState__activeStates=A:this._simpleState__activeStates=[A],this.renderStates()}}var JoA=Object.defineProperty,voA=Object.getOwnPropertyDescriptor,gO=(t,A,e,i)=>{for(var g=i>1?void 0:i?voA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&JoA(A,e,g),g};class eh extends JA{constructor(){super(...arguments),r(this,"effectColor"),r(this,"effectDistance")}}gO([y(Mt)],eh.prototype,"effectColor",2),gO([y(tA)],eh.prototype,"effectDistance",2);var boA=Object.defineProperty,qoA=Object.getOwnPropertyDescriptor,kd=(t,A,e,i)=>{for(var g=i>1?void 0:i?qoA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&boA(A,e,g),g};const eN=iA("debugui"),tN=iA("debuguilayout");class iN{constructor(){r(this,"width"),r(this,"height")}}class gN{constructor(){r(this,"x"),r(this,"y"),r(this,"width"),r(this,"height")}}const Ks=new w,Gd=new NA,Hw=new FA,IO=class extends Ys{constructor(){super(...arguments),r(this,"_anchoredPosition"),r(this,"sizeDelta",new tA(100,100)),r(this,"pivot",new tA(.5,.5)),r(this,"anchorMin",new tA(0,0)),r(this,"anchorMax",new tA(1,1)),r(this,"minWidth"),r(this,"minHeight"),r(this,"lastMatrix"),r(this,"rectBlock"),r(this,"_transformNeedsUpdate",!1),r(this,"_initialPosition"),r(this,"_parentRectTransform"),r(this,"_lastUpdateFrame",-1),r(this,"_lastAnchoring"),r(this,"_createdBlocks",[]),r(this,"_createdTextBlocks",[])}get parent(){return this._parentRectTransform}get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new tA),this._anchoredPosition}set anchoredPosition(t){this._anchoredPosition=t}get width(){let t=this.sizeDelta.x;if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const A=this._parentRectTransform.width,e=this.anchorMax.x-this.anchorMin.x;t=A*e,t+=this.sizeDelta.x}return this.minWidth!==void 0&&t<this.minWidth?this.minWidth:t}get height(){let t=this.sizeDelta.y;if(this.anchorMin.y!==this.anchorMax.y&&this._parentRectTransform){const A=this._parentRectTransform.height,e=this.anchorMax.y-this.anchorMin.y;t=A*e,t+=this.sizeDelta.y}return this.minHeight!==void 0&&t<this.minHeight?this.minHeight:t}awake(){super.awake(),this._anchoredPosition||(this._anchoredPosition=new tA),this.lastMatrix=new NA,this.rectBlock=new wA,this.rectBlock.name=this.name,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,_E(this,"_anchoredPosition",()=>{this.markDirty()}),_E(this,"sizeDelta",()=>{this.markDirty()}),_E(this,"pivot",()=>{this.markDirty()}),_E(this,"anchorMin",()=>{this.markDirty()}),_E(this,"anchorMax",()=>{this.markDirty()})}onEnable(){var t;super.onEnable(),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,(t=this.Canvas)==null||t.registerTransform(this)}onDisable(){var t;super.onDisable(),this.removeShadowComponent(),(t=this.Canvas)==null||t.unregisterTransform(this)}onParentRectTransformChanged(t){this._transformNeedsUpdate||this.onApplyTransform(tN?`${t.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(tN&&console.warn("RectTransform markDirty()",this.name),this._transformNeedsUpdate=!0,this._lastUpdateFrame=-1)}updateTransform(){(this._transformNeedsUpdate||!this.lastMatrix.equals(this.gameObject.matrix))&&this.canUpdate()&&this.onApplyTransform(this._transformNeedsUpdate?"Marked dirty":"Matrix changed")}canUpdate(){return this._transformNeedsUpdate&&this.activeAndEnabled&&this._lastUpdateFrame!==this.context.time.frame}onApplyTransform(t){var A;if(this.context.time.frameCount===this._lastUpdateFrame)return;this._lastUpdateFrame=this.context.time.frameCount;const e=this.shadowComponent;if(!e)return;this.gameObject.parent?this._parentRectTransform=aA.getComponentInParent(this.gameObject.parent,IO):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,tN&&console.warn("RectTransform \u2192 ApplyTransform",this.name+" because "+t),this.isRoot()?this.Root.screenspace||(e.rotation.y=Math.PI):(e.matrix.identity(),e.matrixAutoUpdate=!1,Ks.set(0,0,0),this.applyPivot(Ks),e.matrix.setPosition(Ks.x,Ks.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(Hw.copy(this.gameObject.quaternion),Hw.x*=-1,Hw.z*=-1,Gd.makeRotationFromQuaternion(Hw),e.matrix.premultiply(Gd)),Ks.set(0,0,0),this.applyAnchoring(Ks),(A=this.Canvas)!=null&&A.screenspace?Ks.z+=.1:Ks.z+=.01,Gd.identity(),Gd.setPosition(Ks.x,Ks.y,Ks.z),e.matrix.premultiply(Gd),e.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const i=!0;for(const g of NR(this.gameObject,Ys,i,1)){if(g===this||!g.activeAndEnabled)continue;const I=g;I.onParentRectTransformChanged&&I.onParentRectTransformChanged(this)}}applyAnchoring(t){this._lastAnchoring||(this._lastAnchoring=new tA);const A=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=A.x,this.gameObject.position.y+=A.y,this._lastAnchoring.copy(this._anchoredPosition),t.x+=this._initialPosition.x-this.gameObject.position.x,t.y+=this._initialPosition.y-this.gameObject.position.y,t.z+=this._initialPosition.z-this.gameObject.position.z;const e=this._parentRectTransform;if(e){let i=0;const g=1-this.anchorMax.y-this.anchorMin.y;i-=e.height*.5*g,t.y+=i;let I=0;const o=1-this.anchorMax.x-this.anchorMin.x;I-=e.width*.5*o,t.x+=I}}applyPivot(t){if(this.pivot&&!this.isRoot()){const A=this.pivot.x-.5;t.x-=A*this.sizeDelta.x*this.gameObject.scale.x;const e=this.pivot.y-.5;t.y-=e*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){const t={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:0,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(t),t}ensureValidSize(t,A=1e-4){return t.width<=0&&(t.width=A),t.height<=0&&(t.height=1e-4),t}createNewBlock(t){t={...this.getBasicOptions(),...t},eN&&console.log(this.name,t);const A=new aR(t);return this._createdBlocks.push(A),A}createNewText(t){eN&&console.log(t),t={...this.getBasicOptions(),...t},eN&&console.log(this.name,t);const A=new rR(t);return this._createdTextBlocks.push(A),A}};let RI=IO;kd([y(tA)],RI.prototype,"anchoredPosition",1),kd([y(tA)],RI.prototype,"sizeDelta",2),kd([y(tA)],RI.prototype,"pivot",2),kd([y(tA)],RI.prototype,"anchorMin",2),kd([y(tA)],RI.prototype,"anchorMax",2);var LoA=Object.defineProperty,xoA=Object.getOwnPropertyDescriptor,oO=(t,A,e,i)=>{for(var g=i>1?void 0:i?xoA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&LoA(A,e,g),g};const _w={backgroundColor:new mA(1,1,1),backgroundOpacity:1,borderColor:new mA(1,1,1),borderOpacity:1};var IN;const Ow=(IN=class extends Ys{constructor(){super(...arguments),r(this,"_alphaFactor",1),r(this,"sRGBColor",new mA(1,0,1)),r(this,"raycastTarget",!0),r(this,"uiObject",null),r(this,"_color",null),r(this,"_rect",null),r(this,"_stateManager",null),r(this,"_currentlyCreatingPanel",!1)}get isGraphic(){return!0}get color(){return this._color||(this._color=new Mt(1,1,1,1)),this._color}set color(t){(!this._color||this._color.r!==t.r||this._color.g!==t.g||this._color.b!==t.b||this._color.alpha!==t.alpha)&&(this._color||(this._color=new Mt(1,1,1,1)),this._color.copy(t),this.onColorChanged())}setAlphaFactor(t){this._alphaFactor=t,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}onColorChanged(){this.uiObject&&(this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),_w.backgroundColor=this.sRGBColor,_w.backgroundOpacity=this._color.alpha*this._alphaFactor,this.applyEffects(_w,this._alphaFactor),this.uiObject.set(_w),this.markDirty())}get m_Color(){return this._color}get rectTransform(){if(this._rect||(this._rect=aA.getComponent(this.gameObject,RI)),!this._rect)throw new Error("Not Supported: Make sure to add a RectTransform component before adding a UI Graphic component.");return this._rect}onParentRectTransformChanged(){var t;(t=this.uiObject)==null||t.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(){super.__internalNewInstanceCreated(),this._rect=null,this.uiObject=null,this._color&&(this._color=this._color.clone())}setState(t){this.makePanel(),this.uiObject&&(this.uiObject.setState(t),this==null||this.markDirty())}setupState(t){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new KoA(this.uiObject)),this.uiObject.setupState(t.state,t.attributes))}setOptions(t){this.makePanel(),this.uiObject&&this.uiObject.set(t)}awake(){super.awake(),this.makePanel(),_E(this,"_color",()=>cIA(this,this.onColorChanged))}onEnable(){var t;super.onEnable(),this.uiObject&&((t=this.rectTransform.shadowComponent)==null||t.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;const t=.015,A={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:t};this.onBeforeCreate(A),this.applyEffects(A),this.onCreate(A),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated(),this.onColorChanged()}onBeforeCreate(t){}onCreate(t){this.uiObject=this.rectTransform.createNewBlock(t),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(t,A=1){var e;const i=(e=this.gameObject)==null?void 0:e.getComponent(eh);i&&(i.effectDistance&&(t.borderWidth=Math.max(Math.abs(i.effectDistance.x),Math.abs(i.effectDistance.y))),i.effectColor&&(t.borderColor=i.effectColor,t.borderOpacity=i.effectColor.alpha*A))}async setTexture(t){if(this.setOptions({backgroundOpacity:0}),t){if(Ow.textureCache.has(t))t=Ow.textureCache.get(t);else if(!t.isRenderTargetTexture){const A=t.clone();A.colorSpace=Nt,Ow.textureCache.set(t,A),t=A}this.setOptions({backgroundImage:t,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"})}else this.setOptions({backgroundImage:null,borderRadius:0,backgroundOpacity:this.color.alpha});this.markDirty()}onAfterAddedToScene(){super.onAfterAddedToScene(),this.shadowComponent&&(this.shadowComponent.offset=this.shadowComponent.position.z)}},r(IN,"textureCache",new Map),IN);let JB=Ow;oO([y(Mt)],JB.prototype,"color",1),oO([y()],JB.prototype,"raycastTarget",2);class Md extends JB{constructor(){super(...arguments),r(this,"_flippedObject",!1)}onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var YoA=Object.defineProperty,ToA=Object.getOwnPropertyDescriptor,Pw=(t,A,e,i)=>{for(var g=i>1?void 0:i?ToA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&YoA(A,e,g),g};let oN=class{constructor(){r(this,"texture",null),r(this,"rect")}};Pw([y(Ye)],oN.prototype,"texture",2);let th=class extends Md{constructor(){super(...arguments),r(this,"_sprite"),r(this,"pixelsPerUnitMultiplier",1)}set image(t){this.sprite||(this.sprite=new oN),this.sprite.texture=t,this.onAfterCreated()}get image(){return this.sprite?this.sprite.texture:null}get sprite(){return this._sprite}set sprite(t){this._sprite!==t&&(this._sprite=t,this.onAfterCreated())}isBuiltinSprite(){var t,A,e,i,g,I,o,s,C,a,n;switch((A=(t=this.sprite)==null?void 0:t.texture)==null?void 0:A.name){case"InputFieldBackground":case"UISprite":case"Background":case"Knob":return!0}return!((g=(i=(e=this.sprite)==null?void 0:e.texture)==null?void 0:i.name)!=null&&g.length)&&((s=(o=(I=this.sprite)==null?void 0:I.texture)==null?void 0:o.image)==null?void 0:s.width)===32&&((n=(a=(C=this.sprite)==null?void 0:C.texture)==null?void 0:a.image)==null?void 0:n.height)===32}onBeforeCreate(t){var A,e;super.onBeforeCreate(t),this.isBuiltinSprite()&&(t.borderRadius=5/this.pixelsPerUnitMultiplier,((e=(A=this.sprite)==null?void 0:A.texture)==null?void 0:e.name)==="Knob"&&(t.borderRadius=999))}onAfterCreated(){var t;this.__didAwake&&(super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture((t=this.sprite)==null?void 0:t.texture))}};Pw([y(oN)],th.prototype,"sprite",1),Pw([y()],th.prototype,"pixelsPerUnitMultiplier",2);class jw extends Md{constructor(){super(...arguments),r(this,"_mainTexture")}get mainTexture(){return this._mainTexture}set mainTexture(A){this._mainTexture!==A&&(this._mainTexture=A,this.onAfterCreated())}onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),this.setTexture(this.mainTexture))}}Pw([y(Ye)],jw.prototype,"mainTexture",1);var HoA=Object.defineProperty,_oA=Object.getOwnPropertyDescriptor,ho=(t,A,e,i)=>{for(var g=i>1?void 0:i?_oA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&HoA(A,e,g),g};const vB=iA("debugbutton");class bB{constructor(){r(this,"colorMultiplier"),r(this,"disabledColor"),r(this,"fadeDuration"),r(this,"highlightedColor"),r(this,"normalColor"),r(this,"pressedColor"),r(this,"selectedColor")}}ho([y()],bB.prototype,"colorMultiplier",2),ho([y(Mt)],bB.prototype,"disabledColor",2),ho([y()],bB.prototype,"fadeDuration",2),ho([y(Mt)],bB.prototype,"highlightedColor",2),ho([y(Mt)],bB.prototype,"normalColor",2),ho([y(Mt)],bB.prototype,"pressedColor",2),ho([y(Mt)],bB.prototype,"selectedColor",2);class Na extends JA{constructor(){super(...arguments),r(this,"onClick"),r(this,"_isHovered",0),r(this,"colors"),r(this,"transition"),r(this,"animationTriggers"),r(this,"animator"),r(this,"_interactable",!0),r(this,"_requestedAnimatorTrigger"),r(this,"_isInit",!1),r(this,"_image")}onPointerEnter(A){var e,i;this._isHovered+=1,vB&&console.warn("Button Enter",this._isHovered,(e=this.animationTriggers)==null?void 0:e.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.highlightedTrigger):this.transition===1&&this.colors&&((i=this._image)==null||i.setState("hovered")),this.context.input.setCursorPointer())}onPointerExit(){var A,e;this._isHovered-=1,vB&&console.log("Button Exit",this._isHovered,(A=this.animationTriggers)==null?void 0:A.highlightedTrigger,this.animator),this.interactable&&(this._isHovered>0||(this._isHovered=0,this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&((e=this._image)==null||e.setState("normal")),this.context.input.setCursorNormal()))}onPointerDown(A){var e,i;vB&&console.log("Button Down",(e=this.animationTriggers)==null?void 0:e.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&((i=this._image)==null||i.setState("pressed")))}onPointerUp(A){var e,i;vB&&console.warn("Button Up",(e=this.animationTriggers)==null?void 0:e.highlightedTrigger,this.animator,this._isHovered),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this._isHovered?this.animationTriggers.highlightedTrigger:this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&((i=this._image)==null||i.setState(this._isHovered?"hovered":"normal")))}onPointerClick(A){if(this.interactable&&!(A.button!==0&&A.event.pointerType===LG.Mouse)&&(vB&&(console.warn("Button Click",this.onClick),wi("CLICKED button "+this.name+" at "+this.context.time.frameCount)),this.onClick&&this.onClick.listenerCount>0&&(this.onClick.invoke(),A.use(),vB))){const e=this.gameObject.worldPosition;e.add(this.gameObject.worldUp.multiplyScalar(1+Math.random()*.5)),Fe.DrawLabel(e,"CLICK:"+Date.now(),.1,1+Math.random()*.5)}}set interactable(A){this._interactable=A,this._image&&(this._image.setInteractable(A),A?this._image.setState("normal"):this._image.setState("disabled"))}get interactable(){return this._interactable}set_interactable(A){this.interactable=A}awake(){super.awake(),vB&&console.log(this),this._isInit=!1,this.init()}start(){var A;(A=this._image)==null||A.setInteractable(this.interactable),this.gameObject.getComponentInParent(gd)||this.gameObject.addComponent(ww)}onEnable(){super.onEnable()}onDestroy(){this._isHovered&&this.context.input.setCursorNormal()}*setAnimatorTriggerAtEndOfFrame(A){var e;this._requestedAnimatorTrigger=A,yield,yield,this._requestedAnimatorTrigger==A&&((e=this.animator)==null||e.SetTrigger(A))}init(){this._isInit||(this._isInit=!0,this._image=aA.getComponent(this.gameObject,th),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(A){var e,i,g,I,o;A.setInteractable(this.interactable);const s=this.getFinalColor(A.color,(e=this.colors)==null?void 0:e.normalColor),C={state:"normal",attributes:{backgroundColor:s,backgroundOpacity:s.alpha}};A.setupState(C);const a=this.getFinalColor(A.color,(i=this.colors)==null?void 0:i.highlightedColor),n={state:"hovered",attributes:{backgroundColor:a,backgroundOpacity:a.alpha}};A.setupState(n);const B=this.getFinalColor(A.color,(g=this.colors)==null?void 0:g.pressedColor),Q={state:"pressed",attributes:{backgroundColor:B,backgroundOpacity:B.alpha}};A.setupState(Q);const E=this.getFinalColor(A.color,(I=this.colors)==null?void 0:I.selectedColor),h={state:"selected",attributes:{backgroundColor:E,backgroundOpacity:E.alpha}};A.setupState(h);const d=this.getFinalColor(A.color,(o=this.colors)==null?void 0:o.disabledColor),u={state:"disabled",attributes:{backgroundColor:d,backgroundOpacity:d.alpha}};A.setupState(u)}getFinalColor(A,e){return e?A.clone().multiply(e).convertLinearToSRGB():A.clone().convertLinearToSRGB()}}ho([y(Eg)],Na.prototype,"onClick",2),ho([y()],Na.prototype,"colors",2),ho([y()],Na.prototype,"transition",2),ho([y()],Na.prototype,"animationTriggers",2),ho([y(bg)],Na.prototype,"animator",2),ho([y()],Na.prototype,"interactable",1);var OoA=Object.defineProperty,PoA=Object.getOwnPropertyDescriptor,ji=(t,A,e,i)=>{for(var g=i>1?void 0:i?PoA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&OoA(A,e,g),g};const sO=iA("debuguilayout");class Vn{constructor(){r(this,"left",0),r(this,"right",0),r(this,"top",0),r(this,"bottom",0)}get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}ji([y()],Vn.prototype,"left",2),ji([y()],Vn.prototype,"right",2),ji([y()],Vn.prototype,"top",2),ji([y()],Vn.prototype,"bottom",2);class co extends JA{constructor(){super(...arguments),r(this,"_rectTransform",null),r(this,"_needsUpdate",!1),r(this,"childAlignment",0),r(this,"reverseArrangement",!1),r(this,"spacing",0),r(this,"padding"),r(this,"minWidth",0),r(this,"minHeight",0),r(this,"flexibleHeight",0),r(this,"flexibleWidth",0),r(this,"preferredHeight",0),r(this,"preferredWidth",0)}get rectTransform(){return this._rectTransform}onParentRectTransformChanged(A){this._needsUpdate=!0}get isDirty(){return this._needsUpdate}get isLayoutGroup(){return!0}updateLayout(){this._rectTransform&&(sO&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}start(){this._needsUpdate=!0}onEnable(){sO&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(RI);const A=this.gameObject.getComponentInParent(xg);A&&A.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const A=this.gameObject.getComponentInParent(xg);A&&A.unregisterLayoutGroup(this)}set m_Spacing(A){A!==this.spacing&&(this._needsUpdate=!0,this.spacing=A)}get m_Spacing(){return this.spacing}}ji([y()],co.prototype,"childAlignment",2),ji([y()],co.prototype,"reverseArrangement",2),ji([y()],co.prototype,"spacing",2),ji([y(Vn)],co.prototype,"padding",2),ji([y()],co.prototype,"minWidth",2),ji([y()],co.prototype,"minHeight",2),ji([y()],co.prototype,"flexibleHeight",2),ji([y()],co.prototype,"flexibleWidth",2),ji([y()],co.prototype,"preferredHeight",2),ji([y()],co.prototype,"preferredWidth",2);class Zn extends co{constructor(){super(...arguments),r(this,"childControlHeight",!0),r(this,"childControlWidth",!0),r(this,"childForceExpandHeight",!1),r(this,"childForceExpandWidth",!1),r(this,"childScaleHeight",!1),r(this,"childScaleWidth",!1)}onCalculateLayout(A){var e;const i=this.primaryAxis,g=A.width;let I=g;const o=A.height;let s=o;I-=this.padding.horizontal,s-=this.padding.vertical,i==="x"?this.padding.horizontal:this.padding.vertical;const C=i==="x",a=C?"y":"x",n=C?this.childControlWidth:this.childControlHeight,B=C?this.childControlHeight:this.childControlWidth,Q=C?this.childForceExpandWidth:this.childForceExpandHeight,E=C?this.childForceExpandHeight:this.childForceExpandWidth,h=C?s:I,d=C?g:o,u=.5*(C?this.childAlignment%3:Math.floor(this.childAlignment/3));let c=0;C?c+=this.padding.left:c+=this.padding.top;let l=0,p=0;for(let U=0;U<this.gameObject.children.length;U++){const M=this.gameObject.children[U],m=aA.getComponent(M,RI);m!=null&&m.activeAndEnabled&&(p+=1,C?l+=m.width:l+=m.height)}let D=0;const S=this.spacing*(p-1);if(Q||n){let U=0;C?U=I-=S:U=s-=S,p>0&&(D=U/p)}let k=0;k+=this.padding.left,k-=this.padding.right,u!==0&&(c=d-l,c*=u,c-=S*u,C?(c-=this.padding.right*u,c+=this.padding.left*(1-u),c<this.padding.left&&(c=this.padding.left)):(c-=this.padding.bottom*u,c+=this.padding.top*(1-u),c<this.padding.top&&(c=this.padding.top)));let f=1;for(let U=0;U<this.gameObject.children.length;U++){const M=this.gameObject.children[U],m=aA.getComponent(M,RI);if(m!=null&&m.activeAndEnabled){(e=m.pivot)==null||e.set(.5,.5),m.anchorMin.set(0,1),m.anchorMax.set(0,1);const x=g*.5+k*.5;m.anchoredPosition.x!==x&&(m.anchoredPosition.x=x);const L=o*-.5;m.anchoredPosition.y!==L&&(m.anchoredPosition.y=L),E&&B&&m.sizeDelta[a]!==h&&(m.sizeDelta[a]=h),Q&&n&&m.sizeDelta[i]!==D&&(m.sizeDelta[i]=D);const V=C?m.width:m.height,Y=V*.5;if(c+=Y,Q){const b=D*f-D*.5;b>c&&(c=b-D*.5+V+this.padding.left,c-=Y)}let P=c;i==="y"&&(P=-P),m.anchoredPosition[i]!==P&&(m.anchoredPosition[i]=P),c+=Y,c+=this.spacing,f+=1}}}}ji([y()],Zn.prototype,"childControlHeight",2),ji([y()],Zn.prototype,"childControlWidth",2),ji([y()],Zn.prototype,"childForceExpandHeight",2),ji([y()],Zn.prototype,"childForceExpandWidth",2),ji([y()],Zn.prototype,"childScaleHeight",2),ji([y()],Zn.prototype,"childScaleWidth",2);class sN extends Zn{get primaryAxis(){return"y"}}class CN extends Zn{get primaryAxis(){return"x"}}class aN extends co{onCalculateLayout(){}}var joA=Object.defineProperty,WoA=Object.getOwnPropertyDescriptor,dC=(t,A,e,i)=>{for(var g=i>1?void 0:i?WoA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&joA(A,e,g),g},CO=(t=>(t[t.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",t[t.ScreenSpaceCamera=1]="ScreenSpaceCamera",t[t.WorldSpace=2]="WorldSpace",t[t.Undefined=-1]="Undefined",t))(CO||{});const nN=iA("debuguilayout"),aO=class extends id{constructor(){super(...arguments),r(this,"_renderOnTop"),r(this,"_depthWrite",!1),r(this,"_doubleSided",!0),r(this,"_castShadows",!1),r(this,"_receiveShadows",!1),r(this,"_renderMode",-1),r(this,"_rootCanvas"),r(this,"_scaleFactor",1),r(this,"worldCamera"),r(this,"planeDistance",-1),r(this,"_boundRenderSettingsChanged",this.onRenderSettingsChanged.bind(this)),r(this,"previousParent",null),r(this,"_lastMatrixWorld",null),r(this,"_rectTransforms",[]),r(this,"_layoutGroups",new Map),r(this,"_receivers",[]),r(this,"onBeforeRenderRoutine",()=>{var t,A,e,i;if(this.previousParent=this.gameObject.parent,((t=this.context.xr)!=null&&t.isVR||(A=this.context.xr)!=null&&A.isPassThrough)&&this.screenspace){this.gameObject.visible=!1,this.gameObject.removeFromParent();return}this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),(e=this.shadowComponent)==null||e.updateMatrixWorld(!0),(i=this.shadowComponent)==null||i.updateWorldMatrix(!0,!0),this.invokeBeforeRenderEvents(),zo.ensureUpdateMeshUI(cH,this.context))}),r(this,"onAfterRenderRoutine",()=>{var t,A,e,i,g;if(((t=this.context.xr)!=null&&t.isVR||(A=this.context.xr)!=null&&A.isPassThrough)&&this.screenspace){(e=this.previousParent)==null||e.add(this.gameObject);return}if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){if(this.screenspace){const s=this.context.mainCamera;s?.add(this.gameObject)}else this.previousParent.add(this.gameObject);const I=this.context.renderer.autoClear,o=this.context.renderer.autoClearColor;this.context.renderer.autoClear=!1,this.context.renderer.autoClearColor=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),(i=this.shadowComponent)==null||i.updateMatrixWorld(!0),this.invokeBeforeRenderEvents(),zo.ensureUpdateMeshUI(cH,this.context,!0),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=I,this.context.renderer.autoClearColor=o,this.previousParent.add(this.gameObject)}(g=this._lastMatrixWorld)==null||g.copy(this.gameObject.matrixWorld)}),r(this,"_updateRenderSettingsRoutine"),r(this,"_activeRenderMode",-1),r(this,"_lastWidth",-1),r(this,"_lastHeight",-1)}get isCanvas(){return!0}get screenspace(){return this.renderMode!==2}set renderOnTop(t){t!==this._renderOnTop&&(this._renderOnTop=t,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop!==void 0?this._renderOnTop:!!(this.screenspace&&this._renderMode===0)}set depthWrite(t){this._depthWrite!==t&&(this._depthWrite=t,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}set doubleSided(t){this._doubleSided!==t&&(this._doubleSided=t,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}set castShadows(t){this._castShadows!==t&&(this._castShadows=t,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}set receiveShadows(t){this._receiveShadows!==t&&(this._receiveShadows=t,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}get renderMode(){return this._renderMode}set renderMode(t){this._renderMode!==t&&(this._renderMode=t,this.onRenderSettingsChanged())}set rootCanvas(t){this._rootCanvas instanceof aO||(this._rootCanvas=t)}get rootCanvas(){return this._rootCanvas}get scaleFactor(){return this._scaleFactor}set scaleFactor(t){this._scaleFactor=t}awake(){var t;this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,nN&&console.log("Canvas.Awake()",((t=this.previousParent)==null?void 0:t.name)+"/"+this.gameObject.name),super.awake()}start(){this.onUpdateRenderMode()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new NA,this.onUpdateRenderMode(),document.addEventListener("resize",this._boundRenderSettingsChanged),this.context.pre_render_callbacks.push(this.onBeforeRenderRoutine),this.context.post_render_callbacks.push(this.onAfterRenderRoutine)}onDisable(){super.onDisable(),document.removeEventListener("resize",this._boundRenderSettingsChanged);const t=this.context.pre_render_callbacks.indexOf(this.onBeforeRenderRoutine);t!==-1&&this.context.pre_render_callbacks.splice(t,1);const A=this.context.post_render_callbacks.indexOf(this.onAfterRenderRoutine);A!==-1&&this.context.post_render_callbacks.splice(A,1)}registerTransform(t){this._rectTransforms.push(t)}unregisterTransform(t){const A=this._rectTransforms.indexOf(t);A!==-1&&this._rectTransforms.splice(A,1)}registerLayoutGroup(t){const A=t.gameObject;this._layoutGroups.set(A,t)}unregisterLayoutGroup(t){const A=t.gameObject;this._layoutGroups.delete(A)}registerEventReceiver(t){this._receivers.push(t)}unregisterEventReceiver(t){const A=this._receivers.indexOf(t);A!==-1&&this._receivers.splice(A,1)}async onEnterXR(t){this.screenspace?(t.xr.isVR||t.xr.isPassThrough)&&(this.gameObject.visible=!1):(this.gameObject.visible=!1,await yq(1).then(()=>{this.gameObject.visible=!0}))}onLeaveXR(t){this.screenspace&&(t.xr.isVR||t.xr.isPassThrough)&&(this.gameObject.visible=!0)}invokeBeforeRenderEvents(){var t;for(const A of this._receivers)(t=A.onBeforeCanvasRender)==null||t.call(A,this)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new NA);const t=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);nN&&t&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);const A=!1;for(const e of this._rectTransforms){t&&e.markDirty();let i=this._layoutGroups.get(e.gameObject);e.isDirty&&!i&&(i=e.gameObject.getComponentInParent(co)),(e.isDirty||i!=null&&i.isDirty)&&(nN&&!A&&console.log("CANVAS UPDATE ### "+e.name+" ##################################### "+this.context.time.frame),i?.updateLayout(),e.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),Pi.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),fw(this.shadowComponent,this);for(const t of aA.getComponentsInChildren(this.gameObject,Ys))fw(t.shadowComponent,this)}}onUpdateRenderMode(t=!1){if(!t&&this._renderMode===this._activeRenderMode&&this._lastWidth===this.context.domWidth&&this._lastHeight===this.context.domHeight)return;this._activeRenderMode=this._renderMode;let A=this.context.mainCameraComponent,e=10;switch(A&&A.nearClipPlane>0&&A.farClipPlane>0&&(e=Ie.lerp(A.nearClipPlane,A.farClipPlane,.01)),this._renderMode===1&&(this.worldCamera&&(A=this.worldCamera),this.planeDistance>0&&(e=this.planeDistance)),this._renderMode){case 0:case 1:if(this._lastWidth=this.context.domWidth,this._lastHeight=this.context.domHeight,!A)return;const i=e+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-i,this.gameObject.quaternion.identity();const g=this.gameObject.getComponent(RI);let I=!1;g.sizeDelta.x!==this.context.domWidth&&(I=!0),g.sizeDelta.y!==this.context.domHeight&&(I=!0);const o=A.fieldOfView*Math.PI/180,s=2*Math.tan(o/2)*Math.abs(i);this.gameObject.scale.x=s/this.context.domHeight,this.gameObject.scale.y=s/this.context.domHeight,this.gameObject.scale.z=.01,I&&(g.sizeDelta.x=this.context.domWidth,g.sizeDelta.y=this.context.domHeight,g?.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};let xg=aO;dC([y()],xg.prototype,"renderOnTop",1),dC([y()],xg.prototype,"depthWrite",1),dC([y()],xg.prototype,"doubleSided",1),dC([y()],xg.prototype,"castShadows",1),dC([y()],xg.prototype,"receiveShadows",1),dC([y()],xg.prototype,"renderMode",1),dC([y(xg)],xg.prototype,"rootCanvas",1),dC([y()],xg.prototype,"scaleFactor",1),dC([y(Wt)],xg.prototype,"worldCamera",2),dC([y()],xg.prototype,"planeDistance",2);var VoA=Object.defineProperty,ZoA=Object.getOwnPropertyDescriptor,rN=(t,A,e,i)=>{for(var g=i>1?void 0:i?ZoA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&VoA(A,e,g),g};class zn extends JA{constructor(){super(...arguments),r(this,"_alpha",1),r(this,"interactable",!0),r(this,"blocksRaycasts",!0),r(this,"_isDirty",!1),r(this,"_buffer",[])}get alpha(){return this._alpha}set alpha(A){A!==this._alpha&&(this._alpha=A,this.markDirty())}get isCanvasGroup(){return!0}markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),Pi.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}applyChangesNow(){for(const A of aA.getComponentsInChildren(this.gameObject,Ys,this._buffer)){const e=A;e.setAlphaFactor&&e.setAlphaFactor(this._alpha)}}}rN([y()],zn.prototype,"alpha",1),rN([y()],zn.prototype,"interactable",2),rN([y()],zn.prototype,"blocksRaycasts",2);var zoA=Object.defineProperty,XoA=Object.getOwnPropertyDescriptor,ni=(t,A,e,i)=>{for(var g=i>1?void 0:i?XoA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&zoA(A,e,g),g};function Rd(t){t&&(t.getComponentInParent(gd)||(Se()&&console.warn("Create Raycaster on "+t.name+" because no raycaster was found in the hierarchy"),t.addNewComponent(ro)))}class qB extends JA{constructor(){super(...arguments),r(this,"object"),r(this,"target"),r(this,"duration",1),r(this,"relativeMotion",!1),r(this,"coroutine",null),r(this,"targetPos",new w),r(this,"targetRot",new FA),r(this,"targetScale",new w)}start(){Rd(this.gameObject)}onPointerClick(A){A.use(),this.coroutine&&this.stopCoroutine(this.coroutine),this.relativeMotion?this.coroutine=this.startCoroutine(this.moveRelative()):this.coroutine=this.startCoroutine(this.moveToTarget())}*moveToTarget(){if(!this.target||!this.object)return;const A=Ne(this.object).clone(),e=Ne(this.target).clone(),i=Kt(this.object).clone(),g=Kt(this.target).clone(),I=ai(this.object).clone(),o=ai(this.target).clone(),s=A.distanceTo(e),C=i.angleTo(g),a=I.distanceTo(o);if(s<.01&&C<.01&&a<.01){CI(this.object,e),_o(this.object,g),Gl(this.object,o),this.coroutine=null;return}let n=0,B=0;for(;n<1;)n+=this.context.time.deltaTime/this.duration,n>1&&(n=1),B=n<.5?4*n*n*n:1-Math.pow(-2*n+2,3)/2,this.targetPos.lerpVectors(A,e,B),this.targetRot.slerpQuaternions(i,g,B),this.targetScale.lerpVectors(I,o,B),CI(this.object,this.targetPos),_o(this.object,this.targetRot),Gl(this.object,this.targetScale),yield;this.coroutine=null}*moveRelative(){if(!this.target||!this.object)return;const A=this.object.position.clone(),e=this.object.quaternion.clone(),i=this.object.scale.clone(),g=this.target.position.clone(),I=this.target.quaternion.clone(),o=this.target.scale.clone();g.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(g),this.targetRot.copy(this.object.quaternion).multiply(I),this.targetScale.copy(this.object.scale).multiply(o);let s=0,C=0;for(;s<1;)s+=this.context.time.deltaTime/this.duration,s>1&&(s=1),C=s<.5?4*s*s*s:1-Math.pow(-2*s+2,3)/2,this.object.position.lerpVectors(A,this.targetPos,C),this.object.quaternion.slerpQuaternions(e,this.targetRot,C),this.object.scale.lerpVectors(i,this.targetScale,C),yield;this.coroutine=null}beforeCreateDocument(A){var e;if(this.target&&this.object&&this.gameObject){const i=new Fg("Move to "+((e=this.target)==null?void 0:e.name),Kg.tapTrigger(this.gameObject),Et.transformAction(this.object,this.target,this.duration,this.relativeMotion?yU.Relative:yU.Absolute));A.addBehavior(i)}}}ni([y(wA)],qB.prototype,"object",2),ni([y(wA)],qB.prototype,"target",2),ni([y()],qB.prototype,"duration",2),ni([y()],qB.prototype,"relativeMotion",2);var Ww;const Fa=(Ww=class extends JA{constructor(){super(...arguments),r(this,"materialToSwitch"),r(this,"variantMaterial"),r(this,"fadeDuration",0),r(this,"_objectsWithThisMaterial",[]),r(this,"selfModel"),r(this,"targetModels")}awake(){if(this.variantMaterial&&this.materialToSwitch){const t=aA.findObjectsOfType(Si);for(const A of t)for(let e=0;e<A.sharedMaterials.length;e++){const i=A.sharedMaterials[e];if(i===this.materialToSwitch){if(A.gameObject instanceof DA)this._objectsWithThisMaterial.push(A.gameObject);else if(A.gameObject instanceof dI)for(const g of A.gameObject.children)g instanceof DA&&g.material===i&&this._objectsWithThisMaterial.push(g);break}}}}start(){Rd(this.gameObject)}onPointerClick(t){if(t.use(),!!this.variantMaterial)for(let A=0;A<this._objectsWithThisMaterial.length;A++){const e=this._objectsWithThisMaterial[A];e.material=this.variantMaterial}}async beforeCreateDocument(t,A){this.targetModels=[],Fa._materialTriggersPerId={},Fa.variantSwitchIndex=0,this.materialToSwitch&&await Us.assignTextureLOD(this.context,this.sourceId,this.materialToSwitch,0),this.variantMaterial&&await Us.assignTextureLOD(this.context,this.sourceId,this.variantMaterial,0)}createBehaviours(t,A,e){this._objectsWithThisMaterial.find(i=>i.uuid===A.uuid)&&this.targetModels.push(A),this.gameObject.uuid===A.uuid&&(this.selfModel=A,this.materialToSwitch&&(Fa._materialTriggersPerId[this.materialToSwitch.uuid]||(Fa._materialTriggersPerId[this.materialToSwitch.uuid]=[]),Fa._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(t,A){if(!this.materialToSwitch)return;const e=Fa._materialTriggersPerId[this.materialToSwitch.uuid];if(e){const i={};for(const g of e){const I=g.createVariants();I&&I.length>0&&(i[g.selfModel.uuid]=I)}for(const g of e){const I=[];for(const o in i)o!==g.selfModel.uuid&&I.push(...i[o]);g.createAndAttachBehaviors(t,i[g.selfModel.uuid],I)}}delete Fa._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(t,A,e){const i=[],g=[],I=Math.max(0,this.fadeDuration);g.push(Et.fadeAction([...this.targetModels,...e],I,!1)),i.push(Et.fadeAction(A,I,!1)),g.push(Et.fadeAction(A,I,!0)),t.addBehavior(new Fg("Select_"+this.selfModel.name,Kg.tapTrigger(this.selfModel),Et.parallel(...g))),t.addBehavior(new Fg("StartHidden_"+this.selfModel.name,Kg.sceneStartTrigger(),Et.parallel(...i)))}createVariants(){if(!this.variantMaterial)return null;const t=[];for(const A of this.targetModels){const e=A.clone();e.name+=" variant_"+this.variantMaterial.name+"_"+Fa.variantSwitchIndex++,e.name=e.name.replace(/\s/g,"_"),e.material=this.variantMaterial,e.geometry=A.geometry,e.matrix=A.matrix,(!A.parent||!A.parent.isEmpty())&&Wo.createEmptyParent(A),A.parent&&A.parent.add(e),t.push(e)}return t}},r(Ww,"_materialTriggersPerId",{}),r(Ww,"variantSwitchIndex",0),Ww);let ih=Fa;ni([y(qe)],ih.prototype,"materialToSwitch",2),ni([y(qe)],ih.prototype,"variantMaterial",2),ni([y()],ih.prototype,"fadeDuration",2);var gh;const ri=(gh=class extends JA{constructor(){super(...arguments),r(this,"target"),r(this,"toggleOnClick",!1),r(this,"targetState",!0),r(this,"hideSelf",!0),r(this,"selfModel"),r(this,"selfModelClone"),r(this,"targetModel"),r(this,"toggleModel"),r(this,"stateBeforeCreatingDocument",!1),r(this,"targetStateBeforeCreatingDocument",!1)}start(){Rd(this.gameObject)}onPointerClick(t){t.use(),!this.toggleOnClick&&this.hideSelf&&(this.gameObject.visible=!1),this.target&&(this.target.visible=this.toggleOnClick?!this.target.visible:this.targetState)}createBehaviours(t,A,e){A.uuid===this.gameObject.uuid&&(this.selfModel=A,this.selfModelClone=A.clone())}beforeCreateDocument(){this.target&&(this.gameObject[ri.wasVisible]===void 0&&(this.gameObject[ri.wasVisible]=this.gameObject.activeSelf),this.target[ri.wasVisible]===void 0&&(this.target[ri.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[ri.wasVisible],this.targetStateBeforeCreatingDocument=this.target[ri.wasVisible],this.gameObject.visible=!0,this.target.visible=!0)}afterCreateDocument(t,A){if(!this.target)return;this.targetModel=A.document.findById(this.target.uuid);const e=this.selfModel;if(this.selfModel&&this.targetModel){let i=this.selfModel,g=this.targetState;if(this.toggleOnClick)if(g=!this.targetStateBeforeCreatingDocument,!this.selfModelClone.geometry)(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&c_.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[ri.toggleClone]){const s=this.selfModelClone.clone();s.matrix.identity(),s.name+="_toggle"+ri.clonedToggleIndex++,e.add(s),this.gameObject[ri.toggleClone]=s,console.warn("USDZExport: Toggle "+this.gameObject.name+" doesn't have geometry. It will be deep cloned and nested behaviours will likely not work.")}const o=this.gameObject[ri.toggleClone];if(!this.gameObject[ri.reverseToggleClone]){const s=this.selfModelClone.clone();s.matrix.identity(),s.name+="_toggleReverse"+ri.clonedToggleIndex++,e.add(s),this.gameObject[ri.reverseToggleClone]=s}this.toggleModel=this.gameObject[ri.reverseToggleClone],(!this.toggleModel.geometry||!o.geometry)&&console.error("triggers without childs and without geometry won't work!",this,e.geometry),i=o,e.geometry=null,e.material=null}if(this.toggleModel){if(this.toggleOnClick){const o=[];o.push(Et.fadeAction(i,0,!1)),o.push(Et.fadeAction(this.toggleModel,0,!0)),o.push(Et.fadeAction(this.targetModel,0,g)),t.addBehavior(new Fg("Toggle_"+i.name+"_toggleTo"+(g?"On":"Off"),Kg.tapTrigger(i),Et.parallel(...o)));const s=[];s.push(Et.fadeAction(this.toggleModel,0,!1)),s.push(Et.fadeAction(i,0,!0)),s.push(Et.fadeAction(this.targetModel,0,!g)),t.addBehavior(new Fg("Toggle_"+i.name+"_toggleTo"+(g?"Off":"On"),Kg.tapTrigger(this.toggleModel),Et.parallel(...s)))}}else{const o=[];this.hideSelf&&o.push(Et.fadeAction(i,0,!1)),o.push(Et.fadeAction(this.targetModel,0,g)),t.addBehavior(new Fg("Toggle_"+i.name+"_toggleTo"+(g?"On":"Off"),Kg.tapTrigger(i),Et.parallel(...o)))}const I=new Array;this.targetStateBeforeCreatingDocument||I.push(this.targetModel),this.stateBeforeCreatingDocument||I.push(e),this.toggleModel&&I.push(this.toggleModel),t.addBehavior(new Fg("HideOnStart_"+this.gameObject.name,Kg.sceneStartTrigger(),Et.fadeAction(I,0,!1)))}}afterSerialize(t,A){this.gameObject[ri.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[ri.wasVisible],delete this.gameObject[ri.wasVisible]),this.target&&this.target[ri.wasVisible]!==void 0&&(this.target.visible=this.target[ri.wasVisible],delete this.target[ri.wasVisible]),delete this.gameObject[ri.toggleClone],delete this.gameObject[ri.reverseToggleClone]}},r(gh,"clonedToggleIndex",0),r(gh,"wasVisible",Symbol("usdz_SetActiveOnClick_wasVisible")),r(gh,"toggleClone",Symbol("clone for toggling")),r(gh,"reverseToggleClone",Symbol("clone for reverse toggling")),gh);let LB=ri;ni([y(wA)],LB.prototype,"target",2),ni([y()],LB.prototype,"toggleOnClick",2),ni([y()],LB.prototype,"targetState",2),ni([y()],LB.prototype,"hideSelf",2);class BN extends JA{start(){this.gameObject.visible=!1}createBehaviours(A,e,i){e.uuid===this.gameObject.uuid&&A.addBehavior(new Fg("HideOnStart_"+this.gameObject.name,Kg.sceneStartTrigger(),Et.fadeAction(e,0,!1)))}beforeCreateDocument(){this.gameObject.visible=!0}afterCreateDocument(){this.gameObject.visible=!1}}class Ih extends JA{constructor(){super(...arguments),r(this,"target"),r(this,"duration",.5),r(this,"motionType",DU.bounce)}beforeCreateDocument(){}createBehaviours(A,e,i){if(this.target&&e.uuid===this.gameObject.uuid){const g=new Fg("emphasize "+this.name,Kg.tapTrigger(this.gameObject),Et.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));A.addBehavior(g)}}afterCreateDocument(A,e){}}ni([y()],Ih.prototype,"target",2),ni([y()],Ih.prototype,"duration",2),ni([y()],Ih.prototype,"motionType",2);class oh extends JA{constructor(){super(...arguments),r(this,"target"),r(this,"clip",""),r(this,"toggleOnClick",!1)}start(){Rd(this.gameObject)}ensureAudioSource(){if(!this.target){const A=this.gameObject.addNewComponent(fi);A&&(this.target=A,A.spatialBlend=1,A.volume=1,A.loop=!1)}}onPointerClick(A){var e;A.use(),!(!((e=this.target)!=null&&e.clip)&&!this.clip)&&(this.ensureAudioSource(),this.target&&(this.target.isPlaying&&this.toggleOnClick?this.target.stop():(!this.toggleOnClick&&this.target.isPlaying&&this.target.stop(),this.clip?this.target.play(this.clip):this.target.play())))}createBehaviours(A,e,i){if(!(!this.target&&!this.clip)&&e.uuid===this.gameObject.uuid){const g=this.clip?this.clip:this.target?this.target.clip:void 0;if(!g||typeof g!="string")return;const I=this.target?this.target.gameObject:this.gameObject,o=g.split("/").pop(),s=this.target?this.target.volume:1,C=this.target&&this.target.spatialBlend==0?fU.NonSpatial:fU.Spatial;{let a=Et.playAudioAction(I,"audio/"+o,SU.Play,s,C);this.toggleOnClick&&(a.multiplePerformOperation=R_.Stop),this.target&&this.target.loop&&(a=Et.sequence(a).makeLooping());const n=new Fg("playAudio "+this.name,Kg.tapTrigger(this.gameObject),a);A.addBehavior(n)}if(this.target&&this.target.playOnAwake&&this.target.enabled){let a=Et.playAudioAction(I,"audio/"+o,SU.Play,s,C);this.target.loop&&(a=Et.sequence(a).makeLooping());const n=new Fg("playAudioOnStart "+this.name,Kg.sceneStartTrigger(),a);A.addBehavior(n)}}}async afterSerialize(A,e){if(!this.target&&!this.clip)return;const i=this.clip?this.clip:this.target?this.target.clip:void 0;if(!i||typeof i!="string")return;const g=i.split("/").pop(),I=await(await(await fetch(i)).blob()).arrayBuffer(),o=new Uint8Array(I);e.files["audio/"+g]=o}}ni([y(fi)],oh.prototype,"target",2),ni([y(URL)],oh.prototype,"clip",2),ni([y()],oh.prototype,"toggleOnClick",2);var Vw;const Xn=(Vw=class extends JA{constructor(){super(...arguments),r(this,"animator"),r(this,"stateName"),r(this,"trigger","tap"),r(this,"selfModel"),r(this,"stateAnimationModel"),r(this,"animationSequence",new Array),r(this,"animationLoopAfterSequence",new Array)}get target(){var t;return(t=this.animator)==null?void 0:t.gameObject}start(){Rd(this.gameObject)}onPointerClick(t){var A;t.use(),this.target&&this.stateName&&((A=this.animator)==null||A.play(this.stateName,0,0,.1))}createBehaviours(t,A,e){A.uuid===this.gameObject.uuid&&(this.selfModel=A)}afterSerialize(){if(Xn.rootsWithExclusivePlayback.size>1){const t='Multiple root objects targeted by more than one animation. To work around QuickLook bug FB13410767, animations will be set as "exclusive" and activating them will stop other animations being marked as exclusive.';Se()&&Ci(t),console.warn(t,...Xn.rootsWithExclusivePlayback)}Xn.animationActions=[],Xn.rootsWithExclusivePlayback=new Set}afterCreateDocument(t,A){if(!this.animationSequence||!this.stateAnimationModel||!this.target)return;const e=A.document,i=A.extensions.find(o=>o instanceof Ed);if(!i)return;const g=i.getClipCount(this.target)>1;g&&(Se()&&console.warn("Setting exclusive playback for "+this.target.name+"@"+this.stateName+" because it has "+i.getClipCount(this.target)+" animations. This works around QuickLook bug FB13410767."),Xn.rootsWithExclusivePlayback.add(this.target));const I=(o,s)=>{let C=Xn.animationActions.find(a=>a.affectedObjects==o&&a.start==s.start&&a.duration==s.duration);return C||(C=Et.startAnimationAction(o,s.start,s.duration),Xn.animationActions.push(C)),C};e.traverse(o=>{var s,C;if(o.uuid===((s=this.target)==null?void 0:s.uuid)){const a=Et.sequence();if(this.animationSequence!==void 0)for(const B of this.animationSequence)a.addAction(I(o,B));if(this.animationLoopAfterSequence!==void 0){const B=a.actions.length==0?a:Et.sequence();for(const Q of this.animationLoopAfterSequence)B.addAction(I(o,Q));B.makeLooping(),a!==B&&a.addAction(B)}const n=new Fg("tap "+this.name+" for "+this.stateName+" on "+((C=this.target)==null?void 0:C.name),this.trigger=="tap"?Kg.tapTrigger(this.selfModel):Kg.sceneStartTrigger(),a);g&&n.makeExclusive(!0),t.addBehavior(n)}})}createAnimation(t,A,e){var i,g,I,o;if(!this.target||!this.animator)return;const s=(i=this.animator)==null?void 0:i.runtimeAnimatorController;let C=s?.findState(this.stateName),a=[],n=[];if(s&&C){const B=new Array;B.push(C);let Q=!1;for(;B.length<100;){if(!C||C===null||!C.transitions||C.transitions.length===0){(g=C.motion)!=null&&g.isLooping&&(Q=!0);break}const E=C.transitions.find(d=>d.conditions.length===0),h=E?s.getState(E.destinationState,0):null;if(h&&B.includes(h)){C=h,Q=!0;break}else if(E){if(C=h,!C)break;B.push(C)}else{Q=((I=C.motion)==null?void 0:I.isLooping)??!1;break}}if(Q&&C){const E=B.indexOf(C);a=B.slice(0,E),n=B.slice(E),console.log("found loop from "+this.stateName,"states until loop",a,"states looping",n)}else a=B,n=[],console.log("found no loop from "+this.stateName,"states",a)}if(a=a.filter(B=>{var Q,E,h;return((Q=B.motion)==null?void 0:Q.clip)&&((h=(E=B.motion)==null?void 0:E.clip.tracks)==null?void 0:h.length)>0}),n=n.filter(B=>{var Q,E,h;return((Q=B.motion)==null?void 0:Q.clip)&&((h=(E=B.motion)==null?void 0:E.clip.tracks)==null?void 0:h.length)>0}),a.length===0&&n.length===0){console.warn("No clips found for state "+this.stateName+" on "+((o=this.animator)==null?void 0:o.name)+", can't export animation data");return}if(this.stateAnimationModel=A,a.length>0){this.animationSequence=new Array;for(const B of a)this.animationSequence.push(t.registerAnimation(this.target,B.motion.clip))}if(n.length>0){this.animationLoopAfterSequence=new Array;for(const B of n)this.animationLoopAfterSequence.push(t.registerAnimation(this.target,B.motion.clip))}}},r(Vw,"animationActions",[]),r(Vw,"rootsWithExclusivePlayback",new Set),Vw);let sh=Xn;ni([y(bg)],sh.prototype,"animator",2),ni([y()],sh.prototype,"stateName",2);class Ch extends JA{constructor(){super(...arguments),r(this,"target")}getType(){}getDuration(){}}ni([y(wA)],Ch.prototype,"target",2);class Ud extends JA{constructor(){super(...arguments),r(this,"target")}}ni([y(Ch)],Ud.prototype,"target",2);class Nd extends Ch{constructor(){super(...arguments),r(this,"type",1),r(this,"duration",1)}getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}ni([y()],Nd.prototype,"type",2),ni([y()],Nd.prototype,"duration",2);class QN extends Ud{}var $oA=Object.defineProperty,AsA=Object.getOwnPropertyDescriptor,Ka=(t,A,e,i)=>{for(var g=i>1?void 0:i?AsA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&$oA(A,e,g),g};const nO=iA("debugcharactercontroller");class xB extends JA{constructor(){super(...arguments),r(this,"center",new w(0,0,0)),r(this,"radius",.5),r(this,"height",2),r(this,"_rigidbody",null),r(this,"_activeGroundCollisions"),r(this,"_contactVelocity",new w)}get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(Pt),this._rigidbody||(this._rigidbody=this.gameObject.addNewComponent(Pt)),this.rigidbody)}awake(){this._activeGroundCollisions=new Set}onEnable(){const A=this.rigidbody;let e=this.gameObject.getComponent(Wn);e||(e=this.gameObject.addNewComponent(Wn)),e.center.copy(this.center),e.radius=this.radius,e.height=this.height;const i=new w(0,0,1),g=new w(1,0,0),I=new w(0,1,0),o=this.gameObject.getWorldDirection(new w);o.y=0;const s=g.dot(o)<0?-1:1,C=i.angleTo(o)*s;this.gameObject.setRotationFromAxisAngle(I,C),A.lockRotationX=!0,A.lockRotationY=!0,A.lockRotationZ=!0}move(A){this.gameObject.position.add(A)}onCollisionEnter(A){(A.contacts.length==0||A.contacts.some(e=>e.normal.y>.2))&&(this._activeGroundCollisions.add(A),nO&&console.log(`Collision(${this._activeGroundCollisions.size}): ${A.contacts.map(e=>e.normal.y.toFixed(2)).join(", ")} - ${this.isGrounded}`))}onCollisionExit(A){this._activeGroundCollisions.delete(A),nO&&console.log(`Collision(${this._activeGroundCollisions.size}) - ${this.isGrounded}`)}get isGrounded(){return this._activeGroundCollisions.size>0}get contactVelocity(){var A;this._contactVelocity.set(0,0,0);for(const e of this._activeGroundCollisions){const i=(A=this.context.physics.engine)==null?void 0:A.getLinearVelocity(e.collider);i&&(this._contactVelocity.x+=i.x,this._contactVelocity.y+=i.y,this._contactVelocity.z+=i.z)}return this._contactVelocity}}Ka([y(w)],xB.prototype,"center",2),Ka([y()],xB.prototype,"radius",2),Ka([y()],xB.prototype,"height",2);class Ja extends JA{constructor(){super(...arguments),r(this,"controller"),r(this,"movementSpeed",2),r(this,"rotationSpeed",2),r(this,"jumpForce",1),r(this,"doubleJumpForce",2),r(this,"animator"),r(this,"lookForward",!0),r(this,"lookInput",new tA(0,0)),r(this,"moveInput",new tA(0,0)),r(this,"jumpInput",!1),r(this,"_currentSpeed",new w(0,0,0)),r(this,"_currentAngularSpeed",new w(0,0,0)),r(this,"_temp",new w(0,0,0)),r(this,"_jumpCount",0),r(this,"_currentRotation"),r(this,"_raycastOptions",new Oo)}awake(){this._currentRotation=new FA}update(){const A=this.context.input;A.isKeyPressed("KeyW")?this.moveInput.y+=1:A.isKeyPressed("KeyS")&&(this.moveInput.y-=1),A.isKeyPressed("KeyD")?this.lookInput.x+=1:A.isKeyPressed("KeyA")&&(this.lookInput.x-=1),this.jumpInput||(this.jumpInput=A.isKeyDown("Space"))}move(A){this.moveInput.add(A)}look(A){this.lookInput.add(A)}jump(){this.jumpInput=!0}onBeforeRender(){this.handleInput(this.moveInput,this.lookInput,this.jumpInput),this.lookInput.set(0,0),this.moveInput.set(0,0),this.jumpInput=!1}handleInput(A,e,i){var g,I,o,s,C,a,n,B,Q,E,h;if((g=this.controller)!=null&&g.isGrounded&&(this._jumpCount=0,this.doubleJumpForce>0&&((I=this.animator)==null||I.setBool("doubleJump",!1))),this._currentSpeed.z+=A.y*this.movementSpeed*this.context.time.deltaTime,(o=this.animator)==null||o.setBool("running",A.length()>.01),(C=this.animator)==null||C.setBool("jumping",((s=this.controller)==null?void 0:s.isGrounded)===!0&&i),this._temp.copy(this._currentSpeed),this._temp.applyQuaternion(this.gameObject.quaternion),this.controller?this.controller.move(this._temp):this.gameObject.position.add(this._temp),this._currentAngularSpeed.y+=Ie.toRadians(-e.x*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){const d=this.context.mainCameraComponent.forward;d.y=0,d.normalize(),this._currentRotation.setFromUnitVectors(new w(0,0,1),d),this.gameObject.quaternion.slerp(this._currentRotation,this.context.time.deltaTime*10)}if(this.gameObject.rotateY(this._currentAngularSpeed.y),this._currentSpeed.multiplyScalar(1-this.context.time.deltaTime*10),this._currentAngularSpeed.y*=1-this.context.time.deltaTime*10,this.controller&&i&&this.jumpForce>0){let d=(a=this.controller)==null?void 0:a.isGrounded;if(this.doubleJumpForce>0&&!((n=this.controller)!=null&&n.isGrounded)&&this._jumpCount===1&&(d=!0,(B=this.animator)==null||B.setBool("doubleJump",!0)),d){this._jumpCount+=1;const u=this.controller.rigidbody,c=this._jumpCount===2?this.doubleJumpForce:this.jumpForce;u.applyImpulse(new w(0,1,0).multiplyScalar(c))}}if(this.controller){const d=(Q=this.controller)==null?void 0:Q.rigidbody.getVelocity().y;if(d<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new to),this._raycastOptions.ray.origin.copy(Ne(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);const u=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);const c=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(u),(c.length&&c[0].distance>2||d<-10)&&((E=this.animator)==null||E.setBool("falling",!0))}else(h=this.animator)==null||h.setBool("falling",!1)}}}Ka([y(xB)],Ja.prototype,"controller",2),Ka([y()],Ja.prototype,"movementSpeed",2),Ka([y()],Ja.prototype,"rotationSpeed",2),Ka([y()],Ja.prototype,"jumpForce",2),Ka([y()],Ja.prototype,"doubleJumpForce",2),Ka([y(bg)],Ja.prototype,"animator",2);var esA=Object.defineProperty,tsA=Object.getOwnPropertyDescriptor,isA=(t,A,e,i)=>{for(var g=i>1?void 0:i?tsA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&esA(A,e,g),g};class Fd extends rI{constructor(){super(...arguments),r(this,"intensity")}get typeName(){return"ChromaticAberration"}init(){this.intensity.defaultValue=0}onCreateEffect(){const A=new fL;return A.offset=new tA(0,0),A.radialModulation=!0,A.modulationOffset=.15,this.intensity.valueProcessor=e=>e*.02,this.intensity.onValueChanged=e=>{A.offset.x=-e,A.offset.y=e},A}}isA([y(Ke)],Fd.prototype,"intensity",2),As("ChromaticAberration",Fd);var gsA=Object.defineProperty,IsA=Object.getOwnPropertyDescriptor,Zw=(t,A,e,i)=>{for(var g=i>1?void 0:i?IsA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&gsA(A,e,g),g};class $n extends rI{constructor(){super(...arguments),r(this,"postExposure"),r(this,"contrast"),r(this,"hueShift"),r(this,"saturation")}get typeName(){return"ColorAdjustments"}init(){this.postExposure.valueProcessor=A=>(A=Math.pow(2,A),A),this.postExposure.defaultValue=0,this.contrast.valueProcessor=A=>{let e=1;return A>0?e=200:A<0&&(e=100),A/e},this.contrast.defaultValue=0,this.hueShift.valueProcessor=A=>Math.PI*A/180,this.hueShift.defaultValue=0,this.saturation.valueProcessor=A=>A<0?A/100:A/(100*Math.PI),this.saturation.defaultValue=0}unapply(){this.context.renderer.toneMappingExposure=1}onCreateEffect(){this.context.renderer.toneMapping===YI&&this.postExposure.overrideState&&(this.context.renderer.toneMapping=Zh);const A=new SL;this.postExposure.onValueChanged=i=>{this.context.renderer.toneMapping===YI&&(this.context.renderer.toneMapping=Zh),this.postExposure.overrideState&&(this.context.renderer.toneMappingExposure=i)},this.contrast.onValueChanged=i=>{A.contrast=i};const e=new kL;return this.hueShift.onValueChanged=i=>e.hue=i,this.saturation.onValueChanged=i=>e.saturation=i,[e,A]}}Zw([y(Ke)],$n.prototype,"postExposure",2),Zw([y(Ke)],$n.prototype,"contrast",2),Zw([y(Ke)],$n.prototype,"hueShift",2),Zw([y(Ke)],$n.prototype,"saturation",2),As("ColorAdjustments",$n);const osA=(Math.sqrt(5)-1)/4,Yg=(5-Math.sqrt(5))/20,zw=t=>Math.floor(t)|0,Xw=new Float64Array([0,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,1,0,1,1,1,0,1,-1,1,0,-1,1,1,0,-1,-1,-1,0,1,1,-1,0,1,-1,-1,0,-1,1,-1,0,-1,-1,1,1,0,1,1,1,0,-1,1,-1,0,1,1,-1,0,-1,-1,1,0,1,-1,1,0,-1,-1,-1,0,1,-1,-1,0,-1,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,0]);function ssA(t=Math.random){const A=CsA(t),e=new Float64Array(A).map(o=>Xw[o%32*4]),i=new Float64Array(A).map(o=>Xw[o%32*4+1]),g=new Float64Array(A).map(o=>Xw[o%32*4+2]),I=new Float64Array(A).map(o=>Xw[o%32*4+3]);return function(o,s,C,a){let n,B,Q,E,h;const d=(o+s+C+a)*osA,u=zw(o+d),c=zw(s+d),l=zw(C+d),p=zw(a+d),D=(u+c+l+p)*Yg,S=u-D,k=c-D,f=l-D,U=p-D,M=o-S,m=s-k,x=C-f,L=a-U;let V=0,Y=0,P=0,b=0;M>m?V++:Y++,M>x?V++:P++,M>L?V++:b++,m>x?Y++:P++,m>L?Y++:b++,x>L?P++:b++;const T=V>=3?1:0,_=Y>=3?1:0,eA=P>=3?1:0,$=b>=3?1:0,IA=V>=2?1:0,yA=Y>=2?1:0,xA=P>=2?1:0,OA=b>=2?1:0,$A=V>=1?1:0,rA=Y>=1?1:0,RA=P>=1?1:0,jA=b>=1?1:0,YA=M-T+Yg,WA=m-_+Yg,BA=x-eA+Yg,TA=L-$+Yg,W=M-IA+2*Yg,GA=m-yA+2*Yg,fA=x-xA+2*Yg,_A=L-OA+2*Yg,hA=M-$A+3*Yg,Ee=m-rA+3*Yg,q=x-RA+3*Yg,N=L-jA+3*Yg,CA=M-1+4*Yg,bA=m-1+4*Yg,MA=x-1+4*Yg,LA=L-1+4*Yg,ge=u&255,HA=c&255,XA=l&255,se=p&255;let De=.6-M*M-m*m-x*x-L*L;if(De<0)n=0;else{const kA=ge+A[HA+A[XA+A[se]]];De*=De,n=De*De*(e[kA]*M+i[kA]*m+g[kA]*x+I[kA]*L)}let vA=.6-YA*YA-WA*WA-BA*BA-TA*TA;if(vA<0)B=0;else{const kA=ge+T+A[HA+_+A[XA+eA+A[se+$]]];vA*=vA,B=vA*vA*(e[kA]*YA+i[kA]*WA+g[kA]*BA+I[kA]*TA)}let be=.6-W*W-GA*GA-fA*fA-_A*_A;if(be<0)Q=0;else{const kA=ge+IA+A[HA+yA+A[XA+xA+A[se+OA]]];be*=be,Q=be*be*(e[kA]*W+i[kA]*GA+g[kA]*fA+I[kA]*_A)}let ne=.6-hA*hA-Ee*Ee-q*q-N*N;if(ne<0)E=0;else{const kA=ge+$A+A[HA+rA+A[XA+RA+A[se+jA]]];ne*=ne,E=ne*ne*(e[kA]*hA+i[kA]*Ee+g[kA]*q+I[kA]*N)}let Be=.6-CA*CA-bA*bA-MA*MA-LA*LA;if(Be<0)h=0;else{const kA=ge+1+A[HA+1+A[XA+1+A[se+1]]];Be*=Be,h=Be*Be*(e[kA]*CA+i[kA]*bA+g[kA]*MA+I[kA]*LA)}return 27*(n+B+Q+E+h)}}function CsA(t){const A=new Uint8Array(512);for(let e=0;e<512/2;e++)A[e]=e;for(let e=0;e<512/2-1;e++){const i=e+~~(t()*(256-e)),g=A[e];A[e]=A[i],A[i]=g}for(let e=256;e<512;e++)A[e]=A[e-256];return A}var asA=Object.defineProperty,nsA=Object.getOwnPropertyDescriptor,gA=(t,A,e,i)=>{for(var g=i>1?void 0:i?nsA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&asA(A,e,g),g};const $w=iA("debugparticles");var va=(t=>(t[t.Billboard=0]="Billboard",t[t.Stretch=1]="Stretch",t[t.HorizontalBillboard=2]="HorizontalBillboard",t[t.VerticalBillboard=3]="VerticalBillboard",t[t.Mesh=4]="Mesh",t))(va||{});let Ar=class{constructor(){r(this,"alphaKeys"),r(this,"colorKeys")}get duration(){return 1}evaluate(t,A){let e,i=0,g=null,I=0;for(let o=0;o<this.alphaKeys.length;o++){const s=this.alphaKeys[o];(s.time<t||!e)&&(e=s,i=o)}for(let o=0;o<this.colorKeys.length;o++){const s=this.colorKeys[o];(s.time<t||!g)&&(g=s,I=o)}if(g)if(I+1<this.colorKeys.length){const o=this.colorKeys[I+1],s=Ie.remap(t,g.time,o.time,0,1);A.r=Ie.lerp(g.color.r,o.color.r,s),A.g=Ie.lerp(g.color.g,o.color.g,s),A.b=Ie.lerp(g.color.b,o.color.b,s)}else A.r=g.color.r,A.g=g.color.g,A.b=g.color.b;if(e)if(i+1<this.alphaKeys.length){const o=this.alphaKeys[i+1],s=Ie.remap(t,e.time,o.time,0,1);A.alpha=Ie.lerp(e.alpha,o.alpha,s)}else A.alpha=e.alpha;return A}};gA([y()],Ar.prototype,"alphaKeys",2),gA([y()],Ar.prototype,"colorKeys",2);var Kd=(t=>(t[t.Local=0]="Local",t[t.World=1]="World",t[t.Custom=2]="Custom",t))(Kd||{}),AS=(t=>(t[t.Sphere=0]="Sphere",t[t.SphereShell=1]="SphereShell",t[t.Hemisphere=2]="Hemisphere",t[t.HemisphereShell=3]="HemisphereShell",t[t.Cone=4]="Cone",t[t.Box=5]="Box",t[t.Mesh=6]="Mesh",t[t.ConeShell=7]="ConeShell",t[t.ConeVolume=8]="ConeVolume",t[t.ConeVolumeShell=9]="ConeVolumeShell",t[t.Circle=10]="Circle",t[t.CircleEdge=11]="CircleEdge",t[t.SingleSidedEdge=12]="SingleSidedEdge",t[t.MeshRenderer=13]="MeshRenderer",t[t.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",t[t.BoxShell=15]="BoxShell",t[t.BoxEdge=16]="BoxEdge",t[t.Donut=17]="Donut",t[t.Rectangle=18]="Rectangle",t[t.Sprite=19]="Sprite",t[t.SpriteRenderer=20]="SpriteRenderer",t))(AS||{});const rO=class{constructor(){r(this,"mode"),r(this,"constant"),r(this,"constantMin"),r(this,"constantMax"),r(this,"curve"),r(this,"curveMin"),r(this,"curveMax"),r(this,"curveMultiplier")}clone(){var t,A,e;const i=new rO;return i.mode=this.mode,i.constant=this.constant,i.constantMin=this.constantMin,i.constantMax=this.constantMax,i.curve=(t=this.curve)==null?void 0:t.clone(),i.curveMin=(A=this.curveMin)==null?void 0:A.clone(),i.curveMax=(e=this.curveMax)==null?void 0:e.clone(),i.curveMultiplier=this.curveMultiplier,i}evaluate(t,A){const e=A===void 0?Math.random():A;switch(this.mode){case 0:return this.constant;case 1:return t=Ie.clamp01(t),this.curve.evaluate(t)*this.curveMultiplier;case 2:const i=t*this.curveMin.duration,g=t*this.curveMax.duration;return Ie.lerp(this.curveMin.evaluate(i),this.curveMax.evaluate(g),e%1)*this.curveMultiplier;case 3:return Ie.lerp(this.constantMin,this.constantMax,e%1);default:this.curveMax.evaluate(t)*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(t){if(!t)return 0;let A=Number.MIN_VALUE;for(let e=0;e<t.keys.length;e++){const i=t.keys[e];i.value>A&&(A=i.value)}return A}};let re=rO;gA([y()],re.prototype,"mode",2),gA([y()],re.prototype,"constant",2),gA([y()],re.prototype,"constantMin",2),gA([y()],re.prototype,"constantMax",2),gA([y(SB)],re.prototype,"curve",2),gA([y(SB)],re.prototype,"curveMin",2),gA([y(SB)],re.prototype,"curveMax",2),gA([y()],re.prototype,"curveMultiplier",2);var eS;const Js=(eS=class{constructor(){r(this,"mode"),r(this,"color"),r(this,"colorMin"),r(this,"colorMax"),r(this,"gradient"),r(this,"gradientMin"),r(this,"gradientMax")}evaluate(t,A){const e=A===void 0?Math.random():A;switch(this.mode){case 0:return this.color;case 1:return this.gradient.evaluate(t,Js._temp),Js._temp;case 2:return Js._temp.lerpColors(this.colorMin,this.colorMax,e);case 3:return this.gradientMin.evaluate(t,Js._temp),this.gradientMax.evaluate(t,Js._temp2),Js._temp.lerp(Js._temp2,e)}return Js._temp.set(16711935),Js._temp.alpha=1,Js._temp}},r(eS,"_temp",new Mt(0,0,0,1)),r(eS,"_temp2",new Mt(0,0,0,1)),eS);let XI=Js;gA([y(Mt)],XI.prototype,"color",2),gA([y(Mt)],XI.prototype,"colorMin",2),gA([y(Mt)],XI.prototype,"colorMax",2),gA([y(Ar)],XI.prototype,"gradient",2),gA([y(Ar)],XI.prototype,"gradientMin",2),gA([y(Ar)],XI.prototype,"gradientMax",2);var EN=(t=>(t[t.Hierarchy=0]="Hierarchy",t[t.Local=1]="Local",t[t.Shape=2]="Shape",t))(EN||{});class Tg{constructor(){r(this,"cullingMode"),r(this,"duration"),r(this,"emitterVelocityMode"),r(this,"flipRotation"),r(this,"gravityModifier"),r(this,"gravityModifierMultiplier"),r(this,"loop"),r(this,"maxParticles"),r(this,"playOnAwake"),r(this,"prewarm"),r(this,"ringBufferLoopRange"),r(this,"ringBufferMode"),r(this,"scalingMode"),r(this,"simulationSpace"),r(this,"simulationSpeed"),r(this,"startColor"),r(this,"startDelay"),r(this,"startDelayMultiplier"),r(this,"startLifetime"),r(this,"startLifetimeMultiplier"),r(this,"startRotation"),r(this,"startRotationMultiplier"),r(this,"startRotation3D"),r(this,"startRotationX"),r(this,"startRotationXMultiplier"),r(this,"startRotationY"),r(this,"startRotationYMultiplier"),r(this,"startRotationZ"),r(this,"startRotationZMultiplier"),r(this,"startSize"),r(this,"startSize3D"),r(this,"startSizeMultiplier"),r(this,"startSizeX"),r(this,"startSizeXMultiplier"),r(this,"startSizeY"),r(this,"startSizeYMultiplier"),r(this,"startSizeZ"),r(this,"startSizeZMultiplier"),r(this,"startSpeed"),r(this,"startSpeedMultiplier"),r(this,"stopAction"),r(this,"useUnscaledTime")}}gA([y(re)],Tg.prototype,"gravityModifier",2),gA([y(XI)],Tg.prototype,"startColor",2),gA([y(re)],Tg.prototype,"startDelay",2),gA([y(re)],Tg.prototype,"startLifetime",2),gA([y(re)],Tg.prototype,"startRotation",2),gA([y(re)],Tg.prototype,"startRotationX",2),gA([y(re)],Tg.prototype,"startRotationY",2),gA([y(re)],Tg.prototype,"startRotationZ",2),gA([y(re)],Tg.prototype,"startSize",2),gA([y(re)],Tg.prototype,"startSizeX",2),gA([y(re)],Tg.prototype,"startSizeY",2),gA([y(re)],Tg.prototype,"startSizeZ",2),gA([y(re)],Tg.prototype,"startSpeed",2);class Jd{constructor(){r(this,"cycleCount"),r(this,"maxCount"),r(this,"minCount"),r(this,"probability"),r(this,"repeatInterval"),r(this,"time"),r(this,"count"),r(this,"_performed",0)}reset(){this._performed=0}run(A){if(A<=this.time)return 0;let e=0;if(this.cycleCount===0||this._performed<this.cycleCount){const i=this.time+this.repeatInterval*this._performed;if(A>=i&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:e=this.count.constant;break;case 3:e=Ie.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:e=this.count.curve.evaluate(Math.random());break;case 2:const g=Math.random();e=Ie.lerp(this.count.curveMin.evaluate(g),this.count.curveMax.evaluate(g),Math.random());break}}return e}}class uC{constructor(){r(this,"enabled"),r(this,"bursts"),r(this,"rateOverTime"),r(this,"rateOverTimeMultiplier"),r(this,"rateOverDistance"),r(this,"rateOverDistanceMultiplier"),r(this,"system")}get burstCount(){var A;return((A=this.bursts)==null?void 0:A.length)??0}reset(){var A;(A=this.bursts)==null||A.forEach(e=>e.reset())}getBurst(){let A=0;if(this.burstCount>0)for(let e=0;e<this.burstCount;e++){const i=this.bursts[e];this.system.main.loop&&i.time>=this.system.time&&i.reset(),A+=Math.round(i.run(this.system.time))}return A}}gA([y()],uC.prototype,"enabled",2),gA([y()],uC.prototype,"bursts",2),gA([y(re)],uC.prototype,"rateOverTime",2),gA([y()],uC.prototype,"rateOverTimeMultiplier",2),gA([y(re)],uC.prototype,"rateOverDistance",2),gA([y()],uC.prototype,"rateOverDistanceMultiplier",2);class vd{constructor(){r(this,"enabled"),r(this,"color")}}gA([y(XI)],vd.prototype,"color",2);class er{constructor(){r(this,"enabled"),r(this,"separateAxes"),r(this,"size"),r(this,"sizeMultiplier"),r(this,"x"),r(this,"xMultiplier"),r(this,"y"),r(this,"yMultiplier"),r(this,"z"),r(this,"zMultiplier"),r(this,"_time",0),r(this,"_temp",new w)}evaluate(A,e,i){if(e||(e=this._temp),!this.enabled)return e.x=e.y=e.z=1,e;if(this.separateAxes)e.x=this.x.evaluate(A,i)*this.xMultiplier,e.y=this.y.evaluate(A,i)*this.yMultiplier,e.z=this.z.evaluate(A,i)*this.zMultiplier;else{const g=this.size.evaluate(A,i)*this.sizeMultiplier;e.x=g}return e}}gA([y(re)],er.prototype,"size",2),gA([y(re)],er.prototype,"x",2),gA([y(re)],er.prototype,"y",2),gA([y(re)],er.prototype,"z",2);var tS;const bd=(tS=class{constructor(){r(this,"shapeType",5),r(this,"enabled",!0),r(this,"alignToDirection",!1),r(this,"angle",0),r(this,"arc",360),r(this,"arcSpread"),r(this,"arcSpeedMultiplier"),r(this,"arcMode"),r(this,"boxThickness"),r(this,"position"),r(this,"rotation"),r(this,"_rotation",new Wg),r(this,"scale"),r(this,"radius"),r(this,"radiusThickness"),r(this,"sphericalDirectionAmount"),r(this,"randomDirectionAmount"),r(this,"randomPositionAmount"),r(this,"meshShapeType"),r(this,"meshRenderer"),r(this,"_meshObj"),r(this,"_meshGeometry"),r(this,"system"),r(this,"_space"),r(this,"_worldSpaceMatrix",new NA),r(this,"_worldSpaceMatrixInverse",new NA),r(this,"_vector",new w(0,0,0)),r(this,"_temp",new w(0,0,0)),r(this,"_triangle",new LI),r(this,"_dir",new w),r(this,"_loopTime",0),r(this,"_loopDirection",1),$w&&console.log(this)}get type(){return AS[this.shapeType]}initialize(t){this.onInitialize(t),t.position.copy(this._vector)}toJSON(){return this}clone(){return new bd}setMesh(t){this.meshRenderer=t,t?(this._meshObj=t.sharedMeshes[Math.floor(Math.random()*t.sharedMeshes.length)],this._meshGeometry=this._meshObj.geometry):(this._meshObj=void 0,this._meshGeometry=void 0)}update(t,A,e,i){this.system=t,this._space=e,e===1&&(this._worldSpaceMatrix.copy(i.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}applyRotation(t){const A=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return A&&(this._rotation.x=Ie.toRadians(this.rotation.x),this._rotation.y=Ie.toRadians(this.rotation.y),this._rotation.z=Ie.toRadians(this.rotation.z),this._rotation.order="ZYX",t.applyEuler(this._rotation)),A}onInitialize(t){this._vector.set(0,0,0),t.mesh=void 0,t.mesh_geometry=void 0;const A=this._temp.copy(this.position),e=this._space===1;e&&A.applyQuaternion(this.system.worldQuaternion);let i=this.radius;if(e&&(i*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:$w&&Fe.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(A);break;case 4:this.randomConePoint(this.position,this.angle,i,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,i,this.radiusThickness,this.arc,this._vector);break;case 10:this.randomCirclePoint(this.position,i,this.radiusThickness,this.arc,this._vector);break;case 13:const g=this.meshRenderer;g?.destroyed==!1&&this.setMesh(g);const I=t.mesh=this._meshObj,o=t.mesh_geometry=this._meshGeometry;if(I&&o)switch(this.meshShapeType){case 0:{const s=o.getAttribute("position"),C=Math.floor(Math.random()*s.count);this._vector.fromBufferAttribute(s,C),this._vector.applyMatrix4(I.matrixWorld),t.mesh_normal=C}break;case 1:break;case 2:{const s=o.index;if(s){let C=Math.random(),a=Math.random();C+a>1&&(C=1-C,a=1-a);const n=Math.floor(Math.random()*(s.count/3));let B=n*3,Q=n*3+1,E=n*3+2;B=s.getX(B),Q=s.getX(Q),E=s.getX(E);const h=o.getAttribute("position");this._triangle.a.fromBufferAttribute(h,B),this._triangle.b.fromBufferAttribute(h,Q),this._triangle.c.fromBufferAttribute(h,E),this._vector.set(0,0,0).addScaledVector(this._triangle.a,C).addScaledVector(this._triangle.b,a).addScaledVector(this._triangle.c,1-(C+a)),this._vector.applyMatrix4(I.matrixWorld),t.mesh_normal=n}}break}break;default:this._vector.set(0,0,0),Se()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",AS[this.shapeType]),globalThis.__particlesystem_shapetype_unsupported=!0);break}this.randomizePosition(this._vector,this.randomPositionAmount)}this.applyRotation(this._vector),e&&(this._vector.applyQuaternion(this.system.worldQuaternion),this._vector.add(this.system.worldPos)),$w&&Fe.DrawSphere(this._vector,.03,16711680,.5,!0)}getDirection(t,A){var e;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 i=A.x,g=A.y,I=A.z;this._dir.set(i,g,I),(e=this.system)!=null&&e.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;case 13:const o=t.mesh,s=t.mesh_geometry;if(o&&s)switch(this.meshShapeType){case 0:{const C=s.getAttribute("normal"),a=t.mesh_normal;this._dir.fromBufferAttribute(C,a)}break;case 1:break;case 2:{const C=s.index;if(C){const a=t.mesh_normal,n=C.getX(a*3),B=C.getX(a*3+1),Q=C.getX(a*3+2),E=s.getAttribute("position"),h=_i(),d=_i(),u=_i();h.fromBufferAttribute(E,n),d.fromBufferAttribute(E,B),u.fromBufferAttribute(E,Q),h.sub(d),u.sub(d),h.cross(u),this._dir.copy(h).multiplyScalar(-1);const c=Kt(o);this._dir.applyQuaternion(c)}}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),$w&&(Fe.DrawSphere(A,.01,8925952,.5,!0),Fe.DrawDirection(A,this._dir,8925952,.5,!0)),this._dir}randomizePosition(t,A){if(A<=0)return;const e=bd._tempVec;e.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),e.x*=A*this.scale.x,e.y*=A*this.scale.y,e.z*=A*this.scale.z,t.add(e)}randomizeDirection(t,A){if(A===0)return;const e=bd._randomQuat,i=bd._tempVec;i.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),e.setFromAxisAngle(i,A*Math.random()*Math.PI),t.applyQuaternion(e)}spherizeDirection(t,A){if(A===0)return;const e=Math.random()*Math.PI*2,i=Math.acos(1-Math.random()*2),g=Math.sin(i)*Math.cos(e),I=Math.sin(i)*Math.sin(e),o=Math.cos(i),s=new w(g,I,o);t.lerp(s,A)}randomSpherePoint(t,A,e,i,g){const I=Math.random(),o=Math.random(),s=2*Math.PI*I*(i/360),C=Math.acos(2*o-1),a=Ie.lerp(1,1-Math.pow(1-Math.random(),Math.PI),e)*A,n=t.x+this.scale.x*(-a*Math.sin(C)*Math.cos(s)),B=t.y+this.scale.y*(a*Math.sin(C)*Math.sin(s)),Q=t.z+this.scale.z*(a*Math.cos(C));g.x=n,g.y=B,g.z=Q}randomCirclePoint(t,A,e,i,g){const I=Math.random(),o=2*Math.PI*I*(i/360),s=Ie.lerp(1,1-Math.pow(1-Math.random(),Math.PI),e)*A,C=t.x+this.scale.x*s*Math.cos(o),a=t.y+this.scale.y*s*Math.sin(o),n=t.z;g.x=C,g.y=a,g.z=n}randomConePoint(t,A,e,i,g,I,o){let s=0,C=0;switch(I){case 0:s=Math.random(),C=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:s=.5,C=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let a=2*Math.PI*s*(g/360);switch(I){case 2:case 1:a+=Math.PI+.5,a+=this._loopTime*Math.PI*2,a%=Ie.toRadians(g);break}const n=Math.acos(2*C-1),B=Ie.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*e,Q=t.x+-B*Math.sin(n)*Math.cos(a),E=t.y+B*Math.sin(n)*Math.sin(a),h=t.z;o.x=Q*this.scale.x,o.y=E*this.scale.y,o.z=h*this.scale.z}},r(tS,"_randomQuat",new FA),r(tS,"_tempVec",new w),tS);let Bi=bd;gA([y()],Bi.prototype,"shapeType",2),gA([y()],Bi.prototype,"enabled",2),gA([y()],Bi.prototype,"alignToDirection",2),gA([y()],Bi.prototype,"angle",2),gA([y()],Bi.prototype,"arc",2),gA([y()],Bi.prototype,"arcSpread",2),gA([y()],Bi.prototype,"arcSpeedMultiplier",2),gA([y()],Bi.prototype,"arcMode",2),gA([y(w)],Bi.prototype,"boxThickness",2),gA([y(w)],Bi.prototype,"position",2),gA([y(w)],Bi.prototype,"rotation",2),gA([y(w)],Bi.prototype,"scale",2),gA([y()],Bi.prototype,"radius",2),gA([y()],Bi.prototype,"radiusThickness",2),gA([y()],Bi.prototype,"sphericalDirectionAmount",2),gA([y()],Bi.prototype,"randomDirectionAmount",2),gA([y()],Bi.prototype,"randomPositionAmount",2),gA([y()],Bi.prototype,"meshShapeType",2),gA([y(zl)],Bi.prototype,"meshRenderer",2);class Rt{constructor(){r(this,"damping"),r(this,"enabled"),r(this,"frequency"),r(this,"octaveCount"),r(this,"octaveMultiplier"),r(this,"octaveScale"),r(this,"positionAmount"),r(this,"quality"),r(this,"remap"),r(this,"remapEnabled"),r(this,"remapMultiplier"),r(this,"remapX"),r(this,"remapXMultiplier"),r(this,"remapY"),r(this,"remapYMultiplier"),r(this,"remapZ"),r(this,"remapZMultiplier"),r(this,"scrollSpeedMultiplier"),r(this,"separateAxes"),r(this,"strengthMultiplier"),r(this,"strengthX"),r(this,"strengthXMultiplier"),r(this,"strengthY"),r(this,"strengthYMultiplier"),r(this,"strengthZ"),r(this,"strengthZMultiplier"),r(this,"_noise"),r(this,"_time",0),r(this,"_temp",new w)}update(A){this._time+=A.time.deltaTime*this.scrollSpeedMultiplier}apply(A,e,i,g,I,o){if(!this.enabled)return;this._noise||(this._noise=ssA(()=>0));const s=this._temp.set(e.x,e.y,e.z).multiplyScalar(this.frequency),C=this._noise(s.x,s.y,s.z,this._time),a=this._noise(s.x,s.y,s.z,this._time+1e3*this.frequency),n=this._noise(s.x,s.y,s.z,this._time+2e3*this.frequency);this._temp.set(C,a,n).normalize();const B=I/o;let Q=this.positionAmount.evaluate(B);this.separateAxes?(this._temp.x*=Q*this.strengthXMultiplier,this._temp.y*=Q*this.strengthYMultiplier,this._temp.z*=Q*this.strengthZMultiplier):(this.strengthX&&(Q*=this.strengthX.evaluate(B)*1.5),this._temp.multiplyScalar(Q)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z}}gA([y()],Rt.prototype,"damping",2),gA([y()],Rt.prototype,"enabled",2),gA([y()],Rt.prototype,"frequency",2),gA([y()],Rt.prototype,"octaveCount",2),gA([y()],Rt.prototype,"octaveMultiplier",2),gA([y()],Rt.prototype,"octaveScale",2),gA([y(re)],Rt.prototype,"positionAmount",2),gA([y()],Rt.prototype,"quality",2),gA([y(re)],Rt.prototype,"remap",2),gA([y()],Rt.prototype,"remapEnabled",2),gA([y()],Rt.prototype,"remapMultiplier",2),gA([y(re)],Rt.prototype,"remapX",2),gA([y()],Rt.prototype,"remapXMultiplier",2),gA([y(re)],Rt.prototype,"remapY",2),gA([y()],Rt.prototype,"remapYMultiplier",2),gA([y(re)],Rt.prototype,"remapZ",2),gA([y()],Rt.prototype,"remapZMultiplier",2),gA([y()],Rt.prototype,"scrollSpeedMultiplier",2),gA([y()],Rt.prototype,"separateAxes",2),gA([y()],Rt.prototype,"strengthMultiplier",2),gA([y(re)],Rt.prototype,"strengthX",2),gA([y()],Rt.prototype,"strengthXMultiplier",2),gA([y(re)],Rt.prototype,"strengthY",2),gA([y()],Rt.prototype,"strengthYMultiplier",2),gA([y(re)],Rt.prototype,"strengthZ",2),gA([y()],Rt.prototype,"strengthZMultiplier",2);class gi{constructor(){r(this,"enabled"),r(this,"attachRibbonToTransform",!1),r(this,"colorOverLifetime"),r(this,"colorOverTrail"),r(this,"dieWithParticles",!0),r(this,"inheritParticleColor",!0),r(this,"lifetime"),r(this,"lifetimeMultiplier"),r(this,"minVertexDistance",.2),r(this,"mode",0),r(this,"ratio",1),r(this,"ribbonCount",1),r(this,"shadowBias",0),r(this,"sizeAffectsLifetime",!1),r(this,"sizeAffectsWidth",!1),r(this,"splitSubEmitterRibbons",!1),r(this,"textureMode",0),r(this,"widthOverTrail"),r(this,"widthOverTrailMultiplier"),r(this,"worldSpace",!1)}getWidth(A,e,i,g){const I=this.widthOverTrail.evaluate(i,g);return A*=I,A}getColor(A,e,i){const g=this.colorOverTrail.evaluate(i),I=this.colorOverLifetime.evaluate(e);A.x*=g.r*I.r,A.y*=g.g*I.g,A.z*=g.b*I.b,A.w*=g.alpha*I.alpha}}gA([y()],gi.prototype,"enabled",2),gA([y()],gi.prototype,"attachRibbonToTransform",2),gA([y(XI)],gi.prototype,"colorOverLifetime",2),gA([y(XI)],gi.prototype,"colorOverTrail",2),gA([y()],gi.prototype,"dieWithParticles",2),gA([y()],gi.prototype,"inheritParticleColor",2),gA([y(re)],gi.prototype,"lifetime",2),gA([y()],gi.prototype,"lifetimeMultiplier",2),gA([y()],gi.prototype,"minVertexDistance",2),gA([y()],gi.prototype,"mode",2),gA([y()],gi.prototype,"ratio",2),gA([y()],gi.prototype,"ribbonCount",2),gA([y()],gi.prototype,"shadowBias",2),gA([y()],gi.prototype,"sizeAffectsLifetime",2),gA([y()],gi.prototype,"sizeAffectsWidth",2),gA([y()],gi.prototype,"splitSubEmitterRibbons",2),gA([y()],gi.prototype,"textureMode",2),gA([y(re)],gi.prototype,"widthOverTrail",2),gA([y()],gi.prototype,"widthOverTrailMultiplier",2),gA([y()],gi.prototype,"worldSpace",2);class Qi{constructor(){r(this,"enabled"),r(this,"space",0),r(this,"orbitalX"),r(this,"orbitalY"),r(this,"orbitalZ"),r(this,"orbitalXMultiplier"),r(this,"orbitalYMultiplier"),r(this,"orbitalZMultiplier"),r(this,"orbitalOffsetX"),r(this,"orbitalOffsetY"),r(this,"orbitalOffsetZ"),r(this,"speedModifier"),r(this,"speedModifierMultiplier"),r(this,"x"),r(this,"xMultiplier"),r(this,"y"),r(this,"yMultiplier"),r(this,"z"),r(this,"zMultiplier"),r(this,"_system"),r(this,"_temp",new w),r(this,"_temp2",new w),r(this,"_temp3",new w),r(this,"_hasOrbital",!1),r(this,"_index",0),r(this,"_orbitalMatrix",new NA)}update(A){this._system=A}init(A){this._index==0&&(A.debug=!0),this._index+=1,A.orbitx=this.orbitalX.evaluate(Math.random()),A.orbity=this.orbitalY.evaluate(Math.random()),A.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=A.orbitx!=0||A.orbity!=0||A.orbitz!=0}apply(A,e,i,g,I,o,s){var C;if(!this.enabled)return;const a=o/s,n=this.speedModifier.evaluate(a)*this.speedModifierMultiplier,B=this.x.evaluate(a),Q=this.y.evaluate(a),E=this.z.evaluate(a);if(this._temp.set(-B,Q,E),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&((C=this._system)==null?void 0:C.worldPos)){const h=this._temp2.set(i.x,i.y,i.z),d=this.orbitalXMultiplier,u=this.orbitalYMultiplier,c=this.orbitalZMultiplier,l=n*Math.PI*2*10,p=Math.cos(l*d),D=Math.sin(l*d),S=Math.cos(l*u),k=Math.sin(l*u),f=Math.cos(l*c),U=Math.sin(l*c),M=h.x*(S*f)+h.y*(S*U)+h.z*-k,m=h.x*(D*k*f-p*U)+h.y*(D*k*U+p*f)+h.z*(D*S),x=h.x*(p*k*f+D*U)+h.y*(p*k*U-D*f)+h.z*(p*S),L=this._temp3.set(h.x-M,h.y-m,h.z-x);L.normalize(),L.multiplyScalar(.2/I*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),g.x+=L.x,g.y+=L.y,g.z+=L.z}g.x+=this._temp.x,g.y+=this._temp.y,g.z+=this._temp.z,g.x*=n,g.y*=n,g.z*=n}}gA([y()],Qi.prototype,"enabled",2),gA([y()],Qi.prototype,"space",2),gA([y(re)],Qi.prototype,"orbitalX",2),gA([y(re)],Qi.prototype,"orbitalY",2),gA([y(re)],Qi.prototype,"orbitalZ",2),gA([y()],Qi.prototype,"orbitalXMultiplier",2),gA([y()],Qi.prototype,"orbitalYMultiplier",2),gA([y()],Qi.prototype,"orbitalZMultiplier",2),gA([y()],Qi.prototype,"orbitalOffsetX",2),gA([y()],Qi.prototype,"orbitalOffsetY",2),gA([y()],Qi.prototype,"orbitalOffsetZ",2),gA([y(re)],Qi.prototype,"speedModifier",2),gA([y()],Qi.prototype,"speedModifierMultiplier",2),gA([y(re)],Qi.prototype,"x",2),gA([y()],Qi.prototype,"xMultiplier",2),gA([y(re)],Qi.prototype,"y",2),gA([y()],Qi.prototype,"yMultiplier",2),gA([y(re)],Qi.prototype,"z",2),gA([y()],Qi.prototype,"zMultiplier",2);class Hg{constructor(){r(this,"animation"),r(this,"enabled"),r(this,"cycleCount"),r(this,"frameOverTime"),r(this,"frameOverTimeMultiplier"),r(this,"numTilesX"),r(this,"numTilesY"),r(this,"startFrame"),r(this,"startFrameMultiplier"),r(this,"rowMode"),r(this,"rowIndex"),r(this,"spriteCount"),r(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(A){if(!this.sampleOnceAtStart())return this.getIndex(A)}getIndex(A){const e=this.numTilesX*this.numTilesY;A=A*this.cycleCount;let i=this.frameOverTime.evaluate(A%1);return i*=this.frameOverTimeMultiplier,i*=e,i=i%e,i=Math.floor(i),i}}gA([y()],Hg.prototype,"animation",2),gA([y()],Hg.prototype,"enabled",2),gA([y()],Hg.prototype,"cycleCount",2),gA([y(re)],Hg.prototype,"frameOverTime",2),gA([y()],Hg.prototype,"frameOverTimeMultiplier",2),gA([y()],Hg.prototype,"numTilesX",2),gA([y()],Hg.prototype,"numTilesY",2),gA([y(re)],Hg.prototype,"startFrame",2),gA([y()],Hg.prototype,"startFrameMultiplier",2),gA([y()],Hg.prototype,"rowMode",2),gA([y()],Hg.prototype,"rowIndex",2),gA([y()],Hg.prototype,"spriteCount",2),gA([y()],Hg.prototype,"timeMode",2);class gs{constructor(){r(this,"enabled"),r(this,"separateAxes"),r(this,"x"),r(this,"xMultiplier"),r(this,"y"),r(this,"yMultiplier"),r(this,"z"),r(this,"zMultiplier")}evaluate(A,e){return this.enabled?this.separateAxes?0:this.z.evaluate(A,e)*-1:0}}gA([y()],gs.prototype,"enabled",2),gA([y()],gs.prototype,"separateAxes",2),gA([y(re)],gs.prototype,"x",2),gA([y()],gs.prototype,"xMultiplier",2),gA([y(re)],gs.prototype,"y",2),gA([y()],gs.prototype,"yMultiplier",2),gA([y(re)],gs.prototype,"z",2),gA([y()],gs.prototype,"zMultiplier",2);class lo{constructor(){r(this,"enabled"),r(this,"range"),r(this,"separateAxes"),r(this,"x"),r(this,"xMultiplier"),r(this,"y"),r(this,"yMultiplier"),r(this,"z"),r(this,"zMultiplier")}evaluate(A,e){if(!this.enabled)return 0;if(!this.separateAxes){const i=Ie.lerp(this.range.x,this.range.y,e);return this.z.evaluate(i)*-1}return 0}}gA([y()],lo.prototype,"enabled",2),gA([y()],lo.prototype,"range",2),gA([y()],lo.prototype,"separateAxes",2),gA([y(re)],lo.prototype,"x",2),gA([y()],lo.prototype,"xMultiplier",2),gA([y(re)],lo.prototype,"y",2),gA([y()],lo.prototype,"yMultiplier",2),gA([y(re)],lo.prototype,"z",2),gA([y()],lo.prototype,"zMultiplier",2);class Wi{constructor(){r(this,"enabled"),r(this,"dampen"),r(this,"drag"),r(this,"dragMultiplier"),r(this,"limit"),r(this,"limitMultiplier"),r(this,"separateAxes"),r(this,"limitX"),r(this,"limitXMultiplier"),r(this,"limitY"),r(this,"limitYMultiplier"),r(this,"limitZ"),r(this,"limitZMultiplier"),r(this,"multiplyDragByParticleSize",!1),r(this,"multiplyDragByParticleVelocity",!1),r(this,"space"),r(this,"_temp",new w),r(this,"_temp2",new w)}apply(A,e,i,g,I,o,s){if(this.enabled){const C=this.limit.evaluate(I)*this.limitMultiplier;if(e.length()>C){this._temp.copy(e).normalize().multiplyScalar(C);const a=this.dampen*.5;e.x=Ie.lerp(e.x,this._temp.x,a),e.y=Ie.lerp(e.y,this._temp.y,a),e.z=Ie.lerp(e.z,this._temp.z,a),i.x=Ie.lerp(i.x,this._temp.x,a),i.y=Ie.lerp(i.y,this._temp.y,a),i.z=Ie.lerp(i.z,this._temp.z,a)}}}}gA([y()],Wi.prototype,"enabled",2),gA([y()],Wi.prototype,"dampen",2),gA([y(re)],Wi.prototype,"drag",2),gA([y()],Wi.prototype,"dragMultiplier",2),gA([y(re)],Wi.prototype,"limit",2),gA([y()],Wi.prototype,"limitMultiplier",2),gA([y()],Wi.prototype,"separateAxes",2),gA([y(re)],Wi.prototype,"limitX",2),gA([y()],Wi.prototype,"limitXMultiplier",2),gA([y(re)],Wi.prototype,"limitY",2),gA([y()],Wi.prototype,"limitYMultiplier",2),gA([y(re)],Wi.prototype,"limitZ",2),gA([y()],Wi.prototype,"limitZMultiplier",2),gA([y()],Wi.prototype,"multiplyDragByParticleSize",2),gA([y()],Wi.prototype,"multiplyDragByParticleVelocity",2),gA([y()],Wi.prototype,"space",2);const BO=class{constructor(){r(this,"enabled"),r(this,"curve"),r(this,"curveMultiplier"),r(this,"mode"),r(this,"system"),r(this,"_temp",new w),r(this,"_firstUpdate",!0),r(this,"_frames",0)}clone(){var t;const A=new BO;return A.enabled=this.enabled,A.curve=(t=this.curve)==null?void 0:t.clone(),A.curveMultiplier=this.curveMultiplier,A.mode=this.mode,A}get _lastWorldPosition(){return this.system._iv_lastWorldPosition||(this.system._iv_lastWorldPosition=new w),this.system._iv_lastWorldPosition}get _velocity(){return this.system._iv_velocity||(this.system._iv_velocity=new w),this.system._iv_velocity}awake(t){this.system=t,this.reset()}reset(){this._firstUpdate=!0}update(t){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(t){if(this.enabled&&this.system.worldspace!==!1&&this.mode===0){const A=this.curve.evaluate(Math.random(),Math.random());this._temp.copy(this._velocity).multiplyScalar(A),t.add(this._temp)}}applyCurrent(t,A,e){if(this.enabled&&this.system&&this.system.worldspace!==!1&&this.mode===1){const i=this.curve.evaluate(A,e);this._temp.copy(this._velocity).multiplyScalar(i),t.add(this._temp)}}};let tr=BO;gA([y()],tr.prototype,"enabled",2),gA([y(re)],tr.prototype,"curve",2),gA([y()],tr.prototype,"curveMultiplier",2),gA([y()],tr.prototype,"mode",2);class UI{constructor(){r(this,"enabled"),r(this,"range"),r(this,"separateAxes"),r(this,"size"),r(this,"sizeMultiplier"),r(this,"x"),r(this,"xMultiplier"),r(this,"y"),r(this,"yMultiplier"),r(this,"z"),r(this,"zMultiplier")}evaluate(A,e,i,g){const I=A.length(),o=Ie.remap(I,this.range.x,this.range.y,0,1),s=this.size.evaluate(o,i);return g*s}}gA([y()],UI.prototype,"enabled",2),gA([y(tA)],UI.prototype,"range",2),gA([y()],UI.prototype,"separateAxes",2),gA([y(re)],UI.prototype,"size",2),gA([y()],UI.prototype,"sizeMultiplier",2),gA([y(re)],UI.prototype,"x",2),gA([y()],UI.prototype,"xMultiplier",2),gA([y(re)],UI.prototype,"y",2),gA([y()],UI.prototype,"yMultiplier",2),gA([y(re)],UI.prototype,"z",2),gA([y()],UI.prototype,"zMultiplier",2);class YB{constructor(){r(this,"enabled"),r(this,"range"),r(this,"color")}evaluate(A,e,i){const g=A.length(),I=Ie.remap(g,this.range.x,this.range.y,0,1),o=this.color.evaluate(I,e);i.x*=o.r,i.y*=o.g,i.z*=o.b,i.w*=o.alpha}}gA([y()],YB.prototype,"enabled",2),gA([y(tA)],YB.prototype,"range",2),gA([y(XI)],YB.prototype,"color",2);const rsA={name:"HorizontalBlurShader",uniforms:{tDiffuse:{value:null},h:{value:1/512}},vertexShader:`
5412
+ `))}for(const M of f){const m=g.get(M);m&&U.set(M,m)}return U},Q=function(f){const U=B(f),M=s(U);return C(U,M,f)};const E=i.skinnedMesh.skeleton,h=new Array;for(const f in E.bones){const U=E.bones[f],M=E.boneInverses[f];h.push({bone:U,inverse:M})}for(const f of h_(E.bones))h.push({bone:f,inverse:f.matrixWorld.clone().invert()});const d=h[0].bone.parent;d||console.error("No bone parent found for skinned mesh during USDZ export",i.skinnedMesh),h.sort((f,U)=>LE(f.bone,d)>LE(U.bone,d)?1:-1);const u=[],c=[],l=[],p=[];for(const{bone:f}of h)u.push(f.matrix.clone()),c.push(f.position),l.push(f.quaternion),p.push(f.scale);const D=h.map(f=>'"'+LE(f.bone,d)+'"').join(", "),S=h.map(f=>xE(f.inverse.clone().invert())).join(", ");A.beginBlock('def Skeleton "Rig"'),A.appendLine(`uniform matrix4d[] bindTransforms = [${S}]`),A.appendLine(`uniform token[] joints = [${D}]`),A.appendLine('uniform token purpose = "guide"'),A.appendLine(`uniform matrix4d[] restTransforms = [${u.map(f=>xE(f)).join(", ")}]`),A.appendLine(`matrix4d xformOp:transform = ${xE(new NA)}`),A.appendLine('uniform token[] xformOpOrder = ["xformOp:transform"]');const k=Q(h.map(f=>f.bone));if(A.beginBlock('def SkelAnimation "_anim"'),A.appendLine(`uniform token[] joints = [${D}]`),A.appendLine(`quatf[] rotations = [${n(l)}]`),k&&k.quaternion){A.beginBlock("quatf[] rotations.timeSamples = {","");const f=o(k.quaternion);for(const U of f)A.appendLine(U);A.closeBlock()}if(A.appendLine(`half3[] scales = [${a(p)}]`),k&&k.scale){A.beginBlock("half3[] scales.timeSamples = {","");const f=I(k.scale);for(const U of f)A.appendLine(U);A.closeBlock()}if(A.appendLine(`float3[] translations = [${a(c)}]`),k&&k.position){A.beginBlock("float3[] translations.timeSamples = {","");const f=I(k.position);for(const U of f)A.appendLine(U);A.closeBlock()}A.closeBlock(),A.closeBlock()}}onSerialize(A,e){var i;if(!this.model)return;this.skinnedMeshExport(A,e);const g=this.object,I=this.dict.get(g);if(!I||g.isSkinnedMesh)return;YU&&console.log("SERIALIZE",this.model.name,this.object.type,I);const o=new NA;A.appendLine("matrix4d xformOp:transform.timeSamples = {"),A.indent++;const s=new Array;let C=0;for(let a=0;a<I.length;a++)s.push(C),C+=I[a].getDuration()+$o.animationDurationPadding;for(let a=0;a<I.length;a++){const n=I[a];if(!n)continue;const B=s[a];{const Q=n.getSortedTimesArray();if(!Q||Q.length===0){console.error("got an animated object but no time values?",g,n);continue}if(WE){const E=((i=n.clip)==null?void 0:i.name)??"rest",h=n.getDuration();console.log("Write .timeSamples:",E,B,h,I),A.appendLine("# "+E+": start="+(B*n.frameRate).toFixed(3)+", length="+(h*n.frameRate).toFixed(3)+", frames="+n.getFrames())}for(const{time:E,translation:h,rotation:d,scale:u}of n.getValues(Q)){o.compose(h,d,u);const c=`${(B+E)*n.frameRate}: ${xE(o)},`;A.appendLine(c)}}}A.indent--,A.appendLine("}")}}var qIA=Object.defineProperty,LIA=Object.getOwnPropertyDescriptor,P_=(t,A,e,i)=>{for(var g=i>1?void 0:i?LIA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&qIA(A,e,g),g};const j_=iA("debugpost");class Ke{constructor(A){r(this,"_active",!0),r(this,"_value"),r(this,"_valueRaw"),r(this,"_defaultValue"),r(this,"valueProcessor"),r(this,"onValueChanged"),this._value=A,this._defaultValue=A,this._valueRaw=A}get overrideState(){return this._active}set overrideState(A){if(this._active===A)return;this._active=A;const e=A?this._valueRaw:this._defaultValue;this.processValue(e,!0)}get value(){return this._valueRaw}set value(A){this.processValue(A,!1)}set defaultValue(A){this._defaultValue=A}__init(){this.processValue(this._valueRaw,!0)}processValue(A,e){if(A==null||!e&&this.testIfValueChanged(A)===!1)return;const i=this._value;j_&&console.log("VolumeParameter: value changed from",i,"to",A),!this._active&&this._defaultValue!==void 0?(this._value=this._defaultValue,A=this._defaultValue,this._valueRaw=A):(this._valueRaw=A,this._active&&this.valueProcessor&&(A=this.valueProcessor(A)),this._value=A),this.onValueChanged?this.onValueChanged(A,i,this):j_&&console.log("VolumeParameter: onValueChanged not set")}testIfValueChanged(A){return this._valueRaw!==A}}P_([y()],Ke.prototype,"overrideState",1),P_([y()],Ke.prototype,"value",1);var xIA=Object.defineProperty,YIA=Object.getOwnPropertyDescriptor,TIA=(t,A,e,i)=>{for(var g=i>1?void 0:i?YIA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&xIA(A,e,g),g};const HIA=iA("debugpost");class rI extends JA{constructor(A=void 0){if(super(),r(this,"active",!0),r(this,"_result"),r(this,"_didCreateVolumeParameters",!1),A){this.ensureVolumeParameters();for(const e of Object.keys(A)){const i=A[e],g=this[e];g instanceof Ke&&(g.value=i)}}}onEnable(){this.__internalDidAwakeAndStart&&(this.active=!0)}onDisable(){this.active=!1}init(){}apply(){var A;return this.ensureVolumeParameters(),this._result||(this._result=(A=this.onCreateEffect)==null?void 0:A.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){HIA&&console.warn("DISPOSE",this),this._result&&(Array.isArray(this._result)?this._result.forEach(A=>A.dispose()):this._result.dispose()),this._result=void 0}initParameters(){const A=Object.keys(this);for(const e of A){const i=this[e];i instanceof Ke&&i.__init()}}onAfterDeserialize(A,e){if(typeof A=="object"){const i=this.$serializedTypes;if(i){for(const g of Object.keys(i))if(i[g]===Ke){const I=A[g];if(I!==void 0){const o=this[g];o.value=I}}}}}onEditorModification(A){const e=A.propertyName;if(this[e]instanceof Ke){const i=A.value;return this[e].value=i,!0}}ensureVolumeParameters(){if(this._didCreateVolumeParameters)return;this._didCreateVolumeParameters=!0;const A=this.$serializedTypes;if(A)for(const e of Object.keys(A))A[e]===Ke&&(this[e]||(this[e]=new Ke))}}TIA([y()],rI.prototype,"active",2);var _IA=Object.defineProperty,OIA=Object.getOwnPropertyDescriptor,PIA=(t,A,e,i)=>{for(var g=i>1?void 0:i?OIA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&_IA(A,e,g),g};const jIA=iA("debugpost"),TU={};function As(t,A){TU[t]=A}function WIA(t){return t.__type in TU?TU[t.__type]:(jIA&&t.__type&&console.warn("Unknown postprocessing type",t.__type,t),rI)}class hd{constructor(){r(this,"components",[])}init(){var A;(A=this.components)==null||A.forEach(e=>e.init())}}PIA([RE([t=>WIA(t),rI])],hd.prototype,"components",2);var VIA=Object.defineProperty,ZIA=Object.getOwnPropertyDescriptor,zIA=(t,A,e,i)=>{for(var g=i>1?void 0:i?ZIA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&VIA(A,e,g),g};class cd extends rI{constructor(){super(...arguments),r(this,"preset")}get typeName(){return"Antialiasing"}onCreateEffect(){const A=new WX({preset:aE.HIGH,edgeDetectionMode:pG.DEPTH});return this.preset.onValueChanged=e=>{A.applyPreset(e)},A}}zIA([y(Ke)],cd.prototype,"preset",2),As("Antialiasing",cd);class bw{constructor(){r(this,"files",[])}get extensionName(){return"Audio"}onExportObject(A,e,i){const g=aA.getComponents(A,fi);if(g.length)for(const I of g){if(!I.clip||typeof I.clip!="string"||!I.playOnAwake)continue;const o=I.clip.split("/").pop();this.files.includes(I.clip)||this.files.push(I.clip),e.addEventListener("serialize",(s,C)=>{s.appendLine(),s.beginBlock(`def SpatialAudio "${e.name}"`),s.appendLine(`uniform asset filePath = @audio/${o}@`),s.appendLine(`uniform token auralMode = "${I.spatialBlend>0?"spatial":"nonSpatial"}"`),s.appendLine(`uniform token playbackMode = "${I.loop?"loopFromStage":"onceFromStart"}"`),s.appendLine(`uniform float gain = ${I.volume}`),s.closeBlock()})}}async onAfterSerialize(A){for(const e of this.files){const i=e.split("/").pop(),g=await(await(await fetch(e)).blob()).arrayBuffer(),I=new Uint8Array(g);A.files["audio/"+i]=I}}}const MB=iA("debugautosync"),HU=Symbol("syncerId");class XIA{constructor(){r(this,"_syncers",{})}getOrCreateSyncer(A){if(!A.guid)return null;if(this._syncers[A.guid])return this._syncers[A.guid];const e=new $IA(A);return e[HU]=A.guid,this._syncers[e[HU]]=e,e}removeSyncer(A){delete this._syncers[A[HU]]}}const _U=new XIA;class $IA{constructor(A){r(this,"comp"),r(this,"hasChanges",!1),r(this,"changedProperties",{}),r(this,"data",{}),r(this,"_boundEvent"),r(this,"_handleReceivingMethod"),r(this,"_isReceiving",!1),r(this,"_isInit",!1),this.comp=A}get networkingKey(){return this.comp.guid}init(A){if(this._isInit)return;this._isInit=!0,this.comp=A,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 e=this.comp.context.connection.tryGetState(this.comp.guid);e&&this.onHandleReceiving(e)}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(A,e){this._isReceiving||(MB&&console.log("Property changed: "+A,e),this.hasChanges=!0,this.changedProperties[A]=e)}onHandleSending(){if(!this.hasChanges)return;this.hasChanges=!1;const A=this.comp.context.connection;if(!A||!A.isConnected){for(const e in this.changedProperties)delete this.changedProperties[e];return}for(const e in this.data)delete this.data[e];this.data.guid=this.comp.guid;for(const e in this.changedProperties){const i=this.changedProperties[e];delete this.changedProperties[e],this.data[e]=i}A.send(this.networkingKey,this.data)}onHandleReceiving(A){if(MB&&console.log("RECEIVE",this.comp.name,this.comp.guid,A),!this._isInit||!this.comp)return;const e=A.guid;if(!(e&&e!==this.comp.guid)){MB&&console.log("RECEIVED",this.comp.name,this.comp.guid,A);try{this._isReceiving=!0;for(const i in A){if(i==="guid")continue;const g=A[i];this.comp[i]=g,MB&&console.log("SET",i,g)}}catch(i){console.error(i)}finally{this._isReceiving=!1}}}}function AoA(t,A){let e=A!==t;return!e&&t&&A&&(Array.isArray(t)&&Array.isArray(A)||typeof t=="object"&&typeof A=="object")&&(e=!0),e}const ld=Symbol("AutoSyncHandler");function eoA(t){if(t[ld])return t[ld];const A=_U.getOrCreateSyncer(t);return A?.init(t),t[ld]=A,A}function toA(t){const A=t[ld];A&&(_U.removeSyncer(A),A.destroy(),delete t[ld])}const OU=function(t){return function(A,e){var i;let g="";typeof e=="string"?g=e:g=e.name;let I=null,o;typeof t=="string"?o=A[t]:typeof t=="function"&&(o=t);const s=A,C=s.__internalAwake;if(typeof C!="function"){(MB||Se())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+((i=A?.constructor)==null?void 0:i.name)+'" is not supported',A);return}MB&&console.log(g);const a=Symbol(g);s.__internalAwake=function(){if(this[a]!==void 0)return;this[a]=this[g],I=_U.getOrCreateSyncer(this);const B=Object.getOwnPropertyDescriptor(this,g);if(B?.set===void 0){let Q=!1;Object.defineProperty(this,g,{set:function(E){var h;const d=this[a];if(this[a]=E,Q){Se()&&console.warn("Recursive call detected",g);return}Q=!0;try{const u=AoA(E,d);MB&&console.log("SyncField assignment",g,"changed?",u,E),u&&o?.call(this,E,d)!==!1&&((h=eoA(this))==null||h.notifyChanged(g,E))}finally{Q=!1}},get:function(){return this[a]},configurable:!0,enumerable:!0})}I?.init(this),C.call(this)};const n=s.__internalDestroy;s.__internalDestroy=function(){toA(this),n.call(this)}}};var ioA=Object.defineProperty,goA=Object.getOwnPropertyDescriptor,qw=(t,A,e,i)=>{for(var g=i>1?void 0:i?goA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&ioA(A,e,g),g};const es=iA("debugplayersync");class VE extends JA{constructor(){super(...arguments),r(this,"autoSync",!0),r(this,"asset"),r(this,"onPlayerSpawned"),r(this,"_localInstance"),r(this,"onJoinedRoom",()=>{es&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()})}awake(){this.watchTabVisible(),this.onPlayerSpawned||(this.onPlayerSpawned=new Eg)}onEnable(){this.context.connection.beginListen(ht.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(ht.JoinedRoom,this.onJoinedRoom),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(ht.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(ht.JoinedRoom,this.onJoinedRoom)}async getInstance(){var A,e,i,g,I,o;if(this._localInstance)return this._localInstance;if(es&&console.log("PlayerSync.createInstance",(A=this.asset)==null?void 0:A.uri),!((e=this.asset)!=null&&e.asset)&&!((i=this.asset)!=null&&i.uri))return console.error('PlayerSync: can not create an instance because "asset" is not set!'),null;this._localInstance=(g=this.asset)==null?void 0:g.instantiateSynced({parent:this.gameObject},!0);const s=await this._localInstance;if(s){const C=aA.getComponent(s,ts);C?(C.owner=this.context.connection.connectionId,(I=this.onPlayerSpawned)==null||I.invoke(s)):(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!"),aA.destroySynced(s))}else this._localInstance=void 0,console.warn("PlayerSync: failed instantiating asset!");return this._localInstance}destroyInstance(){var A;(A=this._localInstance)==null||A.then(e=>(es&&console.log("PlayerSync.destroyInstance",e),aA.destroySynced(e))),this._localInstance=void 0}watchTabVisible(){window.addEventListener("visibilitychange",A=>{if(document.visibilityState==="visible")for(let e=ts.all.length-1;e>=0;e--){const i=ts.all[e];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}}qw([y()],VE.prototype,"autoSync",2),qw([y(Ct)],VE.prototype,"asset",2),qw([y(Eg)],VE.prototype,"onPlayerSpawned",2);var W_=(t=>(t.OwnerChanged="ownerChanged",t))(W_||{}),dd;const qg=(dd=class extends JA{constructor(){super(...arguments),r(this,"onOwnerChangeEvent",new Eg),r(this,"onFirstOwnerChangeEvent",new Eg),r(this,"hasOwner",!1),r(this,"owner"),r(this,"dontDestroy",!1),r(this,"onUserLeftRoom",t=>{if(t.userId===this.owner){es&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}})}static get all(){return qg._all}static get local(){return qg._local}static getFor(t){if(t instanceof wA)return aA.getComponentInParent(t,qg);if(t instanceof JA)return aA.getComponentInParent(t.gameObject,qg)}static isLocalPlayer(t){const A=qg.getFor(t);return A?.isLocalPlayer??!1}static addEventListener(t,A){return this._callbacks[t]||(this._callbacks[t]=[]),this._callbacks[t].push(A),A}static removeEventListener(t,A){if(!this._callbacks[t])return;const e=this._callbacks[t].indexOf(A);e>=0&&this._callbacks[t].splice(e,1)}static dispatchEvent(t,A){if(this._callbacks[t])for(const e of this._callbacks[t])e(A)}get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(t,A){var e,i;es&&console.log("PlayerSync.onOwnerChange",this,"newOwner",t,"oldOwner",A);const g=qg._local.indexOf(this);g>=0&&qg._local.splice(g,1);const I={playerState:this,oldValue:A,newValue:t};if(this.hasOwner||(this.hasOwner=!0,(e=this.onFirstOwnerChangeEvent)==null||e.invoke(I)),(i=this.onOwnerChangeEvent)==null||i.invoke(I),this.owner===this.context.connection.connectionId){qg._local.push(this);const s=new CustomEvent("local-owner-changed",{detail:I});this.dispatchEvent(s)}const o=new CustomEvent("owner-changed",{detail:I});this.dispatchEvent(o),qg.dispatchEvent("ownerChanged",o)}awake(){qg.all.push(this),es&&console.log("Registered new PlayerState",this.guid,qg.all.length-1,qg.all),this.context.connection.beginListen(ht.UserLeftRoom,this.onUserLeftRoom)}async start(){es&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await Jo(300),this.context.connection.userIsInRoom(this.owner)==!1&&(es&&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||(es&&console.warn("PlayerState.start \u2192 owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?es&&console.warn("PlayerState.start \u2192 owner is still undefined but dontDestroy is set to true",this.name):(es&&console.warn(`PlayerState.start \u2192 owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):console.log("PlayerState.start \u2192 owner is assigned",this.owner)},2e3))}doDestroy(){es&&console.log("PlayerSync.doDestroy \u2192 syncDestroy",this.name),jy(this.gameObject,this.context.connection)}onDestroy(){if(this.context.connection.stopListen(ht.UserLeftRoom,this.onUserLeftRoom),qg.all.splice(qg.all.indexOf(this),1),this.isLocalPlayer){const t=qg._local.indexOf(this);t>=0&&qg._local.splice(t,1)}}},r(dd,"_all",[]),r(dd,"_local",[]),r(dd,"_callbacks",{}),dd);let ts=qg;qw([OU(ts.prototype.onOwnerChange)],ts.prototype,"owner",2);const IoA=iA("debugavatar"),EC=class extends JA{constructor(){super(...arguments),r(this,"connectionId"),r(this,"avatar")}static getAvatar(t){return t>=0&&t<EC.instances.length?EC.instances[t]:null}static onAvatarMarkerCreated(t){return EC._onNewAvatarMarkerAdded.push(t),t}static onAvatarMarkerDestroyed(t){return EC._onAvatarMarkerDestroyed.push(t),t}awake(){EC.instances.push(this),IoA&&console.log(this);for(const t of EC._onNewAvatarMarkerAdded)t({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){EC.instances.splice(EC.instances.indexOf(this),1);for(const t of EC._onAvatarMarkerDestroyed)t({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}};let Lg=EC;r(Lg,"instances",[]),r(Lg,"_onNewAvatarMarkerAdded",[]),r(Lg,"_onAvatarMarkerDestroyed",[]);var ooA=Object.defineProperty,soA=Object.getOwnPropertyDescriptor,CoA=(t,A,e,i)=>{for(var g=i>1?void 0:i?soA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&ooA(A,e,g),g};const ZE=iA("debugxrflags"),V_=iA("disablexrflags");V_&&console.warn("XRFlags are disabled");var hC=(t=>(t[t.Never=0]="Never",t[t.Browser=1]="Browser",t[t.AR=2]="AR",t[t.VR=4]="VR",t[t.FirstPerson=8]="FirstPerson",t[t.ThirdPerson=16]="ThirdPerson",t[t.All=4294967295]="All",t))(hC||{});const Z_=class{constructor(){r(this,"Mask",17)}Has(t){return(this.Mask&t)!==0}Set(t){ZE&&console.warn("Set XR flag state to",t),this.Mask=t,Eo.Apply()}Enable(t){this.Mask|=t,Eo.Apply()}Disable(t){this.Mask&=~t,Eo.Apply()}Toggle(t){this.Mask^=t,Eo.Apply()}EnableAll(){this.Mask=-1,Eo.Apply()}DisableAll(){this.Mask=0,Eo.Apply()}};let MI=Z_;r(MI,"Global",new Z_);var ud;const Ra=(ud=class extends JA{constructor(){super(...arguments),r(this,"visibleIn")}static Apply(){for(const t of this.registry)t.UpdateVisible(MI.Global)}awake(){Ra.registry.push(this)}onEnable(){Ra.firstApply?this.UpdateVisible(MI.Global):(Ra.firstApply=!0,Ra.Apply())}onDestroy(){const t=Ra.registry.indexOf(this);t>=0&&Ra.registry.splice(t,1)}get isOn(){return this.gameObject.visible}UpdateVisible(t=null){if(V_)return;let A;const e=t;if(e&&typeof e=="number"&&(console.assert(typeof e=="number","XRFlag.UpdateVisible: state must be a number",e),ZE&&console.log(e),Ra.buffer.Mask=e,t=Ra.buffer),t instanceof MI?(ZE&&console.warn(this.name,"use passed in mask",t.Mask,this.visibleIn),A=t.Has(this.visibleIn)):(ZE&&console.log(this.name,"use global mask"),MI.Global.Has(this.visibleIn)),A!==void 0)if(A)ZE&&console.log(this.name,"is visible",this.gameObject.uuid),aA.setActive(this.gameObject,!0);else{if(ZE&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},r(ud,"registry",[]),r(ud,"firstApply"),r(ud,"buffer",new MI),ud);let Eo=Ra;CoA([y()],Eo.prototype,"visibleIn",2);var aoA=Object.defineProperty,noA=Object.getOwnPropertyDescriptor,PU=(t,A,e,i)=>{for(var g=i>1?void 0:i?noA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&aoA(A,e,g),g};const pd=iA("debugwebxr"),z_=new FA().setFromAxisAngle(new w(0,1,0),Math.PI);class RB extends JA{constructor(){super(...arguments),r(this,"head"),r(this,"leftHand"),r(this,"rightHand"),r(this,"_syncTransforms")}async onEnterXR(A){if(!this.activeAndEnabled)return;pd&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const e=ts.getFor(this);if(e!=null&&e.owner){const i=this.gameObject.addNewComponent(Lg);i.avatar=this.gameObject,i.connectionId=e.owner}else this.context.connection.isConnected?console.error("No player state found for avatar",this):e&&!this.context.connection.isConnected&&(e.dontDestroy=!0)}onLeaveXR(A){const e=this.gameObject.getComponent(Lg);e&&e.destroy()}onUpdateXR(A){var e,i;if(!this.activeAndEnabled)return;const g=ts.isLocalPlayer(this);if(!g)return;const I=A.xr;if(I.rig&&I.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),I.rig.gameObject.add(this.gameObject)),this._syncTransforms&&g)for(const a of this._syncTransforms)a.fastMode=!0,a.isOwned()||a.requestOwnership();if(this.head&&this.context.mainCamera){const a=this.head.asset;if(a.position.copy(this.context.mainCamera.position),a.quaternion.copy(this.context.mainCamera.quaternion),a.quaternion.x*=-1,this.context.time.frameCount%10===0){const n=aA.getComponentsInChildren(this.head.asset,Eo);for(const B of n)B.enabled=!1,B.gameObject.visible=!1}}const o=A.xr.leftController,s=(e=this.leftHand)==null?void 0:e.asset;o&&s&&(s.position.copy(o.gripPosition),s.quaternion.copy(o.gripQuaternion),s.quaternion.multiply(z_),s.visible=o.isTracking);const C=A.xr.rightController;if(C&&(i=this.rightHand)!=null&&i.asset){const a=this.rightHand.asset;a.position.copy(C.gripPosition),a.quaternion.copy(C.gripQuaternion),a.quaternion.multiply(z_),a.visible=C.isTracking}}onBeforeRender(){this.context.time.frame%10===0&&this.updateRemoteAvatarVisibility()}updateRemoteAvatarVisibility(){var A,e,i;if(this.context.connection.isConnected){const g=ts.getFor(this);if(g&&g.isLocalPlayer==!1){const I=de.getXRSync(this.context);if(I&&I.hasState(g.owner)){this.tryFindAvatarObjectsIfMissing();const o=(A=this.leftHand)==null?void 0:A.asset;o&&(o.visible=I?.isTracking(g.owner,"left")??!1);const s=(e=this.rightHand)==null?void 0:e.asset;s&&(s.visible=I?.isTracking(g.owner,"right")??!1)}if((i=this.head)!=null&&i.asset){const o=aA.getComponentsInChildren(this.head.asset,Eo);for(const s of o)s.enabled=!1,s.gameObject.visible=!0}}}}tryFindAvatarObjectsIfMissing(){if(!this.head||!this.leftHand||!this.rightHand){const A={head:this.head,leftHand:this.leftHand,rightHand:this.rightHand};UH.tryFindAvatarObjects(this.gameObject,this.sourceId||"",A),A.head&&(this.head=A.head),A.leftHand&&(this.leftHand=A.leftHand),A.rightHand&&(this.rightHand=A.rightHand)}}async prepareAvatar(){if(this.tryFindAvatarObjectsIfMissing(),this.head)this.head instanceof wA&&(this.head=new Ct("",this.sourceId,this.head));else{const A=new wA;A.name="Head";const e=DE.createPrimitive(EB.Cube);A.add(e),this.gameObject.add(A),this.head=new Ct("",this.sourceId,A),pd&&console.log("Create head",A)}if(this.rightHand)this.rightHand instanceof wA&&(this.rightHand=new Ct("",this.sourceId,this.rightHand));else{const A=new wA;A.name="Right Hand",this.gameObject.add(A),this.rightHand=new Ct("",this.sourceId,A),pd&&console.log("Create right hand",A)}if(this.leftHand)this.leftHand instanceof wA&&(this.leftHand=new Ct("",this.sourceId,this.leftHand));else{const A=new wA;A.name="Left Hand",this.gameObject.add(A),this.leftHand=new Ct("",this.sourceId,A),pd&&console.log("Create left hand",A)}await this.loadAvatarObjects(this.head,this.leftHand,this.rightHand),ts.isLocalPlayer(this.gameObject)&&(this._syncTransforms=aA.getComponentsInChildren(this.gameObject,Hn))}async loadAvatarObjects(A,e,i){const g=A.loadAssetAsync(),I=e.loadAssetAsync(),o=i.loadAssetAsync(),s=new Array;g&&s.push(g),I&&s.push(I),o&&s.push(o);const C=await Yc(s);pd&&console.log("Avatar loaded results:",C)}}PU([y(Ct)],RB.prototype,"head",2),PU([y(Ct)],RB.prototype,"leftHand",2),PU([y(Ct)],RB.prototype,"rightHand",2);class cC{static Add(A,e,i=null){if(e){for(const g of this.Pois)if(g.obj===e)return;this.Pois.push({obj:e,avatar:i}),this.LastChangeTime=A.time.time}}static Remove(A,e){var i;if(e){for(const g of this.Pois)if(g.obj===e){this.Pois.splice(this.Pois.indexOf(g),1),this.LastChangeTime=A?.time.time??((i=ve.Current)==null?void 0:i.time.time);return}}}}r(cC,"Pois",[]),r(cC,"LastChangeTime",0);class roA{constructor(){r(this,"guid"),r(this,"position",new w)}}class Dd extends JA{constructor(){super(...arguments),r(this,"target",null),r(this,"avatar",null),r(this,"_model",null),r(this,"_targetModel",new roA),r(this,"_currentTargetObject",null),r(this,"_lastUpdateTime",0),r(this,"_lookDuration",0),r(this,"_lastPoiChangedTime",0)}set controlledTarget(A){this.target=A;const e=z.get("MoveRandom");if(e&&this.target){const i=aA.getComponent(this.target,e);i&&i.destroy()}}awake(){if(this.avatar=aA.getComponentInParent(this.gameObject,Lg),this.avatar){const A=aA.getComponentInParent(this.gameObject,Lg);this._model=new pM(this.context.connection,this.guid),A!=null&&A.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",A=>{var e;this.target&&A&&A.guid===((e=this.avatar)==null?void 0:e.guid)&&CI(this.target,A.position)})}update(){var A;if((!this.context.connection.isConnected||(A=this._model)!=null&&A.hasOwnership)&&(cC.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=cC.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){const e=Ne(this._currentTargetObject);CI(this.target,e),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(e))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;const A=cC.Pois;if(A.length>0){const e=A[Math.floor(Math.random()*A.length)];if(e&&e.obj){if(e.avatar&&e.avatar===this.avatar)return;this._currentTargetObject=e.obj}}}}}const zE=iA("debugnetworkingstreams");var lC=(t=>(t.Connected="peer-user-connected",t.StreamReceived="receive-stream",t.StreamEnded="call-ended",t.Disconnected="peer-user-disconnected",t.UserJoined="user-joined",t))(lC||{});class X_{constructor(A,e){r(this,"type","call-ended"),r(this,"userId"),r(this,"direction"),this.userId=A,this.direction=e}}class $_{constructor(A,e){r(this,"type","receive-stream"),r(this,"stream"),r(this,"target"),this.stream=A,this.target=e}}class BoA{constructor(A,e){r(this,"guid"),r(this,"peerId"),r(this,"dontSave",!0),this.guid=A.id,this.peerId=e}}var AO=(t=>(t.Incoming="incoming",t.Outgoing="outgoing",t))(AO||{});class QoA extends ng{constructor(A,e,i){super(),r(this,"userId"),r(this,"direction"),r(this,"call"),r(this,"_stream",null),r(this,"_isDisposed",!1),this.userId=A,this.call=e,this.direction=i,this._stream=null,e.on("stream",g=>{if(zE&&console.log("Receive video",g.getAudioTracks(),g.getVideoTracks()),this._stream=g,i==="incoming"){const I=new $_(g,this);this.dispatchEvent(I)}}),e.on("close",()=>{this.dispatchEvent(new X_(A,i))})}get stream(){return this._stream}close(){this._isDisposed||(this._isDisposed=!0,this.call.close(),Ua(this._stream))}get isOpen(){var A;return((A=this.call.peerConnection)==null?void 0:A.connectionState)==="connected"}get isOpening(){var A;return((A=this.call.peerConnection)==null?void 0:A.connectionState)==="connecting"}get isClosed(){return!this.isOpen}}const yd=class extends ng{constructor(t,A){super(),r(this,"id"),r(this,"context"),r(this,"_peer"),r(this,"_incomingCalls",[]),r(this,"_outgoingCalls",[]),r(this,"_enabled",!1),r(this,"_enabledPeer",!1),r(this,"onConnectRoomFn",this.onConnectRoom.bind(this)),r(this,"onPeerConnectFn",this.onPeerConnect.bind(this)),r(this,"onPeerReceiveCallFn",this.onPeerReceivingCall.bind(this)),this.context=t,this.id=A,this.setupPeer(),navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia}static getOrCreate(t,A){if(yd.instances.has(A))return yd.instances.get(A);const e=new yd(t,A);return yd.instances.set(A,e),e}getMyPeerId(){if(this.context.connection.connectionId)return this.getPeerIdFromUserId(this.context.connection.connectionId)}getPeerIdFromUserId(t){return this.id+"-"+t}getUserIdFromPeerId(t){return t.substring(this.id.length+1)}makeCall(t,A){var e;const i={metadata:{userId:this.context.connection.connectionId}},g=(e=this._peer)==null?void 0:e.call(t,A,i);if(g)return this.registerCall(g,"outgoing")}get peer(){return this._peer}enable(){this._enabled||(this._enabled=!0,this.context.connection.beginListen(ht.JoinedRoom,this.onConnectRoomFn),this.subscribePeerEvents())}disable(){this._enabled&&(this._enabled=!1,this.context.connection.stopListen(ht.JoinedRoom,this.onConnectRoomFn),this.unsubscribePeerEvents())}onConnectRoom(){this.setupPeer()}setupPeer(){if(this.context.connection.connectionId&&!this._enabledPeer){if(this._enabledPeer=!0,!this._peer){const t=this.getMyPeerId();t?this._peer=GY(t):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(t){zE&&console.log("Peer connected as",t),this.context.connection.send("peer-user-connected",new BoA(this,t))}onPeerReceivingCall(t){t.answer(),this.registerCall(t,"incoming")}registerCall(t,A){const e=t.metadata;(!e||!e.userId)&&console.error("Missing call metadata",t);const i=e.userId;A==="incoming"&&zE?console.log("Receive call from",t.metadata):zE&&console.log("Make call to",t.metadata);const g=A==="incoming"?this._incomingCalls:this._outgoingCalls,I=new QoA(i,t,A);return g.push(I),t.on("error",o=>{console.error("Call error",o)}),t.on("close",()=>{zE&&console.log("Call ended",t.metadata),t.close();const o=g.indexOf(I);o!==-1&&g.splice(o,1)}),I.addEventListener("call-ended",o=>{this.dispatchEvent(o)}),A==="incoming"&&(I.addEventListener("receive-stream",o=>{this.dispatchEvent(o)}),t.on("stream",()=>{let o=0;const s=setInterval(()=>{const C=o===0;!I.isOpen&&C&&(o+=1,clearInterval(s),I.close())},2e3)})),I}};let Lw=yd;r(Lw,"instances",new Map);class vu extends ng{constructor(A,e){super(),r(this,"context"),r(this,"peer"),r(this,"_sendingStreams",new Map),r(this,"debug",!1),r(this,"onJoinedRoom",i=>{this.debug&&console.log(`${i.userId} joined room and I'm currently sending ${this._sendingStreams.size} streams`),this._sendingStreams.size>0&&this.updateSendingCalls()}),r(this,"onReceiveStream",i=>{this.debug&&console.log("RECEIVE STREAM",i),this.dispatchEvent({type:"receive-stream",target:this,stream:i.stream,userId:i.userId})}),r(this,"onCallEnded",i=>{this.dispatchEvent(i)}),r(this,"onUserConnected",i=>{if(this.peer.id===i.guid){this.debug&&console.log("USER CONNECTED",i.guid,i);const g=this._sendingStreams.keys().next().value;this.peer.makeCall(i.peerId,g)}}),r(this,"onUserLeft",i=>{this.stopCallsToUsersThatAreNotInTheRoomAnymore()}),this.context=A,this.peer=e,zE&&(this.debug=!0)}static create(A){const e=Lw.getOrCreate(A.context,A.context.connection.connectionId);return new vu(A.context,e)}startSendingStream(A){this._sendingStreams.has(A)?console.warn("Received start sending stream with stream that is already being sent"):(this._sendingStreams.set(A,[]),this.updateSendingCalls())}stopSendingStream(A){if(A){const e=this._sendingStreams.get(A);if(e){this.debug&&console.log("Closing calls",e);for(const i of e)i.close()}this._sendingStreams.delete(A),e&&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(ht.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ht.UserJoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ht.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(ht.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ht.UserJoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ht.UserLeftRoom,this.onUserLeft)}updateSendingCalls(){var A;let e=!1;const i=this.context.connection.connectionId;for(const g of this._sendingStreams.keys()){const I=this._sendingStreams.get(g)||[];for(const o of this.context.connection.usersInRoom()){if(o===i)continue;const s=I.find(C=>C.userId===o);if(!s||((A=s.stream)==null?void 0:A.active)===!1){this.debug&&console.log("Starting call to",o,i);const C=this.peer.makeCall(this.peer.getPeerIdFromUserId(o),g);C&&(e=!0,I.push(C))}}this._sendingStreams.set(g,I)}this.stopCallsToUsersThatAreNotInTheRoomAnymore(),e&&this.debug&&console.log("Currently sending",this._sendingStreams)}stopCallsToUsersThatAreNotInTheRoomAnymore(){for(const A of this._sendingStreams.keys()){const e=this._sendingStreams.get(A);if(e)for(let i=e.length-1;i>=0;i--){const g=e[i];this.context.connection.userIsInRoom(g.userId)||(g.close(),e.splice(i,1))}}}}function Ua(t){if(t&&t instanceof MediaStream)for(const A of t.getTracks())A.stop()}var EoA=Object.defineProperty,hoA=Object.getOwnPropertyDescriptor,eO=(t,A,e,i)=>{for(var g=i>1?void 0:i?hoA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&EoA(A,e,g),g};const coA="noVoip",loA=iA("debugvoip");class UB extends JA{constructor(){super(...arguments),r(this,"autoConnect",!1),r(this,"runInBackground",!0),r(this,"debug",!1),r(this,"_net"),r(this,"_outputStream",null),r(this,"onJoinedRoom",async()=>{await Jo(300),this.autoConnect&&!this.isSending&&this.connect()}),r(this,"_incomingStreams",new Map),r(this,"onReceiveStream",A=>{const e=A.target.userId,i=A.stream,g=this._incomingStreams.get(e);if(g)g.srcObject=i,g.setAttribute("autoplay","true");else{const I=new Audio;this._incomingStreams.set(e,I),I.setAttribute("autoplay","true"),I.srcObject=i}}),r(this,"onStreamEnded",A=>{const e=this._incomingStreams.get(A.userId);Ua(e?.srcObject),this._incomingStreams.delete(A.userId)}),r(this,"onEnabledChanged",()=>{for(const A of this._incomingStreams){const e=A[1];e.muted=!this.enabled}}),r(this,"onVisibilityChanged",()=>{if(this.runInBackground)return;const A=document.visibilityState!=="visible";this.setMuted(A);for(const e of this._incomingStreams){const i=e[1];i.muted=A}})}awake(){loA&&(this.debug=!0),this.debug&&window.addEventListener("keydown",async A=>{A.key==="v"&&(console.log("MUTE?",!this.isMuted),this.setMuted(!this.isMuted))})}onEnable(){this._net||(this._net=vu.create(this)),this._net.addEventListener(lC.StreamReceived,this.onReceiveStream),this._net.addEventListener(lC.StreamEnded,this.onStreamEnded),this._net.enable(),this.autoConnect&&(this.context.connection.isConnected?this.connect():this.context.connection.beginListen(ht.JoinedRoom,this.onJoinedRoom)),this.onEnabledChanged(),window.addEventListener("visibilitychange",this.onVisibilityChanged)}onDisable(){var A;this._net.stopSendingStream(this._outputStream),this._net.removeEventListener(lC.StreamReceived,this.onReceiveStream),this._net.removeEventListener(lC.StreamEnded,this.onStreamEnded),(A=this._net)==null||A.disable(),this.context.connection.stopListen(ht.JoinedRoom,this.onJoinedRoom),this.onEnabledChanged(),window.removeEventListener("visibilitychange",this.onVisibilityChanged)}get isSending(){return this._outputStream!=null&&this._outputStream.active}async connect(A){if(this.context.connection.isConnected){if(!await Ok())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),Ua(this._outputStream),this._outputStream=await this.getAudioStream(A),this._outputStream?(this._net.startSendingStream(this._outputStream),!0):(await Ok()?console.error("VOIP: Could not get audio stream - please make sure to connect an audio device and grant microphone permissions"):qq("Microphone permissions not granted: Please grant microphone permissions to use voice chat"),!1)}disconnect(){this._net.stopSendingStream(this._outputStream),Ua(this._outputStream),this._outputStream=null}setMuted(A){var e;const i=(e=this._outputStream)==null?void 0:e.getAudioTracks();if(i)for(const g of i)g.enabled=!A}get isMuted(){var A;if(this._outputStream===null)return!1;const e=(A=this._outputStream)==null?void 0:A.getAudioTracks();if(e){for(const i of e)if(!i.enabled)return!0}return!1}getFrequency(A){return this.unsupported_getfrequency||(this.unsupported_getfrequency=!0,Se()&&Ci("VOIP: getFrequency is currently not supported"),console.warn("VOIP: getFrequency is currently not supported")),null}async getAudioStream(A){return navigator.mediaDevices.getUserMedia?await navigator.mediaDevices.getUserMedia({audio:A??!0,video:!1}).catch(e=>(console.warn("VOIP failed getting audio stream",e),null)):(console.error("No getDisplayMedia support"),null)}}eO([y()],UB.prototype,"autoConnect",2),eO([y()],UB.prototype,"runInBackground",2);var doA=Object.defineProperty,uoA=Object.getOwnPropertyDescriptor,tO=(t,A,e,i)=>{for(var g=i>1?void 0:i?uoA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&doA(A,e,g),g};const poA=iA("debugmouth");class wd extends JA{constructor(){super(...arguments),r(this,"idle",[]),r(this,"talking",[]),r(this,"marker",null),r(this,"voip",null),r(this,"lastMouthChangeTime",0),r(this,"mouthChangeLength",0)}awake(){setTimeout(()=>{this.voip=aA.findObjectOfType(UB,this.context),this.marker||(this.marker=aA.getComponentInParent(this.gameObject,Lg))},3e3)}update(){var A;if(!this.voip||this.context.time.frameCount%10!==0)return;let e=((A=this.marker)==null?void 0:A.connectionId)??null;if(!e){poA&&(e=null);return}const i=this.voip.getFrequency(e)??0;this.updateLips(i)}updateLips(A){if(this.context.time.time-this.lastMouthChangeTime>this.mouthChangeLength){if(this.mouthChangeLength=.05+Math.random()*.1,this.talking&&this.talking.length>0&&A>30){this.lastMouthChangeTime=this.context.time.time;const e=Math.floor(Math.random()*this.talking.length);this.setMouthShapeActive(this.talking,e)}else if(this.idle.length>0&&this.context.time.time-this.lastMouthChangeTime>.5){this.lastMouthChangeTime=this.context.time.time;const e=Math.floor(Math.random()*this.idle.length);this.setMouthShapeActive(this.idle,e)}}}setMouthShapeActive(A,e){if(A){A!=this.idle?this.idle.map(i=>i.visible=!1):this.talking.map(i=>i.visible=!1);for(let i=0;i<A.length;i++){const g=A[i];g&&(g.visible=i===e)}}}}tO([y(wA)],wd.prototype,"idle",2),tO([y(wA)],wd.prototype,"talking",2);class jU extends JA{constructor(){super(...arguments),r(this,"voip",null),r(this,"marker",null),r(this,"_startPosition",null)}awake(){this.voip=aA.findObjectOfType(UB,this.context),this.marker=aA.getComponentInParent(this.gameObject,Lg)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!==0)return;const A=this.marker.connectionId,e=this.voip.getFrequency(A);if(e==null)return;this._startPosition||(this._startPosition=this.gameObject.position.clone());const i=e/100;this.gameObject.position.y=this._startPosition.y+i*.07}}var DoA=Object.defineProperty,yoA=Object.getOwnPropertyDescriptor,xw=(t,A,e,i)=>{for(var g=i>1?void 0:i?yoA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&DoA(A,e,g),g};class NB extends JA{constructor(){super(...arguments),r(this,"eyes",[]),r(this,"lastBlinkTime",0),r(this,"blinkLength",0),r(this,"eyesOpen",!0),r(this,"state",null)}awake(){this.state=aA.getComponentInParent(this.gameObject,Eo)}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 A of this.eyes)A&&(A.visible=this.eyesOpen)}}}xw([y(wA)],NB.prototype,"eyes",2),xw([y()],NB.prototype,"lastBlinkTime",2),xw([y()],NB.prototype,"blinkLength",2),xw([y()],NB.prototype,"eyesOpen",2);var woA=Object.defineProperty,SoA=Object.getOwnPropertyDescriptor,WU=(t,A,e,i)=>{for(var g=i>1?void 0:i?SoA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&woA(A,e,g),g},VU;const iO=(VU=class extends JA{constructor(){super(...arguments),r(this,"head",null),r(this,"eyes",null),r(this,"target",null),r(this,"brain",null),r(this,"vec",new w),r(this,"currentTargetPoint",new w)}awake(){this.brain||(this.brain=aA.getComponentInParent(this.gameObject,Dd)),this.brain||(console.log("No look at brain found, adding it now"),this.brain=aA.addNewComponent(this.gameObject,Dd)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}update(){const t=this.target;if(t&&this.head){const A=this.eyes;if(A){const e=Ne(t);this.currentTargetPoint.lerp(e,this.context.time.deltaTime/.1);const i=Ne(this.head),g=this.vec.copy(this.currentTargetPoint).sub(i).normalize();if(g.length()<.1)return;const I=iO.forward;if(I.set(0,0,1),I.applyQuaternion(Kt(this.head)),I.dot(g)>.45)for(let o=0;o<A.length;o++)A[o].lookAt(this.currentTargetPoint)}}}},r(VU,"forward",new w(0,0,1)),VU);let XE=iO;WU([y(wA)],XE.prototype,"head",2),WU([y(wA)],XE.prototype,"eyes",2),WU([y(wA)],XE.prototype,"target",2);const Sd=iA("debugavatar");class Yw{constructor(A,e,i,g){r(this,"root"),r(this,"head"),r(this,"leftHand"),r(this,"rigthHand");var I;this.root=A,this.head=e,this.leftHand=i,this.rigthHand=g,(I=this.root)==null||I.traverse(o=>o.layers.set(2))}get isValid(){return this.head!==null&&this.head!==void 0}}class ZU{constructor(){r(this,"avatarRegistryUrl",null)}async getOrCreateNewAvatarInstance(A,e){if(!e)return console.error("Can not create avatar: failed to provide id or root object"),null;let i=null;if(typeof e=="string"){if(i=await this.loadAvatar(A,e),!i){const I=new xs;i=aA.instantiate(eE(e,A.scene),I)}}else i=e;if(!i)return null;const g=this.findAvatar(i);return g.isValid?(Sd&&console.log("[Custom Avatar] valid config",e,Sd?g:""),g):(console.warn("[Custom Avatar] config isn't valid",e,Sd?g:""),null)}async loadAvatar(A,e){if(console.assert(e!=null&&typeof e=="string","Avatar id must not be null"),e.length<=0||!e)return null;if(Sd&&console.log("[Custom Avatar] "+e+", loading..."),e.endsWith(".glb")||(e+=".glb"),this.avatarRegistryUrl===null){const g=await fetch("./"+e);let I=null;if(g.ok){const s=await g.blob();s&&(I=await s.arrayBuffer())}if(!I&&(I=await bG(e,e,0,"no url here go away",!0),!I))return null;const o=await Bs().parseSync(A,I,null,0);return o?.scene??null}const i=new GE;return Ol(i,A),new Promise((g,I)=>{const o=this.avatarRegistryUrl+"/"+e;i.load(o,async s=>{await Bs().createBuiltinComponents(A,o,s,null,void 0),g(s.scene)},s=>{Sd&&console.log("[Custom Avatar] "+s.loaded/s.total*100+"% loaded of "+s.total/1024+"kB")},s=>{console.error("[Custom Avatar] Error when loading: "+s),g(null)})})}cacheModel(A,e){}findAvatar(A){const e=A;let i=e;i.children.length==1&&(i=A.children[0]);let g=this.findAvatarPart(i,["head"]);const I=this.findAvatarPart(i,["left","hand"]),o=this.findAvatarPart(i,["right","hand"]);if(!g){g=e;const s=new w;new Ft().setFromObject(g).getSize(s);const C=Math.max(s.x,s.y,s.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+C+" meters! Should be < 0.3m"),C>.3&&g.scale.multiplyScalar(1/C*.3)}return new Yw(e,g,I,o)}findAvatarPart(A,e){const i=A.name.toLowerCase();let g=!0;for(const I of e){if(!g)break;i.indexOf(I)===-1&&(g=!1)}if(g)return A;if(A.children)for(const I of A.children){const o=this.findAvatarPart(I,e);if(o)return o}return null}handleCustomAvatarErrors(A){if(!A.ok)throw Error(A.statusText);return A}}var foA=Object.defineProperty,moA=Object.getOwnPropertyDescriptor,zU=(t,A,e,i)=>{for(var g=i>1?void 0:i?moA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&foA(A,e,g),g};class $E extends JA{constructor(){super(...arguments),r(this,"length",1),r(this,"depthTest",!0),r(this,"isGizmo",!0),r(this,"_axes",null)}onEnable(){if(this.isGizmo&&!el)return;this._axes||(this._axes=new Fo(this.length)),this._axes.layers.disableAll(),this._axes.layers.set(this.layer),this.gameObject.add(this._axes);const A=this._axes.material;A&&A.depthTest!==void 0&&(A.depthTest=this.depthTest)}onDisable(){this._axes&&this.gameObject.remove(this._axes)}}zU([y()],$E.prototype,"length",2),zU([y()],$E.prototype,"depthTest",2),zU([y()],$E.prototype,"isGizmo",2);class XU extends JA{constructor(){super(...arguments),r(this,"from"),r(this,"to"),r(this,"hint"),r(this,"desiredDistance",1)}onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;const A=Ne(this.to).clone(),e=Ne(this.from).clone(),i=A.distanceTo(e),g=A.clone();g.sub(e);const I=e.clone();I.add(A),I.multiplyScalar(.5);const o=Ne(this.hint).clone();o.sub(I);const s=new w;s.crossVectors(o,g),s.crossVectors(g,s),s.normalize();const C=i*.5,a=Math.max(this.desiredDistance,C),n=Math.sqrt(a*a-C*C),B=s.clone();B.multiplyScalar(n),B.add(I),CI(this.gameObject,B);const Q=I.clone();Q.sub(s),this.gameObject.lookAt(Q)}}const koA=iA("debugusdz");class Tw{constructor(){r(this,"behaviours",[]),r(this,"behaviourComponents",[]),r(this,"behaviourComponentsCopy",[])}get extensionName(){return"Behaviour"}addBehavior(A){this.behaviours.push(A)}onBeforeBuildDocument(A){const e=[];return A.root.traverse(i=>{aA.foreachComponent(i,g=>{var I;const o=g;if(typeof o.createBehaviours=="function"||typeof o.beforeCreateDocument=="function"||typeof o.afterCreateDocument=="function"||typeof o.afterSerialize=="function"){this.behaviourComponents.push(o);const s=(I=o.beforeCreateDocument)==null?void 0:I.call(o,this,A);s instanceof Promise&&e.push(s)}},!1)}),Promise.all(e)}onExportObject(A,e,i){var g;for(const I of this.behaviourComponents)(g=I.createBehaviours)==null||g.call(I,this,e,i)}onAfterBuildDocument(A){for(const e of this.behaviourComponents)typeof e.afterCreateDocument=="function"&&e.afterCreateDocument(this,A);this.behaviourComponentsCopy=this.behaviourComponents.slice(),this.behaviourComponents.length=0}onAfterHierarchy(A,e){var i;if((i=this.behaviours)!=null&&i.length){e.beginBlock('def Scope "Behaviors"');for(const g of this.behaviours)g.writeTo(this,A.document,e);e.closeBlock()}}async onAfterSerialize(A){koA&&console.log("onAfterSerialize behaviours",this.behaviourComponentsCopy);for(const e of this.behaviourComponentsCopy)typeof e.afterSerialize=="function"&&(e.afterSerialize.constructor.name==="AsyncFunction"?await e.afterSerialize(this,A):e.afterSerialize(this,A));this.behaviours.length=0}}var GoA=Object.defineProperty,MoA=Object.getOwnPropertyDescriptor,$U=(t,A,e,i)=>{for(var g=i>1?void 0:i?MoA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&GoA(A,e,g),g};class FB extends rI{constructor(){super(...arguments),r(this,"threshold"),r(this,"intensity"),r(this,"scatter"),r(this,"selectiveBloom",!0)}get typeName(){return"Bloom"}init(){this.threshold.defaultValue=1,this.intensity.defaultValue=0,this.scatter.defaultValue=.2,this.selectiveBloom?(this.threshold.valueProcessor=A=>A,this.intensity.valueProcessor=A=>A,this.scatter.valueProcessor=A=>1*Math.PI*(1-A)):(this.threshold.valueProcessor=A=>A,this.intensity.valueProcessor=A=>A,this.scatter.valueProcessor=A=>100*(1-A))}onCreateEffect(){let A;if(this.selectiveBloom){const e=A=new ML(this.context.scene,this.context.mainCamera,{blendFunction:je.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,intensity:this.intensity.value});e.inverted=!0}else A=new mG;return this.intensity.onValueChanged=e=>{A.intensity=e},this.threshold.onValueChanged=e=>{A.luminanceMaterial.threshold=e},this.scatter.onValueChanged=e=>{A.luminancePass.enabled=!0,A.luminanceMaterial.smoothing=e},A}}$U([y(Ke)],FB.prototype,"threshold",2),$U([y(Ke)],FB.prototype,"intensity",2),$U([y(Ke)],FB.prototype,"scatter",2),As("Bloom",FB);var RoA=Object.defineProperty,UoA=Object.getOwnPropertyDescriptor,zI=(t,A,e,i)=>{for(var g=i>1?void 0:i?UoA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&RoA(A,e,g),g};class is extends JA{constructor(){super(...arguments),r(this,"attachedRigidbody",null),r(this,"isTrigger",!1),r(this,"sharedMaterial"),r(this,"membership",[0]),r(this,"filter"),r(this,"updateProperties",()=>{var A;(A=this.context.physics.engine)==null||A.updateProperties(this)})}get isCollider(){return!0}awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Pt))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Pt))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Pt))}onDisable(){var A;(A=this.context.physics.engine)==null||A.removeBody(this)}get body(){var A;return(A=this.context.physics.engine)==null?void 0:A.getBody(this)}updatePhysicsMaterial(){var A;(A=this.context.physics.engine)==null||A.updatePhysicsMaterial(this)}}zI([y(Pt)],is.prototype,"attachedRigidbody",2),zI([y()],is.prototype,"isTrigger",2),zI([y()],is.prototype,"sharedMaterial",2),zI([y()],is.prototype,"membership",2),zI([y()],is.prototype,"filter",2);class fd extends is{constructor(){super(...arguments),r(this,"radius",.5),r(this,"center",new w(0,0,0))}onEnable(){var A;super.onEnable(),(A=this.context.physics.engine)==null||A.addSphereCollider(this),MD(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),_k(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}}zI([Jg(),y()],fd.prototype,"radius",2),zI([y(w)],fd.prototype,"center",2);class md extends is{constructor(){super(...arguments),r(this,"size",new w(1,1,1)),r(this,"center",new w(0,0,0))}onEnable(){var A;super.onEnable(),(A=this.context.physics.engine)==null||A.addBoxCollider(this,this.size),MD(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),_k(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}}zI([Jg(),y(w)],md.prototype,"size",2),zI([y(w)],md.prototype,"center",2);class Ah extends is{constructor(){super(...arguments),r(this,"sharedMesh"),r(this,"convex",!1)}onEnable(){var A,e,i,g,I;if(super.onEnable(),(A=this.sharedMesh)!=null&&A.isMesh||this.gameObject instanceof DA&&(this.sharedMesh=this.gameObject),(e=this.sharedMesh)!=null&&e.isMesh)(i=this.context.physics.engine)==null||i.addMeshCollider(this,this.sharedMesh,this.convex,ai(this.gameObject));else{const o=this.sharedMesh;if(o!=null&&o.isGroup){console.warn(`MeshCollider mesh is a group "${((g=this.sharedMesh)==null?void 0:g.name)||this.gameObject.name}", adding all children as colliders. This is currently not fully supported (colliders can not be removed from world again)`,this);for(const s in o.children){const C=o.children[s];C.isMesh&&((I=this.context.physics.engine)==null||I.addMeshCollider(this,C,this.convex,ai(this.gameObject)))}}}}}zI([y()],Ah.prototype,"sharedMesh",2),zI([y()],Ah.prototype,"convex",2);class Wn extends is{constructor(){super(...arguments),r(this,"center",new w(0,0,0)),r(this,"radius",.5),r(this,"height",2)}onEnable(){var A;super.onEnable(),(A=this.context.physics.engine)==null||A.addCapsuleCollider(this,this.height,this.radius)}}zI([y(w)],Wn.prototype,"center",2),zI([y()],Wn.prototype,"radius",2),zI([y()],Wn.prototype,"height",2);var NoA=Object.defineProperty,FoA=Object.getOwnPropertyDescriptor,AN=(t,A,e,i)=>{for(var g=i>1?void 0:i?FoA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&NoA(A,e,g),g};class KB extends JA{constructor(){super(...arguments),r(this,"objectBounds",!1),r(this,"color"),r(this,"isGizmo",!0),r(this,"_gizmoObject",null),r(this,"_boxHelper",null)}onEnable(){this.isGizmo&&!el||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new vk(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=SR(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),Pi.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(var A;this._boxHelper;)(A=this._boxHelper)==null||A.update(),yield}}AN([y()],KB.prototype,"objectBounds",2),AN([y(mA)],KB.prototype,"color",2),AN([y()],KB.prototype,"isGizmo",2);class KoA extends EH{constructor(A,e={}){super(A),A._simpleState__activeStates=[],A._simpleState__normalStyles={},A._simpleState__states=e,A._simpleState__statesProperties={};for(const i in e)for(const g in e[i])A._simpleState__statesProperties[g]||(A._simpleState__statesProperties[g]=[]),A._simpleState__statesProperties[g].push(i);for(const i of A._components)A._simpleState__statesProperties[i.id]&&(A._simpleState__normalStyles[i.id]=i.inline?i.inline:i._value);A.__overridedSet=A.set,A.set=this.storeSet.bind(A),A.renderStates=this.renderStates.bind(A),A.setupState=this.setupState.bind(A),A.setState=this.setState.bind(A),A.activatePseudoState=this.activatePseudoState.bind(A),A.deactivatePseudoState=this.deactivatePseudoState.bind(A),A.togglePseudoState=this.togglePseudoState.bind(A)}act(){}attach(){}detach(){}setupState(A,e){this._simpleState__states[A]=e;const i=[];for(const g in e)this._simpleState__statesProperties[g]||(this._simpleState__statesProperties[g]=[],i.push(g)),this._simpleState__statesProperties[g].push(A);for(const g of this._components)i.indexOf(g.id)>-1&&(this._simpleState__normalStyles[g.id]=g.inline?g.inline:g._value)}renderStates(){let A={...this._simpleState__normalStyles};for(const e in this._simpleState__states)this._simpleState__activeStates.indexOf(e)>-1&&(A={...A,...this._simpleState__states[e]});this.set(A,!1)}storeSet(A,e=!0){if(e)for(const i in A)this._simpleState__statesProperties[i]&&(this._simpleState__normalStyles[i]=A[i]);this.__overridedSet(A)}activatePseudoState(A){this._simpleState__activeStates.indexOf(A)===-1&&(this._simpleState__activeStates.push(A),this.renderStates())}deactivatePseudoState(A){const e=this._simpleState__activeStates.indexOf(A);e>-1&&(this._simpleState__activeStates.splice(e,1),this.renderStates())}togglePseudoState(A){const e=this._simpleState__activeStates.indexOf(A);e>-1?this._simpleState__activeStates.splice(e,1):this._simpleState__activeStates.push(A),this.renderStates()}setState(A){Array.isArray(A)?this._simpleState__activeStates=A:this._simpleState__activeStates=[A],this.renderStates()}}var JoA=Object.defineProperty,voA=Object.getOwnPropertyDescriptor,gO=(t,A,e,i)=>{for(var g=i>1?void 0:i?voA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&JoA(A,e,g),g};class eh extends JA{constructor(){super(...arguments),r(this,"effectColor"),r(this,"effectDistance")}}gO([y(Mt)],eh.prototype,"effectColor",2),gO([y(tA)],eh.prototype,"effectDistance",2);var boA=Object.defineProperty,qoA=Object.getOwnPropertyDescriptor,kd=(t,A,e,i)=>{for(var g=i>1?void 0:i?qoA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&boA(A,e,g),g};const eN=iA("debugui"),tN=iA("debuguilayout");class iN{constructor(){r(this,"width"),r(this,"height")}}class gN{constructor(){r(this,"x"),r(this,"y"),r(this,"width"),r(this,"height")}}const Ks=new w,Gd=new NA,Hw=new FA,IO=class extends Ys{constructor(){super(...arguments),r(this,"_anchoredPosition"),r(this,"sizeDelta",new tA(100,100)),r(this,"pivot",new tA(.5,.5)),r(this,"anchorMin",new tA(0,0)),r(this,"anchorMax",new tA(1,1)),r(this,"minWidth"),r(this,"minHeight"),r(this,"lastMatrix"),r(this,"rectBlock"),r(this,"_transformNeedsUpdate",!1),r(this,"_initialPosition"),r(this,"_parentRectTransform"),r(this,"_lastUpdateFrame",-1),r(this,"_lastAnchoring"),r(this,"_createdBlocks",[]),r(this,"_createdTextBlocks",[])}get parent(){return this._parentRectTransform}get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new tA),this._anchoredPosition}set anchoredPosition(t){this._anchoredPosition=t}get width(){let t=this.sizeDelta.x;if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const A=this._parentRectTransform.width,e=this.anchorMax.x-this.anchorMin.x;t=A*e,t+=this.sizeDelta.x}return this.minWidth!==void 0&&t<this.minWidth?this.minWidth:t}get height(){let t=this.sizeDelta.y;if(this.anchorMin.y!==this.anchorMax.y&&this._parentRectTransform){const A=this._parentRectTransform.height,e=this.anchorMax.y-this.anchorMin.y;t=A*e,t+=this.sizeDelta.y}return this.minHeight!==void 0&&t<this.minHeight?this.minHeight:t}awake(){super.awake(),this._anchoredPosition||(this._anchoredPosition=new tA),this.lastMatrix=new NA,this.rectBlock=new wA,this.rectBlock.name=this.name,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,_E(this,"_anchoredPosition",()=>{this.markDirty()}),_E(this,"sizeDelta",()=>{this.markDirty()}),_E(this,"pivot",()=>{this.markDirty()}),_E(this,"anchorMin",()=>{this.markDirty()}),_E(this,"anchorMax",()=>{this.markDirty()})}onEnable(){var t;super.onEnable(),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,(t=this.Canvas)==null||t.registerTransform(this)}onDisable(){var t;super.onDisable(),this.removeShadowComponent(),(t=this.Canvas)==null||t.unregisterTransform(this)}onParentRectTransformChanged(t){this._transformNeedsUpdate||this.onApplyTransform(tN?`${t.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(tN&&console.warn("RectTransform markDirty()",this.name),this._transformNeedsUpdate=!0,this._lastUpdateFrame=-1)}updateTransform(){(this._transformNeedsUpdate||!this.lastMatrix.equals(this.gameObject.matrix))&&this.canUpdate()&&this.onApplyTransform(this._transformNeedsUpdate?"Marked dirty":"Matrix changed")}canUpdate(){return this._transformNeedsUpdate&&this.activeAndEnabled&&this._lastUpdateFrame!==this.context.time.frame}onApplyTransform(t){var A;if(this.context.time.frameCount===this._lastUpdateFrame)return;this._lastUpdateFrame=this.context.time.frameCount;const e=this.shadowComponent;if(!e)return;this.gameObject.parent?this._parentRectTransform=aA.getComponentInParent(this.gameObject.parent,IO):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,tN&&console.warn("RectTransform \u2192 ApplyTransform",this.name+" because "+t),this.isRoot()?this.Root.screenspace||(e.rotation.y=Math.PI):(e.matrix.identity(),e.matrixAutoUpdate=!1,Ks.set(0,0,0),this.applyPivot(Ks),e.matrix.setPosition(Ks.x,Ks.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(Hw.copy(this.gameObject.quaternion),Hw.x*=-1,Hw.z*=-1,Gd.makeRotationFromQuaternion(Hw),e.matrix.premultiply(Gd)),Ks.set(0,0,0),this.applyAnchoring(Ks),(A=this.Canvas)!=null&&A.screenspace?Ks.z+=.1:Ks.z+=.01,Gd.identity(),Gd.setPosition(Ks.x,Ks.y,Ks.z),e.matrix.premultiply(Gd),e.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const i=!0;for(const g of NR(this.gameObject,Ys,i,1)){if(g===this||!g.activeAndEnabled)continue;const I=g;I.onParentRectTransformChanged&&I.onParentRectTransformChanged(this)}}applyAnchoring(t){this._lastAnchoring||(this._lastAnchoring=new tA);const A=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=A.x,this.gameObject.position.y+=A.y,this._lastAnchoring.copy(this._anchoredPosition),t.x+=this._initialPosition.x-this.gameObject.position.x,t.y+=this._initialPosition.y-this.gameObject.position.y,t.z+=this._initialPosition.z-this.gameObject.position.z;const e=this._parentRectTransform;if(e){let i=0;const g=1-this.anchorMax.y-this.anchorMin.y;i-=e.height*.5*g,t.y+=i;let I=0;const o=1-this.anchorMax.x-this.anchorMin.x;I-=e.width*.5*o,t.x+=I}}applyPivot(t){if(this.pivot&&!this.isRoot()){const A=this.pivot.x-.5;t.x-=A*this.sizeDelta.x*this.gameObject.scale.x;const e=this.pivot.y-.5;t.y-=e*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){const t={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:0,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(t),t}ensureValidSize(t,A=1e-4){return t.width<=0&&(t.width=A),t.height<=0&&(t.height=1e-4),t}createNewBlock(t){t={...this.getBasicOptions(),...t},eN&&console.log(this.name,t);const A=new aR(t);return this._createdBlocks.push(A),A}createNewText(t){eN&&console.log(t),t={...this.getBasicOptions(),...t},eN&&console.log(this.name,t);const A=new rR(t);return this._createdTextBlocks.push(A),A}};let RI=IO;kd([y(tA)],RI.prototype,"anchoredPosition",1),kd([y(tA)],RI.prototype,"sizeDelta",2),kd([y(tA)],RI.prototype,"pivot",2),kd([y(tA)],RI.prototype,"anchorMin",2),kd([y(tA)],RI.prototype,"anchorMax",2);var LoA=Object.defineProperty,xoA=Object.getOwnPropertyDescriptor,oO=(t,A,e,i)=>{for(var g=i>1?void 0:i?xoA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&LoA(A,e,g),g};const _w={backgroundColor:new mA(1,1,1),backgroundOpacity:1,borderColor:new mA(1,1,1),borderOpacity:1};var IN;const Ow=(IN=class extends Ys{constructor(){super(...arguments),r(this,"_alphaFactor",1),r(this,"sRGBColor",new mA(1,0,1)),r(this,"raycastTarget",!0),r(this,"uiObject",null),r(this,"_color",null),r(this,"_rect",null),r(this,"_stateManager",null),r(this,"_currentlyCreatingPanel",!1)}get isGraphic(){return!0}get color(){return this._color||(this._color=new Mt(1,1,1,1)),this._color}set color(t){(!this._color||this._color.r!==t.r||this._color.g!==t.g||this._color.b!==t.b||this._color.alpha!==t.alpha)&&(this._color||(this._color=new Mt(1,1,1,1)),this._color.copy(t),this.onColorChanged())}setAlphaFactor(t){this._alphaFactor=t,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}onColorChanged(){this.uiObject&&(this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),_w.backgroundColor=this.sRGBColor,_w.backgroundOpacity=this._color.alpha*this._alphaFactor,this.applyEffects(_w,this._alphaFactor),this.uiObject.set(_w),this.markDirty())}get m_Color(){return this._color}get rectTransform(){if(this._rect||(this._rect=aA.getComponent(this.gameObject,RI)),!this._rect)throw new Error("Not Supported: Make sure to add a RectTransform component before adding a UI Graphic component.");return this._rect}onParentRectTransformChanged(){var t;(t=this.uiObject)==null||t.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(){super.__internalNewInstanceCreated(),this._rect=null,this.uiObject=null,this._color&&(this._color=this._color.clone())}setState(t){this.makePanel(),this.uiObject&&(this.uiObject.setState(t),this==null||this.markDirty())}setupState(t){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new KoA(this.uiObject)),this.uiObject.setupState(t.state,t.attributes))}setOptions(t){this.makePanel(),this.uiObject&&this.uiObject.set(t)}awake(){super.awake(),this.makePanel(),_E(this,"_color",()=>cIA(this,this.onColorChanged))}onEnable(){var t;super.onEnable(),this.uiObject&&((t=this.rectTransform.shadowComponent)==null||t.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;const t=.015,A={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:t};this.onBeforeCreate(A),this.applyEffects(A),this.onCreate(A),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated(),this.onColorChanged()}onBeforeCreate(t){}onCreate(t){this.uiObject=this.rectTransform.createNewBlock(t),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(t,A=1){var e;const i=(e=this.gameObject)==null?void 0:e.getComponent(eh);i&&(i.effectDistance&&(t.borderWidth=Math.max(Math.abs(i.effectDistance.x),Math.abs(i.effectDistance.y))),i.effectColor&&(t.borderColor=i.effectColor,t.borderOpacity=i.effectColor.alpha*A))}async setTexture(t){if(this.setOptions({backgroundOpacity:0}),t){if(Ow.textureCache.has(t))t=Ow.textureCache.get(t);else if(!t.isRenderTargetTexture){const A=t.clone();A.colorSpace=Nt,Ow.textureCache.set(t,A),t=A}this.setOptions({backgroundImage:t,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"})}else this.setOptions({backgroundImage:null,borderRadius:0,backgroundOpacity:this.color.alpha});this.markDirty()}onAfterAddedToScene(){super.onAfterAddedToScene(),this.shadowComponent&&(this.shadowComponent.offset=this.shadowComponent.position.z)}},r(IN,"textureCache",new Map),IN);let JB=Ow;oO([y(Mt)],JB.prototype,"color",1),oO([y()],JB.prototype,"raycastTarget",2);class Md extends JB{constructor(){super(...arguments),r(this,"_flippedObject",!1)}onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var YoA=Object.defineProperty,ToA=Object.getOwnPropertyDescriptor,Pw=(t,A,e,i)=>{for(var g=i>1?void 0:i?ToA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&YoA(A,e,g),g};let oN=class{constructor(){r(this,"texture",null),r(this,"rect")}};Pw([y(Ye)],oN.prototype,"texture",2);let th=class extends Md{constructor(){super(...arguments),r(this,"_sprite"),r(this,"pixelsPerUnitMultiplier",1)}set image(t){this.sprite||(this.sprite=new oN),this.sprite.texture=t,this.onAfterCreated()}get image(){return this.sprite?this.sprite.texture:null}get sprite(){return this._sprite}set sprite(t){this._sprite!==t&&(this._sprite=t,this.onAfterCreated())}isBuiltinSprite(){var t,A,e,i,g,I,o,s,C,a,n;switch((A=(t=this.sprite)==null?void 0:t.texture)==null?void 0:A.name){case"InputFieldBackground":case"UISprite":case"Background":case"Knob":return!0}return!((g=(i=(e=this.sprite)==null?void 0:e.texture)==null?void 0:i.name)!=null&&g.length)&&((s=(o=(I=this.sprite)==null?void 0:I.texture)==null?void 0:o.image)==null?void 0:s.width)===32&&((n=(a=(C=this.sprite)==null?void 0:C.texture)==null?void 0:a.image)==null?void 0:n.height)===32}onBeforeCreate(t){var A,e;super.onBeforeCreate(t),this.isBuiltinSprite()&&(t.borderRadius=5/this.pixelsPerUnitMultiplier,((e=(A=this.sprite)==null?void 0:A.texture)==null?void 0:e.name)==="Knob"&&(t.borderRadius=999))}onAfterCreated(){var t;this.__didAwake&&(super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture((t=this.sprite)==null?void 0:t.texture))}};Pw([y(oN)],th.prototype,"sprite",1),Pw([y()],th.prototype,"pixelsPerUnitMultiplier",2);class jw extends Md{constructor(){super(...arguments),r(this,"_mainTexture")}get mainTexture(){return this._mainTexture}set mainTexture(A){this._mainTexture!==A&&(this._mainTexture=A,this.onAfterCreated())}onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),this.setTexture(this.mainTexture))}}Pw([y(Ye)],jw.prototype,"mainTexture",1);var HoA=Object.defineProperty,_oA=Object.getOwnPropertyDescriptor,ho=(t,A,e,i)=>{for(var g=i>1?void 0:i?_oA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&HoA(A,e,g),g};const vB=iA("debugbutton");class bB{constructor(){r(this,"colorMultiplier"),r(this,"disabledColor"),r(this,"fadeDuration"),r(this,"highlightedColor"),r(this,"normalColor"),r(this,"pressedColor"),r(this,"selectedColor")}}ho([y()],bB.prototype,"colorMultiplier",2),ho([y(Mt)],bB.prototype,"disabledColor",2),ho([y()],bB.prototype,"fadeDuration",2),ho([y(Mt)],bB.prototype,"highlightedColor",2),ho([y(Mt)],bB.prototype,"normalColor",2),ho([y(Mt)],bB.prototype,"pressedColor",2),ho([y(Mt)],bB.prototype,"selectedColor",2);class Na extends JA{constructor(){super(...arguments),r(this,"onClick"),r(this,"_isHovered",0),r(this,"colors"),r(this,"transition"),r(this,"animationTriggers"),r(this,"animator"),r(this,"_interactable",!0),r(this,"_requestedAnimatorTrigger"),r(this,"_isInit",!1),r(this,"_image")}onPointerEnter(A){var e,i;this._isHovered+=1,vB&&console.warn("Button Enter",this._isHovered,(e=this.animationTriggers)==null?void 0:e.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.highlightedTrigger):this.transition===1&&this.colors&&((i=this._image)==null||i.setState("hovered")),this.context.input.setCursorPointer())}onPointerExit(){var A,e;this._isHovered-=1,vB&&console.log("Button Exit",this._isHovered,(A=this.animationTriggers)==null?void 0:A.highlightedTrigger,this.animator),this.interactable&&(this._isHovered>0||(this._isHovered=0,this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&((e=this._image)==null||e.setState("normal")),this.context.input.setCursorNormal()))}onPointerDown(A){var e,i;vB&&console.log("Button Down",(e=this.animationTriggers)==null?void 0:e.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&((i=this._image)==null||i.setState("pressed")))}onPointerUp(A){var e,i;vB&&console.warn("Button Up",(e=this.animationTriggers)==null?void 0:e.highlightedTrigger,this.animator,this._isHovered),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this._isHovered?this.animationTriggers.highlightedTrigger:this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&((i=this._image)==null||i.setState(this._isHovered?"hovered":"normal")))}onPointerClick(A){if(this.interactable&&!(A.button!==0&&A.event.pointerType===LG.Mouse)&&(vB&&(console.warn("Button Click",this.onClick),wi("CLICKED button "+this.name+" at "+this.context.time.frameCount)),this.onClick&&this.onClick.listenerCount>0&&(this.onClick.invoke(),A.use(),vB))){const e=this.gameObject.worldPosition;e.add(this.gameObject.worldUp.multiplyScalar(1+Math.random()*.5)),Fe.DrawLabel(e,"CLICK:"+Date.now(),.1,1+Math.random()*.5)}}set interactable(A){this._interactable=A,this._image&&(this._image.setInteractable(A),A?this._image.setState("normal"):this._image.setState("disabled"))}get interactable(){return this._interactable}set_interactable(A){this.interactable=A}awake(){super.awake(),vB&&console.log(this),this._isInit=!1,this.init()}start(){var A;(A=this._image)==null||A.setInteractable(this.interactable),this.gameObject.getComponentInParent(gd)||this.gameObject.addComponent(ww)}onEnable(){super.onEnable()}onDestroy(){this._isHovered&&this.context.input.setCursorNormal()}*setAnimatorTriggerAtEndOfFrame(A){var e;this._requestedAnimatorTrigger=A,yield,yield,this._requestedAnimatorTrigger==A&&((e=this.animator)==null||e.SetTrigger(A))}init(){this._isInit||(this._isInit=!0,this._image=aA.getComponent(this.gameObject,th),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(A){var e,i,g,I,o;A.setInteractable(this.interactable);const s=this.getFinalColor(A.color,(e=this.colors)==null?void 0:e.normalColor),C={state:"normal",attributes:{backgroundColor:s,backgroundOpacity:s.alpha}};A.setupState(C);const a=this.getFinalColor(A.color,(i=this.colors)==null?void 0:i.highlightedColor),n={state:"hovered",attributes:{backgroundColor:a,backgroundOpacity:a.alpha}};A.setupState(n);const B=this.getFinalColor(A.color,(g=this.colors)==null?void 0:g.pressedColor),Q={state:"pressed",attributes:{backgroundColor:B,backgroundOpacity:B.alpha}};A.setupState(Q);const E=this.getFinalColor(A.color,(I=this.colors)==null?void 0:I.selectedColor),h={state:"selected",attributes:{backgroundColor:E,backgroundOpacity:E.alpha}};A.setupState(h);const d=this.getFinalColor(A.color,(o=this.colors)==null?void 0:o.disabledColor),u={state:"disabled",attributes:{backgroundColor:d,backgroundOpacity:d.alpha}};A.setupState(u)}getFinalColor(A,e){return e?A.clone().multiply(e).convertLinearToSRGB():A.clone().convertLinearToSRGB()}}ho([y(Eg)],Na.prototype,"onClick",2),ho([y()],Na.prototype,"colors",2),ho([y()],Na.prototype,"transition",2),ho([y()],Na.prototype,"animationTriggers",2),ho([y(bg)],Na.prototype,"animator",2),ho([y()],Na.prototype,"interactable",1);var OoA=Object.defineProperty,PoA=Object.getOwnPropertyDescriptor,ji=(t,A,e,i)=>{for(var g=i>1?void 0:i?PoA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&OoA(A,e,g),g};const sO=iA("debuguilayout");class Vn{constructor(){r(this,"left",0),r(this,"right",0),r(this,"top",0),r(this,"bottom",0)}get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}ji([y()],Vn.prototype,"left",2),ji([y()],Vn.prototype,"right",2),ji([y()],Vn.prototype,"top",2),ji([y()],Vn.prototype,"bottom",2);class co extends JA{constructor(){super(...arguments),r(this,"_rectTransform",null),r(this,"_needsUpdate",!1),r(this,"childAlignment",0),r(this,"reverseArrangement",!1),r(this,"spacing",0),r(this,"padding"),r(this,"minWidth",0),r(this,"minHeight",0),r(this,"flexibleHeight",0),r(this,"flexibleWidth",0),r(this,"preferredHeight",0),r(this,"preferredWidth",0)}get rectTransform(){return this._rectTransform}onParentRectTransformChanged(A){this._needsUpdate=!0}get isDirty(){return this._needsUpdate}get isLayoutGroup(){return!0}updateLayout(){this._rectTransform&&(sO&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}start(){this._needsUpdate=!0}onEnable(){sO&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(RI);const A=this.gameObject.getComponentInParent(xg);A&&A.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const A=this.gameObject.getComponentInParent(xg);A&&A.unregisterLayoutGroup(this)}set m_Spacing(A){A!==this.spacing&&(this._needsUpdate=!0,this.spacing=A)}get m_Spacing(){return this.spacing}}ji([y()],co.prototype,"childAlignment",2),ji([y()],co.prototype,"reverseArrangement",2),ji([y()],co.prototype,"spacing",2),ji([y(Vn)],co.prototype,"padding",2),ji([y()],co.prototype,"minWidth",2),ji([y()],co.prototype,"minHeight",2),ji([y()],co.prototype,"flexibleHeight",2),ji([y()],co.prototype,"flexibleWidth",2),ji([y()],co.prototype,"preferredHeight",2),ji([y()],co.prototype,"preferredWidth",2);class Zn extends co{constructor(){super(...arguments),r(this,"childControlHeight",!0),r(this,"childControlWidth",!0),r(this,"childForceExpandHeight",!1),r(this,"childForceExpandWidth",!1),r(this,"childScaleHeight",!1),r(this,"childScaleWidth",!1)}onCalculateLayout(A){var e;const i=this.primaryAxis,g=A.width;let I=g;const o=A.height;let s=o;I-=this.padding.horizontal,s-=this.padding.vertical,i==="x"?this.padding.horizontal:this.padding.vertical;const C=i==="x",a=C?"y":"x",n=C?this.childControlWidth:this.childControlHeight,B=C?this.childControlHeight:this.childControlWidth,Q=C?this.childForceExpandWidth:this.childForceExpandHeight,E=C?this.childForceExpandHeight:this.childForceExpandWidth,h=C?s:I,d=C?g:o,u=.5*(C?this.childAlignment%3:Math.floor(this.childAlignment/3));let c=0;C?c+=this.padding.left:c+=this.padding.top;let l=0,p=0;for(let U=0;U<this.gameObject.children.length;U++){const M=this.gameObject.children[U],m=aA.getComponent(M,RI);m!=null&&m.activeAndEnabled&&(p+=1,C?l+=m.width:l+=m.height)}let D=0;const S=this.spacing*(p-1);if(Q||n){let U=0;C?U=I-=S:U=s-=S,p>0&&(D=U/p)}let k=0;k+=this.padding.left,k-=this.padding.right,u!==0&&(c=d-l,c*=u,c-=S*u,C?(c-=this.padding.right*u,c+=this.padding.left*(1-u),c<this.padding.left&&(c=this.padding.left)):(c-=this.padding.bottom*u,c+=this.padding.top*(1-u),c<this.padding.top&&(c=this.padding.top)));let f=1;for(let U=0;U<this.gameObject.children.length;U++){const M=this.gameObject.children[U],m=aA.getComponent(M,RI);if(m!=null&&m.activeAndEnabled){(e=m.pivot)==null||e.set(.5,.5),m.anchorMin.set(0,1),m.anchorMax.set(0,1);const x=g*.5+k*.5;m.anchoredPosition.x!==x&&(m.anchoredPosition.x=x);const L=o*-.5;m.anchoredPosition.y!==L&&(m.anchoredPosition.y=L),E&&B&&m.sizeDelta[a]!==h&&(m.sizeDelta[a]=h),Q&&n&&m.sizeDelta[i]!==D&&(m.sizeDelta[i]=D);const V=C?m.width:m.height,Y=V*.5;if(c+=Y,Q){const b=D*f-D*.5;b>c&&(c=b-D*.5+V+this.padding.left,c-=Y)}let P=c;i==="y"&&(P=-P),m.anchoredPosition[i]!==P&&(m.anchoredPosition[i]=P),c+=Y,c+=this.spacing,f+=1}}}}ji([y()],Zn.prototype,"childControlHeight",2),ji([y()],Zn.prototype,"childControlWidth",2),ji([y()],Zn.prototype,"childForceExpandHeight",2),ji([y()],Zn.prototype,"childForceExpandWidth",2),ji([y()],Zn.prototype,"childScaleHeight",2),ji([y()],Zn.prototype,"childScaleWidth",2);class sN extends Zn{get primaryAxis(){return"y"}}class CN extends Zn{get primaryAxis(){return"x"}}class aN extends co{onCalculateLayout(){}}var joA=Object.defineProperty,WoA=Object.getOwnPropertyDescriptor,dC=(t,A,e,i)=>{for(var g=i>1?void 0:i?WoA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&joA(A,e,g),g},CO=(t=>(t[t.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",t[t.ScreenSpaceCamera=1]="ScreenSpaceCamera",t[t.WorldSpace=2]="WorldSpace",t[t.Undefined=-1]="Undefined",t))(CO||{});const nN=iA("debuguilayout"),aO=class extends id{constructor(){super(...arguments),r(this,"_renderOnTop"),r(this,"_depthWrite",!1),r(this,"_doubleSided",!0),r(this,"_castShadows",!1),r(this,"_receiveShadows",!1),r(this,"_renderMode",-1),r(this,"_rootCanvas"),r(this,"_scaleFactor",1),r(this,"worldCamera"),r(this,"planeDistance",-1),r(this,"_boundRenderSettingsChanged",this.onRenderSettingsChanged.bind(this)),r(this,"previousParent",null),r(this,"_lastMatrixWorld",null),r(this,"_rectTransforms",[]),r(this,"_layoutGroups",new Map),r(this,"_receivers",[]),r(this,"onBeforeRenderRoutine",()=>{var t,A,e,i;if(this.previousParent=this.gameObject.parent,((t=this.context.xr)!=null&&t.isVR||(A=this.context.xr)!=null&&A.isPassThrough)&&this.screenspace){this.gameObject.visible=!1,this.gameObject.removeFromParent();return}this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),(e=this.shadowComponent)==null||e.updateMatrixWorld(!0),(i=this.shadowComponent)==null||i.updateWorldMatrix(!0,!0),this.invokeBeforeRenderEvents(),zo.ensureUpdateMeshUI(cH,this.context))}),r(this,"onAfterRenderRoutine",()=>{var t,A,e,i,g;if(((t=this.context.xr)!=null&&t.isVR||(A=this.context.xr)!=null&&A.isPassThrough)&&this.screenspace){(e=this.previousParent)==null||e.add(this.gameObject);return}if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){if(this.screenspace){const s=this.context.mainCamera;s?.add(this.gameObject)}else this.previousParent.add(this.gameObject);const I=this.context.renderer.autoClear,o=this.context.renderer.autoClearColor;this.context.renderer.autoClear=!1,this.context.renderer.autoClearColor=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),(i=this.shadowComponent)==null||i.updateMatrixWorld(!0),this.invokeBeforeRenderEvents(),zo.ensureUpdateMeshUI(cH,this.context,!0),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=I,this.context.renderer.autoClearColor=o,this.previousParent.add(this.gameObject)}(g=this._lastMatrixWorld)==null||g.copy(this.gameObject.matrixWorld)}),r(this,"_updateRenderSettingsRoutine"),r(this,"_activeRenderMode",-1),r(this,"_lastWidth",-1),r(this,"_lastHeight",-1)}get isCanvas(){return!0}get screenspace(){return this.renderMode!==2}set renderOnTop(t){t!==this._renderOnTop&&(this._renderOnTop=t,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop!==void 0?this._renderOnTop:!!(this.screenspace&&this._renderMode===0)}set depthWrite(t){this._depthWrite!==t&&(this._depthWrite=t,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}set doubleSided(t){this._doubleSided!==t&&(this._doubleSided=t,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}set castShadows(t){this._castShadows!==t&&(this._castShadows=t,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}set receiveShadows(t){this._receiveShadows!==t&&(this._receiveShadows=t,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}get renderMode(){return this._renderMode}set renderMode(t){this._renderMode!==t&&(this._renderMode=t,this.onRenderSettingsChanged())}set rootCanvas(t){this._rootCanvas instanceof aO||(this._rootCanvas=t)}get rootCanvas(){return this._rootCanvas}get scaleFactor(){return this._scaleFactor}set scaleFactor(t){this._scaleFactor=t}awake(){var t;this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,nN&&console.log("Canvas.Awake()",((t=this.previousParent)==null?void 0:t.name)+"/"+this.gameObject.name),super.awake()}start(){this.onUpdateRenderMode()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new NA,this.onUpdateRenderMode(),document.addEventListener("resize",this._boundRenderSettingsChanged),this.context.pre_render_callbacks.push(this.onBeforeRenderRoutine),this.context.post_render_callbacks.push(this.onAfterRenderRoutine)}onDisable(){super.onDisable(),document.removeEventListener("resize",this._boundRenderSettingsChanged);const t=this.context.pre_render_callbacks.indexOf(this.onBeforeRenderRoutine);t!==-1&&this.context.pre_render_callbacks.splice(t,1);const A=this.context.post_render_callbacks.indexOf(this.onAfterRenderRoutine);A!==-1&&this.context.post_render_callbacks.splice(A,1)}registerTransform(t){this._rectTransforms.push(t)}unregisterTransform(t){const A=this._rectTransforms.indexOf(t);A!==-1&&this._rectTransforms.splice(A,1)}registerLayoutGroup(t){const A=t.gameObject;this._layoutGroups.set(A,t)}unregisterLayoutGroup(t){const A=t.gameObject;this._layoutGroups.delete(A)}registerEventReceiver(t){this._receivers.push(t)}unregisterEventReceiver(t){const A=this._receivers.indexOf(t);A!==-1&&this._receivers.splice(A,1)}async onEnterXR(t){this.screenspace?(t.xr.isVR||t.xr.isPassThrough)&&(this.gameObject.visible=!1):(this.gameObject.visible=!1,await yq(1).then(()=>{this.gameObject.visible=!0}))}onLeaveXR(t){this.screenspace&&(t.xr.isVR||t.xr.isPassThrough)&&(this.gameObject.visible=!0)}invokeBeforeRenderEvents(){var t;for(const A of this._receivers)(t=A.onBeforeCanvasRender)==null||t.call(A,this)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new NA);const t=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);nN&&t&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);const A=!1;for(const e of this._rectTransforms){t&&e.markDirty();let i=this._layoutGroups.get(e.gameObject);e.isDirty&&!i&&(i=e.gameObject.getComponentInParent(co)),(e.isDirty||i!=null&&i.isDirty)&&(nN&&!A&&console.log("CANVAS UPDATE ### "+e.name+" ##################################### "+this.context.time.frame),i?.updateLayout(),e.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),Pi.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),fw(this.shadowComponent,this);for(const t of aA.getComponentsInChildren(this.gameObject,Ys))fw(t.shadowComponent,this)}}onUpdateRenderMode(t=!1){if(!t&&this._renderMode===this._activeRenderMode&&this._lastWidth===this.context.domWidth&&this._lastHeight===this.context.domHeight)return;this._activeRenderMode=this._renderMode;let A=this.context.mainCameraComponent,e=10;switch(A&&A.nearClipPlane>0&&A.farClipPlane>0&&(e=Ie.lerp(A.nearClipPlane,A.farClipPlane,.01)),this._renderMode===1&&(this.worldCamera&&(A=this.worldCamera),this.planeDistance>0&&(e=this.planeDistance)),this._renderMode){case 0:case 1:if(this._lastWidth=this.context.domWidth,this._lastHeight=this.context.domHeight,!A)return;const i=e+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-i,this.gameObject.quaternion.identity();const g=this.gameObject.getComponent(RI);let I=!1;g.sizeDelta.x!==this.context.domWidth&&(I=!0),g.sizeDelta.y!==this.context.domHeight&&(I=!0);const o=A.fieldOfView*Math.PI/180,s=2*Math.tan(o/2)*Math.abs(i);this.gameObject.scale.x=s/this.context.domHeight,this.gameObject.scale.y=s/this.context.domHeight,this.gameObject.scale.z=.01,I&&(g.sizeDelta.x=this.context.domWidth,g.sizeDelta.y=this.context.domHeight,g?.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};let xg=aO;dC([y()],xg.prototype,"renderOnTop",1),dC([y()],xg.prototype,"depthWrite",1),dC([y()],xg.prototype,"doubleSided",1),dC([y()],xg.prototype,"castShadows",1),dC([y()],xg.prototype,"receiveShadows",1),dC([y()],xg.prototype,"renderMode",1),dC([y(xg)],xg.prototype,"rootCanvas",1),dC([y()],xg.prototype,"scaleFactor",1),dC([y(Wt)],xg.prototype,"worldCamera",2),dC([y()],xg.prototype,"planeDistance",2);var VoA=Object.defineProperty,ZoA=Object.getOwnPropertyDescriptor,rN=(t,A,e,i)=>{for(var g=i>1?void 0:i?ZoA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&VoA(A,e,g),g};class zn extends JA{constructor(){super(...arguments),r(this,"_alpha",1),r(this,"interactable",!0),r(this,"blocksRaycasts",!0),r(this,"_isDirty",!1),r(this,"_buffer",[])}get alpha(){return this._alpha}set alpha(A){A!==this._alpha&&(this._alpha=A,this.markDirty())}get isCanvasGroup(){return!0}markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),Pi.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}applyChangesNow(){this._buffer.length=0;for(const A of aA.getComponentsInChildren(this.gameObject,Ys,this._buffer)){const e=A;e.setAlphaFactor&&e.setAlphaFactor(this._alpha)}}}rN([y()],zn.prototype,"alpha",1),rN([y()],zn.prototype,"interactable",2),rN([y()],zn.prototype,"blocksRaycasts",2);var zoA=Object.defineProperty,XoA=Object.getOwnPropertyDescriptor,ni=(t,A,e,i)=>{for(var g=i>1?void 0:i?XoA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&zoA(A,e,g),g};function Rd(t){t&&(t.getComponentInParent(gd)||(Se()&&console.warn("Create Raycaster on "+t.name+" because no raycaster was found in the hierarchy"),t.addNewComponent(ro)))}class qB extends JA{constructor(){super(...arguments),r(this,"object"),r(this,"target"),r(this,"duration",1),r(this,"relativeMotion",!1),r(this,"coroutine",null),r(this,"targetPos",new w),r(this,"targetRot",new FA),r(this,"targetScale",new w)}start(){Rd(this.gameObject)}onPointerClick(A){A.use(),this.coroutine&&this.stopCoroutine(this.coroutine),this.relativeMotion?this.coroutine=this.startCoroutine(this.moveRelative()):this.coroutine=this.startCoroutine(this.moveToTarget())}*moveToTarget(){if(!this.target||!this.object)return;const A=Ne(this.object).clone(),e=Ne(this.target).clone(),i=Kt(this.object).clone(),g=Kt(this.target).clone(),I=ai(this.object).clone(),o=ai(this.target).clone(),s=A.distanceTo(e),C=i.angleTo(g),a=I.distanceTo(o);if(s<.01&&C<.01&&a<.01){CI(this.object,e),_o(this.object,g),Gl(this.object,o),this.coroutine=null;return}let n=0,B=0;for(;n<1;)n+=this.context.time.deltaTime/this.duration,n>1&&(n=1),B=n<.5?4*n*n*n:1-Math.pow(-2*n+2,3)/2,this.targetPos.lerpVectors(A,e,B),this.targetRot.slerpQuaternions(i,g,B),this.targetScale.lerpVectors(I,o,B),CI(this.object,this.targetPos),_o(this.object,this.targetRot),Gl(this.object,this.targetScale),yield;this.coroutine=null}*moveRelative(){if(!this.target||!this.object)return;const A=this.object.position.clone(),e=this.object.quaternion.clone(),i=this.object.scale.clone(),g=this.target.position.clone(),I=this.target.quaternion.clone(),o=this.target.scale.clone();g.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(g),this.targetRot.copy(this.object.quaternion).multiply(I),this.targetScale.copy(this.object.scale).multiply(o);let s=0,C=0;for(;s<1;)s+=this.context.time.deltaTime/this.duration,s>1&&(s=1),C=s<.5?4*s*s*s:1-Math.pow(-2*s+2,3)/2,this.object.position.lerpVectors(A,this.targetPos,C),this.object.quaternion.slerpQuaternions(e,this.targetRot,C),this.object.scale.lerpVectors(i,this.targetScale,C),yield;this.coroutine=null}beforeCreateDocument(A){var e;if(this.target&&this.object&&this.gameObject){const i=new Fg("Move to "+((e=this.target)==null?void 0:e.name),Kg.tapTrigger(this.gameObject),Et.transformAction(this.object,this.target,this.duration,this.relativeMotion?yU.Relative:yU.Absolute));A.addBehavior(i)}}}ni([y(wA)],qB.prototype,"object",2),ni([y(wA)],qB.prototype,"target",2),ni([y()],qB.prototype,"duration",2),ni([y()],qB.prototype,"relativeMotion",2);var Ww;const Fa=(Ww=class extends JA{constructor(){super(...arguments),r(this,"materialToSwitch"),r(this,"variantMaterial"),r(this,"fadeDuration",0),r(this,"_objectsWithThisMaterial",[]),r(this,"selfModel"),r(this,"targetModels")}awake(){if(this.variantMaterial&&this.materialToSwitch){const t=aA.findObjectsOfType(Si);for(const A of t)for(let e=0;e<A.sharedMaterials.length;e++){const i=A.sharedMaterials[e];if(i===this.materialToSwitch){if(A.gameObject instanceof DA)this._objectsWithThisMaterial.push(A.gameObject);else if(A.gameObject instanceof dI)for(const g of A.gameObject.children)g instanceof DA&&g.material===i&&this._objectsWithThisMaterial.push(g);break}}}}start(){Rd(this.gameObject)}onPointerClick(t){if(t.use(),!!this.variantMaterial)for(let A=0;A<this._objectsWithThisMaterial.length;A++){const e=this._objectsWithThisMaterial[A];e.material=this.variantMaterial}}async beforeCreateDocument(t,A){this.targetModels=[],Fa._materialTriggersPerId={},Fa.variantSwitchIndex=0,this.materialToSwitch&&await Us.assignTextureLOD(this.context,this.sourceId,this.materialToSwitch,0),this.variantMaterial&&await Us.assignTextureLOD(this.context,this.sourceId,this.variantMaterial,0)}createBehaviours(t,A,e){this._objectsWithThisMaterial.find(i=>i.uuid===A.uuid)&&this.targetModels.push(A),this.gameObject.uuid===A.uuid&&(this.selfModel=A,this.materialToSwitch&&(Fa._materialTriggersPerId[this.materialToSwitch.uuid]||(Fa._materialTriggersPerId[this.materialToSwitch.uuid]=[]),Fa._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(t,A){if(!this.materialToSwitch)return;const e=Fa._materialTriggersPerId[this.materialToSwitch.uuid];if(e){const i={};for(const g of e){const I=g.createVariants();I&&I.length>0&&(i[g.selfModel.uuid]=I)}for(const g of e){const I=[];for(const o in i)o!==g.selfModel.uuid&&I.push(...i[o]);g.createAndAttachBehaviors(t,i[g.selfModel.uuid],I)}}delete Fa._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(t,A,e){const i=[],g=[],I=Math.max(0,this.fadeDuration);g.push(Et.fadeAction([...this.targetModels,...e],I,!1)),i.push(Et.fadeAction(A,I,!1)),g.push(Et.fadeAction(A,I,!0)),t.addBehavior(new Fg("Select_"+this.selfModel.name,Kg.tapTrigger(this.selfModel),Et.parallel(...g))),t.addBehavior(new Fg("StartHidden_"+this.selfModel.name,Kg.sceneStartTrigger(),Et.parallel(...i)))}createVariants(){if(!this.variantMaterial)return null;const t=[];for(const A of this.targetModels){const e=A.clone();e.name+=" variant_"+this.variantMaterial.name+"_"+Fa.variantSwitchIndex++,e.name=e.name.replace(/\s/g,"_"),e.material=this.variantMaterial,e.geometry=A.geometry,e.matrix=A.matrix,(!A.parent||!A.parent.isEmpty())&&Wo.createEmptyParent(A),A.parent&&A.parent.add(e),t.push(e)}return t}},r(Ww,"_materialTriggersPerId",{}),r(Ww,"variantSwitchIndex",0),Ww);let ih=Fa;ni([y(qe)],ih.prototype,"materialToSwitch",2),ni([y(qe)],ih.prototype,"variantMaterial",2),ni([y()],ih.prototype,"fadeDuration",2);var gh;const ri=(gh=class extends JA{constructor(){super(...arguments),r(this,"target"),r(this,"toggleOnClick",!1),r(this,"targetState",!0),r(this,"hideSelf",!0),r(this,"selfModel"),r(this,"selfModelClone"),r(this,"targetModel"),r(this,"toggleModel"),r(this,"stateBeforeCreatingDocument",!1),r(this,"targetStateBeforeCreatingDocument",!1)}start(){Rd(this.gameObject)}onPointerClick(t){t.use(),!this.toggleOnClick&&this.hideSelf&&(this.gameObject.visible=!1),this.target&&(this.target.visible=this.toggleOnClick?!this.target.visible:this.targetState)}createBehaviours(t,A,e){A.uuid===this.gameObject.uuid&&(this.selfModel=A,this.selfModelClone=A.clone())}beforeCreateDocument(){this.target&&(this.gameObject[ri.wasVisible]===void 0&&(this.gameObject[ri.wasVisible]=this.gameObject.activeSelf),this.target[ri.wasVisible]===void 0&&(this.target[ri.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[ri.wasVisible],this.targetStateBeforeCreatingDocument=this.target[ri.wasVisible],this.gameObject.visible=!0,this.target.visible=!0)}afterCreateDocument(t,A){if(!this.target)return;this.targetModel=A.document.findById(this.target.uuid);const e=this.selfModel;if(this.selfModel&&this.targetModel){let i=this.selfModel,g=this.targetState;if(this.toggleOnClick)if(g=!this.targetStateBeforeCreatingDocument,!this.selfModelClone.geometry)(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&c_.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[ri.toggleClone]){const s=this.selfModelClone.clone();s.matrix.identity(),s.name+="_toggle"+ri.clonedToggleIndex++,e.add(s),this.gameObject[ri.toggleClone]=s,console.warn("USDZExport: Toggle "+this.gameObject.name+" doesn't have geometry. It will be deep cloned and nested behaviours will likely not work.")}const o=this.gameObject[ri.toggleClone];if(!this.gameObject[ri.reverseToggleClone]){const s=this.selfModelClone.clone();s.matrix.identity(),s.name+="_toggleReverse"+ri.clonedToggleIndex++,e.add(s),this.gameObject[ri.reverseToggleClone]=s}this.toggleModel=this.gameObject[ri.reverseToggleClone],(!this.toggleModel.geometry||!o.geometry)&&console.error("triggers without childs and without geometry won't work!",this,e.geometry),i=o,e.geometry=null,e.material=null}if(this.toggleModel){if(this.toggleOnClick){const o=[];o.push(Et.fadeAction(i,0,!1)),o.push(Et.fadeAction(this.toggleModel,0,!0)),o.push(Et.fadeAction(this.targetModel,0,g)),t.addBehavior(new Fg("Toggle_"+i.name+"_toggleTo"+(g?"On":"Off"),Kg.tapTrigger(i),Et.parallel(...o)));const s=[];s.push(Et.fadeAction(this.toggleModel,0,!1)),s.push(Et.fadeAction(i,0,!0)),s.push(Et.fadeAction(this.targetModel,0,!g)),t.addBehavior(new Fg("Toggle_"+i.name+"_toggleTo"+(g?"Off":"On"),Kg.tapTrigger(this.toggleModel),Et.parallel(...s)))}}else{const o=[];this.hideSelf&&o.push(Et.fadeAction(i,0,!1)),o.push(Et.fadeAction(this.targetModel,0,g)),t.addBehavior(new Fg("Toggle_"+i.name+"_toggleTo"+(g?"On":"Off"),Kg.tapTrigger(i),Et.parallel(...o)))}const I=new Array;this.targetStateBeforeCreatingDocument||I.push(this.targetModel),this.stateBeforeCreatingDocument||I.push(e),this.toggleModel&&I.push(this.toggleModel),t.addBehavior(new Fg("HideOnStart_"+this.gameObject.name,Kg.sceneStartTrigger(),Et.fadeAction(I,0,!1)))}}afterSerialize(t,A){this.gameObject[ri.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[ri.wasVisible],delete this.gameObject[ri.wasVisible]),this.target&&this.target[ri.wasVisible]!==void 0&&(this.target.visible=this.target[ri.wasVisible],delete this.target[ri.wasVisible]),delete this.gameObject[ri.toggleClone],delete this.gameObject[ri.reverseToggleClone]}},r(gh,"clonedToggleIndex",0),r(gh,"wasVisible",Symbol("usdz_SetActiveOnClick_wasVisible")),r(gh,"toggleClone",Symbol("clone for toggling")),r(gh,"reverseToggleClone",Symbol("clone for reverse toggling")),gh);let LB=ri;ni([y(wA)],LB.prototype,"target",2),ni([y()],LB.prototype,"toggleOnClick",2),ni([y()],LB.prototype,"targetState",2),ni([y()],LB.prototype,"hideSelf",2);class BN extends JA{start(){this.gameObject.visible=!1}createBehaviours(A,e,i){e.uuid===this.gameObject.uuid&&A.addBehavior(new Fg("HideOnStart_"+this.gameObject.name,Kg.sceneStartTrigger(),Et.fadeAction(e,0,!1)))}beforeCreateDocument(){this.gameObject.visible=!0}afterCreateDocument(){this.gameObject.visible=!1}}class Ih extends JA{constructor(){super(...arguments),r(this,"target"),r(this,"duration",.5),r(this,"motionType",DU.bounce)}beforeCreateDocument(){}createBehaviours(A,e,i){if(this.target&&e.uuid===this.gameObject.uuid){const g=new Fg("emphasize "+this.name,Kg.tapTrigger(this.gameObject),Et.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));A.addBehavior(g)}}afterCreateDocument(A,e){}}ni([y()],Ih.prototype,"target",2),ni([y()],Ih.prototype,"duration",2),ni([y()],Ih.prototype,"motionType",2);class oh extends JA{constructor(){super(...arguments),r(this,"target"),r(this,"clip",""),r(this,"toggleOnClick",!1)}start(){Rd(this.gameObject)}ensureAudioSource(){if(!this.target){const A=this.gameObject.addNewComponent(fi);A&&(this.target=A,A.spatialBlend=1,A.volume=1,A.loop=!1)}}onPointerClick(A){var e;A.use(),!(!((e=this.target)!=null&&e.clip)&&!this.clip)&&(this.ensureAudioSource(),this.target&&(this.target.isPlaying&&this.toggleOnClick?this.target.stop():(!this.toggleOnClick&&this.target.isPlaying&&this.target.stop(),this.clip?this.target.play(this.clip):this.target.play())))}createBehaviours(A,e,i){if(!(!this.target&&!this.clip)&&e.uuid===this.gameObject.uuid){const g=this.clip?this.clip:this.target?this.target.clip:void 0;if(!g||typeof g!="string")return;const I=this.target?this.target.gameObject:this.gameObject,o=g.split("/").pop(),s=this.target?this.target.volume:1,C=this.target&&this.target.spatialBlend==0?fU.NonSpatial:fU.Spatial;{let a=Et.playAudioAction(I,"audio/"+o,SU.Play,s,C);this.toggleOnClick&&(a.multiplePerformOperation=R_.Stop),this.target&&this.target.loop&&(a=Et.sequence(a).makeLooping());const n=new Fg("playAudio "+this.name,Kg.tapTrigger(this.gameObject),a);A.addBehavior(n)}if(this.target&&this.target.playOnAwake&&this.target.enabled){let a=Et.playAudioAction(I,"audio/"+o,SU.Play,s,C);this.target.loop&&(a=Et.sequence(a).makeLooping());const n=new Fg("playAudioOnStart "+this.name,Kg.sceneStartTrigger(),a);A.addBehavior(n)}}}async afterSerialize(A,e){if(!this.target&&!this.clip)return;const i=this.clip?this.clip:this.target?this.target.clip:void 0;if(!i||typeof i!="string")return;const g=i.split("/").pop(),I=await(await(await fetch(i)).blob()).arrayBuffer(),o=new Uint8Array(I);e.files["audio/"+g]=o}}ni([y(fi)],oh.prototype,"target",2),ni([y(URL)],oh.prototype,"clip",2),ni([y()],oh.prototype,"toggleOnClick",2);var Vw;const Xn=(Vw=class extends JA{constructor(){super(...arguments),r(this,"animator"),r(this,"stateName"),r(this,"trigger","tap"),r(this,"selfModel"),r(this,"stateAnimationModel"),r(this,"animationSequence",new Array),r(this,"animationLoopAfterSequence",new Array)}get target(){var t;return(t=this.animator)==null?void 0:t.gameObject}start(){Rd(this.gameObject)}onPointerClick(t){var A;t.use(),this.target&&this.stateName&&((A=this.animator)==null||A.play(this.stateName,0,0,.1))}createBehaviours(t,A,e){A.uuid===this.gameObject.uuid&&(this.selfModel=A)}afterSerialize(){if(Xn.rootsWithExclusivePlayback.size>1){const t='Multiple root objects targeted by more than one animation. To work around QuickLook bug FB13410767, animations will be set as "exclusive" and activating them will stop other animations being marked as exclusive.';Se()&&Ci(t),console.warn(t,...Xn.rootsWithExclusivePlayback)}Xn.animationActions=[],Xn.rootsWithExclusivePlayback=new Set}afterCreateDocument(t,A){if(!this.animationSequence||!this.stateAnimationModel||!this.target)return;const e=A.document,i=A.extensions.find(o=>o instanceof Ed);if(!i)return;const g=i.getClipCount(this.target)>1;g&&(Se()&&console.warn("Setting exclusive playback for "+this.target.name+"@"+this.stateName+" because it has "+i.getClipCount(this.target)+" animations. This works around QuickLook bug FB13410767."),Xn.rootsWithExclusivePlayback.add(this.target));const I=(o,s)=>{let C=Xn.animationActions.find(a=>a.affectedObjects==o&&a.start==s.start&&a.duration==s.duration);return C||(C=Et.startAnimationAction(o,s.start,s.duration),Xn.animationActions.push(C)),C};e.traverse(o=>{var s,C;if(o.uuid===((s=this.target)==null?void 0:s.uuid)){const a=Et.sequence();if(this.animationSequence!==void 0)for(const B of this.animationSequence)a.addAction(I(o,B));if(this.animationLoopAfterSequence!==void 0){const B=a.actions.length==0?a:Et.sequence();for(const Q of this.animationLoopAfterSequence)B.addAction(I(o,Q));B.makeLooping(),a!==B&&a.addAction(B)}const n=new Fg("tap "+this.name+" for "+this.stateName+" on "+((C=this.target)==null?void 0:C.name),this.trigger=="tap"?Kg.tapTrigger(this.selfModel):Kg.sceneStartTrigger(),a);g&&n.makeExclusive(!0),t.addBehavior(n)}})}createAnimation(t,A,e){var i,g,I,o;if(!this.target||!this.animator)return;const s=(i=this.animator)==null?void 0:i.runtimeAnimatorController;let C=s?.findState(this.stateName),a=[],n=[];if(s&&C){const B=new Array;B.push(C);let Q=!1;for(;B.length<100;){if(!C||C===null||!C.transitions||C.transitions.length===0){(g=C.motion)!=null&&g.isLooping&&(Q=!0);break}const E=C.transitions.find(d=>d.conditions.length===0),h=E?s.getState(E.destinationState,0):null;if(h&&B.includes(h)){C=h,Q=!0;break}else if(E){if(C=h,!C)break;B.push(C)}else{Q=((I=C.motion)==null?void 0:I.isLooping)??!1;break}}if(Q&&C){const E=B.indexOf(C);a=B.slice(0,E),n=B.slice(E),console.log("found loop from "+this.stateName,"states until loop",a,"states looping",n)}else a=B,n=[],console.log("found no loop from "+this.stateName,"states",a)}if(a=a.filter(B=>{var Q,E,h;return((Q=B.motion)==null?void 0:Q.clip)&&((h=(E=B.motion)==null?void 0:E.clip.tracks)==null?void 0:h.length)>0}),n=n.filter(B=>{var Q,E,h;return((Q=B.motion)==null?void 0:Q.clip)&&((h=(E=B.motion)==null?void 0:E.clip.tracks)==null?void 0:h.length)>0}),a.length===0&&n.length===0){console.warn("No clips found for state "+this.stateName+" on "+((o=this.animator)==null?void 0:o.name)+", can't export animation data");return}if(this.stateAnimationModel=A,a.length>0){this.animationSequence=new Array;for(const B of a)this.animationSequence.push(t.registerAnimation(this.target,B.motion.clip))}if(n.length>0){this.animationLoopAfterSequence=new Array;for(const B of n)this.animationLoopAfterSequence.push(t.registerAnimation(this.target,B.motion.clip))}}},r(Vw,"animationActions",[]),r(Vw,"rootsWithExclusivePlayback",new Set),Vw);let sh=Xn;ni([y(bg)],sh.prototype,"animator",2),ni([y()],sh.prototype,"stateName",2);class Ch extends JA{constructor(){super(...arguments),r(this,"target")}getType(){}getDuration(){}}ni([y(wA)],Ch.prototype,"target",2);class Ud extends JA{constructor(){super(...arguments),r(this,"target")}}ni([y(Ch)],Ud.prototype,"target",2);class Nd extends Ch{constructor(){super(...arguments),r(this,"type",1),r(this,"duration",1)}getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}ni([y()],Nd.prototype,"type",2),ni([y()],Nd.prototype,"duration",2);class QN extends Ud{}var $oA=Object.defineProperty,AsA=Object.getOwnPropertyDescriptor,Ka=(t,A,e,i)=>{for(var g=i>1?void 0:i?AsA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&$oA(A,e,g),g};const nO=iA("debugcharactercontroller");class xB extends JA{constructor(){super(...arguments),r(this,"center",new w(0,0,0)),r(this,"radius",.5),r(this,"height",2),r(this,"_rigidbody",null),r(this,"_activeGroundCollisions"),r(this,"_contactVelocity",new w)}get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(Pt),this._rigidbody||(this._rigidbody=this.gameObject.addNewComponent(Pt)),this.rigidbody)}awake(){this._activeGroundCollisions=new Set}onEnable(){const A=this.rigidbody;let e=this.gameObject.getComponent(Wn);e||(e=this.gameObject.addNewComponent(Wn)),e.center.copy(this.center),e.radius=this.radius,e.height=this.height;const i=new w(0,0,1),g=new w(1,0,0),I=new w(0,1,0),o=this.gameObject.getWorldDirection(new w);o.y=0;const s=g.dot(o)<0?-1:1,C=i.angleTo(o)*s;this.gameObject.setRotationFromAxisAngle(I,C),A.lockRotationX=!0,A.lockRotationY=!0,A.lockRotationZ=!0}move(A){this.gameObject.position.add(A)}onCollisionEnter(A){(A.contacts.length==0||A.contacts.some(e=>e.normal.y>.2))&&(this._activeGroundCollisions.add(A),nO&&console.log(`Collision(${this._activeGroundCollisions.size}): ${A.contacts.map(e=>e.normal.y.toFixed(2)).join(", ")} - ${this.isGrounded}`))}onCollisionExit(A){this._activeGroundCollisions.delete(A),nO&&console.log(`Collision(${this._activeGroundCollisions.size}) - ${this.isGrounded}`)}get isGrounded(){return this._activeGroundCollisions.size>0}get contactVelocity(){var A;this._contactVelocity.set(0,0,0);for(const e of this._activeGroundCollisions){const i=(A=this.context.physics.engine)==null?void 0:A.getLinearVelocity(e.collider);i&&(this._contactVelocity.x+=i.x,this._contactVelocity.y+=i.y,this._contactVelocity.z+=i.z)}return this._contactVelocity}}Ka([y(w)],xB.prototype,"center",2),Ka([y()],xB.prototype,"radius",2),Ka([y()],xB.prototype,"height",2);class Ja extends JA{constructor(){super(...arguments),r(this,"controller"),r(this,"movementSpeed",2),r(this,"rotationSpeed",2),r(this,"jumpForce",1),r(this,"doubleJumpForce",2),r(this,"animator"),r(this,"lookForward",!0),r(this,"lookInput",new tA(0,0)),r(this,"moveInput",new tA(0,0)),r(this,"jumpInput",!1),r(this,"_currentSpeed",new w(0,0,0)),r(this,"_currentAngularSpeed",new w(0,0,0)),r(this,"_temp",new w(0,0,0)),r(this,"_jumpCount",0),r(this,"_currentRotation"),r(this,"_raycastOptions",new Oo)}awake(){this._currentRotation=new FA}update(){const A=this.context.input;A.isKeyPressed("KeyW")?this.moveInput.y+=1:A.isKeyPressed("KeyS")&&(this.moveInput.y-=1),A.isKeyPressed("KeyD")?this.lookInput.x+=1:A.isKeyPressed("KeyA")&&(this.lookInput.x-=1),this.jumpInput||(this.jumpInput=A.isKeyDown("Space"))}move(A){this.moveInput.add(A)}look(A){this.lookInput.add(A)}jump(){this.jumpInput=!0}onBeforeRender(){this.handleInput(this.moveInput,this.lookInput,this.jumpInput),this.lookInput.set(0,0),this.moveInput.set(0,0),this.jumpInput=!1}handleInput(A,e,i){var g,I,o,s,C,a,n,B,Q,E,h;if((g=this.controller)!=null&&g.isGrounded&&(this._jumpCount=0,this.doubleJumpForce>0&&((I=this.animator)==null||I.setBool("doubleJump",!1))),this._currentSpeed.z+=A.y*this.movementSpeed*this.context.time.deltaTime,(o=this.animator)==null||o.setBool("running",A.length()>.01),(C=this.animator)==null||C.setBool("jumping",((s=this.controller)==null?void 0:s.isGrounded)===!0&&i),this._temp.copy(this._currentSpeed),this._temp.applyQuaternion(this.gameObject.quaternion),this.controller?this.controller.move(this._temp):this.gameObject.position.add(this._temp),this._currentAngularSpeed.y+=Ie.toRadians(-e.x*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){const d=this.context.mainCameraComponent.forward;d.y=0,d.normalize(),this._currentRotation.setFromUnitVectors(new w(0,0,1),d),this.gameObject.quaternion.slerp(this._currentRotation,this.context.time.deltaTime*10)}if(this.gameObject.rotateY(this._currentAngularSpeed.y),this._currentSpeed.multiplyScalar(1-this.context.time.deltaTime*10),this._currentAngularSpeed.y*=1-this.context.time.deltaTime*10,this.controller&&i&&this.jumpForce>0){let d=(a=this.controller)==null?void 0:a.isGrounded;if(this.doubleJumpForce>0&&!((n=this.controller)!=null&&n.isGrounded)&&this._jumpCount===1&&(d=!0,(B=this.animator)==null||B.setBool("doubleJump",!0)),d){this._jumpCount+=1;const u=this.controller.rigidbody,c=this._jumpCount===2?this.doubleJumpForce:this.jumpForce;u.applyImpulse(new w(0,1,0).multiplyScalar(c))}}if(this.controller){const d=(Q=this.controller)==null?void 0:Q.rigidbody.getVelocity().y;if(d<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new to),this._raycastOptions.ray.origin.copy(Ne(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);const u=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);const c=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(u),(c.length&&c[0].distance>2||d<-10)&&((E=this.animator)==null||E.setBool("falling",!0))}else(h=this.animator)==null||h.setBool("falling",!1)}}}Ka([y(xB)],Ja.prototype,"controller",2),Ka([y()],Ja.prototype,"movementSpeed",2),Ka([y()],Ja.prototype,"rotationSpeed",2),Ka([y()],Ja.prototype,"jumpForce",2),Ka([y()],Ja.prototype,"doubleJumpForce",2),Ka([y(bg)],Ja.prototype,"animator",2);var esA=Object.defineProperty,tsA=Object.getOwnPropertyDescriptor,isA=(t,A,e,i)=>{for(var g=i>1?void 0:i?tsA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&esA(A,e,g),g};class Fd extends rI{constructor(){super(...arguments),r(this,"intensity")}get typeName(){return"ChromaticAberration"}init(){this.intensity.defaultValue=0}onCreateEffect(){const A=new fL;return A.offset=new tA(0,0),A.radialModulation=!0,A.modulationOffset=.15,this.intensity.valueProcessor=e=>e*.02,this.intensity.onValueChanged=e=>{A.offset.x=-e,A.offset.y=e},A}}isA([y(Ke)],Fd.prototype,"intensity",2),As("ChromaticAberration",Fd);var gsA=Object.defineProperty,IsA=Object.getOwnPropertyDescriptor,Zw=(t,A,e,i)=>{for(var g=i>1?void 0:i?IsA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&gsA(A,e,g),g};class $n extends rI{constructor(){super(...arguments),r(this,"postExposure"),r(this,"contrast"),r(this,"hueShift"),r(this,"saturation")}get typeName(){return"ColorAdjustments"}init(){this.postExposure.valueProcessor=A=>(A=Math.pow(2,A),A),this.postExposure.defaultValue=0,this.contrast.valueProcessor=A=>{let e=1;return A>0?e=200:A<0&&(e=100),A/e},this.contrast.defaultValue=0,this.hueShift.valueProcessor=A=>Math.PI*A/180,this.hueShift.defaultValue=0,this.saturation.valueProcessor=A=>A<0?A/100:A/(100*Math.PI),this.saturation.defaultValue=0}unapply(){this.context.renderer.toneMappingExposure=1}onCreateEffect(){this.context.renderer.toneMapping===YI&&this.postExposure.overrideState&&(this.context.renderer.toneMapping=Zh);const A=new SL;this.postExposure.onValueChanged=i=>{this.context.renderer.toneMapping===YI&&(this.context.renderer.toneMapping=Zh),this.postExposure.overrideState&&(this.context.renderer.toneMappingExposure=i)},this.contrast.onValueChanged=i=>{A.contrast=i};const e=new kL;return this.hueShift.onValueChanged=i=>e.hue=i,this.saturation.onValueChanged=i=>e.saturation=i,[e,A]}}Zw([y(Ke)],$n.prototype,"postExposure",2),Zw([y(Ke)],$n.prototype,"contrast",2),Zw([y(Ke)],$n.prototype,"hueShift",2),Zw([y(Ke)],$n.prototype,"saturation",2),As("ColorAdjustments",$n);const osA=(Math.sqrt(5)-1)/4,Yg=(5-Math.sqrt(5))/20,zw=t=>Math.floor(t)|0,Xw=new Float64Array([0,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,1,0,1,1,1,0,1,-1,1,0,-1,1,1,0,-1,-1,-1,0,1,1,-1,0,1,-1,-1,0,-1,1,-1,0,-1,-1,1,1,0,1,1,1,0,-1,1,-1,0,1,1,-1,0,-1,-1,1,0,1,-1,1,0,-1,-1,-1,0,1,-1,-1,0,-1,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,0]);function ssA(t=Math.random){const A=CsA(t),e=new Float64Array(A).map(o=>Xw[o%32*4]),i=new Float64Array(A).map(o=>Xw[o%32*4+1]),g=new Float64Array(A).map(o=>Xw[o%32*4+2]),I=new Float64Array(A).map(o=>Xw[o%32*4+3]);return function(o,s,C,a){let n,B,Q,E,h;const d=(o+s+C+a)*osA,u=zw(o+d),c=zw(s+d),l=zw(C+d),p=zw(a+d),D=(u+c+l+p)*Yg,S=u-D,k=c-D,f=l-D,U=p-D,M=o-S,m=s-k,x=C-f,L=a-U;let V=0,Y=0,P=0,b=0;M>m?V++:Y++,M>x?V++:P++,M>L?V++:b++,m>x?Y++:P++,m>L?Y++:b++,x>L?P++:b++;const T=V>=3?1:0,_=Y>=3?1:0,eA=P>=3?1:0,$=b>=3?1:0,IA=V>=2?1:0,yA=Y>=2?1:0,xA=P>=2?1:0,OA=b>=2?1:0,$A=V>=1?1:0,rA=Y>=1?1:0,RA=P>=1?1:0,jA=b>=1?1:0,YA=M-T+Yg,WA=m-_+Yg,BA=x-eA+Yg,TA=L-$+Yg,W=M-IA+2*Yg,GA=m-yA+2*Yg,fA=x-xA+2*Yg,_A=L-OA+2*Yg,hA=M-$A+3*Yg,Ee=m-rA+3*Yg,q=x-RA+3*Yg,N=L-jA+3*Yg,CA=M-1+4*Yg,bA=m-1+4*Yg,MA=x-1+4*Yg,LA=L-1+4*Yg,ge=u&255,HA=c&255,XA=l&255,se=p&255;let De=.6-M*M-m*m-x*x-L*L;if(De<0)n=0;else{const kA=ge+A[HA+A[XA+A[se]]];De*=De,n=De*De*(e[kA]*M+i[kA]*m+g[kA]*x+I[kA]*L)}let vA=.6-YA*YA-WA*WA-BA*BA-TA*TA;if(vA<0)B=0;else{const kA=ge+T+A[HA+_+A[XA+eA+A[se+$]]];vA*=vA,B=vA*vA*(e[kA]*YA+i[kA]*WA+g[kA]*BA+I[kA]*TA)}let be=.6-W*W-GA*GA-fA*fA-_A*_A;if(be<0)Q=0;else{const kA=ge+IA+A[HA+yA+A[XA+xA+A[se+OA]]];be*=be,Q=be*be*(e[kA]*W+i[kA]*GA+g[kA]*fA+I[kA]*_A)}let ne=.6-hA*hA-Ee*Ee-q*q-N*N;if(ne<0)E=0;else{const kA=ge+$A+A[HA+rA+A[XA+RA+A[se+jA]]];ne*=ne,E=ne*ne*(e[kA]*hA+i[kA]*Ee+g[kA]*q+I[kA]*N)}let Be=.6-CA*CA-bA*bA-MA*MA-LA*LA;if(Be<0)h=0;else{const kA=ge+1+A[HA+1+A[XA+1+A[se+1]]];Be*=Be,h=Be*Be*(e[kA]*CA+i[kA]*bA+g[kA]*MA+I[kA]*LA)}return 27*(n+B+Q+E+h)}}function CsA(t){const A=new Uint8Array(512);for(let e=0;e<512/2;e++)A[e]=e;for(let e=0;e<512/2-1;e++){const i=e+~~(t()*(256-e)),g=A[e];A[e]=A[i],A[i]=g}for(let e=256;e<512;e++)A[e]=A[e-256];return A}var asA=Object.defineProperty,nsA=Object.getOwnPropertyDescriptor,gA=(t,A,e,i)=>{for(var g=i>1?void 0:i?nsA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&asA(A,e,g),g};const $w=iA("debugparticles");var va=(t=>(t[t.Billboard=0]="Billboard",t[t.Stretch=1]="Stretch",t[t.HorizontalBillboard=2]="HorizontalBillboard",t[t.VerticalBillboard=3]="VerticalBillboard",t[t.Mesh=4]="Mesh",t))(va||{});let Ar=class{constructor(){r(this,"alphaKeys"),r(this,"colorKeys")}get duration(){return 1}evaluate(t,A){let e,i=0,g=null,I=0;for(let o=0;o<this.alphaKeys.length;o++){const s=this.alphaKeys[o];(s.time<t||!e)&&(e=s,i=o)}for(let o=0;o<this.colorKeys.length;o++){const s=this.colorKeys[o];(s.time<t||!g)&&(g=s,I=o)}if(g)if(I+1<this.colorKeys.length){const o=this.colorKeys[I+1],s=Ie.remap(t,g.time,o.time,0,1);A.r=Ie.lerp(g.color.r,o.color.r,s),A.g=Ie.lerp(g.color.g,o.color.g,s),A.b=Ie.lerp(g.color.b,o.color.b,s)}else A.r=g.color.r,A.g=g.color.g,A.b=g.color.b;if(e)if(i+1<this.alphaKeys.length){const o=this.alphaKeys[i+1],s=Ie.remap(t,e.time,o.time,0,1);A.alpha=Ie.lerp(e.alpha,o.alpha,s)}else A.alpha=e.alpha;return A}};gA([y()],Ar.prototype,"alphaKeys",2),gA([y()],Ar.prototype,"colorKeys",2);var Kd=(t=>(t[t.Local=0]="Local",t[t.World=1]="World",t[t.Custom=2]="Custom",t))(Kd||{}),AS=(t=>(t[t.Sphere=0]="Sphere",t[t.SphereShell=1]="SphereShell",t[t.Hemisphere=2]="Hemisphere",t[t.HemisphereShell=3]="HemisphereShell",t[t.Cone=4]="Cone",t[t.Box=5]="Box",t[t.Mesh=6]="Mesh",t[t.ConeShell=7]="ConeShell",t[t.ConeVolume=8]="ConeVolume",t[t.ConeVolumeShell=9]="ConeVolumeShell",t[t.Circle=10]="Circle",t[t.CircleEdge=11]="CircleEdge",t[t.SingleSidedEdge=12]="SingleSidedEdge",t[t.MeshRenderer=13]="MeshRenderer",t[t.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",t[t.BoxShell=15]="BoxShell",t[t.BoxEdge=16]="BoxEdge",t[t.Donut=17]="Donut",t[t.Rectangle=18]="Rectangle",t[t.Sprite=19]="Sprite",t[t.SpriteRenderer=20]="SpriteRenderer",t))(AS||{});const rO=class{constructor(){r(this,"mode"),r(this,"constant"),r(this,"constantMin"),r(this,"constantMax"),r(this,"curve"),r(this,"curveMin"),r(this,"curveMax"),r(this,"curveMultiplier")}clone(){var t,A,e;const i=new rO;return i.mode=this.mode,i.constant=this.constant,i.constantMin=this.constantMin,i.constantMax=this.constantMax,i.curve=(t=this.curve)==null?void 0:t.clone(),i.curveMin=(A=this.curveMin)==null?void 0:A.clone(),i.curveMax=(e=this.curveMax)==null?void 0:e.clone(),i.curveMultiplier=this.curveMultiplier,i}evaluate(t,A){const e=A===void 0?Math.random():A;switch(this.mode){case 0:return this.constant;case 1:return t=Ie.clamp01(t),this.curve.evaluate(t)*this.curveMultiplier;case 2:const i=t*this.curveMin.duration,g=t*this.curveMax.duration;return Ie.lerp(this.curveMin.evaluate(i),this.curveMax.evaluate(g),e%1)*this.curveMultiplier;case 3:return Ie.lerp(this.constantMin,this.constantMax,e%1);default:this.curveMax.evaluate(t)*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(t){if(!t)return 0;let A=Number.MIN_VALUE;for(let e=0;e<t.keys.length;e++){const i=t.keys[e];i.value>A&&(A=i.value)}return A}};let re=rO;gA([y()],re.prototype,"mode",2),gA([y()],re.prototype,"constant",2),gA([y()],re.prototype,"constantMin",2),gA([y()],re.prototype,"constantMax",2),gA([y(SB)],re.prototype,"curve",2),gA([y(SB)],re.prototype,"curveMin",2),gA([y(SB)],re.prototype,"curveMax",2),gA([y()],re.prototype,"curveMultiplier",2);var eS;const Js=(eS=class{constructor(){r(this,"mode"),r(this,"color"),r(this,"colorMin"),r(this,"colorMax"),r(this,"gradient"),r(this,"gradientMin"),r(this,"gradientMax")}evaluate(t,A){const e=A===void 0?Math.random():A;switch(this.mode){case 0:return this.color;case 1:return this.gradient.evaluate(t,Js._temp),Js._temp;case 2:return Js._temp.lerpColors(this.colorMin,this.colorMax,e);case 3:return this.gradientMin.evaluate(t,Js._temp),this.gradientMax.evaluate(t,Js._temp2),Js._temp.lerp(Js._temp2,e)}return Js._temp.set(16711935),Js._temp.alpha=1,Js._temp}},r(eS,"_temp",new Mt(0,0,0,1)),r(eS,"_temp2",new Mt(0,0,0,1)),eS);let XI=Js;gA([y(Mt)],XI.prototype,"color",2),gA([y(Mt)],XI.prototype,"colorMin",2),gA([y(Mt)],XI.prototype,"colorMax",2),gA([y(Ar)],XI.prototype,"gradient",2),gA([y(Ar)],XI.prototype,"gradientMin",2),gA([y(Ar)],XI.prototype,"gradientMax",2);var EN=(t=>(t[t.Hierarchy=0]="Hierarchy",t[t.Local=1]="Local",t[t.Shape=2]="Shape",t))(EN||{});class Tg{constructor(){r(this,"cullingMode"),r(this,"duration"),r(this,"emitterVelocityMode"),r(this,"flipRotation"),r(this,"gravityModifier"),r(this,"gravityModifierMultiplier"),r(this,"loop"),r(this,"maxParticles"),r(this,"playOnAwake"),r(this,"prewarm"),r(this,"ringBufferLoopRange"),r(this,"ringBufferMode"),r(this,"scalingMode"),r(this,"simulationSpace"),r(this,"simulationSpeed"),r(this,"startColor"),r(this,"startDelay"),r(this,"startDelayMultiplier"),r(this,"startLifetime"),r(this,"startLifetimeMultiplier"),r(this,"startRotation"),r(this,"startRotationMultiplier"),r(this,"startRotation3D"),r(this,"startRotationX"),r(this,"startRotationXMultiplier"),r(this,"startRotationY"),r(this,"startRotationYMultiplier"),r(this,"startRotationZ"),r(this,"startRotationZMultiplier"),r(this,"startSize"),r(this,"startSize3D"),r(this,"startSizeMultiplier"),r(this,"startSizeX"),r(this,"startSizeXMultiplier"),r(this,"startSizeY"),r(this,"startSizeYMultiplier"),r(this,"startSizeZ"),r(this,"startSizeZMultiplier"),r(this,"startSpeed"),r(this,"startSpeedMultiplier"),r(this,"stopAction"),r(this,"useUnscaledTime")}}gA([y(re)],Tg.prototype,"gravityModifier",2),gA([y(XI)],Tg.prototype,"startColor",2),gA([y(re)],Tg.prototype,"startDelay",2),gA([y(re)],Tg.prototype,"startLifetime",2),gA([y(re)],Tg.prototype,"startRotation",2),gA([y(re)],Tg.prototype,"startRotationX",2),gA([y(re)],Tg.prototype,"startRotationY",2),gA([y(re)],Tg.prototype,"startRotationZ",2),gA([y(re)],Tg.prototype,"startSize",2),gA([y(re)],Tg.prototype,"startSizeX",2),gA([y(re)],Tg.prototype,"startSizeY",2),gA([y(re)],Tg.prototype,"startSizeZ",2),gA([y(re)],Tg.prototype,"startSpeed",2);class Jd{constructor(){r(this,"cycleCount"),r(this,"maxCount"),r(this,"minCount"),r(this,"probability"),r(this,"repeatInterval"),r(this,"time"),r(this,"count"),r(this,"_performed",0)}reset(){this._performed=0}run(A){if(A<=this.time)return 0;let e=0;if(this.cycleCount===0||this._performed<this.cycleCount){const i=this.time+this.repeatInterval*this._performed;if(A>=i&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:e=this.count.constant;break;case 3:e=Ie.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:e=this.count.curve.evaluate(Math.random());break;case 2:const g=Math.random();e=Ie.lerp(this.count.curveMin.evaluate(g),this.count.curveMax.evaluate(g),Math.random());break}}return e}}class uC{constructor(){r(this,"enabled"),r(this,"bursts"),r(this,"rateOverTime"),r(this,"rateOverTimeMultiplier"),r(this,"rateOverDistance"),r(this,"rateOverDistanceMultiplier"),r(this,"system")}get burstCount(){var A;return((A=this.bursts)==null?void 0:A.length)??0}reset(){var A;(A=this.bursts)==null||A.forEach(e=>e.reset())}getBurst(){let A=0;if(this.burstCount>0)for(let e=0;e<this.burstCount;e++){const i=this.bursts[e];this.system.main.loop&&i.time>=this.system.time&&i.reset(),A+=Math.round(i.run(this.system.time))}return A}}gA([y()],uC.prototype,"enabled",2),gA([y()],uC.prototype,"bursts",2),gA([y(re)],uC.prototype,"rateOverTime",2),gA([y()],uC.prototype,"rateOverTimeMultiplier",2),gA([y(re)],uC.prototype,"rateOverDistance",2),gA([y()],uC.prototype,"rateOverDistanceMultiplier",2);class vd{constructor(){r(this,"enabled"),r(this,"color")}}gA([y(XI)],vd.prototype,"color",2);class er{constructor(){r(this,"enabled"),r(this,"separateAxes"),r(this,"size"),r(this,"sizeMultiplier"),r(this,"x"),r(this,"xMultiplier"),r(this,"y"),r(this,"yMultiplier"),r(this,"z"),r(this,"zMultiplier"),r(this,"_time",0),r(this,"_temp",new w)}evaluate(A,e,i){if(e||(e=this._temp),!this.enabled)return e.x=e.y=e.z=1,e;if(this.separateAxes)e.x=this.x.evaluate(A,i)*this.xMultiplier,e.y=this.y.evaluate(A,i)*this.yMultiplier,e.z=this.z.evaluate(A,i)*this.zMultiplier;else{const g=this.size.evaluate(A,i)*this.sizeMultiplier;e.x=g}return e}}gA([y(re)],er.prototype,"size",2),gA([y(re)],er.prototype,"x",2),gA([y(re)],er.prototype,"y",2),gA([y(re)],er.prototype,"z",2);var tS;const bd=(tS=class{constructor(){r(this,"shapeType",5),r(this,"enabled",!0),r(this,"alignToDirection",!1),r(this,"angle",0),r(this,"arc",360),r(this,"arcSpread"),r(this,"arcSpeedMultiplier"),r(this,"arcMode"),r(this,"boxThickness"),r(this,"position"),r(this,"rotation"),r(this,"_rotation",new Wg),r(this,"scale"),r(this,"radius"),r(this,"radiusThickness"),r(this,"sphericalDirectionAmount"),r(this,"randomDirectionAmount"),r(this,"randomPositionAmount"),r(this,"meshShapeType"),r(this,"meshRenderer"),r(this,"_meshObj"),r(this,"_meshGeometry"),r(this,"system"),r(this,"_space"),r(this,"_worldSpaceMatrix",new NA),r(this,"_worldSpaceMatrixInverse",new NA),r(this,"_vector",new w(0,0,0)),r(this,"_temp",new w(0,0,0)),r(this,"_triangle",new LI),r(this,"_dir",new w),r(this,"_loopTime",0),r(this,"_loopDirection",1),$w&&console.log(this)}get type(){return AS[this.shapeType]}initialize(t){this.onInitialize(t),t.position.copy(this._vector)}toJSON(){return this}clone(){return new bd}setMesh(t){this.meshRenderer=t,t?(this._meshObj=t.sharedMeshes[Math.floor(Math.random()*t.sharedMeshes.length)],this._meshGeometry=this._meshObj.geometry):(this._meshObj=void 0,this._meshGeometry=void 0)}update(t,A,e,i){this.system=t,this._space=e,e===1&&(this._worldSpaceMatrix.copy(i.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}applyRotation(t){const A=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return A&&(this._rotation.x=Ie.toRadians(this.rotation.x),this._rotation.y=Ie.toRadians(this.rotation.y),this._rotation.z=Ie.toRadians(this.rotation.z),this._rotation.order="ZYX",t.applyEuler(this._rotation)),A}onInitialize(t){this._vector.set(0,0,0),t.mesh=void 0,t.mesh_geometry=void 0;const A=this._temp.copy(this.position),e=this._space===1;e&&A.applyQuaternion(this.system.worldQuaternion);let i=this.radius;if(e&&(i*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:$w&&Fe.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(A);break;case 4:this.randomConePoint(this.position,this.angle,i,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,i,this.radiusThickness,this.arc,this._vector);break;case 10:this.randomCirclePoint(this.position,i,this.radiusThickness,this.arc,this._vector);break;case 13:const g=this.meshRenderer;g?.destroyed==!1&&this.setMesh(g);const I=t.mesh=this._meshObj,o=t.mesh_geometry=this._meshGeometry;if(I&&o)switch(this.meshShapeType){case 0:{const s=o.getAttribute("position"),C=Math.floor(Math.random()*s.count);this._vector.fromBufferAttribute(s,C),this._vector.applyMatrix4(I.matrixWorld),t.mesh_normal=C}break;case 1:break;case 2:{const s=o.index;if(s){let C=Math.random(),a=Math.random();C+a>1&&(C=1-C,a=1-a);const n=Math.floor(Math.random()*(s.count/3));let B=n*3,Q=n*3+1,E=n*3+2;B=s.getX(B),Q=s.getX(Q),E=s.getX(E);const h=o.getAttribute("position");this._triangle.a.fromBufferAttribute(h,B),this._triangle.b.fromBufferAttribute(h,Q),this._triangle.c.fromBufferAttribute(h,E),this._vector.set(0,0,0).addScaledVector(this._triangle.a,C).addScaledVector(this._triangle.b,a).addScaledVector(this._triangle.c,1-(C+a)),this._vector.applyMatrix4(I.matrixWorld),t.mesh_normal=n}}break}break;default:this._vector.set(0,0,0),Se()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",AS[this.shapeType]),globalThis.__particlesystem_shapetype_unsupported=!0);break}this.randomizePosition(this._vector,this.randomPositionAmount)}this.applyRotation(this._vector),e&&(this._vector.applyQuaternion(this.system.worldQuaternion),this._vector.add(this.system.worldPos)),$w&&Fe.DrawSphere(this._vector,.03,16711680,.5,!0)}getDirection(t,A){var e;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 i=A.x,g=A.y,I=A.z;this._dir.set(i,g,I),(e=this.system)!=null&&e.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;case 13:const o=t.mesh,s=t.mesh_geometry;if(o&&s)switch(this.meshShapeType){case 0:{const C=s.getAttribute("normal"),a=t.mesh_normal;this._dir.fromBufferAttribute(C,a)}break;case 1:break;case 2:{const C=s.index;if(C){const a=t.mesh_normal,n=C.getX(a*3),B=C.getX(a*3+1),Q=C.getX(a*3+2),E=s.getAttribute("position"),h=_i(),d=_i(),u=_i();h.fromBufferAttribute(E,n),d.fromBufferAttribute(E,B),u.fromBufferAttribute(E,Q),h.sub(d),u.sub(d),h.cross(u),this._dir.copy(h).multiplyScalar(-1);const c=Kt(o);this._dir.applyQuaternion(c)}}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),$w&&(Fe.DrawSphere(A,.01,8925952,.5,!0),Fe.DrawDirection(A,this._dir,8925952,.5,!0)),this._dir}randomizePosition(t,A){if(A<=0)return;const e=bd._tempVec;e.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),e.x*=A*this.scale.x,e.y*=A*this.scale.y,e.z*=A*this.scale.z,t.add(e)}randomizeDirection(t,A){if(A===0)return;const e=bd._randomQuat,i=bd._tempVec;i.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),e.setFromAxisAngle(i,A*Math.random()*Math.PI),t.applyQuaternion(e)}spherizeDirection(t,A){if(A===0)return;const e=Math.random()*Math.PI*2,i=Math.acos(1-Math.random()*2),g=Math.sin(i)*Math.cos(e),I=Math.sin(i)*Math.sin(e),o=Math.cos(i),s=new w(g,I,o);t.lerp(s,A)}randomSpherePoint(t,A,e,i,g){const I=Math.random(),o=Math.random(),s=2*Math.PI*I*(i/360),C=Math.acos(2*o-1),a=Ie.lerp(1,1-Math.pow(1-Math.random(),Math.PI),e)*A,n=t.x+this.scale.x*(-a*Math.sin(C)*Math.cos(s)),B=t.y+this.scale.y*(a*Math.sin(C)*Math.sin(s)),Q=t.z+this.scale.z*(a*Math.cos(C));g.x=n,g.y=B,g.z=Q}randomCirclePoint(t,A,e,i,g){const I=Math.random(),o=2*Math.PI*I*(i/360),s=Ie.lerp(1,1-Math.pow(1-Math.random(),Math.PI),e)*A,C=t.x+this.scale.x*s*Math.cos(o),a=t.y+this.scale.y*s*Math.sin(o),n=t.z;g.x=C,g.y=a,g.z=n}randomConePoint(t,A,e,i,g,I,o){let s=0,C=0;switch(I){case 0:s=Math.random(),C=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:s=.5,C=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let a=2*Math.PI*s*(g/360);switch(I){case 2:case 1:a+=Math.PI+.5,a+=this._loopTime*Math.PI*2,a%=Ie.toRadians(g);break}const n=Math.acos(2*C-1),B=Ie.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*e,Q=t.x+-B*Math.sin(n)*Math.cos(a),E=t.y+B*Math.sin(n)*Math.sin(a),h=t.z;o.x=Q*this.scale.x,o.y=E*this.scale.y,o.z=h*this.scale.z}},r(tS,"_randomQuat",new FA),r(tS,"_tempVec",new w),tS);let Bi=bd;gA([y()],Bi.prototype,"shapeType",2),gA([y()],Bi.prototype,"enabled",2),gA([y()],Bi.prototype,"alignToDirection",2),gA([y()],Bi.prototype,"angle",2),gA([y()],Bi.prototype,"arc",2),gA([y()],Bi.prototype,"arcSpread",2),gA([y()],Bi.prototype,"arcSpeedMultiplier",2),gA([y()],Bi.prototype,"arcMode",2),gA([y(w)],Bi.prototype,"boxThickness",2),gA([y(w)],Bi.prototype,"position",2),gA([y(w)],Bi.prototype,"rotation",2),gA([y(w)],Bi.prototype,"scale",2),gA([y()],Bi.prototype,"radius",2),gA([y()],Bi.prototype,"radiusThickness",2),gA([y()],Bi.prototype,"sphericalDirectionAmount",2),gA([y()],Bi.prototype,"randomDirectionAmount",2),gA([y()],Bi.prototype,"randomPositionAmount",2),gA([y()],Bi.prototype,"meshShapeType",2),gA([y(zl)],Bi.prototype,"meshRenderer",2);class Rt{constructor(){r(this,"damping"),r(this,"enabled"),r(this,"frequency"),r(this,"octaveCount"),r(this,"octaveMultiplier"),r(this,"octaveScale"),r(this,"positionAmount"),r(this,"quality"),r(this,"remap"),r(this,"remapEnabled"),r(this,"remapMultiplier"),r(this,"remapX"),r(this,"remapXMultiplier"),r(this,"remapY"),r(this,"remapYMultiplier"),r(this,"remapZ"),r(this,"remapZMultiplier"),r(this,"scrollSpeedMultiplier"),r(this,"separateAxes"),r(this,"strengthMultiplier"),r(this,"strengthX"),r(this,"strengthXMultiplier"),r(this,"strengthY"),r(this,"strengthYMultiplier"),r(this,"strengthZ"),r(this,"strengthZMultiplier"),r(this,"_noise"),r(this,"_time",0),r(this,"_temp",new w)}update(A){this._time+=A.time.deltaTime*this.scrollSpeedMultiplier}apply(A,e,i,g,I,o){if(!this.enabled)return;this._noise||(this._noise=ssA(()=>0));const s=this._temp.set(e.x,e.y,e.z).multiplyScalar(this.frequency),C=this._noise(s.x,s.y,s.z,this._time),a=this._noise(s.x,s.y,s.z,this._time+1e3*this.frequency),n=this._noise(s.x,s.y,s.z,this._time+2e3*this.frequency);this._temp.set(C,a,n).normalize();const B=I/o;let Q=this.positionAmount.evaluate(B);this.separateAxes?(this._temp.x*=Q*this.strengthXMultiplier,this._temp.y*=Q*this.strengthYMultiplier,this._temp.z*=Q*this.strengthZMultiplier):(this.strengthX&&(Q*=this.strengthX.evaluate(B)*1.5),this._temp.multiplyScalar(Q)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z}}gA([y()],Rt.prototype,"damping",2),gA([y()],Rt.prototype,"enabled",2),gA([y()],Rt.prototype,"frequency",2),gA([y()],Rt.prototype,"octaveCount",2),gA([y()],Rt.prototype,"octaveMultiplier",2),gA([y()],Rt.prototype,"octaveScale",2),gA([y(re)],Rt.prototype,"positionAmount",2),gA([y()],Rt.prototype,"quality",2),gA([y(re)],Rt.prototype,"remap",2),gA([y()],Rt.prototype,"remapEnabled",2),gA([y()],Rt.prototype,"remapMultiplier",2),gA([y(re)],Rt.prototype,"remapX",2),gA([y()],Rt.prototype,"remapXMultiplier",2),gA([y(re)],Rt.prototype,"remapY",2),gA([y()],Rt.prototype,"remapYMultiplier",2),gA([y(re)],Rt.prototype,"remapZ",2),gA([y()],Rt.prototype,"remapZMultiplier",2),gA([y()],Rt.prototype,"scrollSpeedMultiplier",2),gA([y()],Rt.prototype,"separateAxes",2),gA([y()],Rt.prototype,"strengthMultiplier",2),gA([y(re)],Rt.prototype,"strengthX",2),gA([y()],Rt.prototype,"strengthXMultiplier",2),gA([y(re)],Rt.prototype,"strengthY",2),gA([y()],Rt.prototype,"strengthYMultiplier",2),gA([y(re)],Rt.prototype,"strengthZ",2),gA([y()],Rt.prototype,"strengthZMultiplier",2);class gi{constructor(){r(this,"enabled"),r(this,"attachRibbonToTransform",!1),r(this,"colorOverLifetime"),r(this,"colorOverTrail"),r(this,"dieWithParticles",!0),r(this,"inheritParticleColor",!0),r(this,"lifetime"),r(this,"lifetimeMultiplier"),r(this,"minVertexDistance",.2),r(this,"mode",0),r(this,"ratio",1),r(this,"ribbonCount",1),r(this,"shadowBias",0),r(this,"sizeAffectsLifetime",!1),r(this,"sizeAffectsWidth",!1),r(this,"splitSubEmitterRibbons",!1),r(this,"textureMode",0),r(this,"widthOverTrail"),r(this,"widthOverTrailMultiplier"),r(this,"worldSpace",!1)}getWidth(A,e,i,g){const I=this.widthOverTrail.evaluate(i,g);return A*=I,A}getColor(A,e,i){const g=this.colorOverTrail.evaluate(i),I=this.colorOverLifetime.evaluate(e);A.x*=g.r*I.r,A.y*=g.g*I.g,A.z*=g.b*I.b,A.w*=g.alpha*I.alpha}}gA([y()],gi.prototype,"enabled",2),gA([y()],gi.prototype,"attachRibbonToTransform",2),gA([y(XI)],gi.prototype,"colorOverLifetime",2),gA([y(XI)],gi.prototype,"colorOverTrail",2),gA([y()],gi.prototype,"dieWithParticles",2),gA([y()],gi.prototype,"inheritParticleColor",2),gA([y(re)],gi.prototype,"lifetime",2),gA([y()],gi.prototype,"lifetimeMultiplier",2),gA([y()],gi.prototype,"minVertexDistance",2),gA([y()],gi.prototype,"mode",2),gA([y()],gi.prototype,"ratio",2),gA([y()],gi.prototype,"ribbonCount",2),gA([y()],gi.prototype,"shadowBias",2),gA([y()],gi.prototype,"sizeAffectsLifetime",2),gA([y()],gi.prototype,"sizeAffectsWidth",2),gA([y()],gi.prototype,"splitSubEmitterRibbons",2),gA([y()],gi.prototype,"textureMode",2),gA([y(re)],gi.prototype,"widthOverTrail",2),gA([y()],gi.prototype,"widthOverTrailMultiplier",2),gA([y()],gi.prototype,"worldSpace",2);class Qi{constructor(){r(this,"enabled"),r(this,"space",0),r(this,"orbitalX"),r(this,"orbitalY"),r(this,"orbitalZ"),r(this,"orbitalXMultiplier"),r(this,"orbitalYMultiplier"),r(this,"orbitalZMultiplier"),r(this,"orbitalOffsetX"),r(this,"orbitalOffsetY"),r(this,"orbitalOffsetZ"),r(this,"speedModifier"),r(this,"speedModifierMultiplier"),r(this,"x"),r(this,"xMultiplier"),r(this,"y"),r(this,"yMultiplier"),r(this,"z"),r(this,"zMultiplier"),r(this,"_system"),r(this,"_temp",new w),r(this,"_temp2",new w),r(this,"_temp3",new w),r(this,"_hasOrbital",!1),r(this,"_index",0),r(this,"_orbitalMatrix",new NA)}update(A){this._system=A}init(A){this._index==0&&(A.debug=!0),this._index+=1,A.orbitx=this.orbitalX.evaluate(Math.random()),A.orbity=this.orbitalY.evaluate(Math.random()),A.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=A.orbitx!=0||A.orbity!=0||A.orbitz!=0}apply(A,e,i,g,I,o,s){var C;if(!this.enabled)return;const a=o/s,n=this.speedModifier.evaluate(a)*this.speedModifierMultiplier,B=this.x.evaluate(a),Q=this.y.evaluate(a),E=this.z.evaluate(a);if(this._temp.set(-B,Q,E),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&((C=this._system)==null?void 0:C.worldPos)){const h=this._temp2.set(i.x,i.y,i.z),d=this.orbitalXMultiplier,u=this.orbitalYMultiplier,c=this.orbitalZMultiplier,l=n*Math.PI*2*10,p=Math.cos(l*d),D=Math.sin(l*d),S=Math.cos(l*u),k=Math.sin(l*u),f=Math.cos(l*c),U=Math.sin(l*c),M=h.x*(S*f)+h.y*(S*U)+h.z*-k,m=h.x*(D*k*f-p*U)+h.y*(D*k*U+p*f)+h.z*(D*S),x=h.x*(p*k*f+D*U)+h.y*(p*k*U-D*f)+h.z*(p*S),L=this._temp3.set(h.x-M,h.y-m,h.z-x);L.normalize(),L.multiplyScalar(.2/I*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),g.x+=L.x,g.y+=L.y,g.z+=L.z}g.x+=this._temp.x,g.y+=this._temp.y,g.z+=this._temp.z,g.x*=n,g.y*=n,g.z*=n}}gA([y()],Qi.prototype,"enabled",2),gA([y()],Qi.prototype,"space",2),gA([y(re)],Qi.prototype,"orbitalX",2),gA([y(re)],Qi.prototype,"orbitalY",2),gA([y(re)],Qi.prototype,"orbitalZ",2),gA([y()],Qi.prototype,"orbitalXMultiplier",2),gA([y()],Qi.prototype,"orbitalYMultiplier",2),gA([y()],Qi.prototype,"orbitalZMultiplier",2),gA([y()],Qi.prototype,"orbitalOffsetX",2),gA([y()],Qi.prototype,"orbitalOffsetY",2),gA([y()],Qi.prototype,"orbitalOffsetZ",2),gA([y(re)],Qi.prototype,"speedModifier",2),gA([y()],Qi.prototype,"speedModifierMultiplier",2),gA([y(re)],Qi.prototype,"x",2),gA([y()],Qi.prototype,"xMultiplier",2),gA([y(re)],Qi.prototype,"y",2),gA([y()],Qi.prototype,"yMultiplier",2),gA([y(re)],Qi.prototype,"z",2),gA([y()],Qi.prototype,"zMultiplier",2);class Hg{constructor(){r(this,"animation"),r(this,"enabled"),r(this,"cycleCount"),r(this,"frameOverTime"),r(this,"frameOverTimeMultiplier"),r(this,"numTilesX"),r(this,"numTilesY"),r(this,"startFrame"),r(this,"startFrameMultiplier"),r(this,"rowMode"),r(this,"rowIndex"),r(this,"spriteCount"),r(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(A){if(!this.sampleOnceAtStart())return this.getIndex(A)}getIndex(A){const e=this.numTilesX*this.numTilesY;A=A*this.cycleCount;let i=this.frameOverTime.evaluate(A%1);return i*=this.frameOverTimeMultiplier,i*=e,i=i%e,i=Math.floor(i),i}}gA([y()],Hg.prototype,"animation",2),gA([y()],Hg.prototype,"enabled",2),gA([y()],Hg.prototype,"cycleCount",2),gA([y(re)],Hg.prototype,"frameOverTime",2),gA([y()],Hg.prototype,"frameOverTimeMultiplier",2),gA([y()],Hg.prototype,"numTilesX",2),gA([y()],Hg.prototype,"numTilesY",2),gA([y(re)],Hg.prototype,"startFrame",2),gA([y()],Hg.prototype,"startFrameMultiplier",2),gA([y()],Hg.prototype,"rowMode",2),gA([y()],Hg.prototype,"rowIndex",2),gA([y()],Hg.prototype,"spriteCount",2),gA([y()],Hg.prototype,"timeMode",2);class gs{constructor(){r(this,"enabled"),r(this,"separateAxes"),r(this,"x"),r(this,"xMultiplier"),r(this,"y"),r(this,"yMultiplier"),r(this,"z"),r(this,"zMultiplier")}evaluate(A,e){return this.enabled?this.separateAxes?0:this.z.evaluate(A,e)*-1:0}}gA([y()],gs.prototype,"enabled",2),gA([y()],gs.prototype,"separateAxes",2),gA([y(re)],gs.prototype,"x",2),gA([y()],gs.prototype,"xMultiplier",2),gA([y(re)],gs.prototype,"y",2),gA([y()],gs.prototype,"yMultiplier",2),gA([y(re)],gs.prototype,"z",2),gA([y()],gs.prototype,"zMultiplier",2);class lo{constructor(){r(this,"enabled"),r(this,"range"),r(this,"separateAxes"),r(this,"x"),r(this,"xMultiplier"),r(this,"y"),r(this,"yMultiplier"),r(this,"z"),r(this,"zMultiplier")}evaluate(A,e){if(!this.enabled)return 0;if(!this.separateAxes){const i=Ie.lerp(this.range.x,this.range.y,e);return this.z.evaluate(i)*-1}return 0}}gA([y()],lo.prototype,"enabled",2),gA([y()],lo.prototype,"range",2),gA([y()],lo.prototype,"separateAxes",2),gA([y(re)],lo.prototype,"x",2),gA([y()],lo.prototype,"xMultiplier",2),gA([y(re)],lo.prototype,"y",2),gA([y()],lo.prototype,"yMultiplier",2),gA([y(re)],lo.prototype,"z",2),gA([y()],lo.prototype,"zMultiplier",2);class Wi{constructor(){r(this,"enabled"),r(this,"dampen"),r(this,"drag"),r(this,"dragMultiplier"),r(this,"limit"),r(this,"limitMultiplier"),r(this,"separateAxes"),r(this,"limitX"),r(this,"limitXMultiplier"),r(this,"limitY"),r(this,"limitYMultiplier"),r(this,"limitZ"),r(this,"limitZMultiplier"),r(this,"multiplyDragByParticleSize",!1),r(this,"multiplyDragByParticleVelocity",!1),r(this,"space"),r(this,"_temp",new w),r(this,"_temp2",new w)}apply(A,e,i,g,I,o,s){if(this.enabled){const C=this.limit.evaluate(I)*this.limitMultiplier;if(e.length()>C){this._temp.copy(e).normalize().multiplyScalar(C);const a=this.dampen*.5;e.x=Ie.lerp(e.x,this._temp.x,a),e.y=Ie.lerp(e.y,this._temp.y,a),e.z=Ie.lerp(e.z,this._temp.z,a),i.x=Ie.lerp(i.x,this._temp.x,a),i.y=Ie.lerp(i.y,this._temp.y,a),i.z=Ie.lerp(i.z,this._temp.z,a)}}}}gA([y()],Wi.prototype,"enabled",2),gA([y()],Wi.prototype,"dampen",2),gA([y(re)],Wi.prototype,"drag",2),gA([y()],Wi.prototype,"dragMultiplier",2),gA([y(re)],Wi.prototype,"limit",2),gA([y()],Wi.prototype,"limitMultiplier",2),gA([y()],Wi.prototype,"separateAxes",2),gA([y(re)],Wi.prototype,"limitX",2),gA([y()],Wi.prototype,"limitXMultiplier",2),gA([y(re)],Wi.prototype,"limitY",2),gA([y()],Wi.prototype,"limitYMultiplier",2),gA([y(re)],Wi.prototype,"limitZ",2),gA([y()],Wi.prototype,"limitZMultiplier",2),gA([y()],Wi.prototype,"multiplyDragByParticleSize",2),gA([y()],Wi.prototype,"multiplyDragByParticleVelocity",2),gA([y()],Wi.prototype,"space",2);const BO=class{constructor(){r(this,"enabled"),r(this,"curve"),r(this,"curveMultiplier"),r(this,"mode"),r(this,"system"),r(this,"_temp",new w),r(this,"_firstUpdate",!0),r(this,"_frames",0)}clone(){var t;const A=new BO;return A.enabled=this.enabled,A.curve=(t=this.curve)==null?void 0:t.clone(),A.curveMultiplier=this.curveMultiplier,A.mode=this.mode,A}get _lastWorldPosition(){return this.system._iv_lastWorldPosition||(this.system._iv_lastWorldPosition=new w),this.system._iv_lastWorldPosition}get _velocity(){return this.system._iv_velocity||(this.system._iv_velocity=new w),this.system._iv_velocity}awake(t){this.system=t,this.reset()}reset(){this._firstUpdate=!0}update(t){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(t){if(this.enabled&&this.system.worldspace!==!1&&this.mode===0){const A=this.curve.evaluate(Math.random(),Math.random());this._temp.copy(this._velocity).multiplyScalar(A),t.add(this._temp)}}applyCurrent(t,A,e){if(this.enabled&&this.system&&this.system.worldspace!==!1&&this.mode===1){const i=this.curve.evaluate(A,e);this._temp.copy(this._velocity).multiplyScalar(i),t.add(this._temp)}}};let tr=BO;gA([y()],tr.prototype,"enabled",2),gA([y(re)],tr.prototype,"curve",2),gA([y()],tr.prototype,"curveMultiplier",2),gA([y()],tr.prototype,"mode",2);class UI{constructor(){r(this,"enabled"),r(this,"range"),r(this,"separateAxes"),r(this,"size"),r(this,"sizeMultiplier"),r(this,"x"),r(this,"xMultiplier"),r(this,"y"),r(this,"yMultiplier"),r(this,"z"),r(this,"zMultiplier")}evaluate(A,e,i,g){const I=A.length(),o=Ie.remap(I,this.range.x,this.range.y,0,1),s=this.size.evaluate(o,i);return g*s}}gA([y()],UI.prototype,"enabled",2),gA([y(tA)],UI.prototype,"range",2),gA([y()],UI.prototype,"separateAxes",2),gA([y(re)],UI.prototype,"size",2),gA([y()],UI.prototype,"sizeMultiplier",2),gA([y(re)],UI.prototype,"x",2),gA([y()],UI.prototype,"xMultiplier",2),gA([y(re)],UI.prototype,"y",2),gA([y()],UI.prototype,"yMultiplier",2),gA([y(re)],UI.prototype,"z",2),gA([y()],UI.prototype,"zMultiplier",2);class YB{constructor(){r(this,"enabled"),r(this,"range"),r(this,"color")}evaluate(A,e,i){const g=A.length(),I=Ie.remap(g,this.range.x,this.range.y,0,1),o=this.color.evaluate(I,e);i.x*=o.r,i.y*=o.g,i.z*=o.b,i.w*=o.alpha}}gA([y()],YB.prototype,"enabled",2),gA([y(tA)],YB.prototype,"range",2),gA([y(XI)],YB.prototype,"color",2);const rsA={name:"HorizontalBlurShader",uniforms:{tDiffuse:{value:null},h:{value:1/512}},vertexShader:`
5411
5413
 
5412
5414
  varying vec2 vUv;
5413
5415